trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Per-session deployed-asset staleness detection (issue #2444).
//!
//! Why: `core::session_launch::prepare_session` deploys agents/skills into a
//! managed session's `.claude/{agents,skills}` exactly ONCE, at launch time
//! (DOC-34/#2002). A session that stays alive for days never re-syncs when the
//! bundled/catalog agent or skill source changes underneath it, so its deployed
//! copy silently drifts stale relative to what a fresh session would get — the
//! exact dogfood observation behind #2444 (a deployed skill still at v1.0.0
//! while the catalog had already moved to v1.1.0, and a missing agent added to
//! the catalog after launch). This module answers "is THIS session's deployed
//! workspace stale?" by re-targeting the SAME manifest/plan/checksum comparison
//! [`crate::core::update_check::detect_for_framework`] already performs for the
//! framework's own `~/.claude` deployment — no new staleness mechanism, just
//! pointed at a session's own workspace via
//! [`FrameworkPaths::for_managed_workspace`], mirroring how `doctor_staleness.rs`
//! (issue #2876) and `doctor_output_style.rs` (issue #2333) already reuse
//! existing manifest-checksum machinery rather than inventing new ones.
//! What: [`session_workdir`] resolves the on-disk directory a session's assets
//! deploy into (`workspace_path`, falling back to `cwd` for local-path/adopted
//! sessions); [`session_asset_staleness`] runs the full agent+skill comparison
//! and returns the [`StalenessReport`]; [`session_assets_stale`] is the boolean
//! summary `tm sessions ls`'s stale-assets marker and `tm sessions sync-assets`'s
//! pre-check consume. [`session_plan`] and [`session_asset_staleness_with_catalog`]
//! split the cheap per-session plan resolution from the expensive catalog-side
//! hash compute (issue #2444 review MEDIUM finding) so a batch caller —
//! `daemon::managed_routes::summary::checked_summaries`, computing this marker
//! for every session on every `tm sessions ls` — can group sessions by their
//! resolved `(agent_source, skill_source)` pair and share ONE
//! [`crate::core::update_check::CatalogHashes::compute`] across every session
//! using that same catalog, instead of recomposing the ~40+ catalog agents once
//! PER SESSION.
//! Test: `session_workdir_prefers_workspace_path`,
//! `session_workdir_falls_back_to_cwd`, `session_asset_staleness_ok_when_fresh`,
//! `session_asset_staleness_flags_catalog_drift`.

use std::path::Path;

use crate::core::manifest::HarnessPlan;
use crate::core::paths::FrameworkPaths;
use crate::core::update_check::{
    CatalogHashes, DeployedAgentHashes, StalenessReport, detect_for_framework,
};
use crate::session_manager::SessionRecord;

/// Resolve the on-disk directory a session's deployed assets live under.
///
/// Why: [`crate::core::session_launch::prepare_session_with_repo_url`] deploys
/// into `workspace_path` for daemon-provisioned sessions, but a local-path /
/// adopted session (#1502/#1433) has no provisioned workspace at all — its
/// assets deploy into `cwd` instead. Every call site that needs "where do this
/// session's assets live" (staleness detection here, and the `sync-assets`
/// redeploy) must resolve identically, or they would silently disagree about
/// which directory is authoritative.
/// What: `workspace_path` when set, else `cwd`.
/// Test: `session_workdir_prefers_workspace_path`,
/// `session_workdir_falls_back_to_cwd`.
pub fn session_workdir(record: &SessionRecord) -> &Path {
    record
        .workspace_path
        .as_deref()
        .unwrap_or(record.cwd.as_path())
}

/// Compute the full staleness report for a session's deployed workspace.
///
/// Why: exposed separately from [`session_assets_stale`] so a future detail
/// surface (a `tm sessions info` staleness breakdown, or `tm doctor`) can show
/// WHICH agents/skills drifted rather than only whether any did.
/// What: builds a workspace-scoped [`FrameworkPaths`] via
/// [`FrameworkPaths::for_managed_workspace`] — deploy DESTINATIONS move to
/// `<workdir>/.claude/{agents,skills}`, while the bundled/catalog SOURCE paths
/// stay at the shared framework install, exactly as a real session deploy uses
/// them — and delegates to [`detect_for_framework`] with `project_dir = workdir`
/// so any project-level manifest override the session's own workspace carries
/// (e.g. `.trusty-mpm/manifest.toml`) is honoured exactly as launch would.
/// Test: `session_asset_staleness_flags_catalog_drift`,
/// `session_asset_staleness_ok_when_fresh`.
pub fn session_asset_staleness(record: &SessionRecord) -> StalenessReport {
    let workdir = session_workdir(record);
    let fw = FrameworkPaths::for_managed_workspace(workdir);
    detect_for_framework(&fw, workdir)
}

/// Resolve the workspace-scoped [`FrameworkPaths`] and [`HarnessPlan`] for a
/// session, WITHOUT doing any expensive catalog compose/hash work.
///
/// Why (issue #2444 review): a batch caller comparing many sessions needs to
/// know each session's resolved `(plan.agent_source, plan.skill_source)`
/// pair BEFORE deciding whether it can share an already-computed
/// [`CatalogHashes`] or must compute a new one — that decision has to happen
/// without paying the compose cost first. This is exactly the manifest-
/// resolve step [`session_asset_staleness`] and
/// `core::session_launch::sync_session_assets` already perform internally;
/// splitting it out here means a batch caller does not have to re-implement
/// (and risk diverging from) that resolution.
/// What: builds `FrameworkPaths::for_managed_workspace(session_workdir(record))`
/// and resolves its [`HarnessPlan`] exactly as [`session_asset_staleness`]
/// does — only file reads of small manifest/config files (project-level
/// `.trusty-mpm/manifest.toml` if present, the framework's own `config.toml`),
/// never a catalog directory scan or agent compose.
/// Test: `session_plan_resolves_default_bundled_source`.
pub fn session_plan(record: &SessionRecord) -> (FrameworkPaths, HarnessPlan) {
    session_plan_under(record, &FrameworkPaths::home_base())
}

/// [`session_plan`] with the framework install's base directory supplied by the
/// caller instead of read from `$HOME` (#5040).
///
/// Why: everything below this function resolves from `FrameworkPaths`, so `$HOME`
/// enters the staleness comparison at exactly one point —
/// [`FrameworkPaths::for_managed_workspace`]. That single read is what forced
/// every test of the batch staleness path to redirect the PROCESS-GLOBAL `$HOME`
/// and carry `#[serial_test::serial]`, which orders those tests against each
/// other but not against the rest of the binary; a concurrent test reading a
/// `$HOME`-derived path then observed the redirect and produced a wrong answer
/// (#5040's `left: 25, right: 1`). Taking the base as an argument lets a test be
/// hermetic without touching the environment at all.
/// What: identical to [`session_plan`] except that the workspace-scoped
/// [`FrameworkPaths`] is built with
/// [`FrameworkPaths::for_managed_workspace_under`] against `base`.
/// Test: `session_plan_under_matches_session_plan_at_home`.
pub fn session_plan_under(record: &SessionRecord, base: &Path) -> (FrameworkPaths, HarnessPlan) {
    let workdir = session_workdir(record);
    let fw = FrameworkPaths::for_managed_workspace_under(base, workdir);
    let catalog_root = crate::content::catalog_root_for(&fw.root);
    let sources = crate::core::manifest::ManifestSources::resolve(workdir, &catalog_root);
    let manifest = crate::core::manifest::resolve_manifest(&sources);
    let plan = HarnessPlan::from_manifest(&manifest, &fw, &catalog_root);
    (fw, plan)
}

/// Compute a session's staleness report reusing a precomputed [`CatalogHashes`]
/// for its resolved catalog source pair.
///
/// Why: the cheap, per-session half of the comparison a batch caller runs
/// AFTER grouping sessions by [`session_plan`]'s resolved `(agent_source,
/// skill_source)` pair and computing (or reusing) the matching
/// [`CatalogHashes`] — see the module doc for the full #2444 review
/// rationale. Reads only this session's OWN deployed manifest + on-disk
/// files; performs zero catalog I/O.
/// What: loads this session's deployed `AgentManifest`/`SkillManifest`
/// from `fw.agent_deploy_dir()`/`fw.claude_skills_dir()` and delegates to
/// [`CatalogHashes::detect`] with `plan`'s selection predicates.
/// Test: `session_asset_staleness_with_catalog_matches_uncached_result`.
pub fn session_asset_staleness_with_catalog(
    fw: &FrameworkPaths,
    plan: &HarnessPlan,
    catalog: &CatalogHashes,
) -> StalenessReport {
    // #4409: agents are deployed to (and therefore drift in) the tm-managed
    // config-dir tier; skills remain per-workspace.
    // #4619 review: LAZY, not eager. This is the SINGLE-session path
    // (`GET …/managed/{id}`, which `tm session resume` reads); it shares its
    // read with nobody, so pre-hashing every catalog stem would read more than
    // the old code did whenever the plan selects a subset.
    let agents_dir = fw.agent_deploy_dir();
    let deployed_agents = DeployedAgentHashes::lazy(
        crate::core::agent_manifest::AgentManifest::load(&agents_dir),
        &agents_dir,
    );
    session_asset_staleness_with_shared(fw, plan, catalog, &deployed_agents)
}

/// [`session_asset_staleness_with_catalog`] with the deployed-AGENT read ALSO
/// supplied by the caller (issue #4322).
///
/// Why: `fw.agent_deploy_dir()` is one machine-global directory — #4409
/// exempted it from `for_managed_project`'s per-workspace rewrite — so every
/// session in a `tm ls` listing resolves it to the SAME path and was reading
/// the same 42 files over and over. Hoisting that read to the batch caller
/// (`crate::daemon::managed_routes::summary::staleness_inputs`) mirrors
/// exactly what #2444's review already did for the CATALOG half: compute the
/// shared part once, fan out only the part that genuinely differs per session.
///
/// Answer-preserving, not merely faster: the deployed-agent bytes are shared
/// INPUT, and the only thing that varies per session — the plan's selection
/// and ignore predicates — is applied after the read, inside
/// [`CatalogHashes::detect`]. Two sessions reading the same directory at
/// slightly different instants could previously disagree if something wrote to
/// it mid-listing; one read for the whole listing removes that skew as well.
/// What: reads only this session's own skill manifest + per-workspace skill
/// files, then delegates to [`CatalogHashes::detect`].
/// Test: `session_asset_staleness_with_shared_matches_unshared`,
/// `stale_assets_for_many_reads_shared_agent_dir_once_for_the_whole_fleet`.
pub fn session_asset_staleness_with_shared(
    fw: &FrameworkPaths,
    plan: &HarnessPlan,
    catalog: &CatalogHashes,
    deployed_agents: &DeployedAgentHashes,
) -> StalenessReport {
    let skills_dir = fw.claude_skills_dir();
    // #5626: an unreadable ledger is `unknown`, not fresh. The empty default
    // made every deployed skill look absent, so `detect` reported the whole
    // catalog as `new` — or, once the plan selected nothing, reported currency
    // this read never established. `unknown` is the report's own documented
    // "nothing authoritative to compare against" state.
    let deployed_skills = match crate::core::skill_manifest::SkillManifest::load(&skills_dir) {
        Ok(m) => m,
        Err(e) => {
            tracing::warn!(
                dir = %skills_dir.display(),
                error = %e,
                "skill ownership ledger unreadable — staleness is undetermined"
            );
            return StalenessReport {
                unknown: true,
                ..StalenessReport::default()
            };
        }
    };
    catalog.detect(
        deployed_agents,
        &deployed_skills,
        &skills_dir,
        |name| plan.agent_selected(name),
        |name| plan.skill_selected(name),
        |name| plan.agent_staleness_ignored(name),
    )
}

/// Whether a session's deployed agents/skills have drifted from the catalog.
///
/// Why: the boolean summary `tm sessions ls`'s stale-assets marker and the
/// `sync-assets` pre-check need. `unknown` (neither a bundled nor catalog
/// source tree could be found to compare against) is deliberately treated as
/// "not stale", matching [`StalenessReport`]'s own documented semantics —
/// nothing authoritative to compare against is not evidence of drift.
/// What: `session_asset_staleness(record).stale`.
/// Test: `session_asset_staleness_ok_when_fresh`,
/// `session_asset_staleness_flags_catalog_drift`.
pub fn session_assets_stale(record: &SessionRecord) -> bool {
    session_asset_staleness(record).stale
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::agent_deployer::deploy_agents_filtered;
    use crate::session_manager::{ManagedSessionId, ManagedSessionState};
    use chrono::Utc;
    use std::path::PathBuf;
    use tempfile::TempDir;

    /// Build a minimal `SessionRecord` for a workspace-rooted session.
    fn make_record(workspace: Option<PathBuf>, cwd: PathBuf) -> SessionRecord {
        SessionRecord {
            id: ManagedSessionId::new(),
            tmux_name: "tm-test".to_string(),
            cwd,
            task: "test".to_string(),
            state: ManagedSessionState::Active,
            created_at: Utc::now(),
            last_activity_at: None,
            workspace_path: workspace,
            repo_url: None,
            branch: None,
            pending_decision: None,
            proposed_default: None,
            correlation: Default::default(),
            runtime: Default::default(),
            ephemeral: false,
            workspace_owned: false,
            source_id: None,
            claude_session_id: None,
            scrollback_path: None,
            last_cwd: None,
            deliverable_id: None,
            pane_id: None,
            tmux_server: None,
            injection_status: Default::default(),
            worktree_owner: None,
            terminal_at: None,
            stop_cause: None,
            kind: Default::default(),
        }
    }

    #[test]
    fn session_workdir_prefers_workspace_path() {
        let ws = PathBuf::from("/workspace");
        let record = make_record(Some(ws.clone()), PathBuf::from("/cwd"));
        assert_eq!(session_workdir(&record), ws.as_path());
    }

    /// #5040: the explicit-base form must be the same resolution
    /// [`session_plan`] performs, so a test built on `session_plan_under`
    /// proves what production actually does.
    ///
    /// #6580: both halves read `$HOME` — `session_plan` through
    /// `FrameworkPaths::default()` and the explicit half through
    /// `FrameworkPaths::home_base()` — in two separate calls. A sibling test
    /// moving `$HOME` between them made the two halves resolve under different
    /// roots, so the comparison failed while proving nothing about the two
    /// forms. [`fake_home`] pins `$HOME` for the whole body and
    /// `#[serial_test::serial]` keeps every other `$HOME` mover out.
    #[test]
    #[serial_test::serial]
    fn session_plan_under_matches_session_plan_at_home() {
        let (_home, _guard) = fake_home();
        let record = make_record(
            Some(PathBuf::from("/some/workspace")),
            PathBuf::from("/some/cwd"),
        );
        let (fw_default, plan_default) = session_plan(&record);
        let (fw_explicit, plan_explicit) =
            session_plan_under(&record, &FrameworkPaths::home_base());

        assert_eq!(fw_default, fw_explicit);
        assert_eq!(plan_default.agent_source, plan_explicit.agent_source);
        assert_eq!(plan_default.skill_source, plan_explicit.skill_source);
    }

    #[test]
    fn session_workdir_falls_back_to_cwd() {
        let cwd = PathBuf::from("/cwd");
        let record = make_record(None, cwd.clone());
        assert_eq!(session_workdir(&record), cwd.as_path());
    }

    /// RAII guard restoring `$HOME` on drop (including panic) — mirrors the
    /// identical pattern in `core::standalone::load::tests::HomeGuard`.
    ///
    /// Why: [`session_asset_staleness`] resolves its bundled-source half via
    /// `FrameworkPaths::for_managed_workspace`, which always anchors the
    /// framework SOURCE tree at `FrameworkPaths::default().root` (the real
    /// `$HOME/.trusty-mpm` in production, by design — the daemon supports no
    /// `--root` override). A test exercising real staleness drift must
    /// therefore point `$HOME` at a throwaway tempdir so it reads/writes a
    /// fake framework tree, never the developer's real one.
    struct HomeGuard(Option<String>);
    impl Drop for HomeGuard {
        fn drop(&mut self) {
            // SAFETY: paired with `#[serial_test::serial]` — 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") },
            }
        }
    }

    /// Point `$HOME` at a fresh tempdir for the duration of the guard.
    fn fake_home() -> (TempDir, HomeGuard) {
        let home = TempDir::new().unwrap();
        let prior = std::env::var("HOME").ok();
        // SAFETY: serialized via `#[serial_test::serial]` on every caller.
        unsafe { std::env::set_var("HOME", home.path()) };
        (home, HomeGuard(prior))
    }

    #[test]
    #[serial_test::serial]
    fn session_asset_staleness_ok_when_fresh() {
        // Deploy a session's agents from the (fake-home) bundled source; a
        // freshly deployed workspace must not be reported stale.
        let (home, _guard) = fake_home();
        let fw = FrameworkPaths::default();
        let bundled = fw.agent_source_dir();
        std::fs::create_dir_all(&bundled).unwrap();
        std::fs::write(bundled.join("rust-engineer.md"), "v1 body").unwrap();

        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let session_fw = FrameworkPaths::for_managed_workspace(&workspace);
        deploy_agents_filtered(
            &bundled,
            &session_fw.agent_deploy_dir(),
            &session_fw.skill_deploy_dir(),
            |_| true,
        )
        .unwrap();

        let record = make_record(Some(workspace.clone()), workspace);
        assert!(
            !session_assets_stale(&record),
            "freshly deployed session must not be stale"
        );
    }

    #[test]
    #[serial_test::serial]
    fn session_asset_staleness_flags_catalog_drift() {
        // The #2444 scenario: the bundled/catalog source changes AFTER the
        // session already deployed from it (a framework upgrade landing
        // mid-session) — the session's workspace must now report stale.
        let (home, _guard) = fake_home();
        let fw = FrameworkPaths::default();
        let bundled = fw.agent_source_dir();
        std::fs::create_dir_all(&bundled).unwrap();
        std::fs::write(bundled.join("rust-engineer.md"), "v1 body").unwrap();

        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let session_fw = FrameworkPaths::for_managed_workspace(&workspace);
        deploy_agents_filtered(
            &bundled,
            &session_fw.agent_deploy_dir(),
            &session_fw.skill_deploy_dir(),
            |_| true,
        )
        .unwrap();

        let record = make_record(Some(workspace.clone()), workspace);
        assert!(!session_assets_stale(&record));

        // Framework upgrade changes the bundled source out from under it.
        std::fs::write(bundled.join("rust-engineer.md"), "v2 body — catalog moved").unwrap();
        assert!(
            session_assets_stale(&record),
            "session must be reported stale once the bundled source changed"
        );
    }

    /// #7727 review: a session deployed from a `{{TM_SKILLS}}` body is fresh
    /// against its own skills tier and stale against a catalog hashed with any
    /// other root.
    #[test]
    #[serial_test::serial]
    fn session_placeholder_body_is_fresh_only_against_its_skills_root() {
        use trusty_agents_common::agents::skill_root::SKILLS_ROOT_PLACEHOLDER;

        let (home, _guard) = fake_home();
        let fw = FrameworkPaths::default();
        let bundled = fw.agent_source_dir();
        std::fs::create_dir_all(&bundled).unwrap();
        let body = format!("Read `{SKILLS_ROOT_PLACEHOLDER}/self-improvement-loop/SKILL.md`.");
        std::fs::write(bundled.join("rust-engineer.md"), body).unwrap();

        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let session_fw = FrameworkPaths::for_managed_workspace(&workspace);
        deploy_agents_filtered(
            &bundled,
            &session_fw.agent_deploy_dir(),
            &session_fw.skill_deploy_dir(),
            |_| true,
        )
        .unwrap();

        let record = make_record(Some(workspace.clone()), workspace);
        assert!(
            !session_assets_stale(&record),
            "deployed with the session's own skills root must be fresh"
        );

        let (fw_s, plan) = session_plan(&record);
        let other_root = home.path().join("other-skills");
        let catalog = crate::core::update_check::CatalogHashes::compute(
            &plan.agent_source,
            &plan.skill_source,
            &other_root,
        );
        assert!(
            session_asset_staleness_with_catalog(&fw_s, &plan, &catalog).stale,
            "a catalog hashed with a different skills root must read as stale"
        );
    }

    #[test]
    #[serial_test::serial]
    fn session_plan_resolves_default_bundled_source() {
        // With no project-level manifest override, `session_plan`'s resolved
        // agent/skill source must equal the shared framework bundled dirs —
        // the property `checked_summaries`'s batch grouping (issue #2444
        // review) depends on to collapse multiple sessions onto ONE
        // `CatalogHashes::compute` call.
        let (home, _guard) = fake_home();
        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let record = make_record(Some(workspace.clone()), workspace);

        let (fw, plan) = session_plan(&record);
        assert_eq!(plan.agent_source, fw.agent_source_dir());
        assert_eq!(plan.skill_source, fw.skill_source_dir());
    }

    #[test]
    #[serial_test::serial]
    fn session_asset_staleness_with_catalog_matches_uncached_result() {
        // The batched (`session_plan` + `CatalogHashes` + `session_asset_staleness_with_catalog`)
        // path must agree EXACTLY with the uncached `session_asset_staleness`
        // path — sharing the catalog compute must never change the answer.
        let (home, _guard) = fake_home();
        let fw = FrameworkPaths::default();
        let bundled = fw.agent_source_dir();
        std::fs::create_dir_all(&bundled).unwrap();
        std::fs::write(bundled.join("rust-engineer.md"), "v1 body").unwrap();

        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let session_fw = FrameworkPaths::for_managed_workspace(&workspace);
        deploy_agents_filtered(
            &bundled,
            &session_fw.agent_deploy_dir(),
            &session_fw.skill_deploy_dir(),
            |_| true,
        )
        .unwrap();
        // Catalog drifts after deploy, so both paths must agree it is stale.
        std::fs::write(bundled.join("rust-engineer.md"), "v2 body").unwrap();

        let record = make_record(Some(workspace.clone()), workspace);
        let uncached = session_asset_staleness(&record);

        let (session_fw, plan) = session_plan(&record);
        let catalog = crate::core::update_check::CatalogHashes::compute(
            &plan.agent_source,
            &plan.skill_source,
            &session_fw.skill_deploy_dir(),
        );
        let cached = session_asset_staleness_with_catalog(&session_fw, &plan, &catalog);

        assert_eq!(uncached.stale, cached.stale);
        assert!(
            cached.stale,
            "the catalog drift must be detected either way"
        );
    }

    /// Issue #4322: hoisting the DEPLOYED-agent read out of the per-session
    /// fan-out must not change any answer.
    ///
    /// Why: this is the whole correctness claim of the optimization. A faster
    /// `tm ls` that reports a wrong staleness verdict is strictly worse than
    /// the slow one, so the shared-read path is pinned against the unshared
    /// path it replaced — including the change LIST, not just the boolean, so
    /// a shared read that silently dropped or duplicated an agent would fail
    /// here rather than pass on a coincidentally-equal `stale` flag.
    /// What: builds a genuinely drifted workspace, then asserts
    /// `session_asset_staleness_with_shared` (shared deployed-agent read) and
    /// `session_asset_staleness_with_catalog` (per-session read) agree
    /// exactly.
    #[test]
    #[serial_test::serial]
    fn session_asset_staleness_with_shared_matches_unshared() {
        let (home, _guard) = fake_home();
        let fw = FrameworkPaths::default();
        let bundled = fw.agent_source_dir();
        std::fs::create_dir_all(&bundled).unwrap();
        std::fs::write(bundled.join("rust-engineer.md"), "v1 body").unwrap();

        let workspace = home.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let session_fw = FrameworkPaths::for_managed_workspace(&workspace);
        deploy_agents_filtered(
            &bundled,
            &session_fw.agent_deploy_dir(),
            &session_fw.skill_deploy_dir(),
            |_| true,
        )
        .unwrap();
        // Drift the catalog so both paths must report a real change.
        std::fs::write(bundled.join("rust-engineer.md"), "v2 body — catalog moved").unwrap();

        let record = make_record(Some(workspace.clone()), workspace);
        let (fw_s, plan) = session_plan(&record);
        let catalog = CatalogHashes::compute(
            &plan.agent_source,
            &plan.skill_source,
            &fw_s.skill_deploy_dir(),
        );

        let unshared = session_asset_staleness_with_catalog(&fw_s, &plan, &catalog);
        let shared_agents = DeployedAgentHashes::read(&fw_s.agent_deploy_dir(), &catalog);
        let shared = session_asset_staleness_with_shared(&fw_s, &plan, &catalog, &shared_agents);

        assert!(unshared.stale, "fixture must be genuinely stale");
        assert_eq!(
            unshared.stale, shared.stale,
            "sharing the deployed-agent read must not change the verdict"
        );
        assert_eq!(
            unshared.changes, shared.changes,
            "sharing the deployed-agent read must not change WHICH artifacts \
             are reported as drifted"
        );
    }
}