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
//! Tests binding `tm issue` to THIS repo's own lifecycle model.
//!
//! Why: the four `status:*` labels are mutually exclusive, and the only thing
//! that made that true was an agent remembering to pass `--add-label` and
//! `--remove-label` in one `gh issue edit`. These tests pin the repo-root
//! `issue-state.yaml` to the exact edge set CLAUDE.md documents (an extra or a
//! missing edge FAILS), and prove the label swap reaches `gh` as ONE call.
//! What: [`project_model`] loads the real YAML; the `project_*` tests assert the
//! edge set, the single-call swap through a fake `gh` (no network), the
//! two-label refusal, and the evidence-required close.
//! Test: this IS the test module (classified test file: 3000-SLOC cap).

use std::cell::RefCell;

use super::config::{
    DEFAULT_MODEL_YAML, ModelSource, STATUS_LIFECYCLE_YAML, StateModel, builtin_for_target,
    describe_source,
};
use super::ops;
use super::state::{CurrentState, StateMachine};
use crate::commands::ticket::runner::{CommandOutput, CommandRunner};
use crate::commands::ticket::system::GhTicketSystem;
use trusty_mpm::core::trusty_tools_config::ResolvedTicketing;

/// Load + validate the repo-root `issue-state.yaml` — the file `tm issue`'s
/// CWD tier reads.
///
/// A deleted, renamed, unparseable, or invalid model fails every test in this
/// file rather than skipping them.
fn project_model() -> StateModel {
    let path = trusty_common::test_harness::test_repo_root()
        .expect("resolve the checkout")
        .join("issue-state.yaml");
    let yaml =
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    let model: StateModel = serde_yaml::from_str(&yaml).expect("repo-root issue-state.yaml parses");
    super::validate::validate_model(&model).expect("repo-root issue-state.yaml is valid");
    model
}

/// The lifecycle CLAUDE.md documents, as `(from, to)` pairs.
///
/// `open` and `closed` are label-less; the middle four are the mutually
/// exclusive `status:*` labels.
const EXPECTED_EDGES: &[(&str, &str)] = &[
    // Forward, one rung at a time.
    ("open", "status:in-progress"),
    ("status:in-progress", "status:coded"),
    ("status:coded", "status:merged"),
    ("status:merged", "status:tested"),
    ("status:tested", "closed"),
    // #7647: closing early — every one of these requires `--note`.
    ("status:coded", "closed"),
    ("status:merged", "closed"),
    ("status:in-progress", "closed"),
    ("open", "closed"),
    // Backward: live verification failed and a fix PR is open.
    ("status:merged", "status:coded"),
    // Release a claim, and reopen from anywhere.
    ("status:in-progress", "open"),
    ("status:coded", "open"),
    ("status:merged", "open"),
    ("status:tested", "open"),
    ("closed", "open"),
];

#[test]
fn project_model_declares_the_documented_states() {
    let m = project_model();
    let names: Vec<&str> = m.states.iter().map(|s| s.name.as_str()).collect();
    assert_eq!(
        names,
        vec![
            "open",
            "status:in-progress",
            "status:coded",
            "status:merged",
            "status:tested",
            "closed",
        ]
    );
    // `open` and `closed` are the absence of a label; the rest carry theirs.
    let sm = StateMachine::new(&m);
    assert_eq!(sm.state_label("open"), None);
    assert_eq!(sm.state_label("closed"), None);
    assert_eq!(sm.state_label("status:coded"), Some("status:coded"));
    assert!(sm.closes_issue("closed"));
    assert!(!sm.closes_issue("open"));
}

#[test]
fn project_model_declares_exactly_the_documented_edges() {
    let m = project_model();
    let mut actual: Vec<(&str, &str)> = m
        .transitions
        .iter()
        .map(|t| (t.from.as_deref().unwrap_or("null"), t.to.as_str()))
        .collect();
    let mut expected: Vec<(&str, &str)> = EXPECTED_EDGES.to_vec();
    actual.sort_unstable();
    expected.sort_unstable();
    // An EXTRA or a MISSING edge fails here, naming both sides.
    assert_eq!(
        actual, expected,
        "issue-state.yaml's edge set drifted from the lifecycle in CLAUDE.md"
    );
}

#[test]
fn project_model_rejects_skipping_a_rung() {
    let m = project_model();
    let sm = StateMachine::new(&m);
    // Every non-adjacent forward move is absent from the graph. `closed` is the
    // exception since #7647 — it is reachable from every open state, always
    // with evidence, so the skip rule is asserted on the labelled rungs only.
    assert!(!sm.transition_allowed(Some("open"), "status:coded"));
    assert!(!sm.transition_allowed(Some("open"), "status:merged"));
    assert!(!sm.transition_allowed(Some("status:in-progress"), "status:merged"));
    assert!(!sm.transition_allowed(Some("status:coded"), "status:tested"));
}

/// Owner ruling 2026-09-07: a merged issue whose live verification failed and
/// which drew a follow-up fix PR moves back to `status:coded`.
///
/// Before the edge existed, `tm issue transition 6914 status:coded` was refused
/// because the model declared only `status:merged -> status:tested` and
/// `status:merged -> open`. The forward and release edges are asserted here too,
/// so widening the model does not quietly cost `status:merged` its other moves.
#[test]
fn project_model_allows_merged_back_to_coded_for_a_followup_fix() {
    let m = project_model();
    let sm = StateMachine::new(&m);
    assert!(
        sm.transition_allowed(Some("status:merged"), "status:coded"),
        "a merged issue whose live verification failed must be codeable again"
    );
    assert!(sm.transition_allowed(Some("status:merged"), "status:tested"));
    assert!(sm.transition_allowed(Some("status:merged"), "open"));
    // The edge is one-directional per rung: nothing else gains a way back.
    assert!(!sm.transition_allowed(Some("status:tested"), "status:merged"));
    assert!(!sm.transition_allowed(Some("status:coded"), "status:in-progress"));
    let mut targets = sm.allowed_targets_from(Some("status:merged"));
    targets.sort_unstable();
    assert_eq!(
        targets,
        vec!["closed", "open", "status:coded", "status:tested"]
    );
}

#[test]
fn project_model_resolves_an_unlabelled_open_issue_as_open() {
    let m = project_model();
    let sm = StateMachine::new(&m);
    let labels = vec!["bug".to_string(), "P1".to_string()];
    assert_eq!(
        sm.resolve_current_state(&labels, true),
        CurrentState::One("open")
    );
}

// ---- injected `gh` (no network) --------------------------------------------

/// A scripted [`CommandRunner`] standing in for the `gh` binary.
///
/// Returns queued outputs in order and records every `(program, args)` so a
/// test can assert what reached `gh` — including that a label swap was ONE
/// invocation carrying both flags.
struct FakeGh {
    outputs: RefCell<Vec<CommandOutput>>,
    calls: RefCell<Vec<Vec<String>>>,
}

impl FakeGh {
    fn new(outputs: Vec<CommandOutput>) -> Self {
        Self {
            outputs: RefCell::new(outputs),
            calls: RefCell::new(Vec::new()),
        }
    }
    fn calls(&self) -> Vec<Vec<String>> {
        self.calls.borrow().clone()
    }
}

impl CommandRunner for FakeGh {
    fn run(&self, program: &str, args: &[&str]) -> anyhow::Result<CommandOutput> {
        let mut argv = vec![program.to_string()];
        argv.extend(args.iter().map(|a| (*a).to_string()));
        self.calls.borrow_mut().push(argv);
        let mut queued = self.outputs.borrow_mut();
        if queued.is_empty() {
            return Ok(ok_out(""));
        }
        Ok(queued.remove(0))
    }
}

fn ok_out(stdout: &str) -> CommandOutput {
    CommandOutput {
        success: true,
        stdout: stdout.to_string(),
        stderr: String::new(),
    }
}

/// The `gh issue view --json …` payload for an open issue carrying `labels`.
fn issue_json(number: u64, labels: &[&str]) -> String {
    let labels: Vec<String> = labels
        .iter()
        .map(|l| format!("{{\"name\":\"{l}\"}}"))
        .collect();
    format!(
        "{{\"number\":{number},\"title\":\"t\",\"body\":\"\",\"state\":\"OPEN\",\
         \"labels\":[{}],\"assignees\":[]}}",
        labels.join(",")
    )
}

#[test]
fn project_transition_coded_to_merged_is_one_gh_edit_with_both_flags() {
    let m = project_model();
    // 1: `gh issue view`; the rest default to a bare success.
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:coded"]))]);
    let sys = GhTicketSystem::new(gh);

    let report = ops::transition(&sys, &m, 1234, "status:merged", None).expect("transition");
    assert_eq!(report.from.as_deref(), Some("status:coded"));
    assert_eq!(report.to, "status:merged");

    let edits: Vec<Vec<String>> = sys
        .runner()
        .calls()
        .into_iter()
        .filter(|c| {
            c.get(1).map(String::as_str) == Some("issue")
                && c.get(2).map(String::as_str) == Some("edit")
        })
        .collect();
    assert_eq!(
        edits.len(),
        1,
        "the swap must be ONE gh issue edit: {edits:?}"
    );
    let edit = &edits[0];
    let pos = |flag: &str, value: &str| edit.windows(2).any(|w| w[0] == flag && w[1] == value);
    assert!(
        pos("--add-label", "status:merged"),
        "missing --add-label status:merged in {edit:?}"
    );
    assert!(
        pos("--remove-label", "status:coded"),
        "missing --remove-label status:coded in {edit:?}"
    );
    // No separate add/remove call could have left two labels visible.
    assert!(
        !sys.runner()
            .calls()
            .iter()
            .any(|c| c.get(2).map(String::as_str) == Some("close")),
        "merging does not close the issue"
    );
}

#[test]
fn project_transition_refuses_two_status_labels_and_names_repair() {
    let m = project_model();
    let gh = FakeGh::new(vec![ok_out(&issue_json(
        1234,
        &["status:coded", "status:merged"],
    ))]);
    let sys = GhTicketSystem::new(gh);

    let err = ops::transition(&sys, &m, 1234, "status:tested", None)
        .unwrap_err()
        .to_string();
    assert!(err.contains("multiple state labels"), "got: {err}");
    assert!(
        err.contains("tm issue repair 1234"),
        "must name the repair command, got: {err}"
    );
    // Nothing was mutated: the only gh call is the read.
    let calls = sys.runner().calls();
    assert_eq!(calls.len(), 1, "must not mutate on refusal: {calls:?}");
    assert_eq!(calls[0].get(2).map(String::as_str), Some("view"));
}

#[test]
fn project_repair_resolves_two_status_labels_to_the_later_one() {
    let m = project_model();
    let gh = FakeGh::new(vec![ok_out(&issue_json(
        1234,
        &["status:coded", "status:merged"],
    ))]);
    let sys = GhTicketSystem::new(gh);

    let kept = ops::repair(&sys, &m, 1234).expect("repair");
    assert_eq!(kept, "status:merged", "keeps the more advanced state");
    let removed: Vec<Vec<String>> = sys
        .runner()
        .calls()
        .into_iter()
        .filter(|c| c.iter().any(|a| a == "--remove-label"))
        .collect();
    assert_eq!(removed.len(), 1, "one removal: {removed:?}");
    assert!(
        removed[0].iter().any(|a| a == "status:coded"),
        "must remove the stale label, got {:?}",
        removed[0]
    );
}

#[test]
fn project_close_requires_evidence_and_then_closes() {
    let m = project_model();

    // Without --note the edge is refused before any mutation.
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:tested"]))]);
    let sys = GhTicketSystem::new(gh);
    let err = ops::transition(&sys, &m, 1234, "closed", None)
        .unwrap_err()
        .to_string();
    assert!(err.contains("requires evidence"), "got: {err}");
    assert!(err.contains("--note"), "got: {err}");
    assert_eq!(sys.runner().calls().len(), 1, "read only");

    // With --note it drops the label, comments the evidence, then closes.
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:tested"]))]);
    let sys = GhTicketSystem::new(gh);
    ops::transition(&sys, &m, 1234, "closed", Some("tm 0.9.1 live run: OK"))
        .expect("transition with evidence");
    let verbs: Vec<String> = sys
        .runner()
        .calls()
        .iter()
        .filter_map(|c| c.get(2).cloned())
        .collect();
    assert_eq!(
        verbs,
        vec!["view", "edit", "comment", "close"],
        "got {verbs:?}"
    );
    let comment = sys
        .runner()
        .calls()
        .into_iter()
        .find(|c| c.get(2).map(String::as_str) == Some("comment"))
        .expect("comment call");
    assert!(
        comment.iter().any(|a| a.contains("tm 0.9.1 live run: OK")),
        "the evidence must reach the issue, got {comment:?}"
    );
}

/// #7647: `closed` is reachable from every open state, and never without
/// evidence.
///
/// Before the edges existed, `tm issue transition <n> closed` was refused from
/// anything but `status:tested`, so CLAUDE.md's rung 1-3 close-at-merge rule and
/// every administrative fold fell back to a bare `gh issue close` — no audit
/// comment, and the stale `status:*` label left on the issue.
#[test]
fn project_close_reaches_every_open_state_and_always_needs_a_note_7647() {
    let m = project_model();
    let sm = StateMachine::new(&m);
    for from in [
        "open",
        "status:in-progress",
        "status:coded",
        "status:merged",
        "status:tested",
    ] {
        assert!(
            sm.transition_allowed(Some(from), "closed"),
            "{from} → closed must be a legal edge"
        );
        assert!(
            sm.requires_note(Some(from), "closed"),
            "{from} → closed must refuse without --note"
        );
    }
}

/// #7647: the rung 1-3 close-at-merge path, end to end through a fake `gh`.
///
/// The note is the PR and squash SHA rather than a live run, but it is still
/// mandatory, and the close still drops the state label and comments first.
#[test]
fn project_close_from_coded_refuses_without_evidence_then_closes_7647() {
    let m = project_model();

    // No --note: refused before any mutation.
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:coded"]))]);
    let sys = GhTicketSystem::new(gh);
    let err = ops::transition(&sys, &m, 1234, "closed", None)
        .unwrap_err()
        .to_string();
    assert!(err.contains("requires evidence"), "got: {err}");
    assert_eq!(sys.runner().calls().len(), 1, "read only");

    // With --note: label dropped, evidence commented, issue closed.
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:coded"]))]);
    let sys = GhTicketSystem::new(gh);
    ops::transition(&sys, &m, 1234, "closed", Some("PR #8050 squash abc1234"))
        .expect("close at merge with evidence");
    let verbs: Vec<String> = sys
        .runner()
        .calls()
        .iter()
        .filter_map(|c| c.get(2).cloned())
        .collect();
    assert_eq!(
        verbs,
        vec!["view", "edit", "comment", "close"],
        "got {verbs:?}"
    );
    let edit = sys
        .runner()
        .calls()
        .into_iter()
        .find(|c| c.get(2).map(String::as_str) == Some("edit"))
        .expect("edit call");
    assert!(
        edit.windows(2)
            .any(|w| w[0] == "--remove-label" && w[1] == "status:coded"),
        "the stale lifecycle label must come off, got {edit:?}"
    );
}

#[test]
fn project_release_a_claim_removes_the_label_without_closing() {
    let m = project_model();
    let gh = FakeGh::new(vec![ok_out(&issue_json(1234, &["status:in-progress"]))]);
    let sys = GhTicketSystem::new(gh);

    let report = ops::transition(&sys, &m, 1234, "open", Some("claim stale")).expect("release");
    assert_eq!(report.to, "open");
    let verbs: Vec<String> = sys
        .runner()
        .calls()
        .iter()
        .filter_map(|c| c.get(2).cloned())
        .collect();
    assert_eq!(verbs, vec!["view", "edit", "comment"], "got {verbs:?}");
    let edit = sys
        .runner()
        .calls()
        .into_iter()
        .find(|c| c.get(2).map(String::as_str) == Some("edit"))
        .expect("edit call");
    assert!(
        edit.windows(2)
            .any(|w| w[0] == "--remove-label" && w[1] == "status:in-progress"),
        "got {edit:?}"
    );
    assert!(
        !edit.iter().any(|a| a == "--add-label"),
        "`open` has no label to add, got {edit:?}"
    );
}

#[test]
fn project_seed_labels_skips_the_labelless_states() {
    let m = project_model();
    let gh = FakeGh::new(vec![ok_out("[]")]);
    let sys = GhTicketSystem::new(gh);
    let report = ops::seed_labels(&sys, &m, &ResolvedTicketing::default(), None, true, &[])
        .expect("seed dry-run");
    assert_eq!(
        report.created,
        vec![
            "status:in-progress".to_string(),
            "status:coded".to_string(),
            "status:merged".to_string(),
            "status:tested".to_string(),
            // #6914: the framework's own labels seed alongside the model's.
            "trusty-mpm".to_string(),
        ],
        "only the four labelled states, plus the policy set, are seeded"
    );
    assert!(
        report.workstream_skipped,
        "no session name was supplied, so the ws/ label is skipped and said so"
    );
}

/// #6914: against THIS repo's real `issue-state.yaml`, one `seed-labels` run
/// creates every label the harness applies — the four lifecycle labels, the
/// `trusty-mpm` convention label, and `ws/<session>`.
#[test]
fn project_seed_labels_covers_the_whole_harness_label_set() {
    let m = project_model();
    let gh = FakeGh::new(vec![ok_out("[]")]);
    let sys = GhTicketSystem::new(gh);
    let report = ops::seed_labels(
        &sys,
        &m,
        &ResolvedTicketing::default(),
        Some("tm-tcode-01"),
        true,
        &[],
    )
    .expect("seed dry-run");
    assert_eq!(
        report.created,
        vec![
            "status:in-progress".to_string(),
            "status:coded".to_string(),
            "status:merged".to_string(),
            "status:tested".to_string(),
            "trusty-mpm".to_string(),
            "ws/tm-tcode-01".to_string(),
        ]
    );
    assert!(!report.workstream_skipped);
}

// ---- #8609: the built-in model knows the `status:*` lifecycle --------------

/// The loader's answer when no `issue-state.yaml` is found: the Unicorn
/// Factory default, tagged as the embedded default.
fn embedded_default() -> (StateModel, ModelSource) {
    let model: StateModel = serde_yaml::from_str(DEFAULT_MODEL_YAML).expect("default parses");
    let source = ModelSource::EmbeddedDefault {
        searched_from: std::path::PathBuf::from("/repo"),
    };
    (model, source)
}

/// Why (#8609): the embedded lifecycle is a copy of the repo-root model, and a
/// copy that drifts would give a repo without a model a different lifecycle
/// from the one TICKETING.md documents.
#[test]
fn status_lifecycle_matches_the_repo_model_8609() {
    let embedded: StateModel =
        serde_yaml::from_str(STATUS_LIFECYCLE_YAML).expect("embedded lifecycle parses");
    assert_eq!(embedded, project_model());
}

/// Why (#8609): apex-companion has no `issue-state.yaml`, and
/// `tm issue transition 1019 status:in-progress` was rejected with the Unicorn
/// Factory's state list. The built-in model must take that target, and the
/// transition must then reach `gh` as the documented label add.
#[test]
fn builtin_for_target_selects_the_status_lifecycle_8609() {
    let (model, source) =
        builtin_for_target(embedded_default(), "status:in-progress").expect("lifecycle target");
    assert!(
        matches!(source, ModelSource::EmbeddedStatusLifecycle { .. }),
        "{source:?}"
    );
    assert!(describe_source(&source).contains("`status:*` lifecycle"));

    let gh = FakeGh::new(vec![ok_out(&issue_json(1019, &["bug"]))]);
    let sys = GhTicketSystem::new(gh);
    let report = ops::transition(&sys, &model, 1019, "status:in-progress", None)
        .expect("open → status:in-progress is a lifecycle edge");
    assert_eq!(report.from.as_deref(), Some("open"));
    assert!(
        sys.runner().calls().iter().any(|c| c
            .windows(2)
            .any(|w| w[0] == "--add-label" && w[1] == "status:in-progress")),
        "{:?}",
        sys.runner().calls()
    );

    // Closing still demands evidence under the built-in lifecycle.
    let (model, _) = builtin_for_target(embedded_default(), "closed").expect("closed");
    let gh = FakeGh::new(vec![ok_out(&issue_json(1019, &["status:tested"]))]);
    let sys = GhTicketSystem::new(gh);
    let err = ops::transition(&sys, &model, 1019, "closed", None)
        .expect_err("no --note")
        .to_string();
    assert!(err.contains("requires evidence"), "{err}");
}

/// Why (#8609): the switch must not reach past its case — a model read from a
/// file, a Unicorn Factory target, and a name neither model knows all keep the
/// loader's answer, so the unknown-state error still names the default.
#[test]
fn builtin_for_target_keeps_a_file_model_and_unicorn_targets_8609() {
    for to in ["approved", "no-such-state"] {
        let (_, source) = builtin_for_target(embedded_default(), to).expect(to);
        assert!(
            matches!(source, ModelSource::EmbeddedDefault { .. }),
            "{to}: {source:?}"
        );
    }
    let file = ModelSource::File(std::path::PathBuf::from("/repo/issue-state.yaml"));
    let (_, source) = builtin_for_target((embedded_default().0, file.clone()), "status:coded")
        .expect("file model");
    assert_eq!(source, file);
}