trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Harness mode selection: `daily-driver` (token-efficient, default) vs
//! `parity` (full-schema benchmark mode) — #2059, vision spec §5.9
//! ("Reconciliation with Parity-Spec Decision D2").
//!
//! Why: the parity spec (D2) mandates byte-identical, full tool schemas
//! across every model for benchmark fairness; the production harness wants
//! deferred schemas / compaction / per-model optimisation for real coding
//! work. §5.9's resolved decision is two modes selected by a three-tier
//! precedence, rather than picking one behaviour permanently. This module
//! is ONLY the selection mechanism — resolving which mode applies to a
//! given run and making that resolution queryable. It deliberately does
//! NOT implement any token-efficiency behaviour (deferred schemas,
//! compaction, repo-map): that is P1B's job, hooking into the branch
//! points this module's callers expose (`prompt::assemble_system_prompt_for_mode`,
//! `agent_loop::AgentLoop`'s `mode`-aware `tool_definitions`). In M1 both
//! modes are functionally identical.
//!
//! **Precedence note:** §5.9 states the three-tier hierarchy, highest to
//! lowest, as: (1) `TRUSTY_CODE_MODE` env var ("escape hatch... overrides
//! all"), (2) `task.run`'s `mode` param ("overrides setting"), (3)
//! `.claude/settings.json`'s `code_harness.mode` (the configured default).
//! [`resolve_mode`] implements EXACTLY this order. (A paraphrase of this
//! ticket's delegation put the env var last instead of first; §5.9's own
//! table and the raw issue #2059 text both independently state env-var-
//! highest, so this module follows the spec verbatim — flagged explicitly
//! for the reader rather than silently reconciled.)
//!
//! What: [`HarnessMode`] (`DailyDriver` | `Parity`, `Default` =
//! `DailyDriver`), [`HarnessMode::parse_lenient`] (case/separator-tolerant
//! string parsing), and [`resolve_mode`] (the three-tier precedence chain,
//! reading the env var and `.claude/settings.json` directly — no injected
//! clock/env abstraction, matching this crate's existing
//! `task::mock_llm::build_llm_client` precedent for a small, direct
//! `std::env`/`std::fs` read in production code).
//! Test: `mode::tests::*` (precedence order, lenient parsing, unknown-value
//! degrade-to-next-tier, settings.json presence/absence/malformed-JSON).
//!
//! [`resolve_mode`]: crate::mode::resolve_mode
//! [`HarnessMode`]: crate::mode::HarnessMode
//! [`HarnessMode::parse_lenient`]: crate::mode::HarnessMode::parse_lenient

use std::path::Path;

use serde::{Deserialize, Serialize};

/// Escape-hatch environment variable (§5.9): `TRUSTY_CODE_MODE=parity` or
/// `daily-driver`. Highest precedence — overrides everything else.
pub const MODE_ENV_VAR: &str = "TRUSTY_CODE_MODE";

/// The two harness modes §5.9 resolves between.
///
/// Why: see module docs. A closed, two-variant enum (not a raw `String`)
/// so every downstream `match` is exhaustive and a typo can never silently
/// select an unintended mode.
/// What: `DailyDriver` (default; where P1B's token-efficiency layers will
/// apply) and `Parity` (full schemas, parity-spec benchmark mode). Wire
/// representation is `"daily-driver"` / `"parity"` (kebab-case), matching
/// §5.9's example JSON verbatim.
/// Test: `mode::tests::wire_representation_is_kebab_case`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HarnessMode {
    DailyDriver,
    Parity,
}

impl Default for HarnessMode {
    /// §5.9: "`daily-driver` (DEFAULT)".
    fn default() -> Self {
        HarnessMode::DailyDriver
    }
}

impl HarnessMode {
    /// The stable wire string for this mode (matches the serde
    /// `rename_all = "kebab-case"` representation).
    ///
    /// Why: callers building a plain JSON response field (`task.run`'s
    /// immediate `{"mode": ...}`, the CLI's human-readable summary line)
    /// want this without round-tripping through `serde_json`.
    /// Test: `mode::tests::as_str_matches_serde_rename`.
    pub fn as_str(&self) -> &'static str {
        match self {
            HarnessMode::DailyDriver => "daily-driver",
            HarnessMode::Parity => "parity",
        }
    }

    /// Parse a mode string leniently: case-insensitive, `_`/`-`
    /// interchangeable, surrounding whitespace ignored.
    ///
    /// Why: every precedence tier's raw value (an env var, a JSON string
    /// field, a CLI flag) is human-typed and should not require
    /// byte-perfect casing to work.
    /// What: `None` for anything that isn't recognisably `"daily-driver"`
    /// or `"parity"` — callers treat `None` as "this source does not
    /// contribute a value", falling through to the next-lower-precedence
    /// tier (see [`resolve_mode`]'s docs for why this, rather than a hard
    /// error, was chosen).
    /// Test: `mode::tests::parse_lenient_accepts_case_and_separator_variants`,
    /// `mode::tests::parse_lenient_rejects_unknown_values`.
    pub fn parse_lenient(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
            "daily-driver" | "dailydriver" => Some(HarnessMode::DailyDriver),
            "parity" => Some(HarnessMode::Parity),
            _ => None,
        }
    }
}

/// Resolve the effective [`HarnessMode`] for one `task.run` call, per §5.9's
/// three-tier precedence (highest to lowest): [`MODE_ENV_VAR`] > `task_param`
/// (the `task.run` request's own `mode` field) > `.claude/settings.json`'s
/// `code_harness.mode` > [`HarnessMode::default`].
///
/// Why: the single place this precedence is implemented, so `task::protocol`
/// never has to re-derive it.
/// What: checks each tier in order; a tier whose value is absent OR fails
/// to parse (see [`HarnessMode::parse_lenient`]'s docs — this is the
/// "clear error or fall back to default" choice this ticket asks to be
/// made explicit: an invalid value at ANY tier is treated exactly like an
/// absent one, falling through to the next tier, rather than hard-erroring
/// the whole call) is skipped.
/// `project_root` is `Option` because a projectless workstream has no project
/// and therefore no `.claude/settings.json` tier to consult — that tier is
/// simply skipped, exactly as an absent file already was. Projectless is a
/// supported state, never an error, so it still resolves a mode (env var, then
/// the request's own `mode`, then the default).
/// Test: `mode::tests::env_var_wins_over_everything`,
/// `mode::tests::task_param_wins_over_settings_json`,
/// `mode::tests::settings_json_wins_over_default`,
/// `mode::tests::default_when_nothing_set`,
/// `mode::tests::invalid_env_var_falls_through_to_next_tier`,
/// `mode::tests::projectless_skips_settings_tier_and_still_resolves`.
pub fn resolve_mode(task_param: Option<&str>, project_root: Option<&Path>) -> HarnessMode {
    if let Some(mode) = std::env::var(MODE_ENV_VAR)
        .ok()
        .and_then(|v| HarnessMode::parse_lenient(&v))
    {
        return mode;
    }
    if let Some(mode) = task_param.and_then(HarnessMode::parse_lenient) {
        return mode;
    }
    if let Some(mode) = project_root.and_then(read_settings_json_mode) {
        return mode;
    }
    HarnessMode::default()
}

/// Read the project's `settings.json` `code_harness.mode` key.
///
/// Why: the project-scoped config location §5.9's example JSON uses. #5426
/// moves it to Trusty Code's own `.trusty-code/settings.json` while keeping
/// `.claude/settings.json` readable, so a project that has not imported yet
/// still gets its configured mode.
/// What: the file comes from [`crate::paths::settings_file`] — same precedence
/// as agents, skills, and plugins. `None` when the file is missing, not valid
/// JSON, or the key is absent/unparseable; absence at any step is "this source
/// does not contribute", never an error (mirrors
/// `project_context::load_project_context`'s same graceful-degrade convention).
/// A file that resolved but then fails to READ or PARSE is a different case — a
/// config the operator wrote and expects to take effect — so it falls back to
/// the next tier with a `warn` naming the path tried, rather than silently.
/// Test: `mode::tests::settings_json_wins_over_default`,
/// `mode::tests::missing_settings_json_is_not_an_error`,
/// `mode::tests::malformed_settings_json_is_not_an_error`,
/// `mode::tests::trusty_code_settings_json_sets_the_mode_without_a_claude_dir`,
/// `mode::tests::trusty_code_settings_json_outranks_claude`.
fn read_settings_json_mode(project_root: &Path) -> Option<HarnessMode> {
    // #5426: resolved, not joined — `.trusty-code/settings.json` wins.
    let resolved = crate::paths::settings_file(project_root);
    if resolved.source == crate::paths::ConfigSource::Default {
        return None;
    }
    let path = resolved.path;
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "project settings.json resolved but could not be read; \
                 falling back to the next harness-mode tier"
            );
            return None;
        }
    };
    let value: serde_json::Value = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "project settings.json is not valid JSON; \
                 falling back to the next harness-mode tier"
            );
            return None;
        }
    };
    let mode_str = value.get("code_harness")?.get("mode")?.as_str()?;
    HarnessMode::parse_lenient(mode_str)
}

/// Serializes every test in this crate that sets/reads the process-wide
/// [`MODE_ENV_VAR`] — `cargo test` runs tests in parallel within one binary,
/// and an unguarded `set_var`/`remove_var` pair would race across modules
/// (both here and in `task::protocol::tests`). `pub(crate)` (not private to
/// `tests` below) so other test modules needing to mutate the SAME env var
/// share ONE lock, mirroring `task::mock_llm::MOCK_LLM_ENV_LOCK`'s identical
/// cross-module rationale. A `tokio::sync::Mutex` (not `std::sync::Mutex`)
/// because `task::protocol::tests::task_run_resolves_and_reports_mode` holds
/// the guard across `.await` (spanning several `task_run` calls) — clippy's
/// `await_holding_lock` correctly flags a std mutex held that way.
#[cfg(test)]
pub(crate) static MODE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

#[cfg(test)]
mod tests {
    use super::*;

    async fn with_env_mode<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
        let _guard = MODE_ENV_LOCK.lock().await;
        // SAFETY: test-only env mutation; serialized by `MODE_ENV_LOCK`.
        unsafe {
            match value {
                Some(v) => std::env::set_var(MODE_ENV_VAR, v),
                None => std::env::remove_var(MODE_ENV_VAR),
            }
        }
        let result = f();
        unsafe {
            std::env::remove_var(MODE_ENV_VAR);
        }
        result
    }

    fn project_with_settings(json: Option<&str>) -> tempfile::TempDir {
        let tmp = tempfile::tempdir().expect("tempdir");
        if let Some(json) = json {
            let dir = tmp.path().join(".claude");
            std::fs::create_dir_all(&dir).expect("mkdir");
            std::fs::write(dir.join("settings.json"), json).expect("write settings.json");
        }
        tmp
    }

    #[test]
    fn wire_representation_is_kebab_case() {
        assert_eq!(
            serde_json::to_value(HarnessMode::DailyDriver).unwrap(),
            serde_json::json!("daily-driver")
        );
        assert_eq!(
            serde_json::to_value(HarnessMode::Parity).unwrap(),
            serde_json::json!("parity")
        );
    }

    #[test]
    fn as_str_matches_serde_rename() {
        for mode in [HarnessMode::DailyDriver, HarnessMode::Parity] {
            assert_eq!(
                serde_json::json!(mode.as_str()),
                serde_json::to_value(mode).unwrap()
            );
        }
    }

    #[test]
    fn parse_lenient_accepts_case_and_separator_variants() {
        for s in ["parity", "PARITY", " Parity "] {
            assert_eq!(HarnessMode::parse_lenient(s), Some(HarnessMode::Parity));
        }
        for s in [
            "daily-driver",
            "DAILY-DRIVER",
            "daily_driver",
            "dailydriver",
        ] {
            assert_eq!(
                HarnessMode::parse_lenient(s),
                Some(HarnessMode::DailyDriver)
            );
        }
    }

    #[test]
    fn parse_lenient_rejects_unknown_values() {
        assert_eq!(HarnessMode::parse_lenient("bogus"), None);
        assert_eq!(HarnessMode::parse_lenient(""), None);
    }

    #[tokio::test]
    async fn default_when_nothing_set() {
        let project = project_with_settings(None);
        with_env_mode(None, || {
            assert_eq!(
                resolve_mode(None, Some(project.path())),
                HarnessMode::DailyDriver
            );
        })
        .await;
    }

    /// A projectless run has no `.claude/settings.json` tier to read; it must
    /// still resolve a mode from the remaining tiers rather than error.
    #[tokio::test]
    async fn projectless_skips_settings_tier_and_still_resolves() {
        with_env_mode(None, || {
            assert_eq!(
                resolve_mode(None, None),
                HarnessMode::DailyDriver,
                "projectless must fall through to the default, not error"
            );
            assert_eq!(
                resolve_mode(Some("parity"), None),
                HarnessMode::Parity,
                "the request's own mode must still apply when projectless"
            );
        })
        .await;
    }

    #[tokio::test]
    async fn settings_json_wins_over_default() {
        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
        with_env_mode(None, || {
            assert_eq!(
                resolve_mode(None, Some(project.path())),
                HarnessMode::Parity
            );
        })
        .await;
    }

    #[tokio::test]
    async fn task_param_wins_over_settings_json() {
        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "parity"}}"#));
        with_env_mode(None, || {
            assert_eq!(
                resolve_mode(Some("daily-driver"), Some(project.path())),
                HarnessMode::DailyDriver
            );
        })
        .await;
    }

    #[tokio::test]
    async fn env_var_wins_over_everything() {
        let project = project_with_settings(Some(r#"{"code_harness": {"mode": "daily-driver"}}"#));
        with_env_mode(Some("parity"), || {
            assert_eq!(
                resolve_mode(Some("daily-driver"), Some(project.path())),
                HarnessMode::Parity
            );
        })
        .await;
    }

    #[tokio::test]
    async fn invalid_env_var_falls_through_to_next_tier() {
        let project = project_with_settings(None);
        with_env_mode(Some("not-a-real-mode"), || {
            assert_eq!(
                resolve_mode(Some("parity"), Some(project.path())),
                HarnessMode::Parity
            );
        })
        .await;
    }

    #[test]
    fn missing_settings_json_is_not_an_error() {
        let project = project_with_settings(None);
        assert_eq!(read_settings_json_mode(project.path()), None);
    }

    #[test]
    fn malformed_settings_json_is_not_an_error() {
        let project = project_with_settings(Some("not valid json"));
        assert_eq!(read_settings_json_mode(project.path()), None);
    }

    /// `.trusty-code/settings.json` sets the harness mode on a project with no
    /// `.claude/` at all (#5426).
    ///
    /// Why: "a clean project can install and run without a `.claude/`
    /// directory" is not true if the mode tier still requires one. On
    /// `origin/main` this fails: `read_settings_json_mode` joined
    /// `.claude/settings.json` directly, so a `.trusty-code`-only project fell
    /// through to the default.
    /// What: writes only `.trusty-code/settings.json` and asserts the mode.
    /// Test: this function IS the test.
    #[test]
    fn trusty_code_settings_json_sets_the_mode_without_a_claude_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dir = tmp.path().join(".trusty-code");
        std::fs::create_dir_all(&dir).expect("mkdir");
        std::fs::write(
            dir.join("settings.json"),
            r#"{"code_harness": {"mode": "parity"}}"#,
        )
        .expect("write settings.json");
        assert!(!tmp.path().join(".claude").exists());

        assert_eq!(
            read_settings_json_mode(tmp.path()),
            Some(HarnessMode::Parity)
        );
    }

    /// `.trusty-code/settings.json` outranks `.claude/settings.json`.
    ///
    /// Why: the compatibility root is an input of last resort; a project that
    /// has stated its own configuration must not be overruled by the file it
    /// migrated away from.
    /// What: writes conflicting modes to both and asserts the native one wins.
    /// Test: this function IS the test.
    #[test]
    fn trusty_code_settings_json_outranks_claude() {
        let tmp = tempfile::tempdir().expect("tempdir");
        for (dirname, mode) in [(".trusty-code", "parity"), (".claude", "daily-driver")] {
            let dir = tmp.path().join(dirname);
            std::fs::create_dir_all(&dir).expect("mkdir");
            std::fs::write(
                dir.join("settings.json"),
                format!(r#"{{"code_harness": {{"mode": "{mode}"}}}}"#),
            )
            .expect("write settings.json");
        }

        assert_eq!(
            read_settings_json_mode(tmp.path()),
            Some(HarnessMode::Parity)
        );
    }
}