diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md index 62644044..7d8ac7ac 100644 --- a/docs/os/IMPLEMENTATION_STATUS.md +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -12,7 +12,7 @@ proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. | R3: Install current Python and UI packages | Candidate PKGBUILDs, JS lock and native pacman adapter | CI must build/install exact source packages; fixed Arch snapshot and signed upstream inputs | | R4: Real non-root graphical login and supervised services | Candidate Wayfire session and user service target | Live/VM qualification pending; no privileged browser or agent auto-start | | R5: Produce and UEFI boot exact live ISO | Candidate isolated Archiso/QEMU workflow | Exact ISO/source/hash/serial/screenshot evidence required; no ready claim until observed | -| R6: Recover durable private state | Pending | Concurrent writes, crash recovery, backup/restore, migrations | +| R6: Recover durable private state | Candidate locking/sync, transactional outbox and data-only recovery | Contention, interruption, backup/restore and schema refusal tests; installed reboot/power-loss evidence still required | | R7: Explicit blank-disk installation | Pending | Disposable VM install, boot without ISO, persistence | | R8: Whole-OS update and recovery | Pending | Signed artifacts, failed update recovery; app rollback is insufficient | | R9: Qualify hardware and one Linux governed workflow | Pending | Named hardware matrix and observed effect verification | diff --git a/docs/os/STATE_RECOVERY.md b/docs/os/STATE_RECOVERY.md new file mode 100644 index 00000000..c883c0d6 --- /dev/null +++ b/docs/os/STATE_RECOVERY.md @@ -0,0 +1,98 @@ +# Durable state and data recovery + +The packaged session selects `PHIOS_STATE_ROOT=$HOME/.local/state/phios`. +Memory uses `memory/canonical.sqlite3`, Spine uses `spine-v0.1/ledger`, and +Curiosity uses `curiosity`. Memory configuration is +`$XDG_CONFIG_HOME/phios/memory.json` (normally `~/.config/phios/memory.json`). +CLI processes inherit the same root. Outside the session, the existing +`~/.phios` location remains the legacy default. A relative or empty state-root +environment is an error. Legacy data is copied through backup/restore into a +new root; it is never silently moved or enabled. + +New files use mode 0600 and new directories 0700. Existing permissions are not +silently changed. Files must be caller-owned, regular, singly linked and not +writable by other users. POSIX traversal refuses symlinks at every ancestor. +These checks do not authenticate a human, isolate a malicious same-user process, +attest Windows ACLs or encrypt data. + +## Acknowledged writes + +Spine, Mandala and Curiosity JSONL writers hold an exclusive process lock, +validate history, write a complete record and sync file/directory before +returning. Readers hold a shared lock and reject malformed, duplicate-key, +non-finite, oversize and incomplete records. The per-record bound is 16 MiB. +Reading never repairs or discards evidence. A caught failed write truncates only +that unacknowledged append; a killed writer can leave an incomplete tail that +blocks normal reads and later writes. + +Memory transactions reserve the SQLite writer before reading idempotency keys +or revision heads, use FULL synchronization and close each connection. Outbox +publication is idempotent under the ledger lock. Publishing an older revision +cannot mark a newer pending revision readable. Binding, lease and run claim +files are synced before an executor can be entered. No permission or adapter +promotion follows from these changes. + +## Backup and restore + +Backups are private, unencrypted directories with a versioned manifest and +exact file hashes. Keep them under operator-controlled storage. The manifest +establishes internal integrity, not external authenticity. SQLite's online +backup API captures canonical database state; ledger capture can span a later +moment, recorded by the manifest's capture window. + +```sh +phi-state backup --state-root "$PHIOS_STATE_ROOT" --output "$HOME/phios-backup-001" +phi-state verify "$HOME/phios-backup-001" +phi-state restore "$HOME/phios-backup-001" --new-state-root "$HOME/.local/state/phios-restored" +``` + +Both operations require a new destination, including refusal of an existing +empty directory. Restore verifies all file hashes, SQLite structure, canonical +record hashes and exact published memory receipts before creating output. +Unknown backup/database schemas are held without speculative migration. +Failure preserves partial output for review and returns a nonzero status. + +| Data | Restore behavior | +| --- | --- | +| Canonical memory | New memory database; pending outbox stays pending | +| Published memory receipts | Exact receipts in the active Mandala ledger | +| Curiosity artifacts/pointers | Active data paths after zero-authority validation | +| Effect, approval, binding, lease and session history | `recovered-audit/`, outside active lookup paths | +| Claims, enabled configuration, credentials, caches and vector indexes | Excluded; no replay or enabling | + +Stop the old session before selecting a restored root. Review a disabled memory +configuration before enabling readers or reconciling a pending memory outbox. +Rebuild derived indexes explicitly. Historical authority stays historical; +restore creates no active decision, binding, lease or executor. + +## Interrupted final records + +Normal backup holds an incomplete tail. This explicit option preserves a +verified complete prefix and all original bytes in a new backup: + +```sh +phi-state backup --state-root "$PHIOS_STATE_ROOT" \ + --output "$HOME/phios-recovery-001" --preserve-incomplete-tail +phi-state verify "$HOME/phios-recovery-001" +``` + +The manifest lists incomplete audit files; original bytes are archived as +`.jsonl.bin` outside active paths. The original root remains untouched and held. +Malformed complete rows still fail. Published memory must retain its exact +valid receipt. After restore into a fresh root, a reviewed memory runtime can +reconcile pending canonical memory publication once. The option never resumes +an uncertain effect, infers a missing receipt or releases an old claim. Preserve +the original root and assess uncertain operations separately. + +## Qualification limits + +Focused tests cover contention, duplicate publication, disk-full interruption, +SIGKILL, backup/restore, hash tampering, authority injection and unknown schemas. +An installed-system lane must still prove no-ISO reboot and abrupt power-loss +recovery. Whole-OS recovery, hardware storage behavior, Windows custody and +agent isolation remain separate gates. A volatile live image loses its state +on reboot unless a verified backup has been copied off the image. + +References: [Python SQLite APIs](https://docs.python.org/3/library/sqlite3.html), +[SQLite transactions](https://www.sqlite.org/lang_transaction.html), and +[SQLite synchronization](https://www.sqlite.org/pragma.html#pragma_synchronous). diff --git a/phios/curiosity_store.py b/phios/curiosity_store.py index 746d244a..3c7e14f5 100644 --- a/phios/curiosity_store.py +++ b/phios/curiosity_store.py @@ -20,6 +20,7 @@ from typing import Any, Mapping from phios.curiosity import CuriosityArtifact +from phios.state_io import StateIntegrityError, append_jsonl, read_jsonl CURIOSITY_RETURN_POINTER_SCHEMA_VERSION = ( "phios.curiosity_return_pointer.v0.2" @@ -368,30 +369,14 @@ def __init__(self, root: Path) -> None: @staticmethod def _append_json(path: Path, payload: Mapping[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(_canonical_json(payload) + "\n") + append_jsonl(path, payload) @staticmethod def _read_jsonl(path: Path) -> list[object]: - if not path.exists(): - return [] - values: list[object] = [] - for index, line in enumerate( - path.read_text(encoding="utf-8").splitlines(), - start=1, - ): - if not line.strip(): - raise CuriosityStoreError( - f"blank line in append-only store at line {index}" - ) - try: - values.append(json.loads(line)) - except json.JSONDecodeError as exc: - raise CuriosityStoreError( - f"invalid JSON at {path.name}:{index}" - ) from exc - return values + try: + return list(read_jsonl(path)) + except StateIntegrityError as exc: + raise CuriosityStoreError(f"invalid JSON at {path.name}: {exc}") from exc def artifacts(self) -> list[CuriosityArtifact]: result: list[CuriosityArtifact] = [] @@ -422,8 +407,8 @@ def append_artifact(self, artifact: CuriosityArtifact) -> bool: digest = artifact.curiosity_artifact_sha256 if self.get_artifact(digest) is not None: return False - self._append_json(self.artifacts_path, artifact.to_dict()) - return True + return append_jsonl(self.artifacts_path, artifact.to_dict(), + identity_field="curiosity_artifact_sha256") def get_artifact( self, @@ -651,11 +636,8 @@ def append_return_pointer( for item in self.return_pointers() ): return False - self._append_json( - self.return_pointers_path, - pointer.to_dict(), - ) - return True + return append_jsonl(self.return_pointers_path, pointer.to_dict(), + identity_field="return_pointer_sha256") def latest_return_pointer( self, diff --git a/phios/mandala/ledger.py b/phios/mandala/ledger.py index d34cf660..a4bf9d2f 100644 --- a/phios/mandala/ledger.py +++ b/phios/mandala/ledger.py @@ -1,8 +1,9 @@ from __future__ import annotations -import json from pathlib import Path +from phios.state_io import append_jsonl, read_jsonl + from .receipts import ReceiptEnvelope @@ -13,44 +14,30 @@ def __init__(self, path: Path) -> None: self.path = path.expanduser() def append(self, receipt: ReceiptEnvelope) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - with self.path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(self.path, receipt.to_dict()) + + def append_if_absent(self, receipt: ReceiptEnvelope) -> bool: + """Publish exactly once across processes, refusing identity collisions.""" + return append_jsonl(self.path, receipt.to_dict(), identity_field="receipt_id") def recent(self, limit: int = 10) -> list[dict[str, object]]: if isinstance(limit, bool) or not isinstance(limit, int): raise TypeError("recent limit must be an integer") if limit < 0: raise ValueError("recent limit must be non-negative") - if limit == 0 or not self.path.exists(): + if limit == 0: return [] - lines = self.path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(self.path)[-limit:] def has_receipt(self, receipt_id: str) -> bool: """Return whether an exact receipt ID already exists in the append-only ledger.""" - if not self.path.exists(): - return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - try: - payload = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(payload, dict) and payload.get("receipt_id") == receipt_id: - return True - return False + return self.get_receipt(receipt_id) is not None def get_receipt(self, receipt_id: str) -> dict[str, object] | None: """Return the persisted receipt row for an exact receipt ID.""" - if not self.path.exists(): - return None - for line in self.path.read_text(encoding="utf-8").splitlines(): - try: - payload = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(payload, dict) and payload.get("receipt_id") == receipt_id: + for payload in read_jsonl(self.path): + if payload.get("receipt_id") == receipt_id: return payload return None diff --git a/phios/memory/cli.py b/phios/memory/cli.py index 6d60320d..25175467 100644 --- a/phios/memory/cli.py +++ b/phios/memory/cli.py @@ -7,6 +7,7 @@ from pathlib import Path from phios.mandala import OriginKind +from phios.state_paths import configured_state_root, memory_config_path from .config import MemoryRuntimeConfig, write_disabled_template from .legacy import plan_legacy_agent_memory_import @@ -15,8 +16,8 @@ from .operator import MemoryOperatorRuntime from .system_history import SystemHistoryPersistenceBridge -DEFAULT_CONFIG = Path.home() / ".phios" / "memory" / "config.json" -DEFAULT_STATE_ROOT = Path.home() / ".phios" / "memory" +DEFAULT_CONFIG = memory_config_path() +DEFAULT_STATE_ROOT = configured_state_root() / "memory" def build_parser() -> argparse.ArgumentParser: diff --git a/phios/memory/publisher.py b/phios/memory/publisher.py index 8e523f7f..a2c1a638 100644 --- a/phios/memory/publisher.py +++ b/phios/memory/publisher.py @@ -18,8 +18,7 @@ def publish_pending(self) -> int: published = 0 for payload in self.store.pending_receipts(): receipt = _receipt_from_payload(payload) - if not self.ledger.has_receipt(receipt.receipt_id): - self.ledger.append(receipt) + self.ledger.append_if_absent(receipt) self.store.mark_receipt_published(receipt.operation_id) published += 1 return published diff --git a/phios/memory/store.py b/phios/memory/store.py index fed943bf..97798c0a 100644 --- a/phios/memory/store.py +++ b/phios/memory/store.py @@ -1,13 +1,17 @@ from __future__ import annotations import json +import hashlib import sqlite3 +from contextlib import contextmanager from datetime import UTC, datetime from pathlib import Path -from typing import Any +from typing import Any, Iterator + +from phios.state_io import StateIntegrityError, prepare_state_file from .models import MemoryRecord -from .validation import strict_canonical_json +from .validation import sha256_json, strict_canonical_json SCHEMA_VERSION = 1 @@ -17,19 +21,36 @@ class MemoryStore: def __init__(self, path: Path) -> None: self.path = path.expanduser() - self.path.parent.mkdir(parents=True, exist_ok=True) + prepare_state_file(self.path) self._initialize() - def _connect(self) -> sqlite3.Connection: - conn = sqlite3.connect(self.path) - conn.row_factory = sqlite3.Row - conn.execute("PRAGMA foreign_keys = ON") - return conn + @contextmanager + def _connect(self) -> Iterator[sqlite3.Connection]: + conn = sqlite3.connect(self.path, timeout=30, isolation_level=None) + try: + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA synchronous = FULL") + # Acquire the writer reservation before reading an idempotency key + # or revision head, not after another writer can change it. + conn.execute("BEGIN IMMEDIATE") + yield conn + conn.commit() + except BaseException: + conn.rollback() + raise + finally: + conn.close() def _initialize(self) -> None: with self._connect() as conn: - conn.executescript( - """ + if conn.execute("SELECT 1 FROM sqlite_master WHERE name='store_metadata'").fetchone(): + prior = conn.execute( + "SELECT value FROM store_metadata WHERE key='schema_version'" + ).fetchone() + if prior is not None and int(prior["value"]) != SCHEMA_VERSION: + raise RuntimeError("unsupported governed-memory schema version") + schema = """ CREATE TABLE IF NOT EXISTS store_metadata ( key TEXT PRIMARY KEY, value TEXT NOT NULL @@ -71,7 +92,11 @@ def _initialize(self) -> None: status TEXT NOT NULL DEFAULT 'pending' ); """ - ) + # executescript implicitly commits in Python's legacy transaction + # mode. Execute this fixed DDL within the same held transaction. + for statement in schema.split(";"): + if statement.strip(): + conn.execute(statement) row = conn.execute( "SELECT value FROM store_metadata WHERE key='schema_version'" ).fetchone() @@ -196,8 +221,8 @@ def mark_receipt_published(self, operation_id: str) -> None: if payload.get("operation") in {"put", "revise"}: record_id = payload["record_versions"][0]["record_id"] conn.execute( - "UPDATE record_heads SET published=1 WHERE record_id=?", - (record_id,), + "UPDATE record_heads SET published=1 WHERE record_id=? AND revision=?", + (record_id, payload["record_versions"][0]["revision"]), ) def pending_receipts(self) -> list[dict[str, object]]: @@ -479,7 +504,7 @@ def _live_record_from_row( @staticmethod def _record_from_payload(payload: dict[str, Any]) -> MemoryRecord: - return MemoryRecord( + record = MemoryRecord( record_id=str(payload["record_id"]), revision=int(payload["revision"]), source_id=str(payload["source_id"]), @@ -507,3 +532,10 @@ def _record_from_payload(payload: dict[str, Any]) -> MemoryRecord: content_sha256=str(payload["content_sha256"]), record_sha256=str(payload["record_sha256"]), ) + body = record.to_dict() + body.pop("record_sha256") + if (record.to_dict() != payload or + hashlib.sha256(record.text.encode("utf-8")).hexdigest() != record.content_sha256 or + sha256_json(body) != record.record_sha256): + raise StateIntegrityError("canonical memory record integrity check failed") + return record diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index 9ff2d1b7..76f8afae 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -1,10 +1,11 @@ from __future__ import annotations -import json import os from pathlib import Path from typing import TYPE_CHECKING +from phios.state_io import append_jsonl, read_jsonl, sync_directory + from .models import ExecutionReceipt if TYPE_CHECKING: @@ -69,9 +70,7 @@ def __init__(self, path: Path) -> None: self.path = path.expanduser() def append(self, receipt: ExecutionReceipt) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - with self.path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(self.path, receipt.to_dict()) def recent(self, limit: int = 10) -> list[dict[str, object]]: if isinstance(limit, bool) or not isinstance(limit, int): @@ -80,16 +79,13 @@ def recent(self, limit: int = 10) -> list[dict[str, object]]: raise ValueError("recent limit must be non-negative") if limit == 0 or not self.path.exists(): return [] - lines = self.path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(self.path)[-limit:] def append_macro_receipt(self, receipt: "MacroSpineReceipt") -> None: """Append one immutable macro-to-Spine execution receipt.""" path = self.path.parent / "macro-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_receipts( self, @@ -104,8 +100,7 @@ def recent_macro_receipts( path = self.path.parent / "macro-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_dispatch_receipt( self, @@ -114,9 +109,7 @@ def append_macro_dispatch_receipt( """Append one immutable governed DO dispatch receipt.""" path = self.path.parent / "macro-dispatch-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_dispatch_receipts( self, @@ -135,8 +128,7 @@ def recent_macro_dispatch_receipts( path = self.path.parent / "macro-dispatch-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_run_journal_entry( self, @@ -145,9 +137,7 @@ def append_macro_run_journal_entry( """Append one immutable MacroRunState journal entry.""" path = self.path.parent / "macro-run-journal.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(entry.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, entry.to_dict()) def macro_run_journal_entries( self, @@ -160,8 +150,8 @@ def macro_run_journal_entries( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if run_id is None: return rows @@ -174,9 +164,7 @@ def append_macro_run_resume_receipt( """Append evidence for one validated MacroRun reconstruction.""" path = self.path.parent / "macro-run-resume-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_run_resume_receipts( self, @@ -195,8 +183,7 @@ def recent_macro_run_resume_receipts( path = self.path.parent / "macro-run-resume-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_macro_run_start_receipt( self, @@ -205,9 +192,7 @@ def append_macro_run_start_receipt( """Append one immutable macro run-start admission receipt.""" path = self.path.parent / "macro-run-start-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_macro_run_start_receipts( self, @@ -226,15 +211,14 @@ def recent_macro_run_start_receipts( path = self.path.parent / "macro-run-start-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def claim_macro_start_dedupe(self, dedupe_sha256: str) -> bool: """Atomically reserve one trigger/macro admission identity.""" self._validate_sha256(dedupe_sha256, "dedupe_sha256") claim_dir = self.path.parent / "macro-start-dedupe-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{dedupe_sha256}.claim" try: fd = os.open( @@ -246,6 +230,9 @@ def claim_macro_start_dedupe(self, dedupe_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(dedupe_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_macro_start_dedupe_claim(self, dedupe_sha256: str) -> None: @@ -258,13 +245,15 @@ def release_macro_start_dedupe_claim(self, dedupe_sha256: str) -> None: / f"{dedupe_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def claim_macro_run_id(self, run_id_sha256: str) -> bool: """Atomically reserve one requested macro run identity.""" self._validate_sha256(run_id_sha256, "run_id_sha256") claim_dir = self.path.parent / "macro-run-id-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{run_id_sha256}.claim" try: fd = os.open( @@ -276,6 +265,9 @@ def claim_macro_run_id(self, run_id_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(run_id_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_macro_run_id_claim(self, run_id_sha256: str) -> None: @@ -288,6 +280,8 @@ def release_macro_run_id_claim(self, run_id_sha256: str) -> None: / f"{run_id_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def append_schedule_service_state( self, @@ -296,9 +290,7 @@ def append_schedule_service_state( """Append one immutable schedule-service cursor/state entry.""" path = self.path.parent / "schedule-service-state.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(entry.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, entry.to_dict()) def schedule_service_state_entries( self, @@ -311,8 +303,8 @@ def schedule_service_state_entries( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -325,9 +317,7 @@ def append_schedule_service_poll_receipt( """Append one immutable schedule-service poll receipt.""" path = self.path.parent / "schedule-service-poll-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_schedule_service_poll_receipts( self, @@ -346,8 +336,7 @@ def recent_schedule_service_poll_receipts( path = self.path.parent / "schedule-service-poll-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_schedule_worker_lease( self, @@ -356,9 +345,7 @@ def append_schedule_worker_lease( """Append one immutable schedule-worker lease snapshot.""" path = self.path.parent / "schedule-worker-leases.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(lease.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, lease.to_dict()) def latest_schedule_worker_lease( self, @@ -371,8 +358,7 @@ def latest_schedule_worker_lease( if not path.exists(): return None latest: dict[str, object] | None = None - for line in path.read_text(encoding="utf-8").splitlines(): - row = json.loads(line) + for row in read_jsonl(path): if row.get("service_id") == service_id: latest = row return latest @@ -384,9 +370,7 @@ def append_schedule_worker_event( """Append one immutable worker ownership lifecycle event.""" path = self.path.parent / "schedule-worker-events.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(event.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, event.to_dict()) def schedule_worker_events( self, @@ -399,8 +383,8 @@ def schedule_worker_events( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -413,9 +397,7 @@ def append_schedule_worker_tick_receipt( """Append one immutable schedule-worker cycle receipt.""" path = self.path.parent / "schedule-worker-ticks.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def schedule_worker_tick_receipts( self, @@ -428,8 +410,8 @@ def schedule_worker_tick_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -463,11 +445,7 @@ def append_operator_log_revision( """Append one immutable operator-log revision.""" path = self.path.parent / "operator-log-revisions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(revision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, revision.to_dict()) def operator_log_revisions( self, @@ -480,8 +458,8 @@ def operator_log_revisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if note_id is None: return rows @@ -497,11 +475,7 @@ def append_ghostwalk_accepted_intent_revision( self.path.parent / "ghostwalk-accepted-intent-revisions.jsonl" ) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(revision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, revision.to_dict()) def ghostwalk_accepted_intent_revisions( self, @@ -517,8 +491,8 @@ def ghostwalk_accepted_intent_revisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -539,11 +513,7 @@ def append_ghostwalk_policy_admission_receipt( self.path.parent / "ghostwalk-policy-admission-receipts.jsonl" ) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def ghostwalk_policy_admission_receipts( self, @@ -559,8 +529,8 @@ def ghostwalk_policy_admission_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -578,11 +548,7 @@ def append_ghostwalk_authority_request( """Append one immutable Ghost-Walk authority request.""" path = self.path.parent / "ghostwalk-authority-requests.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(request.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, request.to_dict()) def ghostwalk_authority_requests( self, @@ -595,8 +561,8 @@ def ghostwalk_authority_requests( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is None: return rows @@ -614,11 +580,7 @@ def append_ghostwalk_authorization_decision( """Append one immutable Ghost-Walk authorization decision.""" path = self.path.parent / "ghostwalk-authorization-decisions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(decision.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, decision.to_dict()) def ghostwalk_authorization_decisions( self, @@ -631,8 +593,8 @@ def ghostwalk_authorization_decisions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if authority_request_sha256 is None: return rows @@ -650,11 +612,7 @@ def append_ghostwalk_executable_binding( """Append one immutable Ghost-Walk executable binding.""" path = self.path.parent / "ghostwalk-executable-bindings.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(binding.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, binding.to_dict()) def ghostwalk_executable_bindings( self, @@ -668,8 +626,8 @@ def ghostwalk_executable_bindings( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is not None: rows = [ @@ -694,11 +652,7 @@ def append_ghostwalk_action_lease_record( """Append one immutable Ghost-Walk ActionLease custody record.""" path = self.path.parent / "ghostwalk-action-lease-records.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(record.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, record.to_dict()) def ghostwalk_action_lease_records( self, @@ -713,8 +667,8 @@ def ghostwalk_action_lease_records( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if target_inference_receipt_sha256 is not None: rows = [ @@ -747,11 +701,7 @@ def append_ghostwalk_lease_execution_receipt( """Append one immutable Ghost-Walk leased execution receipt.""" path = self.path.parent / "ghostwalk-lease-execution-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def ghostwalk_lease_execution_receipts( self, @@ -764,8 +714,8 @@ def ghostwalk_lease_execution_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if action_lease_sha256 is None: return rows @@ -782,11 +732,7 @@ def append_phivessel_proposal( """Append one zero-authority PhiVessel proposal record.""" path = self.path.parent / "phivessel-proposals.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(proposal.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, proposal.to_dict()) def phivessel_proposals( self, @@ -799,8 +745,8 @@ def phivessel_proposals( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if work_id is None: return rows @@ -817,11 +763,7 @@ def append_interaction_guard_receipt( """Append one immutable GUI interaction guard receipt.""" path = self.path.parent / "interaction-guard-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(receipt.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, receipt.to_dict()) def recent_interaction_guard_receipts( self, @@ -840,8 +782,7 @@ def recent_interaction_guard_receipts( path = self.path.parent / "interaction-guard-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_session( self, @@ -850,9 +791,7 @@ def append_ghostwalk_session( """Append one immutable ghost-walk demonstration session.""" path = self.path.parent / "ghostwalk-sessions.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(session.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, session.to_dict()) def ghostwalk_sessions( self, @@ -865,8 +804,8 @@ def ghostwalk_sessions( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if session_id is None: return rows @@ -879,11 +818,7 @@ def append_ghostwalk_observation( """Append one immutable ghost-walk observation.""" path = self.path.parent / "ghostwalk-observations.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write( - json.dumps(observation.to_dict(), sort_keys=True) + "\n" - ) + append_jsonl(path, observation.to_dict()) def ghostwalk_observations( self, @@ -896,8 +831,8 @@ def ghostwalk_observations( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if session_id is None: return rows @@ -910,9 +845,7 @@ def append_ghostwalk_draft_receipt( """Append one immutable ghost-walk draft compilation receipt.""" path = self.path.parent / "ghostwalk-draft-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_ghostwalk_draft_receipts( self, @@ -931,8 +864,7 @@ def recent_ghostwalk_draft_receipts( path = self.path.parent / "ghostwalk-draft-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_capture_receipt( self, @@ -941,9 +873,7 @@ def append_ghostwalk_capture_receipt( """Append one immutable ghost-walk OS capture receipt.""" path = self.path.parent / "ghostwalk-capture-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_ghostwalk_capture_receipts( self, @@ -962,8 +892,7 @@ def recent_ghostwalk_capture_receipts( path = self.path.parent / "ghostwalk-capture-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_listener_receipt( self, @@ -972,9 +901,7 @@ def append_ghostwalk_listener_receipt( """Append one immutable Windows ghost-walk listener receipt.""" path = self.path.parent / "ghostwalk-listener-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_listener_receipts( self, @@ -987,8 +914,8 @@ def ghostwalk_listener_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if listener_id is None: return rows @@ -1031,9 +958,7 @@ def append_uia_element_snapshot( """Append one immutable privacy-bounded UIA element snapshot.""" path = self.path.parent / "uia-element-snapshots.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(snapshot.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, snapshot.to_dict()) def uia_element_snapshots( self, @@ -1046,8 +971,8 @@ def uia_element_snapshots( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if snapshot_sha256 is None: return rows @@ -1064,9 +989,7 @@ def append_uia_lookup_receipt( """Append one immutable Windows UIA semantic lookup receipt.""" path = self.path.parent / "uia-lookup-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_uia_lookup_receipts( self, @@ -1085,8 +1008,7 @@ def recent_uia_lookup_receipts( path = self.path.parent / "uia-lookup-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_semantic_revalidation_receipt( self, @@ -1095,9 +1017,7 @@ def append_semantic_revalidation_receipt( """Append one immutable semantic selector replay receipt.""" path = self.path.parent / "semantic-revalidation-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_semantic_revalidation_receipts( self, @@ -1116,8 +1036,7 @@ def recent_semantic_revalidation_receipts( path = self.path.parent / "semantic-revalidation-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_desktop_interaction_receipt( self, @@ -1126,9 +1045,7 @@ def append_desktop_interaction_receipt( """Append one immutable governed desktop interaction receipt.""" path = self.path.parent / "desktop-interaction-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_desktop_interaction_receipts( self, @@ -1147,8 +1064,7 @@ def recent_desktop_interaction_receipts( path = self.path.parent / "desktop-interaction-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_post_action_verification_receipt( self, @@ -1157,9 +1073,7 @@ def append_post_action_verification_receipt( """Append one immutable post-action verification receipt.""" path = self.path.parent / "post-action-verification-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_post_action_verification_receipts( self, @@ -1178,8 +1092,7 @@ def recent_post_action_verification_receipts( path = self.path.parent / "post-action-verification-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_ghostwalk_state_snapshot( self, @@ -1188,9 +1101,7 @@ def append_ghostwalk_state_snapshot( """Append one immutable before/after Ghost-Walk UI state snapshot.""" path = self.path.parent / "ghostwalk-ui-state-snapshots.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(snapshot.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, snapshot.to_dict()) def ghostwalk_state_snapshots( self, @@ -1203,8 +1114,8 @@ def ghostwalk_state_snapshots( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if action_observation_sha256 is None: return rows @@ -1222,9 +1133,7 @@ def append_transition_inference_receipt( """Append one immutable Ghost-Walk transition inference receipt.""" path = self.path.parent / "transition-inference-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_transition_inference_receipts( self, @@ -1243,8 +1152,7 @@ def recent_transition_inference_receipts( path = self.path.parent / "transition-inference-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def transition_inference_receipt( self, @@ -1256,8 +1164,7 @@ def transition_inference_receipt( path = self.path.parent / "transition-inference-receipts.jsonl" if not path.exists(): return None - for line in reversed(path.read_text(encoding="utf-8").splitlines()): - row = json.loads(line) + for row in reversed(read_jsonl(path)): if row.get("receipt_sha256") == receipt_sha256: return row return None @@ -1269,9 +1176,7 @@ def append_uia_state_observation_receipt( """Append one immutable bounded UIA state-observer receipt.""" path = self.path.parent / "uia-state-observer-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_uia_state_observation_receipts( self, @@ -1290,8 +1195,7 @@ def recent_uia_state_observation_receipts( path = self.path.parent / "uia-state-observer-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_transition_coordinator_receipt( self, @@ -1300,9 +1204,7 @@ def append_transition_coordinator_receipt( """Append one immutable Ghost-Walk transition coordinator receipt.""" path = self.path.parent / "transition-coordinator-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_transition_coordinator_receipts( self, @@ -1321,8 +1223,7 @@ def recent_transition_coordinator_receipts( path = self.path.parent / "transition-coordinator-receipts.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def append_baseline_refresh_receipt( self, @@ -1331,9 +1232,7 @@ def append_baseline_refresh_receipt( """Append one immutable Ghost-Walk baseline refresh receipt.""" path = self.path.parent / "baseline-refresh-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def baseline_refresh_receipts( self, @@ -1346,8 +1245,8 @@ def baseline_refresh_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if service_id is None: return rows @@ -1413,9 +1312,7 @@ def append_ghostwalk_host_receipt( """Append one immutable Ghost-Walk host lifecycle receipt.""" path = self.path.parent / "ghostwalk-host-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_host_receipts( self, @@ -1428,8 +1325,8 @@ def ghostwalk_host_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if host_id is None: return rows @@ -1495,9 +1392,7 @@ def append_ghostwalk_control_receipt( """Append one immutable Ghost-Walk control-surface receipt.""" path = self.path.parent / "ghostwalk-control-receipts.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def ghostwalk_control_receipts( self, @@ -1510,8 +1405,8 @@ def ghostwalk_control_receipts( if not path.exists(): return [] rows = [ - json.loads(line) - for line in path.read_text(encoding="utf-8").splitlines() + row + for row in read_jsonl(path) ] if surface_id is None: return rows @@ -1581,9 +1476,7 @@ def append_reconciliation( """Append one immutable reconciliation receipt beside execution history.""" path = self.path.parent / "execution-reconciliations.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(receipt.to_dict(), sort_keys=True) + "\n") + append_jsonl(path, receipt.to_dict()) def recent_reconciliations( self, @@ -1598,15 +1491,14 @@ def recent_reconciliations( path = self.path.parent / "execution-reconciliations.jsonl" if limit == 0 or not path.exists(): return [] - lines = path.read_text(encoding="utf-8").splitlines() - return [json.loads(line) for line in lines[-limit:]] + return read_jsonl(path)[-limit:] def claim_binding(self, binding_sha256: str) -> bool: """Atomically reserve one governed binding for an execution attempt.""" self._validate_binding_sha256(binding_sha256) claim_dir = self.path.parent / "binding-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{binding_sha256}.claim" try: fd = os.open( @@ -1618,6 +1510,9 @@ def claim_binding(self, binding_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(binding_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_binding_claim(self, binding_sha256: str) -> None: @@ -1630,14 +1525,15 @@ def release_binding_claim(self, binding_sha256: str) -> None: / f"{binding_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def has_consumed_binding(self, binding_sha256: str) -> bool: """Return true once a bound action reached an allowed executor attempt.""" if not self.path.exists(): return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - entry = json.loads(line) + for entry in read_jsonl(self.path): provenance = entry.get("governed_provenance") if not isinstance(provenance, dict): continue @@ -1654,7 +1550,7 @@ def claim_action_lease(self, lease_sha256: str) -> bool: self._validate_sha256(lease_sha256, "lease_sha256") claim_dir = self.path.parent / "action-lease-claims" - claim_dir.mkdir(parents=True, exist_ok=True) + claim_dir.mkdir(mode=0o700, parents=True, exist_ok=True) claim_path = claim_dir / f"{lease_sha256}.claim" try: fd = os.open( @@ -1666,6 +1562,9 @@ def claim_action_lease(self, lease_sha256: str) -> bool: return False with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(lease_sha256 + "\n") + handle.flush() + os.fsync(handle.fileno()) + sync_directory(claim_dir) return True def release_action_lease_claim(self, lease_sha256: str) -> None: @@ -1678,6 +1577,8 @@ def release_action_lease_claim(self, lease_sha256: str) -> None: / f"{lease_sha256}.claim" ) claim_path.unlink(missing_ok=True) + if claim_path.parent.exists(): + sync_directory(claim_path.parent) def has_consumed_action_lease(self, lease_sha256: str) -> bool: """Return true once an ActionLease reached an allowed executor attempt.""" @@ -1685,8 +1586,7 @@ def has_consumed_action_lease(self, lease_sha256: str) -> bool: self._validate_sha256(lease_sha256, "lease_sha256") if not self.path.exists(): return False - for line in self.path.read_text(encoding="utf-8").splitlines(): - entry = json.loads(line) + for entry in read_jsonl(self.path): provenance = entry.get("governed_provenance") if not isinstance(provenance, dict): continue diff --git a/phios/spine/runtime.py b/phios/spine/runtime.py index c33038dd..0bd2b205 100644 --- a/phios/spine/runtime.py +++ b/phios/spine/runtime.py @@ -62,6 +62,7 @@ SomaPerceptionService, TesseractOcrProvider, ) +from phios.state_paths import configured_state_root from .api_keys import ApiKeyBoundary from .collaborator import PhiVesselAdapter @@ -94,7 +95,7 @@ def __init__( allowed_permissions: Iterable[str] = (), task_id: str | None = None, ) -> None: - self.state_root = (state_root or Path.home() / ".phios" / "spine-v0.1").expanduser() + self.state_root = (state_root or configured_state_root() / "spine-v0.1").expanduser() allowed = tuple(dict.fromkeys(allowed_permissions)) self.registry = CapabilityRegistry() self.api_keys = ApiKeyBoundary() diff --git a/phios/state_io.py b/phios/state_io.py new file mode 100644 index 00000000..be8568fb --- /dev/null +++ b/phios/state_io.py @@ -0,0 +1,209 @@ +"""Durable JSONL I/O; receipt content and authority remain caller-owned. + +Writers serialize on the file inode, sync before acknowledging an append and +refuse corrupt/truncated history. Recovery is never an implicit read side effect. +""" +from __future__ import annotations + +import json +import importlib +import os +import stat +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator, Mapping + +MAX_RECORD_BYTES = 16 * 1024 * 1024 + + +def sync_directory(path: Path) -> None: + if os.name == "posix": + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +class StateIntegrityError(ValueError): + """State is unsafe or incomplete; preserve it for explicit recovery.""" + + +def _encode(payload: Mapping[str, Any]) -> bytes: + data = (json.dumps(dict(payload), sort_keys=True, ensure_ascii=False, + allow_nan=False) + "\n").encode("utf-8") + if len(data) > MAX_RECORD_BYTES: + raise ValueError("state record exceeds 16 MiB") + return data + + +def _object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise StateIntegrityError("duplicate JSON object key") + result[key] = value + return result + + +def _reject_constant(value: str) -> None: + raise StateIntegrityError(f"non-finite JSON value: {value}") + + +def _prefix(handle: Any, *, preserve_tail: bool) -> tuple[list[dict[str, Any]], bytes]: + handle.seek(0) + result: list[dict[str, Any]] = [] + number = 0 + while line := handle.readline(MAX_RECORD_BYTES + 1): + number += 1 + if len(line) > MAX_RECORD_BYTES: + raise StateIntegrityError(f"oversize state record at line {number}") + if not line.endswith(b"\n"): + if preserve_tail: + return result, line + raise StateIntegrityError(f"incomplete state record at line {number}") + try: + row = json.loads(line, object_pairs_hook=_object, parse_constant=_reject_constant) + except (ValueError, UnicodeError) as exc: + raise StateIntegrityError(f"invalid state record at line {number}: {exc}") from exc + if not isinstance(row, dict): + raise StateIntegrityError(f"state record at line {number} must be an object") + result.append(row) + return result, b"" + + +def _rows(handle: Any) -> list[dict[str, Any]]: + return _prefix(handle, preserve_tail=False)[0] + + +@contextmanager +def _parent(path: Path, *, create: bool) -> Iterator[int | None]: + """Walk POSIX parents without following symlinks, including ancestors.""" + if os.name != "posix": + for ancestor in (path, *path.parents): + if ancestor.is_symlink(): + raise StateIntegrityError("state paths cannot contain symlinks") + if create: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + yield None + return + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + parent = os.open(path.anchor, flags) + try: + for part in path.parts[1:-1]: + if create: + try: + os.mkdir(part, mode=0o700, dir_fd=parent) + except FileExistsError: + pass + else: + os.fsync(parent) + child = os.open(part, flags, dir_fd=parent) + os.close(parent) + parent = child + yield parent + finally: + os.close(parent) + + +@contextmanager +def _locked(path: Path, *, write: bool) -> Iterator[tuple[Any, int | None]]: + path = path.expanduser().absolute() + with _parent(path, create=write) as parent: + flags = os.O_RDWR if write or os.name == "nt" else os.O_RDONLY + flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + location: str | Path = path.name if parent is not None else path + options = {"dir_fd": parent} if parent is not None else {} + if write: + try: + fd = os.open(location, flags | os.O_CREAT | os.O_EXCL, 0o600, **options) + except FileExistsError: + fd = os.open(location, flags, **options) + else: + fd = os.open(location, flags, **options) + with os.fdopen(fd, "r+b" if write or os.name == "nt" else "rb", buffering=0) as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: + raise StateIntegrityError("state must be a regular file with one link") + if os.name == "posix": + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise StateIntegrityError("state owner or write permissions are unsafe") + import fcntl + fcntl.flock(fd, fcntl.LOCK_EX if write else fcntl.LOCK_SH) + else: + msvcrt = importlib.import_module("msvcrt") + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + try: + yield handle, parent + finally: + if os.name == "posix": + fcntl.flock(fd, fcntl.LOCK_UN) + else: + handle.seek(0) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + try: + with _locked(path, write=False) as (handle, _parent_fd): + return _rows(handle) + except FileNotFoundError: + return [] + + +def prepare_state_file(path: Path) -> None: + """Create a private regular file or validate an existing owned file.""" + with _locked(path, write=True) as (handle, parent): + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + + +def recoverable_jsonl_prefix(path: Path) -> tuple[list[dict[str, Any]], bytes]: + """Read an intact prefix and a final incomplete row; never modify/replay it. + + Malformed complete rows still fail. Only explicit recovery tooling should + call this, with the original bytes archived outside active runtime paths. + """ + try: + with _locked(path, write=False) as (handle, _parent_fd): + return _prefix(handle, preserve_tail=True) + except FileNotFoundError: + return [], b"" + + +def append_jsonl( + path: Path, payload: Mapping[str, Any], *, identity_field: str | None = None, +) -> bool: + data = _encode(payload) + if identity_field is not None and not isinstance(payload.get(identity_field), str): + raise ValueError("idempotent append requires a string identity") + with _locked(path, write=True) as (handle, parent): + history = _rows(handle) + if identity_field is not None: + matches = [row for row in history + if row.get(identity_field) == payload[identity_field]] + if matches: + if len(matches) != 1 or _encode(matches[0]) != data: + raise StateIntegrityError("receipt identity collision or duplicate history") + return False + handle.seek(0, os.SEEK_END) + start = handle.tell() + try: + remaining = memoryview(data) + while remaining: + written = os.write(handle.fileno(), remaining) + if written <= 0: + raise OSError("state write made no progress") + remaining = remaining[written:] + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + except BaseException: + # A caught I/O failure must not poison previously committed history. + # A killed process cannot reach this cleanup; its incomplete tail is + # instead detected and held by every later reader/writer. + os.ftruncate(handle.fileno(), start) + os.fsync(handle.fileno()) + raise + return True diff --git a/phios/state_paths.py b/phios/state_paths.py new file mode 100644 index 00000000..d21fddb3 --- /dev/null +++ b/phios/state_paths.py @@ -0,0 +1,24 @@ +"""Packaged Linux state location, with explicit legacy compatibility.""" +from __future__ import annotations + +import os +from pathlib import Path + + +def configured_state_root() -> Path: + value = os.environ.get("PHIOS_STATE_ROOT") + if value is None: + return Path.home() / ".phios" + path = Path(value).expanduser() + if not value.strip() or not path.is_absolute() or path == Path(path.anchor): + raise ValueError("PHIOS_STATE_ROOT must be an explicit absolute state directory") + return path + + +def memory_config_path() -> Path: + if "PHIOS_STATE_ROOT" not in os.environ: + return Path.home() / ".phios/memory/config.json" + value = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))).expanduser() + if not value.is_absolute(): + raise ValueError("XDG_CONFIG_HOME must be absolute") + return value / "phios/memory.json" diff --git a/phios/state_recovery.py b/phios/state_recovery.py new file mode 100644 index 00000000..998f2b6b --- /dev/null +++ b/phios/state_recovery.py @@ -0,0 +1,307 @@ +"""Verified data-only backup/restore into a fresh operator-owned state root.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import sqlite3 +import uuid +from contextlib import closing +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from phios.memory.models import MemoryRecord +from phios.memory.publisher import _receipt_from_payload +from phios.memory.store import SCHEMA_VERSION +from phios.curiosity_store import CuriosityStore +from phios.state_io import ( + StateIntegrityError, _locked, append_jsonl, prepare_state_file, read_jsonl, + recoverable_jsonl_prefix, sync_directory, +) +from phios.state_paths import configured_state_root + +FORMAT = "phios.data-backup.v1" +CANONICAL = "memory/canonical.sqlite3" +MEMORY_LEDGER = "spine-v0.1/ledger/mandala-receipts.jsonl" +DATA_FILES = {CANONICAL, MEMORY_LEDGER, "curiosity/artifacts.jsonl", "curiosity/return-pointers.jsonl"} + + +def _safe_root(root: Path) -> Path: + root = root.expanduser().absolute() + if not root.is_dir(): + raise ValueError("an existing owned state directory is required") + # A nonexistent child lets the shared directory walker check every ancestor. + try: + with _locked(root / "manifest.json", write=False): + pass + except FileNotFoundError: + pass + if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o022): + raise StateIntegrityError("state root owner or write permissions are unsafe") + return root + + +def _hash(path: Path) -> dict[str, Any]: + digest = hashlib.sha256() + with _locked(path, write=False) as (handle, _parent): + size = os.fstat(handle.fileno()).st_size + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return {"sha256": digest.hexdigest(), "size": size} + + +def _copy(source: Path, destination: Path) -> None: + with _locked(source, write=False) as (reader, _source_parent): + with _locked(destination, write=True) as (writer, parent): + for chunk in iter(lambda: reader.read(1024 * 1024), b""): + remaining = memoryview(chunk) + while remaining: + count = writer.write(remaining) + if not count: + raise OSError("backup copy made no progress") + remaining = remaining[count:] + os.fsync(writer.fileno()) + if parent is not None: + os.fsync(parent) + + +def _database(path: Path) -> list[tuple[dict[str, Any], bool]]: + # Validate both SQLite structural integrity and the domain's content hashes. + with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as conn: + conn.row_factory = sqlite3.Row + version = conn.execute("SELECT value FROM store_metadata WHERE key='schema_version'").fetchone() + if version is None or version[0] != str(SCHEMA_VERSION): + raise StateIntegrityError("unsupported canonical memory schema; no implicit migration") + if [row[0] for row in conn.execute("PRAGMA integrity_check")] != ["ok"]: + raise StateIntegrityError("canonical database integrity check failed") + if conn.execute("PRAGMA foreign_key_check").fetchone() is not None: + raise StateIntegrityError("canonical database foreign-key check failed") + for row in conn.execute("SELECT * FROM records"): + payload = json.loads(row["payload_json"]) + kwargs = dict(payload) + kwargs.pop("record_sha256") + kwargs.pop("content_sha256") + for field in ("provenance_refs", "derived_from", "transformation_lineage_sha256s", + "taint_labels", "contradicts"): + if field in kwargs: + kwargs[field] = tuple(kwargs[field]) + record = MemoryRecord.build(**kwargs) + if (record.to_dict() != payload or record.record_sha256 != row["record_sha256"] or + record.record_id != row["record_id"] or record.revision != row["revision"] or + record.source_id != row["source_id"] or record.scope_id != row["scope_id"] or + record.classification != row["classification"] or record.expires_at != row["expires_at"]): + raise StateIntegrityError("canonical record content or identity hash mismatch") + receipts: list[tuple[dict[str, Any], bool]] = [] + for row in conn.execute("SELECT * FROM receipt_outbox ORDER BY rowid"): + payload = json.loads(row["receipt_json"]) + receipt = _receipt_from_payload(payload).to_dict() + if (receipt["operation_id"] != row["operation_id"] or + receipt["action_authority"] is not False or receipt["execution_authority"] is not False): + raise StateIntegrityError("backup can restore only zero-authority memory receipts") + receipts.append((receipt, bool(row["published"]))) + return receipts + + +def _write_json(path: Path, payload: dict[str, Any]) -> None: + prepare_state_file(path) + with _locked(path, write=True) as (handle, parent): + data = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False).encode() + b"\n" + remaining = memoryview(data) + while remaining: + written = handle.write(remaining) + if not written: + raise OSError("metadata write made no progress") + remaining = remaining[written:] + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + + +def backup(source: Path, destination: Path, *, preserve_incomplete_tail: bool = False) -> dict[str, Any]: + source = _safe_root(source) + destination = destination.expanduser().absolute() + if destination.is_relative_to(source): + raise ValueError("backup destination must be outside the active state root") + destination.mkdir(mode=0o700) # no overwrite, including an empty existing directory + started = datetime.now(UTC).isoformat() + files: list[str] = [] + incomplete: list[str] = [] + + def capture_rows(path: Path, name: str) -> list[dict[str, Any]]: + rows, tail = recoverable_jsonl_prefix(path) + if tail and not preserve_incomplete_tail: + raise StateIntegrityError(f"incomplete audit tail in {name}; explicit preservation required") + if tail: + raw = "audit/" + name.replace("/", "-") + ".bin" + if raw not in files: + _copy(path, destination / raw) + files.append(raw) + incomplete.append(raw) + return rows + + db = source / CANONICAL + if db.exists(): + # Validate path custody, then use SQLite's online snapshot API rather + # than copying database/WAL bytes from a running process. + _hash(db) + target = destination / CANONICAL + prepare_state_file(target) + with closing(sqlite3.connect(db.as_uri() + "?mode=ro", uri=True, timeout=30)) as original: + with closing(sqlite3.connect(target)) as snapshot: + original.backup(snapshot) + with _locked(target, write=True) as (handle, parent): + os.fsync(handle.fileno()) + if parent is not None: + os.fsync(parent) + receipts = _database(target) + originals = capture_rows(source / MEMORY_LEDGER, "spine-ledger-mandala-receipts.jsonl") + for receipt, published in receipts: + matches = [row for row in originals if row.get("receipt_id") == receipt["receipt_id"]] + if published and (len(matches) != 1 or matches[0] != receipt): + raise StateIntegrityError("published canonical data lacks its exact durable receipt") + if matches and (len(matches) != 1 or matches[0] != receipt): + raise StateIntegrityError("canonical memory receipt collision") + if published: + append_jsonl(destination / MEMORY_LEDGER, receipt, identity_field="receipt_id") + prepare_state_file(destination / MEMORY_LEDGER) + files.extend([CANONICAL, MEMORY_LEDGER]) + for name in ["curiosity/artifacts.jsonl", "curiosity/return-pointers.jsonl"]: + path = source / name + if path.exists(): + rows = capture_rows(path, name) + prepare_state_file(destination / name) + for row in rows: + append_jsonl(destination / name, row) + files.append(name) + # All effect, decision, binding, lease and session evidence is archived + # outside active runtime paths. Claim markers and credentials are excluded. + ledger = source / "spine-v0.1/ledger" + if ledger.exists(): + for path in sorted(ledger.glob("*.jsonl")): + if re.fullmatch(r"[a-z0-9][a-z0-9-]{0,100}\.jsonl", path.name) is None: + raise StateIntegrityError("unexpected ledger filename") + name = "audit/" + path.name + rows = capture_rows(path, "spine-ledger-" + path.name) + prepare_state_file(destination / name) + for row in rows: + append_jsonl(destination / name, row) + files.append(name) + manifest = { + "schema_version": FORMAT, "canonical_schema_version": SCHEMA_VERSION, + "backup_id": str(uuid.uuid4()), "capture_started_at": started, + "capture_finished_at": datetime.now(UTC).isoformat(), + "authority_restored": False, "configuration_restored": False, + "derived_indexes_restored": False, "encrypted": False, + "incomplete_audit_files": sorted(set(incomplete)), + "files": {name: _hash(destination / name) for name in sorted(files)}, + } + _write_json(destination / "manifest.json", manifest) + sync_directory(destination.parent) + verify_backup(destination) + return manifest + + +def verify_backup(source: Path) -> dict[str, Any]: + source = _safe_root(source) + with _locked(source / "manifest.json", write=False) as (handle, _parent): + manifest = json.load(handle) + expected = {"schema_version", "canonical_schema_version", "backup_id", "capture_started_at", + "capture_finished_at", "authority_restored", "configuration_restored", + "derived_indexes_restored", "encrypted", "incomplete_audit_files", "files"} + if (not isinstance(manifest, dict) or set(manifest) != expected or + manifest["schema_version"] != FORMAT or manifest["canonical_schema_version"] != SCHEMA_VERSION or + any(manifest[key] is not False for key in ["authority_restored", "configuration_restored", + "derived_indexes_restored", "encrypted"])): + raise StateIntegrityError("unsupported or authority-bearing backup format") + files = manifest["files"] + if not isinstance(files, dict) or len(files) > 512: + raise StateIntegrityError("invalid backup inventory") + for name, identity in files.items(): + if not isinstance(name, str) or not (name in DATA_FILES or + re.fullmatch(r"audit/[a-z0-9][a-z0-9-]{0,150}\.jsonl(?:\.bin)?", name)): + raise StateIntegrityError("unexpected backup path") + if not isinstance(identity, dict) or set(identity) != {"sha256", "size"}: + raise StateIntegrityError("invalid backup file identity") + if (not isinstance(identity["sha256"], str) or + re.fullmatch(r"[0-9a-f]{64}", identity["sha256"]) is None or + type(identity["size"]) is not int or identity["size"] < 0): + raise StateIntegrityError("invalid backup hash or size") + if _hash(source / name) != identity: + raise StateIntegrityError(f"backup hash or size mismatch: {name}") + if name.endswith(".jsonl"): + read_jsonl(source / name) + if CANONICAL in files: + receipts = _database(source / CANONICAL) + expected_receipts = [receipt for receipt, published in receipts if published] + if MEMORY_LEDGER not in files or read_jsonl(source / MEMORY_LEDGER) != expected_receipts: + raise StateIntegrityError("active restored ledger must contain only exact published memory receipts") + elif MEMORY_LEDGER in files: + raise StateIntegrityError("a restored memory ledger requires its canonical database") + incomplete = manifest["incomplete_audit_files"] + if (not isinstance(incomplete, list) or + any(not isinstance(name, str) or not name.endswith(".jsonl.bin") or name not in files + for name in incomplete) or len(incomplete) != len(set(incomplete))): + raise StateIntegrityError("invalid incomplete-audit inventory") + curiosity = CuriosityStore(source / "curiosity") + targets = {item.curiosity_artifact_sha256 for item in curiosity.artifacts()} + if any(pointer.artifact_sha256 not in targets for pointer in curiosity.return_pointers()): + raise StateIntegrityError("curiosity return pointer has no verified artifact") + return manifest + + +def restore(source: Path, destination: Path) -> dict[str, Any]: + source = source.expanduser().absolute() + destination = destination.expanduser().absolute() + manifest = verify_backup(source) # no destination writes until all input checks pass + if destination.is_relative_to(source): + raise ValueError("restore destination must be outside the backup") + destination.mkdir(mode=0o700) + for name in manifest["files"]: + target = "recovered-" + name if name.startswith("audit/") else name + _copy(source / name, destination / target) + if CANONICAL in manifest["files"]: + _database(destination / CANONICAL) + receipt = {"schema_version": "phios.data-restore.v1", "backup_id": manifest["backup_id"], + "restore_id": str(uuid.uuid4()), "authority_restored": False, + "configuration_restored": False, "derived_indexes_restored": False, + "incomplete_audit_files": manifest["incomplete_audit_files"], + "canonical_schema_version": SCHEMA_VERSION, "release_ready": False} + _write_json(destination / "restored-state.json", receipt) + sync_directory(destination.parent) + return receipt + + +def main() -> int: + parser = argparse.ArgumentParser(prog="phi-state", description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + create = commands.add_parser("backup", help="Create a private data-only backup in a new directory") + create.add_argument("--state-root", type=Path, default=configured_state_root()) + create.add_argument("--output", type=Path, required=True) + create.add_argument("--preserve-incomplete-tail", action="store_true", + help="Archive incomplete final audit rows outside active paths; source stays held") + inspect = commands.add_parser("verify", help="Verify all backup hashes and canonical integrity") + inspect.add_argument("backup", type=Path) + recover = commands.add_parser("restore", help="Restore data into a fresh state root; authority stays held") + recover.add_argument("backup", type=Path) + recover.add_argument("--new-state-root", type=Path, required=True) + args = parser.parse_args() + try: + if args.command == "backup": + result = backup(args.state_root, args.output, + preserve_incomplete_tail=args.preserve_incomplete_tail) + elif args.command == "verify": + result = verify_backup(args.backup) + else: + result = restore(args.backup, args.new_state_root) + print(json.dumps(result, indent=2)) + return 0 + except (OSError, ValueError, TypeError, KeyError, sqlite3.Error) as exc: + print(f"State operation failed; preserve any partial destination for review: {exc}") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml index 93a0f4ba..6ebddc5a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,6 +56,7 @@ phi-memory = "phios.memory.cli:main" phi-ledger = "phios.ledger_reports.cli:main" phi-trust = "phios.trust_cli:main" phi-operator = "phios.ghostwalk_operator:main" +phi-state = "phios.state_recovery:main" [tool.setuptools] packages = ["phios", "phios.shell", "phios.core", "phios.display", "phios.desktop", "phios.adapters", "phios.services", "phios.templates", "phios.ml", "phios.mcp", "phios.mcp.resources", "phios.mcp.tools", "phios.mcp.prompts", "phios.spine", "phios.mandala", "phios.soma", "phios.reality", "phios.apps", "phios.memory", "phios.ledger_reports", "phios.reflex", "phios.reflex.providers", "phios.covenant", "phios.network"] diff --git a/tests/test_durable_state_v01.py b/tests/test_durable_state_v01.py new file mode 100644 index 00000000..60eb2b26 --- /dev/null +++ b/tests/test_durable_state_v01.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +import errno +import json +import os +import sqlite3 +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import pytest + +from phios.curiosity import CuriosityArtifact +from phios.curiosity_store import CuriosityStore +from phios.memory import MemoryOperatorRuntime, MemoryRecord, MemoryRuntimeConfig, MemoryStore +from phios.state_io import StateIntegrityError, append_jsonl, read_jsonl +from phios.state_paths import configured_state_root, memory_config_path +from phios.state_recovery import backup, restore, verify_backup + + +def test_concurrent_processes_preserve_exact_complete_records(tmp_path: Path) -> None: + path = tmp_path / "private" / "ledger.jsonl" + script = """ +import sys +from pathlib import Path +from phios.state_io import append_jsonl +for index in range(15): + append_jsonl(Path(sys.argv[1]), {"id": f"{sys.argv[2]}:{index}", "text": "α" * 8192}) +""" + children = [subprocess.Popen([sys.executable, "-c", script, str(path), str(i)]) + for i in range(4)] + for child in children: + assert child.wait(timeout=30) == 0 + rows = read_jsonl(path) + assert {row["id"] for row in rows} == {f"{i}:{j}" for i in range(4) for j in range(15)} + assert len(rows) == 60 + assert all(row["text"] == "α" * 8192 for row in rows) + assert path.stat().st_mode & 0o777 == 0o600 + assert path.parent.stat().st_mode & 0o777 == 0o700 + + +def test_concurrent_idempotent_publication_has_one_winner(tmp_path: Path) -> None: + path = tmp_path / "ledger.jsonl" + payload = {"receipt_id": "same", "effect_performed": False} + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map( + lambda _: append_jsonl(path, payload, identity_field="receipt_id"), range(32), + )) + assert sum(results) == 1 + assert read_jsonl(path) == [payload] + with pytest.raises(StateIntegrityError, match="collision"): + append_jsonl(path, {**payload, "effect_performed": True}, identity_field="receipt_id") + assert read_jsonl(path) == [payload] + + +def test_partial_disk_full_write_keeps_previously_acknowledged_history( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + path = tmp_path / "ledger.jsonl" + append_jsonl(path, {"id": "committed"}) + before = path.read_bytes() + original = os.write + count = 0 + + def interrupted(fd: int, data: bytes) -> int: + nonlocal count + count += 1 + if count == 1: + return original(fd, data[:5]) + raise OSError(errno.ENOSPC, "test disk is full") + + monkeypatch.setattr(os, "write", interrupted) + with pytest.raises(OSError, match="full"): + append_jsonl(path, {"id": "not-acknowledged"}) + assert path.read_bytes() == before + assert read_jsonl(path) == [{"id": "committed"}] + + +@pytest.mark.skipif(os.name != "posix", reason="SIGKILL qualification is POSIX-specific") +def test_killed_writer_leaves_a_detected_tail_and_cannot_silently_continue(tmp_path: Path) -> None: + path = tmp_path / "ledger.jsonl" + append_jsonl(path, {"id": "committed"}) + script = """ +import os, sys +from pathlib import Path +from phios.state_io import append_jsonl +original = os.write +def stop_mid_write(fd, data): + original(fd, data[:9]) + print("PARTIAL", flush=True) + os.read(0, 1) + raise RuntimeError("test must kill this process") +os.write = stop_mid_write +append_jsonl(Path(sys.argv[1]), {"id": "interrupted"}) +""" + child = subprocess.Popen([sys.executable, "-c", script, str(path)], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + try: + assert child.stdout is not None and child.stdout.readline().strip() == "PARTIAL" + finally: + child.kill() + child.wait(timeout=5) + evidence = path.read_bytes() + with pytest.raises(StateIntegrityError, match="incomplete"): + read_jsonl(path) + with pytest.raises(StateIntegrityError, match="incomplete"): + append_jsonl(path, {"id": "must-not-append"}) + assert path.read_bytes() == evidence + + +@pytest.mark.parametrize("content", [b'{}\nBROKEN\n{}\n', b'{"id":1,"id":2}\n', b'{"v":NaN}\n']) +def test_malformed_history_is_held_instead_of_skipped(tmp_path: Path, content: bytes) -> None: + path = tmp_path / "ledger.jsonl" + path.write_bytes(content) + with pytest.raises(StateIntegrityError): + read_jsonl(path) + with pytest.raises(StateIntegrityError): + append_jsonl(path, {"new": True}) + assert path.read_bytes() == content + + +def test_symlink_ancestors_and_hardlink_aliases_are_refused(tmp_path: Path) -> None: + real = tmp_path / "real" + real.mkdir() + alias = tmp_path / "alias" + alias.symlink_to(real, target_is_directory=True) + with pytest.raises((OSError, StateIntegrityError)): + append_jsonl(alias / "ledger.jsonl", {"id": "denied"}) + assert not (real / "ledger.jsonl").exists() + path = real / "ledger.jsonl" + append_jsonl(path, {"id": "original"}) + os.link(path, real / "second-link") + with pytest.raises(StateIntegrityError, match="one link"): + append_jsonl(path, {"id": "denied"}) + + +def _record(revision: int) -> MemoryRecord: + return MemoryRecord.build( + record_id="same-record", revision=revision, source_id="operator", source_kind="human", + provenance_refs=(), created_at="2026-09-30T00:00:00+00:00", scope_id="private", + classification="operator", retention_policy_id="retain", expires_at=None, + epistemic_kind="source", text=f"revision {revision}", + ) + + +def test_old_publication_never_publishes_a_newer_pending_revision(tmp_path: Path) -> None: + store = MemoryStore(tmp_path / "canonical.sqlite3") + for revision in [1, 2]: + record = _record(revision) + store.put_pending(record, operation_id=f"op-{revision}", request_sha256=str(revision) * 64, + receipt_json=json.dumps({"operation": "put", "record_versions": [ + {"record_id": record.record_id, "revision": revision}, + ]})) + store.mark_receipt_published("op-1") + assert store.get("same-record") is None + store.mark_receipt_published("op-2") + assert store.get("same-record") == _record(2) + + +def test_concurrent_memory_operation_retries_commit_once(tmp_path: Path) -> None: + store = MemoryStore(tmp_path / "canonical.sqlite3") + record = _record(1) + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda _: store.put_pending( + record, operation_id="same-operation", request_sha256="a" * 64, receipt_json="{}", + ), range(24))) + assert sum(results) == 1 + assert len(store.pending_receipts()) == 1 + + +def test_unknown_schema_is_refused_before_any_schema_change(tmp_path: Path) -> None: + path = tmp_path / "canonical.sqlite3" + with sqlite3.connect(path) as conn: + conn.executescript("CREATE TABLE store_metadata(key TEXT PRIMARY KEY, value TEXT);" + "INSERT INTO store_metadata VALUES('schema_version', '999');") + before = path.read_bytes() + with pytest.raises(RuntimeError, match="unsupported"): + MemoryStore(path) + assert path.read_bytes() == before + + +def _seed(root: Path) -> MemoryOperatorRuntime: + runtime = MemoryOperatorRuntime( + state_root=root / "memory", + config=MemoryRuntimeConfig(enabled=True, principal_id="operator", scopes=("private",), + classifications=("operator",), retention_policy_id="retain"), + allowed_permissions=("memory.write", "memory.read"), + ) + assert runtime.put(_record(1), operation_id="put-1", task_id="test-data").status == "ok" + return runtime + + +def _reidentify(directory: Path, name: str) -> None: + import hashlib + path = directory / "manifest.json" + manifest = json.loads(path.read_text()) + data = (directory / name).read_bytes() + manifest["files"][name] = {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)} + path.write_text(json.dumps(manifest)) + + +def test_backup_restore_preserves_data_without_replaying_authority(tmp_path: Path) -> None: + root = tmp_path / "state" + runtime = _seed(root) + artifact = CuriosityArtifact.build( + artifact_kind="question", title="Recovery", content="Can this data survive a crash?", + created_at="2026-09-30T00:00:00+00:00", created_by="operator", + ) + CuriosityStore(root / "curiosity").append_artifact(artifact) + active_authority = root / "spine-v0.1/ledger/ghostwalk-authorization-decisions.jsonl" + append_jsonl(active_authority, {"receipt_id": "historical-only", "execution_authority": True}) + (root / "credentials.json").write_text("a credential must not be included") + saved = tmp_path / "backup" + manifest = backup(root, saved) + assert verify_backup(saved) == manifest + recovered = tmp_path / "restored" + receipt = restore(saved, recovered) + assert receipt["authority_restored"] is False + assert receipt["configuration_restored"] is False + assert not (recovered / "credentials.json").exists() + assert not (recovered / "spine-v0.1/ledger/ghostwalk-authorization-decisions.jsonl").exists() + assert (recovered / "recovered-audit/ghostwalk-authorization-decisions.jsonl").is_file() + store = MemoryStore(recovered / "memory/canonical.sqlite3") + assert store.get("same-record") == runtime.store.get("same-record") + assert CuriosityStore(recovered / "curiosity").artifacts() == [artifact] + assert recovered.stat().st_mode & 0o777 == 0o700 + with pytest.raises(FileExistsError): + restore(saved, recovered) + + +def test_corrupt_backup_is_rejected_before_destination_creation(tmp_path: Path) -> None: + _seed(tmp_path / "state") + saved = tmp_path / "backup" + backup(tmp_path / "state", saved) + path = saved / "memory/canonical.sqlite3" + path.write_bytes(b"corrupt") + with pytest.raises(StateIntegrityError, match="hash"): + restore(saved, tmp_path / "must-not-exist") + assert not (tmp_path / "must-not-exist").exists() + + +def test_rehashed_unknown_schema_is_held_without_implicit_migration(tmp_path: Path) -> None: + _seed(tmp_path / "state") + saved = tmp_path / "backup" + backup(tmp_path / "state", saved) + with sqlite3.connect(saved / "memory/canonical.sqlite3") as conn: + conn.execute("UPDATE store_metadata SET value='999' WHERE key='schema_version'") + _reidentify(saved, "memory/canonical.sqlite3") + with pytest.raises(StateIntegrityError, match="unsupported"): + restore(saved, tmp_path / "must-not-exist") + assert not (tmp_path / "must-not-exist").exists() + + +def test_logically_corrupt_canonical_data_cannot_be_read_as_a_valid_record(tmp_path: Path) -> None: + runtime = _seed(tmp_path / "state") + with runtime.store._connect() as conn: + row = conn.execute("SELECT payload_json FROM records").fetchone() + payload = json.loads(row[0]) + payload["text"] = "tampered text retaining the original hashes" + conn.execute("UPDATE records SET payload_json=?", (json.dumps(payload),)) + with pytest.raises(StateIntegrityError, match="integrity"): + runtime.store.get("same-record") + + +def test_rehashed_authority_injection_cannot_enter_active_restored_ledger(tmp_path: Path) -> None: + _seed(tmp_path / "state") + saved = tmp_path / "backup" + backup(tmp_path / "state", saved) + name = "spine-v0.1/ledger/mandala-receipts.jsonl" + append_jsonl(saved / name, {"receipt_id": "injected", "execution_authority": True}) + _reidentify(saved, name) + with pytest.raises(StateIntegrityError, match="only exact published memory"): + restore(saved, tmp_path / "must-not-exist") + assert not (tmp_path / "must-not-exist").exists() + + +def test_tail_recovery_preserves_raw_evidence_and_reconciles_pending_memory(tmp_path: Path) -> None: + root = tmp_path / "state" + runtime = _seed(root) + # Simulate termination after a receipt append but before marking the outbox. + with runtime.store._connect() as conn: + conn.execute("UPDATE receipt_outbox SET published=0") + conn.execute("UPDATE record_heads SET published=0") + original = runtime.ledger.path.read_bytes() + b'{"receipt_id":"interrupted' + runtime.ledger.path.write_bytes(original) + with pytest.raises(StateIntegrityError, match="incomplete"): + backup(root, tmp_path / "held-backup") + saved = tmp_path / "salvage-backup" + manifest = backup(root, saved, preserve_incomplete_tail=True) + assert manifest["incomplete_audit_files"] == ["audit/spine-ledger-mandala-receipts.jsonl.bin"] + assert runtime.ledger.path.read_bytes() == original + assert (saved / manifest["incomplete_audit_files"][0]).read_bytes() == original + recovered = tmp_path / "restored" + restore(saved, recovered) + resumed = MemoryOperatorRuntime(state_root=recovered / "memory", config=runtime.config, + allowed_permissions=("memory.read",)) + assert resumed.publisher.publish_pending() == 1 + assert resumed.store.get("same-record") == _record(1) + assert len(resumed.ledger.recent()) == 1 + assert resumed.publisher.publish_pending() == 0 + assert runtime.ledger.path.read_bytes() == original + + +def test_packaged_and_legacy_paths_require_explicit_state_selection(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("PHIOS_STATE_ROOT", raising=False) + assert configured_state_root() == Path.home() / ".phios" + monkeypatch.setenv("PHIOS_STATE_ROOT", "/home/operator/.local/state/phios") + monkeypatch.setenv("XDG_CONFIG_HOME", "/home/operator/.config") + assert configured_state_root() == Path("/home/operator/.local/state/phios") + assert memory_config_path() == Path("/home/operator/.config/phios/memory.json") + monkeypatch.setenv("PHIOS_STATE_ROOT", "relative/path") + with pytest.raises(ValueError, match="absolute"): + configured_state_root()