trusty-mpm 1.3.4

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Clone or refresh a managed project workspace for a registered alias.
//!
//! Why: `tm load <alias>` is the idempotent entry point that turns a registered
//! name into a ready-to-drive, isolated project directory (DOC-24
//! SPEC-STANDALONE-MPM-02). Making it idempotent (clone-once, refresh-many)
//! means `run` can call it unconditionally and it also serves as the
//! "bring this project up to date" verb.
//! What: [`load_alias`] resolves the alias from the registry, clones (or
//! fast-forward-pulls) the repo into
//! `<managed_root>/projects/<alias>/repo/`, runs `prepare_session` from the
//! session-launch core, writes `.trusty-mpm/managed.toml`, and returns the
//! absolute path to `repo/`.
//! Test: unit tests for the marker-file write logic; git operations are
//! integration-only (require network/git binary).

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::Context;
use serde::{Deserialize, Serialize};

use super::registry::ManagedRegistry;

/// The marker file written into every managed project.
///
/// Why: the marker lets `path`, `ls`, `rm`, and `update` know a directory is
/// tm-managed and carries the metadata needed to replay a launch deterministically
/// (DOC-24 SPEC-STANDALONE-MPM-03d).
/// What: a TOML struct at `.trusty-mpm/managed.toml`.
/// Test: `test_marker_write_round_trip`.
#[derive(Debug, Serialize, Deserialize)]
pub struct ManagedMarker {
    /// The alias this project was cloned from.
    pub alias: String,
    /// The clone URL.
    pub url: String,
    /// Sentinel for the branch/ref intent (currently always `"default"`, meaning
    /// the remote's default branch was cloned without `-b`; branch selection is
    /// a future enhancement — do not interpret this as a literal Git ref name).
    pub git_ref: String,
    /// Absolute path to the tm-global CLAUDE_CONFIG_DIR.
    pub claude_config_dir: String,
}

/// Load (clone or refresh) the managed workspace for `alias`.
///
/// Why: the idempotent load verb is the load-bearing primitive behind `run`;
/// separating it lets callers (`tm load`, `tm run`) both call it without
/// duplicating the clone/prepare logic.
/// What:
/// 1. Looks up the alias in the registry under `managed_root`.
/// 2. Derives `<managed_root>/projects/<alias>/repo/` as the checkout dir.
/// 3. If `repo/` doesn't exist: clones via `git clone --depth 1 <url> repo/`.
/// 4. If `repo/` exists: `git -C repo/ pull --ff-only` (best-effort, non-fatal).
/// 5. Runs `prepare_session` from `crate::core::session_launch` on `repo/`.
/// 6. Writes `.trusty-mpm/managed.toml`.
/// 7. (WI-3) Pre-seeds project trust + MCP-server approval into
///    `<claude_config_dir>/.claude.json` via [`super::trust_seed::preseed_managed_trust`].
/// 8. Returns the absolute `PathBuf` to `repo/`.
///
/// The trust seed (step 7) writes ONLY into `<claude_config_dir>` — never to
/// `~/.claude.json` or `~/.claude/` (isolation invariant, WI-7).
///
/// Test: `test_marker_write_round_trip` (marker); git operations require network.
pub fn load_alias(
    alias: &str,
    managed_root: &Path,
    claude_config_dir: &Path,
) -> anyhow::Result<PathBuf> {
    let registry = ManagedRegistry::load(managed_root)
        .with_context(|| format!("failed to load registry from {}", managed_root.display()))?;
    let entry = registry
        .get(alias)
        .with_context(|| format!("alias '{alias}' is not registered"))?;
    let url = entry.url.clone();
    let git_ref = entry.git_ref.clone();

    let project_dir = managed_root.join("projects").join(alias);
    let repo_dir = project_dir.join("repo");

    if !repo_dir.exists() {
        clone_repo(&url, &project_dir)?;
    } else {
        pull_ff_only(&repo_dir);
    }

    // Issue #1651: thread the registry clone `url` as the authoritative git
    // remote so the per-project `repo/.mcp.json` pins `TRUSTY_MEMORY_PALACE` to
    // the repo's canonical `owner-repo` slug (the same `derive_palace_id`
    // mechanism #1605 uses for the per-project injection). The clone URL is more
    // authoritative than probing the checkout's own origin remote (which a
    // shallow / renamed / origin-less clone might lack); the operator
    // `TRUSTY_MEMORY_PALACE` override still wins over it per `derive_palace_id`
    // precedence.
    let pins = run_prepare_session(&repo_dir, Some(&url), managed_root)?;
    write_marker(&repo_dir, alias, &url, &git_ref, claude_config_dir)?;

    // Issue #3950 (fifth instance, follow-up to #3934): `pins` carries each
    // builtin's ACTUAL per-run pin result — read straight off the
    // `PrepReport` the `run_prepare_session` call above already produced —
    // rather than re-deriving from the manifest toggle alone. A previous
    // version of this call re-resolved just the `trusty-memory`/
    // `trusty-search` manifest toggle via `resolve_conditional_mcp_toggles`,
    // which reflected only whether the injector was ATTEMPTED, not whether
    // its write actually SUCCEEDED (disk full, permission error, transient
    // I/O fault) — and never gated the two unconditional builtins
    // (`trusty-mpm`/`trusty-review`) on their own write result at all.
    // Passing a hardcoded `true, true, true, true` (or any value not sourced
    // from this run's actual injector outcomes) to the trust-seed call below
    // reopens the exact vulnerability this fixes: a spoofed or stale
    // `.mcp.json` entry surviving a failed or disabled force-overwrite would
    // then get its name pre-approved with unverified content behind it.

    // WI-3 sub-parts 2+3: pre-seed project trust + MCP-server approval into
    // <claude_config_dir>/.claude.json so managed sessions start without dialogs.
    // Writes ONLY to <claude_config_dir>/.claude.json — never to ~/.claude.json.
    // Non-fatal: a seed failure only means the operator may see the trust dialog.
    if let Err(err) = super::trust_seed::preseed_managed_trust(
        claude_config_dir,
        &repo_dir,
        pins.trusty_mpm,
        pins.trusty_review,
        pins.trusty_memory,
        pins.trusty_search,
    ) {
        tracing::warn!("failed to pre-seed managed trust for '{alias}': {err}");
    }

    Ok(repo_dir)
}

/// Each framework builtin's ACTUAL per-run `.mcp.json` pin result, as
/// observed by [`run_prepare_session`]'s `prepare_session_with_repo_url` call
/// (issue #3950).
///
/// Why: a bare `(bool, bool, bool, bool)` tuple returned across a function
/// boundary is easy to mis-order (e.g. swapping `trusty_mpm`/`trusty_review`
/// silently type-checks); this struct names each field so a transposition
/// bug is a compile-time field-name error instead of a silent security gap.
/// What: `true` when that name's force-overwrite injector's `Result` was
/// `Ok` THIS run (for `trusty_memory`/`trusty_search`, additionally gated on
/// the manifest toggle having been on — see
/// [`crate::core::session_launch::PrepReport`]'s `trusty_*_injected` fields,
/// which this struct mirrors verbatim).
#[derive(Debug, Clone, Copy)]
struct InjectedMcpPins {
    trusty_mpm: bool,
    trusty_review: bool,
    trusty_memory: bool,
    trusty_search: bool,
}

/// Clone the repository into `<project_dir>/repo/`.
///
/// Why: `git clone` is the authoritative way to get a fresh checkout;
/// shelling out avoids a heavy libgit2 dependency.
/// What: runs `git clone --depth 1 <url> repo/` in `project_dir`, creating
/// the directory first.
/// Test: integration-only (requires git binary + network).
fn clone_repo(url: &str, project_dir: &Path) -> anyhow::Result<()> {
    std::fs::create_dir_all(project_dir).with_context(|| {
        format!(
            "failed to create project directory {}",
            project_dir.display()
        )
    })?;
    let status = Command::new("git")
        .args(["clone", "--depth", "1", url, "repo"])
        .current_dir(project_dir)
        .status()
        .context("failed to spawn git clone")?;
    if !status.success() {
        anyhow::bail!("git clone failed for '{url}'");
    }
    Ok(())
}

/// Attempt a fast-forward pull; non-fatal on any failure.
///
/// Why: idempotent `load` should refresh an existing checkout but must never
/// destroy user edits — fast-forward only is the safest pull strategy.
/// What: runs `git -C <repo_dir> pull --ff-only`; silently ignores failures
/// (dirty tree, network unavailable) so a load with local modifications still
/// succeeds.
/// Test: integration-only.
fn pull_ff_only(repo_dir: &Path) {
    let result = Command::new("git")
        .args(["pull", "--ff-only"])
        .current_dir(repo_dir)
        .status();
    if let Ok(status) = result
        && !status.success()
    {
        eprintln!(
            "warning: git pull --ff-only failed in {}; skipping refresh",
            repo_dir.display()
        );
    }
}

/// Run `prepare_session` on the given repo directory, pinning the palace to the
/// cloned-from `repo_url` (issue #1651).
///
/// Why: `prepare_session` deploys composed agents, skills, and CLAUDE.md so the
/// project-local half of the managed configuration is complete — and (issue
/// #1605/#1651) injects the per-project `repo/.mcp.json` trusty-memory stub.
/// Threading the registry clone URL as the authoritative git remote makes the
/// injector pin `env.TRUSTY_MEMORY_PALACE` to the repo's canonical `owner-repo`
/// slug (the highest-precedence `derive_palace_id` source after the operator
/// override), so the managed session lands in the SAME palace a non-tm Claude
/// session in that repo would use. `None` falls back to probing the checkout's
/// own `git remote get-url origin`, then to the directory-basename slug.
///
/// Issue #1927 (DOC-24 SPEC-STANDALONE-MPM-04): this previously resolved
/// `FrameworkPaths::default()`, which always deploys composed agents/skills
/// under the REAL `$HOME/.claude/{agents,skills}` — a direct isolation-invariant
/// violation for the "fully isolated" standalone driver. `load_alias` already
/// carries `managed_root` (the shared framework install, e.g. `~/.trusty-mpm` or
/// an operator override), so it is threaded here and combined with `repo_dir`
/// via `FrameworkPaths::for_managed_project`, which keeps every framework SOURCE
/// path (agent/skill templates, hooks, instructions, catalog root) resolving
/// from `managed_root` exactly as before, while re-targeting ONLY the deploy
/// destination to the project-local `repo_dir/.claude/{agents,skills}` tree
/// (SPEC-STANDALONE-MPM-04 item 1). This is intentionally distinct from — and
/// not a redundant re-deploy of — the tm-global `<managed_root>/claude-config/`
/// deploy that `core::standalone::global_config::ensure_global_config_dir`
/// performs separately (and earlier) in every CLI command handler that calls
/// `load_alias`: the two writes target two different trees that Claude Code
/// merges (tm-global ⊕ project-local), matching the DOC-24 layering model.
/// What: resolves `FrameworkPaths::for_managed_project(managed_root, repo_dir)`
/// and calls `crate::core::session_launch::prepare_session_with_repo_url`,
/// forwarding `repo_url` to the trusty-memory MCP palace-slug derivation.
/// Returns the [`InjectedMcpPins`] the resulting `PrepReport` actually
/// observed (issue #3950) so the caller can gate `enabledMcpjsonServers`
/// membership on real per-run write success instead of re-deriving from the
/// manifest toggle alone.
/// Test: `run_prepare_session_pins_palace_from_clone_url`,
/// `run_prepare_session_bare_stub_when_no_identity`,
/// `run_prepare_session_never_writes_real_home_claude_dirs`,
/// `run_prepare_session_reports_all_pins_true_on_success`,
/// `load_alias_excludes_builtins_from_managed_trust_when_mcp_json_write_fails`;
/// `prepare_session` itself is covered in session_launch/tests.rs.
fn run_prepare_session(
    repo_dir: &Path,
    repo_url: Option<&str>,
    managed_root: &Path,
) -> anyhow::Result<InjectedMcpPins> {
    let fw = crate::core::paths::FrameworkPaths::for_managed_project(managed_root, repo_dir);
    let report =
        crate::core::session_launch::prepare_session_with_repo_url(&fw, repo_dir, repo_url)
            .map_err(|e| anyhow::anyhow!("prepare_session failed: {e}"))?;
    // Issue #2149: a roster-deploy failure no longer aborts preparation —
    // surface it loudly rather than let it hide behind a silent `Ok(())`.
    for err in &report.roster_errors {
        tracing::error!(
            repo_dir = %repo_dir.display(),
            "roster provisioning gap (session still launches with its trusty-mpm identity): {err}"
        );
    }
    Ok(InjectedMcpPins {
        trusty_mpm: report.trusty_mpm_injected,
        trusty_review: report.trusty_review_injected,
        trusty_memory: report.trusty_memory_injected,
        trusty_search: report.trusty_search_injected,
    })
}

/// Write `.trusty-mpm/managed.toml` into the repo directory.
///
/// Why: the marker lets every other lifecycle verb (`path`, `ls`, `rm`) detect
/// a managed directory and read the metadata needed to replay a launch.
/// What: creates `.trusty-mpm/` if absent, serializes [`ManagedMarker`] to
/// TOML, and writes `managed.toml`.
/// Test: `test_marker_write_round_trip`.
fn write_marker(
    repo_dir: &Path,
    alias: &str,
    url: &str,
    git_ref: &str,
    claude_config_dir: &Path,
) -> anyhow::Result<()> {
    let dot_dir = repo_dir.join(".trusty-mpm");
    std::fs::create_dir_all(&dot_dir)
        .with_context(|| format!("failed to create {}", dot_dir.display()))?;
    let marker = ManagedMarker {
        alias: alias.to_string(),
        url: url.to_string(),
        git_ref: git_ref.to_string(),
        claude_config_dir: claude_config_dir.to_string_lossy().to_string(),
    };
    let toml = toml::to_string_pretty(&marker).context("failed to serialize managed.toml")?;
    std::fs::write(dot_dir.join("managed.toml"), toml)
        .context("failed to write .trusty-mpm/managed.toml")?;
    Ok(())
}

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

    /// RAII guard that clears an env var for the duration of a test and restores
    /// the prior value on drop.
    ///
    /// Why: the palace-pin test must be hermetic against an ambient
    /// `TRUSTY_MEMORY_PALACE` override (which `derive_palace_id` honours at
    /// highest precedence and would otherwise mask the URL-derived slug).
    /// What: snapshots the prior value, removes the var, and restores it on drop.
    /// Pairs with `#[serial_test::serial]` so concurrent tests never race on the
    /// shared process environment.
    /// Test: used by `run_prepare_session_pins_palace_from_clone_url`.
    struct EnvClearGuard {
        key: &'static str,
        prior: Option<String>,
    }

    impl EnvClearGuard {
        fn clear(key: &'static str) -> Self {
            let prior = std::env::var(key).ok();
            // SAFETY: tests run serially under `#[serial_test::serial]`, so no
            // other thread reads/writes the environment concurrently.
            unsafe { std::env::remove_var(key) };
            Self { key, prior }
        }
    }

    impl Drop for EnvClearGuard {
        fn drop(&mut self) {
            // SAFETY: see `clear`.
            unsafe {
                match self.prior.take() {
                    Some(v) => std::env::set_var(self.key, v),
                    None => std::env::remove_var(self.key),
                }
            }
        }
    }

    /// Why (issue #1651): the standalone `load` path must pin the per-project
    /// `repo/.mcp.json` trusty-memory palace to the registry CLONE URL's
    /// canonical `owner-repo` slug — the same `derive_palace_id` mechanism #1605
    /// uses — rather than leaving a bare stub or relying on probing the
    /// checkout's own origin remote. Threading the clone URL explicitly is the
    /// authoritative identity (a shallow/origin-less clone might lack a remote).
    /// What: runs `run_prepare_session` on a repo dir with an explicit clone URL
    /// and asserts the injected `.mcp.json` carries
    /// `env.TRUSTY_MEMORY_PALACE == "bobmatnyc-trusty-tools"`.
    /// Test: itself.
    #[test]
    #[serial_test::serial]
    fn run_prepare_session_pins_palace_from_clone_url() {
        // Hermetic: an ambient override would win over the URL-derived slug.
        let _guard = EnvClearGuard::clear("TRUSTY_MEMORY_PALACE");
        // #3965: `run_prepare_session` drives `prepare_session`, which seeds
        // `$HOME/.claude.json` via the REAL process `$HOME` (not a param this
        // function takes) — point `$HOME` at a throwaway dir so this never
        // writes into the operator's real file. See `HomeGuard` below.
        let fake_home = crate::test_support::hermetic_temp_dir();
        let _home_guard = {
            let prior = std::env::var("HOME").ok();
            // SAFETY: serialized via `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", fake_home.path()) };
            HomeGuard(prior)
        };
        let tmp = crate::test_support::hermetic_temp_dir();
        // Deliberately a session-id-like basename: the pin must come from the
        // clone URL, NOT this directory name.
        let repo = tmp.path().join("0c8f1a2b3c4d");
        std::fs::create_dir_all(&repo).unwrap();
        let managed_root = tmp.path().join("managed-root");

        run_prepare_session(
            &repo,
            Some("git@github.com:bobmatnyc/trusty-tools.git"),
            &managed_root,
        )
        .expect("run_prepare_session succeeds");

        let mcp_path = repo.join(".mcp.json");
        assert!(
            mcp_path.exists(),
            "run_prepare_session must write repo/.mcp.json"
        );
        let value: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&mcp_path).unwrap()).unwrap();
        assert_eq!(
            value["mcpServers"]["trusty-memory"]["env"]["TRUSTY_MEMORY_PALACE"],
            serde_json::json!("bobmatnyc-trusty-tools"),
            "standalone load must pin the palace to the clone URL's owner-repo slug, \
             not the workspace basename"
        );
    }

    /// Why (issue #1651): when no clone URL is threaded AND the checkout has no
    /// git origin remote AND no env override, the injection must fail open with
    /// a BARE trusty-memory stub (no `env` key) so the session still gets the
    /// memory tools — backward-compatible with the pre-#1651 behaviour.
    /// What: runs `run_prepare_session(repo, None)` on a non-repo dir whose
    /// basename does not slugify and asserts the trusty-memory block has no
    /// `TRUSTY_MEMORY_PALACE` pin. (A non-empty basename would fall back to the
    /// parent-dir slug, so we assert only the no-`env` shape is preserved when
    /// pinning is impossible.)
    /// Test: itself.
    #[test]
    #[serial_test::serial]
    fn run_prepare_session_bare_stub_when_no_identity() {
        let _guard = EnvClearGuard::clear("TRUSTY_MEMORY_PALACE");
        // #3965: `$HOME` override — see `run_prepare_session_pins_palace_from_clone_url`.
        let fake_home = crate::test_support::hermetic_temp_dir();
        let _home_guard = {
            let prior = std::env::var("HOME").ok();
            // SAFETY: serialized via `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", fake_home.path()) };
            HomeGuard(prior)
        };
        let tmp = crate::test_support::hermetic_temp_dir();
        // A basename that slugifies to empty (only separators) cannot yield a
        // parent-dir slug, so with no URL/remote/override the stub stays bare.
        let repo = tmp.path().join("---");
        std::fs::create_dir_all(&repo).unwrap();
        let managed_root = tmp.path().join("managed-root");

        run_prepare_session(&repo, None, &managed_root).expect("run_prepare_session succeeds");

        let value: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(repo.join(".mcp.json")).unwrap())
                .unwrap();
        let memory = &value["mcpServers"]["trusty-memory"];
        assert_eq!(
            memory["command"],
            serde_json::json!("trusty-memory"),
            "the trusty-memory stub must still be present"
        );
        assert!(
            memory.get("env").is_none(),
            "with no derivable identity the stub must be bare (no TRUSTY_MEMORY_PALACE env); got {memory}"
        );
    }

    /// RAII guard restoring `$HOME` on drop (including panic) — mirrors the
    /// identical pattern in `standalone::global_config::tests::test_mcp_config_review_no_home_write`.
    ///
    /// Why: the isolation regression test below must point the process at a
    /// throwaway `$HOME` so a bug (`FrameworkPaths::default()`) would write to
    /// that FAKE home, not the developer's real `~/.claude`; the guard makes
    /// this safe under panics and keeps `$HOME` correct for tests that run
    /// after this one.
    /// What: snapshots the prior `$HOME` value and restores it on drop.
    /// Test: used by `run_prepare_session_never_writes_real_home_claude_dirs`.
    struct HomeGuard(Option<String>);
    impl Drop for HomeGuard {
        fn drop(&mut self) {
            // SAFETY: paired with `#[serial_test::serial]` below — no other
            // thread reads/writes the environment concurrently.
            match self.0 {
                Some(ref p) => unsafe { std::env::set_var("HOME", p) },
                None => unsafe { std::env::remove_var("HOME") },
            }
        }
    }

    /// Why (issue #1927, DOC-24 SPEC-STANDALONE-MPM-04): before this fix,
    /// `run_prepare_session` built `FrameworkPaths::default()`, which resolves
    /// `claude_agents`/`claude_skills` under the REAL `$HOME/.claude` — so the
    /// "fully isolated" standalone driver silently deployed agents and skills
    /// into the user's real global `~/.claude/agents` and `~/.claude/skills`,
    /// directly violating the isolation invariant. This test points `$HOME` at
    /// a throwaway tempdir (so a regression would be caught, not accidentally
    /// masked by writing to the real developer home) and asserts the fake
    /// home's `.claude/agents`/`.claude/skills` stay completely absent, while
    /// the project-local `repo/.claude/agents`/`repo/.claude/skills` receive
    /// the deploy instead.
    /// What: seeds a minimal agent source file under
    /// `<fake_home>/.trusty-mpm/framework/agents/` (the SAME tree
    /// `managed_root` resolves to in production, since `~/.trusty-mpm` is the
    /// default managed root — no skill source is seeded because
    /// `core::skill_source::ensure_skill_source_fresh`, part of the
    /// `prepare_session` pipeline, self-heals `framework/skills/` from the
    /// compiled-in bundle unconditionally, overwriting any hand-seeded file),
    /// runs `run_prepare_session` against a `repo/` under a SEPARATE temp dir,
    /// then asserts (a) `$HOME/.claude/agents` and `$HOME/.claude/skills` do
    /// not exist, (b) the agent landed in the tm-managed `CLAUDE_CONFIG_DIR`
    /// tier and NOT in `repo/.claude/agents` (issue #4409 moved the bundled
    /// agent destination off the workspace), and (c) `repo/.claude/skills/`
    /// was populated with at least one deployed skill — skills are still
    /// project-local.
    /// Test: itself.
    #[test]
    #[serial_test::serial]
    fn run_prepare_session_never_writes_real_home_claude_dirs() {
        let _palace_guard = EnvClearGuard::clear("TRUSTY_MEMORY_PALACE");

        let fake_home = crate::test_support::hermetic_temp_dir();
        let _home_guard = {
            let prior = std::env::var("HOME").ok();
            // SAFETY: serialized via `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", fake_home.path()) };
            HomeGuard(prior)
        };

        // managed_root mirrors the real default (`~/.trusty-mpm`) under the
        // fake home, so this test exercises the exact production shape.
        let managed_root = fake_home.path().join(".trusty-mpm");
        let agents_src = managed_root.join("framework").join("agents");
        std::fs::create_dir_all(&agents_src).unwrap();
        std::fs::write(
            agents_src.join("regression-agent.md"),
            "---\nname: regression-agent\nrole: engineer\n---\n\n\
             # Regression Agent\n\nAgent content.\n",
        )
        .unwrap();

        // repo/ lives under a SEPARATE temp dir so it can never coincidentally
        // land inside the fake home tree.
        let project_root = crate::test_support::hermetic_temp_dir();
        let repo = project_root.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();

        run_prepare_session(&repo, None, &managed_root).expect("run_prepare_session succeeds");

        assert!(
            !fake_home.path().join(".claude").join("agents").exists(),
            "run_prepare_session must NOT write to the real $HOME/.claude/agents (issue #1927)"
        );
        assert!(
            !fake_home.path().join(".claude").join("skills").exists(),
            "run_prepare_session must NOT write to the real $HOME/.claude/skills (issue #1927)"
        );

        // Issue #4409: the bundled agent must land in the tm-managed
        // `CLAUDE_CONFIG_DIR` tier, never in the workspace. A copy under
        // `repo/.claude/agents` would shadow the canonical roster.
        let agent_tier =
            crate::core::paths::FrameworkPaths::for_managed_project(&managed_root, &repo)
                .agent_deploy_dir();
        assert!(
            agent_tier.join("regression-agent.md").exists(),
            "run_prepare_session must deploy agents to the tm-managed config tier ({}) — #4409",
            agent_tier.display()
        );
        assert!(
            !repo.join(".claude").join("agents").exists(),
            "run_prepare_session must NOT deploy bundled agents into the workspace (#4409)"
        );
        let deployed_skills_dir = repo.join(".claude").join("skills");
        let has_deployed_skill = deployed_skills_dir
            .read_dir()
            .map(|mut entries| entries.next().is_some())
            .unwrap_or(false);
        assert!(
            has_deployed_skill,
            "run_prepare_session must deploy the compiled-in skill bundle to \
             repo/.claude/skills (project-local, DOC-24); dir: {}",
            deployed_skills_dir.display()
        );
    }

    /// Why (issue #3950 — fifth instance, sanity/no-over-correction check):
    /// on a normal, unobstructed run every builtin's write succeeds, so
    /// `run_prepare_session` must report all four as pinned — proving the
    /// fix does not over-correct into never trusting them.
    /// What: runs `run_prepare_session` against a clean repo dir and asserts
    /// the returned [`InjectedMcpPins`] are all `true`.
    /// Test: itself.
    #[test]
    #[serial_test::serial]
    fn run_prepare_session_reports_all_pins_true_on_success() {
        let _palace_guard = EnvClearGuard::clear("TRUSTY_MEMORY_PALACE");
        let fake_home = crate::test_support::hermetic_temp_dir();
        let _home_guard = {
            let prior = std::env::var("HOME").ok();
            // SAFETY: serialized via `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", fake_home.path()) };
            HomeGuard(prior)
        };

        let tmp = crate::test_support::hermetic_temp_dir();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        let managed_root = tmp.path().join("managed-root");

        let pins =
            run_prepare_session(&repo, None, &managed_root).expect("run_prepare_session succeeds");

        assert!(
            pins.trusty_mpm,
            "trusty-mpm pin must succeed on a clean run"
        );
        assert!(
            pins.trusty_review,
            "trusty-review pin must succeed on a clean run"
        );
        assert!(
            pins.trusty_memory,
            "trusty-memory pin must succeed on a clean run (default-on toggle)"
        );
        assert!(
            pins.trusty_search,
            "trusty-search pin must succeed on a clean run (default-on toggle)"
        );
    }

    /// Issue #3950 (fifth instance of the name-approval/content-pinning
    /// vulnerability class, found by code-critic while approving PR #3946).
    ///
    /// Why: `load_alias` (the `tm load`/`tm run` daemon-managed driver) is
    /// the ONE production call site that has BOTH the actual `PrepReport`
    /// from this run's injectors AND the `preseed_managed_trust` call in the
    /// SAME function — so this test drives the two real production
    /// functions back to back (`run_prepare_session` then
    /// `preseed_managed_trust`, exactly as `load_alias` calls them) rather
    /// than a full `load_alias` (which needs a network `git clone`). A write
    /// failure is forced for REAL — not by mocking a boolean — by making
    /// `repo/.mcp.json` an existing DIRECTORY before running preparation:
    /// `inject_mcp_server`'s shared read-merge-write helper calls
    /// `std::fs::write(&mcp_path, ..)`, which fails with an IO error
    /// (`Is a directory`) regardless of permission bits — portable even in a
    /// CI container that runs as root, where a read-only-directory
    /// permission trick would not actually block the write.
    /// What: asserts (1) `run_prepare_session`'s returned pins are all
    /// `false` (the write genuinely failed, not merely "toggle off"), and
    /// (2) feeding those ACTUAL pins into `preseed_managed_trust` (mirroring
    /// `load_alias`) excludes all four builtin names from
    /// `<claude_config_dir>/.claude.json`'s `enabledMcpjsonServers` — the
    /// name must not enter the approved set when nothing pinned its content
    /// behind it this run.
    /// Test: itself; `run_prepare_session_reports_all_pins_true_on_success`
    /// covers the complementary non-regression case.
    #[test]
    #[serial_test::serial]
    fn load_alias_excludes_builtins_from_managed_trust_when_mcp_json_write_fails() {
        let _palace_guard = EnvClearGuard::clear("TRUSTY_MEMORY_PALACE");
        let fake_home = crate::test_support::hermetic_temp_dir();
        let _home_guard = {
            let prior = std::env::var("HOME").ok();
            // SAFETY: serialized via `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", fake_home.path()) };
            HomeGuard(prior)
        };

        let tmp = crate::test_support::hermetic_temp_dir();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        // Force EVERY builtin injector's write to fail — all four share the
        // same `inject_mcp_server` read-merge-write helper over this one
        // file (see that helper's doc in `session_launch::settings`).
        std::fs::create_dir_all(repo.join(".mcp.json")).unwrap();
        let managed_root = tmp.path().join("managed-root");
        let claude_config_dir = tmp.path().join("claude-config");

        let pins = run_prepare_session(&repo, None, &managed_root).expect(
            "run_prepare_session must still succeed: injector failures are non-fatal to launch",
        );
        assert!(
            !pins.trusty_mpm,
            "a failed write must never count as pinned, even though trusty-mpm has no manifest toggle"
        );
        assert!(!pins.trusty_review, "same as trusty-mpm, for trusty-review");
        assert!(
            !pins.trusty_memory,
            "a failed write must never count as pinned, independent of the manifest toggle"
        );
        assert!(
            !pins.trusty_search,
            "same as trusty-memory, for trusty-search"
        );

        crate::core::standalone::preseed_managed_trust(
            &claude_config_dir,
            &repo,
            pins.trusty_mpm,
            pins.trusty_review,
            pins.trusty_memory,
            pins.trusty_search,
        )
        .expect("preseed_managed_trust succeeds");

        let value: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(claude_config_dir.join(".claude.json")).unwrap(),
        )
        .unwrap();
        let key = repo.to_string_lossy().to_string();
        let enabled: Vec<&str> = value["projects"][&key]["enabledMcpjsonServers"]
            .as_array()
            .expect("enabledMcpjsonServers is an array")
            .iter()
            .filter_map(|v| v.as_str())
            .collect();

        assert!(
            !enabled.contains(&"trusty-mpm"),
            "trusty-mpm must not be pre-approved when its pin write failed this run: {enabled:?}"
        );
        assert!(
            !enabled.contains(&"trusty-review"),
            "trusty-review must not be pre-approved when its pin write failed this run: {enabled:?}"
        );
        assert!(
            !enabled.contains(&"trusty-memory"),
            "trusty-memory must not be pre-approved when its pin write failed this run: {enabled:?}"
        );
        assert!(
            !enabled.contains(&"trusty-search"),
            "trusty-search must not be pre-approved when its pin write failed this run: {enabled:?}"
        );
    }

    #[test]
    fn test_marker_write_round_trip() {
        let tmp = crate::test_support::hermetic_temp_dir();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        let cfg = tmp.path().join("claude-config");

        write_marker(
            &repo,
            "my-alias",
            "https://github.com/org/r",
            "default",
            &cfg,
        )
        .unwrap();

        let toml_path = repo.join(".trusty-mpm").join("managed.toml");
        assert!(toml_path.exists());
        let text = std::fs::read_to_string(&toml_path).unwrap();
        let marker: ManagedMarker = toml::from_str(&text).unwrap();
        assert_eq!(marker.alias, "my-alias");
        assert_eq!(marker.url, "https://github.com/org/r");
        assert_eq!(
            marker.git_ref, "default",
            "git_ref must be the 'default' sentinel, not a literal branch name"
        );
    }
}