loopflow 0.12.1

Run steps and flows with coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
//! `lf doctor` — the ledger reports on itself.
//!
//! Every wave question is a query against the run ledger, so a ledger that is
//! wrong, deaf, or ambiguous makes every downstream answer confidently wrong.
//! These checks exist because each one failed silently at least once: a schema
//! drift dropped 29 hours of writes while `debug!` swallowed the error, a
//! column rename left `node='step'` and `node='skill'` meaning the same thing,
//! and the old process-grained run view once spliced one process's label onto
//! another's cost.
//!
//! Checks are pure functions of the rows, so they are tested without a store.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::Path;

use anyhow::{anyhow, Result};
use time::{Duration, OffsetDateTime};

use crate::lf::output::Colors;
use crate::receipt::{EvidenceKind, PrIdentity, PrReference, Receipt};
use crate::store::RunEventRow;
use crate::wave::journal::{fold_thread, journal_path, memory_facts, read_events};

/// A node value the current binary understands. `step` is the pre-054 spelling
/// of `skill`; rows carrying it are history the readers silently drop.
const NODES: [&str; 3] = ["run", "flow", "skill"];
const EVENTS: [&str; 4] = ["started", "completed", "errored", "escalated"];

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Status {
    Ok,
    Warn,
    Fail,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Check {
    pub name: &'static str,
    pub status: Status,
    pub detail: String,
}

impl Check {
    fn ok(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status: Status::Ok,
            detail: detail.into(),
        }
    }
    fn warn(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status: Status::Warn,
            detail: detail.into(),
        }
    }
    fn fail(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            status: Status::Fail,
            detail: detail.into(),
        }
    }
}

/// Exits non-zero when any check fails, so a cron can gate on it.
#[derive(Debug, serde::Serialize)]
struct DoctorReport<'a> {
    store: StoreReport,
    rows: usize,
    checks: &'a [Check],
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
struct StoreReport {
    build_provenance: crate::build_info::BuildProvenance,
    migration_authority: String,
    build_source_identity: String,
    build_source_root: Option<String>,
    build_source_revision: String,
    database_path: String,
    latest_known_migration: String,
    latest_applied_migration: Option<String>,
    migration_error: Option<String>,
}

pub fn run(json: bool) -> Result<()> {
    let database_path = crate::store::database_path_from_env()?;
    let opened = crate::store::sqlite::SqliteStore::new(&database_path);
    let mut store_report = inspect_store(&database_path);
    let (events, mut checks) = match opened {
        Ok(store) => {
            let events = store.list_run_events_since(0)?;
            let mut checks = audit(&events);
            checks.push(check_capture(&store, &events)?);
            checks.push(check_usage_coverage(&store)?);
            let (facts, known) = gather_receipt_audit(&store, &events);
            checks.push(check_receipts(&facts, &known));
            (events, checks)
        }
        Err(error) => {
            let detail = error.to_string();
            store_report.migration_error = Some(detail.clone());
            (Vec::new(), vec![Check::fail("store", detail)])
        }
    };
    // Binary freshness remains useful when the store cannot open.
    checks.push(check_binary_freshness());
    if json {
        println!(
            "{}",
            serde_json::to_string(&DoctorReport {
                store: store_report,
                rows: events.len(),
                checks: &checks,
            })?
        );
    } else {
        print_checks(&store_report, &checks, events.len());
    }

    if checks.iter().any(|check| check.status == Status::Fail) {
        return Err(anyhow!("run ledger audit failed"));
    }
    Ok(())
}

const FRESHNESS: &str = "binary-freshness";
const UPSTREAM: &str = "origin/main";
const UPSTREAM_REFSPEC: &str = "+refs/heads/main:refs/remotes/origin/main";

/// Report whether the running binary predates merged upstream work.
fn check_binary_freshness() -> Check {
    let revision = crate::build_info::source_revision();
    let Some(repo) = freshness_repo() else {
        return Check::warn(
            FRESHNESS,
            format!(
                "cannot compare build revision {}: no git checkout at this binary's source root \
                 or working directory. Run `lf doctor` from a loopflow checkout to learn whether \
                 the running binary is current",
                crate::build_info::short_revision(revision)
            ),
        );
    };

    if let Err(error) = crate::engine::git::fetch(&repo, "origin", UPSTREAM_REFSPEC) {
        return Check::warn(
            FRESHNESS,
            format!("cannot prove whether the running lf is current: could not refresh {UPSTREAM}: {error}"),
        );
    }

    match crate::build_info::classify_revision(revision, &repo, UPSTREAM) {
        crate::build_info::BuildFreshness::Current { revision } => Check::ok(
            FRESHNESS,
            format!(
                "running lf is built from {}, current with {UPSTREAM}",
                crate::build_info::short_revision(&revision)
            ),
        ),
        crate::build_info::BuildFreshness::Behind { revision, missing } => {
            let commits = missing
                .iter()
                .map(|commit| {
                    format!(
                        "{} {}",
                        crate::build_info::short_revision(&commit.revision),
                        commit.subject
                    )
                })
                .collect::<Vec<_>>()
                .join("; ");
            Check::warn(
                FRESHNESS,
                format!(
                    "running lf is built from {} and is {} merged commit(s) behind {UPSTREAM}, so \
                     these fixes are not running: {commits}. Rebuilding is an operator action; \
                     this check installs nothing",
                    crate::build_info::short_revision(&revision),
                    missing.len(),
                ),
            )
        }
        crate::build_info::BuildFreshness::OffMain { revision } => Check::ok(
            FRESHNESS,
            format!(
                "running lf is built from {}, which is not on {UPSTREAM}; nothing to compare",
                crate::build_info::short_revision(&revision)
            ),
        ),
        crate::build_info::BuildFreshness::Unprovable { reason } => Check::warn(
            FRESHNESS,
            format!("cannot prove whether the running lf is current: {reason}"),
        ),
    }
}

/// Prefer the build checkout, then walk up from the working directory.
fn freshness_repo() -> Option<std::path::PathBuf> {
    if let Some(root) = crate::build_info::source_root() {
        if root.join(".git").exists() {
            return Some(root.to_path_buf());
        }
    }
    let cwd = std::env::current_dir().ok()?;
    cwd.ancestors()
        .find(|ancestor| ancestor.join(".git").exists())
        .map(Path::to_path_buf)
}

fn inspect_store(path: &Path) -> StoreReport {
    let mut latest_applied_migration = None;
    let mut migration_error = None;
    if path.exists() {
        match rusqlite::Connection::open_with_flags(
            path,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
        ) {
            Ok(connection) => {
                match crate::store::migrations::latest_applied_version_sqlite(&connection) {
                    Ok(version) => latest_applied_migration = version,
                    Err(error) => migration_error = Some(error.to_string()),
                }
                if let Err(error) = crate::store::migrations::validate_sqlite(&connection) {
                    migration_error.get_or_insert_with(|| error.to_string());
                }
            }
            Err(error) => migration_error = Some(error.to_string()),
        }
    }
    StoreReport {
        build_provenance: crate::build_info::provenance(),
        migration_authority: match crate::build_info::migration_authority() {
            crate::build_info::MigrationAuthority::Published => "published",
            crate::build_info::MigrationAuthority::ValidationOnly => "validation-only",
        }
        .to_string(),
        build_source_identity: crate::build_info::source_identity(),
        build_source_root: crate::build_info::source_root().map(|root| root.display().to_string()),
        build_source_revision: crate::build_info::source_revision().to_string(),
        database_path: path.display().to_string(),
        latest_known_migration: crate::store::migrations::latest_known_version(),
        latest_applied_migration,
        migration_error,
    }
}

fn check_capture(
    store: &crate::store::sqlite::SqliteStore,
    events: &[RunEventRow],
) -> Result<Check> {
    let launches = store.agent_launches_since(0)?;
    let launch_ids = launches
        .iter()
        .map(|launch| launch.id.clone())
        .collect::<Vec<_>>();
    let turns = store.agent_turns_for_launches(&launch_ids)?;
    let turn_ids = turns.iter().map(|turn| turn.id.clone()).collect::<Vec<_>>();
    let assets = store.context_assets_for_turns(&turn_ids)?;

    let mut failures = Vec::new();
    let mut prompt_only = 0;
    let mut pruned = 0;
    for launch in &launches {
        if launch.capture_status == "pruned" {
            // Tombstoned by `lf runs reconcile`: the artifact is known-absent
            // and the absence is acknowledged. Counted, never a failure — must
            // short-circuit before the file-resolution checks below, which would
            // otherwise flag the known-absent file as a fresh failure.
            pruned += 1;
            continue;
        }
        if crate::trace::resolve_artifact(&launch.artifact_dir).is_err()
            || crate::trace::resolve_artifact(&launch.conversation_path).is_err()
            || launch
                .provider_events_path
                .as_deref()
                .is_some_and(|path| crate::trace::resolve_artifact(path).is_err())
        {
            failures.push(format!("{} has an unsafe artifact path", launch.id));
        }
        if launch.capture_status == "prompt_only" {
            prompt_only += 1;
        }
        if launch.capture_status == "partial" {
            failures.push(format!("{} is partial", launch.id));
        }
        if launch.capture_status == "capturing"
            && events.iter().any(|event| {
                event.process_id == launch.process_id
                    && event.node == "run"
                    && event.event != "started"
            })
        {
            failures.push(format!(
                "{} stayed capturing after its process ended",
                launch.id
            ));
        }
        if launch.capture_status == "complete" {
            let conversation_path = crate::trace::resolve_artifact(&launch.conversation_path);
            let conversation_read = match &conversation_path {
                Ok(path) => {
                    crate::trace::read_conversation_status(path).map_err(|error| error.to_string())
                }
                Err(error) => Err(error.to_string()),
            };
            match conversation_read {
                Ok(read) => {
                    if read.incomplete_tail {
                        failures.push(format!("{} has an unterminated event tail", launch.id));
                    }
                    if read
                        .events
                        .windows(2)
                        .any(|pair| pair[1].seq != pair[0].seq + 1)
                    {
                        failures.push(format!("{} has non-monotonic events", launch.id));
                    }
                    if read.events.len() as i64 != launch.conversation_event_count {
                        failures.push(format!("{} has a stale event count", launch.id));
                    }
                }
                Err(error) => failures.push(format!("{}: {error}", launch.id)),
            }
            if let Ok(path) = conversation_path {
                if std::fs::metadata(path)
                    .is_ok_and(|metadata| metadata.len() as i64 != launch.conversation_bytes)
                {
                    failures.push(format!("{} has a stale byte count", launch.id));
                }
            }
            if !turns.iter().any(|turn| {
                turn.launch_id == launch.id
                    && matches!(turn.status.as_str(), "completed" | "failed" | "interrupted")
            }) {
                failures.push(format!("{} has no terminal turn", launch.id));
            }
        }
    }
    let known_artifacts: HashSet<&str> = launches
        .iter()
        .map(|launch| launch.artifact_dir.as_str())
        .collect();
    for artifact in crate::trace::list_launch_artifact_dirs()? {
        if !known_artifacts.contains(artifact.as_str()) {
            failures.push(format!("orphan trace artifact {artifact}"));
        }
    }

    let mut assets_by_turn: HashMap<&str, Vec<&crate::trace::ContextAssetRow>> = HashMap::new();
    for asset in &assets {
        assets_by_turn
            .entry(asset.turn_id.as_str())
            .or_default()
            .push(asset);
    }
    for turn in &turns {
        if !crate::trace::resolve_artifact(&turn.task_prompt_path).is_ok_and(|path| path.is_file())
            || turn.system_prompt_path.as_deref().is_some_and(|path| {
                !crate::trace::resolve_artifact(path).is_ok_and(|path| path.is_file())
            })
        {
            failures.push(format!("{} is missing a prompt artifact", turn.id));
        }
        if turn.context_coverage == "unknown" {
            continue;
        }
        let Some(turn_assets) = assets_by_turn.get(turn.id.as_str()) else {
            failures.push(format!("{} has no context assets", turn.id));
            continue;
        };
        let system: u64 = turn_assets
            .iter()
            .filter(|row| row.asset.channel == crate::trace::ContextChannel::System)
            .map(|row| row.asset.attributed_tokens)
            .sum();
        let task: u64 = turn_assets
            .iter()
            .filter(|row| row.asset.channel == crate::trace::ContextChannel::Task)
            .map(|row| row.asset.attributed_tokens)
            .sum();
        if system as i64 != turn.system_tokens || task as i64 != turn.task_tokens {
            failures.push(format!("{} has mismatched asset tokens", turn.id));
        }
    }

    let pruned_clause = if pruned > 0 {
        format!(", {pruned} pruned")
    } else {
        String::new()
    };
    if !failures.is_empty() {
        return Ok(Check::fail(
            "capture",
            format!(
                "{} failure(s); {} launches, {} turns, {} bytes{pruned_clause}: {}",
                failures.len(),
                launches.len(),
                turns.len(),
                launches
                    .iter()
                    .map(|launch| launch.conversation_bytes)
                    .sum::<i64>(),
                failures.into_iter().take(4).collect::<Vec<_>>().join("; ")
            ),
        ));
    }
    if prompt_only > 0 {
        return Ok(Check::warn(
            "capture",
            format!(
                "{} launches and {} turns are consistent; {prompt_only} interactive launch(es) are prompt-only{pruned_clause}",
                launches.len(),
                turns.len()
            ),
        ));
    }
    Ok(Check::ok(
        "capture",
        format!(
            "{} launches, {} turns, {} assets, {} bytes{pruned_clause}",
            launches.len(),
            turns.len(),
            assets.len(),
            launches
                .iter()
                .map(|launch| launch.conversation_bytes)
                .sum::<i64>()
        ),
    ))
}

pub fn audit(events: &[RunEventRow]) -> Vec<Check> {
    if events.is_empty() {
        return vec![Check::warn("continuity", "ledger is empty")];
    }
    let now = OffsetDateTime::now_utc().unix_timestamp();
    vec![
        check_continuity(events, now),
        check_vocabulary(events),
        check_attribution(events),
        check_identity(events),
        check_lineage(events),
    ]
}

/// A launch that finished capturing and recorded no provider measurement is a
/// launch whose cost is lost. Spend lives only on turns now, so absent usage is
/// correctly `None` rather than a fictitious zero — which makes it invisible
/// unless something counts it. This is that count.
///
/// Scoped to `complete` launches: `capturing` has not finished, `prompt_only`
/// never streamed, and `partial`/`pruned` already report themselves through
/// `check_capture`. The breakdown names providers because that is the actionable
/// unit — a provider reporting nothing is a mapping gap, not a quiet week.
fn check_usage_coverage(store: &crate::store::sqlite::SqliteStore) -> Result<Check> {
    let launches: Vec<_> = store
        .agent_launches_since(0)?
        .into_iter()
        .filter(|launch| launch.capture_status == "complete")
        .collect();
    if launches.is_empty() {
        return Ok(Check::ok("usage", "no completed launches recorded"));
    }
    let launch_ids = launches
        .iter()
        .map(|launch| launch.id.clone())
        .collect::<Vec<_>>();
    let measured: HashSet<String> = store
        .agent_turns_for_launches(&launch_ids)?
        .into_iter()
        .filter(|turn| {
            turn.provider_input_tokens.is_some()
                || turn.provider_output_tokens.is_some()
                || turn.cache_read_tokens.is_some()
                || turn.cost_usd.is_some()
        })
        .map(|turn| turn.launch_id)
        .collect();

    let mut missing_by_provider: BTreeMap<&str, (usize, usize)> = BTreeMap::new();
    for launch in &launches {
        let entry = missing_by_provider
            .entry(launch.provider.as_str())
            .or_default();
        entry.1 += 1;
        if !measured.contains(&launch.id) {
            entry.0 += 1;
        }
    }
    let covered = launches
        .iter()
        .filter(|launch| measured.contains(&launch.id))
        .count();
    let total = launches.len();
    if covered == total {
        return Ok(Check::ok(
            "usage",
            format!("{total} completed launches all report provider usage"),
        ));
    }
    let breakdown = missing_by_provider
        .iter()
        .filter(|(_, (missing, _))| *missing > 0)
        .map(|(provider, (missing, seen))| format!("{provider} {missing}/{seen}"))
        .collect::<Vec<_>>()
        .join(", ");
    Ok(Check::warn(
        "usage",
        format!("{covered}/{total} completed launches report provider usage; missing: {breakdown}"),
    ))
}

/// Silence longer than this is reported. The 29.2-hour outage is the reason
/// the number exists; a day-granularity check missed it entirely, because the
/// silence began mid-day and ended mid-day and both days held rows.
const MAX_SILENCE_HOURS: f64 = 24.0;

/// A day the ledger recorded nothing is a day it may not have been listening —
/// but so is a long silence inside two busy days. Measure both.
fn check_continuity(events: &[RunEventRow], now: i64) -> Check {
    let days: BTreeSet<_> = events.iter().filter_map(|e| day_of(e.ts)).collect();
    let (Some(first), Some(last_event_day)) = (days.first(), days.last()) else {
        return Check::warn("continuity", "no timestamps");
    };
    let last = day_of(now)
        .map(|today| today.max(*last_event_day))
        .unwrap_or(*last_event_day);

    let mut gaps = Vec::new();
    let mut cursor = *first;
    while cursor < last {
        cursor += Duration::days(1);
        if cursor < last && !days.contains(&cursor) {
            gaps.push(cursor.to_string());
        }
    }

    let span = format!("{first} → {last}");
    if !gaps.is_empty() {
        return Check::fail(
            "continuity",
            format!("{} gap-day(s) in {span}: {}", gaps.len(), gaps.join(", ")),
        );
    }

    let silence = longest_silence_hours(events, now);
    if silence > MAX_SILENCE_HOURS {
        return Check::warn(
            "continuity",
            format!(
                "no gap-days ({span}), but {silence:.1}h of silence — was the ledger listening?"
            ),
        );
    }
    Check::ok(
        "continuity",
        format!("no gap-days ({span}); longest silence {silence:.1}h"),
    )
}

/// The largest interval between consecutive recorded events or between the
/// latest event and now, in hours. The tail matters most during an active
/// outage: until a later write succeeds, there is no second event to expose it.
fn longest_silence_hours(events: &[RunEventRow], now: i64) -> f64 {
    let mut stamps: Vec<i64> = events.iter().map(|event| event.ts).collect();
    stamps.push(now);
    stamps.sort_unstable();
    stamps
        .windows(2)
        .map(|pair| pair[1] - pair[0])
        .max()
        .unwrap_or(0) as f64
        / 3600.0
}

/// A half-landed rename leaves two spellings of one concept, and every query
/// grouping on it silently drops history.
fn check_vocabulary(events: &[RunEventRow]) -> Check {
    let mut unknown: HashMap<String, usize> = HashMap::new();
    for event in events {
        if !NODES.contains(&event.node.as_str()) {
            *unknown.entry(format!("node={}", event.node)).or_default() += 1;
        }
        if !EVENTS.contains(&event.event.as_str()) {
            *unknown.entry(format!("event={}", event.event)).or_default() += 1;
        }
    }
    if unknown.is_empty() {
        return Check::ok("vocabulary", "node and event values are all known");
    }
    let mut parts: Vec<_> = unknown
        .into_iter()
        .map(|(value, count)| format!("{value} ({count} rows)"))
        .collect();
    parts.sort();
    Check::fail(
        "vocabulary",
        format!("values outside the closed set: {}", parts.join(", ")),
    )
}

/// A process may name only one command, and its terminal row names that work.
fn check_attribution(events: &[RunEventRow]) -> Check {
    let mut commands: HashMap<&str, HashSet<&str>> = HashMap::new();
    let mut terminal = 0usize;
    let mut terminal_unnamed = 0usize;

    for event in events {
        if let Some(command) = event.command.as_deref() {
            commands
                .entry(&event.process_id)
                .or_default()
                .insert(command);
        }
        if event.node == "run" && event.event != "started" {
            terminal += 1;
            if event.command.is_none() && event.flow.is_none() && event.skill.is_none() {
                terminal_unnamed += 1;
            }
        }
    }

    let ambiguous = commands.values().filter(|set| set.len() > 1).count();
    if ambiguous == 0 && terminal_unnamed == 0 {
        return Check::ok("attribution", "every terminal row names its work");
    }
    Check::fail(
        "attribution",
        format!(
            "{ambiguous} process_id(s) carry >1 command; {terminal_unnamed}/{terminal} terminal rows name no command, flow, or skill"
        ),
    )
}

/// Repo identity is the absolute main-repo root, never a basename.
fn check_identity(events: &[RunEventRow]) -> Check {
    let repos: HashSet<Option<&str>> = events.iter().map(|event| event.repo.as_deref()).collect();
    let invalid = repos
        .iter()
        .filter(|repo| repo.is_none_or(|repo| !Path::new(repo).is_absolute()))
        .count();
    if invalid == 0 {
        return Check::ok(
            "identity",
            format!("{} repo value(s), all absolute", repos.len()),
        );
    }
    Check::fail(
        "identity",
        format!(
            "{invalid}/{} repo value(s) are missing or not absolute",
            repos.len()
        ),
    )
}

fn check_lineage(events: &[RunEventRow]) -> Check {
    let processes: HashMap<&str, &str> = events
        .iter()
        .map(|event| (event.process_id.as_str(), event.run_id.as_str()))
        .collect();
    let dangling: HashSet<&str> = events
        .iter()
        .filter_map(|event| {
            let parent = event.parent_process_id.as_deref()?;
            (processes.get(parent).copied() != Some(event.run_id.as_str())).then_some(parent)
        })
        .collect();
    if dangling.is_empty() {
        return Check::ok("lineage", "every parent process resolves");
    }
    Check::fail(
        "lineage",
        format!(
            "{} parent process id(s) are missing or belong to another trace",
            dangling.len()
        ),
    )
}

// ── Receipt sweep ───────────────────────────────────────────────────

/// Known ids for each evidence kind — the resolution surface the receipt
/// sweep checks against. Gathered from the store and wave journals; the check
/// itself is pure over these sets.
///
/// `unavailable` records kinds whose backing store or journal could not be read
/// this run. A receipt of an unavailable kind can't be judged resolved-or-orphaned
/// — the sweep reports it as *inaccessible* rather than silently calling it
/// orphaned, so a dropped read never masquerades as a missing record.
#[derive(Debug, Default)]
pub struct ReceiptKnownIds {
    pub chat_turn_ids: HashSet<String>,
    pub run_ids: HashSet<String>,
    pub trace_turn_ids: HashSet<String>,
    pub pm_ids: HashSet<String>,
    pub prs: Vec<PrIdentity>,
    pub unavailable: HashSet<EvidenceKind>,
    pub errors: Vec<String>,
}

impl ReceiptKnownIds {
    /// Record that an evidence kind's backing source could not be read, so its
    /// receipts are reported inaccessible (not orphaned) and the reason is
    /// surfaced in the check detail.
    fn mark_unavailable(&mut self, kind: EvidenceKind, error: impl Into<String>) {
        self.unavailable.insert(kind);
        self.errors.push(error.into());
    }
}

/// One memory fact paired with its claim wave, for the receipt sweep.
#[derive(Debug, Clone)]
pub struct ReceiptFact {
    pub wave: String,
    pub receipts: Vec<Receipt>,
}

/// Audit curated memory facts for receipt health: missing (zero receipts),
/// orphaned (reference resolves to no known record), and cross-wave (receipt
/// wave ≠ claim wave). Pure over the facts and known-id sets — testable
/// without a store.
///
/// During the post-contract grace window all findings are `warn`, not `fail`,
/// so pre-contract claims and cross-machine references don't break the gate.
/// Cross-wave is always `warn` — legitimate for child→parent citation.
/// How one receipt fared against the known-id sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Resolution {
    /// The reference resolves to a known record.
    Resolved,
    /// The reference resolves to no known record (a real dangling pointer).
    Orphaned,
    /// The reference's evidence kind could not be read this run, so we can't
    /// judge it — surfaced, never silently counted as orphaned.
    Inaccessible,
}

fn check_receipts(facts: &[ReceiptFact], known: &ReceiptKnownIds) -> Check {
    if facts.is_empty() && known.errors.is_empty() {
        return Check::ok("receipts", "no memory facts to audit");
    }

    let mut missing = 0;
    let mut orphaned = 0;
    let mut inaccessible = 0;
    let mut cross_wave = 0;
    let mut total_receipts = 0;

    for fact in facts {
        if fact.receipts.is_empty() {
            missing += 1;
            continue;
        }
        for receipt in &fact.receipts {
            total_receipts += 1;
            if receipt.wave != fact.wave {
                cross_wave += 1;
            }
            match resolve_receipt(receipt, known) {
                Resolution::Resolved => {}
                Resolution::Orphaned => orphaned += 1,
                Resolution::Inaccessible => inaccessible += 1,
            }
        }
    }

    let total_facts = facts.len();
    let mut detail = format!(
        "{total_facts} fact(s) with {total_receipts} receipt(s): \
         {missing} missing, {orphaned} orphaned, {inaccessible} inaccessible, {cross_wave} cross-wave"
    );
    if !known.errors.is_empty() {
        detail.push_str(&format!(
            "; unreadable evidence: {}",
            known.errors.join("; ")
        ));
    }

    if missing > 0 || orphaned > 0 || inaccessible > 0 || cross_wave > 0 || !known.errors.is_empty()
    {
        Check::warn("receipts", detail)
    } else {
        Check::ok("receipts", detail)
    }
}

fn resolve_receipt(receipt: &Receipt, known: &ReceiptKnownIds) -> Resolution {
    if known.unavailable.contains(&receipt.kind) {
        return Resolution::Inaccessible;
    }
    let resolved = match receipt.kind {
        EvidenceKind::ChatTurn => known.chat_turn_ids.contains(&receipt.reference),
        EvidenceKind::WorkerReport => known.run_ids.contains(&receipt.reference),
        EvidenceKind::Trace => known.trace_turn_ids.contains(&receipt.reference),
        EvidenceKind::Pm => known.pm_ids.contains(&receipt.reference),
        EvidenceKind::Pr => PrReference::parse(&receipt.reference)
            .is_some_and(|target| known.prs.iter().any(|id| target.matches(id))),
    };
    if resolved {
        Resolution::Resolved
    } else {
        Resolution::Orphaned
    }
}

/// Gather memory facts (with their claim wave) and the known-id sets for each
/// evidence kind, from the store and every wave journal on this machine.
fn gather_receipt_audit(
    store: &crate::store::sqlite::SqliteStore,
    events: &[RunEventRow],
) -> (Vec<ReceiptFact>, ReceiptKnownIds) {
    let mut known = ReceiptKnownIds::default();
    let mut facts = Vec::new();

    known.run_ids = events.iter().map(|e| e.run_id.clone()).collect();

    // Trace turns: a failure to read launches or their turns leaves the set
    // unknown, so mark the whole kind inaccessible rather than judging every
    // trace receipt orphaned against an empty set.
    match store.agent_launches_since(0) {
        Ok(launches) => {
            let launch_ids: Vec<String> = launches.iter().map(|l| l.id.clone()).collect();
            match store.agent_turns_for_launches(&launch_ids) {
                Ok(turns) => known.trace_turn_ids = turns.iter().map(|t| t.id.clone()).collect(),
                Err(err) => {
                    known.mark_unavailable(EvidenceKind::Trace, format!("trace turns: {err}"))
                }
            }
        }
        Err(err) => known.mark_unavailable(EvidenceKind::Trace, format!("agent launches: {err}")),
    }

    match store.all_task_prs() {
        Ok(prs) => known.prs = prs.iter().filter_map(|pr| pr.pr_identity()).collect(),
        Err(err) => known.mark_unavailable(EvidenceKind::Pr, format!("task PRs: {err}")),
    }

    let waves = match store.list_waves(None) {
        Ok(waves) => waves,
        Err(err) => {
            // Without the wave list we can read neither journals (chat turns,
            // facts) nor PM snapshots — the sweep is blind for those kinds.
            known.mark_unavailable(EvidenceKind::ChatTurn, format!("wave list: {err}"));
            known.mark_unavailable(EvidenceKind::Pm, format!("wave list: {err}"));
            return (facts, known);
        }
    };

    for wave in &waves {
        let repo_root = Path::new(wave.repo());
        let journal = journal_path(repo_root, wave.name());
        if journal.exists() {
            let journal_events = read_events(&journal);
            for fact in memory_facts(&journal_events) {
                facts.push(ReceiptFact {
                    wave: wave.name().to_string(),
                    receipts: fact.receipts,
                });
            }
            let fold = fold_thread(&journal_events);
            known
                .chat_turn_ids
                .extend(fold.turns.iter().map(|t| t.id.clone()));
            known
                .chat_turn_ids
                .extend(fold.open.iter().map(|t| t.id.clone()));
        }

        match store.pm_snapshot(wave.repo(), wave.name()) {
            Ok(Some(snapshot)) => {
                match serde_json::from_str::<serde_json::Value>(&snapshot.payload) {
                    Ok(payload) => {
                        for key in ["items", "projects"] {
                            if let Some(arr) = payload.get(key).and_then(|v| v.as_array()) {
                                for entry in arr {
                                    if let Some(id) = entry.get("id").and_then(|v| v.as_str()) {
                                        known.pm_ids.insert(id.to_string());
                                    }
                                }
                            }
                        }
                    }
                    Err(err) => known.mark_unavailable(
                        EvidenceKind::Pm,
                        format!("PM snapshot for wave '{}': {err}", wave.name()),
                    ),
                }
            }
            Ok(None) => {}
            Err(err) => known.mark_unavailable(
                EvidenceKind::Pm,
                format!("PM snapshot for wave '{}': {err}", wave.name()),
            ),
        }
    }

    (facts, known)
}

fn day_of(ts: i64) -> Option<time::Date> {
    OffsetDateTime::from_unix_timestamp(ts)
        .ok()
        .map(|dt| dt.date())
}

fn print_checks(store: &StoreReport, checks: &[Check], rows: usize) {
    let colors = Colors::default();
    println!(
        "build: {} ({}) · migrations {}",
        store.build_provenance, store.build_source_identity, store.migration_authority
    );
    println!("revision: {}", store.build_source_revision);
    if let Some(root) = &store.build_source_root {
        println!("source: {root}");
    }
    println!("database: {}", store.database_path);
    println!(
        "migrations: applied {} / known {}",
        store.latest_applied_migration.as_deref().unwrap_or("none"),
        store.latest_known_migration
    );
    if let Some(error) = &store.migration_error {
        println!("migration error: {error}");
    }
    println!("ledger: {rows} run events\n");
    for check in checks {
        let (mark, color) = match check.status {
            Status::Ok => ("ok  ", colors.green),
            Status::Warn => ("warn", colors.yellow),
            Status::Fail => ("FAIL", colors.red),
        };
        println!(
            "{color}{mark}{reset}  {bold}{name:<13}{reset} {detail}",
            color = color,
            reset = colors.reset,
            bold = colors.bold,
            mark = mark,
            name = check.name,
            detail = check.detail,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::{
        audit, check_capture, check_continuity, check_usage_coverage, inspect_store, Status,
    };
    use crate::store::RunEventRow;

    const DAY: i64 = 86_400;

    #[test]
    fn store_report_exposes_unknown_applied_migration() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("loopflow.db");
        let connection = rusqlite::Connection::open(&path).unwrap();
        crate::store::migrations::apply_sqlite(&connection).unwrap();
        connection
            .execute(
                "INSERT INTO schema_migrations (version, applied_at)
                 VALUES ('9.0.001_divergent', unixepoch() + 1)",
                [],
            )
            .unwrap();
        drop(connection);

        let report = inspect_store(&path);

        assert_eq!(
            report.latest_applied_migration.as_deref(),
            Some("9.0.001_divergent")
        );
        let error = report.migration_error.unwrap();
        assert!(error.contains("9.0.001_divergent"), "{error}");
        assert!(error.contains("latest known"), "{error}");
    }

    /// Drive a real capture to `complete`, returning its launch id and the
    /// conversation artifact on disk. Uses the production write path so the
    /// tombstone tests act on genuinely-shaped rows.
    fn captured_launch(
        guard: &crate::journal::TestLedgerGuard,
        skill: &str,
    ) -> (String, std::path::PathBuf) {
        let capture = crate::trace::CaptureHandle::begin(
            crate::trace::TraceCaptureContext {
                run_id: crate::id::TraceId::new(),
                process_id: crate::id::ExecId::new(),
                repo: guard.home().to_path_buf(),
                worktree: guard.home().to_path_buf(),
                wave: Some("infrastructure".to_string()),
                project: None,
                task: Some("W2-235".to_string()),
                flow: None,
                skill: Some(skill.to_string()),
            },
            crate::trace::PreparedTurnContext::from_prompts("system", "task"),
            crate::trace::CaptureStart {
                provider: "codex".to_string(),
                model: Some("gpt-5".to_string()),
                surface: "headless".to_string(),
                input_op: "initial".to_string(),
                gather_ms: 1,
                render_ms: 2,
                raw_provider: true,
                basis: None,
                control: None,
            },
        )
        .unwrap();
        capture.begin_turn("message", "follow up").unwrap();
        capture.finish("completed", false).unwrap();

        let store = crate::journal::open_ledger().unwrap();
        let launch = store
            .agent_launches_since(0)
            .unwrap()
            .into_iter()
            .find(|launch| launch.skill.as_deref() == Some(skill))
            .expect("the capture we just drove must be in the ledger");
        assert_eq!(launch.capture_status, "complete");
        let conversation = crate::trace::resolve_artifact(&launch.conversation_path).unwrap();
        assert!(conversation.is_file());
        (launch.id, conversation)
    }

    /// The same production path, but with the provider reporting what it
    /// measured — the shape a covered launch has.
    fn captured_launch_with_usage(guard: &crate::journal::TestLedgerGuard, skill: &str) {
        let capture = crate::trace::CaptureHandle::begin(
            crate::trace::TraceCaptureContext {
                run_id: crate::id::TraceId::new(),
                process_id: crate::id::ExecId::new(),
                repo: guard.home().to_path_buf(),
                worktree: guard.home().to_path_buf(),
                wave: Some("infrastructure".to_string()),
                project: None,
                task: None,
                flow: None,
                skill: Some(skill.to_string()),
            },
            crate::trace::PreparedTurnContext::from_prompts("system", "task"),
            crate::trace::CaptureStart {
                provider: "claude".to_string(),
                model: Some("opus".to_string()),
                surface: "headless".to_string(),
                input_op: "initial".to_string(),
                gather_ms: 1,
                render_ms: 2,
                raw_provider: true,
                basis: None,
                control: None,
            },
        )
        .unwrap();
        capture.record_conversation(crate::chat::types::ConversationEvent::TurnUsage {
            turn_id: "turn-1".to_string(),
            usage: crate::chat::types::TurnUsage {
                input_tokens: 40,
                output_tokens: 5_197,
                ..Default::default()
            },
        });
        capture.finish("completed", false).unwrap();
    }

    /// Spend lives only on turns now, so a launch that reported nothing is
    /// correctly `None` everywhere — invisible unless this check counts it. The
    /// provider breakdown is the actionable part: it is how a harness that stops
    /// reporting usage announces itself instead of silently costing nothing.
    #[test]
    fn a_completed_launch_that_reported_no_usage_is_a_coverage_warning() {
        let guard = crate::journal::TestLedgerGuard::new();
        captured_launch(&guard, "kickoff");
        let store = crate::journal::open_ledger().unwrap();

        let check = check_usage_coverage(&store).unwrap();

        assert_eq!(check.status, Status::Warn, "{}", check.detail);
        assert!(
            check.detail.contains("0/1") && check.detail.contains("codex 1/1"),
            "the warning must name the provider that reported nothing: {}",
            check.detail
        );
    }

    #[test]
    fn a_launch_whose_provider_measured_the_turn_is_covered() {
        let guard = crate::journal::TestLedgerGuard::new();
        captured_launch_with_usage(&guard, "implement");
        let store = crate::journal::open_ledger().unwrap();

        let check = check_usage_coverage(&store).unwrap();

        assert_eq!(check.status, Status::Ok, "{}", check.detail);
    }

    #[test]
    fn a_tombstoned_capture_is_counted_while_fresh_loss_still_fails() {
        // The whole point of W2-235: acknowledged historical loss goes green
        // and stays visible as a count, but the surface must remain sensitive
        // to a capture that goes missing afterwards.
        let guard = crate::journal::TestLedgerGuard::new();
        let (historical, historical_file) = captured_launch(&guard, "kickoff");
        let store = crate::journal::open_ledger().unwrap();
        assert_eq!(check_capture(&store, &[]).unwrap().status, Status::Ok);

        // The artifact vanishes out of band — the disk-reclaim shape that
        // produced the 235 dangling references on the release host.
        std::fs::remove_file(&historical_file).unwrap();
        let check = check_capture(&store, &[]).unwrap();
        assert_eq!(check.status, Status::Fail, "{}", check.detail);
        assert!(check.detail.contains("1 failure(s)"), "{}", check.detail);

        // Acknowledge it the way `lf runs reconcile --apply` does.
        store
            .reconcile_launch_capture(
                &historical,
                "pruned",
                Some("conversation artifact absent at reconcile"),
                500,
            )
            .unwrap();
        let check = check_capture(&store, &[]).unwrap();
        assert_eq!(check.status, Status::Ok, "{}", check.detail);
        assert!(check.detail.contains("1 pruned"), "{}", check.detail);

        // A *new* capture loss must still be a failure — un-acknowledged loss
        // is the actionable signal a red capture check is supposed to carry.
        let (_, fresh_file) = captured_launch(&guard, "implement");
        std::fs::remove_file(&fresh_file).unwrap();
        let check = check_capture(&store, &[]).unwrap();
        assert_eq!(check.status, Status::Fail, "{}", check.detail);
        assert!(check.detail.contains("1 failure(s)"), "{}", check.detail);
        assert!(check.detail.contains("1 pruned"), "{}", check.detail);
    }

    fn row(run_id: &str, ts: i64, node: &str, event: &str) -> RunEventRow {
        RunEventRow {
            run_id: run_id.to_string(),
            process_id: run_id.to_string(),
            parent_process_id: None,
            seq: 0,
            ts,
            repo: Some("/src/loopflow".to_string()),
            worktree: None,
            wave: None,
            node: node.to_string(),
            event: event.to_string(),
            command: None,
            flow: None,
            skill: None,
            step_index: None,
            error: None,
        }
    }

    fn named(mut row: RunEventRow, command: &str) -> RunEventRow {
        row.command = Some(command.to_string());
        row
    }

    fn status_of(rows: &[RunEventRow], name: &str) -> Status {
        audit(rows)
            .into_iter()
            .find(|check| check.name == name)
            .expect("check exists")
            .status
    }

    #[test]
    fn a_missing_day_is_a_failure() {
        // The 29-hour outage looked exactly like this: writes, silence, writes.
        let rows = [
            row("a", DAY, "run", "completed"),
            row("b", DAY * 3, "run", "completed"),
        ];
        let check = check_continuity(&rows, DAY * 3);
        assert_eq!(check.status, Status::Fail);
        assert!(check.detail.contains("1 gap-day"), "{}", check.detail);
    }

    #[test]
    fn a_long_silence_inside_two_busy_days_is_still_caught() {
        // The real 29.2h outage: rows early on day 1, rows late on day 2, no
        // missing day at all. A gap-day check calls this healthy. It is not.
        let rows = [
            row("a", DAY, "run", "completed"),              // day 1, 00:00
            row("b", DAY + 3600, "run", "completed"),       // day 1, 01:00
            row("c", DAY * 2 + 79_200, "run", "completed"), // day 2, 22:00
        ];
        let check = check_continuity(&rows, DAY * 2 + 79_200);
        assert_eq!(check.status, Status::Warn, "{}", check.detail);
        assert!(check.detail.contains("silence"), "{}", check.detail);
    }

    #[test]
    fn consecutive_days_have_no_gap() {
        let rows = [
            row("a", DAY, "run", "completed"),
            row("b", DAY + 3600, "run", "completed"),
            row("c", DAY * 2, "run", "completed"),
        ];
        assert_eq!(check_continuity(&rows, DAY * 2).status, Status::Ok);
    }

    #[test]
    fn an_active_silence_after_the_last_event_is_caught() {
        let rows = [
            row("a", DAY, "run", "completed"),
            row("b", DAY + 3600, "run", "completed"),
        ];

        let check = check_continuity(&rows, DAY + 26 * 3600);
        assert_eq!(check.status, Status::Warn, "{}", check.detail);
        assert!(
            check.detail.contains("25.0h of silence"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn a_half_landed_rename_is_caught() {
        // `step` is the pre-054 spelling of `skill`. Both in one ledger means
        // every query grouping on node silently drops history.
        let rows = [
            row("a", DAY, "run", "completed"),
            row("a", DAY, "step", "completed"),
        ];
        assert_eq!(status_of(&rows, "vocabulary"), Status::Fail);
    }

    #[test]
    fn one_process_carrying_two_commands_is_unattributable() {
        let rows = [
            named(row("shared", DAY, "run", "started"), r#"["lf","wave"]"#),
            named(row("shared", DAY, "run", "started"), r#"["lf","op","pm"]"#),
            row("shared", DAY, "run", "completed"),
        ];
        let check = audit(&rows)
            .into_iter()
            .find(|c| c.name == "attribution")
            .unwrap();
        assert_eq!(check.status, Status::Fail);
        assert!(check.detail.contains("1 process_id"), "{}", check.detail);
    }

    #[test]
    fn a_terminal_row_that_names_its_work_attributes_cleanly() {
        let mut terminal = row("a", DAY, "run", "completed");
        terminal.command = Some(r#"["lf","code"]"#.to_string());
        let rows = [
            named(row("a", DAY, "run", "started"), r#"["lf","code"]"#),
            terminal,
        ];
        assert_eq!(status_of(&rows, "attribution"), Status::Ok);
    }

    #[test]
    fn two_processes_in_one_trace_are_attributable() {
        let mut parent = named(row("shared", DAY, "run", "completed"), r#"["lf","wave"]"#);
        parent.process_id = "parent".to_string();
        let mut child = named(row("shared", DAY, "run", "completed"), r#"["lf","pm"]"#);
        child.process_id = "child".to_string();
        child.parent_process_id = Some("parent".to_string());
        assert_eq!(status_of(&[parent, child], "attribution"), Status::Ok);
    }

    #[test]
    fn a_repo_basename_fails_identity() {
        let mut event = row("a", DAY, "run", "completed");
        event.repo = Some("loopflow".to_string());
        assert_eq!(status_of(&[event], "identity"), Status::Fail);
    }

    #[test]
    fn a_dangling_parent_process_id_fails_the_doctor() {
        let mut event = row("a", DAY, "run", "completed");
        event.parent_process_id = Some("missing".to_string());
        assert_eq!(status_of(&[event], "lineage"), Status::Fail);
    }

    #[test]
    fn a_parent_from_another_trace_fails_lineage() {
        let mut parent = row("trace-a", DAY, "run", "completed");
        parent.process_id = "parent".to_string();
        let mut child = row("trace-b", DAY, "run", "completed");
        child.process_id = "child".to_string();
        child.parent_process_id = Some("parent".to_string());
        assert_eq!(status_of(&[parent, child], "lineage"), Status::Fail);
    }

    // ── receipt sweep tests (pure over facts + known-id sets) ─────────

    use super::{check_receipts, ReceiptFact, ReceiptKnownIds};
    use crate::receipt::{EvidenceKind, PrIdentity, Receipt};

    fn receipt(kind: EvidenceKind, reference: &str, wave: &str) -> Receipt {
        Receipt::new(kind, reference, wave)
    }

    fn known(turn_ids: &[&str], run_ids: &[&str]) -> ReceiptKnownIds {
        ReceiptKnownIds {
            chat_turn_ids: turn_ids.iter().map(|s| s.to_string()).collect(),
            run_ids: run_ids.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn no_facts_is_ok() {
        let check = check_receipts(&[], &ReceiptKnownIds::default());
        assert_eq!(check.status, Status::Ok);
    }

    #[test]
    fn facts_with_resolving_receipts_are_ok() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![
                receipt(EvidenceKind::ChatTurn, "turn-3", "ship"),
                receipt(EvidenceKind::WorkerReport, "run-9", "ship"),
            ],
        }];
        let known = known(&["turn-3"], &["run-9"]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Ok);
        assert!(check.detail.contains("1 fact(s)"), "{}", check.detail);
    }

    #[test]
    fn facts_with_zero_receipts_warn_during_grace() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![],
        }];
        let check = check_receipts(&facts, &ReceiptKnownIds::default());
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 missing"), "{}", check.detail);
    }

    #[test]
    fn orphaned_receipts_warn() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(EvidenceKind::ChatTurn, "turn-99", "ship")],
        }];
        let known = known(&["turn-3"], &[]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 orphaned"), "{}", check.detail);
    }

    #[test]
    fn cross_wave_receipts_warn() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(EvidenceKind::ChatTurn, "turn-3", "product")],
        }];
        let known = known(&["turn-3"], &[]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 cross-wave"), "{}", check.detail);
    }

    fn known_pr(repo: &str, number: u32, shas: &[&str]) -> ReceiptKnownIds {
        ReceiptKnownIds {
            prs: vec![PrIdentity {
                repo: repo.to_string(),
                number,
                shas: shas.iter().map(|s| s.to_string()).collect(),
            }],
            ..Default::default()
        }
    }

    #[test]
    fn pr_receipt_resolves_by_repo_and_number() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(
                EvidenceKind::Pr,
                "loopflow/loopflow#912@abc123",
                "ship",
            )],
        }];
        let known = known_pr("loopflow/loopflow", 912, &["abc123"]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Ok);
    }

    #[test]
    fn pr_receipt_with_matching_number_but_wrong_repo_is_orphaned() {
        // A bare number scan would resolve this; matching repo + number rejects it.
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(EvidenceKind::Pr, "other/repo#912", "ship")],
        }];
        let known = known_pr("loopflow/loopflow", 912, &[]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 orphaned"), "{}", check.detail);
    }

    #[test]
    fn pr_receipt_with_unknown_number_is_orphaned() {
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(EvidenceKind::Pr, "loopflow/loopflow#999", "ship")],
        }];
        let known = known_pr("loopflow/loopflow", 912, &[]);
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 orphaned"), "{}", check.detail);
    }

    #[test]
    fn inaccessible_evidence_is_surfaced_not_orphaned() {
        // The store couldn't read task PRs, so a pr receipt is inaccessible —
        // reported and explained, never silently counted orphaned.
        let facts = vec![ReceiptFact {
            wave: "ship".to_string(),
            receipts: vec![receipt(EvidenceKind::Pr, "loopflow/loopflow#912", "ship")],
        }];
        let mut known = ReceiptKnownIds::default();
        known.mark_unavailable(EvidenceKind::Pr, "task PRs: database is locked");
        let check = check_receipts(&facts, &known);
        assert_eq!(check.status, Status::Warn);
        assert!(check.detail.contains("1 inaccessible"), "{}", check.detail);
        assert!(check.detail.contains("0 orphaned"), "{}", check.detail);
        assert!(
            check.detail.contains("database is locked"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn unreadable_evidence_warns_even_with_no_facts() {
        // A wave-list failure yields zero facts; the sweep must still warn and
        // surface the error rather than reporting a clean "nothing to audit".
        let mut known = ReceiptKnownIds::default();
        known.mark_unavailable(EvidenceKind::ChatTurn, "wave list: connection refused");
        let check = check_receipts(&[], &known);
        assert_eq!(check.status, Status::Warn);
        assert!(
            check.detail.contains("connection refused"),
            "{}",
            check.detail
        );
    }
}