a3s-code-core 9.0.0

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

use crate::verification::{VerificationReport, VerificationStatus};
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub const MUTATION_OBSERVATION_SCHEMA: &str = "a3s.code.mutation-observation.v1";
const MUTATING_FILE_TOOLS: &[&str] = &["write", "edit", "patch", "download"];

/// How a successful run closed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CompletionTerminal {
    /// No workspace mutation. A final answer is enough.
    #[default]
    Narrative,
    /// Required checks passed and were bound to the mutation digest.
    Verified { effect_digest: String },
    /// A host-confirmed waiver bound to the mutation digest. Not a verification pass.
    Waived { effect_digest: String },
    /// Step closures did not share one effect digest. Not a narrative success
    /// and not a combined digest. Each digest stays on the step that closed it.
    Distinct,
}

impl CompletionTerminal {
    pub fn is_narrative(&self) -> bool {
        matches!(self, Self::Narrative)
    }
}

/// Fold step closures into the session terminal. A bound closure is not
/// rewritten as narrative. Different digests are not hashed together.
pub fn fold_step_completions(terminals: &[CompletionTerminal]) -> CompletionTerminal {
    let mut bound = Vec::new();
    for terminal in terminals {
        if terminal.is_narrative() || bound.contains(terminal) {
            continue;
        }
        bound.push(terminal.clone());
    }
    match bound.as_slice() {
        [] => CompletionTerminal::Narrative,
        [one] => one.clone(),
        many => {
            if let Some(digest) = completion_digest(&many[0]) {
                if many
                    .iter()
                    .all(|terminal| completion_digest(terminal) == Some(digest))
                {
                    if many
                        .iter()
                        .any(|terminal| matches!(terminal, CompletionTerminal::Verified { .. }))
                    {
                        return CompletionTerminal::Verified {
                            effect_digest: digest.to_string(),
                        };
                    }
                    return many[0].clone();
                }
            }
            CompletionTerminal::Distinct
        }
    }
}

fn completion_digest(terminal: &CompletionTerminal) -> Option<&str> {
    match terminal {
        CompletionTerminal::Narrative | CompletionTerminal::Distinct => None,
        CompletionTerminal::Verified { effect_digest }
        | CompletionTerminal::Waived { effect_digest } => Some(effect_digest.as_str()),
    }
}

/// Host- or user-confirmed waiver. The model cannot mint this from prose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompletionWaiverV1 {
    pub effect_digest: String,
    pub reason: String,
}

impl CompletionWaiverV1 {
    pub fn new(effect_digest: impl Into<String>, reason: impl Into<String>) -> Option<Self> {
        let effect_digest = effect_digest.into();
        let reason = reason.into();
        if effect_digest.trim().is_empty() || reason.trim().is_empty() {
            return None;
        }
        Some(Self {
            effect_digest,
            reason,
        })
    }
}

/// Whether this run is an ordinary execution or the admitted exit from plan mode.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PlanRunAdmission {
    pub claims_implementation: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan_digest: Option<String>,
}

impl PlanRunAdmission {
    pub fn ordinary() -> Self {
        Self::default()
    }

    pub fn implementation(plan_digest: impl Into<String>) -> Self {
        Self {
            claims_implementation: true,
            plan_digest: Some(plan_digest.into()),
        }
    }

    /// A claim without a non-empty accepted-plan digest is an ordinary run.
    pub fn label(&self) -> &'static str {
        match (
            self.claims_implementation,
            self.plan_digest.as_deref().map(str::trim),
        ) {
            (true, Some(digest)) if !digest.is_empty() => "plan_implementation",
            _ => "ordinary",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MutationRecord {
    pub tool: String,
    pub path: String,
    pub content_digest: String,
}

/// A background child that shares this workspace and has not been observed yet.
/// Paths land on this ledger when the child settles. This is not a second digest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct OpenWorkspaceChild {
    task_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    porcelain: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    head: Option<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    nongit: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MutationLedger {
    records: Vec<MutationRecord>,
    #[serde(default)]
    digest: String,
    /// Background writers still sharing the workspace. Empty means none.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    open_children: Vec<OpenWorkspaceChild>,
    /// The latest workspace re-read failed. Not part of the effect digest:
    /// a partial list is not an identity a waiver can close.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    observation_incomplete: bool,
}

impl MutationLedger {
    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    pub fn digest(&self) -> &str {
        &self.digest
    }

    pub fn paths(&self) -> impl Iterator<Item = &str> {
        self.records.iter().map(|record| record.path.as_str())
    }

    /// Latest content digest recorded for a mutated path (path-boundary match).
    pub fn content_digest_for_path(&self, path: &str) -> Option<&str> {
        self.records.iter().rev().find_map(|record| {
            if crate::verification::mutation_path_matches(record.path.as_str(), path) {
                Some(record.content_digest.as_str())
            } else {
                None
            }
        })
    }

    /// True when any record for `path` stored a non-empty content digest.
    ///
    /// A later `changed_paths` row hashes tool metadata, not file bytes. Callers
    /// that need the write's bytes must not treat that later row as the only
    /// digest.
    pub fn has_content_digest(&self, path: &str) -> bool {
        self.records.iter().any(|record| {
            !record.content_digest.is_empty()
                && crate::verification::mutation_path_matches(record.path.as_str(), path)
        })
    }

    /// True when a recorded content digest for `path` is exactly `digest`.
    pub fn content_digest_matches(&self, path: &str, digest: &str) -> bool {
        let digest = digest.trim();
        if digest.is_empty() {
            return false;
        }
        self.records.iter().any(|record| {
            record.content_digest == digest
                && crate::verification::mutation_path_matches(record.path.as_str(), path)
        })
    }

    /// Record a workspace mutation. Ignores reads and tools that did not
    /// publish a path. `changed_paths` means the workspace already differed,
    /// including a failed or timed-out wrapper. Command text is not parsed.
    /// A `file_path` on a failed write is not applied, so it does not count.
    pub fn observe_tool(&mut self, tool: &str, exit_code: i32, metadata: Option<&Value>) {
        let Some(metadata) = metadata else {
            return;
        };
        let tool_key = tool.to_ascii_lowercase();
        if metadata.get("changed_paths").is_some() {
            record_changed_paths(self, &tool_key, metadata);
        }
        if let Some(task_id) = metadata.get("workspace_child").and_then(Value::as_str) {
            self.observe_workspace_child(task_id);
        }
        if exit_code != 0 {
            record_nested_tool_effects(self, metadata);
            return;
        }
        if MUTATING_FILE_TOOLS.contains(&tool_key.as_str()) {
            if let Some(path) = metadata.get("file_path").and_then(Value::as_str) {
                self.push(tool_key, path, content_digest(metadata));
            }
            return;
        }
        record_nested_tool_effects(self, metadata);
    }

    fn observe_workspace_child(&mut self, task_id: &str) {
        let task_id = task_id.trim();
        if task_id.is_empty() {
            return;
        }
        if let Some(paths) = crate::porcelain::take_settled_workspace_child(task_id) {
            self.record_child_paths(task_id, &paths);
            return;
        }
        let Some(marker) = crate::porcelain::child_marker(task_id) else {
            return;
        };
        if self
            .open_children
            .iter()
            .any(|child| child.task_id == marker.task_id)
        {
            return;
        }
        self.open_children.push(OpenWorkspaceChild {
            task_id: marker.task_id,
            porcelain: marker.porcelain,
            head: marker.head,
            nongit: marker.nongit,
        });
    }

    pub fn has_open_children(&self) -> bool {
        !self.open_children.is_empty()
    }

    pub fn observation_incomplete(&self) -> bool {
        self.observation_incomplete
    }

    /// The current re-read is authoritative. A later successful read clears
    /// a previous failure so resume does not stick on a transient git miss.
    pub fn set_observation_incomplete(&mut self, incomplete: bool) {
        self.observation_incomplete = incomplete;
    }

    /// Record a workspace delta the tools did not publish. Paths already on
    /// the ledger are not added again, so a bound digest stays stable.
    pub fn observe_unseen_paths(&mut self, paths: &[String]) {
        let seen = self
            .records
            .iter()
            .map(|record| record.path.clone())
            .collect::<std::collections::HashSet<_>>();
        let accepted: Vec<String> = paths
            .iter()
            .map(|path| path.trim().trim_start_matches("./"))
            .filter(|path| !path.is_empty() && !seen.contains(*path))
            .filter(|path| {
                *path != ".a3s"
                    && !path.starts_with(".a3s/")
                    && *path != ".git"
                    && !path.starts_with(".git/")
            })
            .map(str::to_string)
            .collect();
        if accepted.is_empty() {
            return;
        }
        for path in accepted {
            self.records.push(MutationRecord {
                tool: "workspace".to_string(),
                path,
                content_digest: String::new(),
            });
        }
        self.rehash();
    }

    fn record_child_paths(&mut self, task_id: &str, paths: &[String]) {
        self.open_children.retain(|child| child.task_id != task_id);
        for path in paths {
            self.push("task".to_string(), path, String::new());
        }
    }

    fn push(&mut self, tool: String, path: &str, content_digest: String) {
        if crate::porcelain::is_harness_path(path) {
            return;
        }
        let path = path.trim();
        if path.is_empty() {
            return;
        }
        self.records.push(MutationRecord {
            tool,
            path: path.to_string(),
            content_digest,
        });
        self.rehash();
    }

    fn rehash(&mut self) {
        self.records
            .sort_by(|left, right| left.path.cmp(&right.path).then(left.tool.cmp(&right.tool)));
        self.digest = effect_digest(&self.records);
    }
}

/// Fold settled background writers into this ledger before the gate runs.
/// A child that is still running is waited on. Cancellation leaves it open
/// so narrative success cannot hide the write.
pub async fn absorb_open_workspace_children(
    ledger: &mut MutationLedger,
    workspace: &std::path::Path,
    cancel: &tokio_util::sync::CancellationToken,
) -> bool {
    let pending = ledger.open_children.to_vec();
    let mut incomplete = false;
    for child in pending {
        if let Some(paths) = crate::porcelain::take_settled_workspace_child(&child.task_id) {
            ledger.record_child_paths(&child.task_id, &paths);
            continue;
        }
        if crate::porcelain::workspace_child_pending(&child.task_id) {
            if let Some(paths) =
                crate::porcelain::await_workspace_child(&child.task_id, workspace, cancel).await
            {
                ledger.record_child_paths(&child.task_id, &paths);
            }
            continue;
        }
        if child.nongit && child.porcelain.is_none() && child.head.is_none() {
            continue;
        }
        let observed = crate::porcelain::delta(
            workspace,
            crate::porcelain::snapshot_from_parts(
                child.porcelain.clone(),
                child.head.clone(),
                Vec::new(),
            ),
        )
        .await;
        if observed.incomplete {
            incomplete = true;
        }
        ledger.record_child_paths(&child.task_id, &observed.paths);
    }
    incomplete
}

fn record_changed_paths(ledger: &mut MutationLedger, tool: &str, metadata: &Value) {
    let Some(paths) = metadata.get("changed_paths").and_then(Value::as_array) else {
        return;
    };
    for path in paths {
        if let Some(path) = path.as_str() {
            ledger.push(tool.to_string(), path, content_digest(metadata));
        }
    }
}

fn record_nested_tool_effects(ledger: &mut MutationLedger, metadata: &Value) {
    for (name, nested) in nested_tool_calls(metadata) {
        ledger.observe_tool(name, 0, nested);
    }
}

/// Child tool effects published by a wrapper. Search hits also use `results`,
/// but they have no `exit_code` and no tool name, so they are not mutations.
pub(crate) fn nested_tool_calls(metadata: &Value) -> Vec<(&str, Option<&Value>)> {
    let mut calls = Vec::new();
    push_nested_calls(
        &mut calls,
        metadata.pointer("/program/tool_calls"),
        "tool_name",
    );
    push_nested_calls(&mut calls, metadata.get("results"), "tool");
    calls
}

fn push_nested_calls<'a>(
    out: &mut Vec<(&'a str, Option<&'a Value>)>,
    calls: Option<&'a Value>,
    name_key: &str,
) {
    let Some(calls) = calls.and_then(Value::as_array) else {
        return;
    };
    for call in calls {
        if call.get("success").and_then(Value::as_bool) != Some(true) {
            continue;
        }
        if call.get("exit_code").and_then(Value::as_i64) != Some(0) {
            continue;
        }
        let Some(name) = call.get(name_key).and_then(Value::as_str) else {
            continue;
        };
        if name.is_empty() {
            continue;
        }
        out.push((name, call.get("metadata")));
    }
}

fn content_digest(metadata: &Value) -> String {
    if let Some(after) = metadata.get("after").and_then(Value::as_str) {
        return sha256::digest(after.as_bytes());
    }
    sha256::digest(metadata.to_string().as_bytes())
}

fn effect_digest(records: &[MutationRecord]) -> String {
    let canonical = records
        .iter()
        .map(|record| format!("{}|{}|{}", record.tool, record.path, record.content_digest))
        .collect::<Vec<_>>()
        .join("\n");
    sha256::digest(canonical.as_bytes())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompletionGate {
    Allow(CompletionTerminal),
    /// Ask the model once more, naming the missing evidence. Not a success.
    Continue {
        message: String,
    },
    /// Do not return `AgentResult` success.
    Incomplete {
        message: String,
    },
}

pub fn decide_completion(
    ledger: &MutationLedger,
    reports: &[VerificationReport],
    waivers: &[CompletionWaiverV1],
    allow_continuation: bool,
) -> CompletionGate {
    decide_with_observations(ledger, reports, waivers, allow_continuation, &[])
}

pub fn decide_with_observations(
    ledger: &MutationLedger,
    reports: &[VerificationReport],
    waivers: &[CompletionWaiverV1],
    allow_continuation: bool,
    observations: &[crate::external_observation::ExternalObservationV1],
) -> CompletionGate {
    let open = crate::external_observation::still_open(observations, waivers, ledger.digest());
    if crate::external_observation::blocks_success(&open) {
        let digest = open
            .iter()
            .map(|observation| observation.digest.as_str())
            .collect::<Vec<_>>()
            .join(",");
        let message = format!(
            "completion gate: external observation {digest} still requires a workspace change. A final answer does not clear it. Bind a newer observation of the same subject or a host waiver for the observation digest."
        );
        return if allow_continuation {
            CompletionGate::Continue { message }
        } else {
            CompletionGate::Incomplete { message }
        };
    }
    if ledger.has_open_children() {
        let ids = ledger
            .open_children
            .iter()
            .map(|child| child.task_id.as_str())
            .collect::<Vec<_>>()
            .join(",");
        let message = format!(
            "completion gate: background workspace task {ids} has not been observed. A final answer does not observe its writes."
        );
        return CompletionGate::Incomplete { message };
    }
    if ledger.observation_incomplete() {
        return CompletionGate::Incomplete {
            message: "completion gate: workspace observation is incomplete, so this digest is not the effect. A final answer, a waiver, or a verification of a partial list does not close it.".to_string(),
        };
    }
    if ledger.is_empty() {
        return CompletionGate::Allow(CompletionTerminal::Narrative);
    }
    let digest = ledger.digest().to_string();
    if waivers.iter().any(|waiver| waiver.effect_digest == digest) {
        return CompletionGate::Allow(CompletionTerminal::Waived {
            effect_digest: digest,
        });
    }
    if reports
        .iter()
        .any(|report| report_binds_pass(report, &digest))
    {
        return CompletionGate::Allow(CompletionTerminal::Verified {
            effect_digest: digest,
        });
    }
    let message = format!(
        "completion gate: workspace mutation {digest} has no bound Passed verification and no host waiver. Assistant text does not count. Bind a verification_report.effect_digest to this digest with required checks Passed, or obtain a host waiver for this digest."
    );
    // A host waiver is not model-grantable, and editor-authored reports are
    // rejected. Built-in bash may bind a digest only when an existence check
    // matches a mutated path *and* on-disk content matches the ledger digest.
    // The optional verifier turn already ran or was skipped before this
    // decision. Spending the one continuation here cannot close the gate; it
    // only invites another tool call. An open external observation still
    // continues, because a workspace write can satisfy that subject.
    CompletionGate::Incomplete { message }
}

fn report_binds_pass(report: &VerificationReport, digest: &str) -> bool {
    if report.effect_digest.as_deref() != Some(digest) {
        return false;
    }
    let required: Vec<_> = report
        .checks
        .iter()
        .filter(|check| check.required)
        .collect();
    if required.is_empty() {
        return false;
    }
    required
        .iter()
        .all(|check| check.status == VerificationStatus::Passed)
        && !matches!(
            report.status,
            VerificationStatus::Failed | VerificationStatus::NeedsReview
        )
}

/// Model-visible observation attached after a mutation. Never a verification pass.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MutationObservationV1 {
    pub schema: String,
    pub path: String,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_revision: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub items: Vec<String>,
}

impl MutationObservationV1 {
    pub fn unavailable(path: impl Into<String>) -> Self {
        Self {
            schema: MUTATION_OBSERVATION_SCHEMA.to_string(),
            path: path.into(),
            status: "unavailable".to_string(),
            workspace_revision: None,
            items: Vec::new(),
        }
    }

    pub fn stale(path: impl Into<String>, workspace_revision: Option<u64>) -> Self {
        Self {
            schema: MUTATION_OBSERVATION_SCHEMA.to_string(),
            path: path.into(),
            status: "stale".to_string(),
            workspace_revision,
            items: Vec::new(),
        }
    }

    pub fn diagnostics(
        path: impl Into<String>,
        workspace_revision: Option<u64>,
        items: Vec<String>,
    ) -> Self {
        Self {
            schema: MUTATION_OBSERVATION_SCHEMA.to_string(),
            path: path.into(),
            status: "diagnostics".to_string(),
            workspace_revision,
            items,
        }
    }

    pub fn render(&self) -> String {
        let items = if self.items.is_empty() {
            String::new()
        } else {
            format!(" items={}", self.items.join(" | "))
        };
        format!(
            "[mutation observation] path={} status={}{items}",
            self.path, self.status
        )
    }
}

/// Build the observation attached to a mutation. A stale snapshot drops
/// diagnostic items so a previous revision cannot be presented as current.
pub fn observation_from_diagnostics(
    path: &str,
    revision: Option<u64>,
    stale: bool,
    items: Vec<String>,
) -> MutationObservationV1 {
    if stale {
        return MutationObservationV1::stale(path, revision);
    }
    MutationObservationV1::diagnostics(path, revision, items)
}

/// Tool-result text the next model call sees. This is the observation
/// attachment; it is not a `code_diagnostics` tool invocation.
pub fn model_visible_observation(output: &str, observation: &MutationObservationV1) -> String {
    let rendered = observation.render();
    if output.contains("[mutation observation]") {
        output.to_string()
    } else if output.is_empty() {
        rendered
    } else {
        format!("{output}\n{rendered}")
    }
}

pub fn attach_observation(metadata: &mut Option<Value>, observation: &MutationObservationV1) {
    let value = serde_json::to_value(observation).unwrap_or(Value::Null);
    match metadata {
        Some(Value::Object(map)) => {
            map.insert("mutation_observation".to_string(), value);
        }
        Some(other) => {
            *metadata = Some(serde_json::json!({
                "previous": other,
                "mutation_observation": value,
            }));
        }
        None => {
            *metadata = Some(serde_json::json!({ "mutation_observation": value }));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::verification::VerificationCheck;

    fn ledger_with_write() -> MutationLedger {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "write",
            0,
            Some(&serde_json::json!({"file_path": "src/lib.rs", "after": "fn main() {}"})),
        );
        ledger
    }

    #[test]
    fn read_only_tool_does_not_open_the_gate() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "read",
            0,
            Some(&serde_json::json!({"file_path": "src/lib.rs"})),
        );
        assert!(ledger.is_empty());
        assert!(matches!(
            decide_completion(&ledger, &[], &[], false),
            CompletionGate::Allow(CompletionTerminal::Narrative)
        ));
    }

    #[test]
    fn assistant_prose_does_not_satisfy_a_mutation() {
        let ledger = ledger_with_write();
        let decision = decide_completion(&ledger, &[], &[], false);
        match decision {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
                assert!(!message.contains("tests passed"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn open_external_observation_still_continues_once() {
        let observation = crate::external_observation::ExternalObservationV1::new(
            "review",
            "src/lib.rs",
            "obs-digest",
            "needs a workspace change",
            crate::external_observation::RequiredAction::WorkspaceChange,
        )
        .expect("observation");
        match decide_with_observations(
            &MutationLedger::default(),
            &[],
            &[],
            true,
            &[observation.clone()],
        ) {
            CompletionGate::Continue { message } => {
                assert!(message.starts_with("completion gate:"));
                assert!(message.contains("external observation"));
            }
            other => panic!("expected continue, got {other:?}"),
        }
        match decide_with_observations(&MutationLedger::default(), &[], &[], false, &[observation])
        {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
                assert!(message.contains("external observation"));
            }
            other => panic!("expected incomplete without continuation, got {other:?}"),
        }
    }

    #[test]
    fn unbound_mutation_does_not_spend_a_continuation_the_model_cannot_close() {
        let ledger = ledger_with_write();
        match decide_completion(&ledger, &[], &[], true) {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
                assert!(message.contains("Assistant text does not count"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn bound_passed_report_allows_verified_terminal() {
        let ledger = ledger_with_write();
        let report = VerificationReport::new(
            "edit",
            vec![VerificationCheck::required("build", "command", "compiles")
                .with_status(VerificationStatus::Passed)],
        )
        .with_effect_digest(ledger.digest());
        match decide_completion(&ledger, &[report], &[], false) {
            CompletionGate::Allow(CompletionTerminal::Verified { effect_digest }) => {
                assert_eq!(effect_digest, ledger.digest());
            }
            other => panic!("expected verified, got {other:?}"),
        }
    }

    #[test]
    fn empty_required_checks_are_not_a_pass() {
        let ledger = ledger_with_write();
        let report = VerificationReport::new("edit", vec![]).with_effect_digest(ledger.digest());
        assert!(matches!(
            decide_completion(&ledger, &[report], &[], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[test]
    fn incomplete_observation_is_not_closed_by_a_waiver_of_a_partial_digest() {
        let mut ledger = ledger_with_write();
        ledger.set_observation_incomplete(true);
        let waiver = CompletionWaiverV1::new(ledger.digest(), "user accepted residual risk")
            .expect("waiver");
        match decide_completion(&ledger, &[], &[waiver], false) {
            CompletionGate::Incomplete { message } => {
                assert!(message.contains("observation is incomplete"));
                assert!(!message.contains("tests passed"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
        let mut empty = MutationLedger::default();
        empty.set_observation_incomplete(true);
        assert!(matches!(
            decide_completion(&empty, &[], &[], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[test]
    fn waiver_is_distinct_and_does_not_transfer_to_another_digest() {
        let ledger = ledger_with_write();
        let waiver = CompletionWaiverV1::new(ledger.digest(), "user accepted residual risk")
            .expect("waiver");
        match decide_completion(&ledger, &[], &[waiver.clone()], false) {
            CompletionGate::Allow(CompletionTerminal::Waived { effect_digest }) => {
                assert_eq!(effect_digest, ledger.digest());
            }
            other => panic!("expected waiver, got {other:?}"),
        }
        let mut other = MutationLedger::default();
        other.observe_tool(
            "write",
            0,
            Some(&serde_json::json!({"file_path": "other.rs", "after": "different"})),
        );
        assert!(matches!(
            decide_completion(&other, &[], &[waiver], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[test]
    fn diagnostic_appears_on_the_next_model_visible_tool_result() {
        let observation = observation_from_diagnostics(
            "src/lib.rs",
            Some(4),
            false,
            vec!["src/lib.rs:3: unused variable".to_string()],
        );
        let visible = model_visible_observation("wrote src/lib.rs", &observation);
        assert!(visible.contains("unused variable"));
        assert!(!visible.contains("code_diagnostics"));
        let message = crate::llm::Message::tool_result("write-1", &visible, false);
        let model_input = message
            .content
            .iter()
            .find_map(|block| match block {
                crate::llm::ContentBlock::ToolResult {
                    content: crate::llm::ToolResultContentField::Text(text),
                    ..
                } => Some(text.as_str()),
                _ => None,
            })
            .expect("tool result is the next model input");
        assert!(model_input.contains("unused variable"));
        let stale = observation_from_diagnostics(
            "src/lib.rs",
            Some(3),
            true,
            vec!["src/lib.rs:1: previous revision".to_string()],
        );
        assert!(!stale.render().contains("previous revision"));
        assert!(stale.render().contains("stale"));
    }

    #[test]
    fn unavailable_observation_does_not_satisfy_the_gate() {
        let ledger = ledger_with_write();
        let observation = MutationObservationV1::unavailable("src/lib.rs");
        assert!(observation.render().contains("unavailable"));
        assert!(matches!(
            decide_completion(&ledger, &[], &[], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[test]
    fn unseen_workspace_path_opens_the_gate_without_a_second_digest() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "write",
            0,
            Some(&serde_json::json!({ "file_path": "src/lib.rs" })),
        );
        let digest = ledger.digest().to_string();
        ledger.observe_unseen_paths(&[
            "src/lib.rs".to_string(),
            ".a3s/tui/outcomes/v1/id.json".to_string(),
            "guest.txt".to_string(),
        ]);
        assert_ne!(ledger.digest(), digest);
        assert!(ledger.paths().any(|path| path == "guest.txt"));
        assert!(!ledger.paths().any(|path| path.contains(".a3s")));
        assert_eq!(
            ledger.paths().filter(|path| *path == "src/lib.rs").count(),
            1,
            "an already recorded path must not mint a second effect identity"
        );
        assert!(matches!(
            decide_completion(&ledger, &[], &[], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[tokio::test]
    async fn background_workspace_child_blocks_narrative_until_its_delta_is_observed() {
        let workspace = tempfile::tempdir().unwrap();
        let task_id = "task-open-child";
        crate::porcelain::reserve_workspace_child(task_id);
        crate::porcelain::begin_workspace_child(task_id, workspace.path()).await;
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "task",
            0,
            Some(&serde_json::json!({ "workspace_child": task_id })),
        );
        match decide_completion(&ledger, &[], &[], true) {
            CompletionGate::Incomplete { message } => {
                assert!(message.contains("background workspace task"));
                assert!(message.contains(task_id));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }

        std::fs::write(workspace.path().join("guest.txt"), "hello\n").unwrap();
        crate::porcelain::settle_workspace_child(task_id, workspace.path()).await;
        absorb_open_workspace_children(
            &mut ledger,
            workspace.path(),
            &tokio_util::sync::CancellationToken::new(),
        )
        .await;
        assert!(
            ledger.paths().any(|path| path == "guest.txt"),
            "settled background write was not a parent mutation"
        );
        assert!(matches!(
            decide_completion(&ledger, &[], &[], false),
            CompletionGate::Incomplete { .. }
        ));
    }

    #[test]
    fn failed_wrapper_with_changed_paths_opens_the_gate() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "bash",
            1,
            Some(&serde_json::json!({
                "exit_code": 1,
                "changed_paths": ["guest.txt"]
            })),
        );
        match decide_completion(&ledger, &[], &[], false) {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn failed_write_path_without_changed_paths_is_not_a_mutation() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "write",
            1,
            Some(&serde_json::json!({"file_path": "guest.txt"})),
        );
        assert!(ledger.is_empty());
    }

    #[test]
    fn bash_without_changed_paths_is_not_a_mutation() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({"command": "rm -rf src"})),
        );
        assert!(ledger.is_empty());
    }

    #[test]
    fn stale_observation_omits_items() {
        let observation = MutationObservationV1::stale("src/lib.rs", Some(4));
        assert!(observation.items.is_empty());
        assert_eq!(observation.status, "stale");
        assert!(!observation.render().contains("error"));
    }

    #[test]
    fn nested_batch_write_opens_the_gate() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "batch",
            0,
            Some(&serde_json::json!({
                "status": "complete",
                "results": [{
                    "tool": "write",
                    "success": true,
                    "exit_code": 0,
                    "metadata": {"file_path": "src/lib.rs", "after": "fn main() {}"}
                }, {
                    "title": "not a tool call",
                    "success": true
                }]
            })),
        );
        match decide_completion(&ledger, &[], &[], false) {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn retrieval_index_stamp_is_not_a_source_mutation() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "search",
            0,
            Some(&serde_json::json!({
                "changed_paths": [".a3s-code/grep-trigram/stamp.txt"]
            })),
        );
        assert!(
            matches!(
                decide_completion(&ledger, &[], &[], false),
                CompletionGate::Allow(CompletionTerminal::Narrative)
            ),
            "a retrieval index stamp opened the completion gate"
        );
    }

    #[test]
    fn skill_changed_paths_open_the_gate() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "skill",
            0,
            Some(&serde_json::json!({
                "skill_name": "writer",
                "tool_calls": 1,
                "changed_paths": ["guest.txt"]
            })),
        );
        match decide_completion(&ledger, &[], &[], false) {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn nested_program_write_opens_the_gate() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "program",
            0,
            Some(&serde_json::json!({
                "program": {
                    "tool_calls": [{
                        "tool_name": "write",
                        "success": true,
                        "exit_code": 0,
                        "metadata": {"file_path": "src/lib.rs", "after": "fn main() {}"}
                    }]
                }
            })),
        );
        match decide_completion(&ledger, &[], &[], false) {
            CompletionGate::Incomplete { message } => {
                assert!(message.starts_with("completion gate:"));
            }
            other => panic!("expected incomplete, got {other:?}"),
        }
    }

    #[test]
    fn bound_step_closure_is_not_rewritten_as_narrative() {
        let verified = CompletionTerminal::Verified {
            effect_digest: "digest-a".to_string(),
        };
        assert_eq!(
            fold_step_completions(&[CompletionTerminal::Narrative, verified.clone()]),
            verified
        );
        assert_eq!(
            fold_step_completions(&[
                verified.clone(),
                CompletionTerminal::Waived {
                    effect_digest: "digest-a".to_string(),
                },
            ]),
            verified
        );
        assert_eq!(
            fold_step_completions(&[
                CompletionTerminal::Verified {
                    effect_digest: "digest-a".to_string(),
                },
                CompletionTerminal::Verified {
                    effect_digest: "digest-b".to_string(),
                },
            ]),
            CompletionTerminal::Distinct
        );
        assert!(CompletionTerminal::Distinct != CompletionTerminal::Narrative);
    }

    #[test]
    fn plan_claim_without_digest_is_ordinary() {
        let claimed = PlanRunAdmission {
            claims_implementation: true,
            plan_digest: None,
        };
        assert_eq!(claimed.label(), "ordinary");
        assert_eq!(
            PlanRunAdmission::implementation("abc").label(),
            "plan_implementation"
        );
    }

    #[test]
    fn fold_same_digest_waivers_keeps_first_bound_terminal() {
        let waived = CompletionTerminal::Waived {
            effect_digest: "same".into(),
        };
        assert_eq!(
            fold_step_completions(&[waived.clone(), waived.clone()]),
            waived
        );
        assert!(completion_digest(&CompletionTerminal::Distinct).is_none());
        assert!(completion_digest(&CompletionTerminal::Narrative).is_none());
    }

    #[test]
    fn fold_same_digest_prefers_verified_over_waived() {
        let verified = CompletionTerminal::Verified {
            effect_digest: "d".into(),
        };
        let waived = CompletionTerminal::Waived {
            effect_digest: "d".into(),
        };
        assert_eq!(fold_step_completions(&[waived, verified.clone()]), verified);
    }

    #[test]
    fn fold_different_digests_is_distinct() {
        assert_eq!(
            fold_step_completions(&[
                CompletionTerminal::Verified {
                    effect_digest: "a".into(),
                },
                CompletionTerminal::Verified {
                    effect_digest: "b".into(),
                },
            ]),
            CompletionTerminal::Distinct
        );
    }

    #[test]
    fn nested_tool_calls_skip_failed_and_nameless_entries() {
        let metadata = serde_json::json!({
            "results": [
                {"tool": "write", "success": false, "exit_code": 0, "metadata": {"file_path": "a.rs"}},
                {"tool": "write", "success": true, "exit_code": 1, "metadata": {"file_path": "b.rs"}},
                {"tool": "", "success": true, "exit_code": 0, "metadata": {"file_path": "c.rs"}},
                {"success": true, "exit_code": 0, "metadata": {"file_path": "d.rs"}},
                {"tool": "write", "success": true, "exit_code": 0, "metadata": {"file_path": "e.rs", "after": "ok"}}
            ]
        });
        let mut ledger = MutationLedger::default();
        ledger.observe_tool("task", 1, Some(&metadata));
        assert!(
            ledger.paths().any(|path| path == "e.rs"),
            "only the successful named nested write should land"
        );
        assert!(!ledger.paths().any(|path| path == "a.rs"));
        assert!(!ledger.paths().any(|path| path == "b.rs"));
    }

    #[test]
    fn completion_waiver_rejects_blank_digest_or_reason() {
        assert!(CompletionWaiverV1::new("   ", "reason").is_none());
        assert!(CompletionWaiverV1::new("digest", "   ").is_none());
        assert!(CompletionWaiverV1::new("", "reason").is_none());
    }

    #[test]
    fn content_digest_for_path_misses_unrelated_records() {
        let ledger = ledger_with_write();
        assert!(ledger.content_digest_for_path("other.rs").is_none());
        assert!(ledger.content_digest_for_path("src/lib.rs").is_some());
    }

    #[test]
    fn observe_workspace_child_ignores_blank_and_missing_markers() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({"workspace_child": "   "})),
        );
        assert!(!ledger.has_open_children());

        let missing = format!("missing-child-{}", std::process::id());
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({ "workspace_child": missing })),
        );
        assert!(!ledger.has_open_children());
    }

    #[tokio::test]
    async fn observe_workspace_child_records_settled_paths_and_dedupes_open_markers() {
        let root = tempfile::tempdir().unwrap();
        let settled = format!("settled-child-{}", std::process::id());
        let watch = crate::porcelain::Watch::start(root.path()).await;
        crate::porcelain::install_workspace_child(&settled, watch);
        std::fs::write(root.path().join("guest.txt"), "x\n").unwrap();
        crate::porcelain::settle_workspace_child(&settled, root.path()).await;

        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({ "workspace_child": settled })),
        );
        assert!(!ledger.has_open_children());
        assert!(!ledger.is_empty());

        let open = format!("open-child-{}", std::process::id());
        let watch = crate::porcelain::Watch::start(root.path()).await;
        crate::porcelain::install_workspace_child(&open, watch);
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({ "workspace_child": open })),
        );
        assert!(ledger.has_open_children());
        ledger.observe_tool(
            "bash",
            0,
            Some(&serde_json::json!({ "workspace_child": open })),
        );
        assert_eq!(ledger.open_children.len(), 1);
        crate::porcelain::settle_workspace_child(&open, root.path()).await;
        let _ = crate::porcelain::take_settled_workspace_child(&open);
    }

    #[test]
    fn push_ignores_empty_paths() {
        let mut ledger = MutationLedger::default();
        ledger.observe_tool(
            "write",
            0,
            Some(&serde_json::json!({"file_path": "   ", "after": "x"})),
        );
        assert!(ledger.is_empty());
    }

    #[test]
    fn model_visible_observation_covers_empty_and_already_tagged_output() {
        let observation =
            MutationObservationV1::diagnostics("src/a.rs", Some(1), vec!["warn".into()]);
        let rendered = model_visible_observation("", &observation);
        assert!(rendered.contains("[mutation observation]") || !rendered.is_empty());
        let tagged = model_visible_observation("[mutation observation]\nprior", &observation);
        assert!(tagged.contains("[mutation observation]"));
        let combined = model_visible_observation("body", &observation);
        assert!(combined.contains("body"));
    }

    #[test]
    fn report_binds_pass_rejects_digest_mismatch_and_empty_required() {
        let ledger = ledger_with_write();
        let digest = ledger.digest().to_string();
        let mismatched = VerificationReport::new(
            "edit",
            vec![VerificationCheck::required("build", "command", "compiles")
                .with_status(VerificationStatus::Passed)],
        )
        .with_effect_digest("other-digest");
        assert!(!report_binds_pass(&mismatched, &digest));
        let empty_required = VerificationReport::new(
            "edit",
            vec![VerificationCheck::optional("note", "info", "n")
                .with_status(VerificationStatus::Passed)],
        )
        .with_effect_digest(&digest);
        assert!(!report_binds_pass(&empty_required, &digest));
    }

    #[test]
    fn attach_observation_wraps_non_object_and_none_metadata() {
        let observation =
            MutationObservationV1::diagnostics("src/a.rs", Some(1), vec!["warn".into()]);
        let mut none_meta = None;
        attach_observation(&mut none_meta, &observation);
        assert!(none_meta
            .as_ref()
            .unwrap()
            .get("mutation_observation")
            .is_some());

        let mut scalar = Some(serde_json::json!("prior"));
        attach_observation(&mut scalar, &observation);
        assert_eq!(scalar.as_ref().unwrap()["previous"], "prior");
        assert!(scalar
            .as_ref()
            .unwrap()
            .get("mutation_observation")
            .is_some());
    }

    #[tokio::test]
    async fn absorb_open_children_skips_nongit_without_snapshots() {
        let root = tempfile::tempdir().unwrap();
        let mut ledger = MutationLedger::default();
        let task_id = format!("nongit-{}", std::process::id());
        ledger.open_children.push(OpenWorkspaceChild {
            task_id: task_id.clone(),
            porcelain: None,
            head: None,
            nongit: true,
        });
        let incomplete = absorb_open_workspace_children(
            &mut ledger,
            root.path(),
            &tokio_util::sync::CancellationToken::new(),
        )
        .await;
        assert!(!incomplete);
        // Nongit markers without snapshots are skipped without settling, so the
        // open child remains until a later successful observation clears it.
        assert_eq!(ledger.open_children.len(), 1);
        assert_eq!(ledger.open_children[0].task_id, task_id);
    }

    #[tokio::test]
    async fn absorb_open_children_deltas_git_backed_markers() {
        let root = tempfile::tempdir().unwrap();
        let status = std::process::Command::new("git")
            .args(["init"])
            .current_dir(root.path())
            .status()
            .unwrap();
        assert!(status.success());
        std::fs::write(root.path().join("README.md"), "hi\n").unwrap();
        let _ = std::process::Command::new("git")
            .args(["add", "README.md"])
            .current_dir(root.path())
            .status();
        let _ = std::process::Command::new("git")
            .args([
                "-c",
                "user.email=t@t",
                "-c",
                "user.name=t",
                "commit",
                "-m",
                "i",
            ])
            .current_dir(root.path())
            .status();

        let before_porcelain = crate::porcelain::lines(root.path()).await;
        std::fs::write(root.path().join("guest.txt"), "delta\n").unwrap();

        let mut ledger = MutationLedger::default();
        // No pending porcelain slot: absorb must take the delta branch.
        ledger.open_children.push(OpenWorkspaceChild {
            task_id: format!("git-child-{}", std::process::id()),
            porcelain: before_porcelain,
            head: None,
            nongit: false,
        });
        let incomplete = absorb_open_workspace_children(
            &mut ledger,
            root.path(),
            &tokio_util::sync::CancellationToken::new(),
        )
        .await;
        assert!(!incomplete || ledger.open_children.is_empty());
        assert!(ledger.open_children.is_empty());
    }
}