Repository navigation
A repository's maintainers register the document sources Loom pulls from - #215
Merged
Merged
Conversation
zlareb1
force-pushed
the
feat/knowledge-sources-registry
branch
5 times, most recently
from
November 3, 2026 19:12
ee9b413 to
e4dff5b
Compare
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
force-pushed
the
feat/knowledge-sources-registry
branch
from
November 3, 2026 19:40
e4dff5b to
0852884
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changelog category (leave one):
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, andcode.repo.removeretires 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.
loom.knowledge_sources, migration080_knowledge_sources.sql, the next free number on main. ReplacingMergeTree keyed(org, namespace, name), modelled onloom.qa_sourcesandloom.code_repos. Every read isFINAL; every write is a full version row withcreated_atcarried forward, never anALTER UPDATE. The row holdssource_id(a UUID that names one registration: written once byadd, carried by every later write), ids and filters (config_json), the sealed credential, and on an inactive rowpending_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 inserver/clients/gdrive.py, so a caller cannot point the server at a host of its choosing.loom.code_index_stateunderknowledge_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 lastsync_nowrequest;listandinspectreturn it assync.requested_at.addresets it before a new source goes active, so a re-added name never starts on an old stamp.docs_namespaces()puts its documents in), so the transport's namespace gate decides:VIEWERforlistandinspect,ADMIN(the repository's maintainers) foradd,check,rotate,removeandsync_now.checkwrites nothing but isADMINbecause 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,rotateandsync_nowrefuse a namespace that is no repository's trunk (NOT_A_CODE_NAMESPACE); for the last three the message says the repository is gone andknowledge.source.removeretires the source. That check reads the cached repository registry (refreshed everycode_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.knowledge-source:<org>:<namespace>(server.core.leases.holding, the claim self-signup and subject revocation use):add,rotate,remove,sync_now, and incode.repo.removethe retirement of the sources together with its registry row. A probe runs outside it. Under the leaseaddre-checks that the repository is still registered (itsloom.code_reposrow, through the code plane'sCodeRepo.code_repo_row; a repository the operator's configuration owns counts as registered, sincecode.repo.removerefuses it), the trunk, the name, the quota and the name's documents, then resets the sync state and inserts.rotatere-reads the source and refuses one removed (SOURCE_NOT_FOUND) or removed and added again as another source, told apart bysource_ideven within one second (SOURCE_REPLACED, 409);sync_nowre-reads it too and refusesSOURCE_NOT_FOUNDorSOURCE_REPLACEDthe 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 beforecode.repo.remove's retirement (which then retires it) or wholly after (and sees the repository gone).code.repo.removeretires 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 answersOVERLOADED(retry); a lease store that cannot answer refuses (LeaseUnavailable, 503), never writes unlocked.knowledge_source:*sync-state write leaveversionto 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 owncode_index_statekeys keep their writer'sversion_now; nothing else writes these keys). The one writer outside the lease isloom 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.source:<name>and written by the sync worker's actor,worker:knowledge-source-sync(SYNC_WORKER_ACTORinserver/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 theworker:kind (theworker:structured-profileprecedent). A caller's own document taggedsource:<name>is never counted, listed byinspect, retired, or a reason to refuse a name. Thesource:*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 anadd/upsert/bulk_addre-save of the same text) may change its other tags but not add or drop asource:*one (SOURCE_TAGS_LOCKED,server/knowledge/app/writes.py).SOURCE_DELETE_PENDINGwhile they wait to be retired,SOURCE_DOCUMENTS_KEPTwhile kept ones remain (the message asks for them to be deleted withknowledge.deletefirst). A removed source with no documents frees its name at once.seal("knowledge_sources.credential", …), the same helper and root as the tracker password and repository token, under its own purpose; the tuple joinsSEALED/_KEYSinserver/cli/secrets.py, soloom secrets resealcovers it. A deployment with no root secret refuses the add (NO_ROOT_SECRET) instead of storing plaintext. A stored credential that no longer opens makescheckanswercredential_invalid; it is never read as "no auth".removeandcode.repo.removeclear it on the inactive row. No output model has a credential field, andaddandrotatedeclare anaudit_subjectwithout it (the shapetracker.source.addandcode.repo.adduse;test_audit_subject_credentials.pystays green):addrecords namespace, name, kind, config anddry_run,rotatethe namespace and name;removeandsync_nowcarry no credential and keep the default subject (their input). The rawcredentialargument reaches no call ledger:loom.agent_events.argskeeps only allow-listed argument names, and a unit test pins it.server/knowledge/app/source_probes.py), withgdrivethe only kind: exchange the service account's JSON key for a read-only token (JWT bearer grant signed with the key, through the existingpyjwt[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 byknowledge_source_probe_timeout_s; past itaddandrotateanswerSOURCE_UNREACHABLEandcheckanswersreachable: false. A 403 whose error reason is a rate limit is reported asrate_limited, not as a refused credential.addandrotateprobe before any write (CREDENTIAL_REFUSED,SOURCE_UNREACHABLE;dry_runprobes only). An error names the HTTP status (http_403) or the folder the account cannot see, never the store's response body.knowledge_sources_max_per_namespace(default 8,SOURCE_QUOTA, LIVE) andknowledge_source_probe_timeout_s(default 20 s, at most 25, under the 30 s op budget, LIVE).NO_MEMORY_CONTENTbesideloom.qa_sourcesandloom.code_repos. The documents a sync will write are covered by the existingloom.documents,chunksanddocument_blobssteps; the sync state goes with the code index (loom.code_index_stateis 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.pytoserver/tracker/domain/sources.pyasSOURCE_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.removenow 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 fieldsources_deactivated. The namespace purge that follows deletes the sources' sync state (itsloom.code_index_staterows) 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 answerOVERLOADEDwhile a source write of the namespace runs, and refuses when the lease store cannot answer.knowledge.add,knowledge.upsert,knowledge.bulk_addandknowledge.update_metadatacan 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 asource:*tag. It applies only to documents the sync worker wrote; none exist until the worker ships, so no current call is refused.bulk_addchecks every entry before it chunks or embeds any. The other writers ofloom.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_nowandremove(delete_documents=true)only record the request, and the docs say so.Tenant isolation: the namespace gate runs before every handler;
listandinspectread only the addressed(org, namespace); an unknown source isSOURCE_NOT_FOUND(404), and a namespace with no sources lists empty.listandinspectare probed bytest_cross_principal_leakage.pyas registered; the fiveADMINops are in its_SKIP_OPS, with a unit test thatcheck_authorizedrefuses 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_statechanges a key N-1 reads, the newcode.repo.removeoutput 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 servingcode.repo.removedoes not retire the namespace's sources, which then stay active, keep their sealed credentials and count toward the quota untilknowledge.source.removeretires them, whilecheck,rotateandsync_nowrefuse 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 withoutcode.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, andlist,inspectandremovestill serve it so a maintainer can see and retire it.Compatibility, rollout and rollback
maturity="experimental"(HTTP and SDK reach only; not in the MCPalllisting). Existing ops:code.repo.removegains the output fieldsources_deactivated(additive) and can now answerOVERLOADED(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_addandupdate_metadatagain the refusalSOURCE_TAGS_LOCKED, for sync-written documents only. The new ops answerOVERLOADEDand the 503 the same way. Output fields left out on purpose:removehas nodeactivated,addnowritten, the add/rotate probe noreachable(each would always be true; a refusal is the false case), andsync_nownoqueued. 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.LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE(8, LIVE) andLOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S(20 s, at most 25, LIVE).loom.knowledge_sourcestable and anyknowledge_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 answersSOURCE_REPLACEDfor one removed and added again with the same creation second, each registration gets its ownsource_idthat rotate and remove carry, remove counts documents with sequential consistency, async_nowwhose source was removed before its lease answersSOURCE_NOT_FOUNDwith the state unchanged andpending_deletekept, and one whose source was removed and added again answersSOURCE_REPLACEDand 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 recordspending_deleteonly with documents,SOURCE_DELETE_PENDINGandSOURCE_DOCUMENTS_KEPT, a re-added name's sync state reset before the row goes active,check,rotateandsync_nowrefuse a source whose namespace is no trunk whileinspectreads it andremoveretires 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 theloom.code_reposrow (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; theADMINandVIEWERgates throughcheck_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,versionleft 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 OAutherrorstring such asrate_limit_exceededcounts 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 asCREDENTIAL_REFUSEDbefore 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 anadd,upsertorbulk_addre-save of a worker-written document cannot add or drop asource:*tag; a re-save with the samesource:*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; abulk_addwith 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.test_rmt_write_paths.py(the table is abuilder),test_schema_baseline.py(the journal),test_sdk_errors_from_response.py(SOURCE_REPLACEDreaches the SDK asPreconditionFailed, 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 needLOOM_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 makeremove(delete_documents=true)writepending_deleteandaddanswerSOURCE_DELETE_PENDING, orSOURCE_DOCUMENTS_KEPTwhen 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.pywith the source tests, through the real lease (its statements show insystem.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 includingsource_id, on one throwaway ClickHouse):mixed-version gate: ok.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-dumpon 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 typecheckandmake test-unitpass; the integration suite passes if server behaviour changed.docs/reference/configuration.mdand thedocs/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).main; no merged migration is edited.hooks/,lib/,bin/,skills/,.mcp.json, the Codexplugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version.npm --prefix frontend run build) and its tests pass, iffrontend/changed.docs/describe the system as it now is, and this description names any operator steps and wire changes.🤖 Generated with Claude Code