diff --git a/README.md b/README.md index 2f205b5a..61f6e5d8 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) [![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3721-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3795-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,721 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,795 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked diff --git a/bin/mind-palace b/bin/mind-palace index 18e6b9aa..049c52eb 100755 --- a/bin/mind-palace +++ b/bin/mind-palace @@ -22,6 +22,8 @@ mind-palace [args...] — run from any directory DAY-TO-DAY start | stop | status | reset [--force|--confirm] the supervised lifecycle (scripts/palace.py) + destroy [--confirm] remove a named instance, its open content cached + cache [fill|prune] [--confirm] the shared cache (~/.mind-palace/cache) talk [--offline] interactive chat (--offline = no-Ollama demo) monitor run the dashboard/chat HTTP server standalone sandbox [--input NAME=PATH] [--timeout N] run code in the powerless sandbox @@ -66,7 +68,7 @@ if [ "$#" -gt 0 ]; then shift; fi case "$verb" in ""|help|-h|--help) usage ;; - start|stop|status|reset|deploy) py "$SCRIPTS/palace.py" "$verb" "$@" ;; + start|stop|status|reset|destroy|cache|deploy) py "$SCRIPTS/palace.py" "$verb" "$@" ;; dream|relate|lanes|reembed|vault-sync|embed|dialogue-sync|tick|queue|query|ingest-chat|code-seed|code-backfill|code-rebuild) py "$SCRIPTS/palace.py" "$verb" "$@" ;; stack) py "$SCRIPTS/stack.py" "$@" ;; diff --git a/config/defaults.toml b/config/defaults.toml index 0e533104..750ac072 100644 --- a/config/defaults.toml +++ b/config/defaults.toml @@ -131,8 +131,10 @@ overlap_chars = 150 # ingress's table, a stream of items its edge reader (`edge/corpus/`) writes under `root//` # and `sync_corpus.palace` lands a batch at a time, observed, at `corpus//`. Off for the # default instance, which declares no source; a named instance turns it on in its own overlay. -# `root` resolves against the instance's root (a named instance's may not leave it). `batch` is -# the items one request lands; the runner sizes it, the script takes it as its argument. +# `root` resolves against the instance's root (a named instance's may not leave it; the corpus +# instance's root is `~/.mind-palace/instances/corpus`, so its streams are under +# `~/.mind-palace/instances/corpus/sources`). `batch` is the items one request lands; the runner +# sizes it, the script takes it as its argument. enabled = false root = "data/corpus" sources = [] diff --git a/config/instances/corpus.toml b/config/instances/corpus.toml index 8e88232b..8272104e 100644 --- a/config/instances/corpus.toml +++ b/config/instances/corpus.toml @@ -3,9 +3,15 @@ # # Selected by `MIND_PALACE_OVERLAY=config/instances/corpus.toml`. A named overlay replaces the whole # per-machine chain, so nothing of Ouroboros's `ouroboros.toml` or `levers.toml` reaches this -# instance, and every namespace it holds (data, spools, locks, identities, the corpus streams) is -# derived from its id under `/instances/corpus/` (DI-2). It declares no vault, no transcripts -# and no code agent, so it reads none of the default instance's sources. +# instance, and every namespace it holds (data, spools, locks, identities, the corpus streams) lies +# under its root (DI-2). It declares no vault, no transcripts and no code agent, so it reads none of +# the default instance's sources. +# +# Its root is its own, outside every checkout and worktree (dn-instance-lifecycle §7): the data was +# moved to `~/.mind-palace/instances/corpus` on 2026-11-11, and the old location, `instances/corpus` +# in the corpus stage-1 worktree, is a symbolic link to it. It is a dataset other instances draw on +# (read only, in place, or through the shared cache once `palace cache fill` has run under this +# overlay) and the fixture for regression and stress runs. # # It has one writer, `scripts/corpus.py ingest`, a process its operator starts and stops; no # LaunchAgent is installed for it and no daemon tick runs it. The edge readers (`edge/corpus/`) @@ -14,6 +20,7 @@ [instance] id = "corpus" +root = "~/.mind-palace/instances/corpus" # The stack's embedder, shared with the default instance's daemon when that runs: the runner # yields to other callers (dn-corpus-instance §5.1). diff --git a/core/ingest/derive.py b/core/ingest/derive.py index 0e43635b..2dcf31a6 100644 --- a/core/ingest/derive.py +++ b/core/ingest/derive.py @@ -80,11 +80,12 @@ class DrainReport: left: int = 0 seconds: float = 0.0 cut: int = 0 # texts the embedder took only a prefix of (`embed_fitting`) + cached: int = 0 # atoms taken from the shared cache instead of the embedder def __str__(self) -> str: return (f"{self.items} item(s), {self.chunks} chunk(s), {self.embedded} embedded, " - f"{self.reused} reused, {self.empty} empty, {self.left} left pending, " - f"{self.cut} cut, {self.seconds:.1f}s") + f"{self.reused} reused, {self.cached} cached, {self.empty} empty, " + f"{self.left} left pending, {self.cut} cut, {self.seconds:.1f}s") def pending(catalog: Any, plane: Any, *, lexical: Any | None = None, @@ -144,17 +145,28 @@ def canonical_chunks(record: IngestRecord) -> list[Chunk]: def embed_missing(plane: Any, embedder: Any, texts: Sequence[str], *, batch: int = 64, - streams: int = 1) -> tuple[dict[str, list[float]], int, int]: + streams: int = 1, cache: Any = None, + ) -> tuple[dict[str, list[float]], int, int, int]: """Embed the distinct texts whose atoms the plane does not hold, `batch` a request and `streams` requests in flight at once, a text the server refuses for its length cut to fit (`embed_fitting`, which the embedder applies to every request; it is applied again here for an - embedder object that does not). Returns `{atom id: vector}`, how many atoms the plane held - already, and how many texts were cut, by either.""" + embedder object that does not). An atom the plane lacks is first looked up in the shared + cache under the instance's embedder key (`cache`, a `VectorCache`; dn-instance-lifecycle + §6.5) and taken from it when found. Returns `{atom id: vector}`, how many atoms the plane held + already, how many texts were cut, by either, and how many vectors the cache gave.""" wanted = {plane_atom_id(t): t for t in dict.fromkeys(texts)} known = set(plane.known_atoms(list(wanted))) todo = [(a, t) for a, t in wanted.items() if a not in known] if not todo: - return {}, len(known), 0 + return {}, len(known), 0, 0 + found: dict[str, list[float]] = cache.vectors([a for a, _ in todo]) if cache is not None \ + else {} + dim = getattr(plane, "dim", None) + if isinstance(dim, int): # a vector of another width is not this plane's geometry + found = {a: v for a, v in found.items() if len(v) == dim} + todo = [(a, t) for a, t in todo if a not in found] + if not todo: + return dict(found), len(known), 0, len(found) groups = [todo[i:i + batch] for i in range(0, len(todo), batch)] before = getattr(embedder, "cut", None) @@ -177,7 +189,8 @@ def one(group: list[tuple[str, str]]) -> tuple[list[tuple[str, list[float]]], in cut += n if isinstance(before, int): cut += int(getattr(embedder, "cut", before)) - before # the embedder's own cuts - return out, len(known), cut + out.update(found) + return out, len(known), cut, len(found) def drain(stores: Any, *, batch: int = 64, streams: int = 1, max_items: int | None = None, @@ -212,23 +225,25 @@ def derive_entries(stores: Any, entries: Iterable[CatalogEntry], *, batch: int = again, which the plane's landing reconciles to nothing, and one with no chunk is counted empty.""" start = clock() - items = chunks = embedded = reused = empty = cut = 0 + items = chunks = embedded = reused = empty = cut = cached = 0 group: list[tuple[IngestRecord, list[Chunk]]] = [] size = 0 target = max(1, batch * max(1, streams)) + vcache = getattr(stores, "cache", None) def flush() -> None: - nonlocal items, chunks, embedded, reused, cut, group, size + nonlocal items, chunks, embedded, reused, cut, cached, group, size if not group: return texts = [c.text for _, cs in group for c in cs] - fresh, held, n_cut = embed_missing(stores.plane, stores.embedder, texts, batch=batch, - streams=streams) + fresh, held, n_cut, n_cached = embed_missing(stores.plane, stores.embedder, texts, + batch=batch, streams=streams, cache=vcache) rows = [_chunk_row(r, c, fresh.get(plane_atom_id(c.text))) for r, cs in group for c in cs] stores.plane.add(rows) # the key: the occupancy, last items += len(group) chunks += len(rows) - embedded += len(fresh) + embedded += len(fresh) - n_cached + cached += n_cached reused += held cut += n_cut if landed is not None: @@ -247,7 +262,7 @@ def flush() -> None: flush() flush() return DrainReport(items=items, chunks=chunks, embedded=embedded, reused=reused, empty=empty, - seconds=clock() - start, cut=cut) + seconds=clock() - start, cut=cut, cached=cached) # ── the lexical index's own backfill ─────────────────────────────────────────────────────────── diff --git a/core/ingest/purge.py b/core/ingest/purge.py index fea3b55b..415658f1 100644 --- a/core/ingest/purge.py +++ b/core/ingest/purge.py @@ -14,14 +14,22 @@ On success it drops derived rows, removes the raw blob, and deletes the tombstoned catalog rows for that digest. `scripts/purge_raw.py` is the owner-facing entry. + +A purge reaches the shared cache too (dn-instance-lifecycle §6.6), so the cache is no way around +erasure: before the raw object is deleted its chunks are derived again, as the landing derived +them, and the cache loses the raw object and the vector of every atom of those chunks under every +embedder key; the digest is recorded there, so no later fill or destroy puts it back. """ from __future__ import annotations from dataclasses import dataclass +from typing import Any +from core.kernel.ingest.pipeline import derive_chunks from core.kernel.stores.rawstore import RawStore from core.stores.catalog import VaultCatalog +from core.stores.plane import atom_id from core.stores.vectorstore import VectorStore @@ -34,6 +42,8 @@ class PurgeResult: digest: str raw_removed: bool paths_removed: tuple[str, ...] + cache_raw_removed: bool = False + cache_vectors_removed: int = 0 def purge_raw( @@ -43,6 +53,7 @@ def purge_raw( store: VectorStore, catalog: VaultCatalog, confirm: bool = False, + cache: Any = None, ) -> PurgeResult: """Permanently remove a note's raw bytes + derived rows. Owner-gated; see module docstring.""" if not confirm: @@ -56,7 +67,16 @@ def purge_raw( ) paths = tuple(catalog.paths_for_digest(digest)) # all tombstoned at this point + forgot = None + if cache is not None: + # the shared cache first, while the bytes that name its atoms are still here: the atoms of + # the chunks the landing derived (`derive_chunks`, the one raw→chunks derivation) + data = raw.get(digest) if raw.exists(digest) else cache.raw(digest) + atoms = [atom_id(c.text) for c in derive_chunks(data)] if data is not None else [] + forgot = cache.forget(digest, atoms) store.delete(digest=digest) # derived (idempotent; usually already gone) raw_removed = raw.delete(digest) # the irreversible step catalog.remove_digest(digest) - return PurgeResult(digest=digest, raw_removed=raw_removed, paths_removed=paths) + return PurgeResult(digest=digest, raw_removed=raw_removed, paths_removed=paths, + cache_raw_removed=bool(forgot and forgot.raw_removed), + cache_vectors_removed=forgot.vectors_removed if forgot else 0) diff --git a/core/ingest/writer.py b/core/ingest/writer.py index 8d01a98f..5888a586 100644 --- a/core/ingest/writer.py +++ b/core/ingest/writer.py @@ -33,7 +33,7 @@ from dataclasses import dataclass, field from typing import Any -from core.ingest.derive import EMBED_JOB, HOLDS +from core.ingest.derive import EMBED_JOB, HOLDS, LexicalReport, derive_lexical from core.ingest.index import index_amendment, index_batch from core.ingest.landing import ( attest_once, @@ -75,6 +75,9 @@ class Stores: # the lexical index (dn-two-phase-ingestion D1): landed beside the raw object whenever it is # open, and the UNCHANGED check's witness in place of the plane's rows under lazy embedding lexical: Any | None = None + # the shared cache's vectors under the instance's embedder key (dn-instance-lifecycle §6.5): + # the vector drain takes an atom the plane lacks from it before it calls the embedder + cache: Any | None = None @dataclass(frozen=True) @@ -203,6 +206,7 @@ def lexical_witness(self, path: str) -> bool: return self.lazy or not self.keeps_vectors(path) def land(self, plan: Sequence[Effect]) -> list[Outcome]: + self.heal_lexical() self.price(plan) if self.batch and batchable(plan): out = self.land_batch(plan) @@ -218,6 +222,25 @@ def land(self, plan: Sequence[Effect]) -> list[Outcome]: self.derive_later() return out + def heal_lexical(self) -> LexicalReport | None: + """Re-derive a stale lexical index before anything lands (dn-instance-lifecycle §5). + + An index whose units another tokenizer made refuses to land (`TokenizerMismatch`), and the + embed job that would re-derive it is asked for only after a landing succeeds, so nothing + healed it unasked: on 2026-11-11 every repository sync of the code instance stopped at the + index until it was re-derived by hand. Every landing passes here, so the writer resets such + an index and lands every active item of the lexical classes again under the current + tokenizer (`derive_lexical`), then lands the plan. Timed as the `rederive` stage. Returns + what the re-derivation did, or None when the index was current or not open.""" + lexical = self.stores.lexical + if lexical is None or not getattr(lexical, "stale", False): + return None + start = time.perf_counter() + report = derive_lexical(self.stores, max_chars=self.max_chars, + overlap_chars=self.overlap_chars) + self.timing["rederive"] = self.timing.get("rederive", 0.0) + time.perf_counter() - start + return report + def derive_later(self) -> None: """Ask for the embed drain once a plan has landed an item without its vector: one job of the queue's coalescing kind, folded into the row already waiting if there is one, under no diff --git a/core/kernel/stores/rawstore.py b/core/kernel/stores/rawstore.py index 36a8a20b..f89554e7 100644 --- a/core/kernel/stores/rawstore.py +++ b/core/kernel/stores/rawstore.py @@ -10,6 +10,7 @@ from __future__ import annotations import hashlib +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path @@ -17,6 +18,10 @@ @dataclass class RawStore: root: Path + # Where a miss is looked up before it raises (dn-instance-lifecycle §6.5): the shared cache's + # object by digest. What it returns is checked against the digest here as well, and only then + # copied in, so the address is the whole trust decision. None: a miss raises, as it always did. + fallback: Callable[[str], bytes | None] | None = None def __post_init__(self) -> None: self.root.mkdir(parents=True, exist_ok=True) @@ -43,7 +48,13 @@ def add_text(self, text: str) -> tuple[str, bool]: return self.add(text.encode("utf-8")) def get(self, digest: str) -> bytes: - return self._path(digest).read_bytes() + p = self._path(digest) + if not p.exists() and self.fallback is not None: + data = self.fallback(digest) + if data is not None and hashlib.sha256(data).hexdigest() == digest: + self.add(data) + return data + return p.read_bytes() def exists(self, digest: str) -> bool: return self._path(digest).exists() diff --git a/core/relations.py b/core/relations.py index 20663032..a088ab56 100644 --- a/core/relations.py +++ b/core/relations.py @@ -35,7 +35,7 @@ from core.kernel.complex_types import EdgeSign from core.kernel.config import Config, get_config from core.kernel.constitution import Message -from core.kernel.ingest.logseq import _LINK, parse_note +from core.kernel.ingest.logseq import _LINK, _decode, parse_text from core.kernel.provenance import Provenance from core.stores.vectorstore import open_vector_store @@ -119,6 +119,10 @@ class RelationDetector: vectors: Rows chat: Callable[[list[Message]], str] | None = None # None = authored edges only max_pairs: int = 24 + # The raw store the authored edges are parsed from, by each note's catalog digest + # (dn-instance-lifecycle §3.3 step 6): the edges are a function of the landed bytes, so a reset + # rebuilds them without the vault. None reads each note's vault file, as before. + raw: Any = None def notes(self) -> list[Note]: """Active authored-solo notes that exist on disk, oldest first.""" @@ -134,13 +138,13 @@ def notes(self) -> list[Note]: # authored --------------------------------------------------------------------------------- def authored(self, notes: list[Note]) -> int: by_title = {n.title.lower(): n for n in notes} - vault = self.config.ingestion.vault.path count = 0 for n in notes: - path = Path(n.source_path) - if not path.exists(): + data = self._bytes_of(n) + if data is None: continue - props = parse_note(path, vault).properties + props = parse_text(_decode(data), source_path=n.source_path, title=n.title, + raw_bytes=data).properties for rel, (sign, factor) in RELATIONS.items(): for target in _LINK.findall(props.get(rel, "")) or ( [props[rel]] if props.get(rel) else [] @@ -159,6 +163,14 @@ def authored(self, notes: list[Note]) -> int: count += 1 return count + def _bytes_of(self, n: Note) -> bytes | None: + """A note's landed bytes: its raw object by digest when the raw store is given, else its + vault file; None when neither holds it.""" + if self.raw is not None: + return self.raw.get(n.digest) if self.raw.exists(n.digest) else None + path = Path(n.source_path) + return path.read_bytes() if path.exists() else None + # interpreted ------------------------------------------------------------------------------ def candidates(self, notes: list[Note]) -> list[tuple[Note, Note, float]]: rows = self.vectors.all_rows(clearance=MIRROR_READ) @@ -220,6 +232,27 @@ def _messages(self, a: Note, b: Note) -> list[Message]: ] +def authored_notes(catalog: Catalog) -> list[Note]: + """Every active authored-solo note the catalog holds, by path, whether or not its vault file + is on disk: the notes whose authored edges a rebuild from raw derives.""" + return sorted((Note(e.source_path, e.title, e.digest, "") for e in catalog.active_entries() + if e.provenance == Provenance.AUTHORED_SOLO.value), + key=lambda n: n.source_path) + + +def rebuild_authored(catalog: Catalog, raw: Any, edges: EdgeSink, config: Config) -> int: + """The authored relation edges, derived again from the landed bytes alone: the reset's + rebuild step for the rows of provenance `authored-solo` (dn-instance-lifecycle §3.3).""" + detector = RelationDetector(config=config, edges=edges, catalog=catalog, + vectors=_NoRows(), chat=None, raw=raw) + return detector.authored(authored_notes(catalog)) + + +class _NoRows: + def all_rows(self, *, clearance: Clearance[Provenance]) -> Sequence[Mapping[str, Any]]: + return [] + + _STAMP = re.compile(r"(\d{4}-\d{2}-\d{2})-(\d{6})") @@ -250,6 +283,8 @@ def build_relation_detector( server = build_model_server(cfg) chat = lambda messages: server.chat("synthesis", messages, think=False, temperature=0.0) # noqa: E731 + from core.kernel.stores.rawstore import RawStore + return RelationDetector( config=cfg, edges=open_edge_store(cfg), @@ -257,4 +292,5 @@ def build_relation_detector( vectors=open_vector_store(cfg), chat=chat, max_pairs=max_pairs, + raw=RawStore(cfg.paths.raw_store), ) diff --git a/core/stores/agent_observations.py b/core/stores/agent_observations.py index 6c33fcf2..d04427a3 100644 --- a/core/stores/agent_observations.py +++ b/core/stores/agent_observations.py @@ -36,13 +36,12 @@ write-side only; the live first projection over history is bp-020's, deliberately deferred. Engine: SQLite (plan Q6) — an identity-keyed append-style ledger, the runs/versions/ -snapshots convention, not the DuckDB telemetry lane. Reset semantics (plan §6(h)): this -store is CORPUS-side (the observed stratum) and joins `reset_targets()` — wiped with the -corpus, unlike the snapshot LEDGER pattern. That corpus-side call covers current READINGS -only, which rebuild by re-projection from git; the worldview HISTORY — generations -superseded when a bumped interpreter re-projects — lives in the ledger-class, reset-guarded -sidecar (`core/stores/observation_history.py`, discriminator `store='agent'`; -dn-self-sensing §2.5 ruling). +snapshots convention, not the DuckDB telemetry lane. Reset semantics: this store is derived, +step 4 of the class table in `ops/lifecycle/inventory.py`. A reset clears the current readings +and re-projects them from git's history, without the attestor. The worldview history, the +generations superseded when a bumped interpreter re-projects, is a ledger the reset keeps +(`core/stores/observation_history.py`, discriminator `store='agent'`; dn-self-sensing §2.5 +ruling). """ from __future__ import annotations @@ -284,8 +283,8 @@ def close(self) -> None: def open_agent_observation_store(config: Config | None = None) -> AgentObservationStore: """The `open_*` helper: `data/agent_observations.sqlite` (plan §6(b) — the sibling-store - convention beside `code_observations`, no dedicated cfg path; registered in - `reset_targets()` as a corpus-side wipe target, plan §6(h)).""" + convention beside `code_observations`, no dedicated cfg path). Derived in the class table + of `ops/lifecycle/inventory.py`: a reset clears it and re-projects git's history.""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/cache.py b/core/stores/cache.py new file mode 100644 index 00000000..27f22f30 --- /dev/null +++ b/core/stores/cache.py @@ -0,0 +1,537 @@ +"""The shared cache: content-addressed entries one instance leaves and another takes back +(dn-instance-lifecycle §6.3 to §6.6). + +One place, `~/.mind-palace/cache`, shared by every instance of the machine's user, under the home +root and outside every instance's root and every checkout: + + LAYOUT the layout's version + raw// a raw object, the raw store's own layout + vectors//atoms.sqlite atom id -> the vector as the plane returns it; names the + embedder, its fields in vectors//key.json + sources// a downloaded source file, with sources//MANIFEST + purged.sqlite the digests a purge erased, with the day; nothing enters + under one of them again + uses.sqlite the day each entry was last put or taken, for retention + +An entry holds no path, no title and no class: a raw object is named by its digest, a vector by +its atom id, the hash of its text, and the text is not stored with the vector. The address is the +whole trust decision: a raw object is checked against its digest when it is taken, and a mismatch +is refused and the entry deleted. Which content may enter is decided by the instance that fills +the cache (`ops/lifecycle/destroy.py`), by an allow-list of open sources; this module stores and +returns entries, refuses a purged digest and a source file that is not a plain file of its source +(a link, which would carry bytes no allow-list chose), and erases what a purge names. + +Reading never creates the cache: a lookup in a cache that does not exist finds nothing. The +location is a constant of the code (`cache_home`), as the instances' home is; the tests pass a +temporary directory to the constructor. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import sqlite3 +import stat +import time +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np + +LAYOUT = 1 +RETENTION_DAYS = 180 +_BATCH = 400 + + +def cache_home() -> Path: + """The shared cache's one location, under the home root every instance's home is under.""" + return Path.home() / ".mind-palace" / "cache" + + +def vector_key(model: str, template: str, dim: int, backend: str) -> tuple[str, dict[str, Any]]: + """The vector namespace's key: the plane's geometry (model, document template, dimension) + with the runtime backend that served it, hashed. A vector is reused only under the same key, + so two geometries never mix (falsifier LCF-6 names when the key would need the model file).""" + fields: dict[str, Any] = {"model": model, "template": template, "dim": int(dim), + "backend": backend} + digest = hashlib.sha256(json.dumps(fields, sort_keys=True).encode("utf-8")).hexdigest() + return digest[:24], fields + + +def key_of(cfg: Any) -> tuple[str, dict[str, Any]]: + """An instance's vector key: its configured geometry and embedding backend.""" + e = cfg.embedding + return vector_key(e.model, e.document_template, e.dim, cfg.runtime.embedding_backend) + + +def _day(t: float) -> float: + """A time, to the start of its UTC day.""" + return float(int(t // 86400) * 86400) + + +def _relative(name: str) -> Path: + """A manifest's file name as a path relative to its source; refused when absolute or when it + climbs out (`..`).""" + rel = Path(name) + if not name or rel.is_absolute() or ".." in rel.parts: + raise ValueError(f"a source file is relative to its source: {name!r}") + return rel + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _file_sha256(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as fh: + for block in iter(lambda: fh.read(1 << 20), b""): + h.update(block) + return h.hexdigest() + + +def _batches(items: Sequence[str]) -> Iterable[Sequence[str]]: + for i in range(0, len(items), _BATCH): + yield items[i:i + _BATCH] + + +def _ro(path: Path) -> sqlite3.Connection | None: + """A read-only connection to `path`, or None when it does not exist (nothing is created).""" + if not path.is_file(): + return None + return sqlite3.connect(f"file:{path}?mode=ro", uri=True) + + +@dataclass(frozen=True) +class CacheSize: + entries: int + bytes: int + + +@dataclass(frozen=True) +class ForgetReport: + raw_removed: bool + vectors_removed: int + + +@dataclass +class Cache: + """The cache under `root`. Every write takes the entry whole (write, then rename) and is + idempotent; every read checks what it returns.""" + + root: Path + + # ── plumbing ─────────────────────────────────────────────────────────────────────────── + + @property + def exists(self) -> bool: + return self.root.is_dir() + + def _ensure(self) -> None: + self.root.mkdir(parents=True, exist_ok=True) + layout = self.root / "LAYOUT" + if not layout.exists(): + layout.write_text(f"{LAYOUT}\n", encoding="utf-8") + + def _db(self, name: str, ddl: str) -> sqlite3.Connection: + self._ensure() + conn = sqlite3.connect(str(self.root / name)) + conn.executescript(ddl) + return conn + + def _uses(self) -> sqlite3.Connection: + return self._db("uses.sqlite", "CREATE TABLE IF NOT EXISTS uses (kind TEXT NOT NULL, " + "id TEXT NOT NULL, last REAL NOT NULL, PRIMARY KEY (kind, id));") + + def _touch(self, kind: str, ids: Iterable[str], *, now: float | None = None) -> None: + """Record that these entries were put or taken, to the day: retention needs no finer + clock, and a finer one would say when some instance read an open entry (§6.4).""" + ids = list(ids) + if not ids or not self.exists: + return + at = _day(time.time() if now is None else now) + conn = self._uses() + try: + with conn: + conn.executemany("INSERT OR REPLACE INTO uses (kind, id, last) VALUES (?, ?, ?)", + [(kind, i, at) for i in ids]) + finally: + conn.close() + + def _purged_db(self) -> sqlite3.Connection: + return self._db("purged.sqlite", "CREATE TABLE IF NOT EXISTS purged (digest TEXT " + "PRIMARY KEY, at REAL NOT NULL);") + + # ── purged digests ───────────────────────────────────────────────────────────────────── + + def purged(self) -> set[str]: + conn = _ro(self.root / "purged.sqlite") + if conn is None: + return set() + try: + return {str(r[0]) for r in conn.execute("SELECT digest FROM purged")} + finally: + conn.close() + + def is_purged(self, digest: str) -> bool: + return digest in self.purged() + + # ── raw objects ──────────────────────────────────────────────────────────────────────── + + def _raw_path(self, digest: str) -> Path: + return self.root / "raw" / digest[:2] / digest + + def has_raw(self, digest: str) -> bool: + return self._raw_path(digest).is_file() + + def raw_digests(self) -> set[str]: + d = self.root / "raw" + if not d.is_dir(): + return set() + return {p.name for p in d.glob("*/*") if p.is_file() and not p.name.endswith(".tmp")} + + def raw(self, digest: str) -> bytes | None: + """The raw object `digest`, checked against its address; None when the cache lacks it. An + entry whose bytes do not hash to its name is refused and deleted.""" + p = self._raw_path(digest) + if not p.is_file(): + return None + data = p.read_bytes() + if _sha256(data) != digest: + p.unlink(missing_ok=True) + return None + self._touch("raw", [digest]) + return data + + def put_raw(self, digest: str, data: bytes) -> bool: + """Store a raw object under its digest; False when it is held already, purged, or its + bytes are not the digest's.""" + if _sha256(data) != digest or self.is_purged(digest): + return False + p = self._raw_path(digest) + if p.is_file(): + self._touch("raw", [digest]) + return False + self._ensure() + p.parent.mkdir(parents=True, exist_ok=True) + tmp = p.with_name(p.name + ".tmp") + tmp.write_bytes(data) + tmp.replace(p) + self._touch("raw", [digest]) + return True + + # ── vectors ──────────────────────────────────────────────────────────────────────────── + + def _vector_dir(self, key: str) -> Path: + return self.root / "vectors" / key + + def vector_keys(self) -> list[str]: + d = self.root / "vectors" + return sorted(p.name for p in d.iterdir() if p.is_dir()) if d.is_dir() else [] + + def vectors(self, key: str, atom_ids: Sequence[str]) -> dict[str, list[float]]: + """The cached vectors of these atoms under `key`; an atom the cache lacks is absent.""" + conn = _ro(self._vector_dir(key) / "atoms.sqlite") + if conn is None or not atom_ids: + if conn is not None: + conn.close() + return {} + out: dict[str, list[float]] = {} + try: + for batch in _batches(list(dict.fromkeys(atom_ids))): + marks = ", ".join("?" for _ in batch) + for aid, blob in conn.execute( + f"SELECT atom_id, vector FROM atoms WHERE atom_id IN ({marks})", + list(batch)): + out[str(aid)] = np.frombuffer(blob, dtype=np.float64).tolist() + finally: + conn.close() + self._touch(f"vector:{key}", out) + return out + + def vector_ids(self, key: str) -> set[str]: + conn = _ro(self._vector_dir(key) / "atoms.sqlite") + if conn is None: + return set() + try: + return {str(r[0]) for r in conn.execute("SELECT atom_id FROM atoms")} + finally: + conn.close() + + def put_vectors(self, key: str, fields: Mapping[str, Any], + vectors: Mapping[str, Sequence[float]]) -> int: + """Store vectors under `key` (its fields written beside them); returns those added.""" + if not vectors: + return 0 + self._ensure() + d = self._vector_dir(key) + d.mkdir(parents=True, exist_ok=True) + meta = d / "key.json" + if not meta.exists(): + meta.write_text(json.dumps(dict(fields), sort_keys=True), encoding="utf-8") + conn = sqlite3.connect(str(d / "atoms.sqlite")) + try: + conn.execute("CREATE TABLE IF NOT EXISTS atoms (atom_id TEXT PRIMARY KEY, " + "dim INTEGER NOT NULL, vector BLOB NOT NULL)") + added = 0 + with conn: + for aid, vec in vectors.items(): + arr = np.asarray(list(vec), dtype=np.float64) + cur = conn.execute("INSERT OR IGNORE INTO atoms (atom_id, dim, vector) " + "VALUES (?, ?, ?)", [aid, int(arr.size), arr.tobytes()]) + added += cur.rowcount + finally: + conn.close() + self._touch(f"vector:{key}", vectors) + return added + + def view(self, key: str) -> VectorCache: + return VectorCache(self, key) + + # ── downloaded source files ──────────────────────────────────────────────────────────── + + def _source_dir(self, source: str) -> Path: + if not source or "/" in source or source.startswith("."): + raise ValueError(f"not a source name: {source!r}") + return self.root / "sources" / source + + def source_manifest(self, source: str) -> list[dict[str, Any]]: + f = self._source_dir(source) / "MANIFEST" + if not f.is_file(): + return [] + return list(json.loads(f.read_text(encoding="utf-8"))) + + def sources(self) -> list[str]: + d = self.root / "sources" + return sorted(p.name for p in d.iterdir() if p.is_dir()) if d.is_dir() else [] + + def put_source_files(self, source: str, base: Path, files: Sequence[str]) -> int: + """Copy `files` (relative to `base`) into the source's namespace, each named in its + MANIFEST with its size, SHA-256 and when it was fetched; returns the files added. A file + that is not a plain file of its source (`plain_file`) is refused before anything is + written: the selection is by name, and a link would carry another file's bytes in.""" + if not files: + return 0 + for rel in files: + _relative(rel) + if not plain_file(base / rel, base): + raise ValueError(f"{base / rel} is not a plain file of its source: a symbolic " + "link, a file with another hard link, or one that resolves out " + "of the source's directory") + self._ensure() + d = self._source_dir(source) + manifest = {m["file"]: m for m in self.source_manifest(source)} + added = 0 + for rel in files: + src = base / rel + sha = _file_sha256(src) + if rel in manifest and manifest[rel]["sha256"] == sha: + continue + dest = d / rel + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(dest.name + ".tmp") + shutil.copyfile(src, tmp) + tmp.replace(dest) + manifest[rel] = {"file": rel, "size": src.stat().st_size, "sha256": sha, + "fetched": time.strftime("%Y-%m-%dT%H:%M:%SZ", + time.gmtime(src.stat().st_mtime))} + added += 1 + (d / "MANIFEST").write_text(json.dumps(sorted(manifest.values(), + key=lambda m: m["file"]), indent=1), + encoding="utf-8") + self._touch("source", [source]) + return added + + def take_source(self, source: str, dest: Path) -> int: + """Copy the source's cached files into `dest`, each one whose size and SHA-256 match its + manifest row; a file that does not match is refused and its entry deleted. A row whose + name is absolute or climbs out of its directory is refused, and nothing is read or written + for it: every instance of the user can write the cache. Returns the files copied. Files + `dest` already holds are left as they are.""" + d = self._source_dir(source) + copied = 0 + for m in self.source_manifest(source): + try: + rel = _relative(str(m.get("file", ""))) + except ValueError: + continue + src, out = d / rel, dest / rel + if not (_under(src, d) and _under(out, dest)): + continue + if out.exists() or not src.is_file(): + continue + if src.stat().st_size != int(m["size"]) or _file_sha256(src) != m["sha256"]: + src.unlink(missing_ok=True) + continue + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(out.name + ".tmp") + shutil.copyfile(src, tmp) + tmp.replace(out) + copied += 1 + if copied: + self._touch("source", [source]) + return copied + + # ── erasure ──────────────────────────────────────────────────────────────────────────── + + def forget(self, digest: str, atom_ids: Iterable[str]) -> ForgetReport: + """What a purge of `digest` owes the cache (§6.6): the raw object, and the vector of every + atom of its chunks under every key, deleted; the digest recorded, so no fill puts it back. + The atoms are deleted and not recorded, since an atom's text may be held by an open item + whose content is public.""" + atoms = list(dict.fromkeys(atom_ids)) + raw_removed = False + p = self._raw_path(digest) + if p.is_file(): + p.unlink() + raw_removed = True + removed = 0 + for key in self.vector_keys(): + f = self._vector_dir(key) / "atoms.sqlite" + if not f.is_file() or not atoms: + continue + conn = sqlite3.connect(str(f)) + try: + with conn: + for batch in _batches(atoms): + marks = ", ".join("?" for _ in batch) + removed += conn.execute( + f"DELETE FROM atoms WHERE atom_id IN ({marks})", list(batch)).rowcount + finally: + conn.close() + conn = self._purged_db() + try: + with conn: + conn.execute("INSERT OR IGNORE INTO purged (digest, at) VALUES (?, ?)", + [digest, _day(time.time())]) + finally: + conn.close() + return ForgetReport(raw_removed=raw_removed, vectors_removed=removed) + + # ── retention and reporting ──────────────────────────────────────────────────────────── + + def sizes(self) -> dict[str, CacheSize]: + """The cache's size by namespace: raw, each vector key, each source.""" + out: dict[str, CacheSize] = {} + + def size_of(paths: Iterable[Path]) -> CacheSize: + files = [p for p in paths if p.is_file()] + return CacheSize(len(files), sum(p.stat().st_size for p in files)) + + out["raw"] = size_of((self.root / "raw").glob("*/*")) + for key in self.vector_keys(): + n = len(self.vector_ids(key)) + f = self._vector_dir(key) / "atoms.sqlite" + out[f"vectors/{key}"] = CacheSize(n, f.stat().st_size if f.is_file() else 0) + for source in self.sources(): + m = self.source_manifest(source) + out[f"sources/{source}"] = CacheSize(len(m), sum(int(e["size"]) for e in m)) + return out + + def stale(self, *, days: int = RETENTION_DAYS, + now: float | None = None) -> dict[str, list[str]]: + """The entries not put or taken for `days`, by kind: what a prune would remove.""" + at = time.time() if now is None else now + cutoff = at - days * 86400 + conn = _ro(self.root / "uses.sqlite") + last: dict[tuple[str, str], float] = {} + if conn is not None: + try: + last = {(str(k), str(i)): float(t) + for k, i, t in conn.execute("SELECT kind, id, last FROM uses")} + finally: + conn.close() + + def old(kind: str, ident: str) -> bool: + return last.get((kind, ident), 0.0) < cutoff + + out: dict[str, list[str]] = {"raw": sorted(d for d in self.raw_digests() + if old("raw", d))} + for key in self.vector_keys(): + out[f"vector:{key}"] = sorted(a for a in self.vector_ids(key) + if old(f"vector:{key}", a)) + out["source"] = [s for s in self.sources() if old("source", s)] + return out + + def prune(self, *, days: int = RETENTION_DAYS, now: float | None = None) -> int: + """Remove the entries not put or taken for `days`; returns how many.""" + stale = self.stale(days=days, now=now) + removed = 0 + for digest in stale["raw"]: + self._raw_path(digest).unlink(missing_ok=True) + removed += 1 + for kind, ids in stale.items(): + if not kind.startswith("vector:") or not ids: + continue + f = self._vector_dir(kind.split(":", 1)[1]) / "atoms.sqlite" + conn = sqlite3.connect(str(f)) + try: + with conn: + for batch in _batches(ids): + marks = ", ".join("?" for _ in batch) + removed += conn.execute( + f"DELETE FROM atoms WHERE atom_id IN ({marks})", list(batch)).rowcount + finally: + conn.close() + for source in stale["source"]: + shutil.rmtree(self._source_dir(source), ignore_errors=True) + removed += 1 + return removed + + +@dataclass(frozen=True) +class VectorCache: + """The cache's vectors under one key: what the vector drain looks an atom up in before it + calls the embedder (§6.5).""" + + cache: Cache + key: str + + def vectors(self, atom_ids: Sequence[str]) -> dict[str, list[float]]: + return self.cache.vectors(self.key, atom_ids) + + +def with_cache(stores: Any, cfg: Any, cache: Cache | None = None) -> Any: + """Give the writer's stores their two reuse paths (§6.5), and return them: the raw store + looks a miss up in the cache by digest, and, in an instance that embeds, the vector drain + looks an atom up under the instance's embedder key before it calls the embedder. The cache is + the shared one unless given. Idempotent.""" + shared = cache if cache is not None else Cache(cache_home()) + raw = getattr(stores, "raw", None) + if raw is not None and getattr(raw, "fallback", "absent") is None: + raw.fallback = shared.raw + if cfg.embedding.enabled and getattr(stores, "cache", None) is None: + stores.cache = shared.view(key_of(cfg)[0]) + return stores + + +def _under(path: Path, root: Path) -> bool: + """Whether `path` resolves inside `root` (a link in the cache cannot carry a name out).""" + real_root = Path(os.path.realpath(root)) + return real_root in Path(os.path.realpath(path)).parents + + +def plain_file(path: Path, base: Path) -> bool: + """Whether `path` is a plain file of the source directory `base`: a regular file, not a + symbolic link, with no other hard link, that resolves inside `base`. What a fill copies is + chosen by name, so a file that fails this could hold another file's bytes (an instance's + catalog, a note outside the root), which no allow-list chose; the writing side refuses it as + `take_source` refuses a name that climbs out on the reading side.""" + try: + st = path.lstat() + except FileNotFoundError: + return False + return (stat.S_ISREG(st.st_mode) and st.st_nlink == 1 and _under(path, base)) + + +def same_volume_free(path: Path) -> int: + """Free bytes on the volume that holds `path` (or its nearest existing parent).""" + p = path + while not p.exists() and p != p.parent: + p = p.parent + st = os.statvfs(p) + return st.f_bavail * st.f_frsize diff --git a/core/stores/causal_edges.py b/core/stores/causal_edges.py index e5561e34..0740ace7 100644 --- a/core/stores/causal_edges.py +++ b/core/stores/causal_edges.py @@ -25,8 +25,9 @@ falsifier). Composing action→commit with commit→file is Δ's `ComposedGraph` job (C≠D composition). Sibling-store convention (`chat_events.py`/`reference_edges.py`): SQLite, no dedicated cfg path — -`data/causal_edges.sqlite` beside the L1 store. A corpus-side derived layer (a pure function of -retained raw + the ledger), so it joins `reset_targets()` and rebuilds by re-integration. +`data/causal_edges.sqlite` beside the L1 store. Derived, step 9 of the class table in +`ops/lifecycle/inventory.py`: a reset clears it and integrates it again over the chat events and +the commit ledger (decision D6 of dn-instance-lifecycle). """ from __future__ import annotations @@ -194,8 +195,8 @@ def close(self) -> None: def open_causal_edge_store(config: Config | None = None) -> CausalEdgeStore: """`data/causal_edges.sqlite` beside the L1 store (the sibling-store convention; no dedicated - cfg path). Registered in `reset_targets()` as a corpus-side wipe target — rebuilt by - re-integration from the immutable rawstore-backed L1 + the commit ledger.""" + cfg path). Derived in the class table of `ops/lifecycle/inventory.py`: a reset clears it and + integrates it again over the chat events and the commit ledger.""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/chat_events.py b/core/stores/chat_events.py index b04f8396..730777a0 100644 --- a/core/stores/chat_events.py +++ b/core/stores/chat_events.py @@ -19,8 +19,9 @@ chatlog's `transcript_digest` and re-extracts iff that digest changed (`replace_session`). Sibling-store convention (`code_observations.py`/`chatlog.py`): SQLite, no dedicated cfg path — -`data/chat_events.sqlite` beside the chatlog. A corpus-side derived layer, so it joins -`reset_targets()` (launcher) as a wipe target, rebuilt by re-projection from the immutable rawstore. +`data/chat_events.sqlite` beside the chatlog. Derived, step 8 of the class table in +`ops/lifecycle/inventory.py`: a reset clears it and re-projects it from the chat log and the raw +store. """ from __future__ import annotations @@ -114,8 +115,8 @@ def close(self) -> None: def open_chat_event_store(config: Config | None = None) -> ChatEventStore: """`data/chat_events.sqlite` beside the chatlog (the sibling-store convention; no dedicated cfg - path). Registered in `reset_targets()` as a corpus-side wipe target — rebuilt by re-projection - from the immutable rawstore (the orchestrator's post-merge step).""" + path). Derived in the class table of `ops/lifecycle/inventory.py`: a reset clears it and + re-projects it from the chat log and the raw store.""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/chat_retention.py b/core/stores/chat_retention.py new file mode 100644 index 00000000..a47c96bc --- /dev/null +++ b/core/stores/chat_retention.py @@ -0,0 +1,122 @@ +"""The chat sensor's retention ledger: which raw objects are transcripts, in the order the sensor +retained them (dn-instance-lifecycle §3.4). + +The chat log is derived: its rows are a deterministic parse of a transcript's bytes, and the bytes +are in the raw store (CS-1). What no other store holds is which raw objects are transcripts and in +what order they were retained, and the order matters: the first write of a turn stands +(`ChatlogStore.add_batch`), and a session that later shows a candidate secret is held at its state +before it. So the chat log is the fold of the retained transcripts in retention order, and this +ledger is that order. The sensor appends a row when it retains bytes that are new, before it +extracts anything; a reset replays the rows through the same parse, guard and landing, reading +the bytes back from the raw store, with no transcript directory. + +Append-only: a row is never updated or deleted, and its `seq` is the retention order. `at` is a +wall-clock bookmark only (Law C4). + +An instance whose chat log predates this ledger has one row a transcript digest the chat log +names, seeded at the ledger's first open (`seed_from`): ordered within a session by the lowest +turn the digest wrote. A digest that wrote no row (refused, empty, unparseable, or grown with no +new prose) is not in that seed, and leaving it out changes nothing in a replay, so the replay of +the seed gives back the chat log as it stands. +""" + +from __future__ import annotations + +import sqlite3 +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + +from core.kernel.config import Config + +RETENTION_FILE = "chat_retention.sqlite" + +_DDL = """ +CREATE TABLE IF NOT EXISTS retained ( + seq INTEGER PRIMARY KEY, -- the retention order + digest TEXT NOT NULL UNIQUE, -- the raw object's SHA-256 + file TEXT NOT NULL, -- the transcript's file stem when retained (for the report) + at TEXT NOT NULL -- wall bookmark only +); +CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +""" + + +def _now() -> str: + return datetime.now(UTC).replace(tzinfo=None).isoformat(timespec="seconds") + + +@dataclass(frozen=True) +class Retained: + seq: int + digest: str + file: str + + +@dataclass +class RetentionLedger: + path: Path + + def __post_init__(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + self._conn = sqlite3.connect(str(self.path)) + self._conn.executescript(_DDL) + self._conn.commit() + + def append(self, digest: str, file: str) -> bool: + """Record that the sensor retained `digest`; False when it is recorded already.""" + with self._conn: + cur = self._conn.execute( + "INSERT OR IGNORE INTO retained (digest, file, at) VALUES (?, ?, ?)", + [digest, file, _now()]) + return cur.rowcount == 1 + + def rows(self) -> list[Retained]: + return [Retained(int(s), str(d), str(f)) for s, d, f in self._conn.execute( + "SELECT seq, digest, file FROM retained ORDER BY seq")] + + def count(self) -> int: + return int(self._conn.execute("SELECT count(*) FROM retained").fetchone()[0]) + + def seeded(self) -> bool: + return self._conn.execute("SELECT 1 FROM meta WHERE key = 'seeded'").fetchone() is not None + + def seed_from(self, chatlog_path: Path) -> int: + """Fill an empty ledger from a chat log that predates it, once: one row a distinct + `transcript_digest`, ordered by session and, within one, by the lowest turn the digest + wrote. Read only from the chat log; returns the rows written.""" + if self.seeded(): + return 0 + written = 0 + if self.count() == 0 and chatlog_path.exists(): + src = sqlite3.connect(f"file:{chatlog_path}?mode=ro", uri=True) + try: + found = src.execute( + "SELECT transcript_digest, session_id, MIN(turn_index) AS first " + "FROM chat_utterances GROUP BY transcript_digest " + "ORDER BY session_id, first, transcript_digest").fetchall() + except sqlite3.OperationalError: + found = [] + finally: + src.close() + with self._conn: + for digest, session, _first in found: + cur = self._conn.execute( + "INSERT OR IGNORE INTO retained (digest, file, at) VALUES (?, ?, ?)", + [str(digest), str(session), _now()]) + written += cur.rowcount + with self._conn: + self._conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('seeded', ?)", + [str(written)]) + return written + + def close(self) -> None: + self._conn.close() + + +def open_retention_ledger(config: Config | None = None) -> RetentionLedger: + """`data/chat_retention.sqlite`, beside the chat log it orders.""" + from core.kernel.config import get_config + + cfg = config or get_config() + return RetentionLedger(cfg.paths.data_dir / RETENTION_FILE) diff --git a/core/stores/chatlog.py b/core/stores/chatlog.py index 19ab4fd7..36777be6 100644 --- a/core/stores/chatlog.py +++ b/core/stores/chatlog.py @@ -38,11 +38,10 @@ over those bytes — the same two-layer shape as ingest (raw → derived), no new pattern. Engine: SQLite — an identity-keyed append-style ledger, the sibling-store convention -(`code_observations.py`), not the DuckDB telemetry lane. Reset semantics (Q6): this store -is CORPUS-side (the observed stratum) and joins `reset_targets()` (`ops/lifecycle/ -launcher.py`) as a wipe target — wiped with the corpus, rebuilt by re-ingest from the -IMMUTABLE rawstore (which is NOT a reset target — raw is sacred). [cross-ref: extension, -dn-chat-sensor; the launcher registration is the orchestrator's post-merge step.] +(`code_observations.py`), not the DuckDB telemetry lane. Reset semantics: this store is +derived, step 7 of the class table in `ops/lifecycle/inventory.py` (dn-instance-lifecycle §3.3, +§3.4). A reset clears it and rebuilds it by replaying the chat sensor's retention ledger, reading +each transcript's bytes from the raw store, which a reset keeps. Spine-invisible in v1 (dn-chat-sensor §3): this plan writes NO chain and registers NO stratum. bp-064 (clock wiring, CS-4) joins the store to the spine as a g1-chained store @@ -222,8 +221,8 @@ def close(self) -> None: def open_chatlog_store(config: Config | None = None) -> ChatlogStore: """The `open_*` helper: `data/chatlog.sqlite` (the sibling-store convention beside - `code_observations`, no dedicated cfg path; registered in `reset_targets()` as a - corpus-side wipe target — the orchestrator's post-merge step, Q6).""" + `code_observations`, no dedicated cfg path). Derived in the class table of + `ops/lifecycle/inventory.py`: a reset clears it and replays the retention ledger.""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/code_observations.py b/core/stores/code_observations.py index 0da7d724..a424bbad 100644 --- a/core/stores/code_observations.py +++ b/core/stores/code_observations.py @@ -30,13 +30,11 @@ the deterministic reference extractor (Lane 1, V4-seeded patterns) is B-c / bp-013. Engine: SQLite (plan Q2) — an identity-keyed append-style ledger, the runs/versions/ -snapshots convention, not the DuckDB telemetry lane. Reset semantics (plan Q4): this store -is CORPUS-side (the observed stratum) and joins `reset_targets()` — wiped with the corpus, -unlike the snapshot LEDGER (build history, reset-guarded). [cross-ref: extension, bp-018] -That corpus-side call covers the current READINGS only, which rebuild by re-projection -from git; the worldview HISTORY — generations superseded when a bumped interpreter -re-projects — lives in the ledger-class, reset-guarded sidecar -(`core/stores/observation_history.py`; dn-self-sensing §2.5 ruling). +snapshots convention, not the DuckDB telemetry lane. Reset semantics: this store is derived, +step 3 of the class table in `ops/lifecycle/inventory.py`. A reset clears the current readings +and re-projects them from the commit ledger, which it keeps, without the attestor. The worldview +history, the generations superseded when a bumped interpreter re-projects, is a ledger the reset +keeps (`core/stores/observation_history.py`; dn-self-sensing §2.5 ruling). """ from __future__ import annotations @@ -327,8 +325,8 @@ def close(self) -> None: def open_code_observation_store(config: Config | None = None) -> CodeObservationStore: """The `open_*` helper: `data/code_observations.sqlite` (plan Q2 — the sibling-store - convention beside `derived_store`, no dedicated cfg path; registered in - `reset_targets()` as a corpus-side wipe target, plan Q4).""" + convention beside `derived_store`, no dedicated cfg path). Derived in the class table of + `ops/lifecycle/inventory.py`: a reset clears it and re-projects the commit ledger.""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/edges.py b/core/stores/edges.py index b140c10c..bc604574 100644 --- a/core/stores/edges.py +++ b/core/stores/edges.py @@ -134,6 +134,14 @@ def delete_rel_type(self, rel_type: str) -> int: self._conn.commit() return cur.rowcount + def delete_provenance(self, provenance: str) -> int: + """Delete every edge of one provenance; returns rows removed. A lifecycle reset clears the + authored rows, which it derives again from the landed bytes, and keeps the interpreted + ones, which are model output (dn-instance-lifecycle §3.3).""" + cur = self._conn.execute("DELETE FROM edges WHERE provenance = ?", [provenance]) + self._conn.commit() + return cur.rowcount + @staticmethod def _row(r: sqlite3.Row) -> Edge: return Edge(edge_id=r["edge_id"], u=r["u"], v=r["v"], w=r["w"], diff --git a/core/stores/observation_history.py b/core/stores/observation_history.py index 5e460223..ff10953d 100644 --- a/core/stores/observation_history.py +++ b/core/stores/observation_history.py @@ -5,9 +5,8 @@ # INVARIANT: append-only. No delete/update method EXISTS on this class — ledger-class is # structural, the same move as the no-provenance-parameter mint discipline. # ENFORCED: structurally (absent API) + INSERT OR IGNORE on the identity PK, and by the -# reset guard: `observation_history.sqlite` is in `_RESET_GUARD` -# (ops/lifecycle/launcher.py), never a reset target — history does not rebuild -# (the old interpreters no longer exist at HEAD). +# class table (ops/lifecycle/inventory.py), which names it a ledger a reset keeps: +# history does not rebuild, since the old interpreters no longer exist at HEAD. """The history sidecar for the observation-store family (bp-018, dn-self-sensing §2.4/§2.5). ONE store for the FAMILY, discriminated by member name (`store`: 'code' today; 'agent' @@ -135,8 +134,9 @@ def close(self) -> None: def open_observation_history_store(config: Config | None = None) -> ObservationHistoryStore: """The `open_*` helper: `data/observation_history.sqlite` (the sibling-store - convention, no dedicated cfg path). GUARDED (bp-018 Item 4): named in `_RESET_GUARD`, - never a reset target — dn-self-sensing §2.5, history does not rebuild.""" + convention, no dedicated cfg path). A ledger in the class table of + `ops/lifecycle/inventory.py`, kept by a reset: history does not rebuild (dn-self-sensing + §2.5).""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/core/stores/plane.py b/core/stores/plane.py index 569d7e0e..ae17f7c1 100644 --- a/core/stores/plane.py +++ b/core/stores/plane.py @@ -640,6 +640,36 @@ def reset(self) -> None: conn.execute("ROLLBACK") raise + def reset_relations(self) -> None: + """Forget every occupancy and supersession edge, and keep the atoms and the recorded + geometry: a lifecycle reset's clearing of the plane (dn-instance-lifecycle §4.2). The atom + table is a memo of one function, the embedder's vector of a text under the recorded + geometry, so keeping it loses no derived state, and the drain that rebuilds the relations + finds every atom held and embeds nothing. The `held` cache is left stale by excess, which + no search sees (PLN-4); `repair` brings it in step once the relations are rebuilt.""" + with self._writing() as conn: + conn.execute("BEGIN IMMEDIATE") + try: + for p in PLANE_CLASSES: + conn.execute(f"DELETE FROM {OCC[p]}") + conn.execute(f"DELETE FROM {SUP[p]}") + conn.execute("COMMIT") + except BaseException: + conn.execute("ROLLBACK") + raise + + def drop_unheld(self) -> int: + """Delete the atoms no occupancy of any class holds, current or not: after a lifecycle + reset's rebuild, the atom table holds exactly what the rebuilt relations name. Returns the + atoms deleted.""" + with self._writing() as conn: + referenced: set[str] = set() + for p in PLANE_CLASSES: + referenced |= {str(r[0]) for r in conn.execute( + f"SELECT DISTINCT atom_id FROM {OCC[p]}")} + orphans = sorted(self.atoms.ids() - referenced) + return self.atoms.delete(orphans) if orphans else 0 + # ── the `held` cache (the prefilter) and its repair ratchet ────────────────────────────── def _held_truth(self, conn: sqlite3.Connection, diff --git a/core/stores/reference_edges.py b/core/stores/reference_edges.py index 316564ac..b7efeed4 100644 --- a/core/stores/reference_edges.py +++ b/core/stores/reference_edges.py @@ -72,9 +72,11 @@ is never mutated (re-projection of the same commit is a no-op; a φ_code upgrade is a versioned re-interpretation, §2.2, never an in-place overwrite). -**Reset semantics (v1 Q4, unchanged).** Corpus-layer, like `code_observations.sqlite`: wiped -with the corpus via `reset_targets()` (registration is the orchestrator's post-merge step, -oq-0013 concurrence), unlike the snapshot LEDGER (build history, reset-guarded). +**Reset semantics.** A ledger in the class table of `ops/lifecycle/inventory.py`, kept by a +reset (decision D3 of dn-instance-lifecycle): a commit's reading is the union of every projection +so far, and the rows carry no extractor version, so a re-projection under today's extractor would +not give them back. A reset's re-projection of the code observations mints edges this store +already holds, and `INSERT OR IGNORE` drops them. Consumers: the detangling instruments, the parked s(C,D) external-corroboration feature (finding-0021), and (bp-026's warrant) the dn-core-query-protocol algebra's `references_to` @@ -413,8 +415,8 @@ def close(self) -> None: def open_reference_edge_store(config: Config | None = None) -> ReferenceEdgeStore: """The `open_*` helper: `data/reference_edges.sqlite` — the sibling-store convention - beside `code_observations.sqlite`. Corpus-layer (Q4): a `reset_targets()` wipe target - (registered by the orchestrator post-merge, oq-0013 concurrence).""" + beside `code_observations.sqlite`. A ledger in the class table of + `ops/lifecycle/inventory.py`, kept by a reset (decision D3).""" from core.kernel.config import get_config cfg = config or get_config() diff --git a/docs/design-notes/dn-corpus-instance.md b/docs/design-notes/dn-corpus-instance.md index fa33973a..9ddb43a2 100644 --- a/docs/design-notes/dn-corpus-instance.md +++ b/docs/design-notes/dn-corpus-instance.md @@ -208,7 +208,10 @@ hypothesis the instance tests is that `ρ_b` on these six sources is well below The instance's id is `corpus`. Under DI-2 everything it holds is derived from that id and disjoint from the default instance by construction: its root is `instances/corpus/` (gitignored, one -directory to mount or archive), its stores, spool, lock and levers under it, its Keychain items +directory to mount or archive) [banner: amended 2026-11-12, dn-instance-lifecycle §7: the root is +declared, `~/.mind-palace/instances/corpus`, outside every checkout; the data moved there on +2026-11-11 and `instances/corpus` in the corpus stage-1 worktree is a symbolic link to it], its +stores, spool, lock and levers under it, its Keychain items `corpus.`, its launchd labels `com.mind-palace.corpus.`, its exhaust lane inside its root. It declares no vault, no transcripts and no code agent, so it reads none of the default instance's sources; the loader refuses an overlay that could reach anything another instance @@ -219,6 +222,7 @@ writes, and the property test over generated ids checks the invariant. `[ESTABLI # config/instances/corpus.toml: the open-corpus instance (dn-corpus-instance). [instance] id = "corpus" +root = "~/.mind-palace/instances/corpus" # added 2026-11-12 (dn-instance-lifecycle §7) [runtime] embedding_backend = "llamacpp" @@ -242,7 +246,7 @@ enabled = false enabled = false [ingestion.corpus] # the sources of §7, each a line of the ingress's table (§5.2) -root = "instances/corpus/sources" # dumps and stream checkpoints land here, under the instance's root +root = "sources" # dumps and stream checkpoints land here, under the instance's root ``` The `[ingestion.corpus]` section does not exist in the schema today; it is the one config change @@ -598,7 +602,8 @@ and held locally and never republished; the 2024-04-02 archive and the API for S default is withdrawn. - **CIF-4 (the compact graph is not compact):** an occupancy row above 300 B or an edge above 24 B measured at stage 1. Then §4.3's 31 GB is 60 or more and the cap bites at 100 GB. -- **CIF-5 (the instance reaches outside):** a write under anything but `instances/corpus/`, or a +- **CIF-5 (the instance reaches outside):** a write under anything but its root + (`~/.mind-palace/instances/corpus/` since 2026-11-12; `instances/corpus/` before), or a read of the default instance's sources. SAF-5; the loader's refusal is the guard. - **CIF-6 (a batch does not converge):** a batch interrupted and re-run that lands a different state. ING-11 says it cannot; a difference is a transcription defect in the lander. diff --git a/docs/design-notes/dn-instance-lifecycle.md b/docs/design-notes/dn-instance-lifecycle.md new file mode 100644 index 00000000..cdfdb342 --- /dev/null +++ b/docs/design-notes/dn-instance-lifecycle.md @@ -0,0 +1,1159 @@ +--- +type: design-note +id: dn-instance-lifecycle +track: deployed-instances +status: draft # provenance description, never a gate; the merge is ratification +implementation: built # part B built §3 to §8; §10 records where the build departs +created: 2026-11-12 +updated: 2026-11-14 +links: + - docs/design-notes/dn-temporal-snapshot.md # §2.2 the inventory this note checks and extends; §2.3 item 7 the reset as it was; §3.2 the landing log (SN-1, merged with #92) + - core/stores/landings.py # the landing log, in the catalog's file: kept whole by the reset, removed with the root by a destroy + - docs/design-notes/chat-sensor.md # CS-1: the transcript retained verbatim before extraction; the chat log a derived layer over raw + - docs/design-notes/self-sensing.md # §2.5: readings rebuilt by re-projection, history ledger-class and kept + - docs/design-notes/code-observation-projection.md # §2.4, §2.5: observations and reference edges, corpus-side + - docs/design-notes/dn-two-phase-ingestion.md # the vector and the lexical units as derived fields; the drain and the backfill + - docs/design-notes/dn-palace-lite.md # `[instance] root`, an instance that embeds nothing, the repository sync + - docs/design-notes/dn-corpus-instance.md # the corpus instance, its sources and its one writer + - docs/design-notes/vector-membership-store.md # atoms, occupancies, the purge (A3.7) + - docs/design-notes/dn-embedder-use.md # the tokenizer's identity and the re-derivation of a stale index + - docs/design-notes/verdict-authority.md # the verdict ledger and its applied dispositions +supersedes: null +superseded_by: null +warrant: null +--- + +# The instance's lifecycle: a reset that rebuilds, a destroy that keeps a cache, the corpus at its own root + +> Drafted on the branch `feat/instance-lifecycle`, cut from `origin/main` at `0a5fba27`, and +> rebased onto `8d4dff3d` once pull request #92 had merged (2026-11-12, `ab67880f`), and #89 +> after it. Every line cited is a line of the base, `8d4dff3d`, the tree this branch merges onto. +> The claims about code at those lines were read at `0a5fba27` and checked again at the base, +> where these had moved and are cited at their new lines: `perform` and the receipt's timing in +> `core/ingest/ingress.py`, the query log's name in `core/sentence/surface.py`, and in +> `core/ingest/writer.py` the version chains and the two key writes of `Writer.finish` and +> `Writer.link`. This branch changes `writer.py`, and its heal of §5 moves every line after +> `Writer.land` down by 23: at the branch's head the two key writes are at `:475-476` and +> `:489-490`. The landing log, which #92 brought into the base, was read at `8d4dff3d`, and the +> passages about it (§3.6, §4.4 to §4.7, §6.1, §6.2, §6.4, §7, §10 items 16 to 30) name functions +> rather than lines. The note is as built: part B built §3 to §8, and §10 records where the build +> departs from the design, the changes an audit of the build asked for among them, those part C +> made with the landing log in the base, and those two audits of part C asked for. Grades: +> `[ESTABLISHED]` is a fact of the code at the lines cited or of a ratified note; `[DERIVED]` is +> argued here from those; `[INFERENCE]` is a design call with a named falsifier; `[PROPOSED]` is +> a choice this note makes and leaves to the owner (§9). + +## 1. Purpose and scope + +### 1.1 The owner's decisions + +These five bind this note. They are recorded here in this note's words. + +1. **A reset loses nothing (2026-11-11).** It clears the derived stores and rebuilds them from the + raw store; the raw store and every ledger are kept. +2. **A destroy keeps only a cache (2026-11-11).** Destroying an instance removes it, except what + another instance can take back as a cache. +3. **The corpus lives at its own root (2026-11-11).** The corpus instance's data is at + `~/.mind-palace/instances/corpus`, outside every checkout. It is a dataset other instances can + draw on and the fixture for regression and stress runs. It was moved there on 2026-11-11, and + its old location, `instances/corpus` in the worktree of the corpus's stage 1, is a symbolic link + to it. +4. **A change replaces what it changes (2026-11-12).** The new reset is the reset: there is no + switch back to the old behaviour and no old command beside it. Reverting the pull request is + the rollback. +5. **One definition (2026-11-12).** What a store is and how an operation computes is defined once, + in the code, and is the same for every instance. What reset and destroy do is not a setting. + +### 1.2 What this note decides + +1. **Every store an instance writes is in exactly one class (§3):** a ledger, an owner's + declaration, a derived store with its rebuild, model output, or operational state. The classes + are one table in the code, and a test fails when a store is opened that the table does not + name. `[INFERENCE, falsifier LCF-1]` +2. **A reset clears the derived stores and rebuilds them in a fixed order, in its own process, + under the instance's supervisor lock, and keeps everything else (§4).** The raw store, the + catalog with the landing log in its file, the attestations, the version chains, the verdicts + and the queue, which the reset at main removes, are kept. `[DERIVED from decision 1 and §3]` The + lexical index and the + authored relation edges, which it leaves today, are rebuilt. `[PROPOSED, D11]` +3. **The chat log is rebuilt from the raw store through a new ledger of retained transcripts + (§3.4).** Today a kept raw store makes the chat sensor skip every transcript it has seen, so + nothing would rebuild the chat log. `[ESTABLISHED for the gap; INFERENCE for the ledger, + falsifier LCF-3]` +4. **Every landing re-derives a stale lexical index before it lands, in the one writer (§5).** + `[PROPOSED, D12; falsifier LCF-4]` +5. **Destroy applies to a named instance only, is a dry run unless confirmed, and leaves a shared + cache of raw objects, vectors and downloaded sources at `~/.mind-palace/cache` (§6).** Only the + open sources' content enters the cache, never a private stratum's, and a purge reaches it. + `[PROPOSED]` +6. **The corpus instance declares its root, and its stores are read in place, read only, by the + regression and stress tooling (§7).** `[PROPOSED]` + +### 1.3 Out of scope + +The landing log itself (`core/stores/landings.py` and the catalog's writing methods, merged with +pull request #92) and the stages after it (dn-temporal-snapshot §12; the algebra of cuts on the +branch `feat/cut-algebra`), which this note reads and does not change; the erasure of what a purge +leaves in the stores it does not reach today (dn-temporal-snapshot §6.1), except the cache this +note adds; backups and migration archives; the curated store's second writer +(`scripts/curate_local.py`), which this note keeps out of the reset (§3.3); and the Keychain items +of a destroyed instance, which §6.2 names and leaves to the owner. + +## 2. What exists + +### 2.1 The reset at main + +`palace reset` (`scripts/palace.py:270-271`) calls `Launcher.reset(confirm=...)` +(`ops/lifecycle/launcher.py:1864-1893`). It refuses while the last run is active and its process +alive (`:1866-1869`), prints its targets, and without `--confirm` removes nothing (`:1877-1881`). +With it, it deletes each target with its `-wal` and `-shm` files (`:1882-1890`) and tells the +operator to export the notes into the vault again and start the daemon, which re-ingests them +(`:1891-1892`). `[ESTABLISHED]` + +The targets (`reset_targets`, `:1810-1862`) are the raw store, the vector store, the catalog, the +interpreted artifacts (`derived.sqlite`), the attestations, the queue, the version chains, the +authored supersessions, the verdicts and their dispositions, the code and agent observations, the +reference edges, the chat log, the chat events, the causal edges and the memberships. +`_RESET_GUARD` (`:111-118`) names what an assertion keeps out of the targets: the HashiCorp Vault +storage, the run ledger, the self-modification ledger, the telemetry, the commit ledger +(`code_snapshots.sqlite`), the observation history, the backup staging and the logs. +`[ESTABLISHED]` + +So the reset at main is a fresh start: it empties the instance's content and its record of how +the content came to be, and keeps the operational ledgers. Its last purpose stated in the code is +to re-tag every note `authored-solo` on re-ingest (`:1878-1880`). `[ESTABLISHED]` + +### 2.2 Where the code contradicts itself + +- **Raw is a target, and the chat sensor's design says it is not.** The chat log's module header + (`core/stores/chatlog.py:41-45`), the chat sensor's (`ops/chat_sensor.py:38-41`) and the + comment inside `reset_targets` (`launcher.py:1839-1843`) say the chat log is rebuilt by re-ingest + from the raw store and that raw is never a reset target. Raw is the first target + (`launcher.py:1815`), and has been since `b8f0d446` (2026-06-29), before the chat sensor existed. + The raw store holds the only copy of a transcript the CLI has pruned from its directory + (`ops/chat_sensor.py:12-15`), so the reset at main loses transcripts. `[ESTABLISHED]` +- **With raw kept, nothing rebuilds the chat log either.** The sensor stores each transcript + first and extracts only when the raw store reports the bytes new (`ops/chat_sensor.py:310-313`). + After a reset that kept raw, every transcript still on disk is reported unchanged and skipped, + and a transcript no longer on disk is never read. Nothing records which raw objects are + transcripts: the sensor writes no catalog row and no attestation (`ops/chat_sensor.py:3-9`). + `[ESTABLISHED]` +- **The lexical index and the relation edges outlive a reset** (dn-temporal-snapshot §2.3 item 7): + neither `lexical.sqlite` nor `edges.sqlite` is a target, so after a reset at main both hold rows + about items that are gone. `[ESTABLISHED]` +- **The authored relation edges are read from the vault's files, not from raw.** + `RelationDetector.authored` parses `Path(n.source_path)` from disk and skips a note whose file is + gone (`core/relations.py:123-158`). `[ESTABLISHED]` +- **Re-projection appends to a ledger.** The code sensor's projection of a commit emits an + attestation (`ops/code_sensor.py:492-500`), so a rebuild through it as written would append to + the attestation ledger. `[ESTABLISHED]` + +### 2.3 A stale lexical index blocks every landing + +The lexical index records the tokenizer its units were made by and refuses to land or to score +under another (`core/stores/lexical.py:159-182`, `TokenizerMismatch`). Only the lexical backfill +re-derives it (`core/ingest/derive.py:286-330`), and it runs in the `embed` job +(`scheduler/embed.py:39-48`) and `palace embed` (`launcher.py:1784-1807`). The `embed` job is +enqueued after a landing succeeds (`core/ingest/writer.py:216-219`). So an index left stale by a +tokenizer change refuses the landing whose success would have asked for its repair. This happened +on 2026-11-11, when pull request #90 was deployed: the code instance's index had been made by the +legacy tokenizer, the post-merge hook's `repo-sync` stopped at `LexicalStore.land_many` on every +run, and it was repaired by hand with `palace embed` (2,021 items re-derived in 11 s), after which +a `repo-sync` landed 110 files. `[ESTABLISHED]` + +## 3. The inventory + +Every store an instance writes, by class. Paths are relative to the instance's data directory +(`cfg.paths.data_dir`; `derived_store.parent` is the same directory under the default paths, +`config/defaults.toml` `[paths]`). This extends dn-temporal-snapshot §2.2, which lists the stores a +sentence can read, with the operational ones, and was checked against the code at `0a5fba27`, and +for the landing log at `8d4dff3d`. + +### 3.1 Ledgers: sources of truth, kept + +| store | writer | why it is a ledger | +|---|---|---| +| `raw/` (`core/kernel/stores/rawstore.py`) | the writer's derive step (`writer.py:407-412`), the chat sensor (`chat_sensor.py:310`) | the verbatim bytes; every derived store is a function of them; a purge is its one deletion (`rawstore.py:51-61`) | +| `vault_catalog.sqlite` (`core/stores/catalog.py`) | the writer's key (`writer.py:452-453`, `:466-467`), the vault sync, the founding, dialogue and curated landers | the map from path to digest, title, class and identity, with its landing log in the same file (§3.6) | +| the landing log: `landing_chains` and `landings` in `vault_catalog.sqlite` (`core/stores/landings.py`) | the catalog's writing methods, in the transaction of the row each writes, and the genesis at the first open of a catalog with rows and no log (`VaultCatalog._migrate`) | append-only and hash-chained: which digest each path held when; the catalog's rows are its fold (SNP-5). Kept whole with the catalog's file (`LANDING_LOG` in `ops/lifecycle/inventory.py`) | +| `versions.sqlite` (`core/stores/versions.py`) | `Writer.finish` for the place that keeps chains (`writer.py:438-448`) | the version chains of `mirror_authored` | +| `attestations.sqlite` (`core/attestation/store.py`) | the attestor, from the writer and the sensors | append-only, content-addressed; the record of who produced what | +| `chat_retention.sqlite` (new, §3.4) | the chat sensor, at retention | which raw objects are transcripts, in the order they were retained | +| `code_snapshots.sqlite` (`ops/code_snapshot.py`) | the code sensor | the commit ledger; already in `_RESET_GUARD` | +| `observation_history.sqlite` (`core/stores/observation_history.py`) | the code and self sensors, on supersession | superseded generations, whose interpreters no longer exist (self-sensing §2.5); already guarded | +| `reference_edges.sqlite` (`core/stores/reference_edges.py`) | the code sensor's projection | append-only, `INSERT OR IGNORE`; a commit's reading is the union of every projection so far, and the rows carry no extractor version (dn-temporal-snapshot §2.2), so a re-projection under today's extractor would not give the rows back. Kept: decision D3 | +| `query_log.jsonl` (`core/sentence/surface.py:59`) | the sentence surface | the record of what was asked | +| `runs.sqlite`, `selfmod_ledger.sqlite`, `effectors/effects.sqlite` | the launcher, the self-modification gate, the effectors | the system's own runs and acts | + +### 3.2 The owner's declarations: never derived, kept + +| store | writer | +|---|---| +| `authored_supersessions.sqlite` (`core/stores/authored_supersession.py`) | the owner's declarations, never model output (`authored_supersession.py:150-157`) | +| `verdicts.sqlite` (`core/stores/verdicts.py`) | owner-signed verdicts, verified before they are stored (`verdicts.py:1-9`) | + +The reset at main deletes both. A declaration cannot be computed from anything, so neither is a +reset's to clear. `[DERIVED]` + +### 3.3 Derived and regenerable: cleared and rebuilt + +Each is a function of the ledgers above, computed by code that runs without a model. The rebuild +runs in this order; each step reads only ledgers and the steps before it. + +| # | store | rebuilt from | by | +|---|---|---|---| +| 1 | `lexical.sqlite` (`core/stores/lexical.py`) | catalog, raw | `LexicalStore.reset`, then `derive_lexical` (`derive.py:286-330`) | +| 2 | the plane's occupancies and supersession log (`vectors.lance/plane.sqlite`, `core/stores/plane.py`) | catalog, raw, the atom table (§4.2), the cache (§6.5) | a reset of the plane's relations that keeps the atoms, then the drain (`derive.py:183-200`) over every plane class | +| 3 | `code_observations.sqlite` | commit ledger | `CodeSensor.backfill_observations` (`ops/code_sensor.py:827-844`), the attestor off; the reference edges it mints again are already held and are ignored (`reference_edges.py:290`) | +| 4 | `agent_observations.sqlite` | git's first-parent history of the build plans | `SelfSensor.sync` (`ops/self_sensor.py:248-270`), the attestor off | +| 5 | `memberships.sqlite` and the code atoms' occupancy (`core/stores/memberships.py`): replaced by §10 item 1, which keeps it (D14) | commit ledger, git | the code lane's `backfill` over `ledger_versions` (`scheduler/code_sync.py:59-76`), without the job's `capture_commit_diffs`, which appends to the commit ledger | +| 6 | the authored rows of `edges.sqlite` (provenance `authored-solo`) | catalog, raw | `RelationDetector.authored`, changed to parse each active note's raw bytes by its catalog digest instead of its vault file | +| 7 | `chatlog.sqlite` | the retention ledger, raw | a replay of the retention ledger (§3.4) | +| 8 | `chat_events.sqlite` | chat log, raw | `ChatEventProjector.project` (`core/chat_events.py:199-215`) | +| 9 | `causal_edges.sqlite` | chat events, commit ledger | `Integrator.integrate` (`core/integrator.py:97-116`) | +| 10 | `verdict_dispositions.sqlite` | verdicts | `apply_verdict` over every verdict in sequence order (`core/verdict/apply.py:68-77`) | + +Then the atoms that no occupancy and no membership holds are dropped, so the atom table holds +exactly what the rebuilt relations name (as built, the plane's occupancies alone, since the +membership store is kept: §10 item 1). Steps 2 and 5 are skipped by an instance that embeds +nothing; steps 3 to 5 by one whose code sensor and code lane are off; steps 7 to 9 by one that +reads no transcripts. A step with nothing to rebuild costs a read of its inputs. As built there is +no step 5 (§10 item 1). + +The interpreted rows of `edges.sqlite` stay: they are model output (§3.5). So the reset of that +store deletes the rows of provenance `authored-solo` and keeps the rest, the one derived store +cleared by rows and not by file. `[DERIVED]` + +The rebuild writes no ledger, save one case of the landing log: on a catalog that holds rows and +no log yet, the catalog's first open, which the rebuild makes, writes the log's genesis (§3.6). The +derivations above write only their own stores once the attestor is left out (steps 3 and 4) and +the reference edges are found held (step 3). An attestation from the first derivation still names +the same output, since the output is a deterministic function of the same input. `[DERIVED; the +property is P2 in §8, the genesis P17]` + +### 3.4 The chat log, and the ledger it needs + +The chat log is derived: its rows are a deterministic parse of the transcript's bytes (CS-1, CS-3; +`ops/chat_sensor.py:101-140`), and the session's id is read from the bytes too +(`record["sessionId"]`, `:130`). What is in no store but the chat log is which raw objects are +transcripts and in what order they were retained, and the order matters: the first write of a turn +stands (`chatlog.py:148-166`), and a session that later shows a candidate secret is held at its +state before it (`chat_sensor.py:316-322`), so the chat log is the fold of the retained transcripts +in retention order, not of the newest one. `[ESTABLISHED]` + +So the sensor gains a ledger, written at retention, before extraction (CS-1's order): + +```sql +CREATE TABLE IF NOT EXISTS retained ( + seq INTEGER PRIMARY KEY, -- the retention order + digest TEXT NOT NULL UNIQUE, -- the raw object's SHA-256 + file TEXT NOT NULL, -- the transcript's file stem when retained (for the report) + at TEXT NOT NULL -- wall bookmark only +); +``` + +A transcript whose bytes are new appends a row; the rest of `_ingest` is unchanged. The rebuild +replays the rows in `seq` order through the same parse, guard and `add_batch`, reading the bytes +from the raw store, so it needs no transcript directory. At its first open on an instance that +predates it, the ledger is filled from the chat log: one row per distinct `transcript_digest`, +ordered within a session by the lowest turn the digest wrote. A digest that wrote no row (refused, +empty, unparseable, or grown with no new prose) is not in that seed and changes nothing in a +replay, so the replay of the seed gives back the chat log as it stands. `[DERIVED]` + +The rebuilt chat log equals the one before under the same interpreter version and the same guard +patterns. Under a changed guard the replay is the re-derivation the change asks for: a session +refused before may land, or the reverse. `[DERIVED]` + +### 3.5 Model output, and what else cannot be computed again exactly: kept + +| store | why it is kept | +|---|---| +| `derived.sqlite` (`core/stores/derived.py`) | interpreted artifacts: a model's output over the notes the pass read (dn-temporal-snapshot §2.2). The reset at main deletes it. Decision D4 | +| the interpreted rows of `edges.sqlite` | a model's labels (`core/relations.py:198-210`) or a `link` request's (`writer.py:555-569`). Decision D4 | +| `run_ledger.sqlite`, `dream_runs.sqlite` | dream claims and experiment runs, with the surface text the model wrote | +| `claim_ops.sqlite` | proposals by design a model's (`core/kernel/recursion_ops.py:44-46`) | +| `staging.sqlite` | staged hypotheses, generation-clocked | +| `structural.duckdb` | invariants of the graph as it stood at each dream pass: a measurement of a past state that no ledger holds | +| `research_curated.lance` | its second writer adds rows with no catalog row and no raw object (`scripts/curate_local.py:96-108`), so they cannot be rebuilt. Decision D5 | +| `eval_results.duckdb`, `probes.sqlite` | measurements of the system | + +The causal edges are not in this table, though dn-temporal-snapshot §2.3 item 4 shows they are +not a function of their inputs' present state: the integrator resolves a commit against the +ledger as it stands at its pass. They are model-free, every input is kept, and a rebuild gives the +edges an integration over the present ledger gives, which resolves every commit the earlier passes +resolved and possibly more. So they are rebuilt (step 9), and their guarantee is weaker than the +others' (§4.4). Decision D6. `[DERIVED]` + +### 3.6 The catalog and its landing log + +The catalog is the head of every landed item and the idempotence key (ING-7). Since pull request +#92 its file holds its past as well: the landing log (`core/stores/landings.py`; +dn-temporal-snapshot §3.2, stage SN-1), two tables, `landing_chains` and `landings`, an +append-only, hash-chained record of which digest each path held when. The catalog's writing +methods append to it in the transaction of the row each writes, so the catalog's rows are the +log's fold (SNP-5). The sources the catalog was landed from may be gone, as a transcript may be, +as a dialogue export may be, so the log can be computed from nothing else, and the rows from +nothing but the log. `[ESTABLISHED]` + +- **The log is a ledger, and the reset keeps it.** The reset keeps the catalog's file whole, so it + keeps the log: every row and every chain's head hash, byte for byte, once the log is there (a + catalog with no log yet gets its genesis, the next items). `[DERIVED; P2]` +- **Nothing in the reset appends to it.** Two rebuild steps open the catalog: those of the + lexical index and the authored relation edges (`OPENS_CATALOG` in `ops/lifecycle/rebuild.py`). + Each reads its active rows (`active_entries`) and calls none of its writing methods. The plane + step reads no catalog row, since it rebuilds from raw what the plane held (§4.2), so it does not + open the catalog. The heal of §5 reads it through the writer's open stores, as the lexical step + does. The chat log's replay, the re-projections, the chat events, the causal edges and the + dispositions do not open it. `[ESTABLISHED; P2, P10, P17]` +- **The one write is the first open's.** `VaultCatalog`'s constructor sets WAL, runs its DDL and + migration, and on the first open of a catalog that has rows and no log writes the log's genesis + (`VaultCatalog._migrate`, `LandingLog.genesis`), which needs the instance's landing-log secret: + `landing-log-key`, or `.landing-log-key` under a named instance, read through the process's + configuration. So a reset of an instance whose catalog has rows and no log yet writes the genesis + at the rebuild's first open, after the clearing, as any first open on main does (the daemon's + start, a sync, a reader), and leaves the catalog's rows as they were. Without the secret that + open raises `LandingLogKeyMissing`, and by then it has created the log's two empty tables + (`executescript` commits the DDL before the genesis asks for the key; measured on a scratch + catalog), so opening the catalog cannot itself be the check. The reset reads the catalog read + only before anything is written and refuses without the secret (§4.5). With a log already in the + file the reset needs no secret: it appends no row and seeks no path by its key. + `[ESTABLISHED for the constructor; DERIVED for the reset; P17]` +- **What stays a follow-up.** The catalog's rows could be rebuilt as the log's fold instead of kept. + That needs a write of the catalog's table that bypasses its logging methods, which belongs in + `core/stores/catalog.py`, and it gives a reset nothing while the file is kept whole. The + version-keyed derived stores could be rebuilt for every version and not only the head: a replay + of the log's `store` and `retire` rows in chain order gives the lexical units, the plane's + occupancies and its supersession log of every version landed since the chain began + (dn-temporal-snapshot §5.2, §5.3 read the same stores as functions of a cut). A genesis records + each path's head alone, under a horizon (dn-temporal-snapshot §8), so for an instance whose + catalog predates the log the versions superseded before its genesis are in no ledger but + `mirror_authored`'s version chains. Both are decision D2. `[DERIVED]` + +### 3.7 Operational state: kept, not content + +`queue.sqlite`, `tasks.sqlite`, `telemetry.duckdb`, `supervisor.lock`, the ingress spools and +their receipts under the interface handoff directory, `handoff/dialogue/*.json` and their +`.synced` marks, `code/.synced`, `code_sensing_handoff/`, `agent_sensing_handoff/`, the +corpus sources' stream cursors, `logs/`, `backup-staging/`, `mint_ids_backup/`, +`reembed_bodyonly_backup/`, `effectors/drafts/` and the HashiCorp Vault storage in `vault/`. + +The reset at main deletes the queue. A queued job may carry an ingress request whose text is only +in the spool's `queued/` file, so deleting the queue loses a landing the operator asked for. The +reset keeps it. Every derived job kind in it (`embed`, `repository_sync`, the code lanes) is +idempotent and finds nothing to do after the rebuild. Decision D7. `[DERIVED]` + +## 4. Reset + +### 4.1 What it clears and what it keeps + +It clears the stores of §3.3, each by its own `reset` method or, for a store with none, by +deleting its file; and the rows of provenance `authored-solo` in `edges.sqlite`. It keeps every +other store of §3, byte for byte, the catalog's file whole with its landing log (§3.6), save the +log's genesis on a catalog that held rows and no log yet. The +classes are one table in `ops/lifecycle/` (the store's path +relative to the data directory, its class, and for a derived store its rebuild step), and +`reset_targets` and `_RESET_GUARD` are replaced by it. `[DERIVED]` + +### 4.2 The vectors without the embedder + +The atom table is a memo of one function: the embedder's vector of a text, keyed by the text's +hash (`plane.py:113-115`) under the geometry the plane records (`plane.py:154-166`). Keeping it +through a reset loses no derived state and keeps the rebuild from calling the embedder. So the +plane's reset for a lifecycle reset forgets the occupancies and the supersession log and keeps the +atoms and the recorded geometry. The rebuild re-occupies exactly the (path, digest) pairs the plane +held current before the clearing, read once with each occupancy's title and class and kept in the +marker (§4.3), and nothing more: an item a lazy instance landed without its vector stays waiting +for the embed job, so the plane comes back to its state before. Each pair is rebuilt from raw at +the digest the plane held, whether or not that digest is still the catalog's head: a note edited +after it was embedded, and landed again without its vector, comes back at the version the plane +held, and its new version stays with the embed job. Raw keeps every version, and a purge removes +an object's occupancies with it, so a held version can be read when a reset starts. A purge while +a reset is pending is the exception: the marker names the version and the cleared plane no longer +holds it, so the purge removes no occupancy, and the rerun skips the version and counts it (§4.3). +The step reads no catalog row, so it does not open the catalog (§3.6). The drain over those items +finds every atom held (`embed_missing`, `derive.py:146-180`) and embeds nothing; the atoms no +rebuilt row holds are dropped last. The `held` and `current` cache columns of the atom table are +repaired from the rebuilt relations by the plane's existing repair ratchet. A configured embedder that differs from the recorded geometry is +not a reset's business: the reset refuses and names `palace reembed` (§4.5). `[INFERENCE, +falsifier LCF-2]` + +### 4.3 What starts the rebuild + +The reset runs the rebuild itself, in its own process, after the clearing, under the instance's +supervisor lock (`ops/lifecycle/lock.py`), which the daemon and some of the writers take as well +(below). It writes a marker, `reset.pending` in the data directory, before it clears anything and +removes it when the last step has run. While the marker is there the daemon's start and every +command that lands into the instance or writes a store the reset rebuilds refuse, naming the +reset: the launcher's on-demand verbs, and the scripts that write (`scripts/ingest.py`, +`scripts/corpus.py ingest` and `embed`, `watch`, `purge_raw`, `ingest_self_knowledge`, +`mint_ids`, `migrate_chunk_keys`, `migrate_provenance_split`, `reembed_bodyonly`, +`ingest_founding`, the code and self sensors' `snapshot_code` and `sense_self`, which the +post-commit hook runs on every commit on main and whose failed sync it reports and lets the next +one heal, `verdict.py submit` and `review`, which apply dispositions, `talk`, which lands what the +inbox kept when no daemon is live, and the swap of the plane migrations `ops.plane_migrate` and +`ops.float16_migrate`). `palace destroy` refuses too (§6.1). So nothing starts to land into a +half-rebuilt instance. A test runs each of those scripts under the marker, and a scan of +`scripts/` fails on a script that calls a builder of a landing or of a derived store and is not +among them (§8, P9). Every step is idempotent, so `palace reset --confirm` run again after an +interruption clears the derived stores again and finishes. `[INFERENCE, falsifier LCF-5]` + +A writer reads the marker when it starts, so the marker does not stop one that started before +the reset. The lock stops those that take it: the daemon, `repo-sync`, `scripts/ingest.py`, +`scripts/corpus.py ingest` and `embed`, and `watch`. The other writers take none (the launcher's +`vault-sync`, `embed`, `dream`, `relate`, `lanes`, `reembed`, `ingest-chat`, `dialogue-sync` and +`cache fill`, and `purge_raw`, `ingest_self_knowledge`, `mint_ids`, `migrate_chunk_keys`, +`migrate_provenance_split`, `reembed_bodyonly`, `ingest_founding`, `snapshot_code`, +`sense_self`, `verdict.py submit`, `review`, `talk` and the two plane migrations), so a reset +confirmed while one of them runs is not excluded from it, and that writer goes on writing into the +stores the reset clears and rebuilds. Whether they should hold the lock for their whole run is +open question 7. `[ESTABLISHED]` + +A rerun finishes only if no step fails the same way every time, so whatever would stop a step +that way is either found before anything is written, the marker included, or tolerated by the +step. As built: a derived store that does not lie under the data directory (a store beside +`derived_store` configured elsewhere) would be refused by the clearing, so the reset finds it +first and refuses; a commit the commit ledger holds that the repository no longer has (a rewrite +and a garbage collection) would fail the code observations' re-projection, so the reset checks +every ledgered commit first and refuses, naming them (§4.5); a retained transcript whose raw +object a purge erased is skipped by the chat log's replay and counted as purged in its report, so +the erasure stands and the reset finishes (§6.6); and a version the plane held whose raw object a +purge erased while the reset was pending is skipped by the plane step and counted the same way +(§4.2). An instance whose commits are gone for good can be reset only once the loss is accepted, +which this note does not design (open question 4). `[DERIVED; P7, P9]` + +### 4.4 Its guarantees + +- **Nothing is lost.** Every store of §3.1, §3.2, §3.5 and §3.7 is byte for byte what it was: + a raw object's file, and every row of every table of a kept SQLite or DuckDB file, save the + landing log's genesis on a catalog that held rows and no log yet (the next item). `[DERIVED]` +- **The landing log is kept, and nothing is appended to it.** Every row of the log and each + chain's head hash are what they were, since no step writes the catalog (§3.6). On a catalog + with rows and no log, the rebuild's first open writes its genesis, as any first open does, and + the catalog's rows stay as they were. `[DERIVED; P2, P17]` +- **The rebuild converges to the state before.** For each derived store but the causal edges, the + head after the rebuild equals the head before, with the wall-time bookmarks left out + (`landed_at`, `observed_at`, `created_at`, `at`, `updated_at`; Law C4). The head is: every row of + the chat log, the chat events, the dispositions, the code and agent observations' current + readings and the authored relation edges; the current units and their postings, and the + version records of the current versions, in the lexical index; the current occupancies of each + plane class with their atoms' vectors; the current memberships (as built, kept and not + rebuilt: §10 item 1). Two purges are the exceptions: a transcript a purge erased since the last + rebuild, without which the chat log and the chat events come back, and a version the plane held + that a purge erased while the reset was pending, without which the plane comes back. `[DERIVED; + P3, P9]` +- **The head only.** The lexical units and plane occupancies of superseded versions, and the + plane's supersession log, are rebuilt for the current versions only (and for the versions the + plane held, §4.2). The landing log names every version landed since its chain began, so a replay + of it could rebuild them; that replay is a follow-up (§3.6). No query at `8d4dff3d` reads a + superseded version's lexical units or occupancies: the purge finds them by digest, and the + migration that re-keys the plane's rows reads them to re-key them (`rekey_store`, + `core/ingest/index.py`), which a head-only plane leaves nothing to miss. The re-derivation of a + stale index and the re-embedding after a model change already rebuild the head only. Decision + D2. `[ESTABLISHED for the readers; DERIVED]` +- **The causal edges equal a fresh integration over the present inputs**, and a reset run twice + gives the same edges. `[DERIVED; P4]` +- **No embedder call when the atoms are held, and no ledger written** but that genesis. + `[DERIVED; P2, P8, P17]` +- **A reset of a reset is the reset.** Two resets in a row leave the same state as one. `[P4]` + +### 4.5 Its refusals + +A live daemon (the last run active and its process the supervisor, `_supervisor_alive`, +`launcher.py:193-244`); the supervisor lock held by another writer; a configured embedder whose +geometry is not the one the plane records; a derived store that does not lie under the data +directory, and a commit the commit ledger holds that the repository no longer has (§4.3); and a +catalog that holds rows and no landing log while the instance's landing-log secret is not in the +environment, since the rebuild's first open of it would write the log's genesis (§3.6). The last +is read before any open (`catalog_without_log`, `landing_log_secret` in +`ops/lifecycle/rebuild.py`), for the steps that open the catalog, and its refusal names the item +the process reads. Each refusal says what to do, and writes nothing, the marker included: the +geometry is read from the plane's record read only (`geometry_mismatch`), not through the plane, +whose open would create its `-wal` and `-shm`, and the run ledger is not opened (§4.6). When a +reset is pending and the embedder has changed, the refusal says to finish the reset under the +embedder the plane was built with and to change the embedder after it, since `palace reembed` +refuses while the marker stands. + +### 4.6 Its dry run + +As today: without `--confirm` nothing is written. The dry run prints, by class, every store it +would clear with its row count, the rebuild's steps with the count of items each would read, the +stores it keeps, and for the plane the items it re-occupies, the distinct atoms they need and how +many of those the atom table lacks (the embedder is called for those alone), and the items of the +plane's classes whose current version holds no vector, which the reset leaves to the embed job; +the items the plane holds at a version older than the catalog's head are counted among both. When +the catalog holds rows and no landing log, it says the rebuild's first open writes the genesis. + +It writes no row of any store, and on an instance at rest it creates, removes and touches no file. +It reads each SQLite store it counts with `read_only` (`ops/lifecycle/inventory.py`): a store at +rest, with no `-wal`, or an empty one a reader left, and no `-journal`, has every committed page +in its main file and is read `immutable=1`, since a `mode=ro` read of a WAL database creates its +`-wal` and `-shm` and rewrites a `-shm` already there. A store whose `-wal` holds frames is read +`mode=ro`, which updates its `-shm`, since `immutable=1` would miss those frames; that is an +instance not at rest. The plane's geometry is read from its record read only, and the atoms the +table lacks are counted through the atom table, which opens no file of the plane's SQLite. The +launcher's run ledger, through which every command asks whether a run is live, is opened only +when a command writes to it and read only before that (`LazyRunLedger`), so the dry run creates +no file under a root that does not exist either. `[ESTABLISHED, measured on a fixture at rest and +through the command; P6, P11]` + +### 4.7 The landing log's secret, by command and instance + +The secret is read through the process's configuration (`landing_log_key`), so its item is the +instance's own: `landing-log-key` for the default instance, `.landing-log-key` for a named one +selected by `MIND_PALACE_OVERLAY`. `[ESTABLISHED]` + +- **A reset** needs it only while the catalog holds rows and no log: the rebuild's first open + writes the genesis. With the log in the file it needs none. Without it, when it is needed, the + reset refuses before anything is written and names the item (§4.5). `[ESTABLISHED; P17]` +- **A destroy and a cache fill** need none: they read the catalog read only and remove it, or + leave it, whole (§6.2). `[ESTABLISHED; P17]` +- **Under a named instance**, `scripts/run_with_secrets.sh` refuses to run, since it places the + default instance's items, so a reset that needs the secret is run with the instance's own item + in its environment under its own name (`docs/runbook.md` shows how). The default instance's item + does not serve a named instance. `[ESTABLISHED; P17]` +- **The corpus** is a named instance whose catalog has rows and no log yet (§7): a reset of it, + and any landing into it, needs `corpus.landing-log-key` placed first. + +## 5. A sync heals a stale lexical index + +`Writer.land` (`core/ingest/writer.py:205-219`) is where every landing into the lexical index +passes: the ingress's `perform` (`core/ingest/ingress.py:716-763`) builds a `Writer` for each +request, script and sync, and every command that lands calls it, through the daemon's handlers +(`scheduler/ingress.py:215`, `:273`) or through `run_library` (`repo_sync_now`, `vault_sync_now`, +the inbox at `core/ingest/inbox.py:121`, the corpus runner at `scripts/corpus.py:254`). Outside +the writer only `derive_lexical` writes the index: the older landers (`core/ingest/sync.py`, the +founding, dialogue and curated lanes) do not open it. So the writer heals the index, before it +prices the plan: when `stores.lexical` is +open and `stale`, it runs `derive_lexical(self.stores)`, which resets the index and lands every +active item of the lexical classes again under the current tokenizer, and then lands the plan. +`derive_lexical` is in `core/ingest/derive.py`, which `writer.py` already imports, so no new +dependency; the heal is one more stage of the landing, reported among the writer's timings as +`rederive`, which the receipt carries already (`ingress.py:758-759`). `[INFERENCE, falsifier +LCF-4]` + +In `writer.py` it changes `land`, adds `Writer.heal_lexical` and a `cache` field of `Stores` (the +vector cache of §6.5), and imports `derive_lexical` and `LexicalReport` from `derive.py`; it +leaves `finish` as it is, whose two key writes #92 changed. It changes none of `lexical.py` or +`landing.py` (pull request #93 changes them), `ingress.py` or `sync.py`. The heal +reads the catalog's active rows and appends nothing to its landing log: a healing sync's one new +row of the log is its own landing (P10). + +## 6. Destroy + +### 6.1 Scope and refusals + +`palace destroy` (in `scripts/palace.py` and `Launcher.destroy`) acts on the instance the +configuration selects (`MIND_PALACE_OVERLAY`), and only on a named one: the default instance is +refused by this command, whatever its state. Without `--confirm` it is a dry run. It refuses, and +writes nothing, when: the instance is the default one; a run of it is live; another writer holds +its supervisor lock; a LaunchAgent with its label (`cfg.instance.label`) is installed; its root's +real path lies inside a git working tree, is the home root `~/.mind-palace` itself, or holds the +cache; or the free space on the cache's volume is less than what the cache would gain plus a +margin. `[PROPOSED, D1]` + +As built, a root is removed only when it holds nothing but the instance's own state, since the +removal takes the whole root: it also refuses a root with a top-level entry no path of the +instance's namespaces lies at or under (`namespaces_of(cfg).paths`), an entry of the data +directory the class table does not name, a `.git` anywhere below it, a root at, inside or around +another declared instance's root (a derived root inside the checkout excepted, §10 item 5), a +source file the cache would take that is a link (§6.4), and a configured embedder that is not the +plane's geometry (§6.5). It refuses while a reset of the instance is pending, as `cache fill` +does: a reset interrupted after its clearing leaves the plane without the occupancies the fill +selects vectors by, so a destroy then would keep none of the instance's vectors (§10 item 28). +The dry run lists the root's top-level entries, and it takes no lock: it probes the supervisor +lock read only, reads the catalog's and the plane's SQLite files through `read_only`, and reads +the launcher's run ledger without opening it (§4.6), so on an instance at rest it creates and +touches no file, run as a command or in-process, and it creates no root that does not exist. The +loader accepts such a root for a named instance; only destroy refuses it. + +### 6.2 What it removes, and what it leaves + +It fills the cache from the instance (§6.4), then removes the instance's root, the declared one or +`/instances/`, without following a symbolic link out of it. The catalog's file goes with +the root, and the landing log in it. A destroy reads the catalog's rows read only and never opens +it through `VaultCatalog`, so it needs no landing-log secret, even for a catalog that holds no log +yet. It leaves what is not in the root: the sources the instance read outside it (a declared +vault, a transcript directory, a repository), its overlay in `config/instances/`, which is code, +and its Keychain items (`.`), which the dry run and the result name for the owner to +remove. `.landing-log-key` is among them: the instance's namespaces do not list it +(`namespaces_of(cfg).secrets`), so `keychain_items` adds it. After the destroy it keys nothing but +a copy of the catalog's file kept elsewhere, a backup's for one. `[PROPOSED]` + +The sources inside the root go with it: an open-corpus source's directory under the root's +`sources/`, of which the cache keeps the stream files (§6.4) and nothing else. The whole downloads +some edge readers keep under `/raw/` (`edge/corpus/`: arxiv, hackernews, openalex, +gutenberg, stackexchange), the cursors and the state files are removed with nothing kept. The dry +run names the sources it leaves, and those it removes with the count and bytes of their files the +cache does not take. `[ESTABLISHED]` + +### 6.3 The cache + +One place, `~/.mind-palace/cache`, shared by every instance of the machine's user, under the home +root and outside every instance's root and every checkout. Its layout: + +``` +~/.mind-palace/cache/ + LAYOUT the layout's version + raw// the raw store's own layout (`rawstore.py:24-26`) + vectors//atoms.sqlite atom id -> the vector as the plane stores it; names the + embedder (§6.5), its fields in vectors//key.json + sources// downloaded source files, with sources//MANIFEST + (file, size, SHA-256, when fetched) + purged.sqlite the digests a purge erased, with the day (§6.6) + uses.sqlite the day each entry was last put or taken, for retention +``` + +An entry holds no path, no title and no class: a raw object is named by its digest, a vector by +its atom id, which is the hash of its text, and the text is not stored with the vector. The +location is a constant of the code, as the instances' home is; a test passes a temporary +directory to the functions that take the cache's root. Retention: an entry stays until pruned. +`palace cache prune`, a dry run unless confirmed, removes the entries not taken for 180 days, and +`palace cache` reports the cache's size by namespace. `[PROPOSED, D8]` + +### 6.4 What may enter the cache + +The cache is a channel between instances, so what enters it is fixed in code, by an allow-list, +and everything else is refused. An item is **open** when its catalog path lies in the space of an +open-corpus source (`corpus//`, `core/ingest/table.py:454-455`) or a repository source +(`code//`, `:456-457`), or its class is `curated`. Then: + +- a raw object enters when some catalog row, active or tombstoned, names its digest at an open + item's path; +- a vector enters when its atom is held, current or not, by an open item's occupancy or by a code + membership (as built, by an open item's occupancy only: §10 item 2); +- a source file enters when it is a stream file of an open-corpus source (the stream's manifest + and the parts it names, and the items' metadata, which `scripts/corpus.py fetch` copies back + into an empty source), and a plain file of that source: not a symbolic link, not a file with + another hard link, not one that resolves out of the source's directory (`plain_file` in + `core/stores/cache.py`). Not a stream cursor, a checkpoint, or a whole download a reader keeps + under `raw/`, which no reader takes back from the cache. + +Nothing else: no raw object of `authored-solo` or `authored-dialogue` (the mirror's notes, the +dialogue), no observed item outside an open-corpus source (the dialogue's model turns, the inbox, +the sensors' readings), no transcript (the chat sensor's raw objects have no catalog row), no raw +object no catalog row names, and no digest in `purged.sqlite`. `[PROPOSED, D9]` + +Nothing of the catalog's file enters either. The fill reads the catalog's rows to select by path +and class and writes none of them: no row of the map, no row of the landing log, no chain's half +of the log's key and no part of the instance's secret reaches the cache. The source files are +chosen by name, and a name that is a link would carry other bytes in: the catalog's file, linked +or hard-linked from a stream part inside the root, or a note outside it. So a fill and a destroy +refuse a source file that is not a plain file of its source before they write anything +(`link_refusal` in `ops/lifecycle/destroy.py`), and the cache's own writer refuses it as well +(`Cache.put_source_files`), as `take_source` refuses a name that climbs out on the reading side. +P12 and P17 search every file of a filled cache for each of the log's values and find none, and +P12 links a stream part to the catalog's file, by a symbolic and by a hard link, and to a note, +and finds each refused. `[ESTABLISHED; P12, P17]` + +Why sharing an object held by an open item is safe even when a private item holds the same bytes: +a cache entry carries no path, title or class, so it says only that some open item held these +bytes, and the open item's source holds them in public. The same argument covers an atom shared by +a note and a corpus document. What would break it is an entry whose existence says something the +open sources do not, which the allow-list excludes by taking open items alone. `[DERIVED]` + +Reading the cache is not restricted by class: a lookup by hash of bytes the reading instance +already holds tells it only that some open item held them. A lookup that finds an entry does +write: it records the day the entry was taken, in `uses.sqlite`, which the prune reads. So when a +private note's chunk has the text of an open chunk, the cache records the day some instance took +that open atom, and nothing of the note: no path, no instance, no time finer than the day. +`purged.sqlite` holds the digest of every object a purge erased, a private note's among them, with +the day; a digest names content only to someone who holds the content, and it must be kept, or a +later fill would put the object back. `[DERIVED]` + +### 6.5 How an instance reuses the cache + +- **A vector, by atom.** The vector cache's key is the plane's geometry (`Fingerprint`: model, + document template, dimension) together with the runtime backend that served it + (`[runtime] embedding_backend`), hashed. `embed_missing` (`derive.py:146-180`) looks up the + atoms the plane lacks in the cache under the instance's key before it calls the embedder, and + lands a found vector as if embedded; `DrainReport` counts it as `cached`. A vector is reused only + under the same key, so a geometry never mixes, provided a vector is filed under the key of the + embedder that made it: a fill and a destroy refuse unless the configured geometry is the one the + plane recorded, as a reset does. The plane does not record the backend, so a change of backend + alone between embedding and a fill files the vectors under the new backend's key; whether to + record it is open question 5. `[PROPOSED; falsifier LCF-6]` +- **A raw object, by digest.** `RawStore.get` on a miss reads the cache's object, checks that its + SHA-256 is the digest asked for, and copies it in; a mismatch is refused and the entry deleted. + The address is the whole trust decision. This is how an instance takes a raw object it has a + digest for and no bytes: a catalog seeded from another instance's for a fixture (§7), or a + replay of the landing log (§3.6, a follow-up). +- **A source, by file.** An edge reader of an open-corpus source looks in `cache/sources//` + before it downloads, and takes a file whose size and SHA-256 match its manifest row. The entry's + trust is the trust of the download that filled it, on this machine. +- **Filling without destroying.** `palace cache fill`, a dry run unless confirmed, copies an + instance's open content into the cache by the same selection as destroy, without removing + anything. It is how the corpus shares its vectors with the instances that draw on it (§7). + +### 6.6 A purge reaches the cache + +`purge_raw` (`core/ingest/purge.py:40-62`) gains a step before it deletes the raw object: it reads +the object's bytes, derives its chunks as the landing did, and removes from the cache the raw +object and the vector of every atom of those chunks, under every key; then records the digest in +`purged.sqlite`. Every fill and every destroy refuses a digest recorded there, so no later +instance puts it back. The atoms are deleted and not recorded, since an atom's text may be held by +an open item whose content is public; the cost of deleting one an open item also holds is one +embedding. So the cache is no way around erasure. A transcript can be purged too: it has no +catalog row, so the gate passes, and a later reset's replay of the retention ledger skips its +digest and says so (§4.3). `[PROPOSED, D10]` + +## 7. The corpus at its own root + +`config/instances/corpus.toml` declares `[instance] root = "~/.mind-palace/instances/corpus"`, as +`config/instances/code.toml` declares its own, and its header says so in place of +`/instances/corpus/`. The loader already refuses a declared root inside a working tree +(`core/kernel/config/loader.py:1187-1210`), so the corpus can no longer land in a checkout. The +sources stay at `sources/` under the root (`[ingestion.corpus] root`), which is where the moved +data has them. The docs that name the old location are updated: `dn-corpus-instance.md` (§3, the +CIF-5 falsifier), the runbook's corpus section, `config/defaults.toml`'s comment and +`scripts/corpus.py`'s usage lines where they name a path; the dated experiment record +`docs/experiments/corpus-stage1-2026-11-07.md` is a record of its day and keeps its text, with +one line under its header saying where the data lives now. + +**A shared dataset.** Other instances draw on it in two ways, both read only: in place, through a +read-only open of its stores (SQLite with `immutable=1`, since a `mode=ro` connection to a WAL +database creates its `-wal` and `-shm` files; Lance read-only) for the regression reads; and +through the cache, once the corpus has filled it (`palace cache fill` under the corpus's overlay), +for a stress instance that lands corpus items and takes their vectors by atom and their raw +objects by digest instead of embedding again. Only the corpus's own tooling writes under its +root: `scripts/corpus.py` (its `ingest` and `embed` under the supervisor lock, its `isolation` +and `lexical` beside them) and the stage-1 measurements (`eval/corpus/`, into `results/`), and, +besides them, a confirmed lifecycle command run under its overlay. + +**The regression fixture.** A regression run reads fixed numbers off the corpus read only: the +catalog's count of active items, a lexical query's top hits, a `near` query's answer. Part B +reports the first two in the pull request, from a read-only check that the configuration resolves +the corpus to its root and that its stores open. + +**Never through `VaultCatalog`.** The corpus's catalog holds 400,274 rows and no landing log yet. +Opening it through `VaultCatalog` would write under the root: the WAL files, the migration, the +log's two tables and a genesis of 400,274 rows, or, without `corpus.landing-log-key`, refuse after +creating the two empty tables (§3.6). So a regression read opens the corpus's SQLite files with +`immutable=1` and its Lance table read only, and never opens the catalog through its class. The +check was run again on the rebased tree, with the landing log in the base and without +`corpus.landing-log-key` in its environment: the configuration resolves `corpus` to +`~/.mind-palace/instances/corpus`; the catalog holds 400,274 +rows, all active, in `vault_files` alone; the lexical index holds 1,369,944 units made by the +legacy tokenizer, and the query "superconductivity phase transition" returned the same five hits +as on 2026-11-12, in 17.37 s at a load average of 2.84; the Lance table holds 1,338,585 rows. A +snapshot of the whole root before and after, 389,745 entries (389,417 files, 18,949,782,338 +bytes) by type, size and modification time, showed no entry added, removed or changed. +`[ESTABLISHED, measured 2026-11-13]` + +**Reset and destroy of the corpus.** The corpus is a named instance, so both apply. A reset needs +`corpus.landing-log-key` placed first, since its first open of the catalog writes the genesis +(§4.7); a destroy needs no secret. The whole root is 18,949,782,338 bytes in 389,417 files; its +raw store is 387,838 objects of 1,003,892,779 bytes, by a snapshot of the root's metadata taken +on 2026-11-13. On disk the raw store takes about twice its bytes, one file per object in whole +blocks: the stage-1 record counts it at 2.0 GB of allocated blocks (`eval/corpus/footprint.py`). +A reset keeps the raw store and the catalog and rebuilds the lexical index and the +plane relations from them; it re-occupies only what the plane held, every atom of which the atom +table holds, so the embedder is not called, and the items still waiting for a vector stay with +the embed job. + +A `palace cache fill` would fill the cache with all of it, since every corpus item is open. Its +dry run, on a copy-on-write clone of the root (2026-11-13, 16.3 s at a load average of 2.87, 687 +MB resident), plans 387,838 raw objects (1,003,892,779 bytes), 468 source files of the six +sources (1,372,531,168 bytes) and 1,338,585 vectors, which the cache stores as float64 +(8,224,266,240 bytes): 10,600,690,187 bytes by the plan's count, which is what the room check +weighs. That count is of bytes, and the disk takes more: the cache stores the raw objects one file +each, as the raw store does, and the vectors in SQLite pages. The fill reads the vectors in +batches, so its memory does not grow with the plane. Its time, and the space it takes on disk, +are not measured. + +A destroy of the corpus refuses as the root stands. The root holds entries no namespace of the +instance names: some written at the root by the repository's own corpus tooling (the runner's +`isolation.json`, `gate.log`, `progress.json` and `progress-vectors.json`, and the stage-1 +measurements' `results/`), and some by nothing in the repository (`logs/`, +`progress-vectors-backfill3.json`, and `data/lexical-ascii`, which the class table does not name, +since it names the stores the repository's code writes). They would have to be moved out first; +whether the corpus tooling's own files at the root are the instance's state, for a destroy to +remove, is open question 8. A destroy would also remove the readers' whole downloads under +`sources//raw/` (810 files, 2,598,652,044 bytes, of which stackexchange's archives are +2,393,902,716) and the state files, none of which the cache takes (§6.2). Neither a fill nor a +destroy of the corpus is run by this pull request, and the runbook does not offer the corpus's +fill until its time is measured. + +## 8. What the build tests + +Each property is a test on fixture palaces under a temporary directory: notes in a vault, a +transcript through the chat sensor, a repository through `repo-sync` and the code lanes, verdicts, +an attestation trail, a model-free stand-in for the embedder that counts its calls. No test opens +a real instance. Lean adds nothing here that the tests cannot check: every property is about the +code's stores on finite fixtures, and the algebra the rebuild rests on (a fold of a log, the +catalog as that fold) is #92's and dn-temporal-snapshot's. + +- **P1, the inventory is total.** After a fixture exercises every lane, every path under the data + directory is in exactly one class of the table, and every `open_*` helper's path is in the table. +- **P2, a reset keeps every ledger.** Every raw object's file and every row of every table of every + store of §3.1, §3.2, §3.5 and §3.7 is the same before and after a confirmed reset, the attestation + ledger included, and the landing log's: on a fixture whose log has a genesis and landings, every + row of the log and each chain's head hash, and every chain still verifies. Two resets, and a + reset interrupted and finished, append nothing to it either (P4, P9). +- **P3, the rebuild converges.** For each derived store but the causal edges, the head of §4.4 + after a confirmed reset equals the head before, the wall-time bookmarks left out. +- **P4, a reset is idempotent.** Two confirmed resets leave the state one leaves, the causal edges + included. +- **P5, the chat stores come from raw.** With the transcript directory emptied after the first + sync, a reset gives back the chat log and the chat events as they were; a fixture with a grown + session and one held by the guard included. +- **P6, the dry run writes nothing**: no row of any store, and on an instance at rest no file + created, removed or touched (§4.6); it names every store it would clear. +- **P7, the refusals.** A live run, the lock held, a changed embedder geometry, a ledgered commit + the repository no longer has, a derived store outside the data directory: each refuses and + every byte is unchanged, and no marker is written. The live run is held by a ledger of its own, + as the daemon holds it, so the reset and a fresh launcher's on-demand verb read it from the file + (`LazyRunLedger.last`), with its frames in the `-wal` and after a checkpoint, and neither opens + its own ledger; once the run stops, neither refuses. +- **P8, no embedder call.** A reset of an instance whose atoms are held calls the embedder zero + times. +- **P9, an interrupted reset finishes.** A failure injected at each rebuild step leaves the + marker; the daemon's start and `repo-sync` refuse; a second `reset --confirm` finishes and P3 + holds. A purge, between the interruption and the rerun, of a version the marker names: the + rerun skips it, counts it and finishes. A changed embedder while the reset is pending: the + refusal names the way out, and the reset finishes once the embedder is restored. Every script + that writes refuses while the marker stands, before it opens anything, run with the builders it + would reach past the marker replaced by ones that fail at once; a scan of `scripts/` finds every + script that calls a builder of a landing or of a derived store among them; and the two plane + migrations refuse their swap and run their dry run. +- **P10, a sync heals a stale index.** A repository landed under the legacy tokenizer, its index + then opened under the current one: `repo_sync_now` lands where it raised `TokenizerMismatch` + before, and the index is no longer stale; the same through `Writer.land` for a vault plan. In + both, the one row the sync adds to the landing log is its own landing's: the heal adds none. +- **P11, destroy's refusals.** The default instance, a live run (held by a ledger of its own, as in + P7), the lock held, a pending reset, a root in a working tree, a root that is or holds the cache, + a symbolic link out of the root, a root holding a git repository or a file not the instance's + own, a root around another instance's, a changed embedder geometry: each refuses and writes + nothing, and once the pending reset has finished the fill selects every vector the plane held + before it; the dry run, on an instance at rest (every store + closed), creates, removes and touches no file, and names the sources it leaves and those it + removes. Run as commands in a process of their own, on a root at rest whose catalog has an empty + `-wal` and a `-shm` beside it, the dry runs of `destroy`, `reset` and `cache fill` create, + remove and touch no file, the run ledger included, and on a root that does not exist none of + them creates it. +- **P12, destroy keeps exactly the cache's classes.** After a confirmed destroy of a fixture with + notes, dialogue, a transcript, corpus items and a repository, the root is gone; the cache's raw + objects are exactly the digests open items named, its vectors exactly the atoms open items or + code memberships held (as built, open items only: §10 item 2), its sources exactly the open + sources' downloaded files; no raw object of a note, a dialogue turn or a transcript, and no + vector only a private item held, is in it; and no file of it holds a value of the landing log (a + chain's half of the key or its key check, a row's key of its path, commitment or hash), the + secret, or a table of the catalog's file. A stream part that is a link (a symbolic link to the + catalog's file, a hard link to it, a symbolic link to a note outside the root) refuses the + destroy and the fill, writing nothing, and the cache refuses to store it. So does a regular file + that resolves out of its source: the catalog's file reached through the stream directory linked + to the data directory, a link that stays inside the root, and through a manifest part that + climbs out of the stream. +- **P13, a cached vector is reused without the embedder.** A new instance under the same key + drains an item whose atoms are cached with zero embedder calls, and its vectors equal the cached + ones byte for byte; under another key it calls the embedder. +- **P14, a raw object is taken by digest and checked.** A cached object is copied in on a miss; a + corrupted entry is refused and removed. +- **P15, a purge reaches the cache.** After a purge of a digest, the cache holds neither its raw + object nor any vector of its chunks' atoms, the digest is recorded, and a later fill or destroy + of an instance holding it does not put it back. +- **P16, the corpus resolves to its root.** Loading the corpus overlay gives + `~/.mind-palace/instances/corpus` as the root and every data path under it (a configuration test + with a temporary home; the check of the real stores is the read-only one of §7, run once and + reported, not a test). +- **P17, the landing log through a reset and a destroy.** The steps that open the catalog, through + the rebuild's context or through `VaultCatalog` itself, are exactly `OPENS_CATALOG`, and the + clearing opens it never. On a catalog with rows and no log, a reset without the secret refuses, + its dry run too, with every row of every store unchanged and no log table created; with the + secret its dry run still writes nothing, and the confirmed reset writes the genesis at its first + open, the catalog's rows stay as they were, the log + holds one `store` for each of them and nothing more, and every chain verifies. Under a named + instance loaded through its overlay, the item is `.landing-log-key` and the default + instance's does not serve; a reset of a catalog that has its log needs no secret; a destroy + needs none, its dry run names the item among those it leaves, and the cache holds no value of + the log. + +## 9. Decisions for the owner + +Each is proposed, with the recommendation first. + +- **D1, destroy's scope.** Recommended: named instances only, the default instance refused by the + command whatever its state, a dry run unless confirmed. The alternative, a destroy of the default + instance behind a second confirmation, would remove the checkout's `data/` and the HashiCorp + Vault storage in it. +- **D2, a reset rebuilds the head of the version-keyed stores and keeps the catalog's rows.** With + the landing log in main (#92), the reset keeps the catalog's file whole, the log in it, and + appends nothing to it (§3.6). What D2 now covers is what the reset does not yet take from the + log: the lexical units and plane occupancies of superseded versions, and the plane's + supersession log, are rebuilt for the current versions (and those the plane held) only, and the + catalog's rows are kept rather than folded from the log. Recommended: accept both for now, and + make the log's replay a follow-up: every version landed since a chain began rebuilt from the + log's `store` and `retire` rows, and the catalog's rows as the log's fold through a write of the + catalog that bypasses its logging methods. The versions superseded before an instance's genesis + stay head-only, since no ledger but `mirror_authored`'s version chains holds them. The + alternative is to keep the lexical index and the plane's relations out of the reset until that + follow-up, which leaves the stale rows of §2.2 in place. +- **D3, the reference edges are a ledger.** Recommended: kept by the reset until their rows carry + the extractor's version; then the current extractor's rows become derived and the older ones + stay. +- **D4, model output is kept.** Recommended: the interpreted artifacts, the interpreted relation + edges, the dream claims, the claim operations, the staged hypotheses and the structural snapshots + are all kept by the reset. The reset at main deletes the interpreted artifacts. +- **D5, the curated store is kept whole** until its second writer lands through the catalog. +- **D6, the causal edges are rebuilt**, with the weaker guarantee of §4.4, rather than kept. +- **D7, the queue is kept** by the reset, which deletes it at main. +- **D8, where the cache lives and its retention.** Recommended: `~/.mind-palace/cache`, one + namespace per kind of entry, entries kept until a prune removes those not taken for 180 days, + pruning a dry run unless confirmed. +- **D9, what may enter the cache.** Recommended: the raw objects, vectors and downloaded files of + the open-corpus sources, the repository sources and the curated class; never a private stratum's + content, a transcript, or a digest a purge erased. Code enters because the repository it came + from already holds it on this machine; an owner who reads a private repository through an + instance may strike code from the list. +- **D10, a purge reaches the cache**, removing the raw object and its chunks' vectors and recording + the digest so it never enters again. +- **D11, the lexical index and the authored relation edges become reset targets**, rebuilt from + raw; the interpreted relation edges stay. +- **D12, a sync re-derives a stale lexical index before it lands**, in the one writer, for every + command that lands. +- **D13, the corpus's configuration** declares `[instance] root = "~/.mind-palace/instances/corpus"` + in `config/instances/corpus.toml`. +- **D14, the membership store is kept by the reset**, found in the build (§10 item 1). Recommended: + keep it, since it holds the code atoms' embedder ledger beside their occupancy and deleting it + would make the code lane embed every code atom again; `palace code-rebuild` stays what derives + it. The alternative is the design's step 5, a rebuild through the code lane's backfill, which + first needs that ledger moved out of the store. + +## 10. As built + +Part B built §3 to §8 with these departures, each found in the code: + +1. **The membership store is kept, not rebuilt (§3.3 step 5).** `memberships.sqlite` holds the code + atoms' embedder ledger (`MembershipStore.record_atoms`, `known_atoms` by embedder identity) + beside the occupancy rows, so deleting the file would forget which code atoms the plane holds + and make the code lane embed them again. It is classed as kept; `palace code-rebuild` remains + what derives its occupancy. The rebuild runs steps 1 to 4 and 6 to 10. +2. **Code membership vectors do not enter the cache (§6.4).** No reader takes a code atom back from + the cache (the code lane does not look there), so caching them would store what nothing reads. + The vectors that enter are the plane's prose atoms held by open items. +3. **The reuse wiring is `with_cache`, not `build_stores` (§6.5).** `core/ingest/ingress.py` was + being changed by pull request #89 when this was built, so the cache is attached to the writer's + stores by `core.stores.cache.with_cache` where the drain runs: the embed job, `palace embed`, + the reset and the corpus runner. A landing through `run_library` alone does not take raw + objects from the cache. #89 has since merged; wiring the cache through `build_stores` is left + as a follow-up. +4. **A source is reused when its stream is empty (§6.5).** The reuse is `scripts/corpus.py fetch` + copying a cached stream, checked file by file against its manifest, into a source that has none + before the reader resumes it. So the cache takes a source's stream files. Some edge readers also + keep whole downloads under `raw/`, which the cache does not take, since no reader looks for + them there; a destroy removes them with the root, and its dry run counts them (§6.2). +5. **A derived root `/instances/` may be destroyed (§6.1, §6.2).** It lies in a working + tree but is the gitignored instance directory §6.2 names; any other root in a working tree + refuses. A root that is itself a symbolic link refuses too. +6. **A rebuild step whose input store is absent writes nothing**: the chat events without a chat + log, the causal edges without chat events, the agent observations without a repository, so a + reset creates no empty store an instance never had. +7. **The vector drain keeps only a cached vector of the plane's width**, so a cache filled under a + key whose geometry the configuration names but the plane does not hold is never landed. +8. **The corpus's lexical index predates the recorded tokenizer.** The read-only check of §7 found + no `meta` table: by the store's own rule its units are the legacy tokenizer's, so the next + landing into the corpus re-derives its 1,369,944 units before it lands (§5). + +An audit of the build found these, and the build was changed to match the design's guarantees: + +9. **The plane step re-occupies what the plane held, not every pending item (§4.2).** Draining every + pending item embedded a lazy instance's backlog inside the reset. The (path, digest) pairs the + plane held current are read before the clearing and kept in the marker. A second audit found + that the step still rebuilt only the pairs that were the catalog's head, so a held note edited + since it was embedded lost its occupancy; each held pair is now rebuilt at its own digest, with + the occupancy's title and class. +10. **A step's inputs are checked before the clearing, or tolerated (§4.3).** A pruned ledgered + commit refuses the reset before anything is written; a purged transcript is skipped by the + replay. +11. **Destroy removes only the instance's own state (§6.1).** A root holding anything else, a git + repository below it, or another instance's root refuses; the dry run probes the lock without + creating it. +12. **A fill files vectors only under the plane's own geometry, and streams them (§6.5, §7).** The + plan counts atoms; the fill reads and writes 2,048 vectors at a time. +13. **The cache records its uses and purges to the day (§6.4)**, and `take_source` refuses a + manifest name that is absolute or climbs out of its directory. +14. **`clear` checks that every store it clears lies under the data directory (§4.1)**, the check + `reset_targets` made before it was replaced. +15. **The corpus is read with `immutable=1` (§7).** The first read-only check opened its SQLite files + with `mode=ro`, and on a WAL database that creates the `-wal` and `-shm` files: on 2026-11-12 it + created an empty `lexical.sqlite-wal` and a `lexical.sqlite-shm` under the corpus root and + touched `vault_catalog.sqlite-shm`, with no row changed. The check was run again with + `immutable=1`; a snapshot of the data directory and the Lance tree before and after showed no + entry created, removed or touched. + +Part C rebased the branch onto `8d4dff3d`, with the landing log of #92 in the base, and made the +lifecycle correct with it: + +16. **The reset keeps the catalog's file whole, its landing log in it, and appends nothing to the + log (§3.6).** The inventory names the log as a ledger in the catalog's entry (`LANDING_LOG`). + P2 now checks every row of the log and each chain's head hash, and P4, P9 and P10 that two + resets, an interrupted one and a healing sync append nothing. +17. **A reset refuses before a genesis it has no secret for (§3.6, §4.5).** Found in the code: the + steps that open the catalog do so after the clearing, and the constructor's genesis needs + the secret, so a missing secret would have stopped a reset with its derived stores cleared and + the marker left; and the constructor without the secret raises after `executescript` has + created the log's two empty tables, so opening the catalog cannot be the check. The reset reads + the catalog read only first (`catalog_without_log`) and refuses, naming the item, with nothing + written. `OPENS_CATALOG` names the steps that open it, and a test records every open. +18. **Destroy names the landing log's item (§6.2).** Found in the code: the instance's namespaces + (`namespaces_of(cfg).secrets`) do not list `.landing-log-key`, so the dry run did not name + it among the items a destroy leaves; `keychain_items` adds it. +19. **The lifecycle's SQLite readers create no file (§4.6, §6.1).** Found by a probe on a fixture + at rest: destroy's dry run created the catalog's and the plane's `-wal` and `-shm` files, since + its readers opened them `mode=ro`, and P11 passed only because the fixture held its stores open. + The readers of the destroy and of the reset go through `read_only`, the fixture's own reader + too, and P11 runs on an instance at rest. The reset's dry run still opened the plane through + the vector store, until item 25. +20. **The corpus check was run again on the rebased tree, over the whole root (§7)**, never through + `VaultCatalog`, which on the corpus's catalog would write the log's genesis or refuse. + +An audit of part C found these, and the build was changed to match: + +21. **The plane step opens no catalog, and skips a held version a purge erased (§3.6, §4.2, + §4.3).** It read no catalog row and opened the catalog anyway, so a reset whose only + catalog-opening step was the plane wrote a genesis, or needed the secret, for nothing; it no + longer opens it, and `OPENS_CATALOG` is the lexical index and the authored relation edges. A + purge between an interrupted reset and its rerun could erase a version the marker named, and + every rerun then failed at the plane step with the marker left; the step now skips such a + version and counts it, as the chat log's replay skips a purged transcript. +22. **Whatever stops a rebuild every time refuses before the marker (§4.3, §4.5).** The check that + a derived store lies under the data directory ran in the clearing, after the marker was + written, so a store configured outside it left the marker on every rerun; it now runs with + the other preflights, and the clearing keeps it as its own guard. +23. **Every script that writes reads the marker (§4.3).** `purge_raw`, `ingest_self_knowledge`, + `mint_ids`, `scripts/corpus.py embed`, `watch`, `migrate_chunk_keys`, + `migrate_provenance_split` and `reembed_bodyonly` did not; each now refuses while it stands, + before it opens anything. The exclusion of a writer that started before the reset is open + question 7. +24. **A source file that is a link enters no cache (§6.4).** The fill takes source files by name, + so a stream part linked to the catalog's file inside the root, or to a note outside it, put + that file into the cache; destroy refused only links out of the root, and `cache fill` none. A + fill and a destroy now refuse a source file that is not a plain file of its source, and the + cache's writer refuses one too. +25. **The dry runs write nothing through the command (§4.5, §4.6, §6.1).** The launcher opened its + run ledger when it was built, so every command, a dry run or a refusal of reset, destroy or + cache fill included, created `data/runs.sqlite`, and under a root that did not exist created + the root; a store with an empty `-wal` left by a reader was read `mode=ro`, which rewrote its + `-shm`; and the reset's geometry check opened the plane. The ledger is now opened at its first + write and read only before (`LazyRunLedger`), a store whose `-wal` is empty is read + `immutable=1`, and the geometry is read from the plane's record read only. A test runs the + three commands in a process of their own. +26. **Destroy's dry run names what it leaves and what it removes (§6.2).** It said it left "its + sources" while it removed the sources inside the root, whose whole downloads the cache does not + take; it now names the sources it leaves outside the root, and those it removes with the count + and bytes of their files the cache does not take. A reset pending under a changed embedder now + refuses with the way out, since `palace reembed` refuses while the marker stands (§4.5). +27. **Every command that lands or writes a derived store reads the marker (§4.3).** Item 23 left + out the founding ingest, the code and self sensors' syncs, which the post-commit hook runs on + every commit on main, and `verdict.py submit`; a search of every entry point under `scripts/` + and `ops/` found the review REPL, the live talk loop and the swap of the two plane migrations + as well. A founding item landed while the marker stood kept its active catalog row and lost its + vectors at the rerun, which re-occupies only the versions the marker names, and the code + sensor, run under the marker in a test, began syncing the repository's whole history. Each now + refuses while the marker stands, before it opens anything; the migrations' dry runs, which swap + nothing, still run. A test runs each script under the marker, with the builders it would reach + past it replaced by ones that fail at once, and a scan of `scripts/` fails on a script that + calls a builder of a landing or of a derived store and is not run that way. The scan reads + `scripts/` alone; the runnable modules under `ops/` were read, and of them only the two + migrations write a store the reset rebuilds. +28. **A destroy refuses a pending reset (§6.1).** It did not read the marker, so after a reset + interrupted past its clearing it filled the cache with no vector, the plane holding no + occupancy, and removed the root, neither its dry run nor its result saying why. It now refuses + while the marker stands, as `cache fill` does, and once the reset has finished the fill selects + every vector again. +29. **Two guards had no test (§4.6, §6.4).** The commands' run ledger, read from the file until a + write opens it, is the live-daemon check of every command that only asks, and the live-run + tests opened the run through the launcher's own ledger, so they read it through that + connection; the run is now held by a ledger of its own, as by the daemon. A source file is + refused when it resolves out of its source, which is the one guard against a regular file + reached through a directory link inside the root, which destroy's scan allows, or through a + manifest part that climbs out of the stream; P12 now reaches the catalog's file both ways. Each + guard was removed in turn, and a test failed. +30. **A test of the tier wrote the checkout's data directory (§3.4).** The chat sensor's wiring + test built the sensor on the default configuration, so it opened the chat log, the raw store + and the retention ledger in the checkout's data directory, and seeded the ledger from the chat + log there. The deploy gate runs the tier in the checkout of the running instance while its + daemon still runs the code before the ledger, so the test would seed that instance's ledger + early; a transcript the old daemon retained after it would get no row, since the new daemon's + start seeds nothing again, and a replay would rebuild its session from a later digest, or not + at all when the guard holds that one. The test now opens its stores under a temporary + directory. A seed run at every build, adding the chat log's digests the ledger lacks, would + close such a gap whatever opened it; it is open question 9. + +## Falsifiers + +- **LCF-1 (the inventory is not total):** a store written by a lane the fixtures exercise that the + class table does not name. P1 finds it. +- **LCF-2 (the atoms are not a memo):** a reset whose drain lands a vector that differs from the one + the plane held for the same atom under the same geometry. +- **LCF-3 (the chat log is not the fold of the retained transcripts):** a fixture whose replay of + the retention ledger gives a chat log that differs from the one the sensor built. +- **LCF-4 (the heal is not enough):** a landing that still raises `TokenizerMismatch`, or a command + that lands into an instance without passing `Writer.land`. +- **LCF-5 (the marker leaks):** a writer that starts while `reset.pending` exists and lands, or a + script under `scripts/` that calls a builder of a landing or of a derived store and is not run + under the marker by P9. A writer that started before the reset and takes no lock is not + excluded by the marker (§4.3, open question 7). +- **LCF-6 (the vector key is too coarse):** two instances under the same key whose embedders give + one text vectors with a cosine below 0.9999; then the key needs the model file's digest. +- **LCF-7 (the rebuild writes the catalog):** a reset of a catalog that has its landing log after + which the log holds a row it did not hold, or a chain's head hash differs; or a step that opens + the catalog and is not in `OPENS_CATALOG`. P2 and P17 find it. + +## Open questions + +1. The vector key names the model and the backend but not the model file. A requantized file under + the same name would share a key (LCF-6). The llama.cpp backend can report the file it serves; + whether to put its digest in the key is open until a measurement says the geometry moves. +2. The default instance has no destroy. Whether it needs a command that empties it to a fresh start + (the reset at main's old purpose) is open; this note gives none, by decision 4. +3. A reset of the corpus re-derives its 1,369,944 lexical units from raw and re-occupies the plane + over its 1,338,585 stored vectors; its time at that size is not measured here. +4. A commit the commit ledger holds and the repository has lost refuses every reset of the instance + (§4.3). Whether a reset may then drop that commit's code observations, and on what + confirmation, is a decision this note leaves open. +5. The plane records its geometry (`Fingerprint`: model, document template, dimension) but not the + runtime backend that served the embedder, and the vector cache's key names both (§6.5). A + change of backend alone between embedding and a fill is not caught: the fill files the plane's + vectors under the new backend's key. Catching it needs the plane to record the backend, as a + new key of its `meta` table written beside the geometry at the first landing, checked by the + fill, the destroy and the reset as the geometry is, with a rule for a plane that predates the + key. Whether to make that schema change is open. +6. Whether the landing log's genesis should move off a catalog's first open is open with the owner + (dn-temporal-snapshot §12, SN-1). Moved off it, a reset would never need the secret, and the + refusal of §4.5 would go with it. +7. A reset excludes a writer that starts after it (the marker) and one that holds the supervisor + lock, but not an on-demand writer that takes no lock and started before it (§4.3): such a + writer goes on writing into the stores the reset clears and rebuilds. Closing that needs every + writer to hold a lock the reset takes for the writer's whole run. Either every on-demand + writer takes the supervisor lock, as `repo-sync` and `scripts/ingest.py` do, which widens the + lock beyond the supervisor role dn-supervision-and-liveness §2.6 gives it and makes two + on-demand writers exclude each other; or the writers share a lock the reset takes alone. Which + one is a decision this note leaves open. +8. The corpus tooling writes files at the corpus's root that no namespace of the instance names + (§7): the runner's `isolation.json`, `gate.log`, `progress.json` and `progress-vectors.json`, + and the stage-1 measurements' `results/`. A destroy refuses such a root until they are moved + out. Whether they are the instance's own state, for a destroy to remove with the root, and + whether the measurements' results should be kept elsewhere first, is a decision this note + leaves open. +9. The retention ledger is seeded from the chat log once, at its first open (§3.4). A transcript + retained after that seed by code that writes no row, a daemon still running the code before + the ledger or one a rollback put back, gets none, and a replay rebuilds its session from a + later digest, or not at all when the guard holds that one (§10 item 30). A seed run at every + build, adding each digest of the chat log the ledger lacks, closes that gap, but it appends + after the rows already there: the turns a missing digest first wrote are then replayed from the + later digest before it, and the rebuilt chat log names that digest for them. Placing a digest + at its retention position needs an order the ledger does not keep. Whether to seed at every + build, and how to order what it adds, is a decision this note leaves open. + +## Cross-references + +- dn-temporal-snapshot §2.2 (the inventory), §2.3 item 7 (the reset as it was), §3.2 (the landing + log, SN-1, merged with #92), §5.2 and §5.3 (vectors and the lexical index as functions of a + cut), §6.1 (what a purge leaves), §8 (horizons), §12 (the genesis at the first open); the + algebra of cuts on the branch `feat/cut-algebra`, which amends it. +- chat-sensor CS-1 and CS-3; `core/stores/chatlog.py` header (the chat log as a derived layer). +- self-sensing §2.5 (readings rebuilt, history kept); code-observation-projection §2.4, §2.5. +- dn-two-phase-ingestion D1 (the vector and the units as derived fields); dn-embedder-use (the + tokenizer's identity). +- dn-palace-lite (`[instance] root`); dn-corpus-instance §3 (the corpus's namespace). +- verdict-authority §3, §4 (the verdicts and their application). diff --git a/docs/experiments/corpus-stage1-2026-11-07.md b/docs/experiments/corpus-stage1-2026-11-07.md index 7324bc56..e40068e8 100644 --- a/docs/experiments/corpus-stage1-2026-11-07.md +++ b/docs/experiments/corpus-stage1-2026-11-07.md @@ -15,6 +15,9 @@ links: # Corpus stage 1: about a gigabyte of open text in a named instance +> Where the data lives now: `~/.mind-palace/instances/corpus` (moved 2026-11-11; the +> `instances/corpus` this report names is a symbolic link to it; dn-instance-lifecycle §7). + **Question.** dn-corpus-instance §6 asks stage 1 two things: whether the sources connect, and whether crowding is real at a million chunks; and it names the measurements that answer them and the falsifiers that would say no. This report gives what was built, what was ingested, and every diff --git a/docs/runbook.md b/docs/runbook.md index 23d579be..3c7f2103 100644 --- a/docs/runbook.md +++ b/docs/runbook.md @@ -35,11 +35,10 @@ mind-palace query '' # ask a sentence of the query algebra, read-onl # Remote dashboard + chat from your phone: set [monitor] enabled=true + host=, then # `mind-palace start` spawns it → http://:8787 (see "Remote dashboard + chat" below) -# --- FRESH START (done 2026-06-29; re-runnable) — see "Fresh start" below --------------------- -launchctl bootout gui/$(id -u)/com.mind-palace.watch 2>/dev/null # retire the old watcher -mind-palace reset --confirm # hard-wipe corpus (Vault guarded) -# …then re-export notes into ~/.mind-palace/vault/janus_notes/ + point Synctrain there… -mind-palace start # re-ingests as authored-solo +# --- RESET / DESTROY: see "Instance lifecycle" below ------------------------------------------- +mind-palace reset # dry run: the derived stores a reset clears and rebuilds +mind-palace reset --confirm # clear them, rebuild from raw + the ledgers (nothing is lost) +mind-palace destroy # dry run (named instances only): what the shared cache keeps # --- ONE-TIME ENABLEMENT ---------------------------------------------------------------------- mind-palace ingest-self-knowledge # so "how do you work?" answers from docs @@ -992,7 +991,7 @@ every owner-facing script — see the quick-reference above and `mind-palace hel mind-palace status # preflight checklist + recent runs mind-palace start # the full system, foreground (Ctrl-C = drain) mind-palace stop # graceful drain of the live run (from another shell) -mind-palace reset --confirm # the fresh-start corpus wipe (see below) +mind-palace reset --confirm # clear the derived stores and rebuild them (see "Instance lifecycle") ``` **What `start` does:** seals the core → preflight (ensure data dirs; verify Ollama up, Vault @@ -1025,23 +1024,12 @@ knob can be correlated to the run/commit it was tuned during. `launchctl bootstrap` / `bootout` commands, including retiring the old `com.mind-palace.watch`). Logs at `data/logs/palace.{out,err}.log`. `ExitTimeOut=120` is the drain window before launchd escalates to KILL. -### Fresh start — wipe the corpus + re-export notes (executed 2026-06-29; re-runnable) +### Fresh start (2026-06-29): the reset's old behaviour, replaced -`palace reset` surgically wipes the **corpus + derived layer** (raw, vectors, vault catalog, the now- -stale attestation chain, the queue) and is hard-guarded to **never** touch the production Vault Raft -store (`data/vault`), the run/self-mod ledgers, telemetry, backups, or logs. It refuses while a run is -live. Sequence for a clean re-export onto the new Synctrain-over-Tailscale setup: - -```sh -launchctl bootout gui/$(id -u)/com.mind-palace.watch 2>/dev/null # stop the old watcher first -mind-palace reset --confirm # hard-wipe the corpus (restic = net) -# re-export your notes into ~/.mind-palace/vault/janus_notes/ and point Synctrain there -mind-palace start # re-ingests everything as authored-solo -``` - -`[ingestion.vault] path` is set to `~/.mind-palace/vault/janus_notes` (config/ouroboros.toml) so only that synced -subdir is ingested — old/stray files in the vault root are ignored. A fresh re-ingest tags everything -`authored-solo` natively, so the provenance-split migration is **not needed** after a reset. +On 2026-06-29 `palace reset` wiped the raw store, the catalog, the attestations and the derived +stores so the notes could be exported again and re-ingested as `authored-solo`. That reset is gone: +it deleted the only copy of the transcripts the CLI had pruned, and the owner's decision of +2026-11-11 is that a reset loses nothing. What `reset` does now is in "Instance lifecycle" below. ### Remote dashboard + chat — the edge monitor over Tailscale (owner-operated) @@ -1067,6 +1055,127 @@ network** (only counts + the *shape* of activity). It is deliberately NOT sealed --- +## Instance lifecycle: reset, destroy, the shared cache (dn-instance-lifecycle) + +**Reset** clears an instance's derived stores and rebuilds them from the raw store and the ledgers +(`ops/lifecycle/inventory.py` is the one table of what each store is). It keeps the raw store, the +catalog with the landing log in its file, the version chains, the attestations, the chat sensor's +retention ledger, the commit ledger, the reference edges, the verdicts, the authored +supersessions, every model output and the queue, row for row; no step appends to the landing +log, and only on a catalog with rows and no log yet does the rebuild's first open of it write the +log's genesis (below). It rebuilds, in order: the lexical index, the plane's occupancies (the +atoms are kept, so no embedder is called while they are held), the code and agent observations +(re-projected without the attestor), the authored relation edges (parsed from raw), the chat log +(replayed from the retention ledger, with no transcript directory), the chat events, the causal +edges and the verdict dispositions. The plane step re-occupies only what the plane held current +before the clearing, each at the version it held, so on a lazy instance the items still waiting +for a vector stay with the embed job, and a note edited since it was embedded stays searchable at +its old version until the embed job takes the new one. It refuses a live daemon, the supervisor +lock held, an embedder whose geometry is not the plane's (that is `palace reembed`), a derived +store configured outside the data directory, a commit the commit ledger holds that the repository +no longer has, and, when the catalog holds rows and no landing log yet, an environment without +the instance's landing-log secret, since the rebuild's first open of the catalog writes the log's +genesis; each refusal writes nothing, its marker included, and neither does the dry run. A +transcript a purge erased is skipped by the chat log's replay, and a version the plane held that +a purge erased while a reset was pending by the plane step; each step's report counts them. + +```sh +mind-palace reset # dry run: each derived store with its rows, every kept store by class +mind-palace reset --confirm # under the supervisor lock, behind data/reset.pending +``` + +While `data/reset.pending` exists the daemon's start and every command that lands or writes a +derived store refuse: the on-demand verbs, and the scripts that write (`scripts/ingest.py`, +`scripts/corpus.py ingest` and `embed`, `purge_raw`, `ingest_self_knowledge`, `mint_ids`, `watch`, +`ingest_founding`, `verdict.py submit`, `review`, `talk`, the migrations, and the code and self +sensors' `snapshot_code` and `sense_self`, so a commit on main meanwhile has its post-commit hook +report a failed sync, which a sync after the reset heals). So does `destroy`. Each reads the +marker when it starts, so it does not stop a writer already running, and only some writers take +the supervisor lock the reset takes (the daemon, `repo-sync`, `scripts/ingest.py`, the corpus +runner, `watch`): run a reset when no on-demand command (`embed`, `vault-sync`, `lanes`, `dream` +and the like) is running (the note's open question 7). If a reset is interrupted, run +`reset --confirm` again: it clears and rebuilds every store the marker names. If the embedder was +changed meanwhile, the reset refuses: restore the embedder the plane was built with, finish the +reset, then change it with `palace reembed --confirm`. A reset rebuilds the current version of +each item only (decision D2); no query reads a superseded version's units or occupancies, and +rebuilding every version from the landing log is a follow-up. + +**The landing log's secret, for reset and destroy.** A reset needs it only while the catalog holds +rows and no landing log (an instance last written before the log came in): the rebuild's first open +of the catalog writes the log's genesis, as any first open does. The dry run says when, and a +reset that needs the secret and lacks it refuses, naming the item. Once the log is in the file, a +reset needs no secret. A destroy and a cache fill need none: they read the catalog read only and +remove it, or leave it, whole. The item is the instance's own (§0): the wrapper places the default +instance's, and refuses a named instance, so a named instance's reset that needs the secret is +given its own item under its own name: + +```sh +mind-palace run-with-secrets mind-palace reset --confirm # the default instance +env ".landing-log-key=$(security find-generic-password -a mind-palace -s .landing-log-key -w)" \ + MIND_PALACE_OVERLAY=config/instances/.toml mind-palace reset --confirm +``` + +**Every landing heals a stale lexical index.** When the index's tokenizer is not the current one, +the writer re-derives it before it lands (the `rederive` stage of the receipt's timing), so a +tokenizer change no longer stops `repo-sync` until `palace embed` is run by hand. On the corpus +instance this is a re-derivation of its whole index at the next `scripts/corpus.py ingest`: its +index predates the recorded tokenizer (checked read only on 2026-11-12). + +**Destroy** removes a named instance (never the default one) and leaves its open content in the +shared cache, `~/.mind-palace/cache`: the raw objects and vectors of the open-corpus sources, the +repository sources and the curated class, and the open-corpus sources' stream files. Nothing of +the mirror's notes, the dialogue or the transcripts enters it, and no source file that is a link. +It refuses a live run, the lock held, a pending reset (finish it first: a reset interrupted after +its clearing leaves the plane without the occupancies the fill takes vectors by), an installed +LaunchAgent, a root inside a git working tree, a root that is the home root, holds the cache or +holds a symbolic link out of itself, a root that holds anything but the instance's own state (a git +repository below it, a file no namespace of the instance names, another instance's root), a source +file the cache would take that is a link (a symbolic link, a hard link, a file that resolves out of +its source), an embedder whose geometry is not the plane's, and a cache volume without room. The dry +run writes nothing: it reads every store read only and opens no run ledger, so it creates no file, +nor a root that does not exist. It lists the root's top-level entries; names the sources the +instance read outside its root, which a destroy leaves, and those inside it, which go with the root, +with the count and bytes of their files the cache does not take (the whole downloads some readers +keep under `raw/`, the cursors, the state files); and names its overlay and its Keychain items, +which a destroy leaves, `.landing-log-key` among them: the catalog's file goes with the root, +its landing log in it, and nothing of the log enters the cache, so the item keys nothing afterwards +but a copy of that file kept elsewhere. + +```sh +MIND_PALACE_OVERLAY=config/instances/.toml mind-palace destroy # dry run +MIND_PALACE_OVERLAY=config/instances/.toml mind-palace destroy --confirm +MIND_PALACE_OVERLAY=config/instances/.toml mind-palace cache fill [--confirm] # fill, keep +mind-palace cache # its size by namespace +mind-palace cache prune --confirm # remove entries not taken for 180 days +``` + +The cache is read back three ways: the embed drain takes a vector by atom under the same embedder +key before it calls the embedder; the raw store takes an object by digest on a miss, checked against +its SHA-256; `scripts/corpus.py fetch` copies a cached source stream in before the edge reader +resumes it. `scripts/purge_raw.py` reaches the cache: the object and its chunks' vectors go, and the +digest is recorded so no fill puts it back. + +A fill of the corpus is not offered yet. Its dry run (on a clone of the root, 2026-11-13) plans +387,838 raw objects of 1,003,892,779 bytes, 468 source files of 1,372,531,168 bytes and 1,338,585 +vectors, 8,224,266,240 bytes as float64: 10,600,690,187 bytes by the plan's count, which the room +check weighs. The disk takes more than those bytes (the raw objects one file each, which the +stage-1 record counts at 2.0 GB of blocks for the raw store, and the vectors in SQLite pages), +and neither that nor the fill's time has been measured. A destroy of the corpus refuses as its +root stands: the root holds the corpus tooling's own files and leftovers no code here writes +(dn-instance-lifecycle §7, open question 8). + +**The corpus instance** lives at `~/.mind-palace/instances/corpus` (`[instance] root` in +`config/instances/corpus.toml`); its old location, `instances/corpus` in the corpus stage-1 +worktree, is a symbolic link to it. Read it in place read only for regression numbers: SQLite +with `immutable=1`, since a `mode=ro` connection to a WAL database creates its `-wal` and `-shm` +files, and Lance read only. Never open its catalog through `VaultCatalog` to read it: the catalog +holds 400,274 rows and no landing log yet, so that open would write under the root (the WAL +files, the migration, the log's tables and a genesis of 400,274 rows), or, without +`corpus.landing-log-key`, refuse after creating the log's two empty tables. Only the corpus's own +tooling writes under it (`scripts/corpus.py`, and the stage-1 measurements into `results/`), and a +lifecycle command run under its overlay writes only when confirmed. Its next ingest, like a reset +of the corpus, needs `corpus.landing-log-key` placed first. + ## Code-execution sandbox — libraries, data-piping, WASM (BUILD-SPEC §11, owner-operated) Executed code is **powerless** (Invariant 4): network-off, vault-less, non-root, read-only rootfs, diff --git a/ops/chat_sensor.py b/ops/chat_sensor.py index 7583a62d..3ce12930 100644 --- a/ops/chat_sensor.py +++ b/ops/chat_sensor.py @@ -35,10 +35,14 @@ still excluded — the daemon does not ingest its own live session. Cut-time exclusion of open sessions is bp-064's certificate concern. -Spine-invisible in v1: NO chain written, NO stratum registered (bp-064, CS-4). The -`reset_targets()` registration of `data/chatlog.sqlite` (corpus-side wipe target; rebuilds -by re-ingest from the IMMUTABLE rawstore, which is NOT reset) is the ORCHESTRATOR's -post-merge step (`ops/lifecycle/launcher.py` is outside this plan's write_scope). +Spine-invisible in v1: NO chain written, NO stratum registered (bp-064, CS-4). + +The retention ledger (dn-instance-lifecycle §3.4): the sensor records each transcript it retains, +in order, before it extracts anything (`core/stores/chat_retention.py`), and a transcript is +extracted when the ledger did not hold its digest. The chat log is a derived store: a reset clears +it and `rebuild` replays the ledger, reading each transcript's bytes back from the raw store, which +a reset keeps, so the chat log comes back even for a transcript the CLI has pruned from its +directory. The sole future reader is the ratified cross-strata correlator (CS-5 — its own scoped grant, surfacing-only); this plan wires NO reader. @@ -58,6 +62,7 @@ from core.kernel.agent_scope import sensor_scope from core.kernel.scope import Stratum from core.kernel.stores.rawstore import RawStore +from core.stores.chat_retention import RetentionLedger, open_retention_ledger from core.stores.chatlog import ChatlogStore, ChatUtterance, open_chatlog_store # role → speaker (CS-3 metadata mapping). NEVER a provenance input (CS-2 firewall). @@ -243,12 +248,15 @@ class ChatSyncReport: empty: list[str] = field(default_factory=list) # parsed to 0 utterances unparseable: list[str] = field(default_factory=list) # every line failed to decode skipped_active: str | None = None # the excluded open session (Q4), if present + # a rebuild's replay only: a retained transcript whose raw object a purge erased, skipped (the + # erasure stands, and the chat log comes back without it; dn-instance-lifecycle §6.6) + purged: list[str] = field(default_factory=list) def total_accounted(self) -> int: """The sum of the mutually-exclusive buckets — equals `files_seen` iff nothing skipped.""" return (self.sessions_ingested + self.sessions_grown + len(self.refused_sessions) + len(self.unchanged) - + len(self.empty) + len(self.unparseable) + + len(self.empty) + len(self.unparseable) + len(self.purged) + (1 if self.skipped_active else 0)) def is_fully_accounted(self) -> bool: @@ -262,7 +270,8 @@ def __str__(self) -> str: f"retained={self.transcripts_retained} unchanged={len(self.unchanged)} " f"refused={len(self.refused_sessions)} empty={len(self.empty)} " f"unparseable={len(self.unparseable)} " - f"active_skipped={'yes' if self.skipped_active else 'no'} " + + (f"purged={len(self.purged)} " if self.purged else "") + + f"active_skipped={'yes' if self.skipped_active else 'no'} " f"accounted={'ok' if self.is_fully_accounted() else 'BROKEN'}") @@ -279,6 +288,9 @@ class ChatSensor: store: ChatlogStore guard: ChatSecretGuard active_session_id: str | None = None # the open session to EXCLUDE (Q4) + # Which raw objects are transcripts, in retention order (dn-instance-lifecycle §3.4). None + # keeps the raw store's `is_new` as the change signal (the tests that build a bare sensor). + retention: RetentionLedger | None = None def _transcript_paths(self) -> list[Path]: """The session transcripts on disk, in a stable (name-sorted) order — deterministic.""" @@ -303,15 +315,28 @@ def _ingest(self, path: Path, report: ChatSyncReport, known: set[str]) -> None: tuning recovers it), and the session is NAMED.""" session_id = path.stem text = path.read_text(encoding="utf-8") - # CS-1: byte-verbatim retention BEFORE any extraction. `is_new` is the growth signal — an - # unchanged transcript hashes identically (skip, no churn); a grown one hashes anew (its - # tail re-ingests). Retention is unconditional — even a refused/unparseable session's raw - # is kept (the archive never depends on extraction succeeding). - _digest, is_new = self.rawstore.add_text(text) - if not is_new: + # CS-1: byte-verbatim retention BEFORE any extraction. The growth signal is whether these + # bytes were retained before: an unchanged transcript hashes identically (skip, no churn); + # a grown one hashes anew (its tail re-ingests). Retention is unconditional: even a + # refused/unparseable session's raw is kept (the archive never depends on extraction + # succeeding). With the retention ledger, the ledger's row is the signal, written here + # before extraction: a crash between the raw write and the row leaves the transcript to + # extract on the next pass, but an extraction cut short after the row is skipped as + # unchanged by the next sync, and only a reset's replay of the ledger recovers it. + digest, is_new = self.rawstore.add_text(text) + if is_new: + report.transcripts_retained += 1 + fresh = self.retention.append(digest, session_id) if self.retention is not None \ + else is_new + if not fresh: report.unchanged.append(session_id) # content-identical — nothing to do return - report.transcripts_retained += 1 + self._extract(session_id, text, report, known) + + def _extract(self, session_id: str, text: str, report: ChatSyncReport, + known: set[str]) -> None: + """Parse, guard and land one retained transcript's text (CS-3 → CS-2), bucketing it. + The one extraction both a sync and a rebuild run.""" outcome = _parse_lines(text) for u in outcome.utterances: # CS-3 guard, fail-closed, whole-session if self.guard.scan(u.text): @@ -364,6 +389,31 @@ def backfill(self) -> ChatSyncReport: `sync()`, kept as a named entry for the D2 semantics and the existing call sites.""" return self.sync() + def rebuild(self) -> ChatSyncReport: + """Replay the retention ledger into the chat log (dn-instance-lifecycle §3.4): each + retained transcript in retention order, its bytes read back from the raw store, through the + same parse, guard and landing a sync runs. Reads no transcript directory, so it gives back + the chat log a reset cleared even for transcripts the CLI has pruned. Idempotent: a replay + over a chat log that holds every turn adds none.""" + report = ChatSyncReport() + if self.retention is None: + return report + known = set(self.store.sessions()) + for row in self.retention.rows(): + report.files_seen += 1 + try: + data = self.rawstore.get(row.digest) + except FileNotFoundError: + report.purged.append(row.file) # erased by a purge: nothing to replay + continue + text = data.decode("utf-8") + try: + self._extract(row.file, text, report, known) + except SecretInUtteranceError: + continue # named in report.refused_sessions + known |= set(self.store.sessions()) + return report + def _default_transcripts_dir() -> Path: """The local Claude Code transcript dir for this repo — the CLI's cwd→dir mangling @@ -388,10 +438,14 @@ def build_chat_sensor(config: Config | None = None, *, from config.loader import get_config cfg = config or get_config() + store = open_chatlog_store(cfg) + retention = open_retention_ledger(cfg) + retention.seed_from(store.path) # once, for a chat log that predates the ledger return ChatSensor( transcripts_dir=cfg.ingestion.transcripts.transcripts_dir or _default_transcripts_dir(), rawstore=RawStore(cfg.paths.raw_store), - store=open_chatlog_store(cfg), + store=store, guard=ChatSecretGuard(), active_session_id=active_session_id, + retention=retention, ) diff --git a/ops/float16_migrate.py b/ops/float16_migrate.py index c91aaed0..4b801ac7 100644 --- a/ops/float16_migrate.py +++ b/ops/float16_migrate.py @@ -20,7 +20,9 @@ Run it with writers stopped (`mind-palace stack down`): the long-running servers keep the old store's handles open until they restart. A store already in float16 is left alone; a store not yet -on the shared plane must take `ops.plane_migrate` first. +on the shared plane must take `ops.plane_migrate` first. A run that swaps is refused while a reset +of the instance is pending (`data/reset.pending`), whose rebuild writes the plane; the dry run, +which swaps nothing, is not. """ from __future__ import annotations @@ -187,8 +189,13 @@ def main(argv: list[str] | None = None) -> int: help="build and verify beside the live store; swap nothing") a = ap.parse_args(argv) from core.kernel.config import get_config + from ops.lifecycle.inventory import refusal cfg = get_config() + pending = None if a.dry_run else refusal(cfg, "the float16 migration") # the swap writes it + if pending is not None: + print(pending) + return 1 targets = {"vectors": cfg.paths.vector_store, "curated": cfg.paths.curated_store} names = list(targets) if a.store == "all" else [a.store] ok = True diff --git a/ops/lifecycle/__init__.py b/ops/lifecycle/__init__.py index 07ded8e9..934af0bf 100644 --- a/ops/lifecycle/__init__.py +++ b/ops/lifecycle/__init__.py @@ -10,6 +10,8 @@ (Vault / Ollama / podman) read-only and fail closed with a clear checklist; * the **launcher** (`launcher.py`) — `start` (preflight → record run → rebuild-if-empty → supervise) with a graceful shutdown hook (SIGTERM/SIGINT → finish at a job boundary → mark - the run clean → optional final snapshot), `stop`, `status`, and `reset` (the surgical - fresh-start wipe that guards the production Vault Raft store). + the run clean → optional final snapshot), `stop`, `status`, `reset`, which clears the + instance's derived stores and rebuilds them from the raw store and the ledgers, keeping + every ledger (`rebuild.py`, over the class table of `inventory.py`), and `destroy`, which + removes a named instance and leaves its open content in the shared cache (`destroy.py`). """ diff --git a/ops/lifecycle/destroy.py b/ops/lifecycle/destroy.py new file mode 100644 index 00000000..95de6b29 --- /dev/null +++ b/ops/lifecycle/destroy.py @@ -0,0 +1,441 @@ +"""Destroying a named instance, and what it leaves: the shared cache's open content +(dn-instance-lifecycle §6). + +The cache is a channel between instances, so what enters it is fixed here, by an allow-list, and +everything else is refused. An item is **open** when its catalog path lies in the space of an +open-corpus source (`corpus//`) or a repository source (`code//`), or its class is +`curated`. Then a raw object enters when a catalog row, active or tombstoned, names its digest at +an open item's path; a vector enters when its atom is held, current or not, by an open item's +occupancy in the plane; and a source file enters when it is a stream file of an open-corpus +source (a stream's named parts, its manifest and its items' metadata), and a plain file of that +source (`plain_file`). Never a cursor, a checkpoint or a whole download a reader keeps under +`raw/`, which nothing reads back from the cache and a destroy removes with the root. Nothing of +the mirror's notes, the dialogue, an observed item outside an open-corpus source, or a transcript +enters, and no digest a purge recorded. An entry carries no path, title or class, so it says only +that some open item held these bytes, which that item's source holds in public. Nothing of the +catalog's file enters either: the fill reads the digests of open items' rows and nothing else of +it, and the source files are chosen by name, so a fill and a destroy refuse a source file that is +a link (`link_refusal`), which could name the catalog's file or a note; no row of the catalog, no +row of its landing log and no part of the log's secret reaches the cache. + +A destroy fills the cache by this selection and then removes the instance's root, without +following a symbolic link out of it, the catalog's file and its landing log with it. It reads the +catalog read only and never opens it through `VaultCatalog`, so it needs no landing-log secret, +even for a catalog that holds no log yet. `palace cache fill` is the same fill without the removal. +Both refuse when the configured embedder is not the geometry the plane recorded, so a vector is +filed only under the key of the embedder that made it. The plan counts what a fill would add and +holds no vector; the fill reads the vectors in batches, so neither grows with the plane. The dry +run of either creates and touches no file of an instance at rest (`read_only`, and the launcher's +run ledger read only until a write opens it). + +A root is removed only when it holds nothing but the instance's own state: every top-level entry +is one the instance's namespaces name, every entry of its data directory is in the class table, +nothing below it is a git repository, and no other instance declared on this host has its root +at, inside or around it. +""" + +from __future__ import annotations + +import json +import os +import shutil +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from core.ingest.table import CODE_SPACE, CORPUS +from core.kernel.provenance import Provenance +from core.stores.cache import Cache, key_of, plain_file, same_volume_free +from ops.lifecycle.inventory import read_only + +#: Free space the cache's volume keeps beyond what a fill adds. +FREE_MARGIN = 1 << 30 +#: Vectors a fill reads from the plane and writes to the cache at once. +FILL_BATCH = 2048 +_CORPUS_SPACE = f"{CORPUS}/" + + +def is_open(source_path: str, provenance: str) -> bool: + """Whether an item's content may enter the cache (decision D9).""" + return (source_path.startswith(_CORPUS_SPACE) or source_path.startswith(CODE_SPACE) + or provenance == Provenance.CURATED.value) + + +@dataclass +class FillPlan: + """What a fill would put in the cache, before any of it is written.""" + + raw: list[str] = field(default_factory=list) + raw_bytes: int = 0 + atoms: list[str] = field(default_factory=list) # the atoms whose vectors a fill adds + dim: int = 0 + key: str = "" + key_fields: dict[str, Any] = field(default_factory=dict) + sources: dict[str, list[str]] = field(default_factory=dict) + source_bytes: int = 0 + refused_purged: int = 0 + + @property + def bytes(self) -> int: + # the cache stores a vector as float64 (`Cache.put_vectors`) + return self.raw_bytes + self.source_bytes + 8 * self.dim * len(self.atoms) + + def __str__(self) -> str: + files = sum(len(f) for f in self.sources.values()) + return (f"{len(self.raw)} raw object(s) ({self.raw_bytes:,} bytes), " + f"{len(self.atoms)} vector(s), {files} source file(s) of " + f"{len(self.sources)} source(s) ({self.source_bytes:,} bytes); " + f"{self.refused_purged} purged digest(s) refused") + + +def _catalog_rows(cfg: Any) -> list[tuple[str, str, str]]: + """Every catalog row, active or tombstoned: (path, digest, class), read only.""" + path = Path(cfg.paths.vault_catalog) + if not path.is_file(): + return [] + conn = read_only(path) + try: + return [(str(p), str(d), str(c)) for p, d, c in conn.execute( + "SELECT source_path, digest, provenance FROM vault_files")] + finally: + conn.close() + + +def _open_atoms(cfg: Any, open_paths: set[str], purged: set[str]) -> set[str]: + """The atoms an open item's occupancy holds, current or not, in any class, read only.""" + from core.stores.plane import OCC, PLANE_FILE + + db = Path(cfg.paths.vector_store) / PLANE_FILE + if not db.is_file() or not open_paths: + return set() + conn = read_only(db) + atoms: set[str] = set() + try: + for occ in OCC.values(): + for path, digest, atom in conn.execute( + f"SELECT source_path, digest, atom_id FROM {occ}"): + if str(path) in open_paths and str(digest) not in purged: + atoms.add(str(atom)) + finally: + conn.close() + return atoms + + +def _source_files(base: Path) -> list[str]: + """The files of a source the cache takes, relative to its directory: the stream's manifest and + the parts it names, and the items' metadata, which are what `scripts/corpus.py fetch` copies + back into an empty source. Cursors, checkpoints and the whole downloads some readers keep + under `raw/` are not taken: nothing reads them back from the cache.""" + man = base / "stream" / "manifest.json" + if not man.is_file(): + return [] + parts = [str(p["file"]) for p in json.loads(man.read_text(encoding="utf-8"))["parts"]] + files = ["stream/manifest.json", *(f"stream/{f}" for f in parts)] + if (base / "meta" / "items.jsonl").is_file(): + files.append("meta/items.jsonl") + return [f for f in files if (base / f).is_file()] + + +def linked_source_files(cfg: Any) -> list[Path]: + """The files the cache would take from the open-corpus sources that are not plain files of + their source (`plain_file`): a symbolic link, a file with another hard link, or one that + resolves out of its source. Their bytes may be another file's, the catalog's or a note's, + which the selection by name did not choose, so a fill and a destroy refuse them.""" + if not cfg.ingestion.corpus.enabled: + return [] + root = Path(cfg.ingestion.corpus.root) + out: list[Path] = [] + for name in cfg.ingestion.corpus.sources: + base = root / name + out += [base / f for f in _source_files(base) if not plain_file(base / f, base)] + return out + + +def link_refusal(cfg: Any) -> str | None: + """Why a fill may not take the sources' files as they stand, or None (`linked_source_files`).""" + linked = linked_source_files(cfg) + if not linked: + return None + return (f"{', '.join(str(p) for p in linked)} would enter the cache as a source's download " + "and is a link (a symbolic link, a file with another hard link, or a file that " + "resolves out of its source), whose bytes may be another file's; remove it first") + + +def left_behind(cfg: Any) -> tuple[list[Path], list[Path]]: + """The sources the instance read, split by where they are: those outside its root, which a + destroy leaves (the vault, the transcript directory, each repository, the corpus sources' + directory when it is elsewhere), and those inside it, which go with the root.""" + paths: list[Path] = [] + ing = cfg.ingestion + if ing.vault.enabled: + paths.append(Path(ing.vault.path)) + if ing.transcripts.enabled: + paths.append(Path(ing.transcripts.transcripts_dir)) + if ing.code.enabled: + paths += [Path(r.path) for r in ing.code.repositories] + if ing.corpus.enabled: + paths.append(Path(ing.corpus.root)) + real_root = Path(os.path.realpath(cfg.instance.root)) + inside = [p for p in paths if _inside(Path(os.path.realpath(p)), real_root)] + return [p for p in paths if p not in inside], inside + + +def uncached_source_files(cfg: Any) -> tuple[int, int]: + """The files under the open-corpus sources' directories inside the root that the cache does + not take, with their bytes: the whole downloads some readers keep under `raw/`, the cursors + and the state files. A destroy removes them with the root and keeps nothing of them.""" + if not cfg.ingestion.corpus.enabled: + return 0, 0 + root = Path(cfg.ingestion.corpus.root) + real_root = Path(os.path.realpath(cfg.instance.root)) + files = size = 0 + for name in cfg.ingestion.corpus.sources: + base = root / name + if not base.is_dir() or not _inside(Path(os.path.realpath(base)), real_root): + continue + taken = {base / f for f in _source_files(base)} + for here, _dirs, names in os.walk(base, followlinks=False): + for n in names: + p = Path(here) / n + if p not in taken: + files += 1 + size += p.lstat().st_size + return files, size + + +def geometry_refusal(cfg: Any) -> str | None: + """Why this instance's vectors may not be filed under its configured key, or None: the plane + recorded another geometry (model, document template, dimension), as it does after a change + of embedder in the overlay and before `palace reembed`. Read only (`geometry_mismatch`).""" + from ops.lifecycle.rebuild import geometry_mismatch + + why = geometry_mismatch(cfg) if cfg.embedding.enabled else None + if why is None: + return None + return (f"{why}; a fill would file them under the configured embedder's key. Re-embed first " + "(`palace reembed --confirm`), or restore the configuration") + + +def plan_fill(cfg: Any, cache: Cache) -> FillPlan: + """The fill this instance would make: its open raw objects, the atoms whose vectors it adds, + and its source files. Counts only; no vector is read.""" + from core.kernel.stores.rawstore import RawStore + from core.stores.plane import GeometryMismatch + + why = geometry_refusal(cfg) + if why is not None: + raise GeometryMismatch(why) + + purged = cache.purged() + plan = FillPlan() + rows = _catalog_rows(cfg) + open_rows = [(p, d) for p, d, c in rows if is_open(p, c)] + raw = RawStore(Path(cfg.paths.raw_store)) if Path(cfg.paths.raw_store).is_dir() else None + for digest in sorted({d for _, d in open_rows}): + if digest in purged: + plan.refused_purged += 1 + continue + if raw is not None and raw.exists(digest) and not cache.has_raw(digest): + plan.raw.append(digest) + plan.raw_bytes += raw._path(digest).stat().st_size + if cfg.embedding.enabled: + atoms = _open_atoms(cfg, {p for p, _ in open_rows}, purged) + plan.key, plan.key_fields = key_of(cfg) + plan.atoms = sorted(atoms - cache.vector_ids(plan.key)) + plan.dim = int(cfg.embedding.dim) + if cfg.ingestion.corpus.enabled: + root = Path(cfg.ingestion.corpus.root) + for name in cfg.ingestion.corpus.sources: + base = root / name + have = {m["file"]: m["size"] for m in cache.source_manifest(name)} + files = [f for f in _source_files(base) + if have.get(f) != (base / f).stat().st_size] + if files: + plan.sources[name] = files + plan.source_bytes += sum((base / f).stat().st_size for f in files) + return plan + + +@dataclass(frozen=True) +class FillReport: + raw: int + vectors: int + source_files: int + + def __str__(self) -> str: + return (f"{self.raw} raw object(s), {self.vectors} vector(s), " + f"{self.source_files} source file(s) added") + + +def fill(cfg: Any, cache: Cache, plan: FillPlan) -> FillReport: + """Write a plan into the cache.""" + from core.kernel.stores.rawstore import RawStore + + raw = RawStore(Path(cfg.paths.raw_store)) + added_raw = sum(cache.put_raw(d, raw.get(d)) for d in plan.raw) + added_vec = 0 + if plan.atoms: + from core.stores.vectorstore import open_vector_store + + atoms = open_vector_store(cfg).plane.atoms + for i in range(0, len(plan.atoms), FILL_BATCH): + payload = atoms.payload(plan.atoms[i:i + FILL_BATCH]) + added_vec += cache.put_vectors(plan.key, plan.key_fields, + {a: v for a, (_text, v) in payload.items()}) + files = 0 + root = Path(cfg.ingestion.corpus.root) + for name, rels in plan.sources.items(): + files += cache.put_source_files(name, root / name, rels) + return FillReport(raw=int(added_raw), vectors=added_vec, source_files=files) + + +# ── destroy's refusals ───────────────────────────────────────────────────────────────────── + + +def _inside(path: Path, root: Path) -> bool: + return path == root or root in path.parents + + +def link_out(root: Path) -> Path | None: + """The first symbolic link under `root` whose target lies outside it, or None.""" + return _scan(root)[0] + + +def _scan(root: Path) -> tuple[Path | None, Path | None]: + """One walk of `root`, following no link: the first symbolic link whose target lies outside + it, and the first `.git` below it (a repository's directory or a worktree's file).""" + real_root = Path(os.path.realpath(root)) + out: Path | None = None + git: Path | None = None + for here, dirs, files in os.walk(root, followlinks=False): + for name in [*dirs, *files]: + p = Path(here) / name + if git is None and name == ".git": + git = p + if out is None and p.is_symlink() \ + and not _inside(Path(os.path.realpath(p)), real_root): + out = p + if out is not None and git is not None: + break + return out, git + + +def foreign_entries(cfg: Any) -> list[str]: + """What the root holds that is not this instance's own state: a top-level entry no path of its + namespaces lies at or under (`namespaces_of(cfg).paths`, the data directory among them), and + an entry of its data directory the class table does not name.""" + from core.kernel.config.loader import namespaces_of + from ops.lifecycle.inventory import unclassified + + root = Path(cfg.instance.root) + if not root.is_dir(): + return [] + real_root = Path(os.path.realpath(root)) + own: set[str] = set() + for p in {*namespaces_of(cfg).paths, Path(cfg.paths.data_dir)}: + real = Path(os.path.realpath(p)) + if real_root in real.parents: + own.add(real.relative_to(real_root).parts[0]) + out = sorted(e.name + ("/" if e.is_dir() else "") for e in root.iterdir() + if e.name not in own) + data = Path(cfg.paths.data_dir) + out += [f"{data.name}/{p.name}" for p in unclassified(cfg)] + return out + + +def top_entries(root: Path) -> list[str]: + """The root's top-level entries, for the dry run.""" + if not root.is_dir(): + return [] + return sorted(e.name + ("/" if e.is_dir() and not e.is_symlink() else "") + for e in root.iterdir()) + + +def other_roots(cfg: Any) -> list[tuple[str, Path, bool]]: + """The root of every other instance declared on this host, and whether it is a named one: the + default instance's (the checkout) and each other overlay's under config/instances/.""" + from core.kernel.config import loader + + out: list[tuple[str, Path, bool]] = [] + for name, other in loader._declared_instances(Path(os.devnull)): + if other.instance.id != cfg.instance.id: + out.append((name, Path(other.instance.root), other.instance.named)) + return out + + +def refusals(cfg: Any, cache: Cache, *, installed: bool, home: Path | None = None) -> list[str]: + """Why this instance may not be destroyed, empty when it may. The live run and the lock are + the launcher's to check; these are the configuration's and the disk's.""" + from core.kernel.config import loader + + if not cfg.instance.named: + return ["the default instance is never destroyed by this command (decision D1)"] + out: list[str] = [] + root = Path(cfg.instance.root) + real = Path(os.path.realpath(root)) + home_root = Path(os.path.realpath(home if home is not None + else Path.home() / ".mind-palace")) + cache_real = Path(os.path.realpath(cache.root)) + if installed: + out.append(f"a LaunchAgent with its label ({cfg.instance.label('palace')}) is installed; " + "remove it first") + derived = Path(os.path.realpath(Path(loader.REPO_ROOT) / "instances" / cfg.instance.id)) + tree = loader._working_tree_of(real) + if tree is not None and real != derived: + out.append(f"its root {root} lies inside the git working tree {tree}") + if real == home_root: + out.append(f"its root {root} is the home root itself") + if _inside(cache_real, real): + out.append(f"its root {root} holds the cache {cache.root}") + if _inside(real, cache_real): + out.append(f"its root {root} lies inside the cache {cache.root}") + for name, other, other_named in other_roots(cfg): + other_real = Path(os.path.realpath(other)) + # a derived root lies inside the default instance's, the checkout (§10 item 5) + if _inside(other_real, real) or (other_named and _inside(real, other_real)): + out.append(f"its root {root} is at, inside or around the root {other} of the " + f"instance {name}") + if root.is_symlink(): + out.append(f"its root {root} is a symbolic link; destroy the directory it names instead") + elif root.exists(): + link, git = _scan(root) + if link is not None: + out.append(f"{link} is a symbolic link out of the root; remove it first") + if git is not None: + out.append(f"{git.parent} below the root is a git repository; move it out first") + foreign = foreign_entries(cfg) + if foreign: + out.append(f"its root {root} holds what is not the instance's own state: " + + ", ".join(foreign) + "; move it out first") + for why in (link_refusal(cfg), geometry_refusal(cfg)): + if why is not None: + out.append(why) + return out + + +def keychain_items(cfg: Any) -> list[str]: + """The secret item names this instance reads, for the owner to remove by hand: its namespaces' + items, and the landing log's (`.landing-log-key` for a named instance), which they do not + list. The log goes with the catalog's file, so its secret keys nothing afterwards but a copy + of that file kept elsewhere.""" + from core.kernel.config.loader import namespaces_of + from core.stores.landings import LANDING_LOG_KEY + + return sorted({*namespaces_of(cfg).secrets, cfg.instance.secret(LANDING_LOG_KEY)}) + + +def room(cache: Cache, plan: FillPlan) -> str | None: + """Why the cache's volume cannot take the fill, or None.""" + free = same_volume_free(cache.root) + if free < plan.bytes + FREE_MARGIN: + return (f"the cache's volume has {free:,} bytes free; the fill needs {plan.bytes:,} and " + f"a margin of {FREE_MARGIN:,}") + return None + + +def remove_root(root: Path) -> None: + """Remove the instance's root. `rmtree` unlinks a symbolic link inside it and never follows + one; a root that is itself a link is refused before this (`refusals`).""" + if root.is_symlink(): + raise RuntimeError(f"{root} is a symbolic link") + shutil.rmtree(root) diff --git a/ops/lifecycle/inventory.py b/ops/lifecycle/inventory.py new file mode 100644 index 00000000..ff946fbb --- /dev/null +++ b/ops/lifecycle/inventory.py @@ -0,0 +1,229 @@ +"""Every store an instance writes, in exactly one class (dn-instance-lifecycle §3). + +One table, the same for every instance, says what each store under an instance's data directory +is and so what a reset does to it: + +* **ledger**: a source of truth: the raw objects, the catalog with its landing log, the version + chains, the attestations, the chat sensor's retention ledger, the commit ledger, the observation + history, the reference edges, the query log, the run and self-modification ledgers, the effects. + Kept. The landing log (`LANDING_LOG`, dn-temporal-snapshot §3.2) is two tables in the catalog's + own file, so the catalog's entry is kept whole, the log with it. +* **declaration**: what the owner declared and no code computes: the authored supersessions and + the signed verdicts. Kept. +* **derived**: a function of the ledgers, computed again without a model: cleared by a reset and + rebuilt, in the order of `step`, each step reading only ledgers and the steps before it. +* **kept**: model output, and what else no rebuild computes again exactly: the interpreted + artifacts, the dream claims, the claim operations, the staged hypotheses, the structural + snapshots, the curated store, the measurements, and the code lane's membership store, which + holds the code atoms' embedder ledger beside their occupancy. Kept. +* **operational**: the queue, the locks, the spools and their marks, the logs, the backups and + the HashiCorp Vault storage. Kept: not content. + +`reset_targets` and `_RESET_GUARD` were two lists that disagreed with the chat sensor's design; +this table replaces both. A store opened under the data directory that the table does not name +fails the inventory's test (falsifier LCF-1). +""" + +from __future__ import annotations + +import json +import sqlite3 +from collections.abc import Callable +from dataclasses import dataclass +from enum import StrEnum +from pathlib import Path +from typing import Any + +#: The landing log's tables, a ledger inside the catalog's file (`core/stores/landings.py`): the +#: append-only, hash-chained history of which digest each path held when, whose fold is the +#: catalog's rows. They share the catalog's entry below, so a reset keeps them as it keeps the file. +LANDING_LOG = ("landing_chains", "landings") + +#: Written before a reset clears anything, removed when its last rebuild step has run. While it is +#: there the daemon's start and every command that lands or writes a derived store refuse (each +#: reads it when it starts, through `refusal`), so nothing starts to land into a half-rebuilt +#: instance; it names the derived stores the reset found, so a reset run again after an +#: interruption rebuilds every one of them, a store whose file it had already removed included. +RESET_MARKER = "reset.pending" + + +class Kind(StrEnum): + LEDGER = "ledger" + DECLARATION = "declaration" + DERIVED = "derived" + KEPT = "kept" + OPERATIONAL = "operational" + + +@dataclass(frozen=True) +class Store: + """One entry of the data directory: its name there, its class, where it is under a given + configuration, and for a derived store its rebuild step and how a reset clears it.""" + + name: str + kind: Kind + where: Callable[[Any], Path] + step: int = 0 # the rebuild's order, for a derived store + clear: str = "file" # "file", "relations" (the plane), "index" (lexical), "rows" + note: str = "" + + def path(self, cfg: Any) -> Path: + return Path(self.where(cfg)) + + +def _data(name: str) -> Callable[[Any], Path]: + return lambda cfg: Path(cfg.paths.data_dir) / name + + +def _paths(attr: str) -> Callable[[Any], Path]: + return lambda cfg: Path(getattr(cfg.paths, attr)) + + +def _sibling(name: str) -> Callable[[Any], Path]: + """A store opened beside the interpreted artifacts (`derived_store.parent / name`).""" + return lambda cfg: Path(cfg.paths.derived_store).parent / name + + +L, D, X, K, OP = Kind.LEDGER, Kind.DECLARATION, Kind.DERIVED, Kind.KEPT, Kind.OPERATIONAL + +STORES: tuple[Store, ...] = ( + # ── ledgers ────────────────────────────────────────────────────────────────────────────── + Store("raw", L, _paths("raw_store"), note="the verbatim bytes; a purge is its one deletion"), + Store("vault_catalog.sqlite", L, _paths("vault_catalog"), + note="path to digest, title, class, identity, and the landing log, its past"), + Store("versions.sqlite", L, _data("versions.sqlite"), note="mirror_authored's chains"), + Store("attestations.sqlite", L, _paths("attestation_store"), note="append-only"), + Store("chat_retention.sqlite", L, _data("chat_retention.sqlite"), + note="which raw objects are transcripts, in retention order"), + Store("code_snapshots.sqlite", L, _data("code_snapshots.sqlite"), note="the commit ledger"), + Store("observation_history.sqlite", L, _data("observation_history.sqlite"), + note="superseded generations, whose interpreters no longer exist"), + Store("reference_edges.sqlite", L, _data("reference_edges.sqlite"), + note="append-only, no extractor version on its rows (decision D3)"), + Store("query_log.jsonl", L, _data("query_log.jsonl"), note="what was asked"), + Store("runs.sqlite", L, _data("runs.sqlite"), note="the system's runs"), + Store("selfmod_ledger.sqlite", L, lambda cfg: Path(cfg.selfmod.ledger_db)), + Store("effectors", L, lambda cfg: Path(cfg.effectors.ledger_db).parent, + note="the effects ledger and the drafts it stages"), + # ── the owner's declarations ───────────────────────────────────────────────────────────── + Store("authored_supersessions.sqlite", D, _sibling("authored_supersessions.sqlite")), + Store("verdicts.sqlite", D, _sibling("verdicts.sqlite"), note="owner-signed, verified"), + # ── derived: cleared and rebuilt, in this order ────────────────────────────────────────── + Store("lexical.sqlite", X, _data("lexical.sqlite"), step=1, clear="index", + note="catalog, raw"), + Store("vectors.lance", X, _paths("vector_store"), step=2, clear="relations", + note="the plane's occupancies and supersession log; the atoms are kept as a memo"), + Store("code_observations.sqlite", X, _data("code_observations.sqlite"), step=3, + note="commit ledger, by re-projection without the attestor"), + Store("agent_observations.sqlite", X, _data("agent_observations.sqlite"), step=4, + note="git's first-parent history of the build plans, without the attestor"), + Store("edges.sqlite", X, _sibling("edges.sqlite"), step=6, clear="rows", + note="the authored rows only; the interpreted rows are model output and stay"), + Store("chatlog.sqlite", X, _data("chatlog.sqlite"), step=7, note="retention ledger, raw"), + Store("chat_events.sqlite", X, _data("chat_events.sqlite"), step=8, note="chat log, raw"), + Store("causal_edges.sqlite", X, _data("causal_edges.sqlite"), step=9, + note="chat events, commit ledger (decision D6: a fresh integration)"), + Store("verdict_dispositions.sqlite", X, _sibling("verdict_dispositions.sqlite"), step=10, + note="verdicts, applied in sequence order"), + # ── kept: model output and what no rebuild computes again exactly ──────────────────────── + Store("derived.sqlite", K, _paths("derived_store"), note="interpreted artifacts (D4)"), + Store("memberships.sqlite", K, _sibling("memberships.sqlite"), + note="the code atoms' embedder ledger with their occupancy; rebuilt by code-rebuild"), + Store("run_ledger.sqlite", K, _sibling("run_ledger.sqlite")), + Store("dream_runs.sqlite", K, _sibling("dream_runs.sqlite")), + Store("claim_ops.sqlite", K, _sibling("claim_ops.sqlite")), + Store("staging.sqlite", K, _sibling("staging.sqlite")), + Store("structural.duckdb", K, _sibling("structural.duckdb")), + Store("research_curated.lance", K, _paths("curated_store"), note="decision D5"), + Store("eval_results.duckdb", K, _sibling("eval_results.duckdb")), + Store("probes.sqlite", K, _sibling("probes.sqlite")), + Store("lexical", K, _data("lexical"), note="the corpus's measurement outputs"), + Store("edges", K, _data("edges"), note="the corpus's measurement outputs"), + Store("codes", K, _data("codes"), note="the corpus's measurement outputs"), + # ── operational: kept, not content ─────────────────────────────────────────────────────── + Store("queue.sqlite", OP, _data("queue.sqlite"), note="decision D7: kept"), + Store("tasks.sqlite", OP, _data("tasks.sqlite")), + Store("telemetry.duckdb", OP, _paths("telemetry_db")), + Store("supervisor.lock", OP, _data("supervisor.lock")), + Store(RESET_MARKER, OP, _data(RESET_MARKER)), + Store("handoff", OP, lambda cfg: Path(cfg.interface.handoff_dir)), + Store("airlock", OP, lambda cfg: Path(cfg.airlock.handoff_dir)), + Store("code", OP, _data("code"), note="the repository sources' marks"), + Store("code_sensing_handoff", OP, _data("code_sensing_handoff")), + Store("agent_sensing_handoff", OP, _data("agent_sensing_handoff")), + Store("corpus", OP, lambda cfg: Path(cfg.ingestion.corpus.root), + note="the corpus sources' streams and cursors"), + Store("logs", OP, _data("logs")), + Store("backup-staging", OP, _data("backup-staging")), + Store("mint_ids_backup", OP, _data("mint_ids_backup")), + Store("reembed_bodyonly_backup", OP, _data("reembed_bodyonly_backup")), + Store("vault", OP, _data("vault"), note="the HashiCorp Vault storage"), +) + + +def derived() -> list[Store]: + """The derived stores, in rebuild order.""" + return sorted((s for s in STORES if s.kind is Kind.DERIVED), key=lambda s: s.step) + + +def classify(cfg: Any, path: Path) -> Store | None: + """The table's entry for `path`: the store it is, or lies inside, or is a SQLite sidecar of + (`-wal`, `-shm`, `-journal`); None when the table names nothing there.""" + p = Path(path) + for suffix in ("-wal", "-shm", "-journal"): + if p.name.endswith(suffix): + p = p.with_name(p.name[: -len(suffix)]) + found: Store | None = None + for s in STORES: + where = s.path(cfg) + if p == where or where in p.parents: + # the innermost entry wins (`effectors` holds its ledger and its drafts) + if found is None or len(where.parts) > len(found.path(cfg).parts): + found = s + return found + + +def unclassified(cfg: Any) -> list[Path]: + """Every entry directly under the data directory the table does not name (LCF-1).""" + data = Path(cfg.paths.data_dir) + if not data.is_dir(): + return [] + return sorted(p for p in data.iterdir() if classify(cfg, p) is None) + + +def read_only(path: Path) -> sqlite3.Connection: + """A read of a SQLite store that creates and touches no file when the store is at rest. A + database at rest has every committed page in its main file: it has no `-wal` file, or an empty + one a reader left behind (a `mode=ro` reader cannot remove the files it made), and no + `-journal`. It is read `immutable=1`, since a `mode=ro` connection to a WAL database creates its + `-wal` and `-shm` files, and rewrites a `-shm` already there. A database whose `-wal` holds + frames, or that has a `-journal`, may hold committed pages outside its main file, which + `immutable=1` would not see, so it is read `mode=ro`, beside the files already there, and that + read updates its `-shm`.""" + wal, journal = Path(f"{path}-wal"), Path(f"{path}-journal") + pending = journal.exists() or (wal.exists() and wal.stat().st_size > 0) + query = "mode=ro" if pending else "immutable=1" + return sqlite3.connect(f"file:{path}?{query}", uri=True) + + +def marker(cfg: Any) -> Path: + return Path(cfg.paths.data_dir) / RESET_MARKER + + +def reset_pending(cfg: Any) -> dict[str, Any] | None: + """The interrupted reset's record, or None when no reset is pending.""" + m = marker(cfg) + if not m.exists(): + return None + try: + return dict(json.loads(m.read_text(encoding="utf-8"))) + except (ValueError, OSError): + return {"stores": [s.name for s in derived()]} + + +def refusal(cfg: Any, what: str) -> str | None: + """The line a writer prints when it refuses because a reset is pending, else None.""" + if reset_pending(cfg) is None: + return None + return (f"refusing {what} — a reset of this instance is pending ({marker(cfg)}): its derived " + "stores are being rebuilt. Run `palace reset --confirm` again to finish it.") diff --git a/ops/lifecycle/launcher.py b/ops/lifecycle/launcher.py index 138693f1..74df420f 100644 --- a/ops/lifecycle/launcher.py +++ b/ops/lifecycle/launcher.py @@ -5,7 +5,8 @@ supervisor + watcher with a **graceful shutdown hook** (SIGTERM/SIGINT → stop claiming new work, let the in-flight job finish at its boundary — the scheduler is already cooperative — then mark the run CLEAN). `stop` signals the live run's pid. `status` shows preflight + the last runs. -`reset` is the surgical fresh-start wipe. +`reset` clears the derived stores and rebuilds them from the ledgers; `destroy` removes a named +instance and leaves its open content in the shared cache (dn-instance-lifecycle). Recovery (nervous-system-and-ambassador.md §1): if the *previous* run never marked itself stopped (crash / kill -9 / power loss), `start` comes up in **recovery mode** — scheduler halted, watcher @@ -30,7 +31,7 @@ from typing import TYPE_CHECKING, Any, Protocol from config.loader import InstanceConfig, namespaces_of -from ops.lifecycle.lock import SupervisorLock, SupervisorLockHeld +from ops.lifecycle.lock import SupervisorLock, SupervisorLockHeld, held_elsewhere from ops.lifecycle.preflight import Preflight, run_preflight from ops.lifecycle.runs import RunLedger, RunRecord, git_state @@ -105,18 +106,6 @@ def start(self) -> None: ... def alive(self) -> bool: ... def stop(self) -> None: ... -# Data files/dirs the reset wipe must NEVER touch: the production Vault Raft store, the run + -# self-mod ledgers, telemetry history, the live backup staging, and logs. The corpus targets are -# computed from cfg.paths; this guard is defense-in-depth so a path mistake can't nuke Vault. -_RESET_GUARD = ("vault", "runs.sqlite", "selfmod_ledger.sqlite", "telemetry.duckdb", - "code_snapshots.sqlite", - # Observation worldview HISTORY (bp-018, dn-self-sensing §2.5 split): - # current READINGS are corpus-side and wiped (code_observations.sqlite - # stays a reset target — rebuilt by re-projection from git); superseded - # generations do NOT rebuild (their interpreters no longer exist at HEAD). - "observation_history.sqlite", - "backup-staging", "logs") - # Default cadence for the trough housekeeping passes (dream + curate). They only actually run # when the foreground gate is clear (the supervisor's HEAVY_TIERS check), so this is a ceiling. _HOUSEKEEPING_INTERVAL_S = 6 * 3600 @@ -797,6 +786,10 @@ class Launcher: # W for the status rate block. Field, not config: `core/config/loader.py` is schema'd and # drops unknown sections, so a `[status]` key would be inert (bp-102 §11 / finding-0174). status_window_minutes: float = _STATUS_WINDOW_MINUTES + # The reset's embedder, built only when a rebuilt atom is missing from the atom table; and the + # shared cache's location (`~/.mind-palace/cache` when None). Both injectable for the tests. + embedder_factory: Callable[[Config], Any] | None = None + cache_root: Path | None = None _stopping: bool = field(default=False, init=False) _run_id: int | None = field(default=None, init=False) _run: RunRecord | None = field(default=None, init=False) # the active RunRecord (for snapshots) @@ -841,6 +834,11 @@ def start(self, *, force: bool = False, max_ticks: int | None = None) -> int: # Ahead of preflight deliberately — an unrunnable state should not first cost the operator # preflight's uncosted 120 s Ollama probe (finding-0195). Same shape as `reset()`'s guard # (:1124), with liveness identity-checked so a recycled pid cannot brick start forever. + from ops.lifecycle.inventory import refusal + pending = refusal(self.cfg, "to start") + if pending is not None: + print(pending) + return 1 if not self.cfg.embedding.enabled: # the lite profile (dn-palace-lite): the daemon wires the embedder's consumers (the # librarian, the code embed lane, the airlock's ranking), and an instance that embeds @@ -1600,7 +1598,13 @@ def live_run(self) -> Any: return run if run is not None and run.active and _pid_alive(run.pid) else None def _refuse_if_live(self, what: str) -> bool: - """A live daemon is the single writer; an on-demand pass beside it would be a second.""" + """A live daemon is the single writer; an on-demand pass beside it would be a second. A + pending reset refuses too: its derived stores are half rebuilt (dn-instance-lifecycle).""" + from ops.lifecycle.inventory import refusal + pending = refusal(self.cfg, what) + if pending is not None: + print(pending) + return True run = self.live_run() if run is not None: print(f"refusing {what} — run #{run.id} (pid {run.pid}) is live; it owns the stores. " @@ -1793,8 +1797,9 @@ def embed_now(self) -> int: return 1 from core.ingest import ingress from core.ingest.derive import derive_lexical, drain + from core.stores.cache import Cache, cache_home, with_cache cfg = self.cfg - stores = ingress.build_stores(cfg) + stores = with_cache(ingress.build_stores(cfg), cfg, Cache(self.cache_root or cache_home())) lexical = derive_lexical(stores) # a changed tokenizer re-derives the index first if lexical.items or lexical.rederived: print(f"lexical: {lexical}") @@ -1806,97 +1811,244 @@ def embed_now(self) -> int: print(f"embed: {report}") return 0 - # --- reset (the fresh-start wipe) ------------------------------------------------------- - def reset_targets(self) -> list[Path]: - """The corpus + its derived/chain layer + the stale queue. Computed from cfg.paths; - each is asserted to be under data/ and outside the guard set (never the Vault Raft).""" - p = self.cfg.paths - candidates = [ - p.raw_store, p.vector_store, p.vault_catalog, p.derived_store, p.attestation_store, - p.data_dir / "queue.sqlite", - # Sibling stores opened via `derived_store.parent / ` (no dedicated cfg path). - # All four are corpus/derived-chain provenance: left behind, their rows reference - # wiped artifacts — orphaned history that would pollute a fresh graph's record. - p.data_dir / "versions.sqlite", # note-version supersession history - p.data_dir / "authored_supersessions.sqlite", # owner-declared K₀↔K₀ (founding) - p.data_dir / "verdicts.sqlite", # verdict ledger over derived artifacts - p.data_dir / "verdict_dispositions.sqlite", # dispositions derived from verdicts - # Code observations are CORPUS-side (the observed stratum, ratified - # code-observation-projection.md §2.4) — wiped with the corpus, unlike the - # snapshot LEDGER (build history, in _RESET_GUARD above). bp-012 Item 4 / Q4. - p.data_dir / "code_observations.sqlite", - # Lane-1 reference edges are CORPUS-side too (cross-stratum doc↔code refs minted - # at projection time, ratified §2.5) — their rows reference wiped corpus/code - # endpoints, so they orphan on reset like the observations. bp-013 Q4 (parked to - # the orchestrator; launcher.py was outside the builder's write_scope). - p.data_dir / "reference_edges.sqlite", - # Agent (self-sensing) observations are CORPUS-side too — the third stream's - # READINGS (dn-self-sensing §2.5 ruling): wiped with the corpus, rebuilt by - # re-projection from git's build-plan `cost:` history. The worldview HISTORY - # (superseded generations) rides the guarded `observation_history.sqlite` - # sidecar above, unaffected by this reset. bp-019 Item 8 / §6(h). - p.data_dir / "agent_observations.sqlite", - # Chat utterances are CORPUS-side too — the observed chat stratum's READINGS - # (ratified dn-chat-sensor CS-2). Wiped with the corpus and rebuilt by re-ingest - # from the IMMUTABLE rawstore (p.raw_store, above — the verbatim archive is NOT a - # reset target; raw is sacred). bp-063 Q6 (parked to the orchestrator; launcher.py - # was outside the builder's write_scope). - p.data_dir / "chatlog.sqlite", - # The L1 action log is CORPUS-side too — the dialogue stratum's DERIVED layer (bp-069 - # Item 3): wiped with the corpus and rebuilt by re-projection from the rawstore-backed - # chatlog (the raw archive is NOT a reset target). It holds only structural refs. - p.data_dir / "chat_events.sqlite", - # The C-fiber causal edges are CORPUS-side too — the integrator's DERIVED output - # (bp-071): a pure function of retained L1 + the ledger (the floor invariant), so wiped - # with the corpus and rebuilt by re-integration. Structural refs only; no content. - p.data_dir / "causal_edges.sqlite", - # The membership relation M ⊆ V × O is CORPUS-side too (bp-152): every row is an - # occupancy of a vector-plane atom, so left behind it would point into a wiped plane. - p.data_dir / "memberships.sqlite", - ] - out: list[Path] = [] - for c in candidates: - assert p.data_dir in c.parents or c.parent == p.data_dir, f"target {c} not under data/" - assert c.name not in _RESET_GUARD and c.name != "vault", f"refusing to wipe guarded {c}" - out.append(c) - return out + # --- reset: clear the derived stores and rebuild them (dn-instance-lifecycle §4) ----------- + def _cache(self) -> Any: + from core.stores.cache import Cache, cache_home + return Cache(self.cache_root or cache_home()) - def reset(self, *, confirm: bool) -> int: - import shutil + def _embedder(self, cfg: Config) -> Any: + if self.embedder_factory is not None: + return self.embedder_factory(cfg) + from core.ingest.embed import build_embedder + return build_embedder(cfg) + + def _live_supervisor(self) -> RunRecord | None: run = self.runs.last() - if run is not None and run.active and _pid_alive(run.pid): + return run if run is not None and run.active and _supervisor_alive(run) else None + + def reset(self, *, confirm: bool) -> int: + """Clear the instance's derived stores and rebuild them from the raw store and the + ledgers, keeping every ledger, declaration, model output and operational store as it was + (dn-instance-lifecycle §4; the class table is `ops/lifecycle/inventory.py`). A dry run + unless confirmed. Refused beside a live daemon, while another writer holds the supervisor + lock, and when the configured embedder is not the plane's geometry; each refusal writes + nothing, and neither does the dry run. Runs under the supervisor lock, which the daemon, + `repo-sync`, `scripts/ingest.py` and the corpus runner take as well, behind a marker that + makes the daemon's start and every command that lands or writes a derived store refuse + until the last step has run; run again, it finishes an interrupted reset. A writer reads + the marker when it starts, so one that takes no lock and started before the reset is not + excluded from it (the note's open question 7). Whatever would stop a rebuild the same way + on every run (a derived store outside the data directory, a ledgered commit the + repository no longer holds, the landing log's secret when the catalog's first open would + write the log's genesis) refuses before anything is written, the marker included. The + catalog's file is kept whole, its landing log with it; no step appends to the log, and on + a catalog with rows and no log yet the rebuild's first open writes its genesis.""" + from ops.lifecycle import rebuild + from ops.lifecycle.inventory import reset_pending + + run = self._live_supervisor() + if run is not None: print(f"refusing reset — run #{run.id} (pid {run.pid}) is live. `palace stop` first.") return 1 - targets = self.reset_targets() - print("fresh-start reset will remove the corpus + derived layer:") - for t in targets: - print(f" - {t} (+ -wal/-shm if present)") - vault_raft = self.cfg.paths.data_dir / "vault" - print(f"GUARDED (never touched): production Vault Raft ({vault_raft}), " - "run/self-mod ledgers, telemetry, backups, logs.") + stores = rebuild.found(self.cfg) + why = (rebuild.geometry_mismatch(self.cfg) + if any(s.clear == "relations" for s in stores) else None) + if why is not None and reset_pending(self.cfg) is not None: + # `reembed` refuses while the marker stands, so naming it here would send the owner + # back and forth between the two refusals + print(f"refusing reset — {why}, and a reset of this instance is pending. Finish it " + "under the embedder the plane was built with: restore that embedder in the " + "configuration and run `palace reset --confirm` again; change the embedder " + "after it, with `palace reembed --confirm`. Nothing was written.") + return 1 + if why is not None: + print(f"refusing reset — {why}. A reset keeps the atoms of one geometry; a change of " + "embedder is `palace reembed --confirm`. Nothing was written.") + return 1 + missing = rebuild.missing_inputs(self.cfg, self.repo_root, stores) + if missing: + for m in missing: + print(f"refusing reset — {m}. Nothing was written.") + return 1 + pending = reset_pending(self.cfg) + print(("finishing an interrupted reset" if pending is not None else "reset") + + f" of instance {self.cfg.instance.id!r} ({self.cfg.paths.data_dir}):") + for line in rebuild.describe(self.cfg, stores): + print(line) + if not confirm: + print("\nDRY RUN — nothing written. Re-run with --confirm.") + return 0 + lock = SupervisorLock(namespaces_of(self.cfg).supervisor_lock) + try: + lock.acquire() + except SupervisorLockHeld: + print(f"refusing reset — another writer holds the supervisor lock ({lock.path}).") + return 1 + try: + ctx = rebuild.Context(cfg=self.cfg, repo=self.repo_root, + embedder_factory=self._embedder, cache=self._cache()) + print("\nrebuilding:") + rebuild.run(ctx, stores) + finally: + lock.release() + print(f"\nreset done: {len(stores)} derived store(s) rebuilt; every other store kept.") + return 0 + + # --- destroy: a named instance, leaving its open content in the cache (§6) ----------------- + def _agent_installed(self) -> bool: + return self.installed_plist.exists() or \ + self.domain.installed_plist(self.launchd_label).exists() + + def destroy(self, *, confirm: bool) -> int: + """Remove a named instance's root, after filling the shared cache with its open content + (raw objects by digest, vectors by embedder and atom, downloaded source files). A dry run + unless confirmed. Refuses the default instance, a live run, the supervisor lock held, a + pending reset, an installed LaunchAgent, a root inside a git working tree or holding or + inside the cache or the home root itself, a root at, inside or around another declared + instance's, a root that holds a git repository or anything that is not the instance's own + state, a symbolic link out of the root, a source file the cache would take that is a link, + a configured embedder that is not the plane's geometry, and a cache volume without room; + each refusal writes nothing, the dry run included. Leaves the sources the instance read + outside its root, its overlay, and its Keychain items, which it names for the owner; the + sources inside the root go with it, and of them the cache keeps the stream files alone.""" + from ops.lifecycle import destroy as d + from ops.lifecycle.inventory import refusal + + cfg = self.cfg + cache = self._cache() + why = d.refusals(cfg, cache, installed=self._agent_installed()) + if why: + for w in why: + print(f"refusing destroy — {w}.") + return 1 + # a reset interrupted after its clearing leaves the plane without the occupancies the fill + # selects vectors by, so a destroy then would keep none of them: it refuses, as a fill does + pending = refusal(cfg, "destroy") + if pending is not None: + print(pending) + return 1 + run = self._live_supervisor() + if run is not None: + print(f"refusing destroy — run #{run.id} (pid {run.pid}) is live. `palace stop` first.") + return 1 + root = cfg.instance.root + lock = SupervisorLock(namespaces_of(cfg).supervisor_lock) + if not confirm: + # the dry run writes nothing, so it probes the lock without taking it (or creating it) + if held_elsewhere(lock.path): + print(f"refusing destroy — another writer holds the supervisor lock ({lock.path}).") + return 1 + plan = d.plan_fill(cfg, cache) + if self._print_destroy(cache, plan) is None: + return 1 + print("\nDRY RUN — nothing written. Re-run with --confirm.") + return 0 + if root.exists(): + try: + lock.acquire() + except SupervisorLockHeld: + print(f"refusing destroy — another writer holds the supervisor lock ({lock.path}).") + return 1 + try: + plan = d.plan_fill(cfg, cache) + if self._print_destroy(cache, plan) is None: + return 1 + report = d.fill(cfg, cache, plan) + if root.exists(): + d.remove_root(root) + finally: + lock.release() + print(f"\ndestroyed {cfg.instance.id!r}: the cache took {report}.") + return 0 + + def _print_destroy(self, cache: Any, plan: Any) -> Any: + """Print what a destroy would do; None (with the refusal printed) when the cache's volume + cannot take the fill.""" + from ops.lifecycle import destroy as d + + cfg = self.cfg + short = d.room(cache, plan) + if short is not None: + print(f"refusing destroy — {short}.") + return None + root = cfg.instance.root + outside, inside = d.left_behind(cfg) + print(f"destroy instance {cfg.instance.id!r} at {root}:") + print(f" the cache ({cache.root}) takes: {plan}") + print(f" removed: {root}, holding " + (", ".join(d.top_entries(root)) or "nothing") + + ("" if root.exists() else " (it does not exist)")) + if inside: + files, size = d.uncached_source_files(cfg) + print(" sources inside the root, removed with it: " + + ", ".join(str(p) for p in inside) + + f"; the cache keeps their stream files above and none of their other {files:,} " + f"file(s) ({size:,} bytes): whole downloads, cursors and state") + print(" left: the sources it read outside its root (" + + (", ".join(str(p) for p in outside) or "none") + "), its overlay in " + "config/instances/, and its Keychain items: " + + (", ".join(d.keychain_items(cfg)) or "(none)")) + return plan + + # --- the shared cache (§6.3 to §6.5) ------------------------------------------------------ + def cache_report(self) -> int: + cache = self._cache() + if not cache.exists: + print(f"cache: {cache.root} does not exist yet") + return 0 + print(f"cache: {cache.root}") + for name, size in sorted(cache.sizes().items()): + print(f" {name}: {size.entries:,} entr(ies), {size.bytes:,} bytes") + print(f" purged digests recorded: {len(cache.purged()):,}") + return 0 + + def cache_fill(self, *, confirm: bool) -> int: + """Copy this instance's open content into the cache by destroy's selection, removing + nothing: how the corpus shares its vectors and objects with the instances that draw on + it. A dry run unless confirmed.""" + from ops.lifecycle import destroy as d + + if self._refuse_if_live("cache fill"): + return 1 + cache = self._cache() + for why in (d.link_refusal(self.cfg), d.geometry_refusal(self.cfg)): + if why is not None: + print(f"refusing cache fill — {why}.") + return 1 + plan = d.plan_fill(self.cfg, cache) + print(f"cache fill from {self.cfg.instance.id!r} into {cache.root}: {plan}") + short = d.room(cache, plan) + if short is not None: + print(f"refusing cache fill — {short}.") + return 1 + if not confirm: + print("DRY RUN — nothing written. Re-run with --confirm.") + return 0 + print(f"cache fill: {d.fill(self.cfg, cache, plan)}") + return 0 + + def cache_prune(self, *, confirm: bool) -> int: + """Remove the cache's entries not put or taken for the retention period (180 days). A + dry run unless confirmed.""" + from core.stores.cache import RETENTION_DAYS + + cache = self._cache() + stale = cache.stale(days=RETENTION_DAYS) + n = sum(len(v) for v in stale.values()) + print(f"cache prune: {n} entr(ies) not taken for {RETENTION_DAYS} days in {cache.root}") if not confirm: - print("\nDRY RUN — nothing removed. Re-run with --confirm. Your restic snapshot is the " - "safety net; a fresh re-ingest re-tags everything authored-solo (mooting the " - "provenance migration).") + print("DRY RUN — nothing removed. Re-run with --confirm.") return 0 - removed = 0 - for t in targets: - for path in (t, Path(str(t) + "-wal"), Path(str(t) + "-shm")): - if path.is_dir(): - shutil.rmtree(path) - removed += 1 - elif path.exists(): - path.unlink() - removed += 1 - print(f"\nremoved {removed} path(s). Re-export notes into the vault, then `palace start` " - "(it will re-ingest as authored-solo).") + print(f"cache prune: removed {cache.prune(days=RETENTION_DAYS)}") return 0 def build_launcher(config: Config | None = None, **kw) -> Launcher: from config.loader import REPO_ROOT, get_config - from ops.lifecycle.runs import open_run_ledger + from ops.lifecycle.runs import LazyRunLedger cfg = config or get_config() kw.setdefault("launchd_label", cfg.instance.label("palace")) # this instance's job, DI-2 - return Launcher(cfg=cfg, runs=open_run_ledger(cfg), repo_root=REPO_ROOT, **kw) + # the ledger is opened at its first write, so a command that only asks whether a run is live + # (the dry runs and refusals of reset, destroy and cache fill) creates no file + return Launcher(cfg=cfg, runs=LazyRunLedger(cfg.paths.data_dir / "runs.sqlite"), + repo_root=REPO_ROOT, **kw) diff --git a/ops/lifecycle/lock.py b/ops/lifecycle/lock.py index a1b861d3..fe188117 100644 --- a/ops/lifecycle/lock.py +++ b/ops/lifecycle/lock.py @@ -112,3 +112,22 @@ def __enter__(self) -> SupervisorLock: def __exit__(self, *exc: object) -> None: self.release() + + +def held_elsewhere(path: Path) -> bool: + """Whether some open file description holds the lock at `path`, probed without creating the + file or writing it: a lock file that does not exist is held by nobody, and an existing one is + opened read only and tried. For a dry run, which must write nothing; a confirmed act takes + the lock with `SupervisorLock.acquire`.""" + if not path.exists(): + return False + fd = os.open(path, os.O_RDONLY) + try: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return True + fcntl.flock(fd, fcntl.LOCK_UN) + return False + finally: + os.close(fd) diff --git a/ops/lifecycle/rebuild.py b/ops/lifecycle/rebuild.py new file mode 100644 index 00000000..b9944641 --- /dev/null +++ b/ops/lifecycle/rebuild.py @@ -0,0 +1,720 @@ +"""A lifecycle reset: clear an instance's derived stores and rebuild them from its ledgers +(dn-instance-lifecycle §4). + +The class table (`ops/lifecycle/inventory.py`) names the derived stores and their order. A reset +clears each one it finds, each by its own method (the lexical index's `reset`, the plane's +relations with its atoms kept, the authored rows of the relation edges) or by deleting its file, +then runs the rebuild steps in order, each reading only ledgers and the steps before it, and +writes no ledger: the sensors re-project without their attestor, and the reference edges a +re-projection mints again are found held. Every other store is kept as it was. + +What it guarantees, and the tests check (§8): every ledger, declaration and kept store is the same +row for row, the catalog's file whole with the landing log in it (every row, every chain's head +hash); each derived store's head after the rebuild equals its head before, wall-clock bookmarks +left out (the causal edges equal a fresh integration over the same inputs); no embedder call while +the atoms are held; a second reset leaves what the first left. The version-keyed stores are rebuilt +for the current versions only (decision D2); a replay of the landing log's rows, which would give +every version landed since its genesis, is a follow-up (§3.6). + +No step writes the catalog or appends to its landing log: the two steps that open it +(`OPENS_CATALOG`) read its active rows and nothing else. But its first open through `VaultCatalog` +writes the log's genesis when it holds rows and no log yet, which needs the instance's landing-log +secret. So that case is found read only before anything is cleared, and the reset refuses without +the secret (`missing_inputs`) rather than stopping after the clearing; with the secret, that +genesis is the one write a reset makes to a ledger. +""" + +from __future__ import annotations + +import json +import os +import sqlite3 +import subprocess +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from ops.lifecycle.inventory import Kind, Store, derived, marker, read_only, reset_pending + +#: Read before the clearing so the dry run and the refusals can say what a reset would do. +SQLITE_SIDECARS = ("-wal", "-shm", "-journal") +_ALL = 1 << 30 # "every session": the projectors' bound, set past any instance + + +@dataclass +class Context: + """What the steps share: the configuration, the repository the sensors read, the embedder's + factory (called only when an atom is missing), and the stores opened once.""" + + cfg: Any + repo: Path + embedder_factory: Callable[[Any], Any] + cache: Any = None + opened: dict[str, Any] = field(default_factory=dict) + # The plane's current occupancies before the clearing, as (path, digest, title, class): what + # the plane step rebuilds, and nothing more (§4.2). Read once and kept in the marker, so a + # reset run again after an interruption rebuilds what the plane held before the first run + # cleared it. The title and class are the occupancy's own, so a held version that is no longer + # the catalog's head (an edit a lazy instance has not yet embedded) is rebuilt as it was held. + plane_held: list[tuple[str, str, str, str]] = field(default_factory=list) + + def raw(self) -> Any: + if "raw" not in self.opened: + from core.kernel.stores.rawstore import RawStore + + fallback = self.cache.raw if self.cache is not None else None + self.opened["raw"] = RawStore(Path(self.cfg.paths.raw_store), fallback=fallback) + return self.opened["raw"] + + def catalog(self) -> Any: + if "catalog" not in self.opened: + from core.stores.catalog import VaultCatalog + + self.opened["catalog"] = VaultCatalog(Path(self.cfg.paths.vault_catalog)) + return self.opened["catalog"] + + def lexical(self) -> Any: + if "lexical" not in self.opened: + from core.stores.lexical import LexicalStore + + path = derived_path(self.cfg, "lexical.sqlite") + self.opened["lexical"] = LexicalStore(path) if path.exists() else None + return self.opened["lexical"] + + def vectors(self) -> Any: + if "vectors" not in self.opened: + from core.stores.vectorstore import open_vector_store + + self.opened["vectors"] = open_vector_store(self.cfg) + return self.opened["vectors"] + + def close(self) -> None: + for name in ("lexical",): + s = self.opened.get(name) + if s is not None: + s.close() + + +class _LazyEmbedder: + """The embedder, built on its first call: a rebuild whose atoms are all held never builds + one, so a reset needs no model server when it embeds nothing.""" + + def __init__(self, factory: Callable[[], Any]) -> None: + self._factory = factory + self._made: Any = None + + def _it(self) -> Any: + if self._made is None: + self._made = self._factory() + return self._made + + def embed_documents(self, texts: list[str]) -> list[list[float]]: + return list(self._it().embed_documents(texts)) + + def embed_query(self, text: str) -> list[float]: + return list(self._it().embed_query(text)) + + +def derived_path(cfg: Any, name: str) -> Path: + for s in derived(): + if s.name == name: + return s.path(cfg) + raise KeyError(name) + + +def applies(cfg: Any, s: Store) -> bool: + """Whether a derived store is this instance's to rebuild: the plane only where it embeds.""" + if s.clear == "relations": + return bool(cfg.embedding.enabled) + return True + + +def found(cfg: Any) -> list[Store]: + """The derived stores a reset clears and rebuilds: those present, and those an interrupted + reset recorded in its marker (whose files it may already have removed), in rebuild order.""" + pending = reset_pending(cfg) or {} + named = set(pending.get("stores", ())) + return [s for s in derived() + if applies(cfg, s) and (s.name in named or s.path(cfg).exists())] + + +# ── the clearing ─────────────────────────────────────────────────────────────────────────── + + +def _remove_file(path: Path) -> None: + for p in (path, *(Path(str(path) + x) for x in SQLITE_SIDECARS)): + if p.is_dir(): + raise RuntimeError(f"{p} is a directory where a derived store's file was expected") + p.unlink(missing_ok=True) + + +def under_data(cfg: Any, path: Path) -> bool: + """Whether `path` lies under the instance's data directory, by real path.""" + data = Path(os.path.realpath(cfg.paths.data_dir)) + return data in Path(os.path.realpath(path)).parents + + +def _inside_data(cfg: Any, path: Path) -> None: + """Refuse to clear a store that does not lie under the instance's data directory: the class + table computes each path from the configuration, and a path mistake must not reach outside. + The reset finds this before it writes its marker (`missing_inputs`); this is the clearing's own + guard.""" + if not under_data(cfg, path): + raise RuntimeError(f"refusing to clear {path}: it does not lie under the data directory " + f"{cfg.paths.data_dir}") + + +def clear(ctx: Context, stores: list[Store]) -> None: + """Clear each store, idempotently. The chat sensor's retention ledger is seeded from the chat + log first, for an instance whose chat log predates it, while there is a chat log to read. Every + path is checked to lie under the data directory before anything is cleared.""" + cfg = ctx.cfg + for s in stores: + _inside_data(cfg, s.path(cfg)) + names = {s.name for s in stores} + if "chatlog.sqlite" in names: + from core.stores.chat_retention import open_retention_ledger + + ledger = open_retention_ledger(cfg) + try: + ledger.seed_from(derived_path(cfg, "chatlog.sqlite")) + finally: + ledger.close() + for s in stores: + path = s.path(cfg) + if s.clear == "index": + lexical = ctx.lexical() + if lexical is None: + from core.stores.lexical import LexicalStore + + lexical = ctx.opened["lexical"] = LexicalStore(path) + lexical.reset() + elif s.clear == "relations": + ctx.vectors().plane.reset_relations() + elif s.clear == "rows": + from core.kernel.provenance import Provenance + from core.stores.edges import EdgeStore + + edges = EdgeStore(path) + try: + edges.delete_provenance(Provenance.AUTHORED_SOLO.value) + finally: + edges.close() + else: + _remove_file(path) + + +# ── the rebuild steps ────────────────────────────────────────────────────────────────────── + + +def _lexical(ctx: Context) -> str: + from types import SimpleNamespace + + from core.ingest.derive import derive_lexical + + stores = SimpleNamespace(lexical=ctx.lexical(), catalog=ctx.catalog(), raw=ctx.raw()) + return f"lexical index: {derive_lexical(stores)}" + + +def _readable(raw: Any, digest: str) -> bool: + """Whether the raw store can give the bytes of `digest`: it holds them, or its fallback (the + shared cache) gives them, checked against the digest and copied in.""" + if raw.exists(digest): + return True + try: + raw.get(digest) + except FileNotFoundError: + return False + return True + + +def _plane(ctx: Context) -> str: + """Re-occupy what the plane held before the clearing, and nothing more: an item still waiting + for its vector (a lazy instance's backlog) is left to the embed job, so the plane comes back to + its state before and the embedder is called only for a held atom the atom table lacks. Each + held pair is rebuilt from raw at the digest the plane held, with the occupancy's title and + class, whether or not that digest is still the catalog's head: raw keeps every version, and a + note edited since it was embedded stays searchable at the version the plane held until the + embed job takes the new one. The step reads no catalog row, so it does not open the catalog. + + A held pair whose raw object is gone is skipped and counted, as the chat log's replay skips a + purged transcript: a purge is the raw store's one deletion, and one run between an interrupted + reset and its rerun erases a version the marker still names (`plane_held`), so the rerun + finishes with the erasure standing instead of failing at this step every time (§4.3).""" + from types import SimpleNamespace + + from core.ingest.derive import derive_entries + from core.stores.catalog import CatalogEntry + + cfg = ctx.cfg + vectors = ctx.vectors() + view = None + if ctx.cache is not None: + from core.stores.cache import key_of + + view = ctx.cache.view(key_of(cfg)[0]) + raw = ctx.raw() + stores = SimpleNamespace(raw=raw, plane=vectors, lexical=ctx.lexical(), + embedder=_LazyEmbedder(lambda: ctx.embedder_factory(cfg)), + cache=view) + held = sorted(ctx.plane_held) + kept = [h for h in held if _readable(raw, h[1])] + entries = [CatalogEntry(source_path=p, digest=d, title=t, active=True, provenance=c) + for p, d, t, c in kept] + report = derive_entries(stores, entries, batch=cfg.embedding.batch, + streams=cfg.embedding.streams) + dropped = vectors.plane.drop_unheld() + repaired = vectors.plane.repair() + return (f"plane: {report}; {len(held) - len(kept)} held version(s) whose raw object a purge " + f"erased skipped; {dropped} atom(s) no rebuilt row holds dropped; held cache " + f"{repaired.held_fixed} fixed") + + +def _code_observations(ctx: Context) -> str: + from core.sensing import CodeSensingHandoff + from core.stores.code_observations import open_code_observation_store + from core.stores.observation_history import open_observation_history_store + from core.stores.reference_edges import open_reference_edge_store + from ops.code_sensor import CodeSensor + from ops.code_snapshot import open_snapshot_db + + cfg = ctx.cfg + ledger = Path(cfg.paths.data_dir) / "code_snapshots.sqlite" + if not ledger.exists(): + return "code observations: no commit ledger, nothing to re-project" + sensor = CodeSensor( + repo=ctx.repo, db=open_snapshot_db(ledger), attestor=None, + observations=open_code_observation_store(cfg), + obs_handoff=CodeSensingHandoff(handoff=Path(cfg.paths.data_dir) / "code_sensing_handoff"), + reference_edges=(open_reference_edge_store(cfg) + if (Path(cfg.paths.data_dir) / "reference_edges.sqlite").exists() + else None), + history=open_observation_history_store(cfg)) + return f"code observations: re-projected {sensor.backfill_observations()} commit(s)" + + +def _agent_observations(ctx: Context) -> str: + from core.sensing import AgentSensingHandoff + from core.stores.agent_observations import open_agent_observation_store + from core.stores.observation_history import open_observation_history_store + from ops.self_sensor import SelfSensor + + cfg = ctx.cfg + if not (Path(ctx.repo) / ".git").exists(): + return "agent observations: no repository, nothing to re-project" + sensor = SelfSensor( + repo=ctx.repo, store=open_agent_observation_store(cfg), + handoff=AgentSensingHandoff(handoff=Path(cfg.paths.data_dir) / "agent_sensing_handoff"), + attestor=None, history=open_observation_history_store(cfg)) + return f"agent observations: {sensor.sync()}" + + +def _authored_edges(ctx: Context) -> str: + from core.relations import rebuild_authored + from core.stores.edges import EdgeStore + + edges = EdgeStore(derived_path(ctx.cfg, "edges.sqlite")) + try: + n = rebuild_authored(ctx.catalog(), ctx.raw(), edges, ctx.cfg) + finally: + edges.close() + return f"authored relation edges: {n}" + + +def _chatlog(ctx: Context) -> str: + from core.stores.chat_retention import open_retention_ledger + from core.stores.chatlog import open_chatlog_store + from ops.chat_sensor import ChatSecretGuard, ChatSensor + + cfg = ctx.cfg + if not (Path(cfg.paths.data_dir) / "chat_retention.sqlite").exists(): + return "chat log: no retention ledger, nothing to replay" + sensor = ChatSensor(transcripts_dir=Path(cfg.paths.data_dir) / "no-transcripts", + rawstore=ctx.raw(), store=open_chatlog_store(cfg), + guard=ChatSecretGuard(), retention=open_retention_ledger(cfg)) + try: + return f"chat log: replayed {sensor.rebuild()}" + finally: + sensor.store.close() + if sensor.retention is not None: + sensor.retention.close() + + +def _chat_events(ctx: Context) -> str: + from core.chat_events import ChatEventProjector + from core.stores.chat_events import open_chat_event_store + from core.stores.chatlog import open_chatlog_store + + cfg = ctx.cfg + if not derived_path(cfg, "chatlog.sqlite").exists(): + return "chat events: no chat log, nothing to project" + projector = ChatEventProjector(chatlog=open_chatlog_store(cfg), rawstore=ctx.raw(), + store=open_chat_event_store(cfg)) + return f"chat events: projected {projector.project(max_sessions=_ALL)} session(s)" + + +def _causal_edges(ctx: Context) -> str: + from core.integrator import Integrator + from core.stores.causal_edges import open_causal_edge_store + from core.stores.chat_events import open_chat_event_store + + cfg = ctx.cfg + if not derived_path(cfg, "chat_events.sqlite").exists(): + return "causal edges: no chat events, nothing to integrate" + path = Path(cfg.paths.data_dir) / "code_snapshots.sqlite" + # the commit ledger, read only: an instance without one resolves every commit unknown + ledger = (read_only(path) if path.exists() + else sqlite3.connect(":memory:")) + try: + integrator = Integrator(events=open_chat_event_store(cfg), ledger=ledger, + edges=open_causal_edge_store(cfg)) + return f"causal edges: {integrator.integrate(max_sessions=_ALL)}" + finally: + ledger.close() + + +def _dispositions(ctx: Context) -> str: + from core.stores.verdicts import VerdictStore + from core.verdict.apply import apply_verdict + from core.verdict.dispositions import DispositionStore + + cfg = ctx.cfg + verdicts_path = Path(cfg.paths.derived_store).parent / "verdicts.sqlite" + if not verdicts_path.exists(): + return "verdict dispositions: no verdicts" + verdicts = VerdictStore(verdicts_path) + dispositions = DispositionStore(derived_path(cfg, "verdict_dispositions.sqlite")) + try: + records = sorted(verdicts.all(), key=lambda r: r.seq) + for record in records: + apply_verdict(record, dispositions) + finally: + verdicts.close() + dispositions.close() + return f"verdict dispositions: {len(records)} verdict(s) applied" + + +#: The rebuild steps that open the catalog (`Context.catalog`): the lexical index and the authored +#: relation edges, which read its active rows. The plane step reads none (it rebuilds what the +#: plane held, from raw), so it does not open it. The catalog's first open writes the landing +#: log's genesis when it holds rows and no log yet (`catalog_without_log`). A test checks that +#: these are exactly the steps that open it. +OPENS_CATALOG = frozenset({"lexical.sqlite", "edges.sqlite"}) + +#: The rebuild step of each derived store, by name. A test replaces one to inject a failure. +STEPS: dict[str, Callable[[Context], str]] = { + "lexical.sqlite": _lexical, + "vectors.lance": _plane, + "code_observations.sqlite": _code_observations, + "agent_observations.sqlite": _agent_observations, + "edges.sqlite": _authored_edges, + "chatlog.sqlite": _chatlog, + "chat_events.sqlite": _chat_events, + "causal_edges.sqlite": _causal_edges, + "verdict_dispositions.sqlite": _dispositions, +} + + +def run(ctx: Context, stores: list[Store], say: Callable[[str], None] = print) -> list[str]: + """The whole reset under the caller's lock: the marker, the clearing, every step in order, + and the marker's removal last. Interrupted anywhere, the marker stays and names every store, + so the next run clears and rebuilds them all again.""" + m = marker(ctx.cfg) + before = reset_pending(ctx.cfg) or {} + record: dict[str, Any] = { + "stores": sorted({s.name for s in stores} | set(before.get("stores", ()))), + "started": datetime.now(UTC).isoformat(timespec="seconds")} + if any(s.clear == "relations" for s in stores): + held = before.get("plane_held") + if held is None: + held = sorted(plane_held(ctx.cfg)) + record["plane_held"] = held + ctx.plane_held = [(str(p), str(d), str(t), str(c)) for p, d, t, c in held] + m.parent.mkdir(parents=True, exist_ok=True) + tmp = m.with_name(m.name + ".tmp") + tmp.write_text(json.dumps(record), encoding="utf-8") + tmp.replace(m) + done: list[str] = [] + try: + clear(ctx, stores) + for s in stores: + line = STEPS[s.name](ctx) + say(f" {s.step:>2}. {line}") + done.append(line) + finally: + ctx.close() + m.unlink() + return done + + +# ── reading, for the refusals and the dry run ────────────────────────────────────────────── + + +def plane_held(cfg: Any) -> set[tuple[str, str, str, str]]: + """The (path, digest, title, class) of every current occupancy of every plane class, read + only: what the plane step rebuilds.""" + from core.stores.plane import OCC, PLANE_FILE + + db = Path(cfg.paths.vector_store) / PLANE_FILE + if not db.is_file(): + return set() + conn = read_only(db) + try: + out: set[tuple[str, str, str, str]] = set() + for prov, occ in OCC.items(): + try: + out |= {(str(p), str(d), str(t), prov.value) for p, d, t in conn.execute( + f"SELECT source_path, digest, MIN(title) FROM {occ} WHERE current = 1 " + "GROUP BY source_path, digest")} + except sqlite3.Error: + continue + return out + finally: + conn.close() + + +def plane_heads(cfg: Any) -> set[tuple[str, str]]: + """The (path, digest) of every current occupancy of every plane class, read only.""" + return {(p, d) for p, d, _, _ in plane_held(cfg)} + + +def recorded_geometry(cfg: Any) -> str | None: + """The geometry the plane recorded at its first landing (its `meta` fingerprint: model, + document template, dimension), read only; None when there is no plane or no record.""" + from core.stores.plane import PLANE_FILE + + db = Path(cfg.paths.vector_store) / PLANE_FILE + if not db.is_file(): + return None + try: + conn = read_only(db) + except sqlite3.Error: + return None + try: + row = conn.execute("SELECT value FROM meta WHERE key = 'fingerprint'").fetchone() + except sqlite3.Error: + row = None + finally: + conn.close() + return None if row is None else str(row[0]) + + +def geometry_mismatch(cfg: Any) -> str | None: + """Why the configured embedder is not the geometry the plane recorded, or None: the comparison + `SharedPlane.check_geometry` makes, read only, since opening the plane to ask would create its + `-wal` and `-shm` and a refusal writes nothing.""" + from core.stores.vectorstore import fingerprint_of + + recorded = recorded_geometry(cfg) + mine = fingerprint_of(cfg).as_json() + if recorded is None or recorded == mine: + return None + return f"the plane's vectors came from {recorded}; the configured embedder is {mine}" + + +def catalog_without_log(cfg: Any) -> int: + """The catalog's rows when it holds rows and no landing log yet, else 0, read only. That is + the catalog whose first open through `VaultCatalog`, the rebuild's own included, writes the + log's genesis (`VaultCatalog._migrate`), which needs the instance's landing-log secret. A + file that is not a SQLite database, or holds no catalog table, is 0: no step would open it as + a catalog.""" + path = Path(cfg.paths.vault_catalog) + if not path.is_file(): + return 0 + try: + conn = read_only(path) + except sqlite3.Error: + return 0 + try: + tables = {str(r[0]) for r in conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'table'")} + if "vault_files" not in tables: + return 0 + if "landing_chains" in tables and conn.execute( + "SELECT 1 FROM landing_chains LIMIT 1").fetchone() is not None: + return 0 + return int(conn.execute("SELECT count(*) FROM vault_files").fetchone()[0]) + except sqlite3.Error: + return 0 + finally: + conn.close() + + +def landing_log_secret() -> str | None: + """Why the landing log's secret cannot be read, or None when it can: the item the catalog's + own open reads (`core.stores.landings.landing_log_key`, under the process's configuration), + absent, or not 32 bytes of hex.""" + from core.kernel.config import get_config + from core.stores.landings import LANDING_LOG_KEY, LandingLogKeyMissing, landing_log_key + + try: + landing_log_key() + except LandingLogKeyMissing: + name = get_config().instance.secret(LANDING_LOG_KEY) + return (f"get_secret({name!r}) is not in the environment, or is not 32 random bytes as " + "64 hex digits") + return None + + +def missing_inputs(cfg: Any, repo: Path, stores: list[Store]) -> list[str]: + """What would stop a rebuild the same way on every run, found before anything is written, the + marker included, so a reset that could not finish refuses with nothing written instead of + failing after the clearing and leaving the marker to block every writer. A derived store that + does not lie under the data directory (a store beside `derived_store` configured elsewhere), + which the clearing refuses to touch. A commit the commit ledger holds that the repository no + longer has (pruned by a rewrite and a garbage collection), which the code observations' + re-projection reads. And the landing log's secret, when the catalog holds rows and no log yet: + the first step that opens the catalog writes the log's genesis there, and without the secret + that open refuses, after it has created the log's two empty tables, so the case is found here, + read only, before any open. A raw object a purge erased is not missing: the chat log's replay + and the plane step skip it and say so (§4.3, §6.6).""" + out = [f"the derived store {s.path(cfg)} does not lie under the data directory " + f"{cfg.paths.data_dir}, and a reset clears nothing outside it. Configure it under the " + "data directory first" for s in stores if not under_data(cfg, s.path(cfg))] + if any(s.name in OPENS_CATALOG for s in stores): + rows = catalog_without_log(cfg) + why = landing_log_secret() if rows else None + if why is not None: + out.append(f"the catalog holds {rows:,} row(s) and no landing log yet, so the " + "rebuild's first open of it writes the log's genesis, which needs the " + f"instance's landing-log secret, and {why}. Place it (runbook §0) and run " + "the reset with it in the environment") + if any(s.name == "code_observations.sqlite" for s in stores): + ledger = Path(cfg.paths.data_dir) / "code_snapshots.sqlite" + if ledger.is_file(): + conn = read_only(ledger) + try: + shas = [str(r[0]) for r in conn.execute("SELECT commit_sha FROM snapshots")] + except sqlite3.Error: + shas = [] + finally: + conn.close() + gone = _absent_commits(repo, shas) + if gone: + out.append(f"{len(gone)} commit(s) the commit ledger holds are not in the " + f"repository {repo} ({', '.join(g[:10] for g in gone[:3])}" + f"{', ...' if len(gone) > 3 else ''}), so their code observations " + "could not be re-projected. Bring the commits back first") + return out + + +def _absent_commits(repo: Path, shas: list[str]) -> list[str]: + """The commits of `shas` the repository at `repo` does not hold, by one `cat-file` pass.""" + if not shas: + return [] + if not (Path(repo) / ".git").exists(): + return sorted(shas) + proc = subprocess.run(["git", "-C", str(repo), "cat-file", "--batch-check"], + input="".join(f"{s}^{{commit}}\n" for s in shas), text=True, + capture_output=True, check=True) + return sorted(s for s, line in zip(shas, proc.stdout.splitlines(), strict=True) + if line.endswith(" missing")) + + +def row_count(path: Path) -> int | None: + """The rows of every table of a SQLite file, read only; None for anything else.""" + if not path.is_file(): + return None + try: + conn = read_only(path) + except sqlite3.Error: + return None + try: + tables = [str(r[0]) for r in conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'table'")] + return sum(int(conn.execute(f'SELECT count(*) FROM "{t}"').fetchone()[0]) + for t in tables) + except sqlite3.Error: + return None + finally: + conn.close() + + +def describe(cfg: Any, stores: list[Store]) -> list[str]: + """The dry run's lines: what is cleared, by class what is kept.""" + from ops.lifecycle.inventory import STORES + + lines = ["clears and rebuilds (derived):"] + for s in stores: + path = s.path(cfg) + target = path / "plane.sqlite" if s.clear == "relations" else path + n = row_count(target) + how = {"index": "reset, then the lexical backfill", + "relations": "occupancies and supersession log; atoms kept", + "rows": "the authored rows only"}.get(s.clear, "file") + lines.append(f" {s.step:>2}. {s.name} ({'?' if n is None else n} row(s); {how}) " + f"<- {s.note}") + if s.clear == "relations": + lines.extend(_plane_lines(cfg, target)) + for kind in (Kind.LEDGER, Kind.DECLARATION, Kind.KEPT, Kind.OPERATIONAL): + present = [s.name for s in STORES if s.kind is kind and s.path(cfg).exists()] + lines.append(f"keeps ({kind.value}): {', '.join(present) or '(none present)'}") + rows = catalog_without_log(cfg) if any(s.name in OPENS_CATALOG for s in stores) else 0 + if rows: + lines.append(f"the catalog holds {rows:,} row(s) and no landing log yet: the rebuild's " + "first open of it writes the log's genesis, as any first open does, and " + "leaves its rows as they are") + return lines + + +def _plane_lines(cfg: Any, plane_db: Path) -> list[str]: + """The plane's part of the dry run: what the rebuild re-occupies (every pair the plane holds + current, as `_plane` rebuilds them), how many of those are no longer the catalog's head, the + atoms that needs and how many of them the atom table lacks (those, and only those, call the + embedder), and the items whose current version holds no vector, which the reset leaves to the + embed job.""" + heads = plane_heads(cfg) + atoms = _head_atoms(plane_db) + lacking = 0 + if atoms: + from core.stores.vectorstore import open_vector_store + + lacking = len(atoms - open_vector_store(cfg).plane.atoms.present(sorted(atoms))) + waiting, older = _without_vector(cfg, heads) + return [f" re-occupies the {len(heads)} item(s) the plane holds current ({older} of them " + f"at a version older than the catalog's), with {len(atoms)} distinct atom(s); the " + f"atom table lacks {lacking} of them, so the embedder is called for {lacking} atom(s)", + f" {waiting} item(s) of the plane's classes hold no vector for their current " + "version (waiting for the embed job, or with no text); the reset leaves them so"] + + +def _without_vector(cfg: Any, heads: set[tuple[str, str]]) -> tuple[int, int]: + """Read only: the active catalog items of the plane's classes whose current version the plane + does not hold current, and how many of those the plane holds at an older version.""" + from core.ingest.derive import HOLDS + + path = Path(cfg.paths.vault_catalog) + if not path.is_file(): + return 0, 0 + conn = read_only(path) + try: + rows = conn.execute("SELECT source_path, digest, provenance FROM vault_files " + "WHERE active = 1").fetchall() + finally: + conn.close() + paths = {p for p, _ in heads} + waiting = [str(p) for p, d, c in rows + if str(c) in HOLDS and (str(p), str(d)) not in heads] + return len(waiting), sum(1 for p in waiting if p in paths) + + +def _head_atoms(plane_db: Path) -> set[str]: + """The distinct atoms the plane's current occupancies hold, read only.""" + if not plane_db.is_file(): + return set() + from core.stores.plane import OCC + + conn = read_only(plane_db) + try: + held: set[str] = set() + for occ in OCC.values(): + try: + held |= {str(r[0]) for r in conn.execute( + f"SELECT DISTINCT atom_id FROM {occ} WHERE current = 1")} + except sqlite3.Error: + continue + return held + finally: + conn.close() diff --git a/ops/lifecycle/runs.py b/ops/lifecycle/runs.py index 08b9e5b2..0dde1ba2 100644 --- a/ops/lifecycle/runs.py +++ b/ops/lifecycle/runs.py @@ -20,6 +20,7 @@ from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path +from typing import Any from config.loader import Config @@ -87,9 +88,12 @@ class RunLedger: path: Path def __post_init__(self) -> None: + self._lock = threading.RLock() + self._connect() + + def _connect(self) -> None: if str(self.path) != ":memory:": self.path.parent.mkdir(parents=True, exist_ok=True) - self._lock = threading.RLock() self._conn = sqlite3.connect(str(self.path), check_same_thread=False) self._conn.row_factory = sqlite3.Row with self._lock: @@ -155,6 +159,53 @@ def close(self) -> None: self._conn.close() +def last_run(path: Path) -> RunRecord | None: + """The last run the ledger at `path` holds, read without creating or touching a file of it + (`read_only`): None when there is no ledger, or no table in it yet.""" + if not Path(path).is_file(): + return None + from ops.lifecycle.inventory import read_only + + conn = read_only(Path(path)) + conn.row_factory = sqlite3.Row + try: + r = conn.execute("SELECT * FROM runs ORDER BY id DESC LIMIT 1").fetchone() + except sqlite3.Error: + return None + finally: + conn.close() + return _row(r) if r else None + + +class LazyRunLedger(RunLedger): + """The run ledger of a command that may only ask about runs: opened, and created when absent, + at the first use that needs the open ledger, and not before. Until then `last` reads the file + read only (`last_run`), so a dry run or a refusal that asks whether a run is live creates no + file, under a root that does not exist either (dn-instance-lifecycle §4.6, §6.1). + `build_launcher` gives the launcher this one; every other use of the ledger is unchanged.""" + + def __post_init__(self) -> None: + self._lock = threading.RLock() + + def __getattr__(self, name: str) -> Any: + # only the connection is made late; any other missing attribute is a plain error + if name != "_conn": + raise AttributeError(name) + with self._lock: + if "_conn" not in self.__dict__: + self._connect() + return self.__dict__["_conn"] + + def last(self) -> RunRecord | None: + if "_conn" in self.__dict__: + return super().last() + return last_run(self.path) + + def close(self) -> None: + if "_conn" in self.__dict__: + super().close() + + def open_run_ledger(config: Config | None = None) -> RunLedger: from config.loader import get_config diff --git a/ops/plane_migrate.py b/ops/plane_migrate.py index 7b3e42cf..4ddb7705 100644 --- a/ops/plane_migrate.py +++ b/ops/plane_migrate.py @@ -22,7 +22,9 @@ `~/mind-palace-archive/-pre-a3-` and the build renamed into its place. Run it with writers stopped (`mind-palace stack down`, or at least `palace tick pause`): the -long-running servers keep the old store's handles open until they restart. +long-running servers keep the old store's handles open until they restart. A run that swaps is +refused while a reset of the instance is pending (`data/reset.pending`), whose rebuild writes the +plane; the dry run, which swaps nothing, is not. """ from __future__ import annotations @@ -228,8 +230,13 @@ def main(argv: list[str] | None = None) -> int: help="build and verify beside the live store; swap nothing") a = ap.parse_args(argv) from core.kernel.config import get_config + from ops.lifecycle.inventory import refusal cfg = get_config() + pending = None if a.dry_run else refusal(cfg, "the plane migration") # the swap writes it + if pending is not None: + print(pending) + return 1 targets = {"vectors": cfg.paths.vector_store, "curated": cfg.paths.curated_store} names = list(targets) if a.store == "all" else [a.store] ok = True diff --git a/papers/2026-11-11-instance-lifecycle/paper.tex b/papers/2026-11-11-instance-lifecycle/paper.tex new file mode 100644 index 00000000..9f8b1b88 --- /dev/null +++ b/papers/2026-11-11-instance-lifecycle/paper.tex @@ -0,0 +1,379 @@ +% A self-contained article for one pull request. +\documentclass[11pt]{article} +\usepackage[T1]{fontenc} +\usepackage{lmodern} +\usepackage{microtype} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,amsthm,mathtools} +\usepackage{algorithm} +\usepackage{algpseudocode} +\usepackage{booktabs} +\usepackage{tabularx} +\usepackage[numbers,sort&compress]{natbib} +\usepackage[hidelinks]{hyperref} +\usepackage[capitalise,noabbrev]{cleveref} + +\theoremstyle{plain} +\newtheorem{proposition}{Proposition} +\theoremstyle{definition} +\newtheorem{definition}{Definition} +\theoremstyle{remark} +\newtheorem{remark}{Remark} + +\newcommand{\code}[1]{\texttt{#1}} + +% The read-only check of the corpus instance (2026-11-13, on the tree with the landing log). +\newcommand{\corpusitems}{400{,}274} +\newcommand{\corpusunits}{1{,}369{,}944} +\newcommand{\corpusrows}{1{,}338{,}585} +\newcommand{\corpusentries}{389{,}745} +\newcommand{\lexsec}{17.4} +\newcommand{\lexload}{2.84} +\newcommand{\ntests}{74} + +\title{Reset, Destroy and a Shared Cache: the Lifecycle of a Knowledge-Store Instance} +\author{Alberto Serrano-Calva} +\date{\today} + +\begin{document} +\maketitle + +\begin{abstract} +A knowledge store that keeps the verbatim bytes of everything it ingests can treat every index over +those bytes as a materialized view. We use that to give an instance a lifecycle with two operations +whose meaning is fixed in code. A reset classifies each of the instance's stores as a ledger, an +owner's declaration, a derived store, model output, or operational state, clears the derived stores +and rebuilds them in a fixed order from the raw store and the ledgers, and keeps everything else row +for row. A destroy removes a named instance and leaves its open content in a cache shared by every +instance of the machine, addressed by content, so that another instance can take a raw object by its +digest, a vector by its embedder and text hash, and a downloaded source stream by its manifest +without a trust decision beyond the address. A purge reaches the cache, so the cache is no way +around erasure. The catalog's file also holds a hash-chained log of the catalog's past: a reset +keeps it whole and appends nothing to it, and refuses before writing anything when the catalog's +first open would write the log's genesis without the instance's secret; a destroy removes the log +with the catalog and lets none of it into the cache. Two gaps in the store had to close first: the +chat log could not be rebuilt because nothing recorded which raw objects were transcripts, and a +lexical index made by an older tokenizer refused every landing while the job that would repair it +ran only after a landing. We add a retention ledger for the first and a repair inside the one +writer for the second. \ntests{} tests on +fixture palaces check that a reset keeps every ledger, the log's rows and chain heads among them, +converges to the state before for each derived store, is idempotent, calls no embedder while the +atoms are held, and finishes after an interruption at any step, and that a destroy removes only +the instance's own state and leaves exactly the cache's classes. +\end{abstract} + +\section{Introduction} + +The store this article concerns keeps every ingested input verbatim in a content-addressed raw +store and lands it through one writer that records the item in a catalog, a version chain and an +attestation ledger, then derives its lexical units and its vectors. Several instances of the store +run on one machine: the owner's default instance, a code instance that indexes repositories, and a +corpus instance holding \corpusitems{} open-text items. Two operations on an instance had no single +meaning. The reset at the starting commit deleted the raw store, the catalog, the attestations, the +verdicts and most derived stores, so it lost the only copy of transcripts that their source +application had already pruned, and it left the lexical index and the relation edges behind, +pointing at items that no longer existed. There was no destroy. + +The owner's decisions fix the meanings: a reset clears what is derived and rebuilds it from raw, so +it loses nothing; a destroy removes an instance and keeps only what another instance can reuse as a +cache; the corpus instance lives at its own root outside every checkout. Two standing rules bind the +build: a change replaces what it changes, with no switch back to the old behaviour, and what an +operation computes is defined once and is the same in every instance. + +The contributions are: a class table of every store an instance writes (\cref{sec:inventory}); a +reset that rebuilds the derived stores in an order where each step reads only ledgers and earlier +steps, with a marker that refuses every writer that starts before it finishes (\cref{sec:reset}); a retention +ledger that makes the chat log a fold of retained transcripts and a lexical repair inside the +writer (\cref{sec:gaps}); a shared, content-addressed cache with an allow-list of open content and +erasure that reaches it (\cref{sec:destroy}); and tests of each property (\cref{sec:eval}). + +\section{Background} + +Helland argues that once storage is cheap the log of what happened is the source of truth and every +database is a cache of part of it \citep{helland2015immutability}. A derived store is then a +materialized view, and its maintenance a view-maintenance problem \citep{gupta1995views}; a full +recomputation is the simplest correct maintenance. Build systems face the same question of what to +rebuild and in which order, and separate the scheduler from the rebuilding strategy; a rebuild that +keeps a memo of a pure function's results, indexed by a hash of its input, and fetches a result +from it instead of recomputing is their constructive trace, and a memo shared between instances is +their cloud build \citep{mokhov2018build}. Content addressing makes a memo shareable: Venti +names every block by its hash so that identical data is stored once and any holder of the address +can verify what it receives \citep{quinlan2002venti}, and Nix builds a shared store and binary +caches on the same principle, with garbage collection of what nothing references +\citep{dolstra2004nix}. Erasure across derived state is harder: a deletion in the source must reach +every artifact computed from it, which Cao and Yang address for learned models +\citep{cao2015unlearning}; here the derived artifacts are indexes and a cache, and the problem is to +name every one. + +\section{The inventory}\label{sec:inventory} + +\begin{definition} +A store is a \emph{ledger} when it records something no other store records (the raw objects, the +catalog, the version chains, the attestations, the commit ledger, the reference edges, the run +ledgers). It is a \emph{declaration} when the owner wrote it and no code can compute it (verdicts, +authored supersessions). It is \emph{derived} when a function without a model computes it from +ledgers. It is \emph{kept} when it is model output or otherwise cannot be computed again exactly. It +is \emph{operational} when it is state of the running system and not content. +\end{definition} + +The classes are one table in code (\code{ops/lifecycle/inventory.py}), each entry with the path it +lies at under a configuration and, for a derived store, its rebuild step. The reset's two older +lists, its targets and its guard, are replaced by it. A test exercises every lane on a fixture and +fails if any entry of the data directory is unclassified. + +Three classifications are choices with consequences. The catalog is a ledger, and its file holds +a second one: the landing log, an append-only, hash-chained record of which digest each path held +when, written in the transaction of each catalog row, so that the catalog's rows are the log's +fold. A transcript or a dialogue export the catalog was landed from may be gone, so the log can be +computed from nothing else; the reset keeps the file whole. The reference edges are a ledger: their +rows carry no extractor version, so a re-projection would not give them back. The code lane's +membership store is kept: it holds the code atoms' embedder ledger beside their occupancy, and +clearing it would forget which code atoms are held under which embedder. + +\section{Reset}\label{sec:reset} + +\begin{algorithm}[t] +\caption{Reset of an instance $I$ with derived stores $D_1,\dots,D_k$ in rebuild order.} +\label{alg:reset} +\begin{algorithmic}[1] +\Require no live supervisor of $I$; the supervisor lock of $I$ acquired; embedder geometry equals the plane's; every ledgered commit present; the landing log's secret present if the catalog holds rows and no log +\State $F \gets \{D_j : D_j \text{ present}\} \cup \text{stores named by a pending marker}$ +\State $H \gets$ the plane's current (path, digest) pairs, or those a pending marker holds +\State write marker $\{F, H\}$ atomically +\State seed the retention ledger from the chat log if it predates the ledger +\ForAll{$D \in F$} \State clear $D$ by its own method (index reset, plane relations, authored rows, or file) +\EndFor +\ForAll{$D \in F$ in step order} \State rebuild $D$ from ledgers and $D_1..D_{j-1}$, writing no ledger +\EndFor +\State remove the marker +\end{algorithmic} +\end{algorithm} + +\Cref{alg:reset} gives the reset. The steps are: the lexical index (reset, then the lexical +backfill from the catalog and raw); the plane's occupancies and supersession log, whose atoms are +kept, re-occupied for exactly the pairs $H$, each from raw at its own digest even where the +catalog's head has moved on, so that items a lazy instance has not yet embedded stay with its +embed job; the code and agent observations, re-projected with the attestor left out; the authored +relation edges, parsed from each note's raw bytes by its catalog digest instead of its vault file; +the chat log, replayed from the retention ledger; the chat events; the causal edges; the verdict +dispositions, by applying every verdict in sequence order. + +\begin{proposition}[No embedder call]\label{prop:noembed} +Let the plane's atom table map $\mathrm{id}(t) = (\ell, \mathrm{sha256}(t))$, where $\ell$ is the +atom's layer (prose, for a note's chunk), to the embedder's vector of text $t$ under the recorded +geometry $g$. If a reset keeps the table and the configured +geometry equals $g$, the rebuild calls the embedder only for texts whose atom the table lacks. +\end{proposition} +\begin{proof}[Sketch] +The drain embeds exactly the atoms \code{known\_atoms} does not report, and the table reports every +atom it holds. Keeping it loses no derived state, since each row is a value of one function at one +argument. The reset refuses a changed geometry, so no row of another function is consulted. +\end{proof} + +\begin{proposition}[Convergence]\label{prop:conv} +For each derived store except the causal edges, the head after a reset equals the head before it, +wall-clock bookmarks excluded, provided every derivation is deterministic in its inputs and the +inputs are kept. +\end{proposition} +The head is what a reader reads: current units and postings, current occupancies with their atoms' +vectors, every row of the chat log, events, dispositions, observations and authored edges. The +version-keyed stores are rebuilt for current versions only; the landing log names every version +landed since its chain began, so a replay of it could rebuild the rest, which is left as future +work. The causal edges resolve commits against the +commit ledger as it stands at each pass, so they equal a fresh integration over the present inputs; +a second reset gives the same edges. + +\paragraph{The landing log.} Two steps open the catalog (the lexical index and the authored +edges), and neither writes it: each reads its active rows. The plane's step reads no row of it, +since it rebuilds from raw what the plane held, and does not open it. The one write a reset can +cause there is the catalog's own. The first open of a catalog that holds rows and no log writes the +log's genesis, keyed by the instance's secret, as any first open does; without the secret that +open refuses, but only after creating the log's two empty tables. So the reset reads the catalog +read only before it writes its marker and refuses, naming the secret's item, rather than stopping +after the clearing. With the log in the file the reset needs no secret, and the log's every row +and every chain's head hash are what they were. + +The marker makes the reset recoverable: every clear and every step is idempotent, the marker names +every store found, and a second confirmed reset clears and rebuilds them all, including a store +whose file the first had already removed. While the marker exists the daemon's start and every +command that lands or writes a derived store refuse. Each reads the marker when it starts, so it +does not exclude a writer already running; the lock does, for the writers that take it, and the +on-demand writers that take none are not excluded, which is left open. A rerun finishes only if no +step fails the same way every time, so whatever would stop a step that way is found before the +marker is written or tolerated by the step: a derived store outside the data directory, and a +commit the commit ledger holds that the repository has pruned, refuse the reset with nothing +written; a retained transcript whose raw object a purge erased is skipped by the replay and +counted, and so is a version the plane held that a purge erased while the reset was pending, so +the erasure stands. + +\section{Two gaps closed}\label{sec:gaps} + +\paragraph{The chat log is a fold.} The chat sensor stored each transcript in the raw store and +extracted it only when the raw store reported the bytes new, and it recorded nothing else. With +raw kept, a rebuild would see every transcript as unchanged and extract nothing, and a pruned +transcript would never be read. The order matters too: the first write of a turn stands and a +session that later shows a candidate secret is held at its state before it, so the chat log is the +left fold of retained transcripts in retention order. We add an append-only retention ledger +\code{(seq, digest, file, at)}, written at retention before extraction; its row is now the sensor's +change signal. That closes the gap between the raw write and the row; an extraction cut short after +the row is skipped as unchanged by the next sync, and a reset's replay of the ledger recovers it. +For an instance +whose chat log predates the ledger, the ledger is seeded from the chat log once: one row per +distinct transcript digest, ordered within a session by the lowest turn it wrote. A digest that +wrote no row changes nothing in a replay, so the seed's replay gives back the chat log. + +\paragraph{A stale index blocks every landing.} The lexical index records its tokenizer and +refuses to land or score under another. The job that re-derives it was enqueued only after a landing +succeeded, so a tokenizer change left the code instance's repository sync failing on every run +until the index was re-derived by hand (2,021 items in 11~s). The writer now checks the index before +it prices a plan and, when stale, resets it and lands every active item again before the plan. A +test reproduces the stuck state and shows the sync landing. + +\section{Destroy and the shared cache}\label{sec:destroy} + +A destroy applies to a named instance only and is a dry run unless confirmed; the dry run takes no +lock and writes no file, reading each SQLite file at rest (no \code{-wal}, or an empty one) with +\code{immutable=1}, since a read-only connection to a WAL database creates its \code{-wal} and +\code{-shm} files, and asking the run ledger whether a run is live without opening it, so it +creates no root that does not exist. A destroy reads the catalog read only and removes it whole, +its landing log with it, so it needs no secret. It refuses a live run, a held lock, a pending +reset, an installed agent, a root inside a git working tree, a root that is the home root, holds the cache, or +contains a symbolic link out of itself, a source file the cache would take that is a link, and a +cache volume without room. Since it removes the whole root, it also refuses a root +that holds anything but the instance's own state: a top-level entry no namespace of the instance +names, an unclassified entry of its data directory, a git repository below it, or another declared +instance's root. It fills the cache, then removes the root. A fill refuses unless the configured +embedder is the geometry the plane recorded, so a vector is filed only under the key of the +embedder that made it; its plan counts atoms, and the fill copies vectors in batches. + +The cache lives at one place under the home root, with namespaces for raw objects by digest, vectors +by key and atom, and source files with a manifest of size and SHA-256. A vector's key hashes the +embedder's model, document template, dimension and serving backend. An entry carries no path, title +or class. A lookup records the day the entry was taken, for retention, and nothing finer. + +\begin{definition} +An item is \emph{open} when its catalog path lies in an open-corpus source's space +(\code{corpus//}) or a repository source's (\code{code//}), or its class is curated. A +raw object enters the cache when a catalog row at an open path names its digest; a vector enters +when an open item's occupancy holds its atom; a source file enters when it is a named part, manifest +or metadata file of an open-corpus stream and a plain file of its source: not a symbolic link, not +a file with another hard link, not one that resolves out of the source. Nothing else enters: no +digest a purge recorded, no row of the catalog or of its landing log, and no part of the log's +secret. +\end{definition} + +\begin{remark} +Sharing an atom that both an open item and a private note hold reveals nothing beyond the open +source: the entry says only that some open item held this text, which its source publishes. An +entry whose existence said more than the open sources would break the argument; the allow-list +takes open items alone. +\end{remark} + +Three readers take entries back: the vector drain looks up an atom under its own key before calling +the embedder, discarding a vector of another width; the raw store, on a miss, takes an object whose +bytes hash to the digest asked for and deletes an entry that does not; and the corpus runner copies +a cached stream in, file by file against the manifest, before its edge reader resumes. A purge, +before deleting a raw object, derives its chunks as the landing did, removes the object and every +atom's vector under every key from the cache, and records the digest, so no fill restores it. The +atoms are deleted rather than recorded, since an atom's text may be held by an open item; the cost +of deleting a shared one is one embedding. Entries not taken for 180 days are removed by a prune. + +\section{Evaluation}\label{sec:eval} + +\paragraph{Tests.} \ntests{} tests run on fixture palaces that exercise every lane: three notes with +an authored and an interpreted relation edge and a superseded version, three open-corpus items, a +repository landed lexically and read by the code sensor, four transcripts (one grown, one held by +the secret guard, one with a commit that the integrator resolves), signed verdicts, and an +attestation trail. With the transcript directory emptied, a confirmed reset leaves the raw files +byte for byte and every kept store row for row, the attestation ledger unchanged, each derived head +equal to the head before, the chat log rebuilt from raw alone, and no embedder built. Two resets +equal one; a fresh integration adds no causal edge. The rebuilt atom table holds exactly the atoms +the rebuilt rows name. On a lazy instance with a backlog the reset builds no embedder and the +backlog stays. A purged transcript is skipped and the reset finishes. The dry run writes nothing, +on an instance at rest not even a file's modification time, and names each store. A live run, a +held lock, a changed geometry, a pruned ledgered commit and a derived store outside the data +directory each refuse with every byte unchanged and no marker written; the live run is held by a +ledger of its own, as the daemon holds it, and each command reads it from the file. A failure injected at each +of the nine steps leaves the marker, the daemon and the repository sync refuse, and a second reset +converges; a held version purged before the rerun is skipped by it, a changed embedder while the +reset is pending is refused with the way out, and every script that writes refuses while the +marker stands, a scan of the scripts finding none that calls a writer and is not run so. A +destroy's refusals each write nothing, a root holding a repository, a foreign file or another +instance and a pending reset among them, after which the fill selects every vector again, and its +dry run leaves every file's size and modification time as they were. Run as commands in processes of their own, on a root at rest whose catalog has an empty +\code{-wal} beside it, the dry runs of destroy, reset and fill change no file, and on a root that +does not exist they create none. A stream part linked to the catalog's file, by a symbolic or a +hard link, or to a note, is refused by the destroy, the fill and the cache, and so is the +catalog's file reached through a stream directory linked inside the root or a manifest part that +climbs out of the stream. With a dialogue turn, a +model's reply, an inbox item and a curated item added, a confirmed destroy leaves exactly the open +digests, the atoms open items held, and the stream's downloaded files in the cache, and no note, +dialogue, inbox item, transcript or vector only a private item held. A new instance takes a cached vector with no embedder +call and the same values; under another key it embeds. A corrupted raw entry is refused and +removed. A purge removes the object and its atoms' vectors under two keys, and a later fill from an +instance still holding it does not restore them. + +The landing log is checked on the same fixtures. A reset keeps every row of the log and each +chain's head hash, and so do two resets, a reset interrupted and finished, and a sync that heals a +stale index, whose one new row is its own landing. The steps that open the catalog are recorded at +every open and are exactly the two named. On a catalog with rows and no log, a reset without the +secret refuses, its dry run too, with every row unchanged and no log table created; with the +secret its dry run still writes nothing, and the reset writes the genesis at its first open, one +\code{store} row for each catalog row and nothing more, and every chain verifies. Under a named instance loaded through its configuration +overlay, the instance's own item is the one read and the default instance's does not serve; a +reset of a catalog that has its log needs no secret; a destroy needs none, names the item among +those it leaves, and no file of the filled cache holds a value of the log. A destroy's dry run on +an instance at rest, every store closed, creates and touches no file. Mutating any of the +mechanisms these tests name (one at a time, restoring each) makes at least one test fail. + +\paragraph{The corpus at its root.} With the corpus overlay declaring its root, a read-only check +on the tree with the landing log in its base (SQLite opened \code{immutable=1}, the Lance table +only read, the catalog never opened through its class) resolved the root to the declared +directory \code{instances/corpus} under the home root, counted \corpusitems{} active catalog items, +\corpusunits{} current lexical units and \corpusrows{} vector rows, and answered one lexical query +(\emph{superconductivity phase transition}, top hit the Wikipedia article Superconductivity) in +\lexsec{}~s at a one-minute load average of \lexload{} on a shared machine, scored under the legacy +tokenizer: the index has no recorded tokenizer, so by the store's own rule it is the legacy one's, +and the next corpus landing will re-derive the whole index first. The corpus's catalog has no +landing log yet, so opening it through its class would write the log's genesis under the root, or +refuse without the corpus's secret after creating the log's tables. A snapshot of the whole root +before and after the check, \corpusentries{} entries by type, size and modification time, showed +none added, removed or changed. An earlier check opened the files with \code{mode=ro}, which on a +WAL database creates its \code{-wal} and \code{-shm} files; it created two such files under the +corpus root and changed no row. + +\section{Limitations and future work} + +A reset rebuilds current versions only, and keeps the catalog's rows rather than folding them from +the landing log. A replay of the log would rebuild every version landed since its chain began, and +the fold needs a catalog write outside its logging methods; both are follow-ups, and the versions +superseded before a catalog's genesis are in no ledger but the version chains. A reset excludes a +writer that starts after it and one that holds the supervisor lock, but not an on-demand writer +that takes no lock and started before it; closing that needs a lock every writer holds for its +whole run, a decision left open. The retention ledger is seeded from the chat log once, so a +transcript retained after the seed by code that writes no row is replayed from a later digest; +a seed at every build closes that but cannot put a digest at its place in the retention order, +and is left open. The vector key +names the model but not the model file, so a requantized file under one name would share a key; a +measurement would say whether to add its digest. Code membership vectors do not enter the cache, +because no reader takes them back yet. The cost of a full reset of the corpus instance, and of the +lexical re-derivation its next landing will run, is not measured here, nor is the time of a fill +of the cache from the corpus, whose plan counts 1.0~GB of raw objects, 1.4~GB of source files and +8.2~GB of vectors. A destroy of the corpus refuses as its root stands: its tooling writes files at +the root that no namespace of the instance names, and whether they are the instance's state is +left open. A pruned ledgered commit +refuses every reset of its instance until a way to accept that loss is designed. The plane does not +record the embedder's backend, so a change of backend alone is not caught before a fill; catching +it needs the plane to record the backend beside its geometry, a schema change left open. The class +table is checked on fixtures; a store a lane writes that the fixtures do not exercise would escape it. + +\section{Conclusion} + +Treating every index as a view over kept bytes gives an instance a reset that loses nothing and a +destroy that leaves a shared, verifiable cache. The table that classifies stores is the one place +both operations read, so they mean the same thing in every instance. + +\bibliographystyle{plainnat} +\bibliography{refs} + +\end{document} diff --git a/papers/2026-11-11-instance-lifecycle/refs.bib b/papers/2026-11-11-instance-lifecycle/refs.bib new file mode 100644 index 00000000..e2a25026 --- /dev/null +++ b/papers/2026-11-11-instance-lifecycle/refs.bib @@ -0,0 +1,54 @@ +@inproceedings{helland2015immutability, + author = {Helland, Pat}, + title = {Immutability Changes Everything}, + booktitle = {7th Biennial Conference on Innovative Data Systems Research (CIDR)}, + address = {Asilomar, California}, + year = {2015} +} + +@article{gupta1995views, + author = {Gupta, Ashish and Mumick, Inderpal Singh}, + title = {Maintenance of Materialized Views: Problems, Techniques, and Applications}, + journal = {IEEE Data Engineering Bulletin}, + volume = {18}, + number = {2}, + pages = {3--18}, + year = {1995} +} + +@article{mokhov2018build, + author = {Mokhov, Andrey and Mitchell, Neil and Peyton Jones, Simon}, + title = {Build Systems {\`a} la Carte}, + journal = {Proceedings of the ACM on Programming Languages}, + volume = {2}, + number = {ICFP}, + note = {Article 79}, + year = {2018}, + doi = {10.1145/3236774} +} + +@inproceedings{quinlan2002venti, + author = {Quinlan, Sean and Dorward, Sean}, + title = {Venti: A New Approach to Archival Storage}, + booktitle = {Proceedings of the Conference on File and Storage Technologies (FAST)}, + pages = {89--101}, + publisher = {USENIX Association}, + year = {2002} +} + +@inproceedings{dolstra2004nix, + author = {Dolstra, Eelco and de Jonge, Merijn and Visser, Eelco}, + title = {Nix: A Safe and Policy-Free System for Software Deployment}, + booktitle = {Proceedings of the 18th Large Installation System Administration Conference (LISA)}, + pages = {79--92}, + publisher = {USENIX Association}, + year = {2004} +} + +@inproceedings{cao2015unlearning, + author = {Cao, Yinzhi and Yang, Junfeng}, + title = {Towards Making Systems Forget with Machine Unlearning}, + booktitle = {Proceedings of the 2015 IEEE Symposium on Security and Privacy}, + pages = {463--480}, + year = {2015} +} diff --git a/scheduler/embed.py b/scheduler/embed.py index 590e1ad2..c67973e2 100644 --- a/scheduler/embed.py +++ b/scheduler/embed.py @@ -8,7 +8,9 @@ idempotent at the plane, so the queue folds every request into the one row waiting (`_IDEMPOTENT_KINDS`), and a job a crash left running goes back to the queue and runs again as if it had not started. It calls the embedder and no chat model, so it -pins (`router._PINNED_KINDS`) and runs at BACKGROUND priority, like `code_sync`. +pins (`router._PINNED_KINDS`) and runs at BACKGROUND priority, like `code_sync`. An atom the plane +lacks is first looked up in the shared cache under the instance's embedder key +(dn-instance-lifecycle §6.5), so a vector another instance left there is not embedded again. """ from __future__ import annotations @@ -19,6 +21,7 @@ from config.loader import Config from core.ingest import ingress from core.ingest.derive import EMBED_JOB, derive_lexical, drain +from core.stores.cache import with_cache from scheduler.queue import PRIORITY_BACKGROUND, Job, JobQueue from scheduler.router import Router @@ -34,7 +37,8 @@ def embed_handler(cfg: Config, *, stores: Callable[[], Any] | None = None) -> Ha def the_stores() -> Any: if "s" not in opened: - opened["s"] = stores() if stores is not None else ingress.build_stores(cfg) + opened["s"] = with_cache(stores() if stores is not None + else ingress.build_stores(cfg), cfg) return opened["s"] def handle(_job: Job) -> str: diff --git a/scripts/cli.py b/scripts/cli.py index 36be4976..62451f88 100644 --- a/scripts/cli.py +++ b/scripts/cli.py @@ -21,6 +21,8 @@ DAY-TO-DAY start | stop | status | reset [--force|--confirm] the supervised lifecycle (scripts/palace.py) + destroy [--confirm] remove a named instance, its open content cached + cache [fill|prune] [--confirm] the shared cache (~/.mind-palace/cache) talk [--offline] interactive chat (--offline = no-Ollama demo) monitor run the dashboard/chat HTTP server standalone sandbox [--input NAME=PATH] [--timeout N] run code in the powerless sandbox @@ -59,7 +61,8 @@ help | -h | --help this message """ -_PALACE = ("start", "stop", "status", "reset", "deploy", "dream", "relate", "lanes", "reembed", +_PALACE = ("start", "stop", "status", "reset", "destroy", "cache", "deploy", "dream", "relate", + "lanes", "reembed", "vault-sync", "embed", "dialogue-sync", "tick", "queue", "query", "ingest-chat", "code-seed", "code-backfill", "code-rebuild") diff --git a/scripts/corpus.py b/scripts/corpus.py index ec83750f..eaa1d60d 100644 --- a/scripts/corpus.py +++ b/scripts/corpus.py @@ -123,6 +123,11 @@ def isolation(cfg: Config, live: list[Path]) -> dict[str, Any]: def cmd_isolation(a: argparse.Namespace) -> int: cfg = corpus_config() + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "ingest") + if pending is not None: + raise SystemExit(pending) proof = isolation(cfg, [Path(p).resolve() for p in a.live]) root = cfg.instance.root root.mkdir(parents=True, exist_ok=True) @@ -138,6 +143,14 @@ def cmd_fetch(a: argparse.Namespace) -> int: f"{', '.join(cfg.ingestion.corpus.sources)}") out = cfg.ingestion.corpus.root / a.source out.mkdir(parents=True, exist_ok=True) + # the shared cache first (dn-instance-lifecycle §6.5): a stream another instance left there is + # copied in, each file checked against its manifest row, and the reader resumes after it + from core.stores.cache import Cache, cache_home + + if not (out / "stream" / "manifest.json").exists(): + taken = Cache(cache_home()).take_source(a.source, out) + if taken: + print(f"fetch {a.source}: {taken} file(s) taken from the shared cache") argv = [sys.executable, "-m", f"edge.corpus.{a.source}", "--out", str(out), *a.rest] return subprocess.call(argv, cwd=Path(__file__).resolve().parent.parent) @@ -194,6 +207,11 @@ def cmd_ingest(a: argparse.Namespace) -> int: from ops.lifecycle.lock import SupervisorLock, SupervisorLockHeld cfg = corpus_config() + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "ingest") + if pending is not None: + raise SystemExit(pending) proof = isolation(cfg, [Path(p).resolve() for p in a.live]) if not proof["isolated"]: print(json.dumps(proof["checks"], indent=1), file=sys.stderr) @@ -215,7 +233,9 @@ def on_signal(signum: int, _frame: Any) -> None: signal.signal(signal.SIGTERM, on_signal) signal.signal(signal.SIGINT, on_signal) stop_file = root / "STOP" - stores = build_stores(cfg) + from core.stores.cache import with_cache + + stores = with_cache(build_stores(cfg), cfg) gate = Gate(chat_port=a.chat_port, embed_port=cfg.runtime.port_for("embedding") or 8081, log=root / "gate.log") stores.embedder = GatedEmbedder(stores.embedder, gate, streams=a.streams, batch=a.embed_batch) @@ -399,6 +419,11 @@ def cmd_embed(a: argparse.Namespace) -> int: from ops.corpus.embedder import EmbedderStopped, Gate, GatedEmbedder cfg = corpus_config() + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "embed") + if pending is not None: + raise SystemExit(pending) root = cfg.instance.root lock = _writer_lock(cfg) stopping = {"why": ""} diff --git a/scripts/ingest_founding.py b/scripts/ingest_founding.py index b2271503..3583ee15 100644 --- a/scripts/ingest_founding.py +++ b/scripts/ingest_founding.py @@ -7,7 +7,8 @@ `{"source_path", "title", "body", "date", "supersedes"?}`. `date` is the musing's RECONSTRUCTED original date (required — undated is refused); `supersedes` is an earlier item's `source_path` this one revises (optional). Ingested through the steady-state path as AUTHORED_SOLO — the initial -condition. Needs the live embedder (Ollama). +condition. Needs the live embedder (Ollama). Refused while a reset of the instance is pending +(`data/reset.pending`), before the manifest is read, as every writer is. This is CURATION, not training (founding-corpus.md §1): the weights never move. The founding set is deliberately biased-coherent and MUST NOT be reused as the Track-L control corpus (§2.3). @@ -26,6 +27,14 @@ def main(argv: list[str]) -> int: if len(argv) != 1: print(__doc__) return 2 + from config.loader import get_config + from ops.lifecycle.inventory import refusal + + cfg = get_config() + pending = refusal(cfg, "the founding ingest") # it lands; a pending reset refuses writers + if pending is not None: + print(pending) + return 1 from core.ingest.founding import FoundingItem, build_and_ingest_founding data = json.loads(Path(argv[0]).read_text(encoding="utf-8")) @@ -34,7 +43,7 @@ def main(argv: list[str]) -> int: date=d["date"], supersedes=d.get("supersedes")) for d in data ] - print(build_and_ingest_founding(items)) + print(build_and_ingest_founding(items, cfg)) return 0 diff --git a/scripts/ingest_self_knowledge.py b/scripts/ingest_self_knowledge.py index 332f3680..88170045 100644 --- a/scripts/ingest_self_knowledge.py +++ b/scripts/ingest_self_knowledge.py @@ -25,9 +25,15 @@ def main() -> int: seal() # structural egress guard first (Invariant 1) — local stores + local Ollama only from config.loader import get_config from core.ingest import ingress + from ops.lifecycle.inventory import refusal + cfg = get_config() + pending = refusal(cfg, "ingest-self-knowledge") # nothing lands into a half-rebuilt instance + if pending is not None: + print(pending) + return 1 # the docs' library script through the writer, as the daemon lands it (dn-ingress-language §E8) - print(ingress.run_library(get_config(), "sync_docs")["effects"]) + print(ingress.run_library(cfg, "sync_docs")["effects"]) return 0 diff --git a/scripts/migrate_chunk_keys.py b/scripts/migrate_chunk_keys.py index fb021ce2..3ec67849 100644 --- a/scripts/migrate_chunk_keys.py +++ b/scripts/migrate_chunk_keys.py @@ -35,8 +35,14 @@ def main(argv: list[str]) -> int: from config.loader import get_config from core.ingest.index import rekey_preview, rekey_store from core.stores.vectorstore import open_vector_store - - store = open_vector_store(get_config()) + from ops.lifecycle.inventory import refusal + + cfg = get_config() + pending = refusal(cfg, "the re-key") if apply else None # a pending reset refuses writers + if pending is not None: + print(pending) + return 1 + store = open_vector_store(cfg) total, changing = rekey_preview(store) print(f"note rows: {total}; ids to re-key: {changing}") if not apply: diff --git a/scripts/migrate_provenance_split.py b/scripts/migrate_provenance_split.py index a0aa2b7d..6fc61357 100644 --- a/scripts/migrate_provenance_split.py +++ b/scripts/migrate_provenance_split.py @@ -38,9 +38,14 @@ def main(argv: list[str]) -> int: seal() # structural egress guard first (Invariant 1) — this touches local stores only from config.loader import get_config from core.stores.catalog import VaultCatalog + from ops.lifecycle.inventory import refusal apply = "--apply" in argv cfg = get_config() + pending = refusal(cfg, "the relabel") if apply else None # a pending reset refuses writers + if pending is not None: + print(pending) + return 1 store = open_vector_store(cfg) catalog = VaultCatalog(cfg.paths.vault_catalog) diff --git a/scripts/mint_ids.py b/scripts/mint_ids.py index ce1e6efc..d40190c5 100644 --- a/scripts/mint_ids.py +++ b/scripts/mint_ids.py @@ -32,6 +32,13 @@ def main(argv: list[str]) -> int: from ops.lifecycle.runs import open_run_ledger cfg = get_config() + if "--confirm" in argv: + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "the id migration") # it lands; a pending reset refuses writers + if pending is not None: + print(pending) + return 1 sync = build_vault_sync(cfg) if "--confirm" not in argv: # dry-run is the default (fail-safe) diff --git a/scripts/palace.py b/scripts/palace.py index 0f3c9aef..f105a8ca 100644 --- a/scripts/palace.py +++ b/scripts/palace.py @@ -9,7 +9,13 @@ uv run scripts/palace.py status # preflight + recent runs + system snapshot uv run scripts/palace.py queue # read-only: waiting jobs, grouped by kind uv run scripts/palace.py query "" # read-only: a query sentence; --log = the sensor - uv run scripts/palace.py reset --confirm # fresh-start wipe of the corpus layer + uv run scripts/palace.py reset # dry run: what a reset clears and rebuilds + uv run scripts/palace.py reset --confirm # clear the derived stores, rebuild them from raw + uv run scripts/palace.py destroy # dry run: remove a named instance, cache its content + uv run scripts/palace.py destroy --confirm # (the default instance is refused) + uv run scripts/palace.py cache # the shared cache's size by namespace + uv run scripts/palace.py cache fill [--confirm] # copy this instance's open content into it + uv run scripts/palace.py cache prune [--confirm] # remove entries not taken for 180 days uv run scripts/palace.py deploy # promotion gate: cycle the live run onto HEAD uv run scripts/palace.py ingest-chat # on-demand: ingest the local Claude Code transcripts uv run scripts/palace.py code-seed # on-demand: seed the code embed lane (HEAD .py blobs) @@ -55,7 +61,8 @@ _ROOT = Path(__file__).resolve().parent.parent # repo root, for the bless path resolution USAGE = ("usage: palace.py " - "{start|stop|down|up|restart|status|queue|query|reset|deploy|ingest-chat|code-seed|" + "{start|stop|down|up|restart|status|queue|query|reset|destroy|cache|deploy|ingest-chat|" + "code-seed|" "code-backfill|code-rebuild|dream|vault-sync|embed|repo-sync|dialogue-sync|relate|lanes|" "reembed|" "tick|bless} " @@ -269,6 +276,18 @@ def main(argv: list[str]) -> int: return launcher.status() if cmd == "reset": return launcher.reset(confirm="--confirm" in flags) + if cmd == "destroy": + return launcher.destroy(confirm="--confirm" in flags) + if cmd == "cache": + sub = [a for a in argv[1:] if not a.startswith("-")] + if not sub: + return launcher.cache_report() + if sub == ["fill"]: + return launcher.cache_fill(confirm="--confirm" in flags) + if sub == ["prune"]: + return launcher.cache_prune(confirm="--confirm" in flags) + print("usage: palace.py cache [fill|prune] [--confirm]", file=sys.stderr) + return 2 if cmd == "deploy": return launcher.deploy(skip_tests="--skip-tests" in flags) if cmd == "ingest-chat": diff --git a/scripts/purge_raw.py b/scripts/purge_raw.py index 4be93109..495dd5e3 100644 --- a/scripts/purge_raw.py +++ b/scripts/purge_raw.py @@ -5,7 +5,10 @@ A vault delete only TOMBSTONES (derived dropped, raw kept). This removes the raw blob too — deliberate, irreversible, and refused unless `--confirm` is passed AND the digest is held by -no active note (tombstone it from the vault first). Lists tombstoned digests with `--list`. +no active note (tombstone it from the vault first). Lists tombstoned digests with `--list`. The +shared cache (`~/.mind-palace/cache`) loses the object and its chunks' vectors as well, and records +the digest so no instance puts it back (dn-instance-lifecycle §6.6). Refused while a reset of the +instance is pending (`data/reset.pending`), as every writer is. """ from __future__ import annotations @@ -25,12 +28,22 @@ def main(argv: list[str]) -> int: from config.loader import get_config from core.ingest.purge import PurgeRefusedError, purge_raw from core.kernel.stores.rawstore import RawStore + from core.stores.cache import Cache, cache_home from core.stores.catalog import VaultCatalog cfg = get_config() + listing = "--list" in argv or not argv + if not listing: + # a purge beside a pending reset could erase a version the reset's marker names + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "a purge") + if pending is not None: + print(pending) + return 1 catalog = VaultCatalog(cfg.paths.vault_catalog) - if "--list" in argv or not argv: + if listing: tombstoned: dict[str, list[str]] = {} for entry in catalog._conn.execute( # noqa: SLF001 (admin script, read-only) "SELECT source_path, digest FROM vault_files WHERE active = 0 ORDER BY digest" @@ -53,12 +66,14 @@ def main(argv: list[str]) -> int: store=open_vector_store(cfg), catalog=catalog, confirm=confirm, + cache=Cache(cache_home()), ) except PurgeRefusedError as e: print(f"REFUSED: {e}") return 1 print(f"purged {result.digest}: raw_removed={result.raw_removed} " - f"paths={list(result.paths_removed)}") + f"paths={list(result.paths_removed)} cache: raw_removed={result.cache_raw_removed} " + f"vectors_removed={result.cache_vectors_removed}") return 0 diff --git a/scripts/reembed_bodyonly.py b/scripts/reembed_bodyonly.py index 82b71493..c3b576f6 100644 --- a/scripts/reembed_bodyonly.py +++ b/scripts/reembed_bodyonly.py @@ -130,9 +130,15 @@ def main(argv: list[str]) -> int: from core.dreaming import build_dreamer from core.ingest.run import run_ingest from core.stores.derived import open_derived_store + from ops.lifecycle.inventory import refusal from ops.lifecycle.runs import open_run_ledger cfg = get_config() + if "--confirm" in argv: + pending = refusal(cfg, "the re-embed") # a pending reset refuses writers + if pending is not None: + print(pending) + return 1 derived = open_derived_store(cfg) if "--confirm" not in argv: # dry-run is the default (fail-safe) diff --git a/scripts/review.py b/scripts/review.py index 530e5b99..ba1bc9e6 100644 --- a/scripts/review.py +++ b/scripts/review.py @@ -16,7 +16,8 @@ signing only, no model in the path. The verdict store is append-only (a correction is a new, higher-seq verdict, never an edit). Fail-closed on a missing owner key (refuse, as `scripts/verdict.py:43-47`). Verdicts + probes are operational ground truth, ∉ `MIRROR_READABLE`. -Zone A, no network. +Zone A, no network. Refused while a reset of the instance is pending (`data/reset.pending`), as +`verdict.py submit` is: each verdict applies a disposition, a store the reset rebuilds. A/B is NATIVE: `RunLedger.runs()` maps `run_id → pipeline` ("phase7" | "dream_v2"); interleaving claims labeled by their run's pipeline IS the A/B — precision splits fall out of a verdict × @@ -255,8 +256,13 @@ def main(argv: list[str]) -> int: from config.loader import get_config, get_secret from core.stores.runledger import open_run_ledger + from ops.lifecycle.inventory import refusal cfg = get_config() + pending = refusal(cfg, "the review") # each verdict applies a disposition a reset rebuilds + if pending is not None: + print(pending) + return 1 seed = get_secret(cfg.attestation.owner_key_secret) if not seed: # fail closed — exactly scripts/verdict.py:43-47 print(f"error: no owner signing key at get_secret({cfg.attestation.owner_key_secret!r}); " diff --git a/scripts/sense_self.py b/scripts/sense_self.py index 0bcf6c14..2d297d53 100644 --- a/scripts/sense_self.py +++ b/scripts/sense_self.py @@ -5,7 +5,9 @@ Sync semantics subsume both the per-commit hook case (one missing commit) and full-history backfill — idempotent, oldest first, a missed hook heals on the next run. Stateless: reads -git subprocess output + config paths only (§2.6); no model, no transcript access. +git subprocess output + config paths only (§2.6); no model, no transcript access. Refused while a +reset of the instance is pending (`data/reset.pending`), since the agent observations are a store +the reset rebuilds: the post-commit hook reports a failed sync, and a sync after the reset heals. """ from __future__ import annotations @@ -19,6 +21,13 @@ def main() -> int: + from config.loader import get_config + from ops.lifecycle.inventory import refusal + + pending = refusal(get_config(), "the self sensor's sync") # a pending reset refuses writers + if pending is not None: + print(pending) + return 1 print(build_self_sensor().sync()) return 0 diff --git a/scripts/snapshot_code.py b/scripts/snapshot_code.py index e0679ff0..952d75d3 100644 --- a/scripts/snapshot_code.py +++ b/scripts/snapshot_code.py @@ -5,7 +5,9 @@ Sync semantics subsume both the per-commit hook case (one missing commit) and backfill (all missing commits) — idempotent, oldest first, a missed hook heals on the next run. -Model-less: the agent holds git-read, ledger-write, attest, and nothing else. +Model-less: the agent holds git-read, ledger-write, attest, and nothing else. Refused while a +reset of the instance is pending (`data/reset.pending`), since the code observations are a store +the reset rebuilds: the post-commit hook reports a failed sync, and a sync after the reset heals. """ from __future__ import annotations @@ -19,6 +21,13 @@ def main() -> int: + from config.loader import get_config + from ops.lifecycle.inventory import refusal + + pending = refusal(get_config(), "the code sensor's sync") # a pending reset refuses writers + if pending is not None: + print(pending) + return 1 print(build_code_sensor().sync()) return 0 diff --git a/scripts/talk.py b/scripts/talk.py index ee92387d..8b3f70e7 100644 --- a/scripts/talk.py +++ b/scripts/talk.py @@ -16,6 +16,10 @@ graph (scripts/ingest_self_knowledge.py). OFFLINE uses a hashing embedder + a deterministic responder over a throwaway temp store seeded with a few sample notes + the real design docs, so the full loop (retrieve / explain / status / task→deferred / capture) runs with no Ollama. + +LIVE is refused while a reset of the instance is pending (`data/reset.pending`): with no daemon +live it lands what the inbox kept, and a verdict the Ambassador carries applies a disposition, so +it is a writer, and a writer does not start beside a half-rebuilt instance. """ from __future__ import annotations @@ -130,6 +134,13 @@ def main(argv: list[str]) -> int: runtime = _offline_runtime() print("mind-palace (OFFLINE demo — deterministic, throwaway store).") else: + from config.loader import get_config + from ops.lifecycle.inventory import refusal + + pending = refusal(get_config(), "to talk") # it lands the inbox's record with no daemon + if pending is not None: + print(pending) + return 1 from ops.lifecycle.launcher import build_launcher from scheduler.interface import build_conversation_runtime runtime = build_conversation_runtime() diff --git a/scripts/verdict.py b/scripts/verdict.py index b40a139a..6ae2fff0 100644 --- a/scripts/verdict.py +++ b/scripts/verdict.py @@ -10,7 +10,9 @@ it verifies against the owner PUBLIC key (`ops/attestation/owner.pub`), appends to the append-only store (monotonic seq), and applies the disposition (a `wrong`/`noise` verdict retracts its subject from the active projection; weight promotion is parked). The Ambassador is transport only (§4); this -CLI is the owner's direct surface. Zone A, no network. +CLI is the owner's direct surface. Zone A, no network. `submit` is refused while a reset of the +instance is pending (`data/reset.pending`): the dispositions it applies are a store the reset +rebuilds. """ from __future__ import annotations @@ -62,7 +64,12 @@ def cmd_sign(subject_id: str, verdict: str, seq: int | None) -> int: def cmd_submit(blob: str) -> int: from core.verdict import SignedVerdict from core.verdict.apply import build_verdict_receiver, effect_of + from ops.lifecycle.inventory import refusal + pending = refusal(_cfg(), "a verdict") # it applies a disposition, which a reset rebuilds + if pending is not None: + print(pending) + return 1 try: signed = SignedVerdict.from_dict(json.loads(blob)) except (ValueError, KeyError) as e: diff --git a/scripts/watch.py b/scripts/watch.py index e8081c53..a2616aec 100644 --- a/scripts/watch.py +++ b/scripts/watch.py @@ -71,6 +71,12 @@ def main() -> int: from scheduler.vault_sync import VAULT_SYNC_KIND, build_vault_watcher cfg = get_config() + from ops.lifecycle.inventory import refusal + + pending = refusal(cfg, "to start") # a reset's marker refuses the daemon's start too + if pending is not None: + print(pending) + return 1 # FIRST — before the queue, the loader, or the watcher exist. Nothing may be claimed, swept # or even opened until this process is established as the sole supervisor. diff --git a/tests/fixtures/lifecycle.py b/tests/fixtures/lifecycle.py new file mode 100644 index 00000000..1e142b96 --- /dev/null +++ b/tests/fixtures/lifecycle.py @@ -0,0 +1,431 @@ +"""A whole palace on temporary stores, for the lifecycle's tests (dn-instance-lifecycle §8): notes +in a vault with authored and interpreted relation edges, a superseded note version, open-corpus +items, a repository landed lexically and read by the code sensor, transcripts through the chat +sensor (one grown, one held by the guard), the chat events and causal edges over them, signed +verdicts and their dispositions, and an attestation trail. Every path the configuration names is +under one root; nothing reads or writes a live instance. The embedder is a deterministic fake that +counts its calls. + +`dump` reads every store read only: a SQLite file as its tables' rows, a directory as its files' +bytes, so two dumps compare a palace before and after a reset or a destroy. +""" + +from __future__ import annotations + +import json +import sqlite3 +import subprocess +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any + +from core.attestation.attestor import StoreAttestor +from core.attestation.store import AttestationStore +from core.ingest import ingress +from core.ingest.readers import PalaceView +from core.ingest.table import build_table +from core.ingest.writer import Stores +from core.kernel.config import get_config +from core.kernel.config.loader import InstanceConfig, RepositoryConfig +from core.kernel.stores.rawstore import RawStore +from core.sentence import ast +from core.sentence.plan import compile_sentence +from core.stores.catalog import VaultCatalog +from core.stores.edges import open_edge_store +from core.stores.lexical import LexicalStore, lexical_path +from core.stores.vectorstore import VectorStore, fingerprint_of +from core.stores.versions import open_version_store +from edge.corpus.stream import StreamWriter +from tests.fixtures.embedding import DIM, FakeEmbedder + +REPO = "toy" +CORPUS_SOURCE = "alpha" + + +class CountingEmbedder(FakeEmbedder): + """The fake embedder, counting the texts it is asked for.""" + + def __init__(self) -> None: + self.calls = 0 + self.texts = 0 + + def embed_documents(self, texts: list[str]) -> list[list[float]]: + self.calls += 1 + self.texts += len(texts) + return super().embed_documents(texts) + + +def git(repo: Path, *args: str) -> str: + return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, + text=True).stdout.strip() + + +def commit(repo: Path, message: str) -> str: + git(repo, "add", "-A") + git(repo, "-c", "user.email=t@example.org", "-c", "user.name=t", "commit", "-q", "-m", + message) + return git(repo, "rev-parse", "HEAD") + + +def make_repo(at: Path) -> Path: + """A repository on `main` with code that references a doc, and a doc that names the code.""" + (at / "pkg").mkdir(parents=True) + (at / "docs").mkdir() + git(at.parent, "init", "-q", "-b", "main", str(at)) + (at / "pkg" / "embed.py").write_text( + 'def embed_fitting(texts):\n """Cut a text to fit; see docs/landing.md."""\n' + " return texts\n") + (at / "docs" / "landing.md").write_text( + "# Landing\n\nThe cut lives in `pkg/embed.py`.\n") + commit(at, "one") + (at / "pkg" / "derive.py").write_text( + "from pkg.embed import embed_fitting\n\n\ndef drain():\n return embed_fitting([])\n") + commit(at, "two") + return at + + +def instance_config(root: Path, repo: Path | None = None, *, named: str | None = None, + lazy: bool = False, embedding: bool = True, model: str | None = None, + sources: Path | None = None) -> Any: + """A palace whose every written path is under `root` (its data under `root/data`), reading + its vault and transcripts from under `sources` (`root` when not given), its corpus streams + from `root/sources`, and `repo` as its code. A named instance's destroy refuses a root that + holds what is not its own state, so a named fixture reads its vault from outside its root. + + A named fixture's configuration is built here, not loaded, so the process's configuration + (`get_config()`), which the landing log reads its secret through, stays the default + instance's, and the suite's item keys its catalog. A test of the named instance's own item, + `.landing-log-key`, loads the instance through an overlay instead.""" + data = root / "data" + data.mkdir(parents=True, exist_ok=True) + read = sources if sources is not None else root + (read / "vault").mkdir(parents=True, exist_ok=True) + (read / "transcripts").mkdir(exist_ok=True) + base = get_config() + paths = replace(base.paths, data_dir=data, raw_store=data / "raw", + vector_store=data / "vectors.lance", + curated_store=data / "research_curated.lance", + vault_catalog=data / "vault_catalog.sqlite", + derived_store=data / "derived.sqlite", telemetry_db=data / "telemetry.duckdb", + attestation_store=data / "attestations.sqlite") + code = replace(base.ingestion.code, enabled=repo is not None, embed=False, + repositories=(RepositoryConfig(REPO, repo, "main"),) if repo else ()) + corpus = replace(base.ingestion.corpus, enabled=True, root=root / "sources", + sources=(CORPUS_SOURCE,)) + ingestion = replace(base.ingestion, code=code, corpus=corpus, + vault=replace(base.ingestion.vault, path=read / "vault", enabled=True), + transcripts=replace(base.ingestion.transcripts, enabled=True, + transcripts_dir=read / "transcripts")) + emb = replace(base.embedding, enabled=embedding, lazy=lazy, dim=DIM) + if model: + emb = replace(emb, model=model) + cfg = replace(base, paths=paths, ingestion=ingestion, embedding=emb, + interface=replace(base.interface, handoff_dir=data / "handoff"), + airlock=replace(base.airlock, handoff_dir=data / "airlock"), + selfmod=replace(base.selfmod, ledger_db=data / "selfmod_ledger.sqlite"), + effectors=replace(base.effectors, ledger_db=data / "effectors" / "effects.sqlite", + drafts_dir=data / "effectors" / "drafts", + handoff_dir=data / "handoff" / "sensing")) + if named is not None: + cfg = replace(cfg, instance=InstanceConfig(named, home=root)) + return cfg + + +def stores_for(cfg: Any, embedder: Any, *, lexical: LexicalStore | None = None) -> Stores: + """The writer's stores over `cfg`'s paths, the attestor writing the instance's own ledger.""" + return Stores(raw=RawStore(cfg.paths.raw_store), + plane=VectorStore(cfg.paths.vector_store, dim=DIM, + embedder=fingerprint_of(cfg)) if cfg.embedding.enabled + else _noplane(), + embedder=embedder, catalog=VaultCatalog(cfg.paths.vault_catalog), + versions=open_version_store(cfg), + attestor=StoreAttestor(AttestationStore(cfg.paths.attestation_store)), + edges=open_edge_store(cfg), + lexical=lexical if lexical is not None else LexicalStore(lexical_path(cfg))) + + +def _noplane() -> Any: + from core.stores.noplane import NoPlane + + return NoPlane() + + +def perform(cfg: Any, stores: Stores, text: str, role: str = "cli", *, + batch: bool = False) -> dict[str, Any]: + plan = compile_sentence(text, ingress.grant_for(role), role=role) + assert isinstance(plan.term, ast.Do) + view = PalaceView(build_table(cfg), role, stores.catalog, refresh=False) + return ingress.perform(plan.term, cfg, role, stores=stores, view=view, batch=batch) + + +def fill_stream(cfg: Any, n: int = 3) -> None: + w = StreamWriter(cfg.ingestion.corpus.root / CORPUS_SOURCE, part_bytes=300) + for i in range(n): + w.append(f"a-{i}", f"alpha {i}", + f"open item {i}: a paragraph of public text about landing without vectors. " + "It shares this sentence with every other item of the stream. " * 2) + w.close() + + +def _rec(rtype: str, content: Any, session: str, ts: str) -> dict[str, Any]: + return {"type": rtype, "sessionId": session, "timestamp": ts, "uuid": "u", + "parentUuid": None, "message": {"role": rtype, "content": content}} + + +def transcript(cfg: Any, session: str, turns: list[tuple[str, Any]]) -> Path: + p = Path(cfg.ingestion.transcripts.transcripts_dir) / f"{session}.jsonl" + p.write_text("".join(json.dumps(_rec(r, c, session, f"2026-11-0{1 + i % 8}T00:00:00Z")) + "\n" + for i, (r, c) in enumerate(turns)), encoding="utf-8") + return p + + +@dataclass +class Built: + cfg: Any + root: Path + repo: Path + embedder: CountingEmbedder + stores: Stores + owner: Any = None + notes: dict[str, Path] = field(default_factory=dict) + + +def build_palace(root: Path, repo: Path, *, named: str | None = None) -> Built: + """Exercise every lane the lifecycle tests read, under `root`.""" + from core.attestation import Ed25519Signer, generate_seed + from core.chat_events import build_chat_event_projector + from core.integrator import build_integrator + from core.kernel.complex_types import EdgeSign + from core.relations import RelationDetector + from core.sensing import AgentSensingHandoff, CodeSensingHandoff + from core.stores.agent_observations import open_agent_observation_store + from core.stores.code_observations import open_code_observation_store + from core.stores.observation_history import open_observation_history_store + from core.stores.reference_edges import open_reference_edge_store + from core.stores.verdicts import VerdictStore + from core.verdict import VerdictPayload, sign_verdict + from core.verdict.apply import apply_verdict, receive_verdict + from core.verdict.dispositions import DispositionStore + from ops.chat_sensor import build_chat_sensor + from ops.code_sensor import CodeSensor + from ops.code_snapshot import open_snapshot_db + from ops.self_sensor import SelfSensor + + cfg = instance_config(root, repo, named=named, + sources=root.parent / f"{named}-read" if named else None) + emb = CountingEmbedder() + stores = stores_for(cfg, emb) + b = Built(cfg, root, repo, emb, stores) + vault = Path(cfg.ingestion.vault.path) + # notes: one supports another; one changes, so a superseded version exists + b.notes = { + "alpha": vault / "alpha.md", "beta": vault / "beta.md", "gamma": vault / "gamma.md"} + b.notes["alpha"].write_text("supports:: [[beta]]\n\nAlpha: landing needs no vector.\n") + b.notes["beta"].write_text("Beta: an item is complete without its vector.\n") + b.notes["gamma"].write_text("Gamma, first draft.\n") + assert perform(cfg, stores, "do sync_vault")["effects"].get("landed") == 3 + b.notes["gamma"].write_text("Gamma, second draft, which supersedes the first.\n") + perform(cfg, stores, "do sync_vault") + assert stores.edges is not None + detector = RelationDetector(config=cfg, edges=stores.edges, catalog=stores.catalog, + vectors=stores.plane, chat=None) + detector.run() + cat = {e.title: e.digest for e in stores.catalog.active_entries()} + stores.edges.add(cat["beta"], cat["gamma"], sign=EdgeSign.SUPPORT, rel_type="supports", + w=0.8, provenance="interpreted") + # open corpus items, observed, with plane rows + fill_stream(cfg) + perform(cfg, stores, f'do sync_corpus(name: "{CORPUS_SOURCE}", batch: 10)', role="corpus", + batch=True) + # the repository, lexically, and its commits through the code sensor + perform(cfg, stores, f'do sync_repository(name: "{REPO}")') + data = Path(cfg.paths.data_dir) + sensor = CodeSensor( + repo=repo, db=open_snapshot_db(data / "code_snapshots.sqlite"), attestor=stores.attestor, + observations=open_code_observation_store(cfg), + obs_handoff=CodeSensingHandoff(handoff=data / "code_sensing_handoff"), + reference_edges=open_reference_edge_store(cfg), + history=open_observation_history_store(cfg)) + sensor.sync() + sensor.backfill_observations() + SelfSensor(repo=repo, store=open_agent_observation_store(cfg), + handoff=AgentSensingHandoff(handoff=data / "agent_sensing_handoff"), + attestor=None, history=open_observation_history_store(cfg)).sync() + # transcripts: one plain, one grown, one held at its state before a secret + chat = build_chat_sensor(cfg) + transcript(cfg, "s-plain", [("user", "how does a reset work?"), + ("assistant", [{"type": "text", "text": "it rebuilds."}])]) + transcript(cfg, "s-grown", [("user", "first question")]) + transcript(cfg, "s-held", [("user", "a clean opening")]) + head = git(repo, "rev-parse", "HEAD") + transcript(cfg, "s-commit", [ + ("user", "commit it"), + ("assistant", [{"type": "tool_use", "id": "t1", "name": "Bash", + "input": {"command": "git commit -m two"}}]), + ("user", [{"type": "tool_result", "tool_use_id": "t1", + "content": f"[main {head[:7]}] two"}]), + ("assistant", "committed")]) + chat.sync() + transcript(cfg, "s-grown", [("user", "first question"), + ("assistant", "a later answer, after it grew")]) + transcript(cfg, "s-held", [("user", "a clean opening"), + ("assistant", "api_key = " + "A1b2C3d4" * 5)]) + chat.sync() + build_chat_event_projector(cfg).project(max_sessions=100) + build_integrator(cfg).integrate(max_sessions=100) + # verdicts, signed by an owner key, and their dispositions + owner = Ed25519Signer.from_seed(generate_seed(), "owner") + b.owner = owner + verdicts = VerdictStore(data / "verdicts.sqlite") + dispositions = DispositionStore(data / "verdict_dispositions.sqlite") + for seq, (subject, verdict) in enumerate([("claim-1", "novel_useful"), ("claim-2", "wrong"), + ("claim-1", "noise")], start=1): + rec = receive_verdict(sign_verdict(VerdictPayload( + subject_id=subject, verdict=verdict, seq=seq, timestamp="2026-11-01T00:00:00"), + owner), verdicts, owner_pub_b64=owner.public_b64()) + apply_verdict(rec, dispositions) + verdicts.close() + dispositions.close() + write_kept_stores(cfg) + return b + + +def close_stores(b: Built) -> None: + """Close every store the fixture holds open, as an instance at rest has them: SQLite then + checkpoints each database and removes its `-wal` and `-shm`. They are closed by hand and not + left to the garbage collector: a connection the collector finalizes keeps its two files, as a + run under coverage showed.""" + s = b.stores + plane = getattr(s.plane, "plane", None) # the vector store's plane; NoPlane has none + for store in (s.catalog, s.lexical, s.versions, s.edges, getattr(s.attestor, "store", None), + plane): + if store is not None and hasattr(store, "close"): + store.close() + + +def write_kept_stores(cfg: Any) -> None: + """One row or more in each kept store a reset must leave as it was (§3.5, §3.7): an + interpreted artifact (decision D4), a queued job carrying a request (D7), a dream run and its + claim, a claim operation and a staged hypothesis.""" + from core.kernel.provenance import Provenance + from core.kernel.recursion_ops import OpKind + from core.kernel.scope import Stratum + from core.stores.claim_ops import open_claim_op_store + from core.stores.derived import DerivedStore + from core.stores.runledger import open_run_ledger + from core.stores.staging import StagedItem, open_staging_store + from scheduler.queue import JobQueue + + derived = DerivedStore(Path(cfg.paths.derived_store)) + derived.add(kind="synthesis", summary="a model's sentence over two notes", subjects=("x",)) + derived.close() + queue = JobQueue(Path(cfg.paths.data_dir) / "queue.sqlite") + queue.enqueue("ingress", "small", 1024, payload={"text": "a request only the queue holds"}) + queue.close() + runs = open_run_ledger(cfg) + run = runs.start_run(pipeline="toy", config_fingerprint="f", corpus_digest="c", node_count=3, + edge_count=2, duration_s=0.1, spectral_stats={}) + runs.add_claim(run, kind="bridge", confidence=0.5, support=("a", "b"), + surface_text="a claim a model wrote", polarity="support") + runs.close() + ops = open_claim_op_store(cfg) + ops.record(OpKind.RECORD_WARRANT, "claim-1", text="a warrant") + ops.close() + staging = open_staging_store(cfg) + staging.stage("toy", [StagedItem(Stratum.OBSERVED, Provenance.OBSERVED, "d" * 64, "p")]) + staging.close() + + +# ── reading a palace back ─────────────────────────────────────────────────────────────────── + +#: Columns that hold a wall-clock bookmark: a rebuild writes its own time there (Law C4). +WALL = frozenset({"landed_at", "observed_at", "created_at", "at", "updated_at", "recorded_at", + "projected_at", "integrated_at", "extracted_at", "minted_at"}) + + +def sqlite_rows(path: Path, *, wall: bool = True) -> dict[str, list[tuple[Any, ...]]]: + """Every table's rows, sorted, read only, creating no file (`read_only`); `wall=False` leaves + the wall-clock columns out.""" + from ops.lifecycle.inventory import read_only + + conn = read_only(path) + try: + out: dict[str, list[tuple[Any, ...]]] = {} + for (table,) in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table' " + "AND name NOT LIKE 'sqlite_%'"): + cols = [str(r[1]) for r in conn.execute(f'PRAGMA table_info("{table}")')] + keep = [c for c in cols if wall or c not in WALL] + sel = ", ".join(f'"{c}"' for c in keep) + out[str(table)] = sorted(conn.execute(f'SELECT {sel} FROM "{table}"').fetchall(), + key=repr) + return out + finally: + conn.close() + + +def dump_path(path: Path, *, wall: bool = True) -> Any: + """A store's content: a SQLite file's rows, another file's bytes, a directory's files.""" + if path.is_dir(): + return {str(p.relative_to(path)): dump_path(p, wall=wall) + for p in sorted(path.rglob("*")) if p.is_file() + and not p.name.endswith(("-wal", "-shm", ".lock"))} + if not path.exists(): + return None + head = path.read_bytes()[:16] + if head.startswith(b"SQLite format 3"): + return sqlite_rows(path, wall=wall) + return path.read_bytes() + + +def dump(cfg: Any, kinds: set[Any] | None = None) -> dict[str, Any]: + """Every store of the class table under `cfg`, of `kinds` (all when None), in full.""" + from ops.lifecycle.inventory import STORES + + return {s.name: dump_path(s.path(cfg)) for s in STORES + if (kinds is None or s.kind in kinds) and s.name not in {"vectors.lance", + "supervisor.lock"}} + + +def heads(cfg: Any) -> dict[str, Any]: + """Each derived store's head, the wall-clock bookmarks left out (§4.4).""" + from core.kernel.clearance import MAINTENANCE_READ + from core.stores.plane import OCC + + data = Path(cfg.paths.data_dir) + out: dict[str, Any] = {} + for name in ("chatlog.sqlite", "chat_events.sqlite", "verdict_dispositions.sqlite", + "code_observations.sqlite", "agent_observations.sqlite"): + p = data / name + out[name] = sqlite_rows(p, wall=False) if p.exists() else None + edges = sqlite_rows(data / "edges.sqlite", wall=False)["edges"] + out["edges"] = edges + lex = sqlite3.connect(f"file:{data / 'lexical.sqlite'}?mode=ro", uri=True) + try: + out["lexical.units"] = sorted(lex.execute( + "SELECT source_path, digest, chunk_index, provenance, title, length FROM units " + "WHERE current = 1").fetchall()) + out["lexical.postings"] = sorted(lex.execute( + "SELECT u.source_path, u.digest, u.chunk_index, p.term, p.tf FROM postings p " + "JOIN units u ON u.unit_id = p.unit_id WHERE u.current = 1").fetchall()) + out["lexical.versions"] = sorted(lex.execute( + "SELECT v.source_path, v.digest, v.units FROM versions v WHERE EXISTS (SELECT 1 " + "FROM units u WHERE u.source_path = v.source_path AND u.digest = v.digest " + "AND u.current = 1) OR v.units = 0").fetchall()) + finally: + lex.close() + if cfg.embedding.enabled: + plane_db = Path(cfg.paths.vector_store) / "plane.sqlite" + conn = sqlite3.connect(f"file:{plane_db}?mode=ro", uri=True) + try: + occ = {p.value: sorted(conn.execute( + f"SELECT source_path, digest, chunk_index, atom_id, row_id, title FROM {t} " + "WHERE current = 1").fetchall()) for p, t in OCC.items()} + finally: + conn.close() + out["plane.occupancies"] = occ + store = VectorStore(cfg.paths.vector_store, dim=DIM, embedder=fingerprint_of(cfg)) + atoms = sorted({a for rows in occ.values() for _, _, _, a, _, _ in rows}) + out["plane.vectors"] = {a: list(v) for a, (_t, v) + in sorted(store.plane.atoms.payload(atoms).items())} + out["plane.count"] = store.reader(MAINTENANCE_READ).count() + return out diff --git a/tests/integration/test_instance_lifecycle.py b/tests/integration/test_instance_lifecycle.py new file mode 100644 index 00000000..4104c608 --- /dev/null +++ b/tests/integration/test_instance_lifecycle.py @@ -0,0 +1,1627 @@ +"""The instance's lifecycle (docs/design-notes/dn-instance-lifecycle.md §8): a reset that clears the +derived stores and rebuilds them from raw and the ledgers, a destroy that leaves a shared cache of +open content, the cache's reuse paths, a purge that reaches the cache, a sync that heals a stale +lexical index, and the corpus instance at its own root. + +Every test runs on fixture palaces under a temporary directory (`tests/fixtures/lifecycle.py`): +notes, a superseded note version, authored and interpreted relation edges, open-corpus items, a +repository through the repository sync and the code sensor, transcripts through the chat sensor +(one grown, one held by the guard), chat events and causal edges, signed verdicts and an +attestation trail. No test opens a real instance or the real cache. +""" + +from __future__ import annotations + +import os +import sqlite3 +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from core.kernel.config import loader +from ops.lifecycle import rebuild +from ops.lifecycle.inventory import STORES, Kind, unclassified +from ops.lifecycle.launcher import Launcher +from ops.lifecycle.lock import SupervisorLock +from ops.lifecycle.runs import LazyRunLedger, RunLedger +from tests.fixtures.lifecycle import ( + CORPUS_SOURCE, + REPO, + Built, + CountingEmbedder, + build_palace, + commit, + dump, + heads, + instance_config, + make_repo, + perform, + stores_for, +) + +KEPT = {Kind.LEDGER, Kind.DECLARATION, Kind.KEPT, Kind.OPERATIONAL} + + +@pytest.fixture(scope="module") +def repo(tmp_path_factory: pytest.TempPathFactory) -> Path: + return make_repo(tmp_path_factory.mktemp("git") / "repo") + + +@pytest.fixture +def palace(tmp_path: Path, repo: Path) -> Built: + return build_palace(tmp_path / "p", repo) + + +def launcher_for(b: Built, *, cache: Path | None = None, + embedder: CountingEmbedder | None = None) -> tuple[Launcher, list[Any]]: + """The palace's launcher, its embedder factory recording each embedder it builds, and its run + ledger opened at the first write, as `build_launcher` gives it.""" + made: list[Any] = [] + + def factory(_cfg: Any) -> Any: + e = embedder or CountingEmbedder() + made.append(e) + return e + + lau = Launcher(cfg=b.cfg, runs=LazyRunLedger(Path(b.cfg.paths.data_dir) / "runs.sqlite"), + repo_root=b.repo, embedder_factory=factory, + cache_root=cache or b.root.parent / "cache", + installed_plist=b.root / "no-agent.plist") + return lau, made + + +def raw_files(b: Built) -> dict[str, bytes]: + raw = Path(b.cfg.paths.raw_store) + return {str(p.relative_to(raw)): p.read_bytes() for p in sorted(raw.rglob("*")) + if p.is_file()} + + +def causal(b: Built) -> list[tuple[Any, ...]]: + from tests.fixtures.lifecycle import sqlite_rows + + rows = sqlite_rows(Path(b.cfg.paths.data_dir) / "causal_edges.sqlite", wall=False) + return sorted(r for t in rows.values() for r in t) + + +# ── the landing log, read back ────────────────────────────────────────────────────────────── + + +def landing_log(cfg: Any) -> dict[str, list[tuple[Any, ...]]]: + """The catalog's landing log, read only: every chain's row and every row of the log, in + order, each column as stored.""" + con = sqlite3.connect(f"file:{cfg.paths.vault_catalog}?mode=ro", uri=True) + try: + return {"chains": con.execute("SELECT * FROM landing_chains ORDER BY chain").fetchall(), + "rows": con.execute("SELECT * FROM landings ORDER BY chain, seq").fetchall()} + finally: + con.close() + + +def chain_heads(cfg: Any) -> dict[int, tuple[int, bytes]]: + """Each chain's head: its last position and that row's hash.""" + con = sqlite3.connect(f"file:{cfg.paths.vault_catalog}?mode=ro", uri=True) + try: + return {int(c): (int(s), bytes(h)) for c, s, h in con.execute( + "SELECT chain, seq, hash FROM landings AS l WHERE seq = " + "(SELECT max(seq) FROM landings WHERE chain = l.chain)")} + finally: + con.close() + + +def chains_verify(cfg: Any) -> bool: + """Whether the log has a chain and every chain verifies (`LandingLog.verify`: the hashes and + the commitments recomputed), read only. The check needs no secret.""" + from core.stores.landings import LandingLog + + con = sqlite3.connect(f"file:{cfg.paths.vault_catalog}?mode=ro", uri=True) + try: + log = LandingLog(con, lambda: b"") + chains = log.all_chains() + return bool(chains) and all(log.verify(c).ok for c in chains) + finally: + con.close() + + +def appended(before: dict[str, list[tuple[Any, ...]]], + after: dict[str, list[tuple[Any, ...]]]) -> list[tuple[Any, ...]]: + """The log's rows in `after` that `before` did not have, in order, once every chain and every + row `before` had is found unchanged in `after`.""" + old = {(r[0], r[1]): r for r in before["rows"]} + new = {(r[0], r[1]): r for r in after["rows"]} + assert after["chains"] == before["chains"] + assert all(new.get(k) == r for k, r in old.items()) + return [r for k, r in sorted(new.items()) if k not in old] + + +def without_log(cfg: Any) -> None: + """The catalog as one written before the landing log is, as the corpus's still is: its rows + and no log.""" + con = sqlite3.connect(cfg.paths.vault_catalog) + try: + con.executescript("DROP TABLE landings; DROP TABLE landing_chains;") + finally: + con.close() + + +# ── P1: the inventory is total ────────────────────────────────────────────────────────────── + + +def test_p1_every_store_a_palace_writes_is_in_exactly_one_class(palace: Built) -> None: + assert unclassified(palace.cfg) == [] + names = [s.name for s in STORES] + assert len(names) == len(set(names)) + paths = [s.path(palace.cfg) for s in STORES] + assert len(paths) == len(set(paths)), "two entries name one path" + + +def test_p1_every_open_helper_path_is_in_the_table(palace: Built) -> None: + """Each store an `open_*` helper opens lands at a path the table classifies.""" + from core.stores.agent_observations import open_agent_observation_store + from core.stores.causal_edges import open_causal_edge_store + from core.stores.chat_events import open_chat_event_store + from core.stores.chat_retention import open_retention_ledger + from core.stores.chatlog import open_chatlog_store + from core.stores.code_observations import open_code_observation_store + from core.stores.edges import open_edge_store + from core.stores.lexical import lexical_path + from core.stores.observation_history import open_observation_history_store + from core.stores.reference_edges import open_reference_edge_store + from core.stores.verdicts import open_verdict_store + from core.stores.versions import open_version_store + from core.verdict.dispositions import open_disposition_store + from ops.lifecycle.inventory import classify + + cfg = palace.cfg + opened: list[Any] = [open_agent_observation_store(cfg), open_causal_edge_store(cfg), + open_chat_event_store(cfg), open_retention_ledger(cfg), open_chatlog_store(cfg), + open_code_observation_store(cfg), open_edge_store(cfg), + open_observation_history_store(cfg), open_reference_edge_store(cfg), + open_verdict_store(cfg), open_version_store(cfg), open_disposition_store(cfg)] + for store in opened: + assert classify(cfg, Path(store.path)) is not None, store.path + assert classify(cfg, lexical_path(cfg)) is not None + + +# ── P2 to P5, P8: a confirmed reset ───────────────────────────────────────────────────────── + + +def test_p2_p3_p5_p8_a_reset_keeps_every_ledger_and_the_rebuild_converges( + palace: Built) -> None: + b = palace + for t in Path(b.cfg.ingestion.transcripts.transcripts_dir).iterdir(): + t.unlink() # P5: the transcripts are gone from their directory + lau, made = launcher_for(b) + before_kept, before_raw, before = dump(b.cfg, KEPT), raw_files(b), heads(b.cfg) + before_atts = dump(b.cfg)["attestations.sqlite"] + before_log, before_heads = landing_log(b.cfg), chain_heads(b.cfg) + for name in ("derived.sqlite", "queue.sqlite", "run_ledger.sqlite", "claim_ops.sqlite", + "staging.sqlite", "verdicts.sqlite", "versions.sqlite", "chat_retention.sqlite", + "code_snapshots.sqlite", "reference_edges.sqlite", "attestations.sqlite"): + assert any(before_kept[name].values()), f"the fixture writes no row in {name}" + kinds = {r[2] for r in before_log["rows"]} + assert {"genesis", "store", "horizon"} <= kinds, "the fixture's log has a genesis and landings" + assert len(before_heads) > 1 and chains_verify(b.cfg) # a chain for each class + assert lau.reset(confirm=True) == 0 + assert raw_files(b) == before_raw # P2: raw, byte for byte + assert dump(b.cfg, KEPT) == before_kept # P2: every kept store + assert dump(b.cfg)["attestations.sqlite"] == before_atts # no ledger written + assert landing_log(b.cfg) == before_log # P2: every log row, and + assert chain_heads(b.cfg) == before_heads # each chain's head hash: + assert chains_verify(b.cfg) # the rebuild appends none + after = heads(b.cfg) + for name in before: + assert after[name] == before[name], name # P3 + assert after["chatlog.sqlite"]["chat_utterances"] # P5: from raw alone + assert made == [] # P8: no embedder built + assert not (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + + +def test_p3_the_interpreted_edges_stay_and_the_authored_are_rebuilt(palace: Built) -> None: + edges_path = Path(palace.cfg.paths.data_dir) / "edges.sqlite" + con = sqlite3.connect(edges_path) + interpreted = con.execute("SELECT * FROM edges WHERE provenance = 'interpreted'").fetchall() + con.close() + assert interpreted + lau, _ = launcher_for(palace) + assert lau.reset(confirm=True) == 0 + con = sqlite3.connect(edges_path) + try: + assert con.execute("SELECT * FROM edges WHERE provenance = 'interpreted'").fetchall() \ + == interpreted # byte for byte, kept + assert con.execute("SELECT count(*) FROM edges WHERE provenance = 'authored-solo'" + ).fetchone()[0] == 1 + finally: + con.close() + + +def test_p4_a_reset_twice_is_the_reset_once_and_the_causal_edges_a_fresh_integration( + palace: Built) -> None: + b = palace + lau, _ = launcher_for(b) + log = landing_log(b.cfg) + assert lau.reset(confirm=True) == 0 + once, once_causal, once_kept = heads(b.cfg), causal(b), dump(b.cfg, KEPT) + assert lau.reset(confirm=True) == 0 + assert heads(b.cfg) == once and causal(b) == once_causal and dump(b.cfg, KEPT) == once_kept + assert landing_log(b.cfg) == log # two resets append nothing to the log + from core.integrator import build_integrator + build_integrator(b.cfg).integrate(max_sessions=100) # a fresh pass adds none + assert causal(b) == once_causal + + +def test_p3_the_atom_table_holds_exactly_what_the_rebuilt_rows_name(palace: Built) -> None: + """The plane's occupancies are forgotten and rebuilt for the heads (§4.2, §4.4), and the atoms + no rebuilt row holds are dropped last: a superseded version's occupancy and its atom go.""" + from core.stores.plane import OCC + from core.stores.vectorstore import VectorStore, fingerprint_of + from tests.fixtures.embedding import DIM + + def atoms() -> set[str]: + return VectorStore(palace.cfg.paths.vector_store, dim=DIM, + embedder=fingerprint_of(palace.cfg)).plane.atoms.ids() + + def rows(current: int) -> list[tuple[str, str]]: + con = sqlite3.connect(Path(palace.cfg.paths.vector_store) / "plane.sqlite") + try: + return [(str(p), str(a)) for t in OCC.values() for p, a in con.execute( + f"SELECT source_path, atom_id FROM {t} WHERE current = ?", [current])] + finally: + con.close() + + superseded = rows(0) + assert superseded, "the fixture holds a superseded version's occupancy" + before = atoms() + lau, _ = launcher_for(palace) + assert lau.reset(confirm=True) == 0 + assert rows(0) == [] # the old relations are forgotten + after = atoms() + assert after == {a for _, a in rows(1)} # exactly what the rebuilt rows name + assert before - after # the superseded atom was dropped + + +def test_p3_a_lazy_backlog_is_left_to_the_embed_job( + tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """On a lazy instance, items landed without their vector stay so: the reset re-occupies only + what the plane held, calls no embedder, and the dry run counts the backlog. A held note edited + since it was embedded comes back at the version the plane held, not dropped.""" + from core.ingest.derive import drain + + cfg = instance_config(tmp_path / "lazy", None, lazy=True) + stores = stores_for(cfg, CountingEmbedder()) + for i in range(3): + (Path(cfg.ingestion.vault.path) / f"n{i}.md").write_text(f"note {i}, embedded later\n") + assert perform(cfg, stores, "do sync_vault")["effects"] == {"landed": 3} + assert drain(stores, max_items=1).items == 1 # one held, two waiting + before = heads(cfg) + made: list[Any] = [] + + def factory(c: Any) -> CountingEmbedder: + made.append(c) + return CountingEmbedder() + + lau = Launcher(cfg=cfg, runs=RunLedger(tmp_path / "runs.sqlite"), repo_root=tmp_path, + embedder_factory=factory, + cache_root=tmp_path / "cache", installed_plist=tmp_path / "no.plist") + assert lau.reset(confirm=False) == 0 + out = capsys.readouterr().out + assert "re-occupies the 1 item(s)" in out and "2 item(s) of the plane's classes hold no " \ + "vector" in out and "the embedder is called for 0 atom(s)" in out + assert lau.reset(confirm=True) == 0 + assert made == [] + assert heads(cfg)["plane.occupancies"] == before["plane.occupancies"] + assert sum(len(v) for v in before["plane.occupancies"].values()) == 1 + + # The held note is edited and landed again, not yet embedded: the plane holds its old version, + # which is no longer the catalog's head. The reset rebuilds that version from raw, so the note + # stays searchable as it was and its new version stays with the embed job. + held_path = next(r[0] for rows in before["plane.occupancies"].values() for r in rows) + (Path(cfg.ingestion.vault.path) / held_path).write_text("note edited, embedded later\n") + assert perform(cfg, stores, "do sync_vault")["effects"] == {"landed": 1, "unchanged": 2} + head = stores.catalog.get(held_path) + assert head is not None and all(r[1] != head.digest + for rows in before["plane.occupancies"].values() + for r in rows) + before = heads(cfg) + assert lau.reset(confirm=False) == 0 + out = capsys.readouterr().out + assert "re-occupies the 1 item(s) the plane holds current (1 of them at a version older " \ + "than the catalog's)" in out and "3 item(s) of the plane's classes hold no vector " \ + "for their current version" in out and "the embedder is called for 0 atom(s)" in out + assert lau.reset(confirm=True) == 0 + out = capsys.readouterr().out + assert "plane: 1 item(s)" in out and "0 atom(s) no rebuilt row holds dropped" in out + assert made == [] + assert heads(cfg)["plane.occupancies"] == before["plane.occupancies"] + assert heads(cfg)["plane.vectors"] == before["plane.vectors"] + assert sum(len(v) for v in before["plane.occupancies"].values()) == 1 + + +def test_p3_a_purged_transcript_is_skipped_and_the_reset_finishes( + palace: Built, capsys: pytest.CaptureFixture[str]) -> None: + """A purge is how raw content is erased, and a transcript has no catalog row, so a retained + transcript can lose its raw object. The replay skips it and says so; the reset finishes, and + the chat log comes back without that session.""" + from core.ingest.purge import purge_raw + + b = palace + con = sqlite3.connect(Path(b.cfg.paths.data_dir) / "chat_retention.sqlite") + held = [str(d) for d, f in con.execute("SELECT digest, file FROM retained ORDER BY seq") + if f == "s-held"] + con.close() + assert len(held) == 2 + for digest in held: + purge_raw(digest, raw=b.stores.raw, store=b.stores.plane, catalog=b.stores.catalog, + confirm=True) + lau, _ = launcher_for(b) + assert lau.reset(confirm=True) == 0 + assert "purged=2" in capsys.readouterr().out + assert not (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + con = sqlite3.connect(Path(b.cfg.paths.data_dir) / "chatlog.sqlite") + sessions = {str(r[0]) for r in con.execute("SELECT DISTINCT session_id FROM chat_utterances")} + con.close() + assert "s-plain" in sessions and "s-held" not in sessions + assert lau.reset(confirm=True) == 0 # and again, as a reset is + + +def test_p7_a_missing_commit_refuses_before_anything_is_cleared(tmp_path: Path) -> None: + """A commit the commit ledger holds that the repository has since pruned: the re-projection + could not read it, so the reset refuses with nothing written, rather than failing after the + clearing and leaving the marker behind.""" + from tests.fixtures.lifecycle import git + + repo = make_repo(tmp_path / "git" / "repo") + b = build_palace(tmp_path / "p", repo) + git(repo, "reset", "-q", "--hard", "HEAD~1") + git(repo, "reflog", "expire", "--expire=now", "--all") + git(repo, "gc", "-q", "--prune=now") + lau, _ = launcher_for(b) + _unchanged(b, lambda: lau.reset(confirm=True)) + assert not (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + + +# ── P6: the dry run ───────────────────────────────────────────────────────────────────────── + + +def test_p6_the_dry_run_writes_nothing_and_names_every_store_it_would_clear( + palace: Built, capsys: pytest.CaptureFixture[str]) -> None: + lau, _ = launcher_for(palace) + before, before_heads = dump(palace.cfg), heads(palace.cfg) + assert lau.reset(confirm=False) == 0 + out = capsys.readouterr().out + assert dump(palace.cfg) == before and heads(palace.cfg) == before_heads + for s in rebuild.found(palace.cfg): + assert s.name in out + assert "DRY RUN" in out + + +def test_p6_the_dry_run_at_rest_creates_and_touches_no_file(palace: Built) -> None: + """On an instance at rest, every store closed: the dry run reads each SQLite file, the plane's + included, without creating or touching a file, asks the plane's geometry read only, and reads + the run ledger read only, so nothing under the root changes, not even a modification time.""" + from tests.fixtures.lifecycle import close_stores + + lau, _ = launcher_for(palace) + close_stores(palace) + before = _files(palace.root) + assert not [f for f in before if f.endswith(("-wal", "-shm"))], "the fixture is not at rest" + assert lau.reset(confirm=False) == 0 + assert _files(palace.root) == before + + +# ── P7: the refusals ──────────────────────────────────────────────────────────────────────── + + +def _unchanged(b: Built, act: Any) -> None: + before, before_heads = dump(b.cfg), heads(b.cfg) + assert act() == 1 + assert dump(b.cfg) == before and heads(b.cfg) == before_heads + + +def _live_elsewhere(b: Built) -> RunLedger: + """A live run opened through a ledger of its own, as the daemon holds the run ledger: a + launcher's ledger, opened at its first write, reads the run from the file (`last_run`).""" + holder = RunLedger(Path(b.cfg.paths.data_dir) / "runs.sqlite") + holder.open_run(commit_sha="x", dirty=False, pid=os.getpid()) + return holder + + +def _refuses_while_live(b: Built, holder: RunLedger, act: Any, *, + cache: Path | None = None) -> None: + """`act(launcher)` refuses beside the holder's live run, with the run's frames in the `-wal` + and again after a checkpoint has emptied it; each launcher reads the run from the file and + never opens its own ledger, and a fresh launcher's on-demand verb refuses the same way.""" + for checkpoint in (False, True): + if checkpoint: + holder._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") + assert Path(f"{holder.path}-wal").stat().st_size == 0 + lau, _ = launcher_for(b, cache=cache) + _unchanged(b, lambda lau=lau: act(lau)) + fresh, _ = launcher_for(b) + assert fresh._refuse_if_live("embed") + assert "_conn" not in lau.runs.__dict__ and "_conn" not in fresh.runs.__dict__ + + +def test_p7_a_live_run_refuses(palace: Built) -> None: + """The run is held by another ledger, as by the daemon, so the refusal rests on the read of + the file each command makes (`LazyRunLedger.last`); once the run stops, nothing refuses.""" + holder = _live_elsewhere(palace) + try: + _refuses_while_live(palace, holder, lambda lau: lau.reset(confirm=True)) + run = holder.last() + assert run is not None + holder.mark_stopped(run.id, clean=True) + assert not launcher_for(palace)[0]._refuse_if_live("embed") + finally: + holder.close() + + +def test_p7_the_lock_held_refuses(palace: Built) -> None: + lau, _ = launcher_for(palace) + lock = SupervisorLock(Path(palace.cfg.paths.data_dir) / "supervisor.lock") + lock.acquire() + try: + _unchanged(palace, lambda: lau.reset(confirm=True)) + finally: + lock.release() + + +def test_p7_a_changed_embedder_geometry_refuses(palace: Built) -> None: + lau, _ = launcher_for(palace) + lau.cfg = replace(palace.cfg, embedding=replace(palace.cfg.embedding, model="another-model")) + _unchanged(palace, lambda: lau.reset(confirm=True)) + + +def test_p7_a_derived_store_outside_the_data_directory_refuses_before_the_marker( + palace: Built, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """`derived_store` configured outside the data directory puts the dispositions beside it, where + the clearing refuses to reach. The reset finds that before it writes anything, the marker + included, so no writer is left refusing behind a marker every rerun would leave again.""" + import shutil + + lau, _ = launcher_for(palace) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + data = Path(palace.cfg.paths.data_dir) + for name in ("derived.sqlite", "verdicts.sqlite", "verdict_dispositions.sqlite"): + shutil.copy2(data / name, elsewhere / name) + lau.cfg = replace(palace.cfg, paths=replace(palace.cfg.paths, + derived_store=elsewhere / "derived.sqlite")) + before = _files(elsewhere) + for confirm in (True, True, False): + _unchanged(palace, lambda c=confirm: lau.reset(confirm=c)) + assert not (data / "reset.pending").exists() + assert "does not lie under the data directory" in capsys.readouterr().out + assert _files(elsewhere) == before + + +# ── P17: the landing log through a reset and a destroy ────────────────────────────────────── + + +def test_p17_the_steps_that_open_the_catalog_are_the_ones_the_refusal_reads( + palace: Built, monkeypatch: pytest.MonkeyPatch) -> None: + """The refusal without the landing log's secret is read for the steps of `OPENS_CATALOG` + alone, so those must be every step that opens the catalog: each step is run with the step's + name recorded at each open, through the context or through `VaultCatalog` itself, and the + clearing opens it never.""" + from core.stores.catalog import VaultCatalog + + current = ["the clearing"] + opened: set[str] = set() + real_context, real_init = rebuild.Context.catalog, VaultCatalog.__post_init__ + + def context_catalog(self: Any) -> Any: + opened.add(current[0]) + return real_context(self) + + def init(self: Any) -> None: + opened.add(current[0]) + real_init(self) + + monkeypatch.setattr(rebuild.Context, "catalog", context_catalog) + monkeypatch.setattr(VaultCatalog, "__post_init__", init) + for name, step in list(rebuild.STEPS.items()): + def named(ctx: Any, _name: str = name, _step: Any = step) -> str: + current[0] = _name + return str(_step(ctx)) + monkeypatch.setitem(rebuild.STEPS, name, named) + assert {s.name for s in rebuild.found(palace.cfg)} == set(rebuild.STEPS) # every step runs + lau, _ = launcher_for(palace) + assert lau.reset(confirm=True) == 0 + assert opened == rebuild.OPENS_CATALOG + + +def test_p17_a_reset_that_would_write_the_genesis_refuses_without_the_secret( + palace: Built, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """A catalog with rows and no landing log, as one written before the log is: the rebuild's + first open of it writes the log's genesis, which needs the secret. Without it the reset + refuses, its dry run too, before anything is written, the log's empty tables included; with it + the genesis is written at that open, the catalog's rows stay as they were and the log + verifies.""" + from core.stores.landings import LANDING_LOG_KEY + from tests.conftest import LANDING_LOG_TEST_KEY + from tests.fixtures.lifecycle import sqlite_rows + + b = palace + rows = sqlite_rows(Path(b.cfg.paths.vault_catalog))["vault_files"] + without_log(b.cfg) + assert rebuild.catalog_without_log(b.cfg) == len(rows) > 0 + before = heads(b.cfg) + monkeypatch.delenv(LANDING_LOG_KEY) + lau, _ = launcher_for(b) + _unchanged(b, lambda: lau.reset(confirm=False)) + _unchanged(b, lambda: lau.reset(confirm=True)) + out = capsys.readouterr().out + assert "no landing log yet" in out and f"get_secret({LANDING_LOG_KEY!r})" in out + assert not (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + tables = sqlite_rows(Path(b.cfg.paths.vault_catalog)) + assert set(tables) == {"vault_files"} and tables["vault_files"] == rows + monkeypatch.setenv(LANDING_LOG_KEY, LANDING_LOG_TEST_KEY) + before_dry = dump(b.cfg) + assert lau.reset(confirm=False) == 0 + assert "writes the log's genesis" in capsys.readouterr().out + # with the secret at hand the dry run still writes nothing: no genesis, no log table + assert dump(b.cfg) == before_dry + assert set(sqlite_rows(Path(b.cfg.paths.vault_catalog))) == {"vault_files"} + assert lau.reset(confirm=True) == 0 + assert sqlite_rows(Path(b.cfg.paths.vault_catalog))["vault_files"] == rows + assert chains_verify(b.cfg) and heads(b.cfg) == before + log = landing_log(b.cfg)["rows"] + # the genesis: a `store` of every catalog row, and nothing a rebuild step appended + assert sorted(r[4] for r in log if r[2] == "store") == sorted(r[0] for r in rows) + assert {r[2] for r in log} <= {"genesis", "store", "retire", "move", "horizon"} + + +def _lexical_overlay(tmp_path: Path, name: str, root: Path, repo: Path) -> Path: + """A named instance declared as `config/instances/code.toml` declares the code instance, under + another id and root, reading the fixture's repository: no embedder, the repository landed + lexically.""" + import json + import tomllib + + declared = tomllib.loads( + (Path(loader.REPO_ROOT) / "config" / "instances" / "code.toml").read_text()) + lines = ["[instance]", f'id = "{name}"', f'root = "{root}"', ""] + for section, values in declared.items(): + if section == "instance": + continue + for title, table in ([(f"{section}.{k}", v) for k, v in values.items()] + if section == "ingestion" else [(section, values)]): + lines.append(f"[{title}]") + lines += [f"{k} = {json.dumps(v)}" for k, v in table.items() if k != "repositories"] + lines.append("") + lines += ["[[ingestion.code.repositories]]", f'name = "{REPO}"', f'path = "{repo}"', + 'ref = "main"', ""] + overlay = tmp_path / f"{name}.toml" + overlay.write_text("\n".join(lines)) + return overlay + + +def _log_values(cfg: Any) -> list[bytes]: + """What of the landing log no cache may hold: each chain's secret half and key check, each + row's key of its path, commitment and hash, and the suite's secret, as hex and as bytes.""" + from tests.conftest import LANDING_LOG_TEST_KEY + + con = sqlite3.connect(f"file:{cfg.paths.vault_catalog}?mode=ro", uri=True) + try: + out = [bytes(v) for row in con.execute("SELECT secret, key_check FROM landing_chains") + for v in row] + out += [bytes(v) for row in con.execute( + "SELECT path_key, commitment, hash FROM landings") for v in row if v is not None] + finally: + con.close() + return [*out, LANDING_LOG_TEST_KEY.encode(), bytes.fromhex(LANDING_LOG_TEST_KEY)] + + +def _cache_holds_nothing_of(cache_root: Path, values: list[bytes]) -> None: + """No file of the cache holds one of `values`, and no SQLite file of it holds a table of the + catalog's file: the map or the landing log.""" + files = [p for p in cache_root.rglob("*") if p.is_file()] + assert files + for p in files: + data = p.read_bytes() + assert not any(v in data for v in values), p + if data.startswith(b"SQLite format 3"): + con = sqlite3.connect(f"file:{p}?immutable=1", uri=True) + try: + tables = {str(r[0]) for r in con.execute( + "SELECT name FROM sqlite_master WHERE type = 'table'")} + finally: + con.close() + assert not tables & {"vault_files", "landing_chains", "landings"}, p + + +def test_p17_a_named_instance_resets_with_its_own_item_and_destroys_with_none( + tmp_path: Path, repo: Path, home: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """Under a named instance, loaded as a process loads it (`MIND_PALACE_OVERLAY`), the landing + log's secret is the instance's own item, `.landing-log-key`. A reset of a catalog with a + log needs no secret; one whose first open writes the genesis needs that item, and the default + instance's does not serve. A destroy needs none, leaves nothing of the log in the cache, and + names the item among those it leaves for the owner.""" + from core.stores.landings import LANDING_LOG_KEY + from tests.conftest import LANDING_LOG_TEST_KEY + + root = home / ".mind-palace" / "instances" / "t" + monkeypatch.setenv(loader.OVERLAY_ENV, str(_lexical_overlay(tmp_path, "t", root, repo))) + loader.get_config.cache_clear() + cfg = loader.get_config() + item = cfg.instance.secret(LANDING_LOG_KEY) + assert cfg.instance.named and cfg.instance.root == root and item == "t.landing-log-key" + monkeypatch.setenv(item, LANDING_LOG_TEST_KEY) + cache_root = home / ".mind-palace" / "cache" + Path(cfg.paths.data_dir).mkdir(parents=True) + lau = Launcher(cfg=cfg, runs=RunLedger(Path(cfg.paths.data_dir) / "runs.sqlite"), + repo_root=repo, cache_root=cache_root, + launchd_label=cfg.instance.label("palace"), + installed_plist=tmp_path / "no-agent.plist") + assert lau.repo_sync_now() == 0 + log = landing_log(cfg) + assert log["rows"] and chains_verify(cfg) + # a catalog with its log: no step appends to it, so the reset needs no secret at all + monkeypatch.delenv(item) + monkeypatch.delenv(LANDING_LOG_KEY) + assert lau.reset(confirm=True) == 0 + assert landing_log(cfg) == log + # a catalog without a log: the reset's first open writes the genesis, keyed by the item + without_log(cfg) + monkeypatch.setenv(LANDING_LOG_KEY, LANDING_LOG_TEST_KEY) # the default's, not t's + before = dump(cfg) + assert lau.reset(confirm=True) == 1 + assert repr(item) in capsys.readouterr().out + assert dump(cfg) == before + monkeypatch.setenv(item, LANDING_LOG_TEST_KEY) + assert lau.reset(confirm=True) == 0 + assert chains_verify(cfg) + values = _log_values(cfg) + # a destroy reads the catalog read only and removes it whole: no secret, the dry run included + monkeypatch.delenv(item) + monkeypatch.delenv(LANDING_LOG_KEY) + capsys.readouterr() + assert lau.destroy(confirm=False) == 0 + assert item in capsys.readouterr().out # left for the owner, and named + assert lau.destroy(confirm=True) == 0 + assert not root.exists() + _cache_holds_nothing_of(cache_root, values) + + +# ── P9: an interrupted reset finishes ─────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("step", sorted(rebuild.STEPS)) +def test_p9_a_reset_interrupted_at_any_step_leaves_the_marker_and_finishes( + palace: Built, step: str, monkeypatch: pytest.MonkeyPatch) -> None: + b = palace + before, log = heads(b.cfg), landing_log(b.cfg) + lau, _ = launcher_for(b) + + def boom(_ctx: Any) -> str: + raise RuntimeError(f"injected at {step}") + + monkeypatch.setitem(rebuild.STEPS, step, boom) + if step not in {s.name for s in rebuild.found(b.cfg)}: + pytest.skip(f"the fixture has no {step}") + with pytest.raises(RuntimeError, match="injected"): + lau.reset(confirm=True) + assert (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + assert lau.start(max_ticks=1) == 1 # the daemon refuses + assert lau.repo_sync_now() == 1 # and a writer refuses + monkeypatch.undo() + assert lau.reset(confirm=True) == 0 + assert not (Path(b.cfg.paths.data_dir) / "reset.pending").exists() + assert heads(b.cfg) == before and landing_log(b.cfg) == log + + +def _interrupt_at_the_plane(lau: Launcher, monkeypatch: pytest.MonkeyPatch) -> None: + def boom(_ctx: Any) -> str: + raise RuntimeError("injected at the plane step") + + monkeypatch.setitem(rebuild.STEPS, "vectors.lance", boom) + with pytest.raises(RuntimeError, match="injected"): + lau.reset(confirm=True) + monkeypatch.undo() + + +def test_p9_a_purge_while_a_reset_is_pending_leaves_it_to_finish( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """The marker names the versions the plane held. A purge between the interrupted run and the + rerun (the core's `purge_raw`; `scripts/purge_raw.py` itself refuses while the marker stands) + erases one of them: the rerun skips it and says so, as the chat log's replay skips a purged + transcript, and finishes, the erasure standing.""" + from core.ingest.derive import drain + from core.ingest.purge import purge_raw + + cfg = instance_config(tmp_path / "lazy", None, lazy=True) + stores = stores_for(cfg, CountingEmbedder()) + for i in range(3): + (Path(cfg.ingestion.vault.path) / f"n{i}.md").write_text(f"note {i}, embedded later\n") + perform(cfg, stores, "do sync_vault") + drain(stores, max_items=1) + held_path, old = next((r[0], r[1]) for rows in heads(cfg)["plane.occupancies"].values() + for r in rows) + (Path(cfg.ingestion.vault.path) / held_path).write_text("note edited, embedded later\n") + perform(cfg, stores, "do sync_vault") # the plane holds the old version + lau = Launcher(cfg=cfg, runs=LazyRunLedger(tmp_path / "runs.sqlite"), repo_root=tmp_path, + embedder_factory=lambda _c: CountingEmbedder(), + cache_root=tmp_path / "cache", installed_plist=tmp_path / "no.plist") + _interrupt_at_the_plane(lau, monkeypatch) + purge_raw(old, raw=stores.raw, store=stores.plane, catalog=stores.catalog, confirm=True) + assert not stores.raw.exists(old) + capsys.readouterr() + assert lau.reset(confirm=True) == 0 + assert "1 held version(s) whose raw object a purge erased skipped" in capsys.readouterr().out + assert not (Path(cfg.paths.data_dir) / "reset.pending").exists() + assert not any(heads(cfg)["plane.occupancies"].values()) # the erasure stands + + +def test_p9_a_changed_embedder_while_a_reset_is_pending_names_the_way_out( + palace: Built, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """`reembed` refuses while a reset is pending and names the reset; the reset refuses a changed + embedder. So the reset's refusal names the one way out: finish the reset under the embedder the + plane was built with, then change the embedder.""" + lau, _ = launcher_for(palace) + _interrupt_at_the_plane(lau, monkeypatch) + capsys.readouterr() + lau.cfg = replace(palace.cfg, embedding=replace(palace.cfg.embedding, model="another-model")) + assert lau.reset(confirm=True) == 1 + out = capsys.readouterr().out + assert "a reset of this instance is pending" in out and "restore that embedder" in out + assert lau.reembed_now(confirm=True) == 1 + assert "`palace reset --confirm` again" in capsys.readouterr().out + lau.cfg = palace.cfg # restored: the reset finishes + assert lau.reset(confirm=True) == 0 + assert not (Path(palace.cfg.paths.data_dir) / "reset.pending").exists() + + +# ── the scripts that write refuse while a reset is pending ────────────────────────────────── + +#: Each script that lands into an instance or writes a store the reset rebuilds, with the +#: arguments of its writing run. A script that calls one of `WRITER_CALLS` must be here. +WRITER_SCRIPTS: tuple[tuple[str, list[str] | None], ...] = ( + ("purge_raw", ["0" * 64, "--confirm"]), ("ingest_self_knowledge", None), + ("mint_ids", ["--confirm"]), ("migrate_chunk_keys", ["--apply"]), + ("migrate_provenance_split", ["--apply"]), ("reembed_bodyonly", ["--confirm"]), + ("watch", None), ("corpus", ["embed"]), ("ingest", None), + ("ingest_founding", ["founding.json"]), ("snapshot_code", None), ("sense_self", None), + ("verdict", ["submit", "{}"]), ("review", []), ("talk", [])) + +#: The calls by which a script lands into an instance or writes a store the reset rebuilds: the +#: ingress and its stores, the vault's, the founding set's and the curated set's landings, a +#: purge, the drains, the sensors and projectors of the derived stores, the verdict receiver, +#: and the conversation runtime, which lands what the inbox kept when no daemon is live. +WRITER_CALLS = frozenset({ + "run_library", "build_stores", "run_ingest", "build_and_ingest_founding", + "build_and_ingest_curated", "purge_raw", "build_vault_sync", "build_code_corpus_sync", + "drain", "derive_lexical", "dialogue_sync", "build_code_sensor", "build_self_sensor", + "build_chat_sensor", "build_chat_event_projector", "build_integrator", + "build_relation_detector", "build_verdict_receiver", "build_conversation_runtime"}) + +#: The builders some scripts reach once past the marker, each replaced in the test below by one +#: that fails it at once: a script that does not refuse would otherwise go on to write, and the +#: sensors would sync the whole history of the repository the test runs in. +PAST_THE_MARKER = ("ops.code_sensor.build_code_sensor", "ops.self_sensor.build_self_sensor", + "core.ingest.founding.build_and_ingest_founding", + "core.verdict.apply.build_verdict_receiver", + "scheduler.interface.build_conversation_runtime") + + +@pytest.mark.parametrize(("script", "argv"), WRITER_SCRIPTS, ids=[s for s, _ in WRITER_SCRIPTS]) +def test_p9_every_writing_script_refuses_while_a_reset_is_pending( + script: str, argv: list[str] | None, tmp_path: Path, repo: Path, home: Path, + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """LCF-5: the marker refuses every writer, the scripts as the launcher's verbs, and each + refuses before it opens anything, so the instance holds nothing but the marker after it.""" + import argparse + import importlib + + def past(*_a: Any, **_kw: Any) -> Any: + raise AssertionError(f"{script} went past a pending reset's marker") + + root = home / ".mind-palace" / "instances" / "t" + monkeypatch.setenv(loader.OVERLAY_ENV, str(_lexical_overlay(tmp_path, "t", root, repo))) + loader.get_config.cache_clear() + cfg = loader.get_config() + Path(cfg.paths.data_dir).mkdir(parents=True) + (Path(cfg.paths.data_dir) / "reset.pending").write_text('{"stores": []}') + module = importlib.import_module(f"scripts.{script}") + monkeypatch.setattr(module, "seal", lambda: None, raising=False) # process-wide otherwise + for target in PAST_THE_MARKER: + monkeypatch.setattr(target, past) + monkeypatch.setattr(module, target.rsplit(".", 1)[1], past, raising=False) + if script == "corpus": + monkeypatch.setattr(module, "corpus_config", lambda: cfg) + with pytest.raises(SystemExit) as refused: + module.cmd_embed(argparse.Namespace()) + out = str(refused.value.code) + else: + assert (module.main() if argv is None else module.main(argv)) == 1 + out = capsys.readouterr().out + assert "a reset of this instance is pending" in out + assert sorted(str(p.relative_to(root)) for p in root.rglob("*")) == \ + ["data", "data/reset.pending"] + + +def test_p9_every_script_that_calls_a_writer_is_run_under_the_marker() -> None: + """LCF-5, kept whole: every script under scripts/ that calls one of `WRITER_CALLS` is in + `WRITER_SCRIPTS`, so the test above runs it while the marker stands and sees it refuse before + it opens anything. A new script that lands or writes a derived store fails here until it reads + the marker and is listed.""" + import ast + + calling: set[str] = set() + for path in sorted((Path(loader.REPO_ROOT) / "scripts").glob("*.py")): + called = set() + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if isinstance(node, ast.Call): + f = node.func + called.add(f.id if isinstance(f, ast.Name) else getattr(f, "attr", "")) + if called & WRITER_CALLS: + calling.add(path.stem) + listed = {s for s, _ in WRITER_SCRIPTS} + assert {"ingest_founding", "snapshot_code", "sense_self", "verdict", "talk"} <= calling + assert calling <= listed, sorted(calling - listed) + + +@pytest.mark.parametrize("module", ["plane_migrate", "float16_migrate"]) +def test_p9_the_plane_migrations_refuse_to_swap_while_a_reset_is_pending( + module: str, palace: Built, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """The two migrations of the plane's store run for the default instance only (DI-2) and swap + the store a reset's plane step rebuilds: while the marker stands each refuses before it builds + anything; its dry run, which builds beside the store and swaps nothing, still runs.""" + import importlib + from types import SimpleNamespace + + mod = importlib.import_module(f"ops.{module}") + calls: list[bool] = [] + + def migrate(_path: Path, *, dry_run: bool, **_kw: Any) -> Any: + calls.append(dry_run) + return SimpleNamespace(verified=True) + + monkeypatch.setattr(mod, "migrate", migrate) # nothing is built, swapped or archived + monkeypatch.setattr("core.kernel.config.get_config", lambda: palace.cfg) + (Path(palace.cfg.paths.data_dir) / "reset.pending").write_text('{"stores": []}') + assert mod.main(["--store", "vectors"]) == 1 + assert "a reset of this instance is pending" in capsys.readouterr().out + assert calls == [] + assert mod.main(["--store", "vectors", "--dry-run"]) == 0 + assert calls == [True] + + +# ── the chat sensor's retention ledger ────────────────────────────────────────────────────── + + +def test_the_retention_ledger_seeds_from_a_chat_log_that_predates_it(palace: Built) -> None: + """An instance whose chat log was written before the ledger existed: the ledger is seeded + from the chat log, and its replay gives back the same chat log.""" + data = Path(palace.cfg.paths.data_dir) + before = heads(palace.cfg)["chatlog.sqlite"] + (data / "chat_retention.sqlite").unlink() + lau, _ = launcher_for(palace) + assert lau.reset(confirm=True) == 0 + assert heads(palace.cfg)["chatlog.sqlite"] == before + + +# ── P10: a sync heals a stale lexical index ───────────────────────────────────────────────── + + +def test_p10_repo_sync_lands_where_a_stale_index_refused(tmp_path: Path) -> None: + """The 2026-11-11 state: the code instance's index made by the legacy tokenizer, so every + repository sync stopped at `LexicalStore.land_many` (`TokenizerMismatch`). The sync now + re-derives the index in the writer before it lands.""" + from core.ingest import ingress + from core.ingest.lexical import LEGACY, Tokenizer, TokenizerMismatch + from core.stores.lexical import LexicalStore, lexical_path + + repo = make_repo(tmp_path / "repo") + cfg = instance_config(tmp_path / "lite", repo, embedding=False) + stores = ingress.build_stores(cfg) + stores.lexical = LexicalStore(lexical_path(cfg), tokenizer=LEGACY) + assert ingress.run_library(cfg, "sync_repository", {"name": REPO}, stores=stores, + refresh=False)["effects"] == {"landed": 3} + (repo / "pkg" / "late.py").write_text("def late():\n return 'landed after the change'\n") + commit(repo, "three") + current = LexicalStore(lexical_path(cfg), tokenizer=Tokenizer()) + assert current.stale + with pytest.raises(TokenizerMismatch): # the stuck state, reproduced + current.land(source_path="x", digest="d", provenance="code", title="x", chunks=()) + lau = Launcher(cfg=cfg, runs=RunLedger(tmp_path / "runs.sqlite"), repo_root=repo) + log = landing_log(cfg) + assert lau.repo_sync_now() == 0 + healed = LexicalStore(lexical_path(cfg)) + assert not healed.stale and healed.recorded_tokenizer() == Tokenizer().identity + paths = {p for p, _ in healed.landed_versions()} + assert f"code/{REPO}/pkg/late.py" in paths and len(paths) == 4 + # the heal re-derived every item's units and appended nothing: the one new row of the log is + # the new file's landing + assert [(r[2], r[4]) for r in appended(log, landing_log(cfg))] == \ + [("store", f"code/{REPO}/pkg/late.py")] + + +def test_p10_the_writer_heals_a_stale_index_for_a_vault_plan(tmp_path: Path) -> None: + from core.ingest.lexical import LEGACY, Tokenizer + from core.stores.lexical import LexicalStore, lexical_path + + cfg = instance_config(tmp_path / "v", None, lazy=True) + emb = CountingEmbedder() + stores = stores_for(cfg, emb, lexical=LexicalStore(lexical_path(cfg), tokenizer=LEGACY)) + (Path(cfg.ingestion.vault.path) / "one.md").write_text("one note\n") + assert perform(cfg, stores, "do sync_vault")["effects"] == {"landed": 1} + (Path(cfg.ingestion.vault.path) / "two.md").write_text("a second note\n") + stores.lexical = LexicalStore(lexical_path(cfg), tokenizer=Tokenizer()) + assert stores.lexical.stale + log = landing_log(cfg) + receipt = perform(cfg, stores, "do sync_vault") + assert receipt["effects"].get("landed") == 1 and "rederive" in receipt["timing"] + assert not stores.lexical.stale and len(stores.lexical.landed_versions()) == 2 + new = appended(log, landing_log(cfg)) # the landing's row, none of the heal's + assert len(new) == 1 and new[0][2] == "store" and str(new[0][4]).endswith("two.md") + + +# ── P11, P12: destroy ─────────────────────────────────────────────────────────────────────── + + +@pytest.fixture +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + h = tmp_path / "home" + h.mkdir() + monkeypatch.setenv("HOME", str(h)) + return h + + +@pytest.fixture +def named(tmp_path: Path, repo: Path, home: Path) -> Built: + return build_palace(home / ".mind-palace" / "instances" / "t", repo, named="t") + + +def test_p11_destroy_refuses_the_default_instance(palace: Built) -> None: + lau, _ = launcher_for(palace) + _unchanged(palace, lambda: lau.destroy(confirm=True)) + + +def test_p11_destroy_refuses_a_live_run_and_the_lock_held(named: Built, home: Path) -> None: + lau, _ = launcher_for(named, cache=home / ".mind-palace" / "cache") + lock = SupervisorLock(Path(named.cfg.paths.data_dir) / "supervisor.lock") + lock.acquire() + try: + _unchanged(named, lambda: lau.destroy(confirm=True)) + finally: + lock.release() + holder = _live_elsewhere(named) # the run held by another ledger, as by the daemon + try: + for confirm in (True, False): + _refuses_while_live(named, holder, lambda lau, c=confirm: lau.destroy(confirm=c), + cache=home / ".mind-palace" / "cache") + finally: + holder.close() + assert not (home / ".mind-palace" / "cache").exists() + + +def test_p11_destroy_refuses_a_pending_reset( + named: Built, home: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """A reset interrupted after its clearing leaves the plane without the occupancies a fill + selects vectors by, so a destroy then would keep none of the instance's vectors. While the + marker stands a destroy refuses, its dry run too, and writes nothing; once the reset has + finished, the fill selects every vector again and the destroy proceeds.""" + from core.stores.cache import Cache + from ops.lifecycle import destroy as d + + cache_root = home / ".mind-palace" / "cache" + lau, _ = launcher_for(named, cache=cache_root) + atoms = d.plan_fill(named.cfg, Cache(cache_root)).atoms + assert atoms + + def boom(_ctx: Any) -> str: + raise RuntimeError("injected at the plane step") + + with monkeypatch.context() as m: # the fixture's HOME stays patched + m.setitem(rebuild.STEPS, "vectors.lance", boom) + with pytest.raises(RuntimeError, match="injected"): + lau.reset(confirm=True) + assert (Path(named.cfg.paths.data_dir) / "reset.pending").exists() + assert d.plan_fill(named.cfg, Cache(cache_root)).atoms == [] # what a fill would keep now + capsys.readouterr() + for confirm in (False, True): + _unchanged(named, lambda c=confirm: lau.destroy(confirm=c)) + assert "a reset of this instance is pending" in capsys.readouterr().out + assert named.root.exists() and not cache_root.exists() + assert lau.reset(confirm=True) == 0 + assert d.plan_fill(named.cfg, Cache(cache_root)).atoms == atoms + assert lau.destroy(confirm=False) == 0 + + +def test_p11_destroy_refuses_a_root_that_holds_the_cache_or_links_out( + named: Built, home: Path, tmp_path: Path) -> None: + lau, _ = launcher_for(named, cache=named.root / "cache") + _unchanged(named, lambda: lau.destroy(confirm=True)) # the root holds it + outside = tmp_path / "outside" + outside.mkdir() + (outside / "keep.txt").write_text("not the instance's") + (named.root / "link").symlink_to(outside) + lau, _ = launcher_for(named, cache=home / ".mind-palace" / "cache") + _unchanged(named, lambda: lau.destroy(confirm=True)) # a link out of the root + assert (outside / "keep.txt").exists() + + +def test_p11_destroy_refuses_a_root_in_a_working_tree_or_the_home_root( + tmp_path: Path, repo: Path, home: Path) -> None: + tree = tmp_path / "tree" + tree.mkdir() + (tree / ".git").mkdir() + b = build_palace(tree / "inst", repo, named="w") + lau, _ = launcher_for(b, cache=home / ".mind-palace" / "cache") + _unchanged(b, lambda: lau.destroy(confirm=True)) + from core.stores.cache import Cache + from ops.lifecycle import destroy as d + + at_home = replace(b.cfg, instance=loader.InstanceConfig("h", home=home / ".mind-palace")) + assert any("home root" in w for w in d.refusals( + at_home, Cache(tmp_path / "elsewhere"), installed=False, home=home / ".mind-palace")) + + +def test_p11_destroy_refuses_an_installed_agent(named: Built, home: Path) -> None: + lau, _ = launcher_for(named, cache=home / ".mind-palace" / "cache") + lau.installed_plist.write_text("") + _unchanged(named, lambda: lau.destroy(confirm=True)) + + +def _files(root: Path) -> dict[str, tuple[int, int, bool]]: + """Every entry under `root`, directories included: its size, its mtime and whether it is a + directory, so a dry run that creates, removes or touches anything is seen.""" + out: dict[str, tuple[int, int, bool]] = {} + for p in [root, *sorted(root.rglob("*"))]: + st = p.lstat() + out[str(p.relative_to(root))] = (st.st_size if p.is_file() else 0, st.st_mtime_ns, + p.is_dir()) + return out + + +def test_p11_the_destroy_dry_run_writes_nothing( + named: Built, home: Path, capsys: pytest.CaptureFixture[str]) -> None: + """On an instance at rest: its stores closed, so no SQLite file has a `-wal` or `-shm` beside + it, and a reader that opened one `mode=ro` would create them; the run ledger is read only. The + dry run names the sources it leaves and those it removes with the root.""" + from tests.fixtures.lifecycle import close_stores + + lau, _ = launcher_for(named, cache=home / ".mind-palace" / "cache") + before = dump(named.cfg) + close_stores(named) + before_files = _files(home) + assert [f for f in before_files if f.endswith(("-wal", "-shm"))] == [] + assert lau.destroy(confirm=False) == 0 + # the tree first: a read of a WAL database (the dump's own) creates its -wal and -shm + assert _files(home) == before_files # no file added, removed or touched + assert dump(named.cfg) == before and not (home / ".mind-palace" / "cache").exists() + assert not (Path(named.cfg.paths.data_dir) / "supervisor.lock").exists() + out = capsys.readouterr().out + left = [line for line in out.splitlines() if line.strip().startswith("left:")] + assert len(left) == 1 + for kept in (named.cfg.ingestion.vault.path, named.cfg.ingestion.transcripts.transcripts_dir, + named.repo): + assert str(kept) in left[0] + assert str(named.cfg.ingestion.corpus.root) not in left[0] # inside the root: removed + assert f"sources inside the root, removed with it: {named.cfg.ingestion.corpus.root}" in out + + +def _palace(env: dict[str, str], *argv: str) -> Any: + """`scripts/palace.py` in a process of its own, as a shell runs it.""" + import subprocess + import sys + + return subprocess.run([sys.executable, str(Path(loader.REPO_ROOT) / "scripts" / "palace.py"), + *argv], capture_output=True, text=True, timeout=300, env=env) + + +def test_p11_the_commands_dry_runs_create_and_touch_no_file( + tmp_path: Path, repo: Path, home: Path) -> None: + """`palace destroy`, `palace reset` and `palace cache fill`, each run as a shell runs it under + a named instance's overlay, on an instance at rest whose catalog has an empty `-wal` beside + it, as a `mode=ro` reader leaves it with a `-shm` (the corpus's catalog has both): no file + under the home is created, removed or touched, the launcher's run ledger included. On a root + that does not exist, none of the three creates it.""" + from tests.conftest import LANDING_LOG_TEST_KEY + + root = home / ".mind-palace" / "instances" / "t" + env = {**os.environ, "HOME": str(home), + loader.OVERLAY_ENV: str(_lexical_overlay(tmp_path, "t", root, repo))} + landed = _palace({**env, "t.landing-log-key": LANDING_LOG_TEST_KEY}, "repo-sync") + assert landed.returncode == 0, landed.stdout + landed.stderr + for db in root.rglob("*.sqlite"): # at rest: each database checkpointed and closed + con = sqlite3.connect(db) + con.execute("PRAGMA wal_checkpoint(TRUNCATE)") + con.close() + catalog = root / "data" / "vault_catalog.sqlite" + con = sqlite3.connect(f"file:{catalog}?mode=ro", uri=True) # it leaves an empty -wal, a -shm + con.execute("SELECT count(*) FROM vault_files").fetchone() + con.close() + wal = Path(f"{catalog}-wal") + if not wal.exists(): # a platform whose reader leaves none: one left by hand + wal.write_bytes(b"") + assert wal.stat().st_size == 0 + before = _files(home) + for argv in (["destroy"], ["reset"], ["cache", "fill"]): + done = _palace(env, *argv) + assert done.returncode == 0 and "DRY RUN" in done.stdout, (argv, done.stdout, done.stderr) + assert _files(home) == before, argv + absent = home / ".mind-palace" / "instances" / "u" + env[loader.OVERLAY_ENV] = str(_lexical_overlay(tmp_path, "u", absent, repo)) + for argv in (["destroy"], ["reset"], ["cache", "fill"]): + done = _palace(env, *argv) + assert done.returncode == 0 and "DRY RUN" in done.stdout, (argv, done.stdout, done.stderr) + assert not absent.exists(), argv + assert argv != ["destroy"] or "it does not exist" in done.stdout + + +def test_p11_destroy_refuses_a_root_that_holds_a_checkout_or_foreign_files( + tmp_path: Path, repo: Path, home: Path) -> None: + """A root may hold only the instance's own state: a git repository below it, or a file no + namespace of the instance names, refuses, and nothing under the root is removed.""" + from tests.fixtures.lifecycle import git + + b = build_palace(home / "work", repo, named="w") + lau, _ = launcher_for(b, cache=home / ".mind-palace" / "cache") + (b.root / "notes-of-mine.txt").write_text("not the instance's") + _unchanged(b, lambda: lau.destroy(confirm=True)) + (b.root / "notes-of-mine.txt").unlink() + project = b.root / "data" / "logs" / "someproject" + project.mkdir(parents=True) + git(project, "init", "-q") + _unchanged(b, lambda: lau.destroy(confirm=True)) + assert (project / ".git").exists() + import shutil + + shutil.rmtree(project) + assert lau.destroy(confirm=False) == 0 # its own state alone: a dry run proceeds + + +def test_p11_destroy_refuses_a_root_around_another_instance( + tmp_path: Path, repo: Path, home: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A root that holds other instances' roots, whether they are declared on the host or are + only directories it does not own, refuses.""" + from core.stores.cache import Cache + from ops.lifecycle import destroy as d + + b = build_palace(home / ".mind-palace" / "instances" / "t", repo, named="t") + around = instance_config(home / ".mind-palace" / "instances", None, named="u", + sources=tmp_path / "u-read") + why = d.refusals(around, Cache(home / ".mind-palace" / "cache"), installed=False) + assert any("not the instance's own state" in w and "t/" in w for w in why), why + monkeypatch.setattr(d, "other_roots", lambda cfg: [ + ("'corpus'", home / ".mind-palace" / "instances" / "corpus", True)]) + why = d.refusals(around, Cache(home / ".mind-palace" / "cache"), installed=False) + assert any("'corpus'" in w for w in why), why + assert d.refusals(b.cfg, Cache(home / ".mind-palace" / "cache"), installed=False) == [] + + +def test_p11_destroy_and_fill_refuse_a_changed_embedder_geometry( + named: Built, home: Path) -> None: + """After a change of model in the overlay and before a re-embed, the plane holds the old + model's vectors: filing them under the new model's key would mix two geometries.""" + from core.stores.cache import Cache + from core.stores.plane import GeometryMismatch + from ops.lifecycle import destroy as d + + cache_root = home / ".mind-palace" / "cache" + lau, _ = launcher_for(named, cache=cache_root) + lau.cfg = replace(named.cfg, embedding=replace(named.cfg.embedding, model="another-model")) + _unchanged(named, lambda: lau.destroy(confirm=True)) + _unchanged(named, lambda: lau.destroy(confirm=False)) + _unchanged(named, lambda: lau.cache_fill(confirm=True)) + with pytest.raises(GeometryMismatch): + d.plan_fill(lau.cfg, Cache(cache_root)) + assert not cache_root.exists() + + +def _catalog(b: Built) -> list[tuple[str, str, str]]: + con = sqlite3.connect(f"file:{b.cfg.paths.vault_catalog}?mode=ro", uri=True) + try: + return [(str(p), str(d), str(c)) for p, d, c in con.execute( + "SELECT source_path, digest, provenance FROM vault_files")] + finally: + con.close() + + +def _occupancies(b: Built) -> list[tuple[str, str]]: + from core.stores.plane import OCC + + con = sqlite3.connect(f"file:{Path(b.cfg.paths.vector_store) / 'plane.sqlite'}?mode=ro", + uri=True) + try: + return [(str(p), str(a)) for t in OCC.values() + for p, a in con.execute(f"SELECT source_path, atom_id FROM {t}")] + finally: + con.close() + + +def _land_by_hand(b: Built, rows: list[tuple[str, Any, bytes]]) -> dict[str, str]: + """Raw objects and catalog rows the fixture's lanes do not write: {path: digest}.""" + out: dict[str, str] = {} + for path, provenance, text in rows: + digest, _ = b.stores.raw.add(text) + b.stores.catalog.record(path, digest, path, provenance=provenance) + out[path] = digest + return out + + +def test_p12_destroy_keeps_exactly_the_cache_classes(named: Built, home: Path) -> None: + """The expectations are written from the fixture's own lanes, by path and class, not by the + selection the code makes: the corpus stream's items, the repository's files and one curated + item enter; the notes, a dialogue turn, a model's reply in the dialogue, an inbox item and the + transcripts do not.""" + from core.kernel.provenance import Provenance + from core.stores.cache import Cache, key_of + from ops.lifecycle import destroy as d + + b = named + private_rows = _land_by_hand(b, [ + ("dialogue/openwebui/c1/m1", Provenance.AUTHORED_DIALOGUE, b"a dialogue turn, private"), + ("dialogue/openwebui/c1/m2", Provenance.OBSERVED, b"the model's reply, private"), + ("dialogue/inbox/c/1/owner", Provenance.AUTHORED_DIALOGUE, b"an inbox item, private")]) + curated = _land_by_hand(b, [("curated/ref-1", Provenance.CURATED, b"a curated reference")]) + catalog, occ = _catalog(b), _occupancies(b) + notes = {d_ for p, d_, c in catalog if c == Provenance.AUTHORED_SOLO.value} + corpus = {d_ for p, d_, c in catalog if p.startswith(f"corpus/{CORPUS_SOURCE}/") + and c == Provenance.OBSERVED.value} + code = {d_ for p, d_, c in catalog if p.startswith(f"code/{REPO}/")} + assert notes and corpus and code + retained = sqlite3.connect(Path(b.cfg.paths.data_dir) / "chat_retention.sqlite") + transcripts = {str(r[0]) for r in retained.execute("SELECT digest FROM retained")} + retained.close() + stream = b.cfg.ingestion.corpus.root / CORPUS_SOURCE + downloaded = set(d._source_files(stream)) + assert any(f.startswith("stream/") and f != "stream/manifest.json" for f in downloaded) + cache_root = home / ".mind-palace" / "cache" + log_values = _log_values(b.cfg) + lau, _ = launcher_for(b, cache=cache_root) + assert lau.destroy(confirm=True) == 0 + assert not b.root.exists() # the catalog's file with it, the landing log in it + _cache_holds_nothing_of(cache_root, log_values) + cache = Cache(cache_root) + assert cache.raw_digests() == corpus | code | set(curated.values()) + assert not cache.raw_digests() & (notes | set(private_rows.values()) | transcripts) + open_paths = {p for p, _, _ in catalog + if p.startswith((f"corpus/{CORPUS_SOURCE}/", f"code/{REPO}/"))} + want = {a for p, a in occ if p in open_paths} + only_private = {a for p, a in occ if p not in open_paths} - want + key = key_of(b.cfg)[0] + assert cache.vector_ids(key) == want and want + assert not cache.vector_ids(key) & only_private + assert {m["file"] for m in cache.source_manifest(CORPUS_SOURCE)} == downloaded + assert not any("cursor" in m["file"] or "state" in m["file"] + for m in cache.source_manifest(CORPUS_SOURCE)) + assert not stream.exists() + + +def test_p12_a_source_file_that_is_a_link_enters_no_cache( + named: Built, home: Path, tmp_path: Path) -> None: + """The fill takes a source's stream files by name, so a name that is a link would carry other + bytes in: a symbolic link to the catalog's file inside the root, a hard link to it, or a link + to a note outside the root. A destroy and a fill refuse each, writing nothing, and the cache + itself refuses to store one.""" + import json + import os + + from core.stores.cache import Cache + + b = named + base = Path(b.cfg.ingestion.corpus.root) / CORPUS_SOURCE + manifest = json.loads((base / "stream" / "manifest.json").read_text()) + part = base / "stream" / str(manifest["parts"][0]["file"]) + original = part.read_bytes() + catalog = Path(b.cfg.paths.vault_catalog) + note = Path(b.cfg.ingestion.vault.path) / "alpha.md" + cache_root = home / ".mind-palace" / "cache" + lau, _ = launcher_for(b, cache=cache_root) + for make in (lambda: part.symlink_to(catalog), lambda: os.link(catalog, part), + lambda: part.symlink_to(note)): + part.unlink() + make() + _unchanged(b, lambda: lau.destroy(confirm=True)) + _unchanged(b, lambda: lau.destroy(confirm=False)) + _unchanged(b, lambda: lau.cache_fill(confirm=True)) + assert not cache_root.exists() and b.root.exists() + with pytest.raises(ValueError, match="not a plain file"): + Cache(tmp_path / "direct").put_source_files(CORPUS_SOURCE, base, + [str(part.relative_to(base))]) + assert not (tmp_path / "direct").exists() + part.unlink() + part.write_bytes(original) + assert lau.destroy(confirm=False) == 0 # a plain stream again: it proceeds + + +def test_p12_a_stream_reached_out_of_its_source_enters_no_cache( + named: Built, home: Path, tmp_path: Path) -> None: + """A file reached through a directory link that stays inside the root, or through a manifest + part that climbs out of the stream, is a regular file with one link, and destroy's scan + follows no link out of the root: what refuses it is that it resolves out of its source + (`plain_file`). The stream directory linked to the data directory, whose manifest names the + catalog's file: a fill refuses, writing nothing, and the cache's writer refuses the file. A + part of the real manifest that climbs to the catalog's file: a fill and a destroy refuse + before writing anything.""" + import json + import os + + from core.stores.cache import Cache + from ops.lifecycle import destroy as d + + b = named + base = Path(b.cfg.ingestion.corpus.root) / CORPUS_SOURCE + stream, aside = base / "stream", base / "stream.aside" + catalog = Path(b.cfg.paths.vault_catalog) + data = Path(b.cfg.paths.data_dir) + cache_root = home / ".mind-palace" / "cache" + lau, _ = launcher_for(b, cache=cache_root) + stream.rename(aside) + stream.symlink_to(data, target_is_directory=True) + (data / "manifest.json").write_text(json.dumps({"parts": [{"file": catalog.name}]})) + assert stream / catalog.name in d.linked_source_files(b.cfg) + assert d.link_out(b.root) is None # the link stays inside the root + _unchanged(b, lambda: lau.cache_fill(confirm=True)) + _unchanged(b, lambda: lau.cache_fill(confirm=False)) + _unchanged(b, lambda: lau.destroy(confirm=True)) + with pytest.raises(ValueError, match="not a plain file"): + Cache(tmp_path / "direct").put_source_files(CORPUS_SOURCE, base, + [f"stream/{catalog.name}"]) + assert not (tmp_path / "direct").exists() and not cache_root.exists() + stream.unlink() + aside.rename(stream) + (data / "manifest.json").unlink() + manifest_path = stream / "manifest.json" + original = manifest_path.read_text() + manifest = json.loads(original) + manifest["parts"].append({"file": os.path.relpath(catalog, stream)}) + manifest_path.write_text(json.dumps(manifest)) + assert [p.resolve() for p in d.linked_source_files(b.cfg)] == [catalog.resolve()] + for act in (lambda: lau.cache_fill(confirm=True), lambda: lau.destroy(confirm=True), + lambda: lau.destroy(confirm=False)): + _unchanged(b, act) + assert not cache_root.exists() and b.root.exists() + manifest_path.write_text(original) + assert lau.destroy(confirm=False) == 0 # its own stream again: it proceeds + + +def test_a_fill_streams_its_vectors_in_batches( + palace: Built, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The plan counts the atoms and holds no vector; the fill reads them a batch at a time.""" + from core.stores.cache import Cache, key_of + from ops.lifecycle import destroy as d + + monkeypatch.setattr(d, "FILL_BATCH", 2) + cache = Cache(tmp_path / "cache") + plan = d.plan_fill(palace.cfg, cache) + assert len(plan.atoms) > 2 and not hasattr(plan, "vectors") + report = d.fill(palace.cfg, cache, plan) + assert report.vectors == len(plan.atoms) + assert cache.vector_ids(key_of(palace.cfg)[0]) == set(plan.atoms) + + +def test_the_cache_records_its_uses_to_the_day(tmp_path: Path) -> None: + import hashlib + + from core.stores.cache import Cache + + cache = Cache(tmp_path / "cache") + data = b"an open object" + cache.put_raw(hashlib.sha256(data).hexdigest(), data) + cache.forget("0" * 64, []) + for name, table in (("uses.sqlite", "SELECT last FROM uses"), + ("purged.sqlite", "SELECT at FROM purged")): + con = sqlite3.connect(tmp_path / "cache" / name) + times = [float(r[0]) for r in con.execute(table)] + con.close() + assert times and all(t % 86400 == 0 for t in times), name + + +# ── P13, P14: reuse ───────────────────────────────────────────────────────────────────────── + + +def _filled_cache(b: Built, root: Path) -> Any: + from core.stores.cache import Cache + from ops.lifecycle import destroy as d + + cache = Cache(root) + d.fill(b.cfg, cache, d.plan_fill(b.cfg, cache)) + return cache + + +def test_p13_a_cached_vector_is_reused_without_the_embedder( + palace: Built, tmp_path: Path) -> None: + from core.ingest.derive import drain + from core.stores.cache import key_of, with_cache + from tests.fixtures.lifecycle import fill_stream + + cache = _filled_cache(palace, tmp_path / "cache") + key = key_of(palace.cfg)[0] + for model, calls in ((None, 0), ("another-model", None)): + cfg = instance_config(tmp_path / f"new-{model}", None, lazy=True, model=model) + emb = CountingEmbedder() + stores = with_cache(stores_for(cfg, emb), cfg, cache) + fill_stream(cfg) + perform(cfg, stores, f'do sync_corpus(name: "{CORPUS_SOURCE}", batch: 10)', + role="corpus", batch=True) + report = drain(stores) + if calls == 0: + assert emb.calls == 0 and report.cached > 0 and report.embedded == 0 + atoms = sorted(cache.vector_ids(key)) + mine = stores.plane.plane.atoms.payload(atoms) + assert {a: list(v) for a, (_t, v) in mine.items()} == cache.vectors(key, atoms) + else: + assert emb.calls > 0 and report.cached == 0 + + +def test_p13_a_cached_vector_of_another_width_is_not_landed(tmp_path: Path) -> None: + """A cache entry under the instance's key whose width is not the plane's is never landed + (§10 item 7): the drain embeds the atom instead.""" + from core.ingest.derive import drain + from core.kernel.ingest.pipeline import derive_chunks + from core.stores.cache import Cache, key_of, with_cache + from core.stores.plane import atom_id + from tests.fixtures.embedding import DIM + from tests.fixtures.lifecycle import fill_stream + + cfg = instance_config(tmp_path / "w", None, lazy=True) + cache = Cache(tmp_path / "cache") + emb = CountingEmbedder() + stores = with_cache(stores_for(cfg, emb), cfg, cache) + fill_stream(cfg) + perform(cfg, stores, f'do sync_corpus(name: "{CORPUS_SOURCE}", batch: 10)', role="corpus", + batch=True) + atoms = {atom_id(c.text) for e in stores.catalog.active_entries() + for c in derive_chunks(stores.raw.get(e.digest))} + key, fields = key_of(cfg) + assert cache.put_vectors(key, fields, {a: [0.5] * (DIM + 1) for a in atoms}) == len(atoms) + report = drain(stores) + assert report.cached == 0 and emb.calls > 0 + held = stores.plane.plane.atoms.payload(sorted(atoms)) + assert held and all(len(v) == DIM for _t, v in held.values()) + + +def test_p13_the_vector_key_names_the_backend() -> None: + """Two instances that differ only in the backend serving the embedder share no vectors.""" + from core.kernel.config import get_config + from core.stores.cache import key_of + + base = get_config() + other = replace(base, runtime=replace(base.runtime, embedding_backend=( + "ollama" if base.runtime.embedding_backend != "ollama" else "llamacpp"))) + assert key_of(base)[0] != key_of(other)[0] + assert key_of(base)[1]["backend"] != key_of(other)[1]["backend"] + + +def test_p14_a_raw_object_is_taken_by_digest_and_checked(tmp_path: Path) -> None: + import hashlib + + from core.kernel.stores.rawstore import RawStore + from core.stores.cache import Cache + + cache = Cache(tmp_path / "cache") + data = b"open bytes, addressed by their hash" + digest = hashlib.sha256(data).hexdigest() + assert cache.put_raw(digest, data) + raw = RawStore(tmp_path / "raw", fallback=cache.raw) + assert raw.get(digest) == data and raw.exists(digest) # copied in on a miss + other = b"another object" + d2 = hashlib.sha256(other).hexdigest() + assert cache.put_raw(d2, other) + (tmp_path / "cache" / "raw" / d2[:2] / d2).write_bytes(b"tampered") + with pytest.raises(FileNotFoundError): + RawStore(tmp_path / "raw2", fallback=cache.raw).get(d2) + assert not cache.has_raw(d2) # refused and removed + + +# ── P15: a purge reaches the cache ────────────────────────────────────────────────────────── + + +def test_p15_a_purge_reaches_the_cache_and_no_fill_puts_it_back( + palace: Built, tmp_path: Path, repo: Path) -> None: + from core.ingest.purge import purge_raw + from core.kernel.ingest.pipeline import derive_chunks + from core.stores.cache import key_of, vector_key + from core.stores.plane import atom_id + from ops.lifecycle import destroy as d + + b = palace + cache = _filled_cache(b, tmp_path / "cache") + path = f"corpus/{CORPUS_SOURCE}/a-0" + entry = b.stores.catalog.get(path) + assert entry is not None and cache.has_raw(entry.digest) + atoms = {atom_id(c.text) for c in derive_chunks(b.stores.raw.get(entry.digest))} + key = key_of(b.cfg)[0] + assert atoms & cache.vector_ids(key) + # the same atoms under a second embedder's key: a purge reaches every key + other_key, other_fields = vector_key("another-model", "t", 3, "another-backend") + assert cache.put_vectors(other_key, other_fields, {a: [0.1, 0.2, 0.3] for a in atoms}) + b.stores.catalog.tombstone(path) + result = purge_raw(entry.digest, raw=b.stores.raw, store=b.stores.plane, + catalog=b.stores.catalog, confirm=True, cache=cache) + assert result.cache_raw_removed and result.cache_vectors_removed > len(atoms) + assert not cache.has_raw(entry.digest) and not atoms & cache.vector_ids(key) + assert not atoms & cache.vector_ids(other_key) + assert entry.digest in cache.purged() + other = build_palace(tmp_path / "other", repo) # an instance still holding it + assert other.stores.catalog.get(path) is not None + d.fill(other.cfg, cache, d.plan_fill(other.cfg, cache)) + assert not cache.has_raw(entry.digest) + assert not atoms & cache.vector_ids(key) - _shared_atoms(other, path) + + +def _shared_atoms(b: Built, purged_path: str) -> set[str]: + """Atoms of the purged item another open item of `b` also holds: those may stay.""" + occ = _occupancies(b) + return {a for p, a in occ if p != purged_path and p.startswith("corpus/")} + + +def test_a_cached_source_is_taken_only_inside_its_directories(tmp_path: Path) -> None: + """Every instance of the user can write the cache, so a manifest row that names a path out of + the source's directory, or an absolute one, is refused: nothing is read or written for it.""" + import json + + from core.stores.cache import Cache + + cache = Cache(tmp_path / "cache") + base = tmp_path / "src" + (base / "stream").mkdir(parents=True) + (base / "stream" / "manifest.json").write_text("{}") + assert cache.put_source_files("alpha", base, ["stream/manifest.json"]) == 1 + with pytest.raises(ValueError): + cache.put_source_files("alpha", base, ["../outside"]) + secret = tmp_path / "secret.txt" + secret.write_text("outside the cache") + manifest = tmp_path / "cache" / "sources" / "alpha" / "MANIFEST" + rows = json.loads(manifest.read_text()) + import hashlib + + sha = hashlib.sha256(secret.read_bytes()).hexdigest() + rows += [{"file": "../../../secret.txt", "size": secret.stat().st_size, "sha256": sha}, + {"file": str(secret), "size": secret.stat().st_size, "sha256": sha}] + manifest.write_text(json.dumps(rows)) + dest = tmp_path / "dest" / "alpha" + assert cache.take_source("alpha", dest) == 1 + assert sorted(str(p.relative_to(tmp_path / "dest")) for p in (tmp_path / "dest").rglob("*") + if p.is_file()) == ["alpha/stream/manifest.json"] + assert secret.read_text() == "outside the cache" + + +def test_the_cache_prunes_what_was_not_taken_for_the_retention(tmp_path: Path) -> None: + import hashlib + import time + + from core.stores.cache import RETENTION_DAYS, Cache + + cache = Cache(tmp_path / "cache") + data = b"old" + digest = hashlib.sha256(data).hexdigest() + cache.put_raw(digest, data) + later = time.time() + (RETENTION_DAYS + 1) * 86400 + assert cache.stale(now=later)["raw"] == [digest] + assert cache.stale()["raw"] == [] + assert cache.prune(now=later) == 1 and not cache.has_raw(digest) + + +# ── P16: the corpus at its own root ───────────────────────────────────────────────────────── + + +def test_p16_the_corpus_overlay_resolves_to_its_own_root( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setattr(loader, "_CONFIG_DIR", tmp_path) + monkeypatch.setattr(loader, "_INSTANCE_OVERLAY", tmp_path / "ouroboros.toml") + monkeypatch.setattr(loader, "_LEGACY_OVERLAY", tmp_path / "local.toml") + monkeypatch.setattr(loader, "LEVERS_OVERLAY", tmp_path / "levers.toml") + monkeypatch.setenv(loader.OVERLAY_ENV, + str(loader.REPO_ROOT / "config" / "instances" / "corpus.toml")) + cfg = loader.load_config() + root = home / ".mind-palace" / "instances" / "corpus" + assert cfg.instance.id == "corpus" and cfg.instance.root == root + assert cfg.paths.data_dir == root / "data" + assert cfg.ingestion.corpus.root == root / "sources" + for p in loader.namespaces_of(cfg).paths: + assert str(p).startswith(str(root)), p diff --git a/tests/integration/test_lifecycle.py b/tests/integration/test_lifecycle.py index 1eaecf59..8dc9493d 100644 --- a/tests/integration/test_lifecycle.py +++ b/tests/integration/test_lifecycle.py @@ -2,8 +2,8 @@ Exercises the whole lifecycle without any live daemon or model: the run ledger's clean/unclean detection (the basis for recovery), preflight's fail-closed aggregation, the launcher's graceful -start→serve→mark-clean, recovery on an unclean prior run, and that `reset` wipes the corpus but -NEVER the production Vault Raft store. +start→serve→mark-clean, recovery on an unclean prior run, and that `reset` clears the derived +stores and never a ledger or the production Vault Raft store. """ import dataclasses @@ -266,34 +266,38 @@ def test_force_resumes_normally_after_unclean(tmp_path): assert not _last(launcher.runs).recovery -# --- reset (the fresh-start wipe) --------------------------------------------------------------- -def test_reset_wipes_corpus_but_never_the_vault_raft(tmp_path): +# --- reset (clear the derived stores, rebuild them; dn-instance-lifecycle) --------------------- +def test_reset_keeps_raw_the_ledgers_and_the_vault_raft(tmp_path): + """A reset clears derived stores only: the raw store, the catalog, the version chains, the + declarations, the reference edges and the production Vault Raft store are never touched + (the reset at main deleted all but the last).""" + from core.stores.chat_events import ChatEventStore + cfg = _cfg(tmp_path) - # seed the corpus layer + a production Vault Raft store that MUST survive (cfg.paths.raw_store).mkdir(parents=True) (cfg.paths.raw_store / "blob").write_text("x") cfg.paths.vault_catalog.write_text("catalog") - # the four sibling provenance stores (opened via derived_store.parent, no cfg path) - sidecars = ["versions.sqlite", "authored_supersessions.sqlite", - "verdicts.sqlite", "verdict_dispositions.sqlite", - "code_observations.sqlite", # observed stratum: a reset target (bp-012 Item 4) - "reference_edges.sqlite"] # Lane-1 doc↔code refs: reset target (bp-013 Q4) - for name in sidecars: + kept = ["versions.sqlite", "authored_supersessions.sqlite", "verdicts.sqlite", + "reference_edges.sqlite", "code_snapshots.sqlite", "observation_history.sqlite"] + for name in kept: (cfg.paths.data_dir / name).write_text("rows") (cfg.paths.data_dir / "vault").mkdir() (cfg.paths.data_dir / "vault" / "raft.db").write_text("VAULT RAFT — DO NOT DELETE") + ChatEventStore(cfg.paths.data_dir / "chat_events.sqlite").close() # a derived store runs = RunLedger(tmp_path / "runs.sqlite") - launcher = Launcher(cfg=cfg, runs=runs, repo_root=Path(".").resolve()) + launcher = Launcher(cfg=cfg, runs=runs, repo_root=tmp_path) - assert launcher.reset(confirm=False) == 0 # dry-run removes nothing - assert cfg.paths.raw_store.exists() - assert all((cfg.paths.data_dir / n).exists() for n in sidecars) + assert launcher.reset(confirm=False) == 0 # dry run writes nothing + assert (cfg.paths.data_dir / "chat_events.sqlite").exists() + assert not (cfg.paths.data_dir / "reset.pending").exists() assert launcher.reset(confirm=True) == 0 - assert not cfg.paths.raw_store.exists() # corpus wiped - assert not cfg.paths.vault_catalog.exists() - assert not any((cfg.paths.data_dir / n).exists() for n in sidecars) # provenance sidecars wiped + assert (cfg.paths.raw_store / "blob").read_text() == "x" + assert cfg.paths.vault_catalog.read_text() == "catalog" + assert all((cfg.paths.data_dir / n).read_text() == "rows" for n in kept) assert (cfg.paths.data_dir / "vault" / "raft.db").exists() # Vault Raft UNTOUCHED + assert not (cfg.paths.data_dir / "chat_events.sqlite").exists() # cleared; no chat log + assert not (cfg.paths.data_dir / "reset.pending").exists() def test_reset_refused_while_a_run_is_live(tmp_path): diff --git a/tests/unit/test_chat_sync.py b/tests/unit/test_chat_sync.py index 9ad1edbc..bff69f8d 100644 --- a/tests/unit/test_chat_sync.py +++ b/tests/unit/test_chat_sync.py @@ -10,6 +10,7 @@ from __future__ import annotations +import dataclasses import json from pathlib import Path from typing import Any, cast @@ -97,10 +98,21 @@ def test_secret_bearing_session_is_refused_whole(tmp_path: Path) -> None: # --- the REUSED builder is the wiring path (no duplicate — finding-0108 G1) --------------------- -def test_build_chat_sensor_is_reused_from_ops_and_wires_the_handles() -> None: - sensor = build_chat_sensor(get_config()) +def test_build_chat_sensor_is_reused_from_ops_and_wires_the_handles(tmp_path: Path) -> None: + """The default configuration with its data under `tmp_path`: the builder opens the chat log, + the retention ledger, which it seeds from the chat log once, and the raw store, so on the + checkout's own data directory it would write them there, and the deploy gate runs this tier in + the checkout of the running instance.""" + base = get_config() + data = tmp_path / "data" + cfg = dataclasses.replace(base, paths=dataclasses.replace(base.paths, data_dir=data, + raw_store=data / "raw")) + sensor = build_chat_sensor(cfg) assert isinstance(sensor, ChatSensor) # transcripts dir is config-derived (REPO_ROOT slug under ~/.claude/projects), not hard-coded assert "/.claude/projects/" in str(sensor.transcripts_dir) assert isinstance(sensor.guard, ChatSecretGuard) assert sensor.active_session_id is None # the daemon is not a live CLI session (Q2) + assert sensor.retention is not None + for opened in (sensor.store.path, sensor.retention.path, sensor.rawstore.root): + assert data in Path(opened).parents, opened # nothing of the checkout's diff --git a/tests/unit/test_code_sensor.py b/tests/unit/test_code_sensor.py index 69e82f21..a74948eb 100644 --- a/tests/unit/test_code_sensor.py +++ b/tests/unit/test_code_sensor.py @@ -152,31 +152,11 @@ def test_version_bump_makes_backfill_reproject_and_archive(repo, tmp_path, monke def test_reset_wipes_readings_but_refuses_the_worldview_history(tmp_path): - """Pins §6(f): `reset_targets()` still lists the readings store (corpus-side, wiped, - rebuilt by re-projection) and the history sidecar is NOT a target — it sits in - `_RESET_GUARD`, where the launcher's target assertion refuses it outright.""" - from typing import cast - - from config.loader import Config - from ops.lifecycle.launcher import _RESET_GUARD, Launcher - from ops.lifecycle.runs import RunLedger - - class _Paths: - def __init__(self, d: Path) -> None: - self.data_dir = d - self.raw_store = d / "raw.sqlite" - self.vector_store = d / "vectors.lance" - self.vault_catalog = d / "vault_catalog.sqlite" - self.derived_store = d / "derived.sqlite" - self.attestation_store = d / "attestations.sqlite" - - class _Cfg: - def __init__(self, d: Path) -> None: - self.paths = _Paths(d) - - launcher = Launcher(cfg=cast(Config, _Cfg(tmp_path / "data")), - runs=cast(RunLedger, None), repo_root=tmp_path) - names = {t.name for t in launcher.reset_targets()} - assert "code_observations.sqlite" in names # readings: corpus-side, wiped - assert "observation_history.sqlite" not in names # the worldview ledger is NOT a target… - assert "observation_history.sqlite" in _RESET_GUARD # …and the guard refuses it structurally + """Pins §6(f), now in the class table (dn-instance-lifecycle §3): the readings store is a + derived store a reset clears and rebuilds by re-projection, and the history sidecar is a + ledger it keeps.""" + from ops.lifecycle.inventory import STORES, Kind + + kind = {s.name: s.kind for s in STORES} + assert kind["code_observations.sqlite"] is Kind.DERIVED # readings: rebuilt + assert kind["observation_history.sqlite"] is Kind.LEDGER # the worldview ledger: kept diff --git a/tests/unit/test_llamacpp_cutover.py b/tests/unit/test_llamacpp_cutover.py index 4907d858..6d676486 100644 --- a/tests/unit/test_llamacpp_cutover.py +++ b/tests/unit/test_llamacpp_cutover.py @@ -122,25 +122,10 @@ def test_dreaming_is_scheduled_by_default_and_the_lever_parses(): assert load_config().dreaming.scheduled is True -def test_reset_targets_include_the_membership_store(tmp_path: Path): - """bp-152's relation points into the vector plane; a reset that kept it would leave - occupancies of atoms that no longer exist.""" - from ops.lifecycle.launcher import Launcher - from ops.lifecycle.runs import RunLedger - - class _Paths: - def __init__(self, d: Path) -> None: - self.data_dir = d - self.raw_store = d / "raw" - self.vector_store = d / "vectors.lance" - self.vault_catalog = d / "vault_catalog.sqlite" - self.derived_store = d / "derived.sqlite" - self.attestation_store = d / "attestations.sqlite" - - class _Cfg: - def __init__(self, d: Path) -> None: - self.paths = _Paths(d) - - launcher = Launcher(cfg=cast(Config, _Cfg(tmp_path / "data")), - runs=cast(RunLedger, None), repo_root=tmp_path) - assert "memberships.sqlite" in {t.name for t in launcher.reset_targets()} +def test_reset_keeps_the_membership_store(tmp_path: Path): + """bp-152's relation holds the code atoms' embedder ledger beside their occupancy, so a reset + keeps it whole (dn-instance-lifecycle §3): clearing it would forget which code atoms the + plane holds under which embedder, and `palace code-rebuild` is what derives it again.""" + from ops.lifecycle.inventory import STORES, Kind + + assert {s.name: s.kind for s in STORES}["memberships.sqlite"] is Kind.KEPT diff --git a/tests/unit/test_self_sensor.py b/tests/unit/test_self_sensor.py index 751681c7..c9b368d0 100644 --- a/tests/unit/test_self_sensor.py +++ b/tests/unit/test_self_sensor.py @@ -7,8 +7,9 @@ all unchanged) — and the sensor reads ONLY `git` subprocess output + config paths, never the working tree, never transcripts (§2.6's statelessness). -Also covers Item 8's wiring surface (`scripts/sense_self.py`, the hook line, the -`reset_targets()` entry): those tests live here per the plan's file list (§7 Item 8). +Also covers Item 8's wiring surface (`scripts/sense_self.py`, the hook line, and the +store's class in `ops/lifecycle/inventory.py`): those tests live here per the plan's file list +(§7 Item 8). """ from __future__ import annotations @@ -395,40 +396,18 @@ def test_post_commit_hook_contains_both_sensor_lines_and_the_branch_guard() -> N assert guard_idx < code_idx and guard_idx < self_idx # the guard is upstream of both -def test_reset_targets_lists_agent_observations_but_refuses_the_history_sidecar( +def test_the_class_table_rebuilds_agent_observations_and_keeps_the_history_sidecar( tmp_path: Path, ) -> None: - """Pins §6(h): `reset_targets()` lists the readings store (corpus-side, wiped, rebuilt - by re-projection) and the shared history sidecar is NOT a target — it sits in - `_RESET_GUARD` (the code-store precedent, `test_code_sensor.py`'s equivalent test, - extended to the agent member). A reset that omitted this store would let readings - survive a corpus wipe — the falsifier named in the plan (§2.5 violated in the - corpus-class direction).""" - from typing import cast - - from config.loader import Config - from ops.lifecycle.launcher import _RESET_GUARD, Launcher - from ops.lifecycle.runs import RunLedger - - class _Paths: - def __init__(self, d: Path) -> None: - self.data_dir = d - self.raw_store = d / "raw.sqlite" - self.vector_store = d / "vectors.lance" - self.vault_catalog = d / "vault_catalog.sqlite" - self.derived_store = d / "derived.sqlite" - self.attestation_store = d / "attestations.sqlite" - - class _Cfg: - def __init__(self, d: Path) -> None: - self.paths = _Paths(d) - - launcher = Launcher(cfg=cast(Config, _Cfg(tmp_path / "data")), - runs=cast(RunLedger, None), repo_root=tmp_path) - names = {t.name for t in launcher.reset_targets()} - assert "agent_observations.sqlite" in names # readings: corpus-side, wiped - assert "observation_history.sqlite" not in names # the shared worldview ledger is NOT… - assert "observation_history.sqlite" in _RESET_GUARD # …and the guard refuses it structurally + """Pins §6(h), now in the class table (dn-instance-lifecycle §3): the readings store is a + derived store a reset clears and rebuilds by re-projection, and the shared history sidecar is + a ledger it keeps. A reset that kept the readings would let them survive a rebuild: the + falsifier named in the plan (§2.5 violated in the corpus-class direction).""" + from ops.lifecycle.inventory import STORES, Kind + + kind = {s.name: s.kind for s in STORES} + assert kind["agent_observations.sqlite"] is Kind.DERIVED # readings: rebuilt + assert kind["observation_history.sqlite"] is Kind.LEDGER # the worldview ledger: kept def test_non_main_branch_commit_projects_nothing_via_the_hook_guard() -> None: