Skip to content

A repository's maintainers register the document sources Loom pulls from - #215

Merged
zlareb1 merged 1 commit into
mainfrom
feat/knowledge-sources-registry
Nov 3, 2026
Merged

zlareb1 merged 1 commit into
mainfrom
feat/knowledge-sources-registry

Conversation

@zlareb1

@zlareb1 zlareb1 commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

A repository's maintainers can register the document sources Loom will pull the repository's documents from (knowledge.source.list, inspect, add, check, rotate, remove, sync_now). A shared folder read with a service account is the one kind served; the credential is probed before it is stored, sealed at rest and never returned or audited, and code.repo.remove retires the sources of the repository it removes.

Why

Design documents that explain a repository's code live in shared folders, not in the repository. Today they reach Loom only through a one-off client-side push (dev/loom_ingest.py), so nobody sees where a repository's documents came from or keeps them current. This PR adds the registry a server-side sync reads: which sources a repository's documents come from, with what credential. The sync worker itself is a separate change; nothing here fetches a document, and the worker PR adds the switch that turns it on and the fields a sync pass writes.

Design.

  • Table loom.knowledge_sources, migration 080_knowledge_sources.sql, the next free number on main. ReplacingMergeTree keyed (org, namespace, name), modelled on loom.qa_sources and loom.code_repos. Every read is FINAL; every write is a full version row with created_at carried forward, never an ALTER UPDATE. The row holds source_id (a UUID that names one registration: written once by add, carried by every later write), ids and filters (config_json), the sealed credential, and on an inactive row pending_delete, the maintainer's request to retire the source's documents. It never holds a host or a URL: the store's API hosts are constants in server/clients/gdrive.py, so a caller cannot point the server at a host of its choosing.
  • Sync state is a separate row, loom.code_index_state under knowledge_source:<name> (the shape the tracker and the PR-history cursor use), so a sync pass never rewrites the row that holds the credential. In this build it holds only the last sync_now request; list and inspect return it as sync.requested_at. add resets it before a new source goes active, so a re-added name never starts on an old stamp.
  • Who may call. Every op is addressed by the repository's trunk code namespace (the one docs_namespaces() puts its documents in), so the transport's namespace gate decides: VIEWER for list and inspect, ADMIN (the repository's maintainers) for add, check, rotate, remove and sync_now. check writes nothing but is ADMIN because its probe spends the source's rate limit with the stored credential. The tracker's org-level rule was not reused: a tracker source creates its own namespaces, a document source writes into a repository namespace that already has admins. add, check, rotate and sync_now refuse a namespace that is no repository's trunk (NOT_A_CODE_NAMESPACE); for the last three the message says the repository is gone and knowledge.source.remove retires the source. That check reads the cached repository registry (refreshed every code_repos_refresh_seconds), not a forced full read per call: which namespace is a trunk is decided across all of a repository's branches and the operator's entries.
  • One lease per namespace. Every write of a namespace's sources runs under one lease, knowledge-source:<org>:<namespace> (server.core.leases.holding, the claim self-signup and subject revocation use): add, rotate, remove, sync_now, and in code.repo.remove the retirement of the sources together with its registry row. A probe runs outside it. Under the lease add re-checks that the repository is still registered (its loom.code_repos row, through the code plane's CodeRepo.code_repo_row; a repository the operator's configuration owns counts as registered, since code.repo.remove refuses it), the trunk, the name, the quota and the name's documents, then resets the sync state and inserts. rotate re-reads the source and refuses one removed (SOURCE_NOT_FOUND) or removed and added again as another source, told apart by source_id even within one second (SOURCE_REPLACED, 409); sync_now re-reads it too and refuses SOURCE_NOT_FOUND or SOURCE_REPLACED the same way, so a request meant for the source it read is never recorded on another source added under the name meanwhile. So each write's checks still hold when it writes: two adds of one name cannot both succeed, the quota holds, a rotate cannot undo a remove, and an add runs wholly before code.repo.remove's retirement (which then retires it) or wholly after (and sees the repository gone). code.repo.remove retires the sources before its registry row inside the same lease, so a failure between the two leaves the repository registered for a retry. A lease held past a 5 s wait answers OVERLOADED (retry); a lease store that cannot answer refuses (LeaseUnavailable, 503), never writes unlocked.
  • Versions from the servers' clocks. A registry write and a knowledge_source:* sync-state write leave version to the column's DEFAULT, the ClickHouse servers' clocks rather than the writing replica's; the lease-serialized writes stay ordered while those clocks differ by less than the lease's handoff between writes (the code plane's own code_index_state keys keep their writer's version_now; nothing else writes these keys). The one writer outside the lease is loom secrets reseal: it writes a row it read again at that row's version + 1, so it replaces exactly that row and any later write wins over it under the same clock condition.
  • Which documents are a source's. The live documents of its namespace tagged source:<name> and written by the sync worker's actor, worker:knowledge-source-sync (SYNC_WORKER_ACTOR in server/knowledge/domain/sources.py, for the worker to import). A caller can set any tag but cannot write as that actor: no token maps to the worker: kind (the worker:structured-profile precedent). A caller's own document tagged source:<name> is never counted, listed by inspect, retired, or a reason to refuse a name. The source:* tags of a worker-written document belong to the worker: a write by anyone else that keeps the worker as the author (knowledge.update_metadata, or an add/upsert/bulk_add re-save of the same text) may change its other tags but not add or drop a source:* one (SOURCE_TAGS_LOCKED, server/knowledge/app/writes.py).
  • Names. A name stays taken while an earlier source's documents are live, since a new source of the name would take them over: SOURCE_DELETE_PENDING while they wait to be retired, SOURCE_DOCUMENTS_KEPT while kept ones remain (the message asks for them to be deleted with knowledge.delete first). A removed source with no documents frees its name at once.
  • The credential. Sealed with seal("knowledge_sources.credential", …), the same helper and root as the tracker password and repository token, under its own purpose; the tuple joins SEALED/_KEYS in server/cli/secrets.py, so loom secrets reseal covers it. A deployment with no root secret refuses the add (NO_ROOT_SECRET) instead of storing plaintext. A stored credential that no longer opens makes check answer credential_invalid; it is never read as "no auth". remove and code.repo.remove clear it on the inactive row. No output model has a credential field, and add and rotate declare an audit_subject without it (the shape tracker.source.add and code.repo.add use; test_audit_subject_credentials.py stays green): add records namespace, name, kind, config and dry_run, rotate the namespace and name; remove and sync_now carry no credential and keep the default subject (their input). The raw credential argument reaches no call ledger: loom.agent_events.args keeps only allow-listed argument names, and a unit test pins it.
  • The probe is one function per kind (server/knowledge/app/source_probes.py), with gdrive the only kind: exchange the service account's JSON key for a read-only token (JWT bearer grant signed with the key, through the existing pyjwt[crypto] dependency), check every folder is a folder the account can see (one call each, run together; the first failure cancels the rest), then list the included file types of all folders in one call (the first 1000). The whole probe is bounded by knowledge_source_probe_timeout_s; past it add and rotate answer SOURCE_UNREACHABLE and check answers reachable: false. A 403 whose error reason is a rate limit is reported as rate_limited, not as a refused credential. add and rotate probe before any write (CREDENTIAL_REFUSED, SOURCE_UNREACHABLE; dry_run probes only). An error names the HTTP status (http_403) or the folder the account cannot see, never the store's response body.
  • Settings (two): knowledge_sources_max_per_namespace (default 8, SOURCE_QUOTA, LIVE) and knowledge_source_probe_timeout_s (default 20 s, at most 25, under the 30 s op budget, LIVE).
  • Erasure: the table holds configuration and an encrypted credential, no memory or document content, so it joins NO_MEMORY_CONTENT beside loom.qa_sources and loom.code_repos. The documents a sync will write are covered by the existing loom.documents, chunks and document_blobs steps; the sync state goes with the code index (loom.code_index_state is already a step-only table).

Alternatives. An in-process snapshot of the registry with a refresher (the tracker and repository registries have one) was left out: nothing on the request path consults this registry, so the ops read the table directly. An operator JSON twin was left out for the same reason. Storing the sync cursor and status in the registry row was rejected: a sync pass would rewrite the row holding the credential. Identifying a source's documents by tag alone was rejected: any writer can set a tag. Optimistic after-write checks for concurrent writes were rejected: without compare-and-set on a ReplacingMergeTree they do not close every interleaving, so the lease (above) serializes the writes.

Small refactor. The tracker's source name rule moves from server/tracker/app/sources.py to server/tracker/domain/sources.py as SOURCE_NAME_RE, so the document-source rule reuses it instead of copying it.

Scope and risk

New table, new op group, new client module, and two changes to existing ops:

  • code.repo.remove now retires the document sources registered on the removed namespace (inactive rows, credentials cleared), before its registry row and under the namespace's document-source lease, and returns them, sorted, in a new output field sources_deactivated. The namespace purge that follows deletes the sources' sync state (its loom.code_index_state rows) and the namespace's documents; the inactive source rows stay (the table holds no content and is not in the purge). Because it takes that lease it can also answer OVERLOADED while a source write of the namespace runs, and refuses when the lease store cannot answer.
  • knowledge.add, knowledge.upsert, knowledge.bulk_add and knowledge.update_metadata can answer a new refusal, SOURCE_TAGS_LOCKED, when a write by anyone but the sync worker that keeps the worker as a document's author adds or drops a source:* tag. It applies only to documents the sync worker wrote; none exist until the worker ships, so no current call is refused. bulk_add checks every entry before it chunks or embeds any. The other writers of loom.documents (delete and bulk-delete supersede rows, which carry the tags unchanged; the erasure saga's mutations; the retention TTL) never change tags.

Not here: the sync worker (with its on/off setting and the sync pass fields), the converters and the dashboard panel. Until the worker exists, sync_now and remove(delete_documents=true) only record the request, and the docs say so.

Tenant isolation: the namespace gate runs before every handler; list and inspect read only the addressed (org, namespace); an unknown source is SOURCE_NOT_FOUND (404), and a namespace with no sources lists empty. list and inspect are probed by test_cross_principal_leakage.py as registered; the five ADMIN ops are in its _SKIP_OPS, with a unit test that check_authorized refuses a viewer, a writer and another org's admin for each.

Rolling upgrade: build N-1 never reads the new table, nothing written to loom.code_index_state changes a key N-1 reads, the new code.repo.remove output field is additive, and the new refusal concerns documents no build writes yet. An N-1 replica neither takes the lease nor writes sources (the ops are new); one serving code.repo.remove does not retire the namespace's sources, which then stay active, keep their sealed credentials and count toward the quota until knowledge.source.remove retires them, while check, rotate and sync_now refuse them (NOT_A_CODE_NAMESPACE). That is harmless while no worker reads them, and a sync worker must skip them. A source can also outlive its trunk without code.repo.remove (a repository retired by editing the deployment's configuration, or a branch that now outranks the trunk): it is in the same state, and list, inspect and remove still serve it so a maintainer can see and retire it.

Compatibility, rollout and rollback

  • Wire: seven new ops, all maturity="experimental" (HTTP and SDK reach only; not in the MCP all listing). Existing ops: code.repo.remove gains the output field sources_deactivated (additive) and can now answer OVERLOADED (the namespace's document-source lease busy past its 5 s wait; retry) or a 503 when the lease store cannot answer; knowledge.add, upsert, bulk_add and update_metadata gain the refusal SOURCE_TAGS_LOCKED, for sync-written documents only. The new ops answer OVERLOADED and the 503 the same way. Output fields left out on purpose: remove has no deactivated, add no written, the add/rotate probe no reachable (each would always be true; a refusal is the false case), and sync_now no queued. New error codes: NOT_A_CODE_NAMESPACE, BAD_KIND, BAD_CONFIG, SOURCE_EXISTS, SOURCE_QUOTA, NO_ROOT_SECRET, CREDENTIAL_REFUSED, SOURCE_UNREACHABLE, SOURCE_NOT_FOUND, SOURCE_REPLACED, SOURCE_DELETE_PENDING, SOURCE_DOCUMENTS_KEPT, SOURCE_TAGS_LOCKED.
  • Settings (two new): LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE (8, LIVE) and LOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S (20 s, at most 25, LIVE).
  • Operator steps: none. The migration creates one table.
  • Rollback: reverting leaves the loom.knowledge_sources table and any knowledge_source:* state rows; neither is read by the previous build.

Tests

Unit (all pass; counts from pytest --collect-only -q):

  • tests/unit/test_knowledge_sources.py, 72 cases: every handler over an in-memory store and a stub probe: sealed credential round trip, dry run, each refusal before any probe (malformed config elements of any JSON type and a folder id or name with a trailing newline included), quota, duplicate name, no root secret, failed probes store nothing, rotate keeps every other column, does not revive a source removed during its probe and answers SOURCE_REPLACED for one removed and added again with the same creation second, each registration gets its own source_id that rotate and remove carry, remove counts documents with sequential consistency, a sync_now whose source was removed before its lease answers SOURCE_NOT_FOUND with the state unchanged and pending_delete kept, and one whose source was removed and added again answers SOURCE_REPLACED and records nothing on the new source, add re-checks registration, the trunk and the name under the lease, check fails closed on an unopenable credential, remove clears the credential and records pending_delete only with documents, SOURCE_DELETE_PENDING and SOURCE_DOCUMENTS_KEPT, a re-added name's sync state reset before the row goes active, check, rotate and sync_now refuse a source whose namespace is no trunk while inspect reads it and remove retires it; the lease: add, rotate, sync_now and remove take the namespace's lease while check and a dry run take none, and a busy lease (OVERLOADED) or a lease store that cannot answer refuses each of them with nothing written; registration read from the loom.code_repos row (and taken as given for a configuration-owned repository); the trunk check reads the cached registry; the audit subjects; the call ledger keeps no credential; the ADMIN and VIEWER gates through check_authorized; the store's statements (FINAL, key prefix, the sync worker's actor on every document read, LIMIT 200) and full registry and sync-state rows compared with the tables' columns, version left to the server's DEFAULT.
  • tests/unit/test_gdrive_probe.py, 22 cases: the signed assertion verifies with the key's public half, one listing for every folder, each failure class, a 403 rate limit told from a refusal, on the token exchange too (it is checked before the 400/401/403 refusal, and the endpoint's OAuth error string such as rate_limit_exceeded counts as a reason), a folder the account cannot see named in the error and the other folder checks cancelled, an EC or public key refused as CREDENTIAL_REFUSED before any call, the overall time limit, and no error carries the response body.
  • tests/unit/test_source_tags_locked.py, 11 cases: a tag edit and an add, upsert or bulk_add re-save of a worker-written document cannot add or drop a source:* tag; a re-save with the same source:* tags passes and keeps the worker as author; its other tags change; a caller's own document takes any tag; the worker itself may change them; a bulk_add with one locked entry writes and embeds nothing.
  • tests/unit/test_code_repo_remove.py, 14 cases (5 new): the namespace's sources are retired with their credentials cleared; sources and registry row are retired under the one lease; a busy lease and a lease store that cannot answer each refuse with nothing written; a failure retiring the sources leaves the repository registered for a retry.
  • Gate files updated: test_rmt_write_paths.py (the table is a builder), test_schema_baseline.py (the journal), test_sdk_errors_from_response.py (SOURCE_REPLACED reaches the SDK as PreconditionFailed, by its 409), the SDK surface, settings-defaults and LIVE-settings snapshots.

Integration, against a server and ClickHouse of my own (all pass):

  • tests/integration/test_knowledge_sources.py, 8 cases. A source whose namespace is no repository's trunk is refused by check, rotate and sync_now and still inspected and removed; add refusals. The other 6 need LOOM_CODE_ORG/LOOM_CODE_NAMESPACE (set on my server as CI sets them; they skip without): list, inspect, sync_now, remove and check over a source seeded on that namespace with the state and registry rows read back, and the name rule: documents written as the sync worker make remove(delete_documents=true) write pending_delete and add answer SOURCE_DELETE_PENDING, or SOURCE_DOCUMENTS_KEPT when kept, while a caller's tagged document is neither listed nor counted and never holds the name. Their finalizer deletes the documents, registry rows and sync-state rows they wrote; a count after the run found none left.
  • tests/integration/test_cross_principal_leakage.py with the source tests, through the real lease (its statements show in system.query_log): 39 passed, 14 skipped on the head rebased onto current main (the end-user issuer cases this local setup does not configure); the new reads are walked as registered.

Gates:

  • make test-mixed-version REQUIRE=1 (N-1 = merge base with main, N = this branch with migration 080 including source_id, on one throwaway ClickHouse): mixed-version gate: ok.
  • Full unit suite (pytest tests/unit -q -p no:randomly) on this change rebased onto the main of its last review: 26149 passed, 18 skipped, 1 xfailed, 0 failed. The final rebase onto current main changes only main's own files (docs and generated SDK tables); format, lint with every generator --check, and the touched test files pass on it (320 passed).
  • make format lint typecheck, every generator --check, make schema-dump on a ClickHouse migrated from empty after the rebase onto current main, applying 080 after main's migrations (only the new table in the diff).

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. The author checks the diff before merge.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed.
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py).
  • A new migration is additive and numbered after the latest on main; no merged migration is edited.
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed.
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.

🤖 Generated with Claude Code

@zlareb1
zlareb1 force-pushed the feat/knowledge-sources-registry branch 5 times, most recently from ee9b413 to e4dff5b Compare November 3, 2026 19:12
loom.knowledge_sources holds the document sources registered on a
repository's trunk code namespace: kind, ids and filters, a registration id
and a credential sealed under knowledge_sources.credential. Seven
experimental ops (knowledge.source.list, inspect, add, check, rotate, remove,
sync_now) read and write it; readers list and inspect, the namespace's
admins do the rest. add and rotate probe the credential (gdrive, a shared
folder read with a service account, is the one kind) before any write;
every write of a namespace's sources is serialized by one lease.
code.repo.remove retires the namespace's sources, and a sync-written
document's source:* tags belong to the sync worker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: zlareb1 <[email protected]>
@zlareb1
zlareb1 force-pushed the feat/knowledge-sources-registry branch from e4dff5b to 0852884 Compare November 3, 2026 19:40
@zlareb1
zlareb1 merged commit 58f5b65 into main Nov 3, 2026
21 of 22 checks passed
@zlareb1
zlareb1 deleted the feat/knowledge-sources-registry branch November 3, 2026 19:41
@pufit pufit mentioned this pull request Nov 4, 2026
9 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant