Skip to content

feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store - #38470

Merged
os-zhuang merged 8 commits into
mainfrom
claude/project-thread-mu3i0t
Nov 29, 2026
Merged

os-zhuang merged 8 commits into
mainfrom
claude/project-thread-mu3i0t

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread

Refs #38369

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: follow-up #38475

维护者速读

  • 自托管部署如果没配嵌入模型(或部署的知识存储没挂上),知识源现在只列出、不构建、不同步、不检索,智能体工具里也不再出现 search_knowledge;启动日志说一次缺了哪一半、怎么补。以前这种部署照样启动构建和同步,工具也列出来,但每次构建和检索都报错。
  • 属于知识库检索这条线,执行您对 ADR-0161 dated note: a mounted knowledge service is enabled by configuration; until then its sources are held and not served #38368 的裁决(四点全按推荐 1A 2A 3A 4A)和 ADR-0161 K8 的日期注记"挂载不等于启用"。这是三单中的第一单:先把"不服务"做实;保存时拒绝(第 2 单)和状态/命令行文字(第 3 单)随后各开一单。
  • 只影响运行时自动挂载知识服务、且缺嵌入模型或知识存储的部署;配齐两半的部署、以及宿主自己挂载知识服务的部署行为不变;从不阻止启动;出问题可整单撤回。
  • 要你做的:批准这次收窄(按审批流程)。

What changes

The authority is the ADR-0161 K8 dated note on item 12 (PR #38401, 0c1b2ff), with ruling 7248214179 (amendment 7248231750, points 1–4) and build notes 7248592159 (points 1–4). This PR is part 1 of the three serial PRs the card names: items 1–2, ruling points 2–3, build notes 1, 2 and 4. Part 2 (the save refusal: item 3, points 1 and 4, build note 3) and part 3 (items 4–5) follow from main after this merges.

  • Enabled by configuration, read once at boot (packages/services/service-knowledge/src/knowledge-service-plugin.ts). The capability composition (packages/core/src/capability-composition.ts) now passes runtimeComposed: { declared } beside deploymentAdapter; declared is true only when the stack lists knowledge in requires. With runtimeComposed set, the plugin reads at kernel:bootstrapped, after every store's start() registered its adapter: an embedder is available (another plugin registered one, or the saved ai.embedder_* settings build one) and the deployment's store is mounted (an adapter of deploymentAdapter's id is registered). Both ⇒ the boot goes on as today. Either missing ⇒ held. A plugin a host mounts (no runtimeComposed) is untouched: it serves from the start, as before.
  • Held (packages/services/service-knowledge/src/knowledge-service.ts, KnowledgeService.settleEnablement). Every source, whichever store it names (point 2: an application-registered store too), is loaded and listed, and never built, synced, reconciled or searched: the boot build, the reload build, the reconcile pass and its job, the record sync (enqueue, upsert, delete and the queued worker), the predicate-write note and the unmounted-adapter report all return. A dropped source keeps its index (a warn line says no store is called). search, rebuildSource and reindexSource throw heldSourcesError: status 503, code SERVICE_UNAVAILABLE, and a message naming the missing half and the fix (build note 2).
  • No reap guard and no store call while not enabled (point 3, build note 1). The lifecycle reap guard used to register at kernel:ready, before the reading; the lifecycle service has no unregister. A runtime-composed plugin now registers it only once the reading says enabled. Held, a retention sweep deletes on time and calls no store.
  • One boot line, never a boot refusal (ADR-0078 §4). info when only a shipped knowledge_source mounted the service and nothing was saved; warn when the stack declares requires: ['knowledge'], when a saved embedder provider builds nothing (a provider saved without its key), or when the store is not mounted. The embedder's own boot line is not also said when held.
  • No tool definition while pending or held (KnowledgeService.knowledgeTools() answers definitions: []). HTTP MCP reads the definitions per request, so it lists search_knowledge only once enabled.
  • stdio (packages/mcp/src/plugin.ts, build note 4). The stdio bridge reads the tool in its own start(), before the reading, so a runtime-composed service hands out nothing there. MCPServerPlugin now registers search_knowledge at kernel:listening (after every kernel:bootstrapped handler) only when the service then hands out its definition. Fail-closed: an unknown state reads as absent, never listed and then withdrawn. The MCP SDK takes a tool after the transport attached and sends notifications/tools/list_changed; skill prompts read the served tools at each listing. A host-mounted service's tool still registers in start(), once.
  • ADR-0087: packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts (notice only, no D2 conversion: the fix is the deployment's configuration, never the item). The changeset carries registered with that id.

Boot window

Between kernel:ready and kernel:bootstrapped the reading is pending. In that window no tool definition is handed out (fail-closed); a record write's sync behaves as today (it embeds through the stand-in embedder, which refuses). Gating starts when the reading settles. No reap guard registers in that window on a runtime-composed plugin.

Point 2 measurement

None of @objectstack/verify's harness.required-providers cases reads as held: every one registers an embedder. The file is unchanged and its 16 cases pass.

Docs

content/docs/ai/knowledge-rag.mdx: a "Mounted is not enabled" bullet under Turning it on (held state, the boot line and its level, the remedy, host-mounted not held), a clause on the "Nothing is configured" embedder bullet, and one sentence under The search_knowledge tool (not listed while held; on stdio registered after the reading, with notifications/tools/list_changed). content/docs/protocol/knowledge.mdx: a "Mounted is not enabled" paragraph after What mounts the service, and the reap-guard section says a runtime-composed service registers no guard until it is read as enabled. Added after sibling #38439 (#38351) merged (f19ee34), with main merged in first. skills/objectstack-ai/SKILL.md is out of scope: follow-up #38475 rewrites its knowledge wording once, from main, after part 3.

Tests

  • packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts, new describe "a runtime-composed knowledge service is enabled by configuration", booted on LiteKernel with a store plugin that counts every call (10 cases): held with no embedder saved (one info line, zero store calls after writes and a delete); no search_knowledge definition, search answers 503 SERVICE_UNAVAILABLE naming the missing half, rebuild refused; requires: ['knowledge'] ⇒ warn; a provider saved without its key ⇒ warn (build note 3's state, read here; its save refusal is part 2); store not mounted ⇒ warn; both halves missing named together; point 2 (an application-registered store is held too); controls: enabled through a host-registered embedder and through saved settings (built, definition handed out); a host-mounted plugin builds as before.
  • packages/services/service-knowledge/src/__tests__/reap-guard.test.ts (point 3, build note 1): held ⇒ registerReapGuard never called and the retention sweep deletes k1, k2 on time with no store call; control: enabled ⇒ the guard registers for ['task'] after the reading and de-indexes before the delete.
  • packages/mcp/src/mcp-knowledge-tools.test.ts (build note 4): HTTP lists the tool only once enabled (pending, held: absent; host-mounted: listed from the start); stdio through MCPServerPlugin with the boot hooks fired by hand: held is never listed and no list_changed is sent; enabled registers at kernel:listening with notifications/tools/list_changed and the same description; host-mounted registers once in start().
  • packages/runtime/src/mcp-knowledge-tools-bridge.test.ts: the runtime bridge reads the definitions per listing (pending and held [], enabled ['search_knowledge']).
  • packages/core/src/capability-composition.test.ts: runtimeComposed: { declared } is passed, declared only when the stack lists the token.
  • scripts/engine-double-contract.pinned.json learns the stdio double's findOne pin (the double routes through assertEngineFindOnePredicate).

Verification

Final head 4659f2a369 (main merged twice since 72a9cbfb6a, for #38439 and #38436; plus the docs commit). At that head, under the lock: closure build exit 0; @objectstack/service-knowledge pnpm test 751 passed; @objectstack/mcp pnpm test 1655 passed; core 26, runtime 7, verify 16 passed; typecheck exit 0 for service-knowledge, core, mcp and runtime; check:engine-double-contract, check:slot-lookup, check-adr-0087-registration (entry at or above PROTOCOL_MAJOR 19), spec check:docs, check:doc-authoring, check-affected-docs, check:adr-anchors exit 0. Dogfood battery at 4659f2a369: VERDICT command-exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · 0 failed. CI at 4659f2a369: 62 check-runs success, 10 skipped, none failed.

The readings below were taken at 72a9cbfb6a and stand where noted. Shared container; every build and test ran through scripts/pm/os-verify-lock.sh.

Tests and typecheck at 72a9cbf
  • Closure build (pnpm --filter '@objectstack/dogfood^...' --filter '@objectstack/cli...' --filter '@objectstack/lint...' build): VERDICT command-exit 0.
  • @objectstack/service-knowledge pnpm test: Test Files 21 passed, Tests 738 passed; typecheck exit 0.
  • @objectstack/mcp pnpm test: Test Files 88 passed, Tests 1655 passed; typecheck exit 0.
  • @objectstack/core capability-composition.test.ts: Tests 26 passed; typecheck exit 0.
  • @objectstack/runtime mcp-knowledge-tools-bridge.test.ts: Tests 7 passed; typecheck exit 0.
  • @objectstack/verify harness.required-providers.test.ts: Tests 16 passed (point 2 measurement above; file unchanged).
  • @objectstack/cli plan.artifact-item-capabilities.test.ts, boot-preparation-parity.test.ts, migrate-meta-engine-guidance.test.ts: Tests 44 passed.
  • @objectstack/spec typecheck exit 0 (migration registry regenerated with the new entry).
  • ESLint over every changed .ts file: exit 0.
Ablation

At 2d6c3dfd (plugin unchanged since): scripts/ablation-replace.mjs replaced const held = this.settleEnablement(ctx, this.service, embedder); with const held = false; void this.settleEnablement;. The runtime-composed describe went 9 failed / 1 passed (the host-mounted control stayed green). Restored; blob back to HEAD, git diff HEAD empty.

Dogfood battery at 72a9cbf

pnpm --filter @objectstack/dogfood test under the lock: VERDICT command-exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · 0 failed.

Live positive control (os dev, showcase app)

The showcase mounts KnowledgeServicePlugin itself (host-mounted, unchanged by this PR), so for the control its two knowledge plugins and the source's adapter: 'memory' were commented out in the worktree only (never committed; restored with git checkout), which lets the runtime compose the service with the Turso store. objectstack dev --seed-admin --log-level info on a file database, signed in as the seeded admin:

  • No embedder saved. One boot line, INFO KnowledgeServicePlugin: the knowledge service is not enabled on this deployment: no embedder is configured (no embedder provider is saved — …). Its sources are held: none is built, synced or searched. To enable it, save an embedder provider, then restart. 1 source(s) held: showcase-showcase_task_notes. (hidden at the default log level, as info should be). No build line. index_status lists the source with build: null. The Knowledge page's rebuild action answers "was not started: [knowledge] the knowledge service is not enabled on this deployment: …". MCP over HTTP: tools/list 20 tools, search_knowledge absent.
  • Embedder saved, restarted. PUT /api/settings/ai saved a custom provider pointing at a local OpenAI-compatible stub. The boot registered the embedder, registered the reap guard for [showcase_task] after the reading, and built the source: "8 row(s) read, 8 written". MCP tools/list 21 tools with search_knowledge; a search_knowledge call answered hits from showcase-showcase_task_notes; the stub logged one call of 8 inputs (build) and one of 1 (search).
  • The boot also logs ERROR [knowledge] the start of the build … was not recorded (Duplicate record refused on 'Knowledge Sync State' …) whenever a build starts, host-mounted or not. That is service-knowledge: every boot logs a false ERROR because the sync-state upsert reads a by-id update as "no row changed" #38418 (open, seat 1), not this change.
  • index_status still reads the adapter while held (here: state: unreadable with the embedder's reason). Saying "not enabled" there, and in os knowledge status / rebuild, is card item 4, part 3.
Gates at 72a9cbf

dispatch-gates --ran: 106 derived families accounted for, 105 run with exit 0, 1 NOT MEASURED: check:dual-build-cjs-loads exits 3 (no dist/ for @objectstack/studio, client-react, scenarios, outside this closure); CI runs it. Among them: check-adr-0087-registration (1 declared-breaking changeset, registered knowledge-service-held-without-embedder-or-store), check-changeset-no-major, check-empty-changeset, spec check:upgrade-guide, check:spec-changes, check:api-surface, check:liveness, check:engine-double-contract (after the stdio double's fix), check:slot-lookup (after typing the store plugin), check:error-status-conformance, check:type-check-debt, check:nul-bytes. check-plugin-teardown-shape --self-test exit 0 after fetching its pinned fixture commit. overlap-check before the push: clean against main and against #38439, #38435 and #38268 (#38418 has no PR yet).

🤖 Generated with Claude Code

https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW

…ources without an embedder or its store

Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW
Co-authored-by: Claude <noreply@anthropic.com>
… sources without an embedder or its store

Pins for the reap guard, both MCP transports and the runtime bridge; the
ADR-0087 upgrade-guide entry and the changeset.

Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW
Co-authored-by: Claude <noreply@anthropic.com>
…h the predicate; type the store plugin

Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW
Co-authored-by: Claude <noreply@anthropic.com>
@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 29, 2026
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 4 package(s): @objectstack/core, @objectstack/mcp, @objectstack/service-knowledge, @objectstack/spec, touching 36 documentable anchor(s).

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

  • content/docs/ai/actions-as-tools.mdx (via MCPServerPlugin (symbol, a top-level class))
  • content/docs/ai/knowledge-rag.mdx (via KnowledgeService (symbol, a top-level class), KnowledgeServicePlugin (symbol, a top-level class))
  • content/docs/ai/natural-language-queries.mdx (via MCPServerPlugin (symbol, a top-level class))
  • content/docs/protocol/kernel/index.mdx (via MCPServerPlugin (symbol, a top-level class))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), KnowledgeServicePlugin (symbol, a top-level class), handleRecordDelete (symbol, a method of class KnowledgeService), handleRecordUpsert (symbol, a method of class KnowledgeService), rebuildSource (symbol, a method of class KnowledgeService), reindexSource (symbol, a method of class KnowledgeService), runtimeComposed (symbol, a field of interface KnowledgeServicePluginOptions))
What this run could not see
  • 11 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 253 client-bound route-ledger rows — the other 184 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 184: 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; 125 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 — 191 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 16f132fbe76686713b709934389113f915c7d647 → packageMentionDocs.

Which tree this was computed on

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

node scripts/docs-audit/affected-docs.mjs --json 16f132fbe76686713b709934389113f915c7d647

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

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5m2rYCwPR3qqhnZDfW

Final green head: 4659f2a3698c259199e3a1f8e628552a6a6a922d.

  • CI at this head: 62 check-runs success, 10 skipped, none failed (Test Core 12/12, Test UI 16/16, Type Check, Lint & Repo Gates, Check Changeset, PR-body guards, Dogfood Regression Gate, Spec property liveness).
  • Full dogfood battery at this head (pnpm --filter @objectstack/dogfood test, under os-verify-lock): VERDICT command-exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · 0 failed.
  • Package suites at this head: service-knowledge 751 passed, mcp 1655 passed, core 26, runtime 7, verify 16; typecheck exit 0 for service-knowledge, core, mcp, runtime.
  • Since the PR opened: main merged (feat(service-knowledge): under the markdown split, a section that fits is one passage #38439 docs sibling, feat(adr-0087): refuse an added migration entry filed below PROTOCOL_MAJOR #38436), and PR 1's docs lines added to content/docs/ai/knowledge-rag.mdx and content/docs/protocol/knowledge.mdx. The body is brought to this head.
  • stdio registers search_knowledge late, at kernel:listening, only once the service reads as enabled; it is never registered and then withdrawn (pinned in packages/mcp/src/mcp-knowledge-tools.test.ts).

This head is not to move under review.


Generated by Claude Code

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb

Contract-review-claim: session_01FEkQ5oQLfL8thb6wtUHnTb · head 4659f2a · 2026-11-29T05:01Z

Face: narrowing (Clause-②: no (narrowing), Metadata-protocol: narrowed), so CONTRACT_REVIEW_TIER, run by an isolated fable subagent of the area, independent of the implementing card thread.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对

L1 (thread L1-a, area o5-ai37000) · read 2026-11-29T05:04Z · Head-sha: 4659f2a3698c259199e3a1f8e628552a6a6a922d · verdict REWORK (body only, one owed declaration)

This is the first L1 record on this PR, a full review. The contract review (fable) on this head is running and is a separate record.

Checklist (l1-face --pr 38470 at 4659f2a: 3 flags, read below)

  • Shape: open, draft, base main. Refs #38369 is right: this is part 1 of the three serial PRs the card names, and parts 2 and 3 follow from main.
  • Scope: 14 files across service-knowledge, core, mcp, a runtime test, the ADR-0087 notice entry, two docs pages and one changeset. Clause-②: no (narrowing) · Metadata-protocol: narrowed. The changeset is minor on service-knowledge, at least the minor a narrowed kind takes, with patch on the rest and the registered ADR-0087 marker for the new notice entry. Narrowing makes it Tier H.
  • Gates: 64 success, 12 expected skip, 0 failed, 0 pending; mergeable_state clean.
  • Flag changeset (runtime): not a defect. The one packages/runtime file is mcp-knowledge-tools-bridge.test.ts. @objectstack/runtime's files is dist, README.md and CHANGELOG.md, so nothing it publishes moves.
  • Flag dogfood: met. The body records the full battery at this head 4659f2a369: VERDICT command-exit 0, 495 files and 4183 tests passed, 0 failed.
  • Flag skills-docs: must-fix 1.

My readings, at this head

  • Core. resolveCapabilityArgument('knowledge') now passes runtimeComposed: { declared }, and declared is stackDeclaredCapabilities(stack).includes('knowledge'). A host-mounted plugin gets no runtimeComposed and is untouched.
  • MCP stdio. registerKnowledgeToolOnceSettled registers search_knowledge at kernel:listening only when the service then hands out its definition. It fails closed, and a host-mounted service's tool still registers in start().
  • Docs, read sentence by sentence. knowledge-rag.mdx ("Mounted is not enabled", the search_knowledge sentence, the "Nothing is configured" clause) and protocol/knowledge.mdx (the K8 paragraph and the reap-guard sentence). Each agrees with the changeset: held with neither half, 503 naming the missing half, no reap guard and no store call, the info/warn boot line, a restart to change it, and host-mounted not held.
  • The changeset, read sentence by sentence, matches the diff, and its FROM → TO names the three remedies.

Must-fix (body only)

  1. Skills-docs: is owed and absent. A narrowed kind owes the line, and l1-face reads it as REWORK. The body says only "skills/objectstack-ai/SKILL.md is out of scope (its own governed card after the build)", with no card number. The skill is affected at this head: SKILL.md:243–246 teaches "A shipped item mounts the knowledge service and its store …", and that is the exact reading this PR makes incomplete, since mounted is no longer enabled. A shipped source with no embedder saved is now held, not served. File the follow-up card and add Skills-docs: follow-up #N to the body.

After the fix: a delta L1 on the body. The head does not move.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 4659f2a3698c259199e3a1f8e628552a6a6a922d
Local-runs: none
Scope: .changeset/38369-knowledge-held-without-embedder-or-store.md, packages/core/src/capability-composition.ts, packages/core/src/capability-composition.test.ts, packages/mcp/src/plugin.ts, packages/mcp/src/mcp-knowledge-tools.test.ts, packages/runtime/src/mcp-knowledge-tools-bridge.test.ts, packages/services/service-knowledge/src/knowledge-service-plugin.ts, packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, packages/services/service-knowledge/src/tests/reap-guard.test.ts, packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts, scripts/engine-double-contract.pinned.json + read, not reviewed: docs/adr/0161 (the K8 dated note on item 12 and the K4 cross-reference, on main), packages/core/src/stack-collections.ts, packages/core/src/kernel.ts and lite-kernel.ts (boot phase order), packages/mcp/src/mcp-server-runtime.ts, packages/mcp/src/mcp-http-tools.ts, packages/mcp/src/stdio-data-bridge.ts, packages/mcp/src/skill-prompts.ts, packages/runtime/src/domains/mcp.ts, packages/runtime/src/app-plugin.ts (seed timing), packages/objectql/src/plugin.ts and lifecycle/lifecycle-service.ts, packages/services/service-knowledge/src/knowledge-build-actions.ts and knowledge-tools.ts, packages/cli/src/commands/serve.ts (the composition call), packages/verify/src/harness.required-providers.test.ts. The two prose faces (content/docs/ai/knowledge-rag.mdx, content/docs/protocol/knowledge.mdx) were read against the tree only.

Reviewed as the net diff of the head against its merge base with main (16f132fbe7), 14 files. This is PR 1 of 3 on card #38369 (items 1–2, ruling points 2–3, build notes 1, 2, 4); items 3–5 are not judged absent.

① Derived judgments

Each accept-set and public-surface change the diff implies:

  • resolveCapabilityArgument('knowledge', …) answers { deploymentAdapter, runtimeComposed: { declared } }; declared is stackDeclaredCapabilities(stack).includes('knowledge'), which reads the top-level requires and otherwise every package body's. A stack that only ships a knowledgeSources entry reads false. Right (card item 1; the note's log-level rule needs exactly this bit). Additive: a consumer that reads deploymentAdapter alone is untouched.
  • KnowledgeServicePluginOptions.runtimeComposed (new, optional) and KnowledgeServiceOptions.enabledByConfiguration (new, optional). Unset, every changed branch reduces to the code on main: reapGuardsAllowed starts true, enablementPending starts false, held stays undefined, provideEmbedder's line is said at the same place in the same handler. Right (acceptance: a host-composed plugin behaves as on main; the host-mounted control in the new describe pins it).
  • The reading, once per boot at kernel:bootstrapped: embedder available (a registered embedder service, or one the saved ai.embedder_* settings build) and an adapter of deploymentAdapter's id registered. Both kernels fire kernel:bootstrapped after every start() and every kernel:ready handler, so a store registered in its own start() is seen. Right against the note's "Enabled" bullet.
  • Held: buildSourcesAtBoot, buildReloadedSource, reconcileSources (walks nothing), requestReconcile, the armed-reconcile timer, enqueueRecordSync, processRecordSync (answers not-synced), handleRecordUpsert, handleRecordDelete, dropMetadataSource (index kept, one warn), the predicate-write note, scheduleReconcile and reportUnmountedAdapters all return before any adapter is reached. search, searchWithRefusals, rebuildSource, reindexSource throw 503 SERVICE_UNAVAILABLE. Right against the note's "Not enabled: held, not served" and K7 rule 5 (never answered empty). One public member is not gated, see N1.
  • knowledgeTools().definitions is [] while pending or held; the executor stays and refuses. HTTP reads the definitions per request through a thunk (packages/runtime/src/domains/mcp.ts), so it follows the state with no change there. Right (K9 rule 1: the absence is made at the one definition every transport registers, not at a transport).
  • stdio: search_knowledge no longer registers in MCPServerPlugin.start() for a runtime-composed service (the definition is absent then); it registers at kernel:listening, only when the service then hands the definition out, and a connected client is told by notifications/tools/list_changed. A host-mounted service's tool still registers in start(). Right (build note 4). The skill prompts read the server's registered tools at each listing (servedToolNames), so the claim in the method's comment holds.
  • The refusal text names each missing half and its remedy (heldSourcesText), one sentence shared by the refusal and the boot line. Right (build note 2; point 4's save wording itself is PR 2's).
  • Reap guard: a runtime-composed plugin registers none until the reading says enabled, then registers at once and on every later source change. Right (point 3, build note 1; pinned in reap-guard.test.ts both ways).
  • Log level: info only when not declared, nothing saved (quiet) and the store mounted; warn otherwise; never a throw. Right against the ruled log-line ◆.
  • Exports: KnowledgeHeldReading, heldSourcesError, heldSourcesText are new exports of knowledge-service.ts; additive.
  • scripts/engine-double-contract.pinned.json: one registry row for the test double's findOne. No behaviour. Right.
  • Check-runs on the head: 76 runs, 64 success and 12 skipped, none failed or pending (Check Changeset, Lint & Repo Gates, TypeScript Type Check, Test Core 12/12 shards, Dogfood Regression Gate, Spec property liveness, Build Docs, Governed Surface Queue Guard among them). Those are the gate verdicts; nothing was re-run.

② Semver level

Clause-②: no (narrowing)

The PR body and the changeset both carry Clause-②: no (narrowing) and Metadata-protocol: narrowed, as the claim on the card prescribes for the three PRs. The changeset is @objectstack/service-knowledge minor, @objectstack/core, @objectstack/mcp and @objectstack/spec patch, with a BREAKING banner, a FROM → TO list of three lines and the marker adr-0087: registered knowledge-service-held-without-embedder-or-store, whose entry is in the diff. That matches what the diff publishes: the kind takes minor on the package that carries the narrowing, the option added in core and the later registration in mcp are additive, and spec gains one upgrade-guide entry and no schema change. Check Changeset and the repo gates are green on the head. narrowed is the conservative reading for this slice (the author-facing save refusal is PR 2's); the claim sets it for the card as a whole and it errs toward the stricter disposition. Level right.

③ Boundary flags

  • Dev report 7250400446: open_questions is empty. Nothing to answer.
  • Its out-of-scope finding (an error line "the start of the build … was not recorded" on every boot that builds) is carried by service-knowledge: every boot logs a false ERROR because the sync-state upsert reads a by-id update as "no row changed" #38418, an open card of another seat. Not this diff's; no action here.
  • Build note 1 (guard waits for the reading): met, reapGuardsAllowed. Build note 2 (the direct search refusal names the missing half): met. Build note 4 (stdio): met. Build note 3 is PR 2's; this PR only reads that state as warn, which the ruled log-line ◆ requires.
  • Amendment point 2's measurement: the PR body names none of harness.required-providers' cases as held, and the file's knowledge cases do register an embedder from the app's own plugin; the file is not in the diff and Test Core is green.
  • File surface: every path is in the claim's surface or its recorded widening (7250411187, the pinned-registry row).
  • SQL push-down: the diff adds no query, no id materialisation and no in-app join.
  • Carried to PR 3 (item 4), not owed here: N1 below. The seat should name it in PR 3's order so the index_status change closes it.
  • Suggested follow-up cards, the seat's to file or decline: N2 and N3.

④ Design judgment

The narrowing is read against the ADR-0161 K8 dated note on item 12 on main, which declares this state and names #38369 as its build, and against ruling record 7248214179 (1A 2A 3A 4A).

Does it take a declared capability away at the consumer, or make the spec's own refusal real? The second. On main the declared behaviour of a runtime-mounted service with no embedder is a stand-in whose every use is refused; the note replaces that with "held, not served", and the diff builds it in the service that owns the definition and the stores. No consumer is narrowed: MCP over HTTP is unchanged and simply reads an empty definition list, and the one consumer that changed (stdio) changed to deliver the tool once enabled, not to withhold it. The one capability really removed, a source on an application-registered store being served with no embedder saved, is ruled (2A) with its way out (mount the plugin in plugins[]), is in the FROM → TO list and the upgrade entry, and is pinned.

Attempts to break it:

  • An enabled runtime-composed deployment losing search_knowledge on stdio because the late hook never fires: kernel:listening is triggered unconditionally after kernel:bootstrapped on both kernels, HTTP server or not. Holds.
  • A second reader of the definition that snapshots it before the reading (an agent tool registry, a REST door): the only readers of knowledgeTools() in the tree are the two MCP bridges, and both read at use. Holds.
  • A pending state that never settles: the reading is in the same boot-path handler that provides the embedder; a throw there fails the boot. While pending the tool is absent (fail-closed). Holds.
  • Store missing but embedder present, both missing, a key-less provider, requires declared: each lands on the ruled level and names its half; each is pinned.
  • Host-mounted composition changed by accident: traced branch by branch, no difference; pinned.

Findings:

  • N1 (nit) — KnowledgeService.readIndexState is not gated on the held state, so the Knowledge page's index_status answer still reaches a store while held wherever the plan does not throw first (a source on an application's store that needs no kernel embedder; or the store half missing while a source names another mounted adapter). It is a read on an administrator's request, writes nothing, and is outside the three pins of point 3 (boot, a record write, a retention sweep), so nothing ruled is broken; but "no store is called" in the changeset, the upgrade entry and settleEnablement's comment is wider than the tree until PR 3 makes index_status say "not enabled" (card item 4). The PR body discloses it. Left as an accepted deviation of this head, carried to PR 3.
  • N2 (nit) — the window before the reading. Between kernel:ready and the knowledge plugin's kernel:bootstrapped handler a record write is synced as on main, so a deployment that then reads held can have called a store (and recorded a failed sync) for writes made in that window, a seed deferred to kernel:bootstrapped by an earlier-registered plugin among them; and on a deployment that reads enabled, the reap guard now registers one phase later than on main. Both are bounded by main's own behaviour or by the sweep's timer, the note fixes the reading at kernel:bootstrapped, and the PR body states the window. Not measured here (read-only). Accepted deviation; a follow-up card could pin a write made inside the window.
  • N3 (nit) — the stdio late registration calls registerKnowledgeTools on the server directly, past MCPServerRuntime's own bookkeeping (nativeToolNames, yieldBridgedTool). If an AI tool registry ever bridges a tool named search_knowledge, the bridged one keeps the name on stdio while HTTP serves the native one, the reverse of the mcp stdio: a host whose AI tool registry already carries list_objects / the data tools cannot boot the stdio transport ("Tool list_objects is already registered") #31836 rule; today it is a warn and nothing in the tree registers such a tool. Follow-up card, or a runtime method for a late native tool when PR 2 or 3 next touches packages/mcp.

No must-fix, no should-fix.

Implemented-by: claude/project-thread-mu3i0t
Reviewed-by: session_01FEkQ5oQLfL8thb6wtUHnTb

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对

L1 (thread L1-a, area o5-ai37000) · read 2026-11-29T05:09Z · Head-sha: 4659f2a3698c259199e3a1f8e628552a6a6a922d · verdict ACCEPT (delta, body only)

This is a delta from my REWORK 7251041412. The head has not moved, and the rest of that record stands.

Owed before landing: the contract review on this head (running). Then the seat lands it (Tier H).

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr

维护者速读

席位意见:同意合并。合并后 #38413(队列成批消费,你已裁 A)在它之后接着做,把这个未启用拦截也放进批量路径。

席位核对 — ACCEPT · repo:objectstack#5 · Head-sha 4659f2a3698c259199e3a1f8e628552a6a6a922d · 2026-11-29T05:11Z

  1. 形态:open draft → main,! 标题,14 files,+926/−42,Refs #38369(PR 1/3),Clause-②: no (narrowing),Metadata-protocol: narrowed,Skills-docs: follow-up #38475。
  2. 前提实测:收窄档(队列守卫的 narrowed 一腿,维护者落地)。契约记录经 contractReviewRecordReading 本地读:VERDICT PASS,open 与 unreadable 均为空。
  3. 门禁 check-runs:本 head 66 success、14 skipped、0 失败,mergeable_state clean;全量 dogfood 在本 head exit 0(4183 passed)。
  4. 接受的偏差:契约记录的三条 nit,记入第 2、3 单。
  5. 范围外去向:技能文档 → skills(objectstack-ai): a shipped knowledge source mounts the service, but without an embedder or the deployment store it is held, not enabled (after #38369) #38475;service-knowledge: a bulk import syncs one record per queue message, read, embedded and written alone, so the index trails the data for hours #38413 排在本 PR 之后(overlap: processRecordSync)。
  6. 落地条款:收窄档,维护者批准后才入队;契约档 L2(fable)PASS 7251083329 在本 head,无未闭须修/应修;L1-a delta ACCEPT 7251091156(首轮 7251041412)。批准后由席位落地(ready + auto-merge)。⛔ 未批不入队。

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr

Approval requested (narrowing, Clause-②: no (narrowing), Metadata-protocol: narrowed: the queue guard's narrowed leg, ruling 2026-11-19 on #35321) · 2026-11-29T05:11Z

  • Head-sha: 4659f2a3698c259199e3a1f8e628552a6a6a922d
  • 维护者速读 and the seat's ACCEPT: the seat record above. Contract-tier PASS on this head: 7251083329 (no open must-fix or should-fix). L1-a delta ACCEPT: 7251091156. Ruling: 7248214179.
  • After your approval the seat lands it (ready + auto-merge); it stays draft until then.

@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 29, 2026
@os-zhuang
os-zhuang marked this pull request as ready for review November 29, 2026 05:17
@os-zhuang
os-zhuang added this pull request to the merge queue Nov 29, 2026
Merged via the queue into main with commit 91fc398 Nov 29, 2026
86 checks passed
@os-zhuang
os-zhuang deleted the claude/project-thread-mu3i0t branch November 29, 2026 05:45
os-project-manager pushed a commit that referenced this pull request Nov 29, 2026
The held check #38470 put in processRecordSync moves into resolveRecordSync,
right after the message is read, so the per-message and batch paths both
complete a held service's messages as not-synced without calling a store.
Adds the batch-path held test.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…Korean questions by 2- and 3-character pieces (objectstack-ai#38469)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XJFhX5XfWT8anspjCw9gfjz)_
Part of objectstack-ai#38411. This PR covers Ask 1, Ask 2 and the first two Acceptance
items, plus the model-free half of the eval, and on pgvector the cheaper
matcher for a caseless piece (`LIKE` instead of `ILIKE`). Still open:
the BrightRule model-graded before/after (needs a running BrightRule
environment and model credentials), and Ask 3 (not measured, see below).

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

## 维护者速读

- 用户能看到什么变化:在本地 libSQL 和 PostgreSQL
两种存储上,用中文、日文或韩文不加空格整句提问时,知识检索的关键词一路终于能匹配到段落;英文提问不受影响。
- 为什么做:属于知识平台专题,解决混合检索在中文问题上实际只剩向量一路的问题。
- 出错会怎样:代价是检索变慢(数字见下),最坏情况是关键词一路排序变差,向量一路照常作答;不改索引、不需重建,可直接撤回。
- 要你做什么:无。

取舍数字(合成制度题集,约 6.7 万段落,218 道中文题):

- 中文题关键词一路前 5 名命中率:0.028 → 0.495。
- 本地 libSQL 关键词一路 p95:约 0.12 秒 → 约 0.5 秒。
- 本地 libSQL 混合检索 p95:0.41 秒 → 0.84 秒。
- PostgreSQL 关键词一路 p95:约 0.6 秒 → 约 1.9 秒(本 PR 已把中文片段改成更便宜的匹配方式,排序不变;改之前约
3 秒)。
- 检索词上限 16 是实测拐点:再往上每多约 40% 耗时只多约 1 个点命中率。
- 想再降延迟的两个杠杆:把上限降到 12(命中率 0.459,libSQL 关键词 p95 约 0.31 秒);PostgreSQL
上给段落正文加三元组索引,已立后续卡 objectstack-ai#38473,不在本 PR。
- 未测:BrightRule 模型评分的前后对比,需要运行环境和模型凭据。

## What changes

- `keywordTerms` in `knowledge-turso/src/sql.ts` and
`knowledge-pgvector/src/sql.ts` (one body, kept identical) cuts a run of
Han, Hiragana, Katakana (including the prolonged sound mark) or Hangul
inside a term into overlapping pieces of three characters and of two. A
run of two characters is one piece. A run of one is dropped, because it
would match nearly every passage. Figures and codes next to a run
(`2000`, `X-200`) stay whole terms. Latin-script and spaced queries get
exactly the terms they had before.
- **Selection rule (Ask 2).** `MAX_KEYWORD_TERMS` stays at 16,
re-decided by measurement (below). The cap is filled in this order:
figures, codes and words; then pieces of three characters and runs of
two; then pieces of two characters. A long question therefore keeps the
pieces the libSQL trigram index serves; a short one fills the cap with
pieces of two. Matching is unchanged. No index change, no fingerprint
change, no reindex.
- **pgvector matcher (round 2).** A keyword term the `tsvector` does not
serve is matched as a substring by `LIKE` when it holds no cased letter
(`containsOperator` in `knowledge-pgvector/src/sql.ts`:
`term.toLowerCase() === term.toUpperCase()`; a Han, kana or Hangul
piece, a figure), and by `ILIKE` otherwise. Case folding can find
nothing more for such a term, so the rankings are identical. Nothing
else in the Search section changes. libSQL is unchanged.
- **Docs.** `content/docs/protocol/knowledge.mdx` (the contract's
optional `keywordLeg` case; both Search bullets: the CJK pieces, and on
pgvector `LIKE` / `ILIKE`) and both plugin READMEs. The turso README
said "a Chinese question is one term", which this change made false.
- **Contract (H2 placement, Clause-② yes).**
`@objectstack/service-knowledge/testing`:
`KnowledgeAdapterContractOptions.implements` gains an **optional**
`keywordLeg` member (absent means `false`). When an adapter declares it,
the shared suite asks the unspaced question
「出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗」 over one passage holding 「2000元以下除外」
and five passages holding the question's characters one by one but none
of its words. The passage must be ranked at `topK` 3. knowledge-turso
and knowledge-pgvector declare it. knowledge-memory and the service
stubs have no keyword leg and are untouched. No placement with zero new
exported members exists: the memory adapter and the stubs run the same
suite and have no keyword leg, and the spec contract has no capability
flag to read. The member is optional, so existing callers compile
unchanged; that makes it widening.

## Tests

<details><summary>Unit pins, contract case, ablation (head
b511770)</summary>

- knowledge-turso `acceptance.test.ts`: the Latin and spaced pin is kept
exactly (`What is the X-200 pump? …` gives today's 10 terms; `出差 住宿`
gives `['出差','住宿']`; cap 16). New pin: an unspaced question gives its
figure and then its pieces; `X-200型号的保修期` keeps `X-200`; runs of two and
one; kana and Hangul.
- knowledge-pgvector `keyword-terms.test.ts` (new, no database): the
same pins, plus which matcher each term goes to (`isWordTerm`).
- Contract case: knowledge-turso on `:memory:` and on a `file:` URL, and
knowledge-pgvector on a live PostgreSQL 16 with pgvector 0.6.0 started
in this container.
- Results, local: knowledge-turso `Test Files 4 passed, Tests 284
passed`; knowledge-pgvector live (`OS_TEST_POSTGRES_URL` set,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`) `Test Files 11 passed, Tests 108
passed`; service-knowledge `21 files, 726 tests passed`;
knowledge-memory `3 files, 66 tests passed`. Type check is green for
knowledge-turso, knowledge-pgvector, service-knowledge and
knowledge-memory.
- Ablation (base `sql.ts` swapped in, checked by blob hash, then
restored and checked by hash again): turso goes red with 4 failures (the
piece pin and the contract case, on both store kinds; the Latin pin
stays green); pgvector, live, goes red with 3 failures (the contract
case and two pins).
- Reverse type check: the turso type check first read a
`dist/testing.d.ts` built before this change and refused `keywordLeg`
(TS2353). After the rebuild it passes.
</details>

<details><summary>Round 2: the pgvector matcher (head cde0bbe; code
identical to 81be16f)</summary>

- `keyword-terms.test.ts` gains two pins. `containsOperator` gives
`LIKE` for `元以下`, `出差`, `コー`, `휴가`, `42` and `ILIKE` for `ab`, `X-200`,
`É`. A statement pin runs `adapter.search('出差 ab', …)` against a
recording pool and reads, from the ranking statement itself, the
operator in front of the placeholder each pattern is bound to: `%出差%`
gets `content LIKE`, `%ab%` gets `content ILIKE`.
- knowledge-pgvector live (PostgreSQL 16 + pgvector 0.6.0,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`), contract case included: `Test Files
11 passed (11)`, `Tests 110 passed (110)`, verify lock `VERDICT
command-exit 0`.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: `VERDICT
command-exit 0`.
- Ablation: with the adapter reverted to b511770 (blob hash checked,
then restored and checked again), the statement pin fails: `Tests 1
failed | 4 passed (5)`.
- CI on b511770 (job 141221631158) and on 923c009 (jobs 141222136228
and 141222139195): every failing step is an aggregator reading a
`cancelled` lane (for example "type-check lane `typecheck-workspace`
concluded `cancelled` -- expected `success`"). Each later push to this
branch cancelled the run in flight. 923c009 also held one real error,
TS2353 in the new statement pin (`recipeHash` is not a member of the
search options' `index`), fixed in 81be16f and green locally as above.
</details>

## Measurement

Every harness is a scratch script outside the repository. Corpus: the
BrightRule synthetic set (`scripts/eval/build.ts --distractors 1500`,
brightrule @ 07e21ac). Passages are cut one per article or section, with
attachments kept on their own and each passage prefixed
`【unit|title|attachment】 path`, as the app's clause hook does. Each
document is indexed through `TursoKnowledgeAdapter.upsert` (the real
write path). Two tables:

- 11k: 1,577 documents, 11,025 passages.
- 67k: the same plus 8,000 distractors from seeds 11 to 14, giving 9,577
documents and **67,421 passages**. The card's table had 67,379.

Questions: the **218 zh questions whose expected policies are Chinese**
(230 counting the zh-to-English ones). A hit means a passage of an
expected policy (P) or of the expected article (C) in the keyword leg's
top 5 or top 10. The keyword leg is isolated with an all-zero query
vector, which turns the vector leg off. Intervals are 95% bootstrap
intervals over questions (2,000 resamples). Retrieval is deterministic:
**each side was run 3 times and the rankings were identical on every
run**, on both stores and both tables. So the interval comes from the
question sample, not from run noise.

<details><summary>Keyword leg, libSQL store, before and after</summary>

| table | side | P@5 | P@10 | C@5 | C@10 | questions with any hit | p50
| p95 |
|---|---|---|---|---|---|---|---|---|
| 11k | before | 0.032 [0.009, 0.055] | 0.037 [0.014, 0.064] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 0.7 ms | 20 ms |
| 11k | after | **0.500** [0.431, 0.569] | 0.514 [0.450, 0.583] | 0.486
[0.421, 0.556] | 0.500 [0.435, 0.569] | 206 | 52 to 56 ms | 80 to 93 ms
|
| 67k | before | 0.028 [0.009, 0.050] | 0.032 [0.009, 0.060] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 1.4 ms | 113 to 132 ms |
| 67k | after | **0.495** [0.427, 0.564] | 0.500 [0.431, 0.569] | 0.486
[0.421, 0.556] | 0.491 [0.421, 0.560] | 206 | 305 to 328 ms | **491 to
516 ms** |

All 230 zh questions, 67k: P@5 goes from 0.026 [0.009, 0.048] to 0.470
[0.404, 0.530].
</details>

<details><summary>Choosing the cap and the order (67k, keyword leg
alone)</summary>

| order / cap | P@5 | p50 | p95 |
|---|---|---|---|
| pieces of three and runs of two only (no pieces of two) | 0.404 | 7 ms
| 155 ms |
| three-first, cap 12 | 0.459 | 136 ms | 314 ms |
| **three-first, cap 16 (shipped)** | **0.495** | 321 ms | 507 ms |
| three-first, cap 20 | 0.505 | 440 ms | 690 ms |
| three-first, cap 24 | 0.509 | 552 ms | 910 ms |
| by position, cap 16 | 0.495 | 445 ms | 746 ms |
| by position, cap 32 (every piece of every question but a few) | 0.518
| 670 ms | 1,277 ms |

The questions are 16 characters at the median and 24 at p90, which gives
23 uncapped terms at the median and 34 at p90; 202 of 230 exceed 16. On
the 67k table, a piece of two characters costs one scan of the rows in
scope, about 23 ms (`LIKE` and `instr` cost the same). A piece of three
is served by the trigram index and is nearly free, except for a trigram
most passages hold: about 30 ms to materialise one held by 48,000 rows.
Past 16, recall gains about one point for each further 40% of latency,
and every interval overlaps. Cap 16 with the three-first order is the
knee. Keeping a one-character run measured no recall change.
</details>

<details><summary>Hybrid search latency, libSQL 67k with a 1024-wide
vector column (exact scan)</summary>

| side | p50 | p95 |
|---|---|---|
| before | 258 ms | 410 ms |
| pieces of three only | 266 ms | 429 ms |
| after (three-first, cap 16) | 563 ms | 837 ms |
| three-first, cap 24 | 818 ms | 1,244 ms |

The vector leg here is a bag-of-characters fake embedder, used for its
cost only. Its fused ranking is not reported: a lexical stand-in for an
embedder measures the fusion of two lexical legs, not hybrid retrieval.
</details>

<details><summary>pgvector, live PostgreSQL 16 + pgvector 0.6.0, the
same 67k passages, keyword leg alone</summary>

| side | P@5 | p50 | p95 |
|---|---|---|---|
| before (3 runs) | 0.028 | 132 to 150 ms | 617 to 691 ms |
| pieces, every substring term by `ILIKE` (b511770, 3 runs) | 0.495 |
538 to 563 ms | 2,883 to 3,085 ms |
| **pieces, a caseless term by `LIKE` (this head, 3 runs)** | 0.495 |
187 to 195 ms | **1,832 to 1,925 ms** |

The rankings are identical on every run, identical between the `ILIKE`
and the `LIKE` heads, and the same hit set as libSQL. The tail is
questions holding 公司: its pieces are held by 67,125 of 67,421 passages,
because every clause prefix names its company, so nearly every row
becomes a candidate. On this server `ILIKE '%公司%'` costs 90 ms per scan
against 18 ms for `LIKE` or `strpos`, with identical counts; that is the
matcher change in this PR. What remains of the tail is one substring
scan per piece over nearly every row, and the candidate `tsvector`
computed for each of them.
</details>

Commands, all run from a scratch directory outside the repository:

```
pnpm run eval:build -- --distractors 1500 --out EVALSET                    (in a scratch copy of brightrule, pnpm install --ignore-scripts)
pnpm run eval:build -- --distractors 2000 --seed 11..14 --out EVALSET-sN   (distractors only, keys suffixed)
python3 -I prep.py CORPUS docs.json                                        (clause passages)
tsx eval.ts index docs.json DB 8 zero        and        tsx eval.ts search docs.json DB questions.json VARIANT out.json
tsx eval.mts index / search                  (pgvector, the same shape)
python3 -I score.py zh RUN.json …            (recall, bootstrap intervals, p50/p95)
```

All timings are seconds on a shared 4-core container, with sibling
agents running.

- NOT MEASURED: BrightRule model-graded eval, reason: it needs a running
BrightRule environment and model credentials, and this container has
neither. The keyword-leg retrieval above is the model-free stand-in.
- NOT MEASURED: fused hybrid recall, reason: no real embedder in this
container. A lexical stand-in would measure the fusion of two lexical
legs.
- NOT MEASURED: Ask 3 (a larger per-leg pool before fusion), reason: it
is judged on fused ranking, which needs a real embedder. Ask 3 also
reaches `knowledge-tools.ts`, which is outside this claim.

## Acceptance notes

- **pgvector keyword-leg cost (carrier: objectstack-ai#38473, filed by the seat).**
With the `LIKE` matcher in, pgvector's keyword-leg p95 on the 67k table
goes from about 0.6 s to about 1.9 s. Two levers remain, both outside
this claim. First, compute the candidate `tsvector` only when a word
term needs it (a Search-section change). Second, a pg_trgm GIN index on
the passage content, which serves `LIKE` / `ILIKE` substrings. That is
an index change: a second DDL beside `keywordIndexDdl`
(`knowledge-pgvector/src/sql.ts`), created through `ensureKeywordIndex`
(`pgvector-adapter.ts`), plus a `pg_trgm` extension dependency next to
the `vector` one. It is not a fingerprint change: the index fingerprint
hashes only the embedding model, variant, dimensions and split, and an
older table gets the keyword index at its first search without a
rebuild.
- A lower cap is the cheapest lever on both stores: cap 12 measured P@5
0.459 and libSQL keyword p95 314 ms (cap 16: 0.495 and 507 ms).
- libSQL: a piece of two characters costs one scan of the rows in scope.
Scoring pieces of two only among the candidates that the index-served
terms recruit would remove that scan. It is a Search-section change and
moves each piece's document frequency, so it needs its own measurement.
- **Separator class takes 々, 〆 and 〇 (carrier: objectstack-ai#38411, a remaining item
there, filed by the seat).** The class `\u3000-\u303f` holds 々 (U+3005),
〆 (U+3006) and 〇 (U+3007, the ideographic zero), in both stores. With
this PR's rule that drops a one-character run, 「人々」 yields no keyword
term (on main it kept 「人」) and 「二〇二四年」 loses 「二」. The fix (take
U+3005–U+3007 out of the separator class and into the run, pins in both
stores) lands as a follow-up PR on objectstack-ai#38411 after this one merges, so this
approved head does not move (L1 7250902792).
- To run the pgvector live suites, this container installed
`postgresql-16-pgvector` (0.6.0, Ubuntu noble) and ran a private cluster
on a random port, removed afterwards.

## Verification

- Read first: `packages/plugins/knowledge-turso/src/sql.ts`
(`keywordTerms`: the run split and the final order and cap),
`packages/services/service-knowledge/src/testing.ts` (the optional
`keywordLeg` member and its case),
`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (the
keyword branch of the ranking statement, where `containsOperator` picks
`LIKE` or `ILIKE`).
- Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec
vitest run --maxWorkers=2 src/__tests__/contract.test.ts` should show
the case `the keyword leg › an unspaced question ranks the passage …`
passing on both `:memory:` and `file:`.

<details><summary>Local gate subset at cde0bbe (CI runs the full
farm)</summary>

- Tests and type checks: listed under Tests above.
- `node scripts/pm/dispatch-gates.mjs --commands` derived 101 families
for the 12 changed files (70 at b511770, plus 31 the docs edit brings
in). Each ran with its exit code captured before any pipe. The 31 docs
families and 8 families that read the round-2 files were run at
cde0bbe; the others read files unchanged since b511770 and carry that
reading. `--ran` reconciliation at cde0bbe: `101 derived, 101 run, 0
NOT-MEASURED, 0 UNRUN`. Exit codes: **96 exit 0**, and five not
measured:
- NOT MEASURED: `check:skill-examples`, reason: exit 3, PREREQUISITE NOT
MET, it needs the client SDK's `dist/`. No skill file is touched.
- NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason:
PREREQUISITE NOT MET, its pinned positive-control commit is beyond this
shallow clone.
- NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT
MET, it needs every package's `dist/`.
- NOT MEASURED: `check:query-options-erasure` and
`check:type-check-debt`, reason: repo-wide ESLint and `tsc` scans that
passed the 240 s per-gate limit. CI's Lint & Repo Gates and TypeScript
Type Check carry them.
- `overlap-check` before the push: `VERDICT clean` against origin/main
and the two open PRs that share `knowledge.mdx` (objectstack-ai#38468, objectstack-ai#38470), and
clean against `origin/claude/project-thread-mu3i0t`.
- Self-scan of the changed files for control bytes: no hits.
</details>

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

https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm

<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5pfJqySEaVD3CKvevm -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…atches of 100, and a large backlog is reconciled (objectstack-ai#38509)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XTxm2XFTJzP3Vgjt9Rqx2C2)_

Part of objectstack-ai#38413
Acceptance gap: acceptance 2 is not closed by this PR. The figures here
come from a LOCAL MODEL: 50,000 records on a real SQLite/libSQL store,
with a local embedder at 200 ms per request + 0.5 ms per input, where
the drain takes about 1.7 times as long as a full rebuild. That model
cannot show what a real provider does. With a real provider the ratio
should move toward 1, because per-message queue costs matter less when
every request is slower, but that is not measured. carrier: objectstack-ai#38529 (a
50k drain with a real embedding provider, Blocked-by objectstack-ai#38509).

Clause-②: yes (widening)
Metadata-protocol: none
Ask 3: split to objectstack-ai#38489 (per-source backlog needs a stored counter); the
global waiting count is exact here (getQueueSize through count).

## 维护者速读

- 用户可见变化:批量导入或批量修改几万条记录后,知识库检索追上数据所需的时间大幅缩短(本地模型实测 5 万条约 4 分钟,原来约 2.9
小时);单条保存的体验不变。
- 为什么做:属于知识库检索这条线,解决大批量数据进来后很长时间搜不到新内容的问题,按您的裁决实施(队列加一个可选的批量消费能力)。
-
出错会怎样:只影响走数据库队列的知识同步;某条记录同步失败只会单独重试、进死信,不拖累同批其它记录;邮件发送等其它队列订阅不受影响;可整单撤回。
- 要你做的:无。

## What changes

Ruling A (7250307515): record-sync batching reaches the knowledge worker
through an optional batch-consume member on `IQueueService`. The
database queue adapter implements it, and the knowledge worker uses it
when the composed queue has it.

- **Contract** (`packages/spec/src/contracts/queue-service.ts`). A new
optional member:
`subscribeBatch?(queue: string, handler: QueueBatchHandler, options:
QueueBatchSubscribeOptions): Promise(void)`.
The types it uses are `QueueBatchHandler = (messages: QueueMessage[]) =>
Promise(QueueBatchOutcome[])`, `QueueBatchOutcome = { ok: true } | { ok:
false; error: unknown }` and `QueueBatchSubscribeOptions = { maxBatch:
number }`. The handler answers one outcome per message. A queue takes
either per-message handlers or one batch handler, and `unsubscribe`
removes either. The member is optional: every existing implementation
keeps compiling, and a consumer falls back to per-message `subscribe`.
It is documented in
`content/docs/kernel/runtime-services/queue-service.mdx`.
- **Database queue**
(`packages/services/service-queue/src/db-queue-adapter.ts`). A batch
queue gets a dispatch loop of its own. Each tick it:
- claims up to `maxBatch` due rows, marking each row in flight as it is
claimed;
- renews all their leases in ONE compare-and-set write every third of
`leaseMs` while the handler runs;
- settles each row by its own outcome, so a failure takes the
per-message retry and dead-letter path alone, and one settling write
that throws does not stop the others;
  - ticks again at once while a claim comes back full.

A row the lease reclaim returns to a batch queue wakes that queue's
loop. The main loop is unchanged: the mail send, mail attachment reclaim
and API-flow subscriptions keep one message per call at `batchSize` per
`pollIntervalMs`. `getQueueSize` now counts through `engine.count`.
- **Knowledge worker**. It uses `subscribeBatch` with `maxBatch` 100
(`RECORD_SYNC_BATCH_SIZE`) when the queue has it, and per-message
`subscribe` otherwise. For each source and object in a batch,
`processRecordSyncBatch` does one re-read (`where` AND `id $in`), one
`planIndex` (one fingerprint, ADR-0161 K7), one split, one adapter
`upsert` and one `delete`. When a group with more than one record fails,
its records are synced again one at a time. Messages stay identifiers
only, and no `IKnowledgeAdapter` member is added (K8).
- **Batch against the lease**: a 100-message batch takes about 0.47 s
against the 30 s lease, and one renewal write every 10 s covers every
row in it.
- **`covered` (review M1)**. A message completes without a read only
when all of these hold:
- the source's last build on this node ended `done` and its purge ran
(`result.purged` is a number);
  - the reconcile walks the source (`reconcileExclusion`);
  - the build began more than 5 s after the message was published.

A build that ended `done` without purging covers nothing, so a waiting
delete or where-exit is still synced on both paths. This covers an
adapter without `listDocuments` and a listing that failed.
- **Backlog (ask 2, review S1)**. The rule is now per source and never
blocks. The worker estimates a source's backlog as the queue's waiting
count times the source's share of the batch in hand. When that estimate
reaches both `RECORD_SYNC_BACKLOG_THRESHOLD` (5,000) and
`RECORD_SYNC_BACKLOG_ROW_SHARE` (5 % of the source's rows, counted once
per 10 min), one reconcile of that source is scheduled beside the syncs
and is not awaited. The batch and every other source keep draining, and
`unsubscribe` does not wait for a walk. Once the reconcile ends `done`
with its purge run, the waiting messages it covers complete as
`covered`. After it ends, the next backlog reconcile of that source
waits:
- 10 min if it ended `done`, so a source under sustained writes is not
re-walked back to back;
  - 5 min, doubling to 1 h per failure, if it did not.
- **Held service (ruling 7248214179, from objectstack-ai#38470)**. The held check sits
in `resolveRecordSync`, straight after the message is read. Both paths
therefore complete a not-enabled service's messages as `not-synced`.

**Contract faces touched:**
- `IQueueService.subscribeBatch` (optional), plus the exported types
`QueueBatchHandler`, `QueueBatchOutcome` and
`QueueBatchSubscribeOptions`.
- `api-surface/contracts.json` and `export-origins/contracts.json`
regenerated (+3 lines each); signatures unchanged.
- `KnowledgeService.processRecordSync` takes an optional `publishedAt`
and can answer `covered`. `KnowledgeService.processRecordSyncBatch` is
new.
- `KnowledgeRecordSyncBatchItem` and `KnowledgeRecordSyncBatchResult`
are now exported from `@objectstack/service-knowledge`.
- No error code, authorable key or metadata protocol change.

## Tests

- **1,000 syncs** (`record-sync-queue.test.ts`, real `DbQueueAdapter`,
100 drafts outside `where`): 10 adapter upserts and 10 deletes. 900
documents were embedded, each published document once and no draft; this
counts documents handed to the embedder, not embedder requests. The
index of 900 documents equals `reindexSource` (content and docHash).
- **Poisoned record**: it dead-letters alone, its 7 neighbours are
indexed, and exactly one dead-letter error line is logged.
- **Mixed batch**: deletes, a row moved out of `where`, an edit, a new
draft and a new row in one batch give the same index as the per-message
path. A held service's batch path syncs nothing.
- **M1**: a delete and a where-exit message against a `done` build with
`purged: null` still remove their documents. This is tested on both
paths, for both no-purge causes: no `listDocuments`, and a listing that
failed.
- **S1** (`knowledge-build.test.ts`):
- over the threshold, the batch answers while the reconcile is held
mid-walk, and the next batch of older messages completes as `covered`
with no re-read and no second reconcile (re-walk wait);
  - under the threshold, no reconcile runs;
  - a backlog small against the source's rows is drained;
- one message of source B inside source A's backlog is synced while A is
reconciled;
- a reconcile that ended without a purge is not asked again before its 5
min backoff, and is asked again after it;
  - a store that lists no documents is never reconciled.
- **S2 / N2** (`db-queue-adapter.test.ts`):
- a sole writer keeps the lease entry of every batch row claimed while a
main-loop reclaim reads;
  - one settling write that throws leaves the other rows settled.

<details><summary>Suite and ablation readings (head 76742ab)</summary>

- service-queue: Test Files 5 passed (5), Tests 102 passed (102);
typecheck green.
- service-knowledge: Test Files 22 passed (22), Tests 781 passed (781);
typecheck green.
- **Ablation M1**: the condition `typeof build.result?.purged !==
'number' || build.result.ok === false` was removed from
`coveredByBuild`. Both listing-failed cases went red ("2 failed | 2
passed"); the rebuild-unlisted cases stayed green through
`reconcileExclusion`. Restored to the HEAD blob.
- **Ablation S2**: `inFlight?.add(String(row.id))` was removed from
`claimBatch`. The S2 case went red ("expected [ false, true, true ] to
deeply equal [ true, true, true ]"). Restored to the HEAD blob.
- **Earlier ablations**: the held check went red ("vi.fn() ... called 1
times"), and the group fallback went red ("expected 900 to be less than
or equal to 10").

</details>

## Measurement: 50,000 records, LOCAL MODEL

This is a labelled local model, not a production figure.

- Store: SQLite through the SQL driver for both data and the queue, with
the knowledge-turso libSQL file vector store.
- Embedder: local, with a latency model of 200 ms per request plus 0.5
ms per input, at most 2,048 inputs per request, requests sent in series.
- Setup: default queue options. Each run starts from a copy of the same
database.
- "All changed" means the index starts empty and all 50,000 messages
wait. "None changed" means the index is current and the same 50,000
messages wait.

| run | time | rate | embed requests / inputs |
|---|---|---|---|
| this round, all changed, batch + scheduled reconcile | 217,019 ms |
230/s | 990 / 50,214 |
| this round, all changed, batch only (reconcile off) | 233,169 ms |
214/s | 500 / 50,000 |
| this round, none changed, batch + scheduled reconcile | 91,113 ms |
549/s | 0 / 0 |
| this round, none changed, batch only | 105,653 ms | 473/s | 0 / 0 |
| a reconcile walk over the 50,000 unchanged rows | 1,418 ms | n/a | 0 /
0 |
| full rebuild (previous round) | 142,359 ms | n/a | 500 / 50,000 |
| before, per-message, 600 s window (previous round) | 2,883 drained in
600,446 ms | 4.8/s | 2,884 / 2,884 |

- **Ask 2 now pays.** The scheduled reconcile cut the drain by 7 % with
every record changed (217 s against 233 s) and by 14 % with none changed
(91 s against 106 s). The previous round's awaited reconcile showed 1.3
%.
- **What the floor is.** A covered message still costs its claim and
settle writes, about 1.8 ms each in this model; this is N1 below.
- **Why 5,000 and 5 %.** The worker drains about 214 changed records per
second, so 5,000 messages are about 23 s of draining. A walk over 50,000
unchanged rows takes 1.4 s, and draining costs 2.1 ms per unchanged
message and 4.7 ms per changed one. At 5 % of the rows, the walk's own
reading is about a quarter of the drain it runs beside, or less.
- **Before.** The before figure comes from a 600 s window, not a full
drain. Projected over 50,000 records it is about 2.9 h, with an 83 min
floor at the claim pace of 10 per second.

## Acceptance notes

- **Acceptance 1** (bounded embedder work and adapter writes, an index
equal to a rebuild): covered by the 1,000-sync case, which counts
adapter writes and embedded documents, and by the measurement, which
counts embedder requests.
- **Acceptance 2**: open; see the Acceptance gap line. carrier: objectstack-ai#38529.
- **Acceptance 3**: covered by the poisoned-record case.
- **Acceptance 4**: covered by the mixed-batch parity case and the M1
cases on both paths.
- **Ask 2**: per source, scheduled, remembered, with the numbers above.
- **Ask 3**: split to objectstack-ai#38489.
- **N1**: the batch claim and settle are 2N single-row writes, and the
claim write matches by id alone, so two nodes draining at once can claim
the same rows. carrier: objectstack-ai#38548. It is also the drain floor the
measurement shows.
- **N3**: fixed here. A row the main loop reclaims for a batch-consumed
queue wakes that queue's loop.
- **Local gates**: `check:dual-build-cjs-loads` was NOT MEASURED
locally, because it needs every package's dist. CI runs it.

## Verification

Read first, by risk:
1. `packages/services/service-knowledge/src/knowledge-service.ts`:
`coveredByBuild`, `considerBacklogReconcile` and
`processRecordSyncBatch`.
2. `packages/services/service-queue/src/db-queue-adapter.ts`:
`claimBatch` and its in-flight mark, `dispatchBatch` with its per-row
settle, and the reclaim wake.
3.
`packages/services/service-knowledge/src/knowledge-record-sync-queue.ts`:
the backlog constants and the numbers they cite.

Two-minute check: run `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/knowledge-build.test.ts -t "purged nothing"`.
Expect 4 passed: a delete still syncs after a build that did not purge.

<details><summary>Local gates (head 76742ab)</summary>

- Derived with `dispatch-gates.mjs --commands --repo
objectstack-ai/objectstack` on head 76742ab: 120 commands, all run,
each exiting 0 with the code captured before any pipe.
- `check-plugin-teardown-shape --self-test` passed after the pinned
fixture commit was fetched into the shallow clone.
- `check:skill-examples` first exited 3 (PREREQUISITE NOT MET: client
dist missing). It exited 0 after `@objectstack/client` and
`@objectstack/client-react` were built: "352 prose examples type-check".
- `check:dual-build-cjs-loads`: "126 published require entry point(s)
across 74 package(s) load".
- `--ran` reconciliation: "Run reconciliation — 120 derived, 120 run, 0
NOT-MEASURED, 0 UNRUN".
- The derivation warned that its tree is 17 commits behind origin/main,
with 16 derivation files changed there. No merge was done, since there
is no conflict and no main-caused red; CI judges the merge ref.
- `overlap-check --branch=claude/project-thread-caiyo5`: "origin/main:
merges cleanly", VERDICT clean exit 0.

</details>

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

https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5mC8eA4qtKSweeF7wd -->

---------

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 pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue 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

Development

Successfully merging this pull request may close these issues.

3 participants