amont-agent-process 2.47.0

amont-agent's work process: plan review, implementation review, preview approvals and provenance
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
//! `amont-agent plan-review record`: what each plan-review reviewer did,
//! kept so the panel can later be judged on its own record
//! (docs/plans/2026-10-11-plan-review-learns-model.md).
//!
//! The ledger is `<journal dir>/plan-review/outcomes.jsonl`, one JSON object
//! per completed reviewer, deduped by agent id. The plan body each round
//! reviewed is kept once under `plan-review/bodies/<sha>.md`, because the
//! plan file keeps changing and the ledger holds only the sha.

use std::collections::BTreeSet;
use std::ffi::OsString;
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use crate::plan_review::{self, Completed, AGENT_PREFIX};

pub const USAGE: &str = "\
usage: amont-agent plan-review record <plan.md> [--transcript <path>]
       amont-agent plan-review stats [--json] [--model <id>]

Append one row per completed plan-review reviewer of the plan to
~/.claude/amont-agent/plan-review/outcomes.jsonl, skipping agents already
recorded (by agent id), and save each reviewed plan body once under
plan-review/bodies/.

The reviewers come from the session transcript: --transcript, or else, of
the transcripts under ~/.claude/projects modified in the last 7 days that
reviewed this plan, the one that reviewed its current body, then the newest.

stdin: a JSON array of findings (empty stdin is `[]`):
  {\"role\": str, \"severity\": \"blocking\"|\"high\"|\"medium\"|\"low\",
   \"disposition\": \"accepted\"|\"rejected\"|\"decision\",
   \"section\": str (optional), \"area\": str (optional)}
They are attached to the rows written by this call for the highest round.

stats: one row per (role, model) of the plan-review and implementation-review
ledgers: reviews, findings by severity, accepted findings by severity (plan
review `accepted`, implementation review `fixed`) and accepted high-or-blocking
findings per review. A row with 20 or more reviews and under 0.05 accepted
high-or-blocking per review is marked `retire-candidate` (ADR-0042). --json
prints one array; --model keeps one model.

Exit 0 when the ledger is up to date, 1 when a reviewer has no agent id, no
transcript names the plan or the ledger cannot be written, 2 on a usage error
(including malformed findings).
";

const SCHEMA: &str = "amont-agent-review-outcome-v1";
pub(crate) const SEVERITIES: [&str; 4] = ["blocking", "high", "medium", "low"];
const DISPOSITIONS: [&str; 3] = ["accepted", "rejected", "decision"];
const WEEK: u64 = 7 * 86_400;
const BODY_TTL: u64 = 90 * 86_400;

/// Runs the verb and returns what it says on stdout, for `main` to print:
/// stdout is written only from there (`only_the_emitter_writes_to_stdout`).
pub fn run(args: &[OsString]) -> (String, ExitCode) {
    let args: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return (USAGE.to_string(), ExitCode::SUCCESS);
    }
    let usage = |why: &str| {
        eprint!("amont-agent: {why}\n\n{USAGE}");
        (String::new(), ExitCode::from(2))
    };
    let mut it = args.iter();
    match it.next().map(String::as_str) {
        Some("record") => {}
        Some("stats") => return run_stats(&args[1..]),
        _ => return usage("plan-review takes one verb: record or stats"),
    }
    let mut plan: Option<&String> = None;
    // The last `--transcript` wins, in either form.
    let mut transcript: Option<String> = None;
    let mut operands_only = false;
    while let Some(a) = it.next() {
        if !operands_only && a == "--" {
            operands_only = true;
        } else if !operands_only && a == "--transcript" {
            let Some(v) = it.next() else {
                return usage("--transcript needs a path");
            };
            transcript = Some(v.clone());
        } else if let Some(v) = a.strip_prefix("--transcript=").filter(|_| !operands_only) {
            transcript = Some(v.to_string());
        } else if (!operands_only && a.starts_with('-') && a != "-") || plan.is_some() {
            return usage(&format!("unexpected argument `{a}`"));
        } else {
            plan = Some(a);
        }
    }
    let Some(plan) = plan else {
        return usage("record needs a plan file");
    };
    let mut stdin = String::new();
    if let Err(e) = std::io::stdin().read_to_string(&mut stdin) {
        return usage(&format!("stdin cannot be read: {e}"));
    }
    let findings = match parse_findings(&stdin) {
        Ok(f) => f,
        Err(why) => return usage(&why),
    };
    match record(Path::new(plan), transcript.map(PathBuf::from), &findings) {
        // A status line, not data: stderr (cli.basics.stdout-is-data-stderr-is-talk).
        Ok((said, code)) => {
            eprint!("{said}");
            (String::new(), ExitCode::from(code))
        }
        Err(why) => {
            eprintln!("amont-agent: {why}");
            (String::new(), ExitCode::from(1))
        }
    }
}

/// The findings on stdin, checked: an unknown severity would poison every
/// later aggregate, so it is refused here rather than stored.
fn parse_findings(text: &str) -> Result<Vec<serde_json::Value>, String> {
    if text.trim().is_empty() {
        return Ok(Vec::new());
    }
    let v: serde_json::Value =
        serde_json::from_str(text).map_err(|e| format!("stdin is not JSON: {e}"))?;
    let Some(list) = v.as_array() else {
        return Err("stdin must be a JSON array of findings".into());
    };
    for (i, f) in list.iter().enumerate() {
        let s = |k: &str| f.get(k).and_then(|v| v.as_str());
        if s("role").is_none() {
            return Err(format!("finding {i}: `role` must be a string"));
        }
        for (key, allowed) in [
            ("severity", &SEVERITIES[..]),
            ("disposition", &DISPOSITIONS[..]),
        ] {
            match s(key) {
                Some(v) if allowed.contains(&v) => {}
                other => {
                    return Err(format!(
                        "finding {i}: unknown {key} {}; one of {}",
                        other.unwrap_or("(missing)"),
                        allowed.join("|")
                    ))
                }
            }
        }
        for key in ["section", "area"] {
            if f.get(key).is_some_and(|v| !v.is_string() && !v.is_null()) {
                return Err(format!("finding {i}: `{key}` must be a string"));
            }
        }
    }
    Ok(list.clone())
}

/// One completed reviewer of the plan, with the body it reviewed.
pub(crate) struct Launch {
    pub(crate) role: String,
    pub(crate) sha: String,
    pub(crate) done: Completed,
}

/// The completed launches of `transcript` that reviewed `plan`, in launch
/// order, one per agent: a launch whose prompt carries several blocks for
/// the plan is one reviewer.
fn launches(transcript: &Path, plan: &str) -> std::io::Result<Vec<Launch>> {
    collect(transcript, plan, plan_review::completed_agents)
}

/// [`launches`], with the rounds a reviewer was resumed for by `SendMessage`
/// counted as launches of their own: `plan-apply` reads a round-2 reviewer's
/// patches from its resume.
pub(crate) fn launches_resumable(transcript: &Path, plan: &str) -> std::io::Result<Vec<Launch>> {
    collect(transcript, plan, |r, p| {
        plan_review::completed_agents_resumable(r, p)
    })
}

type Reader = fn(BufReader<std::fs::File>, &str) -> Vec<Completed>;

fn collect(transcript: &Path, plan: &str, completed: Reader) -> std::io::Result<Vec<Launch>> {
    let reader = BufReader::new(std::fs::File::open(transcript)?);
    let mut out = Vec::new();
    for done in completed(reader, AGENT_PREFIX) {
        let found = plan_review::parse_blocks(&done.agent, &done.prompt)
            .into_iter()
            .find(|b| b.path == plan);
        if let Some(b) = found {
            out.push(Launch {
                role: b.role,
                sha: b.sha,
                done,
            });
        }
    }
    Ok(out)
}

/// The transcript to read when none is named: of those touched in the last
/// week that reviewed this plan, the one that reviewed its CURRENT body,
/// then the most recently written. The body comes first because a
/// long-lived session still being appended to can have reviewed an older
/// body days ago; its mtime says nothing about when the review ran.
pub(crate) fn discover(
    plan: &str,
    current: &str,
    load: fn(&Path, &str) -> std::io::Result<Vec<Launch>>,
) -> Option<(PathBuf, Vec<Launch>)> {
    let projects = amont_agent_guard::settings::config_dir()?.join("projects");
    let now = std::time::SystemTime::now();
    let mut best: Option<((bool, std::time::SystemTime), PathBuf, Vec<Launch>)> = None;
    let dirs = match std::fs::read_dir(&projects) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("amont-agent: cannot read {}: {e}", projects.display());
            return None;
        }
    };
    for dir in dirs.flatten() {
        let files = match std::fs::read_dir(dir.path()) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("amont-agent: skipped {}: {e}", dir.path().display());
                continue;
            }
        };
        for f in files.flatten() {
            let path = f.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            let Some(modified) = f.metadata().ok().and_then(|m| m.modified().ok()) else {
                continue;
            };
            let age = now.duration_since(modified).map_or(0, |d| d.as_secs());
            // Nothing can outrank a best that reviewed the current body and
            // is newer: skip the read.
            if age > WEEK
                || best
                    .as_ref()
                    .is_some_and(|(k, _, _)| *k >= (true, modified))
            {
                continue;
            }
            let found = match load(&path, plan) {
                Ok(f) => Ok(f),
                Err(e) => {
                    eprintln!("amont-agent: skipped {}: {e}", path.display());
                    Err(e)
                }
            };
            if let Ok(found) = found {
                let key = (found.iter().any(|l| l.sha == current), modified);
                if !found.is_empty() && best.as_ref().is_none_or(|(k, _, _)| key > *k) {
                    best = Some((key, path, found));
                }
            }
        }
    }
    best.map(|(_, p, l)| (p, l))
}

/// The verdict a reviewer closed with: the first of the three words after
/// `Verdict`. `approve-with-changes` is tried before `approve`, which it
/// starts with.
fn verdict(result: &str) -> Option<&'static str> {
    let lower = result.to_lowercase();
    let after = &lower[lower.find("verdict")? + "verdict".len()..];
    (0..after.len())
        .filter(|&i| after.is_char_boundary(i))
        .find_map(|i| {
            ["rework", "approve-with-changes", "approve"]
                .into_iter()
                .find(|w| after[i..].starts_with(w))
        })
}

pub(crate) fn now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn json_list<'a>(items: impl IntoIterator<Item = &'a String>) -> serde_json::Value {
    serde_json::Value::Array(items.into_iter().map(|s| s.as_str().into()).collect())
}

/// An exclusive lock on the ledger's lock file, held until dropped. Two
/// `record` calls on one transcript would otherwise both read "not yet
/// recorded" and append the same reviewers twice.
pub(crate) struct Lock {
    _held: std::fs::File,
}

#[cfg(unix)]
pub(crate) fn lock(path: &Path) -> std::io::Result<Lock> {
    use std::os::unix::fs::OpenOptionsExt;
    use std::os::unix::io::AsRawFd;
    extern "C" {
        fn flock(fd: i32, op: i32) -> i32;
    }
    const LOCK_EX: i32 = 2;
    let f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .open(path)?;
    amont_agent_guard::journal::private(path, 0o600);
    if unsafe { flock(f.as_raw_fd(), LOCK_EX) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(Lock { _held: f })
}

// holds-until: two `record` calls run at once on Windows. No lock is taken
// there: `File::lock` needs Rust 1.89, above the 1.85 floor, and plan
// reviews run on unix machines. Ends when the floor reaches 1.89.
#[cfg(not(unix))]
pub(crate) fn lock(path: &Path) -> std::io::Result<Lock> {
    let f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    Ok(Lock { _held: f })
}

/// Options for a file only its owner reads: the ledger and the bodies hold
/// what reviewers said about private plans.
pub(crate) fn private_options() -> std::fs::OpenOptions {
    let o = std::fs::OpenOptions::new();
    #[cfg(unix)]
    let o = {
        use std::os::unix::fs::OpenOptionsExt;
        let mut o = o;
        o.mode(0o600);
        o
    };
    o
}

/// The ledger, opened for appending; created when missing.
pub(crate) fn open_ledger(path: &Path) -> std::io::Result<std::fs::File> {
    let f = private_options().append(true).create(true).open(path)?;
    amont_agent_guard::journal::private(path, 0o600);
    Ok(f)
}

/// A saved body, created once: `AlreadyExists` when an earlier call wrote it.
fn create_body(path: &Path) -> std::io::Result<std::fs::File> {
    private_options().write(true).create_new(true).open(path)
}

/// The rows of a ledger, in file order; a missing file is no rows. A torn
/// line (a crash mid-append) is skipped, not fatal. The one reader of every
/// outcomes ledger.
pub fn read_rows(path: &Path) -> std::io::Result<Vec<serde_json::Value>> {
    let text = match std::fs::read(path) {
        Ok(b) => String::from_utf8_lossy(&b).into_owned(),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };
    Ok(text
        .lines()
        .filter_map(|l| serde_json::from_str(l).ok())
        .collect())
}

/// What the ledger already holds: the review agent ids on record, and the round-1
/// body an earlier call recorded for `plan`, if any. A torn line (a crash
/// mid-append) is skipped, not fatal.
fn recorded(path: &Path, plan: &str) -> std::io::Result<(BTreeSet<String>, Option<String>)> {
    let rows = read_rows(path)?;
    // Only review rows: a merge row (`plan-apply`) has an `agent_id` too, and
    // must not make a reviewer look recorded.
    let ids = rows
        .iter()
        .filter(|v| v.get("schema").and_then(|s| s.as_str()) == Some(SCHEMA))
        .filter_map(|v| v.get("agent_id")?.as_str().map(str::to_string))
        .collect();
    let first = rows
        .iter()
        .filter(|v| v.get("plan_path").and_then(|p| p.as_str()) == Some(plan))
        .find_map(|v| v.get("first_round_sha")?.as_str().map(str::to_string));
    Ok((ids, first))
}

fn record(
    plan: &Path,
    transcript: Option<PathBuf>,
    findings: &[serde_json::Value],
) -> Result<(String, u8), String> {
    let text = std::fs::read_to_string(plan)
        .map_err(|e| format!("cannot read {}: {e}", plan.display()))?;
    let real = plan_review::real(plan);
    let real = real.to_string_lossy().into_owned();
    let plan_sha = crate::plan_text::body_sha(&text);
    let (transcript, found) = match transcript {
        Some(t) => {
            let l = launches(&t, &real)
                .map_err(|e| format!("cannot read transcript {}: {e}", t.display()))?;
            (t, l)
        }
        None => discover(&real, &plan_sha, launches).ok_or_else(|| {
            format!(
                "no transcript from the last 7 days has a completed plan-review of {real}; name one with --transcript"
            )
        })?,
    };
    if found.is_empty() {
        return Err(format!(
            "{} has no completed plan-review of {real}",
            transcript.display()
        ));
    }
    // A round is a body: numbered in the order bodies first appear.
    let mut shas: Vec<&str> = Vec::new();
    for l in &found {
        if !shas.contains(&l.sha.as_str()) {
            shas.push(&l.sha);
        }
    }
    let round_of = |sha: &str| shas.iter().position(|s| *s == sha).map_or(0, |i| i + 1);
    let top = shas.len();

    let io = |what: &str| {
        let what = what.to_string();
        move |e: std::io::Error| format!("{what}: {e}")
    };
    let store = amont_agent_guard::journal::dir()
        .ok_or("no home directory, so the ledger cannot be located")?
        .join("plan-review");
    let bodies = store.join("bodies");
    plan_review::private_dir(&store)
        .and_then(|()| plan_review::private_dir(&bodies))
        .ok_or_else(|| format!("cannot create {}", bodies.display()))?;
    let ledger = store.join("outcomes.jsonl");
    let _lock = lock(&store.join("outcomes.jsonl.lock")).map_err(io("cannot lock the ledger"))?;
    let (mut seen, first_on_record) =
        recorded(&ledger, &real).map_err(io(&format!("cannot read {}", ledger.display())))?;
    // Round 1 is the first body the LEDGER saw for this plan, so a review
    // that spans sessions keeps one round-1 body to diff against.
    // holds-until: `round` is still counted within this transcript; a plan
    // reviewed across sessions gets a second round 1 until rounds are
    // numbered from the ledger too.
    let first_round_sha = first_on_record.unwrap_or_else(|| shas[0].to_string());

    // A row describes the body its reviewer read: the current file when it
    // is that body, else the copy an earlier call saved. A body that was
    // never saved records null, not a guess from another body.
    let features = |sha: &str| {
        let saved = (plan_sha != sha)
            .then(|| {
                let file = bodies.join(format!("{sha}.md"));
                std::fs::read_to_string(&file)
                    .map_err(|e| {
                        if e.kind() != std::io::ErrorKind::NotFound {
                            eprintln!("amont-agent: cannot read {}: {e}", file.display());
                        }
                    })
                    .ok()
            })
            .flatten();
        let body = match &saved {
            Some(s) => s.as_str(),
            None if plan_sha == sha => text.as_str(),
            None => return serde_json::Value::Null,
        };
        let meta = plan_review::meta(body);
        serde_json::json!({
            "areas": meta.as_ref().ok().and_then(plan_review::areas_of).map(|a| json_list(&a)).unwrap_or_else(|| serde_json::json!([])),
            "repos": meta.as_ref().map(|m| json_list(&m.repos)).unwrap_or_else(|_| serde_json::json!([])),
            "body_lines": crate::plan_text::canonical(body).lines().count(),
        })
    };

    let at = now();
    let mut buffer = String::new();
    let mut written: BTreeSet<usize> = BTreeSet::new();
    let mut count = 0;
    // The findings on stdin are this call's merge: they belong to the
    // highest round it writes, which is not always the transcript's top.
    let attach_round = found
        .iter()
        .filter(|l| {
            l.done
                .agent_id
                .as_ref()
                .is_some_and(|id| !seen.contains(id))
        })
        .map(|l| round_of(&l.sha))
        .max();
    for l in &found {
        let Some(id) = l.done.agent_id.as_ref() else {
            continue;
        };
        if !seen.insert(id.clone()) {
            continue;
        }
        let round = round_of(&l.sha);
        let attach = Some(round) == attach_round;
        let mine: Vec<&serde_json::Value> = findings
            .iter()
            .filter(|f| attach && f.get("role").and_then(|r| r.as_str()) == Some(&l.role))
            .collect();
        let row = serde_json::json!({
            "schema": SCHEMA,
            "recorded_at": at,
            "role": l.role,
            "agent_id": id,
            "model": l.done.model,
            "tokens": l.done.tokens,
            "seconds": l.done.duration_ms.map(|ms| ms as f64 / 1000.0),
            "round": round,
            "body_sha": l.sha,
            "first_round_sha": first_round_sha,
            "plan_path": real,
            "plan": features(&l.sha),
            "verdict": verdict(&l.done.result),
            "remit": json_list(&plan_review::remit(&l.role)),
            "findings": mine,
        });
        buffer.push_str(&row.to_string());
        buffer.push('\n');
        written.insert(round);
        count += 1;
    }
    if count > 0 {
        let mut f =
            open_ledger(&ledger).map_err(io(&format!("cannot open {}", ledger.display())))?;
        f.write_all(buffer.as_bytes())
            .and_then(|()| f.flush())
            .map_err(io(&format!("cannot write {}", ledger.display())))?;
    }

    for &round in &written {
        let sha = shas[round - 1];
        if plan_sha != sha {
            eprintln!("body of round {round} not saved: the plan changed since it was reviewed");
            continue;
        }
        match create_body(&bodies.join(format!("{sha}.md"))) {
            Ok(mut f) => {
                f.write_all(text.as_bytes())
                    .map_err(io("cannot save the plan body"))?;
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(e) => return Err(format!("cannot save the plan body: {e}")),
        }
    }
    prune(&bodies);

    // Reported after the write: the rows that resolved are already safe.
    let mut missing = false;
    for l in found.iter().filter(|l| l.done.agent_id.is_none()) {
        eprintln!(
            "amont-agent: no agent id for {} in {}",
            l.role,
            transcript.display()
        );
        missing = true;
    }

    let (round, sha) = match written.iter().next_back() {
        Some(&r) => (r, shas[r - 1]),
        None => (top, shas[top - 1]),
    };
    let said = if count > 0 {
        format!("wrote {count} rows (round {round}, plan {})\n", &sha[..12])
    } else if missing {
        format!("no rows written for round {round} of {}\n", &sha[..12])
    } else {
        format!(
            "already recorded round {round} of {}; nothing written\n",
            &sha[..12]
        )
    };
    Ok((said, u8::from(missing)))
}

/// Saved bodies are for looking back at a recent review, not an archive.
/// A failure is said on stderr and never fails the call: the rows are
/// already written, and a body left over is harmless.
fn prune(dir: &Path) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(e) => {
            eprintln!("amont-agent: bodies in {} not pruned: {e}", dir.display());
            return;
        }
    };
    let now = std::time::SystemTime::now();
    for e in entries.flatten() {
        let old = e
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| now.duration_since(t).ok())
            .is_some_and(|d| d.as_secs() > BODY_TTL);
        if old {
            if let Err(why) = std::fs::remove_file(e.path()) {
                eprintln!("amont-agent: body {} not pruned: {why}", e.path().display());
            }
        }
    }
}

pub(crate) const IMPL_SCHEMA: &str = "amont-agent-impl-review-outcome-v1";
const IMPL_ROLE: &str = "implementation-review";
const RETIRE_MIN_REVIEWS: u64 = 20;
const RETIRE_BELOW: f64 = 0.05;

/// One (role, model) line of `plan-review stats`.
#[derive(Default, Debug, PartialEq)]
pub struct Stat {
    pub reviews: u64,
    pub found: [u64; 4],
    pub accepted: [u64; 4],
}

impl Stat {
    /// Accepted blocking and high findings per review.
    pub fn serious_per_review(&self) -> f64 {
        if self.reviews == 0 {
            return 0.0;
        }
        (self.accepted[0] + self.accepted[1]) as f64 / self.reviews as f64
    }

    pub fn retire_candidate(&self) -> bool {
        self.reviews >= RETIRE_MIN_REVIEWS && self.serious_per_review() < RETIRE_BELOW
    }
}

/// The rows of both ledgers folded to one [`Stat`] per (role, model), in key
/// order. Rows of another schema (merge rows) are not reviews.
pub fn tally(rows: &[serde_json::Value]) -> std::collections::BTreeMap<(String, String), Stat> {
    let mut out: std::collections::BTreeMap<(String, String), Stat> = Default::default();
    for r in rows {
        let text = |k: &str| r.get(k).and_then(|v| v.as_str()).unwrap_or("");
        let (role, accepted_word) = match text("schema") {
            SCHEMA => (text("role").to_string(), "accepted"),
            IMPL_SCHEMA => (IMPL_ROLE.to_string(), "fixed"),
            _ => continue,
        };
        let stat = out.entry((role, text("model").to_string())).or_default();
        stat.reviews += 1;
        let list = r.get("findings").and_then(|f| f.as_array());
        for f in list.into_iter().flatten() {
            let Some(i) = f
                .get("severity")
                .and_then(|s| s.as_str())
                .and_then(|s| SEVERITIES.iter().position(|x| *x == s))
            else {
                continue;
            };
            stat.found[i] += 1;
            if f.get("disposition").and_then(|d| d.as_str()) == Some(accepted_word) {
                stat.accepted[i] += 1;
            }
        }
    }
    out
}

/// How `plan-review stats` prints.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Text,
    Json,
}

/// `plan-review stats`: what the panel's seats caught, per role and model.
pub fn stats_report(rows: &[serde_json::Value], model: Option<&str>, format: Format) -> String {
    let tallied = tally(rows);
    let shown: Vec<_> = tallied
        .iter()
        .filter(|((_, m), _)| model.is_none_or(|want| want == m))
        .collect();
    if format == Format::Json {
        let list: Vec<serde_json::Value> = shown
            .iter()
            .map(|((role, model), s)| {
                let by = |a: &[u64; 4]| {
                    serde_json::json!({
                        "blocking": a[0], "high": a[1], "medium": a[2], "low": a[3]
                    })
                };
                serde_json::json!({
                    "role": role,
                    "model": model,
                    "reviews": s.reviews,
                    "findings": by(&s.found),
                    "accepted": by(&s.accepted),
                    "accepted_high_or_blocking_per_review": s.serious_per_review(),
                    "retire_candidate": s.retire_candidate(),
                })
            })
            .collect();
        return format!("{}\n", serde_json::Value::Array(list));
    }
    let mut out = String::new();
    for ((role, model), s) in shown {
        let model = if model.is_empty() { "-" } else { model };
        let sev = |a: &[u64; 4]| format!("{}/{}/{}/{}", a[0], a[1], a[2], a[3]);
        out.push_str(&format!(
            "{role}\t{model}\treviews={}\tfound={}\taccepted={}\tserious/review={:.2}{}\n",
            s.reviews,
            sev(&s.found),
            sev(&s.accepted),
            s.serious_per_review(),
            if s.retire_candidate() {
                "\tretire-candidate"
            } else {
                ""
            }
        ));
    }
    out
}

/// The ledgers' path under the journal directory, for `store`.
fn ledger_path(store: &str) -> Result<PathBuf, String> {
    Ok(amont_agent_guard::journal::dir()
        .ok_or("no home directory, so the ledger cannot be located")?
        .join(store)
        .join("outcomes.jsonl"))
}

fn run_stats(args: &[String]) -> (String, ExitCode) {
    let usage = |why: &str| {
        eprint!("amont-agent: {why}\n\n{USAGE}");
        (String::new(), ExitCode::from(2))
    };
    let (mut json, mut model) = (false, None::<String>);
    let mut it = args.iter();
    while let Some(a) = it.next() {
        if a == "--json" {
            json = true;
        } else if a == "--model" {
            let Some(v) = it.next() else {
                return usage("--model needs a model id");
            };
            model = Some(v.clone());
        } else if let Some(v) = a.strip_prefix("--model=") {
            model = Some(v.to_string());
        } else {
            return usage(&format!("unexpected argument `{a}`"));
        }
    }
    let mut rows = Vec::new();
    for store in ["plan-review", crate::impl_review_outcomes::STORE] {
        let read = ledger_path(store)
            .and_then(|p| read_rows(&p).map_err(|e| format!("cannot read {}: {e}", p.display())));
        match read {
            Ok(mut r) => rows.append(&mut r),
            Err(why) => {
                eprintln!("amont-agent: {why}");
                return (String::new(), ExitCode::from(1));
            }
        }
    }
    (
        stats_report(
            &rows,
            model.as_deref(),
            if json { Format::Json } else { Format::Text },
        ),
        ExitCode::SUCCESS,
    )
}