magi-cli 0.264.3

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
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
//! Explicit recovery of a task's public implementation, independent of historical candidates.

use std::path::Path;

use anyhow::{Context, Result, ensure};
use serde::{Deserialize, Serialize};

use crate::{
    config::{Config, MergeMode},
    git, land,
};

/// Explicit purpose of an existing-PR recovery; never inferred from task prose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum Disposition {
    /// Validate, publish to the selected PR and request fresh owner-approved landing.
    Land,
    /// Finish after local review, without public delivery.
    Review,
}

/// Inputs of the single configuration load used to start a recovery.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigEvidence {
    /// Ordered configuration inputs; remote cache paths include the immutable source commit.
    pub layers: Vec<std::path::PathBuf>,
    /// Task options applied after loading the layers.
    pub overrides: Option<crate::queue::RunOverrides>,
    /// Daemon merge override, only when this task inherits daemon options.
    pub daemon_merge: Option<String>,
}

/// Durable operator selection. Only the recovery command creates this record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Selection {
    /// Existing pull request in this repository.
    pub url: String,
    /// Task-scoped public branch.
    pub branch: String,
    /// Initial public publication lease, independent of the implementation source.
    pub head: String,
    /// Full immutable source commit; older selections used the public lease.
    #[serde(default)]
    pub source_head: Option<String>,
    /// Historical run explicitly selected to prove a launcher rebase.
    #[serde(default)]
    pub source_run: Option<String>,
    /// Immutable proof, recomputed before starting or resuming work.
    #[serde(default)]
    pub source_proof: Option<Box<SourceProof>>,
    /// Missing on old records: requires an explicit new selection before work.
    #[serde(default)]
    pub disposition: Option<Disposition>,
    /// Criteria the operator approved, retained without rewriting them.
    pub instruction: String,
    /// Approval generation: a later selection does not resume an earlier run.
    pub approved_at: jiff::Timestamp,
}

mod lineage;
pub use lineage::SourceProof;

const RETAIN_SOURCES: &str = "retain-recovery-sources";

/// Preserve every historical run's source artifacts before releasing a recovery task.
/// A sidecar survives stale run-state saves and applies even to older run schemas.
pub fn retain_sources(task: &crate::queue::Task, home: &Path) -> Result<()> {
    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
        ensure!(
            crate::run::is_run_id(id),
            "invalid historical run id; refusing source retention"
        );
        let dir = home.join("runs").join(id);
        ensure!(
            dir.is_dir(),
            "historical run {id} is missing; cannot retain its sources"
        );
        std::fs::write(dir.join(RETAIN_SOURCES), &task.id)
            .with_context(|| format!("retaining sources of historical run {id}"))?;
    }
    Ok(())
}

/// Return the retention reason rather than silently treating fold as successful.
pub(crate) fn source_retention_reason(home: &Path, state: &crate::run::RunState) -> Option<String> {
    if explicit_sources_retained(home, &state.id) {
        return Some("explicitly retained recovery source".into());
    }
    // A confirmed merge admits fold preflight even while the queue is held.
    // fold_run must still prove each deletion target under its ownership and
    // output locks. Ready/Failed/Superseded and PR creation alone do not qualify.
    if state.status == crate::run::RunStatus::Merged
        && state.merge.as_ref().is_some_and(|merged| merged.ok)
    {
        return None;
    }
    crate::queue::Queue::at(home.join("queue"))
        .list()
        .iter()
        // Queue completion does not prove that every historical candidate
        // landed. In particular, Superseded and Failed-without-tally runs
        // may still own independent implementations. Keep those sources
        // until recovery transfers them or confirmed-merge preflight captures
        // durable source evidence; Done is not deletion authority.
        .find(|task| task.runs.contains(&state.id))
        .map(|task| {
            format!(
                "source of task {}; inspect recovery lineage before folding",
                task.id
            )
        })
}

pub(crate) fn explicit_sources_retained(home: &Path, id: &str) -> bool {
    home.join("runs")
        .join(id)
        .join(RETAIN_SOURCES)
        .try_exists()
        .unwrap_or(true)
}

impl Selection {
    /// Immutable implementation commit, distinct from the public update lease.
    pub fn source(&self) -> &str {
        self.source_head.as_deref().unwrap_or(&self.head)
    }

    /// Reconcile only the delivery controls; preserve all other resolved settings.
    pub fn configure(&self, config: &mut Config) -> Result<()> {
        match self.disposition {
            Some(Disposition::Land) => {
                ensure!(
                    config.graph.reviewers > 0 && config.graph.review_rounds > 0,
                    "delivery requires at least one reviewer and review round"
                );
                ensure!(
                    !config.verify.gate.is_empty()
                        && config.verify.gate.iter().all(|s| !s.trim().is_empty()),
                    "delivery requires nonempty verify.gate commands; configure the repository's documented gate in a machine/repository layer or recover-pr --config <complete-config>"
                );
                ensure!(
                    !config.verify.e2e.is_empty()
                        && config.verify.e2e.iter().all(|s| !s.trim().is_empty()),
                    "delivery requires nonempty verify.e2e commands; configure the repository's required real-machine checks before recover-pr --disposition land"
                );
                config.merge.mode = MergeMode::Pr;
                config.graph.land = true;
                config.graph.land_approval = true;
            }
            Some(Disposition::Review) => {
                config.merge.mode = MergeMode::None;
                config.graph.land = false;
            }
            None => anyhow::bail!(
                "recovery disposition is missing; select the public head again with recover-pr --disposition land or --disposition review (and --source-head <full-SHA> to preserve a reviewed fix)"
            ),
        }
        Ok(())
    }

    /// Prove the adopted fix contains the selected public implementation.
    pub async fn verify_source(&self, repo: &Path) -> Result<()> {
        if self.source_proof.is_some() {
            self.verify_source_under(repo, &crate::run::home()).await
        } else {
            self.verify_source_under(repo, Path::new("")).await
        }
    }

    async fn verify_source_under(&self, repo: &Path, home: &Path) -> Result<()> {
        let source = git::rev_parse(repo, &format!("{}^{{commit}}", self.source())).await?;
        ensure!(
            source == self.source(),
            "source-head must resolve to its full commit SHA"
        );
        if let Some(proof) = &self.source_proof {
            // Historical state is large; keep replay out of the caller's future storage.
            let actual = Box::pin(lineage::prove(self, repo, home, &proof.current_base)).await?;
            ensure!(
                &actual == proof.as_ref(),
                "saved source proof changed; select the source again"
            );
        } else {
            ensure!(
                git::is_ancestor(repo, &self.head, &source).await,
                "source-head does not preserve the selected public implementation by ancestry; supply --source-run <retained-run-id> for a recorded launcher rebase"
            );
            ensure!(
                self.source_run.is_none(),
                "source-run requires a saved source proof; select again"
            );
        }
        Ok(())
    }

    /// Select and persist evidence without changing the implementation or public lease.
    pub async fn prepare_source(
        &mut self,
        repo: &Path,
        home: &Path,
        current_base: &str,
    ) -> Result<()> {
        ensure!(
            self.source_proof.is_none(),
            "source proof is already selected; refusing to replace saved evidence"
        );
        if self.source_run.is_some() {
            self.source_proof = Some(Box::new(
                Box::pin(lineage::prove(self, repo, home, current_base)).await?,
            ));
            Ok(())
        } else {
            self.verify_source(repo).await
        }
    }

    /// Confirm initial-assignment task identity and immutable criteria.
    pub fn check_task(&self, task: &str, instruction: &str) -> Result<()> {
        self.check_task_assignment(task, instruction, 0)
    }

    /// Confirm the exact repository assignment as well as task and criteria.
    pub fn check_task_assignment(
        &self,
        task: &str,
        instruction: &str,
        assignment: usize,
    ) -> Result<()> {
        ensure!(
            self.branch == crate::run::task_pr_branch_name(task, assignment),
            "recovery head belongs to another task or repository assignment"
        );
        ensure!(
            self.instruction == instruction,
            "recovery criteria changed; select the public head again"
        );
        ensure!(
            [self.head.as_str(), self.source()]
                .iter()
                .all(|sha| sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit())),
            "recovery requires a full commit SHA"
        );
        Ok(())
    }

    /// Read-only forge validation plus fetch; no local branch is moved or pushed.
    pub async fn verify(&self, repo: &Path, remote: &str, base: &str, lease: &str) -> Result<()> {
        let pr_repo = land::slug_of_pr_url(&self.url).context("invalid recovery PR URL")?;
        for args in [
            vec!["remote", "get-url", "--all", remote],
            vec!["remote", "get-url", "--push", "--all", remote],
        ] {
            let urls = git::git(repo, &args).await?;
            ensure!(
                !urls.trim().is_empty(),
                "recovery remote has no repository URL"
            );
            for url in urls.lines() {
                let remote_repo =
                    remote_slug(url).context("cannot prove recovery remote repository identity")?;
                land::ensure_same_repo(&remote_repo, &pr_repo)?;
            }
        }
        self.verify_forge_with(Path::new("gh"), repo, base, lease)
            .await?;
        let fetched = git::fetch(repo, remote, &self.branch).await?;
        ensure!(
            fetched.ok(),
            "fetch selected public head failed: {}",
            fetched.stderr
        );
        let fetched_head =
            git::rev_parse(repo, &format!("refs/remotes/{remote}/{}", self.branch)).await?;
        ensure!(
            fetched_head == lease,
            "public head moved; select and approve its new head before recovery"
        );
        ensure!(
            git::remote_head(repo, remote, &self.branch)
                .await?
                .as_deref()
                == Some(lease),
            "public head lease changed during recovery"
        );
        Ok(())
    }

    async fn verify_forge_with(
        &self,
        program: &Path,
        repo: &Path,
        base: &str,
        lease: &str,
    ) -> Result<()> {
        let found = land::find_open_pr_with(program, repo, &self.branch, base).await?;
        ensure!(
            matches!(found, land::OpenPr::One { ref url, .. } if url == &self.url),
            "selected PR is not the unique open task PR in this repository"
        );
        let view = land::gh_with(
            program,
            repo,
            &[
                "pr".into(),
                "view".into(),
                self.url.clone(),
                "--json".into(),
                "headRefName,headRefOid,baseRefName,state,isCrossRepository".into(),
            ],
        )
        .await?;
        ensure!(view.ok, "could not verify selected PR: {}", view.combined());
        validate_view(&view.stdout, &self.branch, base, lease)
    }
}

// Require a recognizable forge URL rather than guessing through local paths or SSH aliases.
fn remote_slug(url: &str) -> Option<String> {
    let url = url
        .trim()
        .trim_end_matches('/')
        .strip_suffix(".git")
        .unwrap_or(url.trim().trim_end_matches('/'));
    let (host, path) = if let Some(rest) = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))
        .or_else(|| url.strip_prefix("ssh://"))
    {
        let (authority, path) = rest.split_once('/')?;
        (authority.rsplit('@').next()?, path)
    } else {
        let (authority, path) = url.split_once(':')?;
        let (_, host) = authority.split_once('@')?;
        (host, path)
    };
    let mut parts = path.split('/');
    let owner = parts.next()?;
    let repo = parts.next()?;
    if host.is_empty() || owner.is_empty() || repo.is_empty() || parts.next().is_some() {
        return None;
    }
    Some(format!("{host}/{owner}/{repo}"))
}

fn validate_view(raw: &str, branch: &str, base: &str, lease: &str) -> Result<()> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct View {
        head_ref_name: String,
        head_ref_oid: String,
        base_ref_name: String,
        state: String,
        is_cross_repository: bool,
    }
    let view: View = serde_json::from_str(raw).context("selected public head metadata")?;
    ensure!(
        view.state == "OPEN"
            && !view.is_cross_repository
            && view.head_ref_name == branch
            && view.base_ref_name == base,
        "selected PR ownership or base changed"
    );
    ensure!(
        view.head_ref_oid == lease,
        "selected public head moved; refusing recovery"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn recovery_uses_resolved_layers_and_preserves_unrelated_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let machine = dir.path().join("machine.toml");
        let repo = dir.path().join("repository.toml");
        std::fs::write(&machine, "[verify]\ngate = ['documented gate']\ne2e = ['real checks']\n[graph]\nland = false\nland_approval = false\n").unwrap();
        std::fs::write(&repo, "[merge]\nmode = 'none'\nbase = 'trunk'\n").unwrap();
        let mut config = Config::load_layers(&[machine, repo]).unwrap();
        let overrides = crate::queue::RunOverrides {
            merge: Some("none".into()),
            reviewers: Some(2),
            ..Default::default()
        };
        overrides.apply(&mut config);
        let mut selection = Selection {
            url: "url".into(),
            branch: "magi/task-t".into(),
            head: "a".repeat(40),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Land),
            instruction: "criteria".into(),
            approved_at: jiff::Timestamp::now(),
        };
        selection.configure(&mut config).unwrap();
        assert_eq!(config.merge.mode, MergeMode::Pr);
        assert_eq!(config.graph.reviewers, 2);
        assert_eq!(config.merge.base.as_deref(), Some("trunk"));
        assert_eq!(config.verify.gate, ["documented gate"]);
        assert_eq!(config.verify.e2e, ["real checks"]);
        assert!(config.graph.land && config.graph.land_approval);
        let explicit = dir.path().join("explicit.toml");
        std::fs::write(&explicit, "[merge]\nbase = 'other'\n").unwrap();
        let (mut replacement, paths) = Config::discover(dir.path(), Some(&explicit)).unwrap();
        assert_eq!(paths, [explicit]);
        assert!(
            selection
                .configure(&mut replacement)
                .unwrap_err()
                .to_string()
                .contains("verify.gate")
        );
        replacement.verify.gate = vec![" ".into()];
        assert!(selection.configure(&mut replacement).is_err());
        selection.disposition = Some(Disposition::Review);
        selection.configure(&mut replacement).unwrap();
        assert_eq!(replacement.merge.mode, MergeMode::None);
        assert!(!replacement.graph.land);
    }

    #[test]
    fn selected_source_requires_the_same_fetch_and_push_repository() {
        for remote in [
            "https://example.test/team/project.git",
            "git@example.test:team/project.git",
            "ssh://git@example.test/team/project.git",
        ] {
            assert_eq!(
                remote_slug(remote).as_deref(),
                Some("example.test/team/project")
            );
        }
        assert!(remote_slug("/tmp/another.git").is_none());
        assert!(
            land::ensure_same_repo(
                &remote_slug("git@example.test:team/other.git").unwrap(),
                "example.test/team/project"
            )
            .is_err()
        );
        assert!(
            land::ensure_same_repo(
                &remote_slug("git@other.test:team/project.git").unwrap(),
                "example.test/team/project"
            )
            .is_err()
        );
    }

    #[test]
    fn selected_head_refuses_moved_or_foreign_public_heads() {
        let raw = r#"{"headRefName":"magi/task-t","headRefOid":"aaa","baseRefName":"main","state":"OPEN","isCrossRepository":false}"#;
        assert!(validate_view(raw, "magi/task-t", "main", "aaa").is_ok());
        assert!(validate_view(raw, "magi/task-t", "main", "bbb").is_err());
        assert!(validate_view(raw, "magi/task-other", "main", "aaa").is_err());
        assert!(validate_view(raw, "magi/task-t", "other", "aaa").is_err());
        assert!(
            validate_view(&raw.replace("false", "true"), "magi/task-t", "main", "aaa").is_err()
        );
        assert!(
            validate_view(&raw.replace("OPEN", "CLOSED"), "magi/task-t", "main", "aaa").is_err()
        );
    }

    #[test]
    fn selected_head_is_bound_to_authored_criteria_and_task() {
        let selected = Selection {
            url: "url".into(),
            branch: "magi/task-t".into(),
            head: "a".repeat(40),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Review),
            instruction: "approved".into(),
            approved_at: jiff::Timestamp::now(),
        };
        assert!(selected.check_task("t", "approved").is_ok());
        assert!(
            selected
                .check_task("t", "prose mentioning another candidate")
                .is_err()
        );
        assert!(selected.check_task("other", "approved").is_err());
        assert!(selected.check_task_assignment("t", "approved", 2).is_err());
        let mut reassigned = selected;
        reassigned.branch = "magi/task-t-assignment-2".into();
        assert!(reassigned.check_task_assignment("t", "approved", 2).is_ok());
        assert!(
            reassigned
                .check_task_assignment("t", "approved", 1)
                .is_err()
        );
        assert!(reassigned.check_task("t", "approved").is_err());
    }

    fn fake_recovery_gh(
        dir: &Path,
        name: &str,
        list: (&str, &str, i32),
        view: (&str, &str, i32),
    ) -> std::path::PathBuf {
        let list_out = dir.join(format!("{name}-list.stdout"));
        let list_err = dir.join(format!("{name}-list.stderr"));
        let view_out = dir.join(format!("{name}-view.stdout"));
        let view_err = dir.join(format!("{name}-view.stderr"));
        std::fs::write(&list_out, list.0).unwrap();
        std::fs::write(&list_err, list.1).unwrap();
        std::fs::write(&view_out, view.0).unwrap();
        std::fs::write(&view_err, view.1).unwrap();
        #[cfg(windows)]
        {
            let script = dir.join(format!("{name}.cmd"));
            let mut body = String::from("@echo off\r\n");
            body.push_str("if \"%~1 %~2\"==\"pr list\" (\r\n");
            if !list.0.is_empty() {
                body.push_str(&format!("  type \"{}\"\r\n", list_out.display()));
            }
            if !list.1.is_empty() {
                body.push_str(&format!("  type \"{}\" 1>&2\r\n", list_err.display()));
            }
            body.push_str(&format!("  exit /b {}\r\n)\r\n", list.2));
            body.push_str("if \"%~1 %~2\"==\"pr view\" (\r\n");
            if !view.0.is_empty() {
                body.push_str(&format!("  type \"{}\"\r\n", view_out.display()));
            }
            if !view.1.is_empty() {
                body.push_str(&format!("  type \"{}\" 1>&2\r\n", view_err.display()));
            }
            body.push_str(&format!("  exit /b {}\r\n)\r\n", view.2));
            body.push_str("exit /b 1\r\n");
            std::fs::write(&script, body).unwrap();
            script
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
            let script = dir.join(name);
            let emit = |out: &Path, err: &Path, has_out: bool, has_err: bool, code: i32| {
                let mut s = String::new();
                if has_out {
                    s.push_str(&format!("cat {}; ", quote(out)));
                }
                if has_err {
                    s.push_str(&format!("cat {} >&2; ", quote(err)));
                }
                s.push_str(&format!("exit {code}"));
                s
            };
            let body = format!(
                "#!/bin/sh\ncase \"$1 $2\" in\n  'pr list') {} ;;\n  'pr view') {} ;;\n  *) exit 1 ;;\nesac\n",
                emit(
                    &list_out,
                    &list_err,
                    !list.0.is_empty(),
                    !list.1.is_empty(),
                    list.2
                ),
                emit(
                    &view_out,
                    &view_err,
                    !view.0.is_empty(),
                    !view.1.is_empty(),
                    view.2
                ),
            );
            let status = std::process::Command::new("sh")
                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
                .arg(&script)
                .arg(&body)
                .status()
                .unwrap();
            assert!(status.success());
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
            script
        }
    }

    #[tokio::test]
    async fn verify_forge_separates_json_stdout_from_stderr_hints_and_keeps_strict_guards() {
        let tmp = tempfile::tempdir().unwrap();
        let sha = "a".repeat(40);
        let selected = Selection {
            url: "https://github.com/example/repo/pull/1".into(),
            branch: "magi/task-t".into(),
            head: sha.clone(),
            source_head: None,
            source_run: None,
            source_proof: None,
            disposition: Some(Disposition::Land),
            instruction: "approved".into(),
            approved_at: jiff::Timestamp::now(),
        };
        let hint = "To listen to events, run: gh pr view --web\n";
        let list_json = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: recovered","baseRefName":"main","isCrossRepository":false}]"#;
        let view_json = format!(
            r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
        );

        // Appending the stderr hint to stdout (pre-fix bug) still fails strictly.
        let concatenated = format!("{view_json}\n{hint}");
        let strict_err = validate_view(&concatenated, &selected.branch, "main", &sha).unwrap_err();
        assert!(
            format!("{strict_err:#}").contains("trailing characters"),
            "{strict_err:#}"
        );

        // Valid JSON stdout + nonempty stderr hint on both pr list and pr view succeeds.
        let ok_gh = fake_recovery_gh(
            tmp.path(),
            "ok",
            (&format!("{list_json}\n"), hint, 0),
            (&format!("{view_json}\n"), hint, 0),
        );
        selected
            .verify_forge_with(&ok_gh, tmp.path(), "main", &sha)
            .await
            .unwrap();

        // Malformed stdout still fails strict parsing.
        let malformed_gh = fake_recovery_gh(
            tmp.path(),
            "malformed",
            (&format!("{list_json}\n"), "", 0),
            (&format!("{view_json}\ntrailing text\n"), "", 0),
        );
        let err = selected
            .verify_forge_with(&malformed_gh, tmp.path(), "main", &sha)
            .await
            .unwrap_err();
        assert!(
            format!("{err:#}").contains("trailing characters"),
            "{err:#}"
        );

        // Empty stdout + nonempty stderr on exit 0 never falls back to stderr.
        let empty_gh = fake_recovery_gh(
            tmp.path(),
            "empty",
            (&format!("{list_json}\n"), "", 0),
            ("", hint, 0),
        );
        assert!(
            selected
                .verify_forge_with(&empty_gh, tmp.path(), "main", &sha)
                .await
                .is_err()
        );

        // Failed gh invocation with valid JSON stdout preserves stderr diagnostics.
        let failed_gh = fake_recovery_gh(
            tmp.path(),
            "failed",
            (&format!("{list_json}\n"), "", 0),
            (
                &format!("{view_json}\n"),
                "gh: authentication required\n",
                1,
            ),
        );
        let err = selected
            .verify_forge_with(&failed_gh, tmp.path(), "main", &sha)
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("authentication required"), "{err}");

        // Ownership and head guards remain strict when stderr hints are present.
        assert!(
            selected
                .verify_forge_with(&ok_gh, tmp.path(), "main", &"b".repeat(40))
                .await
                .unwrap_err()
                .to_string()
                .contains("moved")
        );
        let wrong_branch_gh = fake_recovery_gh(
            tmp.path(),
            "wrong-branch",
            (&format!("{list_json}\n"), hint, 0),
            (
                &format!(
                    r#"{{"headRefName":"magi/task-other","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":false}}"#
                ),
                hint,
                0,
            ),
        );
        assert!(
            selected
                .verify_forge_with(&wrong_branch_gh, tmp.path(), "main", &sha)
                .await
                .unwrap_err()
                .to_string()
                .contains("ownership or base changed")
        );
        let fork_gh = fake_recovery_gh(
            tmp.path(),
            "fork",
            (&format!("{list_json}\n"), hint, 0),
            (
                &format!(
                    r#"{{"headRefName":"magi/task-t","headRefOid":"{sha}","baseRefName":"main","state":"OPEN","isCrossRepository":true}}"#
                ),
                hint,
                0,
            ),
        );
        assert!(
            selected
                .verify_forge_with(&fork_gh, tmp.path(), "main", &sha)
                .await
                .unwrap_err()
                .to_string()
                .contains("ownership or base changed")
        );
    }
}