a3s-code-core 9.0.0

A3S Code Core - Embeddable AI agent library with tool execution
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
//! Verification contracts for A3S Code 2.0.
//!
//! Verification is represented as structured checks and reports. The first
//! stage is intentionally conservative: required checks start as
//! `needs_review` until a verifier or the harness marks them passed/failed.

use crate::program::ProgramVerificationHint;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

pub const VERIFICATION_REPORT_SCHEMA: &str = "a3s.verification_report.v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerificationStatus {
    Passed,
    Failed,
    NeedsReview,
    Skipped,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationCheck {
    pub id: String,
    pub kind: String,
    pub description: String,
    pub status: VerificationStatus,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suggested_tools: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence_uris: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub residual_risk: Option<String>,
}

impl VerificationCheck {
    pub fn required(
        id: impl Into<String>,
        kind: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: kind.into(),
            description: description.into(),
            status: VerificationStatus::NeedsReview,
            required: true,
            suggested_tools: Vec::new(),
            evidence_uris: Vec::new(),
            residual_risk: None,
        }
    }

    pub fn optional(
        id: impl Into<String>,
        kind: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            required: false,
            ..Self::required(id, kind, description)
        }
    }

    pub fn with_status(mut self, status: VerificationStatus) -> Self {
        self.status = status;
        self
    }

    pub fn with_suggested_tools(
        mut self,
        tools: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.suggested_tools = tools.into_iter().map(Into::into).collect();
        self
    }

    pub fn with_evidence_uris(mut self, uris: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.evidence_uris = uris.into_iter().map(Into::into).collect();
        self
    }

    pub fn with_residual_risk(mut self, risk: impl Into<String>) -> Self {
        self.residual_risk = Some(risk.into());
        self
    }

    pub fn from_program_hint(subject: &str, index: usize, hint: &ProgramVerificationHint) -> Self {
        let id = format!("program:{subject}:{}:{index}", hint.kind);
        let check = if hint.required {
            Self::required(id, hint.kind.clone(), hint.message.clone())
        } else {
            Self::optional(id, hint.kind.clone(), hint.message.clone())
        };

        check
            .with_suggested_tools(hint.suggested_tools.clone())
            .with_evidence_uris(hint.evidence_uris.clone())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationCommand {
    pub id: String,
    pub kind: String,
    pub description: String,
    pub command: String,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Expected process exit code (ACCEPTANCE `expect:exit=N`; presets use 0).
    #[serde(default)]
    pub expect_exit: i32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationPreset {
    pub id: String,
    pub project_kind: String,
    pub description: String,
    pub commands: Vec<VerificationCommand>,
}

impl VerificationPreset {
    pub fn new(
        id: impl Into<String>,
        project_kind: impl Into<String>,
        description: impl Into<String>,
        commands: Vec<VerificationCommand>,
    ) -> Self {
        Self {
            id: id.into(),
            project_kind: project_kind.into(),
            description: description.into(),
            commands,
        }
    }
}

impl VerificationCommand {
    pub fn required(
        id: impl Into<String>,
        kind: impl Into<String>,
        description: impl Into<String>,
        command: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            kind: kind.into(),
            description: description.into(),
            command: command.into(),
            required: true,
            timeout_ms: None,
            expect_exit: 0,
        }
    }

    pub fn optional(
        id: impl Into<String>,
        kind: impl Into<String>,
        description: impl Into<String>,
        command: impl Into<String>,
    ) -> Self {
        Self {
            required: false,
            ..Self::required(id, kind, description, command)
        }
    }

    pub fn with_expect_exit(mut self, expect_exit: i32) -> Self {
        self.expect_exit = expect_exit;
        self
    }

    pub fn with_timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = Some(timeout_ms);
        self
    }

    pub fn to_check(&self) -> VerificationCheck {
        let check = if self.required {
            VerificationCheck::required(
                self.id.clone(),
                self.kind.clone(),
                self.description.clone(),
            )
        } else {
            VerificationCheck::optional(
                self.id.clone(),
                self.kind.clone(),
                self.description.clone(),
            )
        };

        check.with_suggested_tools(["bash"])
    }

    pub fn check_from_execution(
        &self,
        exit_code: i32,
        metadata: Option<&serde_json::Value>,
        execution_error: Option<&str>,
    ) -> VerificationCheck {
        let passed = exit_code == self.expect_exit && execution_error.is_none();
        let mut check = self.to_check().with_status(if passed {
            VerificationStatus::Passed
        } else {
            VerificationStatus::Failed
        });

        let evidence_uris = artifact_uris(metadata);
        if !evidence_uris.is_empty() {
            check = check.with_evidence_uris(evidence_uris);
        }

        if let Some(error) = execution_error {
            return check
                .with_residual_risk(format!("verification command could not run: {error}"));
        }

        if exit_code != self.expect_exit {
            check = check.with_residual_risk(format!(
                "verification command exited with code {exit_code}, expected {}: {}",
                self.expect_exit, self.command
            ));
        }

        check
    }
}

pub fn verification_presets_for_workspace(workspace: impl AsRef<Path>) -> Vec<VerificationPreset> {
    let workspace = workspace.as_ref();
    let mut presets = Vec::new();

    if workspace.join("Cargo.toml").is_file() {
        presets.push(VerificationPreset::new(
            "rust-default",
            "rust",
            "Rust cargo verification",
            vec![
                VerificationCommand::required(
                    "rust:fmt",
                    "format",
                    "Check Rust formatting",
                    "cargo fmt -- --check",
                ),
                VerificationCommand::required(
                    "rust:check",
                    "type_check",
                    "Run Rust type checking",
                    "cargo check",
                ),
                VerificationCommand::required("rust:test", "test", "Run Rust tests", "cargo test"),
                VerificationCommand::optional(
                    "rust:clippy",
                    "lint",
                    "Run Rust clippy lints",
                    "cargo clippy -- -D warnings",
                ),
            ],
        ));
    }

    if workspace.join("package.json").is_file() {
        if let Some(preset) = node_verification_preset(workspace) {
            presets.push(preset);
        }
    }

    if workspace.join("pyproject.toml").is_file() || workspace.join("pytest.ini").is_file() {
        let mut commands = Vec::new();
        if workspace.join("tests").is_dir()
            || file_contains(&workspace.join("pyproject.toml"), "[tool.pytest")
            || workspace.join("pytest.ini").is_file()
        {
            commands.push(VerificationCommand::required(
                "python:test",
                "test",
                "Run Python tests",
                "python -m pytest",
            ));
        }
        if workspace.join("ruff.toml").is_file()
            || workspace.join(".ruff.toml").is_file()
            || file_contains(&workspace.join("pyproject.toml"), "[tool.ruff")
        {
            commands.push(VerificationCommand::optional(
                "python:ruff",
                "lint",
                "Run Ruff lint checks",
                "python -m ruff check .",
            ));
        }
        if workspace.join("mypy.ini").is_file()
            || workspace.join(".mypy.ini").is_file()
            || file_contains(&workspace.join("pyproject.toml"), "[tool.mypy")
        {
            commands.push(VerificationCommand::optional(
                "python:mypy",
                "type_check",
                "Run mypy type checking",
                "python -m mypy .",
            ));
        }
        if !commands.is_empty() {
            presets.push(VerificationPreset::new(
                "python-default",
                "python",
                "Python project verification",
                commands,
            ));
        }
    }

    if workspace.join("go.mod").is_file() {
        presets.push(VerificationPreset::new(
            "go-default",
            "go",
            "Go module verification",
            vec![
                VerificationCommand::required("go:test", "test", "Run Go tests", "go test ./..."),
                VerificationCommand::optional("go:vet", "lint", "Run go vet", "go vet ./..."),
            ],
        ));
    }

    presets
}

fn node_verification_preset(workspace: &Path) -> Option<VerificationPreset> {
    let package_json = std::fs::read_to_string(workspace.join("package.json")).ok()?;
    let package: serde_json::Value = serde_json::from_str(&package_json).ok()?;
    let scripts = package.get("scripts").and_then(|value| value.as_object())?;
    let package_manager = detect_node_package_manager(workspace, &package);
    let mut commands = Vec::new();

    for (script, kind, description, required) in [
        ("test", "test", "Run JavaScript tests", true),
        (
            "typecheck",
            "type_check",
            "Run JavaScript type checks",
            false,
        ),
        ("lint", "lint", "Run JavaScript lint checks", false),
    ] {
        if scripts.contains_key(script) {
            let command = node_script_command(&package_manager, script);
            let id = format!("node:{script}");
            let verification = if required {
                VerificationCommand::required(id, kind, description, command)
            } else {
                VerificationCommand::optional(id, kind, description, command)
            };
            commands.push(verification);
        }
    }

    if commands.is_empty() {
        return None;
    }

    Some(VerificationPreset::new(
        "node-default",
        "node",
        "Node.js package verification",
        commands,
    ))
}

fn detect_node_package_manager(workspace: &Path, package: &serde_json::Value) -> String {
    if let Some(manager) = package
        .get("packageManager")
        .and_then(|value| value.as_str())
    {
        if let Some((name, _)) = manager.split_once('@') {
            return name.to_string();
        }
    }

    if workspace.join("pnpm-lock.yaml").is_file() {
        "pnpm".to_string()
    } else if workspace.join("yarn.lock").is_file() {
        "yarn".to_string()
    } else if workspace.join("bun.lockb").is_file() || workspace.join("bun.lock").is_file() {
        "bun".to_string()
    } else {
        "npm".to_string()
    }
}

fn node_script_command(package_manager: &str, script: &str) -> String {
    match package_manager {
        "pnpm" | "yarn" => format!("{package_manager} {script}"),
        "bun" => format!("bun run {script}"),
        "npm" if script == "test" => "npm test".to_string(),
        "npm" => format!("npm run {script}"),
        other => format!("{other} run {script}"),
    }
}

fn file_contains(path: &Path, needle: &str) -> bool {
    std::fs::read_to_string(path)
        .map(|content| content.contains(needle))
        .unwrap_or(false)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationReport {
    pub schema: String,
    pub subject: String,
    pub status: VerificationStatus,
    pub checks: Vec<VerificationCheck>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub residual_risks: Vec<String>,
    /// Effect digest this report is allowed to close. Unbound reports never pass the completion gate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect_digest: Option<String>,
}

impl VerificationReport {
    pub fn new(subject: impl Into<String>, checks: Vec<VerificationCheck>) -> Self {
        let mut report = Self {
            schema: VERIFICATION_REPORT_SCHEMA.to_string(),
            subject: subject.into(),
            status: VerificationStatus::Skipped,
            checks,
            residual_risks: Vec::new(),
            effect_digest: None,
        };
        report.status = report.derive_status();
        report
    }

    pub fn from_program_hints(subject: &str, hints: &[ProgramVerificationHint]) -> Self {
        let checks = hints
            .iter()
            .enumerate()
            .map(|(index, hint)| VerificationCheck::from_program_hint(subject, index, hint))
            .collect();
        Self::new(format!("program:{subject}"), checks)
    }

    pub fn with_effect_digest(mut self, digest: impl Into<String>) -> Self {
        self.effect_digest = Some(digest.into());
        self
    }

    pub fn with_residual_risk(mut self, risk: impl Into<String>) -> Self {
        self.residual_risks.push(risk.into());
        self.status = self.derive_status();
        self
    }

    pub fn is_complete(&self) -> bool {
        !matches!(self.status, VerificationStatus::NeedsReview)
    }

    pub fn to_value(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or_else(|_| {
            serde_json::json!({
                "schema": VERIFICATION_REPORT_SCHEMA,
                "subject": self.subject,
                "status": "failed",
                "checks": [],
                "residual_risks": ["failed to serialize verification report"],
            })
        })
    }

    fn derive_status(&self) -> VerificationStatus {
        if self
            .checks
            .iter()
            .any(|check| check.status == VerificationStatus::Failed)
        {
            return VerificationStatus::Failed;
        }

        if self.checks.iter().any(|check| {
            check.required
                && matches!(
                    check.status,
                    VerificationStatus::NeedsReview | VerificationStatus::Skipped
                )
        }) {
            return VerificationStatus::NeedsReview;
        }

        if !self.residual_risks.is_empty() {
            return VerificationStatus::NeedsReview;
        }

        if self.checks.is_empty() {
            VerificationStatus::Skipped
        } else {
            VerificationStatus::Passed
        }
    }
}

fn artifact_uris(metadata: Option<&serde_json::Value>) -> Vec<String> {
    let mut uris = Vec::new();
    if let Some(metadata) = metadata {
        collect_artifact_uris(metadata, &mut uris);
    }
    uris.sort();
    uris.dedup();
    uris
}

fn collect_artifact_uris(value: &serde_json::Value, uris: &mut Vec<String>) {
    match value {
        serde_json::Value::Object(object) => {
            if let Some(uri) = object.get("artifact_uri").and_then(|value| value.as_str()) {
                uris.push(uri.to_string());
            }
            for value in object.values() {
                collect_artifact_uris(value, uris);
            }
        }
        serde_json::Value::Array(items) => {
            for value in items {
                collect_artifact_uris(value, uris);
            }
        }
        _ => {}
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationSummary {
    pub status: VerificationStatus,
    pub report_count: usize,
    pub required_check_count: usize,
    pub pending_required_check_count: usize,
    pub failed_check_count: usize,
    pub residual_risk_count: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pending_subjects: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub failed_subjects: Vec<String>,
}

impl VerificationSummary {
    pub fn from_reports(reports: &[VerificationReport]) -> Self {
        let mut required_check_count = 0;
        let mut pending_required_check_count = 0;
        let mut failed_check_count = 0;
        let mut residual_risk_count = 0;
        let mut pending_subjects = Vec::new();
        let mut failed_subjects = Vec::new();

        for report in reports {
            if matches!(report.status, VerificationStatus::NeedsReview) {
                pending_subjects.push(report.subject.clone());
            }

            if matches!(report.status, VerificationStatus::Failed) {
                failed_subjects.push(report.subject.clone());
            }

            residual_risk_count += report.residual_risks.len();

            for check in &report.checks {
                if check.required {
                    required_check_count += 1;
                    if matches!(
                        check.status,
                        VerificationStatus::NeedsReview | VerificationStatus::Skipped
                    ) {
                        pending_required_check_count += 1;
                        pending_subjects.push(report.subject.clone());
                    }
                }

                if check.status == VerificationStatus::Failed {
                    failed_check_count += 1;
                    failed_subjects.push(report.subject.clone());
                }

                if check.residual_risk.is_some() {
                    residual_risk_count += 1;
                    pending_subjects.push(report.subject.clone());
                }
            }
        }

        pending_subjects.sort();
        pending_subjects.dedup();
        failed_subjects.sort();
        failed_subjects.dedup();

        let status = if failed_check_count > 0
            || reports
                .iter()
                .any(|report| report.status == VerificationStatus::Failed)
        {
            VerificationStatus::Failed
        } else if pending_required_check_count > 0
            || residual_risk_count > 0
            || reports
                .iter()
                .any(|report| report.status == VerificationStatus::NeedsReview)
        {
            VerificationStatus::NeedsReview
        } else if reports.is_empty() {
            VerificationStatus::Skipped
        } else {
            VerificationStatus::Passed
        };

        Self {
            status,
            report_count: reports.len(),
            required_check_count,
            pending_required_check_count,
            failed_check_count,
            residual_risk_count,
            pending_subjects,
            failed_subjects,
        }
    }

    pub fn is_complete(&self) -> bool {
        !matches!(self.status, VerificationStatus::NeedsReview)
    }

    /// Whether structured verification is strong enough to authorize `GoalAchieved`.
    ///
    /// Fail-closed: empty reports, skipped/optional-only passes, pending required
    /// checks, failures, and residual risks never authorize completion by themselves.
    /// An LLM may still evaluate prose, but the host/core gate requires this.
    pub fn supports_goal_achievement(&self) -> bool {
        matches!(self.status, VerificationStatus::Passed)
            && self.report_count > 0
            && self.required_check_count > 0
            && self.pending_required_check_count == 0
            && self.failed_check_count == 0
            && self.residual_risk_count == 0
    }

    pub fn to_value(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or_else(|_| {
            serde_json::json!({
                "status": "failed",
                "report_count": self.report_count,
                "required_check_count": self.required_check_count,
                "pending_required_check_count": self.pending_required_check_count,
                "failed_check_count": self.failed_check_count,
                "residual_risk_count": self.residual_risk_count,
                "failed_subjects": ["failed to serialize verification summary"],
            })
        })
    }
}

/// Normalize shell text for preset command coverage checks.
pub fn normalize_shell_command(command: &str) -> String {
    command.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// True when `command` executes `preset` (exact, with trailing args, or after `&&` / `;`).
pub fn shell_command_covers_preset(command: &str, preset: &str) -> bool {
    let command = normalize_shell_command(command);
    let preset = normalize_shell_command(preset);
    if command.is_empty() || preset.is_empty() {
        return false;
    }
    if command == preset || command.starts_with(&format!("{preset} ")) {
        return true;
    }
    let and_prefix = format!("&& {preset}");
    let semi_prefix = format!("; {preset}");
    command.contains(&format!("{and_prefix} "))
        || command.ends_with(&and_prefix)
        || command.contains(&format!("{semi_prefix} "))
        || command.ends_with(&semi_prefix)
}

/// Build a verification report when a shell command covers a workspace preset
/// command **or** a durable `/goal` ACCEPTANCE.md machine criterion
/// (`kind:command` or synthesized `test -f` for `kind:file_exists`).
pub fn shell_verification_report_for_command(
    workspace: &Path,
    command: &str,
    exit_code: i32,
    metadata: Option<&serde_json::Value>,
    execution_error: Option<&str>,
) -> Option<VerificationReport> {
    let matched = verification_presets_for_workspace(workspace)
        .into_iter()
        .flat_map(|preset| preset.commands)
        .chain(acceptance_shell_commands_for_workspace(workspace))
        .find(|preset_command| shell_command_covers_preset(command, &preset_command.command))?;
    let check = matched.check_from_execution(exit_code, metadata, execution_error);
    Some(VerificationReport::new(
        format!("shell:{}", matched.id),
        vec![check],
    ))
}

/// Loop STATE statuses that still own a live `/goal` ACCEPTANCE contract.
///
/// Completed (`verified` / `achieved` / `cancelled`) loops must not pollute
/// shell evidence or GoalAchieved emission for a later goal in the same workspace.
const ACTIVE_GOAL_LOOP_STATUSES: &[&str] = &["running", "retrying", "paused"];

/// True when `STATE.md` marks this loop as still owning durable ACCEPTANCE.
fn loop_owns_active_acceptance_contract(loop_dir: &Path) -> bool {
    let Ok(state) = std::fs::read_to_string(loop_dir.join("STATE.md")) else {
        return false;
    };
    for line in state.lines() {
        let trimmed = line.trim();
        let Some(status) = trimmed.strip_prefix("Status:") else {
            continue;
        };
        let status = status.trim();
        return ACTIVE_GOAL_LOOP_STATUSES
            .iter()
            .any(|allowed| status.eq_ignore_ascii_case(allowed));
    }
    false
}

/// Parse machine ACCEPTANCE criteria from **active** `.a3s/loops/*/ACCEPTANCE.md`
/// so Core shell evidence and Host ACCEPTANCE re-checks share the same predicates.
///
/// Only loops whose `STATE.md` is `running`, `retrying`, or `paused` contribute.
/// Stale completed loops are ignored (avoids leftover `assert:true` authorizing
/// a later goal).
///
/// - `kind:command` → the assert command (with optional `expect:exit`)
/// - `kind:file_exists` → synthesized `test -f <path>` (exit 0 == exists)
pub fn acceptance_shell_commands_for_workspace(
    workspace: impl AsRef<Path>,
) -> Vec<VerificationCommand> {
    let loops = workspace.as_ref().join(".a3s").join("loops");
    let Ok(entries) = std::fs::read_dir(&loops) else {
        return Vec::new();
    };
    let mut commands = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        if !loop_owns_active_acceptance_contract(&path) {
            continue;
        }
        let acceptance = path.join("ACCEPTANCE.md");
        let Ok(body) = std::fs::read_to_string(&acceptance) else {
            continue;
        };
        let loop_id = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("goal");
        commands.extend(parse_acceptance_shell_commands(
            &body,
            loop_id,
            workspace.as_ref(),
        ));
    }
    commands
}

fn parse_acceptance_shell_commands(
    body: &str,
    loop_id: &str,
    workspace: &Path,
) -> Vec<VerificationCommand> {
    let mut commands = Vec::new();
    for (index, line) in body.lines().enumerate() {
        let trimmed = line.trim_start();
        let rest = if let Some(rest) = trimmed.strip_prefix("- [") {
            rest
        } else if let Some(rest) = trimmed.strip_prefix("* [") {
            rest
        } else {
            continue;
        };
        let Some((_mark, body)) = rest.split_once(']') else {
            continue;
        };
        let body = body.trim().trim_start_matches(':').trim();
        let lower = body.to_ascii_lowercase();
        let line_id = format!("acceptance:{loop_id}:{}", index + 1);
        if lower.starts_with("kind:command") {
            let Some(command) = extract_acceptance_assert_command(body) else {
                continue;
            };
            let expect_exit = extract_acceptance_expect_exit(body).unwrap_or(0);
            commands.push(
                VerificationCommand::required(
                    line_id,
                    "acceptance_command",
                    format!("ACCEPTANCE kind:command ({loop_id})"),
                    command,
                )
                .with_expect_exit(expect_exit),
            );
            continue;
        }
        if lower.starts_with("kind:file_exists") || lower.starts_with("kind:file-exists") {
            let Some(path) = extract_acceptance_assert_command(body) else {
                continue;
            };
            // Skip workspace-escaping paths so Core evidence matches Host latch
            // (durable goals prove in-workspace outcomes only).
            if !acceptance_file_path_allowed_in_workspace(workspace, &path) {
                continue;
            }
            let command = format!("test -f {}", shell_quote_acceptance_path(&path));
            commands.push(VerificationCommand::required(
                line_id,
                "acceptance_file_exists",
                format!("ACCEPTANCE kind:file_exists ({loop_id})"),
                command,
            ));
        }
    }
    commands
}

/// Whether a `kind:file_exists` assert may contribute Core shell evidence.
///
/// Relative `../` escapes are rejected. Absolute paths are accepted only when
/// they canonicalize to a regular file under the workspace (otherwise Host
/// latch is the authority and Core must not treat them as machine evidence).
fn acceptance_file_path_allowed_in_workspace(workspace: &Path, path: &str) -> bool {
    if path.is_empty() {
        return false;
    }
    let p = Path::new(path);
    if !p.is_absolute() {
        let mut depth = 0i32;
        for component in p.components() {
            match component {
                std::path::Component::ParentDir => {
                    depth -= 1;
                    if depth < 0 {
                        return false;
                    }
                }
                std::path::Component::Normal(_) => depth += 1,
                std::path::Component::RootDir | std::path::Component::Prefix(_) => return false,
                std::path::Component::CurDir => {}
            }
        }
        return true;
    }
    let Ok(workspace_canon) = workspace.canonicalize() else {
        return false;
    };
    let candidate = PathBuf::from(path);
    if !candidate.is_file() {
        return false;
    }
    let Ok(file_canon) = candidate.canonicalize() else {
        return false;
    };
    file_canon.starts_with(&workspace_canon)
}

/// Quote a path for a synthesized `test -f` ACCEPTANCE predicate.
fn shell_quote_acceptance_path(path: &str) -> String {
    if path.is_empty() {
        return "''".to_string();
    }
    if path
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'))
    {
        return path.to_string();
    }
    format!("'{}'", path.replace('\'', "'\\''"))
}

fn extract_acceptance_assert_command(body: &str) -> Option<String> {
    let idx = body.to_ascii_lowercase().find("assert:")?;
    let after = body[idx + "assert:".len()..].trim_start();
    if let Some(rest) = after.strip_prefix('`') {
        let end = rest.find('`')?;
        let command = rest[..end].trim();
        if command.is_empty() {
            return None;
        }
        return Some(command.to_string());
    }
    let command = after
        .split_whitespace()
        .next()
        .filter(|token| !token.to_ascii_lowercase().starts_with("expect:"))?;
    Some(command.to_string())
}

fn extract_acceptance_expect_exit(body: &str) -> Option<i32> {
    let lower = body.to_ascii_lowercase();
    let idx = lower.find("expect:exit=")?;
    let after = &body[idx + "expect:exit=".len()..];
    let digits: String = after
        .chars()
        .take_while(|c| c.is_ascii_digit() || *c == '-')
        .collect();
    digits.parse().ok()
}

/// Merge a shell-preset verification report into tool metadata when applicable.
pub fn merge_shell_verification_metadata(
    metadata: Option<serde_json::Value>,
    workspace: Option<&Path>,
    command: &str,
    exit_code: i32,
    execution_error: Option<&str>,
) -> Option<serde_json::Value> {
    let mut metadata = metadata.unwrap_or_else(|| serde_json::json!({}));
    if let Some(object) = metadata.as_object_mut() {
        object.insert(
            "verification_shell_command".to_string(),
            serde_json::Value::String(command.to_string()),
        );
    }
    let Some(workspace) = workspace else {
        return Some(metadata);
    };
    if metadata.get("verification_report").is_some() {
        return Some(metadata);
    }
    let Some(report) = shell_verification_report_for_command(
        workspace,
        command,
        exit_code,
        Some(&metadata),
        execution_error,
    ) else {
        return Some(metadata);
    };
    if let Some(object) = metadata.as_object_mut() {
        object.insert("verification_report".to_string(), report.to_value());
    }
    Some(metadata)
}

/// One shell segment that is only an existence check, plus the path it names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExistenceCheck {
    pub segment: String,
    pub path: String,
}

/// Existence checks inside a command.
///
/// A segment must itself be `test -f`, `test -e`, `[ -f ]`, `[ -e ]`, or
/// `[[ -f ]]` / `[[ -e ]]`. `&&`, `||`, `;`, and newlines separate segments, so
/// a `cd` prefix or a trailing `echo` still counts. A command that merely
/// mentions those words (`cargo test`, `echo test -f file`, `true`) does not.
pub(crate) fn existence_checks(command: &str) -> Vec<ExistenceCheck> {
    shell_segments(command)
        .into_iter()
        .filter_map(|segment| {
            let path = path_from_single_existence_check(segment)?;
            Some(ExistenceCheck {
                segment: segment.to_string(),
                path,
            })
        })
        .collect()
}

/// Extract the path from the first existence-check segment.
///
/// Accepts `test -f PATH`, `test -e PATH`, `[ -f PATH ]`, `[ -e PATH ]`, and
/// the same checks inside a compound command.
pub fn path_from_existence_check_command(command: &str) -> Option<String> {
    existence_checks(command)
        .into_iter()
        .next()
        .map(|check| check.path)
}

fn path_from_single_existence_check(command: &str) -> Option<String> {
    let trimmed = command.trim();
    let trimmed = trimmed
        .strip_prefix("command ")
        .map(str::trim_start)
        .unwrap_or(trimmed);
    if let Some(rest) = trimmed.strip_prefix("[[") {
        let rest = rest.trim_start();
        let rest = rest
            .strip_prefix("-f")
            .or_else(|| rest.strip_prefix("-e"))?
            .trim_start();
        let rest = rest.trim_end().strip_suffix("]]")?.trim();
        return unquote_shell_token(rest);
    }
    let rest = if let Some(rest) = trimmed.strip_prefix("test") {
        let rest = rest.trim_start();
        let rest = rest
            .strip_prefix("-f")
            .or_else(|| rest.strip_prefix("-e"))?
            .trim_start();
        rest
    } else {
        let rest = trimmed.strip_prefix('[')?;
        let rest = rest.trim_start();
        let rest = rest
            .strip_prefix("-f")
            .or_else(|| rest.strip_prefix("-e"))?
            .trim_start();
        rest.trim_end()
            .trim_end_matches(']')
            .trim_end()
            .trim_start()
    };
    unquote_shell_token(rest)
}

/// Split on unquoted `&&`, `||`, `;`, and newlines. Quotes stay intact so a
/// path that contains those characters is not a separator.
fn shell_segments(command: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    let mut start = 0;
    let mut quote: Option<char> = None;
    let chars: Vec<(usize, char)> = command.char_indices().collect();
    let mut index = 0;
    while index < chars.len() {
        let (byte, ch) = chars[index];
        if let Some(open) = quote {
            if ch == open {
                quote = None;
            }
            index += 1;
            continue;
        }
        if ch == '\'' || ch == '"' {
            quote = Some(ch);
            index += 1;
            continue;
        }
        let doubled = index + 1 < chars.len()
            && ((ch == '&' && chars[index + 1].1 == '&')
                || (ch == '|' && chars[index + 1].1 == '|'));
        if doubled || ch == ';' || ch == '\n' {
            let segment = command[start..byte].trim();
            if !segment.is_empty() {
                segments.push(segment);
            }
            index += if doubled { 2 } else { 1 };
            start = chars
                .get(index)
                .map(|(next, _)| *next)
                .unwrap_or(command.len());
            continue;
        }
        index += 1;
    }
    let tail = command[start..].trim();
    if !tail.is_empty() {
        segments.push(tail);
    }
    segments
}

fn unquote_shell_token(token: &str) -> Option<String> {
    let token = token.trim();
    if token.is_empty() {
        return None;
    }
    if let Some(inner) = token.strip_prefix('\'') {
        let end = inner.find('\'')?;
        return Some(inner[..end].replace("'\\''", "'"));
    }
    if let Some(inner) = token.strip_prefix('"') {
        let end = inner.find('"')?;
        return Some(inner[..end].to_string());
    }
    Some(token.split_whitespace().next()?.to_string())
}

/// Path-boundary match for mutation verification (not basename-only).
pub(crate) fn mutation_path_matches(mutated: &str, verified: &str) -> bool {
    let mutated = mutated.trim_start_matches("./");
    let verified = verified.trim_start_matches("./");
    if mutated.is_empty() || verified.is_empty() {
        return false;
    }
    if mutated == verified {
        return true;
    }
    // Require a path-boundary suffix match. Basename-only equality across
    // different directories would overfit the gate to false verification.
    mutated.ends_with(&format!("/{verified}")) || verified.ends_with(&format!("/{mutated}"))
}

fn report_is_required_pass(report: &VerificationReport) -> bool {
    matches!(report.status, VerificationStatus::Passed)
        && report.checks.iter().any(|check| check.required)
        && report
            .checks
            .iter()
            .filter(|check| check.required)
            .all(|check| matches!(check.status, VerificationStatus::Passed))
}

/// When a Host shell check proves a mutated path still exists (`test -f` /
/// ACCEPTANCE `kind:file_exists` synthesized to `test -f`), bind the current
/// mutation ledger digest so the completion gate can Allow(Verified). Bare
/// `true` / unrelated presets do not bind — that would overfit the gate.
///
/// Prefer [`bind_host_shell_reports_to_mutations_with_content`] for write-backed
/// mutations so wrong on-disk bytes cannot Verify.
pub fn bind_host_shell_reports_to_mutations(
    reports: &mut [VerificationReport],
    shell_command: Option<&str>,
    mutation_paths: &[String],
    effect_digest: &str,
) {
    bind_host_shell_reports_to_mutations_with_content(
        reports,
        shell_command,
        mutation_paths,
        effect_digest,
        None,
    );
}

/// Like [`bind_host_shell_reports_to_mutations`], optionally requiring
/// `content_match = Some((expected_ledger_digest, on_disk_digest))`.
pub fn bind_host_shell_reports_to_mutations_with_content(
    reports: &mut [VerificationReport],
    shell_command: Option<&str>,
    mutation_paths: &[String],
    effect_digest: &str,
    content_match: Option<(&str, &str)>,
) {
    if mutation_paths.is_empty() || effect_digest.trim().is_empty() {
        return;
    }
    let Some(path) = path_from_existence_check_command(shell_command.unwrap_or("")) else {
        return;
    };
    if !mutation_paths
        .iter()
        .any(|mutated| mutation_path_matches(mutated, &path))
    {
        return;
    }
    if let Some((expected, on_disk)) = content_match {
        if expected.trim().is_empty() || expected != on_disk {
            return;
        }
    }
    for report in reports.iter_mut() {
        if report.effect_digest.is_some() {
            continue;
        }
        if !report_is_required_pass(report) {
            continue;
        }
        report.effect_digest = Some(effect_digest.to_string());
    }
}

/// Synthesize a Host Passed report when bash successfully runs `test -f` /
/// `test -e` on a path that is already on the mutation ledger.
///
/// Existence-only form for ACCEPTANCE predicates. Write-backed mutations should
/// use [`host_report_for_verified_mutation_path_with_content`].
pub fn host_report_for_verified_mutation_path(
    command: &str,
    exit_code: i32,
    mutation_paths: &[String],
    effect_digest: &str,
) -> Option<VerificationReport> {
    host_report_for_verified_mutation_path_with_content(
        command,
        exit_code,
        mutation_paths,
        effect_digest,
        None,
    )
}

/// Like [`host_report_for_verified_mutation_path`] with optional content match.
pub fn host_report_for_verified_mutation_path_with_content(
    command: &str,
    exit_code: i32,
    mutation_paths: &[String],
    effect_digest: &str,
    content_match: Option<(&str, &str)>,
) -> Option<VerificationReport> {
    if exit_code != 0 || effect_digest.trim().is_empty() {
        return None;
    }
    let path = path_from_existence_check_command(command)?;
    if !mutation_paths
        .iter()
        .any(|mutated| mutation_path_matches(mutated, &path))
    {
        return None;
    }
    if let Some((expected, on_disk)) = content_match {
        if expected.trim().is_empty() || expected != on_disk {
            return None;
        }
    }
    let description = if content_match.is_some() {
        format!("Host verified mutated path exists with matching content digest: {path}")
    } else {
        format!("Host verified mutated path still exists: {path}")
    };
    Some(
        VerificationReport::new(
            format!("shell:mutation_path_verify:{path}"),
            vec![VerificationCheck::required(
                format!("mutation_path_verify:{path}"),
                "mutation_path_verify",
                description,
            )
            .with_status(VerificationStatus::Passed)],
        )
        .with_effect_digest(effect_digest),
    )
}

/// Combine an LLM achievement judgment with structured verification evidence.
pub fn goal_achieved_after_evidence_gate(
    llm_achieved: bool,
    reports: &[VerificationReport],
) -> bool {
    llm_achieved && VerificationSummary::from_reports(reports).supports_goal_achievement()
}

/// True when a shell verification subject was derived from ACCEPTANCE.md.
pub fn is_acceptance_verification_subject(subject: &str) -> bool {
    subject.starts_with("shell:acceptance:")
}

/// True when reports include at least one passing ACCEPTANCE-derived shell report.
pub fn reports_include_passing_acceptance(reports: &[VerificationReport]) -> bool {
    reports.iter().any(|report| {
        is_acceptance_verification_subject(&report.subject)
            && matches!(report.status, VerificationStatus::Passed)
            && report
                .checks
                .iter()
                .any(|check| check.required && matches!(check.status, VerificationStatus::Passed))
    })
}

fn reports_include_passing_active_acceptance(
    reports: &[VerificationReport],
    acceptance_commands: &[VerificationCommand],
) -> bool {
    // Group machine criteria by loop id. Every active loop that still owns
    // ACCEPTANCE must have its own passing report — a sibling/orphaned loop's
    // easy criterion must not authorize GoalAchieved for a different loop.
    let mut subjects_by_loop: std::collections::HashMap<String, std::collections::HashSet<String>> =
        std::collections::HashMap::new();
    for command in acceptance_commands {
        let Some(loop_id) = acceptance_loop_id_from_command_id(&command.id) else {
            continue;
        };
        subjects_by_loop
            .entry(loop_id.to_string())
            .or_default()
            .insert(format!("shell:{}", command.id));
    }
    if subjects_by_loop.is_empty() {
        return false;
    }
    subjects_by_loop.values().all(|subjects| {
        reports.iter().any(|report| {
            subjects.contains(&report.subject)
                && matches!(report.status, VerificationStatus::Passed)
                && report.checks.iter().any(|check| {
                    check.required && matches!(check.status, VerificationStatus::Passed)
                })
        })
    })
}

/// Command ids look like `acceptance:<loop_id>:<line>` (loop ids may contain `-`).
fn acceptance_loop_id_from_command_id(command_id: &str) -> Option<&str> {
    let rest = command_id.strip_prefix("acceptance:")?;
    let (loop_id, _line) = rest.rsplit_once(':')?;
    if loop_id.is_empty() {
        return None;
    }
    Some(loop_id)
}

/// Decide whether planning should emit `GoalAchieved` before `End`.
///
/// When the workspace declares durable `/goal` machine ACCEPTANCE criteria on an
/// **active** loop, emission requires a passing report for **each** such loop's
/// criteria — so a workspace preset alone, a completed-loop leftover, or a
/// sibling/orphaned active loop's report cannot authorize GoalAchieved.
/// Host latch still re-checks the current loop ACCEPTANCE.
pub fn should_emit_goal_achieved_for_workspace(
    llm_achieved: bool,
    reports: &[VerificationReport],
    workspace: Option<&Path>,
) -> bool {
    if !goal_achieved_after_evidence_gate(llm_achieved, reports) {
        return false;
    }
    let Some(workspace) = workspace else {
        return true;
    };
    let acceptance = acceptance_shell_commands_for_workspace(workspace);
    if acceptance.is_empty() {
        return true;
    }
    reports_include_passing_active_acceptance(reports, &acceptance)
}

/// Decide whether planning should emit `GoalAchieved` before `End`.
///
/// Kept as a thin wrapper so host/core share one fail-closed contract and tests
/// can pin emission policy without standing up a full agent loop.
pub fn should_emit_goal_achieved(llm_achieved: bool, reports: &[VerificationReport]) -> bool {
    should_emit_goal_achieved_for_workspace(llm_achieved, reports, None)
}

pub fn format_verification_summary(summary: &VerificationSummary) -> String {
    let reports = plural(summary.report_count, "report", "reports");
    let required_checks = plural(
        summary.required_check_count,
        "required check",
        "required checks",
    );

    let mut text = match summary.status {
        VerificationStatus::Skipped if summary.report_count == 0 => {
            "Verification skipped: no reports.".to_string()
        }
        VerificationStatus::Skipped => format!("Verification skipped: {reports}."),
        VerificationStatus::Passed => {
            format!("Verification passed: {reports}, {required_checks}.")
        }
        VerificationStatus::Failed => {
            let failed = if summary.failed_check_count > 0 {
                plural(summary.failed_check_count, "failed check", "failed checks")
            } else {
                "failed report".to_string()
            };
            let subjects = subject_list(&summary.failed_subjects);
            if subjects.is_empty() {
                format!("Verification failed: {failed}. {reports}, {required_checks}.")
            } else {
                format!(
                    "Verification failed: {failed} across subjects: {subjects}. {reports}, {required_checks}."
                )
            }
        }
        VerificationStatus::NeedsReview => {
            let pending = if summary.pending_required_check_count > 0 {
                plural(
                    summary.pending_required_check_count,
                    "pending required check",
                    "pending required checks",
                )
            } else {
                "review required".to_string()
            };
            let subjects = subject_list(&summary.pending_subjects);
            if subjects.is_empty() {
                format!("Verification needs review: {pending}. {reports}, {required_checks}.")
            } else {
                format!(
                    "Verification needs review: {pending} across subjects: {subjects}. {reports}, {required_checks}."
                )
            }
        }
    };

    if summary.residual_risk_count > 0 {
        text.push(' ');
        text.push_str(&format!("Residual risks: {}.", summary.residual_risk_count));
    }

    text
}

pub fn verification_status_label(status: VerificationStatus) -> &'static str {
    match status {
        VerificationStatus::Passed => "passed",
        VerificationStatus::Failed => "failed",
        VerificationStatus::NeedsReview => "needs_review",
        VerificationStatus::Skipped => "skipped",
    }
}

fn plural(count: usize, singular: &str, plural: &str) -> String {
    if count == 1 {
        format!("1 {singular}")
    } else {
        format!("{count} {plural}")
    }
}

fn subject_list(subjects: &[String]) -> String {
    const MAX_SUBJECTS: usize = 5;
    let mut visible: Vec<&str> = subjects
        .iter()
        .take(MAX_SUBJECTS)
        .map(String::as_str)
        .collect();
    if subjects.len() > MAX_SUBJECTS {
        visible.push("...");
    }
    visible.join(", ")
}

pub trait Verifier: Send + Sync {
    fn verify(&self, checks: Vec<VerificationCheck>) -> Result<VerificationReport>;
}

#[derive(Debug, Clone)]
pub struct StaticVerifier {
    subject: String,
}

impl StaticVerifier {
    pub fn new(subject: impl Into<String>) -> Self {
        Self {
            subject: subject.into(),
        }
    }
}

impl Verifier for StaticVerifier {
    fn verify(&self, checks: Vec<VerificationCheck>) -> Result<VerificationReport> {
        Ok(VerificationReport::new(self.subject.clone(), checks))
    }
}

#[cfg(test)]
#[path = "verification/tests.rs"]
mod tests;