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
38use std::path::Path;
39
40use serde::{Deserialize, Serialize};
41
42/// Escape-hatch environment variable (§5.9): `TRUSTY_CODE_MODE=parity` or
43/// `daily-driver`. Highest precedence — overrides everything else.
44pub const MODE_ENV_VAR: &str = "TRUSTY_CODE_MODE";
45
46/// The two harness modes §5.9 resolves between.
47///
48/// Why: see module docs. A closed, two-variant enum (not a raw `String`)
49/// so every downstream `match` is exhaustive and a typo can never silently
50/// select an unintended mode.
51/// What: `DailyDriver` (default; where P1B's token-efficiency layers will
52/// apply) and `Parity` (full schemas, parity-spec benchmark mode). Wire
53/// representation is `"daily-driver"` / `"parity"` (kebab-case), matching
54/// §5.9's example JSON verbatim.
55/// Test: `mode::tests::wire_representation_is_kebab_case`.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum HarnessMode {
59    DailyDriver,
60    Parity,
61}
62
63impl Default for HarnessMode {
64    /// §5.9: "`daily-driver` (DEFAULT)".
65    fn default() -> Self {
66        HarnessMode::DailyDriver
67    }
68}
69
70impl HarnessMode {
71    /// The stable wire string for this mode (matches the serde
72    /// `rename_all = "kebab-case"` representation).
73    ///
74    /// Why: callers building a plain JSON response field (`task.run`'s
75    /// immediate `{"mode": ...}`, the CLI's human-readable summary line)
76    /// want this without round-tripping through `serde_json`.
77    /// Test: `mode::tests::as_str_matches_serde_rename`.
78    pub fn as_str(&self) -> &'static str {
79        match self {
80            HarnessMode::DailyDriver => "daily-driver",
81            HarnessMode::Parity => "parity",
82        }
83    }
84
85    /// Parse a mode string leniently: case-insensitive, `_`/`-`
86    /// interchangeable, surrounding whitespace ignored.
87    ///
88    /// Why: every precedence tier's raw value (an env var, a JSON string
89    /// field, a CLI flag) is human-typed and should not require
90    /// byte-perfect casing to work.
91    /// What: `None` for anything that isn't recognisably `"daily-driver"`
92    /// or `"parity"` — callers treat `None` as "this source does not
93    /// contribute a value", falling through to the next-lower-precedence
94    /// tier (see [`resolve_mode`]'s docs for why this, rather than a hard
95    /// error, was chosen).
96    /// Test: `mode::tests::parse_lenient_accepts_case_and_separator_variants`,
97    /// `mode::tests::parse_lenient_rejects_unknown_values`.
98    pub fn parse_lenient(s: &str) -> Option<Self> {
99        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
100            "daily-driver" | "dailydriver" => Some(HarnessMode::DailyDriver),
101            "parity" => Some(HarnessMode::Parity),
102            _ => None,
103        }
104    }
105}
106
107/// Resolve the effective [`HarnessMode`] for one `task.run` call, per §5.9's
108/// three-tier precedence (highest to lowest): [`MODE_ENV_VAR`] > `task_param`
109/// (the `task.run` request's own `mode` field) > `.claude/settings.json`'s
110/// `code_harness.mode` > [`HarnessMode::default`].
111///
112/// Why: the single place this precedence is implemented, so `task::protocol`
113/// never has to re-derive it.
114/// What: checks each tier in order; a tier whose value is absent OR fails
115/// to parse (see [`HarnessMode::parse_lenient`]'s docs — this is the
116/// "clear error or fall back to default" choice this ticket asks to be
117/// made explicit: an invalid value at ANY tier is treated exactly like an
118/// absent one, falling through to the next tier, rather than hard-erroring
119/// the whole call) is skipped.
120/// Test: `mode::tests::env_var_wins_over_everything`,
121/// `mode::tests::task_param_wins_over_settings_json`,
122/// `mode::tests::settings_json_wins_over_default`,
123/// `mode::tests::default_when_nothing_set`,
124/// `mode::tests::invalid_env_var_falls_through_to_next_tier`.
125pub fn resolve_mode(task_param: Option<&str>, project_root: &Path) -> HarnessMode {
126    if let Some(mode) = std::env::var(MODE_ENV_VAR)
127        .ok()
128        .and_then(|v| HarnessMode::parse_lenient(&v))
129    {
130        return mode;
131    }
132    if let Some(mode) = task_param.and_then(HarnessMode::parse_lenient) {
133        return mode;
134    }
135    if let Some(mode) = read_settings_json_mode(project_root) {
136        return mode;
137    }
138    HarnessMode::default()
139}
140
141/// Read `<project_root>/.claude/settings.json`'s `code_harness.mode` key.
142///
143/// Why: the Claude-Code-compatible, project-scoped config location §5.9's
144/// example JSON uses.
145/// What: `None` when the file is missing, unreadable, not valid JSON, or
146/// the key is absent/unparseable — absence at any step is "this source
147/// does not contribute", never an error (mirrors
148/// `project_context::load_project_context`'s same graceful-degrade
149/// convention for a project-scoped config file).
150/// Test: `mode::tests::settings_json_wins_over_default`,
151/// `mode::tests::missing_settings_json_is_not_an_error`,
152/// `mode::tests::malformed_settings_json_is_not_an_error`.
153fn read_settings_json_mode(project_root: &Path) -> Option<HarnessMode> {
154    let path = project_root.join(".claude").join("settings.json");
155    let raw = std::fs::read_to_string(path).ok()?;
156    let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
157    let mode_str = value.get("code_harness")?.get("mode")?.as_str()?;
158    HarnessMode::parse_lenient(mode_str)
159}
160
161/// Serializes every test in this crate that sets/reads the process-wide
162/// [`MODE_ENV_VAR`] — `cargo test` runs tests in parallel within one binary,
163/// and an unguarded `set_var`/`remove_var` pair would race across modules
164/// (both here and in `task::protocol::tests`). `pub(crate)` (not private to
165/// `tests` below) so other test modules needing to mutate the SAME env var
166/// share ONE lock, mirroring `task::mock_llm::MOCK_LLM_ENV_LOCK`'s identical
167/// cross-module rationale. A `tokio::sync::Mutex` (not `std::sync::Mutex`)
168/// because `task::protocol::tests::task_run_resolves_and_reports_mode` holds
169/// the guard across `.await` (spanning several `task_run` calls) — clippy's
170/// `await_holding_lock` correctly flags a std mutex held that way.
171#[cfg(test)]
172pub(crate) static MODE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    async fn with_env_mode<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
179        let _guard = MODE_ENV_LOCK.lock().await;
180        // SAFETY: test-only env mutation; serialized by `MODE_ENV_LOCK`.
181        unsafe {
182            match value {
183                Some(v) => std::env::set_var(MODE_ENV_VAR, v),
184                None => std::env::remove_var(MODE_ENV_VAR),
185            }
186        }
187        let result = f();
188        unsafe {
189            std::env::remove_var(MODE_ENV_VAR);
190        }
191        result
192    }
193
194    fn project_with_settings(json: Option<&str>) -> tempfile::TempDir {
195        let tmp = tempfile::tempdir().expect("tempdir");
196        if let Some(json) = json {
197            let dir = tmp.path().join(".claude");
198            std::fs::create_dir_all(&dir).expect("mkdir");
199            std::fs::write(dir.join("settings.json"), json).expect("write settings.json");
200        }
201        tmp
202    }
203
204    #[test]
205    fn wire_representation_is_kebab_case() {
206        assert_eq!(
207            serde_json::to_value(HarnessMode::DailyDriver).unwrap(),
208            serde_json::json!("daily-driver")
209        );
210        assert_eq!(
211            serde_json::to_value(HarnessMode::Parity).unwrap(),
212            serde_json::json!("parity")
213        );
214    }
215
216    #[test]
217    fn as_str_matches_serde_rename() {
218        for mode in [HarnessMode::DailyDriver, HarnessMode::Parity] {
219            assert_eq!(
220                serde_json::json!(mode.as_str()),
221                serde_json::to_value(mode).unwrap()
222            );
223        }
224    }
225
226    #[test]
227    fn parse_lenient_accepts_case_and_separator_variants() {
228        for s in ["parity", "PARITY", " Parity "] {
229            assert_eq!(HarnessMode::parse_lenient(s), Some(HarnessMode::Parity));
230        }
231        for s in [
232            "daily-driver",
233            "DAILY-DRIVER",
234            "daily_driver",
235            "dailydriver",
236        ] {
237            assert_eq!(
238                HarnessMode::parse_lenient(s),
239                Some(HarnessMode::DailyDriver)
240            );
241        }
242    }
243
244    #[test]
245    fn parse_lenient_rejects_unknown_values() {
246        assert_eq!(HarnessMode::parse_lenient("bogus"), None);
247        assert_eq!(HarnessMode::parse_lenient(""), None);
248    }
249
250    #[tokio::test]
251    async fn default_when_nothing_set() {
252        let project = project_with_settings(None);
253        with_env_mode(None, || {
254            assert_eq!(resolve_mode(None, project.path()), HarnessMode::DailyDriver);
255        })
256        .await;
257    }
258
259    #[tokio::test]
260    async fn settings_json_wins_over_default() {
261        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
262        with_env_mode(None, || {
263            assert_eq!(resolve_mode(None, project.path()), HarnessMode::Parity);
264        })
265        .await;
266    }
267
268    #[tokio::test]
269    async fn task_param_wins_over_settings_json() {
270        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
271        with_env_mode(None, || {
272            assert_eq!(
273                resolve_mode(Some("daily-driver"), project.path()),
274                HarnessMode::DailyDriver
275            );
276        })
277        .await;
278    }
279
280    #[tokio::test]
281    async fn env_var_wins_over_everything() {
282        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "daily-driver"}}"#));
283        with_env_mode(Some("parity"), || {
284            assert_eq!(
285                resolve_mode(Some("daily-driver"), project.path()),
286                HarnessMode::Parity
287            );
288        })
289        .await;
290    }
291
292    #[tokio::test]
293    async fn invalid_env_var_falls_through_to_next_tier() {
294        let project = project_with_settings(None);
295        with_env_mode(Some("not-a-real-mode"), || {
296            assert_eq!(
297                resolve_mode(Some("parity"), project.path()),
298                HarnessMode::Parity
299            );
300        })
301        .await;
302    }
303
304    #[test]
305    fn missing_settings_json_is_not_an_error() {
306        let project = project_with_settings(None);
307        assert_eq!(read_settings_json_mode(project.path()), None);
308    }
309
310    #[test]
311    fn malformed_settings_json_is_not_an_error() {
312        let project = project_with_settings(Some("not valid json"));
313        assert_eq!(read_settings_json_mode(project.path()), None);
314    }
315}