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
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
//! End-to-end regressions for the runtime-owned Acceptance execution boundary.
//!
//! These drive `execute_acceptance_in_workspace` against a real Git worktree and
//! two deliberately dumb reviewers:
//!
//! * a **canonical reviewer** that emits a verdict and asks for nothing else,
//!   used to prove that the runtime — not the reviewer — ran the declared gates;
//! * a **non-terminating reviewer** that never exits, used to prove the shared
//!   review deadline terminates it, reaps it, and settles as a typed
//!   non-resumable `stalled` hold rather than the generic runtime-limit `error`.
//!
//! Every reviewer writes a marker file before doing anything else, so "the
//! reviewer never started" is an observable fact rather than an inference. That
//! matters: most of the claims here are about work that must *not* happen.
//!
//! Two properties this file exists to defend, beyond the boundary itself:
//!
//! * **Nothing Conflux owns is written into the target.** Every case that runs a
//!   gate also asserts the target tree is exactly what Git says it should be,
//!   and the evidence is looked for in the external store instead.
//! * **Retry refusal is process-local.** A live owner refuses an unchanged
//!   retry; a restarted one admits a fresh bounded attempt from the same
//!   untouched worktree, because the refusal was never written down anywhere a
//!   restart could read it.
//!
//! Each case uses its own change ID. The live-hold registry is process-wide by
//! design — the executor and the shared operator service must see one fact — so
//! two concurrent cases sharing a change ID would share a refusal.
//!
//! The review budget is scoped to milliseconds for the deadline tests. The
//! production partition is whole seconds and its smallest positive work budget
//! is one second, which is a fine bound for an operator and a poor one for a
//! suite with a one-second total runtime target.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use tempfile::TempDir;
use tokio::process::Command;
use tokio::sync::Mutex;

use super::support::{create_test_config_with, init_git_repo, TestAssertionExt};
use crate::agent::AgentRunner;
use crate::ai_command_runner::AiCommandRunner;
use crate::command_queue::CommandQueueConfig;
use crate::config::defaults::{acceptance_store_path_in, default_retry_patterns};
use crate::config::OrchestratorConfig;
use crate::orchestration::acceptance::evidence_location::scoped_acceptance_root_for_test;
use crate::orchestration::acceptance::execution_manifest::{
    AcceptanceAdmission, AcceptanceHoldCategory, LiveAcceptanceHold, LiveAcceptanceHolds,
    ManifestStore, WorkspaceAcceptanceAdmission,
};
use crate::orchestration::acceptance::manifest_builder::repository_project_root;
use crate::orchestration::acceptance::verification_evidence::{EvidenceStore, LEGACY_EVIDENCE_DIR};
use crate::orchestration::AcceptanceResult;
use crate::parallel::executor::{
    execute_acceptance_in_workspace, scoped_review_budget_millis_for_test,
};

const REVIEWER_MARKER: &str = "reviewer-started.txt";
const GATE: &str = "focused-gate";

/// A proposal whose only eligible declaration is one repository-local
/// change-blocking gate running `command`.
fn proposal_with_gate(change: &str, command: &str) -> String {
    format!(
        "---\n\
verifications:\n\
\x20 - id: {GATE}\n\
\x20   requirement: the focused gate passes\n\
\x20   phase: pre-integration\n\
\x20   owner: conflux\n\
\x20   trigger: pull-request-validation\n\
\x20   automation: openspec/changes/{change}/proposal.md\n\
\x20   evidence: {command}\n\
\x20   rerun: {command}\n\
\x20   prerequisites: []\n\
\x20   execution_class: repository-local\n\
\x20   completion_role: change-blocking\n\
---\n\
# Change\n"
    )
}

/// A proposal that declares nothing eligible: an empty blocking allowlist.
const PROPOSAL_WITHOUT_GATES: &str = "---\nchange_type: implementation\n---\n# Change\n";

/// One case's target repository plus the Conflux-owned external root its
/// Acceptance evidence must land under.
///
/// The two are separate temporary directories on purpose. "The store is not in
/// the target" is the whole contract, and a fixture that could satisfy it by
/// accident would not be testing anything.
struct Fixture {
    repo: TempDir,
    external: TempDir,
    change: String,
}

impl Fixture {
    async fn new(change: &str, proposal: &str) -> Self {
        let repo = TempDir::new().or_fail("unexpected error");
        init_git_repo(repo.path()).await;
        let change_dir = repo.path().join("openspec/changes").join(change);
        std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
        std::fs::write(change_dir.join("proposal.md"), proposal).or_fail("unexpected error");
        std::fs::write(
            change_dir.join("tasks.md"),
            "## Implementation Tasks\n\n- [x] 1. done\n",
        )
        .or_fail("unexpected error");
        commit_all(repo.path(), &format!("Apply: {change}")).await;
        Self {
            repo,
            external: TempDir::new().or_fail("unexpected error"),
            change: change.to_string(),
        }
    }

    fn path(&self) -> &Path {
        self.repo.path()
    }

    fn change(&self) -> &str {
        &self.change
    }

    /// The external directory this change's evidence must resolve to, computed
    /// exactly the way production computes it.
    async fn store_root(&self) -> PathBuf {
        self.store_root_under(self.external.path()).await
    }

    async fn store_root_under(&self, external: &Path) -> PathBuf {
        let project = repository_project_root(self.path())
            .await
            .unwrap_or_else(|| self.path().to_path_buf());
        acceptance_store_path_in(external, &project, self.path(), &self.change)
            .or_fail("the external store path must resolve")
    }

    async fn evidence(&self) -> EvidenceStore {
        EvidenceStore::new(self.store_root().await)
    }

    async fn manifests(&self) -> ManifestStore {
        ManifestStore::new(self.store_root().await)
    }

    fn reviewer_started(&self) -> bool {
        self.path().join(REVIEWER_MARKER).exists()
    }

    fn clear_reviewer_marker(&self) {
        let _ = std::fs::remove_file(self.path().join(REVIEWER_MARKER));
    }

    /// Run one bounded Acceptance invocation with the external root scoped to
    /// this fixture.
    async fn accept(
        &self,
        config: &OrchestratorConfig,
        ai_runner: &AiCommandRunner,
    ) -> (AcceptanceResult, u32) {
        self.accept_under(self.external.path().to_path_buf(), config, ai_runner)
            .await
    }

    async fn accept_under(
        &self,
        external: PathBuf,
        config: &OrchestratorConfig,
        ai_runner: &AiCommandRunner,
    ) -> (AcceptanceResult, u32) {
        scoped_acceptance_root_for_test(
            external,
            run_acceptance(&self.change, self.path(), config, ai_runner),
        )
        .await
    }

    /// The set of paths Git reports as staged, unstaged, or untracked.
    ///
    /// Read with no Conflux exclusion whatsoever, which is the point: if
    /// anything this runtime owns landed in the target, it shows up here.
    async fn porcelain_status(&self) -> String {
        let output = Command::new("git")
            .args(["status", "--porcelain=v1", "--untracked-files=all"])
            .current_dir(self.path())
            .output()
            .await
            .or_fail("unexpected error");
        String::from_utf8_lossy(&output.stdout).to_string()
    }
}

async fn commit_all(repo_root: &std::path::Path, message: &str) {
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
    Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(repo_root)
        .output()
        .await
        .or_fail("unexpected error");
}

/// A reviewer that records that it started, emits a canonical verdict, and asks
/// for nothing else. It runs no verification of its own, which is the point:
/// whatever gate evidence exists came from the runtime.
fn canonical_reviewer() -> String {
    format!("sh -c 'touch {REVIEWER_MARKER}; printf \"ACCEPTANCE: PASS\\n\"'")
}

/// A reviewer that records that it started and then never terminates.
fn non_terminating_reviewer() -> String {
    format!("sh -c 'touch {REVIEWER_MARKER}; while true; do sleep 1; done'")
}

fn config_with_reviewer(command: String) -> OrchestratorConfig {
    create_test_config_with(OrchestratorConfig {
        acceptance_command: Some(command),
        ..Default::default()
    })
}

fn runner(acceptance_max_runtime_secs: u64) -> AiCommandRunner {
    AiCommandRunner::new(
        CommandQueueConfig {
            acceptance_max_runtime_secs,
            stagger_delay_ms: 0,
            max_retries: 0,
            retry_delay_ms: 0,
            retry_error_patterns: default_retry_patterns(),
            retry_if_duration_under_secs: 0,
            inactivity_timeout_secs: 0,
            inactivity_kill_grace_secs: 10,
            inactivity_timeout_max_retries: 0,
            strict_process_cleanup: true,
            max_runtime_secs: 0,
        },
        Arc::new(Mutex::new(None)),
    )
}

async fn run_acceptance(
    change: &str,
    repo_root: &std::path::Path,
    config: &OrchestratorConfig,
    ai_runner: &AiCommandRunner,
) -> (AcceptanceResult, u32) {
    let mut agent = AgentRunner::new(config.clone());
    let acceptance_tail_injected = Arc::new(Mutex::new(std::collections::HashMap::new()));
    let acceptance_history = Arc::new(Mutex::new(crate::history::AcceptanceHistory::new()));
    execute_acceptance_in_workspace(
        change,
        repo_root,
        &mut agent,
        None,
        None,
        ai_runner,
        config,
        &acceptance_tail_injected,
        &acceptance_history,
        Some("main"),
        None,
        crate::orchestration::acceptance::AcceptanceCommandMode::Normal,
    )
    .await
    .or_fail("acceptance must return a typed result")
}

fn hold_of(
    result: AcceptanceResult,
) -> crate::orchestration::acceptance::execution_manifest::AcceptanceExecutionHold {
    match result {
        AcceptanceResult::ExecutionHold { hold } => hold,
        other => panic!("expected a typed execution hold, got {other:?}"),
    }
}

// ============================================================================
// The runtime owns declared gate execution — and writes nothing into the target
// ============================================================================

/// The declared gate ran under runtime supervision, its bound evidence exists in
/// the Conflux-owned external store, the reviewer — which ran no verification at
/// all — still produced a verdict, and the target worktree is byte-for-byte what
/// the Apply commit left behind.
///
/// That last clause is constitutional law 4 as a regression: no envelope, no
/// artifact, no manifest, no ignore file, no `.cflx` directory.
#[tokio::test]
async fn acceptance_execution_boundary_runtime_executes_declared_gates_outside_the_target() {
    let fixture = Fixture::new(
        "gates-outside-target",
        &proposal_with_gate("gates-outside-target", "sh -c true"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = fixture.accept(&config, &runner(3600)).await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "a passing declared gate plus a canonical verdict is a PASS, got {result:?}"
    );
    assert!(
        fixture.reviewer_started(),
        "the semantic reviewer must still run"
    );

    // The evidence exists — externally.
    let store_root = fixture.store_root().await;
    assert!(
        store_root.starts_with(fixture.external.path()),
        "the store must resolve under the configured external root: {store_root:?}"
    );
    assert!(
        !store_root.starts_with(fixture.path()),
        "the store must never resolve inside the target: {store_root:?}"
    );
    assert!(
        store_root.join(format!("gates/{GATE}.json")).is_file(),
        "the runtime must write bound evidence for the gate it supervised"
    );
    assert!(store_root.join(format!("gates/{GATE}.log")).is_file());

    let manifest = fixture
        .manifests()
        .await
        .load()
        .expect("the manifest must be persisted to the external store");
    assert_eq!(
        manifest
            .gates
            .iter()
            .map(|gate| gate.verification_id.as_str())
            .collect::<Vec<_>>(),
        vec![GATE],
        "the manifest is the complete blocking allowlist"
    );
    assert_eq!(manifest.candidate_commit_oid.len(), 40);
    assert!(manifest.review_range.contains(".."));
    assert_eq!(
        manifest.gates[0].artifact_path,
        EvidenceStore::artifact_relative_path(GATE),
        "gate artifacts are bound store-relative, never target-relative"
    );

    // And nothing landed in the target. The reviewer's own marker is the single
    // expected entry; it is the *test's* artifact, not Conflux's.
    let status = fixture.porcelain_status().await;
    let unexpected: Vec<&str> = status
        .lines()
        .filter(|line| !line.ends_with(REVIEWER_MARKER))
        .collect();
    assert!(
        unexpected.is_empty(),
        "Acceptance must create no file or directory in the target: {unexpected:?}"
    );
    assert!(
        !fixture.path().join(".cflx").exists(),
        "no target-local Conflux directory may be created"
    );
    assert!(
        !fixture.path().join(LEGACY_EVIDENCE_DIR).exists(),
        "the legacy evidence path must never be recreated"
    );
}

/// A failing declared gate decides the verdict by itself: the reviewer is never
/// started, so no budget is spent rediscovering what the runtime already knows.
#[tokio::test]
async fn acceptance_execution_boundary_failing_gate_fails_without_starting_a_reviewer() {
    let fixture = Fixture::new(
        "failing-gate",
        &proposal_with_gate("failing-gate", "sh -c false"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());

    let (result, iteration) = fixture.accept(&config, &runner(3600)).await;

    match result {
        AcceptanceResult::Fail { findings } => {
            assert!(
                findings.iter().any(|finding| finding.text().contains(GATE)),
                "the failing gate must be the finding's evidence: {findings:?}"
            );
        }
        other => panic!("a failing declared gate must FAIL the change, got {other:?}"),
    }
    assert!(iteration > 0, "a gate-decided FAIL records a real attempt");
    assert!(
        !fixture.reviewer_started(),
        "the reviewer must not be started once the verdict is already determined"
    );
    assert!(
        fixture.porcelain_status().await.is_empty(),
        "even a failing gate must leave the target untouched"
    );
}

/// A change that declares nothing eligible still reaches a verdict. The empty
/// allowlist is a boundary, not a reason to hold.
#[tokio::test]
async fn acceptance_execution_boundary_empty_allowlist_still_reaches_a_verdict() {
    let fixture = Fixture::new("empty-allowlist", PROPOSAL_WITHOUT_GATES).await;
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = fixture.accept(&config, &runner(3600)).await;

    assert!(matches!(result, AcceptanceResult::Pass), "{result:?}");
    assert!(fixture.reviewer_started());
    let manifest = fixture
        .manifests()
        .await
        .load()
        .expect("even a gateless change gets a manifest");
    assert!(!manifest.has_gates());
}

/// A workspace that is not a Git working tree has no candidate to freeze and no
/// evidence to bind, so it gets no manifest — not a hold. Acceptance runs there
/// exactly as it did before the boundary existed.
///
/// The distinction matters: collapsing "never a repository" into "repository
/// unreadable" would turn every non-repository Acceptance into a permanent hold
/// nobody can clear.
#[tokio::test]
async fn acceptance_execution_boundary_non_repository_workspace_gets_no_manifest() {
    let workspace = TempDir::new().or_fail("unexpected error");
    let external = TempDir::new().or_fail("unexpected error");
    let change = "non-repository";
    let change_dir = workspace.path().join("openspec/changes").join(change);
    std::fs::create_dir_all(&change_dir).or_fail("unexpected error");
    std::fs::write(
        change_dir.join("proposal.md"),
        proposal_with_gate(change, "sh -c true"),
    )
    .or_fail("unexpected error");
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = scoped_acceptance_root_for_test(
        external.path().to_path_buf(),
        run_acceptance(change, workspace.path(), &config, &runner(3600)),
    )
    .await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "a non-repository workspace must keep its pre-boundary behaviour, got {result:?}"
    );
    assert!(workspace.path().join(REVIEWER_MARKER).exists());
    assert_eq!(
        std::fs::read_dir(external.path())
            .or_fail("unexpected error")
            .filter_map(Result::ok)
            .count(),
        0,
        "no store may be created for a workspace with no candidate revision"
    );
}

// ============================================================================
// The external store fails closed, and never into the target
// ============================================================================

/// An Acceptance state path that cannot be created is a typed runtime hold
/// emitted *before* the gate launches — and it does not fall back to `.cflx` or
/// any other target path.
#[tokio::test]
async fn acceptance_execution_boundary_unusable_state_path_holds_before_the_gate() {
    let fixture = Fixture::new(
        "unusable-state-path",
        &proposal_with_gate("unusable-state-path", "sh -c true"),
    )
    .await;
    let blocker = TempDir::new().or_fail("unexpected error");
    // A regular file where the root directory must be: `create_dir_all` cannot
    // succeed here, and no retry will change that.
    let occupied = blocker.path().join("occupied");
    std::fs::write(&occupied, b"not a directory").or_fail("unexpected error");
    let config = config_with_reviewer(canonical_reviewer());

    let (result, iteration) = fixture
        .accept_under(occupied.clone(), &config, &runner(3600))
        .await;

    let hold = hold_of(result);
    assert_eq!(hold.category, AcceptanceHoldCategory::StatePathUnavailable);
    assert!(
        hold.evidence
            .iter()
            .any(|line| line.contains("acceptance_store_")),
        "the hold must carry the resolver's own typed code: {:?}",
        hold.evidence
    );
    assert_eq!(iteration, 0, "a bounded hold consumes no attempt number");
    assert!(
        !fixture.reviewer_started(),
        "no reviewer may start once the store is known to be unusable"
    );
    assert!(
        fixture.porcelain_status().await.is_empty(),
        "a state-path failure must never fall back into the target"
    );
    assert!(!fixture.path().join(".cflx").exists());

    // Recoverable, not permanent: the environment fact is not a statement about
    // the input, so it must not refuse the next attempt.
    assert!(
        !hold.category.refuses_unchanged_retry(),
        "an unusable state path must not harden into `unchanged_acceptance_input`"
    );
}

/// A resolved store inside the target repository is refused before anything is
/// created, with the same typed hold. This is the containment law end to end.
#[tokio::test]
async fn acceptance_execution_boundary_store_inside_the_target_is_refused() {
    let fixture = Fixture::new(
        "store-inside-target",
        &proposal_with_gate("store-inside-target", "sh -c true"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = fixture
        .accept_under(
            fixture.path().join(".cflx/acceptance"),
            &config,
            &runner(3600),
        )
        .await;

    let hold = hold_of(result);
    assert_eq!(hold.category, AcceptanceHoldCategory::StatePathUnavailable);
    assert!(
        hold.evidence
            .iter()
            .any(|line| line.contains("acceptance_store_inside_target")),
        "the refusal must name containment specifically: {:?}",
        hold.evidence
    );
    assert!(
        !fixture.path().join(".cflx").exists(),
        "containment must be refused before the directory is created"
    );
    assert!(!fixture.reviewer_started());
    assert!(fixture.porcelain_status().await.is_empty());
}

// ============================================================================
// Cleanliness and the legacy path
// ============================================================================

/// Legacy target-local evidence stops Acceptance with its own typed hold, and is
/// detected even though the old runtime self-ignored it. Nothing below that path
/// is opened, parsed, migrated, rewritten, or deleted: cleaning it up is an
/// explicit repository-owner action.
#[tokio::test]
async fn acceptance_execution_boundary_legacy_target_evidence_holds_without_touching_it() {
    let fixture = Fixture::new(
        "legacy-evidence",
        &proposal_with_gate("legacy-evidence", "sh -c true"),
    )
    .await;
    let legacy = fixture.path().join(LEGACY_EVIDENCE_DIR);
    std::fs::create_dir_all(&legacy).or_fail("unexpected error");
    // Exactly what the previous release left behind: a self-ignoring marker that
    // makes the whole subtree invisible to `git status`, plus a record.
    std::fs::write(legacy.join(".gitignore"), "*\n").or_fail("unexpected error");
    let record = legacy.join(format!("{GATE}.json"));
    std::fs::write(
        &record,
        b"{\"schema\":\"conflux-verification-evidence-v1\"}",
    )
    .or_fail("unexpected error");
    let config = config_with_reviewer(canonical_reviewer());

    // The self-ignore really does hide it from the ordinary status question,
    // which is why a dedicated existence probe is needed rather than a wider
    // cleanliness rule.
    assert!(
        !fixture.porcelain_status().await.contains(".cflx"),
        "the legacy directory is invisible to tracked/untracked porcelain status"
    );

    let (result, iteration) = fixture.accept(&config, &runner(3600)).await;

    let hold = hold_of(result);
    assert_eq!(hold.category, AcceptanceHoldCategory::LegacyTargetEvidence);
    assert!(
        hold.evidence
            .iter()
            .any(|line| line.contains(LEGACY_EVIDENCE_DIR)),
        "the hold must name the path a repository owner has to remove: {:?}",
        hold.evidence
    );
    assert!(
        hold.summary(fixture.change()).contains("Remove the legacy"),
        "the operator-facing summary must state whose job the cleanup is: {}",
        hold.summary(fixture.change())
    );
    assert_eq!(iteration, 0);
    assert!(!fixture.reviewer_started(), "no reviewer may start");
    assert_eq!(
        std::fs::read(&record).or_fail("unexpected error"),
        b"{\"schema\":\"conflux-verification-evidence-v1\"}",
        "legacy content must be left exactly as it was found"
    );
    assert!(
        legacy.join(".gitignore").is_file(),
        "the legacy ignore file must not be removed either"
    );
}

/// Only that one path is probed. An unrelated ignored directory — a build
/// output tree, a dependency cache — is none of the runtime's business, and
/// evaluating it would reintroduce exactly the Conflux-specific status filtering
/// constitutional law 4 forbids.
#[tokio::test]
async fn acceptance_execution_boundary_unrelated_ignored_paths_are_not_evaluated() {
    let fixture = Fixture::new(
        "unrelated-ignored",
        &proposal_with_gate("unrelated-ignored", "sh -c true"),
    )
    .await;
    std::fs::write(fixture.path().join(".gitignore"), "build-output\n").or_fail("unexpected error");
    commit_all(fixture.path(), "chore: ignore build output").await;
    std::fs::create_dir_all(fixture.path().join("build-output")).or_fail("unexpected error");
    std::fs::write(fixture.path().join("build-output/artifact.bin"), b"junk")
        .or_fail("unexpected error");
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = fixture.accept(&config, &runner(3600)).await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "an unrelated ignored path must not hold anything, got {result:?}"
    );
    assert!(fixture.path().join("build-output/artifact.bin").is_file());
}

/// Cleanliness uses the ordinary tracked/untracked porcelain status with nothing
/// excluded, so an untracked target file refuses the capture rather than being
/// waved through. The old evidence-directory exception is gone, not widened.
#[tokio::test]
async fn acceptance_execution_boundary_untracked_target_content_refuses_the_gate() {
    let fixture = Fixture::new(
        "dirty-target",
        &proposal_with_gate("dirty-target", "sh -c true"),
    )
    .await;
    // A Conflux-shaped path, deliberately: under the previous rule anything
    // below `.cflx/` was invisible to the comparison.
    std::fs::create_dir_all(fixture.path().join(".cflx")).or_fail("unexpected error");
    std::fs::write(fixture.path().join(".cflx/scratch.json"), b"{}").or_fail("unexpected error");
    let config = config_with_reviewer(canonical_reviewer());

    let (result, _) = fixture.accept(&config, &runner(3600)).await;

    let hold = hold_of(result);
    assert_eq!(
        hold.category,
        AcceptanceHoldCategory::RuntimeDefect,
        "a dirty target is an environment fact, never a verdict about the change"
    );
    assert!(
        hold.evidence
            .iter()
            .any(|line| line.contains("worktree_dirty")),
        "the hold must say the target was dirty: {:?}",
        hold.evidence
    );
    assert!(
        !hold.category.refuses_unchanged_retry(),
        "cleaning the worktree changes no fingerprint component, so this must stay retryable"
    );
}

// ============================================================================
// External records are cache: losing them costs work, never correctness
// ============================================================================

/// Deleting the external cache reruns the declared gate. It never implies PASS,
/// and it never changes the workflow action.
#[tokio::test]
async fn acceptance_execution_boundary_cache_loss_reruns_the_gate_without_proving_pass() {
    use crate::orchestration::acceptance::gate_execution::plan_manifest_reuse;
    use crate::orchestration::acceptance::verification_evidence::{
        GitRepositoryFacts, ReuseDecision, ReusePolicy,
    };

    let fixture = Fixture::new(
        "cache-loss",
        &proposal_with_gate("cache-loss", "sh -c true"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());

    let (first, _) = fixture.accept(&config, &runner(3600)).await;
    assert!(matches!(first, AcceptanceResult::Pass), "{first:?}");
    let store_root = fixture.store_root().await;
    let envelope = store_root.join(format!("gates/{GATE}.json"));
    assert!(envelope.is_file());
    let manifest = fixture.manifests().await.load().expect("manifest persists");

    // An operator deletes `~/.local/state/cflx/**`.
    std::fs::remove_dir_all(&store_root).or_fail("unexpected error");

    // The plan for the unchanged repository input says "rerun", with the reason
    // naming the absent record — not "reuse", and certainly not "pass".
    let decisions = plan_manifest_reuse(
        &GitRepositoryFacts,
        fixture.path(),
        &EvidenceStore::new(store_root.clone()),
        &manifest,
        ReusePolicy::default(),
    )
    .await;
    match decisions.as_slice() {
        [ReuseDecision::Rerun { reason, .. }] => assert_eq!(
            reason.code(),
            "evidence_missing",
            "a deleted cache is a rerun reason: {}",
            reason.detail()
        ),
        other => panic!("cache loss must force a rerun, got {other:?}"),
    }

    // And the next real invocation executes the gate again, rewriting the
    // record it could no longer prove.
    fixture.clear_reviewer_marker();
    let (second, _) = fixture.accept(&config, &runner(3600)).await;
    assert!(matches!(second, AcceptanceResult::Pass), "{second:?}");
    assert!(
        envelope.is_file(),
        "the rerun must write fresh bound evidence"
    );
    assert!(
        fixture.reviewer_started(),
        "cache loss costs work; it does not suppress the review"
    );
}

/// The invariant the refusal rests on: the fingerprint an invocation *settles*
/// with is the one the next attempt recomputes from the unchanged worktree.
///
/// An executed gate writes its artifact, and the artifact digest is a
/// fingerprint component — so a manifest frozen *before* the gates ran carries a
/// fingerprint that is already stale by the time anything terminal could be
/// recorded against it. Recording that value means the next attempt computes a
/// different one, the guard finds no match, and the review the deadline already
/// stopped is dispatched once more.
#[tokio::test]
async fn acceptance_execution_boundary_settled_fingerprint_survives_gate_execution() {
    use crate::orchestration::acceptance::manifest_builder::build_manifest_for_workspace;
    use crate::orchestration::acceptance::verification_evidence::GitRepositoryFacts;

    let fixture = Fixture::new(
        "settled-fingerprint",
        &proposal_with_gate("settled-fingerprint", "sh -c true"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());

    let external = fixture.external.path().to_path_buf();
    let change = fixture.change().to_string();
    let boundary = scoped_acceptance_root_for_test(external, async {
        crate::parallel::executor::run_acceptance_boundary(
            &change,
            fixture.path(),
            config.get_accept_skill(),
            Some("main"),
            3600,
            None,
        )
        .await
    })
    .await
    .expect("a readable repository must produce a boundary")
    .expect("a Git working tree must produce a manifest");

    assert!(
        boundary.gates.outcomes.iter().any(|outcome| matches!(
            outcome,
            crate::orchestration::acceptance::execution_manifest::GateOutcome::Executed { .. }
        )),
        "the declared gate must really have executed: {:?}",
        boundary.gates.outcomes
    );

    // What a fresh attempt on the untouched worktree would compute.
    let next_attempt = build_manifest_for_workspace(
        &GitRepositoryFacts,
        fixture.path(),
        &fixture.evidence().await,
        fixture.change(),
        config.get_accept_skill(),
        Some("main"),
        3600,
    )
    .await
    .expect("the manifest must be derivable from the workspace");

    assert_eq!(
        boundary.manifest.fingerprint(),
        next_attempt.fingerprint(),
        "the settled fingerprint must equal what the next attempt recomputes for the same \
         commit, tree, inputs, declarations, and tool identity"
    );
    assert!(
        boundary
            .manifest
            .gates
            .iter()
            .all(|gate| gate.artifact_digest.is_some()),
        "the settled manifest must bind the artifacts the gates actually wrote"
    );
}

// ============================================================================
// The shared review deadline
// ============================================================================

/// The central regression: a reviewer that never terminates is terminated by
/// the runtime at the review deadline, its process group is reaped, and the
/// invocation settles as a non-resumable `stalled` execution hold with a stable
/// category — not as the generic runtime-limit `error`, and not into
/// missing-verdict retry.
#[tokio::test]
async fn acceptance_execution_boundary_non_terminating_reviewer_settles_as_stalled() {
    let fixture = Fixture::new("verdictless-reviewer", PROPOSAL_WITHOUT_GATES).await;
    let config = config_with_reviewer(non_terminating_reviewer());
    // A generous absolute limit, so what fires is the review deadline rather
    // than the outer runtime limit this change exists to stop reaching.
    let ai_runner = runner(3600);

    let (result, iteration) =
        scoped_review_budget_millis_for_test(150, fixture.accept(&config, &ai_runner)).await;

    let hold = hold_of(result);
    // Cleanup is *proven*, not accepted as either-or. `ReviewCleanupUnproven`
    // is a real category for a real failure — a reviewer whose process group
    // outlived termination — and accepting it here would have let the proposal's
    // "cleanup is confirmed" claim pass on a run that never proved it.
    assert_eq!(
        hold.category,
        AcceptanceHoldCategory::ReviewDeadlineExhausted,
        "the reviewer's owned process group must be proven quiescent: {}",
        hold.cleanup_diagnostics
    );
    assert!(
        hold.cleanup_confirmed,
        "cleanup evidence must be confirmed: {}",
        hold.cleanup_diagnostics
    );
    assert!(fixture.reviewer_started());
    assert_eq!(
        iteration, 0,
        "a bounded hold is not a verdict and consumes no attempt number"
    );

    let blocker = hold.to_stalled_blocker(fixture.change());
    assert_eq!(blocker.phase, "acceptance");
    assert!(!blocker.resumable);
    assert!(blocker.unblock_condition.is_none());
    assert!(blocker.worktree_preserved);
    assert!(
        blocker
            .evidence
            .iter()
            .any(|line| line == "process_group_cleanup=confirmed"),
        "the published blocker must carry the proof, not just the claim: {:?}",
        blocker.evidence
    );

    // The account of the hold is persisted externally, for an operator to read —
    // and it changed nothing in the target.
    assert!(
        fixture.manifests().await.diagnostics_path().is_file(),
        "the invocation's diagnostics belong in the external store"
    );
    let status = fixture.porcelain_status().await;
    let unexpected: Vec<&str> = status
        .lines()
        .filter(|line| !line.ends_with(REVIEWER_MARKER))
        .collect();
    assert!(
        unexpected.is_empty(),
        "a hold must leave the target untouched: {unexpected:?}"
    );
}

/// The result classifies as a hold rather than as a runtime limit, so it never
/// reaches verdict routing, escalation, or automatic re-dispatch.
#[tokio::test]
async fn acceptance_execution_boundary_hold_is_not_a_runtime_limit_or_a_verdict() {
    let fixture = Fixture::new("hold-classification", PROPOSAL_WITHOUT_GATES).await;
    let config = config_with_reviewer(non_terminating_reviewer());
    let ai_runner = runner(3600);

    let (result, _) =
        scoped_review_budget_millis_for_test(150, fixture.accept(&config, &ai_runner)).await;

    assert!(result.is_execution_hold());
    assert!(!result.is_runtime_limit(), "the outer limit must not fire");
    assert!(!result.is_canonical_verdict());
    assert!(
        !result.permits_acceptance_retry(),
        "a bounded hold must not be re-dispatched automatically"
    );
    assert!(
        crate::orchestration::acceptance::classify_invalid_acceptance_result(&result).is_none(),
        "a boundary decision is not an invalid reviewer response"
    );
}

/// A reviewer that emits its verdict before the deadline keeps it, even though
/// the runtime terminates the still-open process afterwards. Terminating a
/// process that already answered is finalization, not failure.
#[tokio::test]
async fn acceptance_execution_boundary_verdict_before_the_deadline_is_kept() {
    let fixture = Fixture::new("verdict-before-deadline", PROPOSAL_WITHOUT_GATES).await;
    let config = config_with_reviewer(format!(
        "sh -c 'touch {REVIEWER_MARKER}; printf \"ACCEPTANCE: PASS\\n\"; while true; do sleep 1; done'"
    ));
    let ai_runner = runner(3600);

    let (result, iteration) = scoped_review_budget_millis_for_test(
        2_000,
        crate::parallel::executor::scoped_verdict_grace_secs_for_test(
            1,
            fixture.accept(&config, &ai_runner),
        ),
    )
    .await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "a verdict emitted before the deadline must stand, got {result:?}"
    );
    assert!(iteration > 0);
}

// ============================================================================
// Unchanged-input refusal: live while this owner runs, gone after a restart
// ============================================================================

/// A real deadline hold, then an unchanged retry in the *same* owner process.
///
/// The refusal holds: no gate, no reviewer, no attempt number. And it holds
/// without anything being written into the target worktree, which is what makes
/// it a live-owner fact rather than a durable one.
#[tokio::test]
async fn acceptance_execution_boundary_live_owner_refuses_unchanged_input() {
    let fixture = Fixture::new("live-owner-refusal", PROPOSAL_WITHOUT_GATES).await;
    let ai_runner = runner(3600);

    let (first, _) = scoped_review_budget_millis_for_test(
        150,
        fixture.accept(
            &config_with_reviewer(non_terminating_reviewer()),
            &ai_runner,
        ),
    )
    .await;
    let first_hold = hold_of(first);
    assert_eq!(
        first_hold.category,
        AcceptanceHoldCategory::ReviewDeadlineExhausted
    );
    fixture.clear_reviewer_marker();

    // Same owner, same worktree. A canonical reviewer would pass instantly, so a
    // PASS here would mean the refusal was lost rather than that the change is
    // good.
    let (second, iteration) = fixture
        .accept(&config_with_reviewer(canonical_reviewer()), &ai_runner)
        .await;

    let hold = hold_of(second);
    assert_eq!(hold.fingerprint, first_hold.fingerprint);
    assert_eq!(
        hold.category,
        AcceptanceHoldCategory::ReviewDeadlineExhausted
    );
    assert!(hold
        .summary(fixture.change())
        .contains("unchanged_acceptance_input"));
    assert_eq!(iteration, 0);
    assert!(
        !fixture.reviewer_started(),
        "no reviewer may be dispatched for an unchanged input in the same owner"
    );
}

/// Restart: a real deadline hold, then an entirely fresh owner — a new live-hold
/// registry, new agent, new history, new runner — admits one fresh bounded
/// attempt from the same untouched worktree, with no repository mutation.
///
/// This replaces `acceptance_execution_boundary_restart_reaches_the_same_refusal`.
/// The old contract re-derived the refusal from a manifest the previous process
/// had written into the worktree. That was durable out-of-worktree-proof state
/// that changed the next action, which constitutional law 1 forbids once the
/// record moved outside the tree — so the refusal is now process-local, and a
/// restart deliberately permits one new bounded attempt while still reusing any
/// cached gate result that is still valid.
#[tokio::test]
async fn acceptance_execution_boundary_restart_admits_one_fresh_attempt() {
    let fixture = Fixture::new("restart-admits", PROPOSAL_WITHOUT_GATES).await;
    let ai_runner = runner(3600);

    let (first, _) = scoped_review_budget_millis_for_test(
        150,
        fixture.accept(
            &config_with_reviewer(non_terminating_reviewer()),
            &ai_runner,
        ),
    )
    .await;
    assert!(first.is_execution_hold(), "{first:?}");
    fixture.clear_reviewer_marker();

    // "Restart": the owner's typed state is gone. The external cache and the
    // worktree are exactly as the previous owner left them.
    crate::orchestration::acceptance::execution_manifest::live_acceptance_holds()
        .clear(fixture.change());

    let (second, iteration) = fixture
        .accept(&config_with_reviewer(canonical_reviewer()), &ai_runner)
        .await;

    assert!(
        matches!(second, AcceptanceResult::Pass),
        "a restarted owner must admit one fresh bounded attempt, got {second:?}"
    );
    assert!(
        fixture.reviewer_started(),
        "the fresh attempt really dispatches a reviewer"
    );
    assert!(iteration > 0, "the fresh attempt records a real verdict");
    assert!(
        fixture
            .porcelain_status()
            .await
            .lines()
            .all(|line| line.ends_with(REVIEWER_MARKER)),
        "admission after restart must require no repository mutation"
    );
}

/// The shared admission port — the one classifier behind `retry_change`,
/// `retry_errors`, Start/F5, terminal-error queue intent, and automatic mark
/// settlement — refuses from live state and admits after a restart.
///
/// Both the explicit and the automatic edge go through this one `classify`, so
/// proving it here proves it for every caller rather than for one of them.
#[tokio::test]
async fn acceptance_execution_boundary_shared_admission_is_live_owner_scoped() {
    use crate::orchestration::acceptance::manifest_builder::build_manifest_for_workspace;
    use crate::orchestration::acceptance::verification_evidence::GitRepositoryFacts;
    use crate::orchestration::operator_command::AcceptanceAdmissionPort;

    let fixture = Fixture::new(
        "shared-admission",
        &proposal_with_gate("shared-admission", "sh -c true"),
    )
    .await;
    let config = config_with_reviewer(canonical_reviewer());
    let workspace = fixture.path().to_path_buf();
    let resolve = move |_change: &str| Some(workspace.clone());

    let manifest = build_manifest_for_workspace(
        &GitRepositoryFacts,
        fixture.path(),
        &fixture.evidence().await,
        fixture.change(),
        config.get_accept_skill(),
        Some("main"),
        0,
    )
    .await
    .expect("the manifest must be derivable");

    // A live owner that recorded a deadline hold for this exact input.
    let live = Arc::new(LiveAcceptanceHolds::new());
    live.record(
        fixture.change(),
        LiveAcceptanceHold {
            category: AcceptanceHoldCategory::ReviewDeadlineExhausted,
            fingerprint: manifest.fingerprint(),
            review_base_ref: Some("main".to_string()),
        },
    );
    let admission = WorkspaceAcceptanceAdmission::with_holds(
        resolve.clone(),
        config.get_accept_skill(),
        None,
        live.clone(),
    );
    let refusal = scoped_acceptance_root_for_test(
        fixture.external.path().to_path_buf(),
        admission.classify(fixture.change()),
    )
    .await;
    match &refusal {
        AcceptanceAdmission::Refuse {
            outcome,
            category,
            components,
            ..
        } => {
            assert_eq!(*outcome, "unchanged_acceptance_input");
            assert_eq!(*category, AcceptanceHoldCategory::ReviewDeadlineExhausted);
            assert!(!components.is_empty());
        }
        other => panic!("a live owner must refuse the unchanged input, got {other:?}"),
    }

    // Restart: a new registry is what a restarted owner has, and it admits.
    let restarted = WorkspaceAcceptanceAdmission::with_holds(
        resolve.clone(),
        config.get_accept_skill(),
        None,
        Arc::new(LiveAcceptanceHolds::new()),
    );
    assert_eq!(
        scoped_acceptance_root_for_test(
            fixture.external.path().to_path_buf(),
            restarted.classify(fixture.change()),
        )
        .await,
        AcceptanceAdmission::Admit,
        "external cache must not recreate retry refusal after owner restart"
    );

    // And within the live owner, a repository change still restores eligibility.
    std::fs::write(fixture.path().join("repair.rs"), "fn repaired() {}\n")
        .or_fail("unexpected error");
    commit_all(fixture.path(), "Apply: repair").await;
    assert_eq!(
        scoped_acceptance_root_for_test(
            fixture.external.path().to_path_buf(),
            admission.classify(fixture.change()),
        )
        .await,
        AcceptanceAdmission::Admit,
        "a repository-visible change must restore live-owner retry eligibility"
    );
}

/// A repository-visible change to the candidate produces a new fingerprint and
/// permits exactly one fresh bounded attempt, even while the owner still
/// remembers the previous hold.
#[tokio::test]
async fn acceptance_execution_boundary_changed_input_permits_a_new_attempt() {
    let fixture = Fixture::new("changed-input", PROPOSAL_WITHOUT_GATES).await;
    let ai_runner = runner(3600);

    let (first, _) = scoped_review_budget_millis_for_test(
        150,
        fixture.accept(
            &config_with_reviewer(non_terminating_reviewer()),
            &ai_runner,
        ),
    )
    .await;
    let refused_fingerprint = hold_of(first).fingerprint;
    fixture.clear_reviewer_marker();

    // The sanctioned recovery: a real repository-visible change.
    std::fs::write(fixture.path().join("repair.rs"), "fn repaired() {}\n")
        .or_fail("unexpected error");
    commit_all(fixture.path(), "Apply: repair").await;

    let (result, _) = fixture
        .accept(&config_with_reviewer(canonical_reviewer()), &ai_runner)
        .await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "a changed candidate must permit a new bounded attempt, got {result:?}"
    );
    assert!(fixture.reviewer_started());
    let stored = fixture
        .manifests()
        .await
        .load()
        .expect("the new attempt rewrites the manifest");
    assert_ne!(stored.fingerprint(), refused_fingerprint);
}

/// Settlement discards both halves of a change's Acceptance state: the external
/// cache and this owner's live refusal. Neither is authority, so dropping them
/// is always safe — and neither removal touches the target worktree, which is
/// the clause constitutional law 4 adds to "deleting out-of-worktree state may
/// discard caches".
#[tokio::test]
async fn acceptance_execution_boundary_settlement_clears_only_external_state() {
    let fixture = Fixture::new(
        "settlement-cleanup",
        &proposal_with_gate("settlement-cleanup", "sh -c true"),
    )
    .await;
    let ai_runner = runner(3600);

    // A real hold, so there is both a cache and a live refusal to clear.
    let (first, _) = scoped_review_budget_millis_for_test(
        150,
        fixture.accept(
            &config_with_reviewer(non_terminating_reviewer()),
            &ai_runner,
        ),
    )
    .await;
    assert!(first.is_execution_hold(), "{first:?}");
    let store_root = fixture.store_root().await;
    assert!(store_root.join(format!("gates/{GATE}.json")).is_file());
    assert!(
        crate::orchestration::acceptance::execution_manifest::live_acceptance_holds()
            .get(fixture.change())
            .is_some(),
        "the live owner must be holding this change before settlement"
    );

    let config = config_with_reviewer(canonical_reviewer());
    scoped_acceptance_root_for_test(fixture.external.path().to_path_buf(), async {
        crate::parallel::executor::clear_acceptance_state(fixture.change(), fixture.path(), &config)
            .await
    })
    .await;

    assert!(
        !store_root.exists(),
        "settlement must discard the external Acceptance cache"
    );
    assert!(
        crate::orchestration::acceptance::execution_manifest::live_acceptance_holds()
            .get(fixture.change())
            .is_none(),
        "settlement must discard the live refusal too"
    );
    let status = fixture.porcelain_status().await;
    let unexpected: Vec<&str> = status
        .lines()
        .filter(|line| !line.ends_with(REVIEWER_MARKER))
        .collect();
    assert!(
        unexpected.is_empty(),
        "clearing out-of-worktree state must not modify the target worktree: {unexpected:?}"
    );
}

/// Editing the change's own artifacts is equally sufficient recovery: the
/// refusal names `change_inputs`, so that has to work.
#[tokio::test]
async fn acceptance_execution_boundary_changed_change_inputs_permit_a_new_attempt() {
    let fixture = Fixture::new("changed-inputs", PROPOSAL_WITHOUT_GATES).await;
    let ai_runner = runner(3600);

    let (first, _) = scoped_review_budget_millis_for_test(
        150,
        fixture.accept(
            &config_with_reviewer(non_terminating_reviewer()),
            &ai_runner,
        ),
    )
    .await;
    assert!(first.is_execution_hold(), "{first:?}");
    fixture.clear_reviewer_marker();

    std::fs::write(
        fixture
            .path()
            .join("openspec/changes")
            .join(fixture.change())
            .join("tasks.md"),
        "## Implementation Tasks\n\n- [x] 1. done\n- [x] 2. also done\n",
    )
    .or_fail("unexpected error");

    let (result, _) = fixture
        .accept(&config_with_reviewer(canonical_reviewer()), &ai_runner)
        .await;

    assert!(
        matches!(result, AcceptanceResult::Pass),
        "changed change inputs must restore eligibility, got {result:?}"
    );
}