trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Unit tests for the project roster deploy (#2074, #7727, #7779).
//!
//! Why: split out of `deploy.rs` so the production file stays inside the
//! 500-SLOC cap while #7779 adds the pinned-handle deploy path.
//! What: the deploy's skip, corrupt-ledger, hand-edit and symlink-refusal
//! branches, the two post-validation swap regressions #7779 closes, and round
//! 2's publish fail-open arm plus the symlinked-roster-file policy it pins.
//! Test: this file IS the test module.

use super::*;
use trusty_agents_common::agents::manifest::Origin;

/// Every dispatchable roster name, for the count assertions below.
fn roster_names() -> Vec<&'static str> {
    DEFAULT_AGENTS.iter().map(EmbeddedAgent::name).collect()
}

/// Every entry beneath `<project>/.trusty-code`, relative and sorted —
/// directories included, since #7779 pinning CREATES them.
fn native_subtree(project_root: &Path) -> Vec<PathBuf> {
    fn walk(dir: &Path, root: &Path, out: &mut Vec<PathBuf>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            out.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
            if entry.file_type().is_ok_and(|t| t.is_dir()) {
                walk(&path, root, out);
            }
        }
    }
    let root = paths::native_config_dir(project_root);
    let mut out = Vec::new();
    walk(&root, &root, &mut out);
    out.sort();
    out
}

/// `.md` filenames actually present in a deployed target directory.
fn deployed_md_files(target: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(target)
        .expect("read_dir on the deploy target")
        .flatten()
        .filter_map(|e| e.file_name().to_str().map(str::to_string))
        .filter(|n| n.ends_with(".md"))
        .collect();
    names.sort();
    names
}

#[test]
fn roster_target_is_under_the_native_config_dir() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert_eq!(
        roster_target(tmp.path()),
        tmp.path().join(".trusty-code").join(AGENTS_DIRNAME)
    );
}

#[test]
fn staged_sources_cover_every_roster_name_and_base_template() {
    let staged = stage_embedded_sources().expect("stage");
    for name in roster_names() {
        assert!(
            staged.path().join(format!("{name}.md")).is_file(),
            "roster agent '{name}' must have a staged source file"
        );
    }
    for base in crate::assets::BASE_AGENT_NAMES {
        let map = trusty_agents_common::agents::builder::build_source_map(staged.path());
        assert!(
            map.contains_key(*base),
            "base template '{base}' must be stageable for extends resolution"
        );
    }
}

/// Assert a symlinked skill-ref location refuses the deploy, writes no
/// agent, and leaves the out-of-project victim byte-identical (#7727).
#[cfg(unix)]
fn assert_skill_ref_symlink_refused(project: &Path, victim: &Path, original: &str) {
    let err = ensure_roster_deployed(project).expect_err("a symlink escape must be refused");
    // #7779: the refusal now comes from the `O_NOFOLLOW` descent for a symlink
    // BELOW the config root, and from the unchanged anchoring check for a
    // config root that escapes the project. Either is the same verdict.
    assert!(
        matches!(
            err,
            RosterDeployError::WriteTarget(
                WriteTargetError::SymlinkEscape { .. } | WriteTargetError::Unpinned { .. }
            )
        ),
        "expected a symlink refusal, got {err:?}"
    );
    assert_eq!(std::fs::read_to_string(victim).expect("victim"), original);
    // #7779: pinning the write targets creates the (empty) directories before
    // the refusal can fire, so the property is "no agent file landed", not "no
    // directory exists".
    assert!(
        deployed_md_files(&roster_target(project)).is_empty(),
        "no agent may be written once the refusal fires"
    );
}

/// #7727 review: `.trusty-code/skill-refs` committed as a symlink out of
/// the project.
#[cfg(unix)]
#[test]
fn symlinked_skill_refs_dir_is_refused_before_any_write() {
    let project = tempfile::tempdir().expect("project");
    let outside = tempfile::tempdir().expect("outside");
    let victim = outside.path().join("self-improvement-loop/SKILL.md");
    std::fs::create_dir_all(victim.parent().expect("parent")).expect("mkdir");
    std::fs::write(&victim, "USER DATA - hand written skill").expect("victim");
    let refs = super::super::skill_refs::project_skill_refs_dir(project.path());
    std::fs::create_dir_all(refs.parent().expect("parent")).expect("mkdir");
    std::os::unix::fs::symlink(outside.path(), &refs).expect("symlink");

    assert_skill_ref_symlink_refused(project.path(), &victim, "USER DATA - hand written skill");
}

/// #7727 review: a real `skill-refs` dir whose one skill folder is a
/// symlink to a user's own skill.
#[cfg(unix)]
#[test]
fn symlinked_skill_folder_is_refused_before_any_write() {
    let project = tempfile::tempdir().expect("project");
    let outside = tempfile::tempdir().expect("outside");
    let user_skill = outside.path().join("my-skill");
    std::fs::create_dir_all(&user_skill).expect("mkdir");
    let victim = user_skill.join("SKILL.md");
    std::fs::write(&victim, "USER SKILL - hand written").expect("victim");
    let refs = super::super::skill_refs::project_skill_refs_dir(project.path());
    std::fs::create_dir_all(&refs).expect("mkdir");
    std::os::unix::fs::symlink(&user_skill, refs.join("verification-before-completion"))
        .expect("symlink");

    assert_skill_ref_symlink_refused(project.path(), &victim, "USER SKILL - hand written");
}

/// #7727 review: one skill-ref file committed as a symlink to a user file.
#[cfg(unix)]
#[test]
fn symlinked_skill_ref_file_is_refused_before_any_write() {
    let project = tempfile::tempdir().expect("project");
    let outside = tempfile::tempdir().expect("outside");
    let victim = outside.path().join("notes.md");
    std::fs::write(&victim, "USER FILE").expect("victim");
    let refs = super::super::skill_refs::project_skill_refs_dir(project.path());
    let link = refs.join("condition-based-waiting/SKILL.md");
    std::fs::create_dir_all(link.parent().expect("parent")).expect("mkdir");
    std::os::unix::fs::symlink(&victim, &link).expect("symlink");

    assert_skill_ref_symlink_refused(project.path(), &victim, "USER FILE");
}

/// A symlinked roster file refuses the deploy instead of being read through.
///
/// Why: #7779 round 2 pins a policy decision rather than closing a hole. The
/// pinned handle opens every entry `O_NOFOLLOW`, READS included, so a symlinked
/// `<roster>.md` now fails the whole deploy where main followed it and preserved
/// it as hand-edited. Keeping the refusal narrows this module's "a hand-edited
/// deployed file is authoritative" policy to REAL files, for the reason stated
/// in the `write_dir` module header; this test is what stops that from drifting
/// back silently.
/// What: symlinks `.trusty-code/agents/engineer.md` at a file outside the
/// project, then asserts the deploy reports `Unpinned`, the link's target is
/// byte-identical, and the only `.md` in the target is the link itself.
/// Test: this function IS the test.
#[cfg(unix)]
#[test]
fn symlinked_roster_file_is_refused_before_any_write() {
    let project = tempfile::tempdir().expect("project tempdir");
    let outside = tempfile::tempdir().expect("outside tempdir");
    let hand_written = outside.path().join("engineer.md");
    let original = "---\nname: engineer\n---\n\nMy own copy.\n";
    std::fs::write(&hand_written, original).expect("write the user's file");
    let target = roster_target(project.path());
    std::fs::create_dir_all(&target).expect("mkdir target");
    std::os::unix::fs::symlink(&hand_written, target.join("engineer.md")).expect("symlink");

    let err =
        ensure_roster_deployed(project.path()).expect_err("a symlinked roster file is refused");

    assert!(
        matches!(
            err,
            RosterDeployError::WriteTarget(WriteTargetError::Unpinned { .. })
        ),
        "expected Unpinned, got {err:?}"
    );
    assert_eq!(
        std::fs::read_to_string(&hand_written).expect("read the link's target"),
        original,
        "the link's target must be untouched"
    );
    assert_eq!(
        deployed_md_files(&target),
        vec!["engineer.md".to_string()],
        "the refusal must fire before any other agent is written"
    );
}

/// An unreadable scratch file fails the publish instead of dropping the file.
///
/// Why: #7779 round 2. `publish_from_scratch` used to `continue` past a scratch
/// read failure while still publishing the ledger, whose checksum named the file
/// that was never written — so `ensure_roster_deployed` returned `Deployed` and
/// `deploy_and_log` logged a deploy that had not happened. Fail-open.
/// What: hands the publish a `DeployResult` naming a file the scratch directory
/// does not hold, and asserts it errors and publishes NOTHING — not even the
/// ledger that was readable.
/// Test: this function IS the test.
#[test]
fn unreadable_scratch_file_fails_the_publish() {
    let project = tempfile::tempdir().expect("project tempdir");
    let agents = NativeWriteDir::open(project.path(), Path::new(AGENTS_DIRNAME))
        .expect("pin the agents dir");
    let scratch = tempfile::tempdir().expect("scratch tempdir");
    std::fs::write(scratch.path().join(MANIFEST_FILE), b"{\"managed\":{}}")
        .expect("scratch ledger");

    let result = DeployResult {
        deployed: vec!["engineer.md".to_string()],
        ..Default::default()
    };
    let err = publish_from_scratch(&agents, scratch.path(), &result)
        .expect_err("an unreadable scratch file must fail the publish");

    assert!(
        err.to_string().contains("engineer.md"),
        "the failure must name the file it could not read: {err}"
    );
    assert!(
        !agents.path().join(MANIFEST_FILE).exists(),
        "no ledger may be published for a run that could not publish its files"
    );
    assert!(
        deployed_md_files(agents.path()).is_empty(),
        "nothing may be published once the read fails"
    );
    assert!(
        matches!(&err, RosterDeployError::Publish { name, .. } if name == "engineer.md"),
        "expected Publish, got {err:?}"
    );
}

#[test]
fn fresh_project_materializes_the_whole_roster() {
    let project = tempfile::tempdir().expect("project tempdir");
    let outcome = ensure_roster_deployed(project.path()).expect("deploy must succeed");
    let RosterDeploy::Deployed { target, result } = outcome else {
        panic!("a clean project must deploy, got: {outcome:?}");
    };

    assert!(result.failed.is_empty(), "no agent may fail: {result:?}");
    // Asserted from the filesystem, not from the deployer's own report.
    let on_disk = deployed_md_files(&target);
    assert_eq!(
        on_disk.len(),
        roster_names().len(),
        "every roster agent must land on disk, got: {on_disk:?}"
    );
    for name in roster_names() {
        assert!(
            target.join(format!("{name}.md")).is_file(),
            "'{name}.md' must exist on disk after the first deploy"
        );
    }

    // The manifest exists beside them and records framework ownership.
    let (manifest_path, status) = roster_manifest_status(project.path());
    assert!(manifest_path.is_file(), "the ledger must exist beside them");
    assert_eq!(
        status,
        ManifestStatus::Present {
            managed: roster_names().len()
        }
    );
    assert_eq!(
        AgentManifest::load(&target).managed["engineer.md"].origin,
        Origin::Bundled
    );
}

#[test]
fn base_templates_are_never_deployed() {
    let project = tempfile::tempdir().expect("project tempdir");
    ensure_roster_deployed(project.path()).expect("deploy");
    for base in crate::assets::BASE_AGENT_NAMES {
        let deployed = deployed_md_files(&roster_target(project.path()));
        assert!(
            !deployed
                .iter()
                .any(|n| n.to_lowercase() == format!("{base}.md")),
            "composition base '{base}' must never be deployed as a dispatchable agent"
        );
    }
}

#[test]
fn second_deploy_of_an_untouched_roster_writes_nothing() {
    let project = tempfile::tempdir().expect("project tempdir");
    ensure_roster_deployed(project.path()).expect("first deploy");
    let outcome = ensure_roster_deployed(project.path()).expect("second deploy");
    let RosterDeploy::Deployed { result, .. } = outcome else {
        panic!("second deploy must still run, got: {outcome:?}");
    };
    assert!(
        result.deployed.is_empty(),
        "an untouched roster must need no rewrite: {result:?}"
    );
    assert_eq!(result.unchanged.len(), roster_names().len());
}

#[test]
fn hand_edited_agent_survives_a_second_deploy() {
    let project = tempfile::tempdir().expect("project tempdir");
    ensure_roster_deployed(project.path()).expect("first deploy");
    let target = roster_target(project.path());
    let edited = target.join("engineer.md");

    let hand_edit = "---\nname: engineer\nmodel: marker/hand-edited\n---\n\nMine now.\n";
    std::fs::write(&edited, hand_edit).expect("hand-edit the deployed agent");

    // Twice, to prove the preservation is stable rather than one-shot.
    for _ in 0..2 {
        let outcome = ensure_roster_deployed(project.path()).expect("re-deploy");
        let RosterDeploy::Deployed { result, .. } = outcome else {
            panic!("re-deploy must run, got: {outcome:?}");
        };
        assert!(
            !result.deployed.contains(&"engineer.md".to_string())
                && !result.repaired.contains(&"engineer.md".to_string()),
            "a hand-edited agent must never be rewritten: {result:?}"
        );
        assert_eq!(
            std::fs::read_to_string(&edited).expect("read back"),
            hand_edit,
            "the hand edit must survive byte-identical"
        );
    }

    // Its neighbours are untouched by the carve-out.
    assert!(target.join("rust-engineer.md").is_file());
}

#[test]
fn untracked_file_is_left_to_the_deployer() {
    let project = tempfile::tempdir().expect("project tempdir");
    let target = roster_target(project.path());
    std::fs::create_dir_all(&target).expect("mkdir target");
    let squatter = "---\nname: engineer\n---\n\nProject-owned, never deployed by us.\n";
    std::fs::write(target.join("engineer.md"), squatter).expect("write untracked file");

    let outcome = ensure_roster_deployed(project.path()).expect("deploy");
    let RosterDeploy::Deployed { result, .. } = outcome else {
        panic!("deploy must run, got: {outcome:?}");
    };
    assert!(
        result
            .untracked_modified
            .contains(&"engineer.md".to_string()),
        "an untracked, differing file is the deployer's own skip branch: {result:?}"
    );
    assert_eq!(
        std::fs::read_to_string(target.join("engineer.md")).expect("read back"),
        squatter
    );
}

#[test]
fn corrupt_manifest_is_reported_and_nothing_is_written() {
    let project = tempfile::tempdir().expect("project tempdir");
    let target = roster_target(project.path());
    std::fs::create_dir_all(&target).expect("mkdir target");
    std::fs::write(target.join(MANIFEST_FILE), b"not valid json{{{").expect("corrupt ledger");

    let err = ensure_roster_deployed(project.path()).expect_err("must refuse");
    assert!(
        matches!(err, RosterDeployError::ManifestCorrupt { .. }),
        "got: {err:?}"
    );
    assert!(
        err.to_string().contains("refusing to deploy"),
        "the message must say nothing was written: {err}"
    );
    // #7779: "nothing is written" covers DIRECTORIES too. Pinning a write target
    // creates it, so opening the skill-refs handle beside the agents one left an
    // empty `skill-refs/` behind after this refusal — which
    // `paths::resolve_project_entry` then reads as a usable native root.
    assert_eq!(
        native_subtree(project.path()),
        vec![
            PathBuf::from(AGENTS_DIRNAME),
            PathBuf::from(AGENTS_DIRNAME).join(MANIFEST_FILE),
            PathBuf::from(AGENTS_DIRNAME).join(format!("{MANIFEST_FILE}.lock")),
        ],
        "a corrupt ledger may leave only the directory it was found in, its \
         ledger, and the lock sidecar taken to read it"
    );
    assert!(
        deployed_md_files(&target).is_empty(),
        "a corrupt ledger must leave the directory untouched"
    );
    // And the ledger itself was never reset.
    assert_eq!(
        std::fs::read_to_string(target.join(MANIFEST_FILE)).expect("read back"),
        "not valid json{{{"
    );
}

#[test]
fn manifest_status_reports_absent_then_present() {
    let project = tempfile::tempdir().expect("project tempdir");
    let (path, status) = roster_manifest_status(project.path());
    assert_eq!(status, ManifestStatus::Absent);
    assert_eq!(status.as_str(), "absent");
    assert!(!path.exists());

    ensure_roster_deployed(project.path()).expect("deploy");
    let (_, status) = roster_manifest_status(project.path());
    assert_eq!(status.as_str(), "present");
    assert!(matches!(status, ManifestStatus::Present { managed } if managed > 0));
}

#[test]
fn manifest_status_reports_corrupt() {
    let project = tempfile::tempdir().expect("project tempdir");
    let target = roster_target(project.path());
    std::fs::create_dir_all(&target).expect("mkdir target");
    std::fs::write(target.join(MANIFEST_FILE), b"{{{").expect("corrupt ledger");
    let (_, status) = roster_manifest_status(project.path());
    assert_eq!(status.as_str(), "corrupt");
}

#[test]
fn deploy_is_skipped_when_claude_agents_dir_wins() {
    let project = tempfile::tempdir().expect("project tempdir");
    let claude = project.path().join(".claude").join(AGENTS_DIRNAME);
    std::fs::create_dir_all(&claude).expect("mkdir .claude/agents");
    std::fs::write(
        claude.join("engineer.md"),
        "---\nname: engineer\n---\n\nProject catalog.\n",
    )
    .expect("write .claude agent");

    let outcome = ensure_roster_deployed(project.path()).expect("skip is not an error");
    assert!(
        matches!(outcome, RosterDeploy::Skipped(SkipReason::CompatRootWins)),
        "a winning .claude/agents/ must never be shadowed, got: {outcome:?}"
    );
    assert!(
        !roster_target(project.path()).exists(),
        "nothing may be written when the deploy is skipped"
    );
}

#[test]
fn deploy_and_log_is_a_no_op_without_a_project() {
    assert!(deploy_and_log(None).is_none());
}

#[test]
fn deploy_and_log_reports_a_corrupt_ledger_without_panicking() {
    crate::test_support::begin_capture();

    let project = tempfile::tempdir().expect("project tempdir");
    let target = roster_target(project.path());
    std::fs::create_dir_all(&target).expect("mkdir target");
    std::fs::write(target.join(MANIFEST_FILE), b"{{{").expect("corrupt ledger");
    assert!(
        deploy_and_log(Some(project.path())).is_none(),
        "a corrupt ledger must degrade to the in-memory roster, not abort"
    );

    // Degrading silently is the failure this branch exists to prevent, so
    // the assertion is on the ERROR event itself — downgrading it to
    // `debug!` must fail this test, not just change a log line.
    let errors = crate::test_support::captured_at_least(tracing::Level::ERROR);
    assert!(
        errors
            .iter()
            .any(|m| m.contains("could not materialize the agent roster")),
        "the corrupt ledger must be reported at ERROR level, got: {errors:?}"
    );
}

#[test]
fn deployed_agents_load_back_through_the_disk_loader() {
    let project = tempfile::tempdir().expect("project tempdir");
    ensure_roster_deployed(project.path()).expect("deploy");
    let loaded = crate::agents::load_all_agents(&roster_target(project.path()));
    assert_eq!(
        loaded.len(),
        roster_names().len(),
        "every deployed file must parse through the disk loader"
    );
    let restricted = loaded
        .iter()
        .find(|c| c.agent.name == "code-critic")
        .expect("code-critic must be deployed");
    let allowed = restricted
        .tools
        .as_ref()
        .and_then(|t| t.allowed.as_ref())
        .expect("code-critic carries a tcode-local tool allowlist");
    assert!(
        !allowed.contains(&"write_file".to_string()),
        "the tcode-local read-only restriction must survive materialization: {allowed:?}"
    );
}

/// Replace a validated directory with a symlink, the way a racing writer does.
#[cfg(unix)]
fn swap_for_symlink(dir: &Path, victim: &Path) {
    std::fs::remove_dir_all(dir).expect("remove the validated directory");
    std::os::unix::fs::symlink(victim, dir).expect("symlink the victim in its place");
}

/// Everything a directory holds, for a "the victim got nothing" assertion.
#[cfg(unix)]
fn entries(dir: &Path) -> Vec<std::ffi::OsString> {
    std::fs::read_dir(dir)
        .expect("read_dir")
        .flatten()
        .map(|e| e.file_name())
        .collect()
}

/// #7779: `skill-refs` swapped for a symlink AFTER validation writes nothing
/// into the victim and reports the swap.
///
/// Why: the reproduced race. A 4 ms `skill-refs -> victim` swap loop during real
/// `tcode` deploys put a `SKILL.md.<pid>.<nanos>.tmp` in the victim in 6 of 40
/// runs, because `check_native_write_target` and `materialize_skill_refs` each
/// resolved the path independently.
/// What: validates by opening the pinned handle, performs the swap, then runs
/// the write. Asserts the victim is empty and the error is
/// `WriteTargetError::Unpinned`.
/// Test: this function IS the test.
#[cfg(unix)]
#[test]
fn swapped_skill_refs_dir_never_reaches_the_victim() {
    let project = tempfile::tempdir().expect("project");
    let victim = tempfile::tempdir().expect("victim");
    let refs = NativeWriteDir::open(project.path(), Path::new(SKILL_REFS_DIRNAME))
        .expect("the skill-refs dir validates");

    swap_for_symlink(refs.path(), victim.path());

    let err = super::super::skill_refs::materialize_skill_refs(&refs)
        .expect_err("a swapped component must be reported");

    assert!(
        matches!(err, WriteTargetError::Unpinned { .. }),
        "expected Unpinned, got {err:?}"
    );
    assert!(
        entries(victim.path()).is_empty(),
        "the victim must receive nothing, found {:?}",
        entries(victim.path())
    );
}

/// #7779: the agents directory swapped AFTER validation publishes nothing into
/// the victim and reports the swap.
///
/// Why: the same race on the older guard at the roster-deploy site. The shared
/// deployer writes through plain paths, so the publish back into the project is
/// the step that has to resolve against the pinned descriptor.
/// What: validates by opening the pinned handle, performs the swap, then
/// publishes a deploy result. Asserts the victim is empty and the error is
/// `WriteTargetError::Unpinned`.
/// Test: this function IS the test.
#[cfg(unix)]
#[test]
fn swapped_agents_dir_never_reaches_the_victim() {
    let project = tempfile::tempdir().expect("project");
    let victim = tempfile::tempdir().expect("victim");
    let agents = NativeWriteDir::open(project.path(), Path::new(AGENTS_DIRNAME))
        .expect("the agents dir validates");

    let scratch = tempfile::tempdir().expect("scratch");
    std::fs::write(scratch.path().join("pm.md"), "composed body").expect("stage");
    std::fs::write(scratch.path().join(MANIFEST_FILE), "{}").expect("stage");
    let mut result = DeployResult::default();
    result.deployed.push("pm.md".to_string());

    swap_for_symlink(agents.path(), victim.path());

    let err = publish_from_scratch(&agents, scratch.path(), &result)
        .expect_err("a swapped component must be reported");

    assert!(
        matches!(
            err,
            RosterDeployError::WriteTarget(WriteTargetError::Unpinned { .. })
        ),
        "expected Unpinned, got {err:?}"
    );
    assert!(
        entries(victim.path()).is_empty(),
        "the victim must receive nothing, found {:?}",
        entries(victim.path())
    );
}