cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Adversarial coverage for bound verification evidence reuse.
//!
//! Every test here is a way an unbound, stale, forged, or self-referential
//! record could otherwise turn "no evidence" into PASS. The Git and process
//! boundaries are in-memory doubles, so these stay unit-scoped: the only real
//! filesystem use is a temporary directory holding the records the module is
//! defined to read from disk.
//!
//! The target tree and the Conflux-owned store are separate directories in
//! every case, because that separation is now the contract: nothing this module
//! writes may land inside the tree it is verifying.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use super::*;
use crate::openspec::VerificationDeclaration;

const COMMIT: &str = "1111111111111111111111111111111111111111";
const TREE: &str = "2222222222222222222222222222222222222222";
const BLOB: &str = "3333333333333333333333333333333333333333";
const TOOL_DIGEST: &str = "4444444444444444444444444444444444444444";
const ARTIFACT_DIGEST: &str = "5555555555555555555555555555555555555555";
const REVIEW_BASE: &str = "6666666666666666666666666666666666666666";

fn tool() -> ToolIdentity {
    ToolIdentity {
        path: "/usr/bin/cargo".to_string(),
        executable_digest: TOOL_DIGEST.to_string(),
        version: Some("cargo 1.80.0".to_string()),
    }
}

fn declaration() -> VerificationDeclaration {
    VerificationDeclaration {
        id: Some("bound-evidence-tests".to_string()),
        requirement: Some("acceptance reuses bound evidence".to_string()),
        phase: Some("pre-integration".to_string()),
        owner: Some("conflux-acceptance".to_string()),
        trigger: Some("pull-request-validation".to_string()),
        automation: Some("src/orchestration/acceptance.rs".to_string()),
        evidence: Some("cargo test orchestration::acceptance --lib".to_string()),
        rerun: Some("cargo test orchestration::acceptance --lib".to_string()),
        prerequisites: Some(Vec::new()),
        execution_class: Some("repository-local".to_string()),
        completion_role: Some("change-blocking".to_string()),
    }
}

fn request() -> VerificationRequest {
    eligible_request(&declaration()).expect("declaration is eligible")
}

fn evidence() -> VerificationEvidence {
    let started_at = "2026-08-23T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
    VerificationEvidence {
        schema: EVIDENCE_SCHEMA.to_string(),
        authority: EVIDENCE_AUTHORITY.to_string(),
        verification_id: "bound-evidence-tests".to_string(),
        commit_oid: COMMIT.to_string(),
        tree_oid: TREE.to_string(),
        review_base_commit: REVIEW_BASE.to_string(),
        review_range: format!("{REVIEW_BASE}..{COMMIT}"),
        argv: vec![
            "cargo".to_string(),
            "test".to_string(),
            "orchestration::acceptance".to_string(),
            "--lib".to_string(),
        ],
        cwd: ".".to_string(),
        automation_path: "src/orchestration/acceptance.rs".to_string(),
        automation_blob_oid: BLOB.to_string(),
        tool: tool(),
        started_at,
        ended_at: started_at + chrono::Duration::seconds(300),
        exit_code: 0,
        artifact_path: EvidenceStore::artifact_relative_path("bound-evidence-tests"),
        artifact_digest: ARTIFACT_DIGEST.to_string(),
        clean_before: true,
        clean_after: true,
    }
}

fn current() -> CurrentBindings {
    CurrentBindings {
        commit_oid: COMMIT.to_string(),
        tree_oid: TREE.to_string(),
        review: Some(ReviewBinding {
            base_commit: REVIEW_BASE.to_string(),
            range: format!("{REVIEW_BASE}..{COMMIT}"),
        }),
        automation_blob_oid: BLOB.to_string(),
        tool: tool(),
        clean: true,
        artifact_digest: Some(ARTIFACT_DIGEST.to_string()),
    }
}

fn decide(current: CurrentBindings) -> ReuseDecision {
    evaluate_reuse(&request(), &evidence(), &current, ReusePolicy::default())
}

fn rerun_code(decision: &ReuseDecision) -> String {
    match decision {
        ReuseDecision::Reuse { .. } => panic!("expected rerun, got reuse"),
        ReuseDecision::Rerun { reason, .. } => reason.code().to_string(),
    }
}

/// The target tree under test. Always a *sibling* of the store below, never its
/// ancestor, so an accidental target-local write would be visible as an entry
/// somewhere it does not belong.
fn target_of(temp: &tempfile::TempDir) -> PathBuf {
    let target = temp.path().join("target");
    std::fs::create_dir_all(&target).expect("create target");
    target
}

/// The Conflux-owned external store, shaped like the real layout.
fn store_of(temp: &tempfile::TempDir) -> EvidenceStore {
    EvidenceStore::new(
        temp.path()
            .join("cflx-state/acceptance/project-slug/workspace-slug/change-a"),
    )
}

fn mismatch_field(decision: &ReuseDecision) -> String {
    match decision {
        ReuseDecision::Rerun {
            reason: RerunReason::Mismatch { field, .. },
            ..
        } => (*field).to_string(),
        other => panic!("expected a binding mismatch, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Schema and fail-closed parsing
// ---------------------------------------------------------------------------

#[test]
fn exact_record_round_trips_through_the_versioned_schema() {
    let bytes = serde_json::to_vec(&evidence()).expect("serialize");
    let parsed = parse_evidence(&bytes).expect("record parses");
    assert_eq!(parsed, evidence());
    assert_eq!(parsed.elapsed_seconds(), Some(300));
}

#[test]
fn unknown_schema_is_refused_rather_than_migrated() {
    let mut value = serde_json::to_value(evidence()).unwrap();
    value["schema"] = serde_json::json!("conflux-verification-evidence-v0");
    let defect = parse_evidence(&serde_json::to_vec(&value).unwrap()).unwrap_err();
    assert_eq!(defect.code(), "evidence_unknown_schema");
}

#[test]
fn agent_authored_authority_marking_is_refused() {
    let mut record = evidence();
    record.authority = "apply-agent".to_string();
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert_eq!(defect.code(), "evidence_agent_authored");
}

#[test]
fn short_commit_id_is_refused() {
    let mut record = evidence();
    record.commit_oid = "1111111".to_string();
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert_eq!(defect.code(), "evidence_malformed");
    assert!(defect.detail().contains("full-length object id"));
}

#[test]
fn missing_required_field_is_refused() {
    let mut value = serde_json::to_value(evidence()).unwrap();
    value.as_object_mut().unwrap().remove("artifact_digest");
    let defect = parse_evidence(&serde_json::to_vec(&value).unwrap()).unwrap_err();
    assert_eq!(defect.code(), "evidence_malformed");
}

#[test]
fn non_json_bytes_are_refused() {
    let defect = parse_evidence(b"not json at all").unwrap_err();
    assert_eq!(defect.code(), "evidence_malformed");
}

#[test]
fn unsuccessful_exit_is_never_a_candidate() {
    let mut record = evidence();
    record.exit_code = 101;
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert!(defect.detail().contains("not success"));
}

#[test]
fn dirty_capture_is_never_a_candidate() {
    for (before, after) in [(false, true), (true, false), (false, false)] {
        let mut record = evidence();
        record.clean_before = before;
        record.clean_after = after;
        let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
        assert!(defect.detail().contains("dirty"), "{before}/{after}");
    }
}

#[test]
fn reversed_timestamps_are_refused() {
    let mut record = evidence();
    record.ended_at = record.started_at - chrono::Duration::seconds(1);
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert!(defect.detail().contains("precedes"));
}

/// The artifact path is not merely constrained to a prefix — it must be exactly
/// the store-relative path this verification's artifact would occupy. Anything
/// else is a record describing a file the store does not own, whether it points
/// into the target, at another gate, or nowhere at all.
#[test]
fn an_artifact_path_the_store_does_not_own_is_refused() {
    for hostile in [
        "target/output.log",
        "/absolute/output.log",
        "gates/../escape.log",
        "gates/some-other-gate.log",
    ] {
        let mut record = evidence();
        record.artifact_path = hostile.to_string();
        let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
        assert_eq!(defect.code(), "evidence_malformed", "'{hostile}'");
        assert!(
            defect.detail().contains("store-relative"),
            "'{hostile}': {}",
            defect.detail()
        );
    }
}

#[test]
fn escaping_cwd_is_refused() {
    assert_eq!(normalize_relative_cwd("../elsewhere"), None);
    assert_eq!(normalize_relative_cwd("/absolute"), None);
    assert_eq!(normalize_relative_cwd("./src/"), Some("src".to_string()));
    assert_eq!(normalize_relative_cwd(""), Some(".".to_string()));

    let mut record = evidence();
    record.cwd = "../elsewhere".to_string();
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert!(defect.detail().contains("repository-relative"));
}

#[test]
fn traversing_verification_id_cannot_name_a_sidecar() {
    assert!(!is_storable_verification_id("../escape"));
    assert!(!is_storable_verification_id("nested/id"));
    assert!(!is_storable_verification_id(""));
    assert!(is_storable_verification_id("bound-evidence-tests"));
}

// ---------------------------------------------------------------------------
// Declaration eligibility
// ---------------------------------------------------------------------------

#[test]
fn eligible_declaration_becomes_a_plain_argv_request() {
    let request = request();
    assert_eq!(request.verification_id, "bound-evidence-tests");
    assert_eq!(request.argv[0], "cargo");
    assert_eq!(request.cwd, ".");
    assert_eq!(request.automation_path, "src/orchestration/acceptance.rs");
}

#[test]
fn non_repository_local_declaration_is_ineligible() {
    let mut declaration = declaration();
    declaration.execution_class = Some("deployed-service".to_string());
    assert_eq!(
        eligible_request(&declaration).unwrap_err().code(),
        "declaration_not_repository_local"
    );
}

#[test]
fn observation_only_declaration_is_ineligible() {
    let mut declaration = declaration();
    declaration.completion_role = Some("operational-observation".to_string());
    assert_eq!(
        eligible_request(&declaration).unwrap_err().code(),
        "declaration_not_change_blocking"
    );
}

#[test]
fn shell_syntax_declaration_is_ineligible() {
    for command in [
        "cargo test | tee out.log",
        "cargo test && cargo clippy",
        "cargo test > out.log",
        "FOO=$BAR cargo test",
    ] {
        let mut declaration = declaration();
        declaration.rerun = Some(command.to_string());
        assert_eq!(
            eligible_request(&declaration).unwrap_err().code(),
            "declaration_shell_syntax",
            "{command}"
        );
    }
}

// ---------------------------------------------------------------------------
// Fail-closed validator: one test per mismatch class
// ---------------------------------------------------------------------------

#[test]
fn exact_match_is_reused() {
    let decision = decide(current());
    assert!(decision.is_reuse());
    assert_eq!(decision.outcome(), "reused");
    assert_eq!(decision.verification_id(), "bound-evidence-tests");
    assert_eq!(decision.to_json()["outcome"], "reused");
}

#[test]
fn stale_commit_reruns() {
    let mut current = current();
    current.commit_oid = "9999999999999999999999999999999999999999".to_string();
    assert_eq!(mismatch_field(&decide(current)), "commit_oid");
}

#[test]
fn stale_tree_reruns() {
    let mut current = current();
    current.tree_oid = "8888888888888888888888888888888888888888".to_string();
    assert_eq!(mismatch_field(&decide(current)), "tree_oid");
}

#[test]
fn changed_automation_blob_reruns() {
    let mut current = current();
    current.automation_blob_oid = "7777777777777777777777777777777777777777".to_string();
    assert_eq!(mismatch_field(&decide(current)), "automation_blob_oid");
}

#[test]
fn different_executable_reruns() {
    let mut current = current();
    current.tool.path = "/opt/homebrew/bin/cargo".to_string();
    assert_eq!(mismatch_field(&decide(current)), "tool_path");
}

#[test]
fn upgraded_executable_reruns() {
    let mut current = current();
    current.tool.executable_digest = "6666666666666666666666666666666666666666".to_string();
    assert_eq!(mismatch_field(&decide(current)), "tool_digest");
}

#[test]
fn different_tool_version_reruns() {
    let mut current = current();
    current.tool.version = Some("cargo 1.81.0".to_string());
    assert_eq!(mismatch_field(&decide(current)), "tool_version");
}

#[test]
fn changed_command_reruns() {
    let mut declaration = declaration();
    declaration.rerun = Some("cargo test orchestration --lib".to_string());
    let request = eligible_request(&declaration).unwrap();
    let decision = evaluate_reuse(&request, &evidence(), &current(), ReusePolicy::default());
    assert_eq!(mismatch_field(&decision), "argv");
}

#[test]
fn evidence_for_another_verification_id_cannot_satisfy_this_one() {
    let mut record = evidence();
    record.verification_id = "some-other-verification".to_string();
    let decision = evaluate_reuse(&request(), &record, &current(), ReusePolicy::default());
    assert_eq!(mismatch_field(&decision), "verification_id");
}

#[test]
fn rewritten_artifact_reruns() {
    let mut current = current();
    current.artifact_digest = Some("0000000000000000000000000000000000000000".to_string());
    assert_eq!(mismatch_field(&decide(current)), "artifact_digest");
}

#[test]
fn missing_artifact_reruns() {
    let mut current = current();
    current.artifact_digest = None;
    assert_eq!(rerun_code(&decide(current)), "evidence_unreadable");
}

#[test]
fn dirty_worktree_reruns() {
    let mut current = current();
    current.clean = false;
    assert_eq!(rerun_code(&decide(current)), "worktree_dirty");
}

#[test]
fn cheap_command_stays_on_the_rerun_path() {
    let mut record = evidence();
    record.ended_at = record.started_at + chrono::Duration::seconds(3);
    let decision = evaluate_reuse(&request(), &record, &current(), ReusePolicy::default());
    assert_eq!(rerun_code(&decision), "below_reuse_duration_threshold");
    assert!(decision.summary().contains("60s reuse threshold"));
}

#[test]
fn duration_policy_threshold_is_repository_tracked() {
    let policy = ReusePolicy {
        min_reuse_seconds: 1,
    };
    let mut record = evidence();
    record.ended_at = record.started_at + chrono::Duration::seconds(3);
    let decision = evaluate_reuse(&request(), &record, &current(), policy);
    assert!(decision.is_reuse());
    assert_eq!(ReusePolicy::default().min_reuse_seconds, 60);
}

#[test]
fn every_rerun_reason_states_an_actionable_detail() {
    let reasons = [
        RerunReason::Ineligible(IneligibleReason::MissingCommand),
        RerunReason::Defect(EvidenceDefect::Missing),
        RerunReason::Mismatch {
            field: "commit_oid",
            recorded: COMMIT.to_string(),
            current: TREE.to_string(),
        },
        RerunReason::DirtyWorktree(vec![" M src/lib.rs".to_string()]),
        RerunReason::Unobservable("git rev-parse failed".to_string()),
        RerunReason::BelowDurationThreshold {
            elapsed: 2,
            threshold: 60,
        },
    ];
    for reason in reasons {
        assert!(!reason.code().is_empty());
        assert!(reason.detail().len() > 10, "{}", reason.code());
    }
}

// ---------------------------------------------------------------------------
// Cleanliness: no Conflux-owned path is excluded any more
// ---------------------------------------------------------------------------

/// The exclusion is gone, not relaxed. Constitutional law 4 says a cleanliness
/// exception does not make a Conflux-owned write permissible, so the honest
/// implementation has no exception at all — and since nothing lands in the
/// target now, there is nothing left for one to protect.
#[test]
fn a_conflux_owned_path_in_the_target_is_dirty_like_any_other() {
    let status = format!(
        "?? {LEGACY_EVIDENCE_DIR}/\n\
         ?? {LEGACY_EVIDENCE_DIR}/bound-evidence-tests.json\n\
          M {LEGACY_EVIDENCE_DIR}/bound-evidence-tests.log\n"
    );
    assert_eq!(
        dirty_entries(&status).len(),
        3,
        "no path is exempt from the tracked/untracked porcelain status"
    );
}

#[test]
fn every_status_entry_counts_as_dirty() {
    let status = " M src/lib.rs\n?? untracked.txt\nA  staged.rs\n";
    assert_eq!(
        dirty_entries(status),
        vec![
            "M src/lib.rs".to_string(),
            "?? untracked.txt".to_string(),
            "A  staged.rs".to_string(),
        ]
    );
}

#[test]
fn a_clean_status_has_no_dirty_entries() {
    assert!(dirty_entries("").is_empty());
}

/// A rename is one entry, whichever side of it you look at: there is no longer
/// a rule that inspects the paths at all.
#[test]
fn a_rename_is_one_dirty_entry() {
    assert_eq!(dirty_entries("R  a.log -> src/leaked.log\n").len(), 1);
}

// ---------------------------------------------------------------------------
// Store authority
// ---------------------------------------------------------------------------

/// The envelope is read-only and runtime-owned, it lives in the external store,
/// and — the part this change adds — no ignore file is written anywhere. Hiding
/// an artifact was never what made one permissible; not writing it into the
/// target is.
#[test]
fn store_writes_a_read_only_envelope_outside_the_target() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let target = target_of(&workspace);
    let store = store_of(&workspace);
    store.store(&evidence()).expect("store");

    let loaded = store.load("bound-evidence-tests").expect("load");
    assert_eq!(loaded, evidence());

    assert!(
        !store.root().starts_with(&target),
        "the store must not be inside the target: {:?}",
        store.root()
    );
    assert_eq!(
        std::fs::read_dir(&target)
            .expect("read target")
            .filter_map(Result::ok)
            .count(),
        0,
        "storing evidence must write nothing into the target"
    );
    assert!(
        !store.directory().join(".gitignore").exists() && !store.root().join(".gitignore").exists(),
        "no self-ignoring file may be written any more"
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let envelope = store.root().join(EvidenceStore::envelope_relative_path(
            "bound-evidence-tests",
        ));
        let mode = std::fs::metadata(&envelope).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o400);
    }
}

/// The store-relative artifact path is part of the record's validity: an
/// envelope naming a repository-relative path — the version-1 shape — is
/// malformed rather than migrated.
#[test]
fn a_target_relative_artifact_path_is_malformed() {
    let mut record = evidence();
    record.artifact_path = format!("{LEGACY_EVIDENCE_DIR}/bound-evidence-tests.log");
    let defect = parse_evidence(&serde_json::to_vec(&record).unwrap()).unwrap_err();
    assert_eq!(defect.code(), "evidence_malformed");
    assert!(
        defect.detail().contains("store-relative"),
        "{}",
        defect.detail()
    );
}

/// Legacy detection is existence, nothing more: no read, no parse, no delete.
#[test]
fn legacy_target_evidence_is_detected_by_existence_alone() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let target = target_of(&workspace);
    assert!(legacy_target_evidence(&target).is_none());

    let legacy = target.join(LEGACY_EVIDENCE_DIR);
    std::fs::create_dir_all(&legacy).expect("create legacy");
    std::fs::write(legacy.join("focused-gate.json"), b"unreadable").expect("write legacy");

    let found = legacy_target_evidence(&target).expect("existing legacy evidence is reported");
    assert_eq!(found, legacy);
    assert!(
        legacy.join("focused-gate.json").is_file(),
        "the probe must not delete what it finds"
    );
}

#[test]
fn store_replaces_a_previous_read_only_sidecar() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let store = store_of(&workspace);
    store.store(&evidence()).expect("first store");
    let mut second = evidence();
    second.commit_oid = "abababababababababababababababababababab".to_string();
    store.store(&second).expect("second store");
    assert_eq!(
        store.load("bound-evidence-tests").unwrap().commit_oid,
        second.commit_oid
    );
}

#[test]
fn missing_sidecar_reports_missing_rather_than_failure() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let store = store_of(&workspace);
    assert_eq!(
        store.load("bound-evidence-tests"),
        Err(EvidenceDefect::Missing)
    );
}

#[cfg(unix)]
#[test]
fn a_writable_envelope_is_reported_as_agent_authored() {
    use std::os::unix::fs::PermissionsExt;

    let workspace = tempfile::tempdir().expect("tempdir");
    let store = store_of(&workspace);
    store.ensure_directory().expect("directory");
    let envelope = store.root().join(EvidenceStore::envelope_relative_path(
        "bound-evidence-tests",
    ));
    std::fs::write(&envelope, serde_json::to_vec(&evidence()).unwrap()).expect("write");
    std::fs::set_permissions(&envelope, std::fs::Permissions::from_mode(0o644)).expect("chmod");

    let defect = store.load("bound-evidence-tests").unwrap_err();
    assert_eq!(defect.code(), "evidence_agent_authored");
}

// ---------------------------------------------------------------------------
// Runtime executor with injected adapters
// ---------------------------------------------------------------------------

#[derive(Clone, Default)]
struct FakeFacts {
    commit: Arc<Mutex<String>>,
    tree: Arc<Mutex<String>>,
    blobs: Arc<Mutex<HashMap<String, String>>>,
    status: Arc<Mutex<String>>,
    tool: Arc<Mutex<ToolIdentity>>,
    /// Digest returned for any hashed file, keyed by call order.
    digests: Arc<Mutex<Vec<String>>>,
    failure: Arc<Mutex<Option<String>>>,
}

impl FakeFacts {
    fn new() -> Self {
        let facts = Self {
            commit: Arc::new(Mutex::new(COMMIT.to_string())),
            tree: Arc::new(Mutex::new(TREE.to_string())),
            blobs: Arc::new(Mutex::new(HashMap::from([(
                "src/orchestration/acceptance.rs".to_string(),
                BLOB.to_string(),
            )]))),
            status: Arc::new(Mutex::new(String::new())),
            tool: Arc::new(Mutex::new(tool())),
            digests: Arc::new(Mutex::new(Vec::new())),
            failure: Arc::new(Mutex::new(None)),
        };
        facts
            .digests
            .lock()
            .unwrap()
            .push(ARTIFACT_DIGEST.to_string());
        facts
    }

    fn check(&self) -> Result<(), String> {
        match self.failure.lock().unwrap().clone() {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }
}

#[async_trait]
impl RepositoryFacts for FakeFacts {
    async fn head_commit(&self, _workspace: &Path) -> Result<String, String> {
        self.check()?;
        Ok(self.commit.lock().unwrap().clone())
    }

    async fn head_tree(&self, _workspace: &Path) -> Result<String, String> {
        self.check()?;
        Ok(self.tree.lock().unwrap().clone())
    }

    async fn tracked_blob_oid(&self, _workspace: &Path, path: &str) -> Result<String, String> {
        self.check()?;
        self.blobs
            .lock()
            .unwrap()
            .get(path)
            .cloned()
            .ok_or_else(|| format!("no blob for {path}"))
    }

    async fn hash_file(&self, _workspace: &Path, _path: &Path) -> Result<String, String> {
        self.check()?;
        let mut digests = self.digests.lock().unwrap();
        if digests.len() > 1 {
            Ok(digests.remove(0))
        } else {
            digests
                .first()
                .cloned()
                .ok_or_else(|| "no digest configured".to_string())
        }
    }

    async fn porcelain_status(&self, _workspace: &Path) -> Result<String, String> {
        self.check()?;
        Ok(self.status.lock().unwrap().clone())
    }

    async fn resolve_tool(
        &self,
        _workspace: &Path,
        _program: &str,
    ) -> Result<ToolIdentity, String> {
        self.check()?;
        Ok(self.tool.lock().unwrap().clone())
    }
}

#[derive(Clone)]
struct FakeSupervisor {
    exit_code: i32,
    output: Vec<u8>,
    calls: Arc<Mutex<Vec<Vec<String>>>>,
    /// Mutation applied to the fake repository while the command "runs".
    during: Arc<dyn Fn() + Send + Sync>,
}

impl FakeSupervisor {
    fn succeeding() -> Self {
        Self {
            exit_code: 0,
            output: b"test result: ok".to_vec(),
            calls: Arc::new(Mutex::new(Vec::new())),
            during: Arc::new(|| {}),
        }
    }
}

#[async_trait]
impl CommandSupervisor for FakeSupervisor {
    async fn run(&self, argv: &[String], _cwd: &Path) -> Result<SupervisedOutcome, String> {
        self.calls.lock().unwrap().push(argv.to_vec());
        (self.during)();
        Ok(SupervisedOutcome {
            exit_code: self.exit_code,
            output: self.output.clone(),
        })
    }
}

/// Advances a fixed amount per observation so elapsed duration is deterministic.
struct StepClock {
    start: DateTime<Utc>,
    step: Arc<Mutex<i64>>,
}

impl StepClock {
    fn new() -> Self {
        Self {
            start: "2026-08-23T00:00:00Z".parse().unwrap(),
            step: Arc::new(Mutex::new(0)),
        }
    }
}

impl Clock for StepClock {
    fn now(&self) -> DateTime<Utc> {
        let mut step = self.step.lock().unwrap();
        let now = self.start + chrono::Duration::seconds(*step * 300);
        *step += 1;
        now
    }
}

/// An executor bound to the target it runs in and the external store it writes
/// to — two separate directories, as production always has them.
fn executor(
    temp: &tempfile::TempDir,
    facts: FakeFacts,
    supervisor: FakeSupervisor,
) -> RuntimeVerificationExecutor<FakeFacts, FakeSupervisor, StepClock> {
    RuntimeVerificationExecutor::new(
        target_of(temp),
        store_of(temp),
        facts,
        supervisor,
        StepClock::new(),
    )
}

#[tokio::test]
async fn runtime_capture_writes_a_reusable_envelope() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    let supervisor = FakeSupervisor::succeeding();
    let outcome = executor(&workspace, facts.clone(), supervisor.clone())
        .capture(&request())
        .await;

    let CaptureOutcome::Captured {
        evidence: captured,
        artifact_location,
    } = &outcome
    else {
        panic!("expected capture, got {outcome:?}");
    };
    assert_eq!(captured.authority, EVIDENCE_AUTHORITY);
    assert_eq!(captured.commit_oid, COMMIT);
    assert_eq!(captured.exit_code, 0);
    assert_eq!(captured.elapsed_seconds(), Some(300));
    assert_eq!(supervisor.calls.lock().unwrap().len(), 1);

    let store = store_of(&workspace);
    assert_eq!(store.load("bound-evidence-tests").unwrap(), **captured);
    let artifact = store.artifact_path("bound-evidence-tests");
    assert_eq!(std::fs::read(&artifact).unwrap(), b"test result: ok");

    // The envelope keeps the store-relative spelling; the report carries the
    // path that actually opens.
    assert_eq!(
        captured.artifact_path,
        EvidenceStore::artifact_relative_path("bound-evidence-tests")
    );
    assert_eq!(artifact_location, &artifact);
    assert_eq!(outcome.artifact_location(), Some(artifact.as_path()));
    assert_eq!(
        outcome.to_json()["artifact_location"].as_str(),
        Some(artifact.display().to_string().as_str())
    );
}

#[tokio::test]
async fn a_failing_command_captures_no_envelope() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let mut supervisor = FakeSupervisor::succeeding();
    supervisor.exit_code = 101;
    supervisor.output = b"error: 1 test failed".to_vec();
    let outcome = executor(&workspace, FakeFacts::new(), supervisor)
        .capture(&request())
        .await;

    assert!(matches!(
        outcome,
        CaptureOutcome::CommandFailed { exit_code: 101, .. }
    ));
    assert_eq!(
        store_of(&workspace).load("bound-evidence-tests"),
        Err(EvidenceDefect::Missing)
    );
}

#[tokio::test]
async fn a_failing_command_reports_an_artifact_path_that_opens() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let mut supervisor = FakeSupervisor::succeeding();
    supervisor.exit_code = 101;
    supervisor.output = b"error: 1 test failed".to_vec();
    let outcome = executor(&workspace, FakeFacts::new(), supervisor)
        .capture(&request())
        .await;

    let CaptureOutcome::CommandFailed {
        artifact_path,
        artifact_location,
        ..
    } = &outcome
    else {
        panic!("expected a command failure, got {outcome:?}");
    };

    // The store-relative spelling stays exactly what the envelope schema uses,
    // and resolves to nothing on its own.
    assert_eq!(
        artifact_path,
        &EvidenceStore::artifact_relative_path("bound-evidence-tests")
    );
    assert!(!Path::new(artifact_path).is_absolute());

    // The reported location is the real file under the external store root, not
    // a bare string: a caller can read the failing output from it directly.
    let store = store_of(&workspace);
    assert!(artifact_location.is_absolute());
    assert!(artifact_location.starts_with(store.root()));
    assert!(!artifact_location.starts_with(target_of(&workspace)));
    assert_eq!(
        std::fs::read(artifact_location).expect("the reported artifact exists on disk"),
        b"error: 1 test failed"
    );

    // And the same location travels on the machine-readable report.
    let reported = outcome.to_json()["artifact_location"]
        .as_str()
        .expect("reports name an openable artifact")
        .to_string();
    assert_eq!(
        std::fs::read(&reported).expect("the reported location is readable"),
        b"error: 1 test failed"
    );
}

#[tokio::test]
async fn capture_is_refused_when_the_worktree_is_dirty_before_execution() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    *facts.status.lock().unwrap() = " M src/lib.rs\n".to_string();
    let supervisor = FakeSupervisor::succeeding();
    let outcome = executor(&workspace, facts, supervisor.clone())
        .capture(&request())
        .await;

    assert!(matches!(
        outcome,
        CaptureOutcome::Refused(CaptureRefusal {
            code: "worktree_dirty",
            ..
        })
    ));
    assert!(
        supervisor.calls.lock().unwrap().is_empty(),
        "a dirty worktree must be refused before the command runs"
    );
}

#[tokio::test]
async fn capture_is_refused_when_a_binding_moves_while_the_command_runs() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    let moved = facts.commit.clone();
    let mut supervisor = FakeSupervisor::succeeding();
    supervisor.during = Arc::new(move || {
        *moved.lock().unwrap() = "cccccccccccccccccccccccccccccccccccccccc".to_string();
    });

    let outcome = executor(&workspace, facts, supervisor)
        .capture(&request())
        .await;
    let CaptureOutcome::Refused(refusal) = outcome else {
        panic!("expected refusal");
    };
    assert_eq!(refusal.code, "binding_moved_during_execution");
    assert_eq!(
        store_of(&workspace).load("bound-evidence-tests"),
        Err(EvidenceDefect::Missing)
    );
}

#[tokio::test]
async fn capture_is_refused_when_the_command_dirties_the_worktree() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    let status = facts.status.clone();
    let mut supervisor = FakeSupervisor::succeeding();
    supervisor.during = Arc::new(move || {
        *status.lock().unwrap() = " M src/generated.rs\n".to_string();
    });

    let outcome = executor(&workspace, facts, supervisor)
        .capture(&request())
        .await;
    assert!(matches!(
        outcome,
        CaptureOutcome::Refused(CaptureRefusal {
            code: "worktree_dirty",
            ..
        })
    ));
}

#[tokio::test]
async fn capture_is_refused_when_repository_state_cannot_be_observed() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    *facts.failure.lock().unwrap() = Some("git rev-parse failed".to_string());
    let outcome = executor(&workspace, facts, FakeSupervisor::succeeding())
        .capture(&request())
        .await;
    assert!(matches!(
        outcome,
        CaptureOutcome::Refused(CaptureRefusal {
            code: "state_unobservable",
            ..
        })
    ));
}

// ---------------------------------------------------------------------------
// End-to-end reuse decisions over the store
// ---------------------------------------------------------------------------

#[tokio::test]
async fn captured_evidence_is_reused_on_the_next_evaluation() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;

    let plan = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(plan.reused_ids(), vec!["bound-evidence-tests"]);
    assert!(plan.rerun_ids().is_empty());
    assert_eq!(plan.to_json()["verifications"][0]["outcome"], "reused");
}

#[tokio::test]
async fn a_new_commit_forces_rerun_of_previously_captured_evidence() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;
    *facts.commit.lock().unwrap() = "dddddddddddddddddddddddddddddddddddddddd".to_string();

    let plan = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(plan.rerun_ids(), vec!["bound-evidence-tests"]);
    assert_eq!(
        plan.to_json()["verifications"][0]["reason"],
        "binding_mismatch"
    );
}

#[tokio::test]
async fn evidence_from_a_dirty_worktree_is_not_reused() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;
    *facts.status.lock().unwrap() = " M src/lib.rs\n".to_string();

    let plan = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(
        plan.to_json()["verifications"][0]["reason"],
        "worktree_dirty"
    );
}

/// The old self-reference problem is solved by *relocation*, not by an
/// exception. A capture writes into the external store, so the target's status
/// is untouched and stays clean, and the very next evaluation reuses the record
/// without anything having to be excluded from the comparison.
#[tokio::test]
async fn a_capture_leaves_the_target_clean_without_any_exclusion() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let target = target_of(&workspace);
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;

    // `FakeFacts` reports the status the runtime would observe: still empty,
    // because nothing was written into the target at all.
    assert!(facts.status.lock().unwrap().is_empty());
    assert_eq!(
        std::fs::read_dir(&target)
            .expect("read target")
            .filter_map(Result::ok)
            .count(),
        0,
        "a capture must write nothing into the target"
    );
    assert!(
        store_of(&workspace)
            .artifact_path("bound-evidence-tests")
            .is_file(),
        "the artifact belongs in the external store"
    );

    let plan = plan_reuse(
        &facts,
        &target,
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(plan.reused_ids(), vec!["bound-evidence-tests"]);
}

/// Deleting the external cache reruns the declared gate. It never proves PASS,
/// and it never changes what the next workflow action would be.
#[tokio::test]
async fn a_deleted_cache_reruns_rather_than_proving_anything() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;
    assert_eq!(
        plan_reuse(
            &facts,
            &target_of(&workspace),
            &store_of(&workspace),
            &[declaration()],
            ReusePolicy::default(),
        )
        .await
        .reused_ids(),
        vec!["bound-evidence-tests"]
    );

    std::fs::remove_dir_all(store_of(&workspace).root()).expect("delete the cache");

    let plan = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(plan.rerun_ids(), vec!["bound-evidence-tests"]);
    assert_eq!(
        plan.to_json()["verifications"][0]["reason"],
        "evidence_missing",
        "cache loss is a rerun reason, never a verdict"
    );
}

#[tokio::test]
async fn missing_evidence_reruns_with_an_actionable_reason() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let plan = plan_reuse(
        &FakeFacts::new(),
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(
        plan.to_json()["verifications"][0]["reason"],
        "evidence_missing"
    );
    assert!(plan.to_json()["verifications"][0]["detail"]
        .as_str()
        .unwrap()
        .contains("runtime-authored"));
}

#[tokio::test]
async fn a_deployed_observation_has_no_local_reuse_decision() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let mut declaration = declaration();
    declaration.execution_class = Some("deployed-service".to_string());
    declaration.completion_role = Some("operational-observation".to_string());
    let plan = plan_reuse(
        &FakeFacts::new(),
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration],
        ReusePolicy::default(),
    )
    .await;
    assert!(plan.is_empty());
}

#[tokio::test]
async fn unobservable_repository_state_reruns_rather_than_reusing() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;
    *facts.failure.lock().unwrap() = Some("git rev-parse failed".to_string());

    let plan = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(
        plan.to_json()["verifications"][0]["reason"],
        "state_unobservable"
    );
}

#[tokio::test]
async fn restart_derives_the_same_decision_from_the_worktree_alone() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let facts = FakeFacts::new();
    executor(&workspace, facts.clone(), FakeSupervisor::succeeding())
        .capture(&request())
        .await;

    // A "restart" is nothing more than dropping every in-memory structure and
    // reading the same worktree again: no cache, no store handle, no prior plan.
    let first = plan_reuse(
        &facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    let restarted_facts = FakeFacts::new();
    let second = plan_reuse(
        &restarted_facts,
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(first, second);
    assert_eq!(second.reused_ids(), vec!["bound-evidence-tests"]);
}

#[tokio::test]
async fn duplicate_declared_ids_produce_one_decision() {
    let workspace = tempfile::tempdir().expect("tempdir");
    let plan = plan_reuse(
        &FakeFacts::new(),
        &target_of(&workspace),
        &store_of(&workspace),
        &[declaration(), declaration()],
        ReusePolicy::default(),
    )
    .await;
    assert_eq!(plan.decisions.len(), 1);
}

#[test]
fn a_tool_that_reports_no_version_records_none() {
    assert_eq!(
        usable_tool_version("  cargo 1.80.0\n"),
        Some("cargo 1.80.0".to_string())
    );
    // `/bin/echo --version` echoes the flag; that is not a version.
    assert_eq!(usable_tool_version("--version\n"), None);
    assert_eq!(usable_tool_version("   \n"), None);
}