pointlock-store 0.1.8

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

use pointlock_ir::{
    ActChannel, ActionExecution, ActionName, ActionOutcome, ActionOutcomeKind,
    AssertionOutcomeRecord, AttemptRecord, BindingState, CallFrame, CheckpointView, ErrorClass,
    EvidenceRef, ExecutionMode, FlowId, Frontier, Hash, HumanPending, HumanPurpose, IterState,
    ObservationRecord, PathFrame, PendingIntent, RunLogEvent, RunLogPayload, RunPath, StepId,
    StepRecord, StepState, StepVerdict, Verdict, VerdictStatus,
};
use serde_json::Value;
use std::collections::BTreeMap;

use crate::error::FoldError;

/// Immutable per-run metadata (the `run` table row): the fold input the
/// 17-event union does not carry — root flow id, provider binding seed, and
/// the identity fields also present in `runStarted`.
#[derive(Debug, Clone, PartialEq)]
pub struct RunMeta {
    /// The run's id.
    pub run_id: String,
    /// The root flow's id (source of the root [`CallFrame`]'s `flowId`;
    /// `runStarted` does not carry it).
    pub flow_id: FlowId,
    /// Content hash of the executing IR.
    pub ir_hash: Hash,
    /// Digest of the bound capability lockfile.
    pub lockfile_digest: Hash,
    /// The run's input parameters.
    pub params_snapshot: Value,
    /// Provider binding seed (M0: copied into the view verbatim; no event
    /// advances the cursor yet — M0-C).
    pub binding: BindingState,
    /// Run creation timestamp (ms since epoch); informational.
    pub created_at_ms: u64,
}

/// Run lifecycle status — the `run.status` column's closed four-value set
/// (07 §3.3 DDL CHECK constraint).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunStatus {
    /// The run is executing (also the `begin_run` seed value).
    Running,
    /// The run was suspended (`runSuspended`).
    Suspended,
    /// A human interaction is pending (`humanRequested`; covers both step
    /// and supervision purposes — the discriminator lives in
    /// `humanPending.purpose`, not at run level; R13).
    AwaitingHuman,
    /// The run finished (`runFinished`).
    Finished,
}

impl RunStatus {
    /// The stored string form (matches the DDL CHECK constraint verbatim).
    pub fn as_str(&self) -> &'static str {
        match self {
            RunStatus::Running => "running",
            RunStatus::Suspended => "suspended",
            RunStatus::AwaitingHuman => "awaitingHuman",
            RunStatus::Finished => "finished",
        }
    }

    /// Parses the stored string form.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "running" => Some(RunStatus::Running),
            "suspended" => Some(RunStatus::Suspended),
            "awaitingHuman" => Some(RunStatus::AwaitingHuman),
            "finished" => Some(RunStatus::Finished),
            _ => None,
        }
    }
}

/// Result of a fold: the materializable view plus the run status the same
/// event sequence implies (kept together so the write path and the rebuild
/// self-check share one transition function).
#[derive(Debug, Clone, PartialEq)]
pub struct FoldedRun {
    /// The deterministic checkpoint view.
    pub view: CheckpointView,
    /// The run status after the last event.
    pub status: RunStatus,
}

/// Folds an ordered event sequence into a [`CheckpointView`] + run status.
///
/// Pure and deterministic: same `(meta, events)` in, same [`FoldedRun`]
/// out. With zero events it returns the seeded pre-start view (empty frame
/// stack, `pending` frontier at the root flow path). Structural violations
/// return [`FoldError`] — see the module docs for the coverage rules.
pub fn fold_checkpoint(meta: &RunMeta, events: &[RunLogEvent]) -> Result<FoldedRun, FoldError> {
    Ok(fold_state(meta, events)?.finish())
}

/// Folds the full ledger into the terminal [`FoldState`] (not yet
/// collapsed to a view). `Store::append_event` caches it per run so the
/// next append folds exactly one event instead of the whole ledger —
/// the single-writer invariant (I1) makes the carried state exact, and
/// `verify_checkpoint` remains the from-scratch cross-check.
pub(crate) fn fold_state(meta: &RunMeta, events: &[RunLogEvent]) -> Result<FoldState, FoldError> {
    let mut state = FoldState::seed(meta);
    let mut prev_seq: Option<u64> = None;
    for event in events {
        if event.run_id != meta.run_id {
            return Err(FoldError::RunIdMismatch {
                seq: event.seq,
                expected: meta.run_id.clone(),
                actual: event.run_id.clone(),
            });
        }
        if let Some(prev) = prev_seq
            && event.seq <= prev
        {
            return Err(FoldError::NonMonotonicSeq {
                prev,
                seq: event.seq,
            });
        }
        prev_seq = Some(event.seq);
        state.apply(event)?;
    }
    Ok(state)
}

/// Scratch record of the step currently being assembled between
/// `stepEntered` and `stepExited`. Kept as a stack: a `call` step stays
/// in flight while its callee's steps enter and exit above it.
#[derive(Debug, Clone)]
struct InFlightStep {
    run_path: RunPath,
    step_id: StepId,
    effect_hash: Hash,
    judge_hash: Hash,
    resolved_inputs: Value,
    attempts: Vec<AttemptRecord>,
    /// Callee outputs harvested from `callFramePopped` (call steps); the
    /// `stepExited` payload's own output takes precedence when present.
    call_outputs: Option<Value>,
    observations: Vec<ObservationRecord>,
    evidence: Vec<EvidenceRef>,
    assertion_outcomes: Vec<AssertionOutcomeRecord>,
    verdict: Option<StepVerdict>,
}

/// (chainIndex, channel, actionName) of one `actionIntent` (item ②).
type DispatchIdentity = (Option<u32>, Option<ActChannel>, Option<ActionName>);

#[derive(Debug, Clone)]
pub(crate) struct FoldState {
    view: CheckpointView,
    status: RunStatus,
    root_flow_id: FlowId,
    started: bool,
    in_flight: Vec<InFlightStep>,
    /// callId → the intent's dispatch identity (item ②): in-memory
    /// carrier from `actionIntent` to the settling `attemptRecord`;
    /// never persisted (the durable shapes stay unchanged).
    intent_dispatch: BTreeMap<String, DispatchIdentity>,
    /// The run-path prefix of each live frame (parallel to `view.frames`):
    /// the root flow path, then each pushed call frame's event path. The
    /// direct-body-child test for `nextIndex` needs it.
    frame_paths: Vec<RunPath>,
}

impl FoldState {
    fn seed(meta: &RunMeta) -> Self {
        let root_path: RunPath = vec![PathFrame::Flow {
            flow_id: meta.flow_id.clone(),
            ir_hash: meta.ir_hash.clone(),
        }];
        FoldState {
            view: CheckpointView {
                run_id: meta.run_id.clone(),
                ir_hash: meta.ir_hash.clone(),
                lockfile_digest: meta.lockfile_digest.clone(),
                params_snapshot: meta.params_snapshot.clone(),
                binding: meta.binding.clone(),
                completed: Vec::new(),
                frames: Vec::new(),
                frontier: Frontier {
                    run_path: root_path,
                    state: StepState::Pending,
                    pending_intent: None,
                },
                human_pending: None,
            },
            status: RunStatus::Running,
            root_flow_id: meta.flow_id.clone(),
            started: false,
            in_flight: Vec::new(),
            intent_dispatch: BTreeMap::new(),
            frame_paths: Vec::new(),
        }
    }

    pub(crate) fn finish(mut self) -> FoldedRun {
        // Live foreach reconstruction (07 §3.2 iterStack): an in-flight
        // span whose successor's run path extends it with an `iteration`
        // frame is a live foreach round; the `as` name comes from the
        // container's stepEntered snapshot ({ items, as }). No carrier ⇒
        // no IterState (never fabricated).
        for frame in &mut self.view.frames {
            frame.iter_stack.clear();
        }
        for pair in self.in_flight.windows(2) {
            let (parent, child) = (&pair[0], &pair[1]);
            if child.run_path.len() <= parent.run_path.len() {
                continue;
            }
            let extends = parent
                .run_path
                .iter()
                .zip(child.run_path.iter())
                .all(|(a, b)| same_site(a, b));
            let Some(PathFrame::Iteration { index, key }) =
                child.run_path.get(parent.run_path.len())
            else {
                continue;
            };
            let Some(var) = parent
                .resolved_inputs
                .get("as")
                .and_then(Value::as_str)
                .filter(|_| extends)
            else {
                continue;
            };
            // The IterState belongs to the innermost frame whose prefix
            // covers the foreach span.
            let owner = self.frame_paths.iter().rposition(|prefix| {
                parent.run_path.len() >= prefix.len()
                    && prefix
                        .iter()
                        .zip(parent.run_path.iter())
                        .all(|(a, b)| same_site(a, b))
            });
            if let Some(owner) = owner
                && owner < self.view.frames.len()
            {
                self.view.frames[owner].iter_stack.push(IterState {
                    var: var.to_owned(),
                    index: *index,
                    key: key.clone(),
                });
            }
        }
        FoldedRun {
            view: self.view,
            status: self.status,
        }
    }

    /// Applies one event. All 17 payload variants are matched explicitly
    /// (`callFramePushed` twice — its `rebase` discriminant selects between
    /// opening a frame and re-entering one); no-op arms are documented as
    /// such (M0 iron rule — nothing is silently ignored via a wildcard).
    pub(crate) fn apply(&mut self, event: &RunLogEvent) -> Result<(), FoldError> {
        let seq = event.seq;
        if !self.started && !matches!(event.payload, RunLogPayload::RunStarted { .. }) {
            return Err(FoldError::EventBeforeRunStarted {
                seq,
                event_type: event.payload.event_type(),
            });
        }
        match &event.payload {
            RunLogPayload::RunStarted {
                ir_hash,
                lockfile_digest,
                params_snapshot,
                // Per-segment supervision policy is log-resident audit data
                // (spine §6.9): CheckpointView has no field for it.
                supervise_policy: _,
            } => {
                if self.started {
                    return Err(FoldError::DuplicateRunStarted { seq });
                }
                self.started = true;
                // The log is the truth: adopt the payload's identity fields
                // (begin_run writes the same values into the run row).
                self.view.ir_hash = ir_hash.clone();
                self.view.lockfile_digest = lockfile_digest.clone();
                self.view.params_snapshot = params_snapshot.clone();
                // Root call frame: flowId comes from RunMeta (the payload
                // does not carry it), inputs are the params snapshot
                // (07 §3.2: the root frame references paramsSnapshot).
                self.view.frames.push(CallFrame {
                    flow_id: self.root_flow_id.clone(),
                    ir_hash: ir_hash.clone(),
                    call_step_id: None,
                    inputs_snapshot: params_snapshot.clone(),
                    vars: Default::default(),
                    iter_stack: Vec::new(),
                    next_index: 0,
                });
                self.view.frontier = Frontier {
                    run_path: vec![PathFrame::Flow {
                        flow_id: self.root_flow_id.clone(),
                        ir_hash: ir_hash.clone(),
                    }],
                    state: StepState::Pending,
                    pending_intent: None,
                };
                self.frame_paths.push(vec![PathFrame::Flow {
                    flow_id: self.root_flow_id.clone(),
                    ir_hash: ir_hash.clone(),
                }]);
                self.status = RunStatus::Running;
            }
            RunLogPayload::StepEntered {
                step_id,
                effect_hash,
                judge_hash,
                resolved_inputs,
            } => {
                self.in_flight.push(InFlightStep {
                    run_path: event.run_path.clone(),
                    step_id: step_id.clone(),
                    effect_hash: effect_hash.clone(),
                    judge_hash: judge_hash.clone(),
                    resolved_inputs: resolved_inputs.clone(),
                    attempts: Vec::new(),
                    call_outputs: None,
                    observations: Vec::new(),
                    evidence: Vec::new(),
                    assertion_outcomes: Vec::new(),
                    verdict: None,
                });
                self.view.frontier = Frontier {
                    run_path: event.run_path.clone(),
                    state: StepState::Ready,
                    pending_intent: None,
                };
            }
            RunLogPayload::PreflightProbed { outcomes } => {
                // The probe outcomes stay log-resident (they are probes,
                // not the step's assert-phase outcomes), but the frontier's
                // STATE materializes (spine §6.2 / §6.6): a passed probe
                // set leaves the step `probing` (the act overwrites it with
                // `acting` moments later — the window is only visible when
                // the run stops in it), and a missed one leaves it
                // `drifted`, which is exactly what a checkpoint suspended
                // on drift must say — 「resume probe failed; awaiting
                // onResumeDrift disposition」 was unobservable before this
                // arm wrote it.
                //
                // An EMPTY outcome list is the `unprobed` mark (07 §4.2
                // rule 1), a note that nothing was checked — not a phase
                // transition; the state stays whatever it was.
                if !outcomes.is_empty() {
                    let missed = outcomes
                        .iter()
                        .any(|outcome| outcome.result != VerdictStatus::Pass);
                    self.view.frontier.state = if missed {
                        StepState::Drifted
                    } else {
                        StepState::Probing
                    };
                }
            }
            RunLogPayload::ActionIntent {
                call_id,
                args_snapshot,
                chain_index,
                channel,
                action_name,
            } => {
                // Fold-internal intent→settle carrier (2026-07-18
                // incorporation, item ②): the durable PendingIntent shape
                // stays unchanged (I1 on existing stores); the identity
                // fields ride in memory keyed by callId, deterministic
                // from events (the full-refold fallback reproduces it).
                self.intent_dispatch.insert(
                    call_id.clone(),
                    (*chain_index, *channel, action_name.clone()),
                );
                // The crash-window key (07 §3.1): frontier records the
                // hanging intent until the matching actionSettled.
                self.view.frontier.state = StepState::Acting;
                self.view.frontier.pending_intent = Some(PendingIntent {
                    call_id: call_id.clone(),
                    args_snapshot: args_snapshot.clone(),
                });
            }
            RunLogPayload::ActionSettled { call_id, outcome } => {
                let step =
                    self.in_flight
                        .last_mut()
                        .ok_or_else(|| FoldError::EventOutsideStep {
                            seq,
                            event_type: event.payload.event_type(),
                        })?;
                let dispatch = self.intent_dispatch.remove(call_id).unwrap_or_default();
                step.attempts
                    .push(attempt_record(call_id, outcome, dispatch));
                // Clear the pending intent this terminal settles. A
                // non-matching callId leaves the intent in place (a runner
                // discipline breach worth surfacing at reconcile time, not
                // papering over here).
                if self
                    .view
                    .frontier
                    .pending_intent
                    .as_ref()
                    .is_some_and(|intent| intent.call_id == *call_id)
                {
                    self.view.frontier.pending_intent = None;
                }
                self.view.frontier.state = StepState::Settling;
            }
            RunLogPayload::ObservationRecorded { observation } => {
                let step =
                    self.in_flight
                        .last_mut()
                        .ok_or_else(|| FoldError::EventOutsideStep {
                            seq,
                            event_type: event.payload.event_type(),
                        })?;
                if let Some(screenshot) = &observation.screenshot {
                    step.evidence.push(screenshot.clone());
                }
                if let Some(ui_snapshot) = &observation.ui_snapshot {
                    step.evidence.push(ui_snapshot.clone());
                }
                step.observations.push(observation.clone());
                self.view.frontier.state = StepState::Observing;
            }
            RunLogPayload::AssertionEvaluated { outcome } => {
                let step =
                    self.in_flight
                        .last_mut()
                        .ok_or_else(|| FoldError::EventOutsideStep {
                            seq,
                            event_type: event.payload.event_type(),
                        })?;
                step.assertion_outcomes.push(outcome.clone());
                self.view.frontier.state = StepState::Asserting;
            }
            RunLogPayload::VerdictRecorded {
                verdict,
                localized,
                localization_gaps: _,
                remote_archival_error: _,
            } => {
                // The judgment's localized manifest merges into the
                // record's evidence (item ③, 2026-07-18): dedup key
                // (sha256, asset.id), first occurrence wins — the same
                // rule the dossier applies, so the two surfaces can
                // never diverge on one ledger. Gaps stay log-resident
                // (the dossier reads them from the event; the checkpoint
                // carries successes only).
                //
                // The target is chosen by the event's OWN run path, never by
                // "is anything in flight". A crash-opened span leaves an
                // in-flight step that has nothing to do with an offline
                // re-judgement written against a completed record, and
                // attaching the verdict to it would silently overwrite a
                // different step's judgment — the ledger would then say the
                // crashed step was judged and the re-judged one was not.
                // Every live `verdictRecorded` is appended at its own step's
                // path (the same path its `stepEntered` used), so path
                // equality selects exactly the target `last_mut()` used to
                // select in every live case.
                let in_flight_at_path = self
                    .in_flight
                    .iter()
                    .rposition(|step| same_instance(&step.run_path, &event.run_path));
                if let Some(index) = in_flight_at_path {
                    let step = &mut self.in_flight[index];
                    merge_evidence(&mut step.evidence, localized);
                    step.verdict = Some(project_verdict(verdict));
                    self.view.frontier.state = StepState::Judged;
                } else if let Some(record) = self
                    .view
                    .completed
                    .iter_mut()
                    .rev()
                    .find(|record| same_instance(&record.run_path, &event.run_path))
                {
                    // Offline re-judgement (judgeDirty, spine §6.7-A): the
                    // log gets a *new* verdictRecorded with `supersedes`;
                    // the fold re-projects the completed record. Rejudge
                    // manifests are empty by construction (nothing is
                    // localized offline) — the merge is a no-op there,
                    // and the arm treats the field identically in both
                    // branches so incremental and full refolds agree.
                    merge_evidence(&mut record.evidence, localized);
                    record.verdict = Some(project_verdict(verdict));
                } else {
                    return Err(FoldError::VerdictWithoutTarget { seq });
                }
            }
            RunLogPayload::StepExited {
                state,
                output,
                localized,
                ..
            } => {
                // Pair the exit with the innermost in-flight entry at the
                // exit's OWN path, never with whatever is on top. Every
                // live exit is LIFO, but a crash-opened span whose step the
                // repaired IR no longer reaches (renamed, deleted, moved)
                // is never re-entered and never closed: it stays under its
                // container, and a blind pop would hand the container's
                // exit (state, output) to the orphan's record while the
                // container itself gets none — and is then re-executed on
                // every later resume. Site-wise match, as for verdicts.
                let index = self
                    .in_flight
                    .iter()
                    .rposition(|step| same_instance(&step.run_path, &event.run_path))
                    .ok_or(FoldError::StepExitedWithoutEntry { seq })?;
                let mut step = self.in_flight.remove(index);
                // An unverified exit's manifest merges here (item ③
                // review fix) — same rule as the verdict-borne one.
                merge_evidence(&mut step.evidence, localized);
                // A terminal exit of the awaiting step settles its pending
                // request without a response — the lazy timeout settlement
                // (verdict unknown) and the aborted disposition both take
                // this path (06 §5.3).
                if self
                    .view
                    .human_pending
                    .as_ref()
                    .is_some_and(|pending| exit_settles_pending(&event.run_path, &pending.run_path))
                {
                    self.view.human_pending = None;
                }
                // Every terminal exit leaves a record (judged / skipped /
                // blocked / aborted alike): completion order == exit order.
                self.view.completed.push(StepRecord {
                    run_path: step.run_path,
                    step_id: step.step_id,
                    // Harvested from the stepEntered carrier (spine §6.1
                    // M1 note).
                    effect_hash: step.effect_hash,
                    judge_hash: step.judge_hash,
                    attempts: step.attempts,
                    resolved_inputs: step.resolved_inputs,
                    // The exit's projected output wins; a call step whose
                    // exit carries none keeps the callee outputs from
                    // callFramePopped.
                    output: output.clone().or(step.call_outputs),
                    observations: step.observations,
                    evidence: step.evidence,
                    assertion_outcomes: step.assertion_outcomes,
                    verdict: step.verdict,
                });
                // Advance the innermost frame's *body* cursor — only when
                // the exited step is a direct body child of that frame
                // (nested container children and iteration instances do
                // not move it; M2). While a callee runs, the innermost
                // frame *is* the callee frame, so this lands on the right
                // frame for nested exits too. Frame identity is compared
                // site-wise (hash-insensitive) so a cross-IR resume
                // segment keeps advancing the same frame.
                let frame = self
                    .view
                    .frames
                    .last_mut()
                    .ok_or(FoldError::NoActiveFrame { seq })?;
                if self
                    .frame_paths
                    .last()
                    .is_some_and(|prefix| direct_body_child(prefix, &event.run_path))
                {
                    frame.next_index += 1;
                }
                self.view.frontier = Frontier {
                    run_path: event.run_path.clone(),
                    state: *state,
                    pending_intent: None,
                };
            }
            RunLogPayload::CallFramePushed {
                frame,
                rebase: false,
            } => {
                self.view.frames.push(frame.clone());
                self.frame_paths.push(event.run_path.clone());
            }
            RunLogPayload::CallFramePushed {
                frame,
                rebase: true,
            } => {
                // A live-frame re-entry under a repaired callee (07 §5.2
                // case (a)) — NOT a new stack level. The addressed level is
                // the event path's `call` depth, not the innermost frame: a
                // resume walks back in from the root, so an outer frame is
                // re-entered while the inner ones it once opened are still
                // on the stack. Cross-IR safe by construction — the count
                // reads the path's shape, never its hashes.
                let level = event
                    .run_path
                    .iter()
                    .filter(|frame| matches!(frame, PathFrame::Call { .. }))
                    .count();
                let depth = self.view.frames.len();
                let Some(open) = self.view.frames.get_mut(level) else {
                    return Err(FoldError::RebaseWithoutFrame { seq, level, depth });
                };
                // ONLY the callee pin moves. `inputsSnapshot` above all
                // stays put: a live frame's snapshot is never re-evaluated
                // for a new IR (07 §5.2 corollary / §4.6), and the descent
                // was licensed precisely because the `inputs` expressions
                // did not change — so the archived values ARE the ones the
                // new IR would produce. The body cursor, iteration stack
                // and vars describe where the frame *is*, which a repaired
                // callee does not move either.
                open.ir_hash = frame.ir_hash.clone();
                // `frame_paths` is left alone: it is only ever compared
                // through `same_site`, which is hash-insensitive precisely
                // so a cross-IR resume keeps matching the same site.
            }
            RunLogPayload::CallFramePopped { outputs } => {
                if self.view.frames.len() <= 1 {
                    return Err(FoldError::PoppedRootFrame { seq });
                }
                self.view.frames.pop();
                self.frame_paths.pop();
                // The innermost in-flight step is the host call step (its
                // callee's steps have all exited); the callee's outputs
                // are the call step's output. Handler-repair frames have
                // no host call step — nothing in flight, nothing to fill.
                if let Some(step) = self.in_flight.last_mut() {
                    step.call_outputs = outputs.clone();
                }
            }
            RunLogPayload::HandlerTriggered {
                hook: _,
                trigger: _,
                disposition: _,
            } => {
                // Documented no-op: handler firing is audit data. The hook
                // trace materializes through the `hook` frames of
                // subsequent events' run paths, not as a view field.
            }
            RunLogPayload::HumanRequested {
                request_id,
                purpose,
                mode,
                prompt,
                // The presented evidence/values and the response contract
                // stay log-resident; HumanPending does not carry them
                // (spine §6.6, 06 §4.3 reads them back from the event).
                presents: _,
                decisions: _,
                output_schema: _,
                deadline_at_ms,
            } => {
                self.view.human_pending = Some(HumanPending {
                    run_path: event.run_path.clone(),
                    request_id: request_id.clone(),
                    purpose: *purpose,
                    mode: *mode,
                    prompt: prompt.clone(),
                    deadline_at_ms: *deadline_at_ms,
                });
                self.view.frontier.state = StepState::AwaitingHuman;
                self.status = RunStatus::AwaitingHuman;
            }
            RunLogPayload::HumanResponded {
                request_id,
                purpose,
                response,
                actor: _,
            } => {
                // Lazy settlement (spine §6.8): a response must pair the
                // pending request; the arbitration result itself
                // (response/actor) stays log-resident.
                let paired = self
                    .view
                    .human_pending
                    .as_ref()
                    .is_some_and(|pending| pending.request_id == *request_id);
                if !paired {
                    return Err(FoldError::UnpairedHumanResponse {
                        seq,
                        request_id: request_id.clone(),
                    });
                }
                // A supervision `suspend` answer is non-final (spine §6.9):
                // the request stays pending across segments and the run
                // keeps awaiting a proceed/abort ruling.
                let retains = *purpose == HumanPurpose::Supervision
                    && response.get("decision").and_then(Value::as_str) == Some("suspend");
                if retains {
                    self.status = RunStatus::AwaitingHuman;
                } else {
                    self.view.human_pending = None;
                    // The frontier step state stays as-is: the follow-up
                    // event (actionIntent on supervision-proceed,
                    // verdictRecorded / stepExited on a human step) moves
                    // it.
                    self.status = RunStatus::Running;
                }
            }
            RunLogPayload::RunSuspended { .. } => {
                // Run-level status only; the frontier keeps its last
                // step-level state so resume knows where the step stood.
                // A suspension while a human request is pending keeps the
                // run self-describing as awaitingHuman (spine §6.8: the
                // wait is a legal suspend point).
                self.status = if self.view.human_pending.is_some() {
                    RunStatus::AwaitingHuman
                } else {
                    RunStatus::Suspended
                };
            }
            RunLogPayload::RunResumed {
                // Log-resident in M0: the fold does not re-base completed
                // records from the alignment report (module docs; M0-C).
                alignment_report: _,
                // Per-segment policy, log-resident (as for runStarted).
                supervise_policy: _,
                event_cursor,
            } => {
                self.status = RunStatus::Running;
                // 07 §4.5 (incorporated 2026-07-18): a cursor-bearing
                // resume extends the lineage and reseeds the watermark.
                // A cursor-less resume (old ledgers) changes nothing —
                // the view names exactly what was recorded, never an
                // invented generation (principle 4). Only new-binary
                // ledgers carry the field, so stored views and refolds
                // agree on every pre-incorporation store (I1).
                if let Some(cursor) = event_cursor {
                    if self.view.binding.session_lineage.last() != Some(&cursor.session_id) {
                        self.view
                            .binding
                            .session_lineage
                            .push(cursor.session_id.clone());
                    }
                    self.view.binding.event_cursor = cursor.clone();
                }
            }
            RunLogPayload::RunFinished {
                verdict: _,
                remote_archival_error: _,
            } => {
                // The folded flow verdict stays log-resident; the view has
                // no field for it (reports read it from the log).
                self.status = RunStatus::Finished;
            }
        }
        Ok(())
    }
}

/// Whether `path` addresses a direct body child of the frame rooted at
/// `prefix`: exactly one extra frame, and that frame is a step or a call
/// (iteration instances and nested container children are not body
/// children).
fn direct_body_child(prefix: &RunPath, path: &RunPath) -> bool {
    path.len() == prefix.len() + 1
        && prefix.iter().zip(path.iter()).all(|(a, b)| same_site(a, b))
        && matches!(
            path.last(),
            Some(PathFrame::Step { .. }) | Some(PathFrame::Call { .. })
        )
}

/// Whether two run paths address the SAME step instance.
///
/// Hash-insensitive by way of [`same_site`], because a cross-IR resume
/// rewrites the flow and callee hashes of a path whose sites are unchanged:
/// a step whose span was opened by the crashed segment carries the OLD
/// flow's hashes, while the events the resume appends carry the new ones.
/// Both branches of the `verdictRecorded` arm use this one notion — if they
/// disagreed, a path could match neither and a legitimate verdict would
/// fold to `VerdictWithoutTarget`.
fn same_instance(a: &[PathFrame], b: &[PathFrame]) -> bool {
    a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| same_site(x, y))
}

/// Whether a `stepExited` at `exited` settles the pending human request
/// anchored at `pending`: the exited step IS the awaiting step, or an
/// ancestor of it. Two ledger shapes need more than exact path equality:
/// an escalate hook's human is anchored at `<host>/hook:…/<human>` and
/// settled in memory when the HOST exits (no event at the hook path), and
/// a cross-IR resume exits the awaiting step at a path carrying the NEW
/// flow hashes while the request was recorded under the old ones. Hence
/// site-wise prefix, through [`same_instance`]. The inbox and overview
/// projections share this one rule so the three surfaces cannot diverge.
pub(crate) fn exit_settles_pending(exited: &[PathFrame], pending: &[PathFrame]) -> bool {
    pending.len() >= exited.len() && same_instance(&pending[..exited.len()], exited)
}

/// Site-wise path-frame identity: hash-insensitive (a cross-IR resume
/// changes the flow/callee hashes of the same site), position-sensitive.
fn same_site(a: &PathFrame, b: &PathFrame) -> bool {
    match (a, b) {
        (PathFrame::Flow { flow_id: a, .. }, PathFrame::Flow { flow_id: b, .. }) => a == b,
        (PathFrame::Step { step_id: a }, PathFrame::Step { step_id: b }) => a == b,
        (
            PathFrame::Call {
                step_id: a,
                callee_flow_id: af,
                ..
            },
            PathFrame::Call {
                step_id: b,
                callee_flow_id: bf,
                ..
            },
        ) => a == b && af == bf,
        (
            PathFrame::Iteration { index: a, key: ak },
            PathFrame::Iteration { index: b, key: bk },
        ) => a == b && ak == bk,
        (a, b) => a == b,
    }
}

/// Merges a judgment's localized manifest into a record's evidence:
/// dedup key (sha256, asset.id), first occurrence wins (item ③ — one
/// rule for checkpoint and dossier).
fn merge_evidence(evidence: &mut Vec<EvidenceRef>, localized: &[EvidenceRef]) {
    for entry in localized {
        let duplicate = evidence
            .iter()
            .any(|existing| existing.sha256 == entry.sha256 && existing.asset.id == entry.asset.id);
        if !duplicate {
            evidence.push(entry.clone());
        }
    }
}

/// Projects a four-way terminal into the durable [`AttemptRecord`]
/// (spine §6.6): discriminant + best-effort classification. The full
/// outcome stays in the `actionSettled` payload.
fn attempt_record(
    call_id: &str,
    outcome: &ActionOutcome,
    dispatch: DispatchIdentity,
) -> AttemptRecord {
    let kind = match outcome {
        ActionOutcome::Succeeded { .. } => ActionOutcomeKind::Succeeded,
        ActionOutcome::Failed { .. } => ActionOutcomeKind::Failed,
        ActionOutcome::Cancelled { .. } => ActionOutcomeKind::Cancelled,
        ActionOutcome::TimedOut { .. } => ActionOutcomeKind::TimedOut,
    };
    // Best-effort M0 classification: ErrorInfo.code is an open string the
    // provider adapter maps onto the closed ErrorClass; when the code
    // already spells a class verbatim we adopt it, otherwise None (a
    // dedicated carrier is M0-C).
    let error_class = match outcome {
        ActionOutcome::Succeeded { .. } => None,
        ActionOutcome::Failed { error }
        | ActionOutcome::Cancelled { error }
        | ActionOutcome::TimedOut { error } => parse_error_class(&error.code),
    };
    let (execution_mode, fallback_reason) = match outcome {
        ActionOutcome::Succeeded { result } => match &result.execution {
            Some(ActionExecution::NativeSemantic { .. }) => {
                (Some(ExecutionMode::NativeSemantic), None)
            }
            Some(ActionExecution::WebSemantic { .. }) => (Some(ExecutionMode::WebSemantic), None),
            Some(ActionExecution::CoordinateFallback {
                fallback_reason, ..
            }) => (
                Some(ExecutionMode::CoordinateFallback),
                Some(*fallback_reason),
            ),
            None => (None, None),
        },
        _ => (None, None),
    };
    let (chain_index, channel, action_name) = dispatch;
    AttemptRecord {
        call_id: call_id.to_owned(),
        outcome: kind,
        error_class,
        execution_mode,
        fallback_reason,
        chain_index,
        channel,
        action_name,
    }
}

fn parse_error_class(code: &str) -> Option<ErrorClass> {
    serde_json::from_value(Value::String(code.to_owned())).ok()
}

/// Projects a folded [`Verdict`] onto the durable per-step [`StepVerdict`]
/// (spine §6.6: summary/evidence stay in the `verdictRecorded` payload).
fn project_verdict(verdict: &Verdict) -> StepVerdict {
    StepVerdict {
        status: verdict.status,
        degraded: verdict.degraded,
        supersedes: verdict.supersedes.clone(),
    }
}

#[cfg(test)]
mod tests {
    use pointlock_ir::{BindingState, EventCursor, SupervisePolicy};
    use serde_json::json;

    use super::*;

    fn hash(fill: char) -> Hash {
        Hash::new(format!("sha256:{}", fill.to_string().repeat(64))).expect("valid hash")
    }

    fn meta() -> RunMeta {
        RunMeta {
            run_id: "run-1".to_owned(),
            flow_id: FlowId::new("checkout").expect("valid flow id"),
            ir_hash: hash('a'),
            lockfile_digest: hash('b'),
            params_snapshot: json!({"user": "alice"}),
            binding: BindingState {
                device_id: "dev-1".to_owned(),
                session_lineage: vec!["s-1".to_owned()],
                event_cursor: EventCursor {
                    session_id: "s-1".to_owned(),
                    last_sequence: 0,
                },
            },
            created_at_ms: 1,
        }
    }

    fn event(seq: u64, run_path: RunPath, payload: RunLogPayload) -> RunLogEvent {
        RunLogEvent {
            run_id: "run-1".to_owned(),
            seq,
            at_ms: 1_000 + seq,
            run_path,
            payload,
        }
    }

    fn run_started() -> RunLogPayload {
        RunLogPayload::RunStarted {
            ir_hash: hash('a'),
            lockfile_digest: hash('b'),
            params_snapshot: json!({"user": "alice"}),
            supervise_policy: Some(SupervisePolicy::Mutating),
        }
    }

    #[test]
    fn zero_events_fold_to_the_seeded_pre_start_view() {
        let folded = fold_checkpoint(&meta(), &[]).expect("fold");
        assert!(folded.view.frames.is_empty());
        assert_eq!(folded.view.frontier.state, StepState::Pending);
        assert_eq!(folded.status, RunStatus::Running);
    }

    #[test]
    fn run_started_initializes_the_root_frame_from_meta_flow_id() {
        let folded = fold_checkpoint(&meta(), &[event(1, vec![], run_started())]).expect("fold");
        assert_eq!(folded.view.frames.len(), 1);
        assert_eq!(folded.view.frames[0].flow_id.as_str(), "checkout");
        assert_eq!(
            folded.view.frames[0].inputs_snapshot,
            json!({"user": "alice"})
        );
        assert_eq!(folded.view.frames[0].next_index, 0);
    }

    #[test]
    fn events_before_run_started_are_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[event(
                1,
                vec![],
                RunLogPayload::StepEntered {
                    step_id: StepId::new("login").expect("valid step id"),
                    effect_hash: hash('c'),
                    judge_hash: hash('d'),
                    resolved_inputs: json!({}),
                },
            )],
        )
        .expect_err("must reject");
        assert_eq!(
            err,
            FoldError::EventBeforeRunStarted {
                seq: 1,
                event_type: "stepEntered"
            }
        );
    }

    #[test]
    fn duplicate_run_started_is_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(2, vec![], run_started()),
            ],
        )
        .expect_err("must reject");
        assert_eq!(err, FoldError::DuplicateRunStarted { seq: 2 });
    }

    #[test]
    fn non_monotonic_seq_is_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    1,
                    vec![],
                    RunLogPayload::RunSuspended {
                        provider_state_summary: None,
                        reason: None,
                    },
                ),
            ],
        )
        .expect_err("must reject");
        assert_eq!(err, FoldError::NonMonotonicSeq { prev: 1, seq: 1 });
    }

    #[test]
    fn step_exited_without_entry_is_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    vec![],
                    RunLogPayload::StepExited {
                        provider_state_summary: None,
                        state: StepState::Judged,
                        output: None,
                        localized: Vec::new(),
                        localization_gaps: Vec::new(),
                    },
                ),
            ],
        )
        .expect_err("must reject");
        assert_eq!(err, FoldError::StepExitedWithoutEntry { seq: 2 });
    }

    #[test]
    fn step_record_fields_are_harvested_from_the_carrier_events() {
        let step_path: RunPath = vec![PathFrame::Step {
            step_id: StepId::new("login").expect("valid step id"),
        }];
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    step_path.clone(),
                    RunLogPayload::StepEntered {
                        step_id: StepId::new("login").expect("valid step id"),
                        effect_hash: hash('c'),
                        judge_hash: hash('d'),
                        resolved_inputs: json!({"element": {"identifier": "loginButton"}}),
                    },
                ),
                event(
                    3,
                    step_path.clone(),
                    RunLogPayload::StepExited {
                        provider_state_summary: None,
                        state: StepState::Judged,
                        output: Some(json!({"ok": true})),
                        localized: Vec::new(),
                        localization_gaps: Vec::new(),
                    },
                ),
            ],
        )
        .expect("fold");
        let record = &folded.view.completed[0];
        assert_eq!(record.effect_hash, hash('c'));
        assert_eq!(record.judge_hash, hash('d'));
        assert_eq!(
            record.resolved_inputs,
            json!({"element": {"identifier": "loginButton"}})
        );
        assert_eq!(record.output, Some(json!({"ok": true})));
    }

    #[test]
    fn popping_the_root_frame_is_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(2, vec![], RunLogPayload::CallFramePopped { outputs: None }),
            ],
        )
        .expect_err("must reject");
        assert_eq!(err, FoldError::PoppedRootFrame { seq: 2 });
    }

    #[test]
    fn unpaired_human_response_is_rejected() {
        let err = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    vec![],
                    RunLogPayload::HumanResponded {
                        request_id: "req-ghost".to_owned(),
                        purpose: pointlock_ir::HumanPurpose::Step,
                        response: json!({}),
                        actor: "cli:tester".to_owned(),
                    },
                ),
            ],
        )
        .expect_err("must reject");
        assert_eq!(
            err,
            FoldError::UnpairedHumanResponse {
                seq: 2,
                request_id: "req-ghost".to_owned()
            }
        );
    }

    fn human_requested(request_id: &str, purpose: HumanPurpose) -> RunLogPayload {
        RunLogPayload::HumanRequested {
            request_id: request_id.to_owned(),
            purpose,
            mode: match purpose {
                HumanPurpose::Step => Some(pointlock_ir::HumanMode::Confirm),
                HumanPurpose::Supervision => None,
            },
            prompt: "Decide".to_owned(),
            presents: json!([]),
            decisions: None,
            output_schema: None,
            deadline_at_ms: match purpose {
                HumanPurpose::Step => Some(9_000),
                HumanPurpose::Supervision => None,
            },
        }
    }

    fn step_entered(id: &str) -> RunLogPayload {
        RunLogPayload::StepEntered {
            step_id: StepId::new(id).expect("valid step id"),
            effect_hash: hash('c'),
            judge_hash: hash('d'),
            resolved_inputs: json!({}),
        }
    }

    fn step_exited() -> RunLogPayload {
        RunLogPayload::StepExited {
            provider_state_summary: None,
            state: StepState::Judged,
            output: None,
            localized: Vec::new(),
            localization_gaps: Vec::new(),
        }
    }

    fn run_suspended() -> RunLogPayload {
        RunLogPayload::RunSuspended {
            reason: None,
            provider_state_summary: None,
        }
    }

    /// A crash-opened span whose step the repaired IR no longer reaches
    /// (renamed `x` -> `x2`) is never re-entered and never closed. The
    /// container's exit must pair with the CONTAINER's entry, not with
    /// whatever is on top of the in-flight stack — otherwise the orphan
    /// takes the container's state/output and the container never gets a
    /// record (so it re-executes on every later resume).
    #[test]
    fn a_container_exit_pairs_with_its_own_entry_over_an_orphaned_open_span() {
        let flow = PathFrame::Flow {
            flow_id: FlowId::new("checkout").expect("valid flow id"),
            ir_hash: hash('a'),
        };
        let step = |id: &str| PathFrame::Step {
            step_id: StepId::new(id).expect("valid step id"),
        };
        let container: RunPath = vec![flow.clone(), step("each")];
        let iteration = PathFrame::Iteration {
            index: 0,
            key: None,
        };
        let orphan: RunPath = vec![flow.clone(), step("each"), iteration.clone(), step("x")];
        let renamed: RunPath = vec![flow, step("each"), iteration, step("x2")];
        let events = [
            event(1, vec![], run_started()),
            // Crashed segment: container entered, body step x entered.
            event(2, container.clone(), step_entered("each")),
            event(3, orphan.clone(), step_entered("x")),
            // Resume under the repaired IR: `each` re-entered (its span
            // is consumed, no new stepEntered), x2 runs, `each` exits.
            event(4, renamed.clone(), step_entered("x2")),
            event(5, renamed.clone(), step_exited()),
            event(
                6,
                container.clone(),
                RunLogPayload::StepExited {
                    provider_state_summary: None,
                    state: StepState::Judged,
                    output: Some(json!({"count": 1})),
                    localized: Vec::new(),
                    localization_gaps: Vec::new(),
                },
            ),
        ];
        let folded = fold_checkpoint(&meta(), &events).expect("fold");
        let completed: Vec<(&str, &RunPath)> = folded
            .view
            .completed
            .iter()
            .map(|record| (record.step_id.as_str(), &record.run_path))
            .collect();
        assert_eq!(completed, vec![("x2", &renamed), ("each", &container)]);
        assert_eq!(
            folded.view.completed[1].output,
            Some(json!({"count": 1})),
            "the container's exit output lands on the container's record"
        );
        // The orphan is still open — nothing closed it.
        let state = fold_state(&meta(), &events).expect("fold state");
        assert_eq!(state.in_flight.len(), 1);
        assert_eq!(state.in_flight[0].run_path, orphan);
    }

    /// An escalate hook's human is anchored UNDER the host step and
    /// settled in memory on lazy timeout — the only ledger trace is the
    /// host's exit. That exit must clear the request (06 §5.3), or a
    /// later suspension folds `awaitingHuman` for a dead request.
    #[test]
    fn a_host_step_exit_settles_the_hook_human_anchored_beneath_it() {
        let host: RunPath = vec![
            PathFrame::Flow {
                flow_id: FlowId::new("checkout").expect("valid flow id"),
                ir_hash: hash('a'),
            },
            PathFrame::Step {
                step_id: StepId::new("pay").expect("valid step id"),
            },
        ];
        let mut hook_human = host.clone();
        hook_human.push(PathFrame::Hook {
            hook: pointlock_ir::HandlerHook::OnFail,
            trigger: 1,
        });
        hook_human.push(PathFrame::Step {
            step_id: StepId::new("ask").expect("valid step id"),
        });
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(2, host.clone(), step_entered("pay")),
                event(3, hook_human, human_requested("req-1", HumanPurpose::Step)),
                event(4, host, step_exited()),
                event(5, vec![], run_suspended()),
            ],
        )
        .expect("fold");
        assert!(folded.view.human_pending.is_none());
        assert_eq!(folded.status, RunStatus::Suspended);
    }

    /// A cross-IR resume exits the awaiting step at a path carrying the
    /// NEW flow hash; the request was recorded under the old one. Site
    /// identity, not hash identity, settles it.
    #[test]
    fn an_exit_under_the_new_ir_hash_settles_the_old_hash_request() {
        let path = |fill: char| -> RunPath {
            vec![
                PathFrame::Flow {
                    flow_id: FlowId::new("checkout").expect("valid flow id"),
                    ir_hash: hash(fill),
                },
                PathFrame::Step {
                    step_id: StepId::new("ask").expect("valid step id"),
                },
            ]
        };
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(2, path('a'), step_entered("ask")),
                event(3, path('a'), human_requested("req-1", HumanPurpose::Step)),
                event(4, path('e'), step_exited()),
            ],
        )
        .expect("fold");
        assert!(folded.view.human_pending.is_none());
    }

    #[test]
    fn supervision_suspend_answer_keeps_the_request_pending() {
        let step_path: RunPath = vec![PathFrame::Step {
            step_id: StepId::new("pay").expect("valid step id"),
        }];
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    step_path.clone(),
                    human_requested("req-1", HumanPurpose::Supervision),
                ),
                event(
                    3,
                    step_path.clone(),
                    RunLogPayload::HumanResponded {
                        request_id: "req-1".to_owned(),
                        purpose: HumanPurpose::Supervision,
                        response: json!({"decision": "suspend"}),
                        actor: "cli:tester".to_owned(),
                    },
                ),
                // The suspend ruling parks the run; the request survives.
                event(
                    4,
                    vec![],
                    RunLogPayload::RunSuspended {
                        provider_state_summary: None,
                        reason: None,
                    },
                ),
            ],
        )
        .expect("fold");
        let pending = folded.view.human_pending.expect("request stays pending");
        assert_eq!(pending.request_id, "req-1");
        assert_eq!(folded.status, RunStatus::AwaitingHuman);

        // A later final ruling still pairs and settles the wait.
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    step_path.clone(),
                    human_requested("req-1", HumanPurpose::Supervision),
                ),
                event(
                    3,
                    step_path.clone(),
                    RunLogPayload::HumanResponded {
                        request_id: "req-1".to_owned(),
                        purpose: HumanPurpose::Supervision,
                        response: json!({"decision": "suspend"}),
                        actor: "cli:tester".to_owned(),
                    },
                ),
                event(
                    4,
                    step_path,
                    RunLogPayload::HumanResponded {
                        request_id: "req-1".to_owned(),
                        purpose: HumanPurpose::Supervision,
                        response: json!({"decision": "proceed"}),
                        actor: "cli:tester".to_owned(),
                    },
                ),
            ],
        )
        .expect("fold");
        assert!(folded.view.human_pending.is_none());
        assert_eq!(folded.status, RunStatus::Running);
    }

    #[test]
    fn run_suspended_while_a_request_is_pending_stays_awaiting_human() {
        let step_path: RunPath = vec![PathFrame::Step {
            step_id: StepId::new("ask").expect("valid step id"),
        }];
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(2, step_path, human_requested("req-2", HumanPurpose::Step)),
                event(
                    3,
                    vec![],
                    RunLogPayload::RunSuspended {
                        provider_state_summary: None,
                        reason: None,
                    },
                ),
            ],
        )
        .expect("fold");
        assert_eq!(folded.status, RunStatus::AwaitingHuman);
        let pending = folded.view.human_pending.expect("pending");
        assert_eq!(pending.deadline_at_ms, Some(9_000));
        assert_eq!(pending.mode, Some(pointlock_ir::HumanMode::Confirm));
    }

    #[test]
    fn step_exit_settles_the_pending_request_without_a_response() {
        // The lazy timeout settlement shape: the awaiting step exits
        // (verdict unknown) with no humanResponded on the ledger.
        let step_path: RunPath = vec![PathFrame::Step {
            step_id: StepId::new("ask").expect("valid step id"),
        }];
        let folded = fold_checkpoint(
            &meta(),
            &[
                event(1, vec![], run_started()),
                event(
                    2,
                    step_path.clone(),
                    RunLogPayload::StepEntered {
                        step_id: StepId::new("ask").expect("valid step id"),
                        effect_hash: hash('c'),
                        judge_hash: hash('d'),
                        resolved_inputs: json!({"presents": []}),
                    },
                ),
                event(
                    3,
                    step_path.clone(),
                    human_requested("req-3", HumanPurpose::Step),
                ),
                event(
                    4,
                    vec![],
                    RunLogPayload::RunSuspended {
                        provider_state_summary: None,
                        reason: None,
                    },
                ),
                event(
                    5,
                    vec![],
                    RunLogPayload::RunResumed {
                        alignment_report: pointlock_ir::AlignmentReport {
                            entries: vec![],
                            resume_point: None,
                            requires_confirmation: vec![],
                        },
                        supervise_policy: None,
                        event_cursor: None,
                    },
                ),
                event(
                    6,
                    step_path,
                    RunLogPayload::StepExited {
                        provider_state_summary: None,
                        state: StepState::Judged,
                        output: None,
                        localized: Vec::new(),
                        localization_gaps: Vec::new(),
                    },
                ),
            ],
        )
        .expect("fold");
        assert!(folded.view.human_pending.is_none());
        assert_eq!(folded.status, RunStatus::Running);
    }

    #[test]
    fn error_class_is_adopted_only_when_the_code_spells_a_class() {
        assert_eq!(
            parse_error_class("action_failed_final"),
            Some(ErrorClass::ActionFailedFinal)
        );
        assert_eq!(parse_error_class("SOME_DAEMON_CODE"), None);
    }
}