core.ingest
core.ingest
Outer-ring residue of ingest (dn-inner-outer-core §2.7, K1 / bp-090).
The pure text-projection machinery (amend, chunk, logseq, pipeline, verify + the package's inner
init text) moved to core/kernel/ingest/. What remains here is the outer half — the modules whose
closure leaves the admissible base: embed (the embedding path via the model client), watch
(watchdog), and the curated/dialogue/founding/index/mint_ids/purge/run/sync runners.
This init is stdlib-import-free so it stays inner by construction (a pure package marker); the
residue submodules beside it are the outer machinery.
code_corpus
The code embed lane (dn-code-ingest-pipeline §2.1/§2.1b/§2.2/§2.3/§2.7; bp-092/CI-1).
Ouroboros's largest artifact — its own code, carrying the math and the §-warrants — was the one
region outside the semantic self-map (finding-0146). This lane pulls it in under the SAME vector
store, embedder, and group-by-digest machinery the notes use, discriminated by a layer coordinate:
- L0a — the structural (AST) reading (
layer=code_ast): one chunk per symbol, sliced at AST boundaries, header-prefixed# {path}:{qualname}{signature}. Nested defs own their lines, so a parent embeds as its SHELL (own lines minus descendants) and the module shell covers preamble + inter-symbol + trailing — every source line in exactly one L0a chunk (F-CI2 byte-cover). - L0b — the windowed textual reading (
layer=code_text): the note chunker's sliding char-window (chunk_text, the ONE window machinery — NOTderive_chunks, whose Logseq property-strip must not run on code) over the RAW source; bodies and#comments flow together. - L1 — the prose reading (
layer=codedoc): module + symbol docstrings + inline comments in source order, windowed as CANONICAL (header-free) prose and prefixed for retrieval by a single# {path}line — it lives in the note neighbourhood.
Derivation is a PURE function of (path, source): re-running yields bit-identical chunks (F-CI2 re-derivability). All embedding is LOCAL (the core embedder) — zero network egress (non-negotiable #1).
[banner: correction] The three projections WERE joined by line-range coordinates carried ON the
vector rows, and digest (the git blob sha) made group-by-digest yield "file = source object,
chunks = members". Neither is true of a code row any more (dn-vector-membership-store D1,
bp-152). The vector plane holds ONE row per distinct idea-atom (layer, content_hash),
corpus-wide and append-only; ALL occupancy — which (path, blob_sha) version holds which atom, at
which slot and lines, and whether that occupancy is current — moved into the membership relation
(core/stores/memberships.py). A version is a FIBER M(path, blob_sha), the source object is
that fiber, and a code consumer resolves a hit through the membership join (D3), never through
group-by-digest. The measured payoff is the reason: 52,755 duplicated embeds over the full ledger
history become 22,502 atoms (2.34×, D7), and a revert or a git mv costs zero geometry.
[banner: correction] A chunk's IDENTITY (content_hash) hashed its full embed text — coordinate
header included — so a git mv re-hashed every chunk of the file and every (path, slot) lineage
chain through it severed, on an operation this repo performs constantly (dn-vector-membership-store
§0.1 F1/F2). CORRECTED per D0 (owner-ruled 2026-07-27, strip-headers-from-the-atom-hash):
identity is the header-free CANONICAL body; the embed text still carries its header (retrieval
context is untouched, R7). L1 additionally cuts its windows over the canonical prose — stripping at
hash time alone leaves window boundaries computed over header-bearing text, so a path-length change
still recuts them. Measured over all 580 tracked .py files at 45c4a15, renaming every one of them:
11,096 atoms minted under the old identity → 2,373 under strip-at-hash-only → 3 under
this pin (those 3 are the parked oversize-threshold residue, issue #31); a one-line top-of-file
insert in every file: 2,114 → 2,114 → 0. Consequence, named: identity now differs from embed
text, so a shared atom's stored text/vector is its FIRST-LANDED rendering and display coordinates
resolve from memberships, never from the stored text.
[banner: supersession] The incremental sync's delete+replace contract (old §2.7) is REVERSED to
keep-and-link per dn-temporal-code-corpus D2 (warrant finding-0163, bp-099): a superseded code
version is RETAINED with current=false, never deleted, and backfill() embeds the full ledger
history (D1) — so every code version is a semantic node and the causal graph's supersession edge
blob(v)→blob(v+1) has both endpoints resolvable. Default retrieval stays current-view (D3).
CodeChunk
dataclass
One embeddable code chunk with its fiber coordinates. layer discriminates the projection;
(qualname, slot_line_start, slot_line_end) are the §2.4 backpointers, and they travel to the
MEMBERSHIP row now (bp-152 D1), not to the vector row.
TWO renderings, deliberately different (D0): text is the EMBED rendering and KEEPS its
coordinate header (retrieval context, R7); canonical_body is the IDENTITY input and is
header-free. Every chunker passes the canonical body from the site that already holds it — it
is NEVER re-derived by re-parsing text, so a body line that legitimately begins with # can
never be mistaken for a coordinate header (a wrong strip is silent identity corruption).
[banner: correction] line_start / line_end are RENAMED to slot_line_start /
slot_line_end (dn-vector-membership-store Amendment A2, owner-ruled 2026-08-06 on issue #34).
The stored values do not change; the name does, because the old name licensed a wrong reading.
They are the SLOT's declared extent — where the symbol lives — never the atom's text
coverage. L0a partitions by INNERMOST OWNER, so a class's chunk holds the class statement,
its docstring and its attributes but NOT its methods (which became their own chunks) — while
the emitted coordinates are owner.lineno, owner.end_lineno, the owner's full declared span.
They coincide exactly for leaf symbols, which is why every leaf-symbol fixture is blind to the
divergence; the module shell is the maximal case, carrying 1..n (the ENTIRE file) for a few
lines of preamble. The values are also non-contiguous in general: a symbol with nested children
owns lines scattered across its span. A consumer that wants "where is this symbol" reads the
span; a consumer that wants the atom's content reads text. This is the intended behavior, not
a defect to fix — the fix was to stop letting the field name hide the difference.
layer
instance-attribute
qualname
instance-attribute
slot_line_start
instance-attribute
slot_line_end
instance-attribute
text
instance-attribute
canonical_body
instance-attribute
content_hash
property
[banner: correction] Identity = the CANONICAL (header-free) body, never the embed text
(D0, owner-ruled 2026-07-27; this hashed self.text before). A filename is mutable: with
the coordinate header inside the hash, a rename re-hashes every chunk and every
(path, slot) occupancy chain through the file severs — on an operation this repo performs
constantly. Embed text may keep headers; identity may not.
LandReport
dataclass
What one land() actually did. atoms_embedded == 0 on a re-land is the reuse claim; the
CURRENCY numbers are what prove idempotence, because a do-nothing lander also embeds zero.
atoms_embedded = 0
class-attribute
instance-attribute
atoms_reused = 0
class-attribute
instance-attribute
membership_rows = 0
class-attribute
instance-attribute
currency = field(default_factory=CurrencyReport)
class-attribute
instance-attribute
current_any_raised = 0
class-attribute
instance-attribute
current_any_lowered = 0
class-attribute
instance-attribute
CodeLander
dataclass
land(path, blob_sha, chunks) — the D2 write path, in the D8 order.
Vector inserts FIRST (append-only; an unreferenced atom is dormant geometry, harmless), the
membership fiber SECOND (one SQLite transaction — the reference truth), currency reconciliation
and current_any maintenance LAST (both re-derivable, so a crash anywhere is repaired by the
next land or by repair_current_any).
⚑ Re-landing is idempotent BECAUSE reconciliation converges, not because the call
short-circuits. Step 4 runs even when step 3 wrote nothing. The tempting "the fiber already
exists, so return" is the C1 bug in its exact original form: on A → B → A the fiber for blob A
already exists carrying current=false, so a short-circuit leaves B marked HEAD — silent
corruption of every default (current-view) read, with nothing raised and nothing logged. The
repo already learned this once at note grain (core/stores/versions.py:22-27).
vectors
instance-attribute
memberships
instance-attribute
embedder
instance-attribute
embedder_identity
instance-attribute
land(path, blob_sha, chunks, *, head_blob_sha=None)
Land one file version. head_blob_sha names the path's CURRENT HEAD blob — it defaults
to the version being landed (the incremental case) and is passed explicitly by a history
backfill, where the version being landed is usually NOT head.
reconcile(path, head_blob_sha)
Steps 4–5 alone, for a path whose HEAD fiber already stands.
This exists so the incremental sync can honor the C1 rule without re-deriving chunks for every unchanged file on every pass. "Unchanged blob ⇒ skip the path entirely" is the same short-circuit at one level up: after A → B → A the HEAD fiber exists, the file looks unchanged, and B is left current forever. Reconciliation is two counting queries per path, so convergence costs nothing worth trading for that.
supersede_path(path)
A vanished file: every fiber of path goes current=false, nothing is deleted
(keep-and-link, D2). Expressed as reconciliation against a blob no fiber has, so there is
ONE currency mechanism rather than a second, subtly different one.
CodeSyncReport
dataclass
embedded_rows = 0
class-attribute
instance-attribute
changed_files = 0
class-attribute
instance-attribute
unchanged_files = 0
class-attribute
instance-attribute
deleted_files = 0
class-attribute
instance-attribute
superseded_rows = 0
class-attribute
instance-attribute
parse_failures = 0
class-attribute
instance-attribute
membership_rows = 0
class-attribute
instance-attribute
CodeCorpusSync
dataclass
Blob-sha-keyed sync of the tracked .py corpus into the vector store. The store's own set of
CODE (source_path, digest) pairs IS the D-fiber state: a file whose blob is already embedded
costs ZERO embeds. On a changed blob the incremental sync() is now keep-and-link
(dn-temporal-code-corpus D2, bp-099 — reverses the §2.7 delete contract): the superseded version
is RETAINED with current=false (never deleted) and the new version lands current=true; a
vanished file's rows likewise flip current=false rather than being removed. backfill()
embeds every HISTORICAL ledger version (D1) so the whole code history is a set of nodes. The
one-time SEED is sync() against an empty store. The embedder runs locally (no network, #1).
repo
instance-attribute
store
instance-attribute
embedder
instance-attribute
memberships
instance-attribute
embedder_identity
instance-attribute
max_chars = _DEFAULT_MAX_CHARS
class-attribute
instance-attribute
overlap_chars = _DEFAULT_OVERLAP_CHARS
class-attribute
instance-attribute
lander
property
sync()
[banner: correction] The D-fiber state WAS the store's own set of CODE
(source_path, digest) pairs. Atom rows carry neither column (D1), so the state re-homes
to the membership store's (path, blob_sha) fibers — the same number, a sturdier home
(the note's §6 re-home (1), applied here; the daemon's incompleteness probe is bp-153's).
A path whose HEAD fiber already stands is UNCHANGED and re-derives nothing — but it is still reconciled. Skipping it outright is the C1 short-circuit one level up: after A → B → A the HEAD fiber exists, the file reads as unchanged, and B stays current.
seed()
The one-time seed run — sync() on a store with no code rows embeds every HEAD blob
(§2.7-2). Scheduler-gated at the call site (BACKGROUND, pinned tier); the memory ceiling
(#8) is enforced by the loader on each embed call, exactly as for vault_sync.
backfill(versions)
Embed the full code HISTORY (dn-temporal-code-corpus D1, bp-099): every distinct ledger
(path, blob_sha) version in versions (from ops.code_lineage.ledger_versions) becomes a
semantic node. Idempotent by construction — a (path, digest) already in the store is
skipped at zero embeds (digest = blob sha, content-addressed) — so a re-run embeds nothing
and re-running after the seed only adds the non-HEAD versions. Each landed version is
current = (blob is that path's HEAD blob), so backfilling into an un-seeded store also
marks HEAD correctly and every superseded version current=false. A parse-fail blob still
embeds (L0b windows + module shell, derive_code_chunks degrades — never a hard stop) and
is counted. Store writes stay on the caller (the supervisor handler), single-writer kept.
[banner: correction] "Already in the store" is now "already has a FIBER" (D1 — the atom row
carries no (source_path, digest) to test). Idempotence is unchanged in kind and stronger
in fact: a re-run derives nothing for a version whose fiber stands, and a version whose
atoms are all already in the plane costs zero embeds even the FIRST time it is landed —
which is the whole point of the split (D7's 52,755 → 22,502 measured).
derive_code_chunks(path, source, *, max_chars=_DEFAULT_MAX_CHARS, overlap_chars=_DEFAULT_OVERLAP_CHARS)
The PURE derivation: (path, source) -> the file's L0a + L0b + L1 chunks. Deterministic and
bit-identically re-derivable from the blob (F-CI2) — parses ONCE with φ_code's parse_source
(the same interpreter, not a second parser). A parse-error file still yields L0b windows and a
module-shell L0a chunk (it embeds as text even when unparseable).
atom_id(chunk)
The atom's identity (D1): "{layer}:{content_hash}" — PATH-FREE and corpus-wide.
The one place the id shape is spelled, so the vector row and the membership row can never
disagree about what an atom is. Dropping the path from the id is the whole atom model in one
character-level change: it promotes code_rows' old per-path dedup to corpus-wide dedup, so
the same body in two files is ONE point with two memberships (PD-1, owner-ruled in). The layer
stays inside identity because two layers with identical text are different readings, not the
same idea (the D1 stratum fence, carried as a test invariant).
code_rows(chunks, vectors, *, current=False)
Assemble ATOM rows — one per distinct (layer, content_hash) (D1). Provenance is HARDCODED
CODE: there is NO parameter, so a caller physically cannot launder code into an authored class
(F-CI1).
[banner: correction] The old docstring said id is (source_path, layer, chunk_hash) —
"doc+layer-scoped" — and that digest is the git blob sha "so group-by-digest yields file =
source object, its chunks = members". Both clauses stop being true here. Under D1 the id is
(layer, content_hash), corpus-wide; the source object is now the MEMBERSHIP FIBER
M(path, blob_sha) (code_memberships, below), and group-by-digest is not the code lane's
path at all — VectorStore.all_rows structurally keeps shed atom rows out of it, because a
grouping keyed on a column these rows do not have produces one bogus set rather than an error
(bp-152 Item 3; the note's §3 Q5).
The shed, stated exactly. The occupancy columns — source_path, digest, title,
chunk_index, qualname, line_* — leave the ROW, not the schema: note rows still carry
them and no prose-lane consumer changes. (title is shed with them because on a code row it
WAS the path under another name; leaving it would stamp each shared atom with its first-landed
path — a coordinate that lies for every other occupancy, which is exactly what D0's consequence
note forbids relying on. Occupancy resolves from memberships, never from the row.)
provenance STAYS, and that is load-bearing rather than incidental: the mirror firewall is
a row PREFILTER — provenance IN (...) with prefilter=True in VectorStore.search — so
shedding the column would not weaken the firewall, it would REMOVE it, silently and with no
failing call anywhere.
The dedup here is the atom side and ONLY the atom side. by_id.setdefault collapses
duplicates, which is correct for geometry — two identical bodies are one idea — and WRONG for
occupancy: two byte-identical L0b windows in one blob are TWO memberships with distinct
chunk_index (the F5 multiset pin). code_memberships therefore builds its own list and never
reuses this dict.
current is the current_any reading now (D1): does ANY current membership contain this atom?
A freshly landed atom defaults to False — it has no occupancy yet at insert time, since D8
puts the vector insert BEFORE the fiber write — and the lander raises it in step 5 for exactly
the atoms whose current-membership count crossed 0→1.
code_memberships(path, blob_sha, chunks)
The version's FIBER: one membership row per chunk, in derivation order (D1/D2 step 3).
This is the A2 translation point — CodeChunk.slot_line_* becomes Membership.slot_line_*
with the name intact, so the "declared extent, not text coverage" reading survives the trip to
storage instead of being re-lost at the boundary.
One row per CHUNK, never per distinct atom. chunk_index is the position in
derive_code_chunks' output, which is a pure deterministic function of (path, source)
(F-CI2), so the key (path, blob_sha, layer, chunk_index) is stable and re-derivable — and two
identical windows in one blob keep both occupancies instead of colliding. Rows land
current=False; currency is not a property of the fiber's construction but of reconciliation
against the path's HEAD (D2 step 4), which is the only place that decides it.
build_code_corpus_sync(config=None, *, repo=None, embedder=None)
Wire a CodeCorpusSync against the configured vector store, membership store, local embedder and repo root. The membership store and the embedder identity are REQUIRED fields rather than optional ones: a lander without an occupancy record is not a lander, and a reuse decision without an embedder identity is the geometry-mixing bug (D2 step 2's pin) waiting to happen.
curated
Ingest the system's own white papers + design notes as a curated self-knowledge graph
(Track B / B4; nervous-system-and-ambassador.md §4).
The Ambassador can explain its own architecture by reading this graph — "fittingly, the white
papers + design notes ARE the corpus" for self-narration. It is CURATED, not authored: it is
the system's design prose, kept in its OWN graph and never merged into the authored mirror
(curated ∉ MIRROR_READABLE — the same firewall as book dreaming). The Ambassador reaches it
only via a deliberate, non-default provenances={CURATED} query.
Reuses the parametrized ingest pipeline (provenance=CURATED) into the existing multi-provenance VectorStore — no new store. Only PROSE docs are ingested (Constitution, Conventions, the docs/ tree). Config and anything that could hold a secret are never sourced here (there are none in the .md tree; the note's own caveat: explain the design, never expose live keys).
CuratedReport
dataclass
ingested = 0
class-attribute
instance-attribute
chunks = 0
class-attribute
instance-attribute
unchanged = 0
class-attribute
instance-attribute
curated_sources(repo_root)
The self-knowledge corpus: the Constitution, the Conventions, and the whole docs/ tree (white papers + design notes). Prose only — never config or secrets.
ingest_curated(paths, raw, store, embedder, catalog, *, repo_root, attestor=None)
Ingest each doc as CURATED. Titles are repo-relative (e.g. docs/design-notes/...).
Idempotent: landing reconciles each path, so a re-run after a doc edit supersedes the old
version and embeds only its changed chunks (A3 — the old delete-by-new-digest left the edited
document's previous version current beside the new one).
build_and_ingest_curated(config=None)
Wire + run the curated ingest against the configured stores + embedder (needs the live embedder — owner-run, see scripts/ingest_self_knowledge.py).
derive
The derived field: an item's vector plane rows, derived from the raw store after the item has landed (dn-two-phase-ingestion D1, D3; ING-19 to ING-21).
The embedder produces one relation of the store, semantic similarity. Every other relation and
the lexical index are functions of the bytes and the graph alone, so an item is complete without
its vector: under [embedding] lazy = true the writer lands the raw object, the lexical units, the
version, the attestation and, last, the key (ING-7), and writes no plane row. The vector is a
derived field of the item's bytes and the embedder's identity, and this module is the drain that
writes it. pending lists the active catalog entries whose current version the plane does not
hold; drain reads each one's bytes back by digest, chunks them as the landing chunked them,
embeds the atoms the plane lacks in batches of the configured size, and lands the rows through the
plane, whose current occupancy of (path, digest) is the drain's own idempotence key, written in
the plane's transaction after the atoms (SharedPlane.land, PLN-4). Run again, the drain finds
nothing pending and embeds nothing; interrupted anywhere, the next run lands what the interrupted
one would have, since an atom inserted before the interruption is found held and not embedded
again (ING-5) and an occupancy not yet written leaves the item pending (ING-20). A reader that
needs a vector the drain has not written finds the item pending and says so (ING-21).
Re-embedding after a model change is the same drain over a reset plane: the plane records the
embedder's identity, model, document template and dimension (core/stores/plane.py::Fingerprint),
refuses another, and reset forgets it, after which every active item is pending and the drain
derives it under the new identity. The catalog, the raw store, the versions, the edges and the
lexical index are untouched by both.
The batch policy follows the measurement of docs/experiments/corpus-measurements-2026-11-07.md:
one stream of 64 chunks a request saturates the embedder at 26 chunks a second, and each further
stream buys at most 15% while every other caller's latency grows to the length of the queue in
front of it; so streams is 1 unless the instance's configuration raises it.
CHUNK_MAX_CHARS = 1200
module-attribute
CHUNK_OVERLAP_CHARS = 150
module-attribute
EMBED_JOB = 'embed'
module-attribute
HOLDS = {Provenance.AUTHORED_SOLO.value: MIRROR_READ, Provenance.AUTHORED_DIALOGUE.value: MIRROR_READ, Provenance.OBSERVED.value: OBSERVED_READ, Provenance.CURATED.value: CURATED_READ}
module-attribute
LEXICAL_CLASSES = frozenset(HOLDS) | {Provenance.CODE.value}
module-attribute
DrainReport
dataclass
What one drain did: the items whose rows it landed and their chunks, the atoms it embedded and the ones the plane held already, the items with no chunk (complete, nothing to derive), the items it left pending under a limit, and its wall time.
items = 0
class-attribute
instance-attribute
chunks = 0
class-attribute
instance-attribute
embedded = 0
class-attribute
instance-attribute
reused = 0
class-attribute
instance-attribute
empty = 0
class-attribute
instance-attribute
left = 0
class-attribute
instance-attribute
seconds = 0.0
class-attribute
instance-attribute
cut = 0
class-attribute
instance-attribute
LexicalReport
dataclass
What one lexical backfill did: the items whose units it landed, the units, the items with no unit (recorded, complete), the items it left under a limit, its wall time, and whether it first reset an index whose units another tokenizer made.
items = 0
class-attribute
instance-attribute
units = 0
class-attribute
instance-attribute
empty = 0
class-attribute
instance-attribute
left = 0
class-attribute
instance-attribute
seconds = 0.0
class-attribute
instance-attribute
rederived = False
class-attribute
instance-attribute
pending(catalog, plane, *, lexical=None, classes=None)
The active catalog entries whose current version the plane does not hold current, of
classes (every plane class when None), in the catalog's order. With the lexical index given,
an entry it records as landed with no unit (an item with no text) is complete with nothing to
derive and is not pending; an entry it has no record of (landed before the index was opened)
stays pending, and the drain finds out by chunking it. The vector's absence is read from the
plane itself, never from a flag: a drain that died before its plane transaction leaves the
item pending, and one that died after it does not (ING-20). The plane is read once a clearance
(current_versions) where it can be, so the set is one pass over the catalog however large
the corpus.
record_of(raw, entry, *, max_chars=CHUNK_MAX_CHARS, overlap_chars=CHUNK_OVERLAP_CHARS)
An entry's chunks, derived from its bytes exactly as the landing derived them
(Writer.store): the same parse, the same chunker, so the drain's rows are the rows a
synchronous landing would have written.
canonical_chunks(record)
One chunk per distinct text within a record (index_amendment's canonical form).
embed_missing(plane, embedder, texts, *, batch=64, streams=1)
Embed the distinct texts whose atoms the plane does not hold, batch a request and
streams requests in flight at once, a text the server refuses for its length cut to fit
(embed_fitting, which the embedder applies to every request; it is applied again here for an
embedder object that does not). Returns {atom id: vector}, how many atoms the plane held
already, and how many texts were cut, by either.
drain(stores, *, batch=64, streams=1, max_items=None, max_chars=CHUNK_MAX_CHARS, overlap_chars=CHUNK_OVERLAP_CHARS, landed=None, clock=time.monotonic)
Derive the plane rows of every pending item (at most max_items), in groups of about
batch × streams chunks: each group's atoms the plane lacks are embedded, then the group's
rows land in one plane transaction, so a long drain commits as it goes and a reader sees each
group's items leave the pending set together. landed is told each group's paths once their
rows are current, for a caller that measures the lag between landing and vector. Idempotent:
a second drain finds nothing pending and embeds nothing (ING-20).
derive_entries(stores, entries, *, batch=64, streams=1, max_chars=CHUNK_MAX_CHARS, overlap_chars=CHUNK_OVERLAP_CHARS, landed=None, clock=time.monotonic)
Derive the plane rows of the given entries, as drain derives the pending ones: in groups
of about batch × streams chunks, each group's missing atoms embedded and its rows landed in
one plane transaction. The caller picks the entries (the corpus runner's backfill takes them
round robin over its sources); an entry whose rows are current already lands its occupancy
again, which the plane's landing reconciles to nothing, and one with no chunk is counted
empty.
lexical_missing(catalog, lexical, *, classes=None)
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.
derive_lexical(stores, *, max_items=None, group=500, max_chars=CHUNK_MAX_CHARS, overlap_chars=CHUNK_OVERLAP_CHARS, clock=time.monotonic)
Land the lexical units of every active item the index has no record of (at most
max_items), read back from the raw store and chunked as the landing chunked them, group
items a transaction. The index is derived and regenerable, as the vectors are, and this is its
drain: run again, it finds nothing missing and writes nothing. It writes no key, no label and
no plane row.
An index whose units another tokenizer made (LexicalStore.stale: the tokenizer changed, or
the index predates the recorded identity and the tokenizer is no longer LEGACY) holds no unit
a query can be scored against, and refuses to land; this drain resets it first, after which
every active item is missing and lands again under the current tokenizer, as re-embedding is
the vector drain over a reset plane. The reset and the backfill run in the one writer, so no
landing reads the empty index between them.
dialogue
The first form's turn lander (dn-ingress D7): one turn of an external chat captured under
its role, the owner's authored-dialogue and the model's observed.
No production path calls it now. The dialogue sync is the library script sync_dialogue, and the
Ambassador's inbox lands through capture_inbox (dn-ingress-language §E13), which replaced this
module's capture, the inbox's first-form lander. capture_turn stays as what the second form
is measured against: the differential oracle for sync_dialogue (DS-5), ING-7's falsifier for a
turn (tests/integration/test_landing_order.py), and the way the plane's tests land turns. It
rides the same path as vault ingest (ingest_note → index_records → VaultCatalog.record),
with the key last.
DialogueCapture
dataclass
raw
instance-attribute
store
instance-attribute
embedder
instance-attribute
catalog
instance-attribute
attestor = None
class-attribute
instance-attribute
capture_turn(text, *, conversation, turn_id, role, at=None)
Store one turn of an external chat (e.g. Open WebUI) idempotently; return
(digest, created). The path is deterministic — dialogue/<conversation>/<turn_id> — so a
re-sync of the same turn is a no-op. Provenance is fixed by ROLE, never by the text: the
owner's turns are authored-dialogue (mirror-readable, their own words); the model's are
observed (recallable as context, never in the mirror or the baselines).
embed
Embedding adapter (BUILD-SPEC §8 derived layer).
Wraps the local embedding model. Documents are embedded plain; queries are wrapped in the model's instruction format (Qwen3-Embedding is instruction-aware on the query side, which materially improves retrieval). Embeddings are a regenerable derived representation — re-embed from the raw store if the model changes (§8).
An input the embedding server cannot take whole is cut, not refused. The server answers an input
longer than its physical batch with an error rather than truncating it, and a chunk's budget of
characters does not bound its tokens (a run of symbols or of another script takes several tokens a
character: one comment of 1,145 characters took 2,951 tokens, past a batch of 2,048). So every
request goes through embed_fitting: a refused batch goes in halves until the refused text is
alone, and that text is cut, by bisection on its characters, to a prefix the server takes and
refuses one character longer, as an embedding model truncates an input at its maximum length. That
prefix is the longest the server takes when a prefix's token count grows with its length, as it
does but for a tokenizer's merges. The embedder counts its cuts, and the ingress's receipt
and the drain's report say how many a landing made. Any other failure is raised.
TOO_LARGE = 'too large to process'
module-attribute
Embedder
dataclass
client
instance-attribute
config
instance-attribute
dim
property
embed_documents(texts)
embed_query(text)
refused_for_length(e)
Whether an embedding error is the server's refusal of an input for its length.
embed_fitting(embed, texts)
The vectors of texts by embed, one request when the server takes it. When it refuses
the request for an input's length, the texts go in halves until the refused text is alone, and
that text is cut by bisection on its characters to a prefix the server takes and refuses one
character longer (the longest it takes when token counts grow with the prefix); the cut is a
function of the text and the server, so the same text is always cut the same way.
Returns the vectors and each cut as (characters, characters kept). Any other error is
raised: nothing guesses past an embedder that fails.
build_embedder(config=None)
files
What the ingress trusts of a file and of a directory: one place for the checks the spools, the inbox's record and the handoff files of the sources that may yield the owner's words all make (dn-ingress §5, dn-ingress-language §E2, §E13).
A directory is trusted when it is a real directory (a symlink is never followed), owned by the
daemon's own account and writable by no other account (by its group only where the caller says the
group writes). A file is read through a descriptor that follows no link and blocks on nothing, as
a regular file under a cap; the caller judges its owner, mode and links from the descriptor's own
stat, so a file swapped after the check is never the one read.
daemon_uid()
The daemon's account: the process's own. One function, so a test can stand another account's ownership in for the daemon's.
check_dir(d, *, group_writes=False)
Why d is not trusted, or None: a real directory (a symlink is not one), owned by the
daemon's own account, writable by no other, and by the group only where the group writes.
real_dir(d)
Whether d is a directory itself, not a link to one.
read_bounded(path, cap)
A file's bytes through a descriptor that follows no link and blocks on nothing: a regular
file under cap bytes, read to at most cap + 1. Raises on anything else.
written_by_one(st)
Why a file, by its descriptor's stat, is not the daemon's own, or None: one link (a
writer keeping a second name could change it after the check), owned by the daemon's account,
writable by no other.
founding
Founding-corpus ingest — authoring the initial condition (founding-corpus.md; build plan Item 3).
The founding corpus is NOT model training and NOT steady-state ingest (founding-corpus.md §1–§2): it is a hand-selected batch of the owner's musings, authored across a long past, injected at once as the graph's initial condition. It must be a dated, supersession-linked sequence (§2.1 — reconstruct the partial order of thought, not a bag stamped "today"), and it MUST share the steady-state ingest path or the provenance model fractures at the origin (§4 / Q3).
So this driver is a thin batch over the ONE pipeline — ingest_note (provenance AUTHORED_SOLO) →
index_records → VaultCatalog.record, exactly the curated.py shape, never a bespoke writer. Two
founding-specific disciplines it enforces:
- Dated, not a bag (§2.1). Every item carries a reconstructed date, recorded as a
date::property IN the note, so the raw content-addressed blob carries it (permanent provenance) andparse_textlifts it intoproperties['date']. An undated item is refused — the timestamp lie (collapsing years into simultaneous peers) is exactly what founding must avoid. (The temporal layer reading these dates is dormant today; the dates are recorded now regardless.) - Supersession-linked (§2.1). When a later musing revises an earlier one, it is recorded as an
OWNER-DECLARED authored-historical supersession (
core/stores/authored_supersession.py; 8f / PD11) — a K₀↔K₀ RELATION between two authored documents, so the active projection shows the current musing and the earlier lives on in history. It is NOT a claim-supersede(no warrant, no derived alternative) and NOT a note-versionsupersedes(two documents, not one doc's versions). Founding is an owner entry point, so it mints anOwnerDeclaration; the store is owner-declared only and refuses any machine caller at its boundary (the-edge-model.md §4a).
Provenance is AUTHORED_SOLO — the owner's writing, the mirror's ground truth. The founding corpus is deliberately biased-coherent, so it CANNOT be the Track-L control corpus (§2.3): the control is a separate, non-curated CURATED-graph act. This driver writes only AUTHORED_SOLO and never the control — the two acts stay mechanically distinct. Ingest, not fine-tuning; the weights never move.
UndatedFoundingItem
Bases: ValueError
A founding item with no reconstructed date — refused (§2.1: a dated sequence, not a bag stamped 'today'; the timestamp lie is exactly what founding must avoid).
ForwardSupersession
Bases: ValueError
A founding item supersedes one not yet ingested — refused: the sequence is ordered (a musing can only revise an EARLIER one), so a forward reference is a manifest error.
FoundingItem
dataclass
One dated musing in the founding sequence. body is the text; date its reconstructed
original date (a date:: property in the note); supersedes the source_path of an
EARLIER item this one revises, or None.
source_path
instance-attribute
title
instance-attribute
body
instance-attribute
date
instance-attribute
supersedes = None
class-attribute
instance-attribute
FoundingReport
dataclass
ingested = 0
class-attribute
instance-attribute
chunks = 0
class-attribute
instance-attribute
superseded = 0
class-attribute
instance-attribute
ingest_founding(items, raw, store, embedder, catalog, *, supersession_store=None, attestor=None)
Ingest the founding sequence through the STEADY-STATE path (no bespoke writer): each item
rides ingest_note (AUTHORED_SOLO) → index_records → VaultCatalog.record, exactly like
curated/dialogue ingest. Dated (undated refused) and supersession-linked (recorded as an
OWNER-DECLARED authored-historical supersession when a later musing revises an earlier — 8f).
Ingest, not fine-tuning — weights never move (§1); AUTHORED_SOLO, never the control (§2.3).
build_and_ingest_founding(items, config=None)
Wire + run the founding ingest against the configured stores + embedder (owner-run; needs the live embedder — see scripts/ingest_founding.py).
inbox
The Ambassador's inbox as a source: the inbox's own record, and its capture (dn-ingress-language §E13).
The owner reaches the Ambassador through the interface handoff: the gateway writes a request, the
core inbox (core/interface.py) asks the Ambassador for a reply, writes the response and removes
the request. Before it writes the response, the inbox keeps the exchange here, in its own record:
one file a request, named by the gateway's id, holding the owner's text as the request file held
it and the reply the inbox sends, each in a field of its own. The directory is the daemon's
account's alone (0700, each record 0600), and nothing but Record.write writes it.
The palace's table reads the record as the source inbox (core/ingest/table.py): the text is the
owner's (authored-dialogue) and the reply is not (observed), by the field each was written
into, so no script, no model and no field a model writes decides a label (ING-13). The library
script capture_inbox stores both under the role inbox, which only the daemon's own jobs speak,
and the one writer lands the plan with the key last (ING-7, ING-16). A record both of whose items
have landed is removed (readers.PalaceView.landed), so the raw store is the bytes' one home and a
run reads only what is pending.
SCRIPT = 'capture_inbox'
module-attribute
Exchange
dataclass
What the inbox keeps of one request: its id, its conversation, the owner's text as the request file held it, the reply the inbox sends, and the request's time.
id
instance-attribute
conversation
instance-attribute
text
instance-attribute
reply
instance-attribute
at
instance-attribute
Record
The inbox's own record, written by the inbox alone: one file an exchange, in a directory of the daemon's account's that no other account may write.
root = root
instance-attribute
of(cfg)
classmethod
write(ex)
Keep one exchange: its record written whole, by a rename, under its id. The same request kept twice (a crash before the inbox removed it) is the same record again.
ensure()
Make the directory, the daemon's alone, and refuse one that is not (a symlink, another account's, or one another account may write). The daemon makes it at start, so its watcher has a directory to watch.
waiting(cfg)
Whether the inbox's record holds an exchange not yet landed: what the daemon's watcher and its catch-up ask before they enqueue the capture. A listing of the directory's names, nothing read; the capture's reader judges each record.
land(cfg, *, stores)
The inbox's capture: the library script capture_inbox under the role inbox, evaluated
and landed by the one writer as the daemon's own job, the records it landed whole removed.
Returns what ingress.perform returns, the receipt's detail.
index
Index ingest records into the vector store + provenance-aware semantic search (BUILD-SPEC §8, §9).
Vectors are derived and regenerable: to re-index after a model/strategy change, rebuild the vector store from the raw corpus (§8) rather than mutating in place.
Chunk points are keyed by a DOC-SCOPED content address (source_path, chunk_hash) (§3/§4,
build plan R1): stable across versions of a note (an unchanged chunk keeps its point) and
distinct across documents (two notes sharing a verbatim chunk keep both points — corroboration,
§7). index_amendment uses that to re-embed only the chunks that actually changed.
[banner: extension] dn-vector-membership-store A3 (2026-10-29): the row a reader sees keeps that
doc-scoped id, while the store keeps ONE atom per distinct chunk text for every prose stratum, so a
chunk two documents share is embedded and stored once and corroboration becomes a count of its
holders. embed_new is where the saving happens: only texts the store does not hold are embedded.
embed_new(store, embedder, texts)
Embed each distinct text whose atom the store does not already hold — and only those (A3:
the embeds the shared plane saves). Returns {atom id: vector}; a text whose atom is known
lands with no vector at all.
index_records(records, embedder, store)
Embed what the store does not already hold and land every record. Returns rows landed.
Within a note, chunks dedupe by content (one point per canonical chunk, §3). Across notes and strata, an identical chunk is one shared atom (A3): embedded once, landed once per document.
[banner: correction] Was: "Identical-content notes (same digest) are embedded once" — by skipping the second record ENTIRELY, so a second note with the same bytes at another path got no rows and could never be found. Embedding is still paid once; every document now lands.
index_amendment(record, existing_rows, embedder, store)
Re-index one note as a chunk-level amendment (ingest-identity-and-amendment.md §4). Returns
(embedded, reused): the stable parts of a frequently-edited note never re-embed.
[banner: extension] A3: on the shared plane, embed only the chunks the plane does not hold and
land the new version — the old one is SUPERSEDED with an edge and its occupancies kept (the
owner's "supersession edge … with the new vector reference set"), never deleted; an emptied
note retires its path. existing_rows is not read there. A table not yet migrated keeps the
pre-A3 replace, reusing existing_rows' vectors.
index_batch(records, embedder, store)
index_amendment for a batch of records on distinct paths, as one landing: one embedding
of the distinct texts the plane does not hold (ING-5: two records sharing a chunk pay once),
then every record's fiber in one add, the plane's one transaction. An emptied record retires
its path, as index_amendment does. A table not yet migrated to the plane lands record by
record. Returns the atoms embedded.
rekey_preview(store)
(note rows, how many ids would change) under the doc-scoped re-key: a read that mutates
nothing, over exactly the rows rekey_store writes.
rekey_store(store)
Re-key every note row to its doc-scoped content id (source_path, chunk_hash) IN PLACE: the
migration off the old {digest}:{chunk_index} scheme (build plan Item 1c). Returns (note rows,
ids changed); a second run changes none.
[banner: correction] Was: read all_rows(), reset() the store and add the rows back. That
read returns neither the shed CODE atoms (D1, bp-152's guard) nor the plane's superseded
occupancies, and reset() drops the table and every relation, so a run deleted every code
atom, every superseded version and every supersession edge, and gave code records the note
lane's key, merging two layers' rows of one text (issue #37; formal/Palace/Plane.lean's
witnesses rekeyReset_drops_history, rekeyReset_merges). The re-key is SCOPED now (PLN-6,
rekey_keeps): the plane's occupancies take their key in place (SharedPlane.rekey_rows,
one column of one transaction), a table that predates the plane re-keys its note records in
place (VectorStore.rekey_records), and no other row, atom, edge or cache entry is read or
written. No vector moves, so there is nothing to re-embed; the raw store and the catalog are
untouched.
semantic_search(query, embedder, store, *, k=5, clearance=MIRROR_READ)
Search the thought-graph. Defaults to the mirror — the introspective default that keeps observed exhaust out of it. A wider read passes a wider clearance, which only an authority can mint (A3.4); a free provenance set is no longer a way in.
grouped_semantic_search(query, embedder, store, *, k=5, clearance=MIRROR_READ)
Semantic search returning results grouped by SOURCE OBJECT instead of flat chunks.
The explicit opt-in to source-grained retrieval: flat semantic_search stays the default
and is untouched (byte-identical), and this is a separate entry point rather than a flag on
it — the recursive-strata I3 floor-zero posture (the grouped mode adds nothing to the flat
path). k is the flat chunk budget; the returned sources are those chunks grouped by
SourceId, so a query hitting two chunks of one note yields one source with two members.
Source order follows search rank (each source at its best hit; see group_sources). Defaults
to the mirror like semantic_search. To expand a hit to its full membership rather than only
the matched chunks, call source_set(store, hit.digest, clearance=…).
ingress
The ingress: a command as a request, the daemon as the one writer (dn-ingress D3, D5, D7).
A surface that speaks a command (do …) compiles it under the grant of the role it speaks
for, and, if admitted, writes a request into its spool, a per-role directory under the
interface handoff directory (cfg.interface.handoff_dir; the daemon makes and owns the
spools, and only a role's own writers may write its spool, §5). The daemon drains the
spools each tick (scheduler/ingress.py), enqueues one job per request as the kind the command
compiles to, and binds the role to the spool the request came from: the filesystem is the
authenticator, no field of the request names a role. The job's payload is the request id and
the sentence's digest (and, for today's kinds, their usual payload), so queue.sqlite never
holds corpus text; the text stays in the request file, whose name is its id. The handler
compiles the sentence again under the spool's grant, the second check, the one that counts,
performs the command under the one writer, and writes the receipt beside the request:
spooled, then queued with the job id, then landed with what landed, or refused with why.
A receipt names the request, never the sentence: the text has one home.
What the daemon trusts of a spool is bounded (two security reviews of 2026-11-05, §9 of the
note). The spools are the daemon's: it makes the root (0755, nobody else adds an entry), the
operator's spool (0700, the owner's account alone writes it) and the agents' spool (3770, the
group writes, the sticky bit keeps one writer from moving another's file), and the queued/,
receipts/ and rejected/ beneath each (the daemon's alone). It drains only a spool whose every
directory is a real directory, owned by its own account and writable by no one it should not be.
A request is read through a file descriptor that follows no link and blocks on nothing: a regular
file with one link, under the size cap, whose id is sixteen hex digits and its name, written, in
the operator's spool, by the daemon's own account. Anything else is moved to rejected/ and
reported, never re-read and never allowed to stop the drain; the daemon then works from its own
copy (stage), so a writer's later change to its file changes nothing. The identities the ingress
mints for turns live under dialogue/ingress/<role>/, so no role's command can name the owner's
turns or another role's.
This module is core: it opens no queue and no store on its own, and imports no scheduler. The
scheduler's drain_spool and ingress_handler are the daemon's side; perform is the landing of
the commands the ingress lands itself, given the components the daemon holds.
SPOOL = 'ingress'
module-attribute
LEGACY_SPOOL = 'door'
module-attribute
MAX_SENTENCE_BYTES = 32 * 1024
module-attribute
MAX_REQUEST_BYTES = 64 * 1024
module-attribute
MAX_SPOOLED = 256
module-attribute
SCAN_MAX = 4096
module-attribute
PRUNE_AFTER_S = 7 * 24 * 3600
module-attribute
ROOT_MODE = 493
module-attribute
SHARED_MODE = 2040
module-attribute
PRIVATE_MODE = 448
module-attribute
SHARED_INNER_MODE = 1512
module-attribute
PRIVATE_INNER_MODE = 448
module-attribute
Report = Callable[[str], None]
module-attribute
SCRIPT_KIND = 'script'
module-attribute
INGRESS_KINDS = frozenset({SCRIPT_KIND})
module-attribute
MAX_RECEIPT_EFFECTS = 200
module-attribute
Busy
Bases: RuntimeError
The role's spool, or its share of the queue, is full: refused now, not queued for later.
Request
dataclass
A command as spooled: its id, the role of the spool it sits in, the sentence, the time.
id
instance-attribute
role
instance-attribute
sentence
instance-attribute
at
instance-attribute
digest
property
The sentence's digest: what the queue carries, and what the handler checks the queued file against before it lands (the review's finding 7).
Receipt
dataclass
What the ingress reports: the request, its role, its kind, its state (spooled, queued,
landed, refused, failed), the job id once enqueued, and what landed or why not. The
sentence is not repeated here: the request file holds it, the receipt names it.
request
instance-attribute
role
instance-attribute
kind
instance-attribute
state
instance-attribute
job = None
class-attribute
instance-attribute
detail = field(default_factory=dict)
class-attribute
instance-attribute
to_dict()
grant_for(role)
The grant a role speaks under at the ingress, a spool's or one of the daemon's own jobs'. An unknown role is refused, never defaulted.
sentence_digest(sentence)
spool_root(cfg)
roles()
The roles the ingress knows, in the order the drain serves them.
ensure_spools(cfg, *, report=None)
The daemon's own making of the spools, each with its mode, and the roles whose spools are
sound to drain: the root, the role's spool and its three subdirectories each pass
check_dir. A role that does not is reported once and not drained; the others are.
kind_of(do)
The queue kind a request takes, and the kind's usual payload: a bare call of a library
script the table maps to one of the queue's own coalescing kinds is that kind, so it coalesces
with the watcher's and the heartbeat's rows; every other request is a script job that names
its staged copy (dn-ingress-language §E7).
lane_of(do)
The quota lane a request counts against: the library scripts the table marks interactive (a capture) are interactive, so a role's syncs never hold its captures; the rest are bulk.
write_request(cfg, *, role, plan)
Spool a compiled request for role. The plan was compiled under grant_for(role) and
checked under the role by the surface (the first check); the daemon compiles it again under
the spool's grant (the second). A request for a spool already MAX_SPOOLED deep is refused
here, before anything is written.
waiting(cfg, healthy)
The sound roles whose spool holds a request file: what the drain looks at before it reads the queue, so an idle tick costs a directory listing per role and nothing more.
pending(cfg, healthy, *, limit=64, per_role=32, report=None)
The requests waiting in the sound spools, oldest first within a role, at most per_role
of a role and limit in all. The role is the spool directory's name, never a field of the
file: the filesystem is the authenticator. A file the daemon does not trust
(_load_request) is moved to rejected/ and reported.
reject(f, say, why, *, cfg=None, role=None)
Move a request file the daemon will not act on to its spool's rejected/ (the daemon's
alone), under a name no earlier rejection holds, and say so; a file the daemon cannot move
is reported once, not every tick. A file whose name is a request id no receipt names yet is
receipted as refused, so its writer learns why: a seen id's receipt is never overwritten.
seen(cfg, role, rid)
Whether a request id was drained before: a receipt names it, in any state but failed.
An id is minted once, so a request file bearing a seen id is a replay (or the leftover of a
crash after its receipt), and is rejected before it can enqueue a second job or overwrite the
first one's receipt. A failed request may be spooled again.
stage(cfg, request)
The daemon's own copy of a validated request, in queued/, which only the daemon writes:
the job names it, and the writer's file is no longer read.
read_request(cfg, role, rid)
A staged request, by the role of its spool and its id; both are checked before either
names a path, the file is read as _load_request reads, and its id must be its name.
discard_queued(cfg, role, rid)
Remove a staged request once its receipt is terminal: the text's one home was the request file, and a landed or refused command needs it no more. A failed one stays (a week), for the operator to spool again.
write_receipt(cfg, receipt)
read_receipt(cfg, role, rid)
prune(cfg, *, now=None, max_age_s=PRUNE_AFTER_S)
Remove what the ingress keeps only for a while: receipts and rejected files older than
max_age_s, and the staged copies of failed requests, or of requests no receipt names, as
old. A staged copy whose job may still run is never removed, and only regular files are
touched. Returns how many were removed.
build_stores(cfg, enqueue=None)
The stores the writer lands into, opened by the daemon, the one writer. The lexical index
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.
reader(cfg, role)
A nested sentence's evaluation, under the role's grant: the read half, whose hits come back as records whose strings are observed (dn-ingress-language §E11).
resolve(do, library=None)
The script a request runs, with its arguments: a library script's, or the inline one.
perform(do, cfg, role, *, stores, library=None, view=None, budget=None, request=None, refresh=False, batch=False, lazy=None)
Run a request under the one writer: evaluate its script under the role (reading the
palace, writing nothing) into a plan, then land the plan, each effect by the writer's rules
(dn-ingress-language §E5). request is the request's id, so the jobs its plan starts start
once however often it runs; refresh runs a structured source's edge reader before its
first read, which only the daemon's own syncs and the owner's CLI ask for; batch lands a
plan of fresh stores on distinct paths a stage at a time (Writer.land_batch, the bulk path
of dn-corpus-instance §5.2); lazy lands each store complete without its plane rows, which
the embed drain derives from the raw store (Writer.lazy, dn-two-phase-ingestion), and is
the instance's [embedding] lazy unless the caller says otherwise. Returns what the receipt
says: each effect's outcome, counted by status, those that changed or were refused named, the
work charged (§E10), and how many texts the embedder had to cut to fit when it cut any.
run_library(cfg, name, kwargs=None, *, role='cli', stores=None, refresh=True, batch=False, lazy=None)
A library script run in this process, as the owner's CLI and scripts run one behind the
live-daemon guard: compiled and admitted under the role's grant as a request is, then
evaluated and landed by the writer, its structured sources refreshed first (unless
refresh is off), a plan of fresh stores a stage at a time when batch is on, lazily
when lazy says so (the instance's [embedding] lazy when it says nothing).
landing
The landing order of the ingress (dn-ingress D1, D5; ING-7 in formal/Palace/Ingress.lean).
A run lands in stages, and the stage order is what makes an interrupted run safe: every prefix is
a consistent state, every stage is idempotent, and the idempotence key (the catalog's digest
for the path, which the UNCHANGED check reads) is the last write. A crash before the key leaves a
run the next run repeats in full, so the next run lands exactly what the interrupted one would
have; a crash after the key changes nothing, since the key is the last write. The two lanes that
wrote the key first (sync_path, capture_turn) and the one that had no key (ingest_curated)
were the audit's defects 1 and 2 (dn-ingress §9).
Two helpers make the stages before the key idempotent at the ledger grain: a version is appended
only when the digest is not already the chain's head (appendIfNew in the model; a revert to an
older version's bytes still appends, since the head differs), and an attestation is emitted once
per (action, digest), so a re-run after a crash between the attestation and the key does not
attest twice. A rename is the one event the digest cannot show: the same bytes under a new path
are a version event by the identity design (bp-031), and sync_path tells it from a re-run by
the catalog, where the old path still binds the identity until the pass tombstones it. The
attestation check reads the ledger's output-hash table (AttestationStore.producers_by_output),
a seek a digest, where it was a pass over every record: at a few hundred thousand records the pass
took seconds and an item landed effect by effect asked it three times.
record_version_if_new(versions, doc_id, digest)
Append the next version unless digest is already the chain's head: the model's
appendIfNew. A re-run after a crash appends nothing; a revert still appends.
attested_by(attestor, action, digest)
The ids of the attestations of action that name digest among their outputs, sorted,
each once: from the store's producers by output (their actions with them) where it has them,
else from its producer ids, each record read for its action.
attested_batch(attestor, digests)
For many digests in one read of the ledger's output-hash table, each digest's producers:
the attestations, of any action, whose outputs name it, as (action, id). attested_by is the
producers of one action, and an attestation's parents (StoreAttestor.emit's auto-link) the
producers of its inputs; the batched landing reads both off this one read a batch
(Writer.land_batch) rather than asking per store.
already_attested(attestor, action, digest)
Whether an attestation of action already names digest among its outputs.
attest_once(attestor, *, agent_role, action, digest, event=False)
Emit the landing's attestation (input and output the content digest: the chain's leaf)
unless one already names it, so a re-run after a crash attests nothing twice. event is a
landing that is an event of its own though its bytes were attested before, a revert that
appended a version: it is attested again. None when there is no attestor or nothing to add.
lexical
The lexical representation of landed text: tokens and BM25 weights, with no model (dn-two-phase-ingestion D1, D2).
A tokenizer alone gives an item a representation a query can be ranked against: the tokens of its
chunks, each weighted by how rare it is across the units an index holds. This module is the
arithmetic, pure over its arguments, so the store that keeps the postings
(core/stores/lexical.py) and a test call one function: the tokens of a text, the term counts of
a unit, the inverse document frequency of a term among n units, and the BM25 weight of a term
in a unit of length dl against the mean length avgdl,
w(t, d) = idf(t) · tf · (k1 + 1) / (tf + k1 · (1 − b + b · dl / avgdl)),
idf(t) = ln(1 + (n − df(t) + 0.5) / (df(t) + 0.5)),
with k1 = 1.2 and b = 0.75 (Robertson and Zaragoza 2009). A query's score for a unit is the
sum over the query's distinct terms. The representation is a function of the bytes alone, so it
is derived, rebuilt from the raw store as the vectors are, and it is complete the moment the item
lands: the structural phase of a two-phase landing answers a lexical near before any vector
exists (ING-19, ING-21). fuse combines a lexical and a semantic ranking by reciprocal rank
(Cormack, Clarke and Buettcher 2009), the "both" arm of the attribution battery.
LexicalIndex is the same weights held in memory as one sparse matrix, units by terms, for a
measurement over a whole corpus at once (the corpus instance's battery, eval/corpus/), where a
query scores millions of units and the store's SQL would be read term by term; rrf is fuse
over arrays of unit numbers, ties broken by unit. Both tokenize with tokens, so the store, the
matrix and a test agree on what a term is.
A term is a Tokenizer's output, and a tokenizer has an identity: the Unicode normal form it
puts text in, its case fold, whether combining marks continue a token, and the version of the
Unicode database its character classes come from. One text in two normal forms (a precomposed
"é" and an "e" followed by a combining acute) is one text to a reader, and must give one set of
terms; without normalization the second form even splits the word at its mark. Units tokenized
under one identity cannot be scored against a query tokenized under another, so every store of
units records the identity it was built with and refuses another (core/stores/lexical.py), as
the plane records its embedder. LEGACY is the tokenizer every index was built with before the
identity was recorded; TOKENIZER is the current one. Only terms are normalized: content
hashes, the raw store and the chunks stay on the bytes as they came.
K1 = 1.2
module-attribute
B = 0.75
module-attribute
RRF_C = 60.0
module-attribute
Form = Literal['NFC', 'NFKC']
module-attribute
Fold = Literal['lower', 'casefold']
module-attribute
FORMS = (None, 'NFC', 'NFKC')
module-attribute
FOLDS = ('lower', 'casefold')
module-attribute
LEGACY = Tokenizer(form=None, fold='lower', marks=False)
module-attribute
TOKENIZER = Tokenizer(form='NFKC', fold='casefold', marks=True)
module-attribute
TokenizerMismatch
Bases: RuntimeError
Units tokenized under one identity met a tokenizer of another. A query's terms and the units' terms would disagree on what a word is, which no score can detect, so the store refuses until its units are re-derived.
Tokenizer
dataclass
How text becomes terms: put in the normal form form (None: as it came), fold case, then
take maximal runs of letters and digits, with combining marks inside a run when marks. Text
is normalized again after the fold, which can leave it unnormalized, so the terms of a text
and of any canonically equivalent text are the same (and of any compatibility-equivalent text
under NFKC).
form = 'NFKC'
class-attribute
instance-attribute
fold = 'casefold'
class-attribute
instance-attribute
marks = True
class-attribute
instance-attribute
identity
property
What a store records: every parameter the terms depend on, the Unicode database's version among them (its character classes and case folds change between versions).
from_identity(identity)
staticmethod
The tokenizer an identity names, if this process can reproduce it; a different Unicode database cannot, and is refused.
LexicalIndex
dataclass
The BM25 weights of a fixed set of units, in memory: one sparse matrix, units by terms, and the tokenizer that made its terms, which tokenizes its queries too.
vocab
instance-attribute
weights
instance-attribute
tokenizer = LEGACY
class-attribute
instance-attribute
units
property
build(texts, *, k1=K1, b=B, batch=100000, tokenizer=None)
staticmethod
The index of texts, one unit each, in order, by tokenizer (the current one when
None).
scores(query)
Every unit's score for a query (zeros where no term matches).
search(query, k=10, among=None)
The top-k units for a query, best first, among the given units if any; a unit that matches no term is never returned.
save(d)
Write the index under d, its tokenizer's identity beside its terms; returns its
bytes.
load(d)
staticmethod
The index saved under d, with the tokenizer it was built by (LEGACY's when it
records none); TokenizerMismatch when this process cannot reproduce that tokenizer.
tokens(text)
The tokens of a text, in order, by the current tokenizer.
term_counts(text)
Each distinct term of a text with its count: one unit's postings.
idf(n, df)
The inverse document frequency of a term in df of n units.
tf_weight(tf, dl, avgdl, *, k1=K1, b=B)
The saturated, length-normalized term frequency of BM25.
bm25(query, units, *, k1=K1, b=B)
Every unit's score for a query, over units given as term counts: the reference the store's SQL-backed scoring is tested against. A unit that shares no term scores 0.
fuse(rankings, *, k, c=RRF_C)
Reciprocal rank fusion of rankings of one set of items: an item's score is the sum over
the rankings of 1 / (c + rank), ranks from 1; the top k, best first, ties by first
appearance.
rrf(rankings, k=10, c=RRF_C)
Reciprocal rank fusion of rankings of one set of units, as fuse, over arrays of unit
numbers: the top k, best first, ties by unit.
mint_ids
The id-mint migration — durable id:: identity + version re-key (bp-034; oq-0019 B; §11 ruling).
The owner-run, offline, idempotent, reversible migrator that mints a durable Logseq id:: into each
vault note lacking a stable id AND re-keys that note's version history from source_path to the
minted id, so no lineage forks at the identity switch — now or on any future rename (the A6 payoff,
temporal-retrieval-algebra.md §2.4). It mirrors core/ingest/purge.py: a deliberate, owner-gated
(confirm=True, fail-closed), offline act — NEVER the watcher's default, NEVER fired in a build
session. The owner runs it once, corpus-wide, with the daemon DOWN (a live-store migration is
deploy-coupled — finding-0066).
Three primitives + one orchestrator:
* preview() — Item 13: pure read. Enumerate the mint set (no-stable-id notes), the re-key plan,
and a pre-state manifest (per-chain (seq, digest)) for verification. Mutates
nothing.
* mint() — Item 15: byte-preserving id:: <uuid4> insertion (one line added, nothing else).
Idempotent-skip any note that already carries a stable id.
* run() — Item 16: backup → dry-run → [confirm] → PER-NOTE (mint-then-rekey) → rescan →
verify no lineage forked → report. Refuses unless the daemon is down.
Why per-note mint-then-rekey and not "re-key all stores, then mint all notes" (the §6 amendment):
the batch order has a crash window — a chain re-keyed to id₁ never written into its note, so a naive
re-run mints a fresh id₂ and orphans the id₁ chain. Minting a note FIRST, then re-keying that note's
chain from its ACTUAL state (its id:: vs which key holds its chain), makes any interleaving
converge — the re-key old is always the note's source_path (a chain lives under either its
source_path, un-migrated, or its own id::, already migrated → CHECK ORDER (ii) no-op).
Zone A, no network (the seal holds); the script scripts/mint_ids.py is the owner-facing entry.
MintRefusedError
Bases: RuntimeError
The migration was refused by a safety gate — no confirm, a live daemon, or a note whose
structure the byte-preserving minter cannot place an id:: into safely (§10: never guess a
format that could corrupt an authored note). The PurgeRefusedError pattern: fail-closed,
named, never a silent partial write.
NotePlan
dataclass
One note's place in the migration: where its chain lives now, and where it must end up.
source_path
instance-attribute
current_doc_id
instance-attribute
target_id
instance-attribute
action
instance-attribute
ChainSnapshot
dataclass
A per-chain pre-state manifest (§4a): the (version_seq, digest) sequence, so verification
checks CARRIED CONTENT equality (old key emptiness alone is necessary but not sufficient).
doc_id
instance-attribute
rows
instance-attribute
MigrationPlan
dataclass
mint_set
instance-attribute
rekey
instance-attribute
skipped
instance-attribute
pre_state
instance-attribute
pre_state_for(doc_id)
MintReport
dataclass
minted = field(default_factory=dict)
class-attribute
instance-attribute
rekeyed = 0
class-attribute
instance-attribute
rescan = ''
class-attribute
instance-attribute
verified = False
class-attribute
instance-attribute
backup_dir = ''
class-attribute
instance-attribute
logseq_id(parsed)
The note's durable id:: value (what bp-031 resolution reads back), or None if absent.
has_yaml_id(text)
Does the note's YAML front-matter (if any) carry an id: key? Repo docs do (id: dn-…).
has_stable_id(parsed)
True if the note already carries a durable id — a Logseq id:: OR a YAML id: — so the
minter SKIPS it (idempotent). This is what keeps repo design-notes/findings untouched.
preview(sync)
Item 13 — the migration's auditable plan, computed by PURE READ (opens no write handle,
mutates no store or file). Enumerates: (a) the mint set — vault notes lacking a stable id — and
(b) the re-key plan — for every in-scope note, source_path → its durable id:: where the chain
is not already filed there. Emits the §4a pre-state manifest so run() can verify carried
content, not merely old-key emptiness.
mint(sync, source_paths)
Item 15 — insert a durable id:: <uuid4> into each named note, byte-preserving except the
single added line. Idempotent-skip any note that gained a stable id since the preview (checked
here). Writes ONLY under the vault (the caller passes vault-scoped source_paths). Returns the
source_path → minted id map the re-key consumes.
run(sync, *, declaration, confirm=False, backup_dir, run_ledger=None, rescan=None)
Item 16 — the offline, confirm-gated, reversible orchestration. Order (§6, the crash-safe
per-note amendment):
daemon-down + confirm gates → backup(vault + version/catalog stores) → dry-run plan →
PER NOTE { mint id:: (if none) → re-key ITS chain source_path→id:: on both stores } →
rescan → VERIFY no lineage forked (against the §4a manifest) → report.
Fail-closed: refuses unless confirm=True, unless the daemon is down (a live daemon would race
the re-key against the watcher's re-ingest — finding-0066), and unless every backup is readable
+ non-empty before any mutation. Reversible: restore_from_backup(backup_dir, sync) reproduces
the pre-migration state exactly (the integration test rehearses this). The re-key is owner-
authorized (declaration); a machine caller is refused at each store boundary.
restore_from_backup(backup_dir, sync)
Reverse a migration: copy the backed-up stores + vault back over the live ones. The stores must be CLOSED first (SQLite holds the file); the caller re-opens after. The integration test exercises this to prove reversibility (§4b) — it is not merely asserted.
purge
Purge-raw — deliberate, owner-gated TRUE deletion (design-notes/vault-sync-and-capture.md).
The watcher never deletes raw: a vault delete only TOMBSTONES (derived dropped, raw kept) so nothing is lost and a re-add dedups. But for genuine privacy deletion the owner must be able to destroy the source bytes too. That is this action — and it is deliberately NOT the watcher's default, mirroring the propose/approve posture of the self-modification gate (Invariant 4): destroying ground truth is consequential and irreversible, so it requires an explicit owner act and refuses to fire on content still in use.
Two gates, both fail-closed:
1. confirm=True must be passed explicitly (no accidental purge).
2. the digest must have zero active references — an active note still holds this content,
so tombstone/delete it from the vault first. (Purge operates on already-tombstoned data.)
On success it drops derived rows, removes the raw blob, and deletes the tombstoned catalog
rows for that digest. scripts/purge_raw.py is the owner-facing entry.
PurgeRefusedError
Bases: RuntimeError
The purge was refused by a safety gate (no confirm, or content still referenced).
PurgeResult
dataclass
digest
instance-attribute
raw_removed
instance-attribute
paths_removed
instance-attribute
purge_raw(digest, *, raw, store, catalog, confirm=False)
Permanently remove a note's raw bytes + derived rows. Owner-gated; see module docstring.
readers
What a script reads through: the palace's sources and places, opened under the speaking role
(dn-ingress-language §E2, §E3). The view the evaluator is handed (core.sentence.interpret.Palace).
Every value a reader yields is labelled here, by the source's rule, never by a script: an item's
content is Content with its label and origin, and every string read off it (its path, title,
digest, properties) is an OStr with the same, so the type checker's sets are sound at run time
(ING-18). A string is not the item's bytes: stored, it is composed and observed (§E3). The one
string that names something is the property a source declares as its items' identity (id:: in
the vault), whose origin says so, so a store may take it as the item's identity (R6) and no other
field can pose as one. An entry of a place is the palace's account of a row, and its strings are
observed. A structured source's edge reader runs only when the caller asks (the daemon's own
syncs and the owner's CLI), never for a request a role spoke. A structured source whose rule may
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. 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.
Listing
A directory source's items in path order, listed at once and read one by one: len is
the number of paths listed, which the evaluator pays for before it reads the first.
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
class-attribute
instance-attribute
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;
refresh runs a structured source's edge reader before its first read.
table = table
instance-attribute
role = role
instance-attribute
catalog = catalog
instance-attribute
open(name)
files(h)
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.
file(h, path)
exists(h, path)
has(path)
Whether the source that owns a path still has it (R6, R7): asked of the source itself, whether or not the speaking role may open it. A stream only appends: an item it has yielded stays its own, a later version of it a new item at the same path, so it has every path in its space (no script retires a stream's item, R7, and no path there lends its identity, R6).
items(h, batch=None)
A structured source's items. A stream's are those past its cursor, the next batch
of them when a batch is given (dn-corpus-instance §5.2); only a stream has a cursor, so
only a stream takes a batch.
landed(outcomes=())
A plan that read a structured source has landed: record the source's cursor if the plan stored every item it read from it (landed, unchanged, or refused by a rule, which a retry would refuse again). A plan that only looked at a source records nothing, so the heartbeat never reads a source as synced that was not. A consumed records source loses each document every item of which the plan landed or found unchanged, never one an item of which was refused, and never one rewritten since it was read: the raw store holds its bytes now, and the next read is of what is pending.
stored(place, prefix)
query(sentence)
edge_env()
The environment an edge reader runs in: launchd's PATH lacks Homebrew's, where podman lives (the third review's finding 4).
read_mark(mark)
What a repository source last landed, or None when it never landed whole.
build_view(cfg, table, role, catalog, **kw)
repository
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.
RepositoryError
Bases: RuntimeError
The repository, its ref or one of its blobs could not be read.
Entry
dataclass
One regular file of a tree: its path in the repository, its blob and the blob's size.
path
instance-attribute
blob
instance-attribute
size
instance-attribute
commit_of(location, ref)
The commit a ref names in the repository.
itemizable(path)
Whether a path of the tree may be an item: not the foundation's, not a tool directory's.
tree(location, commit)
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.
read_blobs(location, blobs)
Each blob's bytes, in the order asked, read by one cat-file --batch process.
is_text(data)
Whether a blob is text: it holds no NUL byte.
behind(location, landed, ref)
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.
run
Run a full ingest of the configured vault into the real stores (BUILD-SPEC §8, §9).
Rebuild semantics: the raw store is append-only and content-addressed (immutable, dedup); the vector store is rebuilt from scratch each run, because vectors are a derived layer regenerable from raw. This is the entry the scheduler (Phase 3) will drive as a job.
IngestSummary
dataclass
notes
instance-attribute
new_raw
instance-attribute
chunks_indexed
instance-attribute
vector_rows
instance-attribute
run_ingest(config=None, *, rebuild=True)
stream
A stream source: items in sequence, written by an edge reader, landed a batch past a cursor (dn-corpus-instance §5.2; dn-ingress-language §E2).
A stream lives in one directory, the handoff between an edge reader and the lander (the edge
writes it with edge/corpus/stream.py and imports nothing of core; this module only reads it).
Its edge reader appends items, each a JSON object on one line with a sequence number (seq, from
1, strictly increasing), an id (the item's identity within the source, the last component of its
path), its content and its title; the reader writes them in part files under stream/ and
names a part in stream/manifest.json only once the part is whole, so a reader of the stream
never sees a part being written. The lander records the last
seq it landed in cursor.json beside the stream, once the plan that read the batch has landed
(the cursor of §E2): read_items(d, after=cursor, limit=b) is then the next batch, and a batch
interrupted before its cursor was written is read again, whole, by the next request. Reading is
pure and bounded: a part above the handoff cap is refused, a line above the record cap is
refused, and nothing here touches the network.
STREAM = 'stream'
module-attribute
MANIFEST = 'manifest.json'
module-attribute
CURSOR = 'cursor.json'
module-attribute
MAX_PART_BYTES = 256 << 20
module-attribute
MAX_LINE_BYTES = (32 << 20) + (64 << 10)
module-attribute
StreamError
Bases: ValueError
A stream that cannot be read as one: a missing or malformed manifest, a part out of order, a line that is not an item.
Part
dataclass
file
instance-attribute
first
instance-attribute
last
instance-attribute
items
instance-attribute
bytes
instance-attribute
item_id_ok(item_id)
Whether an item id is one path component the writer takes: letters, digits, ., _, :
and -, at most 200 characters, not starting with a separator.
manifest(d)
The whole parts of the stream in d, in order; none when it has no manifest yet.
last_seq(d)
The last sequence number the stream's whole parts hold (0 for an empty stream).
cursor(d)
The last sequence number landed (0 before the first batch).
write_cursor(d, seq)
Record that every item up to seq has landed: written once the plan that read them has
landed, never before (a batch interrupted earlier is read again, whole).
read_items(d, *, after=0, limit=None)
The items with seq > after, in order, at most limit of them, read only from the parts
that hold them. Each is checked: its seq the next in order, an id the writer takes, a
string content.
sync
Incremental vault sync — re-ingest changed notes (design-notes/vault-sync-and-capture.md).
Core-side, LOCAL filesystem only: it reads vault files and writes the local stores. No
network, no edge, no sockets — the seal holds and the import-lint proves it. This is the
deterministic engine; the watcher (core/ingest/watch.py) only triggers it, and the
scheduler runs it as a background job so all store mutation stays on the single writer.
Idempotency rides on the existing content-addressing plus the vault catalog:
- unchanged (same digest, still active) → no-op: no re-embed, no new rows.
- changed / new → (re)embed the note's chunks; the previous digest's derived rows are dropped iff no other active file still references that content.
- deleted → tombstone: derived rows dropped, the catalog row marked inactive, and the
raw blob kept (raw is sacred) so a later re-add dedups. True deletion is the separate,
owner-gated purge (
core/ingest/purge.py), never done here.
Everything ingested is authored-solo — the existing AUTHORED provenance tag (the spectrum
split is deferred, see PROGRESS.md). The mirror firewall is unaffected: these are the owner's
own notes, the mirror's ground truth.
SyncOutcome
Bases: Enum
UNCHANGED = 'unchanged'
class-attribute
instance-attribute
INDEXED = 'indexed'
class-attribute
instance-attribute
TOMBSTONED = 'tombstoned'
class-attribute
instance-attribute
SyncReport
dataclass
indexed = 0
class-attribute
instance-attribute
unchanged = 0
class-attribute
instance-attribute
tombstoned = 0
class-attribute
instance-attribute
tally(outcome)
VaultSync
dataclass
vault
instance-attribute
raw
instance-attribute
store
instance-attribute
catalog
instance-attribute
embedder
instance-attribute
pattern = '**/*.md'
class-attribute
instance-attribute
exclude_dirs = DEFAULT_EXCLUDE_DIRS
class-attribute
instance-attribute
max_chars = 1200
class-attribute
instance-attribute
overlap_chars = 150
class-attribute
instance-attribute
attestor = None
class-attribute
instance-attribute
version_store = None
class-attribute
instance-attribute
in_scope(path)
Whether one path is a note the rescan would see: a regular file under the vault that
matches the note pattern and lies in no excluded directory. The ingress's ingest note
asks before landing a single note (dn-ingress §9), so the scope that binds the
rescan binds the sentence.
sync_path(path, *, rename_by_digest=None)
Re-ingest one note as a chunk-level amendment; unchanged content is a no-op.
rename_by_digest (passed by rescan) maps a just-vanished path's content digest to its
(source_path, doc_id); a NEW path with an exact-content match adopts that doc_id so a
rename continues the version chain instead of forking it (bp-031 Item 2).
sync_one(path)
One note, as the rescan would land it: a path new to the catalog whose bytes are a
vanished note's (one still active whose file is gone) adopts that note's identity, so a
note renamed just before it is ingested alone keeps its version chain (the ingress's
ingest note).
handle_deleted(source_path)
A vault file disappeared: drop its projection (by source_path), then tombstone it.
Source-scoped, so an identical-content file elsewhere keeps its own rows. Raw is kept
(sacred); true deletion is the separate, owner-gated purge (core/ingest/purge.py).
[banner: correction] The tombstone is the delete's key: the rescan retires only paths the catalog holds active whose file is gone. It was written first, so a crash before the retire left the deleted note current in the plane and no rescan ever came back to it. It is written last now (ING-7's order, key last): a crash between the two leaves the path active, the next rescan repeats the delete, and the retire is idempotent.
owns(source_path)
Whether a catalog row is the vault's: its path lies under the vault, as the rescan
names its notes. The dialogue's turns (dialogue/…), the curated docs and anything else
the shared catalog holds are not, and a rescan never tombstones them.
rescan()
Full catalog-vs-vault reconciliation. The watcher triggers this; it is the idempotent backbone (an unchanged re-scan does no work) and also the catch-up path for changes that happened while no watcher was running.
in_vault_scope(vault, path, *, pattern='**/*.md', exclude_dirs=DEFAULT_EXCLUDE_DIRS)
iter_vault's predicate for one path: a regular file under vault (resolved, so a
symlink out of the vault is out of scope) that matches pattern, lies in no excluded
directory, and is spelled as the disk spells it. On a case-insensitive disk PAGES/A.md
opens pages/a.md, but the rescan names it pages/a.md: a path in another case is out of
scope, and an excluded directory is excluded in any case.
build_vault_sync(config=None)
Wire a VaultSync against the configured vault + real stores + embedder.
table
The palace's table: the sources a script may open, the places it may write, the roles that speak, the jobs a script may start, and what each role may spend (dn-ingress-language §E2, §E4, §E7, §E10).
As an operating system has a mount table, owners and permissions, the palace has this table, and
it is the one module where the palace's domain is named: the vault, the curated docs, the
dialogue readers, the Ambassador's inbox, the strata as places. The language
(core/sentence/script.py, interpret.py, script_check.py) names none of it; a script names a
source or a place by a string the table must know.
AUTHORED_SOLO = Provenance.AUTHORED_SOLO.value
module-attribute
AUTHORED_DIALOGUE = Provenance.AUTHORED_DIALOGUE.value
module-attribute
OBSERVED = Provenance.OBSERVED.value
module-attribute
CURATED = Provenance.CURATED.value
module-attribute
CODE_LABEL = Provenance.CODE.value
module-attribute
MAX_ITEM_BYTES = 16 << 20
module-attribute
MAX_HANDOFF_BYTES = 256 << 20
module-attribute
MAX_RECORD_BYTES = 2 * MAX_ITEM_BYTES + (64 << 10)
module-attribute
OPERATOR_BUDGET = 50000000000
module-attribute
INBOX = 'inbox'
module-attribute
INBOX_SPACE = 'dialogue/inbox/'
module-attribute
REQUEST_ID = re.compile('[0-9a-f]{32}')
module-attribute
PLACES = {'mirror_authored': Place('mirror_authored', Stratum.MIRROR_AUTHORED, _classes(Stratum.MIRROR_AUTHORED), versions=True, action='ingest_note'), 'dialogue': Place('dialogue', Stratum.DIALOGUE, _classes(Stratum.DIALOGUE), versions=False, action='capture'), 'observed': Place('observed', Stratum.OBSERVED, _classes(Stratum.OBSERVED), versions=False, action='capture'), 'curated': Place('curated', Stratum.CURATED, _classes(Stratum.CURATED), versions=False, action='ingest_curated'), 'reference': Place('reference', Stratum.REFERENCE, _classes(Stratum.REFERENCE), versions=True, action='ingest_code')}
module-attribute
JOBS = {'dream': Job('dream', 'dream', (Stratum.INTERPRETED,), propose=True), 'curate': Job('curate', 'curate', (Stratum.INTERPRETED,), propose=True), 'relate': Job('relate', 'relate', (Stratum.INTERPRETED,), propose=True, args={'pairs': 50}), 'code_sync': Job('code_sync', 'code_sync', (Stratum.REFERENCE,), clock=Clock.COMMIT), 'chat_sync': Job('chat_sync', 'chat_sync', (Stratum.DIALOGUE_TRANSCRIPT,), fibers=frozenset({'C'}), clock=Clock.COMMIT), 'code_observe': Job('code_observe', 'code_observe', (Stratum.REFERENCE,), fibers=frozenset({'F'}), clock=Clock.COMMIT), 'embed': Job('embed', 'embed', (Stratum.MIRROR_AUTHORED, Stratum.DIALOGUE, Stratum.OBSERVED, Stratum.CURATED))}
module-attribute
INTERACTIVE = frozenset({'capture'})
module-attribute
COALESCING = {'sync_vault': 'vault_sync', 'sync_dialogue': 'dialogue_sync'}
module-attribute
CORPUS = 'corpus'
module-attribute
CORPUS_SPACE = 'corpus/'
module-attribute
CODE = 'code'
module-attribute
CODE_SPACE = 'code/'
module-attribute
LEGACY_DIALOGUE = 'dialogue/door/'
module-attribute
Source
dataclass
A source: where it is, how it is read, how its items are labelled, who may open it, and
which paths are its own (R8). A records source is a directory of the daemon's own JSON
documents, each read as a structured source's document; one it consumes 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). 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 <space><path in the repository>
(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
instance-attribute
kind
instance-attribute
location
instance-attribute
format
instance-attribute
readers
instance-attribute
patterns = ()
class-attribute
instance-attribute
exclude = frozenset()
class-attribute
instance-attribute
label = None
class-attribute
instance-attribute
items_of = None
class-attribute
instance-attribute
path_of = None
class-attribute
instance-attribute
label_of = None
class-attribute
instance-attribute
labels = frozenset()
class-attribute
instance-attribute
content_field = 'content'
class-attribute
instance-attribute
space = ''
class-attribute
instance-attribute
refresh = None
class-attribute
instance-attribute
refresh_timeout = 180
class-attribute
instance-attribute
cursor_of = None
class-attribute
instance-attribute
identity = None
class-attribute
instance-attribute
title_of = None
class-attribute
instance-attribute
consume = False
class-attribute
instance-attribute
embed = True
class-attribute
instance-attribute
ref = ''
class-attribute
instance-attribute
mark = None
class-attribute
instance-attribute
in_scope(path)
Whether a path is one of a directory source's items, existing or not: under the location, matching a pattern, in no excluded directory in any case.
spelled(path, listdir=os.listdir)
Whether every component of a path under the location is spelled as the directory
lists it (a case-insensitive disk opens PAGES/A.md for pages/a.md; the source names
it the second way only). listdir may be a reader's cache of the listings.
owns(path)
Whether a path lies in this source's own space (R8).
Place
dataclass
A place: a stratum, the labels it accepts, whether it keeps version chains, the action its attestations record.
name
instance-attribute
stratum
instance-attribute
accepts
instance-attribute
versions
instance-attribute
action
instance-attribute
clock = Clock.PROJECTION_EVENT
class-attribute
instance-attribute
Job
dataclass
A job a script may start: the queue's kind, the strata it writes (for admission), its arguments and their bounds.
name
instance-attribute
kind
instance-attribute
strata
instance-attribute
fibers = frozenset()
class-attribute
instance-attribute
clock = Clock.PROJECTION_EVENT
class-attribute
instance-attribute
propose = False
class-attribute
instance-attribute
args = field(default_factory=dict)
class-attribute
instance-attribute
Role
dataclass
A role: the path prefixes it may write in each place (R3), its budget (§E10), and the labels of the rows it may retire (R7): only the owner's role retires the owner's rows, so no agent can take an authored row out of the palace, whatever its source no longer shows.
name
instance-attribute
prefixes
instance-attribute
budget
instance-attribute
retires = frozenset({OBSERVED})
class-attribute
instance-attribute
retire_only = field(default_factory=dict)
class-attribute
instance-attribute
Table
dataclass
sources
instance-attribute
places
instance-attribute
jobs
instance-attribute
roles
instance-attribute
relations
instance-attribute
interactive
instance-attribute
coalescing
instance-attribute
place_accepts(place)
job_known(job)
source_readable(name, role)
source_labels(name)
owner(path)
The source whose space a path lies in (R8), if any.
may_write(role, place, path)
R3: the role writes the place only under its prefixes, the path normalized.
may_retire(role, place, path)
R3 for a retire: the role's write prefixes, and the prefixes it only retires.
normal(path)
A path the writer takes: no . or .. or empty component, and no character that is not
printed as itself (a control character, DEL, a format character such as a bidirectional
override, a line or paragraph separator), so no path displays as another.
inbox_dir(cfg)
The inbox's record: <data>/inbox, the daemon's account's alone.
inbox_component(conversation)
A conversation as one component of an inbox item's path: itself when it is a plain name
(letters, digits, ., _, -, at most 64, not starting with .), else c- and sixteen hex
digits of its digest, so no conversation adds a component, leaves the space, or displays as
another.
repository_mark(cfg, name)
Where a repository source records the commit whose files it last landed whole.
build_table(cfg)
This palace's table, from its configuration.
write_cursor(source, doc)
Record the newest change a structured source showed, once a plan that read it has landed (the heartbeat reads it to tell a failed sync from a done one).
watch
Local directory watcher — core-side, LOCAL filesystem only, NO network.
Watches a configured directory and signals when its files change, so the system keeps derived
state current as the source is written. It does not mutate the stores itself and does
not import the scheduler: on a change it just calls an injected on_change callback. A
scheduler wiring supplies that callback — scheduler/vault_sync.py enqueues a background
vault_sync (the owner's vault), scheduler/chat_sync.py enqueues a chat_sync (the Claude
Code transcripts, bp-069) — so all store writes stay on the single supervisor writer. One
generic watcher, many watched directories (the class was VaultWatcher; generalizing it to
DirectoryWatcher is a pure rename — a Vault-named class watching chat is a DRY smell).
Seal integrity: this module imports no edge, no sockets, no http — only the local
filesystem (the import-lint proves it). watchdog (FSEvents/inotify) is an OPTIONAL real-time
backend, imported lazily; without it the watcher falls back to polling (a timer that
triggers a periodic rescan). Either way on_change ultimately runs an idempotent re-ingest, so
missed/duplicate events are harmless.
OnChange = Callable[[], None]
module-attribute
ObserverLike
Bases: Protocol
The slice of a watchdog Observer this watcher drives (watchdog is an OPTIONAL dependency, so its own types never appear in signatures here).
stop()
join(timeout=...)
DirectoryWatcher
dataclass
path
instance-attribute
on_change
instance-attribute
debounce_s = 1.0
class-attribute
instance-attribute
poll_interval_s = 5.0
class-attribute
instance-attribute
backend = field(default='', init=False)
class-attribute
instance-attribute
notify()
A change was observed. Arm/re-arm the debounce timer so a save burst fires once.
start(*, prefer='auto')
Begin watching. prefer: 'auto' (watchdog if importable, else poll), 'watchdog',
or 'poll'. Returns the backend actually started.
stop()
writer
The ingress's one writer: it lands a plan effect by effect, each by the rules of dn-ingress-language §E4 (R2 to R8), in the first form's order with the key last (ING-7, ING-16).
A store lands as the first form's landers landed: the raw object, the plane's chunk-level
amendment, the version chain where the place keeps one, the attestation, and last the catalog's
digest, the idempotence key the UNCHANGED check reads (for every place, the key counts only while
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). 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
budget, so a plan that would overrun it is refused before anything is paid.
Each rule is a theorem's hypothesis in formal/Palace/Script.lean: R4 and R8 give the firewall
(ING-14, firewall_store, owned_by_source), R3 confinement (ING-15), R5 and R6 fixed labels and
identities that move only with their bytes (ING-17), R7 retire as reconciliation. The writer is
stricter than the model in places, each written where it is checked: content under any label but
the observed one is an item's whole content under its item's title; an identity read off an item
is the one it declares, and no path takes one another path of its source still holds; a held
identity moves with its label; a role retires only the labels the table gives it; a job runs once
a request, inside its role's share of the queue.
Stores
dataclass
What the writer lands into; each injectable, so the writer is tested with fakes.
raw
instance-attribute
plane
instance-attribute
embedder
instance-attribute
catalog
instance-attribute
versions = None
class-attribute
instance-attribute
attestor = None
class-attribute
instance-attribute
edges = None
class-attribute
instance-attribute
enqueue = None
class-attribute
instance-attribute
lexical = None
class-attribute
instance-attribute
Outcome
dataclass
What one effect did: landed, unchanged, retired, linked, queued, or refused with the rule.
effect
instance-attribute
path
instance-attribute
status
instance-attribute
why = ''
class-attribute
instance-attribute
digest = ''
class-attribute
instance-attribute
attestations = ()
class-attribute
instance-attribute
job = None
class-attribute
instance-attribute
to_dict()
Refused
Bases: Exception
rule = rule
instance-attribute
why = why
instance-attribute
Writer
dataclass
table
instance-attribute
role
instance-attribute
stores
instance-attribute
has
instance-attribute
meter = None
class-attribute
instance-attribute
request = None
class-attribute
instance-attribute
reads = frozenset()
class-attribute
instance-attribute
max_chars = 1200
class-attribute
instance-attribute
overlap_chars = 150
class-attribute
instance-attribute
batch = False
class-attribute
instance-attribute
lazy = False
class-attribute
instance-attribute
embedding = True
class-attribute
instance-attribute
landed = field(default_factory=list)
class-attribute
instance-attribute
started = field(default_factory=set)
class-attribute
instance-attribute
timing = field(default_factory=dict)
class-attribute
instance-attribute
keeps_vectors(path)
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).
embeds_now(path)
Whether a store at path writes its plane rows before its key: it has a vector, and
the landing is not lazy.
lexical_witness(path)
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.
land(plan)
derive_later()
Ask for the embed drain once a plan has landed an item without its vector: one job of
the queue's coalescing kind, folded into the row already waiting if there is one, under no
request, so it is the daemon's own and counts against no role's share. Without a queue (the
owner's CLI or a runner beside no daemon) the items stay pending until embed runs.
land_batch(plan)
A plan of stores on pairwise distinct paths, each naming its path's own identity,
landed one stage at a time across the plan. Every store is admitted first by the same
rules as store (none of them reads what another store of such a plan writes: the paths
differ and no identity is borrowed). Then every admitted store's raw object and chunks;
then the lexical units of every store in one transaction when the index is open, and,
unless the landing is lazy, the plane, one embedding of the atoms it does not hold (ING-5)
and one landing of every fiber; then, store by store, the version row, the attestation and
the key, last.
Each store's steps keep its own order, the key after its rows (ING-7), so a crash at any
point leaves every store at a prefix of its own steps, and the plan run again lands
exactly the uninterrupted plan (ING-9, ING-11; ING-16 on the plan).
price(plan)
The plan's cost, counted before any of it is paid: its writes, each store the UNCHANGED check would not skip (a store the rules will refuse is counted too: the price is a bound) and each retire, link and run; and its embeds, the distinct atoms its stores would add that the plane does not hold (ING-5). Charged to the budget; returns the two counts.
[banner: correction] It asked known_atoms, which answers for every class, so the charge
a receipt reports told the script's role whether an atom exists in a class it cannot read
(the formal audit; known_eq, Witness.known_interferes). It asks for the role's own
classes now (known_atoms_in), so an atom only another class holds is charged as new: the
price stays a bound, and the land itself still reuses the atom.
unchanged(e)
The UNCHANGED check: the path holds these bytes, active, under the same label, and the plane holds their rows at this path, current (under lazy embedding, the lexical index holds their units, since the rows are the drain's, not the landing's). The invariant it keeps is that an active key implies current rows: a retire that died after its plane step and before its tombstone leaves the key active over retired rows, and the same bytes stored again must land.
one(e)
store(e)
admit(e)
The rules a store answers to before anything of it lands (R1 to R8), and the
UNCHANGED check: the store's place, the row its path holds and the identity it takes, or
the outcome when there is nothing to land. Raises Refused with the rule that refused.
derive(e)
A store's first step: its raw object, and its chunks.
index(e, record)
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, 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.
finish(e, adm, record, *, producers=None)
A store's last steps, once its rows are on the plane: the version row where the place
keeps chains, the attestation, and the key, last (ING-7). producers is the ledger's
producers of each digest, (action, id), when the caller read them for a batch; the
attestations this landing adds join them.
identity(e, prev)
R6: a new path's identity is its own, one read off the item it stores, or one held at
a path its source no longer has, with the same bytes. None is the path's own.
holds(path, data, label, digest)
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.)
retire(e)
link(e)
run(e)
batchable(plan)
Whether a plan may land a stage at a time across its effects (Writer.land_batch): every
effect a store naming its path's own identity, on pairwise distinct paths. Such stores read
nothing another of them writes (their paths differ and none borrows an identity), so the
stages commute across them (ING-9).