Skip to content

fix(knowledge-turso)!: Test connection comes with the Turso fields it checks; the group text drops the cloud fallback - #37982

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

os-zhuang merged 9 commits into
mainfrom
claude/area-o1C-37907

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 #37907
Fixes #37680

Clause-②: yes (narrowing)
Metadata-protocol: none
Skills-docs: none — no skill under skills/** teaches the Knowledge page's test action, knowledgeTestActionHandler or the Turso group's text.

维护者速读

  • 用户能看到什么变化:PostgreSQL 部署的知识设置页上不再有「测试连接」按钮;用 Turso 存储的部署里,按钮跟 Turso 字段放在一起,说明文字不再提云版按组织复用数据库,改为说明留空即用数据目录里的 knowledge.db。
  • 为什么做:知识检索设置的复审收尾,让按钮只出现在它检查的字段旁边,并改正一句与实际不符的说明(云版事实已由云席位核实)。
  • 出错会怎样:只影响设置页上的按钮和说明文字,不改任何已存数据;可直接撤回本次合并。
  • 要你做什么:无。

What changes

  • N1 (Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907). The test action_button and knowledgeTestActionHandler move from @objectstack/service-settings (manifest declaration, handler, package export) and @objectstack/service-knowledge (registration) into @objectstack/knowledge-turso's settings contribution. The button is now the last entry of the Turso group, right after turso_auth_token, and contributeKnowledgeTursoSettings registers the handler only where it adds the group. So:
    • no knowledge-turso, or knowledge-turso given its own url/client: the page has no Test connection, and POST /api/settings/knowledge/test answers 400 SETTINGS_ACTION_FAILED (no handler registered), the same envelope as an action no page declares;
    • knowledge-turso reading its URL from settings: the action is on the page and answers the Turso form check with 200, as before.
    • The label moved too: out of the eleven service-settings bundles (settings.knowledge.actions.test), into knowledgeTursoSettingsTranslations, same strings, all 11 locales in step.
    • @objectstack/service-settings no longer exports knowledgeTestActionHandler; @objectstack/knowledge-turso does (plus KNOWLEDGE_TURSO_TEST_ACTION and two structural types). The migration line is in the changeset.
  • N2 (Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907). KnowledgeTursoPlugin.init() warns once when contributeKnowledgeTursoSettings returns false under opensFromSettings(), naming the consequence (nothing can be saved there, the store opens its default file, path given) and the fix. The function now answers whether the page carries BOTH Turso keys, so a host page declaring one group id without the keys also warns.
  • N3 (Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907). content/docs/ai/knowledge-rag.mdx (the Settings → Knowledge bullet) now gives the tidy-up for a PostgreSQL deployment that saved the two Turso keys, naming the sys_secret row the turso_auth_token row's handle points at. The card's else-branch: the 37678 note is no longer pending (see below).
  • Knowledge settings: verify or correct the Turso group's cloud per-organization fallback sentence #37680, folded. The Turso group description: the English fallback loses "In a cloud deployment with a database per organization, leave blank to reuse that organization's own database connection." (no deployment does that: cloud fact 7217205358 on Knowledge settings: verify or correct the Turso group's cloud per-organization fallback sentence #37680), and every locale loses the "On PostgreSQL ... these fields are not read" clause (the group is never shown on PostgreSQL). Each now says "Leave blank to use knowledge.db in the data directory." in its language, 11 locales plus the fallback, in step. Written without backticks around knowledge.db because the page renders the string as plain text.
  • content/docs/ai/knowledge-rag.mdx says Test connection comes with the two fields.

No changeset correction

The 37678 note (PR #37902) was consumed by main's version pass (#37661): it now lives at .changeset/pre/37678-knowledge-turso-settings-group.md and its text is published in the 19.0.0-next.1 CHANGELOG sections of @objectstack/knowledge-turso and @objectstack/service-settings. Earlier heads of this PR edited its tidy sentence as a DELIBERATE CORRECTION of a pending note; contract record 7224029827 (S2) showed that edit no longer reaches any reader before the stable cut and would keep the whole 19.0.0-next.1 section at that cut. This head leaves the consumed note byte-identical to main and puts the sys_secret clause on the docs page instead, as card #37907 routes it for a note that is no longer pending. The two published CHANGELOG entries are release-owned and are not touched here. This PR's own note is .changeset/37907-knowledge-turso-test-connection.md (patch on the three packages, one ADR-0087 marker, BREAKING paragraph for three readers).

Tests

See the report on #37907 for the run log at the final head. New and moved pins:

  • packages/plugins/knowledge-turso/src/__tests__/settings-contribution.test.ts (real LiteKernel, real settings service and HTTP door, real knowledge service): no-store page has no action_button and the test door answers the undeclared-action envelope (control: never_declared); store-from-settings page carries turso, turso_url, turso_auth_token, test in front and the door answers 200 where the control is 400; own-url page has no action; copy carries the action label in 11 locales and the settings bundle no longer does; the description pin (PostgreSQL named once, knowledge.db named, no cloud or "not read" clause, in the fallback and 11 locales); the handler unit pins moved from service-settings; the N2 pins (no settings service and a host page with test but no keys each warn once; a contributed page and an own-url store say nothing).
  • service-settings: the manifest declares no action_button; the retired-keys pin now asserts the no-handler envelope against an undeclared control, and its re-registration case keeps a stub handler.
  • service-knowledge: the mounted page has no test and its door answers as an undeclared action.

Acceptance notes

  • knowledgeTestActionHandler leaving @objectstack/service-settings' entry is a removed export of a published package; the dispatch order and the card name the handler's move, and the changeset carries the FROM/TO import line. Flagged for the seat with the narrowing.
  • The manifest version stays 5: an action_button carries no key, and the spec's bump rule is about keys.

Verification

Two-minute check: pnpm --filter @objectstack/knowledge-turso exec vitest run src/__tests__/settings-contribution.test.ts — every describe green, including "has no Test connection" and "answers Test connection with the Turso check".

Read first: packages/plugins/knowledge-turso/src/settings-contribution.ts (contributeKnowledgeTursoSettings: registration order and the new both-keys return), packages/plugins/knowledge-turso/src/plugin.ts (init() warn), .changeset/37907-knowledge-turso-test-connection.md.

🤖 Generated with Claude Code

https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP

…rn on no contribution; group description

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
@github-actions github-actions Bot added size/l 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 3 package(s): @objectstack/knowledge-turso, @objectstack/service-knowledge, @objectstack/service-settings, touching 18 documentable anchor(s). ⚠️ 2 changed file(s) yielded no anchor (packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

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

  • content/docs/ai/knowledge-rag.mdx (via KnowledgeTursoPlugin (symbol, a top-level class), turso_auth_token (literal, a string literal in contributeKnowledgeTursoSettings), turso_url (literal, a string literal in contributeKnowledgeTursoSettings), /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/deployment/cli.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/deployment/environment-variables.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/deployment/self-hosting.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/permissions/authentication.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/protocol/kernel/config-resolution.mdx (via action_button (literal, a string literal in knowledgeTursoSettingsSpecifiers; a string literal in specifiers), /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/protocol/kernel/error-handling.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/protocol/knowledge.mdx (via KnowledgeTursoPlugin (symbol, a top-level class))
  • content/docs/ui/actions.mdx (via registerAction (symbol, a method of interface SettingsRegistry))

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

  • content/docs/releases/v14.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/releases/v17/17-7.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/releases/v18/18-4.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))
  • content/docs/releases/v18/18-6.mdx (via /api/settings (route, a path literal in knowledgeTursoSettingsSpecifiers))

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
  • 2 changed file(s) yielded no anchor (packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts) — pages documenting those are invisible to this run
  • 7 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 — 12 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 f72f335393f40e27194c56911e6de46052cb6f4c → packageMentionDocs.

Which tree this was computed on

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

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

⚠️ 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 f72f335393f40e27194c56911e6de46052cb6f4c → pass the list as
args.docs, on the commit named under Which tree this was computed on.

…owledge page a real boot has

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · head 9509b99 · 2026-11-27T16:48Z

@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: 9509b9972d4163de0bbfdd28605ae10e6eaaae15
Local-runs: none
Security-touching: no
Scope: packages/plugins/knowledge-turso/src/settings-contribution.ts, packages/plugins/knowledge-turso/src/plugin.ts, packages/plugins/knowledge-turso/src/index.ts, packages/plugins/knowledge-turso/src/tests/settings-contribution.test.ts, packages/plugins/knowledge-turso/src/tests/plugin.test.ts, packages/services/service-knowledge/src/knowledge-settings-contribution.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts, packages/services/service-settings/src/manifests/knowledge.manifest.ts, packages/services/service-settings/src/manifests/knowledge.manifest.test.ts, packages/services/service-settings/src/knowledge-settings-retired-keys.pin.test.ts, packages/services/service-settings/src/settings-default-action-handlers.pin.test.ts, packages/services/service-settings/src/translations/{ar,de,en,es-ES,fr,ja-JP,ko,pt-BR,ru,zh-CN,zh-Hant}.ts + read, not reviewed: packages/services/service-settings/src/settings-service.ts (registerManifest, registerAction, runAction, resetNamespaceRows, the orphaned-secret note), packages/services/service-settings/src/settings-routes.ts (the action door), packages/services/service-settings/src/settings-action-copy.ts, packages/plugins/knowledge-turso/src/plugin.ts outside the hunk (readStoreSettings, resolveStoreUrl, defaultStoreUrl, start, openFromSettings), packages/platform-objects/src/system/sys-secret.object.ts and sys-platform-setting.object.ts (apiMethods), .changeset/config.json, AGENTS.md (Post-Task Checklist step 3), .claude/skills/pm-dispatch/references/{contract-review,execution-duties,security-findings}.md; the two changesets and content/docs/ai/knowledge-rag.mdx are read for ② and for the DELIBERATE CORRECTION.

Inputs read: card #37907 (body, 4 comments, the claim 7217144305 and the dev report 7223647773 included), folded card #37680 (body, 6 comments, the cloud fact 7217205358 and the claim 7217241951 included), PR #37982 (body, 2 comments, 27 files, net diff against the merge base 73d5e34), the 54 check-runs on the head, the log of the failed first attempt of Test Core (8/10), and for context the record 7215949880 on PR #37902.

① Derived judgments

  • Accept-set, the narrowing. POST /api/settings/knowledge/test answers 400 SETTINGS_ACTION_FAILED wherever knowledge-turso does not add its group. RIGHT, and measured rather than asserted: runAction finds no handler and returns the no-handler answer, the route maps ok: false to that envelope, and three suites pin it against an undeclared control action (never_declared) at the HTTP door: the no-store block and the own-url block in knowledge-turso, the retired-keys pin in service-settings, and the mounted-service block in service-knowledge. The base manifest at head declares chunk_target alone and no action_button.
  • Where the action still answers. RIGHT. contributeKnowledgeTursoSettings registers the manifest with the group, then the handler, in that order (registerAction refuses an unregistered namespace; registerManifest carries the namespace's earlier handlers, so rebuild and index_status survive). The store-from-settings block pins the page order turso, turso_url, turso_auth_token, test and a 200 where the control is 400.
  • Handler registered only where the group is added. RIGHT as written: the one registerAction('knowledge', 'test', ...) left in the tree outside tests is inside if (composed !== page). service-knowledge registers none; the settings plugin's default map registers none (pin updated). One consequence is S1.
  • Handler body. RIGHT: moved byte for byte in behaviour (same merge of stored values under the payload, same three answers, same extractOverrides). The declared type changed from SettingsActionHandler to a local structural pair; it stays assignable (TypeScript Type Check green, and the kernel test registers it on the real service).
  • Boot warning (N2 of the card). RIGHT in the two cases the card asks for: init() warns once when the function answers false under opensFromSettings(), and stays silent for a contributed page and for a store with a url of its own (four pins). The both-keys return is stricter than before and correct for its purpose. The line's consequence clause is not true in every case it fires; see N2.
  • Public surface. @objectstack/service-settings loses knowledgeTestActionHandler (both src/index.ts and src/manifests/index.ts); @objectstack/knowledge-turso gains knowledgeTestActionHandler, KNOWLEDGE_TURSO_TEST_ACTION, KnowledgeTursoActionInput, KnowledgeTursoActionResult. No file in the tree at head still imports the removed name from service-settings: git grep finds it only in knowledge-turso's source and test, one comment in the default-handlers pin, the two changesets and three CHANGELOG entries. No doc page, skill, example or app names it, and nothing under packages, ui, apps or examples calls the door except the button's own declaration.
  • The eleven locale edits, label. RIGHT. Each service-settings bundle loses exactly the three lines of settings.knowledge.actions.test and nothing else; the eleven removed labels equal the eleven added to knowledgeTursoSettingsTranslations, string for string. No key is orphaned: the only other actions.test in those bundles is the SMS page's.
  • The eleven locale edits, description (Knowledge settings: verify or correct the Turso group's cloud per-organization fallback sentence #37680). RIGHT and consistent. The cloud per-organization sentence is gone from the fallback (it was in no locale). Every locale and the fallback lose the "on PostgreSQL ... not read" clause and gain one sentence saying blank uses knowledge.db in the data directory; each names PostgreSQL once. The new sentence is true against the code: a blank turso_url reads as unset in readStoreSettings and resolveStoreUrl then opens defaultStoreUrl, which is knowledge.db in dataDirectoryOf. The dropped sentence is false per the cloud fact 7217205358, which this record takes as the card's governing reading and did not re-measure.
  • Manifest version stays 5. RIGHT: an action button carries an id and no key, and the spec's bump rule speaks of keys.
  • Gate verdicts. 37 success, 15 skipped, 1 failure, 1 in progress. The failure is Check Changeset, judged in ②. The one in progress is Test Core (8/10), judged in ③; this record does not stand in for its conclusion.

② Semver level

  • The declaration. Clause-②: no (narrowing) is right for the two things the PR body and the dispatch worry about: an export removed from a published entry and a door that now refuses are both narrowings, and neither makes the line a yes. Read strictly it under-declares one thing: the criterion is "widens the accept set or enlarges the public surface", the surface is what the built entry reaches, and knowledge-turso's entry reaches four new names. The exact spelling for a diff that does both is Clause-②: yes (narrowing). Nothing downstream differs between the two: both land on the narrowing face at this tier, both are Tier H at the queue guard, and the level is patch either way. The record 7215949880 accepted five additive exports under the same spelling on PR fix(knowledge-turso)!: the Knowledge page's Turso fields are contributed by the store that reads them #37902. Recorded as N1, the seat's call.
  • Level. patch on @objectstack/knowledge-turso, @objectstack/service-settings and @objectstack/service-knowledge. RIGHT under AGENTS.md: Metadata-protocol: none takes patch, and "a non-protocol change, widening or breaking, ships patch and keeps its BREAKING banner and ADR-0087 disposition". All three packages publish a changed source file. A removed export at patch is this repository's stated rule, not an oversight; the three packages are in the fixed group at 19.0.0-next.0.
  • Declared where it must be. The ! is in the PR title and the changeset's first line; both declaration lines are line-initial in both carriers and agree; the BREAKING paragraph is there; exactly one ADR-0087 marker, not-required (no-migration-prescription), and its reason holds (a settings manifest and its handlers are runtime registrations).
  • FROM/TO. Present and correct for the two readers it names: the script author is told the answer and to stop calling; the importer is given the one-line import from @objectstack/knowledge-turso. "Same check, same answers" is true. A third reader is missing: S1. A smaller omission is N5.
  • Check Changeset red, the DELIBERATE CORRECTION. This is the correction class, not a collision: .changeset/37678-knowledge-turso-settings-group.md is pending on the merge base, the PR body declares the edit and quotes before and after, and the PR's own note has its own issue-scoped name. One sentence changes, judged clause by clause:
    1. "delete the knowledge rows named turso_url and turso_auth_token, and the sys_secret row the turso_auth_token row's handle names". TRUE: an encrypted key's row holds a handle in value_enc and the ciphertext sits in sys_secret.
    2. "without the store no API door clears that key". TRUE on this head: a write naming the key is refused as undeclared; the built-in reset walks only the keys the page declares (resetNamespaceRows iterates getNamespace values); and the data API serves sys_secret and sys_platform_setting with get and list only.
    3. "the row is a decryptable copy of the token". TRUE, and it is the settings service's own wording for an orphaned row.
    4. "nothing requires it". TRUE: no reader exists where the store is not mounted.
      The PR body's "no other sentence of that note is made false by this diff" holds under the reading 7215949880 used (a note describes its own step); see N3 for the one sentence that needs that reading. With this record at PASS the correction is confirmed once S1 is closed; the gate stays red by design and no gate is changed.

③ Boundary flags

  • open_questions. None raised.
  • Deviation: Knowledge settings: verify or correct the Turso group's cloud per-organization fallback sentence #37680 folded. Accepted: same file, same group, both claims on the cards, both Fixes lines on the PR; the description edits are judged in ①.
  • Deviation: the removed export, taken as ordered. Accepted. The card says to move the button and its registration into knowledge-turso; the handler body has to follow, because knowledge-turso has no runtime dependency on service-settings and service-settings cannot depend on knowledge-turso without closing a cycle through service-knowledge. A copy left behind in service-settings would be an export nothing registers.
  • Deviation: no backticks around knowledge.db in the twelve strings. Accepted: the page renders descriptions as plain text.
  • Deviation: the unexpected file plugin.test.ts. Accepted: its settings fake gains the page a real boot has, so the new warning stays silent there; no assertion is loosened.
  • Deviation: draft PR opened before the local run. Noted; no bearing on this head.
  • out_of_scope: Test Core (8/10). The first attempt failed on six knowledge-turso cases, each "Test timed out in 5000ms": two in acceptance.test.ts, two in contract.test.ts, one in plugin.test.ts (the url option wins), one in settings-contribution.test.ts (a URL saved during the boot). The report's sentence that none asserts anything this diff changed needs one qualification: two of the six sit in files this diff edits, and the last runs through the new registration. Neither case's own lines changed, the first takes neither new path (a url of its own returns from init() early), and the four others are in untouched files; the run shows import 57s and transform 36s for a 65s package run, which reads as runner load. The re-run is in progress at the time of this record. Its conclusion is the gate verdict, not this paragraph.
  • Security. The action door is gated exactly as before: runAction asserts the namespace's write permission before it looks for a handler, so the move changes no permission. This diff puts no secret value into an answer, a remedy or a log line: the handler never returns the token, the new warning names a file path only, and the no-handler answer names the action and namespace. The diff changes no authentication, authorization or secret-handling behaviour, hence the machine line above. One observation about code this diff moves unchanged goes to the seat privately and is not written here; the dev report's security field reads withheld and was not available to this review.
  • SQL push-down (Prime Directive 5). Nothing to find: no query, no id materialisation, no in-app join.

④ Design judgment

The narrowing makes the settings contract's standing refusal real and takes no delivered capability away. The capability is a form check of two fields. Where the two fields are on the page because their one reader put them there, the check is beside them and answers as before. Where they are not, the check read nothing that deployment reads and opened no connection, and its door now gives the answer every action without a handler gets. That is "delivered where read, retired where not", decided by the party that knows whether it reads the keys, the same shape PR #37902 gave the fields themselves.

Tried to break it:

  • Registration order: the handler goes on after the manifest, and the re-registration keeps rebuild and index_status. Held.
  • A settings service without registerAction: the function now answers false and adds nothing, and init() says so. Within the fixed version group this cannot occur.
  • A deployment where the group is contributed but the check is not: none; one branch does both.
  • The reverse, a page that carries the fields and a test button with no handler: reachable. S1.
  • A host page whose own action is named test: N4.
  • The copy load: settings.knowledge.actions.test arrives through the same deep-merging load as the rest of the group; the settings bundle no longer carries the path, pinned in both directions.
  • Truth of the warning in each case it fires: N2.

S1 (should-fix) — a host that registers its own knowledge page declaring both Turso keys and the test button, between the knowledge service's init() and this plugin's, now has a dead button with no line saying so. withKnowledgeTursoSection returns that page untouched, the handler is registered only inside if (composed !== page), the function answers true (both keys present) so no warning fires, and POST /api/settings/knowledge/test answers the no-handler 400. On main the knowledge service registered the handler for that page. The pending note of PR #37902 promises this very host that it "keeps that manifest as written", and neither BREAKING bullet of the new note covers it: the first speaks of deployments where the fields are not on the page, the second of importers. No composition in this repository does this, so the reach is a host outside it. Close it on either face: a third BREAKING bullet ("a host whose own knowledge page declares the test action registers knowledgeTestActionHandler from @objectstack/knowledge-turso itself"); or register the handler when the page left as written declares the action and both keys, with a pin. The prose route is enough and moves no code.

Nits (none affects correctness or the contract):

N1 — the declaration's strict spelling is Clause-②: yes (narrowing), for the four names knowledge-turso's entry gains (see ②). Same face, same tier, same level. Fix on the PR body and the changeset line, or leave it with the precedent of 7215949880 named.

N2 — the warning's consequence clause ("nothing can be saved there and the store opens its default file") is false in two of the cases it fires for. With no knowledge service mounted the store never opens at all, and start() already warns about that separately. With a host page that declares turso_url but not turso_auth_token, the URL can be saved and the store opens the saved URL. The changeset repeats the clause. The remedy the line gives is right in every case. Accepted deviation or follow-up.

N3 — the pending 37678 note says the plugin "loads the same strings, in the same eleven locales"; after this PR the eleven descriptions differ from the ones that note moved. Both notes ship together and the new one says what changed, so it reads true as that note's own step. Left as is.

N4 — the collision test in withKnowledgeTursoSection now includes the generic id test. A host page with its own test action and no Turso keys gets no Turso fields, where on main it got them; the store then cannot be pointed anywhere from the page. It is warned and pinned, and no released version had the fields contributed, so nothing shipped regresses. Accepted deviation.

N5 — the import line sends a service-settings consumer to a package it may not have installed, one whose dependency is a native libSQL client (the entry imports that client as a type only, so the import itself loads nothing native). One clause in the changeset would say so. The two structural types duplicate service-settings' own on a permanent surface.

N6 — the report's account of the six timeouts is slightly too broad (see ③). No action on the tree.

Implemented-by: claude/area-o1C-37907
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3 (isolated sub-agent)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

L1 verdict (L1-a): REWORK at head 9509b9972d4163de0bbfdd28605ae10e6eaaae15 (Fixes #37907, Fixes #37680, folded). Full read · 2026-11-27T16:57Z

席位核对

Contract review. Record 7223849938 at this head is PASS at the contract tier (verify-review-tier PASS) and carries one graded finding, S1. The queue guard reads S1 as open on this head, so the PR cannot go to the seat until a delta record closes it. I adopt the record.

What the next head needs.

  • S1. A host that registers its own knowledge page, declaring both Turso keys and the test button, ahead of this plugin's init() now has a Test connection button that answers the no-handler 400, and nothing logs that. The smallest fix the record accepts is prose only: a third BREAKING bullet in .changeset/37907-knowledge-turso-test-connection.md. It should say that such a host now registers the knowledge / test handler itself, and give the FROM/TO. If the area would rather close it in code (register the handler for that page too, or warn), it needs a pin case.
  • Optional, nits from the record. N2: the boot warning's consequence clause is false in two of its four cases, the one with no knowledge service and the one with turso_url but no token. Fix it in the same commit if the head moves anyway. N1 to N6 otherwise stand as accepted deviations.

Rulings on the area's questions.

  • Declaration. Clause-②: no (narrowing) stands. The removed knowledgeTestActionHandler export and the new 400 are both narrowings. The four names knowledge-turso's entry gains are additive, and record 7215949880 accepted the same spelling on fix(knowledge-turso)!: the Knowledge page's Turso fields are contributed by the store that reads them #37902 (N1). patch on all three packages is right, and the banner, the !, both declaration lines and the ADR-0087 marker are present. No file at this head imports the removed export.
  • DELIBERATE CORRECTION. The rewritten 37678 sentence is true clause by clause against the code (record ②). So the Check Changeset red is the deliberate-correction class, confirmed by an at-tier PASS on the same head.
  • Test Core (8/10). The re-run is still in progress at this reading. The six 5000ms timeouts are file: URL cases. Two of them sit in files this diff edits, but no line of either case changed. Read with the import and transform times, it looks like runner load. The next head needs a green Test Core like any other.
  • Dogfood. It is owed on the narrowing, and the dev reports the full battery green. It has to be re-pinned on the next head.

Next: a new head, then a delta L2 on S1 (and N2 if touched), then a delta L1, then the seat's Tier H handoff.

… (contract review S1, N1, N5)

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · head 7add85f · 2026-11-27T16:58Z

@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: 7add85f4bc2cd68ae93ea5e3253a3df1403772f6
Local-runs: none
Security-touching: no
Scope: every path of the diff outside the prose faces, unchanged since 9509b9972d and carried from record 7223849938: packages/plugins/knowledge-turso/src/settings-contribution.ts, packages/plugins/knowledge-turso/src/plugin.ts, packages/plugins/knowledge-turso/src/index.ts, packages/plugins/knowledge-turso/src/tests/settings-contribution.test.ts, packages/plugins/knowledge-turso/src/tests/plugin.test.ts, packages/services/service-knowledge/src/knowledge-settings-contribution.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts, packages/services/service-settings/src/manifests/knowledge.manifest.ts, packages/services/service-settings/src/manifests/knowledge.manifest.test.ts, packages/services/service-settings/src/knowledge-settings-retired-keys.pin.test.ts, packages/services/service-settings/src/settings-default-action-handlers.pin.test.ts, packages/services/service-settings/src/translations/{ar,de,en,es-ES,fr,ja-JP,ko,pt-BR,ru,zh-CN,zh-Hant}.ts + read, not reviewed, for this delta: packages/plugins/knowledge-turso/src/{index,plugin,turso-adapter,sql,settings-contribution}.ts (their import statements) and package.json, packages/services/service-settings/src/settings-service.ts (registerAction, registerManifest), packages/services/service-settings/src/settings-service.types.ts (SettingsActionHandler), packages/spec/src/system/settings-manifest.zod.ts (SettingsActionResultSchema); .changeset/37907-knowledge-turso-test-connection.md is read for ② and for the finding it answers.

Delta of record 7223849938 (head 9509b9972d), which stays the full review. The net change since that head is one file, .changeset/37907-knowledge-turso-test-connection.md (4 lines added, 3 removed); no code path moved, so ①, ③ and ④ of that record stand as written and are not repeated. Inputs read for this round: that one-file diff, the rewritten PR body, the files named above at the new head, and the check-runs on both heads.

① Derived judgments

Unchanged: no path outside the prose faces moved. Each new sentence of the changeset, against the code at this head:

  • "the public surface grows by four exports of @objectstack/knowledge-turso (listed below)". TRUE: src/index.ts adds KNOWLEDGE_TURSO_TEST_ACTION, knowledgeTestActionHandler and the types KnowledgeTursoActionInput and KnowledgeTursoActionResult, and the note's "New exports" paragraph lists the same four.
  • "BREAKING for three readers". TRUE: three bullets follow.
  • "@objectstack/knowledge-turso depends on the native libSQL client (@libsql/client)". TRUE: it is under dependencies in the package's package.json, not optional.
  • "importing the handler loads nothing native". TRUE. The entry re-exports from four modules. turso-adapter.ts and plugin.ts import @libsql/client with import type only; the one runtime load is the await import('@libsql/client') inside openClient, reached when a store is opened. settings-contribution.ts imports two types and nothing else; sql.ts imports nothing. The static runtime imports of the whole entry are Node built-ins, @objectstack/spec/contracts and the package's own modules.
  • "installing the package installs that dependency". TRUE, same line of package.json.
  • "A host that registers its own knowledge settings page declaring turso_url, turso_auth_token and the test action: KnowledgeTursoPlugin leaves that page as written and registers no handler for it". TRUE: withKnowledgeTursoSection returns the manifest itself when it declares any of the group's ids, and the only registerAction call in the package sits inside if (composed !== page).
  • "so its test button now answers 400 SETTINGS_ACTION_FAILED". TRUE for a host that registers no handler of its own: runAction returns the no-handler answer and the route maps it to that envelope. The knowledge service no longer registers one.
  • "Register the handler yourself after registering the page: settings.registerAction('knowledge', 'test', knowledgeTestActionHandler)". TRUE. The signature is registerAction(namespace, actionId, handler). "After" is the safe order: the call throws for a namespace not yet registered, and a later registerManifest of the same namespace keeps its handlers. The handler is assignable to SettingsActionHandler, read from the two declarations: its input is a subset of the handler input (values, optional payload), and its answer (ok, message, severity of info, warning or error) fits SettingsActionResult. One correction to record 7223849938: no typed call in the tree hands this handler to the real service's registerAction (the contribution reaches it through a local structural interface), so that assignability is read here, not shown by the type-check gate.
  • PR body. The declaration line now reads Clause-②: yes (narrowing) and agrees with the changeset. The rest of the body is unchanged in substance; its sentence "BREAKING paragraph with the import move" undersells the note by one reader and is not false.

② Semver level

  • The declaration. Clause-②: yes (narrowing) on both carriers, line-initial, with the widening half named (four exports) and the narrowing half unchanged. This is the exact spelling for a diff that does both. N1 of record 7223849938 is answered.
  • Level. patch on the three packages, unchanged and still right: Metadata-protocol: none, and a non-protocol change, widening or breaking, ships patch with its banner.
  • Migration text. Now complete for the readers this diff reaches: the script author, the importer (with the dependency it brings, which answers N5), and the host with its own page (with the one call that restores its button).
  • ADR-0087 marker, banner, the !. Unchanged and present.
  • Check Changeset. Still the DELIBERATE CORRECTION class by design; the edit to the pending 37678 note did not move in this round, and its four clauses were judged true in record 7223849938. With this record at PASS and no graded finding open, that correction is confirmed.

③ Boundary flags

  • Gate verdicts at this head. None yet: the check-runs endpoint returned zero runs for 7add85f4bc at 17:00Z, about two minutes after the push. This record reads no gate on this head and does not stand in for any; landing waits for them. The change is one changeset file, so the gates that can differ from the prior head are the changeset and prose ones.
  • Gate verdicts at the prior head. As in record 7223849938: 37 success, 15 skipped, Check Changeset red by design, and Test Core (8/10) still in progress on its re-run at 17:00Z.
  • Security. Nothing in this round touches a permission, a secret or a log line. The new bullet tells a host to register a form check behind the same write permission every settings action has.
  • SQL push-down. Nothing to find.
  • No new dev flag or open question arrived with this head.

④ Design judgment

Unchanged from record 7223849938: the narrowing makes the settings contract's standing refusal real and takes no delivered capability away. The one hole found there, a host page that carries the fields and the button with no handler behind it, is now stated in the migration text with its one-line remedy. That is the prose route the earlier record named as sufficient: the plugin leaving a host page exactly as written is the documented behaviour, and the host now knows what that costs and how to restore it.

S1 (should-fix): closed

No must-fix, no should-fix.

Nits carried from record 7223849938, none affecting correctness or the contract:

N1 — answered on both carriers (see ②).

N2 — the warning's consequence clause is still untrue in two of the cases it fires for; not worse on this head. Accepted deviation.

N3 — left as is.

N4 — accepted deviation.

N5 — answered (see ①).

N6 — no action on the tree.

Implemented-by: claude/area-o1C-37907
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3 (isolated sub-agent)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · head 6c858a1 · 2026-11-27T17:02Z

@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: 6c858a106ce5d46f4ce2b3caecbee92a5ba8632e
Local-runs: none
Security-touching: no
Scope: every path of the net diff outside the prose faces, byte-identical to the set reviewed in record 7223849938: packages/plugins/knowledge-turso/src/settings-contribution.ts, packages/plugins/knowledge-turso/src/plugin.ts, packages/plugins/knowledge-turso/src/index.ts, packages/plugins/knowledge-turso/src/tests/settings-contribution.test.ts, packages/plugins/knowledge-turso/src/tests/plugin.test.ts, packages/services/service-knowledge/src/knowledge-settings-contribution.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts, packages/services/service-settings/src/manifests/knowledge.manifest.ts, packages/services/service-settings/src/manifests/knowledge.manifest.test.ts, packages/services/service-settings/src/knowledge-settings-retired-keys.pin.test.ts, packages/services/service-settings/src/settings-default-action-handlers.pin.test.ts, packages/services/service-settings/src/translations/{ar,de,en,es-ES,fr,ja-JP,ko,pt-BR,ru,zh-CN,zh-Hant}.ts + read, not reviewed, for this delta: .github/workflows/release.yml (the pending count and its pre-mode rule), scripts/changeset-changelog.mjs (the stable cut's fold, foldPrereleaseSections), scripts/release-pending-publish.mjs and scripts/check-empty-changeset.mjs (how each reads .changeset/pre/), .changeset/pre.json, .changeset/config.json, AGENTS.md (Documentation Guardrails, the packages/*/CHANGELOG.md row), packages/plugins/knowledge-turso/CHANGELOG.md and packages/services/service-settings/CHANGELOG.md (the 19.0.0-next.1 section), packages/plugins/knowledge-turso/src/turso-adapter.ts (its imports, moved by main), content/docs/ai/knowledge-rag.mdx; .changeset/pre/37678-knowledge-turso-settings-group.md and .changeset/37907-knowledge-turso-test-connection.md are read for ② and for the finding below.

Second delta of record 7223849938 (head 9509b9972d, the full review), after the delta 7223949181 (head 7add85f4bc). This head is a merge of origin/main (c2103f664d, 49 commits) into 7add85f4bc, with no author commit. Inputs read for this round: the net diff against the new merge base compared with the net diff the earlier records judged, the release tooling named above, the two published CHANGELOG sections, the PR body, and the check-runs on this head.

① Derived judgments

  • (a) The net diff is the same diff. RIGHT. Compared hunk for hunk (index and position lines aside), the net diff against c2103f664d equals the net diff of 7add85f4bc against its own base in 26 of 27 files, code and tests included. The one difference is a path: the hunk that edited .changeset/37678-knowledge-turso-settings-group.md now edits .changeset/pre/37678-knowledge-turso-settings-group.md, same before and after text. Every judgment of records 7223849938 and 7223949181 on the code, the locales, the new changeset and its sentences therefore stands on this head.
  • What main moved under the cited code. Nothing those judgments rest on. Between the two merge bases main changed nothing under packages/services/service-settings/src, and nothing in knowledge-turso or service-knowledge that registers a settings page or action. It did change turso-adapter.ts; its @libsql/client import is still import type, so "importing the handler loads nothing native" still holds.
  • (b) What the merge did to the corrected note. Main's version pass (30a8047bad, chore: version packages (next) (#37661)) consumed the note: it moved the file into .changeset/pre/ and wrote its text, with the OLD stored-values sentence, into the 19.0.0-next.1 section of packages/plugins/knowledge-turso/CHANGELOG.md and packages/services/service-settings/CHANGELOG.md. The note is no longer pending. Read from the tooling:
    1. In pre mode a file under .changeset/pre/ is consumed and skipped: release.yml counts only .changeset/*.md as pending unless the mode is exit, and says the version pass skips the rest. No further prerelease cut reads the corrected copy, so every 19.0.0-next.N tarball keeps the old sentence in its CHANGELOG.
    2. On changeset pre exit the stable cut applies every consumed changeset again, so the stable 19.0.0 section will carry the corrected sentence. That is the first place a reader sees it.
    3. On that same cut the fold in scripts/changeset-changelog.mjs drops a prerelease section only when every entry in it is found, text for text, in the new stable section. The 19.0.0-next.1 entry will hold the old sentence and the stable entry the new one, so the whole 19.0.0-next.1 section is kept, with a warning, in both packages: every entry of that prerelease duplicated under the stable section.
      So the correction is not lost, but it reaches nobody until the stable cut, and it arrives with a side effect on two CHANGELOGs. Graded as S2.
  • Does this PR owe the same correction on the two CHANGELOG lines? No, and it may not make it: AGENTS.md marks packages/*/CHANGELOG.md release-owned, never edited in a code PR, and sends a correction of a released entry to a dedicated docs-only PR that amends that entry. The old sentence is an omission (it names two rows and not the third), not a false statement.
  • Gate verdicts. 42 check-runs on this head at the last read (about 17:08Z): 12 success, 15 skipped, 14 in progress, 1 failure. The failure is Check Changeset. It is red on the edit to the consumed note, and this record does not confirm that edit as a correction of a pending note (see ②), so on this head that red is not covered by any record; closing S2 by route (2) removes the edit it is red on. The type-check, lint, build and test jobs were still running. This record does not stand in for any gate that had not finished.

② Semver level

  • Declaration and level. Unchanged from record 7223949181: Clause-②: yes (narrowing) on both carriers, patch on the three packages, banner, one ADR-0087 marker. The three packages are now at 19.0.0-next.1; the new note .changeset/37907-knowledge-turso-test-connection.md is pending and will be consumed by the next prerelease cut, so its text reaches the prerelease reader as written.
  • The DELIBERATE CORRECTION. The class is a correction of a PENDING note. On this head the note is consumed and its sentence is published in a prerelease CHANGELOG, so the confirmation the two earlier records gave no longer describes what is on the tree, and this record does not renew it. The four clauses of the corrected sentence are still true against the code. The PR body still says the note is "not yet released" and names its old path; both are stale.

③ Boundary flags

  • Card Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907, item N3. The card routes this itself: add the clause "on the changeset if still pending, else on content/docs/ai/knowledge-rag.mdx". The first branch held on the two earlier heads and does not hold on this one. The docs page at this head does not name the sys_secret row. The acceptance line "the tidy text names the sys_secret row" is therefore met only in a consumed file. Part of S2.
  • Security. Nothing in the merge touches a permission, a secret or a log line in the PR's own diff. The sentence at issue is hygiene advice about a stored credential's row; where it is published is a release-text question, judged above.
  • SQL push-down. Nothing to find.
  • No new dev flag or open question arrived with this head.

④ Design judgment

Unchanged from record 7223849938: the narrowing makes the settings contract's standing refusal real and takes no delivered capability away. The merge moved none of the code that judgment was made on.

S2 (should-fix) — the sys_secret clause now lands only on a consumed changeset. Edited there, it reaches no reader before the stable cut, leaves the published 19.0.0-next.1 entries of two packages with the old sentence, and makes the stable cut's fold keep the whole 19.0.0-next.1 section in both CHANGELOGs; meanwhile the card's own else-branch (the docs page) is not taken. Close it on the prose faces, in this PR: (1) add the clause to content/docs/ai/knowledge-rag.mdx, as the card says for a note that is no longer pending; (2) restore .changeset/pre/37678-knowledge-turso-settings-group.md to main's bytes, so this PR no longer edits a consumed note; (3) rewrite the PR body's DELIBERATE CORRECTION section to say so. The two published CHANGELOG entries are not this PR's to touch: if the seat wants them amended, that is a dedicated docs-only PR that changes both entries and the consumed copy to the same text in one stroke, which also keeps the fold whole.

Nits carried from records 7223849938 and 7223949181, none affecting correctness or the contract:

N2 — the warning's consequence clause is untrue in two of the cases it fires for; not worse on this head. Accepted deviation.

N3 — the consumed note's "loads the same strings" sentence; left as is, and now published.

N4 — accepted deviation.

N6 — no action on the tree.

Implemented-by: claude/area-o1C-37907
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3 (isolated sub-agent)

VERDICT: PASS

…e consumed 37678 note is left as main has it (contract review S2)

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

L1 verdict (L1-a): REWORK at head 6c858a106ce5d46f4ce2b3caecbee92a5ba8632e (a merge of origin/main into 7add85f). Delta read · 2026-11-27T17:07Z

席位核对

Contract review. Delta record 7224029827 at this head: PASS at the contract tier (verify-review-tier PASS), with one new graded finding, S2, which the queue guard reads as open.

What changed under the PR. Main's chore: version packages (next) (#37661) consumed .changeset/37678-knowledge-turso-settings-group.md into .changeset/pre/, and its old stored-values sentence is now published in the next-prerelease CHANGELOGs of knowledge-turso and service-settings. The merge carried the N3 correction onto the consumed copy. No further prerelease reads that copy. The stable cut would re-apply it, and because the two sentences now differ, the fold would keep the whole 19.0.0-next.1 section duplicated. So the DELIBERATE CORRECTION class no longer applies (it covers pending notes), and the Check Changeset red on this head is not by design.

Next head, prose only:

  1. Restore .changeset/pre/37678-knowledge-turso-settings-group.md to main's bytes.
  2. Put the sys_secret clause (the token's sys_secret row, which no API door clears without the store) on content/docs/ai/knowledge-rag.mdx. Card Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907 N3 routes it there once the note is no longer pending.
  3. Rewrite the PR body's DELIBERATE CORRECTION section, which still says "not yet released" and names the old path.

Amending the two published CHANGELOG entries is release-owned (AGENTS.md) and goes in a separate docs-only PR if wanted, not this one.

Next: a new head, a delta L2 on S2, green CI including Check Changeset, a delta L1, then the seat's Tier H handoff.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · head 29ed1f4 · 2026-11-27T17: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: 29ed1f480f28045e33c0de6c8441ea81e1178f3b
Local-runs: none
Security-touching: no
Scope: every path of the net diff outside the prose faces, byte-identical to the set reviewed in record 7223849938: packages/plugins/knowledge-turso/src/settings-contribution.ts, packages/plugins/knowledge-turso/src/plugin.ts, packages/plugins/knowledge-turso/src/index.ts, packages/plugins/knowledge-turso/src/tests/settings-contribution.test.ts, packages/plugins/knowledge-turso/src/tests/plugin.test.ts, packages/services/service-knowledge/src/knowledge-settings-contribution.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts, packages/services/service-settings/src/manifests/knowledge.manifest.ts, packages/services/service-settings/src/manifests/knowledge.manifest.test.ts, packages/services/service-settings/src/knowledge-settings-retired-keys.pin.test.ts, packages/services/service-settings/src/settings-default-action-handlers.pin.test.ts, packages/services/service-settings/src/translations/{ar,de,en,es-ES,fr,ja-JP,ko,pt-BR,ru,zh-CN,zh-Hant}.ts + read, not reviewed, for this delta: .changeset/pre/37678-knowledge-turso-settings-group.md at this head, at the merge base and at origin/main (blob ids), and the code the new docs sentence speaks of, as read for record 7223849938 (packages/services/service-settings/src/settings-service.ts: the write gate, resetNamespaceRows, the orphaned-secret note; packages/platform-objects/src/system/sys-secret.object.ts and sys-platform-setting.object.ts: apiMethods), none of which main has moved since; content/docs/ai/knowledge-rag.mdx is read for the finding it answers.

Third delta of record 7223849938 (head 9509b9972d, the full review), after the deltas 7223949181 (head 7add85f4bc) and 7224029827 (head 6c858a106c). Since 6c858a106c one author commit changed two files, both on the prose faces. Inputs read for this round: that two-file diff, the net diff against the merge base c2103f664d compared with the net diff record 7224029827 judged, the rewritten PR body, and the check-runs on this head.

① Derived judgments

  • The consumed note is main's again. RIGHT. .changeset/pre/37678-knowledge-turso-settings-group.md has the same blob id (0fb95aa2f3) at this head, at the merge base and at origin/main; the net diff no longer lists the file. This PR edits no consumed changeset and no published CHANGELOG.
  • The net diff is otherwise the same diff. RIGHT. With that file and the docs page set aside, the net diff against c2103f664d equals the one record 7224029827 judged, hunk for hunk, in the remaining 25 files; the net diff is now 26 files. Every judgment of the earlier records on the code, the tests, the locales and .changeset/37907-knowledge-turso-test-connection.md stands on this head. Main has since moved to bf810f5a40 without touching service-settings src, knowledge-turso, service-knowledge src, the docs page or the consumed note.
  • The new docs sentences, against the code. The Settings and Knowledge bullet of content/docs/ai/knowledge-rag.mdx gains four sentences:
    1. "A PostgreSQL deployment that saved the two Turso keys before the group left the page keeps their rows; the settings service never deletes a stored row." TRUE in the sense the page uses it: no code path removes the row of a key the page no longer declares, which the retired-keys pin holds (turso_url kept and unserved without the store).
    2. "To tidy it up, delete the knowledge rows named turso_url and turso_auth_token, and the sys_secret row the turso_auth_token row's handle names". TRUE: an encrypted key's row holds a handle and the ciphertext sits in sys_secret.
    3. "without the store no API door clears that key, and the row is a decryptable copy of the token". TRUE: a write naming the key is refused as undeclared, the built-in reset walks only declared keys, the data API serves both tables with get and list only, and "decryptable copy" is the settings service's own wording for an orphaned row.
    4. "Nothing requires it." TRUE: nothing reads either key where the store is not mounted.
      The sentence sits beside the statement that on PostgreSQL the page shows none of the three, which is where a reader with such rows arrives.
  • Card Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907, item N3. Met by the card's own else-branch: the note is no longer pending, and the clause is on content/docs/ai/knowledge-rag.mdx. The acceptance line "the tidy text names the sys_secret row" holds on a page a reader sees now.
  • PR body. The DELIBERATE CORRECTION section is replaced by "No changeset correction", which says what the tree shows: the consumed note is byte-identical to main, the clause is on the docs page, the two published CHANGELOG entries are release-owned and untouched. Its N3 bullet says the same. Accurate.
  • Gate verdicts. 46 check-runs on this head at 17:10Z: 14 success, 17 skipped, 14 in progress, 1 cancelled, none failed. Check Changeset is success: with no edit to a note this PR did not add, the gate has nothing to be red on, and no by-design red remains on this PR. The cancelled run is an earlier PR-body guards run superseded by a later one that is success. Build, type-check, lint and the test planner were still running; this record does not stand in for any gate that had not finished.

② Semver level

Unchanged from record 7223949181: Clause-②: yes (narrowing) on both carriers, patch on the three packages, the BREAKING paragraph with its three readers, one ADR-0087 marker. The PR's one changeset is its own pending note, which the next prerelease cut consumes as written. No correction of another note is claimed any more, so nothing of that class is left to confirm.

③ Boundary flags

  • Published 19.0.0-next.1 entries. They keep the shorter tidy sentence, as release-owned text this PR may not edit. It is an omission, not a false statement, and the docs page now carries the full sentence. Amending the two entries and the consumed copy together in a dedicated docs-only PR remains open to the seat; nothing here depends on it.
  • Security. Nothing in this round touches a permission, a secret or a log line. The new sentence is hygiene advice about a stored credential's row, in the words the pending note already used.
  • SQL push-down. Nothing to find.
  • No new dev flag or open question arrived with this head.

④ Design judgment

Unchanged from record 7223849938: the narrowing makes the settings contract's standing refusal real and takes no delivered capability away. Nothing since has moved the code that judgment was made on. The one release-text question the merge raised is settled the way the card routes it, with no edit to a consumed note and no side effect on the stable cut's fold.

S2 (should-fix): closed

No must-fix, no should-fix.

Nits carried from the earlier records, none affecting correctness or the contract:

N2 — the warning's consequence clause is untrue in two of the cases it fires for; not worse on this head. Accepted deviation.

N3 — the consumed note's "loads the same strings" sentence; published as is.

N4 — accepted deviation.

N6 — no action on the tree.

Implemented-by: claude/area-o1C-37907
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3 (isolated sub-agent)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

L1 verdict (L1-a): ACCEPT (delta) at head 29ed1f480f28045e33c0de6c8441ea81e1178f3b (Fixes #37907, Fixes #37680, folded), after REWORK 7223867469 and 7224065063. Delta read · 2026-11-27T17:34Z

席位核对

Gates. Check-runs at 29ed1f4: 41 success, 17 expected skip, 0 failed. The one cancelled row is a superseded PR-body guards run, and its re-run passed. Check Changeset is green, so no by-design red remains. Mergeable state is clean.

Contract review. Delta record 7224135133 at this head: PASS at the contract tier (verify-review-tier PASS). It closes S2 and ends No must-fix, no should-fix. The earlier deltas 7223949181 (S1 closed) and 7224029827 led here, and the code is unchanged since 9509b99. I adopt it.

l1-face items. Fixes #37680 is the intended fold. dogfood is owed at this head: the full battery ran green at 9509b99, and no code has moved since. Re-pinning it to this head is the seat's call at handoff.

Not owed here. The two published 19.0.0-next.1 CHANGELOG entries keep the shorter stored-values sentence. Amending them is release-owned and goes in a separate docs-only PR, if wanted.

Landing: narrowing, so it goes through the seat's Tier H handoff.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Seat record · 2026-11-27T17:36Z · PR #37982 (Fixes #37907, Fixes #37680) · head 29ed1f480f28045e33c0de6c8441ea81e1178f3b · Clause-②: yes (narrowing) — lands as Tier H

维护者速读

  • 做什么:知识库设置页里 Turso 的「测试连接」按钮跟着 Turso 那组字段一起出现:没装 Turso 插件的页面不再显示这个按钮,直接调用测试接口会被拒(400);Turso 分组的说明文字去掉了已经不存在的「云端兜底」说法。
  • 风险:26 个文件 +471/−295,集中在 knowledge-turso、service-settings、service-knowledge 三个包和 11 个语言文件;对外是一处收窄(没有 Turso 分组时测试接口回 400),以及导出 knowledgeTestActionHandler 从 service-settings 搬到 knowledge-turso,升级说明写了搬家前后的位置。
  • 要你做什么:审批人批准即可,契约审核 PASS(记录 7223849938,末次增量 7224135133),Head-sha 29ed1f480f28045e33c0de6c8441ea81e1178f3b;批准后座位自主落地。
  • 不批会怎样:没装 Turso 的项目仍会看到一个点了必然失败的「测试连接」按钮,分组说明仍在讲一个已经撤掉的兜底。

Seat opinion: land.

席位核对 — ACCEPT · repo:objectstack#1 · head 29ed1f480f

  1. Shape. Draft, base main, 26 files (+471/−295): the Turso settings contribution now owns the Test connection action (knowledge-turso/src/settings-contribution.ts, plugin.ts, index.ts + tests), the static knowledge manifest drops it (service-settings/src/manifests/knowledge.manifest.ts, index.ts, pins, 11 translation files), service-knowledge group text, one docs sentence, new .changeset/37907-knowledge-turso-test-connection.md (patch on the three packages, with FROM/TO for the moved export and a host-page BREAKING bullet). Body: Clause-②: yes (narrowing), Metadata-protocol: none. check-governed-merges.mjs --pr 37982: no governed path; the narrowing declaration routes it the Tier H way.
  2. Premise measured. Per the records: POST /api/settings/knowledge/test answers 400 where the Turso group is not on the page, and the action and its handler arrive with the group; Knowledge settings: verify or correct the Turso group's cloud per-organization fallback sentence #37680 is the intended fold. Card acceptance met.
  3. Gates (check-runs at this head). 41 success, 17 skipped, 0 failed; the one cancelled row is a superseded PR-body guards run whose re-run passed. mergeable clean.
  4. Accepted deviations. Dogfood battery ran green at 9509b997 (490 files, 4144 tests). Since then the PR's own commits are a changeset/docs edit (7add85f4, 29ed1f48) and a clean main merge (6c858a10); no PR code moved, so the seat accepts it without a re-pin.
  5. Out of scope → where it went. The two published 19.0.0-next.1 CHANGELOG entries keep the shorter stored-values sentence: optional docs follow-up, area o1-C. Skills-docs: none (no skill teaches this action). Security-touching: yes, conservatively: the moved action reads the Turso connection settings; this diff adds no new credential, permission or auth path. Tier H path either way.
  6. Landing terms. L1-a delta ACCEPT 7224571000 + contract review PASS record 7223849938 with deltas 7223949181, 7224029827, 7224135133 (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-②: yes (narrowing) (Tier H) · PR #37982 (Fixes #37907, Fixes #37680) · head 29ed1f480f28045e33c0de6c8441ea81e1178f3b

@os-zhuang — the Knowledge page's Turso "Test connection" action now ships with the Turso fields it checks: a page without the Turso group has no such action, and POST /api/settings/knowledge/test answers 400 there. knowledgeTestActionHandler moves from @objectstack/service-settings to @objectstack/knowledge-turso (FROM/TO in the changeset), and the group text drops the retired cloud fallback. Records on this head: L1-a ACCEPT 7224571000, contract review PASS 7223849938 (last delta 7224135133, CONTRACT_REVIEW_TIER), 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.

@objectstack-fleet objectstack-fleet Bot added the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Nov 27, 2026
@os-zhuang

Copy link
Copy Markdown
Contributor

我批准了,你改完可以自主落地

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Queue red: cause and fix · new head b1ef64de44

Cause. Deterministic, not load. Main's 0ea3093e (#38033, embedderSettings) added a pin to packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts ("the knowledge page, its test button and its Setup entry are offered as before") that compared knowledge/test with knowledgeTestActionHandler imported from @objectstack/service-settings. This PR moves that export to @objectstack/knowledge-turso. Git merged the two textually: the import line went away with this PR, and the call site stayed, so the queue build failed with ReferenceError: knowledgeTestActionHandler is not defined (queue builds 46088679290 and 46088707850).

Fix (test-only, commit 7ff81fbb2f).

  • service-knowledge: the pin keeps its intent. With embedderSettings: false, the knowledge page equals the default mount's page and keeps its one Setup entry. knowledge/test now answers exactly as on the default mount, and as an undeclared action. That is judged against a never_declared control (ok + severity), never by message text. service-knowledge cannot import knowledge-turso, which depends on it.
  • knowledge-turso: a new top-level describe in settings-contribution.test.ts checks the button where it now lives. With knowledge-turso reading from settings beside a knowledge service mounted with embedderSettings: false, the page carries turso, turso_url, turso_auth_token, test in front and equals the default-mount page. The test door answers 200 with the Turso check (it names the URL it was sent), where the undeclared control answers 400.
  • No other importer remains. In packages/, the symbol appears outside knowledge-turso only in one doc comment and in released CHANGELOG text. None of the four open PRs that overlap this one adds a line using it.

Merge. 9a1f257402 merged main 815e882be9. b1ef64de44 merged main f72f335393 (after #37963 and #37971). Both merged cleanly: no conflict, no regen-pending artefact, no change beyond the merge.

Verification at b1ef64de44, under scripts/pm/os-verify-lock.sh (one locked run, VERDICT command-exit 0):

  • closure build (@objectstack/knowledge-turso... and @objectstack/service-knowledge...): exit 0
  • RED: the test file as merged, before the fix (blob b9a3069e22): Tests 1 failed | 36 passed (37), ReferenceError: knowledgeTestActionHandler is not defined
  • GREEN: the same file at HEAD gives 37/37. knowledge-turso settings-contribution.test.ts gives 27/27.
  • full vitest: service-knowledge 19 files / 646 tests, service-settings 78 / 1535, knowledge-turso 4 / 247, all passed
  • typecheck: service-knowledge (tsc plus test-layer check, which compiles this test file), service-settings and knowledge-turso: exit 0
  • overlap-check: VERDICT clean exit 0 against main and 4 PR heads (at 7ff81fbb2f, before the second merge)

Contract: none touched. The change is two test files. No published schema, export, changeset or governed rule text changes, and the PR body is unchanged.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

CI reading · 2026-11-28T02:10Z · head b1ef64de44 · Test Core (2/10) (job 140826194773) is a flake

The shard's tests ran to completion green: the log reads "Attested: test-2-of-10 ran to completion with every step green (run 46095431003, attempt 1)". The only error is the next step, actions/upload-artifact, failing with Failed to CreateArtifact: Unable to make request: ECONNRESET. That is a network fault on the artifact upload, and it measured nothing about this PR. The seat re-runs the failed job once when the run completes. A second failure counts as real.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Seat record addendum · 2026-11-28T04:06Z · PR #37982 · head b1ef64de44 · lands as Tier H

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

  1. Shape. Since the hand-off head 29ed1f480f: one test-only commit 7ff81fbb2f (two test files: knowledge-turso/src/__tests__/settings-contribution.test.ts, service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts) and two clean main merges (9a1f257402, b1ef64de44). PR body unchanged.
  2. Premise. The queue reds (builds 46088679290, 46088707850) were this PR meeting main's 0ea3093e (feat(service-knowledge): a plugin option keeps the embedder section off the ai settings page #38033): a pin there still called the export this PR moves. Cause and fix are recorded in 7232005283.
  3. Gates (check-runs at this head). 40 success, 15 skipped, 0 failed, after the one re-run of Test Core (2/10) recorded in 7232190655 (an artifact-upload ECONNRESET, tests green). landing-k: OK. Dogfood battery on this head: os-dev-report 7233678248 on Review follow-ups of PR #37902: the Knowledge page's Test connection button moves with the Turso fields it checks #37907 (490 files, 4144 tests, no failures).
  4. Accepted deviations. None. The service-knowledge pin keeps its intent and is judged against the default mount and an undeclared-action control. The relocated Test connection is pinned in knowledge-turso. No refusal or assertion is weakened.
  5. Out of scope. Unchanged from the seat record 7224601315.
  6. Landing terms. os-zhuang APPROVED head 7ff81fbb2f (review 6094972364) and wrote 7231892784 「我批准了,你改完可以自主落地」. The move from there to b1ef64de44 is a clean main merge only. Seat 1 lands it under the maintainer's seat-thread line 2026-11-26T13:33Z 「审批人批准后的 Tier H PR 你可以自主落地」.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Correction to the seat record 7233707059 · 2026-11-28T04:07Z

Item 3 says landing-k: OK. That reading (K = 2) is from 2026-11-28T02:33Z. Re-read at 2026-11-28T04:06Z, just before this landing, it said MERGE MAIN FIRST (K = 24 ≥ 15), and the seat armed the pull anyway. That is the seat's slip, not the area's. The queue builds this pull on top of current main with the full suite, so a semantic conflict shows up there. If that build fails on this pull's own change, the seat dequeues it, and area o1-C merges main and comes back through the seat.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract-review-claim: session_016WV4czzx9dtSEm3jWWL9c3 · b1ef64d · 2026-11-28T04:34Z

@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: b1ef64de442a994555ffb1d1f429fa9e35e441d6
Local-runs: none
Security-touching: no
Scope: every path of the net diff outside the prose faces, the same set reviewed in record 7223849938, byte-identical to it except the two test files this delta names: packages/plugins/knowledge-turso/src/settings-contribution.ts, packages/plugins/knowledge-turso/src/plugin.ts, packages/plugins/knowledge-turso/src/index.ts, packages/plugins/knowledge-turso/src/tests/settings-contribution.test.ts, packages/plugins/knowledge-turso/src/tests/plugin.test.ts, packages/services/service-knowledge/src/knowledge-settings-contribution.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-settings/src/index.ts, packages/services/service-settings/src/manifests/index.ts, packages/services/service-settings/src/manifests/knowledge.manifest.ts, packages/services/service-settings/src/manifests/knowledge.manifest.test.ts, packages/services/service-settings/src/knowledge-settings-retired-keys.pin.test.ts, packages/services/service-settings/src/settings-default-action-handlers.pin.test.ts, packages/services/service-settings/src/translations/{ar,de,en,es-ES,fr,ja-JP,ko,pt-BR,ru,zh-CN,zh-Hant}.ts + read, not reviewed, for this delta: what main moved between the two merge bases under packages/services/service-knowledge/src (knowledge-settings-contribution.ts, knowledge-service-plugin.ts: the embedderSettings option and the call that passes it), packages/plugins/knowledge-turso/src (turso-adapter.ts and sql.ts: their imports), packages/core/src/capability-composition.ts (the knowledge token and the store's mount), packages/spec/src/migrations and packages/spec/src/conversions (the entries main added or edited), .changeset/knowledge-embedder-settings-switch.md, .changeset/pre/37678-knowledge-turso-settings-group.md (blob ids), content/docs/ai/knowledge-rag.mdx; .changeset/37907-knowledge-turso-test-connection.md and the PR body are re-read against the moved code.

Fourth delta of record 7223849938 (head 9509b9972d, the full review), after the deltas 7223949181 (head 7add85f4bc), 7224029827 (head 6c858a106c) and 7224135133 (head 29ed1f480f). Since 29ed1f480f, first-parent: a merge of origin/main 815e882be9 (9a1f257402), one author commit that touches two test files (7ff81fbb2f), and a merge of origin/main f72f335393 (b1ef64de44). The merge base moved from c2103f664d to f72f335393, 40 commits of main. Inputs read for this round: card #37907 with its 5 comments (the second dev report 7233678248 included), PR #37982 with its body and 23 comments (the queue triage 7231378347, the cause-and-fix note 7232005283 and the seat's records 7233707059 and 7233721737 included), the two merges recomputed, the net diff against each base, the author commit, the two test files in full at this head, and the check-runs on this head.

① Derived judgments

  • The net diff is the same diff, apart from the two test files. RIGHT. The net diff against f72f335393 lists the same 26 paths as the net diff of 29ed1f480f against c2103f664d. Compared hunk for hunk (index and position lines aside), 23 files are identical. content/docs/ai/knowledge-rag.mdx differs only in a context line main rewrote two bullets below ("Without a source or the token"); the one removed and the one added line are the same text. The other two are the test files of the author commit. Every judgment of the earlier records on the code, the locales, the docs sentences and .changeset/37907-knowledge-turso-test-connection.md therefore stands on this head.
  • Neither merge resolved a conflict. RIGHT, measured: a fresh three-way merge of each merge's two parents gives the tree the merge commit carries (359285e27a for 9a1f257402, 447dd0e9a7 for b1ef64de44), and the remerge diff of each is empty. No hunk of this PR was changed by hand in a merge.
  • Why the author commit exists. A semantic conflict the textual merge could not see, and the cause-and-fix note 7232005283 states it as the tree shows it. Main's 0ea3093eb2 (feat(service-knowledge): a plugin option keeps the embedder section off the ai settings page #38033, embedderSettings) added a pin to the service-knowledge settings test that called knowledgeTestActionHandler; this PR's hunk in the same file removes that import. At 9a1f257402 the file still holds the call at its line 186 and no import. 7ff81fbb2f replaces that one assertion. This is the queue red the triage 7231378347 reported on that test title.
  • The service-knowledge edit pins what it claims. RIGHT. With embedderSettings: false the test still asserts that the knowledge page is listed, that its manifest equals the default mount's, and that it has exactly one Setup entry; those three lines are main's and are untouched. The replaced assertion now holds knowledge/test to two things: the whole answer equals the default mount's answer, and its ok and severity equal those of never_declared on the same kernel. The second is not vacuous: for the empty input the test sends, the Turso check answers ok: true, info, where the no-handler answer is ok: false, so a handler registered there turns it red.
  • Is the moved assertion judged by the control, never by message text? Yes. No line of it matches, contains or quotes a message string. One comparison is whole-answer equality between two real mounts, the other compares ok and severity with an undeclared control. The title changed from "its test button" to "its actions", which is what the page there has.
  • The knowledge-turso edit pins what it claims. RIGHT. boot gains a third parameter that defaults to an empty object and is spread after the two fixed options, so every earlier call builds the same kernel. The new describe mounts knowledge-turso reading from settings beside a knowledge service with embedderSettings: false: the page's first four ids are turso, turso_url, turso_auth_token, test, its manifest equals the default mount's, and the door answers 200 with ok: true where never_declared answers 400. Its last line asks that the answer name the URL the test itself sent; that is an echo of the input, the same discriminator the store-from-settings block has used since the full review, and it sits beside the control, not in place of it.
  • No earlier pin is weakened. RIGHT. Against 29ed1f480f the knowledge-turso test differs by the author commit and nothing else (25 cases then, 27 now, none removed or edited). In the service-knowledge test the only assertion the commit removes is main's, which names an export this PR retires and cannot hold. The pins the earlier records counted are byte for byte as judged: the mounted-service block (no test on the page, the never_declared control, ok: false) and the HTTP block (400 SETTINGS_ACTION_FAILED beside the control, the sent URL absent from the answer).
  • What main moved under the cited code. Nothing those judgments rest on.
    1. packages/services/service-settings is untouched between the two bases: runAction, registerAction, registerManifest, resetNamespaceRows, the routes, the manifest and the eleven bundles are as read.
    2. knowledge-settings-contribution.ts gains an options argument that gates the ai embedder section only. Its knowledge branch is as before, and this PR's hunk (no test registration) applies to it unchanged. Main's own comment and its pending note .changeset/knowledge-embedder-settings-switch.md say the knowledge page and "its actions" are unchanged by the option, which stays true with this PR.
    3. knowledge-turso: plugin.ts, settings-contribution.ts and index.ts are not touched by main. turso-adapter.ts and sql.ts are (hybrid search, the drop during a build); the @libsql/client import of turso-adapter.ts is still import type, and sql.ts still imports nothing, so "importing the handler loads nothing native" holds.
    4. capability-composition.ts: a stack that ships a knowledge source now mounts the knowledge service without requires, and the service is told the deployment's adapter id. Which store is mounted, and that the Turso store is mounted with urlFromSettings: true, did not move, so the changeset's "where the store does not contribute its group" still names the same deployments.
    5. The semantic migration entries: main added one and edited one, both about knowledge source registration and publish, and added an action-locations conversion. None names the settings action, the handler or the Turso keys. The marker not-required (no-migration-prescription) and its reason stand.
    6. Release text: .changeset/pre/37678-knowledge-turso-settings-group.md is still blob 0fb95aa2f3 at this head and at origin/main. .changeset/config.json, .changeset/pre.json, scripts/changeset-changelog.mjs, .github/workflows/release.yml and AGENTS.md did not move. The published-defect reads of records 7224029827 and 7224135133 (the consumed note, the two 19.0.0-next.1 entries, the docs page as the card's else-branch) stand as written.
  • No other importer arrived. At this head knowledgeTestActionHandler appears outside knowledge-turso only in this PR's changeset, one consumed changeset, one comment in the default-handlers pin and CHANGELOG text. No file main added in the 40 commits imports it.
  • PR body. Unchanged and still accurate for the tree. Its Tests section does not list the new pin; the note 7232005283 does.
  • Gate verdicts. 55 check-runs on this head at 04:37Z: 40 success, 15 skipped, none failed, none in progress. Check Changeset is success. The seat's reading 7232190655 records one re-run of Test Core (2/10) after an artifact-upload fault; the conclusion read here is the re-run's.

② Semver level

Unchanged from record 7223949181: Clause-②: yes (narrowing) on both carriers, patch on the three packages, the BREAKING paragraph with its three readers, one ADR-0087 marker. The author commit changes no published file: two test files, no export, no accepted input, no changeset. The PR's one changeset is its own pending note, byte for byte the one judged.

③ Boundary flags

  • Main beyond the merge base. origin/main as fetched is 28 commits past f72f335393. Two touch the paths read here: 9d111a7f52 (chore: version packages (next) #38032, a version pass: the three packages go to 19.0.0-next.2, CHANGELOG and package.json only) and 6e06729a9b (fix(service-knowledge): a recycle-bin restore re-indexes its rows on a kernel with no realtime service #38067, record hooks in service-knowledge, no settings code). A trial merge of this head with that main is clean, holds no new use of the removed export, and leaves this PR's note pending under .changeset/, to be consumed by the cut after next.2. This is a reading of what the queue will build, not a gate; the queue's full suite is the verdict there, as the seat's correction 7233721737 says.
  • Dev report 7233678248. No open question, no deviation, no out-of-scope finding, security_findings: none. Nothing to route.
  • Security. The delta touches no permission, no secret and no log line. The two test files drive the action door as an administrator, as before.
  • SQL push-down. Nothing to find.

④ Design judgment

Unchanged from record 7223849938: the narrowing makes the settings contract's standing refusal real and takes no delivered capability away. This round is that design meeting a feature main added in the meantime, and it held without a code change: an option that switches off the embedder section of the ai page leaves the Knowledge page alone, so the Turso group and its check are there exactly when the store adds them, with the option on or off. The two test edits say that from both sides, each package pinning what it owns: service-knowledge that it offers no such action either way, knowledge-turso that its action answers either way.

No must-fix, no should-fix.

Nits, none affecting correctness or the contract:

N2 — the warning's consequence clause is untrue in two of the cases it fires for; not worse on this head. Accepted deviation.

N3 — the consumed note's "loads the same strings" sentence; published as is.

N4 — accepted deviation.

N6 — no action on the tree.

N7 — the header comment of the service-knowledge settings test (line 7) still says a kernel that mounts the service offers "both test actions"; since this PR it offers one, and the cases below say so. Carried from the full-review head, not introduced by this delta. A comment only; fix when the file is next touched.

Implemented-by: claude/area-o1C-37907
Reviewed-by: session_016WV4czzx9dtSEm3jWWL9c3 (isolated sub-agent)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Reconciling the approval head in seat record 7233707059 · 2026-11-28T04:40Z

Review 6094972364 (os-zhuang, APPROVED) was submitted at 2026-11-28T01:44Z, when the head was 7ff81fbb2f. The seat's read at 2026-11-28T01:45Z showed that commit_id. The reviews API now reports b1ef64de44 for the same review id: the approval was not dismissed, and GitHub reports it against the current head after the clean main merge. Both readings are of one approval, and it stands on the queued head b1ef64de44.

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 28, 2026
@os-zhuang
os-zhuang added this pull request to the merge queue Nov 28, 2026
Merged via the queue into main with commit bbd9733 Nov 28, 2026
83 of 85 checks passed
@os-zhuang
os-zhuang deleted the claude/area-o1C-37907 branch November 28, 2026 06:04
@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
…eg merged with the vector leg by RRF (objectstack-ai#38037)

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

Clause-②: no
Metadata-protocol: none

## 维护者速读
- 用户能看到什么变化:在知识检索里搜订单号、型号(如
X-200)、人名或「出差」这类短词时,含这些词的段落会排进结果,之前只靠语义向量常被排到前几名之外。
- 为什么做:知识平台总卡下的检索质量子卡,让元数据开发平台上任何知识源(不只制度库)都能按精确词找到内容。
- 出错会怎样:检索结果的排序和分数会变;关键词一路出错时最坏是排序变差或检索报错,权限复核不受影响,撤回本次合并即可恢复原样。
- 要你做什么:无。

## What changes

Both open knowledge stores now search with two legs and merge them by
reciprocal rank fusion (RRF, k = 60, each leg ranks at most `topK`)
inside the adapter, so before the knowledge service re-checks each hit
as the caller.

- **Terms.** The query is split at white space and punctuation; a
hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it
whole (`X-200`, `v1.2`, `a/b`), at most 16 terms. A passage's keyword
score is the sum, over the terms it holds, of the term's BM25 inverse
document frequency among the rows in scope (binary term frequency), so a
word most passages hold weighs little. Keyword ties are ranked by cosine
distance, and fused ties go to the better vector rank, so the keyword
leg never reorders by chunk id what the vector leg ranks.
- **knowledge-turso.** A term of three characters or more is one quoted
FTS5 phrase (an inner double quote doubled), so `X-200` is never FTS5
syntax. It is matched in a contentless trigram FTS5 table beside each
passage table (`TABLE-fts`), keyed through a map table (`TABLE-kw`, an
INTEGER PRIMARY KEY, so a VACUUM cannot renumber it) and kept in step by
three triggers on the passage table (insert, delete, update of
`chunk_id` or `content`), inside the statement that writes the passage.
A shorter term (「出差」) is matched by `content LIKE` over the rows in
scope. The keyword index is made with the passage table and dropped with
it (generation swap, `completeBuild`, `dropSource`). Its names hold a
hyphen, which no source id, generation table or object name can hold; an
object under one of those names that the store did not make is refused
`SERVICE_UNAVAILABLE`, naming it, and never dropped.
- **knowledge-pgvector.** A word of three characters or more is
`phraseto_tsquery('simple', term)` on `to_tsvector('simple', content)`,
served by a GIN expression index (`knowledge_vec_dWIDTH_content_tsv`):
no column added, no row rewritten. A shorter term, or one holding a Han,
kana or Hangul character, is matched by `content ILIKE`: measured on
PostgreSQL 16, the `simple` parser keeps a run of Han characters as one
word (`'出差住宿标准每晚三百元'`), so a tsvector phrase could never find 「住宿标准」
inside it. Both legs run in one statement (one snapshot), each behind
the existing active-generation guard.
- **One WHERE.** The organization filter, the record scope and the
metadata `filter` are built once and applied in both legs (and in the
inverse-document-frequency counts), before either ranks.
- **An index made before this PR still answers.** turso: the first
search of a passage table without a keyword index builds it from the
table's rows in one write transaction (shape-checked first), then
answers from it. pgvector: the first write or search of a width runs
`CREATE INDEX IF NOT EXISTS`; a concurrent loser re-reads the catalogue
and goes on. Both pinned.
- **Score.** A hit's `score` is now the fused rank normalized to (0, 1]:
1 for first in both legs, 0.5 for first in one alone. It was the cosine
similarity.
- Docs: both READMEs, `content/docs/ai/knowledge-rag.mdx` (retrieval and
both store sections), and the two Search bullets plus the adapter table
of `content/docs/protocol/knowledge.mdx`, which this change made
incomplete (outside the claim's file surface; declared in the report).

**Serial with objectstack-ai#37957.** That card adds a visible-ids pre-filter to the
search options and is not started. Whichever lands second applies its
filter or leg to both legs: here the one `WHERE` (`inScope` in both
adapters) is the single place a new filter goes, and it already feeds
both legs and the counts.

## Read first (by risk)

1. `packages/plugins/knowledge-turso/src/sql.ts` `keywordIndexDdl`: the
triggers and the backfill. A trigger that drifts from the passage table
leaves the contentless index wrong silently (the FTS5 `delete` command
needs the indexed text, which `old.content` holds).
2. `packages/plugins/knowledge-turso/src/turso-adapter.ts`
`searchAttempt`: the shared `inScope` in `vec`, `cand` and `stats`; the
parameter numbering (`?1` is the vector in both legs).
3. `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts`
`searchAttempt` and `ensureKeywordIndex`: the one statement and the
first-search index build.

## Two-minute check

`cd packages/plugins/knowledge-turso && pnpm exec vitest run
--maxWorkers=2 src/__tests__/acceptance.test.ts -t "hybrid search"`
prints 16 passed (8 cases on `:memory:` and on a `file:` URL).

## Tests

<details><summary>New pins (turso: acceptance.test.ts, top-level
describe; pgvector: acceptance.live-postgres.test.ts, top-level
describe)</summary>

- An exact code in a question: the fixture asserts the vector leg alone
ranks the code's passage 7th of 7; the hybrid search returns it within
topK = 3; the code alone answers it first with score 1 (both legs). Both
stores.
- 「出差」 (2 characters) and 「住宿标准」 (inside an unsplit run) hit: turso by
LIKE and the trigram index, score 1; pgvector by ILIKE, score 0.5 (the
fake embedder holds a Han run as one word, so only the keyword leg ranks
them).
- The organization filter, a record scope and the metadata filter each
exclude an out-of-scope passage that holds the query's code and short
term, while the in-scope keyword match still ranks. Both stores.
- turso: every query string tried as FTS5 syntax (`X-200`, `"A"`,
`NEAR(the`, `OR`, `* pump^2`, `col:umn`, `-x`, `a AND b NOT c`) answers;
the keyword index follows a rewrite, a delete, a generation swap and
`dropSource`; a table without a keyword index gets one at its first
search, 7 map rows from 7 passages, and stays in step after; an object
table under `TABLE-kw` refuses the build, naming it, and keeps its row.
- pgvector: the GIN index dropped, a new adapter's first search rebuilds
it and answers; with sequential scans priced out the plan names the
index.
- turso: the term splitter, the LIKE escape and the FTS5 phrase quoting,
as a unit.
</details>

<details><summary>Readings (head d0340b7 for both suites; ablations
on b2d204a before the merge of main, which touched no knowledge
package)</summary>

- `knowledge-turso` `vitest run --maxWorkers=2`: Test Files 4 passed
(4), Tests 201 passed (201).
- `knowledge-pgvector` `vitest run --maxWorkers=2` against a private
PostgreSQL 16 with pgvector (UTF8 database): Test Files 8 passed, Tests
96 passed; `reconcile-purge` and `reindex-real-driver` did not load
(`@objectstack/metadata-protocol` / `@objectstack/objectql` unbuilt
here) — NOT MEASURED locally; neither file calls `search`.
- Ablations, each a mutation on disk, the pin run, restored from HEAD,
the pins green again (turso 16/16, pgvector 4/4):
- keyword leg off (`terms = []`): exact-code pin red in both stores,
"expected [ …(3) ] to include 'Seal kit for model X-200, part 7731.'".
- LIKE fallback off (terms under 3 characters dropped): 2-character pin
red, turso "expected 0.5 to be 1", pgvector "expected [] to deeply equal
[ [ 'zh_short:1', 0.5 ] ]".
- filter dropped from the keyword leg only: scope pin red in both
stores, "expected [ 'kw_scope:out' ] to deeply equal []".
</details>

## Acceptance notes

- **BrightRule eval set: NOT MEASURED.** The `objectstack-ai/brightrule`
repository is not attached to this session (the API answers 403, access
not enabled), and the eval needs a real embedding provider. RRF reorders
the vector leg's results whenever the keyword leg ranks something, so
this is the reading that would show a regression; it belongs to whoever
runs that eval next.
- **Score semantics changed.** `KnowledgeHit.score` from these two
stores is the normalized fused rank, no longer the cosine similarity.
The knowledge service sorts hits across sources by score, so a
deployment mixing these stores with another adapter now compares a fused
rank with that adapter's score. No threshold on `score` exists in the
service today.
- **Cost.** A LIKE or ILIKE term scans the rows in scope (the vector leg
is already an exact scan). In pgvector a common word makes most rows
candidates, and each candidate's tsvector is computed once for the
per-term counts. No CJK word segmentation: a Chinese question without
spaces or punctuation is one term, so the keyword leg finds a code, a
name or a phrase as written and the vector leg answers the meaning.
- **turso uses `ln()`**, an SQLite math function: present in the libSQL
client build (SQLite 3.45.1, measured); a remote Turso server is not
measured.
- **pgvector's first-search index build** blocks writes to that width's
table while `CREATE INDEX` runs, once.

## Verification

<details><summary>Local gate families (dispatch-gates --commands on
d0340b7; lock saturated, so run outside it as check gates
are)</summary>

- 99 derived commands run once each; exit codes captured before any
pipe: 91 exit 0; 7 exit 3 PREREQUISITE NOT MET
(`check:doc-formula-expressions`, `check:doc-security-posture`, spec
`check:skill-examples`, `check:docs-transcript-drift`,
`check:dual-build-cjs-loads`, `check:lean-entry-closure` — each "run a
build first"); `spec check:docs` exit 1 "packages/spec/json-schema is
missing" (a missing generated tree, also nothing measured). These 8 are
NOT MEASURED locally; CI runs them on a built tree.
- `dispatch-gates --ran`: "99 derived famil(ies) accounted for".
- `overlap-check`: VERDICT clean exit 0 against origin/main and the
three open PRs sharing the docs files (objectstack-ai#38026, objectstack-ai#37982, objectstack-ai#37963).
- Typecheck: the packages' own `typecheck` needs the dependency closure
built, and the build never got the verify lock (queued about an hour
behind a dogfood holder) — NOT MEASURED through the package script.
Narrowed instead: `tsc -p` over each package's test config with `paths`
to the workspace sources: knowledge-turso 0 errors; knowledge-pgvector 2
errors, both "Cannot find module '@objectstack/objectql'" in the two
unloaded test files.
</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
…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
…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
…t that mounts the knowledge service (objectstack-ai#38013)

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes objectstack-ai#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 objectstack-ai#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 objectstack-ai#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 objectstack-ai#37306

Held off this branch until objectstack-ai#37306 merged (PR objectstack-ai#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: objectstack-ai#37306 did not touch this file, so `main` still carried
the old text.
- **What objectstack-ai#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 (objectstack-ai#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 objectstack-ai#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 objectstack-ai#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):

<details><summary>Tests and typecheck at 33acf12</summary>

- 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.

</details>

<details><summary>Ablations (one per tested behaviour)</summary>

- **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 cd26e8f, `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 aa50e2e,
`git diff HEAD` empty).
- The docs pages are not ablated.

</details>

<details><summary>Live server (REST door, at dd50936)</summary>

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.

</details>

<details><summary>Gates at 33acf12</summary>

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 objectstack-ai#38043, objectstack-ai#37982 and objectstack-ai#37963.

</details>

<details><summary>Dogfood battery at 33acf12</summary>

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.

</details>

## Acceptance notes

- The note on this PR's first head about objectstack-ai#37306's `400 VALIDATION_ERROR`
arriving at the MCP draft door as `SERVICE_UNAVAILABLE` is obsolete:
objectstack-ai#37306 merged with the MCP door passing `refused.code` through.
- Docs Drift Check (comment 7222797378) is receipted here.
`content/docs/ai/knowledge-rag.mdx` and
`content/docs/protocol/knowledge.mdx` are updated on this branch.
`content/docs/permissions/system-context.mdx` row 46 is re-read and
still true: the refusal is not on the `isSystem` path. The other pages
match on the `SERVICE_UNAVAILABLE` literal only and say nothing about
knowledge sources. The release-owned pages are not edited.
- Contract review 7228262724 (PASS) and L1 7228292666 (REWORK: dogfood
battery only) are receipted here. The battery is recorded in comment
7229739676: green, and the head is unchanged. The review's nits N1 to N5
are left for a follow-up card; none of them is changed on this head.

## 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 objectstack-ai#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](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
… 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>
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/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

3 participants