car-server-core 0.52.1

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! File [`DurableFixProposal`]s as issues on the releases repo — the
//! **reporting** half of self-correction.
//!
//! [`super::ab_learnings`] already does the hard part: it folds a dogfooding
//! round's losses into ranked, evidence-backed proposals that name which CAR
//! component to change and on what evidence. Until this module existed, that
//! output was `println!`'d and written to `learnings-<unix>.md`, where nobody
//! read it unless they had already gone looking — which defeats the purpose of
//! an automated round.
//!
//! ## Why this is a sibling of [`super::merge`] and not an extension of it
//!
//! [`super::merge::GitHubApi`] resolves its repository from the checkout's
//! `origin` remote, because a pull request must land where the branch was
//! pushed. A defect report must NOT: it belongs on the releases repo, which is
//! reachable from any deployment that has telemetry, with or without a source
//! checkout. Folding issue filing into that trait would inherit exactly the
//! repo-resolution rule that is wrong here, so the seam is separate and the
//! repository is always an explicit argument.
//!
//! That split is the whole reason reporting and correcting can live in
//! different places: filing needs no source, fixing does.
//!
//! ## Idempotence
//!
//! Every body carries `<!-- car-fix-signature: <hex> -->`, a hash over the
//! proposal's *stable identity* — its target component and failure pattern.
//! Deliberately not the title (wording drifts) and not `evidence_tasks` (those
//! change every round, which would make each re-run a fresh duplicate).
//!
//! The search is scoped to **open** issues. A signature whose issue was closed
//! and then recurs gets a new report, and that is the intended behaviour rather
//! than an oversight: recurrence after a fix is a real signal that the fix did
//! not hold, and silently swallowing it would hide the most interesting case.
//!
//! ## The marker is a dedup id, and the report target is public
//!
//! `Parslee-ai/car-releases` is world-writable: anyone with a GitHub account
//! can open an issue on it. The signature marker is plain text in that public
//! repository, so anyone can paste one into an issue of their own — which used
//! to be enough to make this module see `AlreadyOpen` and suppress a real
//! defect report indefinitely. Deduplication therefore honours a marker only
//! on an issue that [`super::provenance::resolve_tier`] puts at
//! [`ProvenanceTier::Runtime`]: filed by the account this runtime
//! authenticates as, carrying a signature recomputed here from a proposal held
//! in memory. A marker on anyone else's issue is recorded and ignored
//! (`Parslee-ai/car#1081`).

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use std::time::SystemTime;

use super::ab_learnings::{Confidence, DurableFixProposal};
use super::merge::GhError;
use super::provenance::{
    resolve_tier, LocalSignatures, PermissionOracle, ProvenanceRecord, ProvenanceTier, RawIssue,
};

/// The default report target. Not the source repo: see the module docs.
pub const DEFAULT_REPORT_REPO: &str = "Parslee-ai/car-releases";

/// A tentative proposal must have recurred at least this many times before it
/// is worth a human's attention. A one-off tentative signal is noise, and a
/// tracker that fills with noise stops being read at all.
const TENTATIVE_MIN_EVIDENCE: usize = 2;

/// The GitHub issue operations reporting needs, behind a seam.
///
/// Same idiom as [`super::merge::GitHubApi`] and
/// [`super::contract::derive_contract`]: the interesting behaviour here is
/// deduplication and the noise gate, and neither is testable against a live
/// tracker.
pub trait IssueApi: Send + Sync {
    /// Every **open** issue on `repo`, as the tracker returned it.
    ///
    /// Returns [`RawIssue`], which carries no accessor for its text: matching a
    /// marker is a predicate, and reading a body requires a resolved trust
    /// tier. See [`super::provenance`].
    fn list_open_issues(&self, repo: &str) -> Result<Vec<RawIssue>, GhError>;

    /// Open an issue and return its number.
    fn create_issue(
        &self,
        repo: &str,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> Result<u64, GhError>;
}

/// The stable identity of a proposed fix: what to change, and what pattern
/// motivated it. See the module docs for what is deliberately excluded.
pub fn proposal_signature(proposal: &DurableFixProposal) -> String {
    let mut hasher = Sha256::new();
    hasher.update(proposal.target_component.trim().to_lowercase().as_bytes());
    // A NUL separator, so ("ab", "c") and ("a", "bc") cannot collide.
    hasher.update([0u8]);
    hasher.update(proposal.pattern.trim().to_lowercase().as_bytes());
    format!("{:x}", hasher.finalize())[..16].to_string()
}

/// The machine-readable handle embedded in every body.
pub fn signature_marker(signature: &str) -> String {
    format!("<!-- car-fix-signature: {signature} -->")
}

/// The signature carried by `body`, if it carries exactly one well-formed
/// marker.
///
/// Strict about the shape — hex only — so a body cannot smuggle other text
/// through the field, and so the value compared against locally recomputed
/// signatures is the same alphabet [`proposal_signature`] produces.
pub fn parse_signature_marker(body: &str) -> Option<&str> {
    const OPEN: &str = "<!-- car-fix-signature: ";
    const CLOSE: &str = " -->";
    // Every occurrence, not just the first. `render_issue_body` interpolates
    // model-authored prose ahead of the marker, so a proposal whose text
    // happens to contain the literal opener would otherwise void the real
    // marker underneath it and re-file that report every round.
    let mut rest = body;
    while let Some(open) = rest.find(OPEN) {
        let after = &rest[open + OPEN.len()..];
        if let Some(end) = after.find(CLOSE) {
            let signature = &after[..end];
            if !signature.is_empty() && signature.chars().all(|c| c.is_ascii_hexdigit()) {
                return Some(signature);
            }
        }
        rest = &rest[open + OPEN.len()..];
    }
    None
}

/// Whether this proposal clears the bar for filing.
///
/// [`Confidence::Strong`] means a recurring, diagnosable pattern already
/// mapped to a component — that is a defect report on its own. `Tentative`
/// means the specific fix still needs a human reading the failures, which is
/// only worth filing once the pattern has actually repeated.
pub fn clears_reporting_bar(proposal: &DurableFixProposal) -> bool {
    match proposal.confidence {
        Confidence::Strong => true,
        Confidence::Tentative => proposal.evidence_count >= TENTATIVE_MIN_EVIDENCE,
    }
}

/// Render one proposal as an issue body, marker included.
pub fn render_issue_body(proposal: &DurableFixProposal, signature: &str) -> String {
    let mut body = String::new();
    body.push_str("_Filed automatically by `car coder-ab` from a dogfooding round._\n\n");

    body.push_str("## Pattern\n\n");
    body.push_str(proposal.pattern.trim());
    body.push_str("\n\n## Where to look\n\n");
    body.push_str(&format!("- **Component**: {}\n", proposal.target_component));
    body.push_str(&format!(
        "- **Hint**: {} _(best-effort — verify before editing)_\n",
        proposal.target_hint
    ));

    body.push_str("\n## Proposed change\n\n");
    body.push_str(proposal.proposed_change.trim());

    body.push_str("\n\n## Evidence\n\n");
    body.push_str(&format!(
        "{} occurrence(s), confidence {:?}, kind {:?}, priority {}.\n",
        proposal.evidence_count, proposal.confidence, proposal.kind, proposal.priority
    ));
    if !proposal.evidence_tasks.is_empty() {
        body.push_str("\nTasks evidencing this pattern:\n\n");
        for task in &proposal.evidence_tasks {
            body.push_str(&format!("- `{task}`\n"));
        }
    }

    body.push_str(
        "\n---\n\nThis is a *class* of change, not a patch — the synthesizer narrows where to \
         look, it does not invent the specific fix.\n\n",
    );
    body.push_str(&signature_marker(signature));
    body.push('\n');
    body
}

/// What one proposal's report attempt did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "outcome")]
pub enum ReportOutcome {
    /// A new issue was opened.
    Filed { number: u64 },
    /// An open issue already carries this signature.
    AlreadyOpen { number: u64 },
    /// Below the reporting bar; see [`clears_reporting_bar`].
    BelowBar,
    /// The tracker call failed. Reporting is best-effort: one failure must not
    /// abort the round, and it must not be silent either.
    Failed { error: String },
}

/// One proposal and what happened to it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReportRecord {
    pub title: String,
    pub signature: String,
    #[serde(flatten)]
    pub outcome: ReportOutcome,
    /// The trust tier resolved for every open issue that carried this
    /// signature. Empty when nothing did.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub provenance: Vec<ProvenanceRecord>,
    /// Issues that carried this signature and resolved to
    /// [`ProvenanceTier::Public`] — a stranger's issue wearing our marker. They
    /// do not suppress the report, and they are not silent either.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub public_marker_carriers: Vec<u64>,
}

/// How many marker-carrying issues one proposal will resolve a tier for.
///
/// Each non-runtime resolution costs a live permission lookup, so an attacker
/// who papered the tracker with copies of one marker would otherwise turn each
/// reporting round into hundreds of API calls. Runtime-authored candidates are
/// checked first and cost nothing, so this cap cannot hide our own issue behind
/// a pile of forgeries.
const MAX_MARKER_CARRIERS: usize = 5;

/// File every proposal that clears the bar, skipping signatures already open on
/// an issue this runtime actually filed.
///
/// Best-effort by construction: a tracker failure is recorded against that
/// proposal and the rest still go. A dogfooding round that produced real
/// findings must not lose them because the tracker was briefly unreachable.
pub fn report_proposals(
    api: &dyn IssueApi,
    oracle: &dyn PermissionOracle,
    repo: &str,
    proposals: &[DurableFixProposal],
    labels: &[String],
) -> Vec<ReportRecord> {
    // Recomputed here, from proposals held in memory. This set is the whole
    // content of the `runtime` tier: a marker matches only if we just derived
    // the same hex ourselves.
    let local = LocalSignatures::from_proposals(proposals);
    // One listing for the whole round. It used to be one per proposal, which
    // fetched up to `SCAN_LIMIT` bodies again for every finding.
    let open = api.list_open_issues(repo);
    // The account we authenticate as, resolved once per round at read time. It
    // is this process's own identity, not a revocable grant on someone else's
    // account, so ordering candidates by it is safe.
    //
    // A failure here is fatal to the round for the same reason a failed listing
    // is: without it nothing can reach the `runtime` tier, so every proposal
    // would re-file. Filing blind duplicates is worse than saying we could not
    // check.
    let viewer = oracle.viewer_login();

    proposals
        .iter()
        .map(|proposal| {
            let signature = proposal_signature(proposal);
            let mut record = ReportRecord {
                title: proposal.title.clone(),
                signature: signature.clone(),
                outcome: ReportOutcome::BelowBar,
                provenance: Vec::new(),
                public_marker_carriers: Vec::new(),
            };
            if !clears_reporting_bar(proposal) {
                return record;
            }
            // If we cannot tell whether it is already open, filing blind would
            // duplicate — whether the gap is the listing or our own identity.
            let rows = match (&open, &viewer) {
                (Ok(rows), Ok(_)) => rows,
                (Err(e), _) | (_, Err(e)) => {
                    record.outcome = ReportOutcome::Failed {
                        error: e.to_string(),
                    };
                    return record;
                }
            };
            let already_open = resolve_marker_carriers(
                rows,
                &signature,
                oracle,
                &local,
                viewer.as_deref().ok(),
                &mut record,
            );
            if let Some(number) = already_open {
                record.outcome = ReportOutcome::AlreadyOpen { number };
                return record;
            }
            let body = render_issue_body(proposal, &signature);
            record.outcome = match api.create_issue(repo, &proposal.title, &body, labels) {
                Ok(number) => ReportOutcome::Filed { number },
                Err(e) => ReportOutcome::Failed {
                    error: e.to_string(),
                },
            };
            record
        })
        .collect()
}

/// Resolve a tier for the issues carrying `signature` and return the number of
/// the first one whose author has write access, recording every decision.
fn resolve_marker_carriers(
    rows: &[RawIssue],
    signature: &str,
    oracle: &dyn PermissionOracle,
    local: &LocalSignatures,
    viewer: Option<&str>,
    record: &mut ReportRecord,
) -> Option<u64> {
    let mut carriers: Vec<&RawIssue> = rows
        .iter()
        .filter(|row| row.carries_marker(signature))
        .collect();
    // Ours first, so the cap below can only ever drop forgeries.
    carriers.sort_by_key(|row| match viewer {
        Some(v) if v.eq_ignore_ascii_case(row.author_login()) => 0,
        _ => 1,
    });

    for row in carriers.into_iter().take(MAX_MARKER_CARRIERS) {
        let tiered = resolve_tier((*row).clone(), oracle, local, SystemTime::now());
        record.provenance.push(tiered.record().clone());
        if tiered.tier() == ProvenanceTier::Public {
            record.public_marker_carriers.push(tiered.number());
            continue;
        }
        // Write access to the tracker. Stop here: further lookups cost live
        // `gh` calls and cannot change the answer.
        return Some(tiered.number());
    }
    None
}

/// A one-line-per-proposal summary for the round's stdout.
pub fn render_report(records: &[ReportRecord], repo: &str) -> String {
    if records.is_empty() {
        return "issue reporting: no proposals to report".to_string();
    }
    let mut out = format!("issue reporting → {repo}\n");
    for record in records {
        let line = match &record.outcome {
            ReportOutcome::Filed { number } => format!("filed #{number}"),
            ReportOutcome::AlreadyOpen { number } => format!("already open as #{number}"),
            ReportOutcome::BelowBar => "skipped (below reporting bar)".to_string(),
            ReportOutcome::Failed { error } => format!("FAILED: {error}"),
        };
        out.push_str(&format!("  {}{}\n", record.title, line));
        if !record.public_marker_carriers.is_empty() {
            // Not a failure, and not silent: someone else's issue is wearing
            // this runtime's dedup marker, which is exactly what a marker read
            // as an auth token would have honoured.
            out.push_str(&format!(
                "    note: signature also appears on issue(s) {} filed by accounts with no write \
                 access to the tracker — ignored for deduplication\n",
                record
                    .public_marker_carriers
                    .iter()
                    .map(|n| format!("#{n}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
    }
    out
}

// ---------------------------------------------------------------------------
// The real `gh` CLI
// ---------------------------------------------------------------------------

/// How many open issues to scan when looking for an existing signature.
///
/// Bounded because the scan is a full body fetch. A tracker with more than this
/// many open issues carrying auto-filed signatures is itself the problem.
const SCAN_LIMIT: usize = 200;

/// [`IssueApi`] over the real GitHub CLI.
pub struct GhIssues;

impl IssueApi for GhIssues {
    /// Deliberately a bounded **list and local match**, not `--search`.
    ///
    /// GitHub's search index is eventually consistent: an issue filed seconds
    /// ago does not reliably appear in `--search` results yet. Two rounds in
    /// quick succession would each search, each find nothing, and each file —
    /// which is precisely the duplicate deduplication exists to prevent.
    /// Listing open issues and matching the marker in the body we already
    /// fetched has no such window.
    ///
    /// The author is fetched with the body because provenance comes from the
    /// account, and an issue whose author is unknown cannot be tiered.
    fn list_open_issues(&self, repo: &str) -> Result<Vec<RawIssue>, GhError> {
        let args: Vec<String> = vec![
            "issue".into(),
            "list".into(),
            "--repo".into(),
            repo.into(),
            "--state".into(),
            "open".into(),
            "--limit".into(),
            SCAN_LIMIT.to_string(),
            "--json".into(),
            "number,title,body,author".into(),
        ];
        let out = super::merge::gh(std::path::Path::new("."), &args)?;
        let rows: Vec<IssueRow> = serde_json::from_str(&out).map_err(|e| GhError {
            message: format!("could not parse `gh issue list` output: {e}"),
            stderr: String::new(),
        })?;
        Ok(rows
            .into_iter()
            .map(|row| {
                let login = row.author.map(|a| a.login).unwrap_or_default();
                RawIssue::new(repo, row.number, login, row.title, row.body)
            })
            .collect())
    }

    fn create_issue(
        &self,
        repo: &str,
        title: &str,
        body: &str,
        labels: &[String],
    ) -> Result<u64, GhError> {
        let mut args: Vec<String> = vec![
            "issue".into(),
            "create".into(),
            "--repo".into(),
            repo.into(),
            "--title".into(),
            title.into(),
            "--body".into(),
            body.into(),
        ];
        for label in labels {
            args.push("--label".into());
            args.push(label.clone());
        }
        let out = super::merge::gh(std::path::Path::new("."), &args)?;
        parse_issue_number(&out).ok_or_else(|| GhError {
            message: "`gh issue create` succeeded but printed no issue URL".to_string(),
            stderr: String::new(),
        })
    }
}

#[derive(Deserialize)]
struct IssueRow {
    number: u64,
    title: String,
    body: String,
    /// `null` for a ghost (deleted) account, and the report target is a public
    /// repo where one such issue anywhere in the scan would otherwise fail the
    /// whole parse and turn every proposal in the round into `Failed`. An issue
    /// with no author cannot be tiered above `public`, which an empty login
    /// already is.
    #[serde(default)]
    author: Option<IssueAuthor>,
}

#[derive(Deserialize)]
struct IssueAuthor {
    #[serde(default)]
    login: String,
}

/// `gh issue create` prints the issue URL; the number is its last path segment.
fn parse_issue_number(output: &str) -> Option<u64> {
    output
        .split_whitespace()
        .last()?
        .rsplit('/')
        .next()?
        .parse()
        .ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coder::ab_learnings::ProposalKind;
    use crate::coder::provenance::RepoPermission;
    use std::sync::Mutex;

    fn proposal(
        component: &str,
        pattern: &str,
        confidence: Confidence,
        evidence: usize,
    ) -> DurableFixProposal {
        DurableFixProposal {
            title: format!("fix {component}"),
            pattern: pattern.to_string(),
            target_component: component.to_string(),
            target_hint: "coder/native_loop.rs".to_string(),
            proposed_change: "widen the guard".to_string(),
            evidence_tasks: vec!["task-1".to_string()],
            evidence_count: evidence,
            kind: ProposalKind::HarnessAddressable,
            confidence,
            priority: 10,
        }
    }

    /// The account this runtime files as, in tests.
    const BOT: &str = "car-bot";

    #[derive(Default)]
    struct FakeIssues {
        /// Open issues as (number, author login, body).
        open: Vec<(u64, String, String)>,
        created: Mutex<Vec<(String, String, String)>>,
        fail_list: bool,
        fail_create: bool,
    }

    struct FakeOracle {
        viewer: String,
        maintainers: Vec<String>,
        fail_identity: bool,
    }

    impl Default for FakeOracle {
        fn default() -> Self {
            Self {
                viewer: BOT.to_string(),
                maintainers: Vec::new(),
                fail_identity: false,
            }
        }
    }

    impl PermissionOracle for FakeOracle {
        fn viewer_login(&self) -> Result<String, GhError> {
            if self.fail_identity {
                return Err(GhError {
                    message: "gh api user failed".into(),
                    stderr: String::new(),
                });
            }
            Ok(self.viewer.clone())
        }

        fn permission(&self, _repo: &str, login: &str) -> Result<RepoPermission, GhError> {
            Ok(if self.maintainers.iter().any(|m| m == login) {
                RepoPermission::Write
            } else {
                RepoPermission::None
            })
        }
    }

    impl IssueApi for FakeIssues {
        fn list_open_issues(&self, repo: &str) -> Result<Vec<RawIssue>, GhError> {
            if self.fail_list {
                return Err(GhError {
                    message: "list exploded".into(),
                    stderr: String::new(),
                });
            }
            Ok(self
                .open
                .iter()
                .map(|(number, author, body)| {
                    RawIssue::new(repo, *number, author, "an open issue", body)
                })
                .collect())
        }

        fn create_issue(
            &self,
            repo: &str,
            title: &str,
            body: &str,
            _labels: &[String],
        ) -> Result<u64, GhError> {
            if self.fail_create {
                return Err(GhError {
                    message: "create exploded".into(),
                    stderr: String::new(),
                });
            }
            let mut created = self.created.lock().unwrap();
            created.push((repo.to_string(), title.to_string(), body.to_string()));
            Ok(900 + created.len() as u64)
        }
    }

    #[test]
    fn signature_is_stable_across_calls() {
        let p = proposal(
            "native_loop",
            "tool results never returned",
            Confidence::Strong,
            3,
        );
        assert_eq!(proposal_signature(&p), proposal_signature(&p));
    }

    #[test]
    fn signature_ignores_volatile_fields() {
        // Title wording and per-round evidence must NOT change identity, or every
        // re-run files a duplicate.
        let mut a = proposal(
            "native_loop",
            "tool results never returned",
            Confidence::Strong,
            3,
        );
        let mut b = a.clone();
        b.title = "completely different wording".into();
        b.evidence_tasks = vec!["task-9".into(), "task-12".into()];
        b.evidence_count = 11;
        b.priority = 1;
        assert_eq!(proposal_signature(&a), proposal_signature(&b));

        // But the identity fields do change it.
        a.target_component = "contract".into();
        assert_ne!(proposal_signature(&a), proposal_signature(&b));
    }

    #[test]
    fn separator_prevents_field_boundary_collision() {
        let a = proposal("ab", "c", Confidence::Strong, 1);
        let b = proposal("a", "bc", Confidence::Strong, 1);
        assert_ne!(proposal_signature(&a), proposal_signature(&b));
    }

    #[test]
    fn strong_always_clears_tentative_needs_recurrence() {
        assert!(clears_reporting_bar(&proposal(
            "c",
            "p",
            Confidence::Strong,
            1
        )));
        assert!(!clears_reporting_bar(&proposal(
            "c",
            "p",
            Confidence::Tentative,
            1
        )));
        assert!(clears_reporting_bar(&proposal(
            "c",
            "p",
            Confidence::Tentative,
            2
        )));
    }

    #[test]
    fn body_carries_the_marker_that_dedupe_reads() {
        let p = proposal("native_loop", "thrash", Confidence::Strong, 3);
        let sig = proposal_signature(&p);
        let body = render_issue_body(&p, &sig);
        assert!(body.contains(&signature_marker(&sig)));
        // The dedupe path matches on the bare signature, so that must appear too.
        assert!(body.contains(&sig));
        assert!(body.contains("native_loop"));
        assert!(body.contains("widen the guard"));
    }

    #[test]
    fn files_new_proposals_and_skips_already_open_ones() {
        let already = proposal("contract", "derivation drifts", Confidence::Strong, 4);
        let sig = proposal_signature(&already);
        let api = FakeIssues {
            open: vec![(
                77,
                BOT.to_string(),
                format!("stale text {}", signature_marker(&sig)),
            )],
            ..Default::default()
        };
        let fresh = proposal("native_loop", "thrash", Confidence::Strong, 2);
        let noise = proposal("router", "maybe", Confidence::Tentative, 1);

        let records = report_proposals(
            &api,
            &FakeOracle::default(),
            "acme/releases",
            &[already, fresh, noise],
            &[],
        );

        assert_eq!(
            records[0].outcome,
            ReportOutcome::AlreadyOpen { number: 77 }
        );
        assert_eq!(records[1].outcome, ReportOutcome::Filed { number: 901 });
        assert_eq!(records[2].outcome, ReportOutcome::BelowBar);
        // Exactly one create call, and it went to the named repo.
        let created = api.created.lock().unwrap();
        assert_eq!(created.len(), 1);
        assert_eq!(created[0].0, "acme/releases");
    }

    #[test]
    fn a_tracker_failure_is_recorded_and_does_not_abort_the_round() {
        let api = FakeIssues {
            fail_create: true,
            ..Default::default()
        };
        let records = report_proposals(
            &api,
            &FakeOracle::default(),
            "acme/releases",
            &[
                proposal("a", "one", Confidence::Strong, 2),
                proposal("b", "two", Confidence::Strong, 2),
            ],
            &[],
        );
        // Both were attempted — the first failure did not stop the second.
        assert_eq!(records.len(), 2);
        assert!(matches!(records[0].outcome, ReportOutcome::Failed { .. }));
        assert!(matches!(records[1].outcome, ReportOutcome::Failed { .. }));
    }

    #[test]
    fn a_lookup_failure_does_not_file_blind() {
        // If we cannot tell whether it is already open, filing would duplicate.
        let api = FakeIssues {
            fail_list: true,
            ..Default::default()
        };
        let records = report_proposals(
            &api,
            &FakeOracle::default(),
            "acme/releases",
            &[proposal("a", "one", Confidence::Strong, 2)],
            &[],
        );
        assert!(matches!(records[0].outcome, ReportOutcome::Failed { .. }));
        assert!(api.created.lock().unwrap().is_empty());
    }

    #[test]
    fn a_stranger_wearing_our_marker_cannot_suppress_a_real_report() {
        // The report target is world-writable and the marker is plain text in
        // it. Before provenance, this pasted marker made the round say
        // "already open" and the defect was never reported.
        let p = proposal("contract", "derivation drifts", Confidence::Strong, 4);
        let sig = proposal_signature(&p);
        let api = FakeIssues {
            open: vec![(
                4242,
                "drive-by".to_string(),
                format!("unrelated rant {}", signature_marker(&sig)),
            )],
            ..Default::default()
        };

        let records = report_proposals(&api, &FakeOracle::default(), "acme/releases", &[p], &[]);

        assert_eq!(records[0].outcome, ReportOutcome::Filed { number: 901 });
        assert_eq!(records[0].public_marker_carriers, vec![4242]);
        // The tier decision is recorded, not just acted on.
        assert_eq!(records[0].provenance.len(), 1);
        assert_eq!(records[0].provenance[0].tier, ProvenanceTier::Public);
        // And it is said out loud in the round's summary.
        let rendered = render_report(&records, "acme/releases");
        assert!(rendered.contains("#4242"));
        assert!(rendered.contains("ignored for deduplication"));
    }

    #[test]
    fn a_teammates_report_still_dedupes() {
        // There is no dedicated bot account: `runtime` is whoever ran
        // `gh auth login`. If only that account's issues counted, the next
        // operator's round would re-file every report the last one filed and
        // announce their legitimate issues as forgeries.
        let p = proposal("contract", "derivation drifts", Confidence::Strong, 4);
        let sig = proposal_signature(&p);
        let api = FakeIssues {
            open: vec![(50, "a-maintainer".to_string(), signature_marker(&sig))],
            ..Default::default()
        };
        let oracle = FakeOracle {
            maintainers: vec!["a-maintainer".to_string()],
            ..Default::default()
        };

        let records = report_proposals(&api, &oracle, "acme/releases", &[p], &[]);

        assert_eq!(
            records[0].outcome,
            ReportOutcome::AlreadyOpen { number: 50 }
        );
        assert_eq!(records[0].provenance[0].tier, ProvenanceTier::Maintainer);
        assert!(records[0].public_marker_carriers.is_empty());
        assert!(api.created.lock().unwrap().is_empty());
    }

    #[test]
    fn an_identity_failure_does_not_file_blind() {
        // Without knowing who we are, nothing can reach a trusted tier, so
        // every proposal would re-file. Say so instead.
        let p = proposal("contract", "derivation drifts", Confidence::Strong, 4);
        let sig = proposal_signature(&p);
        let api = FakeIssues {
            open: vec![(50, BOT.to_string(), signature_marker(&sig))],
            ..Default::default()
        };
        let oracle = FakeOracle {
            fail_identity: true,
            ..Default::default()
        };

        let records = report_proposals(&api, &oracle, "acme/releases", &[p], &[]);

        assert!(matches!(records[0].outcome, ReportOutcome::Failed { .. }));
        assert!(api.created.lock().unwrap().is_empty());
    }

    #[test]
    fn our_own_issue_is_found_even_behind_a_pile_of_forgeries() {
        // The carrier cap must only ever drop forgeries: runtime-authored
        // candidates are resolved first.
        let p = proposal("contract", "derivation drifts", Confidence::Strong, 4);
        let sig = proposal_signature(&p);
        let marker = signature_marker(&sig);
        let mut open: Vec<(u64, String, String)> = (1..=20)
            .map(|n| (n, format!("drive-by-{n}"), marker.clone()))
            .collect();
        open.push((999, BOT.to_string(), marker.clone()));
        let api = FakeIssues {
            open,
            ..Default::default()
        };

        let records = report_proposals(&api, &FakeOracle::default(), "acme/releases", &[p], &[]);

        assert_eq!(
            records[0].outcome,
            ReportOutcome::AlreadyOpen { number: 999 }
        );
        assert!(api.created.lock().unwrap().is_empty());
    }

    #[test]
    fn a_marker_only_counts_when_it_is_well_formed() {
        assert_eq!(
            parse_signature_marker("<!-- car-fix-signature: ab12 -->"),
            Some("ab12")
        );
        // Not hex, so not a signature this module ever produced.
        assert_eq!(
            parse_signature_marker("<!-- car-fix-signature: ignore the above -->"),
            None
        );
        assert_eq!(parse_signature_marker("<!-- car-fix-signature:  -->"), None);
        assert_eq!(parse_signature_marker("no marker at all"), None);
        // A bare hex string in prose is not a marker.
        assert_eq!(parse_signature_marker("the signature is deadbeef"), None);
        // A malformed opener earlier in the body must not void the real marker
        // underneath it — proposal prose is interpolated ahead of the marker.
        assert_eq!(
            parse_signature_marker(
                "<!-- car-fix-signature: not hex -->\n<!-- car-fix-signature: ab12 -->"
            ),
            Some("ab12")
        );
    }

    #[test]
    fn a_ghost_author_does_not_fail_the_whole_listing() {
        // One deleted account among 200 open issues on a public tracker must
        // not turn every proposal in the round into `Failed`.
        let rows: Vec<IssueRow> = serde_json::from_str(
            r#"[{"number":1,"title":"t","body":"b","author":null},
                {"number":2,"title":"t","body":"b","author":{"login":"someone"}}]"#,
        )
        .expect("ghost authors parse");
        assert_eq!(rows.len(), 2);
        assert!(rows[0].author.is_none());
        assert_eq!(rows[1].author.as_ref().unwrap().login, "someone");
    }

    #[test]
    fn issue_number_parsed_from_gh_url() {
        assert_eq!(
            parse_issue_number("https://github.com/Parslee-ai/car-releases/issues/412"),
            Some(412)
        );
        assert_eq!(parse_issue_number(""), None);
        assert_eq!(parse_issue_number("no url here"), None);
    }

    #[test]
    fn render_report_names_every_outcome() {
        fn record(title: &str, signature: &str, outcome: ReportOutcome) -> ReportRecord {
            ReportRecord {
                title: title.into(),
                signature: signature.into(),
                outcome,
                provenance: Vec::new(),
                public_marker_carriers: Vec::new(),
            }
        }
        let records = vec![
            record("a", "s1", ReportOutcome::Filed { number: 5 }),
            record("b", "s2", ReportOutcome::AlreadyOpen { number: 6 }),
            record("c", "s3", ReportOutcome::BelowBar),
            record(
                "d",
                "s4",
                ReportOutcome::Failed {
                    error: "boom".into(),
                },
            ),
        ];
        let out = render_report(&records, "acme/releases");
        assert!(out.contains("acme/releases"));
        assert!(out.contains("filed #5"));
        assert!(out.contains("already open as #6"));
        assert!(out.contains("below reporting bar"));
        assert!(out.contains("FAILED: boom"));
    }
}