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
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! Tests for [`super::publish_pause_snapshot`] (#7282).
//!
//! Every test drives [`FakeVcs`], so none of them needs a git repository, a
//! network, or a `gh` install — which is what makes the default-branch refusal
//! and the post-commit push failure testable at all.

use std::cell::RefCell;
use std::path::{Path, PathBuf};

use chrono::TimeZone as _;

use super::*;

/// One recorded subprocess invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Call {
    /// `"git"` or `"tm"`.
    program: &'static str,
    /// The argv, without the program.
    args: Vec<String>,
    /// The `GIT_INDEX_FILE` overlay, when one was set.
    index_file: Option<PathBuf>,
}

/// A scripted [`PauseVcs`] that records every call.
///
/// Why: the publish sequence's contract is the exact set of commands it runs —
/// specifically that no `git add` ever appears and that only allowlisted paths
/// enter `update-index`. Recording is how that is asserted.
/// What: responses are matched by argv prefix, longest match first and — at
/// equal length — last one scripted, so one test can override one step of the
/// happy path. Anything unmatched succeeds with empty output.
struct FakeVcs {
    /// `(argv prefix, response)` pairs.
    script: Vec<(Vec<String>, CmdOut)>,
    /// Everything the publish ran, in order.
    calls: RefCell<Vec<Call>>,
    /// `(--body-file path, its contents)` read at the moment `tm` was invoked.
    ///
    /// The body lives in a scratch directory the publish drops before it
    /// returns, so a test that read the file afterwards would be reading a path
    /// that no longer exists — which is the point of `#7282`'s scratch fix.
    bodies: RefCell<Vec<(PathBuf, String)>>,
}

impl FakeVcs {
    fn new() -> Self {
        Self {
            script: Vec::new(),
            calls: RefCell::new(Vec::new()),
            bodies: RefCell::new(Vec::new()),
        }
    }

    /// Script a success with `stdout` for any argv starting with `prefix`.
    fn ok(mut self, prefix: &[&str], stdout: &str) -> Self {
        self.script.push((
            prefix.iter().map(|s| (*s).to_string()).collect(),
            CmdOut {
                success: true,
                stdout: stdout.to_string(),
                stderr: String::new(),
            },
        ));
        self
    }

    /// Script a failure with `stderr` for any argv starting with `prefix`.
    fn fail(mut self, prefix: &[&str], stderr: &str) -> Self {
        self.script.push((
            prefix.iter().map(|s| (*s).to_string()).collect(),
            CmdOut {
                success: false,
                stdout: String::new(),
                stderr: stderr.to_string(),
            },
        ));
        self
    }

    fn respond(&self, args: &[String]) -> CmdOut {
        let mut best: Option<&(Vec<String>, CmdOut)> = None;
        for entry in &self.script {
            if args.len() >= entry.0.len()
                && args[..entry.0.len()] == entry.0[..]
                && best.is_none_or(|b| entry.0.len() >= b.0.len())
            {
                best = Some(entry);
            }
        }
        best.map(|e| e.1.clone()).unwrap_or(CmdOut {
            success: true,
            stdout: String::new(),
            stderr: String::new(),
        })
    }

    fn calls(&self) -> Vec<Call> {
        self.calls.borrow().clone()
    }

    /// The argv of every recorded `git` call, joined for substring assertions.
    fn git_argv(&self) -> Vec<String> {
        self.calls()
            .into_iter()
            .filter(|c| c.program == "git")
            .map(|c| c.args.join(" "))
            .collect()
    }

    /// Every distinct `GIT_INDEX_FILE` this driver was handed.
    fn index_files(&self) -> Vec<PathBuf> {
        let mut seen: Vec<PathBuf> = self
            .calls()
            .into_iter()
            .filter_map(|c| c.index_file)
            .collect();
        seen.sort();
        seen.dedup();
        seen
    }
}

impl PauseVcs for FakeVcs {
    fn git(
        &self,
        _repo: &Path,
        args: &[String],
        index_file: Option<&Path>,
    ) -> anyhow::Result<CmdOut> {
        self.calls.borrow_mut().push(Call {
            program: "git",
            args: args.to_vec(),
            index_file: index_file.map(Path::to_path_buf),
        });
        Ok(self.respond(args))
    }

    fn tm(&self, _repo: &Path, args: &[String]) -> anyhow::Result<CmdOut> {
        self.calls.borrow_mut().push(Call {
            program: "tm",
            args: args.to_vec(),
            index_file: None,
        });
        if let Some(i) = args.iter().position(|a| a == "--body-file") {
            let path = PathBuf::from(&args[i + 1]);
            let body = std::fs::read_to_string(&path).unwrap_or_default();
            self.bodies.borrow_mut().push((path, body));
        }
        Ok(self.respond(args))
    }
}

/// A driver scripted for the whole happy path.
fn happy() -> FakeVcs {
    FakeVcs::new()
        .ok(&["rev-parse", "--abbrev-ref", "HEAD"], "main\n")
        .ok(
            &["rev-parse", "--abbrev-ref", "origin/HEAD"],
            "origin/main\n",
        )
        // exit 1 from `check-ignore` = the path is NOT ignored = tracked here.
        .fail(&["check-ignore"], "")
        .ok(&["rev-parse", "origin/main"], "base000\n")
        .ok(&["rev-parse", "base000^{tree}"], "basetree0\n")
        .ok(&["hash-object"], "blob111\n")
        .ok(&["write-tree"], "newtree9\n")
        .ok(&["commit-tree"], "c0ffee1\n")
        .ok(
            &["pr", "open"],
            "opened PR #4242 — https://github.com/bobmatnyc/trusty-tools/pull/4242\n",
        )
        .ok(&["pr", "merge"], "auto-merge armed on #4242\n")
}

fn ts() -> chrono::DateTime<chrono::Utc> {
    chrono::Utc
        .with_ymd_and_hms(2026, 9, 9, 18, 30, 15)
        .unwrap()
}

fn request<'a>(dir: &'a Path, paths: Vec<String>) -> PublishRequest<'a> {
    PublishRequest {
        repo: dir,
        session_id: "trusty-tools-95",
        // #7464: `None` exercises the documented fallback to the session id.
        session_name: None,
        timestamp: ts(),
        paths,
        default_branch: None,
    }
}

/// A request for a project whose configured default branch is `branch`.
fn request_on<'a>(dir: &'a Path, paths: Vec<String>, branch: &'a str) -> PublishRequest<'a> {
    PublishRequest {
        default_branch: Some(branch),
        ..request(dir, paths)
    }
}

fn snapshot_paths() -> Vec<String> {
    vec![
        ".trusty-mpm/sessions/abc/session-20260909-183015.md".to_string(),
        ".trusty-mpm/sessions/sessions-log.jsonl".to_string(),
    ]
}

/// The `--session` value the publish handed `tm pr open`.
///
/// Why (#7464): that value is the whole `ws/<session>` label, so a test has to
/// read it off the recorded argv rather than infer it.
fn pr_open_session(vcs: &FakeVcs) -> String {
    let call = vcs
        .calls()
        .into_iter()
        .find(|c| c.program == "tm" && c.args.first().is_some_and(|a| a == "pr"))
        .expect("the publish must call `tm pr open`");
    let at = call
        .args
        .iter()
        .position(|a| a == "--session")
        .expect("`tm pr open` must be given a session");
    call.args[at + 1].clone()
}

/// Why (#7464): the publish handed `tm pr open` the managed session's UUID, so
/// `gh pr create` failed with `could not add label: 'ws/<uuid>' not found` and
/// the snapshot commit stranded on a local branch with no PR. The label carries
/// the session NAME — the one session launch and `tm issue seed-labels` create.
/// Test: itself.
#[test]
fn the_workstream_label_comes_from_the_session_name() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let uuid = "b175bb88-af7f-5ba5-b75d-85795d60b234";
    let req = PublishRequest {
        session_id: uuid,
        session_name: Some("tm-agents"),
        ..request(dir.path(), snapshot_paths())
    };

    publish_pause_snapshot(&vcs, &req)
        .unwrap()
        .expect("a changed tree publishes");

    let session = pr_open_session(&vcs);
    assert_eq!(session, "tm-agents", "the NAME, not the managed id");
    assert_ne!(session, uuid);
    let label = crate::core::policy_labels::workstream_label(&session)
        .expect("a non-blank name derives a label");
    assert_eq!(label.name, "ws/tm-agents");
}

/// Why (#7464): a caller that cannot resolve a name — an unmanaged session, or
/// one already pruned from the store — must still publish. The documented
/// fallback is the session id itself, which is the pre-#7464 behaviour.
/// Test: itself.
#[test]
fn an_unnamed_session_falls_back_to_the_session_id() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let req = PublishRequest {
        session_name: Some("   "),
        ..request(dir.path(), snapshot_paths())
    };

    publish_pause_snapshot(&vcs, &req)
        .unwrap()
        .expect("a changed tree publishes");

    // The DOCUMENTED fallback: `PublishRequest::session_id`.
    assert_eq!(pr_open_session(&vcs), "trusty-tools-95");
}

/// Why: the defect was a commit on whatever branch the checkout was on. The
/// branch name is the receipt that a pause got its own branch off `origin/main`.
/// Test target: `branch_name`, via the public entry point.
#[test]
fn publish_branch_name_carries_session_and_timestamp() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("a changed tree publishes");

    assert_eq!(out.branch, "chore/sessions-trusty-tools-95-20260909-183015");
    assert_eq!(out.commit, "c0ffee1");
    assert_eq!(
        out.pr_url,
        "https://github.com/bobmatnyc/trusty-tools/pull/4242"
    );
    assert!(out.auto_merge_armed);

    // The commit is parented on `origin/main`, not on local HEAD.
    let argv = vcs.git_argv();
    assert!(
        argv.iter()
            .any(|a| a.starts_with("commit-tree newtree9 -p base000")),
        "{argv:?}"
    );
    // The branch ref is created and pushed without ever checking it out.
    assert!(
        argv.iter()
            .any(|a| a
                == "update-ref refs/heads/chore/sessions-trusty-tools-95-20260909-183015 c0ffee1"),
        "{argv:?}"
    );
    assert!(
        argv.iter()
            .any(|a| a.starts_with("push origin refs/heads/")),
        "{argv:?}"
    );
}

/// Why: the whole safety claim of this change is that a pause can never sweep
/// in a file it does not own. `git add` is the command that would, and the
/// scratch index is what keeps the shared one out of it.
/// Test target: the `update-index` / `read-tree` sequence.
#[test]
fn publish_commits_only_the_allowlisted_paths() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap();

    let argv = vcs.git_argv();
    assert!(
        !argv.iter().any(|a| a.starts_with("add")),
        "a pause must never run `git add`: {argv:?}"
    );
    assert!(
        !argv
            .iter()
            .any(|a| a.contains("stash") || a.contains("checkout")),
        "a pause must not stash or check anything out: {argv:?}"
    );

    let staged: Vec<&String> = argv
        .iter()
        .filter(|a| a.starts_with("update-index"))
        .collect();
    assert_eq!(staged.len(), 2, "{argv:?}");
    assert_eq!(
        staged[0],
        "update-index --add --cacheinfo 100644,blob111,.trusty-mpm/sessions/abc/session-20260909-183015.md"
    );
    assert_eq!(
        staged[1],
        "update-index --add --cacheinfo 100644,blob111,.trusty-mpm/sessions/sessions-log.jsonl"
    );

    // Every index-mutating call uses the scratch index, never the shared one.
    for call in vcs.calls().iter().filter(|c| c.program == "git") {
        let verb = call.args.first().map(String::as_str).unwrap_or("");
        if matches!(verb, "read-tree" | "update-index" | "write-tree") {
            assert!(
                call.index_file.is_some(),
                "`{verb}` ran against the shared index"
            );
        }
    }
}

/// Why: a caller that could name any path would turn the pause into an
/// arbitrary-commit primitive, which is exactly what the allowlist forbids.
/// Test target: `allowlisted`.
#[test]
fn publish_rejects_a_path_outside_the_sessions_tree() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let paths = vec![
        ".trusty-mpm/sessions/abc/session-1.md".to_string(),
        "crates/trusty-mpm/src/lib.rs".to_string(),
    ];
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), paths)).unwrap_err();

    assert!(
        matches!(
            &err,
            PublishError::Step {
                step: "allowlist",
                ..
            }
        ),
        "{err:?}"
    );
    assert!(
        err.to_string().contains("crates/trusty-mpm/src/lib.rs"),
        "{err}"
    );
    assert!(
        vcs.calls().is_empty(),
        "nothing may be spawned once the allowlist rejects a path"
    );
}

/// Why (owner ruling, #7282 round 5): a pause is live state and publishes as
/// its own PR, so a checkout parked on a feature branch must still produce one.
/// The commit is built with plumbing against `origin/<default>` and the PR
/// names its own `--head`, so the checkout's branch cannot leak into either —
/// which is what makes refusing it unnecessary. Nothing about the feature
/// branch may appear in the commit, the push, or the PR.
/// Test target: the detached-HEAD guard, permitting arm.
#[test]
fn a_feature_branch_checkout_still_publishes() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().ok(
        &["rev-parse", "--abbrev-ref", "HEAD"],
        "fix/7282-something\n",
    );
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("a feature-branch checkout publishes");

    assert_eq!(out.branch, "chore/sessions-trusty-tools-95-20260909-183015");
    assert_eq!(out.commit, "c0ffee1");

    let argv = vcs.git_argv();
    // Parented on `origin/main`, never on the checkout's branch.
    assert!(
        argv.iter()
            .any(|a| a.starts_with("commit-tree newtree9 -p base000")),
        "{argv:?}"
    );
    assert!(
        !argv.iter().any(|a| a.contains("fix/7282-something")),
        "the checkout's branch may not reach any git step: {argv:?}"
    );
    // The PR opens from the chore branch, against the default branch.
    let tm = tm_call(&vcs, 0);
    assert_eq!(
        flag_value(&tm, "--head").as_deref(),
        Some(out.branch.as_str())
    );
    assert_eq!(flag_value(&tm, "--base").as_deref(), Some("main"));
}

/// Why: `session_context_pause` serves every managed project, so a `develop`
/// project must publish from `develop` — the literal `main` the first round
/// carried made every pause on such a project an error.
/// Test target: `resolve_default_branch`, configured arm.
#[test]
fn publish_uses_the_configured_default_branch() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy()
        .ok(&["rev-parse", "--abbrev-ref", "HEAD"], "develop\n")
        .ok(&["rev-parse", "origin/develop"], "base000\n");
    let out = publish_pause_snapshot(&vcs, &request_on(dir.path(), snapshot_paths(), "develop"))
        .unwrap()
        .expect("a changed tree publishes");

    assert_eq!(out.commit, "c0ffee1");
    let argv = vcs.git_argv();
    assert!(
        argv.contains(&"fetch origin develop".to_string()),
        "{argv:?}"
    );
    assert!(
        argv.contains(&"rev-parse origin/develop".to_string()),
        "{argv:?}"
    );
    assert!(
        !argv
            .iter()
            .any(|a| a.contains("origin/HEAD") || a.contains("origin/main")),
        "a configured branch is authoritative; nothing else may be consulted: {argv:?}"
    );

    // The PR opens against `develop`, not `main`.
    let tm = vcs
        .calls()
        .into_iter()
        .find(|c| c.program == "tm")
        .unwrap()
        .args;
    assert_eq!(
        tm[tm.iter().position(|a| a == "--base").unwrap() + 1],
        "develop"
    );
}

/// Why: a project with no declared default branch must still read the branch
/// off its own checkout rather than assume `main`.
/// Test target: `resolve_default_branch`, `origin/HEAD` arm.
#[test]
fn publish_falls_back_to_origin_head_for_the_default_branch() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy()
        .ok(&["rev-parse", "--abbrev-ref", "HEAD"], "develop\n")
        .ok(
            &["rev-parse", "--abbrev-ref", "origin/HEAD"],
            "origin/develop\n",
        )
        .ok(&["rev-parse", "origin/develop"], "base000\n");
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("a changed tree publishes");

    assert_eq!(out.commit, "c0ffee1");
    assert!(
        vcs.git_argv().contains(&"fetch origin develop".to_string()),
        "{:?}",
        vcs.git_argv()
    );
}

/// Why: `main` stays the answer when nothing else names one, and it has to
/// reach the fetch, the parent commit and the PR base — a checkout sitting on
/// some other branch must not become the answer by default.
/// Test target: `resolve_default_branch`, `FALLBACK_BRANCH` arm.
#[test]
fn publish_falls_back_to_main_when_nothing_names_a_branch() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy()
        .ok(&["rev-parse", "--abbrev-ref", "HEAD"], "master\n")
        .fail(
            &["rev-parse", "--abbrev-ref", "origin/HEAD"],
            "fatal: ambiguous argument 'origin/HEAD'",
        );
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("a changed tree publishes");

    assert_eq!(out.commit, "c0ffee1");
    let argv = vcs.git_argv();
    assert!(argv.contains(&"fetch origin main".to_string()), "{argv:?}");
    assert!(
        !argv.iter().any(|a| a.contains("master")),
        "the checkout's branch is not a default-branch answer: {argv:?}"
    );
    assert_eq!(
        flag_value(&tm_call(&vcs, 0), "--base").as_deref(),
        Some("main")
    );
}

/// Why: when the push fails the commit already exists locally, and a person
/// needs to be told exactly where it is instead of re-running a pause that
/// would build a second one.
/// Test target: `git_at`'s commit attribution.
#[test]
fn push_failure_leaves_the_commit_and_names_it() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().fail(&["push"], "remote rejected: no write access");
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();

    let PublishError::Step {
        step,
        branch,
        commit,
        ..
    } = &err
    else {
        panic!("{err:?}");
    };
    assert_eq!(*step, "push");
    assert_eq!(
        branch.as_deref(),
        Some("chore/sessions-trusty-tools-95-20260909-183015")
    );
    assert_eq!(commit.as_deref(), Some("c0ffee1"));
    let text = err.to_string();
    assert!(text.contains("remote rejected"), "{text}");
    assert!(text.contains("push it and open its PR by hand"), "{text}");

    // The local branch ref survives for a person to push.
    assert!(
        vcs.git_argv().iter().any(|a| a.starts_with("update-ref ")),
        "the branch must still have been created"
    );
    // `tm pr open` was never reached.
    assert!(
        !vcs.calls().iter().any(|c| c.program == "tm"),
        "{:?}",
        vcs.calls()
    );
}

/// Why: `tm pr open` failing after a successful push leaves a pushed branch
/// with no PR, which is a different repair than a failed push.
#[test]
fn pr_open_failure_reports_the_pushed_branch() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().fail(&["pr", "open"], "check failed: workstream label");
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();

    let PublishError::Step { step, commit, .. } = &err else {
        panic!("{err:?}");
    };
    assert_eq!(*step, "pr-open");
    assert_eq!(commit.as_deref(), Some("c0ffee1"));
    assert!(err.to_string().contains("workstream label"), "{err}");
}

/// Why: `tm pr open` is the workspace's only `gh pr create` site, and this
/// module must reach GitHub through it rather than growing a second one.
#[test]
fn publish_opens_the_pr_through_tm_pr_open() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap();

    let tm: Vec<Vec<String>> = vcs
        .calls()
        .into_iter()
        .filter(|c| c.program == "tm")
        .map(|c| c.args)
        .collect();
    assert_eq!(tm.len(), 2, "{tm:?}");
    assert_eq!(tm[0][0..2], ["pr".to_string(), "open".to_string()]);
    assert!(tm[0].contains(&"--docs-only".to_string()), "{:?}", tm[0]);
    assert!(tm[0].contains(&"--rung".to_string()), "{:?}", tm[0]);
    assert_eq!(
        tm[0][tm[0].iter().position(|a| a == "--title").unwrap() + 1],
        "chore(sessions): pause snapshot for trusty-tools-95 2026-09-09 18:30Z"
    );
    assert_eq!(
        tm[1],
        vec![
            "pr".to_string(),
            "merge".to_string(),
            "4242".to_string(),
            "--auto".to_string()
        ]
    );

    // The body file `tm pr open` was handed satisfies the nine-field contract.
    // It is read as `tm` saw it: the scratch directory is gone by now.
    let (body_path, body) = vcs.bodies.borrow()[0].clone();
    for heading in [
        "## Outcome",
        "## Changes",
        "## Risk",
        "## Tests",
        "## Baseline",
        // #7336 widened the contract; the generated body must carry the two
        // disclosure fields or `tm pr open` would refuse its own pause PR.
        "## Gates not run",
        "## Partial-red accounting",
        "## Docs",
        "## Review",
    ] {
        assert!(body.contains(heading), "body is missing {heading}:\n{body}");
    }
    assert!(body.trim_end().ends_with(ATTRIBUTION_FOOTER), "{body}");
    assert!(
        !body.to_lowercase().contains("closes #"),
        "a session PR closes nothing: {body}"
    );
    assert!(
        !body_path.exists(),
        "the scratch body must not outlive the publish: {}",
        body_path.display()
    );
}

// ── the explicit head branch (#7282 round 4) ─────────────────────────────

/// REGRESSION (#7282 round 4): the publish reached `pr-open` and `gh pr create`
/// aborted with "you must first push the current branch to a remote, or use the
/// --head flag". The branch WAS pushed; what was missing is that `gh` reads the
/// head from the checkout's current branch, which is the default branch here
/// and never the plumbing-built chore branch. Naming both ends of the PR is the
/// fix.
/// Test target: the `tm pr open` argv.
#[test]
fn pr_open_names_the_chore_branch_as_the_head() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("the happy path publishes");

    let open = tm_call(&vcs, 0);
    assert_eq!(
        flag_value(&open, "--head").as_deref(),
        Some(out.branch.as_str()),
        "{open:?}"
    );
    assert_eq!(
        flag_value(&open, "--base").as_deref(),
        Some("main"),
        "{open:?}"
    );
}

/// Why: the head must be the branch that was pushed, not a name derived a
/// second time — a `--head` naming a ref the push never created opens nothing.
/// Test target: push refspec and `--head`, read from the same run.
#[test]
fn the_pushed_branch_is_the_head_the_pr_opens_from() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy();
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("the happy path publishes");

    let branch = &out.branch;
    let calls = vcs.calls();
    let push_at = calls
        .iter()
        .position(|c| {
            c.program == "git"
                && c.args.first().map(String::as_str) == Some("push")
                && c.args
                    .contains(&format!("refs/heads/{branch}:refs/heads/{branch}"))
        })
        .expect("the exact branch must be pushed");
    let open_at = calls
        .iter()
        .position(|c| c.program == "tm" && c.args.first().map(String::as_str) == Some("pr"))
        .expect("the PR must be opened");
    assert!(
        push_at < open_at,
        "the push must precede pr-open: {calls:?}"
    );
    assert_eq!(calls[push_at].args[1], "origin", "{:?}", calls[push_at]);
}

/// Why: the live failure came from a checkout carrying 89 uncommitted changes,
/// which `gh` warned about. The publish must not read, stage, stash, or switch
/// anything in that checkout — its state is the caller's, and the commit is
/// built from the allowlisted files alone. The fixture sits on a feature
/// branch, because that is now a checkout the publish accepts (#7282 round 5)
/// and the one where a stray `checkout` or `switch` would do the most damage.
/// Test target: the whole command set the publish runs.
#[test]
fn a_dirty_checkout_is_never_read_staged_or_switched() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().ok(&["rev-parse", "--abbrev-ref", "HEAD"], "fix/some-work\n");
    publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap();

    for argv in vcs.git_argv() {
        let verb = argv.split(' ').next().unwrap_or_default();
        assert!(
            !matches!(
                verb,
                "add" | "stash" | "checkout" | "switch" | "status" | "commit"
            ),
            "the publish must not touch the checkout: `git {argv}`"
        );
    }
}

/// Why: a detached checkout has no branch name, so `rev-parse --abbrev-ref
/// HEAD` answers the literal `HEAD`. That must produce the named refusal that
/// tells a person what to do — never a publish onto a `HEAD` branch, and never
/// a panic. This is the one checkout state the publish still refuses (#7282
/// round 5); a feature branch is not.
/// Test target: the detached-HEAD guard, refusing arm.
#[test]
fn a_detached_checkout_is_refused_by_name() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().ok(&["rev-parse", "--abbrev-ref", "HEAD"], "HEAD\n");
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();

    assert_eq!(
        err,
        PublishError::NotOnDefaultBranch {
            expected: "main".to_string(),
            actual: "HEAD".to_string(),
        }
    );
    assert!(err.to_string().contains("detached checkout"), "{err}");
    assert!(
        err.to_string().contains("The snapshot file was written"),
        "{err}"
    );
    assert!(
        !vcs.calls().iter().any(|c| c.program == "tm"),
        "no PR may be opened from a detached checkout: {:?}",
        vcs.calls()
    );
}

/// The argv of the `n`th recorded `tm` call.
fn tm_call(vcs: &FakeVcs, n: usize) -> Vec<String> {
    vcs.calls()
        .into_iter()
        .filter(|c| c.program == "tm")
        .map(|c| c.args)
        .nth(n)
        .unwrap_or_else(|| panic!("no tm call #{n}"))
}

/// The value `flag` was given in `argv`, or `None` when the flag is absent.
fn flag_value(argv: &[String], flag: &str) -> Option<String> {
    let at = argv.iter().position(|a| a == flag)?;
    argv.get(at + 1).cloned()
}

/// Why: `tm pr merge --auto` refuses for reasons a person must act on — a
/// missing label, auto-merge disabled on the repo, a permissions gap. Dropping
/// its stderr left `auto_merge_armed: false` as the entire report, so the PR
/// simply never merged and nothing anywhere said why (#7282 review round 3).
/// The publish itself must still succeed: the PR is the deliverable.
/// Test target: the `pr merge` arm's failure capture.
#[test]
fn auto_merge_failure_is_reported_without_failing_the_publish() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().fail(
        &["pr", "merge"],
        "auto-merge is not enabled for bobmatnyc/trusty-tools",
    );
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("an unarmed PR is still a published PR");

    assert!(!out.auto_merge_armed, "{out:?}");
    assert_eq!(
        out.auto_merge_error.as_deref(),
        Some("auto-merge is not enabled for bobmatnyc/trusty-tools"),
        "{out:?}"
    );
    // The PR and its commit are unaffected — the caller reads them either way.
    assert_eq!(out.branch, "chore/sessions-trusty-tools-95-20260909-183015");
    assert_eq!(out.commit, "c0ffee1");
    assert_eq!(
        out.pr_url,
        "https://github.com/bobmatnyc/trusty-tools/pull/4242"
    );
}

/// Why: `auto_merge_error` is the reason arming failed, so carrying one on a
/// PR that DID arm would make every armed pause look broken.
#[test]
fn a_successful_arming_carries_no_auto_merge_error() {
    let dir = tempfile::TempDir::new().unwrap();
    let out = publish_pause_snapshot(&happy(), &request(dir.path(), snapshot_paths()))
        .unwrap()
        .expect("the happy path opens a PR");
    assert!(out.auto_merge_armed, "{out:?}");
    assert_eq!(out.auto_merge_error, None, "{out:?}");
}

/// Why: two pauses overlapping — two sessions, or two projects on one host —
/// shared one `GIT_INDEX_FILE` and one body file when the scratch directory was
/// `std::env::temp_dir()` with fixed names, so one PR could carry the other's
/// tree with every git step exiting 0 (#7282 review).
/// Test target: the per-call `TempDir`.
#[test]
fn concurrent_publishes_never_share_a_scratch_index() {
    let indexes: Vec<PathBuf> = std::thread::scope(|s| {
        let handles: Vec<_> = (0..8)
            .map(|_| {
                s.spawn(|| {
                    let dir = tempfile::TempDir::new().unwrap();
                    let vcs = happy();
                    publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap();
                    let idx = vcs.index_files();
                    assert_eq!(idx.len(), 1, "one publish uses one index: {idx:?}");
                    idx.into_iter().next().unwrap()
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let mut unique = indexes.clone();
    unique.sort();
    unique.dedup();
    assert_eq!(
        unique.len(),
        indexes.len(),
        "concurrent publishes shared a scratch index: {indexes:?}"
    );
}

/// Why: the first round removed the scratch index only on the success path, so
/// every failed publish left one behind under a name the next publish would
/// reuse.
/// Test target: `TempDir`'s drop on the early-return arms.
#[test]
fn an_early_failure_leaves_no_scratch_file_behind() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().fail(&["write-tree"], "fatal: unable to write new index file");
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();
    assert!(
        matches!(
            err,
            PublishError::Step {
                step: "write-tree",
                ..
            }
        ),
        "{err:?}"
    );

    let idx = vcs.index_files();
    assert_eq!(idx.len(), 1, "{idx:?}");
    assert!(
        !idx[0].exists(),
        "scratch index survived: {}",
        idx[0].display()
    );
    assert!(
        !idx[0].parent().unwrap().exists(),
        "scratch directory survived: {}",
        idx[0].parent().unwrap().display()
    );
}

/// Why: `hash-object` follows a symlink, so a `.trusty-mpm/sessions/` entry
/// pointing at `~/.ssh/id_ed25519` would commit that file's contents under a
/// sessions-tree name. The allowlist is the only place that can refuse it.
/// Test target: `allowlisted`'s regular-file check.
#[test]
fn publish_rejects_a_snapshot_path_that_is_not_a_regular_file() {
    let dir = tempfile::TempDir::new().unwrap();
    let sessions = dir.path().join(".trusty-mpm/sessions");
    std::fs::create_dir_all(&sessions).unwrap();
    std::fs::write(dir.path().join("secret.txt"), b"private").unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink(dir.path().join("secret.txt"), sessions.join("linked.md")).unwrap();
    #[cfg(not(unix))]
    std::fs::create_dir_all(sessions.join("linked.md")).unwrap();

    let vcs = happy();
    let paths = vec![".trusty-mpm/sessions/linked.md".to_string()];
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), paths)).unwrap_err();

    assert!(
        matches!(
            &err,
            PublishError::Step {
                step: "allowlist",
                ..
            }
        ),
        "{err:?}"
    );
    assert!(err.to_string().contains("not a regular file"), "{err}");
    assert!(
        vcs.calls().is_empty(),
        "nothing may be spawned once the allowlist rejects a path"
    );
}

/// Why: `symlink_metadata` on the full path answers about the LEAF only — every
/// ancestor segment is followed first. A `.trusty-mpm/sessions` that is itself a
/// symlink to a directory outside the checkout therefore left the leaf reporting
/// as an ordinary regular file, and `hash-object` committed the redirected
/// content under a sessions-tree name (#7282 review round 3).
/// Test target: `allowlisted`'s per-component walk.
#[cfg(unix)]
#[test]
fn publish_rejects_a_symlinked_sessions_directory() {
    let dir = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    std::fs::write(outside.path().join("session-1.md"), b"redirected").unwrap();
    std::fs::create_dir_all(dir.path().join(".trusty-mpm")).unwrap();
    std::os::unix::fs::symlink(outside.path(), dir.path().join(".trusty-mpm/sessions")).unwrap();

    let vcs = happy();
    let paths = vec![".trusty-mpm/sessions/session-1.md".to_string()];
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), paths)).unwrap_err();

    assert!(
        matches!(
            &err,
            PublishError::Step {
                step: "allowlist",
                ..
            }
        ),
        "{err:?}"
    );
    assert!(err.to_string().contains("symlink"), "{err}");
    assert!(
        vcs.calls().is_empty(),
        "nothing may be spawned once the allowlist rejects a redirected path"
    );
}

/// Why: a project that keeps `.trusty-mpm/sessions/` git-ignored has nothing to
/// publish, and turning that into a failed pause would break every such project.
#[test]
fn publish_skips_a_project_that_ignores_its_sessions() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = FakeVcs::new()
        .ok(&["rev-parse", "--abbrev-ref", "HEAD"], "main\n")
        // exit 0 from `check-ignore` = the path IS ignored.
        .ok(&["check-ignore"], "");
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();

    assert!(matches!(err, PublishError::NotTracked(_)), "{err:?}");
    assert!(
        !vcs.git_argv().iter().any(|a| a.starts_with("fetch")),
        "nothing may be fetched for an untracked sessions tree"
    );
}

/// Why: re-publishing an unchanged snapshot would open an empty PR on every
/// pause. Comparing the assembled tree against `origin/main`'s is what stops it.
#[test]
fn publish_is_a_noop_when_the_tree_is_unchanged() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = happy().ok(&["write-tree"], "basetree0\n");
    let out = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap();

    assert!(out.is_none(), "{out:?}");
    assert!(
        !vcs.git_argv().iter().any(|a| a.starts_with("commit-tree")),
        "no commit may be created when nothing changed"
    );
    assert!(!vcs.calls().iter().any(|c| c.program == "tm"));
}

/// Why: `session_context_pause` also runs against project directories that are
/// not checkouts at all. Treating that as a failed pause would break every such
/// project — and did break seven existing tests before this arm was added.
#[test]
fn publish_skips_a_directory_that_is_not_a_git_repo() {
    let dir = tempfile::TempDir::new().unwrap();
    let vcs = FakeVcs::new().fail(
        &["rev-parse", "--abbrev-ref", "HEAD"],
        "fatal: not a git repository (or any of the parent directories): .git",
    );
    let err = publish_pause_snapshot(&vcs, &request(dir.path(), snapshot_paths())).unwrap_err();

    assert!(matches!(err, PublishError::NotAGitRepo(_)), "{err:?}");
    assert_eq!(vcs.calls().len(), 1, "{:?}", vcs.calls());
}

/// Why: a session id with slashes or spaces would produce an invalid ref.
#[test]
fn slug_bounds_and_sanitizes_the_session_id() {
    assert_eq!(super::slug("trusty-tools-95"), "trusty-tools-95");
    assert_eq!(super::slug("tmux window/1"), "tmux-window-1");
    assert_eq!(super::slug("///"), "session");
    assert_eq!(super::slug(&"x".repeat(80)).len(), 40);
}