Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/os/IMPLEMENTATION_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
98 changes: 98 additions & 0 deletions docs/os/STATE_RECOVERY.md
Original file line number Diff line number Diff line change
@@ -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).
38 changes: 10 additions & 28 deletions phios/curiosity_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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] = []
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
37 changes: 12 additions & 25 deletions phios/mandala/ledger.py
Original file line number Diff line number Diff line change
@@ -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


Expand All @@ -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
5 changes: 3 additions & 2 deletions phios/memory/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions phios/memory/publisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
60 changes: 46 additions & 14 deletions phios/memory/store.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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]]:
Expand Down Expand Up @@ -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"]),
Expand Down Expand Up @@ -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
Loading
Loading