Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
1021ff7
docs(design): the instance's lifecycle, a reset that rebuilds and a d…
ascalva Nov 12, 2026
379daec
feat(chat): a retention ledger, so the chat log is rebuilt from raw
ascalva Nov 12, 2026
38fe541
fix(ingest): every landing re-derives a stale lexical index first
ascalva Nov 12, 2026
d6ffc9e
feat(stores): a shared cache of open content, read back by digest and…
ascalva Nov 12, 2026
0ddf8a3
feat(lifecycle): a reset that rebuilds the derived stores, and a dest…
ascalva Nov 12, 2026
6b73e1e
feat(corpus): the corpus instance declares its own root
ascalva Nov 12, 2026
6b62a88
test(lifecycle): reset, destroy, the cache and the stale-index heal o…
ascalva Nov 12, 2026
e5c28c5
docs(runbook): the instance's lifecycle, reset, destroy and the share…
ascalva Nov 12, 2026
8223715
docs(papers): reset, destroy and a shared cache, the article
ascalva Nov 12, 2026
c19f273
docs(design): the instance's lifecycle as built
ascalva Nov 12, 2026
7bef2e1
docs(readme): the tests badge and count, 3,754
ascalva Nov 12, 2026
521ccbd
fix(lifecycle): a reset that always finishes and gives the plane back…
ascalva Nov 12, 2026
399598e
fix(lifecycle): destroy removes only the instance's own state, and a …
ascalva Nov 12, 2026
6e3169c
docs(stores): the store docstrings name the class table, not the remo…
ascalva Nov 12, 2026
885a788
docs(design): the lifecycle note as repaired, and the runbook to match
ascalva Nov 12, 2026
7767db6
docs(papers): the lifecycle article as repaired
ascalva Nov 12, 2026
5f9b52b
test(lifecycle): a named embedder factory in the lazy-backlog test, f…
ascalva Nov 12, 2026
0d0e088
docs(readme): the tests badge and count, 3,766
ascalva Nov 12, 2026
91b3b8b
fix(lifecycle): the plane step rebuilds each held version, head or not
ascalva Nov 12, 2026
7209df1
docs(lifecycle): a held version is rebuilt at its digest; the backend…
ascalva Nov 12, 2026
06e3618
fix(lifecycle): a reset keeps the landing log and refuses a genesis i…
ascalva Nov 14, 2026
926a75b
docs(lifecycle): the note and the runbook with the landing log in the…
ascalva Nov 14, 2026
0a145c3
docs(papers): the lifecycle article with the landing log in the base
ascalva Nov 14, 2026
6aabbdb
test(lifecycle): the dry run at rest closes the fixture's stores by hand
ascalva Nov 14, 2026
c96112d
docs(readme): the tests badge and count, 3,769
ascalva Nov 14, 2026
e1b052a
fix(lifecycle): what the audit of the rebase found in reset, destroy …
ascalva Nov 14, 2026
9b50b32
docs(lifecycle): the package describes reset and destroy as built, an…
ascalva Nov 14, 2026
5d64f8f
docs(lifecycle): the note and the runbook after the audit of the rebase
ascalva Nov 14, 2026
fd452bc
docs(papers): the lifecycle article after the audit of the rebase
ascalva Nov 14, 2026
503d05f
test(lifecycle): the commands' dry-run test leaves its empty -wal by …
ascalva Nov 14, 2026
ee13895
docs(lifecycle): the purges a rebuild comes back without, and the cor…
ascalva Nov 14, 2026
1d1314c
docs(readme): the tests badge and count, 3,783
ascalva Nov 14, 2026
6cfaa08
fix(lifecycle): every script that lands or writes a derived store rea…
ascalva Nov 14, 2026
31b0ce7
fix(lifecycle): destroy refuses while a reset of the instance is pending
ascalva Nov 14, 2026
a8c025d
test(lifecycle): a live run read from the file, and a stream reached …
ascalva Nov 14, 2026
29ac302
test(chat): the builder's wiring test opens its stores under a tempor…
ascalva Nov 14, 2026
933d6ee
docs(lifecycle): the note and the runbook after the second audit of t…
ascalva Nov 14, 2026
11408e1
docs(papers): the lifecycle article after the second audit of the rebase
ascalva Nov 14, 2026
35f4ac9
docs(readme): the tests badge and count, 3,795
ascalva Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion bin/mind-palace
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ mind-palace <verb> [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 <code.py|-> [--input NAME=PATH] [--timeout N] run code in the powerless sandbox
Expand Down Expand Up @@ -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" "$@" ;;
Expand Down
6 changes: 4 additions & 2 deletions config/defaults.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,10 @@ overlap_chars = 150
# ingress's table, a stream of items its edge reader (`edge/corpus/`) writes under `root/<name>/`
# and `sync_corpus.palace` lands a batch at a time, observed, at `corpus/<name>/<id>`. 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 = []
Expand Down
13 changes: 10 additions & 3 deletions config/instances/corpus.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<root>/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/`)
Expand All @@ -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).
Expand Down
41 changes: 28 additions & 13 deletions core/ingest/derive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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 ───────────────────────────────────────────────────────────
Expand Down
22 changes: 21 additions & 1 deletion core/ingest/purge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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(
Expand All @@ -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:
Expand All @@ -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)
25 changes: 24 additions & 1 deletion core/ingest/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
13 changes: 12 additions & 1 deletion core/kernel/stores/rawstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,18 @@
from __future__ import annotations

import hashlib
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path


@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)
Expand All @@ -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()
Expand Down
Loading
Loading