pointlock_ir/record.rs
1//! Durable execution records and the checkpoint materialization view.
2//!
3//! Definition home adjudicated to `pointlock-ir` (type truth source, R12) so
4//! `pointlock-store` and `pointlock-runner` share one shape without violating
5//! the dependency direction; pending spine batch incorporation.
6//!
7//! Shapes follow spine §6.6 (`CheckpointView`/`StepRecord`), §6.7-A
8//! (`AlignmentReport`), and 07 §3.2 (`CallFrame` refinement,
9//! `humanPending.purpose`).
10
11use std::collections::BTreeMap;
12
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17use crate::primitives::{ActionName, AssertId, FlowId, Hash, StepId};
18use crate::run_path::RunPath;
19use crate::runtime::{EvidenceRef, StepVerdict, Viewport};
20use crate::vocab::{
21 ActChannel, AlignmentClass, Channel, CoordinateFallbackReason, ErrorClass, ExecutionMode,
22 HumanMode, HumanPurpose, ScreenshotOmissionReason, StepState, UiSnapshotOmissionReason,
23 VerdictStatus,
24};
25
26/// Discriminant-only projection of an `ActionOutcome` for durable attempt
27/// records (the full outcome lives in the RunLog `actionSettled` payload).
28/// Pending incorporation.
29#[derive(
30 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
31)]
32#[serde(rename_all = "camelCase")]
33pub enum ActionOutcomeKind {
34 /// Completed with a result.
35 Succeeded,
36 /// Failed with a structured error.
37 Failed,
38 /// Cooperatively cancelled.
39 Cancelled,
40 /// Action budget elapsed.
41 TimedOut,
42}
43
44/// One attempt of an action step (spine §6.6): every dispatch, successful
45/// or not, leaves one record keyed by its WAL callId.
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
47#[serde(rename_all = "camelCase", deny_unknown_fields)]
48pub struct AttemptRecord {
49 /// The caller-generated action id (matches the `actionIntent` WAL entry).
50 pub call_id: String,
51 /// Four-way terminal discriminant.
52 pub outcome: ActionOutcomeKind,
53 /// Runner-side error classification, for non-succeeded outcomes.
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub error_class: Option<ErrorClass>,
56 /// The execution mode the provider reported.
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub execution_mode: Option<ExecutionMode>,
59 /// Fallback reason when `executionMode` is `coordinateFallback`.
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub fallback_reason: Option<CoordinateFallbackReason>,
62 /// 1-based `binding.attempts` position of the dispatch (2026-07-18
63 /// incorporation, item ② — carried from the `actionIntent` event;
64 /// absent on pre-incorporation ledgers).
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub chain_index: Option<u32>,
67 /// The dispatched attempt's locating channel.
68 #[serde(skip_serializing_if = "Option::is_none")]
69 pub channel: Option<ActChannel>,
70 /// The dispatched attempt's provider-native action name.
71 #[serde(skip_serializing_if = "Option::is_none")]
72 pub action_name: Option<ActionName>,
73}
74
75/// The provider-side session profile captured at a failure or suspension
76/// instant (07 §2.2, incorporated 2026-07-18): pure forensic material for
77/// the dossier/overview — resume reconcile, the fold's binding provenance
78/// and alignment never consume it. Rides `stepExited` (fail/unknown
79/// verdict in force at exit) and `runSuspended` as an additive optional
80/// payload field; absent on ledgers recorded before incorporation.
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
82#[serde(rename_all = "camelCase", deny_unknown_fields)]
83pub struct ProviderStateSummary {
84 /// Known session generations, best-effort: the checkpoint-known
85 /// lineage plus the live session observed at capture.
86 pub session_lineage: Vec<String>,
87 /// The capture-instant cursor (`currentCursor()` RPC). Absent when
88 /// the call failed — never a stale bind-time value (principle 4).
89 #[serde(skip_serializing_if = "Option::is_none")]
90 pub event_cursor: Option<EventCursor>,
91 /// The attested capability baseline at capture.
92 pub attestation: AttestationSnapshot,
93 /// `ProviderSession::health()` at capture; a failed call records
94 /// `{ ok: false, degraded: "<errorClass>" }`.
95 pub health: SessionHealthSnapshot,
96 /// The bound device.
97 pub device_id: String,
98 /// `lockfile.device.platform`; absent when the assembly layer did
99 /// not supply it (the SPI attestation does not carry it).
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub platform: Option<String>,
102}
103
104/// The two attestation facts 07 §2.2 pins into the summary (deliberately
105/// not the full `CapabilityAttestation`).
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
107#[serde(rename_all = "camelCase", deny_unknown_fields)]
108pub struct AttestationSnapshot {
109 /// Digest of the attested lockfile.
110 pub lockfile_digest: Hash,
111 /// Attestation timestamp, verbatim.
112 pub attested_at: String,
113}
114
115/// Wire twin of the provider-kit `SessionHealth` (defined here because
116/// provider-kit depends on ir, not vice versa).
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
118#[serde(rename_all = "camelCase", deny_unknown_fields)]
119pub struct SessionHealthSnapshot {
120 /// Whether the session answered healthy.
121 pub ok: bool,
122 /// Degradation note (an error class when the health call failed).
123 #[serde(skip_serializing_if = "Option::is_none")]
124 pub degraded: Option<String>,
125}
126
127/// A localized observation record (spine §6.6; omissions are typed data).
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
129#[serde(rename_all = "camelCase", deny_unknown_fields)]
130pub struct ObservationRecord {
131 /// Provider-scoped observation id.
132 pub observation_id: String,
133 /// Capture timestamp (ms since epoch).
134 pub captured_at_ms: u64,
135 /// The capture-time viewport, verbatim from the provider observation
136 /// (M3a additive close of the registered W1 gap; absent on ledgers
137 /// recorded before the field existed, or when the provider reported
138 /// a non-finite scale factor — the runner refuses to persist a value
139 /// serde_json would write as `null` and never read back).
140 ///
141 /// Compat note: the additive claim is one-directional — readers
142 /// built before this field existed reject ledgers containing it
143 /// (`deny_unknown_fields`, fail-closed per R12); binary downgrade
144 /// against a store written by a newer runner is unsupported.
145 #[serde(skip_serializing_if = "Option::is_none")]
146 pub viewport: Option<Viewport>,
147 /// Localized screenshot evidence, when captured.
148 #[serde(skip_serializing_if = "Option::is_none")]
149 pub screenshot: Option<EvidenceRef>,
150 /// Why the screenshot was legitimately omitted.
151 #[serde(skip_serializing_if = "Option::is_none")]
152 pub screenshot_omission: Option<ScreenshotOmissionReason>,
153 /// Localized UI-tree evidence, when captured.
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub ui_snapshot: Option<EvidenceRef>,
156 /// Why the UI snapshot was legitimately omitted.
157 #[serde(skip_serializing_if = "Option::is_none")]
158 pub ui_snapshot_omission: Option<UiSnapshotOmissionReason>,
159}
160
161/// Outcome of one assertion evaluation along its verify chain (spine §6.6).
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
163#[serde(rename_all = "camelCase", deny_unknown_fields)]
164pub struct AssertionOutcomeRecord {
165 /// The assertion's id.
166 pub assert_id: AssertId,
167 /// Three-valued result (a chain that ran dry is `unknown`, never `fail`).
168 pub result: VerdictStatus,
169 /// The channel that completed the evaluation, when one did.
170 #[serde(skip_serializing_if = "Option::is_none")]
171 pub channel: Option<Channel>,
172 /// Human-readable evaluation reason.
173 pub reason: String,
174}
175
176/// The durable record of one completed step (spine §6.6).
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
178#[serde(rename_all = "camelCase", deny_unknown_fields)]
179pub struct StepRecord {
180 /// Full run path of this step instance.
181 pub run_path: RunPath,
182 /// The step's stable id.
183 pub step_id: StepId,
184 /// Effect-domain hash at execution time (alignment input).
185 pub effect_hash: Hash,
186 /// Judge-domain hash at execution time (alignment input).
187 pub judge_hash: Hash,
188 /// Every dispatch attempt, in order.
189 pub attempts: Vec<AttemptRecord>,
190 /// Input expressions evaluated once at `ready` and snapshotted;
191 /// never re-evaluated on resume.
192 pub resolved_inputs: Value,
193 /// Projected step output, when the step declares outputs.
194 #[serde(skip_serializing_if = "Option::is_none")]
195 pub output: Option<Value>,
196 /// Localized observations.
197 pub observations: Vec<ObservationRecord>,
198 /// Localized evidence (content-addressed).
199 pub evidence: Vec<EvidenceRef>,
200 /// Assertion outcomes, in declaration order.
201 pub assertion_outcomes: Vec<AssertionOutcomeRecord>,
202 /// The folded verdict projection, absent for unasserted mutations (R4).
203 #[serde(skip_serializing_if = "Option::is_none")]
204 pub verdict: Option<StepVerdict>,
205}
206
207/// One live `foreach` iteration inside a call frame (07 §3.2).
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "camelCase", deny_unknown_fields)]
210pub struct IterState {
211 /// The iteration variable name (`foreach ... as`).
212 #[serde(rename = "as")]
213 pub var: String,
214 /// Zero-based index of the current item.
215 pub index: u64,
216 /// Optional stable item key (keyed foreach is reserved, v0.2).
217 #[serde(skip_serializing_if = "Option::is_none")]
218 pub key: Option<String>,
219}
220
221/// One frame of the live call stack (07 §3.2 refinement; `frames[0]` is the
222/// root flow frame). Pending spine incorporation of the refined fields.
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
224#[serde(rename_all = "camelCase", deny_unknown_fields)]
225pub struct CallFrame {
226 /// The flow executing in this frame.
227 pub flow_id: FlowId,
228 /// Content hash of that flow's IR.
229 pub ir_hash: Hash,
230 /// The host call step's id; absent for the root frame and for
231 /// handler-repair launched frames (spine §9).
232 #[serde(skip_serializing_if = "Option::is_none")]
233 pub call_step_id: Option<StepId>,
234 /// Call-by-value input snapshot taken when the frame was pushed;
235 /// never updated from a newer IR (07 §5.2).
236 pub inputs_snapshot: Value,
237 /// `let` bindings materialized in this frame (SSA, single assignment).
238 pub vars: BTreeMap<String, Value>,
239 /// Live `foreach` iterations, innermost last.
240 pub iter_stack: Vec<IterState>,
241 /// Index of the next body step to schedule in this frame.
242 pub next_index: u64,
243}
244
245/// The WAL'd intent of a dispatched-but-unsettled action (spine §6.6).
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
247#[serde(rename_all = "camelCase", deny_unknown_fields)]
248pub struct PendingIntent {
249 /// The caller-generated action id to reconcile against.
250 pub call_id: String,
251 /// The evaluated arguments as dispatched.
252 pub args_snapshot: Value,
253}
254
255/// The execution frontier: the single in-flight step (spine §6.6).
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
257#[serde(rename_all = "camelCase", deny_unknown_fields)]
258pub struct Frontier {
259 /// Run path of the in-flight step.
260 pub run_path: RunPath,
261 /// Its lifecycle state at materialization time.
262 pub state: StepState,
263 /// The hanging action intent, when crash-vulnerable work was in flight.
264 #[serde(skip_serializing_if = "Option::is_none")]
265 pub pending_intent: Option<PendingIntent>,
266}
267
268/// A pending human interaction (spine §6.6 + R13 purpose discriminator;
269/// 06 §8-Q4 adopted — `mode`/`deadlineAtMs` are carried so lazy timeout
270/// settlement needs no event-stream re-read).
271#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
272#[serde(rename_all = "camelCase", deny_unknown_fields)]
273pub struct HumanPending {
274 /// Run path of the awaiting step (or gated step for supervision).
275 pub run_path: RunPath,
276 /// The request id the response must pair with.
277 pub request_id: String,
278 /// Why the interaction exists (step vs supervision gate).
279 pub purpose: HumanPurpose,
280 /// Interaction mode of a `purpose="step"` request; absent for
281 /// supervision gates (06 §2.1).
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub mode: Option<HumanMode>,
284 /// The prompt shown to the human (auto-generated gate description for
285 /// supervision requests).
286 pub prompt: String,
287 /// Absolute response deadline (ms since epoch); absent for supervision
288 /// requests, which have no deadline (spine §6.9).
289 #[serde(skip_serializing_if = "Option::is_none")]
290 pub deadline_at_ms: Option<u64>,
291}
292
293/// Event-log cursor of the bound provider session (spine §6.6; advanced
294/// ack-after-persist, never across session generations).
295#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
296#[serde(rename_all = "camelCase", deny_unknown_fields)]
297pub struct EventCursor {
298 /// The provider session that issued the recorded events.
299 pub session_id: String,
300 /// Last sequence durably consumed from that session.
301 pub last_sequence: u64,
302}
303
304/// The run's provider binding state (spine §6.6).
305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
306#[serde(rename_all = "camelCase", deny_unknown_fields)]
307pub struct BindingState {
308 /// The bound device.
309 pub device_id: String,
310 /// Every provider session generation of this run, oldest first.
311 pub session_lineage: Vec<String>,
312 /// Cursor into the issuing session's event log.
313 pub event_cursor: EventCursor,
314}
315
316/// The deterministic materialized view of a RunLog at a safe point
317/// (spine §6.6); always reconstructible by folding the log.
318#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
319#[serde(rename_all = "camelCase", deny_unknown_fields)]
320pub struct CheckpointView {
321 /// The run this view materializes.
322 pub run_id: String,
323 /// Content hash of the executing IR.
324 pub ir_hash: Hash,
325 /// Digest of the capability lockfile the IR was bound against.
326 pub lockfile_digest: Hash,
327 /// The run's input parameters, snapshotted at start.
328 pub params_snapshot: Value,
329 /// Provider binding state.
330 pub binding: BindingState,
331 /// Records of all completed steps, in completion order.
332 pub completed: Vec<StepRecord>,
333 /// The live call stack; `frames[0]` is the root flow frame.
334 pub frames: Vec<CallFrame>,
335 /// The single in-flight step.
336 pub frontier: Frontier,
337 /// The pending human interaction, when suspended on one.
338 #[serde(skip_serializing_if = "Option::is_none")]
339 pub human_pending: Option<HumanPending>,
340}
341
342/// One aligned step in a resume alignment report (spine §6.7-A).
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
344#[serde(rename_all = "camelCase", deny_unknown_fields)]
345pub struct AlignmentEntry {
346 /// Which instance was classified (07 §5.2: the report entry is
347 /// path-addressed).
348 ///
349 /// A step id alone is ambiguous the moment a run nests: the same id
350 /// recurs once per `foreach` round and once per call of a callee, so
351 /// two entries could name the same step and mean different instances.
352 /// The path says which one — and it is the same address
353 /// `requiresConfirmation` already uses, so the two halves of the
354 /// report finally speak one vocabulary.
355 pub run_path: RunPath,
356 /// The step being classified. Kept alongside the path: it is what a
357 /// reader recognizes, and what `--allow-mutating-reexec` names.
358 pub step_id: StepId,
359 /// Its alignment class.
360 pub class: AlignmentClass,
361 /// Sub-domain annotation, e.g. `preflightChanged` (02 §12.3 ruling 6).
362 #[serde(skip_serializing_if = "Option::is_none")]
363 pub reason: Option<String>,
364}
365
366/// A step whose re-execution needs explicit human authorization
367/// (07 §5.2/§5.4 unified gate).
368#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
369#[serde(rename_all = "camelCase", deny_unknown_fields)]
370pub struct RequiresConfirmation {
371 /// Run path of the gated step.
372 pub run_path: RunPath,
373 /// The step id `--allow-mutating-reexec` takes for this gate (07 §5.4
374 /// step 2: authorization names steps one by one, never a wildcard).
375 ///
376 /// Without it a reader has to re-derive the id from the path — which is
377 /// exactly what the CLI did, and what every other consumer would have
378 /// had to reimplement. Additive optional field (spine §6.1 R12): absent
379 /// on pre-incorporation ledgers, where consumers fall back to the path.
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 pub step_id: Option<StepId>,
382 /// Gate cause. Known values: `mutatingReexec`, `positionalReplay`,
383 /// `orderInvalidated`, `frontierUnknown` (07 §5.4); closed-set
384 /// incorporation pending.
385 pub cause: String,
386 /// Human-readable explanation.
387 pub reason: String,
388}
389
390/// The alignment report a resume records in `runResumed` (spine §6.7-A).
391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
392#[serde(rename_all = "camelCase", deny_unknown_fields)]
393pub struct AlignmentReport {
394 /// Per-step classifications, in new-IR order.
395 pub entries: Vec<AlignmentEntry>,
396 /// The computed resume point, absent when the run cannot resume.
397 #[serde(skip_serializing_if = "Option::is_none")]
398 pub resume_point: Option<RunPath>,
399 /// Steps requiring explicit re-execution authorization.
400 pub requires_confirmation: Vec<RequiresConfirmation>,
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use serde_json::json;
407
408 #[test]
409 fn iter_state_uses_the_as_keyword_on_the_wire() {
410 let iter = IterState {
411 var: "item".to_owned(),
412 index: 2,
413 key: None,
414 };
415 let wire = serde_json::to_value(&iter).expect("serialize");
416 assert_eq!(wire, json!({"as": "item", "index": 2}));
417 }
418
419 #[test]
420 fn checkpoint_view_round_trips_with_absent_optionals() {
421 let view = CheckpointView {
422 run_id: "run-1".to_owned(),
423 ir_hash: serde_json::from_value(json!(format!("sha256:{}", "a".repeat(64))))
424 .expect("hash"),
425 lockfile_digest: serde_json::from_value(json!(format!("sha256:{}", "b".repeat(64))))
426 .expect("hash"),
427 params_snapshot: json!({"user": "alice"}),
428 binding: BindingState {
429 device_id: "dev-1".to_owned(),
430 session_lineage: vec!["s-1".to_owned()],
431 event_cursor: EventCursor {
432 session_id: "s-1".to_owned(),
433 last_sequence: 42,
434 },
435 },
436 completed: vec![],
437 frames: vec![CallFrame {
438 flow_id: serde_json::from_value(json!("checkout")).expect("flow id"),
439 ir_hash: serde_json::from_value(json!(format!("sha256:{}", "a".repeat(64))))
440 .expect("hash"),
441 call_step_id: None,
442 inputs_snapshot: json!({}),
443 vars: BTreeMap::new(),
444 iter_stack: vec![],
445 next_index: 3,
446 }],
447 frontier: Frontier {
448 run_path: vec![],
449 state: StepState::Acting,
450 pending_intent: Some(PendingIntent {
451 call_id: "c-1".to_owned(),
452 args_snapshot: json!({"x": 1}),
453 }),
454 },
455 human_pending: None,
456 };
457 let wire = serde_json::to_value(&view).expect("serialize");
458 assert_eq!(wire["frontier"]["state"], "acting");
459 assert_eq!(wire["binding"]["eventCursor"]["lastSequence"], 42);
460 assert!(wire.get("humanPending").is_none());
461 assert!(wire["frames"][0].get("callStepId").is_none());
462 let back: CheckpointView = serde_json::from_value(wire).expect("deserialize");
463 assert_eq!(back, view);
464 }
465
466 #[test]
467 fn human_pending_purpose_discriminates_supervision() {
468 // Supervision requests carry no mode and no deadline (spine §6.9):
469 // both optionals are absent on the wire, never null.
470 let pending = HumanPending {
471 run_path: vec![],
472 request_id: "req-1".to_owned(),
473 purpose: HumanPurpose::Supervision,
474 mode: None,
475 prompt: "Approve mutating dispatch of tapPay".to_owned(),
476 deadline_at_ms: None,
477 };
478 let wire = serde_json::to_value(&pending).expect("serialize");
479 assert_eq!(wire["purpose"], "supervision");
480 let object = wire.as_object().expect("object");
481 assert!(!object.contains_key("mode"));
482 assert!(!object.contains_key("deadlineAtMs"));
483 let back: HumanPending = serde_json::from_value(wire).expect("deserialize");
484 assert_eq!(back, pending);
485 }
486
487 #[test]
488 fn human_pending_step_purpose_carries_mode_and_deadline() {
489 // 06 §8-Q4 adopted: a step-purpose pending request carries its
490 // mode and absolute deadline for lazy settlement.
491 let pending = HumanPending {
492 run_path: vec![],
493 request_id: "req-2".to_owned(),
494 purpose: HumanPurpose::Step,
495 mode: Some(crate::vocab::HumanMode::Confirm),
496 prompt: "Confirm the transfer".to_owned(),
497 deadline_at_ms: Some(1_700_000_600_000),
498 };
499 let wire = serde_json::to_value(&pending).expect("serialize");
500 assert_eq!(wire["mode"], "confirm");
501 assert_eq!(
502 wire["deadlineAtMs"],
503 serde_json::json!(1_700_000_600_000_u64)
504 );
505 let back: HumanPending = serde_json::from_value(wire).expect("deserialize");
506 assert_eq!(back, pending);
507 }
508}