letitloop 0.2.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.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
orchestrator/state.py ADDED
@@ -0,0 +1,871 @@
1
+ """Event-sourced task state with append-only signed WAL, hash chain, replay.
2
+
3
+ Phase 0.5: all state changes are events appended to a WAL with
4
+ monotonic sequence numbers and a SHA-256 hash chain; current state is a
5
+ derived projection. Snapshots are atomic (tmp + os.replace) and replay
6
+ restores attempt/evidence/worker_results/data from the WAL.
7
+
8
+ Public API is backward-compatible with the pre-0.5 snapshot state store:
9
+ - State methods: transition, force_complete, record_approach, increment_attempt,
10
+ add_evidence, add_worker_result, add_retry_metadata, pause, cancel,
11
+ legal_transitions, is_terminal, can_resume, set_journal_dir,
12
+ recover_from_journal, to_dict, from_dict, qc_was_executed.
13
+ - Module functions: create_initial_state, load_state, replay_wal,
14
+ recover_from_journal, save_state.
15
+ - state.events remains a list of transition-style dicts (from/to/reason) so
16
+ existing consumers (handoff, cli) keep working; the WAL carries the full
17
+ event-sourced records with seq/hash chain.
18
+ """
19
+
20
+ import copy
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import shutil
25
+ from datetime import datetime, timezone
26
+ from typing import Any, Dict
27
+
28
+ from .exceptions import IllegalTransitionError, StateError
29
+
30
+ JOURNAL_FILENAME = "state.journal.jsonl"
31
+ WAL_FILENAME = "state.wal.jsonl"
32
+ SNAPSHOT_FILENAME = "state.json"
33
+ STATE_SCHEMA_VERSION = 2
34
+
35
+ STATES = frozenset(
36
+ {
37
+ "DRAFTED",
38
+ "PREFLIGHT_RUNNING",
39
+ "PREFLIGHT_FAILED",
40
+ "BLOCKED",
41
+ "READY",
42
+ "WORKING",
43
+ "VERIFYING",
44
+ "VERIFICATION_FAILED",
45
+ "RETRY_PENDING",
46
+ "CRASHED",
47
+ "ESCALATED",
48
+ "VERIFIED",
49
+ "QC_RUNNING",
50
+ "QC_REJECTED",
51
+ "QC_INSUFFICIENT_EVIDENCE",
52
+ "QC_CONDITIONAL_PASS",
53
+ "QC_PASSED",
54
+ "COMPLETE",
55
+ "FORCE_COMPLETE",
56
+ "DEGRADED_PASS",
57
+ "PAUSED",
58
+ "CANCELLED",
59
+ }
60
+ )
61
+
62
+ TERMINAL_STATES = frozenset({"COMPLETE", "FORCE_COMPLETE", "DEGRADED_PASS", "ESCALATED", "BLOCKED", "CANCELLED"})
63
+
64
+ LEGAL_TRANSITIONS = {
65
+ "DRAFTED": {"PREFLIGHT_RUNNING", "RETRY_PENDING", "CANCELLED"},
66
+ "PREFLIGHT_RUNNING": {"PREFLIGHT_FAILED", "READY", "PAUSED", "CANCELLED"},
67
+ "PREFLIGHT_FAILED": {"BLOCKED", "PREFLIGHT_RUNNING", "CANCELLED"},
68
+ "BLOCKED": {"PREFLIGHT_RUNNING", "DRAFTED", "CANCELLED"},
69
+ "READY": {"WORKING", "PAUSED", "CANCELLED"},
70
+ "WORKING": {"VERIFYING", "CRASHED", "PAUSED", "CANCELLED"},
71
+ "VERIFYING": {"VERIFICATION_FAILED", "VERIFIED", "PAUSED", "CANCELLED"},
72
+ "VERIFICATION_FAILED": {"RETRY_PENDING", "FORCE_COMPLETE", "ESCALATED", "CANCELLED"},
73
+ "RETRY_PENDING": {"WORKING", "ESCALATED", "QC_REJECTED", "PAUSED", "CANCELLED"},
74
+ "CRASHED": {"RETRY_PENDING", "DRAFTED", "CANCELLED"},
75
+ "VERIFIED": {"QC_RUNNING", "COMPLETE", "CANCELLED"},
76
+ "QC_RUNNING": {
77
+ "QC_REJECTED",
78
+ "QC_INSUFFICIENT_EVIDENCE",
79
+ "QC_CONDITIONAL_PASS",
80
+ "QC_PASSED",
81
+ "PAUSED",
82
+ "CANCELLED",
83
+ },
84
+ "QC_REJECTED": {"RETRY_PENDING", "FORCE_COMPLETE", "ESCALATED", "CANCELLED"},
85
+ "QC_INSUFFICIENT_EVIDENCE": {"RETRY_PENDING", "FORCE_COMPLETE", "ESCALATED", "CANCELLED"},
86
+ "QC_CONDITIONAL_PASS": {"RETRY_PENDING", "FORCE_COMPLETE", "ESCALATED", "CANCELLED"},
87
+ "QC_PASSED": {"COMPLETE", "DEGRADED_PASS", "CANCELLED"},
88
+ "PAUSED": {"READY", "DRAFTED", "CANCELLED"},
89
+ "ESCALATED": set(),
90
+ "COMPLETE": set(),
91
+ "FORCE_COMPLETE": set(),
92
+ "DEGRADED_PASS": set(),
93
+ "CANCELLED": set(),
94
+ }
95
+
96
+ _DELETE_SENTINEL = {"__delete__": True}
97
+
98
+
99
+ def _now():
100
+ return datetime.now(timezone.utc).isoformat()
101
+
102
+
103
+ def _canonical(obj: Any) -> str:
104
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
105
+
106
+
107
+ def _sha256_text(text: str) -> str:
108
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
109
+
110
+
111
+ def _event_hash(event: Dict[str, Any]) -> str:
112
+ core = dict(event)
113
+ core.pop("event_hash", None)
114
+ return _sha256_text(_canonical(core))
115
+
116
+
117
+ def _fsync_dir(path: str) -> None:
118
+ """Best-effort directory fsync (POSIX only; Windows handles via file fsync)."""
119
+ if os.name == "nt":
120
+ return
121
+ try:
122
+ fd = os.open(os.path.dirname(os.path.abspath(path)), os.O_DIRECTORY)
123
+ except OSError:
124
+ return
125
+ try:
126
+ os.fsync(fd)
127
+ finally:
128
+ os.close(fd)
129
+
130
+
131
+ def _validate_jsonable(payload: Any) -> None:
132
+ """Reject non-JSON-serializable payloads (objects/functions)."""
133
+ try:
134
+ json.dumps(payload, ensure_ascii=False)
135
+ except (TypeError, ValueError) as e:
136
+ raise StateError(f"event payload not JSON-serializable: {e}") from e
137
+
138
+
139
+ class State:
140
+ """Event-sourced task state.
141
+
142
+ All mutations emit an event to the WAL (append + fsync) and then apply
143
+ it in memory. The snapshot is a derived projection written atomically.
144
+
145
+ Attributes:
146
+ task_id: str
147
+ status: str (current state name)
148
+ attempt: int (current retry attempt, 1-based)
149
+ changed_approaches: list[str] — recorded approach descriptions per retry
150
+ events: list[dict] — transition-style entries (from/to/reason), derived
151
+ evidence: dict — keyed by event/check id, value = path to evidence file
152
+ worker_results: list[dict] — past worker runs
153
+ data: dict — extensible metadata
154
+ _journal_dir: str or None — directory for WAL + journal
155
+ _seq: int — last applied WAL sequence number
156
+ _hash_head: str — hash of last applied WAL event
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ task_id,
162
+ status="DRAFTED",
163
+ attempt=1,
164
+ changed_approaches=None,
165
+ events=None,
166
+ evidence=None,
167
+ worker_results=None,
168
+ data=None,
169
+ journal_dir=None,
170
+ *,
171
+ seq=0,
172
+ hash_head="",
173
+ schema_version=STATE_SCHEMA_VERSION,
174
+ ):
175
+ if status not in STATES and status is not None:
176
+ raise StateError(f"invalid state: {status}")
177
+ if not isinstance(attempt, int) or attempt < 1:
178
+ raise StateError(f"attempt must be int >= 1, got {attempt!r}")
179
+ self.task_id = task_id
180
+ self.status = status
181
+ self.attempt = attempt
182
+ self.changed_approaches = list(changed_approaches or [])
183
+ self.events = list(events or [])
184
+ self.evidence = dict(evidence or {})
185
+ self.worker_results = list(worker_results or [])
186
+ self.data = dict(data or {})
187
+ self._journal_dir = journal_dir
188
+ self._seq = int(seq)
189
+ self._hash_head = hash_head
190
+ self._schema_version = schema_version
191
+
192
+ # ------------------------------------------------------------------
193
+ # WAL plumbing
194
+ # ------------------------------------------------------------------
195
+
196
+ @property
197
+ def wal_path(self):
198
+ if not self._journal_dir:
199
+ raise StateError("journal_dir not set")
200
+ return os.path.join(self._journal_dir, WAL_FILENAME)
201
+
202
+ @property
203
+ def journal_path(self):
204
+ if not self._journal_dir:
205
+ raise StateError("journal_dir not set")
206
+ return os.path.join(self._journal_dir, JOURNAL_FILENAME)
207
+
208
+ def set_journal_dir(self, journal_dir):
209
+ """Set the directory for WAL/journal persistence."""
210
+ self._journal_dir = journal_dir
211
+
212
+ def _build_event(self, event_type, payload, reason=""):
213
+ """Build a full WAL event with seq, prev_hash and self-hash."""
214
+ _validate_jsonable(payload)
215
+ seq = self._seq + 1
216
+ event = {
217
+ "seq": seq,
218
+ "timestamp": _now(),
219
+ "event_type": event_type,
220
+ "task_id": self.task_id,
221
+ "prev_hash": self._hash_head,
222
+ "payload": payload,
223
+ }
224
+ if reason:
225
+ event["reason"] = reason
226
+ event["event_hash"] = _event_hash(event)
227
+ return event
228
+
229
+ def _append_wal(self, event):
230
+ """Append + fsync one event to the WAL. Fail-closed on I/O error.
231
+
232
+ When no journal_dir is set the state is in-memory only: the event is
233
+ not persisted (matching the pre-0.5 ephemeral semantic), but the
234
+ in-memory projection still applies.
235
+ """
236
+ if not self._journal_dir:
237
+ return
238
+ try:
239
+ os.makedirs(self._journal_dir, exist_ok=True)
240
+ with open(self.wal_path, "a", encoding="utf-8") as f:
241
+ f.write(_canonical(event) + "\n")
242
+ f.flush()
243
+ os.fsync(f.fileno())
244
+ except OSError as e:
245
+ raise StateError(f"failed to append WAL: {e}") from e
246
+
247
+ def _append_journal(self, event):
248
+ """Append + fsync one event to the audit journal (best-effort)."""
249
+ if not self._journal_dir:
250
+ return
251
+ try:
252
+ os.makedirs(self._journal_dir, exist_ok=True)
253
+ with open(self.journal_path, "a", encoding="utf-8") as f:
254
+ f.write(_canonical(event) + "\n")
255
+ f.flush()
256
+ os.fsync(f.fileno())
257
+ except OSError as e:
258
+ raise StateError(f"failed to append journal: {e}") from e
259
+
260
+ # ------------------------------------------------------------------
261
+ # Event application (replay + live)
262
+ # ------------------------------------------------------------------
263
+
264
+ def _apply_event(self, event, *, replay=False):
265
+ """Verify chain/sequence/hash and apply one event to in-memory state."""
266
+ if not isinstance(event, dict):
267
+ raise StateError("event must be dict")
268
+ required = {"seq", "timestamp", "event_type", "task_id", "prev_hash", "payload", "event_hash"}
269
+ missing = required - set(event.keys())
270
+ if missing:
271
+ raise StateError(f"event missing fields: {sorted(missing)}")
272
+ if event["task_id"] != self.task_id:
273
+ raise StateError("event task_id mismatch")
274
+ if not isinstance(event["seq"], int) or event["seq"] != self._seq + 1:
275
+ raise StateError(f"sequence mismatch: expected {self._seq + 1}, got {event['seq']}")
276
+ if event["prev_hash"] != self._hash_head:
277
+ raise StateError("hash chain mismatch: prev_hash mismatch")
278
+ if _event_hash(event) != event["event_hash"]:
279
+ raise StateError("event hash mismatch")
280
+
281
+ event_type = event["event_type"]
282
+ payload = event["payload"]
283
+ if not isinstance(payload, dict):
284
+ raise StateError("payload must be dict")
285
+
286
+ if event_type == "INIT":
287
+ if self._seq != 0:
288
+ raise StateError("duplicate INIT")
289
+ if payload.get("status", "DRAFTED") not in STATES:
290
+ raise StateError("invalid init status")
291
+ self.status = payload.get("status", "DRAFTED")
292
+ self.attempt = int(payload.get("attempt", 1))
293
+ self.changed_approaches = list(payload.get("changed_approaches", []))
294
+ self.evidence = dict(payload.get("evidence", {}))
295
+ self.worker_results = list(payload.get("worker_results", []))
296
+ self.data = dict(payload.get("data", {}))
297
+ self.events.append(
298
+ {
299
+ "timestamp": event["timestamp"],
300
+ "from": "",
301
+ "to": self.status,
302
+ "reason": event.get("reason", "state initialized"),
303
+ }
304
+ )
305
+ elif event_type == "TRANSITION":
306
+ new_status = payload["to"]
307
+ if new_status not in STATES:
308
+ raise IllegalTransitionError(self.status, new_status, f"unknown target state: {new_status}")
309
+ self._validate_transition(self.status, new_status)
310
+ self.status = new_status
311
+ transition_entry = {
312
+ "timestamp": event["timestamp"],
313
+ "from": payload.get("from", self.status),
314
+ "to": new_status,
315
+ "reason": payload.get("reason", event.get("reason", "")),
316
+ }
317
+ if payload.get("evidence_path"):
318
+ transition_entry["evidence_path"] = payload["evidence_path"]
319
+ self.events.append(transition_entry)
320
+ elif event_type == "ATTEMPT_INCREMENT":
321
+ self.attempt += int(payload.get("delta", 1))
322
+ if self.attempt < 1:
323
+ raise StateError("attempt invalid after increment")
324
+ elif event_type == "APPROACH_RECORDED":
325
+ self.changed_approaches.append(str(payload.get("description", "")))
326
+ elif event_type == "EVIDENCE_ADD":
327
+ self.evidence[str(payload["key"])] = str(payload["path"])
328
+ elif event_type == "WORKER_RESULT_ADD":
329
+ self.worker_results.append(copy.deepcopy(payload["result"]))
330
+ elif event_type == "RETRY_METADATA_ADD":
331
+ self.data.setdefault("retry_metadata", [])
332
+ self.data["retry_metadata"].append(copy.deepcopy(payload["metadata"]))
333
+ elif event_type == "DATA_PATCH":
334
+ patch = payload.get("patch", {})
335
+ if not isinstance(patch, dict):
336
+ raise StateError("DATA_PATCH patch must be dict")
337
+ for k, v in patch.items():
338
+ if v is _DELETE_SENTINEL:
339
+ self.data.pop(k, None)
340
+ else:
341
+ self.data[k] = copy.deepcopy(v)
342
+ elif event_type == "FORCE_COMPLETE":
343
+ self.status = "FORCE_COMPLETE"
344
+ self.data["force_complete"] = copy.deepcopy(payload)
345
+ elif event_type == "ESCALATE":
346
+ if self.status in ("COMPLETE", "FORCE_COMPLETE", "DEGRADED_PASS"):
347
+ raise IllegalTransitionError(f"cannot force-escalate a {self.status} task")
348
+ self.status = "ESCALATED"
349
+ self.data["escalation_reason"] = event.get("reason", "")
350
+ self.events.append(
351
+ {
352
+ "timestamp": event["timestamp"],
353
+ "from": payload.get("from", ""),
354
+ "to": "ESCALATED",
355
+ "reason": event.get("reason", "force escalation"),
356
+ }
357
+ )
358
+ elif event_type == "FORCE_BLOCK":
359
+ if self.status in ("COMPLETE", "FORCE_COMPLETE", "DEGRADED_PASS"):
360
+ raise IllegalTransitionError(f"cannot force-block a {self.status} task")
361
+ self.status = "BLOCKED"
362
+ self.data["block_reason"] = event.get("reason", "")
363
+ self.events.append(
364
+ {
365
+ "timestamp": event["timestamp"],
366
+ "from": payload.get("from", ""),
367
+ "to": "BLOCKED",
368
+ "reason": event.get("reason", "forced block"),
369
+ }
370
+ )
371
+ elif event_type == "WORKER_RESULT_PATCH":
372
+ idx = int(payload["index"])
373
+ if idx < 0 or idx >= len(self.worker_results):
374
+ raise StateError(f"WORKER_RESULT_PATCH index {idx} out of range")
375
+ self.worker_results[idx] = copy.deepcopy(payload["result"])
376
+ elif event_type == "PAUSE":
377
+ self._validate_transition(self.status, "PAUSED")
378
+ self.status = "PAUSED"
379
+ self.events.append(
380
+ {
381
+ "timestamp": event["timestamp"],
382
+ "from": payload.get("from", ""),
383
+ "to": "PAUSED",
384
+ "reason": event.get("reason", "operator pause"),
385
+ }
386
+ )
387
+ elif event_type == "CANCEL":
388
+ self._validate_transition(self.status, "CANCELLED")
389
+ self.status = "CANCELLED"
390
+ self.events.append(
391
+ {
392
+ "timestamp": event["timestamp"],
393
+ "from": payload.get("from", ""),
394
+ "to": "CANCELLED",
395
+ "reason": event.get("reason", "operator cancel"),
396
+ }
397
+ )
398
+ else:
399
+ raise StateError(f"unknown event_type: {event_type}")
400
+
401
+ self._seq = event["seq"]
402
+ self._hash_head = event["event_hash"]
403
+
404
+ def _validate_transition(self, old, new):
405
+ allowed = LEGAL_TRANSITIONS.get(old, set())
406
+ if new not in allowed:
407
+ if old in TERMINAL_STATES:
408
+ raise IllegalTransitionError(f"cannot transition from terminal state {old}")
409
+ raise IllegalTransitionError(f"illegal transition: {old} -> {new} (allowed from {old}: {sorted(allowed)})")
410
+
411
+ # ------------------------------------------------------------------
412
+ # Public mutation API (all event-sourced)
413
+ # ------------------------------------------------------------------
414
+
415
+ def append_event(self, event_type, payload, reason=""):
416
+ """Append a raw event to the WAL and apply it. Returns the event dict."""
417
+ if self._seq == 0 and event_type != "INIT":
418
+ # Raw-constructed state (e.g. State(task_id, status=...)) that was
419
+ # never created via create_initial_state. Synthesize an INIT from
420
+ # the current projection so the WAL chain starts cleanly instead of
421
+ # mid-chain (fail-closed replay requires a leading INIT, seq=1).
422
+ self.append_event(
423
+ "INIT",
424
+ {
425
+ "status": self.status,
426
+ "attempt": self.attempt,
427
+ "changed_approaches": list(self.changed_approaches),
428
+ "evidence": dict(self.evidence),
429
+ "worker_results": list(self.worker_results),
430
+ "data": dict(self.data),
431
+ },
432
+ reason="synthesized INIT for raw-constructed state",
433
+ )
434
+ event = self._build_event(event_type, payload, reason=reason)
435
+ prev_seq = self._seq
436
+ prev_hash = self._hash_head
437
+ prev_status = self.status
438
+ self._apply_event(event, replay=False)
439
+ try:
440
+ self._append_wal(event)
441
+ self._append_journal(event)
442
+ except Exception:
443
+ self._seq = prev_seq
444
+ self._hash_head = prev_hash
445
+ self.status = prev_status
446
+ raise
447
+ return event
448
+
449
+ def transition(self, new_status, reason="", evidence_path=None):
450
+ """Transition to new_status if legal. Event-sourced."""
451
+ payload = {"from": self.status, "to": new_status}
452
+ if evidence_path:
453
+ payload["evidence_path"] = evidence_path
454
+ self.append_event("TRANSITION", payload, reason=reason)
455
+
456
+ def force_complete(self, reason="", failed_checks=None, output_hash="", waived_files=None, cleanup_decision=""):
457
+ """Transition to FORCE_COMPLETE with auditable waiver metadata."""
458
+ payload = {
459
+ "reason": reason,
460
+ "failed_checks": failed_checks or [],
461
+ "output_hash": output_hash,
462
+ "waived_files": waived_files or [],
463
+ "cleanup_decision": cleanup_decision,
464
+ "timestamp": _now(),
465
+ }
466
+ self.append_event("FORCE_COMPLETE", payload, reason=reason)
467
+
468
+ def record_approach(self, description):
469
+ """Record a changed approach description for the current retry."""
470
+ self.append_event("APPROACH_RECORDED", {"description": description})
471
+
472
+ def increment_attempt(self):
473
+ """Increment the retry attempt counter."""
474
+ self.append_event("ATTEMPT_INCREMENT", {"delta": 1}, reason="increment attempt")
475
+
476
+ def add_evidence(self, key, path):
477
+ """Link evidence artifact to the state."""
478
+ self.append_event("EVIDENCE_ADD", {"key": key, "path": path})
479
+
480
+ def add_worker_result(self, result):
481
+ """Append a recorded worker run."""
482
+ self.append_event("WORKER_RESULT_ADD", {"result": result})
483
+
484
+ def add_retry_metadata(self, metadata: dict):
485
+ """Append structured retry metadata."""
486
+ self.append_event("RETRY_METADATA_ADD", {"metadata": metadata})
487
+
488
+ def patch_data(self, patch: dict):
489
+ """Event-sourced data mutation. None values delete the key."""
490
+ normalized = {}
491
+ for k, v in patch.items():
492
+ normalized[k] = _DELETE_SENTINEL if v is None else v
493
+ self.append_event("DATA_PATCH", {"patch": normalized})
494
+
495
+ def delete_data_key(self, key: str):
496
+ """Event-sourced removal of a data key."""
497
+ self.append_event("DATA_PATCH", {"patch": {key: _DELETE_SENTINEL}})
498
+
499
+ def force_escalate(self, reason="stall: no progress in supervision loop"):
500
+ """Privileged escalation to ESCALATED from any non-success state.
501
+
502
+ Audited via the ESCALATE event. Refuses to demote a completed task.
503
+ Used by the stall sweeper and failsafe retry paths only.
504
+ """
505
+ self.append_event("ESCALATE", {"from": self.status}, reason=reason)
506
+
507
+ def force_block(self, reason="task crashed"):
508
+ """Privileged forced block from any non-success state.
509
+
510
+ Audited via the FORCE_BLOCK event. Refuses to demote a completed task.
511
+ Used by the task-crash barrier only.
512
+ """
513
+ self.append_event("FORCE_BLOCK", {"from": self.status}, reason=reason)
514
+
515
+ def patch_worker_result(self, index: int, result: dict):
516
+ """Event-sourced replacement of a recorded worker result."""
517
+ self.append_event("WORKER_RESULT_PATCH", {"index": index, "result": result})
518
+
519
+ # ------------------------------------------------------------------
520
+ # Query API (unchanged)
521
+ # ------------------------------------------------------------------
522
+
523
+ def legal_transitions(self):
524
+ return LEGAL_TRANSITIONS.get(self.status, set())
525
+
526
+ def is_terminal(self):
527
+ return self.status in TERMINAL_STATES
528
+
529
+ def can_resume(self):
530
+ """Return True if this state is in a resumable (non-terminal) state."""
531
+ return self.status not in TERMINAL_STATES and self.status != "DRAFTED"
532
+
533
+ def pause(self, reason="operator pause"):
534
+ """Transition to PAUSED if legal. Returns True on success."""
535
+ if "PAUSED" in self.legal_transitions():
536
+ self.append_event("PAUSE", {"from": self.status}, reason=reason)
537
+ return True
538
+ return False
539
+
540
+ def cancel(self, reason="operator cancel"):
541
+ """Transition to CANCELLED if legal. Returns True on success."""
542
+ if "CANCELLED" in self.legal_transitions():
543
+ self.append_event("CANCEL", {"from": self.status}, reason=reason)
544
+ return True
545
+ return False
546
+
547
+ def recover_from_journal(self) -> bool:
548
+ """Flag state when the journal contains events the snapshot does not.
549
+
550
+ Does NOT rewrite persistence — only marks data["recovered_from_journal"]
551
+ for the audit trail. The WAL replay is authoritative for recovery.
552
+ """
553
+ if not self._journal_dir:
554
+ return False
555
+ journal_path = self.journal_path
556
+ if not os.path.isfile(journal_path):
557
+ return False
558
+ journal_events = []
559
+ try:
560
+ with open(journal_path, "r", encoding="utf-8") as f:
561
+ for line in f:
562
+ line = line.strip()
563
+ if line:
564
+ journal_events.append(json.loads(line))
565
+ except (OSError, json.JSONDecodeError):
566
+ return False
567
+ ahead = len(journal_events) > len(self.events)
568
+ if not ahead and journal_events and self.events:
569
+ ahead = journal_events[-1] != self.events[-1]
570
+ if ahead:
571
+ self.data["recovered_from_journal"] = True
572
+ return ahead
573
+
574
+ @property
575
+ def qc_was_executed(self):
576
+ return "qc_verdict" in self.evidence
577
+
578
+ # ------------------------------------------------------------------
579
+ # Serialization
580
+ # ------------------------------------------------------------------
581
+
582
+ def to_dict(self):
583
+ return {
584
+ "task_id": self.task_id,
585
+ "status": self.status,
586
+ "attempt": self.attempt,
587
+ "changed_approaches": list(self.changed_approaches),
588
+ "events": list(self.events),
589
+ "evidence": dict(self.evidence),
590
+ "worker_results": list(self.worker_results),
591
+ "data": dict(self.data),
592
+ "schema_version": self._schema_version,
593
+ "seq": self._seq,
594
+ "hash_head": self._hash_head,
595
+ }
596
+
597
+ @classmethod
598
+ def from_dict(cls, d, journal_dir=None):
599
+ if not isinstance(d, dict) or not isinstance(d.get("task_id"), str) or not d["task_id"]:
600
+ raise StateError("snapshot missing required 'task_id' field")
601
+ return cls(
602
+ task_id=d["task_id"],
603
+ status=d.get("status", "DRAFTED"),
604
+ attempt=d.get("attempt", 1),
605
+ changed_approaches=list(d.get("changed_approaches", [])),
606
+ events=list(d.get("events", [])),
607
+ evidence=dict(d.get("evidence", {})),
608
+ worker_results=list(d.get("worker_results", [])),
609
+ data=dict(d.get("data", {})),
610
+ journal_dir=journal_dir,
611
+ seq=int(d.get("seq", 0)),
612
+ hash_head=d.get("hash_head", ""),
613
+ schema_version=int(d.get("schema_version", 1)),
614
+ )
615
+
616
+ def __repr__(self):
617
+ return f"<State {self.task_id} status={self.status} attempt={self.attempt}>"
618
+
619
+
620
+ def _require_task_id(d: dict) -> str:
621
+ task_id = d.get("task_id") if isinstance(d, dict) else None
622
+ if not isinstance(task_id, str) or not task_id:
623
+ raise StateError("snapshot missing required 'task_id' field")
624
+ return task_id
625
+
626
+
627
+ def _migrate_legacy_snapshot(d: dict, journal_dir: str) -> State:
628
+ """Convert a pre-0.5 snapshot (no seq/hash_head) into an event-sourced State.
629
+
630
+ The legacy snapshot is treated as a synthetic INIT so the WAL hash chain
631
+ has a valid head. No data is lost; unknown data keys survive in `data`.
632
+ The INIT is appended to the WAL so subsequent events chain correctly.
633
+ """
634
+ state = State(
635
+ task_id=_require_task_id(d),
636
+ status=d.get("status", "DRAFTED"),
637
+ attempt=d.get("attempt", 1),
638
+ changed_approaches=list(d.get("changed_approaches", [])),
639
+ events=list(d.get("events", [])),
640
+ evidence=dict(d.get("evidence", {})),
641
+ worker_results=list(d.get("worker_results", [])),
642
+ data=dict(d.get("data", {})),
643
+ journal_dir=journal_dir,
644
+ )
645
+ state.data.setdefault("migrated_from_snapshot_v1", True)
646
+ if journal_dir:
647
+ init_event = state._build_event(
648
+ "INIT",
649
+ {
650
+ "status": state.status,
651
+ "attempt": state.attempt,
652
+ "changed_approaches": list(state.changed_approaches),
653
+ "evidence": dict(state.evidence),
654
+ "worker_results": list(state.worker_results),
655
+ "data": dict(state.data),
656
+ },
657
+ reason="migrated from snapshot v1",
658
+ )
659
+ state._append_wal(init_event)
660
+ state._seq = init_event["seq"]
661
+ state._hash_head = init_event["event_hash"]
662
+ state.events = []
663
+ return state
664
+
665
+
666
+ def create_initial_state(task_id, journal_dir=None):
667
+ """Create a fresh DRAFTED state for the given task_id (event-sourced)."""
668
+ state = State(
669
+ task_id=task_id,
670
+ status="DRAFTED",
671
+ attempt=1,
672
+ events=[],
673
+ journal_dir=journal_dir,
674
+ )
675
+ # Append INIT + a DRAFTED marker event so the WAL chain starts cleanly.
676
+ # INIT carries the initial projection; replay must not require a
677
+ # persisted snapshot to reconstruct the state.
678
+ state.append_event(
679
+ "INIT",
680
+ {
681
+ "status": "DRAFTED",
682
+ "attempt": 1,
683
+ "changed_approaches": [],
684
+ "evidence": {},
685
+ "worker_results": [],
686
+ "data": {},
687
+ },
688
+ reason="state initialized",
689
+ )
690
+ return state
691
+
692
+
693
+ def load_state(path, journal_dir=None):
694
+ """Load state from a JSON file. Returns State or raises.
695
+
696
+ Reads the snapshot (if present), then replays the WAL (if present) that
697
+ may be ahead of the snapshot, verifying the hash chain and transitions.
698
+ Fail-closed: corrupt JSON, hash mismatch, sequence gap, or illegal
699
+ transition all raise StateError/IllegalTransitionError.
700
+ """
701
+ if not os.path.isfile(path):
702
+ raise StateError(f"state file not found: {path}")
703
+ effective_journal_dir = journal_dir or os.path.dirname(os.path.abspath(path))
704
+ try:
705
+ with open(path, "r", encoding="utf-8") as f:
706
+ raw = json.load(f)
707
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
708
+ raise StateError(f"state file corrupt: {exc}") from exc
709
+
710
+ if not isinstance(raw, dict):
711
+ raise StateError("state file must be a JSON object")
712
+
713
+ if raw.get("schema_version") == STATE_SCHEMA_VERSION:
714
+ state = State.from_dict(raw, journal_dir=effective_journal_dir)
715
+ else:
716
+ state = _migrate_legacy_snapshot(raw, effective_journal_dir)
717
+ # Persist the migrated snapshot immediately (best-effort; if it fails
718
+ # the in-memory state is still usable for this run).
719
+ try:
720
+ save_state(state, path, backup=True)
721
+ except StateError:
722
+ pass
723
+
724
+ # Replay WAL events ahead of the snapshot (verifies chain + seq + legality).
725
+ state = replay_wal(path, state=state)
726
+ state.recover_from_journal()
727
+ return state
728
+
729
+
730
+ def replay_wal(state_path, state=None):
731
+ """Replay the WAL and return the authoritative derived State.
732
+
733
+ When the WAL starts with a valid new-format INIT (seq=1), the ENTIRE
734
+ chain is replayed from scratch — every event hash, sequence number, and
735
+ transition is verified. The snapshot is only a checkpoint, never trusted
736
+ over the WAL. Fail-closed on any integrity violation.
737
+
738
+ Fallbacks:
739
+ - No WAL file: snapshot stands (legacy / checkpoint-only state).
740
+ - Legacy-format WAL (no seq/event_hash) with a migrated snapshot: legacy
741
+ lines are skipped — they carry no chain to verify; snapshot is truth.
742
+ - New-format WAL without a leading INIT: hard error (inconsistent).
743
+ """
744
+ journal_dir = os.path.dirname(os.path.abspath(state_path))
745
+ if state is None:
746
+ try:
747
+ with open(state_path, "r", encoding="utf-8") as f:
748
+ raw = json.load(f)
749
+ state = State.from_dict(raw, journal_dir=journal_dir)
750
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
751
+ raise StateError(f"state file corrupt: {exc}") from exc
752
+
753
+ wal_path = os.path.join(journal_dir, WAL_FILENAME)
754
+ if not os.path.isfile(wal_path):
755
+ return state
756
+ wal_events = []
757
+ try:
758
+ with open(wal_path, "r", encoding="utf-8") as f:
759
+ for line in f:
760
+ line = line.strip()
761
+ if not line:
762
+ continue
763
+ wal_events.append(json.loads(line))
764
+ except (OSError, json.JSONDecodeError, ValueError):
765
+ raise StateError("WAL file corrupt: failed to parse events")
766
+
767
+ if not wal_events:
768
+ return state
769
+
770
+ first = wal_events[0]
771
+ is_new_format = isinstance(first, dict) and first.get("event_type") == "INIT" and first.get("seq") == 1
772
+ if not is_new_format:
773
+ # Legacy WAL: only tolerated when the snapshot was migrated from v1.
774
+ if state.data.get("migrated_from_snapshot_v1"):
775
+ return state
776
+ raise StateError("WAL does not start with INIT (seq=1)")
777
+
778
+ # Authoritative full-chain replay from a fresh empty state.
779
+ task_id = first.get("task_id")
780
+ if not isinstance(task_id, str) or not task_id:
781
+ raise StateError("WAL INIT event missing task_id")
782
+ fresh = State(task_id=task_id, status="DRAFTED", journal_dir=journal_dir)
783
+ for event in wal_events:
784
+ fresh._apply_event(event, replay=True)
785
+ fresh.data.setdefault("recovered_from_wal", True)
786
+ return fresh
787
+
788
+
789
+ def recover_from_journal(journal_path, journal_dir=None):
790
+ """Rebuild state from journal file. Returns State or None.
791
+
792
+ Legacy journal entries (from/to dicts) are turned into a best-effort
793
+ reconstructed state; full hash-chain integrity is only guaranteed via WAL.
794
+ """
795
+ if not os.path.isfile(journal_path):
796
+ return None
797
+ task_id = ""
798
+ events = []
799
+ data = {}
800
+ attempt = 1
801
+ changed_approaches = []
802
+ evidence = {}
803
+ worker_results = []
804
+ last_status = None
805
+ try:
806
+ with open(journal_path, "r", encoding="utf-8") as f:
807
+ for line in f:
808
+ line = line.strip()
809
+ if not line:
810
+ continue
811
+ entry = json.loads(line)
812
+ if entry.get("event_type") == "INIT":
813
+ task_id = entry.get("task_id", "")
814
+ last_status = entry.get("payload", {}).get("status", last_status)
815
+ elif entry.get("event_type") == "TRANSITION":
816
+ events.append(
817
+ {
818
+ "timestamp": entry.get("timestamp", ""),
819
+ "from": entry.get("payload", {}).get("from", ""),
820
+ "to": entry.get("payload", {}).get("to", last_status),
821
+ "reason": entry.get("payload", {}).get("reason", ""),
822
+ }
823
+ )
824
+ last_status = entry.get("payload", {}).get("to", last_status)
825
+ elif entry.get("from") is not None:
826
+ # Legacy journal line
827
+ task_id = entry.get("_task_id", task_id)
828
+ events.append(entry)
829
+ last_status = entry.get("to", last_status)
830
+ except (json.JSONDecodeError, OSError):
831
+ return None
832
+ if not events and not last_status:
833
+ return None
834
+ state = State(
835
+ task_id=task_id or "recovered",
836
+ status=last_status or "DRAFTED",
837
+ attempt=attempt,
838
+ changed_approaches=changed_approaches,
839
+ events=events,
840
+ evidence=evidence,
841
+ worker_results=worker_results,
842
+ data=data,
843
+ journal_dir=journal_dir,
844
+ )
845
+ return state
846
+
847
+
848
+ def save_state(state, path, backup=True):
849
+ """Persist state to a JSON file with atomic write and optional versioned backup.
850
+
851
+ Creates a timestamped backup before overwriting so previous states can be
852
+ reconstructed if the file is later corrupted. Writes tmp + fsync +
853
+ os.replace (atomic).
854
+ """
855
+ os.makedirs(os.path.dirname(path), exist_ok=True)
856
+ if backup and os.path.isfile(path):
857
+ backup_dir = os.path.join(os.path.dirname(path), "state_backups")
858
+ os.makedirs(backup_dir, exist_ok=True)
859
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%f")
860
+ backup_path = os.path.join(backup_dir, f"state.{ts}.bak.json")
861
+ shutil.copy2(path, backup_path)
862
+ tmp = path + ".tmp"
863
+ try:
864
+ with open(tmp, "w", encoding="utf-8") as f:
865
+ json.dump(state.to_dict(), f, indent=2, ensure_ascii=False)
866
+ f.flush()
867
+ os.fsync(f.fileno())
868
+ os.replace(tmp, path)
869
+ _fsync_dir(path)
870
+ except OSError as e:
871
+ raise StateError(f"failed to save state: {e}") from e