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 the project's `settings.json` `code_harness.mode` key.
152///
153/// Why: the project-scoped config location §5.9's example JSON uses. #5426
154/// moves it to Trusty Code's own `.trusty-code/settings.json` while keeping
155/// `.claude/settings.json` readable, so a project that has not imported yet
156/// still gets its configured mode.
157/// What: the file comes from [`crate::paths::settings_file`] — same precedence
158/// as agents, skills, and plugins. `None` when the file is missing, not valid
159/// JSON, or the key is absent/unparseable; absence at any step is "this source
160/// does not contribute", never an error (mirrors
161/// `project_context::load_project_context`'s same graceful-degrade convention).
162/// A file that resolved but then fails to READ or PARSE is a different case — a
163/// config the operator wrote and expects to take effect — so it falls back to
164/// the next tier with a `warn` naming the path tried, rather than silently.
165/// Test: `mode::tests::settings_json_wins_over_default`,
166/// `mode::tests::missing_settings_json_is_not_an_error`,
167/// `mode::tests::malformed_settings_json_is_not_an_error`,
168/// `mode::tests::trusty_code_settings_json_sets_the_mode_without_a_claude_dir`,
169/// `mode::tests::trusty_code_settings_json_outranks_claude`.
170fn read_settings_json_mode(project_root: &Path) -> Option<HarnessMode> {
171    // #5426: resolved, not joined — `.trusty-code/settings.json` wins.
172    let resolved = crate::paths::settings_file(project_root);
173    if resolved.source == crate::paths::ConfigSource::Default {
174        return None;
175    }
176    let path = resolved.path;
177    let raw = match std::fs::read_to_string(&path) {
178        Ok(raw) => raw,
179        Err(e) => {
180            tracing::warn!(
181                path = %path.display(),
182                error = %e,
183                "project settings.json resolved but could not be read; \
184                 falling back to the next harness-mode tier"
185            );
186            return None;
187        }
188    };
189    let value: serde_json::Value = match serde_json::from_str(&raw) {
190        Ok(value) => value,
191        Err(e) => {
192            tracing::warn!(
193                path = %path.display(),
194                error = %e,
195                "project settings.json is not valid JSON; \
196                 falling back to the next harness-mode tier"
197            );
198            return None;
199        }
200    };
201    let mode_str = value.get("code_harness")?.get("mode")?.as_str()?;
202    HarnessMode::parse_lenient(mode_str)
203}
204
205/// Serializes every test in this crate that sets/reads the process-wide
206/// [`MODE_ENV_VAR`] — `cargo test` runs tests in parallel within one binary,
207/// and an unguarded `set_var`/`remove_var` pair would race across modules
208/// (both here and in `task::protocol::tests`). `pub(crate)` (not private to
209/// `tests` below) so other test modules needing to mutate the SAME env var
210/// share ONE lock, mirroring `task::mock_llm::MOCK_LLM_ENV_LOCK`'s identical
211/// cross-module rationale. A `tokio::sync::Mutex` (not `std::sync::Mutex`)
212/// because `task::protocol::tests::task_run_resolves_and_reports_mode` holds
213/// the guard across `.await` (spanning several `task_run` calls) — clippy's
214/// `await_holding_lock` correctly flags a std mutex held that way.
215#[cfg(test)]
216pub(crate) static MODE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    async fn with_env_mode<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
223        let _guard = MODE_ENV_LOCK.lock().await;
224        // SAFETY: test-only env mutation; serialized by `MODE_ENV_LOCK`.
225        unsafe {
226            match value {
227                Some(v) => std::env::set_var(MODE_ENV_VAR, v),
228                None => std::env::remove_var(MODE_ENV_VAR),
229            }
230        }
231        let result = f();
232        unsafe {
233            std::env::remove_var(MODE_ENV_VAR);
234        }
235        result
236    }
237
238    fn project_with_settings(json: Option<&str>) -> tempfile::TempDir {
239        let tmp = tempfile::tempdir().expect("tempdir");
240        if let Some(json) = json {
241            let dir = tmp.path().join(".claude");
242            std::fs::create_dir_all(&dir).expect("mkdir");
243            std::fs::write(dir.join("settings.json"), json).expect("write settings.json");
244        }
245        tmp
246    }
247
248    #[test]
249    fn wire_representation_is_kebab_case() {
250        assert_eq!(
251            serde_json::to_value(HarnessMode::DailyDriver).unwrap(),
252            serde_json::json!("daily-driver")
253        );
254        assert_eq!(
255            serde_json::to_value(HarnessMode::Parity).unwrap(),
256            serde_json::json!("parity")
257        );
258    }
259
260    #[test]
261    fn as_str_matches_serde_rename() {
262        for mode in [HarnessMode::DailyDriver, HarnessMode::Parity] {
263            assert_eq!(
264                serde_json::json!(mode.as_str()),
265                serde_json::to_value(mode).unwrap()
266            );
267        }
268    }
269
270    #[test]
271    fn parse_lenient_accepts_case_and_separator_variants() {
272        for s in ["parity", "PARITY", " Parity "] {
273            assert_eq!(HarnessMode::parse_lenient(s), Some(HarnessMode::Parity));
274        }
275        for s in [
276            "daily-driver",
277            "DAILY-DRIVER",
278            "daily_driver",
279            "dailydriver",
280        ] {
281            assert_eq!(
282                HarnessMode::parse_lenient(s),
283                Some(HarnessMode::DailyDriver)
284            );
285        }
286    }
287
288    #[test]
289    fn parse_lenient_rejects_unknown_values() {
290        assert_eq!(HarnessMode::parse_lenient("bogus"), None);
291        assert_eq!(HarnessMode::parse_lenient(""), None);
292    }
293
294    #[tokio::test]
295    async fn default_when_nothing_set() {
296        let project = project_with_settings(None);
297        with_env_mode(None, || {
298            assert_eq!(
299                resolve_mode(None, Some(project.path())),
300                HarnessMode::DailyDriver
301            );
302        })
303        .await;
304    }
305
306    /// A projectless run has no `.claude/settings.json` tier to read; it must
307    /// still resolve a mode from the remaining tiers rather than error.
308    #[tokio::test]
309    async fn projectless_skips_settings_tier_and_still_resolves() {
310        with_env_mode(None, || {
311            assert_eq!(
312                resolve_mode(None, None),
313                HarnessMode::DailyDriver,
314                "projectless must fall through to the default, not error"
315            );
316            assert_eq!(
317                resolve_mode(Some("parity"), None),
318                HarnessMode::Parity,
319                "the request's own mode must still apply when projectless"
320            );
321        })
322        .await;
323    }
324
325    #[tokio::test]
326    async fn settings_json_wins_over_default() {
327        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
328        with_env_mode(None, || {
329            assert_eq!(
330                resolve_mode(None, Some(project.path())),
331                HarnessMode::Parity
332            );
333        })
334        .await;
335    }
336
337    #[tokio::test]
338    async fn task_param_wins_over_settings_json() {
339        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
340        with_env_mode(None, || {
341            assert_eq!(
342                resolve_mode(Some("daily-driver"), Some(project.path())),
343                HarnessMode::DailyDriver
344            );
345        })
346        .await;
347    }
348
349    #[tokio::test]
350    async fn env_var_wins_over_everything() {
351        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "daily-driver"}}"#));
352        with_env_mode(Some("parity"), || {
353            assert_eq!(
354                resolve_mode(Some("daily-driver"), Some(project.path())),
355                HarnessMode::Parity
356            );
357        })
358        .await;
359    }
360
361    #[tokio::test]
362    async fn invalid_env_var_falls_through_to_next_tier() {
363        let project = project_with_settings(None);
364        with_env_mode(Some("not-a-real-mode"), || {
365            assert_eq!(
366                resolve_mode(Some("parity"), Some(project.path())),
367                HarnessMode::Parity
368            );
369        })
370        .await;
371    }
372
373    #[test]
374    fn missing_settings_json_is_not_an_error() {
375        let project = project_with_settings(None);
376        assert_eq!(read_settings_json_mode(project.path()), None);
377    }
378
379    #[test]
380    fn malformed_settings_json_is_not_an_error() {
381        let project = project_with_settings(Some("not valid json"));
382        assert_eq!(read_settings_json_mode(project.path()), None);
383    }
384
385    /// `.trusty-code/settings.json` sets the harness mode on a project with no
386    /// `.claude/` at all (#5426).
387    ///
388    /// Why: "a clean project can install and run without a `.claude/`
389    /// directory" is not true if the mode tier still requires one. On
390    /// `origin/main` this fails: `read_settings_json_mode` joined
391    /// `.claude/settings.json` directly, so a `.trusty-code`-only project fell
392    /// through to the default.
393    /// What: writes only `.trusty-code/settings.json` and asserts the mode.
394    /// Test: this function IS the test.
395    #[test]
396    fn trusty_code_settings_json_sets_the_mode_without_a_claude_dir() {
397        let tmp = tempfile::tempdir().expect("tempdir");
398        let dir = tmp.path().join(".trusty-code");
399        std::fs::create_dir_all(&dir).expect("mkdir");
400        std::fs::write(
401            dir.join("settings.json"),
402            r#"{"code_harness": {"mode": "parity"}}"#,
403        )
404        .expect("write settings.json");
405        assert!(!tmp.path().join(".claude").exists());
406
407        assert_eq!(
408            read_settings_json_mode(tmp.path()),
409            Some(HarnessMode::Parity)
410        );
411    }
412
413    /// `.trusty-code/settings.json` outranks `.claude/settings.json`.
414    ///
415    /// Why: the compatibility root is an input of last resort; a project that
416    /// has stated its own configuration must not be overruled by the file it
417    /// migrated away from.
418    /// What: writes conflicting modes to both and asserts the native one wins.
419    /// Test: this function IS the test.
420    #[test]
421    fn trusty_code_settings_json_outranks_claude() {
422        let tmp = tempfile::tempdir().expect("tempdir");
423        for (dirname, mode) in [(".trusty-code", "parity"), (".claude", "daily-driver")] {
424            let dir = tmp.path().join(dirname);
425            std::fs::create_dir_all(&dir).expect("mkdir");
426            std::fs::write(
427                dir.join("settings.json"),
428                format!(r#"{{"code_harness": {{"mode": "{mode}"}}}}"#),
429            )
430            .expect("write settings.json");
431        }
432
433        assert_eq!(
434            read_settings_json_mode(tmp.path()),
435            Some(HarnessMode::Parity)
436        );
437    }
438}