Skip to content

fix(cli): os knowledge rebuild and status give the right answer behind a load balancer - #37578

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-37466-knowledge-cli-lb
Nov 26, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-37466-knowledge-cli-lb

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Bill · project thread

Fixes #37466

Clause-②: yes (widening)
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:多节点部署的运维用命令行重建知识源时,进度查询打到别的节点不再直接报失败,而是在共享存储上改看各节点一致的索引状态,并新增一个等待上限选项;查看状态时会说明应答节点上没有构建记录。
  • 为什么做:知识库重建运维入口的后续修复,替多节点部署的运维和自动化脚本解决“构建在跑或已成功却被报失败”的问题。
  • 出错会怎样:只影响命令行的结论,不影响服务端构建本身;可直接撤回本改动恢复旧行为。
  • 要你做什么:无。

What changes

Design: the card's second option. The build record stays per node (no service change); the CLI falls back to the index state the store reports, which is the same on every node when the adapter's store is shared between nodes (not memory).

  • os knowledge rebuild reads index_status once before it starts the build, as the baseline (its index state and its adapter). A progress read answered by a node without this build's record (no record, or a record with another startedAt) is no longer an exit 1. It reads the index state instead: when the baseline said a build was due (due: true: never built, new fingerprint, changed recipe, no recipe hash on an adapter with completeBuild), the index turning current means a complete build recorded itself (adapters record the recipe hash only in completeBuild), and the command exits 0, saying the counts were not read.
  • When no build was due (the index already current, unreadable from a transient adapter error, or a state that never turns current), or the baseline was not read, the index state cannot tell a running build from a finished one (a same-fingerprint rebuild opens no building generation in either adapter: knowledge-memory and knowledge-pgvector beginBuild), so the command keeps polling until a read reaches the building node, whose record decides.
  • On the memory adapter (id memory), whose index is a per-process map, the index state is never read as the build's end: each node answers for its own index, so only the building node's record decides. The docs and the status line say the index state is the same on every node only when the adapter's store is shared.
  • Failure is reported only on the build's own recorded failure (failed / not-run) or after the new --timeout (seconds, default 600, counted as polls times --interval) of reads that reach no record of this build and do not see the index turn current. The timeout message says the build may still be running and points at os knowledge status; a read that reaches the record starts the timeout again, so a single-node build is never cut off.
  • os knowledge status labels the record as the answering node's, and when that node holds none says a build run on another node (or before a restart) is not shown, while the index state is the store's.
  • content/docs/deployment/cli.mdx Knowledge section and a patch changeset.

Measured before designing: index_status already returns index (state, due, detail, held) from the store and build (or null) from the answering node, so "no record on this node" (build: null) and "never built" (index.state: nothing) are separate fields; no service change was needed.

Tests

packages/cli/src/commands/knowledge/knowledge.test.ts, new describe "a poll that lands on a node without the build record": still running (polls alternate between a node without the record and the building node, exit 0), succeeded (index turns current, exit 0), an older record on the answering node read as no record, an index already current waits for the building node and reports its recorded failure, an unreadable baseline followed by a current index elsewhere is no exit 0, the memory adapter's current index elsewhere is no exit 0 and the building node's record decides, --timeout exits 1 with its statement, and the timeout restarts on a read of the record. Existing rebuild tests gained the baseline read.

Readings at 3b35169
  • vitest run src/commands/knowledge/knowledge.test.ts: Test Files 1 passed, Tests 14 passed (lock VERDICT command-exit 0).
  • Ablation at 91e9a57 (rebuild.ts restored to the base c385d3b, tests kept): Tests 9 failed, 3 passed; restored, green.
  • Ablation of the due predicate (put back to the state-based baseline on disk): Tests 1 failed (the unreadable-baseline case), 13 passed; restored.
  • Ablation of the memory check (forced false on disk): Tests 1 failed (the memory case), 13 passed; restored.
  • pnpm --filter @objectstack/cli typecheck: VERDICT command-exit 0 (incl. check:test-typecheck OK).

Acceptance notes

  • The index_status answer carries no node identity, so os knowledge status can only say "the node that answered", never which node ran a build.
  • A failed build seen only through other nodes leaves the index due; the CLI cannot read that failure from the store and ends on --timeout.
  • The memory check matches the adapter id memory, the knowledge-memory default; a memory adapter registered under another id is not recognised, so for it the index-current exit stays possible.
  • --timeout counts reads times --interval, not wall-clock time; a hung request is not bounded by it (accepted N1).

Verification

Read first: packages/cli/src/commands/knowledge/rebuild.ts (the fallback branch after the record check), then the new tests.
Two-minute check: pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 src/commands/knowledge/knowledge.test.ts shows 14 passed.


Generated by Claude Code

…when a poll lands on another node

Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 26, 2026
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/cli, touching 7 documentable anchor(s).

2 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via index_status (literal, a string literal in KnowledgeRebuild), os knowledge rebuild (command, read off packages/cli/src/commands/knowledge/rebuild.ts), os knowledge status (command, read off packages/cli/src/commands/knowledge/status.ts))
  • content/docs/deployment/cli.mdx (via index_status (literal, a string literal in KnowledgeRebuild), os knowledge rebuild (command, read off packages/cli/src/commands/knowledge/rebuild.ts), os knowledge status (command, read off packages/cli/src/commands/knowledge/status.ts))
What this run could not see
  • 1 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 40 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 0161cdcd1edd20886aead2878a3b38a87b12bed1 — the merge of head 3b351697d10880a91dd4a6bafce636e6c68b116f into base 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 0161cdcd1edd20886aead2878a3b38a87b12bed1 && git checkout 0161cdcd1edd20886aead2878a3b38a87b12bed1
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6 3b351697d10880a91dd4a6bafce636e6c68b116f && git checkout -B drift-repro 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6 && git merge --no-ff 3b351697d10880a91dd4a6bafce636e6c68b116f

node scripts/docs-audit/affected-docs.mjs --json 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 0f6a1e518f3c4639b03f86a8c07d9d08d91bddb6 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X

Contract-review-claim: session_01Utp6CYtTDvfPQDzMbZnN5X · head 91e9a57 · 2026-11-26T14:18Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 91e9a57551df14ae7ba4be6d17e6696fc2c90338
Local-runs: none

Read: card #37466 (body, triage, first touch, claim, os-dev report), the PR #37578 body and Acceptance notes, the net diff against main (5 files, +248/−51, CLI and docs only), and the 55 check-runs on the head: 40 success, 15 skipped, 0 failure. Required contexts are green (Lint & Repo Gates, TypeScript Type Check, Test Core and shards 1–10, Build Core, Governed Surface Queue Guard, Check Changeset, PR-body guards).

① Derived judgments

  • Design. The PR takes the card's second option and makes no service change. That is right: index_status already returns index from the store and build (or null) from the answering node as separate fields (knowledge-build-actions.ts:151-152).
  • Public surface. os knowledge rebuild gains --timeout (seconds, default 600, min 1). It now also makes one index_status read before rebuild, and only with --wait. Its exit codes change: a poll answered by another node no longer exits 1 on its own. os knowledge status changes one output line. Nothing is removed or renamed, and no option is refused that was accepted before.
  • No false success: mostly holds. Success comes from the build's own done record, or from the index turning current after a baseline that was not current. A missing baseline state counts as current (rebuild.ts:109), so it never yields success. A same-fingerprint rebuild waits for the building node's record, which is correct because neither adapter opens a building generation for it. failed and not-run records still exit 1 (rebuild.ts:135). Two paths still give a false exit 0:
    • S2 (should-fix): baseline judged by state instead of due. indexWasCurrent is state === 'current', so any other state counts as a valid "was not current" baseline. unreadable is one of those states, and readIndexState returns it when the adapter read throws (knowledge-service.ts:890), so it can be transient. Take a transient error on the baseline read of a same-fingerprint rebuild: the next poll on another node reads current and exits 0 saying "a complete build has recorded itself", while this build is still running and may still fail. Separately, unknown, listed-*, not-built-here and a no-recipe-hash with no completeBuild never turn current, so for those the line "(waiting for it to turn current)" can only end on --timeout. Fix: take the fallback exit only when indexBefore?.due === true, which is exactly the never-built, new-fingerprint, recipe-changed and no-recipe-hash-with-completeBuild set the docblock names. Treat every other state like current. Add a test with an unreadable baseline followed by a current poll on another node, and assert no exit 0.
    • S3 (should-fix): the premise does not hold for the memory adapter. The code, docs and status line all say the store's index state is "the same on every node". That is true for pgvector. It is false for the default memory adapter, whose index is a per-process Map (knowledge-memory/src/index.ts:91). Behind a load balancer the baseline can come from a node whose memory index is due (restarted, boot build not yet done, or buildAtBoot: false). A later poll can then land on a node whose own memory index is current, and the command exits 0 while the build on the third node runs. Fix: do not take the index-current exit when the source's adapter is memory (the view carries it). In cli.mdx (the status and rebuild paragraphs) and the status line, say the index is the same on every node only when the adapter's store is shared.
  • Poll loop. There is no tight spin: every pass waits --interval seconds (min 1) before its read. The no-record wait is bounded by --timeout and resets only on a read of this build's record, so a single-node build is never cut off. A build that stays running on its node is followed for as long as it runs, as before. Every read failure still exits 1 at once, as before.
    • N1 (nit): --timeout counts reads times --interval, not wall-clock time, and runKnowledgeAction (not in the diff) sets no request timeout. A request that hangs is therefore not bounded by --timeout. The flag text and the docs describe this accurately, so it is a note, not a defect.
  • Stale or older records. A record with another startedAt is read as no record (tested). startedAt is always present on a real server, because rebuildSource sets the record synchronously (knowledge-service.ts:924-931). The startedAt === undefined branch only covers an older server.
  • Tests: real controls. The 6 new cases cover each branch with a negative control. A current baseline never exits 0 from the index; the build's own recorded failure still exits 1; --timeout 4 against --interval 2 exits on exactly the 2nd unseen read; and the reset case turns red if the reset is removed. The ablation result (9 of 12 red when rebuild.ts is put back to the base) explains as follows:
    • The 3 that stay green: the two os knowledge status cases, because the ablation restored only rebuild.ts and status.ts kept the PR's text. Also the --no-wait case: the new baseline read is gated on flags.wait (rebuild.ts:86), so its single-request sequence is the same on base.
    • Of the 9 red, 3 are older rebuild cases ("follows it to its end", "did not finish", "refusal text"). They turn red only because the fixture gained a baseline response that base hands to rebuild. That is a fixture shift, not behaviour, so the behavioural evidence is the 6 new cases. That is enough.
    • The status text change has no ablation reading, but its assertion pins the new line ("none recorded there"), which the base line would fail.
    • None of the 12 covers an unreadable baseline (S2).

② Semver level

③ Boundary flags

  • open_questions: empty. Nothing to answer.
  • Accepted limit 1: no node identity in index_status. Acceptable, and no card needed. It limits labelling only: status now says "the node that answered", which is true, and it says when that node holds no record. Adding a node id to the answer is a service change outside this card. A shared build record (the card's first option) would remove the limit.
  • Accepted limit 2: a failed build seen only through other nodes ends on --timeout. Acceptable, and no card needed. Exit 1 is the right code for a failure; it only comes late, and the message honestly says the build may still be running. The same timeout also catches a successful same-fingerprint rebuild whose reads never reach the building node. At the default that needs about 300 reads in a row to miss one node, which is negligible under round-robin. File the shared build record only if an operator reports the wait.
  • Dev flags: the two out_of_scope_findings are these two limits, answered above. dogfood_battery n/a is right: no ! and no narrowing arm. security_findings: none, agreed; the admin gate is unchanged and server-side.
  • SQL push-down: not applicable. The diff is CLI and docs only, with no data access, id materialisation or join.
  • Owed before merge: S1 (two declaration lines), S2 (a one-line predicate and one test), S3 (an adapter check or a docs qualification). N1 is optional.

Implemented-by: claude/issue-37466-knowledge-cli-lb
Reviewed-by: session_01Utp6CYtTDvfPQDzMbZnN5X

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X

席位核对

Head-sha: 91e9a57551df14ae7ba4be6d17e6696fc2c90338
REWORK — L1, seat repo:objectstack#5

  1. Shape: draft against main. CLI and docs only. Not governed, not security-touching.
  2. Premise: the --timeout option and the fallback that reads the shared index state are sound. Both accepted limits (no node identity in index_status; a failed build seen only through other nodes ends on --timeout with exit 1) stand with no card.
  3. Gates: contract record 7194806473 (TIER_DEFAULT) reads PASS with three should-fix findings owed before landing. CI on this head: 40 success, 15 skipped, 0 failed.
  4. Owed before landing (ids from the record):
  5. Accepted deviations: N1 (--timeout counts polls times --interval; the PR already says so).
  6. Landing terms: after the delta the seat re-reviews with the same reviewer. Then the area lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 3b351697d10880a91dd4a6bafce636e6c68b116f
Local-runs: none

This is a delta review on 91e9a575 (record 7194806473; seat REWORK 7194818791). I read the delta diff 91e9a575..3b351697, the net diff against main (still 5 files, now +306/−51, CLI and docs only), the PR body as edited at 15:09:57Z, the changeset, dev report 7195831596, and the check-runs on the new head.

The check-runs on the new head are 40 success, 17 skipped, 0 failure, and 2 re-runs started by the body edit:

  • PR-body guards: the re-run is success.
  • Check Changeset: the re-run is still in_progress. Its first run on this same head (14:38Z) was success, but that run read the body while it still said Clause-②: no. The seat should see the re-run green before landing.

① Derived judgments

  • S2 — closed. The fallback now exits only when the baseline said due === true and the adapter is not memory (indexCanTell). An unreadable, current, unread or never-current baseline now waits for the building node's record, so the false exit 0 is gone. The new test is a real control: an unreadable baseline, then two current polls elsewhere, ends on --timeout with no "The index is current". The dev's ablation, putting the state-based predicate back, turns only this case red.
  • S3 — closed. With adapter id memory, the index state is never taken as the build's end, and the line says why. The docs (status and rebuild paragraphs), the status line and the docblocks now say the index is the same on every node only for a shared store (pgvector).
    • The new test is a real control: a memory baseline that is due, then a current poll with no record, is not an exit 0, and the building node's done decides. The dev's ablation, forcing the check false, turns only this case red.
    • The status test pins the new line ("not on the memory adapter").
  • N1 — stays open, accepted. Nothing changed. The PR's Acceptance notes now name it.
  • N2 (nit, new): one wrong comment. The comment at rebuild.ts indexCanTell says every due: true state turns current at a build's end. listed-empty is due: true (an adapter with listDocuments and no indexStatus), and it becomes listed-documents, never current.
    • The only effect: on such an adapter the line "(waiting for it to turn current)" can end only on the building node's record or on --timeout. There is no false exit 0, because current comes only from indexStatus.
    • Fix if touched again: name listed-empty among the states that leave the record as the only answer.
  • Nothing else moved. The poll loop, timeout reset and record matching are unchanged from the head already reviewed. No tight spin and no unbounded no-record wait.

② Semver level

  • S1 — closed. Clause-②: yes (widening) now stands at line start in both the changeset body and the PR body, and the two agree. The level stays patch on @objectstack/cli, which is right: a non-protocol widening ships patch. Metadata-protocol: none stands. The changeset text now also states the shared-store and not-memory conditions, which matches the code. No BREAKING banner, migration or ADR-0087 marker is owed.

③ Boundary flags

  • open_questions: empty.
  • Memory check by id only (the dev's out-of-scope finding, now in the PR's Acceptance notes): acceptable, and not worth a card on its own.
    • knowledge-memory's plugin does accept opts.id (knowledge-memory/src/index.ts:422), so a renamed memory adapter is possible. But a false exit 0 then needs a multi-node deployment on a renamed per-process adapter, a due baseline and a poll that lands on another node whose own index is current. That deployment re-embeds the source on every node anyway.
    • The real fix is server-side: the adapter or index_status says whether its index is shared. That belongs with the card's first option (a shared build record) if that is ever filed. The Acceptance note is the right carrier for now.
  • The two original accepted limits stand as judged in record 7194806473.
  • SQL push-down: not applicable (CLI and docs only).
  • security_findings: withheld in the dev report: nothing in the delta touches auth or the admin gate, and the delta has nothing to withhold. The seat may ask the dev to restate it as none.

Implemented-by: claude/issue-37466-knowledge-cli-lb
Reviewed-by: session_01Utp6CYtTDvfPQDzMbZnN5X

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X

席位核对 (delta)

Head-sha: 3b351697d10880a91dd4a6bafce636e6c68b116f
ACCEPT — L1, seat repo:objectstack#5

  1. Shape: draft against main. CLI and docs only. Not governed, not security-touching. Clause-②: yes (widening) at patch, now in both the changeset and the PR body.
  2. Closed: S1, S2 and S3 from REWORK 7194818791. Each new test is a real control.
  3. Gates: delta record 7195958256 (TIER_DEFAULT) reads PASS. CI on this head: 0 failed. Check Changeset re-ran after the body edit (15:10:05Z) and is green.
  4. Accepted deviations: N1 (--timeout counts polls; the Acceptance notes say so), N2 (the indexCanTell comment's "every due: true state turns current" misses listed-empty; the only effect is a wait, never a false exit 0). The memory-id-only check needs no card; the Acceptance note is enough.
  5. Out of scope and where it went: none. The dev report's security_findings: withheld reads as none on this diff.
  6. Landing terms: not governed, under 3000 lines, no decision owed. The area lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-bill · session_01Utp6Cb4BAjgQ43tqy1DvVJ

Landing · 2026-11-26T15:15Z · zone ai-37000

Probe Reading
Head 3b351697d10880a91dd4a6bafce636e6c68b116f = ACCEPT 7195972600 head (delta contract record 7195958256 PASS)
Checks on head success=42 skipped=17, 0 failure; Check Changeset re-ran green after the body edit
Governed check-governed-merges.mjs --pr 37578: NOT governed, 357 lines ≤ 3000; body declares Clause-② yes (widening), Metadata-protocol none (no narrowing)

State change: ready for review + auto-merge (merge queue). #37466 closes on merge; close-out follows. N1/N2 accepted as described in the record.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 26, 2026 15:16
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 26, 2026
Merged via the queue into main with commit 54b1e76 Nov 26, 2026
60 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-37466-knowledge-cli-lb branch November 26, 2026 16:13
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…t page, and a stalled build is cancelled (objectstack-ai#37570)

<!-- claude-projects-attribution: {"github_login":"os-bill"} -->
_Requested by **Bill** · [project
thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg3zXREECfPtgrM8TPQaxn1v)_

Fixes objectstack-ai#37465

Clause-②: yes (widening)
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:多节点部署里,知识源重建时构建锁中途失效,构建会在下一页停下,状态显示为"租约丢失";嵌入调用卡住 15
分钟无进展,构建会被取消并释放锁,状态显示为"超时",不必重启即可再次重建。
- 为什么做:属于知识检索(RAG)落地这条线,替运维省掉两个节点重复花的嵌入费用,也解决卡死后只能重启的问题。
-
出错会怎样:最坏情况是构建的收尾一步(切换到新索引)一直不返回,这个知识源会一直显示"运行中",直到它返回或进程重启;已写入的内容保留,下次重建会跳过已写部分;改动可直接撤回。
- 要你做什么:无。

## What changes

**Cluster lease fence (service-knowledge).** `rebuildSource` now runs
its walk under a build fence (`startBuildFence`, `knowledge-build.ts`),
and `walkObjectSource` asks the fence before each page:
- The lease is lost when the handle reports `isHeld() === false`, when a
renewal failed and the handle no longer holds the lease, or when no
renewal has succeeded within `BUILD_LEASE_MS`. The last case covers a
lock store that does not answer, or a renewal that hangs.
- When the lease is lost, the walk stops before the next page's read:
nothing more is embedded, purged or completed. The record's status is
`lease-lost` and the lease is released.
- A lease lost after the last page also skips the purge and
`completeBuild`.

**Stall bound (service-knowledge).** `BUILD_STALL_LIMIT_MS` is a fixed
15-minute ceiling on the time between two pages or two purge deletions
(and before the first page, and from the last page to the purge). It is
not a settings key and not an option, so ADR-0049's key-with-reader rule
has no key to apply to.
- Past the bound, the build is cancelled: its status is `timed-out`, the
lease is released, and nothing is purged or completed.
- The walk races every store and engine call it waits on before the
completion against the bound: `beginBuild`, the document listing, each
page's `engine.find`, `adapter.upsert` and `adapter.delete`, and the
purge. Such a call that never answers no longer holds the source's walk
chain, so the next rebuild runs at once (with the one exception named in
Acceptance notes).
- Each purge deletion restarts the bound (the `serialize` hook in
`walkObjectSource` ticks the fence when each candidate settles), so a
large, healthy purge is never cut short.
- `rebuildSource` also races the whole walk. That covers what the walk
does not fence: the wait in the source's queue behind another walk, and
`planIndex`.
- **The completion is not a page.** The private `completeBuild` helper
checks the fence first, so a lease lost during the purge, or a purge
that answers after the bound, completes nothing. Once it lets the
completion begin, it calls `fence.completing()`, which disarms the bound
for the rest of the build, and awaits `adapter.completeBuild` without a
race. A switch that began before the bound passed therefore still
commits, and the record reads `done` or `failed`, never `timed-out` over
a switched index. pgvector's sweep of the replaced generation runs
inside that call, so it is not cut short either.
- The source's walk chain (`reindexTails`) stays held until the
completion settles. No rebuild on this node can begin a build, and so
take pgvector's builder lock, beside an old switch or sweep. The old
call's `finally` (which clears the adapter's `builds` entry and releases
its lock) can therefore no longer clear a newer build's entry or lock.
The cost, named in the docs: a completion that never answers keeps the
build `running` until it answers or the process restarts.

**pgvector builder-lock fence.**
- Each build write and removal (`ctx.reason === 'reindex'`, for a build
this adapter began) first checks in `pg_locks`, on the lock's own
session, that the source's advisory lock is still held. If it is not,
the write is refused with `LOCK_CONFLICT` (409) before anything is
embedded.
- `completeBuild` completes only the build this adapter began, and only
the generation that build began. Otherwise it is refused with
`LOCK_CONFLICT` and switches, records and deletes nothing.
- A lock kept from an earlier build is re-checked at `beginBuild`, so a
lock whose session ended is no longer kept.
- **Behind a transaction-mode pooler** the advisory lock does not stay
with the session that took it, so the check reads a held lock as lost.
Such a deployment was already unsupported; before this change its builds
ran with a release warning, and now every complete build is refused at
its first page. The refusal's remedy and the changeset name the pooler
and the fix: a direct or session-mode endpoint.

**N3.** A pgvector search that meets three generation switches is
refused with `CONCURRENT_MODIFICATION` (409). The rows for
`CONCURRENT_MODIFICATION` and `LOCK_CONFLICT` leave
`scripts/error-status-unpinned-baseline.json`.
`check:error-status-conformance` required the `LOCK_CONFLICT` removal
too, because the new pgvector refusals declare its status.

**N2.** Measured live: `beginBuild` under the active fingerprint already
retires a building generation of another fingerprint. This PR pins that
with a live test and states it in the docs; no code change was needed.
What remains is that no build is due after a revert (`readIndexState`
reads `current`), so the stale generation stays until the next build of
any kind. See Acceptance notes.

**N4** is not implemented. Two sweeps of one retired generation need two
lock holders at once. The fence now refuses a lapsed builder's
`completeBuild`, and `beginBuild` sweeps only under a freshly checked
lock.

**knowledge-turso (measured, not changed).** It has no builder lock:
`beginBuild` takes up any generation under the same fingerprint, so
there is no builder identity for an "own generation" check beyond the
fingerprint, which `completeBuild` already requires. Its cluster-lease
protection is the service-level fence in this PR.

**CLI.** The CLI's `KnowledgeBuildView.status` type and the `rebuild.ts`
comments list `lease-lost` and `timed-out`. No runtime change: a
followed rebuild already exits 1 on any status other than `done`.

**Docs.** `content/docs/ai/knowledge-rag.mdx` adds generation item 6
(the pgvector fence), extends item 5 (the reverted fingerprint) and adds
a paragraph on the two stops in "The first build, and rebuilding a
source". That paragraph's `lease-lost` sentence links back to item 5: on
pgvector, the stopped build's builder lock stays with its node until the
idle time passes. None of these sections is one that objectstack-ai#37442 edits.

**Widening.** The exported `KnowledgeBuildRecord.status` gains
`lease-lost` and `timed-out`. Nothing else becomes newly exported from
the package entry.

### Files to read first (by risk)

1. `packages/services/service-knowledge/src/knowledge-service.ts`,
`rebuildSource` and the private `completeBuild` helper: the race on
`fence.cancelled`, the status taken from `fence.stop()` when the walk
returns `ok: false`, and `fence.completing()` before the unraced
`adapter.completeBuild`.
2. `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts`:
`holdsBuilderLock` (the `pg_locks` key split into `classid`/`objid`) and
the `completeBuild` own-generation check.
3. `packages/services/service-knowledge/src/knowledge-build.ts`,
`startBuildFence`: the local lease expiry (`heldUntil`) for a renewal
that never settles, and `completing()` (the bound disarmed for good).

### Two-minute verification

`pnpm --filter @objectstack/service-knowledge exec vitest run
src/__tests__/knowledge-build-fence.test.ts` should report 14 passed.
The first case shows 1 page embedded of 3 and `lease-lost`. The stall
case shows `timed-out` at 15 minutes of fake time, then a next build
that completes. The completion case shows a build still `running` at 30
minutes, then `done`, with the second `beginBuild` only after it.

## Tests

<details><summary>Local readings</summary>

- `knowledge-build-fence.test.ts` (new, 14 cases):
- lapse mid-walk: 1 of 3 pages embedded, `find` called once,
`completeBuild` 0, `lease-lost`, released once;
  - lapse after the last page: no purge and no complete;
  - lapse during the purge: no complete, `lease-lost`;
  - renewals that hang past the lease: `lease-lost`;
- an embed call that never answers: `timed-out` at the bound, lease
released, the next build `done`;
  - a slow build with progress inside each bound: `done`;
- a completion that answers only after twice the bound: the build stays
`running` with its lease kept; a rebuild asked meanwhile answers the
same running record; a complete walk asked meanwhile does not call
`beginBuild` until the completion settles; then `done`, the lease
released once, and the queued walk's `beginBuild` runs second;
- a purge of three deletions, each taking most of the bound: `done`,
`purged: 3`;
- a hung listing: `timed-out` with no complete, then a second build
`done`;
- a hung purge removal, with a store that keeps listing the document
until a removal lands: the first build `timed-out`; the second build
also `timed-out` at its purge, with no second removal call and no
complete; once the hung removal answers, the document is gone and a
third build is `done`;
- a build queued behind a plain reindex (no fence) whose upsert never
answers: `timed-out` at the bound, lease released, no `beginBuild`;
  - no cluster service: bound only;
  - fence unit: the first stop kept, and `close()` disarms the bound;
- fence unit: after `completing()`, `cancelled` never settles and
`progressed()` does not re-arm the bound.
- service-knowledge full suite at e5bac7e: Test Files 15 passed, Tests
462 passed; typecheck exit 0.
- CLI: typecheck exit 0; `src/commands/knowledge/knowledge.test.ts` 7
passed.
- knowledge-pgvector against a local PostgreSQL 16.16 with pgvector
0.8.7 (`OS_EXPECT_LIVE_DIALECT_MATRIX=1`): Test Files 8 passed, Tests 83
passed, against 76 before this PR. New:
`build-fence.live-postgres.test.ts` (6 cases) and
`search-switches.test.ts` (1). Typecheck exit 0.
- Ablations, each a mutation on disk then `git restore`:
  - per-page lease check disabled: 2 fence cases red;
  - pgvector `fenceBuild` disabled: 2 live cases red;
- the fence check in the private `completeBuild` helper disabled: the
lease-lost-during-purge case red.
- the `fencedCall` around the purge or the listing removed, one at a
time: the matching hung-call case red each time (the second build waits
behind the chain).
- `fence.completing()` removed, and separately the old race around
`completeBuild` restored: the completion case red each time.
  - the purge-deletion tick removed: the large-purge case red.
- both `unbounded` guards in the fence removed: the `completing()` unit
case red.
- the per-document chain around purge deletions removed: the
hung-purge-removal case red.
- `rebuildSource`'s race of the whole walk replaced by a plain await:
the queued-build case red. Before that case was added, this ablation
stayed green: the walk's own fenced calls cover everything but the wait
in the source's queue and the unfenced `planIndex` and tenancy reads.

</details>

## Acceptance notes

- The bound is per page (and per purge deletion), not per build. A
whole-build ceiling would cut a large, healthy build. A page holds at
most 100 rows, so 15 minutes without one finishing means a call is not
answering. The value matches pgvector's default `buildLockIdleMs`.
- The completion is not bounded, by the seat's ruling. A completion that
never answers keeps the build `running`, its lease renewed and the
source's walk chain held, until it answers or the process restarts. That
is the price of never starting a build on this node beside an old switch
or sweep. The docs name it.
- A call the build stopped waiting on cannot be withdrawn.
`AdapterContext` has no abort signal, and adding one would be an
ADR-0161 contract member, which this PR does not add. If such a call
answers later, its page is written; for pgvector that write is still
fenced by the builder lock.
- N2 remainder: after a revert, `readIndexState` reads `current`, so no
build runs and the stale building generation stays until the next build.
Retiring it without a build would need `indexStatus` or a read-time
sweep. Not done here.
- Turso N3 sibling: knowledge-turso's three-switch search refusal is
coded, but as `SERVICE_UNAVAILABLE` 503 ("the store is not ready"),
while pgvector now answers `CONCURRENT_MODIFICATION` 409 for the same
condition. Parity card objectstack-ai#37597 (p3, sub of objectstack-ai#37465) codes it
`CONCURRENT_MODIFICATION` 409; this PR leaves turso alone.
- A purge removal that never answers is abandoned at the bound, but it
still holds that one document's own sync chain, which is per document
and separate from the source's walk chain. The removal never landed, so
the store still lists the document. Every later complete build therefore
reaches it in its purge, queues behind the hung removal, and is
cancelled `timed-out` in turn, completing nothing, until the removal
answers or the process restarts. That document's event sync waits behind
it too. Keeping the per-document chain is deliberate: freeing it would
let a late delete race the event sync of that document. The
hung-purge-removal test asserts exactly this, with a store that keeps
listing the document.
- `knowledge-service.ts` edits stay inside `walkObjectSource` and
`rebuildSource`, plus the import block, a one-parameter pass-through in
`reindexWith` that threads the fence, and the private `completeBuild`
helper (its fence check and `fence.completing()`). None of these touches
the regions objectstack-ai#37442 edits; overlap-check reports a clean merge.

## Verification

- overlap-check at e5bac7e: `VERDICT clean exit 0` against origin/main
(54d6726), objectstack-ai#37442 and objectstack-ai#37578 (which shares `rebuild.ts`). No merge of
main was needed.
- The derived gates at e5bac7e (112 with `--repo
objectstack-ai/objectstack`): `--ran` reconciliation reports 111 run and
1 NOT MEASURED, `check-plugin-teardown-shape --self-test`, a recorded
exit 3 (PREREQUISITE NOT MET: shallow clone).
- PR check-runs at e5bac7e: 40 success, 15 skipped, 0 failure. Every
required context is green. Temporal Conformance (live PG + MySQL) runs
only in the merge queue. This round did not touch knowledge-pgvector;
its last local live reading is 83/83 on PostgreSQL 16.16 with pgvector
0.8.7, at fda121f.

---

_Generated by [Claude
Code](https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ)_

<!-- signed: repo:objectstack#5 · os-bill ·
session_01Utp6Cb4BAjgQ43tqy1DvVJ -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…a type with its loader, its registry and two authoring guards (objectstack-ai#37676)

<!-- claude-projects-attribution: {"github_login":"os-bill"} -->
_Requested by **Bill** · [project
thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgHittdG1nUD4Ne4ozfqAXgk)_

Fixes objectstack-ai#37304

Clause-②: yes (narrowing)
Metadata-protocol: narrowed
Skills-docs: follow-up objectstack-ai#37310

## 维护者速读

- 用户能看到什么变化:知识源成为一种正式的应用配置,可以随应用一起发布,也可以在 Studio
里新建和修改;保存后平台自动建立、更新或清除对应的检索索引。旧写法升级时会被明确拒绝,迁移命令会列出每一处要改的地方。
- 为什么做:属于“知识检索平台化”专题,让应用写一份知识源配置就有可用的检索,并且谁能建知识源、能索引哪些数据都有人管。
-
出错会怎样:只影响用到知识检索的应用。旧配置没迁移时会报出要改的位置,不会悄悄丢数据或建错索引;新增的“管理知识源”权限默认只有平台管理员有;回退本改动即可恢复原状。
- 要你做什么:批准一次。这是一次不兼容的协议收紧,改了两份对外技能文件(各一两行),改动量也超过三千行,按规则要你批准后才能合并。

## What changes

**New metadata type: `knowledge_source`.** Registered in the metadata
type registry with the one schema `KnowledgeSourceSchema`; a stack
carries its sources in the new top-level collection `knowledgeSources`
(`*.knowledge-source.ts` or `.yml`). An item can be created and changed
at run time (Studio, MCP) and takes no environment overlay. Studio's
menu lists the type under AI, and ADR-0084's type table carries its row.

**New platform capability: `manage_knowledge_sources`.** Platform
administrators hold it by default. Nothing else grants it.

- **The schema is strict.** An undeclared key is refused. `id` becomes
`name`, `source.contentFields` becomes `source.content`, a non-empty
list of field names; `'*'` is refused with the instruction to list the
fields, and an empty-string member is refused too (it names no field).
`embedding`, `vectorStore`, `adapterConfig`, `refresh.cron` and the
`file` / `http` source kinds are retired with their ADR-0087 entries
(three conversions, six retired keys, six retired defs, four semantic
entries on protocol 19). `os migrate meta --from 18` lists every edit
and `--write` applies the ones it can prove.
- **The loader** (`service-knowledge`, `knowledge-source-loader.ts`).
`KnowledgeServicePlugin` reads the published items when it starts and
follows the type while it runs: an added source is registered and built
when a build is due; a changed one is registered again (a changed
`where` or `metadataFields` rebuilds inside the generation, a changed
`content` or `split` builds a new one); a removed one is unregistered
and its index dropped. The reap guard's object set follows the sources.
- **The registry** (`knowledge-source-registry.ts`), under the
maintainer's rulings on this card (record 7192063608, forks 6 and 4d,
both A). A source is held by `(package, name)`. A source registered in
code belongs to no package; it shares one slot with an
environment-authored item of the same name, and the second of the two to
arrive is refused `409 RESOURCE_CONFLICT`, naming both doors. A
package's source of the same name is a second source. Code names a
source by its face: the bare name for the package-less one,
`NAMESPACE-NAME` for a package's; a bare name several sources answer to
is refused `409`, naming the candidates. `search` hits carry the face as
`sourceId`. No `IKnowledgeService` signature changes for addressing.
- **`IKnowledgeAdapter.dropSource?(ctx)`**, implemented by
`knowledge-memory`, `knowledge-pgvector` and `knowledge-turso`; the
contract suite (`@objectstack/service-knowledge/testing`) takes
`implements.dropSource`. An adapter reads the source's index key from
`ctx.source.name` (it was `ctx.source.id`): the bare name for a
package-less source, so an existing index is found under the same key
and nothing is rebuilt.
- **Guard one: the capability.** A write of a `knowledge_source` through
`/meta` (REST and the dispatcher: save, publish, rollback, delete) and
through the MCP draft door needs `manage_knowledge_sources` beside
`manage_metadata`: `403 PERMISSION_DENIED` naming the capability, `401`
for an anonymous caller. It is one row in the existing per-type table
`META_TYPE_WRITE_CAPABILITIES`
(`packages/rest/src/meta-item-read-gate.ts`), so the three doors that
already ask that table ask it for this type too. The package doors ask
it as well (maintainer's ruling A, record 7207325373 on objectstack-ai#37304): each of
the twelve doors that write an existing package (enable, disable,
publish, publish-drafts, discard-drafts, the commit revert, rollback,
revert, adopt-orphans, duplicate, the manifest update, delete) refuses a
caller without the capability `403` when the package holds a knowledge
source: an item, a pending draft, or, for the commit revert and the
rollback, a commit that touched one. A package that holds none is
written as before; a holding that cannot be read refuses `503`. Two
doors are not asked, see Acceptance notes.
- **Guard two: source admission at save.** The same doors save a source
only when its author may themselves search what it would index: an
object of a disabled package, an object the API does not serve for
`search`, a system object without `enable.aiReadable`, or a field the
author may not query refuses the save `403`, naming the object or the
field; a verdict that cannot be reached refuses `503`. The fields a
source's `where` reads are judged with the fields it serves, at save and
at search. A knowledge service that is registered and cannot be resolved
refuses the save `503` at every door (REST, the dispatcher, MCP). The
duplicate door admits each knowledge source it would copy for the caller
before anything is copied, and refuses the whole copy when one is
refused. Over MCP the human is judged.
- **The push door leaves.** `IKnowledgeService.indexDocument` and
`deleteDocument` are removed with the `file` / `http` branches that
served them.
- **Removed exports**, twelve names from `@objectstack/spec/ai`. The
`embedding` module: `EmbeddingModelSchema`, `VectorStoreSchema`,
`VectorStoreProviderSchema` and the types `EmbeddingModel`,
`VectorStore`, `VectorStoreProvider` (the knowledge source was their
only composer). The retired source kinds: `FileKnowledgeSourceSchema`,
`HttpKnowledgeSourceSchema`, `KnowledgeSourceKindSchema` and the types
`FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeSourceKind`. The
changeset lists the same twelve.
- **Boot notice** (`packages/objectql`). A deployment that holds
`knowledge_source` items and mounts no knowledge service says so once at
boot, at warn, naming the items; it is not a boot refusal.
- **CLI.** `os knowledge status` prints the package that holds a source
and no longer a source kind.
- **Showcase.** `examples/app-showcase` ships `showcase_task_notes`
(object `showcase_task`, adapter `memory`) and mounts the knowledge
service and the memory store.
- **Docs.** `content/docs/protocol/knowledge.mdx` and
`content/docs/ai/knowledge-rag.mdx` describe the type, the loader, who
may author a source, and one name per source; the generated references
follow.
- **Skills (Tier H), enumeration row only**, under ruling A on objectstack-ai#32584:
`knowledgeSources` joins the top-level key list in
`skills/objectstack-platform/SKILL.md`.
`skills/objectstack-ai/SKILL.md`'s compiled `supportKb` example changes
two keys (`id` to `name`, `contentFields` to `content`) because the old
spelling is now refused at parse. Teaching the type (prose, tables,
evals) rides objectstack-ai#37310.
- **One ceiling, raised by the row's measured delta and by no more**
(`scripts/check-skills-token-ratchet.mjs`):
`skills/objectstack-platform/SKILL.md` was at zero headroom (24603
priced bytes, 6151 tokens, after objectstack-ai#37442's row); the `knowledgeSources`
row adds 20 bytes, so the priced text is 24623 bytes, 6156 tokens, and
the ceiling moves 6151 to 6156, pinned at the measurement. Nothing else
in the file is cut and nothing rides along.
`skills/objectstack-ai/SKILL.md` stays at 6799 tokens under its ceiling
of 6801.
- **The two rulings the raise path names**, quoted:
- Ruling A on objectstack-ai#32584 (record 6819475461): "a product PR that adds an
authorable `defineStack()` top-level key, or a live member of a schema
symbol bound to a registered exhaustive skills section, carries the
matching skills enumeration row in the same PR. Only that row; prose,
examples and evals still go to the skills sub-card."
- objectstack-ai#32673 letter A (record 6840575378): "a PR that adds a metadata key
and, under ruling A on objectstack-ai#32584, carries the matching enumeration row in a
published skill may raise that skill file's token cap by the row's
measured delta, and by no more. The PR body cites ruling A and this
ruling. Nothing else in the file is cut to make room, and no wider raise
rides along."

## Tests

- `packages/spec/src/ai/knowledge-source.test.ts`: the strict schema,
`'*'` refused, an empty-string member refused (and `minLength: 1` in the
JSON Schema), every retired key answered with its prescription.
-
`packages/services/service-knowledge/src/__tests__/knowledge-source-registry.test.ts`
(new): the slot rules above, both orders of arrival at each door, face
resolution and the `409` with its candidates.
- `.../knowledge-source-loader.test.ts` (new): boot read, add, change
(each of the two rebuild arms), remove with `dropSource`, an adapter
without `dropSource`, the reap guard following the sources.
- `.../knowledge-source-admission.test.ts`: each refusal of guard two
and its fail-closed `503`; the fields `where` reads (keys, `$and` /
`$or` / `$not`, `{ $field }` comparands) judged at save and at search.
- The adapter contract suite with `dropSource: true` in
`knowledge-memory` and `knowledge-turso`; `knowledge-pgvector` declares
it in `contract.live-postgres.test.ts` (see Remaining).
- `packages/rest/src/meta-type-write-capability.test.ts`: every write
shape of a `knowledge_source` for a caller with `manage_metadata` alone,
with `manage_platform_settings`, and with a record grant: `403
PERMISSION_DENIED`, store unchanged, no protocol call; a holder of both
saves, publishes, rolls back and resets; the capability without
`manage_metadata` is refused by the door's own admission.
- `packages/rest/src/meta-write-door-capability-enumeration.test.ts`,
`packages/runtime/src/domains/meta-save-capability-gate.test.ts`,
`packages/runtime/src/domains/mcp-authoring.test.ts`: guard two at REST,
the dispatcher and the MCP save door (the human is judged); on a real
kernel, a knowledge service whose factory throws answers `503` at the
dispatcher and at MCP, and one never registered is not asked.
-
`packages/runtime/src/domains/meta-type-write-capability-parity.test.ts`:
REST and the dispatcher answer the same for the new row.
- `packages/runtime/src/domains/packages-knowledge-source-gate.test.ts`
(new): each of the twelve package doors refuses a `manage_metadata`-only
caller when the package holds a source (item or draft) and the writer
never runs; a holder goes on with no listing read; a package with none
answers as before; a listing that throws refuses `503`; the engine's own
call is not asked; the commit revert and the rollback read the timeline;
the duplicate door's admission of each copied source; a host with no
metadata store holds none; the install door and the ensure-customization
door are not asked.
- `packages/runtime/src/domains/packages-ensure-customization.test.ts`:
a base that holds a knowledge source (a registered item and a stored
row) gets a pair that holds none, and the door writes one manifest and
no row.
- `packages/objectql/src/knowledge-source-unserved.test.ts` (new): the
boot notice.
- `packages/metadata-core/src/knowledge-source-save-admission.test.ts`
(new): the admission seam.

## Acceptance notes

- **Governed (Tier H) and over 3000 changed lines**: draft until the
maintainer's approval. The diff touches `skills/**` and declares a
narrowing.
- **Rulings this PR implements**: record 7192063608 on objectstack-ai#37304 (forks 6
and 4d, both A); earlier on the same card Q1 = B (the type sits in
ADR-0150's bucket 3) and Q2 = B (`manage_knowledge_sources` beside
`manage_metadata`, platform administrators only); and ruling A of
2026-11-27 (record 7207325373): every write door of an existing package
asks the capability when the package holds a knowledge source, and
install stays unasked. The ADR-0150 rows ride objectstack-ai#37545. One ADR line is
edited here, with the zone's approval (claim comment 7203310811 on
objectstack-ai#37304, amended by 7204020473): ADR-0084's type table gains the
`knowledge_source` row its item 6 prescribes for a type registered after
the ruling (AI, `ai`, 5, 高级), spelled as the `ai_context` row is.
Nothing else under `docs/adr/**` changes.
- **The loader's signal** is `protocol.onMetadataMutation` (a save, a
publish, a delete, a revert) plus the `metadata:reloaded` hook (a
package published, installed or removed, a dev reload), not
`metadataService.subscribe`. After either it reads the published set
again and reconciles, so a missed event is repaired by the next one.
- **Guard two is not asked where no knowledge service is mounted**
(there is nothing to ask, and the item is inert there), nor for a system
write.
- **Two package doors are not asked the new capability (limits).** The
install door (`POST /packages`): a package's source arrives by that
door's own admission, as the ruling leaves it. The ensure-customization
door (`POST /packages/:id/ensure-customization`): it writes nothing of
the base and creates an empty pair, so it creates, changes and removes
no knowledge source; the seat confirmed this reading on the condition
that the pair holds no source, which
`packages-ensure-customization.test.ts` pins.
- **The package gate reads before it answers.** For a caller without the
capability the twelve doors read the package's drafts and items (and its
commits, for the two timeline verbs) before the door's own request
checks. A host with no metadata store at all (the table was never
created, or the engine holds no `sys_metadata` object) reads as holding
none, by the same rule the protocol's overlay reads use; any other
failed read refuses `503`.
- **The read-side author exemption** stays keyed on `manage_metadata`.
- **A bare name two sources answer to** is refused `409` at the call
that names it (`resolveSourceRef`), listing the candidates; both sources
register. Where the host cannot place a package's namespace, the
package's face is its bare name, and that name answers `409` for both
sources until the package is placed.
- **The four narrowings the ADR-0150 addendum asks this card to declare,
each counted on this tree**: the install refusal inside a namespace (two
packages of one namespace holding a source of one name): 0. The name
grammar (a source whose name the grammar refuses): 0. The `409` for a
bare name two packages hold: 0. The package-less row under a name a
package holds: 0. The tree holds one knowledge source,
`showcase_task_notes`
(`examples/app-showcase/src/ai/task-notes.knowledge-source.ts`), and no
first-party code registers one through the plugin door.
- **`KnowledgeIndexStatusEntry.kind` is removed** with the source kinds;
`packageId` is added.
- **One ADR-0087 marker.** The gate allows exactly one marker per
breaking changeset, so the changeset carries `registered …` and names
`indexDocument` / `deleteDocument` in prose: they are runtime-interface
members with no metadata form, and the compiler reports each call
(`TS2339`).
- **The boot notice adds one boot read** of `knowledge_source` rows on a
kernel that does not hydrate from its database; it registers nothing
(`plugin.integration.test.ts` pins the permitted reads and now names
this one).
- **pgvector `dropSource` and a concurrent build in another process**:
the drop retires the active and the building generation in one
transaction but does not hold the builder lock across it, so a build
already running in another process could still write its generation
afterwards. Not changed here; it is a candidate follow-up.
- **objectstack-ai#37479 (unregistered adapter) is not folded in.** The loader runs
after publish, so it is not a refusal point for publish; objectstack-ai#37442 adds the
coded refusal for an unmounted adapter.
- **The showcase mounts the two plugins by hand** rather than declaring
`requires: ['knowledge']` (objectstack-ai#37442): the token mounts a libSQL or
pgvector store, which needs a configured embedder, and the demo runs on
the in-memory store with none. A host that mounts the service itself
keeps its own, as objectstack-ai#37442 specifies.
- **Merged with `main` three times** (no rebase). The first merge (at
`45ed022b`) followed objectstack-ai#37442, objectstack-ai#37570 and objectstack-ai#37578: four textual conflicts
(the migration registry template, the CLI knowledge test fixture, the
pgvector adapter's search refusal, the knowledge service's reindex chain
and unmounted-adapter refusal). Code and fixtures those PRs wrote
against the 18 source shape follow the 19 shape here: `source.id` is
`source.name`, `contentFields` is `content`, `reportUnmountedAdapters`
names a source by its face, and the unmounted-adapter index test calls
`reindexSource` now that `indexDocument` is gone. The second merge (at
`c2bfa3ef7`) was forced by a conflict: `main` had gained its own
protocol 19 conversion
(`permission-view-all-fields-beside-record-bypass`), so the conversion
registry, the migration registry template and the retired-key pin now
carry both sets, sorted as the registry sorts them;
`packages/spec/authorable-surface/ai.json` was merged three ways by hand
so that this PR's removals and `main`'s new `ai/Skill:context` both
stand; every generated spec surface was regenerated afterwards. The
third merge (at `8b9b9d235`) was forced by objectstack-ai#37723, which moved the
ADR-0150 D3 rule into
`packages/metadata-core/src/package-scoped-resolution.ts`: `core`'s file
is taken from `main` (a re-export) and the `knowledge_source` row with
its comment sits in `metadata-core`'s `PACKAGE_SCOPED_TYPES`;
`default-changes.ts` keeps both protocol 19 entries (`main`'s
`ai/AIModelConfig:provider` and this PR's `ai/KnowledgeSource:refresh`);
the Studio menu placement pin takes `main`'s move of `position` and
keeps this PR's row. The merge is its own commit and
`packages/spec/authorable-defaults/ai.json` was regenerated in the next
one (`737f44341`).
- **The declared default of `ai/KnowledgeSource:refresh`** sits under
major 19 in `default-changes.ts` (no parsed value changes: the published
JSON Schema now states the `{}` the parser always applied).
- **Enumeration pins found by CI, not by the first local pass.** The
first head was verified on the packages the change edits. CI then failed
on tests in packages it does not edit, each a list that counts metadata
types or the platform administrator's capabilities: the owner-stamp boot
fixture and the unbundled-type list (`packages/metadata`), the tier list
(`packages/metadata-protocol`), the type-label counts
(`packages/platform-objects`), four golden grant lists
(`packages/plugins/plugin-security`), and the generated `zh-Hant`
locale. Each gained the one entry; no product code changed for them. The
suites of those packages and the workspace type check now run locally as
well (see Verification).
- **Review round 1.** The contract review on `45ed21271` (comment
7206413701) read PASS with findings, and the seat ordered a rework
(7206423476). This head answers it: authoring guards cover more doors
and more of what a source reads (the package doors, the duplicate door,
the fields `where` reads, the service lookup at the dispatcher and at
MCP), the `content` member refuses the empty string, the changeset lists
the twelve removed exports, and this body is corrected on the face
collision and states the narrowing counts. The findings' detail is with
the seat. Two nits are carried by cards the zone files under objectstack-ai#37304
(ADR-0084 prose; tombstone wording for code-door registrants).
- **Existing tests edited outside the card's first surface** (claim
amended by the zone, comment 7207505784 on objectstack-ai#37304), each because a
package door now reads the package for a caller without the capability:
- `packages-publish-drafts-request-conformance.test.ts`: the
real-protocol case's caller also holds `manage_knowledge_sources` (its
engine is one nothing may touch; the case pins the protocol's own
order). Assertions unchanged.
- `packages-publish-drafts-probe-caller-context.test.ts`: the protocol
double gains a `getMetaItemsPerPackage` stub beside its `getMetaItems`
stub. Assertions unchanged.
- `package-state-host-store.test.ts` (a kernel with no driver) and
`domains/error-passthrough.test.ts` (a protocol double that throws from
every member): the caller also holds `manage_knowledge_sources`.
Assertions unchanged.
- `packages-ensure-customization.test.ts`, "duplicate: 400 before a row
is read": **the measure changes.** The door now reads the source
package's knowledge sources to admit them before the copy runs, so the
case counts the reads made inside `protocol.duplicatePackage` (still 0)
instead of every engine read; it also asserts the copy was entered once.
- **Open PRs that will conflict with this one** (overlap-check on this
head against 12 open PR heads; `main` itself merges cleanly): objectstack-ai#37422
(the generated references and `scripts/check-skills-token-ratchet.mjs`:
whichever lands second re-measures the row), objectstack-ai#37366
(`packages/spec/export-origins/ai.json`). Whichever of each pair lands
second merges `main`.

## Verification

First files to read, by risk:
1.
`packages/services/service-knowledge/src/knowledge-source-registry.ts`:
the slot and face rules.
2. `packages/services/service-knowledge/src/knowledge-source-loader.ts`:
what each metadata event does to an index.
3. `packages/rest/src/meta-item-read-gate.ts`
(`META_TYPE_WRITE_CAPABILITIES`) and
`packages/metadata-core/src/knowledge-source-save-admission.ts`: the two
guards.
4. `packages/runtime/src/domains/packages.ts`
(`refuseKnowledgeSourcePackageWrite`,
`refuseDuplicatedKnowledgeSources`): the guards at the package doors.

Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run --maxWorkers=2
src/__tests__/knowledge-source-registry.test.ts
src/__tests__/knowledge-source-loader.test.ts`.

Head `cf128e59f` (review round 1). Verified so far on this head,
locally, every heavy run under `scripts/pm/os-verify-lock.sh`: build
exit 0; `@objectstack/runtime` full suite exit 0 (657 files, 13676
passed, 25 skipped); `@objectstack/metadata-core` and
`@objectstack/core` exit 0; `tsc --noEmit` on `packages/runtime` exit 0.
Running now on the same head, and written here when they end: the other
package suites, the workspace type check, the derived gates, the full
dogfood battery and the ablations. CI on this head is in progress. The
previous head's readings (`45ed21271`: 62 check runs green, 185 gates,
the dogfood battery, six ablations) are in the os-dev report, comment
7206197293 on objectstack-ai#37304.

<details><summary>Skills readings (the diff touches
<code>skills/**</code>)</summary>

| | Lines before | Lines after | Tokens before | Tokens after |
|---|---|---|---|---|
| `skills/objectstack-platform/SKILL.md` | 421 | 421 | 6151 | 6156
(ceiling 6156) |
| `skills/objectstack-ai/SKILL.md` | 486 | 486 | 6799 | 6799 (ceiling
6801) |
| All `SKILL.md` files together | 4961 | 4961 | | |
| Ratcheted (authored) bundle | | | 199660 | 199665 (ceiling 204478) |

`skills/objectstack-ai/references/_index.md` is generator-owned (53
lines to 52: the embedding module's row leaves, the knowledge source's
row is reworded) and is measured, not ratcheted. "Before" is `main` at
the third merge (`8b9b9d235`), read with the same script; the bundle's
before figure is this tree's reading less the row's 5 tokens.

</details>

## Remaining

- The same reviewer's read of the round 1 delta
(`45ed21271..cf128e5`), then the seat's hand-off.
- `knowledge-pgvector`'s `dropSource` contract cases have not run
anywhere yet: there is no pgvector in the build container, and the job
with a PostgreSQL service does not run on `pull_request`. Their first
run is the merge queue.

## Human Minimum

- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
- [x] 2. Every name I added uses the casing for its kind.
- [x] 3. No formatter ran; `pnpm lint` passes.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` touched: its generated artifacts are
regenerated and committed.
- [x] 7. No hand edits to `content/docs/references/`,
`packages/*/CHANGELOG.md` or `content/docs/releases/`.
- [x] 8. Title, body and comments are in English.
- [x] The *Before Submitting* list in CONTRIBUTING.md is done.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Utp6CZe3KTAXogcUJuvYEx

<!-- signed: repo:objectstack#5 · os-bill ·
session_01Utp6CZe3KTAXogcUJuvYEx -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

service-knowledge: os knowledge rebuild and status give the right answer behind a load balancer

2 participants