Skip to main content

trusty_code/
mode.rs

1//! Harness mode selection: `daily-driver` (token-efficient, default) vs
2//! `parity` (full-schema benchmark mode) — #2059, vision spec §5.9
3//! ("Reconciliation with Parity-Spec Decision D2").
4//!
5//! Why: the parity spec (D2) mandates byte-identical, full tool schemas
6//! across every model for benchmark fairness; the production harness wants
7//! deferred schemas / compaction / per-model optimisation for real coding
8//! work. §5.9's resolved decision is two modes selected by a three-tier
9//! precedence, rather than picking one behaviour permanently. This module
10//! is ONLY the selection mechanism — resolving which mode applies to a
11//! given run and making that resolution queryable. It deliberately does
12//! NOT implement any token-efficiency behaviour (deferred schemas,
13//! compaction, repo-map): that is P1B's job, hooking into the branch
14//! points this module's callers expose (`prompt::assemble_system_prompt_for_mode`,
15//! `agent_loop::AgentLoop`'s `mode`-aware `tool_definitions`). In M1 both
16//! modes are functionally identical.
17//!
18//! **Precedence note:** §5.9 states the three-tier hierarchy, highest to
19//! lowest, as: (1) `TRUSTY_CODE_MODE` env var ("escape hatch... overrides
20//! all"), (2) `task.run`'s `mode` param ("overrides setting"), (3)
21//! `.claude/settings.json`'s `code_harness.mode` (the configured default).
22//! [`resolve_mode`] implements EXACTLY this order. (A paraphrase of this
23//! ticket's delegation put the env var last instead of first; §5.9's own
24//! table and the raw issue #2059 text both independently state env-var-
25//! highest, so this module follows the spec verbatim — flagged explicitly
26//! for the reader rather than silently reconciled.)
27//!
28//! What: [`HarnessMode`] (`DailyDriver` | `Parity`, `Default` =
29//! `DailyDriver`), [`HarnessMode::parse_lenient`] (case/separator-tolerant
30//! string parsing), and [`resolve_mode`] (the three-tier precedence chain,
31//! reading the env var and `.claude/settings.json` directly — no injected
32//! clock/env abstraction, matching this crate's existing
33//! `task::mock_llm::build_llm_client` precedent for a small, direct
34//! `std::env`/`std::fs` read in production code).
35//! Test: `mode::tests::*` (precedence order, lenient parsing, unknown-value
36//! degrade-to-next-tier, settings.json presence/absence/malformed-JSON).
37//!
38//! [`resolve_mode`]: crate::mode::resolve_mode
39//! [`HarnessMode`]: crate::mode::HarnessMode
40//! [`HarnessMode::parse_lenient`]: crate::mode::HarnessMode::parse_lenient
41
42use std::path::Path;
43
44use serde::{Deserialize, Serialize};
45
46/// Escape-hatch environment variable (§5.9): `TRUSTY_CODE_MODE=parity` or
47/// `daily-driver`. Highest precedence — overrides everything else.
48pub const MODE_ENV_VAR: &str = "TRUSTY_CODE_MODE";
49
50/// The two harness modes §5.9 resolves between.
51///
52/// Why: see module docs. A closed, two-variant enum (not a raw `String`)
53/// so every downstream `match` is exhaustive and a typo can never silently
54/// select an unintended mode.
55/// What: `DailyDriver` (default; where P1B's token-efficiency layers will
56/// apply) and `Parity` (full schemas, parity-spec benchmark mode). Wire
57/// representation is `"daily-driver"` / `"parity"` (kebab-case), matching
58/// §5.9's example JSON verbatim.
59/// Test: `mode::tests::wire_representation_is_kebab_case`.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "kebab-case")]
62pub enum HarnessMode {
63    DailyDriver,
64    Parity,
65}
66
67impl Default for HarnessMode {
68    /// §5.9: "`daily-driver` (DEFAULT)".
69    fn default() -> Self {
70        HarnessMode::DailyDriver
71    }
72}
73
74impl HarnessMode {
75    /// The stable wire string for this mode (matches the serde
76    /// `rename_all = "kebab-case"` representation).
77    ///
78    /// Why: callers building a plain JSON response field (`task.run`'s
79    /// immediate `{"mode": ...}`, the CLI's human-readable summary line)
80    /// want this without round-tripping through `serde_json`.
81    /// Test: `mode::tests::as_str_matches_serde_rename`.
82    pub fn as_str(&self) -> &'static str {
83        match self {
84            HarnessMode::DailyDriver => "daily-driver",
85            HarnessMode::Parity => "parity",
86        }
87    }
88
89    /// Parse a mode string leniently: case-insensitive, `_`/`-`
90    /// interchangeable, surrounding whitespace ignored.
91    ///
92    /// Why: every precedence tier's raw value (an env var, a JSON string
93    /// field, a CLI flag) is human-typed and should not require
94    /// byte-perfect casing to work.
95    /// What: `None` for anything that isn't recognisably `"daily-driver"`
96    /// or `"parity"` — callers treat `None` as "this source does not
97    /// contribute a value", falling through to the next-lower-precedence
98    /// tier (see [`resolve_mode`]'s docs for why this, rather than a hard
99    /// error, was chosen).
100    /// Test: `mode::tests::parse_lenient_accepts_case_and_separator_variants`,
101    /// `mode::tests::parse_lenient_rejects_unknown_values`.
102    pub fn parse_lenient(s: &str) -> Option<Self> {
103        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
104            "daily-driver" | "dailydriver" => Some(HarnessMode::DailyDriver),
105            "parity" => Some(HarnessMode::Parity),
106            _ => None,
107        }
108    }
109}
110
111/// Resolve the effective [`HarnessMode`] for one `task.run` call, per §5.9's
112/// three-tier precedence (highest to lowest): [`MODE_ENV_VAR`] > `task_param`
113/// (the `task.run` request's own `mode` field) > `.claude/settings.json`'s
114/// `code_harness.mode` > [`HarnessMode::default`].
115///
116/// Why: the single place this precedence is implemented, so `task::protocol`
117/// never has to re-derive it.
118/// What: checks each tier in order; a tier whose value is absent OR fails
119/// to parse (see [`HarnessMode::parse_lenient`]'s docs — this is the
120/// "clear error or fall back to default" choice this ticket asks to be
121/// made explicit: an invalid value at ANY tier is treated exactly like an
122/// absent one, falling through to the next tier, rather than hard-erroring
123/// the whole call) is skipped.
124/// `project_root` is `Option` because a projectless workstream has no project
125/// and therefore no `.claude/settings.json` tier to consult — that tier is
126/// simply skipped, exactly as an absent file already was. Projectless is a
127/// supported state, never an error, so it still resolves a mode (env var, then
128/// the request's own `mode`, then the default).
129/// Test: `mode::tests::env_var_wins_over_everything`,
130/// `mode::tests::task_param_wins_over_settings_json`,
131/// `mode::tests::settings_json_wins_over_default`,
132/// `mode::tests::default_when_nothing_set`,
133/// `mode::tests::invalid_env_var_falls_through_to_next_tier`,
134/// `mode::tests::projectless_skips_settings_tier_and_still_resolves`.
135pub fn resolve_mode(task_param: Option<&str>, project_root: Option<&Path>) -> HarnessMode {
136    if let Some(mode) = std::env::var(MODE_ENV_VAR)
137        .ok()
138        .and_then(|v| HarnessMode::parse_lenient(&v))
139    {
140        return mode;
141    }
142    if let Some(mode) = task_param.and_then(HarnessMode::parse_lenient) {
143        return mode;
144    }
145    if let Some(mode) = project_root.and_then(read_settings_json_mode) {
146        return mode;
147    }
148    HarnessMode::default()
149}
150
151/// Read `<project_root>/.claude/settings.json`'s `code_harness.mode` key.
152///
153/// Why: the Claude-Code-compatible, project-scoped config location §5.9's
154/// example JSON uses.
155/// What: `None` when the file is missing, unreadable, not valid JSON, or
156/// the key is absent/unparseable — absence at any step is "this source
157/// does not contribute", never an error (mirrors
158/// `project_context::load_project_context`'s same graceful-degrade
159/// convention for a project-scoped config file).
160/// Test: `mode::tests::settings_json_wins_over_default`,
161/// `mode::tests::missing_settings_json_is_not_an_error`,
162/// `mode::tests::malformed_settings_json_is_not_an_error`.
163fn read_settings_json_mode(project_root: &Path) -> Option<HarnessMode> {
164    let path = project_root.join(".claude").join("settings.json");
165    let raw = std::fs::read_to_string(path).ok()?;
166    let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
167    let mode_str = value.get("code_harness")?.get("mode")?.as_str()?;
168    HarnessMode::parse_lenient(mode_str)
169}
170
171/// Serializes every test in this crate that sets/reads the process-wide
172/// [`MODE_ENV_VAR`] — `cargo test` runs tests in parallel within one binary,
173/// and an unguarded `set_var`/`remove_var` pair would race across modules
174/// (both here and in `task::protocol::tests`). `pub(crate)` (not private to
175/// `tests` below) so other test modules needing to mutate the SAME env var
176/// share ONE lock, mirroring `task::mock_llm::MOCK_LLM_ENV_LOCK`'s identical
177/// cross-module rationale. A `tokio::sync::Mutex` (not `std::sync::Mutex`)
178/// because `task::protocol::tests::task_run_resolves_and_reports_mode` holds
179/// the guard across `.await` (spanning several `task_run` calls) — clippy's
180/// `await_holding_lock` correctly flags a std mutex held that way.
181#[cfg(test)]
182pub(crate) static MODE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    async fn with_env_mode<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
189        let _guard = MODE_ENV_LOCK.lock().await;
190        // SAFETY: test-only env mutation; serialized by `MODE_ENV_LOCK`.
191        unsafe {
192            match value {
193                Some(v) => std::env::set_var(MODE_ENV_VAR, v),
194                None => std::env::remove_var(MODE_ENV_VAR),
195            }
196        }
197        let result = f();
198        unsafe {
199            std::env::remove_var(MODE_ENV_VAR);
200        }
201        result
202    }
203
204    fn project_with_settings(json: Option<&str>) -> tempfile::TempDir {
205        let tmp = tempfile::tempdir().expect("tempdir");
206        if let Some(json) = json {
207            let dir = tmp.path().join(".claude");
208            std::fs::create_dir_all(&dir).expect("mkdir");
209            std::fs::write(dir.join("settings.json"), json).expect("write settings.json");
210        }
211        tmp
212    }
213
214    #[test]
215    fn wire_representation_is_kebab_case() {
216        assert_eq!(
217            serde_json::to_value(HarnessMode::DailyDriver).unwrap(),
218            serde_json::json!("daily-driver")
219        );
220        assert_eq!(
221            serde_json::to_value(HarnessMode::Parity).unwrap(),
222            serde_json::json!("parity")
223        );
224    }
225
226    #[test]
227    fn as_str_matches_serde_rename() {
228        for mode in [HarnessMode::DailyDriver, HarnessMode::Parity] {
229            assert_eq!(
230                serde_json::json!(mode.as_str()),
231                serde_json::to_value(mode).unwrap()
232            );
233        }
234    }
235
236    #[test]
237    fn parse_lenient_accepts_case_and_separator_variants() {
238        for s in ["parity", "PARITY", " Parity "] {
239            assert_eq!(HarnessMode::parse_lenient(s), Some(HarnessMode::Parity));
240        }
241        for s in [
242            "daily-driver",
243            "DAILY-DRIVER",
244            "daily_driver",
245            "dailydriver",
246        ] {
247            assert_eq!(
248                HarnessMode::parse_lenient(s),
249                Some(HarnessMode::DailyDriver)
250            );
251        }
252    }
253
254    #[test]
255    fn parse_lenient_rejects_unknown_values() {
256        assert_eq!(HarnessMode::parse_lenient("bogus"), None);
257        assert_eq!(HarnessMode::parse_lenient(""), None);
258    }
259
260    #[tokio::test]
261    async fn default_when_nothing_set() {
262        let project = project_with_settings(None);
263        with_env_mode(None, || {
264            assert_eq!(
265                resolve_mode(None, Some(project.path())),
266                HarnessMode::DailyDriver
267            );
268        })
269        .await;
270    }
271
272    /// A projectless run has no `.claude/settings.json` tier to read; it must
273    /// still resolve a mode from the remaining tiers rather than error.
274    #[tokio::test]
275    async fn projectless_skips_settings_tier_and_still_resolves() {
276        with_env_mode(None, || {
277            assert_eq!(
278                resolve_mode(None, None),
279                HarnessMode::DailyDriver,
280                "projectless must fall through to the default, not error"
281            );
282            assert_eq!(
283                resolve_mode(Some("parity"), None),
284                HarnessMode::Parity,
285                "the request's own mode must still apply when projectless"
286            );
287        })
288        .await;
289    }
290
291    #[tokio::test]
292    async fn settings_json_wins_over_default() {
293        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
294        with_env_mode(None, || {
295            assert_eq!(
296                resolve_mode(None, Some(project.path())),
297                HarnessMode::Parity
298            );
299        })
300        .await;
301    }
302
303    #[tokio::test]
304    async fn task_param_wins_over_settings_json() {
305        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
306        with_env_mode(None, || {
307            assert_eq!(
308                resolve_mode(Some("daily-driver"), Some(project.path())),
309                HarnessMode::DailyDriver
310            );
311        })
312        .await;
313    }
314
315    #[tokio::test]
316    async fn env_var_wins_over_everything() {
317        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "daily-driver"}}"#));
318        with_env_mode(Some("parity"), || {
319            assert_eq!(
320                resolve_mode(Some("daily-driver"), Some(project.path())),
321                HarnessMode::Parity
322            );
323        })
324        .await;
325    }
326
327    #[tokio::test]
328    async fn invalid_env_var_falls_through_to_next_tier() {
329        let project = project_with_settings(None);
330        with_env_mode(Some("not-a-real-mode"), || {
331            assert_eq!(
332                resolve_mode(Some("parity"), Some(project.path())),
333                HarnessMode::Parity
334            );
335        })
336        .await;
337    }
338
339    #[test]
340    fn missing_settings_json_is_not_an_error() {
341        let project = project_with_settings(None);
342        assert_eq!(read_settings_json_mode(project.path()), None);
343    }
344
345    #[test]
346    fn malformed_settings_json_is_not_an_error() {
347        let project = project_with_settings(Some("not valid json"));
348        assert_eq!(read_settings_json_mode(project.path()), None);
349    }
350}