car-server-core 0.55.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
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
//! The self-healing loop, end to end, against a real coder session.
//!
//! Every other test of this feature stops at a seam. This one runs a **real**
//! `coder.start`: a real git worktree, a real derived outcome contract, the
//! real session loop, the contract evaluated by executing it, the real
//! [`LiveCoderRunner`] publishing a real branch — then the real
//! `heal_select` → `heal_claims` → `heal_gate` → `tick` composition on top.
//!
//! ## Why it exists
//!
//! The loop had 107 unit tests, all against a fake [`TickIo`]. A fake coder
//! returns the shape its author expected, and this one did: it returned a
//! branch name. The real one could not. `session.result_branch` is written in
//! exactly one place in the crate — inside `approve_merge_session`, the
//! function [`LiveCoderRunner`] deliberately refuses to call — so every green
//! session reached `heal_runner`'s `ok_or("session reached approval with no
//! branch")` and failed the item. **The loop as committed could never have
//! opened a pull request.** Nothing that mocks the coder can find that.
//!
//! ## What is real here and what is not
//!
//! Real: the git repository, the worktree, contract derivation and evaluation,
//! branch publication, the diff the panel reads, and every decision in
//! `heal_select` / `heal_gate` / `heal_tick`.
//!
//! Scripted: the model's turns, through the same [`TurnGenerator`] seam
//! `bench.rs` uses. That is what makes the run deterministic and lets it pass
//! in CI with no credentials and no network.
//!
//! Seamed: the two GitHub writes. `open_pr` and `comment` are the only methods
//! this file supplies itself, and both record rather than call.
//!
//! ## In-crate, not `tests/`
//!
//! [`SessionSeed::from_trusted`] is `pub(in crate::coder)` because the type's
//! whole purpose is to prove clearance happened, and its doc names tests as one
//! of the two legal minters. An integration test compiles as a separate crate
//! and cannot reach it. Widening the visibility to place this file in `tests/`
//! would trade the invariant for a directory.

use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use car_inference::{GenerateRequest, InferenceResult};
use serde_json::{json, Value};

use super::heal_claims::ClaimStore;
use super::heal_gate::GateOutcome;
use super::heal_intake::{Checkout, HealTarget, RawPullRequest};
use super::heal_live::CoderRunner;
use super::heal_runner::{delivery_branch, LiveCoderRunner, Reviewer};
use super::heal_select::{Candidate, CandidateKind};
use super::heal_tick::{
    tick, Attempt, DeliverRefusal, Intent, NoClaimSink, RunFailure, TickIo, TickOutcome,
};
use super::merge::{
    CiCheck, CiState, CiSummary, GhError, GitHubApi, PrDeliveryOutcome, PrRecord, PrState,
};
use super::native_loop::TurnGenerator;
use super::provenance::{ProvenanceTier, SessionSeed};
use super::router::EngineChoice;
use super::session::CoderState;
use crate::session::ServerState;

// --- the model seam, the same shape `bench.rs` scripts ----------------------

struct Script {
    turns: Vec<InferenceResult>,
    cursor: AtomicUsize,
}

fn turn(text: &str, tool_calls: Value) -> InferenceResult {
    turn_as("scripted", text, tool_calls)
}

/// A turn reporting a specific `model_used`, which is what the native loop
/// journals as the authoring model.
fn turn_as(model: &str, text: &str, tool_calls: Value) -> InferenceResult {
    serde_json::from_value(json!({
        "text": text,
        "tool_calls": tool_calls,
        "trace_id": "heal-e2e",
        "model_used": model,
        "latency_ms": 0,
    }))
    .expect("scripted InferenceResult shape")
}

#[async_trait::async_trait]
impl TurnGenerator for Script {
    async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
        let i = self.cursor.fetch_add(1, Ordering::SeqCst);
        self.turns
            .get(i)
            .cloned()
            .ok_or_else(|| "heal e2e script exhausted".to_string())
    }
}

/// Turn 0 derives the contract; turn 1 does the work; turn 2 declares done.
///
/// The contract's check is a real shell command the runtime executes against
/// the worktree, so `contract_passed` is the runtime's finding rather than the
/// model's claim — and it would be red if turn 1 wrote nothing.
fn script() -> Arc<dyn TurnGenerator> {
    Arc::new(Script {
        cursor: AtomicUsize::new(0),
        turns: vec![
            turn(
                &json!({
                    "description": "greeting.txt carries the greeting",
                    "checks": [{
                        "name": "content",
                        "command": "grep -q 'hello from car coder' greeting.txt"
                    }]
                })
                .to_string(),
                json!([]),
            ),
            turn(
                "writing greeting.txt",
                json!([{
                    "id": "w1",
                    "name": "write_file",
                    "arguments": {"path": "greeting.txt", "content": "hello from car coder\n"}
                }]),
            ),
            turn("done — greeting.txt written", json!([])),
        ],
    })
}

/// A contract whose only check ALREADY passes on the untouched worktree, from a
/// session that nonetheless writes a file.
///
/// `provision_repo` seeds `README.md` with "seed", so this is the shape a
/// derivation actually produces when its checks do not exercise the reported
/// behaviour — or when the behaviour was already fixed.
///
/// Turn 1 WRITES deliberately. A vacuous contract plus an empty worktree is
/// already refused downstream ("the contract passed but the worktree is
/// unchanged"), so a script that did nothing would be caught by that net and
/// would not exercise this guard at all. With an edit present, the existing net
/// passes and the only thing standing between a contract that tests nothing and
/// an approved pull request is the baseline check.
fn vacuous_script() -> Arc<dyn TurnGenerator> {
    Arc::new(Script {
        cursor: AtomicUsize::new(0),
        turns: vec![
            turn(
                &json!({
                    "description": "the readme mentions the seed",
                    "checks": [{
                        "name": "readme",
                        "command": "grep -q 'seed' README.md"
                    }]
                })
                .to_string(),
                json!([]),
            ),
            turn(
                "adding a note",
                json!([{
                    "id": "w1",
                    "name": "write_file",
                    "arguments": {"path": "NOTES.md", "content": "a change the contract does not check\n"}
                }]),
            ),
            turn("done", json!([])),
        ],
    })
}

// --- a fixed panel ----------------------------------------------------------

struct Fixed {
    model: &'static str,
    answer: &'static str,
    /// A path the diff MUST mention — the change this panel is judging.
    ///
    /// Per-reviewer rather than a constant because different scripts write
    /// different files, and the assertion is only worth having if it names the
    /// file the session in THIS test actually wrote.
    expects: &'static str,
}

#[async_trait::async_trait]
impl Reviewer for Fixed {
    fn model(&self) -> &str {
        self.model
    }
    async fn review(&self, _criteria: &str, diff: &str) -> Result<String, String> {
        // The panel's whole input. A reviewer that is handed
        // "(diff unavailable: ...)" still answers, and the answer is worthless
        // — which is exactly how the `state_dir`-instead-of-repo bug would have
        // survived into production looking like a working review.
        assert!(
            diff.contains(self.expects),
            "the panel was not shown the change it is judging: {diff}"
        );
        Ok(self.answer.to_string())
    }
}

// --- the one seam left: `gh` itself -----------------------------------------

/// Records what GitHub was asked for and answers as GitHub would.
///
/// Everything BELOW this — the commit, the push to a real bare origin, the
/// one-pull-request-per-(head, base) reconciliation — is the real
/// `merge::deliver_pr_with`. Faking `gh` is the boundary of what can run
/// without a network; faking anything below it would repeat the mistake this
/// file exists to catch.
#[derive(Default)]
struct FakeGh {
    prs: Mutex<Vec<PrRecord>>,
    created: Mutex<Vec<(String, String, String, String)>>,
}

impl GitHubApi for FakeGh {
    fn auth_status(&self) -> Result<(), GhError> {
        Ok(())
    }
    fn list_prs_for_head(&self, _dir: &Path, head: &str) -> Result<Vec<PrRecord>, GhError> {
        Ok(self
            .prs
            .lock()
            .unwrap()
            .iter()
            .filter(|_| !head.is_empty())
            .cloned()
            .collect())
    }
    fn create_pr(
        &self,
        dir: &Path,
        head: &str,
        base: &str,
        title: &str,
        body: &str,
        _draft: bool,
    ) -> Result<PrRecord, GhError> {
        self.created.lock().unwrap().push((
            dir.display().to_string(),
            head.to_string(),
            base.to_string(),
            format!("{title}\n{body}"),
        ));
        let record = PrRecord {
            number: 1,
            state: PrState::Open,
            url: "https://example.invalid/pull/1".into(),
            is_draft: false,
            base: base.to_string(),
        };
        self.prs.lock().unwrap().push(record.clone());
        Ok(record)
    }
    fn set_pr_body(&self, _dir: &Path, _number: u64, _body: &str) -> Result<(), GhError> {
        Ok(())
    }
    fn ci_for_sha(&self, _dir: &Path, _number: u64, head_sha: &str) -> Result<CiSummary, GhError> {
        Ok(CiSummary {
            observation_error: None,
            head_sha: head_sha.to_string(),
            state: CiState::Green,
            checks: vec![CiCheck {
                name: "e2e".into(),
                state: CiState::Green,
            }],
        })
    }
}

// --- git ---------------------------------------------------------------------

fn git(dir: &Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("git runs");
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// A real repository with a real initial commit on `main` and a real `origin`.
///
/// The origin is a local bare repo, so the push in delivery is a real push —
/// the step that used to be missing entirely.
fn provision_repo() -> (tempfile::TempDir, tempfile::TempDir) {
    let origin = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    git(origin.path(), &["init", "-q", "--bare", "-b", "main"]);
    git(dir.path(), &["init", "-q", "-b", "main"]);
    git(dir.path(), &["config", "user.name", "heal"]);
    git(dir.path(), &["config", "user.email", "heal@car"]);
    std::fs::write(dir.path().join("README.md"), "seed\n").unwrap();
    git(dir.path(), &["add", "-A"]);
    git(dir.path(), &["commit", "-qm", "seed"]);
    git(
        dir.path(),
        &["remote", "add", "origin", origin.path().to_str().unwrap()],
    );
    git(dir.path(), &["push", "-q", "origin", "main"]);
    (dir, origin)
}

/// The commit `origin` holds on a branch, or `None` when it has no such branch.
fn origin_head(origin: &Path, branch: &str) -> Option<String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(origin)
        .args(["rev-parse", "--verify", &format!("refs/heads/{branch}")])
        .output()
        .expect("git runs");
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
}

// --- the loop's IO, with only the GitHub writes supplied --------------------

struct RealCoderIo {
    runner: LiveCoderRunner,
    item: Candidate,
    comments: Mutex<Vec<String>>,
}

#[async_trait::async_trait]
impl TickIo for RealCoderIo {
    async fn candidates(&self, _t: &HealTarget) -> Result<Vec<Candidate>, String> {
        Ok(vec![self.item.clone()])
    }

    async fn open_prs(&self, _t: &HealTarget) -> Result<Vec<RawPullRequest>, String> {
        Ok(Vec::new())
    }

    async fn intent_for(&self, _i: &Candidate) -> Result<Intent, String> {
        // The tier gate has its own tests; stacking a fake permission oracle in
        // here would test that gate a second time and this composition zero
        // times. What matters to this test is that a `SessionSeed` — not a
        // `String` — is what reaches the session.
        Ok(Intent::Seed(SessionSeed::from_trusted(
            "create greeting.txt containing the text: hello from car coder",
        )))
    }

    fn redact(&self, text: &str) -> String {
        text.to_string()
    }

    /// Delegates. A private reimplementation here would be a second fake coder,
    /// which is the exact failure this file exists to catch.
    async fn run_coder(
        &self,
        target: &HealTarget,
        item: &Candidate,
        seed: &SessionSeed,
    ) -> Result<Attempt, RunFailure> {
        self.runner.run(target, item, seed).await
    }

    /// Delegates, so the REAL delivery runs: a real commit, a real push to a
    /// real bare origin, and the real one-pull-request-per-(head, base)
    /// reconciliation. Only `gh` itself is faked.
    async fn deliver(
        &self,
        target: &HealTarget,
        item: &Candidate,
        session_id: &str,
        gate: &GateOutcome,
    ) -> Result<PrDeliveryOutcome, DeliverRefusal> {
        // The gate summary reaches the pull-request body, so an empty one is a
        // pull request that does not say why it was opened.
        assert!(!gate.summary().is_empty());
        let reference = if target.is_cross_repo() {
            format!("{}#{}", item.repo, item.number)
        } else {
            format!("#{}", item.number)
        };
        let body = format!("self-heal for {reference}. Gate: {}", gate.summary());
        self.runner.deliver(target, item, session_id, &body).await
    }

    async fn abandon(&self, session_id: &str) {
        self.runner.abandon(session_id).await;
    }

    async fn comment(&self, _i: &Candidate, text: &str) -> Result<(), String> {
        self.comments.lock().unwrap().push(text.to_string());
        Ok(())
    }

    fn now_ms(&self) -> u64 {
        10_000_000
    }
}

/// Everything the run needs, kept alive for its duration: the temp dirs delete
/// their contents on drop, and the worktree lives under `state_dir`.
struct Harness {
    io: Arc<RealCoderIo>,
    gh: Arc<FakeGh>,
    state: Arc<ServerState>,
    target: HealTarget,
    repo: tempfile::TempDir,
    origin: tempfile::TempDir,
    _state_dir: tempfile::TempDir,
    _journal: tempfile::TempDir,
}

fn harness(panel: Vec<Arc<dyn Reviewer>>) -> Harness {
    harness_with(panel, script())
}

fn harness_with(panel: Vec<Arc<dyn Reviewer>>, generator: Arc<dyn TurnGenerator>) -> Harness {
    harness_canonical(panel, generator, Arc::new(|m: &str| m.to_string()))
}

/// A harness whose heal.toml asked for `auto` rather than a named engine.
///
/// Deterministic despite `Auto` consulting the machine: this harness's intent
/// is a one-file creation, and `resolve_engine` keeps a SIMPLE task native even
/// where a frontier CLI is installed (`router::auto_simple_task_stays_native_
/// even_with_clis`). So the session resolves to `Native` on a bare CI runner and
/// on a laptop with Claude Code both.
fn harness_auto(panel: Vec<Arc<dyn Reviewer>>, generator: Arc<dyn TurnGenerator>) -> Harness {
    harness_inner(
        panel,
        generator,
        Arc::new(|m: &str| m.to_string()),
        EngineChoice::Auto,
    )
}

fn harness_canonical(
    panel: Vec<Arc<dyn Reviewer>>,
    generator: Arc<dyn TurnGenerator>,
    canonical_model: Arc<dyn Fn(&str) -> String + Send + Sync>,
) -> Harness {
    harness_inner(panel, generator, canonical_model, EngineChoice::Native)
}

fn harness_inner(
    panel: Vec<Arc<dyn Reviewer>>,
    generator: Arc<dyn TurnGenerator>,
    canonical_model: Arc<dyn Fn(&str) -> String + Send + Sync>,
    engine: EngineChoice,
) -> Harness {
    let (repo, origin) = provision_repo();
    let state_dir = tempfile::tempdir().unwrap();
    let journal = tempfile::tempdir().unwrap();
    let state = Arc::new(ServerState::standalone(journal.path().to_path_buf()));
    let gh = Arc::new(FakeGh::default());

    let runner = LiveCoderRunner {
        state: state.clone(),
        generator,
        state_dir: state_dir.path().to_path_buf(),
        routing_exclusions: panel
            .iter()
            .map(|reviewer| reviewer.model().to_string())
            .collect(),
        reviewers: panel,
        max_wall_secs: 300,
        max_iterations: Some(6),
        // What heal.toml ASKED for. Usually `Native` here, so a test exercises
        // the same engine on a developer's laptop as in CI; `harness_auto`
        // passes `Auto` on purpose, and stays deterministic for the reason
        // documented there.
        engine,
        model: None,
        canonical_model,
        github: gh.clone(),
    };

    let target = HealTarget {
        repo: "acme/widgets".into(),
        fix_repo: None,
        checkout: Some(Checkout::Local(repo.path().to_path_buf())),
        label: "self-heal".into(),
        base: "main".into(),
    };

    let io = Arc::new(RealCoderIo {
        runner,
        item: Candidate {
            repo: "acme/widgets".into(),
            number: 7,
            tier: Some(ProvenanceTier::Maintainer),
            labelled: true,
            created_ms: 1,
            kind: CandidateKind::Issue,
        },
        comments: Mutex::new(Vec::new()),
    });

    Harness {
        io,
        gh,
        state,
        target,
        repo,
        origin,
        _state_dir: state_dir,
        _journal: journal,
    }
}

/// The session the tick ran, read back from the daemon's own map.
async fn only_session(
    state: &Arc<ServerState>,
) -> (String, CoderState, Option<std::path::PathBuf>) {
    let sessions = state.coder_sessions.lock().await;
    assert_eq!(sessions.len(), 1, "expected exactly one coder session");
    let (id, entry) = sessions.iter().next().unwrap();
    let s = entry.session.lock().await;
    (id.clone(), s.state, s.workspace_path.clone())
}

#[tokio::test(flavor = "multi_thread")]
async fn a_tick_takes_an_issue_through_a_real_session_to_a_pull_request() {
    let h = harness(vec![
        Arc::new(Fixed {
            model: "reviewer-a",
            answer: "PASS — matches the stated intent",
            expects: "greeting.txt",
        }),
        Arc::new(Fixed {
            model: "reviewer-b",
            answer: "PASS — correctly scoped",
            expects: "greeting.txt",
        }),
        Arc::new(Fixed {
            model: "reviewer-c",
            answer: "FAIL — would prefer a test",
            expects: "greeting.txt",
        }),
    ]);

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-e2e", &NoClaimSink).await;

    let gate_summary = match &outcome {
        TickOutcome::Opened {
            repo,
            number,
            pr_url,
            gate,
            ci,
            delivery,
        } => {
            assert_eq!(repo, "acme/widgets");
            assert_eq!(*number, 7);
            assert!(pr_url.contains("pull/1"));
            assert_eq!(ci.state, CiState::Green);
            assert_eq!(
                ci.head_sha,
                origin_head(h.origin.path(), &delivery_branch(&h.io.item)).unwrap()
            );
            assert_eq!(
                delivery,
                &format!(
                    "delivered with green checks and ready for review at {}",
                    ci.head_sha
                )
            );
            gate.clone()
        }
        other => panic!("expected a pull request, got {other:?}"),
    };
    // 2 of 3 is a strict majority: the dissenter does not block, and the
    // summary carries the count rather than reporting consensus.
    assert!(gate_summary.contains("2/3"), "{gate_summary}");

    // A REAL delivery: a real commit, a real push to a real bare origin, and a
    // real pull request reconciled against it. Before this work there was no
    // branch at all — the loop failed every green session — and after the first
    // fix the branch existed only locally, so `gh pr create --head` would have
    // been asked to open a pull request from a branch GitHub had never seen.
    let branch = delivery_branch(&h.io.item);
    let on_origin = origin_head(h.origin.path(), &branch)
        .unwrap_or_else(|| panic!("{branch} never reached the remote"));

    // …carrying the work the session actually did.
    let content = git(
        h.repo.path(),
        &["show", &format!("{on_origin}:greeting.txt")],
    );
    assert!(content.contains("hello from car coder"), "{content}");

    // …and only that. `main` is untouched on both sides: the loop proposes, it
    // does not land.
    for (where_, files) in [
        (
            "local",
            git(h.repo.path(), &["ls-tree", "--name-only", "main"]),
        ),
        (
            "origin",
            git(h.origin.path(), &["ls-tree", "--name-only", "main"]),
        ),
    ] {
        assert!(
            !files.contains("greeting.txt"),
            "the loop wrote to {where_} main: {files}"
        );
    }

    // Exactly one pull request, opened against the target's base, from the
    // stable per-item branch — the name that lets a retry reconcile to the same
    // pull request instead of stranding a second one.
    let created = h.gh.created.lock().unwrap().clone();
    assert_eq!(created.len(), 1);
    let (dir, head, base, text) = &created[0];
    assert_eq!(head, &branch);
    assert_eq!(base, "main");
    // `gh` must run in the checkout, or it resolves a different repository.
    assert_eq!(dir, &h.repo.path().display().to_string());
    // The body references the issue: coverage matches on exactly this, so a
    // body without it is one the loop duplicates on a later tick.
    assert!(text.contains("#7"), "{text}");
    assert!(text.contains("2/3"), "{text}");

    // The session reached a TERMINAL state, so its git worktree — registered in
    // the operator's own repository — was released rather than held forever by
    // a loop whose expected outcome is rejection.
    let (_id, state, worktree) = only_session(&h.state).await;
    assert_eq!(state, CoderState::Merged);
    if let Some(path) = worktree {
        assert!(
            !path.exists(),
            "the worktree outlived the session: {path:?}"
        );
    }

    // The claim is HELD after success: the item stays taken until a human
    // closes it, so the next tick does not redo work that is already up for
    // review.
    assert_eq!(claims.held_by("acme/widgets", 7), Some("run-e2e"));
    // Success clears the failure history rather than leaving a backoff behind.
    assert!(claims.attempts().is_empty());
    // Nothing was said on the issue, because nothing went wrong.
    assert!(h.io.comments.lock().unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_contract_that_is_green_before_any_edit_never_reaches_the_panel() {
    // car#1293. The worse half of the red-green baseline: an unrunnable check
    // FAILS, so the run reports it — a contract that is already green PASSES,
    // so without this guard the session reaches the gate with the deterministic
    // half satisfied by code nobody in this run wrote, and the panel becomes
    // the only thing actually deciding while the pull request reports both.
    //
    // The panel here would approve unanimously, so if the guard were missing
    // this test would open a pull request.
    let h = harness_with(
        vec![
            Arc::new(Fixed {
                model: "reviewer-a",
                answer: "PASS — looks right",
                expects: "NOTES.md",
            }),
            Arc::new(Fixed {
                model: "reviewer-b",
                answer: "PASS — agreed",
                expects: "NOTES.md",
            }),
        ],
        vacuous_script(),
    );

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-vacuous", &NoClaimSink).await;

    match &outcome {
        TickOutcome::Failed { detail } => {
            assert!(detail.contains("already passes on"), "{detail}");
            // Names the item and says what a human has to decide, rather than
            // reporting a generic failure the maintainer cannot act on.
            assert!(detail.contains("acme/widgets#7"), "{detail}");
            assert!(detail.contains("premise"), "{detail}");
        }
        other => panic!("expected a refusal, got {other:?}"),
    }

    // Nothing was published: no branch on the remote, no pull request.
    assert!(
        origin_head(h.origin.path(), &delivery_branch(&h.io.item)).is_none(),
        "a contract that gates nothing must not deliver"
    );
    assert!(h.gh.created.lock().unwrap().is_empty(), "no pull request");

    // The maintainer is told on the issue — this is a finding about the issue,
    // not a silent skip.
    let comments = h.io.comments.lock().unwrap();
    assert!(
        comments.iter().any(|c| c.contains("already passes on")),
        "{comments:?}"
    );
}

/// car#1299. The assembly-time check only fires when `coder_model` is pinned;
/// unpinned — the default — the router picks, and on a machine with one
/// reachable credential that pick can also be a panel seat.
///
/// The journal has recorded the authoring model all along, so the check can run
/// against what actually wrote the diff rather than against configuration.
/// Here the scripted generator reports `scripted` as its model and a reviewer
/// is named `scripted` too, which is that collision.
/// [`script`], with every turn reporting `model` as the model that served it.
fn script_as(model: &'static str) -> Arc<dyn TurnGenerator> {
    Arc::new(Script {
        cursor: AtomicUsize::new(0),
        turns: vec![
            turn_as(
                model,
                &json!({
                    "description": "greeting.txt carries the greeting",
                    "checks": [{
                        "name": "content",
                        "command": "grep -q 'hello from car coder' greeting.txt"
                    }]
                })
                .to_string(),
                json!([]),
            ),
            turn_as(
                model,
                "writing greeting.txt",
                json!([{
                    "id": "w1",
                    "name": "write_file",
                    "arguments": {"path": "greeting.txt", "content": "hello from car coder\n"}
                }]),
            ),
            turn_as(model, "done — greeting.txt written", json!([])),
        ],
    })
}

#[tokio::test]
async fn a_model_that_wrote_the_change_may_not_review_it() {
    let h = harness(vec![
        Arc::new(Fixed {
            model: "scripted",
            answer: "PASS — looks right to me",
            expects: "greeting.txt",
        }),
        Arc::new(Fixed {
            model: "reviewer-b",
            answer: "PASS — agreed",
            expects: "greeting.txt",
        }),
    ]);

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-self-review", &NoClaimSink).await;

    match &outcome {
        TickOutcome::Failed { detail } => {
            assert!(detail.contains("review its own output"), "{detail}");
            assert!(detail.contains("scripted"), "{detail}");
        }
        other => panic!("a self-reviewing panel must be refused, got {other:?}"),
    }

    // Nothing published on a compromised verdict.
    assert!(
        origin_head(h.origin.path(), &delivery_branch(&h.io.item)).is_none(),
        "a self-reviewed change must not be delivered"
    );
    assert!(h.gh.created.lock().unwrap().is_empty(), "no pull request");
}

/// The same rule when the two sides are spelled differently, which is the
/// PRODUCTION shape and the one a spelling comparison misses entirely.
///
/// An unpinned turn reports `ModelSchema.name` (`car-inference`'s
/// `reported_model_used` takes `candidate_name` unless an exact immutable id
/// was pinned), while a seat is configured however the operator wrote it and
/// `knows_model` accepts an id or a name. For every model whose id and name
/// differ — car#889's `openrouter/google/gemini-3.1-pro-preview` vs
/// `google/gemini-3.1-pro-preview` — those are two spellings of one model, and
/// a gate that compares the strings never fires while reading as covered.
#[tokio::test]
async fn a_seat_spelled_by_id_still_catches_an_author_reported_by_name() {
    let h = harness_canonical(
        vec![
            Arc::new(Fixed {
                model: "openrouter/acme/model-x",
                answer: "PASS — looks right to me",
                expects: "greeting.txt",
            }),
            Arc::new(Fixed {
                model: "reviewer-b",
                answer: "PASS — agreed",
                expects: "greeting.txt",
            }),
        ],
        // The router served the turn and reported the display name.
        script_as("Model X"),
        // The registry knows both spellings as one id.
        Arc::new(|m: &str| match m {
            "Model X" | "openrouter/acme/model-x" => "openrouter/acme/model-x".to_string(),
            other => other.to_string(),
        }),
    );

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-canonical", &NoClaimSink).await;

    match &outcome {
        TickOutcome::Failed { detail } => {
            assert!(detail.contains("review its own output"), "{detail}");
            assert!(detail.contains("Model X"), "{detail}");
            assert!(detail.contains("openrouter/acme/model-x"), "{detail}");
        }
        other => panic!("one model under two spellings must be refused, got {other:?}"),
    }
    assert!(h.gh.created.lock().unwrap().is_empty(), "no pull request");
}

/// A native session that reaches approval with nothing recorded against it.
///
/// `NeedsApproval` is reached by a model declaring done, which journals a
/// terminal — so an empty attribution on the native rung means the record was
/// lost, not that no model wrote the change. Permitting there would be the
/// silently-absent attribution this gate exists to close, one level down.
///
/// Foreman and external sessions are the other case and are NOT refused: they
/// farm to a coding CLI whose backbone CAR never resolved, so "unknown" is the
/// The same refusal when heal.toml asked for `auto` and the router chose native.
///
/// The gate compared `LiveCoderRunner.engine` — the REQUESTED engine — against
/// `Native`. `EngineChoice::Auto` parses, and resolves to `Native` for any
/// simple task and for any machine with no CLI installed, so a session that ran
/// native and lost its attribution walked through the gate because the request
/// said `auto` (car#1357). The session records the RESOLVED engine; that is
/// what the gate reads now.
#[tokio::test]
async fn an_auto_session_that_resolved_native_is_refused_the_same_way() {
    let h = harness_auto(
        vec![
            Arc::new(Fixed {
                model: "reviewer-a",
                answer: "PASS — looks right to me",
                expects: "greeting.txt",
            }),
            Arc::new(Fixed {
                model: "reviewer-b",
                answer: "PASS — agreed",
                expects: "greeting.txt",
            }),
        ],
        script_as(""),
    );

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-auto-native", &NoClaimSink).await;

    match &outcome {
        TickOutcome::Failed { detail } => {
            assert!(detail.contains("no model recorded against it"), "{detail}");
        }
        other => panic!("`auto` that resolved native must be refused too, got {other:?}"),
    }
    assert!(h.gh.created.lock().unwrap().is_empty(), "no pull request");
}

/// honest answer rather than a fault. That is also the DEFAULT engine, which is
/// why this check is scoped to the RESOLVED engine being `Native` rather than to
/// an empty set.
#[tokio::test]
async fn a_native_session_with_no_recorded_author_is_refused() {
    let h = harness_with(
        vec![
            Arc::new(Fixed {
                model: "reviewer-a",
                answer: "PASS — looks right to me",
                expects: "greeting.txt",
            }),
            Arc::new(Fixed {
                model: "reviewer-b",
                answer: "PASS — agreed",
                expects: "greeting.txt",
            }),
        ],
        script_as(""),
    );

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(
        &io,
        &h.target,
        &mut claims,
        "run-unattributed",
        &NoClaimSink,
    )
    .await;

    match &outcome {
        TickOutcome::Failed { detail } => {
            assert!(detail.contains("no model recorded against it"), "{detail}");
        }
        other => panic!("an unattributed native change must be refused, got {other:?}"),
    }
    assert!(h.gh.created.lock().unwrap().is_empty(), "no pull request");
}

#[tokio::test]
async fn a_panel_that_refuses_publishes_nothing_at_all() {
    // The other half of the gate, over the same real session. A refused change
    // must leave no trace in the repository or on the remote, close its own
    // session, and record a failure so the backoff applies.
    let h = harness(vec![
        Arc::new(Fixed {
            model: "reviewer-a",
            answer: "FAIL — wrong approach",
            expects: "greeting.txt",
        }),
        Arc::new(Fixed {
            model: "reviewer-b",
            answer: "FAIL — out of scope",
            expects: "greeting.txt",
        }),
        Arc::new(Fixed {
            model: "reviewer-c",
            answer: "PASS — fine by me",
            expects: "greeting.txt",
        }),
    ]);

    let io: Arc<dyn TickIo> = h.io.clone();
    let mut claims = ClaimStore::new();
    let outcome = tick(&io, &h.target, &mut claims, "run-reject", &NoClaimSink).await;

    match &outcome {
        TickOutcome::Rejected { number, gate, .. } => {
            assert_eq!(*number, 7);
            // One approval against the two a panel of three requires, and the
            // summary names the dissenters — an operator reading a rejection
            // needs to know who objected and why, not just that it happened.
            assert!(gate.starts_with("1/2 required approvals"), "{gate}");
            assert!(gate.contains("reviewer-a: FAIL"), "{gate}");
            assert!(gate.contains("reviewer-b: FAIL"), "{gate}");
        }
        other => panic!("expected a rejection, got {other:?}"),
    }

    // NOTHING was written. No local branch, no remote branch, no pull request.
    // A `car/coder/*` or `car/heal/*` branch means "this was approved"; work a
    // panel refused must not occupy that namespace, and a loop on a cadence
    // whose expected outcome is rejection must not leave a dead branch behind
    // each time.
    let local = git(h.repo.path(), &["branch", "--list", "car/*"]);
    assert!(
        local.trim().is_empty(),
        "a refused change published: {local}"
    );
    assert_eq!(
        origin_head(h.origin.path(), &delivery_branch(&h.io.item)),
        None
    );
    assert!(
        h.gh.created.lock().unwrap().is_empty(),
        "a refused change reached a pull request"
    );

    // The session was closed out, so the worktree went with it.
    let (_id, state, worktree) = only_session(&h.state).await;
    assert_eq!(state, CoderState::Abandoned);
    if let Some(path) = worktree {
        assert!(
            !path.exists(),
            "the worktree outlived the session: {path:?}"
        );
    }

    // Released, so a human or a later tick can take it — but recorded as a
    // failure, so the backoff applies and the loop cannot spin on it.
    assert_eq!(claims.held_by("acme/widgets", 7), None);
    assert!(
        !claims.attempts().is_empty(),
        "the failure was not recorded"
    );
    // The panel's reasons reached the issue, redacted, rather than failing
    // silently.
    let comments = h.io.comments.lock().unwrap().clone();
    assert_eq!(comments.len(), 1);
    assert!(comments[0].contains("reviewer-a"), "{}", comments[0]);
}