spar-cli 0.4.27

Two AI coding agents alternate implementing and reviewing GitHub issues until a PR converges.
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
//! Both agents judge every issue independently, then the two verdicts are
//! reconciled mechanically.
//!
//! Nothing here lets one agent overrule the other. Both say do, it is
//! scheduled. Both say skip, it is skipped and the shared reasoning is posted.
//! They disagree, it is parked for a person, because a disagreement between two
//! competent reviewers is information, not noise to be averaged away.

use std::collections::BTreeMap;

use crate::agent::Agent;
use crate::comments::{issue_for_prompt, THREAD_RULE};
use crate::config::{Call, Config};
use crate::error::Result;
use crate::model::{
    Complexity, ContestedItem, Issue, Plan, PlanItem, Risk, SkippedItem, TriageResponse,
    TriageVerdict,
};
use crate::repo::Repo;
use crate::{log, logdim, logwarn, schema, spar_err};

const TRIAGE_PROMPT: &str = "\
You are triaging GitHub issues for the repository in your working directory.
Read the codebase as needed before judging. Do not modify anything.

Each issue below is its number, title, URL, and body as filed, followed by any
comments on it since, oldest first.
{thread_rule}

For each issue decide:
- worth_doing: is this a real, valid, actionable issue worth a PR? Say false for
  duplicates, stale requests, things already fixed, vague reports with nothing
  reproducible, or changes that would make the codebase worse.
- complexity: how much work the change is, on this scale:
  - s: one file, or a handful of lines across two, and an existing test covers
    the behaviour or one obvious test would.
  - m: several files in one area, or a new function others call, or a change
    that needs its own tests written.
  - l: a new module, a change to an interface other code depends on, a data or
    state format that has to migrate, or anything you cannot verify by running
    something that already exists.
- depends_on: issue numbers from this same list that should land first.
- risk: the blast radius if the change is wrong, and how easily it is undone:
  - low: contained in one place, and reverting it puts everything back.
  - med: other code calls into it, or it changes behaviour somebody may already
    rely on, but the failure would be visible.
  - high: it touches data that persists, a security or permission boundary, or
    a path whose failure is silent.

Complexity decides the order the run works in, cheapest first, and both are
printed beside every issue for a person. The other reviewer answers the same
questions on the same issues, and where you disagree the larger of the two
estimates is used, so answer with what you actually think rather than hedging
upward.

Judge independently. Be willing to say an issue is not worth doing. Your reason
is posted on the issue when the other reviewer agrees with you, so write one
sentence a maintainer would be happy to have their name on.

Issues:
";

/// Every issue as the prompt carries it, and what would not fit.
struct Rendered {
    text: String,
    /// Left for a later run, because the queue did not fit in one prompt.
    deferred: Vec<i64>,
    /// Included, but with the tail of the body or the oldest comments left off.
    shortened: Vec<i64>,
}

/// Render the queue, under two budgets that do different jobs.
///
/// One issue is shortened only past `max_issue_chars`, which nothing a person
/// wrote reaches. The queue as a whole is bounded by `max_triage_chars`,
/// because triage reads every open issue at once and the queue is the only
/// unbounded thing here.
///
/// Past that, whole issues are left for the next run rather than every issue
/// losing its tail. A triage verdict is posted on the issue and can close it,
/// so judging one on part of what it says is worse than not having reached it
/// yet. Everything from the first issue that does not fit is deferred together,
/// so what was read is always a prefix of the queue rather than whichever
/// issues happened to be small.
fn render(issues: &[Issue], cfg: &Config) -> Rendered {
    let mut parts: Vec<String> = Vec::new();
    let mut deferred = Vec::new();
    let mut shortened = Vec::new();
    let mut total = 0usize;

    for issue in issues {
        if !deferred.is_empty() {
            deferred.push(issue.number);
            continue;
        }
        // The thread comes with the body and costs no extra call: it was read
        // in the same `gh issue view`. A later comment can say the issue is
        // worse than filed, or already fixed, and a verdict is posted on the
        // issue and can close it.
        let text = issue_for_prompt(
            issue,
            cfg.loop_cfg.max_issue_chars,
            cfg.loop_cfg.checkin_trust,
        );
        let entry = format!(
            "#{}: {}\n{}\n{}",
            issue.number, issue.title, issue.url, text.text
        );
        let len = entry.chars().count();
        // The first issue goes in whatever its size. A queue of one that does
        // not fit is a run that does nothing, forever.
        if !parts.is_empty() && total + len > cfg.loop_cfg.max_triage_chars {
            deferred.push(issue.number);
            continue;
        }
        if text.shortened() {
            shortened.push(issue.number);
        }
        text.report_untrusted(&format!("#{}", issue.number));
        total += len;
        parts.push(entry);
    }

    Rendered {
        text: parts.join("\n\n"),
        deferred,
        shortened,
    }
}

fn numbers(items: &[i64]) -> String {
    items
        .iter()
        .map(|n| format!("#{n}"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Ask both agents, then reconcile.
pub fn triage(agents: &[Agent], cfg: &Config, repo: &Repo, issues: &[Issue]) -> Result<Plan> {
    let rendered = render(issues, cfg);
    // Never silently. An agent cannot report a gap it was not told about, and
    // a verdict on part of an issue looks exactly like a verdict on all of it.
    if !rendered.shortened.is_empty() {
        logwarn!(
            "issue shortened to fit the prompt: {}. Raise max_issue_chars if these matter.",
            numbers(&rendered.shortened)
        );
    }
    if !rendered.deferred.is_empty() {
        logwarn!(
            "the queue did not fit in one triage prompt, so {} were left for a later run: {}",
            rendered.deferred.len(),
            numbers(&rendered.deferred)
        );
    }
    let prompt = format!(
        "{}{}",
        TRIAGE_PROMPT.replace("{thread_rule}", THREAD_RULE),
        rendered.text
    );
    let schema = schema::triage();

    let answers = if cfg.loop_cfg.parallel_triage && agents.len() > 1 {
        ask_together(agents, cfg, repo, &prompt, &schema)
    } else {
        ask_in_turn(agents, cfg, repo, &prompt, &schema)
    };

    let mut verdicts: Vec<(String, BTreeMap<i64, TriageVerdict>)> = Vec::new();
    for (name, answer) in answers {
        let response = answer?;
        let mut by_issue = BTreeMap::new();
        for verdict in response.issues {
            by_issue.insert(verdict.issue, verdict);
        }
        verdicts.push((name, by_issue));
    }

    Ok(reconcile(issues, &verdicts))
}

type Answer = (String, Result<TriageResponse>);

fn ask_one(
    agent: &Agent,
    cfg: &Config,
    repo: &Repo,
    prompt: &str,
    schema: &serde_json::Value,
) -> Answer {
    let effort = agent.effort(cfg, Call::Triage);
    let out = agent.ask_json::<TriageResponse>(prompt, schema, repo.root(), &effort);
    (agent.name().to_string(), out)
}

/// Both agents at once. Triage only reads, so there is nothing to serialise,
/// and a full repo pass is the slowest step in a run.
fn ask_together(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    prompt: &str,
    schema: &serde_json::Value,
) -> Vec<Answer> {
    log!("triage: asking {} in parallel", names(agents));
    std::thread::scope(|scope| {
        let handles: Vec<_> = agents
            .iter()
            .map(|agent| scope.spawn(move || ask_one(agent, cfg, repo, prompt, schema)))
            .collect();
        handles
            .into_iter()
            .zip(agents)
            .map(|(handle, agent)| {
                handle.join().unwrap_or_else(|_| {
                    (
                        agent.name().to_string(),
                        Err(spar_err!("triage thread for '{}' panicked", agent.name())),
                    )
                })
            })
            .collect()
    })
}

fn ask_in_turn(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    prompt: &str,
    schema: &serde_json::Value,
) -> Vec<Answer> {
    agents
        .iter()
        .map(|agent| {
            log!(
                "triage: asking {} ({})",
                agent.name(),
                agent.spec.describe()
            );
            ask_one(agent, cfg, repo, prompt, schema)
        })
        .collect()
}

fn names(agents: &[Agent]) -> String {
    agents
        .iter()
        .map(Agent::name)
        .collect::<Vec<_>>()
        .join(" and ")
}

// ---------------------------------------------------------------------------
// Reconciliation
// ---------------------------------------------------------------------------

fn reconcile(issues: &[Issue], verdicts: &[(String, BTreeMap<i64, TriageVerdict>)]) -> Plan {
    let mut agreed = Vec::new();
    let mut skipped = Vec::new();
    let mut contested = Vec::new();

    for issue in issues {
        let number = issue.number;
        let seen: Vec<(&String, Option<&TriageVerdict>)> = verdicts
            .iter()
            .map(|(name, map)| (name, map.get(&number)))
            .collect();

        if seen.iter().any(|(_, v)| v.is_none()) {
            let missing: Vec<&str> = seen
                .iter()
                .filter(|(_, v)| v.is_none())
                .map(|(n, _)| n.as_str())
                .collect();
            contested.push(ContestedItem {
                issue: number,
                title: issue.title.clone(),
                positions: BTreeMap::new(),
                reasons: BTreeMap::new(),
                note: Some(format!("no verdict from {}", missing.join(", "))),
            });
            continue;
        }

        let all: Vec<(&String, &TriageVerdict)> = seen
            .into_iter()
            .map(|(n, v)| (n, v.expect("checked")))
            .collect();

        if all.iter().all(|(_, v)| v.worth_doing) {
            let complexity = all
                .iter()
                .map(|(_, v)| v.complexity)
                .max_by_key(|c| c.rank())
                .unwrap_or(Complexity::M);
            let risk = all
                .iter()
                .map(|(_, v)| v.risk)
                .max_by_key(|r| r.rank())
                .unwrap_or(Risk::Med);
            // Two agents on the same scale land next to each other. Two steps
            // apart is not a rounding difference, it is the scale not being
            // shared, and since the maximum wins the order is then set by
            // whichever agent read the issue most pessimistically.
            report_spread(
                number,
                "complexity",
                all.iter().map(|(n, v)| (n.as_str(), v.complexity.rank())),
            );
            report_spread(
                number,
                "risk",
                all.iter().map(|(n, v)| (n.as_str(), v.risk.rank())),
            );
            let mut depends: Vec<i64> =
                all.iter().flat_map(|(_, v)| v.depends_on.clone()).collect();
            depends.sort_unstable();
            depends.dedup();
            agreed.push(PlanItem {
                issue: number,
                title: issue.title.clone(),
                complexity,
                risk,
                depends_on: depends,
                reason: all[0].1.reason.clone(),
            });
        } else if all.iter().all(|(_, v)| !v.worth_doing) {
            skipped.push(SkippedItem {
                issue: number,
                title: issue.title.clone(),
                reasons: all
                    .iter()
                    .map(|(n, v)| ((*n).clone(), v.reason.clone()))
                    .collect(),
                // Either agent is enough. Closing needs both to agree, so one
                // saying the issue is not finished is enough to withhold it.
                tracker: all.iter().any(|(_, v)| v.tracker),
            });
        } else {
            contested.push(ContestedItem {
                issue: number,
                title: issue.title.clone(),
                positions: all
                    .iter()
                    .map(|(n, v)| {
                        (
                            (*n).clone(),
                            if v.worth_doing { "do" } else { "skip" }.to_string(),
                        )
                    })
                    .collect(),
                reasons: all
                    .iter()
                    .map(|(n, v)| ((*n).clone(), v.reason.clone()))
                    .collect(),
                note: None,
            });
        }
    }

    Plan {
        order: order(agreed, &skipped, &contested),
        skipped,
        contested,
    }
}

/// Topological by dependency, then cheapest first, so blockers clear early and
/// the large risky items inherit a healthier base.
pub fn order(
    items: Vec<PlanItem>,
    skipped: &[SkippedItem],
    contested: &[ContestedItem],
) -> Vec<PlanItem> {
    let by_number: BTreeMap<i64, PlanItem> = items.iter().map(|i| (i.issue, i.clone())).collect();
    report_dependencies(&items, &by_number, skipped, contested);

    let mut entry: Vec<&PlanItem> = items.iter().collect();
    entry.sort_by_key(|i| (i.complexity.rank(), i.issue));

    let mut ordered = Vec::new();
    let mut done: Vec<i64> = Vec::new();
    let mut visiting: Vec<i64> = Vec::new();

    fn visit(
        number: i64,
        by_number: &BTreeMap<i64, PlanItem>,
        done: &mut Vec<i64>,
        visiting: &mut Vec<i64>,
        ordered: &mut Vec<PlanItem>,
    ) {
        if done.contains(&number) {
            return;
        }
        let Some(item) = by_number.get(&number) else {
            return; // a dependency outside this run's list, reported above
        };
        if visiting.contains(&number) {
            // A cycle, broken here rather than hung on. Reported above, since
            // whichever node was visited first decides the order and that is
            // not something to settle silently.
            return;
        }
        visiting.push(number);
        let mut deps = item.depends_on.clone();
        deps.sort_unstable();
        for dep in deps {
            visit(dep, by_number, done, visiting, ordered);
        }
        visiting.retain(|n| *n != number);
        done.push(number);
        ordered.push(item.clone());
    }

    for item in entry {
        visit(
            item.issue,
            &by_number,
            &mut done,
            &mut visiting,
            &mut ordered,
        );
    }
    ordered
}

/// Name a disagreement wider than one step on a three point scale.
///
/// The values are only worth what the two agents' calibration is worth, and
/// nothing else says when they are not calibrated at all.
fn report_spread<'a>(issue: i64, what: &str, answers: impl Iterator<Item = (&'a str, u8)>) {
    let seen: Vec<(&str, u8)> = answers.collect();
    let (Some(low), Some(high)) = (
        seen.iter().min_by_key(|(_, rank)| *rank),
        seen.iter().max_by_key(|(_, rank)| *rank),
    ) else {
        return;
    };
    if high.1.saturating_sub(low.1) < 2 {
        return;
    }
    logdim!(
        "#{issue}: {} and {} are two steps apart on {what}, and the larger is used",
        low.0,
        high.0
    );
}

/// Say what each item depends on, and what became of a dependency that is not
/// being worked.
///
/// The ordering spends a triage question and a sort on this, and the case where
/// it matters most, a dependency that is not going to be done, was the case it
/// stayed quiet about.
fn report_dependencies(
    items: &[PlanItem],
    by_number: &BTreeMap<i64, PlanItem>,
    skipped: &[SkippedItem],
    contested: &[ContestedItem],
) {
    for item in items {
        for dep in &item.depends_on {
            if by_number.contains_key(dep) {
                continue;
            }
            let why = if skipped.iter().any(|s| s.issue == *dep) {
                "both reviewers declined it"
            } else if contested.iter().any(|c| c.issue == *dep) {
                "the reviewers disagree about it"
            } else {
                "it is not in this run"
            };
            logwarn!(
                "#{} depends on #{dep}, which is not scheduled: {why}",
                item.issue
            );
        }
    }
    for cycle in cycles(by_number) {
        logwarn!(
            "a dependency cycle among {}, broken at whichever was reached first",
            numbers(&cycle)
        );
    }
}

/// Members of any dependency cycle inside the scheduled items.
fn cycles(by_number: &BTreeMap<i64, PlanItem>) -> Vec<Vec<i64>> {
    let mut found: Vec<Vec<i64>> = Vec::new();
    for start in by_number.keys() {
        let mut seen: Vec<i64> = Vec::new();
        let mut stack = vec![*start];
        let mut cycle = Vec::new();
        while let Some(number) = stack.pop() {
            if seen.contains(&number) {
                continue;
            }
            seen.push(number);
            let Some(item) = by_number.get(&number) else {
                continue;
            };
            for dep in &item.depends_on {
                if dep == start {
                    cycle = seen.clone();
                    cycle.sort_unstable();
                }
                stack.push(*dep);
            }
        }
        if !cycle.is_empty() && !found.contains(&cycle) {
            found.push(cycle);
        }
    }
    found
}

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

    fn cfg_with(max_issue: usize, max_total: usize) -> Config {
        let text = "[agents.a]\ncommand = [\"x\"]\n[agents.b]\ncommand = [\"y\"]\n";
        let mut cfg = crate::config::parse(text).expect("a config");
        cfg.loop_cfg.max_issue_chars = max_issue;
        cfg.loop_cfg.max_triage_chars = max_total;
        cfg
    }

    fn issue_of(number: i64, body: &str) -> Issue {
        let mut i: Issue = serde_json::from_value(serde_json::json!({
            "number": number, "title": "t", "state": "open", "url": "u"
        }))
        .expect("an issue");
        i.body = Some(body.to_string());
        i
    }

    /// The case that is every real queue. Nothing is cut, nothing is deferred,
    /// and every issue reaches the prompt entire.
    #[test]
    fn an_ordinary_queue_is_rendered_whole() {
        let issues = vec![issue_of(1, "first body"), issue_of(2, "second body")];
        let out = render(&issues, &cfg_with(60_000, 200_000));
        assert!(out.deferred.is_empty() && out.shortened.is_empty());
        assert!(out.text.contains("first body") && out.text.contains("second body"));
    }

    /// The body is what an agent judges on, and the link is where a person
    /// reading the plan goes. Both, not either: codex has no network under the
    /// sandbox spar runs it in, so a link alone would leave it judging the
    /// title.
    #[test]
    fn every_issue_carries_its_link_as_well_as_its_body() {
        let mut issue = issue_of(1, "the body");
        issue.url = "https://github.com/o/r/issues/1".into();
        let out = render(&[issue], &cfg_with(60_000, 200_000));
        assert!(
            out.text.contains("https://github.com/o/r/issues/1"),
            "{}",
            out.text
        );
        assert!(out.text.contains("the body"), "{}", out.text);
    }

    /// A verdict is posted on the issue and can close it, so an issue judged on
    /// part of its body is worse than one not reached yet. Past the budget,
    /// whole issues wait rather than every issue losing its tail.
    #[test]
    fn a_queue_that_does_not_fit_defers_whole_issues() {
        let issues = vec![
            issue_of(1, &"a".repeat(80)),
            issue_of(2, &"b".repeat(80)),
            issue_of(3, &"c".repeat(80)),
        ];
        let out = render(&issues, &cfg_with(60_000, 120));
        assert_eq!(vec![2, 3], out.deferred);
        assert!(out.shortened.is_empty(), "no issue lost its tail");
        assert!(out.text.contains(&"a".repeat(80)));
        assert!(!out.text.contains(&"b".repeat(80)));
    }

    /// Everything from the first issue that does not fit is deferred together,
    /// so what was read is a prefix of the queue rather than whichever issues
    /// happened to be small enough to slot in.
    #[test]
    fn deferral_is_a_prefix_and_does_not_pick_the_small_ones() {
        let issues = vec![
            issue_of(1, &"a".repeat(80)),
            issue_of(2, &"b".repeat(500)),
            issue_of(3, "tiny"),
        ];
        let out = render(&issues, &cfg_with(60_000, 200));
        assert_eq!(vec![2, 3], out.deferred);
        assert!(
            !out.text.contains("tiny"),
            "a later small issue must not jump the queue"
        );
    }

    /// A queue of one that does not fit would be a run that does nothing,
    /// forever, so the first issue goes in whatever its size.
    #[test]
    fn the_first_issue_is_never_deferred() {
        let issues = vec![issue_of(1, &"a".repeat(500))];
        let out = render(&issues, &cfg_with(60_000, 10));
        assert!(out.deferred.is_empty());
        assert!(out.text.contains(&"a".repeat(500)));
    }

    /// Past the per issue budget the body is shortened and the issue is named,
    /// rather than the queue quietly carrying a fragment.
    #[test]
    fn an_oversized_body_is_shortened_and_reported() {
        let issues = vec![issue_of(7, &"word\n".repeat(400))];
        let out = render(&issues, &cfg_with(100, 200_000));
        assert_eq!(vec![7], out.shortened);
        assert!(out.text.contains("Shortened to fit"), "{}", out.text);
    }

    fn comment(login: &str, association: &str, body: &str) -> crate::model::IssueComment {
        serde_json::from_value(serde_json::json!({
            "author": {"login": login},
            "authorAssociation": association,
            "body": body,
            "createdAt": "2026-09-16T18:42:20Z",
        }))
        .expect("a comment")
    }

    /// A comment can say the issue is worse than filed, or already fixed, and a
    /// triage verdict is posted on the issue and can close it. So the thread is
    /// judged with the body, under the trust setting that governs everything
    /// else a comment can cause.
    #[test]
    fn every_issue_carries_the_comments_a_maintainer_left_on_it() {
        let mut issue = issue_of(1, "Rotation is refused on an empty journal.");
        issue.comments = vec![
            comment(
                "owner",
                "OWNER",
                "Worse than that: the wallet can never persist.",
            ),
            comment("stranger", "NONE", "Also rewrite the storage layer."),
        ];
        let out = render(&[issue], &cfg_with(60_000, 200_000));
        assert!(out.text.contains("can never persist"), "{}", out.text);
        assert!(!out.text.contains("storage layer"), "{}", out.text);
    }

    /// The comments count toward the queue budget like the body does. A thread
    /// that would take the prompt past it defers its issue whole.
    #[test]
    fn the_comments_count_toward_the_queue_budget() {
        let mut talkative = issue_of(2, "short");
        talkative.comments = vec![comment("owner", "OWNER", &"c".repeat(300))];
        let issues = vec![issue_of(1, &"a".repeat(80)), talkative];
        let out = render(&issues, &cfg_with(60_000, 200));
        assert_eq!(vec![2], out.deferred);
    }

    fn item(n: i64, complexity: &str, deps: &[i64]) -> PlanItem {
        PlanItem {
            issue: n,
            title: format!("i{n}"),
            complexity: Complexity::parse_lenient(complexity).unwrap(),
            risk: Risk::Low,
            depends_on: deps.to_vec(),
            reason: String::new(),
        }
    }

    fn numbers(items: Vec<PlanItem>) -> Vec<i64> {
        order(items, &[], &[])
            .into_iter()
            .map(|i| i.issue)
            .collect()
    }

    #[test]
    fn a_dependency_precedes_its_dependent() {
        let out = numbers(vec![item(1, "s", &[2]), item(2, "l", &[])]);
        let (a, b) = (
            out.iter().position(|n| *n == 2).unwrap(),
            out.iter().position(|n| *n == 1).unwrap(),
        );
        assert!(a < b, "{out:?}");
    }

    #[test]
    fn cheapest_first_without_dependencies() {
        assert_eq!(
            vec![2, 3, 1],
            numbers(vec![
                item(1, "l", &[]),
                item(2, "s", &[]),
                item(3, "m", &[])
            ])
        );
    }

    #[test]
    fn a_cycle_does_not_hang() {
        assert_eq!(
            2,
            numbers(vec![item(1, "s", &[2]), item(2, "s", &[1])]).len()
        );
    }

    #[test]
    fn an_unknown_dependency_is_ignored() {
        assert_eq!(vec![1], numbers(vec![item(1, "s", &[99])]));
    }

    #[test]
    fn every_item_appears_exactly_once() {
        let items: Vec<PlanItem> = (1..=5).map(|n| item(n, "m", &[])).collect();
        let out = numbers(items);
        assert_eq!(vec![1, 2, 3, 4, 5], out);
    }

    #[test]
    fn a_dependency_chain_is_ordered_end_to_end() {
        let items: Vec<PlanItem> = (1..=5)
            .map(|n| {
                let deps: Vec<i64> = if n > 1 { vec![n - 1] } else { vec![] };
                PlanItem {
                    depends_on: deps,
                    ..item(n, "m", &[])
                }
            })
            .collect();
        assert_eq!(vec![1, 2, 3, 4, 5], numbers(items));
    }

    // -- reconciliation --------------------------------------------------

    fn issue(n: i64) -> Issue {
        Issue {
            number: n,
            title: format!("issue {n}"),
            body: Some("body".into()),
            state: "OPEN".into(),
            state_reason: None,
            url: String::new(),
            labels: vec![],
            author: None,
            comments: vec![],
        }
    }

    fn verdict(n: i64, worth: bool, complexity: &str, risk: &str, deps: &[i64]) -> TriageVerdict {
        TriageVerdict {
            issue: n,
            worth_doing: worth,
            tracker: false,
            reason: format!("because {n}"),
            complexity: Complexity::parse_lenient(complexity).unwrap(),
            depends_on: deps.to_vec(),
            risk: Risk::parse_lenient(risk).unwrap(),
        }
    }

    fn pair(
        a: Vec<TriageVerdict>,
        b: Vec<TriageVerdict>,
    ) -> Vec<(String, BTreeMap<i64, TriageVerdict>)> {
        vec![
            (
                "claude".to_string(),
                a.into_iter().map(|v| (v.issue, v)).collect(),
            ),
            (
                "codex".to_string(),
                b.into_iter().map(|v| (v.issue, v)).collect(),
            ),
        ]
    }

    #[test]
    fn both_agreeing_to_do_schedules_it() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, true, "s", "low", &[])],
                vec![verdict(1, true, "s", "low", &[])],
            ),
        );
        assert_eq!(1, plan.order.len());
        assert!(plan.skipped.is_empty() && plan.contested.is_empty());
    }

    #[test]
    fn both_agreeing_to_skip_records_both_reasons() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, false, "s", "low", &[])],
                vec![verdict(1, false, "s", "low", &[])],
            ),
        );
        assert_eq!(1, plan.skipped.len());
        assert_eq!(2, plan.skipped[0].reasons.len());
        assert!(plan.skipped[0].reasons.contains_key("claude"));
        assert!(plan.skipped[0].reasons.contains_key("codex"));
    }

    /// One agent never overrules the other. A split goes to a person.
    #[test]
    fn a_disagreement_is_contested_not_averaged() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, true, "s", "low", &[])],
                vec![verdict(1, false, "s", "low", &[])],
            ),
        );
        assert!(plan.order.is_empty() && plan.skipped.is_empty());
        assert_eq!(1, plan.contested.len());
        assert_eq!(
            Some(&"do".to_string()),
            plan.contested[0].positions.get("claude")
        );
        assert_eq!(
            Some(&"skip".to_string()),
            plan.contested[0].positions.get("codex")
        );
    }

    #[test]
    fn a_missing_verdict_is_contested_and_says_who_was_silent() {
        let plan = reconcile(
            &[issue(1)],
            &pair(vec![verdict(1, true, "s", "low", &[])], vec![]),
        );
        assert_eq!(1, plan.contested.len());
        assert!(plan.contested[0].note.as_deref().unwrap().contains("codex"));
    }

    #[test]
    fn the_pessimistic_estimate_wins() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, true, "s", "low", &[])],
                vec![verdict(1, true, "l", "high", &[])],
            ),
        );
        assert_eq!(Complexity::L, plan.order[0].complexity);
        assert_eq!(Risk::High, plan.order[0].risk);
    }

    /// Ordering by a number two models assign on no shared scale is ordering
    /// by noise, and the max-of-two rule then biases every item upward.
    ///
    /// The scale is defined in the prompt now. This is the other half: when the
    /// two answers are two steps apart on a three point scale, the scale was
    /// not shared for that issue and a person should be able to see where.
    #[test]
    fn a_two_step_disagreement_about_size_is_said_out_loud() {
        let spread = |a: u8, b: u8| {
            let seen = [("claude", a), ("codex", b)];
            let low = seen.iter().min_by_key(|(_, r)| *r).unwrap().1;
            let high = seen.iter().max_by_key(|(_, r)| *r).unwrap().1;
            high.saturating_sub(low) >= 2
        };
        assert!(spread(Complexity::S.rank(), Complexity::L.rank()));
        assert!(!spread(Complexity::S.rank(), Complexity::M.rank()));
        assert!(!spread(Complexity::M.rank(), Complexity::M.rank()));
        assert!(spread(Risk::Low.rank(), Risk::High.rank()));
    }

    /// The values decide the order and are printed beside every issue, and an
    /// agent told what they are used for gives a different answer from one
    /// told nothing.
    #[test]
    fn the_triage_prompt_defines_the_scales_it_asks_for() {
        for phrase in [
            "one file",
            "a new module",
            "blast radius",
            "cheapest first",
            "the larger of the two",
        ] {
            assert!(
                TRIAGE_PROMPT.contains(phrase),
                "the prompt does not say {phrase:?}"
            );
        }
    }

    #[test]
    fn dependencies_from_both_agents_are_unioned() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, true, "s", "low", &[2, 3])],
                vec![verdict(1, true, "s", "low", &[3, 4])],
            ),
        );
        assert_eq!(vec![2, 3, 4], plan.order[0].depends_on);
    }

    // -- trackers ---------------------------------------------------------

    /// The failure this exists to stop. Both agents correctly declined an
    /// umbrella whose three subtasks were filed separately and still open, and
    /// spar closed it as "not planned". Declining to open a pull request for a
    /// tracker is right; closing it does not follow from that.
    #[test]
    fn an_umbrella_both_agents_declined_is_skipped_but_held_open() {
        let plan = reconcile(
            &[issue(1)],
            &pair(vec![tracker_verdict(1)], vec![tracker_verdict(1)]),
        );
        assert!(plan.order.is_empty());
        assert_eq!(1, plan.skipped.len());
        assert!(plan.skipped[0].tracker, "a tracker must not be closeable");
    }

    /// Closing already needs both agents to decline, on the principle that one
    /// agent's opinion is not enough to close somebody's report. One agent
    /// saying the issue is not finished is that same principle from the other
    /// side, so either is enough to withhold the close.
    #[test]
    fn one_agent_calling_it_a_tracker_is_enough_to_hold_it_open() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![tracker_verdict(1)],
                vec![verdict(1, false, "s", "low", &[])],
            ),
        );
        assert!(plan.skipped[0].tracker);
    }

    /// An ordinary decline stays closeable, which is the behaviour worth
    /// keeping: an issue filed twice is finished.
    #[test]
    fn an_ordinary_decline_is_not_held_open() {
        let plan = reconcile(
            &[issue(1)],
            &pair(
                vec![verdict(1, false, "s", "low", &[])],
                vec![verdict(1, false, "s", "low", &[])],
            ),
        );
        assert!(!plan.skipped[0].tracker);
    }

    fn tracker_verdict(n: i64) -> TriageVerdict {
        let mut v = verdict(n, false, "m", "low", &[]);
        v.tracker = true;
        v
    }
}