diff --git a/.githooks/post-commit b/.githooks/post-commit index cc0879c6..7b649580 100755 --- a/.githooks/post-commit +++ b/.githooks/post-commit @@ -14,4 +14,8 @@ cd "$(git rev-parse --show-toplevel)" || exit 0 if command -v uv >/dev/null 2>&1; then RUN="uv run"; else RUN="./.venv/bin/python"; fi $RUN scripts/snapshot_code.py 2>&1 || echo "code-sensor sync failed (non-blocking; next sync heals)" $RUN scripts/sense_self.py 2>&1 || echo "self-sensor sync failed (non-blocking; next sync heals)" +# The code instance (dn-palace-lite), when it has landed once: as .githooks/post-merge keeps it. +[ -f config/instances/code.toml ] && { MIND_PALACE_OVERLAY=config/instances/code.toml \ + $RUN scripts/palace.py repo-sync --if-landed 2>&1 \ + || echo "code instance sync failed (non-blocking; next sync heals)"; } exit 0 diff --git a/.githooks/post-merge b/.githooks/post-merge new file mode 100755 index 00000000..c748147b --- /dev/null +++ b/.githooks/post-merge @@ -0,0 +1,17 @@ +#!/bin/sh +# A pull or merge that moves main keeps the code instance current (docs/design-notes/ +# dn-palace-lite.md): its repositories' files land by the writer, a changed file a new version, a +# file gone retired, no vector computed. NEVER blocks the merge: a failed sync prints a warning and +# exits 0; the sync is idempotent catch-up, so the next one (any merge or commit on main, or +# `palace repo-sync` by hand) heals the gap. Only an instance already landed once is kept current +# here (`--if-landed`); its first sync is the operator's. +# +# main is the ingestion branch (CONVENTIONS §Commits): exit silently on any other branch or +# detached HEAD. +[ "$(git symbolic-ref --short -q HEAD)" = "main" ] || exit 0 +cd "$(git rev-parse --show-toplevel)" || exit 0 +[ -f config/instances/code.toml ] || exit 0 +if command -v uv >/dev/null 2>&1; then RUN="uv run"; else RUN="./.venv/bin/python"; fi +MIND_PALACE_OVERLAY=config/instances/code.toml $RUN scripts/palace.py repo-sync --if-landed 2>&1 \ + || echo "code instance sync failed (non-blocking; next sync heals)" +exit 0 diff --git a/README.md b/README.md index e023f26f..863c0d21 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-227_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3633-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3651-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) @@ -161,7 +161,7 @@ Utility is a side effect and is treated as one. What the project optimizes for i The base build is complete and the live instance runs always-on under launchd with a gated deployment path. "Complete" is not "wired": this repo distinguishes built, deployed and wired, and its own audit found the summaries were the least honest surface, so this one names the gaps. -Wired and live: ingestion (notes within seconds, code per commit), dreaming on a six-hour cadence, the provenance firewall, the attestation chain, the strict-typed core, CI on every push, deploy-gated releases, the research airlock, the curated literature store, and the query language with its one MCP command, the CLI, the query log as a sensor, and a battery run read-only against the live stores. Built but deliberately dormant, each waiting on its design gate: retrieval demotion for superseded content, the supersession certification layer, effectors (the "hands", flag-off at every tier), recursive dreaming. Open in the language, and stated in every answer: version moves at the note grain are empty (the chains are per note), and there is no snapshot of the notes at a past cut. The causal moves are wired: a transcript turn to the files it produced, and back. So is the ingress: ingestion is written in a generic language, and each path, from the vault sync to a capture, is a script of it (`ingress/`). A surface speaks a request, `do sync_vault` or a script inline, typed under the speaker's grant; the daemon evaluates it under a budget of measured work into a plan and lands the plan as the one writer, under the palace's rules, and the answer is a receipt. The Ambassador's write tools are requests, and its inbox lands the owner's messages through a script of its own, under a role that writes nothing else. Landing is two-phase where an instance asks for it (`[embedding] lazy`): an item lands complete without its vector, with its bytes, label, edges and a lexical index, and the `embed` drain derives the vectors afterwards, idempotently; a query that needs a vector not yet derived reports the item pending instead of guessing (ING-19 to ING-21). The default instance keeps synchronous embedding. Left for later: research, a paper's manifest, and one commit's or one session's backfill as scripts, and the parallel dispatcher, whose laws are proved (DO-6). +Wired and live: ingestion (notes within seconds, code per commit), dreaming on a six-hour cadence, the provenance firewall, the attestation chain, the strict-typed core, CI on every push, deploy-gated releases, the research airlock, the curated literature store, and the query language with its one MCP command, the CLI, the query log as a sensor, and a battery run read-only against the live stores. Built but deliberately dormant, each waiting on its design gate: retrieval demotion for superseded content, the supersession certification layer, effectors (the "hands", flag-off at every tier), recursive dreaming. Open in the language, and stated in every answer: version moves at the note grain are empty (the chains are per note), and there is no snapshot of the notes at a past cut. The causal moves are wired: a transcript turn to the files it produced, and back. So is the ingress: ingestion is written in a generic language, and each path, from the vault sync to a capture, is a script of it (`ingress/`). A surface speaks a request, `do sync_vault` or a script inline, typed under the speaker's grant; the daemon evaluates it under a budget of measured work into a plan and lands the plan as the one writer, under the palace's rules, and the answer is a receipt. The Ambassador's write tools are requests, and its inbox lands the owner's messages through a script of its own, under a role that writes nothing else. Landing is two-phase where an instance asks for it (`[embedding] lazy`): an item lands complete without its vector, with its bytes, label, edges and a lexical index, and the `embed` drain derives the vectors afterwards, idempotently; a query that needs a vector not yet derived reports the item pending instead of guessing (ING-19 to ING-21). The default instance keeps synchronous embedding. An instance may also embed nothing (`[embedding] enabled = false`), and a source may keep no vectors (`[ingestion.code] embed = false`): its items land with their lexical units and no vector, and `near` ranks them by the lexical index and says so. The code instance (`config/instances/code.toml`) lands this repository's files that way, read through git at `main`, for a coding agent to query over MCP. Left for later: research, a paper's manifest, and one commit's or one session's backfill as scripts, and the parallel dispatcher, whose laws are proved (DO-6). The current frontier is the query algebra as the system's interface, the mathematics pushed to where its claims close or break, and the trace as the language's debugger. Behind it, drafted: the palace's memory of itself, the graph as it stood at any past cut, and the conversations that design the system becoming a stratum it can study. @@ -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,633 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,651 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/agents/ambassador/mcp.py b/agents/ambassador/mcp.py index 6465157c..0f56904d 100644 --- a/agents/ambassador/mcp.py +++ b/agents/ambassador/mcp.py @@ -83,13 +83,22 @@ def overview(self) -> dict[str, Any]: } for s in AMBASSADOR.scopes ] - return { + out: dict[str, Any] = { "catalog_by_provenance": dict(catalog), "vector_rows": self.engine._get("vectors").count(), "relation_edges": dict(edges), "versions": self.engine._get("versions").count(), "your_grant": planes, } + if not cfg.embedding.enabled: # the lite profile: say so, and what ranks instead + out["embedding"] = "off: this instance embeds nothing; near ranks by the lexical index" + lexical = self.engine._get("lexical") + if lexical is not None: + out["lexical_units"] = lexical.count() + code = code_sources(cfg) + if code: + out["code"] = code + return out # writes and on-demand work ----------------------------------------------------------------- def _run(self, fn: Callable[[], int]) -> dict[str, Any]: @@ -169,7 +178,9 @@ def status(self) -> dict[str, Any]: "models": { "chat": model_state(cfg.runtime.port_for("routine") or 8080, key=chat_key(policy)), - "embedder": model_state(cfg.runtime.port_for("embedding") or 8081), + # an instance that embeds nothing has no embedder to ask (dn-palace-lite) + "embedder": (model_state(cfg.runtime.port_for("embedding") or 8081) + if cfg.embedding.enabled else "off"), }, "heartbeat": last_tick(cfg.paths.data_dir, interval_s=policy.interval_s), "services": _launch_agents(), @@ -224,6 +235,27 @@ def _ledger(self, op: Callable[[Any], dict[str, Any]]) -> dict[str, Any]: return {**out, "now": now_local().isoformat(timespec="minutes")} +def code_sources(cfg: Any) -> list[dict[str, Any]]: + """Each repository of the lexical code source (dn-palace-lite): the commit whose files it + last landed whole, when, and how many commits its ref has moved past that since, so a reader + knows how current the code stratum is before trusting an answer from it.""" + from core.ingest.readers import read_mark + from core.ingest.repository import behind + from core.ingest.table import repository_mark + from core.kernel.config.loader import lexical_code + + if not lexical_code(cfg): + return [] + out = [] + for repo in cfg.ingestion.code.repositories: + mark = read_mark(repository_mark(cfg, repo.name)) + landed = str(mark["commit"]) if mark else "" + out.append({"repository": repo.name, "ref": repo.ref, "landed": landed[:12] or None, + "at": mark.get("at") if mark else None, + "behind": behind(Path(repo.path), landed, repo.ref) if landed else None}) + return out + + def _launch_agents() -> list[dict[str, str]]: """The stack's LaunchAgents: running (pid) or idle, and the last exit status.""" import subprocess diff --git a/config/instances/code.toml b/config/instances/code.toml new file mode 100644 index 00000000..df5a7ddc --- /dev/null +++ b/config/instances/code.toml @@ -0,0 +1,63 @@ +# The CODE instance: source repositories for a coding agent to query, with no embedder and no +# language model (docs/design-notes/dn-palace-lite.md). +# +# Selected by `MIND_PALACE_OVERLAY=config/instances/code.toml`. A named overlay replaces the whole +# per-machine chain, so nothing of Ouroboros's `ouroboros.toml` or `levers.toml` reaches this +# instance (DI-2). Its state lives under its own root, outside every checkout and worktree, so it +# outlives the one a process happens to run from; it declares no vault, no transcripts and no +# dialogue, so it reads none of the default instance's sources. +# +# The repositories below are read through git's object store at their ref, never their working +# tree. `palace repo-sync` lands each one's files as items of the reference stratum, a changed file +# a new version and a file gone from the ref retired, with their lexical units and no vector; a +# second run after no commit lands nothing. No daemon runs for this instance: it embeds nothing, +# and nothing in it wakes a model. +# +# MIND_PALACE_OVERLAY=config/instances/code.toml uv run scripts/palace.py repo-sync +# MIND_PALACE_OVERLAY=config/instances/code.toml uv run scripts/palace.py query 'near "x" over reference' +# MIND_PALACE_OVERLAY=config/instances/code.toml uv run python scripts/palace_mcp.py + +[instance] +id = "code" +root = "~/.mind-palace/instances/code" + +# No embedder: no plane is opened, no drain runs, and `near` ranks by the lexical index, saying so. +[embedding] +enabled = false + +[dreaming] +scheduled = false # no language model: nothing dreams, relates or curates + +[ingestion.vault] +enabled = false +[ingestion.transcripts] +enabled = false + +[ingestion.code] +enabled = true +embed = false + +# One table per repository; add another to read more. An item is `code//`. +[[ingestion.code.repositories]] +name = "mind-palace" +path = "~/mind-palace" +ref = "main" + +[integrate] +enabled = false + +[backup] +enabled = false + +[secrets] +enabled = false + +[attestation] +enabled = false + +[selfmod] +enabled = false +unattended_enabled = false + +[effectors] +enabled = false diff --git a/core/ingest/derive.py b/core/ingest/derive.py index 659422e2..0e43635b 100644 --- a/core/ingest/derive.py +++ b/core/ingest/derive.py @@ -60,6 +60,11 @@ Provenance.CURATED.value: CURATED_READ, } +# The classes whose items the lexical index holds: the plane's, and the code's, which lands with +# lexical units and no vector (dn-palace-lite), so it is in no plane class and the vector drain +# never sees it. The lexical backfill re-derives all of them after a tokenizer change. +LEXICAL_CLASSES: frozenset[str] = frozenset(HOLDS) | {Provenance.CODE.value} + @dataclass(frozen=True) class DrainReport: @@ -268,10 +273,11 @@ def __str__(self) -> str: def lexical_missing(catalog: Any, lexical: Any, *, classes: Iterable[Provenance] | None = None) -> list[CatalogEntry]: - """The active entries of the plane's classes (of `classes` when given) whose current version - the lexical index has no record of: items landed before the index was opened, by an earlier - writer or while the instance embedded synchronously.""" - wanted = {p.value for p in classes} if classes is not None else set(HOLDS) + """The active entries of the classes the lexical index holds (`LEXICAL_CLASSES`; of `classes` + when given) whose current version the index has no record of: items landed before the index + was opened, by an earlier writer or while the instance embedded synchronously, and every item + after a tokenizer change reset the index, the code's included.""" + wanted = {p.value for p in classes} if classes is not None else set(LEXICAL_CLASSES) have = lexical.landed_versions() return [e for e in catalog.active_entries() if str(e.provenance) in wanted and (e.source_path, e.digest) not in have] diff --git a/core/ingest/embed.py b/core/ingest/embed.py index 1b58a174..ec29ada8 100644 --- a/core/ingest/embed.py +++ b/core/ingest/embed.py @@ -130,6 +130,10 @@ def build_embedder(config: Config | None = None) -> Embedder: from core.models.inference import build_inference_client cfg = config or get_config() + if not cfg.embedding.enabled: # the lite profile: no embedder exists (dn-palace-lite) + from core.stores.noplane import refuse + + raise refuse("building the embedder") # The embedding ROLE picks its own backend (`[runtime] embedding_backend`), independently of # the chat tiers — that is what makes the embedder cutover a real, separately reversible step # (dn-local-model-runtime §2.6 P4). Default is `ollama`, so this returns exactly what it diff --git a/core/ingest/ingress.py b/core/ingest/ingress.py index 8037e74b..8c43b553 100644 --- a/core/ingest/ingress.py +++ b/core/ingest/ingress.py @@ -625,23 +625,35 @@ def prune(cfg: Config, *, now: float | None = None, max_age_s: float = PRUNE_AFT def build_stores(cfg: Config, enqueue: Callable[..., int] | None = None) -> Any: """The stores the writer lands into, opened by the daemon, the one writer. The lexical index - is opened under `[embedding] lazy` alone (dn-two-phase-ingestion D6), so an instance that - embeds synchronously writes nothing it did not write before.""" + is opened when the instance lands lazily, embeds nothing, or has a source that keeps no + vectors (`needs_lexical`; dn-two-phase-ingestion D6, dn-palace-lite), so an instance that + embeds every item synchronously writes nothing it did not write before. An instance that + embeds nothing builds no embedder and opens no plane: the writer is handed `NoPlane`.""" from core.attestation import build_attestor - from core.ingest.embed import build_embedder from core.ingest.writer import Stores + from core.kernel.config.loader import needs_lexical from core.kernel.stores.rawstore import RawStore from core.stores.catalog import VaultCatalog from core.stores.edges import open_edge_store from core.stores.lexical import open_lexical_store - from core.stores.vectorstore import open_vector_store from core.stores.versions import open_version_store - return Stores(raw=RawStore(cfg.paths.raw_store), plane=open_vector_store(cfg), - embedder=build_embedder(cfg), catalog=VaultCatalog(cfg.paths.vault_catalog), + plane: Any = None + embedder: Any = None + if cfg.embedding.enabled: + from core.ingest.embed import build_embedder + from core.stores.vectorstore import open_vector_store + + plane, embedder = open_vector_store(cfg), build_embedder(cfg) + else: + from core.stores.noplane import NoPlane + + plane = NoPlane() + return Stores(raw=RawStore(cfg.paths.raw_store), plane=plane, + embedder=embedder, catalog=VaultCatalog(cfg.paths.vault_catalog), versions=open_version_store(cfg), attestor=build_attestor(cfg), edges=open_edge_store(cfg), enqueue=enqueue, - lexical=open_lexical_store(cfg) if cfg.embedding.lazy else None) + lexical=open_lexical_store(cfg) if needs_lexical(cfg) else None) def reader(cfg: Config, role: str) -> Callable[[str], list[Any]]: @@ -724,7 +736,8 @@ def perform(do: ast.Do, cfg: Config, role: str, *, stores: Any, plan = Evaluator(v, role, meter, library=library or load).run(script, args, kwargs, name=name) reads = frozenset().union(*(classes_of(s.sigma.strata) for s in grant_for(role).scopes)) writer = Writer(table, role, stores, has=v.has, meter=meter, request=request, reads=reads, - batch=batch, lazy=bool(cfg.embedding.lazy) if lazy is None else lazy) + batch=batch, lazy=bool(cfg.embedding.lazy) if lazy is None else lazy, + embedding=bool(cfg.embedding.enabled)) cut_before = getattr(stores.embedder, "cut", None) outcomes = writer.land(plan) if hasattr(v, "landed"): diff --git a/core/ingest/readers.py b/core/ingest/readers.py index e586b83f..b0f0705a 100644 --- a/core/ingest/readers.py +++ b/core/ingest/readers.py @@ -13,7 +13,10 @@ give a label other than the observed one (a dialogue reader's handoff, the inbox's record) is read only as the daemon trusts it (`core/ingest/files.py`), so no other account plants an item its rule would label as the owner's. A records source is a directory of such documents; one the table marks -as consumed loses a document once a plan has landed every item it yields. +as consumed loses a document once a plan has landed every item it yields. A repository source is a +git repository's files at a ref, read as blobs (`core/ingest/repository.py`), each item at the +source's space plus its path in the repository; once a plan has stored every file it listed, the +commit is recorded as landed, the mark its staleness is told by. """ from __future__ import annotations @@ -28,7 +31,7 @@ from pathlib import Path from typing import Any -from core.ingest import stream +from core.ingest import repository, stream from core.ingest.files import check_dir, read_bounded, written_by_one from core.ingest.table import ( MAX_HANDOFF_BYTES, @@ -78,6 +81,38 @@ def __iter__(self) -> Iterator[Record]: return (self._read(p) for p in self._paths) +class RepositoryListing: + """A repository source's files at its ref in path order, listed at once and read a batch of + blobs at a time by one git process each. A script reads a listing more than once (its paths, + then its items), so the records of the first whole pass are kept for the next, and handed to + `done` (the view marks the commit landed once the plan stores every one of them).""" + + BATCH = 256 + + def __init__(self, entries: Sequence[repository.Entry], + read: Callable[[Sequence[repository.Entry]], list[Record]], + done: Callable[[list[Record]], None]) -> None: + self._entries = entries + self._read = read + self._done = done + self._records: list[Record] | None = None + + def __len__(self) -> int: + return len(self._entries) + + def __iter__(self) -> Iterator[Record]: + if self._records is not None: + yield from self._records + return + read: list[Record] = [] + for i in range(0, len(self._entries), self.BATCH): + batch = self._read(self._entries[i:i + self.BATCH]) + read.extend(batch) + yield from batch + self._records = read + self._done(read) + + class PalaceView: """The palace as one evaluation reads it, under one role. `catalog` is the place's index of rows (`VaultCatalog` or a fake); `query` evaluates a read sentence under the role's grant; @@ -100,6 +135,11 @@ def __init__(self, table: Table, role: str, catalog: Any, *, # cursor moves past them once the plan that stores them has landed self._batches: dict[str, tuple[int, list[str]]] = {} self._stream_paths: dict[str, frozenset[str]] = {} + # a repository source's tree as listed: its commit and its files by path in the repository; + # and the items of each whose every file a script read, so the commit is marked once the + # plan has stored them all + self._trees: dict[str, tuple[str, dict[str, repository.Entry]]] = {} + self._listed: dict[str, list[str]] = {} def _listdir(self, d: Path) -> frozenset[str]: """A directory's names, listed once an evaluation.""" @@ -121,12 +161,22 @@ def open(self, name: str) -> Handle: raise ScriptError(f"source({name!r}): no such source") if self.role not in s.readers: raise ScriptError(f"source({name!r}): the role {self.role!r} may not open it") + if s.kind == "repository": + # what a script names it by is its space: `stored(…, under: it)` is its items + return Handle(name, s.space.rstrip("/")) return Handle(name, str(s.location)) - def files(self, h: Handle) -> Listing: + def files(self, h: Handle) -> Listing | RepositoryListing: """The source's items in path order, each read and parsed only when the evaluator asks for the next, so the meter stops a read at the item that ran the budget out.""" s = self._source(h) + if s.kind == "repository": + _, entries = self._tree(s) + + def done(records: list[Record], name: str = s.name) -> None: + self._listed[name] = [str(r["path"]) for r in records] + return RepositoryListing(list(entries.values()), lambda batch: self._blobs(s, batch), + done) if s.kind != "dir": raise ScriptError(f"files({h.name!r}): a directory source; use items(…)") seen: dict[str, Path] = {} @@ -149,6 +199,12 @@ def _named(self, s: Source, path: str) -> Path: def file(self, h: Handle, path: str) -> Record: s = self._source(h) + if s.kind == "repository": + entry = self._tree(s)[1].get(self._relative(s, path)) + if entry is None: + raise ScriptError(f"file({h.name!r}, {path!r}): not a file of the source at " + f"{s.ref}") + return self._blobs(s, [entry])[0] if s.kind != "dir": raise ScriptError(f"file({h.name!r}, …): a directory source") p = self._named(s, path) @@ -159,6 +215,8 @@ def file(self, h: Handle, path: str) -> Record: def exists(self, h: Handle, path: str) -> bool: s = self._source(h) + if s.kind == "repository": + return self._relative(s, path) in self._tree(s)[1] if s.kind == "dir": try: p = self._named(s, path) @@ -178,12 +236,63 @@ def has(self, path: str) -> bool: s = self.table.owner(path) if s is None: return False + if s.kind == "repository": + return self._relative(s, path) in self._tree(s)[1] if s.kind == "dir": return _exists_as(s, path, self._listdir) if s.kind == "stream": return s.owns(path) return any(str(r["path"]) == path for r in self._read_items(s)) + # a repository's files ------------------------------------------------------------------- + + def _tree(self, s: Source) -> tuple[str, dict[str, repository.Entry]]: + """The repository's commit at the source's ref and its files, listed once an evaluation.""" + if s.name not in self._trees: + try: + commit = repository.commit_of(s.location, s.ref) + entries = repository.tree(s.location, commit) + except repository.RepositoryError as err: + raise ScriptError(f"{s.name}: {err}") from None + self._trees[s.name] = (commit, {e.path: e for e in entries}) + return self._trees[s.name] + + @staticmethod + def _relative(s: Source, path: str) -> str: + """A path as the repository names it: an item's path less the source's space.""" + return path.removeprefix(s.space) + + def _blobs(self, s: Source, entries: Sequence[repository.Entry]) -> list[Record]: + """Records of some files of the tree: a blob over the item cap is still an item, one the + writer refuses (R1), read never; a blob that is not text is no item.""" + label = s.label or OBSERVED + small = [e.blob for e in entries if e.size <= MAX_ITEM_BYTES] + try: + data = dict(repository.read_blobs(s.location, small)) + except repository.RepositoryError as err: + raise ScriptError(f"{s.name}: {err}") from None + out = [] + for entry in entries: + path = s.space + entry.path + origin = Origin("item", s.name, path, entry.path) + + def o(v: str, origin: Origin = origin) -> OStr: + return OStr(v, label, origin) + + digest: OStr | None = None + if entry.size > MAX_ITEM_BYTES: + content = Content(b"", label, origin, oversize=entry.size) + else: + blob = data[entry.blob] + if not repository.is_text(blob): + continue + content = Content(blob, label, origin) + digest = o(hashlib.sha256(blob).hexdigest()) + out.append(Record({"path": o(path), "content": content, "digest": digest, + "title": o(entry.path), "properties": Record({}), "tags": [], + "links": []})) + return out + def _markdown(self, s: Source, p: Path) -> Record: label = s.label or OBSERVED size = p.stat().st_size @@ -373,6 +482,12 @@ def landed(self, outcomes: Sequence[Any] = ()) -> None: # a stream's cursor moves past a batch only when the plan stored every item of it if paths and all(p in stored for p in paths): stream.write_cursor(self.table.sources[name].location, last) + for name, items in self._listed.items(): + # a repository's commit is landed once the plan stored every item of its tree + source = self.table.sources[name] + if source.mark is not None and all(p in stored for p in items): + _write_mark(source.mark, {"commit": self._trees[name][0], "ref": source.ref, + "files": len(items)}) for name, files in self._files.items(): if not self.table.sources[name].consume: continue @@ -416,6 +531,27 @@ def _may_author(s: Source) -> bool: return not labels or bool(labels - {OBSERVED}) +def _write_mark(mark: Path, doc: dict[str, Any]) -> None: + """Record what a repository source landed, with the time, atomically.""" + from datetime import UTC, datetime + + mark.parent.mkdir(parents=True, exist_ok=True) + tmp = mark.with_suffix(".tmp") + tmp.write_text(json.dumps({**doc, "at": datetime.now(UTC).isoformat(timespec="seconds")})) + tmp.replace(mark) + + +def read_mark(mark: Path | None) -> dict[str, Any] | None: + """What a repository source last landed, or None when it never landed whole.""" + if mark is None or not mark.is_file(): + return None + try: + doc = json.loads(mark.read_text()) + except (OSError, ValueError): + return None + return doc if isinstance(doc, dict) else None + + def _consume(f: Path, key: tuple[int, int]) -> None: """Remove a landed document, if it is still the file that was read (a rename since replaced it: the new one is pending, and stays).""" diff --git a/core/ingest/repository.py b/core/ingest/repository.py new file mode 100644 index 00000000..06faab21 --- /dev/null +++ b/core/ingest/repository.py @@ -0,0 +1,126 @@ +"""A git repository read as a source: the files of a ref's tree, through git's object store +(dn-palace-lite). + +A repository source's items are the regular files of the tree a ref names, read as blobs, never +through the working tree: so no untracked file, uncommitted edit, data directory or symlink target +beside the repository is ever read, and the files are exactly the commit's whatever the file +system's case rules. Three git commands, each a plumbing read: `rev-parse` resolves the ref to its +commit, `ls-tree` lists the tree, and one `cat-file --batch` process reads the blobs. None of them +touches the network, and git is told so (`GIT_NO_LAZY_FETCH`, `protocol.allow=never`), so a partial +clone's missing blob is an error here, never a fetch. + +The foundation's paths (the constitution, the golden set) are never items, as `read` never opens +them (`core.sentence.types.is_foundation`), nor are the tool directories; a blob holding a NUL byte +is not text and is not an item. +""" + +from __future__ import annotations + +import os +import re +import subprocess +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from pathlib import Path + +from core.sentence.types import is_foundation + +_TOOL_DIRS = (".git/", ".jj/", ".claude/") +_SHA = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}") +_REGULAR = (b"100644", b"100755") + + +class RepositoryError(RuntimeError): + """The repository, its ref or one of its blobs could not be read.""" + + +@dataclass(frozen=True) +class Entry: + """One regular file of a tree: its path in the repository, its blob and the blob's size.""" + + path: str + blob: str + size: int + + +def _env() -> dict[str, str]: + env = dict(os.environ) + env.update({"GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "GIT_OPTIONAL_LOCKS": "0"}) + return env + + +def _git(location: Path, *args: str, stdin: bytes | None = None) -> bytes: + try: + done = subprocess.run(["git", "-c", "protocol.allow=never", "-C", str(location), *args], + input=stdin, capture_output=True, env=_env(), timeout=300) + except (OSError, subprocess.TimeoutExpired) as e: + raise RepositoryError(f"git {args[0]} in {location}: {e}") from None + if done.returncode != 0: + raise RepositoryError(f"git {args[0]} in {location}: " + f"{done.stderr.decode('utf-8', 'replace').strip()[-300:]}") + return done.stdout + + +def commit_of(location: Path, ref: str) -> str: + """The commit a ref names in the repository.""" + if ref.startswith("-"): + raise RepositoryError(f"{ref!r} is not a ref") + return _git(location, "rev-parse", "--verify", "--quiet", "--end-of-options", + f"{ref}^{{commit}}").decode().strip() + + +def itemizable(path: str) -> bool: + """Whether a path of the tree may be an item: not the foundation's, not a tool directory's.""" + folded = path.casefold() + return not is_foundation(path) and not folded.startswith(_TOOL_DIRS) + + +def tree(location: Path, commit: str) -> list[Entry]: + """The regular files of the commit's tree that may be items, in path order: a symlink, a + submodule, the foundation's paths and the tool directories are left out.""" + out = [] + for record in _git(location, "ls-tree", "-r", "-l", "-z", "--full-tree", commit).split(b"\0"): + if not record: + continue + meta, _, name = record.partition(b"\t") + fields = meta.split() + if len(fields) != 4 or fields[1] != b"blob" or fields[0] not in _REGULAR: + continue + path = name.decode("utf-8", "surrogateescape") + if itemizable(path): + out.append(Entry(path, fields[2].decode(), int(fields[3]))) + return sorted(out, key=lambda e: e.path) + + +def read_blobs(location: Path, blobs: Sequence[str]) -> Iterator[tuple[str, bytes]]: + """Each blob's bytes, in the order asked, read by one `cat-file --batch` process.""" + if not blobs: + return + data = _git(location, "cat-file", "--batch", stdin=("\n".join(blobs) + "\n").encode()) + at = 0 + for blob in blobs: + end = data.index(b"\n", at) + header = data[at:end].split() + if len(header) != 3 or header[1] != b"blob": + raise RepositoryError(f"blob {blob} is missing from {location}") + size = int(header[2]) + yield blob, data[end + 1:end + 1 + size] + at = end + 1 + size + 1 # the content, then the batch's own newline + + +def is_text(data: bytes) -> bool: + """Whether a blob is text: it holds no NUL byte.""" + return b"\0" not in data + + +def behind(location: Path, landed: str, ref: str) -> int | None: + """How many commits the ref has that the landed commit has not (None when either is + unknown to the repository, or the landed commit is not a commit's name): how stale a + repository source is.""" + if not _SHA.fullmatch(landed): + return None + try: + out = _git(location, "rev-list", "--count", f"{landed}..{commit_of(location, ref)}") + except RepositoryError: + return None + return int(out.decode().strip() or 0) diff --git a/core/ingest/table.py b/core/ingest/table.py index 8ffaaa8b..7e155f4c 100644 --- a/core/ingest/table.py +++ b/core/ingest/table.py @@ -33,6 +33,7 @@ AUTHORED_DIALOGUE = Provenance.AUTHORED_DIALOGUE.value OBSERVED = Provenance.OBSERVED.value CURATED = Provenance.CURATED.value +CODE_LABEL = Provenance.CODE.value MAX_ITEM_BYTES = 16 << 20 # one item a source yields MAX_HANDOFF_BYTES = 256 << 20 # a structured source's file @@ -57,12 +58,16 @@ class Source: documents, each read as a structured source's document; one it `consume`s is removed once a plan has landed every item it yields (the inbox's record, whose bytes the raw store then holds). A `stream` source is a directory of items in sequence that an edge reader appends to - (`core/ingest/stream.py`), read a batch past its cursor (dn-corpus-instance §5.2).""" + (`core/ingest/stream.py`), read a batch past its cursor (dn-corpus-instance §5.2). A + `repository` source is a git repository's files at a ref, read through git's object store + (`core/ingest/repository.py`), each item at `` + (dn-palace-lite). A source that does not `embed` keeps no vectors: its items land with their + lexical units and no plane row, and nothing derives one later (`Writer.keeps_vectors`).""" name: str - kind: str # "dir" | "file" | "records" | "stream" - location: Path # the directory, or the file - format: str # "markdown" | "json" + kind: str # "dir" | "file" | "records" | "stream" | "repository" + location: Path # the directory, the file, or the repository + format: str # "markdown" | "json" | "git" readers: frozenset[str] patterns: tuple[str, ...] = () # dir: the scope, relative to the location exclude: frozenset[str] = frozenset() # dir: directories excluded, in any case @@ -79,6 +84,9 @@ class Source: identity: str | None = None # the property an item declares its identity in title_of: Callable[[Mapping[str, Any]], str] | None = None # json: an item's title consume: bool = False # records: a document removed once it has landed + embed: bool = True # its items keep vectors (dn-palace-lite) + ref: str = "" # repository: the ref whose tree is its files + mark: Path | None = None # repository: where the commit it landed is kept def in_scope(self, path: Path) -> bool: """Whether a path is one of a directory source's items, existing or not: under the @@ -248,6 +256,9 @@ def _classes(s: Stratum) -> frozenset[str]: action="capture"), "curated": Place("curated", Stratum.CURATED, _classes(Stratum.CURATED), versions=False, action="ingest_curated"), + # the repositories' files (dn-palace-lite): the reference stratum, a version chain per file + "reference": Place("reference", Stratum.REFERENCE, _classes(Stratum.REFERENCE), + versions=True, action="ingest_code"), } JOBS: Mapping[str, Job] = { "dream": Job("dream", "dream", (Stratum.INTERPRETED,), propose=True), @@ -397,8 +408,31 @@ def items_of(docs: Any) -> Iterator[dict[str, Any]]: title_of=lambda it: str(it.get("title") or it["id"])) +# The code of the instance's repositories (dn-palace-lite): one repository source a repository +# `[ingestion.code]` names, its files at its ref, each at `code//`, labelled code, the +# reference stratum's class. Present only while the code lands lexically (`lexical_code`): with the +# code embed lane on, the code is the lane's, as it was. +CODE = "code" +CODE_SPACE = "code/" + + +def repository_mark(cfg: Config, name: str) -> Path: + """Where a repository source records the commit whose files it last landed whole.""" + return Path(cfg.paths.data_dir) / "code" / f"{name}.synced" + + +def _repository_source(cfg: Config, repo: Any) -> Source: + """A repository's files at its ref, read through git, each item labelled code, keeping no + vector. Only the operator's role opens it: the daemon's own sync and the owner's CLI.""" + return Source(name=f"{CODE}/{repo.name}", kind="repository", location=Path(repo.path), + format="git", readers=frozenset({"cli"}), label=CODE_LABEL, + labels=frozenset({CODE_LABEL}), space=f"{CODE_SPACE}{repo.name}/", + embed=False, ref=repo.ref, mark=repository_mark(cfg, repo.name)) + + def build_table(cfg: Config) -> Table: """This palace's table, from its configuration.""" + from core.kernel.config.loader import lexical_code from core.relations import RELATIONS vault = Path(str(cfg.ingestion.vault.path)).expanduser() @@ -419,6 +453,8 @@ def build_table(cfg: Config) -> Table: INBOX: _inbox_source(cfg), **({f"{CORPUS}/{n}": _corpus_source(cfg, n) for n in cfg.ingestion.corpus.sources} if cfg.ingestion.corpus.enabled else {}), + **({f"{CODE}/{r.name}": _repository_source(cfg, r) + for r in cfg.ingestion.code.repositories} if lexical_code(cfg) else {}), } places, jobs = PLACES, JOBS diff --git a/core/ingest/writer.py b/core/ingest/writer.py index 3c45bd43..ddb0045b 100644 --- a/core/ingest/writer.py +++ b/core/ingest/writer.py @@ -7,7 +7,9 @@ the plane holds the rows: the third review's finding 2). Under lazy embedding (dn-two-phase-ingestion, ING-19) a store lands complete without its plane rows: its lexical units take their place before the key, the UNCHANGED check reads them, and the embed drain derives the -rows afterwards (`core/ingest/derive.py`). An effect the rules refuse lands nothing +rows afterwards (`core/ingest/derive.py`). A store of a source that keeps no vectors, or of an +instance that embeds nothing (dn-palace-lite), lands the same way and stays so: no plane row is +written, no embedding is charged and no drain is asked for. An effect the rules refuse lands nothing and the rest of the plan lands; the outcome says which rule refused it. Before the first effect lands, the plan is priced (§E10): its writes, each store the UNCHANGED check would not skip and each other effect, and its embeds, the distinct atoms the plane does not hold, are charged to the @@ -170,10 +172,35 @@ class Writer: # key, and the embed drain derives the plane rows afterwards; a reader that needs a vector # reports the item pending until then. Off, a store embeds before its key as it always did. lazy: bool = False + # Whether the instance embeds at all (`[embedding] enabled`, dn-palace-lite). Off, every store + # lands as a lazy one does and nothing derives its vector later: the instance has no plane. + # On, a store still lands so when its source keeps no vectors (`Source.embed`). + embedding: bool = True landed: list[Outcome] = field(default_factory=list) started: set[str] = field(default_factory=set) # seconds spent in each stage of the last batched landing (admit, derive, index, finish) timing: dict[str, float] = field(default_factory=dict) + _keeps: dict[str, bool] = field(default_factory=dict) + + def keeps_vectors(self, path: str) -> bool: + """Whether the item at `path` has a vector at all: the instance embeds, and the source + that owns the path keeps vectors (a path no source owns, a script's own, does).""" + if not self.embedding: + return False + if path not in self._keeps: + owner = self.table.owner(path) + self._keeps[path] = owner is None or owner.embed + return self._keeps[path] + + def embeds_now(self, path: str) -> bool: + """Whether a store at `path` writes its plane rows before its key: it has a vector, and + the landing is not lazy.""" + return not self.lazy and self.keeps_vectors(path) + + def lexical_witness(self, path: str) -> bool: + """Whether the lexical index, not the plane, is what a store at `path` is held by: the + landing is lazy, or the item has no vector.""" + return self.lazy or not self.keeps_vectors(path) def land(self, plan: Sequence[Effect]) -> list[Outcome]: self.price(plan) @@ -186,7 +213,8 @@ def land(self, plan: Sequence[Effect]) -> list[Outcome]: o = self.one(e) self.landed.append(o) out.append(o) - if self.lazy and any(o.effect == "store" and o.status == "landed" for o in out): + if self.lazy and any(o.effect == "store" and o.status == "landed" + and self.keeps_vectors(o.path) for o in out): self.derive_later() return out @@ -244,9 +272,9 @@ def lap(stage: str) -> None: # the lexical units of every store, one transaction, before any key (ING-7) lexical.land_many([(e.path, rec.digest, e.content.label, e.title, rec.chunks) for _, e, _, rec in staged]) - if not self.lazy: - index_batch([rec for _, _, _, rec in staged], self.stores.embedder, - self.stores.plane) + embedded = [rec for _, e, _, rec in staged if self.embeds_now(e.path)] + if embedded: + index_batch(embedded, self.stores.embedder, self.stores.plane) lap("index") # what the ledger attests already, read once for the batch (a pass per store grows with # the ledger); each store then attests once, as `attest_once` does, its parents the @@ -275,13 +303,13 @@ def price(self, plan: Sequence[Effect]) -> tuple[int, int]: return (0, 0) writes = sum(1 for e in plan if not (isinstance(e, StoreEff) and self.unchanged(e))) self.meter.charge("write", writes) - if self.lazy: + if self.lazy or not self.embedding: return (writes, 0) # nothing is embedded now: the drain's work is its own ids: set[str] = set() chunked: set[str] = set() # the same bytes stored twice are chunked once for e in plan: if isinstance(e, StoreEff) and not e.content.oversize \ - and e.content.digest not in chunked: + and e.content.digest not in chunked and self.embeds_now(e.path): chunked.add(e.content.digest) ids |= {plane_atom_id(c.text) for c in derive_chunks(e.content.data, max_chars=self.max_chars, @@ -339,8 +367,9 @@ def admit(self, e: StoreEff) -> _Admitted | Outcome: place = self.table.places.get(e.place) if place is None: raise Refused("R1", f"no place {e.place!r}") - if self.lazy and self.stores.lexical is None: - raise Refused("R1", "lazy embedding needs the lexical index open; nothing landed") + if self.lexical_witness(e.path) and self.stores.lexical is None: + raise Refused("R1", "a landing without a vector needs the lexical index open; " + "nothing landed") c, path, label = e.content, e.path, e.content.label if c.oversize: raise Refused("R1", f"{path!r} is {c.oversize} bytes, more than an item may have; " @@ -385,13 +414,14 @@ def derive(self, e: StoreEff) -> IngestRecord: def index(self, e: StoreEff, record: IngestRecord) -> None: """A store's middle step, between its raw object and its key: the lexical units when the index is open (a function of the bytes, written before the key like every other stage, - ING-7; under lazy embedding they are what `holds` reads), and the plane rows unless the - landing is lazy, when the drain derives them.""" + ING-7; under lazy embedding, and for an item with no vector, they are what `holds` + reads), and the plane rows unless the landing is lazy, when the drain derives them, or + the item keeps no vector (`keeps_vectors`), when nothing does.""" lexical = self.stores.lexical if lexical is not None: lexical.land(source_path=e.path, digest=record.digest, provenance=e.content.label, title=e.title, chunks=record.chunks) - if not self.lazy: + if self.embeds_now(e.path): index_amendment(record, [], self.stores.embedder, self.stores.plane) def finish(self, e: StoreEff, adm: _Admitted, record: IngestRecord, *, @@ -481,13 +511,14 @@ def identity(self, e: StoreEff, prev: Any) -> str | None: raise Refused("R6", f"unknown naming {n.kind!r}") # pragma: no cover def holds(self, path: str, data: bytes, label: str, digest: str) -> bool: - """Whether the plane holds a version's rows at `path`, current, or, under lazy embedding, - whether the lexical index holds its units current, the landing's own stage (the rows are - the drain's, and their absence is pending, not unlanded: ING-19): an empty one has none to - hold. (It asked `has_digest`, which a retired version's rows still answer.)""" + """Whether the plane holds a version's rows at `path`, current, or, under lazy embedding or + for an item with no vector, whether the lexical index holds its units current, the + landing's own stage (the rows are the drain's, or no one's, and their absence is not an + unlanded item: ING-19): an empty one has none to hold. (It asked `has_digest`, which a + retired version's rows still answer.)""" if not derive_chunks(data, max_chars=self.max_chars, overlap_chars=self.overlap_chars): return True - if self.lazy: + if self.lexical_witness(path): lexical = self.stores.lexical return lexical is not None and bool(lexical.holds_current(path, digest)) clearance = HOLDS.get(label) diff --git a/core/kernel/config/loader.py b/core/kernel/config/loader.py index 0db13ec9..fe361f1c 100644 --- a/core/kernel/config/loader.py +++ b/core/kernel/config/loader.py @@ -225,6 +225,12 @@ class EmbeddingConfig: lazy: bool = False batch: int = 64 streams: int = 1 + # The lite profile (dn-palace-lite). `enabled = False` is an instance that embeds nothing: no + # embedder is built, no vector plane is opened, no embed drain runs, and every item lands + # complete without a vector, its lexical units written before its key, as a lazy landing lands + # it (ING-19). A clause that needs a vector reports that none exist; `near` ranks by the + # lexical index and says so. `lazy` has nothing to defer then, so it is not read. + enabled: bool = True def __post_init__(self) -> None: if self.batch < 1: @@ -415,6 +421,82 @@ class CodeIngestConfig: enabled: bool = False max_chars: int = 1200 overlap_chars: int = 150 + # Whether the code is embedded (dn-palace-lite). True is the code embed lane as it was + # (`code_sync`, the plane's code atoms). False lands each repository's files at its ref + # through the ingress instead, as items of the reference stratum with their lexical units, + # versions and attestations and no plane row, and starts no embed lane: the source keeps no + # vectors while the instance's other sources keep theirs. An instance that embeds nothing + # (`[embedding] enabled = false`) lands its code that way whatever this says. + embed: bool = True + # The repositories the lexical code source reads, each at a ref of its own, an item at + # `code//`. None declared is the instance's own checkout at + # `main`, named after its directory. + repositories: tuple[RepositoryConfig, ...] = () + + +@dataclass(frozen=True) +class RepositoryConfig: + """One repository of the lexical code source: its name (one path segment of its items' + space, `code//`), where it is, and the ref whose tree is its current files. It is read + through git's object store at the ref, never through its working tree, so no untracked file, + uncommitted edit or data directory beside it is ever read.""" + + name: str + path: Path + ref: str = "main" + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or not _INSTANCE_ID.fullmatch(self.name): + raise ValueError(f"[ingestion.code] repository {self.name!r} is not a source name: a " + f"lowercase letter followed by up to 31 lowercase letters, digits or " + f"hyphens") + if not self.ref or self.ref.startswith("-") or any(c.isspace() for c in self.ref): + raise ValueError(f"[ingestion.code] repository {self.name!r}: ref {self.ref!r} is not " + f"a ref git can name") + + +def lexical_code(cfg: Config) -> bool: + """Whether this instance's code lands lexically through the ingress: its code ingestion is on, + and either the code source keeps no vectors or the instance embeds nothing.""" + code = cfg.ingestion.code + return code.enabled and (not code.embed or not cfg.embedding.enabled) + + +def needs_lexical(cfg: Config) -> bool: + """Whether the instance keeps a lexical index: it lands lazily, it embeds nothing, or a source + of it keeps no vectors. An instance that embeds every item synchronously keeps none, so it + writes nothing it did not write before two-phase ingestion.""" + return bool(cfg.embedding.lazy) or not cfg.embedding.enabled or lexical_code(cfg) + + +def _repositories(section: dict[str, Any], root: Path) -> tuple[RepositoryConfig, ...]: + """The repositories `[ingestion.code]` declares (`[[ingestion.code.repositories]]`), a path + `~`-expanded and a relative one under the instance's root; none declared is the checkout, + named after its directory.""" + declared = section.get("repositories") or [] + if not isinstance(declared, list) or not all(isinstance(r, dict) for r in declared): + raise ValueError("[ingestion.code] repositories is a list of tables " + "([[ingestion.code.repositories]], each a name, a path and a ref)") + if not declared: + name = REPO_ROOT.name.casefold() + return (RepositoryConfig(name if _INSTANCE_ID.fullmatch(name) else "checkout", + REPO_ROOT, "main"),) + out = [] + for r in declared: + extra = sorted(set(r) - {"name", "path", "ref"}) + if extra: + raise ValueError(f"[ingestion.code] a repository holds a name, a path and a ref; " + f"refusing the unknown key(s) {extra}") + if "path" not in r: + raise ValueError(f"[ingestion.code] repository {r.get('name')!r} names no path") + path = Path(str(r["path"])).expanduser() + out.append(RepositoryConfig(str(r.get("name", "")), + path if path.is_absolute() else root / path, + str(r.get("ref", "main")))) + names = [r.name for r in out] + if len(set(names)) != len(names): + raise ValueError(f"[ingestion.code] repositories repeat a name: {names}") + return tuple(out) @dataclass(frozen=True) @@ -593,7 +675,7 @@ class InstanceConfig: namespace the instance holds is derived from that id: namespace Ouroboros named instance - root /instances/ + root /instances/, or [instance] root data dir, stores /data/… /data/… ingestion spool /data/handoff /data/handoff supervisor lock /data/supervisor.lock /data/supervisor.lock @@ -604,6 +686,7 @@ class InstanceConfig: vault source ~/.mind-palace/vault declared, else /vault and off transcripts ~/.claude/projects/ declared, else /transcripts and off code agent the checkout off unless its overlay turns it on + code repositories the checkout, at `main` declared, else the checkout (read by git) dialogue lanes openwebui, opencode none airlock in S3 as its overlay names it as its overlay names it exhaust lane ~/.mind-palace/exhaust /exhaust, moved only within root @@ -611,17 +694,25 @@ class InstanceConfig: Vault server [secrets] addr its overlay's own; none if it names none A declared source may lie anywhere but at, inside or around what another instance writes, or - anything the default instance reads or writes. + anything the default instance reads or writes. A code repository is read through git's object + store at its ref, never through its working tree, so it reads nothing an instance writes. `` is the root the root rule gives (`core/kernel/config/root.py`): the checkout the code runs from, or `MIND_PALACE_ROOT` for an installed copy, which from a checkout may name only that checkout. So Ouroboros's paths from a checkout are what they were, and a named instance's state stays under the root its process resolved, beside the instances declared there. + + A named instance may instead hold a root of its own, `[instance] root` (dn-palace-lite): an + absolute directory inside no git working tree, so its state outlives the checkout or worktree + a process happened to run from. Every namespace derives from that root exactly as from the + default one, and the sharing checks hold against it unchanged. + `namespaces_of` reads them off a built Config, and `shared` says what two instances hold in common. The map is injective: distinct ids give disjoint namespaces, none of them Ouroboros's. """ id: str = OUROBOROS + home: Path | None = None # a named instance's declared root (`[instance] root`) def __post_init__(self) -> None: # The map is defined on well-formed ids only: built from `../x`, `root` would climb out of @@ -629,6 +720,8 @@ def __post_init__(self) -> None: # other caller too. if not isinstance(self.id, str) or not _INSTANCE_ID.fullmatch(self.id): raise ValueError(f"not an instance id: {self.id!r}") + if self.home is not None and (not self.named or not Path(self.home).is_absolute()): + raise ValueError(f"a declared root is a named instance's, and absolute: {self.home!r}") @property def named(self) -> bool: @@ -638,7 +731,10 @@ def named(self) -> bool: @property def root(self) -> Path: """What this instance's relative data paths resolve against: the repo root for Ouroboros, - so `data/` is where it always was, and `/instances/` for a named instance.""" + so `data/` is where it always was, and `/instances/` for a named instance, or + the root it declares.""" + if self.home is not None: + return Path(self.home) return REPO_ROOT / _INSTANCES / self.id if self.named else REPO_ROOT @property @@ -1038,17 +1134,19 @@ def _read(path: Path) -> dict[str, Any]: def _declared_id(table: object, source: str) -> str | None: """The id an `[instance]` table declares, or None when there is no table or no id in it. - The table holds `id` and nothing else, so any other key refuses: the loader would ignore it, - and a setting that looks applied but never took is the failure every refusal here exists for. + The table holds `id` and, for a named instance, `root` (`_declared_root`), so any other key + refuses: the loader would ignore it, and a setting that looks applied but never took is the + failure every refusal here exists for. """ if table is None: return None if not isinstance(table, dict): - raise InstanceOverlayError(f"{source}: [instance] must be a table holding one key, id.") - extra = sorted(set(table) - {"id"}) + raise InstanceOverlayError(f"{source}: [instance] must be a table holding an id.") + extra = sorted(set(table) - {"id", "root"}) if extra: raise InstanceOverlayError( - f"{source}: [instance] holds one key, id; refusing the unknown key(s) {extra}.") + f"{source}: [instance] holds an id and a named instance's root; refusing the unknown " + f"key(s) {extra}.") if "id" not in table: return None iid = table["id"] @@ -1074,18 +1172,59 @@ def _named_instance(declared: dict[str, Any], source: Path) -> InstanceConfig: f"{source}: [instance] id = {OUROBOROS!r} is the default chain's, the live instance. " f"Refusing to load a second {OUROBOROS!r}: give this instance its own id, or unset " f"{OVERLAY_ENV} to load the default chain.") - return InstanceConfig(iid) + return InstanceConfig(iid, _declared_root(declared.get("instance"), source)) + + +def _working_tree_of(path: Path) -> Path | None: + """The git working tree a path lies in (the nearest of it and its ancestors holding `.git`, a + checkout's directory or a worktree's file), or None.""" + for p in (path, *path.parents): + if os.path.lexists(p / ".git"): + return p + return None + + +def _declared_root(table: object, source: Path) -> Path | None: + """The root a named overlay declares (`[instance] root`), or None to keep the derived one. + + The point of a declared root is a home the instance's state keeps whichever checkout or + worktree a process runs from, so it is absolute (`~` expands) and lies inside no git working + tree: a worktree is removed when its branch merges, and the state inside it would go with it. + The sharing checks (`_refuse_shared`) then hold against it as against a derived root.""" + if not isinstance(table, dict) or "root" not in table: + return None + given = table["root"] + if not isinstance(given, str) or not given.strip(): + raise InstanceOverlayError(f"{source}: [instance] root = {given!r} names no directory.") + root = Path(given).expanduser() + if not root.is_absolute(): + raise InstanceOverlayError( + f"{source}: [instance] root = {given!r} is relative, so it would move with the " + f"working directory. Give the root as an absolute path (or one starting with ~).") + tree = _working_tree_of(Path(os.path.realpath(root))) + if tree is not None: + raise InstanceOverlayError( + f"{source}: [instance] root = {given!r} lies inside the git working tree {tree}. An " + f"instance's declared root lies outside every checkout and worktree, so its state " + f"outlives them; refusing.") + return root def _ouroboros_instance(raw: dict[str, Any], source: str) -> InstanceConfig: """The default chain is Ouroboros, and so is a file `load_config` reads by path. Its - `[instance]` may restate that; another id would rename the live instance in place.""" + `[instance]` may restate that; another id would rename the live instance in place, and a root + would move it (Ouroboros's root is its checkout's).""" iid = _declared_id(raw.get("instance"), source) if iid is not None and iid != OUROBOROS: raise InstanceOverlayError( f"{source}: [instance] id = {iid!r}, but this configuration is {OUROBOROS!r}. " f"Another instance is loaded from its own overlay, {OVERLAY_ENV}=; refusing to " f"load {OUROBOROS!r} under another id.") + table = raw.get("instance") + if isinstance(table, dict) and "root" in table: + raise InstanceOverlayError( + f"{source}: [instance] root is a named instance's; {OUROBOROS!r} keeps the " + f"checkout's root. Refusing to move the live instance.") return InstanceConfig() @@ -1354,6 +1493,9 @@ def secret(name: object) -> str: enabled=bool(ci.get("enabled", False)), max_chars=int(ci.get("max_chars", 1200)), overlap_chars=int(ci.get("overlap_chars", 150)), + embed=bool(ci.get("embed", True)), + # read only when the code is on: an instance with no code source has none + repositories=_repositories(ci, root) if ci.get("enabled", False) else (), ), corpus=CorpusIngestConfig( enabled=bool(co.get("enabled", False)), @@ -1374,6 +1516,7 @@ def secret(name: object) -> str: lazy=bool(e.get("lazy", False)), batch=int(e.get("batch", 64)), streams=int(e.get("streams", 1)), + enabled=bool(e.get("enabled", True)), ), dreaming=DreamingConfig( similarity_threshold=float(dr["similarity_threshold"]), diff --git a/core/kernel/rings.py b/core/kernel/rings.py index 3f7a5d61..707d3cb0 100644 --- a/core/kernel/rings.py +++ b/core/kernel/rings.py @@ -65,7 +65,9 @@ # computes pure** (stdlib only: the reading side of a corpus stream, its manifest and its cursor, # dn-corpus-instance §5.2) and is claimed: 47 + 1 = 48. **`core.ingest.lexical` computes pure** # (stdlib, NumPy and SciPy: tokens, BM25 weights and the in-memory index of landed chunks, the -# structural phase, dn-two-phase-ingestion) and is claimed: 48 + 1 = 49. +# structural phase, dn-two-phase-ingestion) and is claimed: 48 + 1 = 49. **2026-11-09: +# `core.stores.noplane` computes pure** (stdlib only: the empty plane of an instance that embeds +# nothing, and the refusal a factory raises for one, dn-palace-lite) and is claimed: 49 + 1 = 50. INNER: frozenset[str] = frozenset({ "core", # the root package init (import-free; does not move — §2.3) # ── the kernel subtree: 29 born (K1) + 7 S1 (K3) relocated members + the kernel package init ── @@ -120,4 +122,5 @@ "core.ingest.files", # the ingress's file-trust checks, stdlib only (§E13) "core.ingest.stream", # a corpus stream's reading side, stdlib only (corpus §5.2) "core.ingest.lexical", # tokens, BM25 weights, the in-memory index: NumPy, SciPy + "core.stores.noplane", # the empty plane of an instance that embeds nothing, stdlib only }) diff --git a/core/query.py b/core/query.py index 988e05e4..6c10c6ad 100644 --- a/core/query.py +++ b/core/query.py @@ -402,7 +402,13 @@ class QueryEngine: def _get(self, name: str) -> Any: if name not in self._cache: cfg = self.config - if name == "vectors": + if name in ("vectors", "curated") and not cfg.embedding.enabled: + # an instance that embeds nothing has no plane: an empty one that never fills + # stands in for both, and no store is opened (dn-palace-lite) + from core.stores.noplane import NoPlane + + self._cache[name] = NoPlane() + elif name == "vectors": from core.stores.vectorstore import open_vector_store self._cache[name] = open_vector_store(cfg) @@ -447,12 +453,14 @@ def _get(self, name: str) -> Any: self._cache[name] = open_membership_store(cfg) elif name == "lexical": - # the lexical index (dn-two-phase-ingestion D2): None for an instance that embeds - # synchronously and never built one, so a read creates no store + # the lexical index (dn-two-phase-ingestion D2, dn-palace-lite): None for an + # instance that embeds every item synchronously and never built one, so a read + # creates no store + from core.kernel.config.loader import needs_lexical from core.stores.lexical import lexical_path, open_lexical_store self._cache[name] = (open_lexical_store(cfg) - if cfg.embedding.lazy or lexical_path(cfg).exists() + if needs_lexical(cfg) or lexical_path(cfg).exists() else None) else: raise KeyError(name) diff --git a/core/sentence/execute.py b/core/sentence/execute.py index be5c645c..f587bdec 100644 --- a/core/sentence/execute.py +++ b/core/sentence/execute.py @@ -137,6 +137,10 @@ class Universe: # so. A universe built by hand has neither: every node's vector is known. pending: frozenset[int] = frozenset() lexical: Callable[[str], np.ndarray] | None = None + # The lite profile (dn-palace-lite): the nodes among `pending` that keep no vector at all, + # since the instance embeds nothing or their source keeps none. They are ranked as the pending + # are; what differs is what an answer says: no vector will come, so none is waited for. + unembedded: frozenset[int] = frozenset() def __len__(self) -> int: return len(self.notes) @@ -246,6 +250,37 @@ def _git(root: Path, *args: str) -> bytes | None: return out.stdout if out.returncode == 0 else None +def _window(text: str, chunk: int | None, window: int) -> tuple[str, int, int, int]: + """A window of `window` chunks of `REPO_CHUNK_LINES` lines around `chunk` (from the start when + absent): the text, its first and last chunk, and the chunk count.""" + lines = text.splitlines(keepends=True) + n = max(1, -(-len(lines) // REPO_CHUNK_LINES)) + first = min(0 if chunk is None else max(0, int(chunk) - 2), n - 1) + last = min(n, first + max(1, window)) - 1 + return ("".join(lines[first * REPO_CHUNK_LINES:(last + 1) * REPO_CHUNK_LINES]), first, last, + n) + + +def _read_landed_file(engine: QueryEngine, ref: str, chunk: int | None, *, + window: int) -> Mapping[str, object] | None: + """A repository source's file as it landed (dn-palace-lite): the active item of the reference + stratum at the ref, read from the raw store by its digest, a window of it as a repo file's. + None when no such item is landed, so the ref is read as git's blob instead.""" + try: + entry = engine._get("catalog").get(ref) + except KeyError: # an engine without the catalog + return None + if entry is None or not entry.active or str(entry.provenance) != "code": + return None + from core.kernel.stores.rawstore import RawStore + + data = RawStore(engine.config.paths.raw_store).get(entry.digest) + body, first, last, n = _window(data.decode("utf-8", errors="replace"), chunk, window) + return {"ref": ref, "title": str(entry.title), "provenance": "code", + "stratum": "reference", "digest": str(entry.digest), + "chunks": f"{first}–{last} of {n}", "text": body[:REPO_MAX_CHARS]} + + def _read_repo_file(ref: str, chunk: int | None, *, window: int, cut: str | None) -> Mapping[str, object] | None: """A repo-relative path, a node of the reference graph, read as git's blob in the tree at the @@ -338,7 +373,9 @@ def read_ref(engine: QueryEngine, ref: str, chunk: int | None, *, window: int, return {"ref": ref, "title": f"{ref} ({speaker})", "provenance": "observed", "stratum": "transcript", "speaker": speaker, "text": str(row.get("text", ""))} if "/" in ref and not ref.startswith(("/", "~", "dialogue/")): - return _read_repo_file(ref, chunk, window=window, cut=cut) + landed = _read_landed_file(engine, ref, chunk, window=window) + return landed if landed is not None else _read_repo_file(ref, chunk, window=window, + cut=cut) entry = VaultCatalog(cfg.paths.vault_catalog).get(ref) if entry is None or not entry.active: return None @@ -613,23 +650,28 @@ def _near_pending(self, text: str, carrier: frozenset[int], scores: np.ndarray) pend = sorted(carrier & self.u.pending) if not pend: return "" + none = len(carrier & self.u.unembedded) + # all pending: two-phase ingestion's words; some keep no vector (dn-palace-lite): which + status = ("are pending (landed, their vectors not yet derived)" if not none + else f"have no vector ({_vectorless(len(pend) - none, none)})") + noun = "pending nodes" if not none else "nodes without a vector" lex = self.u.lexical(text) if self.u.lexical is not None else None if lex is None: self.notes.append( - f"near {text!r}: {len(pend)} of the clause's {len(carrier)} nodes are pending " - "(landed, their vectors not yet derived) and no lexical index is open: they " - "score nothing here and are reported, never guessed") - return f"; {len(pend)} pending nodes score nothing (no lexical index)" + f"near {text!r}: {len(pend)} of the clause's {len(carrier)} nodes {status} and " + "no lexical index is open: they score nothing here and are reported, never " + "guessed") + return f"; {len(pend)} {noun} score nothing (no lexical index)" for i in pend: scores[i] = float(np.clip(lex[i], 0.0, 1.0)) matched = sum(1 for i in pend if scores[i] > 0) self.notes.append( - f"near {text!r}: {len(pend)} of the clause's {len(carrier)} nodes are pending " - "(landed, their vectors not yet derived); they are ranked by the lexical index, " + f"near {text!r}: {len(pend)} of the clause's {len(carrier)} nodes {status}; they are " + f"ranked by the lexical index, " f"{matched} of them sharing a term with the text, each labelled `ranked_by`, on a " "scale of their own beside the vectors' cosines; VEC-1's certificate covers the " f"{len(carrier) - len(pend)} with vectors") - return (f"; {len(pend)} pending nodes ranked by the lexical index " + return (f"; {len(pend)} {noun} ranked by the lexical index " f"({matched} share a term), labelled") def eval(self, node: Node) -> Value: @@ -1139,12 +1181,21 @@ def key(j: int) -> tuple[float, int, int]: return sorted(value.members, key=key) +def _vectorless(pending: int, none: int) -> str: + """What a clause's nodes without a vector are: pending (the drain derives them), or keeping + none (the instance embeds nothing, or their source keeps none).""" + parts = ([f"{pending} pending, their vectors not yet derived"] if pending else []) \ + + ([f"{none} keeping none"] if none else []) + return "; ".join(parts) + + def _chain_strata(c: Chain, strata: Mapping[str, str]) -> str: """The strata a chain runs through, in the order it enters them (`transcript+reference`): a chain from a turn over the files it wrote is not the mirror's.""" out: list[str] = [] for node in (c.start, *(v for _, v in c.steps)): - name = strata.get(node, "mirror") + # a version chain's node is `@` (`trace`): its stratum is its ref's + name = strata.get(node) or strata.get(node.rpartition("@")[0], "mirror") if name not in out: out.append(name) return "+".join(out) @@ -1154,7 +1205,11 @@ def _hit(u: Universe, j: int, *, score: float | None = None, detail: dict[str, Any] | None = None) -> Hit: n = u.notes[j] node_detail = dict(n.get("detail") or {}) - if score is not None and j in u.pending: + scored = score is not None or "score" in (detail or {}) # a field's, or a region's + if scored and j in u.unembedded: + # a scored hit that keeps no vector was ranked by the lexical index (dn-palace-lite) + node_detail["ranked_by"] = "lexical: the item keeps no vector" + elif score is not None and j in u.pending: # a scored hit whose vector is pending was ranked by the lexical index (ING-21) node_detail["ranked_by"] = "lexical: the vector is pending" return Hit(ref=str(n.get("source_path", "")), title=str(n.get("title", "")), diff --git a/core/sentence/universe.py b/core/sentence/universe.py index d515c24d..b5dd8aad 100644 --- a/core/sentence/universe.py +++ b/core/sentence/universe.py @@ -239,6 +239,9 @@ def __init__(self, engine: QueryEngine, precedents: Precedents, self.census: dict[str, float] = {} # a paper's full-backbone degree, by the index self._cited_of: dict[str, set[str]] = {} # the citation graph's neighbours, per node read self.pending: list[str] = [] # the nodes landed without a vector yet (two-phase) + # the nodes that keep no vector at all: the instance embeds nothing, or their source keeps + # none (dn-palace-lite); ranked by the lexical index as the pending are, and said so + self.unembedded: list[str] = [] # stores -------------------------------------------------------------------------------------- def store(self, name: str) -> Any: @@ -246,10 +249,25 @@ def store(self, name: str) -> Any: def embed(self, text: str) -> np.ndarray: if text not in self._embeds: + if not self.embeds: + # the lite profile: no embedder exists, so a text has no vector (dn-palace-lite); + # the zero vector scores nothing, and the lexical index ranks what a clause reads + self._embeds[text] = np.zeros(int(self.e.config.embedding.dim)) + return self._embeds[text] v = _unit(self.store("embedder").embed_query(text)) self._embeds[text] = v if v is not None else np.zeros(int(self.e.config.embedding.dim)) return self._embeds[text] + @property + def embeds(self) -> bool: + """Whether the instance embeds at all (`[embedding] enabled`).""" + return bool(self.e.config.embedding.enabled) + + def _vectorless(self, ref: str) -> None: + """Mark a node as one that keeps no vector, ranked by the lexical index.""" + if ref not in self.unembedded: + self.unembedded.append(ref) + # nodes --------------------------------------------------------------------------------------- def add(self, node: _Node) -> _Node: have = self.nodes.get(node.ref) @@ -316,7 +334,7 @@ def load_pending(self) -> None: embeds synchronously, so its universes are what they were.""" from core.ingest.derive import pending - if not bool(self.e.config.embedding.lazy): + if not bool(self.e.config.embedding.lazy) and self.embeds: return lexical = self.lexical_index() if lexical is None: @@ -330,6 +348,11 @@ def load_pending(self) -> None: label = stratum_of_provenance(prov) or "mirror" if label not in ("mirror", "dialogue") or not self.admits(label, prov): continue + if not self.embeds: # nothing is pending: no vector will ever come + self.add(_Node(e.source_path, label, e.title, e.digest, prov, None, + {"vector": "none: the instance embeds nothing"})) + self._vectorless(e.source_path) + continue have = self.nodes.get(e.source_path) if have is None: self.add(_Node(e.source_path, label, e.title, e.digest, prov, None, @@ -345,7 +368,8 @@ def seed_lexical(self, text: str, why: str) -> int: (the vector index cannot reach them): at most `support`, added without a vector.""" from core.kernel.provenance import Provenance - if not bool(self.e.config.embedding.lazy) or not self.admits("curated", "curated"): + if (not bool(self.e.config.embedding.lazy) and self.embeds) \ + or not self.admits("curated", "curated"): return 0 lexical = self.lexical_index() if lexical is None: @@ -366,15 +390,62 @@ def seed_lexical(self, text: str, why: str) -> int: e = waiting[hit.source_path] if hit.source_path in self.nodes: continue - self.add(_Node(e.source_path, "curated", e.title, e.digest, "curated", None, - {"pending": "no vector yet"})) - self.pending.append(e.source_path) + if not self.embeds: + self.add(_Node(e.source_path, "curated", e.title, e.digest, "curated", None, + {"vector": "none: the instance embeds nothing"})) + self._vectorless(e.source_path) + else: + self.add(_Node(e.source_path, "curated", e.title, e.digest, "curated", None, + {"pending": "no vector yet"})) + self.pending.append(e.source_path) added += 1 if added: - self.notes.append(f"curated: {added} pending papers from the lexical index for " - f"{why!r} (their vectors are not yet derived)") + why_none = ("the instance embeds nothing" if not self.embeds + else "their vectors are not yet derived") + self.notes.append(f"curated: {added} papers from the lexical index for {why!r} " + f"({why_none})") return added + def seed_reference_lexical(self, text: str, why: str) -> int: + """The reference stratum's items that keep no vector (a repository source's files, + dn-palace-lite) a `near` text reaches, by the lexical index: the files of its `support` + best units, added without a vector, ranked by the index and said so. An instance whose + index holds no such unit (its code, if any, is the embed lane's) adds nothing here.""" + from core.kernel.provenance import Provenance + + if not self.admits("reference", "code"): + return 0 + lexical = self.lexical_index() + if lexical is None: + return 0 + hits = lexical.search(text, k=self.p.support, classes=[Provenance.CODE]) + files: list[str] = [] + for hit in hits: + if hit.source_path in files: + continue + files.append(hit.source_path) + self.add(_Node(hit.source_path, "reference", hit.title, hit.digest, "code", None, + {"chunk": hit.chunk_index, "vector": "none: the source keeps none"})) + self._vectorless(hit.source_path) + if hits: + self.notes.append(f"reference: {len(files)} files from the {len(hits)} best lexical " + f"units for {why!r} (the index's top {self.p.support}; the files " + "keep no vectors)") + return len(files) + + def seed_item(self, atom: str) -> None: + """An anchor that is a landed item of the reference stratum (a repository source's file): + its node, with the digest and title the catalog holds, and no vector.""" + try: + entry = self.store("catalog").get(atom) + except KeyError: # an engine without the catalog + return + if entry is None or not entry.active or str(entry.provenance) != "code": + return + self.add(_Node(atom, "reference", str(entry.title), str(entry.digest), "code", None, + {"vector": "none: the source keeps none"})) + self._vectorless(atom) + # the indexed strata -------------------------------------------------------------------------- def seed_curated(self, vec: np.ndarray, why: str) -> int: if not self.admits("curated", "curated"): @@ -402,7 +473,7 @@ def seed_curated(self, vec: np.ndarray, why: str) -> int: def seed_code(self, vec: np.ndarray, why: str) -> int: from core.stores.memberships import resolve_occupancies - if not self.admits("reference", "code"): + if not self.admits("reference", "code") or not self.embeds: return 0 rows = self.store("vectors").search(list(map(float, vec)), k=self.p.support, clearance=CODE_READ) @@ -700,6 +771,7 @@ def seed_anchor(self, atom: str, radius: int) -> None: self.seed_curated(node.vector, atom) return if is_repo_path(atom) and self.admits("reference", "code"): + self.seed_item(atom) self.seed_typed(atom, radius, frozenset({Rel.F}) | (self.moves & {Rel.C})) def wire_reference(self) -> None: @@ -808,21 +880,29 @@ def text(ref: str, chunk: int | None, window: int) -> Mapping[str, object] | Non "outside the repo and the vault: named in the transcript's " "stratum, not readable") missing.append("D moves at the note grain: the version chains are per note (use trace)") - pending = frozenset(i for i, n in enumerate(order) if n.ref in set(self.pending)) + waiting = frozenset(i for i, n in enumerate(order) if n.ref in set(self.pending)) + unembedded = frozenset(i for i, n in enumerate(order) if n.ref in set(self.unembedded)) + pending = waiting | unembedded lexical = self._lexical_scores(order, pending) - if pending: - named = ", ".join(order[i].ref for i in sorted(pending)[:5]) - more = f" and {len(pending) - 5} more" if len(pending) > 5 else "" + if waiting: + named = ", ".join(order[i].ref for i in sorted(waiting)[:5]) + more = f" and {len(waiting) - 5} more" if len(waiting) > 5 else "" missing.append( - f"pending: {len(pending)} items landed without a vector yet (the embed drain " + f"pending: {len(waiting)} items landed without a vector yet (the embed drain " f"derives them); a semantic clause ranks them by the lexical index and says so, " f"and S has no edge at them: {named}{more}") + if unembedded: + whose = ("the instance embeds nothing" if not self.embeds + else "their source keeps no vectors") + missing.append( + f"no vector: {len(unembedded)} items keep none ({whose}); a semantic clause ranks " + "them by the lexical index and says so, and S has no edge at them") return Universe(notes=notes, vectors=mat, weights=weights, edges={Rel.F: self.f_edges, Rel.D: {}, Rel.C: self.c_edges}, relations=relations, embed=embed, history=history, witness=witness, cut=self.cut, missing=tuple(missing), text=text, degrees=degrees, - pending=pending, lexical=lexical) + pending=pending, lexical=lexical, unembedded=unembedded) def _lexical_scores(self, order: list[_Node], pending: frozenset[int]) -> Callable[[str], np.ndarray] | None: @@ -868,6 +948,7 @@ def build(engine: QueryEngine, plan: Plan, *, precedents: Precedents = DEFAULT, b.seed_lexical(text, text) if strata & REFERENCE_NAMES: b.seed_code(b.embed(text), text) + b.seed_reference_lexical(text, text) for atom, radius in seeds.anchors: b.seed_anchor(atom, radius) b.wire_reference() diff --git a/core/stores/curated_store.py b/core/stores/curated_store.py index 85dab9dd..131abdfc 100644 --- a/core/stores/curated_store.py +++ b/core/stores/curated_store.py @@ -35,5 +35,9 @@ def open_curated_store(config: Config | None = None) -> VectorStore: from core.kernel.config import get_config cfg = config or get_config() + if not cfg.embedding.enabled: # the lite profile opens no plane (`core/stores/noplane.py`) + from core.stores.noplane import refuse + + raise refuse("opening the curated plane") return VectorStore(path=cfg.paths.curated_store, dim=cfg.embedding.dim, embedder=fingerprint_of(cfg)) diff --git a/core/stores/noplane.py b/core/stores/noplane.py new file mode 100644 index 00000000..b71f5240 --- /dev/null +++ b/core/stores/noplane.py @@ -0,0 +1,75 @@ +"""The plane of an instance that keeps none (dn-palace-lite). + +An instance with `[embedding] enabled = false` embeds nothing, so it opens no vector store: no +LanceDB directory is made, no table is read. The readers that would ask the plane (the writer's +UNCHANGED check, the drain's pending set, the query engine's universe, the MCP surface's counts) +are handed this object instead, whose every read answers what an empty plane answers, so a reader +built for the plane needs no second code path, and whose every write refuses. Nothing is ever +landed into it, and nothing an instance holds is ever read from it. + +`EmbeddingOff` is the refusal, raised by the factories that would build an embedder or open a +plane for such an instance (`build_embedder`, `open_vector_store`, `open_curated_store`), so a code +path the lite profile did not anticipate fails by name instead of reaching for a server or a +directory, and by any method of this object beyond the reads below. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from typing import Any + + +class EmbeddingOff(RuntimeError): + """The instance embeds nothing (`[embedding] enabled = false`): it has no embedder and no + plane, and the operation asked for one.""" + + +def refuse(what: str) -> EmbeddingOff: + return EmbeddingOff(f"{what}: this instance embeds nothing ([embedding] enabled = false), so " + f"it has no embedder and no vector plane") + + +class NoPlane: + """An empty plane that never fills. The reads are the plane's (`VectorStore`) with an empty + answer; a write, or any other method, raises `EmbeddingOff`.""" + + def count(self) -> int: + return 0 + + def all_rows(self, *, clearance: Any = None, include_atom_rows: bool = False + ) -> list[Mapping[str, Any]]: + return [] + + def search(self, vector: Sequence[float], *, k: int = 5, clearance: Any = None, + **_: Any) -> list[Mapping[str, Any]]: + return [] + + def rows_for_source(self, source_path: str, *, clearance: Any = None + ) -> list[Mapping[str, Any]]: + return [] + + def holds_current(self, source_path: str, digest: str, *, clearance: Any = None) -> bool: + return False + + def has_digest(self, digest: str, *, clearance: Any = None) -> bool: + return False + + def current_versions(self, *, clearance: Any = None) -> set[tuple[str, str]]: + return set() + + def known_atoms(self, atom_ids: Sequence[str]) -> set[str]: + return set() + + def known_atoms_in(self, atom_ids: Sequence[str], classes: Iterable[Any]) -> set[str]: + return set() + + def delete_source(self, source_path: str) -> None: + """A retire's plane step: the plane holds nothing at any path, so there is nothing to + take out, and the retire goes on to its key.""" + return None + + def add(self, rows: Iterable[Mapping[str, Any]]) -> int: + raise refuse("adding rows to the vector plane") + + def __getattr__(self, name: str) -> Any: + raise refuse(f"the vector plane's {name!r}") diff --git a/core/stores/vectorstore.py b/core/stores/vectorstore.py index ac320cb0..ea936c20 100644 --- a/core/stores/vectorstore.py +++ b/core/stores/vectorstore.py @@ -986,5 +986,9 @@ def open_vector_store(config: Config | None = None) -> VectorStore: from core.kernel.config import get_config cfg = config or get_config() + if not cfg.embedding.enabled: # the lite profile opens no plane (`core/stores/noplane.py`) + from core.stores.noplane import refuse + + raise refuse("opening the vector plane") return VectorStore(path=cfg.paths.vector_store, dim=cfg.embedding.dim, embedder=fingerprint_of(cfg)) diff --git a/docs/design-notes/dn-palace-lite.md b/docs/design-notes/dn-palace-lite.md new file mode 100644 index 00000000..afa8ac03 --- /dev/null +++ b/docs/design-notes/dn-palace-lite.md @@ -0,0 +1,283 @@ +--- +type: design-note +id: dn-palace-lite +track: query-language +status: draft # provenance description, never a gate; the merge is ratification +implementation: partial # the two switches, the repository source, the code instance, the hooks and the measurements landed 2026-11-09; the shared embedding service (§7.1) and the slim install (§7.2) are proposed, not built +created: 2026-11-09 +updated: 2026-11-09 +links: + - docs/design-notes/dn-two-phase-ingestion.md # an item is complete without its vector (ING-19 to ING-21); this note's starting point + - docs/design-notes/dn-ingress-language.md # the writer's rules, the table, the places, the library scripts + - docs/design-notes/dn-corpus-instance.md # a named instance (DI-2) and its runner; the embedder as the slow stage + - docs/design-notes/dn-query-sentence-algebra.md # the universe, `near`, the support and its notes + - docs/design-notes/dn-code-ingest-pipeline.md # the code embed lane this note leaves as it was + - docs/experiments/palace-lite-2026-11-09.md # the measurements of §6 + - papers/2026-11-09-palace-lite/paper.tex # the article +supersedes: null +superseded_by: null +warrant: null +--- + +# The lite palace: the language model optional, the embedder optional + +> Drafted on a branch from `origin/main` at `2b500e5e`. Every claim about code was read there or +> on the branch; every figure is from `docs/experiments/palace-lite-2026-11-09.md`, measured on +> this machine with the load named beside it. + +## 1. The problem + +Two-phase ingestion made the vector a derived field of an item: an item lands complete, its +bytes, label, lexical units, version, attestation and key, and the embed drain writes its vector +later (ING-19 to ING-21). That leaves three costs in place for an instance that does not need +vectors at all. + +- The default instance's code stratum is a snapshot. Its code ingestion is off, because the code + embed lane embeds every changed file through the embedder, and so a coding agent that asks the + palace about the code reads files as they were at its last snapshot (2026-10-29), while ripgrep + over the checkout finds them as they are. +- A small device cannot run an embedder beside the palace, and an instance that has no use for + semantic similarity should not have to run one. +- A language model runs the dreaming, relation and curation passes. An instance whose job is + lookup has no use for them either. + +The palace should run lean: the language model optional, the embedder optional, and, for the +instances that do want vectors, one shared embedder in front of which the instances queue (§7.1). + +## 2. Two switches + +### 2.1 An instance that embeds nothing + +`[embedding] enabled = false` declares an instance with no embedder. What follows from it: + +- No embedder is built and no vector plane is opened. The factories refuse by name: + `build_embedder`, `open_vector_store` and `open_curated_store` raise `EmbeddingOff` for such an + instance, so a code path the profile did not anticipate fails with the reason instead of + reaching for a server or making a directory. +- The readers that ask a plane (the writer's UNCHANGED check, the drain's pending set, the query + engine's universe, the MCP surface's counts) are handed `NoPlane`, whose every read answers what + an empty plane answers and whose every write refuses (`core/stores/noplane.py`). +- Every store lands as a lazy store lands under ING-19, its lexical units before its key, and + stays so: no embedding is charged to the plan, no plane row is written, no drain is asked for. + The embed job and `palace embed` say there is nothing to derive. +- No daemon runs for it. The daemon wires the embedder's consumers (the librarian, the code embed + lane, the airlock's ranking), so `palace start` refuses such an instance by name; its sources + sync on demand and by the hooks of §4.3. + +### 2.2 A source that keeps no vectors + +The same choice per source: `Source.embed = false` in the table. The writer decides per store, + + keeps_vectors(path) = [embedding] enabled and (the source that owns path).embed + embeds_now(path) = keeps_vectors(path) and not lazy + lexical_witness(path) = lazy or not keeps_vectors(path) + +so a store embeds before its key only when its item keeps a vector and the landing is not lazy; +the UNCHANGED check reads the lexical index when the store lands without a vector; and the drain +is asked for only by a lazy landing of an item that keeps one. An instance can then keep vectors +for its notes while its code lands lexically. Configured today for the code source: +`[ingestion.code] embed = false`. The drain never treats such an item as pending: the code's class +is not one of the plane's (`HOLDS`), and a lazy landing of it asks for no drain. + +### 2.3 What each verb does without a vector + +| verb | reads | without a vector | +|---|---|---| +| `near "t"` | the kernel column `clip(V·q̂)` | ranks the clause's vectorless nodes by the lexical index (BM25 over the same chunks the plane would hold), on a scale of its own, each hit labelled `ranked_by: lexical: the item keeps no vector`; the notes count pending and vectorless nodes apart | +| `diffuse S`, `reach S`, `walk … via S` | the backbone `S`, cosine at or above σ | `S` has no edge at a vectorless node; the answer is empty or covers the nodes with vectors, and the notes say so | +| `reach F`, `walk … via F` | the citation graph at the cut | unchanged; no vector is involved | +| `trace` | the version chain | unchanged; a file's chain grows by one version each sync that lands a change to it | +| `read` | the raw store, or git | unchanged; a landed repository file is read from the raw store by its digest | +| `witness` | the attestations and the edge stores | unchanged | +| `relate` | the signed relation edges | unchanged | +| `top`, `atleast`, `far`, `not`, `and`, `or`, `minus`, `then`, `within`, `over`, `assume` | fields and regions | unchanged; they compose whatever the verbs above produced | + +A query never invents a vector: a node without one is ranked lexically and labelled, or reported. + +### 2.4 The default instance + +Nothing about it changes. `[embedding] enabled` and `[ingestion.code] embed` default to true, the +table holds no repository source unless the code lands lexically, and an instance that embeds every +item synchronously still opens no lexical index (`needs_lexical`). The `reference` place this note +adds is written by the operator's role alone. + +## 3. The language model optional + +The model runs the dreaming, curation and relation passes and the Ambassador's own chat. A lite +instance schedules none of them (`[dreaming] scheduled = false`, `[integrate] enabled = false`), +runs no daemon to wake one, and its sentence engine needs no model: every verb above is plain +arithmetic over the stores. The MCP server's `status` tool reports the embedder of such an +instance as `off` and never probes it. + +## 4. The code instance + +### 4.1 A repository as a source + +A `repository` source is a git repository's files at a ref, read through git's object store and +never through the working tree (`core/ingest/repository.py`): `rev-parse` resolves the ref, +`ls-tree` lists the tree, one `cat-file --batch` process a batch reads the blobs. So no untracked +file, uncommitted edit, data directory or symlink target is read, and the files are the commit's +exactly. Git is told never to fetch (`GIT_NO_LAZY_FETCH`, `protocol.allow=never`), so a partial +clone's missing blob is an error, not a network request. The foundation's paths, the tool +directories, symlinks, submodules and binary blobs are not items. + +Each file lands at `code//` in the new `reference` place (the reference stratum, whose +class is `code`, a version chain per file), through `ingress/sync_repository.palace`: store every +file, retire every landed file the ref no longer has. Once a plan has stored every file it listed, +the commit is recorded as landed (`data/code/.synced`), and `overview` reports how many +commits the ref has moved past it. + +### 4.2 The instance + +`config/instances/code.toml` declares the instance `code`: no embedder, no scheduled model, no +vault, transcripts, dialogue, secrets, effectors, backup or attestation keys, and one repository, +this one, at `main`. A named instance's state lived under `/instances/`, so the +corpus instance's data ended up inside the worktree that first ran it, where removing the worktree +would remove the data. `[instance] root` now lets a named instance declare its own root: an +absolute directory that the loader refuses inside any git working tree. The code instance's is +`~/.mind-palace/instances/code`. Every namespace derives from the declared root exactly as from the +derived one, and the sharing checks (`_refuse_shared`) hold against it unchanged. The default chain +refuses the key. + +The repository is read through git alone, so the instance reads nothing any instance writes, the +default instance's data included, and starts, stops or calls no model server. + +### 4.3 Keeping it current + +Three mechanisms, by cost: + +1. `palace repo-sync`, on demand: under the instance's supervisor lock, refused beside a live + daemon. A re-run after no commit lands nothing. +2. The repository's own hooks. `.githooks/post-commit` already observes every commit on main for + the code sensor; a pull that fast-forwards main commits nothing locally, so + `.githooks/post-merge` now runs `repo-sync --if-landed` after every merge or pull on main, and + the post-commit hook does the same after a commit there. `--if-landed` opens nothing until the + instance has landed once, so its first sync stays the operator's, and a failed sync never blocks + the merge. +3. In a daemon that embeds (the default instance with the code switch of §5), the `repository_sync` + kind runs at housekeeping cadence and at startup in place of the code embed lane. + +The hook is the recommendation: main moves only by a merge or a commit, the hook runs exactly +then, it needs no service, and its cost is the incremental sync of §6.2. A watcher on the +repository would wake on every working-tree write, and a timer would sync on a schedule unrelated +to the commits. + +### 4.4 Serving it to an agent + +The MCP server runs against the instance by its overlay: + + MIND_PALACE_OVERLAY=config/instances/code.toml uv run --project python /scripts/palace_mcp.py + +The read is the one `query` tool; a lookup is `top 5 near "" over reference`, `read +"code//"`, `trace "code//"`. The server's write tools spool requests that +no daemon of this instance lands; the read-only principal of the parallel guest work removes them +from the tool list once it merges. + +## 5. The default instance's code, without embedding + +Once this merges, the default instance can land its own code lexically while its notes keep their +vectors. The lines, in its per-machine overlay: + + [ingestion.code] + enabled = true + embed = false + +With no repository declared, the source is the checkout at `main`, named after its directory. The +daemon then runs `repository_sync` at housekeeping cadence and at startup instead of the embed +lane and its history backfill; the plane gets no code row and the embedder no code text. + +## 6. Measurements + +Recorded in `docs/experiments/palace-lite-2026-11-09.md`, aggregates only. + +### 6.1 Ingestion + +On this machine with nothing else busy (one-minute load 1.8 to 2.2), through the CLI with the +interpreter's start included: + +| run | effects | wall s | peak RSS MB | +|---|---|---|---| +| full ingestion of the repository | 2,015 files landed | 10.9 | 271 | +| again, no commit | all unchanged | 2.5 | 215 | +| after one commit (six files) | 6 landed | 2.6 | 217 | + +The instance at `main` holds 2,021 files as 27,235 lexical units (2.5 million postings over 46,239 +terms) in 112 MB of stores: the lexical index 86.6 MB, the raw store 22.4 MB, everything else under +4 MB, and no vector store. The lexical stage is two thirds of a full ingestion (7.4 of 10.9 s); a +sync that lands nothing spends 0.47 s in the writer and the rest starting up, evaluating the script +and reading the tree through git. + +### 6.2 Lookups against ripgrep + +Eleven questions with answers declared before the first run, asked as `top 5 near "" over +reference`, against the pattern an agent would give ripgrep over a checkout of the same commit: + +- the palace ranks a correct file in its top five for 8 of 11 (rank 1 once, 2 five times, 3 and 4 + once each); ripgrep's output holds a correct file for all 11, and prints a median of 8 files, + from 1 for an exact definition to 18 for a phrase; +- median latency, warm: the palace 163 ms, ripgrep 50 ms; the first query of a process 707 ms; +- what outranks an answer is the text that talks about it most: tests, which name the identifiers + they exercise, then design notes and papers. The three misses are of that kind (the drain's laws, + the module that computes the spectral gap, the module that takes the supervisor lock); +- a file's history: `trace` gives the versions the instance has landed (one, for a file unchanged + since the first sync), where `git log` gives every commit (nine). + +### 6.3 The MCP server + +Spawned as an MCP client spawns it, over the instance: `initialize` answered 0.71 s after the +spawn, the first `query` at 1.30 s, a second at 1.48 s (medians of five); peak resident memory 168 +MB. No vector store, embedder or model client is constructed. + +## 7. Proposed next steps (not built) + +### 7.1 One shared embedding service + +The instances that want vectors share one embedder through a service with a queue in front of the +server, so that no instance owns the embedder and none can starve another. + +- **Priorities.** Three classes, served in order: an interactive query's text (one short input, a + person or an agent waiting), a landing's chunks (an item lands lazily and waits only for its + vector), and a backfill (the drain over a corpus, a re-embedding after a model change). A higher + class preempts at the batch boundary, never inside a request. The measured server takes one + stream of 64 chunks at 26 chunks a second and gains at most 15% per added stream while every + other caller's latency grows by the queue in front of it, so the service keeps one stream for the + lower classes and reserves a slot for queries. +- **Per-instance fairness.** Within a class, instances are served by deficit round robin over + their queues, weighted by a declared share, so a corpus backfill of a hundred million chunks + cannot hold the embedder from another instance's landing for days. +- **Backpressure.** Each class has a bounded queue. A query past its bound is answered lexically + and labelled, as the profile here already does; a landing past its bound lands lazily and its + vector waits for the drain; a backfill past its bound is told to retry after the queue drains. + Nothing blocks a writer. +- **Identity.** Each request carries the embedder fingerprint the instance's plane records (model, + template, dimension), and the service refuses a mismatch, so two instances sharing a server + never mix geometries. + +### 7.2 A slim install for small devices + +The lite profile needs SQLite, NumPy and git, and no LanceDB, no model client and no embedder. A +slim install would make the vector store and the model clients optional extras of the package, so +that a device with a gigabyte of memory runs the code or notes instance of this note, its own +lexical index, and asks the shared embedding service of §7.1 over the network when it wants a +vector. The measured footprint of §6 is the budget. + +### 7.3 What the code instance does not do yet + +- **Identifiers split.** The tokenizer splits on underscores, so `embed_fitting` is the two terms + `embed` and `fitting`. A code tokenizer that also keeps the whole identifier would sharpen + definition lookups; it waits for the tokenizer identity of the embedder study's branch, so the two + changes to the tokenizer do not collide. +- **No citation graph.** The code sensor derives the import and citation edges per commit over the + whole history; on the default instance that ledger is several gigabytes. A head-only observation + of the code instance's repository would give `reach F` its edges at the landed commit. +- **History from the first sync.** `trace` shows the versions the instance landed, one per sync + that changed a file; git's history before the first sync stays git's. +- **`over reference` must be said.** `near` with no `over` reads the mirror by the precedents, and a + code instance has no mirror; an instance's own default strata would remove the need. + +## 8. Laws + +No law changes. ING-19 is the landing of every store here, with the drain never asked; ING-20 and +ING-21 have no pending item to speak of in an instance that embeds nothing; the writer's rules R1 +to R8 hold for the `reference` place as for the others, the repository source owning its space +(R8) and retiring only what its ref no longer has (R7). diff --git a/docs/experiments/palace-lite-2026-11-09.json b/docs/experiments/palace-lite-2026-11-09.json new file mode 100644 index 00000000..55459dc4 --- /dev/null +++ b/docs/experiments/palace-lite-2026-11-09.json @@ -0,0 +1,303 @@ +{ + "full": { + "wall_s": 10.94, + "peak_rss_mb": 271.0, + "effects": "{'landed': 2015}", + "stages_s": "{'admit': 0.273, 'derive': 0.991, 'index': 7.352, 'finish': 0.687}" + }, + "noop": { + "wall_s": 2.53, + "peak_rss_mb": 215.4, + "effects": "{'unchanged': 2015}", + "stages_s": "{'admit': 0.474, 'derive': 0.0, 'index': 0.0, 'finish': 0.0}" + }, + "incremental": { + "wall_s": 2.61, + "peak_rss_mb": 217.0, + "effects": "{'unchanged': 2010, 'landed': 6}", + "stages_s": "{'admit': 0.488, 'derive': 0.005, 'index': 0.08, 'finish': 0.005}" + }, + "to_head": { + "wall_s": 2.58, + "peak_rss_mb": 219.8, + "effects": "{'unchanged': 2015, 'landed': 6}", + "stages_s": "{'admit': 0.473, 'derive': 0.003, 'index': 0.063, 'finish': 0.005}" + }, + "store_mb": { + "attestations.sqlite": 1.56, + "code": 0.0, + "edges.sqlite": 0.02, + "lexical.sqlite": 86.57, + "lexical.sqlite-shm": 0.03, + "lexical.sqlite-wal": 0.0, + "query_log.jsonl": 0.0, + "raw": 22.38, + "reference_edges.sqlite": 0.03, + "runs.sqlite": 0.01, + "supervisor.lock": 0.0, + "tasks.sqlite": 0.02, + "vault_catalog.sqlite": 0.88, + "vault_catalog.sqlite-shm": 0.03, + "vault_catalog.sqlite-wal": 0.0, + "versions.sqlite": 0.55 + }, + "store_total_mb": 112.1, + "items_active": 2021, + "lexical_units": 27235, + "lexical_units_current": 27059, + "postings": 2496241, + "terms": 46239, + "raw_mb": 22.4, + "lookups": { + "lookups": [ + { + "id": "define", + "question": "where is `embed_fitting` defined", + "palace_top": [ + "tests/unit/test_embedder_fit.py", + "core/ingest/embed.py", + "tests/integration/test_two_phase_ingestion.py", + "core/ingest/derive.py", + "core/ingest/ingress.py" + ], + "palace_rank": 2, + "palace_cold_ms": 707.040874985978, + "palace_warm_ms": 156.56500007025898, + "rg_files": 1, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 50.448874942958355 + }, + { + "id": "unchanged", + "question": "where does the writer's UNCHANGED check live", + "palace_top": [ + "docs/design-notes/dn-two-phase-ingestion.md", + "core/ingest/writer.py", + "docs/build-plans/bp-082/journal.md", + "eval/ingress_gas.py", + "tests/integration/test_factory_mint.py" + ], + "palace_rank": 2, + "palace_cold_ms": 161.2649168819189, + "palace_warm_ms": 158.65491703152657, + "rg_files": 18, + "rg_hit": true, + "rg_rank": 4, + "rg_ms": 50.44266697950661 + }, + { + "id": "note", + "question": "which note describes landing without vectors", + "palace_top": [ + "docs/design-notes/dn-two-phase-ingestion.md", + "papers/2026-11-07-two-phase-ingestion/paper.tex", + "formal/Palace/Derived/Defs.lean", + "formal/Spec/Derived.lean", + "README.md" + ], + "palace_rank": 1, + "palace_cold_ms": 330.87029214948416, + "palace_warm_ms": 321.59133395180106, + "rg_files": 1, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 8.185707964003086 + }, + { + "id": "laws", + "question": "which laws govern the embed drain", + "palace_top": [ + "docs/design-notes/dn-two-phase-ingestion.md", + "formal/Spec/Derived.lean", + "formal/Palace/Derived.lean", + "ops/lifecycle/launcher.py", + "papers/2026-11-07-two-phase-ingestion/paper.tex" + ], + "palace_rank": null, + "palace_cold_ms": 291.51158407330513, + "palace_warm_ms": 282.1265000384301, + "rg_files": 14, + "rg_hit": true, + "rg_rank": 5, + "rg_ms": 52.83058318309486 + }, + { + "id": "imports", + "question": "which files import core.ingest.writer", + "palace_top": [ + "core/ingest/writer.py", + "core/ingest/ingress.py", + "core/ingest/derive.py", + "eval/ingress_gas.py", + "tests/integration/test_ingress_scripts.py" + ], + "palace_rank": 2, + "palace_cold_ms": 274.5367500465363, + "palace_warm_ms": 272.24324992857873, + "rg_files": 8, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 52.47145798057318 + }, + { + "id": "spectral", + "question": "which code computes the spectral gap", + "palace_top": [ + "tests/unit/test_lexical_index.py", + "docs/LAWS.md", + "papers/2026-11-07-scale-study/paper.tex", + "papers/2026-11-07-graph-dynamics/paper.tex", + "formal/Palace/Gap.lean" + ], + "palace_rank": null, + "palace_cold_ms": 109.54366717487574, + "palace_warm_ms": 105.32041708938777, + "rg_files": 6, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 29.690958093851805 + }, + { + "id": "bm25", + "question": "where is the BM25 term weight computed", + "palace_top": [ + "tests/unit/test_lexical_index.py", + "core/ingest/lexical.py", + "core/stores/lexical.py", + "papers/2026-11-07-two-phase-ingestion/refs.bib", + "papers/2026-11-07-two-phase-ingestion/paper.tex" + ], + "palace_rank": 2, + "palace_cold_ms": 154.9561668653041, + "palace_warm_ms": 147.1958749461919, + "rg_files": 14, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 52.48079192824662 + }, + { + "id": "root", + "question": "where is the instance root resolved", + "palace_top": [ + "tests/unit/test_install_root.py", + "core/kernel/config/root.py", + "papers/2026-11-07-profiling-and-packaging/paper.tex", + "tests/integration/test_ouroboros_only_tools.py", + "core/kernel/config/loader.py" + ], + "palace_rank": 2, + "palace_cold_ms": 224.47087499313056, + "palace_warm_ms": 197.67195917665958, + "rg_files": 7, + "rg_hit": true, + "rg_rank": 2, + "rg_ms": 54.08595805056393 + }, + { + "id": "lean", + "question": "which Lean file proves the script firewall", + "palace_top": [ + "papers/2026-11-07-ingress-language/paper.tex", + "formal/Spec/Script.lean", + "formal/Palace/Script.lean", + "docs/build-plans/bp-110/journal.md", + "docs/findings/finding-0185.md" + ], + "palace_rank": 3, + "palace_cold_ms": 168.01349981687963, + "palace_warm_ms": 163.2045421283692, + "rg_files": 3, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 9.132000152021646 + }, + { + "id": "lock", + "question": "where is the supervisor lock taken", + "palace_top": [ + "tests/unit/test_supervisor_lock.py", + "docs/build-plans/bp-108/plan.md", + "tests/unit/test_instance_identity.py", + "tests/unit/test_restart_trustworthy.py", + "scripts/watch.py" + ], + "palace_rank": null, + "palace_cold_ms": 157.0644578896463, + "palace_warm_ms": 148.80112512037158, + "rg_files": 14, + "rg_hit": true, + "rg_rank": 5, + "rg_ms": 50.39691715501249 + }, + { + "id": "rrf", + "question": "which constant does reciprocal rank fusion use", + "palace_top": [ + "papers/2026-11-07-two-phase-ingestion/paper.tex", + "papers/2026-11-07-corpus-stage1/paper.tex", + "tests/unit/test_lexical_index.py", + "core/ingest/lexical.py", + "papers/2026-11-07-two-phase-ingestion/refs.bib" + ], + "palace_rank": 4, + "palace_cold_ms": 198.44724982976913, + "palace_warm_ms": 192.61200004257262, + "rg_files": 12, + "rg_hit": true, + "rg_rank": 1, + "rg_ms": 52.527416963130236 + } + ], + "history": { + "id": "history", + "question": "the commit history of core/ingest/writer.py", + "palace_versions": 1, + "palace_ms": 9.0, + "git_commits": 9, + "git_ms": 23.8 + }, + "palace_hits_at_5": 8, + "rg_hits": 11, + "n": 11, + "rg_files_median": 8, + "palace_warm_ms_median": 163.2, + "rg_ms_median": 50.4 + }, + "mcp": { + "initialize": 0.711, + "query_1": 1.304, + "query_2": 1.481, + "peak_rss_mb": 168.141 + }, + "load": [ + "full-start 19:28:22 load { 2.15 3.25 3.43 }", + "full-end 19:28:33 load { 2.04 3.17 3.40 }", + "noop-end 19:28:36 load { 2.04 3.17 3.40 }", + "incr-end 19:28:38 load { 1.96 3.13 3.39 }", + "head-end 19:28:41 load { 1.96 3.13 3.39 }", + "lookups-end 19:28:58 load { 1.82 3.04 3.35 }", + "mcp-end 19:29:06 load { 1.77 2.99 3.33 }" + ], + "real_instance": { + "wall_s": 10.86, + "peak_rss_mb": 271.0, + "files": 2021, + "commit": "2b500e5e", + "du_mb": 126, + "stages_s": { + "admit": 0.261, + "derive": 0.96, + "index": 7.456, + "finish": 0.611 + }, + "load": "1.78 2.91 3.29 before, 1.74 2.87 3.27 after" + }, + "machine": "Apple M2 Pro, 32 GB, macOS; Python 3.15; ripgrep 15.2.0; git via the system's", + "source": { + "repository": "this repository, a local clone", + "full_at": "a91ec39e", + "incremental_commit": "6b8d472b (6 files changed or added)", + "head": "2b500e5e" + } +} diff --git a/docs/experiments/palace-lite-2026-11-09.md b/docs/experiments/palace-lite-2026-11-09.md new file mode 100644 index 00000000..8a770775 --- /dev/null +++ b/docs/experiments/palace-lite-2026-11-09.md @@ -0,0 +1,94 @@ +# The lite palace: a code instance with no embedder (2026-11-09) + +Measurements for `docs/design-notes/dn-palace-lite.md`. Aggregates only; the raw record is +`palace-lite-2026-11-09.json`. + +## Setup + +- Machine: Apple M2 Pro, 32 GB, macOS; Python 3.15; ripgrep 15.2.0. +- Source: this repository, through a local clone, so that one commit could be replayed. The full + ingestion ran at `a91ec39e` (2,015 files after exclusions), the incremental after advancing the + clone's `main` by one real commit, `6b8d472b` (five files changed, one added), then to `2b500e5e` + (three more commits, six files). The lookups ran at `2b500e5e`, the commit the answers were read + at. +- Instance: `config/instances/code.toml`'s settings with the root and the repository path moved + into a scratch directory; no embedder, no plane, no model. Each sync is the CLI's + `uv run scripts/palace.py repo-sync` under `/usr/bin/time -l`, so the wall time includes uv's + environment check and the interpreter's start. +- Load: every timed run waited for a window with no process above 30% CPU but the window server + and a one-minute load under 3.5; the one-minute load during the runs was 1.8 to 2.2. Two other + agents' formal checks and test suites ran before and after the window, never during it. +- The lookups' sentences and ripgrep patterns were fixed before the first run and not tuned + after it (`eval/palace_lite.py`). + +## Ingestion + +| run | effects | wall s | peak RSS MB | writer stages s (admit, derive, index, finish) | +|---|---|---|---|---| +| full, `a91ec39e` | 2,015 landed | 10.94 | 271.0 | 0.27, 0.99, 7.35, 0.69 | +| again, no commit | 2,015 unchanged | 2.53 | 215.4 | 0.47, 0, 0, 0 | +| one commit, `6b8d472b` | 6 landed, 2,010 unchanged | 2.61 | 217.0 | 0.49, 0.005, 0.08, 0.005 | +| three commits, `2b500e5e` | 6 landed, 2,015 unchanged | 2.58 | 219.8 | 0.47, 0.003, 0.06, 0.005 | +| the real instance, `2b500e5e` | 2,021 landed | 10.86 | 271.0 | 0.26, 0.96, 7.46, 0.61 | + +At `2b500e5e` the instance holds 2,021 active items, 27,235 lexical units (27,059 current), +2,496,241 postings over 46,239 terms. Its stores take 112.1 MB of file bytes: the lexical index +86.6 MB, the raw store 22.4 MB, the attestations 1.6 MB, the catalog 0.9 MB, the versions 0.55 MB, +the rest under 0.1 MB each; no vector store exists. The real instance's root measures 126 MB with +`du`, which counts allocated blocks. + +The lexical stage is two thirds of a full ingestion: one transaction of 27,000 units and 2.5 +million postings. A sync that lands nothing still reads every blob of the tree and checks every +file's key and units: 0.47 s in the writer, the rest of its 2.5 s the interpreter's start, the +evaluation of the script and git. + +## Lookups against ripgrep + +The palace is asked `top 5 near "" over reference` in one process over the instance's +stores (cold: the first time; warm: the median of five more). Ripgrep is asked the pattern an agent +would type, `rg -l --sort path `, over the clone's checkout, the median of five. A hit for +the palace is a correct file in its top five; for ripgrep, a correct file among those it prints, +which are what an agent must then open. + +| lookup | palace rank | palace warm ms | palace cold ms | rg files | rg holds it | rg ms | +|---|---|---|---|---|---|---| +| where is `embed_fitting` defined | 2 | 157 | 707 | 1 | yes | 50 | +| where does the writer's UNCHANGED check live | 2 | 159 | 161 | 18 | yes | 50 | +| which note describes landing without vectors | 1 | 322 | 331 | 1 | yes | 8 | +| which laws govern the embed drain | miss | 282 | 292 | 14 | yes | 53 | +| which files import `core.ingest.writer` | 2 | 272 | 275 | 8 | yes | 52 | +| which code computes the spectral gap | miss | 105 | 110 | 6 | yes | 30 | +| where is the BM25 term weight computed | 2 | 147 | 155 | 14 | yes | 52 | +| where is the instance root resolved | 2 | 198 | 224 | 7 | yes | 54 | +| which Lean file proves the script firewall | 3 | 163 | 168 | 3 | yes | 9 | +| where is the supervisor lock taken | miss | 149 | 157 | 14 | yes | 50 | +| which constant reciprocal rank fusion uses | 4 | 193 | 198 | 12 | yes | 53 | +| the commit history of `core/ingest/writer.py` | 1 version | 9 | | 9 commits (`git log`) | | 24 | + +The palace ranks a correct file in its top five for 8 of the 11 lookups; ripgrep's output holds one +for all 11 and prints a median of 8 files. Median warm latency: the palace 163 ms, ripgrep 50 ms. +The first query of the process took 707 ms (the stores opened); the others were within a few +milliseconds of their warm times. + +What outranks the answer is the text that talks about it most. Where a correct file came +second, the first was a test in three of five lookups (a test names the identifiers it exercises +more often than the module that defines them), the design note in one, and in the import lookup the +imported module itself. The misses are of the same kind: for the drain's laws the design note and +the Lean files outrank `docs/LAWS.md`; for the supervisor lock its tests and plans outrank +`ops/lifecycle/lock.py`; for the spectral gap a test, `docs/LAWS.md` and two papers outrank the +module that computes it. That last answer was declared before the run as `core/graph/influence.py` +alone; the palace's fifth hit, `formal/Palace/Gap.lean`, is the Lean proof of the spectral-gap +lemma, which a broader reading of "code about the spectral gap" would count (9 of 11). Ripgrep +never misses a pattern it is given, but an agent must know the pattern and open what it prints: +one file when the pattern is an exact definition, 14 to 18 when it is a phrase. + +The file's history is a limit of the instance, not of the lookup: `trace` shows the versions the +instance has landed, one per sync that changed the file, and this instance began at `a91ec39e`. + +## The MCP server + +Spawned five times as an MCP client spawns it (`uv run --project python +scripts/palace_mcp.py` with the instance's overlay), timed from the spawn: `initialize` answered at +0.71 s, the first `query` at 1.30 s, a second at 1.48 s (medians). Peak resident memory of the +server's process tree: 168 MB. The server never opened a vector store, an embedder or a model +client (the integration tests make constructing any of them fail). diff --git a/eval/palace_lite.py b/eval/palace_lite.py new file mode 100644 index 00000000..bb5cfec8 --- /dev/null +++ b/eval/palace_lite.py @@ -0,0 +1,251 @@ +"""Lookups through a code instance against ripgrep (docs/design-notes/dn-palace-lite.md). + + MIND_PALACE_OVERLAY= uv run python -m eval.palace_lite \ + --checkout [--runs 5] [--out PATH] + MIND_PALACE_OVERLAY= uv run python -m eval.palace_lite --mcp [--runs 5] + +Each lookup is a question with a known answer, the files that hold it. The palace is asked a +sentence through the sentence engine (`top 5 near "" over reference`, or `trace`), in this +process over the instance's own stores, as the MCP server asks it: the first time (cold, the +engine's stores opened by that call) and then `--runs` more times (warm, the median reported). +Ripgrep is asked the pattern an agent would type, over the checkout, its files sorted by path; +its wall time is the median of `--runs`. A lookup is a hit for the palace when an answer is among +the top 5 files it ranks, and for ripgrep when an answer is among the files it prints; the files +ripgrep prints are how many an agent must open, since ripgrep filters and does not rank. Only +paths, counts and times leave the run. + +`--mcp` measures the MCP server over the instance as a client meets it: the command an MCP client +runs is spawned under `/usr/bin/time -l`, and the times from the spawn to the `initialize` answer, +to the first `query` answer and to a second one are taken, then the peak resident memory of the +server's process tree when its input closes; `--runs` spawns, the medians reported. +""" + +from __future__ import annotations + +import argparse +import json +import os +import statistics +import subprocess +import sys +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # repo root on path + + +@dataclass(frozen=True) +class Lookup: + id: str + question: str + sentence: str # `{space}` is the repository's item space, `code//` + rg: tuple[str, ...] # ripgrep's arguments after `rg -l --sort path` + answers: frozenset[str] # repository-relative paths that answer it + + +LOOKUPS: tuple[Lookup, ...] = ( + Lookup("define", "where is `embed_fitting` defined", + 'top 5 near "def embed_fitting" over reference', ("def embed_fitting",), + frozenset({"core/ingest/embed.py"})), + Lookup("unchanged", "where does the writer's UNCHANGED check live", + 'top 5 near "writer UNCHANGED check" over reference', ("UNCHANGED check",), + frozenset({"core/ingest/writer.py"})), + Lookup("note", "which note describes landing without vectors", + 'top 5 near "landing an item without its vector" over reference', + ("-i", "without (its|a) vector", "docs/design-notes"), + frozenset({"docs/design-notes/dn-two-phase-ingestion.md"})), + Lookup("laws", "which laws govern the embed drain", + 'top 5 near "laws of the embed drain" over reference', ("-i", "embed drain"), + frozenset({"docs/LAWS.md"})), + Lookup("imports", "which files import core.ingest.writer", + 'top 5 near "from core.ingest.writer import" over reference', + ("from core.ingest.writer import",), + frozenset({"core/ingest/ingress.py", "eval/ingress_gas.py", "scheduler/interface.py", + "tests/fixtures/ingress.py", + "tests/integration/test_ambassador_conversation.py", + "tests/integration/test_corpus_ingest.py", + "tests/integration/test_ingress_scripts.py", "tests/unit/test_ingress.py"})), + Lookup("spectral", "which code computes the spectral gap", + 'top 5 near "spectral gap" over reference', ("-i", "spectral gap", "--type", "py"), + frozenset({"core/graph/influence.py"})), + Lookup("bm25", "where is the BM25 term weight computed", + 'top 5 near "BM25 term weight" over reference', ("-i", "bm25"), + frozenset({"core/ingest/lexical.py"})), + Lookup("root", "where is the instance root resolved", + 'top 5 near "instance root resolution rule" over reference', ("-i", "instance root"), + frozenset({"core/kernel/config/root.py"})), + Lookup("lean", "which Lean file proves the script firewall", + 'top 5 near "firewall_store theorem" over reference', ("firewall_store", "formal"), + frozenset({"formal/Palace/Script.lean"})), + Lookup("lock", "where is the supervisor lock taken", + 'top 5 near "supervisor lock acquire" over reference', ("SupervisorLock",), + frozenset({"ops/lifecycle/lock.py"})), + Lookup("rrf", "which constant does reciprocal rank fusion use", + 'top 5 near "reciprocal rank fusion constant" over reference', + ("-i", "reciprocal rank"), frozenset({"core/ingest/lexical.py"})), +) +# The file's history: the palace answers with the versions it landed, git with every commit. +HISTORY = ("history", "the commit history of core/ingest/writer.py", + 'trace "{space}core/ingest/writer.py"', "core/ingest/writer.py") + + +@dataclass +class Result: + id: str + question: str + palace_top: list[str] = field(default_factory=list) + palace_rank: int | None = None + palace_cold_ms: float = 0.0 + palace_warm_ms: float = 0.0 + rg_files: int = 0 + rg_hit: bool = False + rg_rank: int | None = None + rg_ms: float = 0.0 + + +def _ask(engine: Any, sentence: str, log: Any) -> list[str]: + from core.sentence.surface import ask_logged, sentence_grant + + answer = ask_logged(sentence, sentence_grant(), surface="eval", role="ambassador", + engine=engine, log=log) + return [h.ref for h in answer.hits] + + +def _ms(f: Any, runs: int) -> tuple[Any, float]: + out, times = None, [] + for _ in range(runs): + t = time.perf_counter() + out = f() + times.append((time.perf_counter() - t) * 1000) + return out, statistics.median(times) + + +def run(checkout: Path, runs: int) -> dict[str, Any]: + from core.kernel.config import get_config + from core.query import QueryEngine + from core.sentence.surface import QueryLog + + cfg = get_config() + space = f"code/{cfg.ingestion.code.repositories[0].name}/" + log = QueryLog(Path(os.devnull)) + engine = QueryEngine(config=cfg) + results = [] + for lk in LOOKUPS: + r = Result(lk.id, lk.question) + t = time.perf_counter() + refs = _ask(engine, lk.sentence, log) + r.palace_cold_ms = (time.perf_counter() - t) * 1000 + refs, r.palace_warm_ms = _ms(lambda lk=lk: _ask(engine, lk.sentence, log), runs) + r.palace_top = [x.removeprefix(space) for x in refs[:5]] + r.palace_rank = next((i + 1 for i, x in enumerate(r.palace_top) if x in lk.answers), + None) + done, r.rg_ms = _ms(lambda lk=lk: subprocess.run( + ["rg", "-l", "--sort", "path", *lk.rg], cwd=checkout, capture_output=True, + text=True), runs) + files = done.stdout.split() + r.rg_files = len(files) + r.rg_hit = any(f in lk.answers for f in files) + r.rg_rank = next((i + 1 for i, f in enumerate(files) if f in lk.answers), None) + results.append(r) + hid, question, sentence, path = HISTORY + t = time.perf_counter() + chains = _ask(engine, sentence.format(space=space), log) + trace_ms = (time.perf_counter() - t) * 1000 + versions = (chains[0].count("→D→") + 1) if chains else 1 + done, git_ms = _ms(lambda: subprocess.run(["git", "log", "--oneline", "--", path], + cwd=checkout, capture_output=True, text=True), runs) + history = {"id": hid, "question": question, "palace_versions": versions, + "palace_ms": round(trace_ms, 1), "git_commits": len(done.stdout.splitlines()), + "git_ms": round(git_ms, 1)} + hits = sum(1 for r in results if r.palace_rank is not None) + rg_hits = sum(1 for r in results if r.rg_hit) + return {"lookups": [asdict(r) for r in results], "history": history, + "palace_hits_at_5": hits, "rg_hits": rg_hits, "n": len(results), + "rg_files_median": statistics.median(r.rg_files for r in results), + "palace_warm_ms_median": round(statistics.median(r.palace_warm_ms + for r in results), 1), + "rg_ms_median": round(statistics.median(r.rg_ms for r in results), 1)} + + +MCP_QUERY = 'top 5 near "writer UNCHANGED check" over reference' + + +def mcp_once(command: list[str]) -> dict[str, float]: + """One spawn of the MCP server: seconds to `initialize`, to the first and second `query` + answers, and the peak resident megabytes of its process tree.""" + def call(i: int, method: str, params: dict[str, Any]) -> str: + return json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + "\n" + + query: dict[str, Any] = {"name": "query", "arguments": {"sentence": MCP_QUERY}} + steps: list[tuple[str, str, dict[str, Any]]] = [ + ("initialize", "initialize", {"protocolVersion": "2025-06-18"}), + ("query_1", "tools/call", query), ("query_2", "tools/call", query)] + t0 = time.perf_counter() + p = subprocess.Popen(["/usr/bin/time", "-l", *command], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + assert p.stdin is not None and p.stdout is not None and p.stderr is not None + out: dict[str, float] = {} + for i, (name, method, params) in enumerate(steps, start=1): + p.stdin.write(call(i, method, params)) + p.stdin.flush() + reply = json.loads(p.stdout.readline()) + assert "result" in reply and not reply["result"].get("isError"), reply + out[name] = time.perf_counter() - t0 + p.stdin.close() + err = p.stderr.read() + p.wait() + rss = next(int(line.split()[0]) for line in err.splitlines() + if "maximum resident set size" in line) + out["peak_rss_mb"] = rss / 2**20 + return out + + +def mcp(runs: int) -> dict[str, float]: + """The MCP server's medians over `runs` spawns, as `uv run` starts it from this checkout.""" + root = Path(__file__).resolve().parent.parent + command = ["uv", "run", "--project", str(root), "python", str(root / "scripts" / + "palace_mcp.py")] + spawns = [mcp_once(command) for _ in range(runs)] + return {k: round(statistics.median(s[k] for s in spawns), 3) for k in spawns[0]} + + +def table(report: dict[str, Any]) -> str: + rows = ["| lookup | palace rank (top 5) | palace warm ms | palace cold ms | rg files | " + "rg holds it | rg ms |", "|---|---|---|---|---|---|---|"] + for r in report["lookups"]: + rows.append(f"| {r['question']} | {r['palace_rank'] or 'miss'} | " + f"{r['palace_warm_ms']:.0f} | {r['palace_cold_ms']:.0f} | {r['rg_files']} | " + f"{'yes' if r['rg_hit'] else 'no'} | {r['rg_ms']:.0f} |") + h = report["history"] + rows.append(f"| {h['question']} | {h['palace_versions']} version(s) | {h['palace_ms']:.0f} | " + f"| {h['git_commits']} commits (git log) | | {h['git_ms']:.0f} |") + return "\n".join(rows) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--checkout", type=Path) + ap.add_argument("--runs", type=int, default=5) + ap.add_argument("--out", type=Path) + ap.add_argument("--mcp", action="store_true") + args = ap.parse_args() + if args.mcp: + print(json.dumps(mcp(args.runs))) + return 0 + if args.checkout is None: + ap.error("--checkout is required for the lookups") + report = run(args.checkout, args.runs) + if args.out: + args.out.write_text(json.dumps(report, indent=1) + "\n") + print(table(report)) + print(f"\npalace hits at 5: {report['palace_hits_at_5']}/{report['n']}; ripgrep holds the " + f"answer: {report['rg_hits']}/{report['n']}; median files ripgrep prints: " + f"{report['rg_files_median']}; median warm ms: palace " + f"{report['palace_warm_ms_median']}, ripgrep {report['rg_ms_median']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ingress/sync_repository.palace b/ingress/sync_repository.palace new file mode 100644 index 00000000..724aefec --- /dev/null +++ b/ingress/sync_repository.palace @@ -0,0 +1,15 @@ +# A repository's files at its ref, into the reference stratum, each at `code//`; a file +# gone from the ref is retired. The source keeps no vectors (dn-palace-lite), so each file lands +# with its lexical units, its version and its attestation, and no plane row. +param name +let repo = source("code/" + name) +let present = files(repo) +let here = paths(present) +for f in present { + store f.content in "reference" +} +for e in stored("reference", under: repo) { + if e.path not in here { + retire e.path in "reference" + } +} diff --git a/ops/lifecycle/launcher.py b/ops/lifecycle/launcher.py index 1cc67177..138693f1 100644 --- a/ops/lifecycle/launcher.py +++ b/ops/lifecycle/launcher.py @@ -488,6 +488,7 @@ def build_components(cfg: Config) -> Components: from core.ingest.code_corpus import build_code_corpus_sync from core.integrator import build_integrator from core.interface import CoreInbox + from core.kernel.config.loader import lexical_code from core.librarian import build_librarian from core.models import Registry, TwoSlotLoader from core.models.ollama_client import OllamaClient @@ -506,11 +507,13 @@ def build_components(cfg: Config) -> Components: CODE_BACKFILL_KIND, CODE_REBUILD_KIND, CODE_SYNC_KIND, + REPOSITORY_SYNC_KIND, code_backfill_handler, code_rebuild_handler, code_sync_handler, enqueue_code_backfill, enqueue_code_sync, + enqueue_repository_sync, ) from scheduler.cron import ( CHAT_EVENTS_KIND, @@ -653,6 +656,12 @@ def health_check() -> list[Flag]: # derived into the plane through the writer's own stores; registered always, ENQUEUED by # the writer after a lazy landing and by the housekeeping below under `[embedding] lazy` EMBED_KIND: embed_handler(cfg, stores=ingress_stores), + # the lexical code source (dn-palace-lite): each repository's files at its ref, landed by + # the writer with no plane row, in place of the code embed lane when the code keeps no + # vectors; ENQUEUED by the housekeeping and the catch-up below only then + REPOSITORY_SYNC_KIND: library_handler( + cfg, "sync_repository", [{"name": r.name} for r in cfg.ingestion.code.repositories], + stores=ingress_stores), } supervisor = Supervisor(queue=queue, loader=loader, handlers=handlers, telemetry=telemetry) # One watcher per watched dir: the owner's vault + the Claude Code transcripts (bp-069). Both @@ -686,7 +695,9 @@ def _housekeeping() -> None: enqueue_chat_events(queue, router) # L1 action-log projection — its delayed rate if cfg.integrate.enabled: # its own agent type — derives, never ingests (bp-071) enqueue_integrate(queue, router) # C-fiber proven edges from L1 + the ledger - if cfg.ingestion.code.enabled: # code embed lane, opt-in (bp-098 / note §2.7): + if lexical_code(cfg): # the code keeps no vectors (dn-palace-lite): its + enqueue_repository_sync(queue, router) # repositories land by the writer instead + elif cfg.ingestion.code.enabled: # code embed lane, opt-in (bp-098 / note §2.7): enqueue_code_sync(queue, router) # INCREMENTAL only; the heavy SEED is `code-seed` if cfg.embedding.lazy: # two-phase ingestion: what landed without a vector enqueue_embed(queue, router) # is derived at housekeeping cadence too (ING-20) @@ -698,7 +709,9 @@ def _catchup() -> None: enqueue_vault_sync(queue, router) # reconcile the corpus; the Job return is discarded if cfg.ingestion.transcripts.enabled: enqueue_chat_sync(queue, router) # startup backfill of every closed session (bp-068) - if cfg.ingestion.code.enabled and _code_backfill_incomplete(cfg, code_driver): + if lexical_code(cfg): + enqueue_repository_sync(queue, router) # what moved while the daemon was down + elif cfg.ingestion.code.enabled and _code_backfill_incomplete(cfg, code_driver): enqueue_code_backfill(queue, router) # history not yet fully embedded (bp-099 D1) enqueue_inbox_capture_if_waiting(queue, router, cfg) # what a crash or `talk` left @@ -828,6 +841,14 @@ 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. + 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 + # nothing has none to wire, so it runs no daemon; its sources sync on demand + print(f"refusing to start — instance {self.cfg.instance.id!r} embeds nothing " + "([embedding] enabled = false), and the daemon builds the embedder's consumers. " + "Sync it on demand: `palace repo-sync`.") + return 1 prev = self.runs.last() if prev is not None and prev.active and _supervisor_alive(prev): print(f"refusing to start — run #{prev.id} (pid {prev.pid}) is live. " @@ -1715,6 +1736,42 @@ def relate_now(self, *, max_pairs: int = 24) -> int: print(f"relate: {build_relation_detector(self.cfg, max_pairs=max_pairs).run()}") return 0 + def repo_sync_now(self) -> int: + """The lexical code source, on demand (dn-palace-lite): each repository's files at its ref + landed by the writer, a changed file a new version, a file gone from the ref retired, no + plane row written and no embedder called. Refused beside a live daemon, whose scheduler + runs the same script as its `repository_sync` job, and while another writer holds the + instance's supervisor lock.""" + from core.kernel.config.loader import lexical_code + + if not lexical_code(self.cfg): + print("repo-sync: this instance's code is not a lexical source ([ingestion.code] " + "enabled = true with embed = false, or [embedding] enabled = false)") + return 2 + if self._refuse_if_live("repo-sync"): + return 1 + from core.ingest import ingress + from ops.lifecycle.lock import SupervisorLock, SupervisorLockHeld + + lock = SupervisorLock(namespaces_of(self.cfg).supervisor_lock) + try: + lock.acquire() + except SupervisorLockHeld: + print("refusing repo-sync — another writer holds the instance's supervisor lock") + return 1 + try: + stores = ingress.build_stores(self.cfg) + for repo in self.cfg.ingestion.code.repositories: + # a first sync is a plan of fresh stores on distinct paths, which lands a stage at + # a time (`Writer.land_batch`); a later one, which retires, lands effect by effect + receipt = ingress.run_library(self.cfg, "sync_repository", {"name": repo.name}, + stores=stores, batch=True) + timing = f", seconds {receipt['timing']}" if receipt.get("timing") else "" + print(f"repo-sync ({repo.name} at {repo.ref}): {receipt['effects']}{timing}") + finally: + lock.release() + return 0 + def vault_sync_now(self) -> int: """One full vault-lane rescan, on demand: raw, vectors (chunk-level amendment), catalog, versions and attestations — the same lane the daemon's `vault_sync` job runs.""" @@ -1730,7 +1787,8 @@ def embed_now(self) -> int: daemon runs as its `embed` job under `[embedding] lazy`. A reset plane (`reembed`) leaves every item pending, so this is also the re-embedding after a model change. The lexical backfill runs first, so this is also the re-derivation of a lexical index whose tokenizer - changed.""" + changed; an instance that embeds nothing runs that backfill only, since the lexical index + is its one index.""" if self._refuse_if_live("embed"): return 1 from core.ingest import ingress @@ -1740,6 +1798,10 @@ def embed_now(self) -> int: lexical = derive_lexical(stores) # a changed tokenizer re-derives the index first if lexical.items or lexical.rederived: print(f"lexical: {lexical}") + if not cfg.embedding.enabled: + print("embed: this instance embeds nothing ([embedding] enabled = false); no vector " + "to derive") + return 0 report = drain(stores, batch=cfg.embedding.batch, streams=cfg.embedding.streams) print(f"embed: {report}") return 0 diff --git a/papers/2026-11-09-palace-lite/paper.tex b/papers/2026-11-09-palace-lite/paper.tex new file mode 100644 index 00000000..e7281982 --- /dev/null +++ b/papers/2026-11-09-palace-lite/paper.tex @@ -0,0 +1,320 @@ +% 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 measurements (docs/experiments/palace-lite-2026-11-09.md). +\newcommand{\nfiles}{2{,}021} +\newcommand{\nunits}{27{,}059} +\newcommand{\tfull}{10.9} +\newcommand{\rssfull}{271} +\newcommand{\storemb}{111} +\newcommand{\lexmb}{86} +\newcommand{\tnoop}{2.5} +\newcommand{\tincr}{2.6} +\newcommand{\nchanged}{six} +\newcommand{\hits}{8} +\newcommand{\rghits}{all 11} +\newcommand{\rgfiles}{8} +\newcommand{\qwarm}{163} +\newcommand{\rgms}{50} +\newcommand{\mcpinit}{0.71} +\newcommand{\mcpq}{1.30} +\newcommand{\mcprss}{168} +\newcommand{\runload}{with no other process above 30\% of a core and a one-minute load of 1.8 to 2.2} + +\title{A Palace Without Vectors: Lexical Ingestion of Source Repositories for a Coding Agent} +\author{Alberto Serrano-Calva} +\date{\today} + +\begin{document} +\maketitle + +\begin{abstract} +A knowledge store that lands every item through one writer can make the embedding of an item a +derived field, written after the item lands. We take the next step and make it optional: an +instance may embed nothing at all, and within an instance that embeds, a single source may keep no +vectors. The writer decides per item whether its plane rows are written before its key, deferred to +a drain, or never written, and the query engine ranks every item without a vector by a BM25 index +over the same chunks, labelling each such answer. The first deployment is a code instance that +lands the files of a git repository at a ref, read through git's object store, for a coding agent +to query over the Model Context Protocol. It ingests the \nfiles{} files of the store's own +repository (\nunits{} lexical units) in \tfull{}~s with a peak resident memory of \rssfull{}~MB and +\storemb{}~MB on disk, and re-syncs after a commit in \tincr{}~s. On eleven lookups with known +answers it ranks a correct file in its top five for \hits{}; ripgrep's output holds a correct +file for \rghits{} of them but prints a median of \rgfiles{} files to open. A query takes a median +of \qwarm{}~ms warm, against \rgms{}~ms for ripgrep, and the server answers its first query +\mcpq{}~s after it is spawned. +\end{abstract} + +\section{Introduction} + +The store this article extends is a local, private knowledge store served to language models +over the Model Context Protocol. It lands every item through one writer, in a fixed order with the +idempotence key last, and computes over its items a vector plane of chunk embeddings, a lexical +index, version chains, a citation graph between files, and signed relations between notes. A +sentence algebra reads them: \code{near} ranks by similarity, \code{reach} and \code{walk} follow +edges, \code{trace} follows versions, \code{read} returns text. + +Two-phase ingestion made an item complete without its vector: the vector is written afterwards by +a drain, and a query that needs a vector not yet written ranks the item lexically and says so. Three +costs remained for instances that need no vectors. The default instance's code was a snapshot, +because its code lane embeds every changed file and was turned off; a coding agent asking the store +about its own code read it as it was at the last snapshot, while a text search of the checkout read it as +it is. A small device cannot run an embedding server beside the store. And an instance whose job is +lookup has no use for the language model that runs the store's dreaming and relation passes. + +The contributions are: +\begin{itemize} +\item two switches, one per instance and one per source, under which items land with their lexical +units, versions and attestations and no vector, with no embedder built and no plane opened when the +whole instance embeds nothing (\cref{sec:profile}); +\item a source that is a git repository's tree at a ref, read through the object store, with a mark +of the commit landed and hooks that keep it current (\cref{sec:repo}); +\item the behaviour of every verb of the algebra without vectors (\cref{sec:verbs}); +\item measurements of a code instance over the store's own repository against ripgrep +(\cref{sec:eval}), and the design of a shared embedding service for the instances that do want +vectors (\cref{sec:future}). +\end{itemize} + +\section{Background} + +\paragraph{The writer.} A request is a script; evaluating it under a role yields a plan of effects +(store, retire, link, run), and the one writer lands the plan effect by effect. A store lands its +raw bytes, then its derived rows, then its version, its attestation and, last, its catalog key; +the UNCHANGED check reads the key and a witness that the derived rows are held, so a landing +interrupted anywhere converges when run again. Under two-phase ingestion the witness of a lazy +store is its lexical units, and the drain later writes the plane rows of every item whose current +version the plane does not hold. Keeping a derived field consistent with its source is the +classical problem of materialized view maintenance \citep{gupta1995views}; here the view is the +vector, and the question becomes whether it must exist at all. + +\paragraph{Lexical retrieval.} The lexical index holds, for every chunk of every current version, +its term counts, and scores a query by BM25 \citep{robertson2009bm25}, +\begin{equation} + s(q,d) = \sum_{t\in q} \ln\!\Big(1+\frac{n-\mathit{df}_t+\tfrac12}{\mathit{df}_t+\tfrac12}\Big) + \cdot \frac{\mathit{tf}_{t,d}\,(k_1+1)}{\mathit{tf}_{t,d}+k_1\big(1-b+b\,\tfrac{|d|}{\overline{|d|}}\big)}, +\end{equation} +with $k_1=1.2$ and $b=0.75$, the document frequencies read from the current units at query time. +BM25 remains a strong baseline against dense retrieval, and a robust one out of domain +\citep{karpukhin2020dpr,thakur2021beir}; on code, natural-language queries against identifiers are +harder for both \citep{husain2019codesearchnet}. + +\section{The lite profile}\label{sec:profile} + +\begin{definition} +For an item at path $p$ landed by a store of an instance $I$, with $S(p)$ the source whose space +holds $p$ (none for a path no source owns), +\begin{align*} + \mathrm{keeps}(p) &= I.\mathit{embeds} \wedge \big(S(p)=\bot \vee S(p).\mathit{embed}\big),\\ + \mathrm{now}(p) &= \mathrm{keeps}(p) \wedge \neg\mathit{lazy}, \qquad + \mathrm{lexical}(p) = \mathit{lazy} \vee \neg\mathrm{keeps}(p). +\end{align*} +A store writes its plane rows before its key when $\mathrm{now}(p)$; its UNCHANGED witness is the +lexical index when $\mathrm{lexical}(p)$, else the plane; and a plan asks for the drain only when it +lands an item with $\mathit{lazy}\wedge\mathrm{keeps}(p)$. +\end{definition} + +\Cref{alg:store} is the store's landing under these predicates. Only the shaded decisions are new: +the order of the stages, the key last, is the writer's as it was. + +\begin{algorithm}[t] +\caption{A store's landing}\label{alg:store} +\begin{algorithmic}[1] +\Procedure{Store}{$e$} + \State admit $e$ by the rules R1--R8; \textbf{if} UNCHANGED($e$) \textbf{return} unchanged + \State $r \gets$ raw bytes of $e$, and its chunks + \If{the lexical index is open} land the units of $r$ \EndIf + \If{$\mathrm{now}(e.\mathit{path})$} embed the atoms the plane lacks; land the plane rows \EndIf + \State record the version; attest; write the key \Comment{the key last} +\EndProcedure +\Function{Unchanged}{$e$} + \State \Return key active at $e$'s digest and label $\wedge$ + $\big(\mathrm{lexical}(e.\mathit{path})$ ? units current : plane rows current$\big)$ +\EndFunction +\end{algorithmic} +\end{algorithm} + +\begin{proposition}\label{prop:none} +In an instance with $I.\mathit{embeds}=\mathit{false}$, no landing, drain or query constructs an +embedder or a vector store, and every landing is idempotent. +\end{proposition} +\begin{proof}[Sketch] +$\mathrm{now}(p)$ is false for every $p$, so no store reaches the embedding step, and the price of a +plan charges no embedding. The stores the writer and the query engine are handed hold an empty +plane that refuses writes, and the factories that build an embedder or open a plane refuse for such +an instance, so any path that reached them would fail rather than construct one. The test suite +replaces the embedder's, the model client's and the vector store's constructors with ones that fail +the test, then lands a repository and a vault and asks \code{near}, \code{read}, \code{reach} and +\code{diffuse} of them. +$\mathrm{lexical}(p)$ is true for every $p$, so the UNCHANGED witness is the lexical index, written +before the key: a second landing of the same bytes finds key and units current and lands nothing, +and an interrupted one finds the key absent and lands again. +\end{proof} + +Within an instance that embeds, a source with $\mathit{embed}=\mathit{false}$ keeps no vectors +while every other source keeps its own: the drain's pending set is computed over the plane's +classes, and the code's class is not one of them, so the drain never derives what the source +declined. The default instance's configuration is unchanged: both switches default to embedding, +and an instance that embeds every item synchronously opens no lexical index. + +\section{A repository as a source}\label{sec:repo} + +A repository source is the tree of a commit that a ref names, read through git's object store +\citep{chacon2014progit}: one \code{rev-parse}, one \code{ls-tree}, and one \code{cat-file +--batch} process per batch of blobs. Its items are the tree's regular text files, at +\code{code//}, labelled \code{code}, landed in a place of the reference stratum that +keeps a version chain per file. Nothing outside the tree is read: no untracked file, uncommitted +edit, symlink target or data directory, and git is told never to fetch. The foundation's paths and +the tool directories are not items. The sync script stores every file and retires every landed file +the ref no longer has; once a plan has stored every file it listed, the commit is recorded as +landed, and the store reports how many commits the ref has moved past it. + +A sync reads every blob of the tree, $O(B)$ for $B$ bytes, and lands only the files whose bytes +changed, each with its new units, its next version and an attestation. Main moves only by a merge +or a commit, so the repository's own hooks keep the instance current: after every merge or pull +on main, and every commit there, the hook runs the sync if the instance has landed once. + +The code instance is a named instance with no embedder, no scheduled model, no vault, transcripts +or dialogue, and its state under a root it declares outside every checkout: a named instance's +state used to live inside the checkout that first ran it, where removing a worktree removed it. + +\section{The verbs without vectors}\label{sec:verbs} + +\begin{table}[t] +\centering\small +\begin{tabularx}{\linewidth}{@{}lX@{}} +\toprule +verb & without a vector \\ +\midrule +\code{near} & the clause's vectorless nodes ranked by BM25 on a scale of their own, each hit +labelled \code{ranked\_by}; the notes count pending and vectorless nodes apart \\ +\code{diffuse S}, \code{via S} & the backbone $S$ (cosine $\ge\sigma$) has no edge at a +vectorless node; the answer covers the nodes with vectors, and the notes say so \\ +\code{reach F}, \code{via F} & unchanged: the citation graph needs no vector \\ +\code{trace} & unchanged: one version per sync that changed the file \\ +\code{read} & unchanged: a landed file is read from the raw store by its digest \\ +\code{witness}, \code{relate} & unchanged \\ +combinators & unchanged: they compose the fields and regions above \\ +\bottomrule +\end{tabularx} +\caption{The algebra's verbs in an instance or source without vectors.}\label{tab:verbs} +\end{table} + +\Cref{tab:verbs} lists what each verb reads and what it does when an item has no vector. The +design rule is the two-phase one: a query never invents a vector. A node without one is ranked +lexically and labelled, or it is reported; the label distinguishes a pending vector, which the +drain will write, from an absent one, which nothing will. + +\section{Evaluation}\label{sec:eval} + +All runs are on one laptop (Apple M2 Pro, 32 GB), the store's own repository as the source, +\runload{}. The lookups and their known answers are in the measurement record, with the +script that repeats them. + +\paragraph{Ingestion.} The first sync of the repository at \code{main} lands \nfiles{} files as +\nunits{} lexical units in \tfull{}~s, with a peak resident memory of \rssfull{}~MB; the +instance's stores take \storemb{}~MB, of which the lexical index is \lexmb{}~MB. A second sync with +no commit lands nothing in \tnoop{}~s. After one commit that touched \nchanged{} files the sync +lands them in \tincr{}~s. The lexical stage is two thirds of a full ingestion, one transaction of +27{,}000 units and 2.5 million postings; a sync that lands nothing spends 0.47~s in the writer and +the rest starting the interpreter, evaluating the script and reading the tree through git. Times +include the interpreter's start, as an operator or a hook meets them. + +\paragraph{Lookups.} \Cref{tab:lookups} compares the palace's top five with ripgrep for eleven +questions. Ripgrep was given the pattern an agent would type; it filters rather than ranks, so its +cost is the number of files an agent must then open. + +\begin{table}[t] +\centering\small +\begin{tabular}{@{}lrrrc@{}} +\toprule +question & palace rank & palace ms & rg files & rg holds it \\ +\midrule +where is \code{embed\_fitting} defined & 2 & 157 & 1 & yes \\ +where does the writer's UNCHANGED check live & 2 & 159 & 18 & yes \\ +which note describes landing without vectors & 1 & 322 & 1 & yes \\ +which laws govern the embed drain & miss & 282 & 14 & yes \\ +which files import \code{core.ingest.writer} & 2 & 272 & 8 & yes \\ +which code computes the spectral gap & miss & 105 & 6 & yes \\ +where is the BM25 term weight computed & 2 & 147 & 14 & yes \\ +where is the instance root resolved & 2 & 198 & 7 & yes \\ +which Lean file proves the script firewall & 3 & 163 & 3 & yes \\ +where is the supervisor lock taken & miss & 149 & 14 & yes \\ +which constant reciprocal rank fusion uses & 4 & 193 & 12 & yes \\ +\midrule +median & & 163 & 8 & \\ +\bottomrule +\end{tabular} +\caption{Eleven lookups with answers declared before the run: the rank of the first correct file +in the palace's top five, its warm latency, and the files ripgrep prints for the +pattern an agent would type (median ripgrep time 50~ms).}\label{tab:lookups} +\end{table} + +The palace ranks a correct file in its top five for \hits{} of the eleven lookups, ripgrep's +output holds one for \rghits{}, and the median number of files ripgrep prints is \rgfiles{}, +from one for an exact definition to eighteen for a phrase. What outranks an answer in the palace is +the text that talks about it most: a test, which names the identifiers it exercises more often than +the module that defines them, then design notes and papers; the three misses are of that kind. One +of them was declared as the module that computes the spectral gap; the palace's fifth hit is the +Lean proof of the spectral-gap lemma, which a broader reading of the question would count. A +file's history is a limit of the instance: \code{trace} gives the versions it landed, one for a +file unchanged since its first sync, where \code{git log} gives nine commits. + +\paragraph{Serving.} Spawned as an MCP client spawns it, the server answers \code{initialize} +after \mcpinit{}~s and its first query after \mcpq{}~s, with a peak resident memory of +\mcprss{}~MB. + +\section{Limitations and future work}\label{sec:future} + +\paragraph{The lexical index on code.} The tokenizer splits identifiers at underscores, so a +definition lookup matches every use of the identifier's words; a tokenizer that also keeps the +whole identifier would sharpen it. The repository source has no citation graph yet: the code +sensor that derives import edges does so for every commit of the history, which on the default +instance is several gigabytes; observing the landed commit alone would give \code{reach F} its +edges. \code{trace} shows the versions the instance landed, not the history before its first sync. + +\paragraph{A shared embedding service.} The instances that do want vectors should share one +embedder through a queue in front of the server: three priority classes (an interactive query's +text, a landing's chunks, a backfill), a higher class preempting at the batch boundary; within a +class, deficit round robin over the instances \citep{shreedhar1996drr}, a fair queueing discipline +\citep{demers1989fq}, so a corpus backfill cannot hold the embedder from another instance's +landing; a bounded queue per class, past which a query is answered lexically, a landing lands +lazily and a backfill retries later, so nothing blocks a writer; and the embedder's fingerprint on +every request, so two instances never mix geometries. + +\paragraph{A slim install.} The profile needs SQLite, NumPy and git, and no vector store or model +client, so those can become optional extras of the package, and a one-gigabyte device can run a +code or notes instance with its own lexical index, asking the shared service for vectors when it +wants them. + +\section{Conclusion} + +Making the vector derived made it deferrable; one more predicate in the writer makes it optional, +per instance and per source, with the same landing order, the same idempotence and the same +labelled fallback in the queries. A code instance built on it lands a repository in seconds with +no model of any kind, stays current through the repository's hooks, and answers an agent's lookups +with a ranked handful of files where a text search returns dozens. + +\bibliographystyle{plainnat} +\bibliography{refs} +\end{document} diff --git a/papers/2026-11-09-palace-lite/refs.bib b/papers/2026-11-09-palace-lite/refs.bib new file mode 100644 index 00000000..b9e61b5f --- /dev/null +++ b/papers/2026-11-09-palace-lite/refs.bib @@ -0,0 +1,68 @@ +@article{robertson2009bm25, + author = {Robertson, Stephen and Zaragoza, Hugo}, + title = {The Probabilistic Relevance Framework: {BM25} and Beyond}, + journal = {Foundations and Trends in Information Retrieval}, + volume = {3}, + number = {4}, + pages = {333--389}, + year = {2009} +} + +@inproceedings{karpukhin2020dpr, + author = {Karpukhin, Vladimir and O{\u{g}}uz, Barlas and Min, Sewon and Lewis, Patrick and Wu, Ledell and Edunov, Sergey and Chen, Danqi and Yih, Wen-tau}, + title = {Dense Passage Retrieval for Open-Domain Question Answering}, + booktitle = {Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)}, + pages = {6769--6781}, + publisher = {Association for Computational Linguistics}, + year = {2020} +} + +@inproceedings{thakur2021beir, + author = {Thakur, Nandan and Reimers, Nils and R{\"u}ckl{\'e}, Andreas and Srivastava, Abhishek and Gurevych, Iryna}, + title = {{BEIR}: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models}, + booktitle = {Proceedings of the Neural Information Processing Systems Track on Datasets and Benchmarks}, + year = {2021} +} + +@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} +} + +@misc{husain2019codesearchnet, + author = {Husain, Hamel and Wu, Ho-Hsiang and Gazit, Tiferet and Allamanis, Miltiadis and Brockschmidt, Marc}, + title = {{CodeSearchNet} Challenge: Evaluating the State of Semantic Code Search}, + howpublished = {arXiv:1909.09436}, + year = {2019} +} + +@inproceedings{demers1989fq, + author = {Demers, Alan and Keshav, Srinivasan and Shenker, Scott}, + title = {Analysis and Simulation of a Fair Queueing Algorithm}, + booktitle = {Proceedings of the ACM SIGCOMM '89 Symposium on Communications Architectures and Protocols}, + pages = {1--12}, + year = {1989} +} + +@article{shreedhar1996drr, + author = {Shreedhar, M. and Varghese, George}, + title = {Efficient Fair Queuing Using Deficit Round-Robin}, + journal = {IEEE/ACM Transactions on Networking}, + volume = {4}, + number = {3}, + pages = {375--385}, + year = {1996} +} + +@book{chacon2014progit, + author = {Chacon, Scott and Straub, Ben}, + title = {Pro Git}, + edition = {2}, + publisher = {Apress}, + year = {2014} +} diff --git a/scheduler/code_sync.py b/scheduler/code_sync.py index d4924a7f..cb0089a6 100644 --- a/scheduler/code_sync.py +++ b/scheduler/code_sync.py @@ -31,6 +31,11 @@ CODE_SYNC_KIND = "code_sync" CODE_BACKFILL_KIND = "code_backfill" # the history backfill (bp-099) — sibling of code_sync CODE_REBUILD_KIND = "code_rebuild" # the D7 atom+membership rebuild (bp-153) — checkpointed +# The lexical code source (dn-palace-lite): with `[ingestion.code] embed = false`, or in an instance +# that embeds nothing, the code is each repository's files at its ref, landed by the ingress's +# writer (`ingress/sync_repository.palace`) with no plane row; this kind runs that script once a +# repository, in place of the embed lane above. +REPOSITORY_SYNC_KIND = "repository_sync" Handler = Callable[[Job], "str | None"] @@ -107,6 +112,14 @@ def handle(job: Job) -> str | None: return handle +def enqueue_repository_sync(queue: JobQueue, router: Router) -> Job: + """Enqueue one background sync of the repositories, the lexical code source. Idempotent (a + file the catalog holds at its bytes is UNCHANGED and lands nothing), so a duplicate folds into + the row waiting; model-less, so it pins and runs at BACKGROUND.""" + plan = router.plan(REPOSITORY_SYNC_KIND, priority=PRIORITY_BACKGROUND) + return queue.enqueue(plan.kind, plan.tier, plan.num_ctx, priority=plan.priority) + + def enqueue_code_rebuild(queue: JobQueue, router: Router) -> Job: """Enqueue the D7 rebuild. Same pinned-tier, BACKGROUND species as its two siblings (it is a model-less embed lane), and idempotent in the strong sense: every phase converges, so a diff --git a/scheduler/embed.py b/scheduler/embed.py index bb8e9d76..590e1ad2 100644 --- a/scheduler/embed.py +++ b/scheduler/embed.py @@ -39,10 +39,14 @@ def the_stores() -> Any: def handle(_job: Job) -> str: # the derived layers in order: the lexical units of any item the index lacks (all of - # them after a tokenizer change, which resets the index first), then the vectors + # them after a tokenizer change, which resets the index first), then the vectors. An + # instance that embeds nothing keeps the lexical index as its only index, so the backfill + # runs whatever the embedding switch says, and only the vector drain is skipped. lexical = derive_lexical(the_stores()) - report = drain(the_stores(), batch=cfg.embedding.batch, streams=cfg.embedding.streams) lexical_note = f"; lexical: {lexical}" if lexical.items or lexical.rederived else "" + if not cfg.embedding.enabled: # the lite profile: nothing has, or will have, a vector + return f"embed: this instance embeds nothing{lexical_note}" + report = drain(the_stores(), batch=cfg.embedding.batch, streams=cfg.embedding.streams) return f"embed: {report}{lexical_note}" return handle diff --git a/scheduler/queue.py b/scheduler/queue.py index afa2a294..2f02874e 100644 --- a/scheduler/queue.py +++ b/scheduler/queue.py @@ -84,7 +84,9 @@ "dialogue_sync", "inbox_capture", # the embed drain (dn-two-phase-ingestion, ING-20): idempotent at the plane, so the one row # the writer and the housekeeping enqueue folds every later request into it - "embed"}) + "embed", + # the repositories' sync (dn-palace-lite): idempotent by the writer's UNCHANGED check + "repository_sync"}) # The kinds a crash may leave RUNNING that `sweep_orphans` puts back in the queue rather than # failing: the idempotent kinds; the ingress's own kind (`core/ingest/ingress.py` INGRESS_KINDS), diff --git a/scheduler/router.py b/scheduler/router.py index 1b0478ca..9e451844 100644 --- a/scheduler/router.py +++ b/scheduler/router.py @@ -47,7 +47,9 @@ # dialogue handoff and the inbox's capture call no chat model "script", "code_observe", "dialogue_sync", "inbox_capture", # the embed drain calls the embedder directly, like `code_sync`, and no chat model - "embed"}) + "embed", + # the lexical code source's sync (dn-palace-lite): git and the writer, no model at all + "repository_sync"}) @dataclass(frozen=True) diff --git a/scripts/palace.py b/scripts/palace.py index 790d6c7d..0f3c9aef 100644 --- a/scripts/palace.py +++ b/scripts/palace.py @@ -18,6 +18,8 @@ uv run scripts/palace.py dream # on-demand: one dreaming pass (no daemon needed) uv run scripts/palace.py vault-sync # on-demand: one full vault-lane rescan (no daemon) uv run scripts/palace.py embed # on-demand: the embed drain (items landed lazily) + uv run scripts/palace.py repo-sync # on-demand: the code repositories, lexical (no vectors) + uv run scripts/palace.py repo-sync --if-landed # the same, only once it has landed (the hooks) uv run scripts/palace.py dialogue-sync # on-demand: Open WebUI chats -> the dialogue stratum uv run scripts/palace.py relate # on-demand: signed relation edges (wakes the model) uv run scripts/palace.py lanes [code-observe|code-embed|dialogue] # on-demand edge lanes @@ -54,7 +56,8 @@ USAGE = ("usage: palace.py " "{start|stop|down|up|restart|status|queue|query|reset|deploy|ingest-chat|code-seed|" - "code-backfill|code-rebuild|dream|vault-sync|embed|dialogue-sync|relate|lanes|reembed|" + "code-backfill|code-rebuild|dream|vault-sync|embed|repo-sync|dialogue-sync|relate|lanes|" + "reembed|" "tick|bless} " "[--force] [--confirm] [--skip-tests] [--dry-run] [] [\"\" --json " "--no-plan --as | --log]") @@ -215,6 +218,19 @@ def queue_overview() -> int: return 0 +def _landed() -> bool: + """Whether this instance's code source has landed a repository whole at least once (its + mark), read from the configuration alone, so nothing is opened or made when it has not.""" + from core.ingest.readers import read_mark + from core.ingest.table import repository_mark + from core.kernel.config import get_config + from core.kernel.config.loader import lexical_code + + cfg = get_config() + return lexical_code(cfg) and any(read_mark(repository_mark(cfg, r.name)) is not None + for r in cfg.ingestion.code.repositories) + + def main(argv: list[str]) -> int: if not argv or argv[0] in {"-h", "--help"}: print(USAGE) @@ -233,6 +249,8 @@ def main(argv: list[str]) -> int: if argv[0] == "query": # read-only: a sentence of the query algebra against the stores, never from core.sentence.surface import run_query # the daemon (dn-query-sentence-algebra, QL-3) return run_query(argv[1:]) + if argv[0] == "repo-sync" and "--if-landed" in argv[1:] and not _landed(): + return 0 # the hook keeps a landed code instance current; its first sync is deliberate from ops.lifecycle.launcher import build_launcher cmd, flags = argv[0], set(argv[1:]) @@ -266,6 +284,7 @@ def main(argv: list[str]) -> int: "dream": ("dreaming pass", launcher.dream_now), "vault-sync": ("vault sync", launcher.vault_sync_now), "embed": ("embed drain", launcher.embed_now), + "repo-sync": ("repository sync", launcher.repo_sync_now), "dialogue-sync": ("dialogue sync", launcher.dialogue_sync_now), "relate": ("relation edges", launcher.relate_now), "lanes": ("lanes: " + (", ".join(lanes) or "all"), diff --git a/tests/integration/test_palace_lite.py b/tests/integration/test_palace_lite.py new file mode 100644 index 00000000..ffda0b74 --- /dev/null +++ b/tests/integration/test_palace_lite.py @@ -0,0 +1,391 @@ +"""The lite profile (docs/design-notes/dn-palace-lite.md): an instance that embeds nothing, a code +source that keeps no vectors, and a repository read as a source through git. + +What is pinned: in an instance with `[embedding] enabled = false` no embedder and no vector plane +is ever constructed, while a repository's files land, re-land as nothing, change, retire, and are +found by `near`, `read`, `trace` and `reach`; the per-source switch keeps a note's vector and the +code's lack of one side by side in an instance that embeds; and the default instance's +configuration and table are what they were. +""" + +from __future__ import annotations + +import json +import subprocess +from dataclasses import replace +from pathlib import Path +from typing import Any, cast + +import pytest + +from core.ingest import ingress +from core.ingest.readers import read_mark +from core.ingest.repository import behind, itemizable +from core.ingest.table import build_table, repository_mark +from core.kernel.config import get_config +from core.kernel.config.loader import ( + InstanceOverlayError, + RepositoryConfig, + _repositories, + lexical_code, + load_config, + needs_lexical, +) +from core.kernel.provenance import Provenance +from core.query import QueryEngine +from core.sentence.surface import QueryLog, ask_logged, sentence_grant +from core.stores.noplane import EmbeddingOff, NoPlane +from tests.fixtures.ingress import EVERY, palace_at, write_file + +REPO = "toy" + + +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") + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + """A repository on `main` with code, a note, a foundation path, a binary and a symlink.""" + r = tmp_path / "repo" + (r / "pkg").mkdir(parents=True) + (r / "docs").mkdir() + _git(r.parent, "init", "-q", "-b", "main", str(r)) + (r / "pkg" / "embed.py").write_text( + 'def embed_fitting(texts):\n """Cut a text to fit the embedder."""\n return texts\n') + (r / "pkg" / "derive.py").write_text( + "from pkg.embed import embed_fitting\n\n\ndef drain():\n return embed_fitting([])\n") + (r / "docs" / "landing.md").write_text( + "# Landing without vectors\n\nAn item lands complete without its vector.\n") + (r / "CONSTITUTION.md").write_text("the foundation is never an item\n") + (r / "pkg" / "blob.bin").write_bytes(b"bin\0ary") + (r / "link.py").symlink_to("pkg/embed.py") + _commit(r, "one") + return r + + +def lite_config(root: Path, repo: Path, *, embedding: bool = False, embed: bool = False) -> Any: + """A palace under `root` reading `repo` as its code: every path the instance writes is under + `root`, embedding as asked, the code keeping no vectors unless `embed`.""" + data = root / "data" + data.mkdir(parents=True, exist_ok=True) + (root / "vault").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 / "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=True, embed=embed, + repositories=(RepositoryConfig(REPO, repo, "main"),)) + return replace(base, paths=paths, + ingestion=replace(base.ingestion, code=code, + vault=replace(base.ingestion.vault, path=root / "vault")), + interface=replace(base.interface, handoff_dir=data / "handoff"), + embedding=replace(base.embedding, enabled=embedding, lazy=False)) + + +@pytest.fixture +def no_vectors(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Constructing an embedder or a vector store fails the test: each attempt is recorded and + refused, so a pass proves none was made.""" + made: list[str] = [] + + def refuse(what: str) -> Any: + def boom(*_a: Any, **_k: Any) -> None: + made.append(what) + raise AssertionError(f"{what} was constructed") + return boom + + from core.ingest import embed + from core.models import inference + from core.stores import vectorstore + monkeypatch.setattr(vectorstore.VectorStore, "__post_init__", refuse("a vector store")) + monkeypatch.setattr(embed.Embedder, "__init__", refuse("an embedder")) + monkeypatch.setattr(inference, "build_inference_client", refuse("an inference client")) + return made + + +def _sync(cfg: Any, stores: Any) -> dict[str, Any]: + return ingress.run_library(cfg, "sync_repository", {"name": REPO}, stores=stores) + + +def _ask(engine: QueryEngine, sentence: str, log: Path) -> dict[str, Any]: + return ask_logged(sentence, sentence_grant(), surface="test", role="ambassador", + engine=engine, log=QueryLog(log)).to_dict() + + +# ── an instance that embeds nothing ──────────────────────────────────────────────────────────── + + +def test_an_instance_that_embeds_nothing_never_builds_an_embedder_or_opens_a_plane( + tmp_path: Path, repo: Path, no_vectors: list[str]) -> None: + cfg = lite_config(tmp_path / "lite", repo) + stores = ingress.build_stores(cfg) + assert isinstance(stores.plane, NoPlane) and stores.embedder is None + assert stores.lexical is not None + landed = _sync(cfg, stores) + assert landed["effects"] == {"landed": 3} + assert sorted(c["path"] for c in landed["changed"]) == [ + "code/toy/docs/landing.md", "code/toy/pkg/derive.py", "code/toy/pkg/embed.py"] + engine = QueryEngine(config=cfg) + log = tmp_path / "log.jsonl" + near = _ask(engine, 'top 3 near "embed fitting" over reference', log) + refs = [h["ref"] for h in near["hits"]] + assert "code/toy/pkg/embed.py" in refs + assert all(h["detail"]["ranked_by"] == "lexical: the item keeps no vector" + for h in near["hits"]) + assert any("the instance embeds nothing" in n for n in near["notes"]) + read = _ask(engine, 'read "code/toy/pkg/embed.py"', log) + assert "def embed_fitting" in read["hits"][0]["text"] + assert read["hits"][0]["stratum"] == "reference" + assert _ask(engine, 'reach F from "code/toy/pkg/derive.py"', log)["hits"] == [] + diffuse = _ask(engine, 'diffuse S from "code/toy/pkg/derive.py" over reference', log) + assert diffuse["hits"] == [] and any("S has no edge" in n for n in diffuse["notes"]) + assert no_vectors == [] + assert not list((tmp_path / "lite").rglob("*.lance")) + + +def test_notes_land_and_rank_lexically_in_an_instance_that_embeds_nothing( + tmp_path: Path, repo: Path, no_vectors: list[str]) -> None: + """The profile is not the code's alone: a vault note lands with its lexical units and no + vector, and `near` over the mirror ranks it by the index and says why.""" + cfg = lite_config(tmp_path / "lite", repo) + write_file(cfg.ingestion.vault.path, "drain.md", "the embed drain derives vectors later\n") + write_file(cfg.ingestion.vault.path, "other.md", "a note about something else\n") + stores = ingress.build_stores(cfg) + assert ingress.run_library(cfg, "sync_vault", stores=stores)["effects"] == {"landed": 2} + near = _ask(QueryEngine(config=cfg), 'near "embed drain"', tmp_path / "log.jsonl") + assert near["hits"][0]["ref"] == str(cfg.ingestion.vault.path / "drain.md") + assert near["hits"][0]["detail"]["ranked_by"] == "lexical: the item keeps no vector" + assert near["hits"][0]["detail"]["vector"] == "none: the instance embeds nothing" + assert no_vectors == [] + + +def test_an_instance_that_embeds_nothing_re_derives_a_stale_lexical_index( + tmp_path: Path, repo: Path, no_vectors: list[str]) -> None: + """The lexical index is this profile's one index, derived like any other: after a tokenizer + change it refuses to land or score until the embed job, which every landing here requests, + resets it and lands every item again under the new tokenizer, deriving no vector.""" + from core.ingest.lexical import LEGACY, Tokenizer + from core.stores.lexical import LexicalStore + from scheduler.embed import embed_handler + + cfg = lite_config(tmp_path / "lite", repo) + stores = ingress.build_stores(cfg) + assert stores.lexical is not None + path = stores.lexical.path + stores.lexical = LexicalStore(path, tokenizer=LEGACY) + assert _sync(cfg, stores)["effects"] == {"landed": 3} + assert stores.lexical.recorded_tokenizer() == LEGACY.identity + stores.lexical = LexicalStore(path, tokenizer=Tokenizer()) + assert stores.lexical.stale + note = embed_handler(cfg, stores=lambda: stores)(cast(Any, None)) # the job is unread + assert note is not None and note.startswith("embed: this instance embeds nothing") + assert "lexical: re-derived" in note + assert stores.lexical.recorded_tokenizer() == Tokenizer().identity + assert not stores.lexical.stale + assert all(stores.lexical.holds_current(e.source_path, e.digest) + for e in stores.catalog.active_entries()) + assert no_vectors == [] + + +def test_the_factories_refuse_an_embedder_and_a_plane_by_name(tmp_path: Path, + repo: Path) -> None: + from core.ingest.embed import build_embedder + from core.stores.curated_store import open_curated_store + from core.stores.vectorstore import open_vector_store + + cfg = lite_config(tmp_path / "lite", repo) + for factory in (build_embedder, open_vector_store, open_curated_store): + with pytest.raises(EmbeddingOff, match="embeds nothing"): + factory(cfg) + plane = NoPlane() + assert plane.count() == 0 and plane.all_rows() == [] and plane.search([0.0]) == [] + assert plane.current_versions() == set() and not plane.holds_current("a", "b") + plane.delete_source("a") # a retire's step: nothing to take + with pytest.raises(EmbeddingOff): + plane.add([{"id": "x"}]) + with pytest.raises(EmbeddingOff): + plane.reset() + + +def test_a_repository_lands_once_changes_retire_and_its_commit_is_marked( + tmp_path: Path, repo: Path) -> None: + cfg = lite_config(tmp_path / "lite", repo) + stores = ingress.build_stores(cfg) + first = _sync(cfg, stores) + assert first["effects"] == {"landed": 3} + mark = read_mark(repository_mark(cfg, REPO)) + assert mark is not None and mark["commit"] == _git(repo, "rev-parse", "main") + assert mark["files"] == 3 + assert _sync(cfg, stores)["effects"] == {"unchanged": 3} # a re-run lands nothing + labels = {str(e.provenance) for e in stores.catalog.active_entries()} + assert labels == {Provenance.CODE.value} + (repo / "pkg" / "embed.py").write_text( + 'def embed_fitting(texts):\n """Cut a text by bisection."""\n return texts\n') + (repo / "docs" / "landing.md").unlink() + head = _commit(repo, "two") + assert behind(repo, mark["commit"], "main") == 1 + second = _sync(cfg, stores) + assert second["effects"] == {"unchanged": 1, "landed": 1, "retired": 1} + assert {c["path"]: c["status"] for c in second["changed"]} == { + "code/toy/pkg/embed.py": "landed", "code/toy/docs/landing.md": "retired"} + assert read_mark(repository_mark(cfg, REPO))["commit"] == head # type: ignore[index] + assert behind(repo, head, "main") == 0 + assert stores.versions is not None + assert len(stores.versions.history("code/toy/pkg/embed.py")) == 2 + assert stores.lexical.units_of("code/toy/docs/landing.md") == 0 # retired: not current + trace = _ask(QueryEngine(config=cfg), 'trace "code/toy/pkg/embed.py"', tmp_path / "log") + assert [h["stratum"] for h in trace["hits"]] == ["reference"] + assert trace["hits"][0]["ref"] == "code/toy/pkg/embed.py@1 →D→ code/toy/pkg/embed.py@2" + + +def test_a_repository_source_reads_the_ref_never_the_working_tree(tmp_path: Path, + repo: Path) -> None: + (repo / "pkg" / "embed.py").write_text("an uncommitted edit\n") + (repo / "untracked.py").write_text("never committed\n") + cfg = lite_config(tmp_path / "lite", repo) + stores = ingress.build_stores(cfg) + _sync(cfg, stores) + paths = {e.source_path for e in stores.catalog.active_entries()} + assert "code/toy/untracked.py" not in paths + assert "code/toy/CONSTITUTION.md" not in paths and "code/toy/pkg/blob.bin" not in paths + assert "code/toy/link.py" not in paths # a symlink is no file + entry = stores.catalog.get("code/toy/pkg/embed.py") + assert b"def embed_fitting" in stores.raw.get(entry.digest) + assert not itemizable("CONSTITUTION.md") and not itemizable("eval/golden/x.md") + assert not itemizable(".claude/settings.json") and itemizable("docs/LAWS.md") + + +# ── a source that keeps no vectors in an instance that embeds ────────────────────────────────── + + +def test_the_code_keeps_no_vectors_while_the_notes_keep_theirs(tmp_path: Path, + repo: Path) -> None: + p = palace_at(tmp_path, lexical=True) + code = replace(p.cfg.ingestion.code, enabled=True, embed=False, + repositories=(RepositoryConfig(REPO, repo, "main"),)) + p.cfg = replace(p.cfg, ingestion=replace(p.cfg.ingestion, code=code)) + assert p.cfg.embedding.enabled and lexical_code(p.cfg) and needs_lexical(p.cfg) + calls: list[int] = [] + embed_documents = p.stores.embedder.embed_documents + + def counted(texts: list[str]) -> list[list[float]]: + calls.append(len(texts)) + return embed_documents(texts) + p.stores.embedder.embed_documents = counted # type: ignore[method-assign] + write_file(p.vault, "a.md", "a note about the drain") + assert p.run("do sync_vault")["effects"] == {"landed": 1} + assert calls # the note was embedded + embedded = sum(calls) + assert p.run(f'do sync_repository(name: "{REPO}")')["effects"] == {"landed": 3} + assert sum(calls) == embedded # the code was not + held = {str(r["source_path"]) for r in p.stores.plane.all_rows(clearance=EVERY)} + assert held == {str(p.vault / "a.md")} + assert p.stores.lexical is not None + assert p.stores.lexical.units_of("code/toy/pkg/embed.py") > 0 + assert p.run(f'do sync_repository(name: "{REPO}")')["effects"] == {"unchanged": 3} + + +def test_a_lazy_instance_asks_no_drain_for_code_that_keeps_no_vectors(tmp_path: Path, + repo: Path) -> None: + p = palace_at(tmp_path, lazy=True) + code = replace(p.cfg.ingestion.code, enabled=True, embed=False, + repositories=(RepositoryConfig(REPO, repo, "main"),)) + p.cfg = replace(p.cfg, ingestion=replace(p.cfg.ingestion, code=code)) + assert p.run(f'do sync_repository(name: "{REPO}")')["effects"] == {"landed": 3} + assert p.jobs == [] # the code's landing asks nothing + write_file(p.vault, "a.md", "a note") + assert p.run("do sync_vault")["effects"] == {"landed": 1} + assert [kind for kind, _ in p.jobs] == ["embed"] # the note's asks for its vector + + +# ── the configuration ───────────────────────────────────────────────────────────────────────── + + +def test_the_default_instance_is_what_it_was() -> None: + cfg = load_config() + assert cfg.embedding.enabled and cfg.ingestion.code.embed + assert not lexical_code(cfg) and not needs_lexical(cfg) + assert not any(s.kind == "repository" for s in build_table(cfg).sources.values()) + assert "reference" in build_table(cfg).places # a place no default role writes into + assert build_table(cfg).roles["ambassador"].prefixes.get("reference") is None + + +def test_the_code_instance_lives_outside_every_checkout(monkeypatch: pytest.MonkeyPatch) -> None: + from core.kernel.config import loader + + monkeypatch.setenv("MIND_PALACE_OVERLAY", "config/instances/code.toml") + cfg = load_config() + assert cfg.instance.id == "code" and not cfg.embedding.enabled + assert cfg.instance.root == Path("~/.mind-palace/instances/code").expanduser() + assert loader._working_tree_of(cfg.instance.root) is None + assert cfg.paths.data_dir == cfg.instance.root / "data" + assert lexical_code(cfg) and [r.name for r in cfg.ingestion.code.repositories] == [ + "mind-palace"] + assert not cfg.secrets.enabled and not cfg.effectors.enabled + assert not cfg.dreaming.scheduled and not cfg.integrate.enabled + + +@pytest.mark.parametrize("root, why", [ + ("instances/x", "relative"), + ("", "names no directory"), +]) +def test_a_declared_root_is_absolute(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + root: str, why: str) -> None: + overlay = tmp_path / "x.toml" + overlay.write_text(f'[instance]\nid = "lite-x"\nroot = "{root}"\n') + monkeypatch.setenv("MIND_PALACE_OVERLAY", str(overlay)) + with pytest.raises(InstanceOverlayError, match=why): + load_config() + + +def test_a_declared_root_inside_a_working_tree_refuses(tmp_path: Path, repo: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + overlay = tmp_path / "x.toml" + overlay.write_text(f'[instance]\nid = "lite-x"\nroot = "{repo / "state"}"\n') + monkeypatch.setenv("MIND_PALACE_OVERLAY", str(overlay)) + with pytest.raises(InstanceOverlayError, match="inside the git working tree"): + load_config() + outside = tmp_path / "home" / "lite-x" + overlay.write_text(f'[instance]\nid = "lite-x"\nroot = "{outside}"\n') + cfg = load_config() + assert cfg.instance.root == outside and cfg.paths.data_dir == outside / "data" + + +def test_the_default_chain_refuses_a_root(tmp_path: Path) -> None: + from core.kernel.config.loader import _ouroboros_instance + + with pytest.raises(InstanceOverlayError, match="named instance's"): + _ouroboros_instance({"instance": {"root": str(tmp_path)}}, "x") + + +def test_repositories_are_named_once_with_known_keys(tmp_path: Path) -> None: + got = _repositories({"repositories": [{"name": "a", "path": "~/a"}, + {"name": "b", "path": "rel", "ref": "dev"}]}, tmp_path) + assert [(r.name, r.ref) for r in got] == [("a", "main"), ("b", "dev")] + assert got[0].path == Path("~/a").expanduser() and got[1].path == tmp_path / "rel" + assert len(_repositories({}, tmp_path)) == 1 # the checkout + for bad, why in ([{"name": "a", "path": "x"}, {"name": "a", "path": "y"}], "repeat"), \ + ([{"name": "A b", "path": "x"}], "not a source name"), \ + ([{"name": "a", "path": "x", "branch": "y"}], "unknown key"), \ + ([{"name": "a"}], "names no path"), \ + ([{"name": "a", "path": "x", "ref": "-x"}], "not a ref"): + with pytest.raises(ValueError, match=why): + _repositories({"repositories": bad}, tmp_path) + + +def test_the_mark_is_json_with_the_time(tmp_path: Path, repo: Path) -> None: + cfg = lite_config(tmp_path / "lite", repo) + _sync(cfg, ingress.build_stores(cfg)) + doc = json.loads(repository_mark(cfg, REPO).read_text()) + assert set(doc) == {"commit", "ref", "files", "at"} and doc["ref"] == "main" diff --git a/tests/unit/test_ingestion_agent_levers.py b/tests/unit/test_ingestion_agent_levers.py index 5f1035d6..d8b29faf 100644 --- a/tests/unit/test_ingestion_agent_levers.py +++ b/tests/unit/test_ingestion_agent_levers.py @@ -184,3 +184,29 @@ def test_integrate_has_its_own_independent_lever(tmp_path) -> None: assert CHAT_SYNC_KIND in k and CODE_SYNC_KIND in k finally: no_integ.queue.close() + + +def test_code_that_keeps_no_vectors_syncs_its_repositories_instead_of_the_embed_lane( + tmp_path) -> None: + """`[ingestion.code] embed = false` (dn-palace-lite): the code lever still gates the agent, + and its paths enqueue the repositories' lexical sync, never the code embed lane or its + history backfill, so no code text reaches the embedder.""" + from scheduler.code_sync import CODE_BACKFILL_KIND, REPOSITORY_SYNC_KIND + + cfg = _cfg(tmp_path / "lexical") + cfg = dataclasses.replace(cfg, ingestion=dataclasses.replace( + cfg.ingestion, code=dataclasses.replace(cfg.ingestion.code, embed=False))) + comps = build_components(cfg) + try: + for which in ("housekeeping", "catchup"): + k = _kinds(comps, which) + assert REPOSITORY_SYNC_KIND in k, which + assert CODE_SYNC_KIND not in k and CODE_BACKFILL_KIND not in k, which + finally: + comps.queue.close() + off = build_components(_cfg(tmp_path / "off", code=False)) + try: + assert REPOSITORY_SYNC_KIND not in _kinds(off, "housekeeping") + assert REPOSITORY_SYNC_KIND not in _kinds(off, "catchup") + finally: + off.queue.close() diff --git a/tests/unit/test_instance_identity.py b/tests/unit/test_instance_identity.py index 4f6ed923..d8717ae9 100644 --- a/tests/unit/test_instance_identity.py +++ b/tests/unit/test_instance_identity.py @@ -160,9 +160,12 @@ def test_a_well_formed_id_is_the_instance(monkeypatch, tmp_path, iid) -> None: assert loader.get_config().instance.id == iid # surfaced through get_config() -@pytest.mark.parametrize("text", ['[instance]\nid = "bench"\nroot = "/tmp"\n', +@pytest.mark.parametrize("text", ['[instance]\nid = "bench"\nhome = "/tmp"\n', + '[instance]\nid = "bench"\nroot = "relative/x"\n', 'instance = "bench"\n']) def test_the_instance_section_holds_one_key(monkeypatch, tmp_path, text) -> None: + """The table holds an id and, for a named instance, an absolute root (dn-palace-lite): + another key, a relative root, or a table that is not one refuses.""" with pytest.raises(loader.InstanceOverlayError): _as_named(monkeypatch, tmp_path, text) diff --git a/tests/unit/test_queue_coalescing.py b/tests/unit/test_queue_coalescing.py index 6f6fd732..30b975a3 100644 --- a/tests/unit/test_queue_coalescing.py +++ b/tests/unit/test_queue_coalescing.py @@ -46,7 +46,7 @@ def test_idempotent_kind_literals_match_the_kind_constants(): `scheduler.queue` (importing them back would cycle). This test is what keeps that duplication honest: rename a kind constant and it fails here rather than silently disabling coalescing.""" from scheduler.chat_sync import CHAT_SYNC_KIND - from scheduler.code_sync import CODE_BACKFILL_KIND, CODE_SYNC_KIND + from scheduler.code_sync import CODE_BACKFILL_KIND, CODE_SYNC_KIND, REPOSITORY_SYNC_KIND from scheduler.cron import ( CHAT_EVENTS_KIND, CURATE_KIND, @@ -63,6 +63,7 @@ def test_idempotent_kind_literals_match_the_kind_constants(): assert _IDEMPOTENT_KINDS == { CHAT_SYNC_KIND, VAULT_SYNC_KIND, CODE_SYNC_KIND, CODE_BACKFILL_KIND, CHAT_EVENTS_KIND, INTEGRATE_KIND, DIALOGUE_SYNC_KIND, INBOX_CAPTURE_KIND, EMBED_KIND, + REPOSITORY_SYNC_KIND, } # The classification's other half, asserted rather than assumed: model-driven passes mint fresh # ledger rows per call, and payload-bearing kinds must never be swallowed by a sibling. diff --git a/tests/unit/test_sentence_types.py b/tests/unit/test_sentence_types.py index 62ff0b2b..a6248478 100644 --- a/tests/unit/test_sentence_types.py +++ b/tests/unit/test_sentence_types.py @@ -178,7 +178,8 @@ def test_read_is_a_text_that_composes_with_nothing_and_reads_by_the_refs_shape() _ARGS = {"ingest_note": 'path: "x.md"', "ingest_doc": 'path: "docs/x.md"', "sync_dialogue": 'reader: "openwebui"', "capture": 'text: "t"', - "link": 'a: "a", b: "b", relation: "supports"', "sync_corpus": 'name: "wikipedia"'} + "link": 'a: "a", b: "b", relation: "supports"', "sync_corpus": 'name: "wikipedia"', + "sync_repository": 'name: "x"'} def _do(text: str, role: str = "ambassador") -> Any: