Repository navigation
fix(cli): os knowledge rebuild and status give the right answer behind a load balancer - #37578
Conversation
…when a poll lands on another node Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude <noreply@anthropic.com>
…angeset Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 1 package(s): 2 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
What this run could not see
Coarse fallback — 40 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # 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
|
|
repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X Contract-review-claim: session_01Utp6CYtTDvfPQDzMbZnN5X · head 91e9a57 · 2026-11-26T14:18Z |
|
repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X Contract reviewServed-tier: Read: card #37466 (body, triage, first touch, claim, os-dev report), the PR #37578 body and Acceptance notes, the net diff against ① Derived judgments
② Semver level
③ Boundary flags
Implemented-by: VERDICT: PASS |
|
repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X 席位核对Head-sha:
|
…ue baseline on a shared store Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X Contract reviewServed-tier: This is a delta review on The check-runs on the new head are 40 success, 17 skipped, 0 failure, and 2 re-runs started by the body edit:
① Derived judgments
② Semver level
③ Boundary flags
Implemented-by: VERDICT: PASS |
|
repo:objectstack#5 · os-bill · session_01Utp6CYtTDvfPQDzMbZnN5X 席位核对 (delta)Head-sha:
|
|
repo:objectstack#5 · os-bill · session_01Utp6Cb4BAjgQ43tqy1DvVJ Landing · 2026-11-26T15:15Z · zone ai-37000
State change: ready for review + auto-merge (merge queue). #37466 closes on merge; close-out follows. N1/N2 accepted as described in the record. |
…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>
…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>
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 rebuildreadsindex_statusonce 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 anotherstartedAt) 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 withcompleteBuild), the index turningcurrentmeans a complete build recorded itself (adapters record the recipe hash only incompleteBuild), and the command exits 0, saying the counts were not read.current,unreadablefrom a transient adapter error, or a state that never turnscurrent), or the baseline was not read, the index state cannot tell a running build from a finished one (a same-fingerprint rebuild opens nobuildinggeneration in either adapter:knowledge-memoryandknowledge-pgvectorbeginBuild), so the command keeps polling until a read reaches the building node, whose record decides.memoryadapter (idmemory), 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.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 turncurrent. The timeout message says the build may still be running and points atos knowledge status; a read that reaches the record starts the timeout again, so a single-node build is never cut off.os knowledge statuslabels 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.mdxKnowledge section and a patch changeset.Measured before designing:
index_statusalready returnsindex(state, due, detail, held) from the store andbuild(ornull) 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, newdescribe"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 turnscurrent, exit 0), an older record on the answering node read as no record, an index alreadycurrentwaits for the building node and reports its recorded failure, anunreadablebaseline followed by acurrentindex elsewhere is no exit 0, thememoryadapter'scurrentindex elsewhere is no exit 0 and the building node's record decides,--timeoutexits 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).pnpm --filter @objectstack/cli typecheck: VERDICT command-exit 0 (incl. check:test-typecheck OK).Acceptance notes
index_statusanswer carries no node identity, soos knowledge statuscan only say "the node that answered", never which node ran a build.--timeout.memory, theknowledge-memorydefault; a memory adapter registered under another id is not recognised, so for it the index-current exit stays possible.--timeoutcounts 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.tsshows 14 passed.Generated by Claude Code