openadapt-kernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ """Wire and DOM-effect commit interceptor.
2
+
3
+ Detects state mutations from actual network methods (POST, PUT, PATCH, DELETE)
4
+ or non-empty dirty form submissions instead of button-label regex heuristics.
5
+ Excludes search/filter inputs from dirty buffers and escapes escalation actions
6
+ so nested quotes never break downstream action parsers.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import time
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Dict, List, Literal, Optional, Sequence, Set
16
+ from urllib.parse import urlparse
17
+
18
+ MUTATING_HTTP_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
19
+
20
+ _SEARCH_FILTER_RE = re.compile(
21
+ r"(?:^|[\s_-])(?:search|searchbox|search[\s_-]query|filter|keyword|pagination|page[\s_-]?size|sort[\s_-]?by|order[\s_-]?by)(?:$|[\s_-])",
22
+ re.IGNORECASE,
23
+ )
24
+ _TELEMETRY_HOSTS = frozenset({
25
+ "google-analytics.com", "analytics.google.com", "posthog.com",
26
+ "segment.io", "segment.com", "sentry.io", "mixpanel.com", "plausible.io",
27
+ })
28
+ _TELEMETRY_PATH_RE = re.compile(
29
+ r"/(?:analytics|telemetry|metrics|beacon|sentry|posthog|_next/data)(?:/|$)", re.IGNORECASE
30
+ )
31
+
32
+
33
+ def _is_telemetry_url(url: str) -> bool:
34
+ parsed = urlparse(url or "")
35
+ host = (parsed.hostname or "").lower()
36
+ if any(host == th or host.endswith(f".{th}") for th in _TELEMETRY_HOSTS):
37
+ return True
38
+ return bool(_TELEMETRY_PATH_RE.search(parsed.path or ""))
39
+
40
+
41
+ def _url_matches_origin(url: str, target_origin: str) -> bool:
42
+ if not target_origin:
43
+ return True
44
+ up = urlparse(url or "")
45
+ tp = urlparse(target_origin)
46
+ if not up.scheme or not up.netloc or not tp.scheme or not tp.netloc:
47
+ return False
48
+ if tp.port is not None:
49
+ return up.scheme.lower() == tp.scheme.lower() and up.netloc.lower() == tp.netloc.lower()
50
+ return up.scheme.lower() == tp.scheme.lower() and (up.hostname or "").lower() == (tp.hostname or "").lower()
51
+
52
+
53
+ @dataclass
54
+ class NetworkEvent:
55
+ method: str
56
+ url: str
57
+ status: Optional[int] = None
58
+ resource_type: str = "fetch"
59
+ post_data_preview: str = ""
60
+
61
+
62
+ @dataclass
63
+ class CommitClassification:
64
+ is_commit: bool
65
+ kind: Literal["read_only_nav", "http_mutation", "form_submit", "file_upload"]
66
+ reason: str
67
+ mutating_events: List[NetworkEvent] = field(default_factory=list)
68
+
69
+
70
+ def is_search_or_filter_field(
71
+ field_id: str,
72
+ input_type: str = "",
73
+ aria_role: str = "",
74
+ label: str = "",
75
+ ) -> bool:
76
+ if input_type.strip().lower() == "search" or aria_role.strip().lower() == "searchbox":
77
+ return True
78
+ combined = f"{field_id} {label}"
79
+ return bool(_SEARCH_FILTER_RE.search(combined))
80
+
81
+
82
+ def sanitize_action_string(prefix: str, message: str, max_len: int = 240) -> str:
83
+ """Format a safe single-line escalation payload with no unescaped quote hazards."""
84
+ compact = re.sub(r"\s+", " ", str(message or "")).strip()[:max_len]
85
+ safe_payload = json.dumps(f"{prefix} {compact}".strip())
86
+ return safe_payload
87
+
88
+
89
+ class CommitInterceptor:
90
+ """Observes form edits and wire events to separate navigation from commits."""
91
+
92
+ def __init__(self, ignored_url_patterns: Sequence[str] = ()) -> None:
93
+ self._dirty_fields: Dict[str, str] = {}
94
+ self._pending_events: List[NetworkEvent] = []
95
+ self._ignored_res = [re.compile(p, re.IGNORECASE) for p in ignored_url_patterns]
96
+ self._attached_pages: List[Any] = []
97
+ self._inflight_mutating: Set[int] = set()
98
+
99
+ @property
100
+ def dirty_fields(self) -> Dict[str, str]:
101
+ return dict(self._dirty_fields)
102
+
103
+ def mark_field_edited(
104
+ self,
105
+ field_id: str,
106
+ value: str,
107
+ *,
108
+ input_type: str = "",
109
+ aria_role: str = "",
110
+ label: str = "",
111
+ ) -> bool:
112
+ """Record a form mutation unless the field is a search/filter control."""
113
+ if is_search_or_filter_field(field_id, input_type=input_type, aria_role=aria_role, label=label):
114
+ return False
115
+ self._dirty_fields[field_id] = value
116
+ return True
117
+
118
+ def clear_dirty_fields(self, field_ids: Optional[Sequence[str]] = None) -> None:
119
+ if field_ids is None:
120
+ self._dirty_fields.clear()
121
+ return
122
+ for fid in field_ids:
123
+ self._dirty_fields.pop(fid, None)
124
+
125
+ def begin_step(self) -> None:
126
+ self._pending_events.clear()
127
+ self._inflight_mutating.clear()
128
+
129
+ def record_network_event(self, event: NetworkEvent) -> None:
130
+ self._pending_events.append(event)
131
+
132
+ def attach_playwright_page(self, page: Any) -> None:
133
+ """Attach non-blocking Playwright request/response observers."""
134
+ if page in self._attached_pages:
135
+ return
136
+ pending_by_req: Dict[int, NetworkEvent] = {}
137
+
138
+ def _on_request(req: Any) -> None:
139
+ try:
140
+ method = str(req.method or "GET").upper()
141
+ url = str(req.url or "")
142
+ rtype = str(getattr(req, "resource_type", "") or "fetch")
143
+ preview = ""
144
+ if method in MUTATING_HTTP_METHODS:
145
+ raw = getattr(req, "post_data", None)
146
+ if isinstance(raw, str):
147
+ preview = raw[:200]
148
+ ev = NetworkEvent(method=method, url=url, resource_type=rtype, post_data_preview=preview)
149
+ pending_by_req[id(req)] = ev
150
+ self._pending_events.append(ev)
151
+ if self._is_mutating_event(ev):
152
+ self._inflight_mutating.add(id(req))
153
+ except Exception:
154
+ return
155
+
156
+ def _on_response(resp: Any) -> None:
157
+ try:
158
+ req = resp.request
159
+ self._inflight_mutating.discard(id(req))
160
+ ev = pending_by_req.get(id(req))
161
+ if ev is not None:
162
+ ev.status = int(resp.status)
163
+ except Exception:
164
+ return
165
+
166
+ def _on_request_failed(req: Any) -> None:
167
+ try:
168
+ self._inflight_mutating.discard(id(req))
169
+ except Exception:
170
+ return
171
+
172
+ page.on("request", _on_request)
173
+ page.on("response", _on_response)
174
+ page.on("requestfailed", _on_request_failed)
175
+ self._attached_pages.append(page)
176
+
177
+ def _is_mutating_event(self, ev: NetworkEvent) -> bool:
178
+ if ev.method.upper() not in MUTATING_HTTP_METHODS:
179
+ return False
180
+ if _is_telemetry_url(ev.url):
181
+ return False
182
+ if any(rx.search(ev.url) for rx in self._ignored_res):
183
+ return False
184
+ return True
185
+
186
+ def has_target_origin_2xx_mutation(self, target_origin: str = "") -> bool:
187
+ return any(
188
+ self._is_mutating_event(ev)
189
+ and _url_matches_origin(ev.url, target_origin)
190
+ and ev.status is not None
191
+ and 200 <= ev.status < 300
192
+ for ev in self._pending_events
193
+ )
194
+
195
+ def wait_for_commit_settle(
196
+ self,
197
+ page: Any,
198
+ *,
199
+ target_origin: str = "",
200
+ timeout_ms: int = 5000,
201
+ quiet_ms: int = 120,
202
+ ) -> bool:
203
+ """Wait for pending target-origin mutating requests + short DOM quiet window."""
204
+ deadline = time.monotonic() + max(timeout_ms, 50) / 1000.0
205
+ page.wait_for_timeout(40)
206
+ while time.monotonic() < deadline:
207
+ inflight = bool(self._inflight_mutating) or any(
208
+ self._is_mutating_event(ev)
209
+ and _url_matches_origin(ev.url, target_origin)
210
+ and ev.status is None
211
+ for ev in self._pending_events
212
+ )
213
+ if inflight:
214
+ page.wait_for_timeout(30)
215
+ continue
216
+ rem_ms = max(int((deadline - time.monotonic()) * 1000), 20)
217
+ try:
218
+ page.evaluate(
219
+ """([q, cap]) => new Promise((res) => {
220
+ let done = false;
221
+ const fin = (v) => { if (!done) { done = true; obs.disconnect(); res(v); } };
222
+ let t = setTimeout(() => fin(true), q);
223
+ const obs = new MutationObserver(() => { clearTimeout(t); t = setTimeout(() => fin(true), q); });
224
+ if (document.body) obs.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true });
225
+ setTimeout(() => fin(false), Math.min(cap, q * 4));
226
+ })""",
227
+ [quiet_ms, rem_ms],
228
+ )
229
+ except Exception:
230
+ page.wait_for_timeout(min(quiet_ms, rem_ms))
231
+ if not self._inflight_mutating:
232
+ return True
233
+ return False
234
+
235
+ def classify_step(
236
+ self,
237
+ *,
238
+ element_tag: str = "",
239
+ element_role: str = "",
240
+ had_file_upload: bool = False,
241
+ form_submitted: bool = False,
242
+ ) -> CommitClassification:
243
+ """Classify the step strictly by observed wire/DOM mutation effects.
244
+
245
+ Navigation links (<a>, role='link') that trigger zero mutating HTTP calls
246
+ and submit zero dirty fields never qualify as commits, preventing
247
+ destructive reloads on SPA menu clicks.
248
+ """
249
+ mutating = [ev for ev in self._pending_events if self._is_mutating_event(ev)]
250
+
251
+ if had_file_upload:
252
+ return CommitClassification(True, "file_upload", "file_upload_dispatched", mutating)
253
+ if mutating:
254
+ return CommitClassification(
255
+ True, "http_mutation", f"observed_{len(mutating)}_mutating_http_requests", mutating
256
+ )
257
+ tag_l, role_l = element_tag.strip().lower(), element_role.strip().lower()
258
+ if form_submitted and self._dirty_fields and tag_l != "a" and role_l != "link":
259
+ return CommitClassification(
260
+ True, "form_submit", f"form_submitted_with_{len(self._dirty_fields)}_dirty_fields", []
261
+ )
262
+ return CommitClassification(False, "read_only_nav", "no_wire_mutation_or_dirty_submit", [])
@@ -0,0 +1,379 @@
1
+ """Default-deny Obligation, Capability, and Saga Ledger.
2
+
3
+ Episodes begin UNVERIFIED and transition to VERIFIED only when every required
4
+ obligation has an independent post-commit read-back proof and no uncommitted
5
+ form fields remain. Timeouts, step-budget exhaustion, crashes, and unverified
6
+ exits deterministically resolve to ESCALATED.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import uuid
14
+ from dataclasses import asdict, dataclass, field
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Iterable, List, Literal, Optional, Sequence
18
+
19
+ ObligationState = Literal["PENDING", "COMMITTED", "EXEMPT", "ESCALATED"]
20
+ EpisodeOutcome = Literal[
21
+ "UNVERIFIED",
22
+ "VERIFIED",
23
+ "ESCALATED",
24
+ "HALTED",
25
+ "FAILED",
26
+ "PREPARE_REQUIRED",
27
+ "AWAITING_MICRO_HANDOFF",
28
+ ]
29
+ CapabilityKind = Literal["consent", "ssa_literal", "constraint"]
30
+
31
+
32
+ def _utc_now() -> str:
33
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
34
+
35
+
36
+ def _normalize_literal(value: str) -> str:
37
+ return " ".join(str(value).strip().split()).lower()
38
+
39
+
40
+ @dataclass
41
+ class ReadBackProof:
42
+ channel: Literal["fresh_reload", "cross_tab", "api_read", "sql_read", "pdf_stream", "artifact_file"]
43
+ url_or_locator: str
44
+ cited_substrings: List[str]
45
+ external_ref: Optional[str] = None
46
+ observed_at_utc: str = field(default_factory=_utc_now)
47
+
48
+ def is_valid(self) -> bool:
49
+ return bool(self.url_or_locator and any(len(s.strip()) >= 2 for s in self.cited_substrings))
50
+
51
+
52
+ @dataclass
53
+ class Obligation:
54
+ obligation_id: str
55
+ description: str
56
+ target_system: str = "default"
57
+ state: ObligationState = "PENDING"
58
+ readback_proof: Optional[ReadBackProof] = None
59
+ exempt_reason: Optional[str] = None
60
+ committed_at_utc: Optional[str] = None
61
+
62
+
63
+ @dataclass
64
+ class CapabilityToken:
65
+ kind: CapabilityKind
66
+ key: str
67
+ value: str
68
+ source_window: str
69
+ turn: int
70
+ subject_key: Optional[str] = None
71
+ obs_hash: str = ""
72
+
73
+ def __post_init__(self) -> None:
74
+ if not self.obs_hash:
75
+ raw = f"{self.kind}|{self.key}|{self.value}|{self.source_window}|{self.subject_key or ''}"
76
+ self.obs_hash = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
77
+
78
+
79
+ @dataclass
80
+ class ProvenanceViolation:
81
+ field_name: str
82
+ attempted_value: str
83
+ reason: str
84
+
85
+
86
+ @dataclass
87
+ class FinalizationDecision:
88
+ outcome: EpisodeOutcome
89
+ reason: str
90
+ pending_obligations: List[str] = field(default_factory=list)
91
+ dirty_fields: List[str] = field(default_factory=list)
92
+ committed_refs: Dict[str, str] = field(default_factory=dict)
93
+
94
+
95
+ class ObligationLedger:
96
+ """Tracks step-0 obligations, typed capabilities, SSA provenance, and Saga state."""
97
+
98
+ def __init__(self, episode_id: Optional[str] = None, subject_key: Optional[str] = None) -> None:
99
+ self.episode_id = episode_id if (episode_id and episode_id.strip()) else f"ep-{uuid.uuid4()}"
100
+ self.subject_key = subject_key
101
+ self.status: EpisodeOutcome = "UNVERIFIED"
102
+ self.obligations: Dict[str, Obligation] = {}
103
+ self.capabilities: List[CapabilityToken] = []
104
+ self.escalation_reason: str = ""
105
+
106
+ # ---- Obligations ----
107
+
108
+ def add_obligation(
109
+ self,
110
+ obligation_id: str,
111
+ description: str,
112
+ target_system: str = "default",
113
+ ) -> Obligation:
114
+ ob = Obligation(
115
+ obligation_id=obligation_id,
116
+ description=description,
117
+ target_system=target_system,
118
+ )
119
+ self.obligations[obligation_id] = ob
120
+ return ob
121
+
122
+ def mark_committed(self, obligation_id: str, proof: ReadBackProof) -> None:
123
+ if obligation_id not in self.obligations:
124
+ raise KeyError(f"Unknown obligation_id: {obligation_id}")
125
+ if not proof.is_valid():
126
+ raise ValueError(f"ReadBackProof for {obligation_id} lacks locator or verbatim citations")
127
+ ob = self.obligations[obligation_id]
128
+ ob.state = "COMMITTED"
129
+ ob.readback_proof = proof
130
+ ob.committed_at_utc = _utc_now()
131
+
132
+ def mark_exempt(self, obligation_id: str, reason: str, proof: ReadBackProof) -> None:
133
+ if obligation_id not in self.obligations:
134
+ raise KeyError(f"Unknown obligation_id: {obligation_id}")
135
+ if not proof.is_valid():
136
+ raise ValueError(f"Exemption for {obligation_id} requires read-back proof")
137
+ ob = self.obligations[obligation_id]
138
+ ob.state = "EXEMPT"
139
+ ob.exempt_reason = reason
140
+ ob.readback_proof = proof
141
+ ob.committed_at_utc = _utc_now()
142
+
143
+ def is_committed(self, obligation_id: str) -> bool:
144
+ ob = self.obligations.get(obligation_id)
145
+ return ob is not None and ob.state in ("COMMITTED", "EXEMPT")
146
+
147
+ def pending_ids(self) -> List[str]:
148
+ return [oid for oid, ob in self.obligations.items() if ob.state == "PENDING"]
149
+
150
+ # ---- Typed Capabilities & Constraints (SEAM + Consent + SSA Provenance) ----
151
+
152
+ def record_consent(self, scope: str, user_text: str, turn: int, source_window: str = "user") -> CapabilityToken:
153
+ tok = CapabilityToken(
154
+ kind="consent",
155
+ key=scope,
156
+ value=user_text,
157
+ source_window=source_window,
158
+ turn=turn,
159
+ subject_key=self.subject_key,
160
+ )
161
+ self.capabilities.append(tok)
162
+ return tok
163
+
164
+ def record_constraint(
165
+ self,
166
+ key: str,
167
+ warning_text: str,
168
+ source_window: str,
169
+ turn: int,
170
+ subject_key: Optional[str] = None,
171
+ ) -> CapabilityToken:
172
+ tok = CapabilityToken(
173
+ kind="constraint",
174
+ key=key,
175
+ value=warning_text,
176
+ source_window=source_window,
177
+ turn=turn,
178
+ subject_key=subject_key or self.subject_key,
179
+ )
180
+ self.capabilities.append(tok)
181
+ return tok
182
+
183
+ def record_ssa_literal(
184
+ self,
185
+ key: str,
186
+ value: str,
187
+ source_window: str,
188
+ turn: int,
189
+ subject_key: Optional[str] = None,
190
+ ) -> CapabilityToken:
191
+ tok = CapabilityToken(
192
+ kind="ssa_literal",
193
+ key=key,
194
+ value=value,
195
+ source_window=source_window,
196
+ turn=turn,
197
+ subject_key=subject_key or self.subject_key,
198
+ )
199
+ self.capabilities.append(tok)
200
+ return tok
201
+
202
+ def has_consent(self, scope_substring: str = "") -> bool:
203
+ needle = scope_substring.strip().lower()
204
+ for tok in self.capabilities:
205
+ if tok.kind != "consent":
206
+ continue
207
+ if not needle or needle in tok.key.lower() or needle in tok.value.lower():
208
+ return True
209
+ return False
210
+
211
+ def verify_ssa_provenance(
212
+ self,
213
+ field_values: Dict[str, str],
214
+ opaque_fields: Iterable[str],
215
+ target_subject_key: Optional[str] = None,
216
+ ) -> List[ProvenanceViolation]:
217
+ """Verify opaque identifiers carry matching SSA provenance for the active subject."""
218
+ opaque_set = {f.strip().lower() for f in opaque_fields}
219
+ active_subject = target_subject_key or self.subject_key
220
+ violations: List[ProvenanceViolation] = []
221
+
222
+ ssa_tokens = [t for t in self.capabilities if t.kind == "ssa_literal"]
223
+ for field_name, val in field_values.items():
224
+ if field_name.strip().lower() not in opaque_set:
225
+ continue
226
+ norm_val = _normalize_literal(val)
227
+ if not norm_val:
228
+ continue
229
+ matches = [t for t in ssa_tokens if _normalize_literal(t.value) == norm_val]
230
+ if not matches:
231
+ violations.append(
232
+ ProvenanceViolation(
233
+ field_name=field_name,
234
+ attempted_value=val,
235
+ reason="unsourced_opaque_identifier",
236
+ )
237
+ )
238
+ continue
239
+ if active_subject is not None:
240
+ subject_matches = [t for t in matches if t.subject_key == active_subject]
241
+ if not subject_matches:
242
+ found_subjects = sorted({str(t.subject_key) for t in matches})
243
+ violations.append(
244
+ ProvenanceViolation(
245
+ field_name=field_name,
246
+ attempted_value=val,
247
+ reason=f"cross_subject_bleed(expected={active_subject}, observed={found_subjects})",
248
+ )
249
+ )
250
+ return violations
251
+
252
+ def render_auditor_context(self) -> Dict[str, Any]:
253
+ """Build zero-history prompt payload for a stateless commit auditor."""
254
+ return {
255
+ "episode_id": self.episode_id,
256
+ "subject_key": self.subject_key,
257
+ "MANDATORY_CONSTRAINTS": [
258
+ {"key": t.key, "warning": t.value, "source": t.source_window, "turn": t.turn}
259
+ for t in self.capabilities
260
+ if t.kind == "constraint"
261
+ ],
262
+ "VERIFIED_CAPABILITIES": {
263
+ "consents": [
264
+ {"scope": t.key, "user_text": t.value, "turn": t.turn}
265
+ for t in self.capabilities
266
+ if t.kind == "consent"
267
+ ],
268
+ "ssa_literals": [
269
+ {"key": t.key, "value": t.value, "source": t.source_window, "subject": t.subject_key}
270
+ for t in self.capabilities
271
+ if t.kind == "ssa_literal"
272
+ ],
273
+ },
274
+ "obligations": {
275
+ oid: {
276
+ "description": ob.description,
277
+ "state": ob.state,
278
+ "external_ref": ob.readback_proof.external_ref if ob.readback_proof else None,
279
+ }
280
+ for oid, ob in self.obligations.items()
281
+ },
282
+ }
283
+
284
+ # ---- Default-Deny Finalization ----
285
+
286
+ def finalize(
287
+ self,
288
+ trigger: Literal["done", "step_limit", "timeout", "error", "manual_abort"],
289
+ dirty_fields: Sequence[str] = (),
290
+ error_detail: str = "",
291
+ ) -> FinalizationDecision:
292
+ """Apply the default-deny receipting law.
293
+
294
+ Only trigger=='done' with zero pending obligations, zero dirty fields,
295
+ and valid read-back proofs on every obligation transitions to VERIFIED.
296
+ """
297
+ dirty = list(dirty_fields)
298
+ pending = self.pending_ids()
299
+ refs = {
300
+ oid: ob.readback_proof.external_ref
301
+ for oid, ob in self.obligations.items()
302
+ if ob.readback_proof and ob.readback_proof.external_ref
303
+ }
304
+
305
+ def _escalate(reason: str, pending_ids: Optional[List[str]] = None) -> FinalizationDecision:
306
+ self.status = "ESCALATED"
307
+ self.escalation_reason = reason
308
+ return FinalizationDecision(
309
+ outcome="ESCALATED",
310
+ reason=reason,
311
+ pending_obligations=pending if pending_ids is None else pending_ids,
312
+ dirty_fields=dirty,
313
+ committed_refs=refs,
314
+ )
315
+
316
+ if trigger != "done":
317
+ detail = f": {error_detail}" if error_detail else ""
318
+ return _escalate(f"default_deny_{trigger}{detail}")
319
+ if not self.obligations:
320
+ return _escalate("no_declared_obligations_verified")
321
+ if dirty:
322
+ return _escalate(f"uncommitted_dirty_fields: {dirty}")
323
+ if pending:
324
+ return _escalate(f"unverified_obligations: {pending}")
325
+ unproven = [
326
+ oid for oid, ob in self.obligations.items()
327
+ if ob.readback_proof is None or not ob.readback_proof.is_valid()
328
+ ]
329
+ if unproven:
330
+ return _escalate(f"missing_readback_proof: {unproven}", pending_ids=unproven)
331
+
332
+ self.status = "VERIFIED"
333
+ self.escalation_reason = ""
334
+ return FinalizationDecision(
335
+ outcome="VERIFIED",
336
+ reason="all_obligations_verified_with_readback",
337
+ pending_obligations=[],
338
+ dirty_fields=[],
339
+ committed_refs=refs,
340
+ )
341
+
342
+ # ---- Durable Saga Checkpointing ----
343
+
344
+ def to_dict(self) -> Dict[str, Any]:
345
+ return {
346
+ "schema": "openadapt.kernel.saga/v1",
347
+ "episode_id": self.episode_id,
348
+ "subject_key": self.subject_key,
349
+ "status": self.status,
350
+ "escalation_reason": self.escalation_reason,
351
+ "obligations": {oid: asdict(ob) for oid, ob in self.obligations.items()},
352
+ "capabilities": [asdict(tok) for tok in self.capabilities],
353
+ }
354
+
355
+ def save_saga(self, path: Path) -> None:
356
+ path.parent.mkdir(parents=True, exist_ok=True)
357
+ path.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
358
+
359
+ @classmethod
360
+ def load_saga(cls, path: Path) -> "ObligationLedger":
361
+ data = json.loads(path.read_text(encoding="utf-8"))
362
+ ledger = cls(episode_id=data["episode_id"], subject_key=data.get("subject_key"))
363
+ ledger.status = data.get("status", "UNVERIFIED")
364
+ ledger.escalation_reason = data.get("escalation_reason", "")
365
+ for oid, ob_d in data.get("obligations", {}).items():
366
+ proof_d = ob_d.get("readback_proof")
367
+ proof = ReadBackProof(**proof_d) if proof_d else None
368
+ ledger.obligations[oid] = Obligation(
369
+ obligation_id=ob_d["obligation_id"],
370
+ description=ob_d["description"],
371
+ target_system=ob_d.get("target_system", "default"),
372
+ state=ob_d["state"],
373
+ readback_proof=proof,
374
+ exempt_reason=ob_d.get("exempt_reason"),
375
+ committed_at_utc=ob_d.get("committed_at_utc"),
376
+ )
377
+ for tok_d in data.get("capabilities", []):
378
+ ledger.capabilities.append(CapabilityToken(**tok_d))
379
+ return ledger