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
//! Tests for the merged-pull-request matcher (#7267).
//!
//! Why: this ladder's grant is what authorises deleting a checkout, so every
//! rung needs a test that fails if the rung is removed, and every FAILURE path
//! needs one proving it refuses rather than reclaims. The probe is faked
//! because the real one is `gh` and `git`; what is under test is the policy —
//! which answers count as landing evidence — not the subprocesses.
//! What: one test per rung, one per failure mode of each rung, and the
//! `resolve_with_index` wiring that decides when a rung may run at all.

use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use super::*;

/// The worktree's HEAD in every test that does not override it.
const HEAD_SHA: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
/// A commit that is not this worktree's HEAD.
const OTHER_SHA: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

/// The worktree directory under test — the fake probe never touches disk.
fn worktree() -> &'static Path {
    Path::new("/nonexistent/worktree-7267")
}

/// The registry root under test — likewise never touched.
fn root() -> &'static Path {
    Path::new("/nonexistent/root-7267")
}

/// A [`LandingProbe`] whose every answer is stated by the test.
pub(crate) struct FakeProbe {
    /// Branch name → what GitHub says about it.
    heads: BTreeMap<String, BranchPrState>,
    /// What `git rev-parse HEAD` answers.
    head_commit: Result<String, String>,
    /// What the commit search answers.
    search: Result<Vec<MergedPrHead>, String>,
    /// Ordered pairs for which `is_ancestor` answers true.
    ancestors: BTreeSet<(String, String)>,
    /// When set, `is_ancestor` fails with this reason instead of answering.
    ancestry_error: Option<String>,
    /// Every probe method called, in order — so a test can prove a rung was
    /// NOT reached.
    calls: RefCell<Vec<String>>,
}

impl Default for FakeProbe {
    fn default() -> Self {
        Self {
            heads: BTreeMap::new(),
            head_commit: Ok(HEAD_SHA.to_string()),
            search: Ok(Vec::new()),
            ancestors: BTreeSet::new(),
            ancestry_error: None,
            calls: RefCell::new(Vec::new()),
        }
    }
}

impl FakeProbe {
    /// State `branch`'s pull-request answer.
    pub(crate) fn with_head(mut self, branch: &str, state: BranchPrState) -> Self {
        self.heads.insert(branch.to_string(), state);
        self
    }

    /// State what the commit search returns.
    pub(crate) fn with_search(mut self, rows: Vec<MergedPrHead>) -> Self {
        self.search = Ok(rows);
        self
    }

    /// State that the commit search FAILS.
    pub(crate) fn with_search_error(mut self, reason: &str) -> Self {
        self.search = Err(reason.to_string());
        self
    }

    /// State what `git rev-parse HEAD` answers.
    pub(crate) fn with_head_commit(mut self, answer: Result<String, String>) -> Self {
        self.head_commit = answer;
        self
    }

    /// State that the ancestry probe FAILS — what an object this checkout does
    /// not hold looks like.
    pub(crate) fn with_ancestry_error(mut self, reason: &str) -> Self {
        self.ancestry_error = Some(reason.to_string());
        self
    }

    /// State that `ancestor` is an ancestor of `descendant`.
    pub(crate) fn with_ancestor(mut self, ancestor: &str, descendant: &str) -> Self {
        self.ancestors
            .insert((ancestor.to_string(), descendant.to_string()));
        self
    }

    /// Did any probe method get called?
    pub(crate) fn calls(&self) -> Vec<String> {
        self.calls.borrow().clone()
    }
}

impl LandingProbe for FakeProbe {
    fn state_for_head(&self, _registry_root: &Path, branch: &str) -> BranchPrState {
        self.calls.borrow_mut().push(format!("head:{branch}"));
        self.heads
            .get(branch)
            .cloned()
            .unwrap_or(BranchPrState::NoPr)
    }

    fn head_commit(&self, _worktree: &Path) -> Result<String, String> {
        self.calls.borrow_mut().push("head_commit".to_string());
        self.head_commit.clone()
    }

    fn merged_prs_containing(
        &self,
        _registry_root: &Path,
        sha: &str,
    ) -> Result<Vec<MergedPrHead>, String> {
        self.calls.borrow_mut().push(format!("search:{sha}"));
        self.search.clone()
    }

    fn is_ancestor(
        &self,
        _worktree: &Path,
        ancestor: &str,
        descendant: &str,
    ) -> Result<bool, String> {
        self.calls
            .borrow_mut()
            .push(format!("ancestor:{ancestor}:{descendant}"));
        if let Some(reason) = &self.ancestry_error {
            return Err(reason.clone());
        }
        Ok(self
            .ancestors
            .contains(&(ancestor.to_string(), descendant.to_string())))
    }
}

/// One row of the commit search, from this repository.
fn row(number: u64, head_ref_oid: &str) -> MergedPrHead {
    MergedPrHead {
        number,
        head_ref_oid: head_ref_oid.to_string(),
        is_cross_repository: false,
    }
}

// ---------------------------------------------------------------------------
// Rung 2 — the round-stem sibling
// ---------------------------------------------------------------------------

/// The reported defect, one rung at a time: a worktree left on `<branch>-r2`
/// after a review round, whose pull request merged under `<branch>` (#7267).
#[test]
fn a_round_sibling_with_a_merged_pr_is_reclaimable() {
    let probe = FakeProbe::default().with_head("fix/7267-thing", BranchPrState::Merged { pr: 91 });
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-thing-r2"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::Merged { pr: 91 });
    assert_eq!(probe.calls(), vec!["head:fix/7267-thing".to_string()]);
}

/// A sibling whose pull request is still OPEN is work in flight — the rung
/// produces nothing and the refusal stands (#7267).
#[test]
fn a_round_sibling_whose_stem_pr_is_open_is_not_widened() {
    let probe = FakeProbe::default().with_head("fix/7267-thing", BranchPrState::Open { pr: 92 });
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-thing-r2"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr, "an open sibling grants nothing");
}

/// A branch with no round suffix costs no sibling lookup at all (#7267).
#[test]
fn a_branch_without_a_round_suffix_asks_for_no_sibling() {
    let probe = FakeProbe::default();
    let _ = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-thing"),
        BranchPrState::NoPr,
        &probe,
    );
    assert!(
        !probe.calls().iter().any(|c| c.starts_with("head:")),
        "no stem to ask about: {:?}",
        probe.calls()
    );
}

// ---------------------------------------------------------------------------
// Rung 3 — the head commit
// ---------------------------------------------------------------------------

/// A branch re-cut under a new name before its pull request opened: no name
/// relates the two, but the COMMIT does (#7267).
#[test]
fn a_renamed_branch_matches_the_pr_opened_from_its_head_commit() {
    let probe = FakeProbe::default().with_search(vec![row(93, HEAD_SHA)]);
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::Merged { pr: 93 });
}

/// A pull request opened from a DESCENDANT of this HEAD carried everything
/// here, so it vouches for the tree too (#7267).
#[test]
fn a_pr_opened_from_a_descendant_of_this_head_also_vouches() {
    let probe = FakeProbe::default()
        .with_search(vec![row(94, OTHER_SHA)])
        .with_ancestor(HEAD_SHA, OTHER_SHA);
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::Merged { pr: 94 });
}

/// A detached worktree has no branch to widen by name, and still reaches the
/// commit rung (#7267).
#[test]
fn a_detached_worktree_can_still_match_by_head_commit() {
    let probe = FakeProbe::default().with_search(vec![row(95, HEAD_SHA)]);
    let out = resolve_landing(worktree(), root(), None, BranchPrState::Unknown, &probe);
    assert_eq!(out, BranchPrState::Merged { pr: 95 });
}

/// A merged pull request the search returned whose head stands in no ancestry
/// relationship to this HEAD vouches for nothing (#7267).
#[test]
fn an_unrelated_merged_pr_containing_no_ancestor_is_not_a_match() {
    let probe = FakeProbe::default().with_search(vec![row(96, OTHER_SHA)]);
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
}

/// A fork's pull request that happens to contain a commit of this name is not
/// this repository's landing evidence (#7267, the #2919 rule).
#[test]
fn a_fork_pull_request_containing_the_commit_is_ignored() {
    let mut fork = row(97, HEAD_SHA);
    fork.is_cross_repository = true;
    let probe = FakeProbe::default().with_search(vec![fork]);
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
}

// ---------------------------------------------------------------------------
// The refusals — every one of these would be a deleted checkout if it granted
// ---------------------------------------------------------------------------

/// The acceptance condition: no merged pull request under ANY route leaves the
/// worktree refused, `--force` or not (#7267).
#[test]
fn no_merged_pr_under_any_stem_is_still_refused() {
    let probe = FakeProbe::default();
    for (branch, exact) in [
        (Some("fix/7267-thing-r2"), BranchPrState::NoPr),
        (Some("fix/7267-thing"), BranchPrState::NoPr),
        (None, BranchPrState::Unknown),
    ] {
        let out = resolve_landing(worktree(), root(), branch, exact.clone(), &probe);
        assert_eq!(out, exact, "branch {branch:?} must stay refused");
    }
}

/// A settled answer about the branch ITSELF is never widened past — an open
/// pull request means work in flight (#7267).
#[test]
fn an_open_pr_on_the_branch_is_never_widened() {
    let probe = FakeProbe::default()
        .with_head("fix/7267-thing", BranchPrState::Merged { pr: 98 })
        .with_search(vec![row(99, HEAD_SHA)]);
    for exact in [
        BranchPrState::Open { pr: 1 },
        BranchPrState::ClosedUnmerged { pr: 2 },
        BranchPrState::LookupFailed {
            reason: "`gh` exited 4".to_string(),
        },
    ] {
        let out = resolve_landing(
            worktree(),
            root(),
            Some("fix/7267-thing-r2"),
            exact.clone(),
            &probe,
        );
        assert_eq!(out, exact, "a settled answer is the answer");
    }
    assert!(probe.calls().is_empty(), "and costs no widening call");
}

/// A HEAD that git could not read denies — the branch-name refusal stands and
/// nothing is reclaimed (#7267 fail-open check).
#[test]
fn a_failed_head_commit_read_leaves_the_refusal_standing() {
    let probe = FakeProbe::default()
        .with_search(vec![row(100, HEAD_SHA)])
        .with_head_commit(Err("`git rev-parse HEAD` failed (128)".to_string()));
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
    assert!(
        !probe.calls().iter().any(|c| c.starts_with("search:")),
        "and never searches on a HEAD it could not read: {:?}",
        probe.calls()
    );
}

/// A `gh` that could not answer the commit search denies (#7267 fail-open
/// check).
#[test]
fn a_failed_commit_search_leaves_the_refusal_standing() {
    let probe = FakeProbe::default().with_search_error("`gh` exited 4: gh auth login");
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
}

/// A git that could not settle the ancestry denies — an unresolvable object is
/// exactly what a pull request head this checkout never fetched looks like
/// (#7267 fail-open check).
#[test]
fn a_failed_ancestry_probe_leaves_the_refusal_standing() {
    let probe = FakeProbe::default()
        .with_search(vec![row(101, OTHER_SHA)])
        .with_ancestry_error("bad object bbbbbbb");
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
}

/// 🔴 #8721 (critic HIGH): on a detached HEAD a search that did not answer is
/// `LookupFailed`, and one that answered with no match stays `Unknown` — the
/// state gate 5 lets reach the landed-content admission.
#[test]
fn worktree_8721_a_detached_head_whose_search_failed_is_a_lookup_failure() {
    let failed = FakeProbe::default().with_search_error("`gh` exited 4: gh auth login");
    let out = resolve_landing(worktree(), root(), None, BranchPrState::Unknown, &failed);
    assert!(
        matches!(&out, BranchPrState::LookupFailed { reason } if reason.contains("gh auth login")),
        "{out:?}"
    );
    let unread = FakeProbe::default().with_head_commit(Err("exit 128".to_string()));
    let out = resolve_landing(worktree(), root(), None, BranchPrState::Unknown, &unread);
    assert!(matches!(out, BranchPrState::LookupFailed { .. }), "{out:?}");
    let answered = FakeProbe::default().with_search(Vec::new());
    let out = resolve_landing(worktree(), root(), None, BranchPrState::Unknown, &answered);
    assert_eq!(out, BranchPrState::Unknown);
}

/// A HEAD the probe reports as empty is not a commit to search for (#7267).
#[test]
fn an_empty_head_commit_reaches_no_search() {
    let probe = FakeProbe::default().with_head_commit(Ok("   ".to_string()));
    let out = resolve_landing(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        BranchPrState::NoPr,
        &probe,
    );
    assert_eq!(out, BranchPrState::NoPr);
    assert_eq!(probe.calls(), vec!["head_commit".to_string()]);
}

// ---------------------------------------------------------------------------
// resolve_with_index — when a rung is allowed to run at all
// ---------------------------------------------------------------------------

/// A merged row keyed by a branch name.
fn index(branch: &str, pr: u64, state: &str) -> PrIndex {
    PrIndex::from_json(
        &format!(r#"[{{"number": {pr}, "headRefName": "{branch}", "state": "{state}"}}]"#),
        400,
    )
}

/// The `tm doctor` probe passes `per_branch_fallback: false` and must pay for
/// no network call — the index's own answer is the whole answer (#7267).
#[test]
fn resolve_with_index_without_fallback_never_calls_the_probe() {
    let probe = FakeProbe::default().with_head("fix/7267-thing", BranchPrState::Merged { pr: 102 });
    let out = resolve_with_index(
        worktree(),
        root(),
        Some("fix/7267-unrelated"),
        &index("fix/7267-thing", 102, "MERGED"),
        false,
        &probe,
    )
    .landing;
    assert_eq!(out, BranchPrState::NoPr);
    assert!(probe.calls().is_empty(), "{:?}", probe.calls());
}

/// #6561's per-branch retry survives the move into this function: a TRUNCATED
/// index still asks `gh` about the branch itself before any widening.
#[test]
fn resolve_with_index_retries_a_truncated_index_per_branch() {
    // A one-row reply against a limit of 1 is indistinguishable from a
    // truncated page, so the index reports incomplete.
    let truncated = PrIndex::from_json(
        r#"[{"number": 103, "headRefName": "someone/else", "state": "MERGED"}]"#,
        1,
    );
    let probe = FakeProbe::default().with_head("fix/7267-mine", BranchPrState::Merged { pr: 104 });
    let out = resolve_with_index(
        worktree(),
        root(),
        Some("fix/7267-mine"),
        &truncated,
        true,
        &probe,
    )
    .landing;
    assert_eq!(out, BranchPrState::Merged { pr: 104 });
    assert_eq!(probe.calls(), vec!["head:fix/7267-mine".to_string()]);
}

/// A COMPLETE index that answers `NoPr` is still widened — the renamed-branch
/// case has nothing to do with the index being truncated (#7267).
#[test]
fn resolve_with_index_widens_a_complete_index_no_pr_answer() {
    let probe = FakeProbe::default().with_search(vec![row(105, HEAD_SHA)]);
    let out = resolve_with_index(
        worktree(),
        root(),
        Some("fix/7267-recut"),
        &index("someone/else", 103, "MERGED"),
        true,
        &probe,
    )
    .landing;
    assert_eq!(out, BranchPrState::Merged { pr: 105 });
}

/// 🔴 #8301: a COMPLETE index answers the round-stem lookup itself, so a
/// `-rN` branch costs no `gh --head` call for its stem.
///
/// Fails on `origin/main`: rung 2 asked the probe about the stem even with a
/// complete index, so `calls()` held `head:fix/8301-batch` and the fake's
/// answer, `Merged`, came back — a network round-trip per round-suffixed tree.
#[test]
fn worktree_8301_a_complete_index_answers_the_round_stem_without_gh() {
    let probe = FakeProbe::default().with_head("fix/8301-batch", BranchPrState::Merged { pr: 106 });
    let out = resolve_with_index(
        worktree(),
        root(),
        Some("fix/8301-batch-r2"),
        &index("someone/else", 103, "MERGED"),
        true,
        &probe,
    )
    .landing;
    assert_eq!(out, BranchPrState::NoPr);
    assert!(
        !probe.calls().iter().any(|c| c.starts_with("head:")),
        "a complete index must answer the stem itself: {:?}",
        probe.calls()
    );
}