Skip to content

feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service - #38013

Merged
os-zhuang merged 12 commits into
mainfrom
claude/area-o1C-37983
Nov 28, 2026
Merged

os-zhuang merged 12 commits into
mainfrom
claude/area-o1C-37983

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes #37983

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: skills/objectstack-ai/SKILL.md § Knowledge Sources (RAG) — the run-time clause now says that where an app ships no source, a run-time save is refused (503 SERVICE_UNAVAILABLE, nothing written) until the stack declares requires: ['knowledge'] and the server restarts (it said such items are never indexed); the matching eval case in skills/objectstack-ai/evals/skills-tools-knowledge.json expects the same; the token-ratchet row moves 6893 → 6906 under ruling record 6513306068, letter B

维护者速读

  • 作者在没装知识服务的部署上,通过工作台、元数据接口或智能体工具保存知识源时,会当场失败并看到原因和修法(先在应用配置里声明需要知识服务并重启,再保存);以前这种保存显示成功却永远不生效。
  • 属于知识库检索这条线,执行您选的方案 D:让作者在保存那一刻就知道,而不是只在看不到的服务器日志里。
  • 只影响在这类部署上保存知识源的作者;在这类部署上复制一个含知识源的整个应用包也会被拒、什么都不复制(这是裁决点名的三处之外的第四处,请批准前读下方的待定问题一节);装包、种子数据、迁移照常通过;出问题可整单撤回。
  • 要你做的:批准这次收窄(按审批流程)。

What changes

Ruling D (maintainer, recorded on #37983, comment 7220511579) is implemented in the one predicate every save door asks, authoredKnowledgeSourceRefusal (packages/metadata-core/src/knowledge-source-save-admission.ts):

  • No knowledge service registered + a non-system writer ⇒ refused. resolveKnowledgeService() answering undefined (or null) used to admit the save; it now answers 503 SERVICE_UNAVAILABLE with a message that names the item, the reason and the remedy in order: add requires: ['knowledge'] to the stack (or, on a host that composes its own kernel, KnowledgeServicePlugin and a knowledge store), restart, then save the source again. Nothing is written.
  • Held as ruled: the engine's own write (isSystem: package install, seed, migration) is never refused (the isSystem check still runs before the service is resolved); a REGISTERED knowledge service with no admitAuthoredSource (not the platform's, for example host-mounted) keeps today's accept. The module doc (:33-34 on main) now says both, and gains a section on the no-service case.
  • Doors. No door code changed shape: PUT /meta/:type/:name in packages/rest passes refused.code through for a non-403 (SERVICE_UNAVAILABLE), the runtime dispatcher PUT derives SERVICE_UNAVAILABLE from 503, and the MCP save_metadata_draft passes refused.code through for a non-403 (on main since knowledge_source: adapter becomes optional (the deployment's store), and a knowledge_source item mounts the knowledge service #37306). Only their comments are updated. Each door is pinned.
  • Why 503 SERVICE_UNAVAILABLE (ADR-0112 status table, STATUS_TO_STANDARD_CODE in packages/spec/src/api/errors.zod.ts): the save needs a service this deployment does not run. It is the code this module already answers for a knowledge service that cannot be reached, and the code the knowledge service answers at index and search for a source whose store is not mounted (the same kind of composition fact). It is also the one code all three doors already carry without a door change. Rejected: 400 VALIDATION_ERROR (the item is valid; a validation code sends the author to fix the item), 403 (not a permission), 501 NOT_IMPLEMENTED (the meta door's answer for a protocol with no saveMetaItem), 409 RESOURCE_CONFLICT and 428 PRECONDITION_REQUIRED (no conflicting resource, no missing request precondition), and a new ledger code (a contract change the ruling did not make). The message carries the remedy and does not say "try again".
  • ADR-0087: Metadata-protocol: narrowed owes a registered entry: packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts (notice only, no D2 conversion: the fix is the deployment's composition, never the item). The changeset carries registered with that id.

Boot line and docs (ruling items 2 and 4), landed after #37306

Held off this branch until #37306 merged (PR #38026, dbe0716); main is now merged in (1ca3a31) and the held commit is re-applied as 33acf12.

  • Boot line (packages/objectql/src/knowledge-source-unserved.ts): the line for knowledge_source items held with no knowledge service now names the same remedy as the save refusal, from the item-4 patch's UNSERVED_REMEDY: declare requires: ['knowledge'] and restart (or, on a host that composes its own kernel, KnowledgeServicePlugin and a knowledge store). Before, it said "add KnowledgeServicePlugin and a knowledge adapter to the composition". Only the boot-line half of that patch was taken: knowledge_source: adapter becomes optional (the deployment's store), and a knowledge_source item mounts the knowledge service #37306 did not touch this file, so main still carried the old text.
  • What knowledge_source: adapter becomes optional (the deployment's store), and a knowledge_source item mounts the knowledge service #37306 changed, and what that changes here. A source the app ships in knowledgeSources now mounts the service by itself, and adapter is optional. So a source saved at run time (Studio, the metadata API, MCP) is never one that mounts the service, and the remedy the maintainer ruled (requires: ['knowledge'], restart, then save) is still the one that fixes such a save. The refusal sentence is unchanged. The docs now also say that a source saved at run time does not mount the service. The boot-line module doc says that the items it names are ones the stack does not ship. Main's knowledge-rag.mdx already said "the token is for an app that ships none and authors its sources at run time", which matches.
  • Docs. content/docs/ai/knowledge-rag.mdx: a bullet beside "Without a source or the token", plus a clause on the run-time-authoring bullet. content/docs/protocol/knowledge.mdx: the boot-line paragraph names the remedy (it named the plugin and an adapter), and a paragraph under "Who may author one" covers the refusal, the duplicate and the holds. Rewritten against main's merged text, not patched blindly: git am --3way conflicted on knowledge-rag.mdx.
  • Changeset: gains the @objectstack/objectql and @objectstack/skills patch lines and their bullets.
  • The MCP draft door on main now passes refused.code through for a non-403 (knowledge_source: adapter becomes optional (the deployment's store), and a knowledge_source item mounts the knowledge service #37306), so this refusal still arrives there as SERVICE_UNAVAILABLE.

Open question

The package duplicate door (POST /packages/:id/duplicate) asks the same predicate for each knowledge source it copies, so on a deployment with no knowledge service it now refuses a duplicate of a package that holds one, 503, naming the remedy (pinned in packages-knowledge-source-gate.test.ts). The ruling names three doors; this is the fourth door that saves a source as the caller. Keeping it refused is the predicate's own reading and the ruling's principle (the copy would be kept and never served); carving it out needs a new input on an exported function. Recommendation: keep it.

Tests

  • packages/metadata-core/src/knowledge-source-save-admission.test.ts: refusal with code, status, the reason sentence and the ordered remedy, for both URL spellings and for undefined/null; an unnamed item; isSystem not refused and the service never resolved; a registered service without the member still admits.
  • REST PUT (packages/rest/src/meta-write-door-capability-enumeration.test.ts): refused on the kernel's branded "never registered" miss and on a server with no kernel provider; system write saved; host-mounted service saved.
  • Runtime dispatcher PUT (packages/runtime/src/domains/meta-save-capability-gate.test.ts): refused on a real ObjectKernel with nothing registered; system write saved; host-mounted service saved.
  • MCP save_metadata_draft (packages/runtime/src/domains/mcp-authoring.test.ts): refused, nothing written, another type still saves; host-mounted service saved.
  • Package duplicate (packages/runtime/src/domains/packages-knowledge-source-gate.test.ts): refused, nothing copied; a package with no source and the engine's own call copy as before.
  • Boot line (packages/objectql/src/knowledge-source-unserved.test.ts): names Declare requires: ['knowledge'] in the stack and restart.

Head is now 5bc3ee1a00. Since 33acf12ec4 it adds only: the test-harness fix 6e4a904ea1 (the MCP knowledge_source contract case from #38053 mounts an admitting knowledge service; comment 7232197442), the skills text, eval expectation, ratchet row and changeset line above, the module-doc wording at index and search, and two clean merges of main (the second carries #38091). No runtime or rest code moved after 33acf12ec4, so the dogfood battery below stands. On 5bc3ee1a00: the skills token ratchet exits 0 (6906, headroom 0; self-test 111 cases pass), check:skill-docs and check:skill-refs exit 0, and the changeset, ADR-0087, NUL-byte and issue-citation gates exit 0. After the harness fix, runtime reads 12315 passed, 0 failed.

Readings at head 33acf12ec4 (main merged in; shared container; every build and test through scripts/pm/os-verify-lock.sh, verdict command-exit 0 each round):

Tests and typecheck at 33acf12
  • Full build (turbo run build, all but docs) exit 0, packages/runtime/.objectstack cleared, @objectstack/spec check:generated exit 0.
  • @objectstack/metadata-core pnpm test: Tests 1113 passed; typecheck exit 0.
  • @objectstack/objectql knowledge-source-unserved.test.ts: Tests 7 passed; typecheck exit 0.
  • @objectstack/rest, 4 files (door enumeration, type-write capability, both org-scope suites): Tests 161 passed; typecheck exit 0.
  • @objectstack/runtime, 10 files (dispatcher save gate, MCP authoring, package knowledge gate, error passthrough, capability parity, org scope, ensure-customization, publish-drafts x2, package state store): Tests 304 passed; typecheck exit 0.
  • On the first head, 5 suites that save a knowledge_source as a capable author with no knowledge service went red: that is the ruled refusal. Their harnesses now mount a knowledge service that admits every source. Two door-level isSystem cases were dropped because inbound HTTP never carries isSystem (metaTypeWriteRefusal answers 401 first); that hold is tested at the predicate instead.
  • Narrowed locally: the full rest and runtime suites, test:repo, and the derived families not listed under Gates run in CI.
Ablations (one per tested behaviour)
  • The save refusal (at dd50936): scripts/ablation-replace.mjs replaced the one new line (anchor 1 -> 0, marker 0 -> 1). @objectstack/metadata-core was rebuilt, and ablation-dist-preflight found the marker in dist/index.js and dist/index.cjs. Exactly these went red: the predicate test (1 of 9), REST PUT (1 of 81), and dispatcher PUT, MCP draft save and package duplicate (3 of 162). Restored with git checkout HEAD (blob back to cd26e8f520, git diff HEAD empty), rebuilt, and preflight --absent was clean.
  • The boot line (at 33acf12): the remedy was put back to main's text (anchor 1 -> 0, marker 0 -> 1; the test imports source, so no build was needed). Red: names the item, the missing service and both remedies (1 of 7). Restored with git checkout HEAD (blob aa50e2ec54, git diff HEAD empty).
  • The docs pages are not ablated.
Live server (REST door, at dd50936)

After a full build I ran pnpm dev:crm -- --fresh -p 38937; the CRM stack declares requires: ['ui', 'automation'] and no knowledge. Signed in as the seeded admin, PUT /api/v1/meta/knowledge_source/faq answered 503, error.code SERVICE_UNAVAILABLE, with the remedy sentence. A GET of the item then answered 404, so nothing was written. The server was stopped by its recorded pid. A positive control on a stack with requires: ['knowledge'] was not run (NOT MEASURED); the unit tests cover the admitted path.

Gates at 33acf12

Local, exit 0 each: check-adr-0087-registration (1 declared-breaking changeset, with its disposition), check-changeset-no-major, check-empty-changeset, spec check:upgrade-guide, check:spec-changes, check:api-surface (unchanged), check:nul-bytes, check:doc-authoring, check-affected-docs, check:issue-citations, check:dispatcher-error-vocabulary, check:startup-registry-verdict, check:durability-log-level. At dd50936 these were also exit 0: check:authorable-surface, check:route-envelope, check:error-status-conformance, check-closing-keyword-parity, check:cross-package-test-inputs, check:test-source-alias, check:adr-anchors. overlap-check before the push: clean against main and against #38043, #37982 and #37963.

Dogfood battery at 33acf12

The full battery, run as CI runs it (no OS_TEST_SHARD, no path), under scripts/pm/os-verify-lock.sh. The build was turbo run build --filter='@objectstack/dogfood^...' and exited 0. The test was pnpm --filter @objectstack/dogfood test.

  • Verdict: VERDICT command-exit 0 · held the lock 1727s (28m47s), in shared-box seconds.
  • Test Files 490 passed | 3 skipped (493)
  • Tests 4144 passed | 68 skipped (4212)
  • Failures: none.

Recorded in comment 7229739676. CI's Dogfood Regression Gate on the PR reads OS_DOGFOOD_RESULT: skipped (the shards run in the merge queue), so it is not evidence for this head.

Acceptance notes

Verification

Read first (by risk): packages/metadata-core/src/knowledge-source-save-admission.ts (the service === undefined || null branch, before the member check), packages/runtime/src/domains/packages-knowledge-source-gate.test.ts (the fourth door), content/docs/protocol/knowledge.mdx (the two paragraphs rewritten against #37306's text).

Two-minute check: pnpm --filter @objectstack/metadata-core exec vitest run src/knowledge-source-save-admission.test.ts — expect the "no knowledge service registered" cases green; flip line if (service === undefined || service === null) return noKnowledgeServiceRefusal(input.item); out and they go red.

Body refreshed 2026-11-28T03:15Z at head 5bc3ee1a00; the readings in the three blocks above were taken at 33acf12ec4.


Generated by Claude Code

…ployment with no knowledge service

Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
Co-authored-by: Claude <noreply@anthropic.com>
…y door that saves a knowledge_source

Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
Co-authored-by: Claude <noreply@anthropic.com>
…nowledge_source save refusal

Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
Co-authored-by: Claude <noreply@anthropic.com>
… mounts a knowledge service; the door isSystem hold lives at the predicate

Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
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 27, 2026
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 5 package(s): @objectstack/metadata-core, @objectstack/objectql, @objectstack/rest, @objectstack/runtime, @objectstack/spec, touching 12 documentable anchor(s).

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

  • content/docs/ai/connect-mcp.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/ai/knowledge-rag.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/api/client-sdk.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/api/error-catalog.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/api/index.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/automation/webhooks.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/deployment/self-hosting.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/kernel/runtime-services/email-service.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/permissions/authentication.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/permissions/authorization.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/permissions/sharing-rules.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/permissions/system-context.mdx (via authoredKnowledgeSourceRefusal (symbol, a top-level function), handleMetadataRequest (symbol, a top-level function), openWriter (symbol, a top-level function), registerMetaItemWriteRoutes (symbol, a top-level function))
  • content/docs/protocol/kernel/error-handling.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/protocol/knowledge.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/ui/print-pages.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))

⛔ 11 release-owned page(s) also name something this change touched. These are read-only:

  • content/docs/releases/implementation-status.mdx (via RestServer (symbol, a top-level class))
  • content/docs/releases/v12.mdx (via RestServer (symbol, a top-level class))
  • content/docs/releases/v16.mdx (via RestServer (symbol, a top-level class))
  • content/docs/releases/v17/17-0.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/releases/v17/17-3.mdx (via RestServer (symbol, a top-level class), SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/releases/v17/17-4.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/releases/v17/17-5.mdx (via RestServer (symbol, a top-level class))
  • content/docs/releases/v17/17-7.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/releases/v18/18-2.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))
  • content/docs/releases/v18/18-3.mdx (via RestServer (symbol, a top-level class))
  • content/docs/releases/v18/18-5.mdx (via SERVICE_UNAVAILABLE (literal, a string literal in noKnowledgeServiceRefusal))

content/docs/releases/ is RELEASE-OWNED (AGENTS.md "Documentation Guardrails"): release
notes are written centrally at release time, and a code PR that edits them is the exact PR
that guardrail exists to stop. They are still audited — read-only. If one of them is actually
wrong, file an issue or open a dedicated docs-only PR; do not edit it here.

What this run could not see
  • 3 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 — 184 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 bbe4258649c1ea8492364413c0669f47140f7707 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from b447ce4e281d5c4e2b95d9d8242a4fcf1318f43a — the merge of head 5bc3ee1a00c4ca0982856ab07cb550ab855dc8e6 into base bbe4258649c1ea8492364413c0669f47140f7707, 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 b447ce4e281d5c4e2b95d9d8242a4fcf1318f43a && git checkout b447ce4e281d5c4e2b95d9d8242a4fcf1318f43a
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin bbe4258649c1ea8492364413c0669f47140f7707 5bc3ee1a00c4ca0982856ab07cb550ab855dc8e6 && git checkout -B drift-repro bbe4258649c1ea8492364413c0669f47140f7707 && git merge --no-ff 5bc3ee1a00c4ca0982856ab07cb550ab855dc8e6

node scripts/docs-audit/affected-docs.mjs --json bbe4258649c1ea8492364413c0669f47140f7707

⚠️ 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 bbe4258649c1ea8492364413c0669f47140f7707 → 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#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · 33acf12 · 2026-11-27T21:08Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 33acf12ec4b1c5a7d50fe55b99864f867d9e1812
Local-runs: none
Scope: packages/spec/src/migrations/entries/semantic/19.knowledge-source-save-refused-without-knowledge-service.ts + packages/metadata-core/src/knowledge-source-save-admission.ts, packages/objectql/src/knowledge-source-unserved.ts, packages/rest/src/meta-item-write-routes.ts, packages/rest/src/rest-server.ts, packages/runtime/src/domains/meta.ts, packages/runtime/src/domains/mcp-authoring.ts, and the eleven test files of the diff (narrowing face: every path outside the prose faces). Read in the cited code, not reviewed: packages/runtime/src/domains/packages.ts (the duplicate door), packages/runtime/src/http-dispatcher.ts (resolveServiceOrLoud, classifyService), packages/rest/src/rest-api-plugin.ts (kernelServiceProvider), packages/services/service-knowledge/src/knowledge-service.ts and knowledge-service-plugin.ts, packages/spec/src/kernel/platform-capabilities.ts, packages/spec/src/api/errors.zod.ts, packages/spec/src/migrations/types.ts, packages/rest/src/meta-item-history-routes.ts.

Inputs: card #37983 body and all four comments (ruling 7220511579, claim 7220546046, dev reports 7222789795 and 7228132286; no earlier contract-review record), PR #38013 body and file list, the net diff against main (merge base 8d34c44, which is origin/main), and the check-runs on the head: 59 success, 12 skipped (opt-in and queue-only jobs), 0 failure, 0 pending.

① Derived judgments

  • Accept set, narrowed, right: authoredKnowledgeSourceRefusal answered undefined (admit) on main when resolveKnowledgeService answered undefined or null for a non-system writer; at this head it answers a 503 SERVICE_UNAVAILABLE refusal. One new line decides it, placed after the isSystem return and the resolve try/catch and before the member check. This is the narrowing ruling D item 1 orders, and the PR declares it.
  • Accept set, held, right: isSystem === true returns before the service is resolved (ruling item 2); a registered service with no admitAuthoredSource still admits (the claim's fold-or-serial line: only "no knowledge service registered" is ruled). Both are pinned at the predicate.
  • Public surface, unchanged, right: the exported function's signature, AuthoredKnowledgeSourceRefusal, KnowledgeSourceSaveAdmitter and KNOWLEDGE_SOURCE_ADMISSION_SERVICE are untouched; noKnowledgeServiceRefusal is module-private; UNSERVED_REMEDY in objectql is module-private. No Zod schema changes. The spec package gains one semantic migration entry (discovered by file name, id unique in the tree).
  • Doors, right: no door changes shape. REST PUT passes refused.code through for a non-403; the dispatcher PUT answers deps.error(message, 503); the MCP draft save passes refused.code through for a non-403; each is pinned with code, status, the reason sentence, the ordered remedy and a zero-write assertion.
  • Derived and wider than the ruling's enumerated doors: the package duplicate door (refuseDuplicatedKnowledgeSources, not in the diff) asks the same predicate, so a non-system duplicate of a package holding a source is refused 503 on a no-service deployment. Declared in the changeset, the entry's surface, the protocol docs page and a pin. See ③.
  • Boot line, right: text only; describeUnservedKnowledgeSources keeps its signature and its warn, never-refuse posture (ADR-0078 §4, ruling item 2). UNSERVED_REMEDY is a const declared below the function that reads it; it is read at call time, after module evaluation, so there is no temporal-dead-zone fault.

② Semver level

  • Clause-②: no (narrowing) and Metadata-protocol: narrowed appear line-initial in both the PR body and the changeset body. narrowed is the right kind ("a value refused or a requirement tightened"): an author's knowledge_source save that main accepts is refused. no is right: no published export or schema moves (check:api-surface unchanged per the green Lint families).
  • Level: @objectstack/metadata-core minor satisfies "a kind takes at least minor on a package the diff moves"; @objectstack/objectql patch (a log sentence) and @objectstack/spec patch (one upgrade-guide entry) are right for what those packages publish. packages/rest and packages/runtime change comments only and carry no line; nothing they publish moves except through the metadata-core dependency.
  • BREAKING banner, the ! title, the FROM to TO mapping and exactly one ADR-0087 marker (registered knowledge-source-save-refused-without-knowledge-service) are present, and the id matches the entry. Both Check Changeset runs and Lint & Repo Gates are green on this head.

③ Boundary flags

  • Open question (both dev reports, PR body): keep the package duplicate door refused? Answer: A, keep it, as pushed. It is a non-system save of the same item through the one predicate; the ruling's rule sentence reads "at each door that saves one", and its reasoning (ADR-0078 §1) applies to the copy equally; a carve-out needs a new input on an exported function, which the ruling did not order. ESCALATED all the same, because the ruling's parenthesis enumerates three doors and this is a fourth: the refusal blocks the duplicate of a whole package (objects, pages, flows) because it holds one source, and the PR body's maintainer summary does not name it. The Tier H approval is where it is decided; the approver should read the "Open question" section before approving. Not a finding against this head.
  • Dev flag, two door-level isSystem cases dropped: accepted. Inbound HTTP carries no isSystem; the hold is pinned at the predicate, with the resolver asserted never called.
  • Dev flag, five collateral suites now mount an admitting knowledge service: accepted. Each harness change is confined to the knowledge name and keeps the branded not-registered miss for every other name.
  • Dev flag, dogfood battery NOT MEASURED locally: answered by the check-run Dogfood Regression Gate, success on this head.
  • Dev flag, positive live control with requires: ['knowledge'] NOT MEASURED: accepted; the admitted path is unchanged code, pinned by the CONTROL cases, and Test Core 1 to 10 are green.
  • Deviations (commit trailers, a throwaway dev-server session token printed to a transcript and the server stopped): no contract effect; noted, nothing owed here.
  • security_findings: none in both reports: this review found none either. The fail direction stays closed; no accept is widened.
  • SQL push-down: no query, no id materialisation and no in-app join is added anywhere in the diff.
  • Author: user.login is objectstack-fleet[bot]; no relay bypass.
  • Tier: ruling item 3 fixes the landing as Tier H by authorised approval. This record does not replace that approval.

④ Design judgment

No must-fix, no should-fix.

Hits file, 19.knowledge-source-save-refused-without-knowledge-service.ts, against ruling D and its first consumer (the upgrade guide, os migrate meta TODOs):

  • Notice-only with no conversionIds is correct: no key or value of the item changes, and the repair is the deployment's composition, so there is no D2 rewrite to judge. The shape matches SemanticMigration (id, surface, replacement, reason, acceptanceCriteria).
  • replacement and reason agree with the code sentence by sentence: 503 SERVICE_UNAVAILABLE, nothing written, system writes held, a host-registered service answering for its own sources, stored items neither rewritten nor refused at boot (the boot path in knowledge-source-unserved.ts only warns).
  • The remedy is real: platform-capabilities.ts lists knowledge as a requested token that mounts the service and the deployment's store, and KnowledgeServicePlugin registers under the name the doors resolve (KNOWLEDGE_SERVICE, 'knowledge').
  • N1 (nit) — surface, acceptanceCriteria and the changeset's FROM line describe the affected deployment as one whose stack "does not declare requires: ['knowledge']". Since knowledge_source: adapter becomes optional (the deployment's store), and a knowledge_source item mounts the knowledge service #37306 a stack that ships a knowledgeSources entry also mounts the service (mountedBy: { collection: 'knowledgeSources' }), and saves there are accepted. The entry over-includes that deployment; following it there adds a redundant token and breaks nothing. Accepted deviation, or a follow-up docs-face card.

Implementing files, against the ruling:

  • knowledge-source-save-admission.ts: holds. Order of checks is type, isSystem, resolve (throw answers the pre-existing unavailable 503), absent service (new refusal), member check, verdict. The message names the item, the reason and the remedy in the ruled order (token, restart, save) and does not say "try again". The module doc's claim that the knowledge service answers the same code for a store that is not mounted is true (UNMOUNTED_ADAPTER_CODE is SERVICE_UNAVAILABLE, status 503). Tried to break: an unnamed or non-object item (handled, pinned); null service (handled, pinned); a resolver that throws (unchanged path).
  • N2 (nit) — code choice. errors.zod.ts glosses SERVICE_UNAVAILABLE as "temporarily unavailable", and this condition lasts until the stack changes. The ruling left the code open ("a coded refusal (ADR-0112)"), the knowledge service already uses the same code for the same kind of composition fact, and no door needs a new mapping. Accepted deviation.
  • N3 (nit) — on the dispatcher transport and the duplicate door resolveServiceOrLoud also answers undefined for the no-instance-in-scope classification, which would be told "this deployment runs no knowledge service". The platform plugin registers a plain instance (ctx.registerService), so the platform's service cannot reach that state; a host that registers a scoped knowledge factory answering nothing for a scope could. Follow-up card at most.
  • knowledge-source-unserved.ts: holds. The line names the same remedy as the refusal (ruling item 2) and keeps "or remove the item(s)". The module doc's account of where such items come from (a system write after boot, or a save made before the refusal) agrees with the predicate.
  • meta-item-write-routes.ts, rest-server.ts, meta.ts, mcp-authoring.ts: comment-only hunks, each true of the code beside it. REST resolveKnowledgeService answers undefined on no provider and on the branded not-registered miss, and rethrows anything else. N4 (nit) — the reworded jsdoc on OpenAuthoringWriter.itemSaveRefusal ("..., or on a deployment with no knowledge service, or undefined ...") no longer parses as a sentence.
  • N5 (nit) — through the duplicate door the predicate's sentence is appended verbatim, so a caller duplicating a package is told to "save the source again" and that "Nothing was written" after "nothing was copied". Wording only.
  • Tests: the new pins assert code, status, reason, ordered remedy and zero writes at the predicate, REST PUT (branded miss and no provider), dispatcher PUT (real kernel and a double), MCP draft save and the duplicate; the host-mounted accept is pinned at each door. The suites that mount an admitting service do so to stay on their own subject and say so.

Observation outside the diff, not graded: POST /meta/:type/:name/publish and /rollback (meta-item-history-routes.ts) write an item without asking this predicate, as on main. After this change no new draft of a source can be created on a no-service deployment, so the residue is rows that predate the refusal, which the boot line names. A follow-up card can decide whether those doors ask too.

Implemented-by: claude/area-o1C-37983
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

L1 review — REWORK (dogfood battery only); merits accepted

Head: 33acf12ec4b1c5a7d50fe55b99864f867d9e1812 (card #37983, ruling D 7220511579)

Merits: accepted. The contract-tier review is record 7228262724: PASS, no must-fix, no should-fix, five nits. The record verifies at tier. The predicate change matches ruling D: the no-service refusal comes after the system-identity return and before the member check. Each of the three ruled doors, plus the package-duplicate door, passes 503 SERVICE_UNAVAILABLE through, and each door is pinned with its code, status, remedy and zero writes. The boot line names the same remedy. The declarations, levels and ADR-0087 entry 19 agree with the diff. All 62 check-runs on the head are green, with 12 skipped by design.

The l1-face changeset flag is answered. The @objectstack/rest and @objectstack/runtime hunks change comments only and no behavior, so they owe no entry, and Check Changeset is green.

REWORK — one item. The title carries ! and the body declares Clause-②: no (narrowing), so the full dogfood battery is owed on this head and recorded under dogfood_battery. That has not happened yet.

  • The report says the local battery is NOT MEASURED.
  • Dogfood Regression Gate shows success on this head, but its job reads OS_DOGFOOD_RESULT: skipped and OS_VERIFY_RESULT: skipped. The three shards and Dogfood Verify CLI did not run on the PR; they run in the merge queue.
  • So no run of the battery is pinned to this head.

To close it, run the full battery on 33acf12ec4 and record it. If the head does not move and the battery is green, the merits acceptance stands and no delta read is owed. A red result that needs a fix moves the head, and the moved head needs a delta read.

For the Tier H approval: the contract review escalates one boundary item rather than grading it. The package-duplicate door is a fourth refusing door, while the ruling's parenthesis names three. The area ruled to keep it refused, because the rule sentence covers every door that saves one. That refusal blocks duplicating a whole package because of one source, and the body's maintainer summary does not mention it. The approver should read the PR's Open question section.

Nits from the record, optional, for a follow-up card: N1 entry 19's surface text includes stacks that already mount the service by shipping a source; N3 a scoped-factory miss would get the no-service sentence; N4 the itemSaveRefusal jsdoc no longer parses; N5 a duplicating caller is told to save the source again. A second follow-up candidate, outside the diff: the meta publish and rollback routes write an item without asking the predicate. The same is true on main.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Dogfood battery — head 33acf12ec4

This answers the L1 REWORK item (7228292666). The head did not move: 33acf12ec4b1c5a7d50fe55b99864f867d9e1812, and the worktree was clean at the start and at the end.

  • Command, as CI runs it with no OS_TEST_SHARD and no path, under scripts/pm/os-verify-lock.sh (slot dev-37983):
    • NODE_OPTIONS=--max-old-space-size=4096 pnpm exec turbo run build --filter='@objectstack/dogfood^...' --concurrency=2, which exited 0;
    • then pnpm --filter @objectstack/dogfood test, which exited 0.
  • Verdict: VERDICT command-exit 0 · held the lock 1727s (28m47s) · waited 366s (6m06s). These are shared-box seconds. The slot had queued for about 63 minutes across eight tries, and seven of those ended in a queue-timeout, which is not a result.
  • Counts:
    • Test Files 490 passed | 3 skipped (493)
    • Tests 4144 passed | 68 skipped (4212)
    • Duration 1725.09s
  • Failures: none.

The battery is green, so nothing needs a fix and no push follows.


Generated by Claude Code

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

L1 verdict (L1-a): ACCEPT at head 33acf12ec4b1c5a7d50fe55b99864f867d9e1812 (Fixes #37983). Delta read answering REWORK 7228292666. The head is unmoved.

Review summary

The REWORK item is closed. The full dogfood battery ran on this head under the verify lock (comment 7229739676). It used CI's command: the build of the dogfood closure, then pnpm --filter @objectstack/dogfood test. The result was VERDICT command-exit 0:

  • 490 files passed and 3 skipped.
  • 4144 tests passed and 68 skipped.
  • 0 failed.

Nothing was pushed, so the merits acceptance in 7228292666 and contract record 7228262724 (PASS, no must-fix, no should-fix) cover this head as they stand.

The duplicate door is named. The body's maintainer summary now names the fourth refusing door, the package duplicate, and points the approver to the Open question section. This answers the contract review's escalation.

Gates. All 62 check-runs on this head were green earlier. Check Changeset and PR-body guards are re-running after the body edit and must finish green before landing.

Next: this is a narrowing, so it goes to the seat for the Tier H approval. The PR is still a draft.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4cwoXEE1amuRAGHdPBs

Seat record · 2026-11-27T23:02Z · PR #38013 (Fixes #37983) · head 33acf12ec4b1c5a7d50fe55b99864f867d9e1812 · Clause-②: no (narrowing) + Metadata-protocol: narrowed — lands as Tier H

维护者速读

  • 做什么:执行你在 2026-11-27T14:12Z 选的方案 D(「D 拒绝保存并说明」)。部署上没装知识服务时,作者通过工作台、元数据接口或智能体工具保存知识源会当场失败,并看到原因和修法。以前这种保存显示成功,却永远不会生效。
  • 风险:21 个文件 +348/−51,大多是各个保存入口的测试,另有一条语义迁移条目和升级说明。装包、种子数据、迁移照常通过。另外,在这类部署上复制一个含知识源的应用包也会被拒,这是裁决点名三处之外的第四处,专区判定保持拒绝,PR 的待定问题一节有说明。
  • 要你做什么:审批人批准即可。契约审核 PASS 7228262724,Head-sha 33acf12ec4b1c5a7d50fe55b99864f867d9e1812;批准后座位自主落地。
  • 不批会怎样:作者在没装知识服务的部署上保存知识源仍显示成功,但什么都检索不到,原因只留在服务器日志里。

Seat opinion: land.

席位核对 — ACCEPT · repo:objectstack#1 · head 33acf12ec4

  1. Shape. Draft, base main, 21 files (+348/−51): packages/metadata-core/src/knowledge-source-save-admission.ts (the save predicate refuses where no knowledge service is mounted) + test; the save doors on both transports, MCP authoring and the package door (rest/src/meta-item-write-routes.ts, rest-server.ts, runtime/src/domains/meta.ts, mcp-authoring.ts) and their pins; objectql/src/knowledge-source-unserved.ts (boot line); semantic migration entry 19.knowledge-source-save-refused-without-knowledge-service.ts; two docs pages; .changeset/37983-knowledge-source-save-needs-the-service.md. Body: Clause-②: no (narrowing), Metadata-protocol: narrowed, Skills-docs: none (reason recorded). check-governed-merges.mjs --pr 38013: no governed path; the narrowing declaration routes it the Tier H way.
  2. Premise measured. Implements the maintainer's ruling D on knowledge: what a knowledge_source saved at run time does on a deployment that mounted no knowledge service (split from #37306 item 4) #37983 (seat ruling record on the card). The package-duplicate door also refuses: the area ruled A (keep it refused), because the rule covers every door that saves an item. It is named in the brief and the PR's Open question section for the approver. Card acceptance met.
  3. Gates (check-runs at this head). 65 success, 16 skipped, 0 failed; the one cancelled row is a Check Changeset run superseded by the body edit, whose re-run passed. mergeable clean. Full dogfood battery green at this head, feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service #38013 comment 7229739676.
  4. Accepted deviations. The fourth door, as above.
  5. Out of scope → where it went. Nits N1–N5 → one follow-up card filed by area o1-C. Security-touching: yes: this PR changes when a save is admitted. The hardening is stated here at rule level only; anything further is with the security seat.
  6. Landing terms. L1-a ACCEPT 7229764783 + contract review PASS 7228262724 (CONTRACT_REVIEW_TIER, same head) ⇒ ②③ in one --handoff stroke. After an authorised APPROVED, seat 1 lands it (maintainer's seat-thread line 2026-11-26T13:33Z 「审批人批准后的 Tier H PR 你可以自主落地」). A head move other than a clean main merge withdraws the hand-off.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4cwoXEE1amuRAGHdPBs

Approval request · Clause-②: no (narrowing), Metadata-protocol: narrowed (Tier H) · PR #38013 (Fixes #37983) · head 33acf12ec4b1c5a7d50fe55b99864f867d9e1812

@os-zhuang: this implements the maintainer's ruling D on #37983. On a deployment with no knowledge service mounted, a knowledge_source save through Studio, the meta API or the MCP authoring tools is refused with the reason and the fix, where it used to report success and never take effect. Package install, seed and migration are unchanged. For your judgement: the package-duplicate door refuses too, a fourth door beyond the three the ruling names; the area kept it refused (see the PR's Open question section). Records on this head:

  • L1-a ACCEPT 7229764783
  • contract review PASS 7228262724 (CONTRACT_REVIEW_TIER)
  • full dogfood battery green (7229739676)
  • seat record ACCEPT above

Every check is green or expected-skip. An APPROVED review on this head lets seat repo:objectstack#1 ready and land it; nothing else is asked.

@os-zhuang
os-zhuang added this pull request to the merge queue Nov 28, 2026
Merged via the queue into main with commit d59478f Nov 28, 2026
74 checks passed
@os-zhuang
os-zhuang deleted the claude/area-o1C-37983 branch November 28, 2026 04:51
@objectstack-fleet objectstack-fleet Bot removed the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Nov 28, 2026
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…entry; it binds to the deployment's store (objectstack-ai#38026)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Fixes objectstack-ai#37306

Clause-②: yes (widening)
Metadata-protocol: added
Skills-docs: follow-up objectstack-ai#37310 — `skills/**` teaches the optional
`adapter` and the item mount after this lands

## 维护者速读

- 用户能看到什么变化:应用作者写知识源时不必再指定存储,也不必在应用里声明需要知识服务;在本机开发(SQLite)、PostgreSQL
和自带存储的部署上,同一个知识源无需修改即可建索引和检索。
- 为什么做:知识库检索专题(按调用者权限过滤的知识检索)中“知识源可移植”的一行,替写知识源的应用作者和 AI
解决“换个数据库就要改知识源”的问题。
- 出错会怎样:最坏是同时注册了两个以上存储、且都不是部署自带的那个时,未写存储的知识源在保存时被明确拒绝并列出可选项;改动可直接撤回。
- 要你做什么:无(“运行中首次保存、部署未装知识服务时怎么办”已拆成单独的待裁决卡)。

## What changes

**Mechanism (the deployment's-store mark).** It is a service option, not
a contract member: `KnowledgeServicePlugin` / `KnowledgeService` take
`deploymentAdapter?: string`, which the runtime sets to the adapter id
of the store it mounted (`resolveCapabilityArgument('knowledge', …)`
answers `{ deploymentAdapter:
resolveKnowledgeStore(input).store.adapterId }`, the same resolution
`resolveCapabilityExtras` mounts from). `IKnowledgeAdapter` and
`registerAdapter` are unchanged, so an adapter that application code
registers is never the deployment's by registering.

1. **`adapter` optional** (`@objectstack/spec`, ADR-0161 K4 / K8 item
11). `KnowledgeSourceSchema.adapter` is `z.string().optional()`.
Omitted, the source is held by the marked store, else the only adapter
registered. Several registered and none the deployment's ⇒ refused at
registration on both doors (`registerSource`, the `knowledge_source`
loader) and at save (`admitAuthoredSource`), `400 VALIDATION_ERROR`,
naming the choices. A source registered first and left unplaceable by
adapters that came later answers the same refusal at index and search,
and `reportUnmountedAdapters` names it once at boot. No adapter at all ⇒
`503 SERVICE_UNAVAILABLE`, naming the marked store.
2. **Placement is resolved where it is used** (`adapterIdFor` /
`adapterFor` / `boundAdapterId`), so a code-door source registered at
init finds a store plugin that registers in `start()`. Every
`getAdapter(source.adapter)` call site (reindex, index state, record
sync, delete, search planning, reap guard, `dropMetadataSource`) now
goes through it. `index_status` reports the adapter a source is placed
on.
3. **An item mounts the service** (K8 item 12).
`PlatformCapabilityProvider` gains optional `mountedBy: { collection }`;
the `knowledge` row of `PLATFORM_CAPABILITY_PROVIDERS` carries `{
collection: 'knowledgeSources' }`. (Review S1, record 7224273377: the
earlier `type` member had no reader and repeated what the spelling map
owns, so it is dropped.) `@objectstack/core` adds
`stackItemCapabilities(stack)` (top level, then each package body), and
`resolveServedCapabilities(…, { itemTokens })` serves them as declared
tokens, reported in a new `byItems` set. `os serve` / `os dev` / `os
start` and verify's `bootStack` read it and pass `database` to the
argument resolver. `os migrate plan` / `apply` compose the same set:
`stackItemCapabilities` is a composition step of both boots in
`boot-preparation-parity.test.ts`. This answers CI's Test Core red at
aba523a and the review's N3.
4. **Item 4 is split to objectstack-ai#37983 (seat ruling).** The first
`knowledge_source` saved at run time on a deployment with no knowledge
service behaves exactly as on main: row 3a's boot line and behaviour are
unchanged. The built item-4 code is kept on
`claude/area-o1C-37306-item4` (fa2b538).
5. **Docs**: `content/docs/ai/knowledge-rag.mdx`,
`content/docs/protocol/knowledge.mdx`; references regenerated
(`gen:docs`).

What a 19.0.0-next.1 stack sees: one that ships a source without
`requires: ['knowledge']` held an inert item with a boot warning. It is
now indexed: the service mounts, the boot pass builds the index, and the
content fields are sent to the configured embedder (ADR-0161 K5:
embedding is egress). The changeset says the same.

Unchanged: a named adapter that is not mounted answers
`SERVICE_UNAVAILABLE` as before (objectstack-ai#37102); a host that mounts
`KnowledgeServicePlugin` itself gets no store and no mark from the
runtime; without a source or the token nothing is mounted. Out of scope
as fenced: `skills/**` (objectstack-ai#37310), the Studio form (objectstack-ai#37309), hosted/EE
mounts, objectstack-ai#37479's unmounted-adapter reporting.

### Deviations (declared)

- **`@objectstack/runtime`, MCP draft door**
(`packages/runtime/src/domains/mcp-authoring.ts`, `itemSaveRefusal`): a
finding from the dev of card objectstack-ai#37983, carried here. The door spelled
every refusal that was not a 403 as `SERVICE_UNAVAILABLE`, so the new
`400 VALIDATION_ERROR` from `admitAuthoredSource` arrived over MCP as
`SERVICE_UNAVAILABLE` with status 400. Now a 403 stays
`PERMISSION_DENIED` and any other verdict keeps its own code, as the
REST door already does. It carries a pin in `mcp-authoring.test.ts` and
a `@objectstack/runtime` patch entry in the changeset. Outside the
claimed file surface.
- **`@objectstack/cli`, the migrate boot**
(`schema-migration-plugins.ts`, `composeServedPlatform`): it reads the
item tokens as `serve` does. The step pin and a behaviour pin cover it:
an item-only stack composes `KnowledgeServicePlugin`, and the control
does not.
- **Two semantic conflicts with main**: main's new readers of the
`adapter` field this change makes optional. Both now read the store a
source is placed on (`boundAdapterId`), each with a pin.
- The boot build pass (main's first-build pass at boot), in 205f667.
- The reconcile's no-`listDocuments` check (main's scheduled reconcile),
in merge 635fb18.
- **Accepted overlaps (seat ruling)**:
- objectstack-ai#37963: one hunk in `knowledge-service.ts`. That PR absorbs the merge
after this lands.
- objectstack-ai#38015: the generated
`content/docs/references/ai/knowledge-source.mdx`. objectstack-ai#38015 has landed.
This head merges main and regenerates the page on the merged tree
(`gen:schema` + `gen:docs`).

File surface beyond the claim, declared:
`packages/runtime/src/domains/mcp-authoring.ts` and its test,
`packages/cli/src/utils/schema-migration-plugins.ts` and its test plus
`boot-preparation-parity.test.ts` (above), the `knowledgeSources`
describe in `packages/spec/src/stack.zod.ts`, `service-knowledge` plugin
options, `knowledge-build-actions.ts`, `knowledge-reap-guard.ts`,
`packages/verify/src/required-providers.ts`,
`packages/core/src/capability-providers.ts` (comments only).

Read first (by risk):
1. `packages/services/service-knowledge/src/knowledge-service.ts`:
`adapterIdFor` and `refuseUnplacedSource`, where the refusal and
placement rules live.
2. `packages/core/src/capability-composition.ts`:
`stackItemCapabilities` and the `knowledge` branch of
`resolveCapabilityArgument`.
3. `packages/spec/src/kernel/platform-capabilities.ts`: the `mountedBy`
row field, the public surface this adds.

Two-minute verification: `pnpm --filter @objectstack/verify exec vitest
run src/harness.required-providers.test.ts -t "an item, no adapter, no
token"` should print one passing case: a stack with a `knowledge_source`
that names no adapter and no `requires: ['knowledge']` boots
`KnowledgeServicePlugin` + `KnowledgeTursoPlugin`, places the source on
`turso` beside an app adapter, and finds the Chinese row for `住宿标准 报销`.

## Tests

Local, under the shared verify lock, at 633041b (the last commit,
af27454, adds only module-top imports to one cli test file; that file
was re-run, see below).

<details><summary>Suites and typecheck</summary>

- `@objectstack/spec` (whole package): 909 files / 28749 passed (+1
todo).
- `@objectstack/core` `capability-composition.test.ts`: 25/25.
- `@objectstack/service-knowledge`: 18 files / 563 tests.
- `@objectstack/verify` `harness.required-providers.test.ts`: 16/16.
- `@objectstack/cli` `boot-preparation-parity.test.ts` +
`schema-migration-plugins.test.ts`: 2 files / 93 tests, at 633041b
and again at af27454 (cli typecheck exit 0 at both).
- `@objectstack/runtime` `mcp-authoring.test.ts`: 73/73, at aba523a;
runtime is unchanged since.
- Typecheck exit 0: spec, core, service-knowledge, verify, cli, runtime.

</details>

<details><summary>Ablations (each restored; blob == HEAD, `git diff
HEAD` empty)</summary>

| Pin | Mutation | Result |
| --- | --- | --- |
| A1 | the deployment's mark in `adapterIdFor` | 2 failed |
| A2 | the registration refusal | 1 failed |
| A3 | the item tokens in `resolveServedCapabilities` | 1 failed |
| A4 | the `knowledge` capability argument | 1 failed |
| A6 | `adapter` optional, redone as `z.string().min(0)` (the first try
was a no-op) | 1 failed |
| A7b | `stackItemCapabilities`, core dist | verify case fails: the
knowledge service is not found |
| A8 | the mark argument, core dist | verify case fails: source refused,
then a TypeError |
| A9 | boot pass reads the named adapter | the boot pin fails |
| A10 | reconcile reads the named adapter | the reconcile pin fails |
| A11 | MCP door respells non-403 as `SERVICE_UNAVAILABLE` | the pin
fails: `SERVICE_UNAVAILABLE` where `VALIDATION_ERROR` was expected |
| A12 | the migrate boot passes no item tokens | the behaviour pin
fails: `KnowledgeServicePlugin` is not composed |

A5 left with item 4.

</details>

## Acceptance notes

- PostgreSQL (pgvector) acceptance is NOT MEASURED end to end, locally
or in CI.
- CI's `capability-mount.live-postgres.test.ts` names `adapter:
'pgvector'` and `requires: ['knowledge']`, so it exercises neither the
omitted adapter nor the item mount (review N2).
  - What pins the card's PostgreSQL line is two unit pins, composed:
- `resolveCapabilityArgument('knowledge', postgres)` answers `{
deploymentAdapter: 'pgvector' }`, the store `resolveCapabilityExtras`
mounts for the same database (core).
- A source with no adapter binds to the marked store
(service-knowledge).
  - Follow-up: objectstack-ai#38040 drops `adapter` and `requires` from the live case.
- Known gap, both boots alike: `os serve --artifact-fallback` (no
config, the stack synthesized from the artifact JSON) reads items from a
config that carries no `knowledgeSources`. The artifact result surfaces
`requires` but no item collection, so an artifact-only stack's sources
do not mount the service there. Follow-up: objectstack-ai#38039; not built here.
- Item 4 and its Acceptance line moved to objectstack-ai#37983 (seat ruling).

## Verification

<details><summary>Container run (os dev, scratch app; at fa2b538,
items 1-3 unchanged since)</summary>

The scratch app held one `knowledge_source`, with no `adapter` and no
`requires`. The embedder was a local bigram fake.

1. `os dev --fresh` booted `KnowledgeServicePlugin` and
`KnowledgeTursoPlugin`.
2. Three Chinese rows were POSTed (201 ×3).
3. `os knowledge rebuild kbx-kbx_policies` ended `done`: 3 rows read, 3
written.
4. `os knowledge status` showed `adapter turso`, `index: current`.
5. MCP `search_knowledge '住宿标准 报销'` ranked `差旅住宿标准` first (score 0.436).

</details>

<details><summary>Gates</summary>

- `dispatch-gates --commands` at 633041b derives 129 families.
- NOT MEASURED locally:
- `check:type-check-debt`: its closure build needs the shared lock (CI
ran `Type Check · debt ledger` green at aba523a).
- `check:skill-examples` and `check:dual-build-cjs-loads`: they exit 3
on prerequisites outside this diff (the client-react, studio and
scenarios dists are not built).
- Exit 0: every other family, the ones that read built output re-run
after the build. That includes `check:generated` ("All 14 generated
artifacts are up to date"), `check:api-surface`, `check:dts-closure`,
`check:i18n*`, `check:docs-transcript-drift` and `check:nul-bytes`.
- `check:test-source-alias` failed once, on the edited cli test file.
The test now pays its dynamic imports at module top, and the gate exits
0.
- overlap-check at af27454 exits 1 against objectstack-ai#37963 only (accepted).
Clean: origin/main, objectstack-ai#38038, objectstack-ai#38037, objectstack-ai#38033, objectstack-ai#38013, objectstack-ai#37982, objectstack-ai#37929.

</details>

---

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

https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…e — a save does not wait for the embedder, a failed sync is retried, a rolled-back write is never indexed (objectstack-ai#38043)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes objectstack-ai#37735
Fixes objectstack-ai#37110

Clause-②: yes (widening) — `KnowledgeServicePluginOptions` gains the
optional `recordSyncRetry`; `KnowledgeService` gains `routeRecordSyncs`,
`recordSyncQueued`, `enqueueRecordSync` and `processRecordSync`; the
package exports `KNOWLEDGE_RECORD_SYNC_QUEUE`,
`RECORD_SYNC_RETRY_DEFAULTS` and the `KnowledgeRecordSync*` types
Metadata-protocol: none

## 维护者速读
-
用户能看到什么变化:保存一条被知识库收录的记录时,不再卡在向量模型上等待,保存立刻返回,几秒后检索才查到新内容;向量模型短暂故障时,同步会自动重试,不再永久丢失。
- 为什么做:知识库检索的可靠性(替接手的旧卡一并解决),保存被向量模型拖慢、同步失败不重试、回滚的写入被收录进索引,这三个问题一次修掉。
-
出错会怎样:最坏是某条记录的检索结果暂时停在旧版本,直到下一次保存、检索发现过期或每日对账把它修好;保存本身不受影响,撤回这次改动即恢复原来的同步方式。
- 要你做什么:无。

## What changes

A record change of an indexed object no longer syncs its document inside
the write. Where the kernel composes a durable `queue` service
(`QueueServicePlugin` over a data engine) and a data engine is bound,
both triggers publish to the `knowledge-record-sync` queue:
- the realtime `knowledge-event-sync` subscription;
- the after-write hooks used on a kernel with no realtime service.

A worker, subscribed in `kernel:ready`, re-reads the row and writes or
removes the document. Everything else keeps the inline path and says so
once at boot at `warn`:
- the kernel's in-memory fallback queue;
- a queue with no `listFailed`;
- no data engine.

`enableEventSync: false` and `refresh.onRecordChange: false` are
unchanged: they publish nothing.

- **The message carries identifiers only:** `{ source, object, recordId,
reason }`, where the reason is `event` or `freshness`. It never carries
a field value. The test reads the stored `sys_job_queue` row.
- **How commit ordering works:** the message is published after the
commit, through ObjectQL's `runAfterOpenUnitsCommit`. It goes out once
the open unit commits (the write's own unit or a caller's
`engine.transaction()`) and is dropped on rollback. With no unit open it
goes out at once. I did not use the other approach (the queue row
joining the write's unit), and no engine change was needed.
- **Rows per save:** one queue row per source per save, with no
`idempotencyKey`. `DbQueueAdapter` suppresses a keyed publish while a
message is pending or running, and for 24 h after it completes. A key
per document would therefore drop a save made while that record's sync
runs, and every save of it for a day after. Each worker run re-reads the
row, so the last committed version wins. `IQueueService` and
`DbQueueAdapter` are unchanged.
- **Retry, then dead letter:** the worker throws on failure, including
when the source's adapter is not mounted. The queue retries on
`recordSyncRetry`: by default 8 attempts, 5 s doubling to a 2 min cap.
The message then becomes a `listFailed` dead letter that names the
source and record, logged once at `error`.
- **Outcomes that are not retried:** a source that is gone, a source no
longer indexing the object, and a malformed message all complete with no
write.
- **The freshness repair goes through the queue:** when a search finds a
document stale, `repairStale` now publishes a `freshness` message
instead of starting an un-awaited inline sync.
- **Who adopts whose seam:** objectstack-ai#37963 touches this freshness path. If this
PR lands first, objectstack-ai#37963 adopts this seam (the queued `freshness` message
in `repairStale`). If objectstack-ai#37963 lands first, this branch merges main and
adopts its seam.
- **Docs:** `content/docs/protocol/knowledge.mdx` gains "Through the
queue" and "Without a durable queue".
`content/docs/ai/knowledge-rag.mdx`, the README and a changeset are
updated too.

## Tests

`src/__tests__/record-sync-queue.test.ts` is new. It boots a real
`ObjectKernel` with `ObjectQLPlugin`, `SqlDriver` (a better-sqlite3
file), `QueueServicePlugin({ adapter: 'db' })` and
`KnowledgeServicePlugin`. Every queue-path case runs once per trigger
(realtime, and the hooks).

The queue-path cases cover:
- a save returns while the embedder is held;
- the queue row holds identifiers only;
- retry, then dead letter;
- nothing is processed inside a caller's `engine.transaction()`;
- a rolled-back insert leaves no document and no row;
- a rolled-back update leaves the committed row indexed;
- a burst of 3 saves gives 3 rows and the last version wins;
- a save after a completed sync is synced;
- a delete, including member and record-granularity searches before the
message is processed;
- a source that is gone.

Further cases:
- nothing is published before the write's own unit commits;
- an `afterInsert` hook that aborts the write's own unit publishes
nothing;
- messages published before a restart are processed after it;
- the freshness message;
- the fallback `warn` and inline sync, plus both switches;
- `destroy()` leaves the message pending.

**Re-land head 5d430ea** (after the merge-queue drop: objectstack-ai#38026 made
`source.adapter` optional, so `processRecordSync` now resolves through
main's `adapterFor(source)`; cause and fix in comment 7229116666). One
locked batch, lock `VERDICT command-exit 0`:
- `turbo build --filter='@objectstack/service-knowledge^...'`: 19 of 19
tasks; `pnpm --filter @objectstack/service-knowledge build`: CJS, ESM
and DTS build success (the build that failed in the queue);
- `pnpm --filter @objectstack/service-knowledge typecheck`:
`check:test-typecheck: OK`;
- `vitest run --maxWorkers=2`: 19 of 19 files, 605 of 605 tests,
including the new pin (a source with no `adapter` syncs through the
queue to the deployment's store, on both triggers);
- NOT MEASURED on this head: an ablation of the new pin (lock saturated
by dogfood holders).

Earlier readings, on head 43dc682 unless noted (all under
`os-verify-lock`):
- `pnpm --filter @objectstack/service-knowledge exec vitest run
--maxWorkers=2`: 19 of 19 files and 593 of 593 tests pass (on merge head
640b356; the one later commit changes only docs and the changeset);
- `pnpm --filter @objectstack/service-knowledge typecheck`:
`check:test-typecheck: OK`.

<details><summary>Ablations (mutated on disk, test file re-run, restored
with git checkout; tests run from source, so no rebuild)</summary>

- enqueue-not-sync (both triggers forced to the inline path): 24 failed.
- rollback-not-indexed (`runAfterOpenUnitsCommit` removed, publish at
once): 4 failed. They are the rolled-back insert (both triggers), the
own-unit test and the own-unit abort. The caller-transaction case stayed
green under this mutation, because on SQLite's single connection the
poller cannot read inside an open transaction. The rollback cases are
the pin for the deferral.
- burst-keeps-last (`idempotencyKey` = source:object:recordId): 9
failed, including the burst, after-completed and delete cases.
- no-field-value-in-message (the row's `title` added to the message on
both triggers): 2 failed (the identifiers-only case for each trigger).
- fallback-inline-warn: two mutations were run.
  - The boot `warn` dropped: 2 failed.
  - A degraded queue or one with no `listFailed` accepted: 2 failed.

</details>

## Acceptance notes

- `MemoryQueueAdapter` (`adapter: 'memory'`) carries no `degraded` label
and has no `listFailed`. It is refused through the `listFailed`
condition, so it takes the inline path with the boot warn.
- **Cross-node race:** in-process serialization (`chainAfter` per
document) orders two runs on one node. Two nodes processing two messages
for one record are not ordered against each other. Each run re-reads the
row, so the last run to finish writes what it read. A save committing
between one node's read and another's write can leave an older version
until the next save, a freshness hit or the reconcile.
- **Distributed realtime adapter:** the realtime trigger relies on the
in-process publish running inside the write (so
`runAfterOpenUnitsCommit` sees the open unit). A realtime adapter that
delivers out of process would publish with no unit open, that is at
once. That is still after the write returned, but not ordered against a
caller's transaction. No such adapter ships today.
- **A system-identity search at chunk granularity** re-reads nothing. It
can answer a deleted record's chunks until the delete's message is
processed. Member searches and `granularity: 'record'` searches do not;
the docs now say so.
- The standard runtime mounts `queue` on every preset except `minimal`.
Under `minimal` the sync takes the inline path with the warn.

## Verification

Two-minute check:

```bash
pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/record-sync-queue.test.ts
```

Expected result: 33 of 33 tests pass.

Read first (by risk):
1. `knowledge-service.ts`: `publishRecordSyncs` (the commit deferral)
and `processRecordSync` (what is retried and what completes).
2. `knowledge-service-plugin.ts`: `startRecordSyncQueue` (the queue
resolution, the fallback warn and the dead-letter line).
3. `knowledge-record-sync-queue.ts`: `recordSyncPublishOptions` (why
there is no idempotency key).

<details><summary>Local gate subset</summary>

`dispatch-gates --commands --repo objectstack-ai/objectstack` derived
119 families. The `--ran` reconciliation reads: 115 run, 3 NOT MEASURED,
1 unrun.

- **Passed:** 113 exit 0.
- **NOT MEASURED, prerequisite** (exit 3, this worktree has no full
build): `check:skill-examples`, `check:dual-build-cjs-loads`,
`check:published-readme-exports`.
- For `check:published-readme-exports`, I confirmed the one new README
import (`QueueServicePlugin` from `@objectstack/service-queue`) by hand
against `service-queue/dist/index.d.ts`.
- **Exit 1 from local build state, not from this diff:**
- `@objectstack/spec check:docs`: `packages/spec/json-schema` is older
than `src`. This branch touches nothing in spec.
- `check:dts-closure`: `packages/rest/dist` has no `.d.ts`. This branch
does not touch rest; the partial dist likely comes from a build I
stopped earlier.
- **Unrun, NOT MEASURED:** `check:type-check-debt`, because it builds
every package under the shared lock.
- **Re-run on 43dc682:** the 39 doc and changeset families, all exit
0.

CI measures the full set.

`overlap-check` on 5d430ea: `VERDICT clean exit 0` against main and
the open PRs, including objectstack-ai#37963, objectstack-ai#38013 and objectstack-ai#37982. Earlier, on
43dc682: `VERDICT clean exit 0` against main and 6 open PRs (objectstack-ai#38038,
objectstack-ai#38037, objectstack-ai#38032, objectstack-ai#38026, objectstack-ai#37982, objectstack-ai#37963).

</details>

---

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ipped vs run-time mount, package-scoped identity) (objectstack-ai#38053)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Part of objectstack-ai#37310

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:用 AI(技能文档或 MCP 搭建)写知识源的作者,现在看到的是新写法:知识源是一份元数据,用
`name`、逐个列出要索引的字段、可以不写存储;MCP
新建知识源暂不提供起始模板(模板里的占位对象和字段会被当成真实值存进去),等设置页表单从作者输入构建 `source` 后再加。
- 为什么做:知识库检索专题(按调用者权限过滤的知识检索)第三阶段的教学一行,替照着技能写知识源的 AI 解决"照文档写出来却被拒绝"的问题。
- 出错会怎样:最坏是技能里某句教法不准,AI 写出的知识源在保存时被明确拒绝并给出修法;不会悄悄索引错的字段;改动可直接撤回。
- 要你做什么:合并(技能文档是受治理面,由你亲手落地);本 PR
只完成卡片的一部分:发布校验的五条规则名要等对应的校验改动(objectstack-ai#37971)合并后再补,新建模板要等设置页表单,所以卡片保持打开。

## What changes

**`skills/objectstack-ai/SKILL.md`, § Knowledge Sources (RAG)**
(ADR-0161 K4, K5, K6 item 6; rows 3a and 3b as merged):

- A source is a `knowledge_source` item: shipped in a package
(`knowledgeSources`, `*.knowledge-source.ts` / `.yml`) or authored in
Studio or over MCP. `KnowledgeServicePlugin({ sources })` and
`registerSource` are a second door for the same schema, and a code
registration and an environment item of one name are one slot, the
second refused. A source's identity is its package and `name`:
`search_knowledge` lists a package's source as `NAMESPACE-NAME` (bare
for a source no package holds). A shipped item (a `knowledgeSources`
entry) mounts the knowledge service and its store with no `requires:
['knowledge']` (objectstack-ai#37306, PR objectstack-ai#38026); an app that ships no source and
authors its sources at run time needs `requires: ['knowledge']`, or its
items are never indexed (as main's `knowledge-rag.mdx` § Turning it on
says).
- The key table is the v1 keys of K4: `name`, `label` / `description`,
`adapter` (optional; omitted ⇒ the deployment's store, else the only one
registered, refused naming them when several and none is the
deployment's), `source.kind`, `source.object`, `source.content` (an
explicit non-empty list; why `'*'` is refused: embedding is egress, K5),
`source.metadataFields`, `source.where`, `source.split`,
`refresh.onRecordChange`, `aiExposed`. The old Hygiene column's advice
(meaningful text only, never ids or system fields; `where` keeps drafts
out) now lives in the `content` and `where` rows, and says `content`.
- Egress and cost (K4): the first build sends every listed field of
every matching record to the embedding provider; a run-time save needs
`manage_knowledge_sources` beside `manage_metadata` and passes save-time
admission.
- The retired keys by name, each with its fix, as the tombstones read:
`id` → `name`, `contentFields` → `content`, `embedding`, `vectorStore`,
`adapterConfig`, `refresh.cron`, and the `file` / `http` arms with their
four keys; `os migrate meta --from 18` for a stack, by hand for a
registration in code.
- The checked example drops `adapter: 'pgvector'` (the deployment's
store) and its comments; it is otherwise row 3a's block.
- `split`: `strategy` is required once `split` is written (`recursive`
only when `split` is omitted); the adapter-list aside is gone.
- The closing note: `topK` is a `search_knowledge` argument; rerank and
hybrid weighting are no source key, and no shipped store has a setting
for either (`knowledge-pgvector` and `knowledge-turso` fuse their legs
by RRF with a fixed `RRF_K = 60`, `pgvector-adapter.ts:124`,
`turso-adapter.ts:95`; no store plugin's options interface has a rerank,
weight or fusion key).
- The routing line in `skills/objectstack-mcp-build/SKILL.md` ("An agent
skill, tool or knowledge source | objectstack-ai") stays true: the
section name is unchanged, so it is not edited.

**Not in this PR, on purpose (amendments 7221575164 and 7224082428):**
the five `os validate` / publish rule ids of PR objectstack-ai#37971
(`knowledge-source-object-unknown`, `knowledge-source-field-unknown`,
`knowledge-source-object-not-searchable`,
`knowledge-source-system-object-not-ai-readable`,
`knowledge-source-field-never-indexed`). objectstack-ai#37971 is still open, so this
PR is `Part of objectstack-ai#37310`: that part follows on this branch after objectstack-ai#37971
lands (the keyword then returns to `Fixes`), or on a later PR if this
one lands first. The create seed is also left open: it waits for the
Studio form (objectstack-ai#37309, row 5).

**`skills/objectstack-ai/evals/skills-tools-knowledge.json`.** Case 3
(kb_article on PostgreSQL) and case 9 (policy_doc, `markdown` split) now
expect `name` and `content`, and forbid a written `contentFields:` key;
case 3 also forbids a written wildcard (`['*'],`, `['*'] }`),
`embedding:` and `vectorStore:`, and its `topK` token becomes `topK:`
(the key written) because the skill now names `topK` as a search
argument. Case 9 also requires `name:` and forbids an `id:` spelling;
case 13 forbids the double-quoted wildcard forms. New case 14 asks for
an app that ships no source and authors one at run time, and requires
the `requires: ['knowledge']` line (either quote style), with no
`contentFields:`. New case 13 asks for a source that indexes "every text
field" and expects an explicit list, the wildcard declined because
embedding is egress, and no written `contentFields:` or wildcard.

**`packages/spec/src/kernel/metadata-create-seeds.ts`: unchanged
(byte-identical to `main`).** A `knowledge_source` create seed was tried
and withdrawn at `4c965f4a5e` (comment 7229668414). Its object binding
and content list sit inside `source`, and the Studio create flow
(`buildCreateModeBody` / `seedPlaceholderKeys` in app-shell's
`createBody.ts`) clears placeholder identity at the top level only, so
it would have saved `example_object` / `example_field` into a new
source: the objectui#12810 defect. No schema-valid seed avoids this,
because `source.object` and a non-empty `content` (K5) are required and
nested. `knowledge_source` stays on `KNOWN_UNSEEDED`, whose comment now
gives the reason: a seed waits until the Studio form (objectstack-ai#37309, row 5)
builds `source` from the author's input. The card allows this ("or the
type stays on `KNOWN_UNSEEDED` with the reason").

**`packages/runtime/src/domains/mcp-authoring.test.ts`.** One case
beside the flow contract case, over the real protocol and the boot type
registry: `list_metadata_items` with `contract: true` for
`knowledge_source` serves no `createSeed`; `contractPath`
`/properties/source/properties/content` serves the content rule
(`minItems: 1`, `minLength: 1`, a pattern that refuses `*` and admits
`body`); the served schema carries no `id` or `contentFields` tombstone;
a hand-written source with one object and one field saves as a draft;
the same item with `content: ['*']`, with an `id`, or with
`contentFields` is refused `422 INVALID_METADATA`, the last two naming
their tombstone's prescription ("use `name`", "use `content`"); nothing
else is written.

**Platform catalog (review round, `6f2e756f58`).** The generator's Boot
cell (`packages/spec/scripts/lib/platform-catalog.ts`) reads ``on
`requires`, or a shipped `knowledgeSources` item`` for a provider that
declares `mountedBy`; `packages/spec/scripts/platform-catalog.test.ts`
pins that cell, with `record-context` as the control that still reads
``on `requires` ``.
`skills/objectstack-project/references/platform-catalog.md` is
regenerated.

**Token ratchet.** The standing ruling, verbatim and untranslated:
「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B). Paid down first,
in the same file: the wiring paragraph's package list, the old
`source.kind` Hygiene column (folded into two rows), the example's four
comments restating table rows and its `refresh: { onRecordChange: true
}` line restating the default, and the split passage's adapter aside.
The row moves 6609 → 6639, the measured remainder, pinned at the
measurement. Review round (`6f2e756f58`): after paying down the intro's
restating clause, its separate `search_knowledge` sentence, the "one
name is one source" clause and the longer closing note, the row moves
6639 → 6695 (+56, the measured remainder) under the same ruling.
Reproduction: `ceil(($(wc -c < skills/objectstack-ai/SKILL.md) - 27) /
4)` = ceil(26779 / 4) = 6695.

## Tests

**Review round at `6f2e756f58`** (merges `main` at `58be6770ab`; note
7230668192): unlocked, 35 commands, each exit 0, including
`check-skills-token-ratchet` (row 6695), `check:nul-bytes`,
`check-empty-changeset`, `check-adr-0087-registration`,
`check-changeset-no-major`, `check:issue-citations`,
`check:doc-authoring`, `check:skill-links`,
`check:skill-identifier-liveness`, `check:skill-frame-sync`,
`check:published-files`; `gen:skill-refs` exit 0. NOT MEASURED locally
(verify lock never acquired in six tries): `check:skill-docs`,
`check:skill-refs`, `check:yaml-examples`, the platform-catalog test,
`metadata-create-seeds.test.ts`, the MCP contract case, eval case 14. CI
on this head is the reading for them. overlap-check: `VERDICT overlap
exit 1`, the same objectstack-ai#36158-against-main conflict in the ratchet file;
`origin/main`, objectstack-ai#38032 and objectstack-ai#38013 merge cleanly.

The lock was saturated: about 70 minutes of queueing, two dogfood runs
ahead. One locked round ran at `3407f7fe6e`; the second round was not
reached. What was not measured locally is marked below, and CI runs it.

<details><summary>Locked round at 3407f7f (VERDICT command-exit 0,
held 365s)</summary>

- `pnpm turbo run build --filter='@objectstack/runtime^...'
--concurrency=2`: exit 0, `Tasks: 41 successful, 41 total`.
- `metadata-create-seeds.test.ts` (spec): the seed pin run here (`Tests
20 passed (20)`) belonged to the withdrawn seed; the file is back to
`main`'s, so CI `Test Core` is the reading. **Patch round at
`4c965f4a5e`:** the app-shell
`createBody.seedPlaceholders-12810.test.ts` (red at `19f3e118f2`, 2
failures, unedited), the spec create-seeds test and the rewritten MCP
case are NOT MEASURED locally (verify lock saturated); their inputs
equal `main`'s, so CI `Test UI` and `Test Core` on this head are the
evidence. Unlocked gates at `4c965f4a5e`, exit 0 each:
`check-skills-token-ratchet` (6639/6639), `check-empty-changeset`,
`check-adr-0087-registration`, `check-changeset-no-major`,
`check:nul-bytes`, `check:issue-citations`, `check:doc-authoring`. The
changeset no longer lists `@objectstack/spec`.
- `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2
src/domains/mcp-authoring.test.ts`: exit 1, `Tests 1 failed | 73 passed
(74)`. The failing assertion is the new case's tombstone half: it
expected the served schema to carry `/properties/id`, and the served
schema drops tombstones (see Acceptance notes). Its content-rule and
seed assertions, which run before it, passed. The tombstone half is
rewritten in `01cf7515c2` to assert absence plus the save refusal. **NOT
MEASURED locally after that rewrite** (the second locked round never
acquired); CI `Test Core` runs it.
- `pnpm --filter @objectstack/spec run check:yaml-examples`: exit 0, `19
tagged YAML example(s) across 1 file(s) validate`.
- `pnpm --filter @objectstack/spec run check:skill-docs`: exit 0, `Skill
docs in sync`.
- `pnpm --filter @objectstack/spec run check:skill-refs`: exit 0, `10
generated files in sync with packages/spec`. The generated skill
references needed no regeneration: the section rewrite changes no
reference input.
- `pnpm --filter @objectstack/spec typecheck`: exit 0.
- `pnpm --filter @objectstack/runtime typecheck`: exit 1. `tsc --noEmit`
is clean. `check:test-typecheck` names 3 files this diff does not touch
(`boolean-written-spelling-row-scope.test.ts`,
`meta-object-publish-column-changes.test.ts`,
`organization-ownership-boot-guard.turso-remote.kernel.test.ts`).
`mcp-authoring.test.ts` is not among them. They are read here as the
closure build's gaps (only `runtime^...` was built) and not as this
diff's; CI `TypeScript Type Check` decides.
- `pnpm --filter @objectstack/spec run check:skill-examples`: exit 3,
PREREQUISITE NOT MET (the `@objectstack/client-react` dist is outside
the built closure). **NOT MEASURED**; CI runs it.

</details>

<details><summary>Unlocked gates (35 derived families, each exit 0, at
3407f7f; the ratchet and nul-bytes re-run at 19f3e11)</summary>

- `node scripts/check-skills-token-ratchet.mjs`: exit 0,
`skills/objectstack-ai/SKILL.md is 6639 tokens (ceiling 6639; headroom
0)`; with `--self-test` exit 0.
- Exit 0 each: `check-adr-0087-registration` (both forms),
`check-changeset-no-major`, `check-closing-keyword-parity` (both),
`check-declaration-mirrors` (both), `check-empty-changeset` (both),
`check-issue-citations`, `check-self-test-wired` (both),
`docs-audit/check-affected-docs`, `docs-audit/check-drift-comment`, and
`pnpm check:` `agent-test-spelling`, `changeset-gate-self-tests`,
`closed-ceremony-text`, `corpus-claim-drift`,
`cross-package-test-inputs`, `doc-authoring`, `issue-citations`,
`keyed-text-bounds`, `nul-bytes`, `pm-skill-id-lint`, `published-files`,
`ratchet-remedy-authority`, `role-word`, `skill-compatibility`,
`skill-frame-sync`, `skill-identifier-liveness`, `skill-links`,
`test-source-alias`, `tier-file-adoption`.
- `dispatch-gates --ran`: `116 derived, 38 run, 0 NOT-MEASURED, 78
UNRUN`. That is a declared narrowing: the lock was saturated, and CI
runs the 78.
- Local-only: `check-skill-frame-freshness` exit 0. `check-dev-prereqs`
exit 1 ("69 of 110 workspace packages … not on disk"), which is the
closure-only build and not a finding.

</details>

<details><summary>Eval runner and the ablation (`skill-evals`,
claude-code-cli 2.1.332, oauth login, served claude-opus-5-5)</summary>

Cases 3, 9 and 13 of `objectstack-ai/skills-tools-knowledge`, both arms,
one repeat each:

| skill text | objectstack-ai#3 with-skill | objectstack-ai#9 with-skill | objectstack-ai#13 with-skill | no-skill
(all three) |
|:--|:--|:--|:--|:--|
| this PR | pass | pass | pass | fail |
| `main`'s `SKILL.md` (`8d34c4404f`, hash `88a20cb583`), new cases
(ablation) | fail: `contentFields:` written; `name:`, `content:` missing
| fail: `contentFields:` written; `content:` missing | fail:
`contentFields:`, `['*'],` and `id: 'faq` written; no egress reason |
fail |

The ablation restored `main`'s `SKILL.md` into the working tree only
(`git restore --source=8d34c4404f`, `git hash-object` = `88a20cb583`).
The run ran, and then `HEAD`'s file came back (`fc845724ac` both on disk
and at `HEAD`). An earlier run of case 13 on this text failed with-skill
only on the token `['*']`, which a correct answer quoted while
explaining the refusal. The forbidden token is now the written wildcard
(`['*'],` / `['*'] }`), and the table above is after that change.

</details>

## Acceptance notes

- The acceptance grep (`git grep -n -E "contentFields|'\*'|adapter:
'ragflow'" skills/objectstack-ai`) returns eight lines. In `SKILL.md`,
three: the `content` row ("`'*'` is refused") and two lines of the
retired-keys paragraph. In the eval file, five: the reference answers of
cases 3 and 13, which name both as retired, and the `must_not_contain`
lists of cases 3, 9 and 13, which forbid a written `contentFields:` and
a written wildcard (`['*'],`, `['*'] }`). The card itself asks the eval
to fail on `contentFields` or `'*'`, which puts the forbidden token on
the assertion line. The reviewer decides whether those lines count as
"naming a retired key as retired".
- `adapter: 'ragflow'` has no hit: objectstack-ai#37004 already removed it.
- The new MCP pin is an `it` inside the existing real-protocol
`describe` of `mcp-authoring.test.ts`, beside the flow contract case,
because that describe holds the real-protocol harness (`realProtocol`,
`STUDIO_BASE`). It is in the shared harness file, not a new file.
- **Premise correction (card item 3).** The card asks the served
contract to carry "the tombstones' prescriptions as the describes read".
It does not, by design: the served JSON Schema drops every
`retiredKey()` tombstone (`{ not: {} }`; see the note in
`packages/metadata-protocol/src/protocol-meta-type-schema.ts`: the
served schema publishes what an author MAY write). The prescription
reaches an MCP author through the save refusal instead. The pin asserts
both halves: the tombstone is absent from the served schema, and a save
that writes the retired key is refused naming its replacement.
- The save half of the MCP pin covers row 3a's parse. Row 4's checks
(objectstack-ai#37971) are not on main, so a hand-written draft is not yet judged by
them here. Today the save passes with no knowledge service mounted ("no
knowledge service judges nothing").
- overlap-check before the PR: `VERDICT overlap exit 1`. `origin/main`,
objectstack-ai#38032 and objectstack-ai#38013 merge cleanly. objectstack-ai#36158 (a draft last updated
2026-11-25) conflicts in `scripts/check-skills-token-ratchet.mjs`. That
conflict is objectstack-ai#36158's own against `origin/main`: `git merge-tree
origin/main` with objectstack-ai#36158's head conflicts in the same file, and every
conflict hunk is at line 798 or later, away from this branch's hunk near
line 453. Reported here, not resolved.

## Verification

Files to read first, by risk:
1. `skills/objectstack-ai/SKILL.md` § Knowledge Sources (RAG): the
`adapter` and `content` rows and the retired-keys paragraph.
2. `packages/spec/src/kernel/metadata-create-seeds.test.ts`: the
`KNOWN_UNSEEDED` reason for `knowledge_source` (no seed;
`metadata-create-seeds.ts` is byte-identical to `main`).
3. `packages/runtime/src/domains/mcp-authoring.test.ts`: the new
contract case.

Two-minute check: `node scripts/check-skills-token-ratchet.mjs`. Expect
`skills/objectstack-ai/SKILL.md is 6695 tokens (ceiling 6695; headroom
0)`.

Readings: `skills/objectstack-ai/SKILL.md` 464 → 469 lines, 26462 →
26806 bytes (6609 → 6695 priced tokens, in two moves). Every published
`SKILL.md` summed: 4936 → 4941 lines, 261366 → 261485 bytes (65342 →
65372 tokens). The eval file is 125 → 137 lines and 13611 → 15185 bytes;
eval fixtures are measured, not ratcheted.

---

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…behind a per-source recipe proof (objectstack-ai#37963)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Fixes objectstack-ai#37467

Clause-②: yes (narrowing)
Metadata-protocol: none
Skills-docs: none — no published skill teaches the knowledge field gate
or its refusals (`git grep` of `skills/objectstack-ai` for the gate, the
display field and `KNOWLEDGE_REBUILD_REQUIRED`: 0 hits)
Security-touching: yes

## 维护者速读

-
用户能看到什么变化:知识检索的权限过滤不再额外检查名为“标题”的旧字段;对象同时有“标题”字段和另一个显示字段的知识源,只有在索引确认按当前方式完整建成后才对非系统用户开放,而且每条命中都要与记录的当前内容核对,对不上的不返回。
- 为什么做:知识检索收口(知识库检索按调用者权限过滤)的遗留清理:旧索引兼容分支退役,改为按知识源确认索引、按命中核对内容。
-
出错会怎样:最坏是这类知识源在重建完成前检索不到内容(会明确报“需要重建”),或刚改过的个别记录暂时搜不到(后台自动补写);不会泄露无权字段,改动可直接撤回。
- 要你做什么:审阅这次安全相关的收紧,决定是否合并。

## What changes

- **The field gate's `title` arm is gone**
(`knowledge-source-admission.ts`, `servedFieldsOf`). The gate asks about
exactly what a document carries under the current recipe: each `content`
and `metadataFields` member and the display field
(`documentTitleField`), less the fields an index never carries.
- **Per-source proof at search time** (`KnowledgeService.unprovenIndex`,
from `planSearches`). `mayServeEarlierRuleTitle` names the sources where
the retired arm mattered: the object declares a field named `title` (or
its fields cannot be enumerated), the index may carry it, and the source
does not serve it. For a non-system caller such a source is searched
only when its adapter's `indexStatus` reports the fingerprint AND the
recipe hash `planIndex` computes now, and only where the builds that
record that hash purge. It is never proven for `refresh.onRecordChange:
false`, or on an adapter with no `indexStatus`, no `completeBuild` or no
`listDocuments`.
- **Per-hit check on a proven source**
(`KnowledgeService.dropUnverifiedHits`; the seat's ruling S1 = B). The
proof speaks for the index as its last complete build left it. So each
hit of a proven source is served only when (a) one system-context read
per source per search round, `where` AND `id` in the hits' record ids,
answers its record, (b) its `documentId` is the one the source derives
from that record, and (c) its stored `docHash` equals the one
`recordToDocument` computes from the row under the current object
definition. The hash covers the title. Every way the check cannot be
made drops the hit: the read throws or answers no list, the hit has no
`sourceRecordId` or no stored hash, the hash cannot be computed, or the
tenancy posture cannot be read. The read decides survival only. A
surviving hit is returned as the store answered it, and nothing the read
returned is put on it. A stale or missing record's own document is
repaired in the background through the existing `repairStale`, once per
document until a later search finds it current; a document under a
foreign id is dropped and not repaired. Under record granularity
`checkFreshness` then reads the same records again, so "one read" is the
new check's own cost.
- **Without the proof the source is refused, never served through the
old arm**: named in `refused` as `KNOWLEDGE_REBUILD_REQUIRED` / 409.
That code is already in `@objectstack/service-knowledge`'s error-code
ledger, which this PR does not change. A search where it was the only
source refuses whole. The caller and the operator are told what ends the
refusal: a complete rebuild, nothing (a configuration no build can
prove), or the next search (an unreadable status). A refused search
starts no build and writes nothing.
- **A source that needs the index proof is never searched without it.**
The adapter a source binds to is resolved once per search, in
`planSearches`: the proof is read from that instance, both search rounds
search that same instance, and a source whose adapter does not resolve
at the plan carries the coded refusal its resolution answered and is
refused, never searched. `searchRound` no longer looks an adapter up.
- **Every other source pays nothing**: no proof read and no per-hit read
when the object declares no `title`, its display field is `title`,
`title` is credential-class or `internal`, or the source serves `title`
itself.
- **Save door (ADR-0161 K4 guard two)**: the same `servedFieldsOf`
judges a save, so an author no longer needs to query a `title` field the
source never indexes. This is the widening half of the declaration; the
display field is still asked.
- Docs: `content/docs/protocol/knowledge.mdx` (the title rule, the
proof, the permanent cases, the per-hit check) and
`content/docs/ai/knowledge-rag.mdx` (the second cause of
`KNOWLEDGE_REBUILD_REQUIRED`).

## Measurements: the per-hit read

Method, enough to rebuild it (the script is not committed: it imports
the in-memory driver from its source by relative path, which is not a
dependency of this package):

- Engine and driver: `new ObjectQL()` from `@objectstack/objectql`,
`registerDriver(new InMemoryDriver(), true)` with `InMemoryDriver`
imported from `packages/drivers/driver-memory/src/index`, then `init()`.
One object `account` (text `name`, text `title`, textarea `body`)
registered with `registry.registerObject`.
- Rows: 2,000, inserted in the system context: `name` "Acme i", `title`
"T i", `body` "body text i " repeated 40 times.
- Source and service: object source `s` over `account`, `content:
['body']`; `new KnowledgeService({ dataEngine: engine })` with a stub
adapter registered as `memory`.
- Hits: for each size n in 5, 25 and 100, the first n rows read in the
system context; each hit's `documentId` is `s:ID`, its `sourceRecordId`
the row id, and its `docHash` `recordToDocument(source, source.source,
row, engine.getSchema('account')).docHash`. So every hit is current.
- Timing: call `dropUnverifiedHits(hits, new Set(['s']))` 20 times to
warm up, then 200 timed rounds per size with `performance.now()`; p50
and p95 from the sorted times. `engine.find` is wrapped to count
system-context calls (round trips) and the rows they return (rows read).
- Re-run: put the file in
`packages/services/service-knowledge/src/__tests__/`, run `pnpm --filter
@objectstack/service-knowledge exec vitest run --maxWorkers=1 FILE`,
delete it.
- Box: the shared container, beside sibling verify runs; load averages
(1, 5, 15 min) 8.07, 7.98, 7.60 at the run. Read the times as an upper
bound on CPU cost. A remote driver adds one database round trip per
proven source per round.

| hits checked | when | round trips per round | rows read per round |
p50 | p95 |
|---|---|---|---|---|---|
| 5 | small: one `topK` 5 page of hits | 1 | 5 | 1.5 ms | 2.5 ms |
| 25 | first round at `topK` 5 (`SEARCH_FIRST_ROUND_FACTOR` 5) | 1 | 25
| 3.3 ms | 7.6 ms |
| 100 | refill at `topK` 5 (`SEARCH_REFILL_FACTOR` 20) | 1 | 100 | 9.2
ms | 14.5 ms |

An earlier run of the same method at load about 7 read 1.6/5.1, 3.3/6.2
and 9.5/12.3 ms (p50/p95).

Rows read are bounded by the distinct record ids among the round's hits
of proven sources, projected to the fields assembly reads. Every hit was
served in every timed round, so the recomputed hash agrees with the
stored one end to end on the real engine.

## Tests


`packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts`:

- proven index: a caller who may not query `title` is served, and the
stored hit is returned unchanged;
- unproven, seven ways (no `indexStatus`, no `completeBuild`, no
`listDocuments`, no recipe hash, another recipe hash, another
fingerprint, a throwing `indexStatus`) plus `refresh.onRecordChange:
false`: refused `KNOWLEDGE_REBUILD_REQUIRED` / 409, never searched. The
caller message and the warn line promise a rebuild only where one ends
the refusal, and the system context is still served;
- per-hit check (new `describe`): CONTROL served with exactly one system
read; the read's fields never reach the caller; dropped for a stored
hash that is not the current one, a hit whose stored docHash differs
from the record's current build inputs, a document a complete build
kept, a foreign `documentId`, no hash, an empty hash, and a record the
read no longer answers; fails closed for a read that throws, one that
answers no list, an unreadable tenancy posture, a hash that cannot be
computed, and a hit with no `sourceRecordId`; a source with a `where`:
the system read asks for `{ $and: [where, { id: { $in } }] }` and a
record outside `where` is dropped; the refill round: a proven source
saturates the first round with stale hits, the refill runs, and its
stale hits are dropped while its current hit is served; a source
searched without the proof is not checked; two race pins for the rule
that a source that needs the index proof is never searched without it:
another adapter instance registered under the same id while the proof is
read is not searched, and an adapter that registers only after its
source was planned is not searched that search (the source is refused
`SERVICE_UNAVAILABLE` / 503);
- an unproven source beside a searchable one; sources where the arm
never mattered read nothing; rebuilt: refused (no `beginBuild`, `upsert`
or `completeBuild` call), then `rebuildSource` completes and the source
is served;
- reverse pins: on a proven index the display field, a `content` field
and a `metadataFields` field the caller may not query each still refuse
the source; on an unproven index a stored earlier-rule title never
reaches the caller;
- `mayServeEarlierRuleTitle` table; save door.

<details><summary>Readings at 3a69848</summary>

- `pnpm exec vitest run --maxWorkers=2` in
`packages/services/service-knowledge`: Test Files 18 passed (18), Tests
611 passed (611), after the merge of main and a rebuild of the
dependency closure under the verify lock.
- `pnpm typecheck` in the package (tsc plus `check:test-typecheck`):
exit 0, "0 file(s) / 0 error(s)".
- The admission file alone: 83 passed (83).

</details>

<details><summary>Ablations (one on-disk mutation each, file restored
after)</summary>

Per-hit check, each run against the admission file:

- hash not compared: red, the four stored-hash-differs cases (the refill
pin among them);
- `documentId` not checked: red, the foreign document;
- usable-hash filter and equality both admit a missing hash: red, no
hash and empty hash. The usable filter ablated alone stays green,
because the equality also refuses a missing hash, so this is a double
ablation by design;
- a record the read no longer answers passes: red, that case;
- a read error serves the hits: red; a non-list answer serves them: red;
- an unreadable posture proceeds: red;
- a hash that cannot be computed trusts the store: red;
- no `sourceRecordId`: the permission filter ablated alone leaves the
new pin green (the check holds it) and turns the existing filter pin
red; filter plus the check's record-id test ablated turns the new pin
red;
- the read's row put on the hit: red, CONTROL and the no-leak pin;
- every source checked: red, the unproven-source case and the hits
elsewhere that carry no hash;
- S4 (a), the `where` conjunct dropped (the system read's `where`
replaced by the id list alone): red, the `where` case;
- S4 (b), the refill round not checked (`served(...)` removed from the
`refilledKept` call site only): red, the refill case;
- the first-round call site not checked (`served(...)` removed from the
`kept` call site only): red, 13 cases;
- the check not wired (the body of `served` replaced by returning the
hits, which removes the check at both call sites, first round and
refill): red, 13 cases.
- resolve once undone (`searchRound` looks the adapter up again by the
source's binding, as before): red, both race pins.

Proof and refusal (earlier rounds, unchanged code): arm restored, proof
skipped, recipe hash not compared, fingerprint not compared, predicate
always true, withheld `title` ignored, served-field check removed,
`onRecordChange: false` proven, no `listDocuments` proven, no
`completeBuild` proven, a `never` refusal promising a rebuild, a refused
search starting a build: each red.

</details>

<details><summary>Gates at 3a69848</summary>

- `dispatch-gates --commands`: 101 families, run locally and reconciled
with `--ran`: 100 exit 0, 1 NOT MEASURED. `check:type-check-debt` exits
3: its coverage half reads OK (132/135 workspace packages type-checked,
0 in the debt ledger), but its re-measure closure build queue-timed-out
twice on the shared verify lock (540 s each). CI's `Type Check · debt
ledger` lane reads it. `✓ dispatch-gates --ran: 101 derived famil(ies)
accounted for — 100 run, 1 NOT-MEASURED`.
- `check-nul-bytes`: OK. `overlap-check`: `VERDICT clean exit 0` against
origin/main, objectstack-ai#38043, objectstack-ai#38038, objectstack-ai#38013 and objectstack-ai#37982.
- Dogfood battery (owed by the `!` title), at 3a69848, under the
verify lock: `pnpm exec turbo run build
--filter='@objectstack/dogfood^...' --concurrency=2 && pnpm --filter
@objectstack/dogfood test`, `VERDICT command-exit 0`, waited 293 s, held
2743 s; Test Files 490 passed, 3 skipped (493); Tests 4144 passed, 68
skipped (4212).

</details>

## Acceptance notes

- Card acceptance 1, per-source proof at search time: `unprovenIndex`
reads `indexStatus` against `planIndex`'s fingerprint and recipe hash on
every search that needs it, never cached. It adds no contract member and
no stored state.
- Card acceptance 2: the arm is removed for proven sources. Unproven
ones are refused and are rebuilt by the existing boot pass, reload,
reconcile or `os knowledge rebuild`, never served through the old arm.
On a proven source a hit the current recipe would not assemble from the
live record is not served either (seat ruling S1 = B).
- Card acceptance 3: no other arm changed; reverse pins above.
- Seat conditions for B: (1) each fail-closed case pinned and ablated,
as above. (2) The no-leak pin plus its ablation. (3) The `indexStatus`
proof is kept beside the per-hit check rather than dropped. (4)
Measurements above. (5) `KNOWLEDGE_REBUILD_REQUIRED` is kept with
messages that say what ends each refusal, and the ledger is unchanged.
(6) Withdrawn by the seat (it concerned a follow-up card). The ruling is
recorded on this PR (7224861986); the PR keeps `Clause-②: yes
(narrowing)` and `Security-touching: yes`, and lands the Tier H way
through the seat.
- The claim's `:178` is not the arm: `documentTitleField` answering
`title` for an object with no definition is the current assembly rule,
so the gate keeps asking about it.
- Narrowing, declared for the seat: for a non-system caller, a
qualifying source is refused until a complete build under the current
recipe has completed (for good under `refresh.onRecordChange: false` or
an adapter missing `indexStatus`, `completeBuild` or `listDocuments`).
On a proven source, a hit whose record changed after its document was
written is dropped until the document is rewritten, and an adapter whose
hits carry no `docHash` serves no hit from it (the built-in adapters
carry it). Under `buildAtBoot: false` only the reconcile, where it runs,
or `os knowledge rebuild SOURCE` ends the first.
- Merged with main after objectstack-ai#37306 landed (f10feed). The one
`planSearches` conflict keeps both intents: the adapter is the one the
source binds to (main's optional-adapter placement) and the index-proof
requirement stays on the admitted entry. Review point S5 is on top of it
(3a69848): a source that needs the index proof is never searched
without it. For every source, an adapter that registers mid-search is
used from the next search on.
- Deviation: with the shared verify lock held by sibling batteries
through repeated 540 s queue-timeouts (five runs queued ahead at the
last try), the package suite, typecheck, single-file runs, ablations and
the measurement ran unlocked at `--maxWorkers=2`. The dogfood battery
ran under the lock.

## Verification

Read first: `knowledge-service.ts` `dropUnverifiedHits` (the per-hit
check and its fail-closed exits), then `planSearches`, `searchRound` and
`unprovenIndex` (the adapter resolved once, the refusal and the
comparison), then `knowledge-source-admission.ts`
`mayServeEarlierRuleTitle` (which sources pay either read).

Two minutes: `pnpm --filter @objectstack/service-knowledge exec vitest
run --maxWorkers=2 src/__tests__/knowledge-source-admission.test.ts`
shows 83 passed, including the `per-hit check` block.

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

https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…r the running deployment does not mount (objectstack-ai#38060)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Fixes objectstack-ai#37961

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: follow-up objectstack-ai#38158 — `skills/objectstack-ai/SKILL.md` §
Knowledge Sources (its `adapter` row, added on `main` by objectstack-ai#38053) does
not yet name this PR's save refusal of an unmounted adapter; objectstack-ai#38158
teaches it there. `content/docs/ai/knowledge-rag.mdx` and
`content/docs/protocol/knowledge.mdx` name the refusal here

## 维护者速读

- 用户能看到什么变化:在 Studio、通过接口或用 AI(MCP)保存知识源时,如果写了本部署没装的存储(例如已退役的 ragflow
或拼错),保存会当场被拒,错误里写明知识源、写的存储名和本部署已装的存储;不写存储、或写已装的存储,照常保存。
- 为什么做:知识库检索专题(按调用者权限过滤的知识检索)的收尾一项,替写知识源的作者和 AI 解决“写错存储要到启动日志或检索报错时才发现”。
-
出错会怎样:最坏是某个本该能保存的知识源被拒;改动只在保存这一处,可直接撤回。包安装、代码注册和离线校验不经过这一检查,仍由启动日志和检索报错兜底。
- 要你做什么:无(这是收窄,按惯例走契约审核)。

## What changes

- **The check**
(`packages/services/service-knowledge/src/knowledge-service.ts`,
`admitAuthoredSource`): a `knowledge_source` item whose `adapter` is a
string naming no adapter the running deployment has registered is
refused `400 VALIDATION_ERROR`. The message names the source, the
adapter and the mounted adapters, as a rule and its remedy: "it names
adapter 'ragflow', which this deployment does not mount (mounted:
memory), and a source's `adapter` must name a mounted store. Name one of
'memory' as its `adapter`, or leave `adapter` out, and the deployment's
store holds it, or mount the 'ragflow' store and save it again." Leaving
`adapter` out is offered only where an omitted adapter would be placed
(the deployment's store is mounted, or one adapter is). The hunk sits
beside the existing unplaced-source check (several adapters, none the
deployment's), the other "which store holds it" refusal, and reads the
registry at request time, after every store's `start()`: nothing is
recorded.
- **Not refused:** an omitted `adapter` (legal since the
deployment's-store change; it is placed by `adapterIdFor`); a named
adapter that is mounted.
- **Doors reached:** every caller of `authoredKnowledgeSourceRefusal`
(`@objectstack/metadata-core`), unchanged: `PUT
/meta/knowledge_source/:name` on both transports, the MCP
`save_metadata_draft` tool, and the package duplicate
(`refuseDuplicatedKnowledgeSources`), which judges each source it copies
for the caller and now refuses a copy whose source names an unmounted
adapter, as it already refused an unplaced one.
- **Not covered by this door, said in the docs and the changeset:** a
package install and any other engine write (`isSystem`, skipped by
`authoredKnowledgeSourceRefusal` before the knowledge service is asked);
a source registered in code (`registerSource`, `KnowledgeServicePlugin({
sources })`), which registers at `init()` before its store's `start()`,
so "not mounted yet" is no verdict there; `objectstack validate`, which
runs with no deployment. For those, `reportUnmountedAdapters` at boot
(`error`) and the `503 SERVICE_UNAVAILABLE` at index and search stay the
signal.
- **How the refusals at this door order:** with no knowledge service
mounted, the door never reaches `admitAuthoredSource`, so the no-service
refusal that objectstack-ai#38013 adds (`503`) comes before this one (`400`). Inside
`admitAuthoredSource`: no identity (`403`), then the unplaced source
(`400`), then this check (`400`), then no data engine (`503`), then the
exposure and field gates (`403`/`503`). The code is the existing
`VALIDATION_ERROR`, the sibling unplaced refusal's code: no new error
code.
- **Docs:** `content/docs/ai/knowledge-rag.mdx` (the not-mounted bullet)
and `content/docs/protocol/knowledge.mdx` (the "Named" binding rule and
guard two, source admission at save).
- **ADR-0087:** semantic entry
`knowledge-source-unmounted-adapter-refused-at-save`
(`packages/spec/src/migrations/entries/semantic/`), registered by the
changeset.

## Tests

-
`packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts`,
in the `admitAuthoredSource` describe, through the real
`KnowledgeService`: a retired (`ragflow`), mistyped (`memroy`) and empty
adapter are each refused `VALIDATION_ERROR`/`400` naming the source, the
adapter and `mounted: memory`; the refusal comes before the field gate;
the system context is admitted; with none mounted the message says
`mounted: none`, with two it names both; CONTROL: a mounted adapter, and
an omitted one (deployment's store, two registered), are admitted. One
existing fixture (`new KnowledgeService({})` in the fail-closed case)
now registers the `memory` adapter its item names, so it still reaches
the no-engine `503` it pins.
-
`packages/qa/dogfood/test/knowledge-source-unmounted-adapter-save.dogfood.test.ts`,
a real booted showcase (knowledge service plus `memory`) with the MCP
server: `PUT /meta/knowledge_source` refuses `ragflow` and `memroy` `400
VALIDATION_ERROR`, nothing stored (GET `404`, not registered); MCP
`save_metadata_draft` with a real OAuth token (`metadata:write
actions:execute`) refuses `ragflow` the same way, and no draft is
stored; CONTROL: a named `memory` source and an omitted-adapter source
save at both doors.

<details><summary>Local runs on head 0b2a3bc (all under
os-verify-lock)</summary>

- Dependency closure `pnpm exec turbo run build
--filter='@objectstack/dogfood^...' --concurrency=2`: exit 0 (covers
`service-knowledge^...`).
- `service-knowledge`: vitest Test Files 18 passed (18), Tests 573
passed (573); `typecheck` (tsc plus `check:test-typecheck`) exit 0.
- `metadata-core`: Test Files 29 passed (29), Tests 1111 passed (1111);
typecheck exit 0.
- Door tests that pin save refusals: runtime `mcp-authoring`,
`meta-save-capability-gate`, `packages-knowledge-source-gate`,
`meta-type-write-capability-parity`: 4 files, 195 passed; rest
`meta-write-door-capability-enumeration`, `meta-type-write-capability`:
2 files, 135 passed.
- `spec` `src/migrations`: 5 files, 206 passed. New dogfood file: 4
passed (4).
- **Dogfood battery** (`pnpm --filter @objectstack/dogfood test`, no
shard, no path): `VERDICT command-exit 0`, held the lock 2405 s; Test
Files 491 passed, 3 skipped (494); Tests 4148 passed, 68 skipped (4216).

</details>

<details><summary>Ablation: the check removed, both layers red;
restored, green</summary>

Through `scripts/ablation-replace.mjs` (anchor hit, restore trap) on the
condition `if (typeof authoredAdapter === 'string' && ...)`, prefixed
with an always-false string comparison carrying the marker
`ABLATED_UNMOUNTED_CHECK`.

- Unit leg (vitest reads `src`; marker count 1 on disk): 2 failed, 43
passed (45). Red: the two refusal cases (`ragflow: expected { admitted:
true } to match object { admitted: false, ... }`). Green: the CONTROL.
- Door leg: `service-knowledge` rebuilt, `ablation-dist-preflight` found
the marker in `dist/` (exit 0); dogfood file 2 failed, 2 passed (4).
Red: the PUT leg (`Saved knowledge_source 'ks_retired_store' ...
expected 200 to be 400`) and the MCP leg. Green: the booted-store check
and the CONTROL.
- A first attempt spelled the mutation as a literal comparison, which
the DTS build refused (TS2367), so that door leg ran with no `dist/` and
is discarded; the unit leg of that attempt is the one above.
- Restore: `git diff HEAD` empty, `git status --porcelain` empty,
rebuilt, `ablation-dist-preflight --absent` exit 0, unit file 45 passed,
dogfood file 4 passed.

</details>

## Acceptance notes

- The claim's file surface names `knowledge-source-admission.ts` for
`admitAuthoredSource`; on 8d34c44 that function lives in
`knowledge-service.ts`, beside the other adapter refusals. The admission
module (`knowledge-source-admission.ts`, the gates) is untouched, so
objectstack-ai#38038's gate-2 rewording and objectstack-ai#37963 do not meet this hunk;
overlap-check reads clean against both.
- `metadata-core` `knowledge-source-save-admission.ts` needed no
threading: the verdict carries `status`/`code`/`message`, which the
doors already pass through.
- A source already stored with an unmounted adapter is not touched; it
keeps answering `503` until it is saved again.

## Verification

Read first: (1) `knowledge-service.ts` the new hunk after the
unplaced-source check in `admitAuthoredSource`, and
`unmountedAdapterSaveText` (remedy wording); (2) the dogfood file's MCP
leg (token, `save_metadata_draft`); (3) the semantic migration entry.

Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run --maxWorkers=2
src/__tests__/knowledge-source-admission.test.ts` shows 45 passed, three
of them the new unmounted-adapter cases.

<details><summary>Gates</summary>

- `node scripts/pm/dispatch-gates.mjs --commands --repo
objectstack-ai/objectstack`: 118 families, all run locally on
0b2a3bc, exit codes captured before any pipe. `--ran`: "118 derived
famil(ies) accounted for — 115 run, 3 NOT-MEASURED (3 DERIVED from a
recorded exit 3)".
- NOT MEASURED: `check:skill-examples`, reason: it reads
`packages/client-react/dist`, outside the dogfood closure built here
(PREREQUISITE NOT MET).
- NOT MEASURED: `check:dual-build-cjs-loads`, reason: it needs a
whole-tree `dist/` build (PREREQUISITE NOT MET).
- NOT MEASURED: `check:type-check-debt`, reason: its re-measure build
waited on the shared verify lock while this branch's battery held it,
and exited 3.
- Local-only: `check:skill-frame-freshness` exit 0; `check:dev-prereqs`
exit 1, "38 of 110 workspace packages declare an entry point under dist/
that is not on disk" (only the dogfood closure is built in this
worktree; a local reading, not a finding).
- `check:adr-0087-registration`: "1 declared-breaking changeset(s), each
carrying an ADR-0087 disposition ... registered
knowledge-source-unmounted-adapter-refused-at-save (new here)".
- `overlap-check` before the PR: "VERDICT clean exit 0" against
origin/main 27ee984 and six open PR heads (objectstack-ai#38056, objectstack-ai#38050, objectstack-ai#38038,
objectstack-ai#38013, objectstack-ai#37982, objectstack-ai#37963).
- CI check-runs: not yet reported at the time of writing; the seat reads
them.

</details>

---

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…rds they may read (objectstack-ai#38160)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes objectstack-ai#37957
Clause-②: no
Metadata-protocol: none

## 维护者速读
-
用户能看到什么变化:只能看到少量记录的用户(例如一千条里只能看二十条)在知识库搜索里,能搜到自己有权看的答案了;以前这些答案排名靠后时会一条都搜不到。系统身份和能看到很多记录的用户行为不变。
- 为什么做:属于“云上知识库(Turso)”这一主线,替权限范围窄的普通用户解决“明明有答案却搜不到”。
-
出错会怎样:最坏是这类用户仍然搜不到(回到以前的样子),不会多看到无权看的内容,因为每条结果仍逐条按权限复核;改动可以直接撤回,旧索引无需迁移。
- 要你做什么:无。

## What changes

**Problem.** A knowledge search re-checks every hit as the caller after
ranking and refills once at `topK × 20`. A caller who may read 20 of
1,000 indexed records gets none of them when they all rank below that
cap.

**`@objectstack/service-knowledge`.** Before the first round, for a
caller who is not the system identity (and has an engine to re-check
with), each object source is narrowed to the records that caller may
read (`sourcesNarrowedToVisible`, `readVisibleIds`):

- One read per object and `where`, as the caller: `find(object, { where:
source.where, fields: ['id'], limit: 501, context })`.
- 500 or fewer ids: the source is handed one `record` scope term holding
them, so the adapter ranks only those rows.
- The adapters OR their scope terms, so the visible ids are INTERSECTED
with a caller-given record scope (`narrowToVisible`, a pure function in
`knowledge-search-scope.ts`), never appended: a one-record scope stays
one record.
- Unchanged path (searched exactly as before): more than 500 ids; a
caller scope holding a parent (`metadata`) term, the card's first
option, since a union of terms cannot say "this parent AND these
records" without an adapter contract change; a narrowing that names no
record (so a caller who reads nothing is answered as before, no hit or
the source's refusal, never a new kind of empty); a read that fails
(logged at `warn`); the system identity.
- The rounds, the refill, the per-hit permission re-check and the
organization filter are untouched. The removed-hit count is still never
returned.

**`@objectstack/knowledge-turso`.** `passageTableDdl` adds `CREATE INDEX
TABLE_record ON TABLE (source_record_id)`. New generations carry it; an
existing generation gets it from its next build. No migration.

**`@objectstack/knowledge-pgvector`.** Its DDL lacked the index too:
`vectorTableDdl` adds `CREATE INDEX IF NOT EXISTS "TABLE_record" ON
TABLE (source_id, generation, source_record_id)` (the table is shared by
every source and generation, hence the prefix).

**Conformance harness** (`@objectstack/service-knowledge/testing`): its
engine double answers the caller's visible-id read under the case's
`wall`, and one new case runs the narrowed search through each real
adapter.

Docs: `content/docs/protocol/knowledge.mdx` (the re-check paragraph,
both stores' table lines). Changeset: patch on the three packages.

### Read first
1. `packages/services/service-knowledge/src/knowledge-search-scope.ts`,
`narrowToVisible`: the intersection. A union here would widen a caller's
own scope; ablation A1 below.
2. `packages/services/service-knowledge/src/knowledge-service.ts`,
`sourcesNarrowedToVisible` / `readVisibleIds`: the read as the caller,
the 500 bound, the fall-backs.
3. `packages/plugins/knowledge-pgvector/src/sql.ts`: the new index on an
existing shared table (see Acceptance notes).

## Tests

All on head `27b7a296bb` (after merging `origin/main` 9726bd8), under
`scripts/pm/os-verify-lock.sh`.

<details><summary>Package suites and typechecks: all exit 0</summary>

```
build closure (service-knowledge, knowledge-turso, knowledge-memory, knowledge-pgvector ^...) B=0
@objectstack/service-knowledge   Test Files 19 passed (19)   Tests 677 passed (677)   typecheck 0
@objectstack/knowledge-turso     Test Files 4 passed (4)     Tests 235 passed (235)   typecheck 0
@objectstack/knowledge-memory    Test Files 3 passed (3)     Tests 66 passed (66)     typecheck 0
@objectstack/knowledge-pgvector  Test Files 3 passed | 7 skipped (10)  Tests 14 passed | 90 skipped (104)  typecheck 0
```
The pgvector live-Postgres files skip here (no Postgres server in this
container): the pgvector index and the conformance case through pgvector
are NOT MEASURED locally.
</details>

New pins:
- `knowledge-service.test.ts`, describe "a narrow caller's search ranks
only the records they may read" (13 cases): 20 of 1,000 readable, all
ranked 900th to 919th, answered best first in one round; more than 500
readable takes the path before (control: none reached); exactly 500
narrows, 501 does not; a one-record scope stays one record; mixed
readable/unreadable scope ids keep only the readable, in the caller's
order; no readable id in scope, and no readable record at all, search as
before; a parent term reads nothing and hands the caller's terms
unchanged; the system identity reads nothing and is handed no scope; the
organization filter is handed beside the narrowed term, equal to the
unnarrowed path's; the source's `where` is the read's `where`, one read
for two sources sharing it; a failed read warns and searches as before;
a record the read answered but the re-check refuses is not served.
- `knowledge-search-scope.test.ts`: `narrowToVisible` (7 cases).
- Conformance (`testing.ts`, through memory and turso): a caller who may
read only the two clauses every other outranks is answered from them
past the refill cap; their one-record scope stays one record.
- `knowledge-turso` acceptance: `EXPLAIN QUERY PLAN` of the adapter's
own scoped search SQL (captured from the client) shows `USING INDEX
TABLE_record` and no scan of the passage table.

Fixture updates (same assertions, now naming the extra caller read):
three pins that counted the caller's reads (`drops hits the user cannot
read`, `the permission re-read stays one query as the caller`, `passes
the caller's context to the row-level re-check`) now see the visible-id
read before the re-check.

<details><summary>Ablations: each mutation reds its pins, then restored
(git status clean after)</summary>

```
A1 intersection -> union (visible ids appended as one more term)   8 failed | 205 passed  exit=1
   incl. "a caller's one-record scope stays one record", "a one-record scope stays one record however many ids are visible",
   "20 records, two of them in scope, topK 5", "a caller scope naming readable and unreadable records"
A2 no narrowing at all                                              7 failed  exit=1
   incl. "a caller who may read 20 of 1,000 records is answered from their 20"
A3 the 500 bound dropped                                            2 failed  exit=1
   "control: ... more than 500 records takes the path before", "exactly 500 ... still narrow; 501 do not"
A4 the system identity narrowed too                                 1 failed  exit=1
   "the system identity: no read, no scope handed, one round of topK"
A5 the organization filter dropped when narrowing                   1 failed  exit=1
   "the organization filter is handed as before beside the narrowed term"
A6 turso source_record_id index removed from passageTableDdl        2 failed (memory and file: URL)  exit=1
```
</details>

## Measurements (amendment)

Scratch script, not committed: 100,000 passages (one per record)
bulk-loaded into one turso generation table (`file:` database, 64-wide
fake embedder), the adapter's own search SQL captured and planned.
Shared box, so read the ratios.

<details><summary>EXPLAIN QUERY PLAN, 20 visible ids of 100k
passages</summary>

```
SEARCH knowledge_bench_g1 USING INDEX knowledge_bench_g1_record (source_record_id=?)          vector leg
SEARCH knowledge_bench_g1 USING INDEX knowledge_bench_g1_record (source_record_id=?)          keyword leg candidates
SEARCH knowledge_bench_g1 USING COVERING INDEX knowledge_bench_g1_record (source_record_id=?) count(*) in scope
```
</details>

<details><summary>Adapter search latency, median of 7 (index dropped:
median of 3)</summary>

```
query                       ids    with index   index dropped
vector-led ("zebra quokka")  20      1.1 ms       38.2 ms
vector-led                  500      3.3 ms       48.5 ms
vector-led                 2000      8.5 ms       55.2 ms
vector-led, unscoped topK 100        59.0 ms
keyword-heavy (3 words each in ~30% of passages)
                             20    232.4 ms      346.3 ms
                            500    240.9 ms      376.4 ms
                           2000    262.9 ms      388.8 ms
keyword-heavy, unscoped topK 25     521.6 ms;  topK 100: 533.0 ms
```
</details>

The 500 cap is not raised. 500 to 2,000 ids costs about 2.6x on the
vector leg (3.3 to 8.5 ms) and about 1.1x on a keyword-heavy query.

## Acceptance notes

- This PR raises recall. With the index the narrowed vector leg reads
only the named records' passages. The keyword leg's candidate set is
still the FTS matches of each term ANDed with the scope (the plan above:
`MULTI-INDEX OR` over the FTS matches), so a query of very common words
still costs FTS-match time. Measured, not filed: no contract or recall
defect.
- pgvector: `CREATE INDEX IF NOT EXISTS` runs on an existing table at
the first write or build per process after the upgrade. It is not
`CONCURRENTLY`, so writes to that table wait while it builds. Same shape
as the existing keyword index's creation.
- `find` does not promise `min(limit, remaining)` rows (an `afterFind`
hook may drop rows from a page). If a hook drops rows from the 501-row
page, a caller with more than 500 rows could be read as having 500 or
fewer, and their search narrowed to a subset. Recall only, never
exposure: every hit is still re-checked. The platform's row security is
pushed into the query, not into `afterFind`.
- An index name `TABLE_record` shares SQLite's table/index namespace
with a legacy table name `knowledge_SOURCE` only for a source id ending
in `_gN_record`. The existing `TABLE_document` index has the same
property.
- Overlap: `node scripts/pm/overlap-check.mjs` on the branch before the
merge: `VERDICT clean exit 0` against `origin/main` and objectstack-ai#38060, objectstack-ai#38056,
objectstack-ai#38050, objectstack-ai#38038, objectstack-ai#38013. objectstack-ai#38056 (F6) shares `sql.ts` and the turso
acceptance file and merges cleanly. Whichever lands second merges main.

## Verification

Two minutes: `pnpm --filter @objectstack/service-knowledge exec vitest
run --maxWorkers=2 src/__tests__/knowledge-service.test.ts -t "narrow
caller"`. Expect 13 passed. Then `pnpm --filter
@objectstack/knowledge-turso exec vitest run --maxWorkers=2
src/__tests__/acceptance.test.ts -t "source_record_id index"`. Expect 2
passed (`:memory:` and `file:`).

Local gate families (`dispatch-gates --commands`) NOT MEASURED: the run
was denied by the session's action classifier. CI runs them all.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
… of one organization (objectstack-ai#38056)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Fixes objectstack-ai#37975

Clause-②: yes (widening)
Metadata-protocol: none
Skills-docs: none — the diff adds two options of one plugin and changes
no metadata an author writes; no published skill names the libSQL
store's search.

## 维护者速读
- 用户能看到什么变化:托管版上单个知识源超过两万段、且只属一个组织时,检索先用一位压缩索引挑候选再精排,20 万段时向量检索从约 1 秒降到约
0.08 秒;只看得到约两成以下记录的检索仍逐条扫描,速度不变。
- 为什么做:知识中台要支撑工单、拜访记录、邮件这类几十万段的知识源;您已选定方案 A(采用新索引,默认开启),替大知识量的托管客户解决检索慢。
- 出错会怎样:最坏是结果与逐条扫描略有出入(实测召回率 0.99
以上);数据库不支持这种索引时构建照常完成、退回逐条扫描并在健康检查里写明;多个组织的数据从不走这条路;阈值设为无穷大即可整体关掉。
- 要你做的:无。

## What changes

A libSQL store read every vector in scope on every search: at 1,536
dimensions, about 1.2 GB at 200,000 passages. Now, when a complete build
finishes on a generation that holds `vectorIndexThreshold` passages or
more (default 20,000), and all of them belong to one organization, the
store gives that generation an approximate index. It is on by default,
per the maintainer's ruling A on objectstack-ai#37975 (「A 采用新索引,默认开启」, recorded in
comment 7231124445).

- **The index.** It is a side table, `knowledge_SOURCE_gN-vec`. It holds
each passage's vector quantized to one bit per dimension (`F1BIT_BLOB`),
a 32nd the size of the float32 column. Three triggers keep it in step
with every write.
- **The vector leg.** The leg takes the `topK x vectorIndexOverfetch`
passages (default 40 per hit) nearest the query's one-bit vector. It
runs the unchanged organization, record-scope and metadata `WHERE` over
them (the `pool`), then ranks the pool by the stored float32 vector.
- **How it feeds RRF.** Its ranks feed the reciprocal rank fusion with
the keyword leg exactly as the exact scan's ranks did. The keyword leg
and the merge are unchanged.
- **The scoped-recall floor.** The search runs again as the exact scan
in either of two cases:
  - fewer than 8 x `topK` of the candidates are in scope;
  - the leg is short of `topK` hits.

The candidates are ranked before the filter, so a thin pool would
re-rank the wrong neighbours. The second case exists because the service
reads a short answer as "the source holds no more". The real-store rows
are under Acceptance notes.
- **Never over two organizations.** The candidates are ranked before the
filter.
- A generation that holds passages of more than one organization gets no
index. Passages with no organization count as one more.
- Every search also reads the `-org` index (`min`, `max`, and `EXISTS
... IS NULL`: three seeks). It takes the exact scan as soon as a second
organization's passage is written.
- This is decided per passage table: a generation table holds one
source, and a cloud store is one organization per database (ADR-0114).
- **When the index is built.** At the end of `completeBuild`, before the
switch transaction, and never on a search.
- It is filled 2,048 passages per transaction on the per-client queue,
so a search waits behind at most one batch.
  - At 200,000 passages this took 2.6 to 3 s and 54 MB.
- A source that grows past the threshold between builds keeps the exact
scan until its next complete build: `os knowledge rebuild`, a
fingerprint change, the boot build or the daily reconcile.
- **A database that refuses the index.** The source keeps the exact
scan, and the build completes.
- A probe of `vector1bit` runs before any DDL. It has to come first:
SQLite creates a trigger that names an unknown function without
complaint, and that trigger would then fail every passage write.
  - A refused DDL transaction rolls back.
- A refused copy batch ends the copy. The side table's count then
differs from the passage table's, so it is never searched, and the next
complete build resumes the copy.
- **The refusal is signalled through the existing `healthCheck()`.** The
service's health endpoint reads it, and the plugin logs it at boot.
  - A database without one-bit vectors is named from boot.
- Each source whose build had its index refused is named with the
reason, until a later build makes the index or the source is dropped.
- So the `healthCheck()` line is how an operator tells whether a hosted
database refused a source's index: a source it names runs the exact scan
for that reason. A source it does not name may still run the exact scan
for another reason above: two organizations, under the threshold at its
last complete build, or a narrow scope.
- `ok` stays `true`, and a store whose index works keeps the message
`libSQL vectors ready` unchanged.
- The record is kept by the process that ran the build, until it
restarts.
- **What a search reads to choose the index.**
  - The index memory is now keyed per generation instance.
- A process reads the catalog for an instance's index once (two reads)
and remembers the answer. A build remembers what it found in its own
process, so a source under the threshold costs no catalog read there,
and two reads once in any other process.
- With `vectorIndexThreshold: Infinity`, a search never reads the
catalog for an index; an index made earlier under a finite threshold
stays in place and is not searched.
- A failed approximate statement forgets that memory and is answered by
the exact scan.
- The one cost left: an index that another process completes inside the
active generation is used here after this process's next complete build
of the source, or a restart. A search that takes the index also reads
the organization index (three seeks).
- **The candidate count is bound only where it is read**, by the
approximate statement. The exact statement binds exactly the values it
reads, so a query without a keyword term leaves no surplus value.
- **Lifecycle and safety.**
- A generation swap and `dropSource` drop the side table, the `-org`
index and the triggers together with the generation's passage table.
- The shape checks run before any drop. An object under one of those
names that the store did not make refuses the call
`SERVICE_UNAVAILABLE`, names the object, and is never dropped.
- **Options.** `vectorIndexThreshold` (`Infinity` turns the index off)
and `vectorIndexOverfetch`, on both `KnowledgeTursoPlugin` and
`TursoKnowledgeAdapter`. Exports `VECTOR_INDEX_THRESHOLD` and
`VECTOR_INDEX_OVERFETCH`.
- **For the contract review:** `vectorIndexOverfetch` must be a whole
number of 8 or more, and the constructor throws `RangeError` below 8.
The minimum follows the 8 x `topK` floor: a smaller over-fetch could
never answer approximately and would only add a one-bit scan to every
search.
- The option is new in this PR and unreleased. Against `main` the PR
only widens; the 8 is a narrowing of what this PR first offered (1 or
more), and the ruling leaves it to the contract review.
- **Docs.** The README Search section, and the two docs pages where they
name the exact scan.

**The mechanism is not `libsql_vector_idx` / `vector_top_k`; the ruling
keeps the card's outcomes and changes only this.** I built the card's
mechanism first (commits `09b0571582` and earlier) and measured it at
200,000 passages:

| Measure at 200,000 passages | DiskANN (`libsql_vector_idx`) | One-bit
index (this PR) |
|---|---|---|
| Build time | 1,439 s | 3 s |
| Extra memory to build | 2.2 GB | 54 MB |
| recall@10, vector only | 0.387 | 0.998 |
| recall@10, hybrid | 0.716 | 1.000 |

- DiskANN never got past 0.46 at any `k`, since `vector_top_k` caps at
200 rows. At 20,000 passages the best setting I tried reached 0.845, at
13 ms per row and 1.27 GB.
- The card's flow holds: over-fetch, then the in-scope WHERE, then the
service's re-check, then RRF, and a short leg re-runs exactly.

**Out of scope here:**

- **F3.** The rule that "callers whose visible ids fit the F3 cap keep
the exact path" lands with whichever of objectstack-ai#37957 and this card lands
second. Until then, a narrow scope goes exact through the floor above.
- **A second approximate attempt over a larger pool.** Retrying with a
10x pool before going exact, for searches that see about a fifth of the
records or less, is not in this PR. It is follow-up objectstack-ai#38066 (ruling A,
item 6).

## Tests

New and changed tests in `src/__tests__/acceptance.test.ts`, run on each
store kind (file, memory) with a threshold of 40:

- **Threshold.** At the threshold, the vector leg is approximate. At 61,
or at `Infinity`, it stays exact.
- **Organizations.** Each of these takes the exact path: two
organizations at build time; a second organization written after the
build; a passage with no organization.
- **Filter, over-fetch and the floor.**
- A metadata filter that the candidates miss falls back to exact
(over-fetch 8).
- With over-fetch 10 and `topK` 2, a scope of all but the two best
passages keeps 18 or more of the 20 candidates, at or above the floor of
16, and stays approximate.
- With the same settings, a scope of 2 records is under the floor and
goes exact.
- **Refused index.** Three variants:
- *ann_no_1bit:* the database creates the DDL, as SQLite does, and
refuses each statement that computes `vector1bit`.
  - *ann_no_ddl:* the database refuses the `F1BIT_BLOB` column.
- *ann_no_copy:* the database makes the index and refuses the copy
batch.

In all three, the build completes, later writes are found by the exact
scan, and `healthCheck()` stays `ok` and names the source and the reason
(plus the missing one-bit vectors for *ann_no_1bit*). No index objects
are left for the first two. For *ann_no_copy* the index is there, short
of its passage table, and is never searched. After `dropSource` the
source is no longer named.
- **Catalog reads.** A search under the threshold, or at `Infinity`,
issues no catalog read for an index, on each store kind. On one file
store, a second adapter reads the catalog of a source under the
threshold once (two reads) over three searches.
- **Case timeouts.** The two 2,000-passage recall cases carry a 30 s
timeout: 1,017 ms and 1,384 ms locally, and 5,971 ms for the scoped case
on CI, past the 5 s default.
- **A term-less query.** It binds exactly the values each vector
statement reads: an approximate answer, then an approximate statement
and the exact one for a scope under the floor.
- **Two adapters on one file store.**
  - The index memory is keyed per generation instance.
- A failed approximate statement is answered by the exact scan, and its
memory is forgotten.
- **Lifecycle.**
- The triggers keep the side table in step on insert, update and delete.
  - A generation swap leaves only the new generation's objects.
  - `dropSource` leaves nothing.
- **Growth.** A source that grew past the threshold gets its index at
its next build.
- **A foreign `-vec` table.** It refuses `completeBuild` and
`dropSource` with `SERVICE_UNAVAILABLE` and is kept.
- **Recall.** recall@10 is at least 0.95 against the exact scan in two
tests:
  - unscoped: 2,000 passages, 40 queries;
- under a record scope keeping 10%, 5% and 3% of 2,000 passages:
measured 1.000 at each share.
- **Options.** `RangeError` for a threshold below 1 and for an
over-fetch of 7 or 8.5; 8 is accepted.

`plugin.test.ts` checks that the plugin passes both options through.

Ablations: each an on-disk source edit run through vitest, each red as
intended, each restored to a blob equal to HEAD with an empty `git diff
HEAD`. Ablations 1a to 3 ran on the first design. Ablations 4 to 15 ran
on `b113f0830f` under the verify lock; the later merge of `main` does
not touch this package's files.

| Ablation | What I changed | Result |
|---|---|---|
| 1a | Search-side organization check returns true | Two-organization
test red: approximate 1, exact 1 |
| 1b | Build-side organization check removed | Two-organization test
red: 5 index objects found |
| 2a | Post-filter dropped | Filter test red: `published` instead of
`draft` |
| 2b | Over-fetch factor 1 | Over-fetch test red |
| 3 | Threshold forced to `Infinity` | Every approximate-path test red |
| 4 | The 8 x `topK` floor removed | 2 failed: the over-fetch test on
both store kinds (`{approximate: 1, exact: 0}` instead of `exact: 1`) |
| 5 | The `vector1bit` probe before the DDL disabled | 2 failed: 5 index
objects instead of none |
| 6 | The catch around the DDL transaction removed | 2 failed:
`completeBuild` rejects |
| 7 | The health check's one-bit probe disabled | 2 failed: the message
does not name the missing one-bit vectors |
| 8 | The health check's per-source refusal record ignored | 2 failed:
the message does not name the source |
| 9 | The index memory not keyed per generation instance | 1 failed: the
instance test, `{approximate: 1, exact: 1}` instead of `{approximate: 0,
exact: 1}` |
| 10 | The catch around the approximate statement removed | 1 failed:
the failed-statement test throws `no such table` |
| 11 | The catch around a copy batch rethrows | 2 failed: *ann_no_copy*
on both store kinds, `completeBuild` rejects |
| 12 | The `Infinity` skip of the catalog read removed | 2 failed: an
adapter that did not build the source reads 2 catalog rows instead of 0
|
| 13 | The build's own "no index" verdict not remembered | 2 failed: 2
catalog reads under the threshold instead of 0 |
| 14 | A search's "no index" answer not remembered | 1 failed: another
adapter reads the catalog 6 times instead of 2 |
| 15 | The candidate count bound for both statements | 2 failed: the
exact statement binds 4 values and reads 3 |

The scoped-recall unit test stays green with ablation 4 (0.997, 0.993,
0.963). It guards recall; the over-fetch test is what pins the floor.

<details><summary>Local runs on the final head 73d2774 (origin/main
6e06729 merged)</summary>

On 73d2774 (test timeouts and wording only, on top of 50e245a),
under the lock: typecheck exit 0, `Tests 256 passed (256)`; the four
derived gates that read the changeset and README exit 0
(`check-changeset-no-major`, `check-empty-changeset`, `check:nul-bytes`,
`check:published-readme-links`). The 100-family union below is from
50e245a.

All under `os-verify-lock`, slot `o1C-37975`, `VERDICT command-exit 0`;
the lock was held 1,544 s after a 201 s wait.

- **Closure build** (`knowledge-turso^...` plus itself,
`--concurrency=2`): exit 0.
- **Typecheck:** `pnpm --filter @objectstack/knowledge-turso typecheck`
exit 0, with `check:test-typecheck` OK (0 errors).
- **Tests:** `pnpm --filter @objectstack/knowledge-turso exec vitest run
--maxWorkers=2` exit 0: `Test Files 4 passed (4)`, `Tests 256 passed
(256)`.
- **Derived gates:** `dispatch-gates --commands` derived 100 commands at
50e245a, and all 100 ran.
- Reconciled with `--ran`, exit codes recorded: `100 derived, 100 run, 0
NOT-MEASURED`.
- 99 recorded exit 0 on the first pass. `check:dual-build-cjs-loads`
exited 1 on that pass, naming `@objectstack/plugin-approvals` (a package
this diff does not touch; its `dist` was rewritten during that pass).
- Re-run alone under the lock on the same head, it exited 0: 126 require
entry points across 74 packages load. The record carries that exit 0.
- **Overlap check:** `VERDICT clean exit 0` against origin/main
0e36120 and the open PRs objectstack-ai#38060, objectstack-ai#38050, objectstack-ai#38013 and objectstack-ai#37982.
- **On `b113f0830f`, the head before the merge, under the lock:**
ablations 4 to 15 as in the table, each red and each restored to a clean
tree; the reconciliation read 100 of 100.

</details>

## Acceptance notes

- **Measured, unscoped**, at 200,000 passages of 1,536 dimensions. The
vectors are clustered synthetic data (latent dimension 384, 200
clusters), all of one organization, `topK` 10. The box was shared, with
a load of about 8 on 4 cores. The script is a scratch `bench.mts`, not
committed.

  | Search | Exact scan, p50 / p95 | One-bit index, p50 / p95 |
  |---|---|---|
| Vector leg only (the keyword leg matches nothing) | 958 / 1,054 ms |
66 / 81 ms |
  | Hybrid | 1,416 / 1,544 ms | 550 / 666 ms |

  - The slowest approximate vector-only search took 104 ms.
- recall@10 against the exact scan, over 100 queries: 0.998 vector-only,
1.000 hybrid.
- Building the index took 2.6 to 3.0 s, with the database file going
from 1,714 to 1,768 MB.

- **Measured, scoped**, on the same 200,000-passage store: 50
vector-only queries per share, a record scope, against the exact scan of
that scope. The "old rule" answers whenever the pool fills `topK`,
computed in SQL on the same store.

| In scope | recall@10 (floor 8) | Worst query | Sent exact | p50 / p95
| Old rule: recall, worst |
  |---|---|---|---|---|---|
  | 10% | 1.000 | 1.0 | 100% | 952 / 993 ms | 0.952, 0.7 |
  | 15% | 1.000 | 1.0 | 100% | 974 / 1,013 ms | 0.980, 0.9 |
  | 20% | 0.992 | 0.9 | 48% | 395 / 1,052 ms | 0.986, 0.9 |

- **Floor 4 against floor 8.** With a floor of 4 x `topK`, the same
bench gave 0.970 at 10% in scope, with a worst query of 0.7 and 44% of
queries sent exact. With 5% and 3% in scope, floor 4 already sent every
query exact (recall 1.000), where the old rule gave 0.914 and 0.878.
- **The simulation agrees.** The reviewer's numpy simulation
(`scoped-recall-floor8-retry-sim.py`, run under the verify lock) gives,
at floor 8: 41% exact and 0.988 at 20%, 99% exact at 15%, 100% exact at
10% and below.
- **Caveats.**
- **Synthetic vectors only.** No real embeddings were tried. Real
embedders put their vectors in a narrower cone, and one-bit quantization
keeps the signs of the coordinates. So on real data the one-bit
ranking's recall may be lower than measured here, and the right
`vectorIndexOverfetch` may be higher.
- **The one-bit leg is still a linear scan.** It is 13 to 15 times
cheaper than the float32 scan. Extrapolated linearly, that is roughly
0.35 to 0.4 s at 1,000,000 passages of one source, with no structure
that cuts the work below linear.
- **The hybrid p95 is the keyword leg's.** 666 ms, against 81 ms for the
vector leg alone. The cost is the keyword leg: `LIKE` for terms under 3
characters, and the trigram match for common trigrams, on an adversarial
bench vocabulary where every word starts with `term`. This PR does not
touch that leg, and no card covers it yet.
- **Only broad searches speed up.** A search whose scope or filter keeps
about 15% of a source's passages or less runs the exact scan. Its recall
holds, and it costs what it cost before this PR (about 1 s at p95 at
200,000 passages).
- **One hosted check is asked for.** On a hosted (Turso) database, after
a complete build of a source of 20,000 passages or more, confirm that
the `knowledge_SOURCE_gN-vec` side table exists. The one-bit vectors and
the DDL have only run on local `file:` and `:memory:` stores here. If it
is missing, the health check names the reason.
- **Nothing is logged at build time.** The adapter has no logger, so a
refusal shows only in the health check's message.
- **The organization rule is per passage table, not store-wide**, as the
ruling confirms. Pinned in both directions (ablations 1a and 1b).
- **Clause-②: yes (widening), re-judged on the final diff.** Two
optional adapter and plugin options and two exported constants are new.
Nothing that was accepted before is refused, with one exception: an
object the store did not make under one of its new hyphenated names
(`knowledge_SOURCE_gN-vec`, `-org`, or a `-vec-*` trigger) now refuses
`completeBuild`, `dropSource` and the opening of a generation with
`SERVICE_UNAVAILABLE`. That is the rule `main` already applies to the
keyword index's names, and the changeset states it. The claim's `no` is
corrected here. Both options are code options, not stored metadata:
`Metadata-protocol: none`.
- **Out-of-scope, noted and not filed:**
  - The keyword leg's cost, as above.
- Bulk upsert grew native memory under the bench until GC ran. Not shown
in production.

## Verification

Read first, by risk:

1. `turso-adapter.ts`, `buildVectorIndex`: the probe, the guarded DDL
transaction, the batched backfill against a generation being swapped
away, and the refusal record.
2. `turso-adapter.ts`, `searchAttempt` and `approximateSearchable`: the
`pool` count, the 8 x `topK` floor, the per-search organization check,
and the short-leg fallback.
3. `sql.ts`, `vectorIndexDdl` and `vectorIndexShape`: the triggers and
the shape check before a drop.

Two-minute check:

```
pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "approximate vector index"
```

Expected: every test passes, on both store kinds. Then edit
`searchAttempt`: change `pool >= VECTOR_MIN_POOL * topK && ` to nothing,
and run it again. The over-fetch test turns red with `{ approximate: 1,
exact: 0 }`.

---

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…s the coded refusal (objectstack-ai#38162)

<!-- claude-projects-attribution: {"github_login":"os-sales"} -->
_Requested by **Sales** · [project
thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu8DXSJ9ux8eFLK9ET17FQgN)_

Fixes objectstack-ai#37411

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 外接 AI
调用工具时参数不符合工具公布的格式,以前拿到的是一句没有错误代码的英文报错,并把传错的键原样回显(含换行和空字符、不限个数);现在两个入口都返回平台统一的带代码拒绝(校验错误、状态
400),最多点名五个错键,每个截短并把控制字符转义。
- 属于 AI 接入面的拒绝格式统一:平台约定每个拒绝都带代码,这条路是唯一的例外,AI 客户端没法按代码处理。
- 只影响调用方自己传错参数时看到的文字;照旧按「出错的工具结果」返回,不会变成连接错误,回滚即恢复旧文字。
- 无。

## What changes

- **Both MCP doors** (Streamable HTTP and stdio) build their server
through `createPlatformMcpServer`
(`packages/mcp/src/request-params.ts`). That seam now also wraps the
SDK's private `validateToolInput`: the SDK's own check still runs first
and decides; only when it refuses with `InvalidParams` are the arguments
parsed again (the SDK's own `normalizeObjectSchema` + `safeParseAsync`)
to read the issues its message had flattened, and the refusal leaves as
the platform's coded tool error: `isError: true`, one text content
holding the `codedErrorResult` JSON, `code: VALIDATION_ERROR`, `status:
400`, `message: "Invalid arguments for tool NAME: ..."` (each problem
named at its path, as before). A refusal the schema parse does not
reproduce (the SDK's argument-size cap) keeps the SDK's answer. A call
that passes is parsed once, as before. If a later SDK renames
`validateToolInput`, server construction fails loudly naming the seam,
as the existing request-handler seam does.
- **Bounded, sanitised echo** (`packages/mcp/src/argument-echo.ts`,
new): at most 5 unknown keys named per object and the rest counted (`4
more unrecognized key(s) not shown.`), each key cut at 64 characters
with a trailing ellipsis, every control character (C0, DEL, C1,
U+2028/2029) written as its backslash-u escape. Applied in two places:
- `strictToolInput` in `mcp-http-tools.ts` (every platform tool): the
unknown-key factory is handed the bounded keys, so a plain misspelling
still gets its rename advice (`sort` → `orderBy`) and the retired
`confirm` member still gets its prescription.
- the seam above, as a backstop for every other tool (the dataset pair's
spec `strictObject` input, bridged AI `ToolRegistry` tools, plugin
tools): a raw key the message quotes is replaced by its bounded form,
path segments are echoed the same way, remaining control characters are
escaped, at most 10 problems are named, and the whole message is cut at
2000 characters.
- `content/docs/ai/knowledge-rag.mdx`: the one hand-written page this
change made false said a schema-stated `search_knowledge` argument is
refused over MCP "as error `-32602` ... without that code"; it now says
the door's schema check answers the same coded `VALIDATION_ERROR` (400).
- Changeset: `@objectstack/mcp` patch.

## Tests

- New `describe` in `packages/mcp/src/request-params.test.ts` (the
seam's existing harness): one test per door (HTTP via
`handleHttpRequest`, stdio via a real `StdioServerTransport` on the
long-lived server) sends a wrong type plus nine unknown keys, each
carrying a newline, a NUL and a 60-character tail, and asserts
`isError`, `code: VALIDATION_ERROR`, `status: 400`, the wrong type named
at `objectName`, exactly five keys named plus `4 more ... not shown`,
the escaped and cut key form, and no raw control character. A third test
pins that a plain misspelling (`sort` on `query_records`) keeps its ``
`sort` → `orderBy` `` advice and is not cut.
- Five existing pins asserted the bare `-32602` text and now read
`VALIDATION_ERROR` (and `status: 400`) off the coded text:
`mcp-record-id-key-mistake-refusal`,
`mcp-http-tools.unknown-argument-keys`, `mcp-dataset-tools`,
`mcp-knowledge-tools`, `mcp-action-confirmation-handoff-33690`. The last
one pinned that the retired `confirm` member mints no code of its own;
it still does not — it answers the same `VALIDATION_ERROR` the
undeclared `bogus` key gets, and the statement comparison between the
two is unchanged.
- `pnpm --filter @objectstack/mcp test`: Test Files 88/88, Tests
1645/1645 at 8ad6141 (f55eeb7 adds only the docs line above). `pnpm
--filter @objectstack/mcp typecheck`: exit 0.
- Local derived gates (`dispatch-gates.mjs --commands`, re-derived at
f55eeb7, 98 commands): 93 exit 0. Not measured locally, CI runs them:
`check:dual-build-cjs-loads` and `spec check:skill-examples`
(prerequisite: no built `dist/` or declarations for the packages they
read), `check-plugin-teardown-shape --self-test` (shallow clone cannot
reach its pinned fixture commit), `check:query-options-erasure` and
`check:type-check-debt` (over the 300 s local cap).

<details><summary>Reproduction on main and ablations</summary>

- On `main` (base 581ae76), a probe sending the failing arguments to
`validate_expression` over HTTP read: `MCP error -32602: Input
validation error: Invalid arguments for tool validate_expression:
Invalid input: expected string, received number at objectName` then
`Unrecognized key(s) on this validate_expression call:` followed by all
ten keys, each with its raw newline and NUL. No `code`, no `status`.
- Ablation 1 (`scripts/ablation-replace.mjs`, delete the
`answerToolArgumentRefusalsWithCode(server);` call): 4 of 10 tests in
`request-params.test.ts` red (both door tests, the misspelling test, the
HTTP control); restored, blob == HEAD.
- Ablation 2 (drop the `withBoundedKeyEcho` wrap): the two door tests
red on the key count (`junk_0`..`junk_8` all named, expected five);
restored, blob == HEAD. The backstop alone escapes and cuts the keys but
does not cap their count, which is why the factory wrap exists.
- Tests import `src/` directly, so neither ablation needed a rebuild.

</details>

## Acceptance notes

- The coded text rides the SDK's own tool-error builder: the refusal is
thrown as a plain `Error` whose message is the `codedErrorResult` text,
and the SDK's `tools/call` handler puts a thrown message into the tool
error verbatim. The door tests pin the resulting shape on both
transports.
- The scenario-eval scorer classifies an uncoded tool error separately
from a coded one; schema refusals will now read as coded
`VALIDATION_ERROR`. That is the point of the card; no scorer fixture
depends on live server output.
- `packages/runtime/src/domains/mcp-authoring.ts` is untouched (open PR
objectstack-ai#38013 owns it).
- The Docs Drift Check lists `content/docs/deployment/cli.mdx`,
`content/docs/protocol/objectql/types.mdx` and the v17.0 release page
via the literal `unrecognized_keys` (the zod issue code this diff
reads). Re-read by hand: all three describe spec metadata refusals (`os
validate`, `FieldSchema`), not an MCP tool argument; none is changed by
this diff. The page this diff did falsify, `knowledge-rag.mdx`, the
check did not list; it was found by grepping the docs for `-32602`.
- Card-level dedupe and reach are on the card; nothing new was found on
the way.

## Verification

- First reads, by risk: `packages/mcp/src/request-params.ts`
(`answerToolArgumentRefusalsWithCode`, `toolArgumentRefusalText`,
`issueSentence`), `packages/mcp/src/argument-echo.ts`, the
`withBoundedKeyEcho` hunk in `packages/mcp/src/mcp-http-tools.ts`.
- Two minutes: `pnpm --filter @objectstack/mcp exec vitest run
--maxWorkers=2 src/request-params.test.ts` — expect 10/10, including the
three `answers the coded refusal` tests.

---

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

<!-- signed: repo:objectstack#2 · os-sales ·
session_01L6bhgU2PeRzoy1CXJoUHGp -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ai residue; objectstack-ai eval cases 2, 6, 7 grade every correct spelling (objectstack-ai#38156)

<!-- claude-projects-attribution: {"github_login":"os-sales"} -->
_Requested by **Sales** · [project
thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuFLwsbUXqRkpg67fCZfuCf3)_

Fixes objectstack-ai#37850

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:用 AI
技能写智能体的开发者会读到更准确的一句话:智能体模型里的「服务商」字段已退役、会被拒绝,唯一例外是旧版工具自动写进去的 openai
默认值,会被接受并自动删掉;做法不变,仍是删掉它。运行时行为不变。
- 为什么做:上一次去掉这个字段的改动在审核里留下的四个尾巴:说法不准一处、评测判分词太窄三处(另一处过期行号已被别的改动删掉)。
-
出错会怎样:只影响技能文字和评测读数,产品行为不变;判分若放得太松会把没学会的答案判对,本次用两轮旧录音重判,不带技能的答案一个也没有因此变对。可以直接撤回。
- 要你做什么:技能包是对外发布的受管文件,需要你批准合并。

## What changes

- `skills/objectstack-ai/SKILL.md` (Model Configuration): "`provider` is
retired (protocol 19): writing it is a parse error" becomes "retired
(protocol 19) and refused, except the `'openai'` an 18.x toolchain wrote
out, which parses and is stripped. Delete it." The instruction is
unchanged. The file sits at zero token headroom, so the clause is paid
for by deletions in the same section: ", never a provider" (the next
clause says the deployment chooses it), the `model` row's "for the
environment" and "model " in "free-string model name", and the
`temperature` row's "`min(0).max(2)`, " (the same cell says "Outside 0–2
is a parse error"). Ceiling unchanged.
- `packages/spec/src/ai/agent.zod.ts`: the `provider` tombstone's jsdoc,
which said the same words, names the one value that parses
(`MODEL_PROVIDER_RETIRED_KEY_RESIDUE`) and that `tsc` refuses it all the
same. Comment only.
- `skills/objectstack-ai/evals/skills-tools-knowledge.json`:
- case 2 (sampling settings): `expected_output` says "refused" instead
of "a parse error"; `must_not_contain` goes from the one spelling
`provider: 'anthropic',` to nine code spellings: single or double
quotes, followed by a comma, a newline, ` }` or `}`, and the JSON form
`"provider": "anthropic"`. The backtick-terminated inline warning (``
`provider: 'anthropic'` ``) still passes.
- case 6 (nightly approval script): the `must_contain_any` group gains
`refuses`.
- case 7 (`run_action` with `confirm: true`): `do not retry` moves from
`must_contain` into a `must_contain_any` group `["do not retry", "Do not
retry", "don't retry", "Don't retry"]`.
- `.changeset/37850-agent-model-provider-refused-residue.md`:
`@objectstack/skills` patch, `@objectstack/spec` patch (jsdoc).

## Why

The four boxes of objectstack-ai#37850, each against `main` 581ae76:

1. **N1, the parse-error wording.** True for every value but one:
`acceptRetiredDefaultResidue(…, { provider: 'openai' })` at
`agent.zod.ts:71`/`:96` strips the 18.x default (pinned by
`agent-model-provider-retirement.test.ts:91-95`). Fixed in the skill and
the jsdoc.
2. **N2, case 2's single forbidden spelling.** Fixed as a set of
spellings, not the bare key: a bare `provider:` fails correct answers
that quote the retired spelling to warn (round-1 answers do exactly
that).
3. **`SKILL.md:457` citing `agent.zod.ts:234, :251`.** Already gone on
`main`: objectstack-ai#37939 (62dd9e1) rewrote that passage and dropped the citation.
Closed with that reason; nothing to change.
4. **Cases 6 and 7 missing their literal phrases.** Judged against the
recorded answers of both objectstack-ai#37796 rounds (round records kept by the seat):
the **grading token** was wrong in both, the teaching is right.
- Case 7: all six with-skill answers say "Don't retry" / "Do not retry"
/ "**don't retry**" next to the right handling of `pending_confirmation`
and `no_confirmation_service`; the grader is a case-sensitive literal
match (`grade.ts`), and `SKILL.md:212` teaches "do not retry".
- Case 6: objectstack-ai#37969 (dc45b1e) already moved it to an any-of group; one
correct with-skill answer still failed it only because it wrote
"refuses" ("ObjectStack refuses decisions made with API tokens").

## Verification

<details><summary>Re-grade of the recorded rounds under the new
assertions (literal grader, script in the thread scratchpad)</summary>

Round 2 (runner fb8b3f2, the clean round):

| case | with-skill before → after | no-skill before → after |
|:--|:--|:--|
| 2 | 3/3 → 3/3 | 0/3 → 0/3 |
| 6 | 1/3 → 3/3 | 0/3 → 0/3 |
| 7 | 0/3 → 3/3 | 0/3 → 0/3 |

Round 1 (789e0c7) with-skill: case 6 0/3 → 3/3, case 7 0/3 → 3/3. Round
1's no-skill arm read project memory (objectstack-ai#37842), so its case 2 flips
(graded then under an older assertion) are not evidence either way.

`pnpm --filter @objectstack/scenarios skill-evals --regrade` on a copy
of round 2 exits 0: the catalog loads; it sets cases 2/6/7 apart as
changed since the round, as designed, so the table above is the
literal-grader reading.
</details>

<details><summary>Local gates at c5dee31; at 72007e7 (S1, a line
number only) and at 61188fd (main merged + the 5-byte cut) the token
ratchet, check-nul-bytes, check:skill-links, check:skill-frame-sync,
check:skill-identifier-liveness, check:skill-docs, check:skill-refs and
check:empty-changeset re-run, exit 0</summary>

All exit 0: `node scripts/check-skills-token-ratchet.mjs`
(`skills/objectstack-ai/SKILL.md is 6893 tokens (ceiling 6893; headroom
0)`), `check-affected-docs`, `check-drift-comment`, `@objectstack/spec`
`build` + `check:generated` (`All 14 generated artifacts are up to
date`), `check:docs`, `check:skill-docs`, `check:skill-refs`,
`check:liveness`, `check:llms-txt`, `check:doc-authoring`,
`check:pm-skill-id-lint`, `check:skill-compatibility`,
`check:skill-frame-sync`, `check:skill-frame-freshness`,
`check:skill-identifier-liveness`, `check:skill-links`,
`check:spec-docblock-symbol-anchors`, `check:spec-parsed-alias`,
`check:skill-top-level-keys`, `check-nul-bytes`,
`check:empty-changeset`. The rest of the derived families are CI's.
</details>

Skills readings (lines), against `main` at the merge:
`skills/objectstack-ai/SKILL.md` 488 → 489; bundle (all
`skills/*/SKILL.md`) 4953 → 4954. Tokens: 6906 → 6906 of 6906 (before
the merge: 6893 → 6893 of 6893).

No eval round run (Sales paused rounds). Two-minute check: `node
scripts/check-skills-token-ratchet.mjs | grep objectstack-ai/SKILL`
prints ✓ at 6893.

## Acceptance notes

- Read first: the SKILL.md hunk (the residue sentence and the three
deletions paying for it), then case 2's spellings.
- Case 2 still lets a code line with trailing spaces or a `//` comment
after `provider: 'anthropic'` (no comma), or `provider:'anthropic'` with
no space, slip past; closing those with literal substrings would start
catching the inline prose warning. Left open.
- Accepted nits from the contract review (not changed this round): case
2's two `}` spellings also fail a correct answer that warns inline with
the braces (the retired key shown inside a backticked `model: { … }`),
so "the inline warning still passes" holds for the bare-key form only,
and a fenced counter-example still fails; case 7 still misses a
typographic apostrophe, "never retry", or bold inside the phrase; case
6's any-of group is met by generic refusal wording and leans on its one
forbidden call spelling (older than this PR).
- `SKILL.md:365`'s cite moves `agent.zod.ts:87-95` → `:89-97`: the jsdoc
hunk adds two lines above the `model` block's keys (review S1).

## Serial

Open PR objectstack-ai#38013 edits other hunks of the same two skill files (the
knowledge-service sentence at `SKILL.md:244`, case 14); the text merges
clean. It does not fit under the token ceiling, though: objectstack-ai#38013 re-pins
`skills/objectstack-ai/SKILL.md` to 6906 at its own measurement (27650
bytes), this PR adds 3 bytes (27596 → 27599), and the two merged are
27653 bytes, `ceil((27653 - 27) / 4)` = 6907, one over objectstack-ai#38013's row.
Whichever lands second goes red on the token ratchet and must cut 2
bytes or re-pin; merging `main` alone is not enough.

**Resolved here:** objectstack-ai#38013 landed first, and this PR's first merge-queue
run went red on exactly that row (6907 / 6906). `main` is merged in
(c725268) and 61188fd deletes a repeated noun inside this PR's own
Model Configuration hunk ("among the providers turned on" → "among the
ones turned on", 5 bytes; "the ones" refers back to "the provider" five
words earlier). The file is 6906 / 6906 and no ceiling moves. The cut is
sized to land on the row: the ratchet is red below its ceiling too, so a
larger cut would have had to lower the row in the same commit.

## Human Minimum

- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
(jsdoc only)
- [x] 2. Every name I added uses the casing for its kind. (none added)
- [x] 3. No formatter ran; `pnpm lint` passes. (left to CI)
- [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. (`check:generated`: all up to date, nothing
to commit)
- [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_01L6bhgUDWstaVZQkWbWFNBK

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

<!-- signed: repo:objectstack#2 · os-sales ·
session_01L6bhgUDWstaVZQkWbWFNBK -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…nd the dropSource cleanup (objectstack-ai#38050)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Fixes objectstack-ai#38022

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 升级到 19 的运维读升级表时,会看到「以下划线开头的知识源 id 要改名并清理旧索引」这一例外,不再被告知「索引原样找回」。
- 为 AI 知识库(epic 37000)的 18 到 19 升级文档补上一处与升级条目不一致的说法。
- 只改文档与报错文案,不影响运行行为,可直接撤回。
- 无。

## What changes

- `content/docs/protocol/knowledge.mdx`: the `id` row of the 18 to 19
table names the underscore exception (`name` refuses it, the source is
rebuilt under a new name) and the `dropSource` cleanup, in the words of
the upgrade entry `knowledge-source-registration-governed`. It states
the memory adapter holds nothing across a restart. The row does not
touch `adapter`, which objectstack-ai#38026 made optional (rows and prose near it
re-read on current main; no contradiction).
- N1: the upgrade entry's reason says the adapter keeps the old index
only where its store outlives the process (Turso, pgvector); the memory
adapter holds nothing across a restart.
- N2: the `id` tombstone in `knowledge-source.zod.ts` says the entry's
manual notices still apply after `os migrate meta --from 18`; the
reference page `content/docs/references/ai/knowledge-source.mdx` carries
the same sentence.
- `.changeset/37304-knowledge-source-governed-type.md` is not edited: it
sits in `.changeset/pre/` (consumed by pre mode). A new patch changeset
covers the spec string change.

## Tests

NOT MEASURED: `knowledge-source.test.ts` and
`retired-key-migrate-sentence.test.ts` (the tombstone still ends with
the migrate sentence and still begins with its pinned prefix), because
the verify lock was never acquired in 4 attempts over about 36 minutes
(holder was a dogfood run; VERDICT queue-timeout exit 99).

## Acceptance notes

- NOT MEASURED: `pnpm gen:docs` regeneration (needs the spec build, same
lock). The reference page was edited by one exact-string substitution
mirroring the zod edit; CI `check:generated` is the judge.

<details><summary>Verification</summary>

- check:doc-authoring, check:doc-anchors, check:doc-frontmatter,
check:docs-nav-label, check:docs-image-tag: exit 0.
check:docs-transcript-drift: exit 3, NOT MEASURED (prerequisite).
- overlap-check at d60a6ce: VERDICT clean exit 0 (main, objectstack-ai#38043,
objectstack-ai#38013, objectstack-ai#37963 merge cleanly).
- Two-minute check: open the knowledge protocol page, 18 to 19 table,
`id` row: it names the underscore exception.

</details>

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

https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…g, 56 changesets added) and state what npm publishes (objectstack-ai#38645)

<!-- claude-projects-attribution: {"github_login":"os-steve"} -->
_Requested by **Steve** · [project
thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9St4eUWHFcCKuRUrCZPperJ)_

Fixes objectstack-ai#38189

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:v19 发布页的 breaking 清单补上 11 月 26 日之后合进来的 56 条改动(其中 30 条还在 main
上、下一次预发布才带上,页上逐条标明),计数和页头的发布状态也改成现在 npm 上的真实情况。
- 为什么做:升级到 19 的人把这页当完整清单用;原清单只数到 19.0.0-next.0 的输入,之后 next.1、next.2 和
main 上的 breaking 改动大多没列。
- 出错会怎样:只改一个文档页,不影响任何代码或发布;某条写错了,读者会被误导,但直接撤回这个改动即可恢复原页。
- 要你做的:无。

## What changes

`content/docs/releases/v19/index.mdx` only.

- **Header.** The publication sentence now states what npm answers:
`latest` is 18.6.0, `next` is `19.0.0-next.2`; the line's versions on
npm are `19.0.0-next.0` (2026-11-26) and `19.0.0-next.2` (2026-11-28).
`19.0.0-next.1` was versioned on `main` (30a8047) and is not on npm, so
its changes first ship in `next.2`.
- **How this list was built.** Re-measured at `6eb23c87` (origin/main at
start, 2026-11-29) with the method the page states:
`classifyReleaseBullet` over every changeset on `main` — the 1,185 in
`.changeset/pre/` (consumed by the next.0, next.1 and next.2 version
passes) and the 219 still pending. 159 breaking from 155 PRs: 98 to act
on, 61 registered.
- **56 new lines' worth of changesets**, each sorted by the classifier
into 需手动处理 (27) or 自动迁移 (29), placed under the page's existing topic
headings, with three new ones: 需手动处理 → Knowledge; 自动迁移 → Knowledge
sources, Sharing and permissions. The 30 still pending carry "— on
`main`".
- **自动迁移 intro** and **Coming from 18.x step 3**: the registered split
restated in changesets (31 on the protocol-19 step, 30 on the
protocol-18 step, of 61).
- **Callout**: no longer says no prerelease was published.

## Tests

The classifier run (script in the dev's scratchpad; it imports
`classifyReleaseBullet` from `scripts/release-github-releases.mjs` and
feeds each changeset body as a CHANGELOG bullet, `- ` on the first line
and two-space indent on the rest), at `b03fd5f5`'s parent tree
`6eb23c87` (the diff touches no changeset):

<details><summary>Raw counts</summary>

```
ALL 1404 {"manual":98,"migrated":61,"other":830,"added":403,"semantic":12}
OLD (in a46efa8 set) 950 {"migrated":31,"manual":71,"other":563,"added":278,"semantic":7}
NEW (after a46efa8) 454 {"manual":27,"other":267,"added":125,"migrated":30,"semantic":5}
  NEW next.0 45 {"other":27,"added":13,"migrated":1,"semantic":2,"manual":2}
  NEW next.1 138 {"manual":9,"other":80,"migrated":12,"added":36,"semantic":1}
  NEW next.2 52 {"added":11,"other":38,"manual":3}
  NEW pending 219 {"added":65,"other":122,"migrated":17,"manual":13,"semantic":2}
missing-from-tree of a46 set: none
```

The same function over the 950 files as they stood at `a46efa8c` (`git
show a46efa8:.changeset/FILE`):
`{"migrated":31,"manual":71,"other":563,"added":278,"semantic":7}`, and
0 of the 950 changed section between `a46efa8c` and `6eb23c87` — the
page's first count reproduces exactly.

</details>

<details><summary>The 57 breaking changesets added after a46efa8 (pass
· section · PR · file)</summary>

```
next.0  manual    37477  37004-retire-knowledge-ragflow.md
next.0  manual    37491  36964-flow-option-label-filters.md
next.0  migrated  37437  35827-data-table-staged-edit-retired.md   (already on the page)
next.1  manual    37605  31908-p4c-sealed-expiry.md
next.1  manual    37640  37604-platform-record-followups.md
next.1  manual    37668  37104-knowledge-settings-readers.md
next.1  manual    37720  37682-i18n-retire-build-chat-keys.md
next.1  manual    37720  37682-retire-build-chat-frontend.md
next.1  manual    37818  37608-disabled-holder-publish-rollback-refused.md
next.1  manual    37883  37575-first-render-grid-shell-passes.md
next.1  manual    37900  36689-mcp-stdio-disabled-package-every-caller.md
next.1  manual    37902  37678-knowledge-turso-settings-group.md
next.1  migrated  37366  37086-define-metadata-form-rename.md
next.1  migrated  37366  37086-form-metadata-type.md
next.1  migrated  37371  36055-view-all-stops-voting-on-fields.md
next.1  migrated  37513  35143-data-model-publish-checks.md
next.1  migrated  37584  37499-disabled-holder-unbound-row-bare-write-refused.md
next.1  migrated  37600  36595-related-list-key-under-arrangement.md
next.1  migrated  37676  37304-knowledge-source-governed-type.md
next.1  migrated  37783  37712-agent-model-provider-retired.md
next.1  migrated  37807  35143-seeds-actions-checks.md
next.1  migrated  37840  36377-flow-bare-ordering-record-date-arithmetic.md
next.1  migrated  37870  37613-book-audience-one-gate.md
next.1  migrated  37910  37717-lookup-depends-on-param-computed-field.md
next.2  manual    37948  37851-disabled-holder-own-row-publish-rollback-refused.md
next.2  manual    38028  managed-email-password-held-off.md
next.2  manual    38042  36679-secret-rewrap-confirmation-exit.md
pending manual    37896  runtime-object-less-action-no-record.md
pending manual    37963  37467-knowledge-title-arm-retired.md
pending manual    37982  37907-knowledge-turso-test-connection.md
pending manual    38038  38019-knowledge-source-review-follow-ups.md
pending manual    38085  37622-related-list-keys-agree-under-arrangement.md
pending manual    38180  auth-switches-read-declaration.md
pending manual    38209  35879-served-schema-platform-stamped-keys.md
pending manual    38268  sec2-wf9p-f12.md
pending manual    38269  37752-app-list-edit-with-ai-removed.md
pending manual    38310  38041-knowledge-source-closure-system-object.md
pending manual    38431  36987-auth-updateuser-returns-void.md
pending manual    38452  38377-retire-split-algorithm-version.md
pending manual    38580  36057-scenarios-delete-agent-confirmation-names.md
pending migrated  37924  37856-ask-ai-action-type-retired.md
pending migrated  37929  36495-action-locations-acted-on.md
pending migrated  37971  37307-knowledge-source-references.md
pending migrated  38001  automation-variable-keys-reserved-segments.md
pending migrated  38013  37983-knowledge-source-save-needs-the-service.md
pending migrated  38060  37961-knowledge-source-unmounted-adapter-refused-at-save.md
pending migrated  38096  34562-record-structural-lint.md
pending migrated  38107  35143-views-dashboards-checks.md
pending migrated  38145  37214-chart-series-measure-format-refused.md
pending migrated  38168  36544-form-view-modal-size-retired.md
pending migrated  38216  33912-share-unknown-recipient-ledger.md
pending migrated  38216  33912-share-unknown-recipient.md
pending migrated  38273  33806-pending-confirmation-service-one-seam.md
pending migrated  38299  35924-publish-reparses-object-draft.md
pending migrated  38398  37753-build-progress-frame-retired.md
pending migrated  38470  38369-knowledge-held-without-embedder-or-store.md
pending migrated  38545  38150-adopt-orphans-door-retired.md
```

PR = the `(#N)` of the commit that added the changeset (`git log
--diff-filter=A`). The pass is the version commit that moved the file
into `.changeset/pre/`: next.0 33a31dc, next.1 30a8047, next.2
9d111a7 (`packages/spec/package.json` reads `19.0.0-next.0/1/2` at
each).

</details>

<details><summary>Page cross-checks</summary>

- Every one of the 155 PRs behind a breaking changeset is linked on the
page (0 missing), and the page links no PR outside that set.
- Each of the 30 pending changesets sits on a line carrying "— on
`main`", and no published one does.
- `!`-titled first-parent commits since 18.6.0 (958ee03) to `6eb23c87`:
135 (87 to `a46efa8c`, as the page said); all 135 are in the list.
- Registered markers resolved to their entry files
(`packages/spec/src/migrations/entries/*/N.*`,
`packages/spec/src/conversions/entries/N/`, and metadata-core's forward
conversion for `permission-view-all-fields-beside-record-bypass`): the
30 registered changesets added after `a46efa8c` name 39 ids, all on step
19; the 31 before it name 33 ids, 32 on step 18 and
`protocol-18-range-refused` on step 19.

</details>

## Acceptance notes

- **Pending changesets are in the list.** The card's done-when covers
every changeset between `a46efa8c` and the measurement sha; 30 of those
are still in `.changeset/` and ship in the next cut, so their lines are
marked "on `main`" and the intro says so.
- **`19.0.0-next.1` is not on npm.** `npm view PKG versions` for
`@objectstack/spec`, `core`, `cli`, `runtime` and `@object-ui/i18n`
lists `19.0.0-next.0` and `19.0.0-next.2` only. The header states that
fact and no more.
- **The registered split is now counted in changesets, not entries.**
The old page said 41 registered entries, 39 on protocol 18. Counting the
ids in the registered markers gives 33 at `a46efa8c` (32 on step 18), so
the 41/39 could not be reproduced from any stated method. The rewritten
intro and step 3 count changesets (31 on step 19, 30 on step 18, of 61),
which match the bullets one to one.
- **Followed the classifier where a title has no `!`:** objectstack-ai#37605, objectstack-ai#37883,
objectstack-ai#37963, objectstack-ai#38209 and objectstack-ai#38269 are breaking by their banner or their
`(narrowing)` arm; objectstack-ai#38209's Clause-② reads "no (narrowing …)", which the
classifier counts as breaking although the body says nothing a client
sends is refused. Listed as classified; no changeset changed.
- **objectstack-ai#37513** merged before the next.0 cut but its changeset was consumed
by next.1 (its body says the next.0 CHANGELOG missed it).
- **One line, several changesets**: objectstack-ai#37720, objectstack-ai#37366 and objectstack-ai#38216 each carry
two changesets; objectstack-ai#37818 with objectstack-ai#37948, objectstack-ai#38038 with objectstack-ai#38310 and objectstack-ai#38013 with
objectstack-ai#38060 share a line. The existing 102 lines were not rewritten.
- **Counts on a release page**: each is anchored to a named measurement
sha, the snapshot the card asks for; it is not a count kept in sync with
the tree.
- **objectstack-ai#37437** (closed card objectstack-ai#37922's bullet) is not added twice.
- **Check Changeset** will be red: this docs-only PR publishes nothing
from any package, the `skip-changeset` case, and the dispatch opens it
without labels, so that label is the seat's to apply.

## Verification

Read first, by risk: the method paragraph and header (`index.mdx` lines
6-47), the 自动迁移 intro, then the new 需手动处理 → Knowledge block.

Two-minute check: `git show
6eb23c8:.changeset/pre/37851-disabled-holder-own-row-publish-rollback-refused.md
| head -12` shows the `fix(metadata-protocol)!` summary and the BREAKING
banner behind the objectstack-ai#37948 line; `npm view @objectstack/spec dist-tags`
prints `{ latest: '18.6.0', next: '19.0.0-next.2' }`.

<details><summary>Local gate readings at b03fd5f</summary>

```
dispatch-gates --commands at b03fd5f: 52 commands (1 path changed)
first pass: 47 exit 0; 5 exit 3/1 = PREREQUISITE NOT MET (lint, spec, client-react unbuilt), re-run after building the closures under os-verify-lock (VERDICT command-exit 0 both):
  pnpm --filter '@objectstack/lint...' build ; pnpm --filter '@objectstack/client-react...' build
final: 52 of 52 :: exit 0
✓ dispatch-gates --ran: 52 derived famil(ies) accounted for — 52 run, 0 NOT-MEASURED (a DERIVED zero — all 52 recorded an exit code and none of them is 3).
check-release-page-status: OK — 3 GA major(s) in scope (v16, v17, v18)
```

</details>

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

https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE

<!-- signed: repo:objectstack#3 · os-steve ·
session_01ADHkmRar3Kkg6SpwVgaaVE -->

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.

knowledge: what a knowledge_source saved at run time does on a deployment that mounted no knowledge service (split from #37306 item 4)

3 participants