Skip to content

refactor(service-knowledge): split KnowledgeService into five concern modules behind a delegating facade - #38700

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

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

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Warren · project thread
Fixes #38660

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户无感:知识检索服务的内部代码按功能拆成五个文件,检索、索引构建、记录同步和保存校验的行为都不变。
  • 属于知识检索专题:原来五千多行挤在一个文件里,后面的对账、保存校验、检索改进几张卡只能排队改它;拆开后可以各改各的文件、并行推进。
  • 若拆分有误,会表现为知识检索、索引或记录同步出错;这次只搬代码,整体撤回这次合并即可恢复原状。
  • 改动超过三千行,需要你批准后才能合并。

What changes

packages/services/service-knowledge/src/knowledge-service.ts goes from 5,571 to 1,658 lines and is now a facade: KnowledgeService keeps every field, its constructor and every member with its name, signature and (for a public member) docblock, and each moved member forwards to its body in one call. Move-only: no member is renamed, no behaviour changes, nothing is added to or removed from the package entry (index.ts is untouched).

The shape is the one the earlier facade splits use (SqlDriver and objectql engine.ts): each body is a module-level function whose this is typed as the part of a per-module host interface it reads; each host member is typed as the class member (KnowledgeService['x']), so a member renamed or retyped on the class is a compile error in the facet. The class's one static block builds the host once per service (knowledge-service-host.ts): methods go as closures that call the service at call time (an instance spy or a subclass override is still the one reached), fields as getters, plus a setter for the six fields a body assigns.

New module Lines What it holds
knowledge-service-sources.ts 415 adapters, the source registry, enablement
knowledge-service-indexing.ts 1,483 build, index state, durable build records, reconcile
knowledge-service-record-sync.ts 944 record sync, sync state and dead letters, backlog
knowledge-service-search.ts 1,147 search and answer, freshness, scope narrowing
knowledge-service-admission.ts 580 save admission, tenancy posture, organization and permission scoping
knowledge-service-top-level.ts 1,067 every top-level declaration of the old file other than the class (the options/logger/held-reading shapes, helpers, constants, refusal texts, record-to-document assembly), moved whole and in order
knowledge-service-host.ts 62 the host holder (built once per service, kept in a WeakMap) and the intersection of the five host interfaces

None of the names collides with the existing knowledge-build.ts, knowledge-build-actions.ts, knowledge-record-sync-queue.ts, knowledge-sync-state.ts, knowledge-source-admission.ts, knowledge-search-scope.ts, knowledge-organization-scope.ts or split/, and nothing was folded into those modules.

Every moved member and its new file

* marks a public member (its docblock stays on the class); every other member is private and its docblock moved with its body.

File # Members
knowledge-service-sources.ts 25 settleEnablement, registerAdapter, getAdapter, adapterIdFor, boundAdapterId, refuseUnplacedSource, reportUnmountedAdapters, listAdapters, registerSource, registerMetadataSource, metadataSources, onSourcesChanged, sourcesChanged, unregisterSource, dropMetadataSource, forget, listSources, describeSources, getSource, describeSource*, handed, handedSources, adapterLabel, faceOfKey, requireEntry
knowledge-service-indexing.ts 32 planIndex, prepareDocuments, readChunkTarget, reindexSource, reindexWith, walkObjectSource, completeBuild, readIndexStateOf, buildRecord, rebuildSource, rebuildOf, buildUnderLease, syncStateIdentity, syncStateWriteFailed, storedCounts, recordBuildStart, recordBuildProgress, recordBuildEnd, closeStaleBuild, closeInterruptedBuilds, buildSourcesAtBoot, buildReloadedSource, buildIfDue, stopBuilds, reconcileSources, enqueueReconcile, reconcilePass, reconcileOf, reconcileExclusion, requestReconcile*, armReconcile, cancelPendingReconcile
knowledge-service-record-sync.ts 29 recordSources, hasDurableSyncState, syncStateOf, pendingRecordSyncs, recordSyncFailure, requestSourceReconcile, clearRepairedFailures, deadLettersOf, recordSyncQueued (getter), enqueueRecordSync, publishRecordSyncs, processRecordSync, resolveRecordSync, coveredByBuild, processRecordSyncBatch, syncRecordGroup, recordSyncWaiting, sourceRowCount, considerBacklogReconcile, syncRows, handleRecordUpsert, syncRecord, syncRow, writeSynced, reportUnindexable, reportWhereUnenforceable, serializeRecordSync, schemaFor, handleRecordDelete*
knowledge-service-search.ts 19 search, searchWithRefusals, searchByKey, sourcesGroupableBy, groupKeyOf, affinityOrderFor, affinityFactsOf, answerByRecord, checkFreshness, dropUnverifiedHits, repairStale, planSearches, unprovenIndex, searchRound, sourcesInScope, sourcesNarrowedToVisible, readVisibleIds, checkScope, resolveSearchTargets
knowledge-service-admission.ts 9 admitSources, admissionDeps, admitAuthoredSource*, unmountedAdapterSaveText, reportGateFailure, readTenancyPosture, scopeByOrganization, sourcesForObject, applyPermissionFilter

114 members moved. Stay on the class, as they were: the 25 fields; eight members that were already one-call delegations at the base (heldReading, adapterFor, indexedSources, label, readIndexState, useRecordSyncQueue, facedRefusals, routeRecordSyncs); and two exceptions rows (below).

The facade gate

scripts/facade-delegation-registry.json gains a facades row for KnowledgeService, a ceilings row for knowledge-service.ts (baseLines 1658 at baseCommit 4c4a984, maxLines 1758 = CEILING_MARGIN 100, ruling 6897467376), and two exceptions rows (card #38660):

  • constructor: state-owning, it reads defaultTopK and enabledByConfiguration off the options into the instance's own fields (the card's "facade keeps fields, constructor").
  • knowledgeTools: bare-this, its body hands the service itself to createKnowledgeTools(this); a facet body is handed the host, so moving it would hand the tool executor the host instead of the service.

The gate's self-test (N7) holds DECLARED_WATCH_HINTS equal to the registry's facade files, so scripts/check-facade-delegation-only.mjs gains the one path string; nothing else in the gate changes.

Three generated or ledgered consequences of the move

  • content/docs/permissions/system-context.mdx: the four isSystem read sites (admitAuthoredSource, admitSources, applyPermissionFilter, searchByKey) now live in the admission and search modules; the generated site register was rewritten by node scripts/check-system-context-census.mjs --write (four anchor paths, nothing else on the page).
  • scripts/tenant-audit-census.mjs: one UNTYPED_RECEIVERS row for knowledge-service-record-sync.ts, receiver adapter (this.adapterFor(source) read through the host, engine: false), the same receiver the existing knowledge-reap-guard.ts row already rules on. Inside the class the census read the method's return type; through the host it cannot.
  • packages/spec/liveness/knowledge_source.json: the ledger cited ten bodies as knowledge-service.ts#NAME; check:liveness resolves the symbol in the cited file, and documentKeyOf no longer lives there, so the gate turned red. Each of the ten citations now names the module that holds the body (dropMetadataSource in sources; walkObjectSource, reindexWith, buildIfDue in indexing; syncRecord in record sync; admitAuthoredSource in admission; affinityOrderFor in search; recordToDocument, objectSourcesFor, documentKeyOf in top-level). No verdict or other text changes. The ledger ships in @objectstack/spec, so the changeset names that package with a patch too.

Net growth beyond a pure move (package source: 5,571 lines before, 7,356 after)

  • 114 one-call stubs on the class (the bodies' signatures kept; 7 non-literal parameter defaults become ? on the stub and stay on the facet, which emits the same declaration; async dropped on the stubs so each returns the facet's own promise, the SqlDriver precedent).
  • The static host block on the class: 120 lines.
  • Five host interfaces, one per facet module: 220 lines; a this parameter on each facet function that reads the service (110 of 114).
  • 44 one-line docblocks on facet functions: 40 point a public member's body at the class's docblock, 4 name a private member that had none.
  • Module headers (about 30 lines each) and the import blocks of the seven new modules.
  • The re-export block in knowledge-service.ts (every name it exported before is still exported from it), and export added to 43 top-level declarations a facet or the facade reads (none reaches index.ts).
  • knowledge-service-host.ts: 62 lines.
  • No type is re-declared.

Published bytes and the changeset

The package's dist changes (its code moves between chunks), so this is not skip-changeset: one patch changeset for @objectstack/service-knowledge (and @objectstack/spec, for the ledger above). The published declaration is unchanged where it is public: built before and after, dist/index.d.ts carries the same 95 top-level declarations with the same text (94 byte-identical, imports and the export list equal as sets); the one that differs is KnowledgeService, whose declaration is line-for-line identical once comments are set aside: the 70 private members whose docblocks moved with their bodies lose those comments. The bundle lists its declarations in another order. dist/testing.d.ts is byte-identical.

Tests

No test file changed. Every moved body was checked as a move, not a rewrite: a throwaway verifier (not committed) proves each of the 114 functions' body, parameters, type parameters, return type and async are token-identical to the base member, every string and template literal byte-identical, and each of the 68 top-level declarations byte-identical but for an added export; it reds on a one-character change (negative control).

Readings at head ad4f458a7c unless a block says otherwise.

service-knowledge suite and typecheck at ad4f458: 25 files, 836 tests pass

os-verify-lock.sh -c 'pnpm --filter @objectstack/service-knowledge test && pnpm --filter @objectstack/service-knowledge typecheck': Test Files 25 passed (25), Tests 836 passed (836), typecheck (tsc plus check:test-typecheck) clean, VERDICT command-exit 0. The same 25 files and 836 tests as on main; no test file changed.

knowledge pins in other packages at 5fffac6: all pass

Run at the merge head 5fffac643b; between it and ad4f458a7c the package source differs only in seven comment lines (facet docblock wording and two module headers), plus the liveness ledger and the changeset.

  • core row-serving and knowledge pins: 3 files, 34 tests
  • service-knowledge-memory: 2 files, 56 tests
  • service-knowledge-turso: 3 files, 267 tests
  • mcp: 1 file, 22 tests
  • runtime: 4 files, 198 tests
  • service-settings: 4 files, 192 tests
  • objectql: 1 file, 7 tests
  • rest: 1 file, 82 tests
  • spec token-estimate: 1 file, 29 tests
  • cli pin: 1 file, 2 tests
  • NOT MEASURED: service-knowledge-pgvector live tests, reason: they need a running Postgres, which this container does not have; CI runs them.
Derived gate families at ad4f458: 121 derived, 118 exit 0, 3 NOT MEASURED

node scripts/pm/dispatch-gates.mjs --commands (no paths; derived from the tree of objectstack-ai/objectstack at ad4f458a7c) named 121 commands; all 121 were run, each exit code captured before any pipe, and --ran reconciled the record: 121 derived famil(ies) accounted for — 118 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3).

Among the 118 at exit 0: check-facade-delegation-only (KnowledgeService: 150 members, 123 delegations, 25 fields, 2 named exceptions; knowledge-service.ts 1658 lines, ceiling 1758) and its self-test, tenant-audit-census and its self-test, check:system-context-census, spec check:liveness, check:empty-state, the changeset gates, check-plugin-teardown-shape --self-test, check:platform-checklist and check:pm-dispatch-gates.

NOT MEASURED (each exited 3, prerequisite not met: they read the built dist/ of every package, and this container did not build the whole workspace; CI runs them):

  • pnpm --filter @objectstack/spec run check:skill-examples
  • pnpm check:dual-build-cjs-loads
  • pnpm check:published-readme-exports

node scripts/check-platform-checklist.mjs --changed-from origin/main: exit 0, no anchored file in the change set.

Published declaration, built before and after

dist/index.d.ts: 95 top-level declarations before and after; 94 byte-identical, imports and the export list equal as sets. KnowledgeService is line-for-line identical once comments are set aside (70 private members lose the docblocks that moved with their bodies). dist/testing.d.ts: byte-identical.

Acceptance notes

  • knowledge-service.ts is 1,658 lines, below the 2,000 bar; what remains is the public docblocks (the published contract), the 25 documented fields, the stubs and the host block.
  • Five files outside the package change because they cite the moved code, none in behaviour: the facade gate's watch-hint list and its registry, one tenant-audit census row, the generated isSystem register on the system-context page, and the knowledge_source liveness ledger. These are additions to the claim's file surface, declared here.
  • The cards that follow on the new files (reconcile, save admission, adjacent passages) land in knowledge-service-indexing.ts, knowledge-service-admission.ts and knowledge-service-search.ts respectively.

Verification

Read first, by risk:

  1. knowledge-service.ts, the static block at the end of the class: every field a body assigns needs its setter there (six do), or the write lands on nothing; the five host interfaces type-check that every member a body reads is there.
  2. knowledge-service-host.ts: the host is built once per service and cached, so a body's this is the same object across calls.
  3. knowledge-service.ts, the stubs of registerMetadataSource, planIndex, reindexSource, reconcileSources, search, searchWithRefusals and answerByRecord, whose non-literal defaults moved to the facet.

Two-minute check: pnpm --filter @objectstack/service-knowledge test (expect 25 files, 836 tests passing, the same suite as main) and node scripts/check-facade-delegation-only.mjs (expect the KnowledgeService line: 150 members, 123 delegations, 25 fields, 2 named exceptions, and knowledge-service.ts: 1658 lines, ceiling 1758).

Signed: repo:objectstack#2 · os-warren · session_01JQwxbZLuMpo8YX4ACmyoNd


Generated by Claude Code

🤖 Generated with Claude Code

https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd

…o on its facet body

Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd
Co-authored-by: Claude <noreply@anthropic.com>
…ies at their modules

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

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/service-knowledge, @objectstack/spec, touching 381 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/spec/liveness/knowledge_source.json), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

51 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json 5ac1ee0bc8a79ab2238ded80123ba91623ad6081.

⛔ 19 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 1 changed file(s) yielded no anchor (packages/spec/liveness/knowledge_source.json) — pages documenting those are invisible to this run
  • 3 anchor(s) matched too much of the corpus to be a work list: PERMISSION_DENIED (literal, 56 pages), VALIDATION_ERROR (literal, 40 pages), organization_id (literal, 43 pages)
  • 37 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 — 182 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 5ac1ee0bc8a79ab2238ded80123ba91623ad6081 → packageMentionDocs.

Which tree this was computed on

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

node scripts/docs-audit/affected-docs.mjs --json 5ac1ee0bc8a79ab2238ded80123ba91623ad6081

⚠️ 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 5ac1ee0bc8a79ab2238ded80123ba91623ad6081 → 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#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

维护者速读

  • 这是什么:知识服务主文件 knowledge-service.ts 原来 5,571 行,按你 「同意,立卡」「按照 fable的方案」 拆成 5 个关注点模块(知识源、建索引、记录同步、检索、准入),原类只留 1,658 行,方法都是一行转调。之后的知识卡改这块代码时不必再排队等同一个文件。
  • 用户能看到什么变化:没有。这是纯搬移,行为不变。席位另派了一个独立核对,逐个比较 114 个转调方法和 68 个顶层声明的代码,结果完全一致;对外导出的名字和公开方法与改前相同。核对还故意改动了 4 处,全部被查出来。
  • 风险:改动行数大(+6,162 / −4,333,超过 3,000 行),按规则要人工批准后才能合并。代码内容只是换了位置。
  • 要你做什么:请 os-zhuang 批准(已请求)。冻结解除后由席位入队。

席位核对

ACCEPT · L1 · area o2-A · Head-sha ad4f458a7cee52716072fa5581efa57f89d6d4e3 · 2026-11-30T06:05Z

  • Face: no governed path (check-governed-merges --pr 38700: 0 of 14 paths on the register). Size 10,495 lines > 3,000, so a human merge or an authorized approval is needed. Clause-②: no / Metadata-protocol: none. The patch changeset for @objectstack/service-knowledge and @objectstack/spec is accepted, because the dist chunks move.
  • Move-only, checked independently (the seat's own read-only check, not the dev's script). AST leaf-token comparison, comments excluded, against the merge base 25ac5dfa. Nothing under service-knowledge or the gate-fed files differs from 39064f62.
    • 114 members delegate in one call (Facet.fn.call(knowledgeServiceHost.of(this), …params)), and their bodies are token-identical to the base. Parameters, defaults, async, return and type parameters all match.
    • 35 members stay on the class unchanged: 25 fields, the constructor and 9 methods.
    • 68 non-class declarations are token-identical and in base order.
    • index.ts exports the same 83 names, the facade module the same 24, and KnowledgeService the same 47 public members.
    • Six members moved a parameter default to the facet (p?: T on the class). The emitted declaration and the behaviour are the same.
    • Host wiring: every this.x a facet reads is a host key, and the six fields the facets assign have setters. There is no super, arguments or bind.
    • Negative control: 4 of 4 mutations caught (a negated condition, one template-literal space, a constant, swapped delegator arguments).
  • Gate-fed files, all mechanical, admitted by amendment 7269887394:
    • check-facade-delegation-only.mjs: one watch path.
    • tenant-audit-census.mjs: one receiver row.
    • system-context.mdx: paths only.
    • knowledge_source.json: 14 file#symbol citations, all present at head.
  • Registry (fable plan, rulings 6624258595 / 6897467376):
    • A KnowledgeService facade row.
    • A ceiling of 1,658 lines, with a maximum of 1,758 (CEILING_MARGIN 100).
    • Two exceptions: the constructor, and knowledgeTools, which passes the service itself.
  • Checks at this head: 72 runs, 62 success, 10 skipped, 0 failed, none running. Mergeable, clean.
  • Changeset: read against the diff, true.
  • Landing: over the human-merge line. The seat requests approval from the governed approvers. After an approval, the seat lands it through the queue once the release freeze lifts. Fixes #38660 closes the card on merge. Knowledge cards queued behind this split stay paused on the maintainer's word (2026-11-30T05:39Z).

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

Contract-review-claim: session_01JQwxbXyLoBzNYY1U8SNPFu · head ad4f458 · 2026-11-30T06:05Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: ad4f458a7cee52716072fa5581efa57f89d6d4e3
Local-runs: probe — read-only text comparison of the base and head git blobs (no build, no test, no gate re-run)
Scope: packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/knowledge-service-sources.ts, packages/services/service-knowledge/src/knowledge-service-indexing.ts, packages/services/service-knowledge/src/knowledge-service-record-sync.ts, packages/services/service-knowledge/src/knowledge-service-search.ts, packages/services/service-knowledge/src/knowledge-service-admission.ts, packages/services/service-knowledge/src/knowledge-service-top-level.ts, packages/services/service-knowledge/src/knowledge-service-host.ts, scripts/facade-delegation-registry.json + scripts/check-facade-delegation-only.mjs, scripts/tenant-audit-census.mjs, packages/spec/liveness/knowledge_source.json
Security-touching: no
Rule-change-verified: none

PR #38700 on card #38660, reviewed for its size (10,495 changed lines), not for a contract path: reviewFace reads no face off the file list. The question asked is whether this is the move-only split the card and the approved large-file plan ordered, with the registry rows the plan names. Inputs: the card body and its five comments, the PR body and file list, the net diff against merge-base 25ac5dfa9c, and the 72 check-runs on the head. The remainder of the diff (.changeset/38660-knowledge-service-split.md, the generated register in content/docs/permissions/system-context.mdx) is the lane seat's ACCEPT at TIER_DEFAULT.

① Derived judgments

  • Package entry: RIGHT. packages/services/service-knowledge/src/index.ts and the package manifest are not in the diff. knowledge-service.ts exported 24 names at the base and exports the same 24 at the head (14 values and 9 types re-exported from knowledge-service-top-level.ts, plus the class): none missing, none added.
  • Public members of KnowledgeService: RIGHT. 124 members at the base, 124 at the head, the same 48 public and 76 private. No member changes visibility or name. Every public member's docblock on the class is identical to the base.
  • Signatures: RIGHT. The only signature lines of the class that differ from the base are (a) async dropped on stubs whose facet body is still async, so the stub returns the facet's own promise and adds no microtask hop, and (b) seven non-literal parameter defaults written as optional on the stub, with the default kept on the facet (registerMetadataSource, planIndex, reindexSource, reconcileSources, search, searchWithRefusals, answerByRecord). Both emit the same declaration. A throw inside a formerly-async member is still a rejection, because the facet function is the async one.
  • The 43 declarations that gained export in knowledge-service-top-level.ts: RIGHT. They are module-internal; index.ts re-exports nothing from the new modules.
  • Accept sets: none changes. No schema, no REST route, no refusal text, no error code is edited: every string in a moved body is on a line identical to the base.
  • Gate verdicts, read off the head's check-runs (72: 62 success, 10 skipped, 0 failure, 0 pending): Lint & Repo Gates, TypeScript Type Check, Test Core (12/12 shards), Build Core, Governed Surface Queue Guard, Type Check UI, Test UI, Build & E2E UI, Live E2E UI, Dogfood Regression Gate, Spec property liveness, Check Changeset and Check PR Size are success. Lint UI and Temporal Conformance (live PG + MySQL) are skipped on this PR run; the queue run carries them.

② Semver level

Clause-②: no — matches the PR body and the changeset; no arm. Metadata-protocol: none is right: nothing an author can write changes.

patch on @objectstack/service-knowledge is right: the package's dist moves between chunks, so the diff publishes, and skip-changeset would have been wrong. patch on @objectstack/spec is right: packages/spec/package.json lists liveness under files, so the ledger edit ships. Not breaking, no ADR-0087 disposition owed.

③ Boundary flags

The report's open_questions is empty. Its seven deviations:

  1. Model-free commit trailer pair: conforms to AGENTS.md; not a deviation of the tree.
  2. Changeset in place of skip-changeset: correct, see ②.
  3. Four files beyond the package (check-facade-delegation-only.mjs, tenant-audit-census.mjs, system-context.mdx, knowledge_source.json): admitted by claim amendment 7269887394; each is judged in ④ or is generated output.
  4. One early push chained to an overlap check that could not answer on a shallow clone: process, the seat's; it has no bearing on this head, and the final push followed a clean check.
  5. Pins in other packages read at 5fffac643b: superseded, Test Core is green on the head itself.
  6. PR body signature line: no bearing.
  7. Three gates and the pgvector live tests not measured locally: the three gates are answered by the head's green lint and type-check jobs. The pgvector live tests are answered by no check-run I can name on this head; the seat confirms them on the queue run before it lands. No moved line touches the pgvector package.

SQL push-down: no finding. The diff adds no query, no id materialisation and no in-app join; every engine call sits on a line identical to the base.

Security: the moved bodies include the permission and admission paths (admitSources, admitAuthoredSource, applyPermissionFilter, scopeByOrganization, readVisibleIds). Their lines are identical to the base and the four isSystem read sites are the same four, re-anchored. No hunk changes or teaches permission, sharing, credential or authentication behaviour, and no hits path is under skills/**.

Escalated: nothing.

④ Design judgment

How the move was read: the base blob of knowledge-service.ts and the eight head blobs were compared as text, member by member, with scripts of my own in scratch space. Nothing was built, run or re-run; the dev's verifier was not used.

knowledge-service-sources.ts, -indexing.ts, -record-sync.ts, -search.ts, -admission.ts — holds. 114 exported functions (25, 32, 29, 19, 9), each named for a base member. For all 114 the body is line-for-line identical to the base member's body once leading indentation is set aside, and the header is identical but for the dropped private or get keyword and the added this parameter. No facet function lacks a stub and no stub lacks a facet function. Every private member's docblock moved with its body unchanged. No body uses this other than as this.member, and none uses arguments or super, so handing a body the host in place of the service cannot change what it sees. Each module imports knowledge-service.ts for types only, so there is no evaluation cycle; no module the facets import by value imports the class module back.

knowledge-service-top-level.ts — holds. After its import block it is the base file's non-class text in the same order; the only differences are 43 added export keywords and blank lines. It holds no module-level mutable state, so nothing is instantiated twice.

knowledge-service.ts — holds. 1,658 lines, under the card's 2,000 bar. Before the static block, the class's only lines absent from the base are stub signatures as in ① and the stub calls; each stub forwards every parameter, in order, to the facet function of its own name. The constructor, the 25 fields, knowledgeTools and the eight members that were already one-call delegations are unchanged. Tried to break the host: (a) a field a body assigns with no setter would throw in strict mode and type-checks anyway, since a getter-only property satisfies a mutable interface member. The facets assign exactly six fields (enablementPending, held, syncStateWriteReported, buildsStopped, reconcileTail, recordSyncBacklog) and the host has exactly those six setters. (b) Every host method is a closure of its own name that calls the service at call time, and every getter and setter reads the field of its own name, so an instance spy, a prototype spy and a subclass override are still what an internal call reaches. (c) The host is cached per service in a WeakMap, so a body's this is one object for the service's life and does not pin it.

knowledge-service-host.ts — holds. Its header's three claims are true of the code: type-only imports, built on first use and kept, a loud throw if the factory was never installed.

scripts/facade-delegation-registry.json — holds against the card. One facades row for KnowledgeService on card #38660. One ceilings row: baseLines 1658 is the file's line count at baseCommit 4c4a984345 (and at the head), maxLines 1758 is baseLines plus CEILING_MARGIN 100, ruling 6897467376 as the card's amendment names. A branch commit as baseCommit follows the existing rows (c27f4ab0d6 is not on main either). Two exceptions rows, constructor and knowledgeTools, each with a reason that is true of the body.

scripts/check-facade-delegation-only.mjs — agrees. One added path in DECLARED_WATCH_HINTS, which the gate's own header requires of the PR that registers a new facade file; nothing else in the gate changes.

scripts/tenant-audit-census.mjs — agrees. The new UNTYPED_RECEIVERS row says receiver adapter in knowledge-service-record-sync.ts is a knowledge index adapter, engine: false. True of every adapter in that file: four are this.adapterFor(source), the rest are parameters typed IKnowledgeAdapter; none is a data engine, so the row hides no engine write.

packages/spec/liveness/knowledge_source.json — agrees. Ten citations repointed; each of the ten symbols is declared in the module the new citation names, no citation of knowledge-service.ts remains in the ledger, and no status, date or note changes.

Findings:

  • N1 (nit) — the two new exceptions rows name #38660 as their card, and this PR closes that card. The gate's header knows two kinds of row: one whose card will move the member, and an accepted terminal one whose reason opens with the ruling that accepted it. After the merge these two are neither in form: no open card moves constructor or knowledgeTools, and their reasons open with state-owning: and bare-this:. The card's acceptance does order an exceptions row with its reason for a member that must stay, so the rows are what was asked, the gate accepts them, and nothing at run time depends on it. knowledgeTools stays for a bare this, a second reason beside the card's "state-owning"; the reason given is correct. Left as an accepted deviation; if the maintainer wants the rows in terminal form or wants knowledgeTools moved through an identity port, that is a follow-up card, not a change on this head.

Observation, not a finding: ADR-0096 and ADR-0161 cite knowledge-service.ts#MEMBER for members whose bodies moved. The citations still resolve, because every member stays on the class as a stub, and the PR is right to leave docs/adr/** untouched.

No must-fix, no should-fix.

Implemented-by: claude/project-thread-e6npb2
Reviewed-by: session_01JQwxbXyLoBzNYY1U8SNPFu

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

Contract review

Served-tier: TIER_DEFAULT
Head-sha: ad4f458a7cee52716072fa5581efa57f89d6d4e3
Local-runs: probe — read-only text comparison of the base and head git blobs (no build, no test, no gate re-run)
Scope: packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/knowledge-service-sources.ts, packages/services/service-knowledge/src/knowledge-service-indexing.ts, packages/services/service-knowledge/src/knowledge-service-record-sync.ts, packages/services/service-knowledge/src/knowledge-service-search.ts, packages/services/service-knowledge/src/knowledge-service-admission.ts, packages/services/service-knowledge/src/knowledge-service-top-level.ts, packages/services/service-knowledge/src/knowledge-service-host.ts, scripts/facade-delegation-registry.json + scripts/check-facade-delegation-only.mjs, scripts/tenant-audit-census.mjs, packages/spec/liveness/knowledge_source.json
Security-touching: no
Rule-change-verified: none

PR #38700 on card #38660, reviewed for its size (10,495 changed lines), not for a contract path: reviewFace reads no face off the file list. The question asked is whether this is the move-only split the card and the approved large-file plan ordered, with the registry rows the plan names. Inputs: the card body and its five comments, the PR body and file list, the net diff against merge-base 25ac5dfa9c, and the 72 check-runs on the head. The remainder of the diff (.changeset/38660-knowledge-service-split.md, the generated register in content/docs/permissions/system-context.mdx) is the lane seat's ACCEPT at TIER_DEFAULT.

① Derived judgments

  • Package entry: RIGHT. packages/services/service-knowledge/src/index.ts and the package manifest are not in the diff. knowledge-service.ts exported 24 names at the base and exports the same 24 at the head (14 values and 9 types re-exported from knowledge-service-top-level.ts, plus the class): none missing, none added.
  • Public members of KnowledgeService: RIGHT. 124 members at the base, 124 at the head, the same 48 public and 76 private. No member changes visibility or name. Every public member's docblock on the class is identical to the base.
  • Signatures: RIGHT. The only signature lines of the class that differ from the base are (a) async dropped on stubs whose facet body is still async, so the stub returns the facet's own promise and adds no microtask hop, and (b) seven non-literal parameter defaults written as optional on the stub, with the default kept on the facet (registerMetadataSource, planIndex, reindexSource, reconcileSources, search, searchWithRefusals, answerByRecord). Both emit the same declaration. A throw inside a formerly-async member is still a rejection, because the facet function is the async one.
  • The 43 declarations that gained export in knowledge-service-top-level.ts: RIGHT. They are module-internal; index.ts re-exports nothing from the new modules.
  • Accept sets: none changes. No schema, no REST route, no refusal text, no error code is edited: every string in a moved body is on a line identical to the base.
  • Gate verdicts, read off the head's check-runs (72: 62 success, 10 skipped, 0 failure, 0 pending): Lint & Repo Gates, TypeScript Type Check, Test Core (12/12 shards), Build Core, Governed Surface Queue Guard, Type Check UI, Test UI, Build & E2E UI, Live E2E UI, Dogfood Regression Gate, Spec property liveness, Check Changeset and Check PR Size are success. Lint UI and Temporal Conformance (live PG + MySQL) are skipped on this PR run; the queue run carries them.

② Semver level

Clause-②: no — matches the PR body and the changeset; no arm. Metadata-protocol: none is right: nothing an author can write changes.

patch on @objectstack/service-knowledge is right: the package's dist moves between chunks, so the diff publishes, and skip-changeset would have been wrong. patch on @objectstack/spec is right: packages/spec/package.json lists liveness under files, so the ledger edit ships. Not breaking, no ADR-0087 disposition owed.

③ Boundary flags

The report's open_questions is empty. Its seven deviations:

  1. Model-free commit trailer pair: conforms to AGENTS.md; not a deviation of the tree.
  2. Changeset in place of skip-changeset: correct, see ②.
  3. Four files beyond the package (check-facade-delegation-only.mjs, tenant-audit-census.mjs, system-context.mdx, knowledge_source.json): admitted by claim amendment 7269887394; each is judged in ④ or is generated output.
  4. One early push chained to an overlap check that could not answer on a shallow clone: process, the seat's; it has no bearing on this head, and the final push followed a clean check.
  5. Pins in other packages read at 5fffac643b: superseded, Test Core is green on the head itself.
  6. PR body signature line: no bearing.
  7. Three gates and the pgvector live tests not measured locally: the three gates are answered by the head's green lint and type-check jobs. The pgvector live tests are answered by no check-run I can name on this head; the seat confirms them on the queue run before it lands. No moved line touches the pgvector package.

SQL push-down: no finding. The diff adds no query, no id materialisation and no in-app join; every engine call sits on a line identical to the base.

Security: the moved bodies include the permission and admission paths (admitSources, admitAuthoredSource, applyPermissionFilter, scopeByOrganization, readVisibleIds). Their lines are identical to the base and the four isSystem read sites are the same four, re-anchored. No hunk changes or teaches permission, sharing, credential or authentication behaviour, and no hits path is under skills/**.

Escalated: nothing.

④ Design judgment

How the move was read: the base blob of knowledge-service.ts and the eight head blobs were compared as text, member by member, with scripts of my own in scratch space. Nothing was built, run or re-run; the dev's verifier was not used.

knowledge-service-sources.ts, -indexing.ts, -record-sync.ts, -search.ts, -admission.ts — holds. 114 exported functions (25, 32, 29, 19, 9), each named for a base member. For all 114 the body is line-for-line identical to the base member's body once leading indentation is set aside, and the header is identical but for the dropped private or get keyword and the added this parameter. No facet function lacks a stub and no stub lacks a facet function. Every private member's docblock moved with its body unchanged. No body uses this other than as this.member, and none uses arguments or super, so handing a body the host in place of the service cannot change what it sees. Each module imports knowledge-service.ts for types only, so there is no evaluation cycle; no module the facets import by value imports the class module back.

knowledge-service-top-level.ts — holds. After its import block it is the base file's non-class text in the same order; the only differences are 43 added export keywords and blank lines. It holds no module-level mutable state, so nothing is instantiated twice.

knowledge-service.ts — holds. 1,658 lines, under the card's 2,000 bar. Before the static block, the class's only lines absent from the base are stub signatures as in ① and the stub calls; each stub forwards every parameter, in order, to the facet function of its own name. The constructor, the 25 fields, knowledgeTools and the eight members that were already one-call delegations are unchanged. Tried to break the host: (a) a field a body assigns with no setter would throw in strict mode and type-checks anyway, since a getter-only property satisfies a mutable interface member. The facets assign exactly six fields (enablementPending, held, syncStateWriteReported, buildsStopped, reconcileTail, recordSyncBacklog) and the host has exactly those six setters. (b) Every host method is a closure of its own name that calls the service at call time, and every getter and setter reads the field of its own name, so an instance spy, a prototype spy and a subclass override are still what an internal call reaches. (c) The host is cached per service in a WeakMap, so a body's this is one object for the service's life and does not pin it.

knowledge-service-host.ts — holds. Its header's three claims are true of the code: type-only imports, built on first use and kept, a loud throw if the factory was never installed.

scripts/facade-delegation-registry.json — holds against the card. One facades row for KnowledgeService on card #38660. One ceilings row: baseLines 1658 is the file's line count at baseCommit 4c4a984345 (and at the head), maxLines 1758 is baseLines plus CEILING_MARGIN 100, ruling 6897467376 as the card's amendment names. A branch commit as baseCommit follows the existing rows (c27f4ab0d6 is not on main either). Two exceptions rows, constructor and knowledgeTools, each with a reason that is true of the body.

scripts/check-facade-delegation-only.mjs — agrees. One added path in DECLARED_WATCH_HINTS, which the gate's own header requires of the PR that registers a new facade file; nothing else in the gate changes.

scripts/tenant-audit-census.mjs — agrees. The new UNTYPED_RECEIVERS row says receiver adapter in knowledge-service-record-sync.ts is a knowledge index adapter, engine: false. True of every adapter in that file: four are this.adapterFor(source), the rest are parameters typed IKnowledgeAdapter; none is a data engine, so the row hides no engine write.

packages/spec/liveness/knowledge_source.json — agrees. Ten citations repointed; each of the ten symbols is declared in the module the new citation names, no citation of knowledge-service.ts remains in the ledger, and no status, date or note changes.

Findings:

  • N1 (nit) — the two new exceptions rows name #38660 as their card, and this PR closes that card. The gate's header knows two kinds of row: one whose card will move the member, and an accepted terminal one whose reason opens with the ruling that accepted it. After the merge these two are neither in form: no open card moves constructor or knowledgeTools, and their reasons open with state-owning: and bare-this:. The card's acceptance does order an exceptions row with its reason for a member that must stay, so the rows are what was asked, the gate accepts them, and nothing at run time depends on it. knowledgeTools stays for a bare this, a second reason beside the card's "state-owning"; the reason given is correct. Left as an accepted deviation; if the maintainer wants the rows in terminal form or wants knowledgeTools moved through an identity port, that is a follow-up card, not a change on this head.

Observation, not a finding: ADR-0096 and ADR-0161 cite knowledge-service.ts#MEMBER for members whose bodies moved. The citations still resolve, because every member stays on the class as a stub, and the PR is right to leave docs/adr/** untouched.

No must-fix, no should-fix.

Implemented-by: claude/project-thread-e6npb2
Reviewed-by: session_01JQwxbXyLoBzNYY1U8SNPFu

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

2026-11-30T06:14Z · L1 ACCEPT and hand-off · #38660 (KnowledgeService split, move-only) at ad4f458a7c.

  • Seat record 7270294239: 维护者速读 + 席位核对 ACCEPT on this head.
  • Move-only checked independently: 114 delegations, 35 kept members and 68 declarations are token-identical to the base, the public surface is unchanged, and the negative control caught 4/4.
  • Contract review at CONTRACT_REVIEW_TIER: PASS on this head (7270418051, re-posted with the face's served tier TIER_DEFAULT; the review ran at CONTRACT_REVIEW_TIER). No must-fix, no should-fix. N1 (the two exceptions rows name the card this PR closes) is accepted as a deviation. Before landing, the seat confirms on the queue run that the pgvector live tests pass.
  • Checks at this head: 62 success, 10 skipped, 0 failed, 0 pending.
  • Over the human-merge line (10,495 lines): requesting approval from the governed approvers. Release freeze: no enqueue by the seat until it lifts.

@github-actions

Copy link
Copy Markdown
Contributor

⛔ merge queue 构建失败 — 先分诊,再决定要不要重排

队列构建 46372721759 红了。队列跑的是全量套件(PR 侧 CI 只跑 affected 子集),
所以失败的测试可能在本 PR 没碰过的包里 —— 那不是重排能修的。每次盲目重排都会让排在后面的所有 PR 重建一轮。

分类:failure —— 按下面的日志分诊。

失败的 job(日志抽取,best effort):

  • Dogfood Regression Gate (3/3) — 失败步骤: Boot example apps and exercise real user flows

    @objectstack/dogfood:test:  FAIL   isolated  test/package-move-in.dogfood.test.ts > dogfood: POST /packages/:id/move-in, the move door (#38150) > A3 (#37468) and the set rule: flow, dataset and report
      ↳ 失败原因: @objectstack/dogfood:test: AssertionError: expected 404 to be 200 // Object.is equality
    

↳ 失败原因 是判读的关键:超时(Test timed out in … / Hook timed out in …)多半是负载/时序,不是本 PR 的回归;
断言(AssertionError: …)才指向真实的行为改变。两者的 FAIL 行长得一模一样,只有这一行能区分。

⚠️ 断言这一侧有一类例外,判据是断言在测什么,不是它是不是 AssertionError。 断言的对象是产品行为(一个值、一个形状、一次拒收)⇒ 照上面读:真实的行为改变,去查,⛔ 不要重排掉;
断言的对象是这次实验自身的有效性前提(跑完的耗时、负载下的先后、任何只在时间预算内才成立的条件)⇒ 它跟超时是同一类,同样对负载敏感,重排一次是合法的判别手段。
识别是机械的:断言的消息或它比较的值本身点名了一段时长、一个时间戳、一个耗时计数。实测过的一对 —— AssertionError: SecurityPlugin.init() ran: expected false to be true 测的是产品行为(真回归);
AssertionError: this run took over a second, so second-precision stamps could have differed too: expected 1006 to be less than 1000 测的是实验前提:它守护的那条不变式当时是绿的,同一个 head 原样重排一次即成功。
穿着 AssertionError 外衣的时间测量,仍然是时间测量。(⛔ 这只改「怎么读一次红」,不改「哪些测试可以重排」——后者由别处管。)

跨 PR 相同签名(24h,按失败测试文件聚合):

历史信号:

  • 本 PR 过去 24h 无队列失败记录(首次)。
  • 过去 24h 队列共有 4 个失败构建(不含本次)。

分诊清单:

  1. 失败测试在本 PR 改动的包里 → 真回归,修 PR。
  2. 失败测试与本 PR 无关 → 看上面的「跨 PR 相同签名」;已有汇总 issue ⇒ flaky/环境问题实锤,去那张 issue 上谈,修好前重排只会再烧一轮全队列。
  3. 两者都不是 → 可能与同组 PR 语义冲突;等前面的 PR 落地或失败出队后再重排一次即可,不要连续重排。

Generated by Claude Code · merge-queue-triage workflow (#4859)

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

2026-11-30T07:46Z · Queue ejection is inherited, not this PR's. Build 46372721759 failed test/package-move-in.dogfood.test.ts A3 (404 vs 200). Anchor #38725 names #38699 as the stack root; this PR touches only service-knowledge and four gate-fed files, nothing on the move-in door. #38699 left the queue at 2026-11-30T07:36Z and is being fixed on its own branch.

Head is unchanged at ad4f458a7c; the contract PASS (7270440820) and the hand-off (7270450318) stand. Ready to re-enqueue as it is. As a governed PR it waits for the approver to enqueue it again; this seat does not.

Merged via the queue into main with commit e6b424b Nov 30, 2026
78 checks passed
@os-zhuang
os-zhuang deleted the claude/project-thread-e6npb2 branch November 30, 2026 08:03
@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 30, 2026
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
… for search_knowledge (objectstack-ai#38729)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ88oxgpPaPHgsNM7N7PvvwbS)_

Refs objectstack-ai#38719 (part 1) — the committed segment timing and the load bench.
Part 2, the baseline on the A4 environment, stays on the card, which
this PR does not close.

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户无感:只新增一个提交进仓库的测速脚本,产品行为不变。
- 属于「私有部署企业版知识检索 10 人同时提问不超时」专题的基线一项,给第三期每项做不做提供数据。
- 出错只会让测速读数不准,不影响任何客户;脚本不随软件包发布,可直接撤回。
- 无。

## What changes

A new, unpublished directory
`packages/plugins/knowledge-pgvector/bench/` (the package's `files` is
`dist`, `README.md`, `CHANGELOG.md`, so nothing here ships):

- `instrument.mjs` — per-search segment timing read through seams the
code already takes. Nothing under `src/` of this package or of
`service-knowledge` is changed:
  - `embed` — the adapter's `embedder` option;
- `pool_wait` + `ranking` + `other_sql` — the adapter's `pool` option, a
`PgPoolLike` whose one-shot query is split into checkout, statement and
release, the same steps `pg.Pool#query` runs;
- `visible_ids` + `permission_recheck` + `system_read` — the service's
`dataEngine` option, each read classified by the arguments the service
passes;
- adapter rounds (a refill round = backfill) — the adapter as registered
with the service.

Concurrent searches are kept apart by an `AsyncLocalStorage` store per
search.
- `run.mjs` — the load bench, runnable against any PostgreSQL URL with
pgvector. It seeds a synthetic dataset into two throwaway schemas,
builds the index through the real `KnowledgeService`, then makes real
`search_knowledge` calls (the tool executor, as a non-system caller)
over record-scope fraction × concurrency. Default grid: 1/10/30/100 %
and unscoped × 1/5/10/20 clients, closed loop.
- Per cell: p50/p95/max/mean of the total and of every segment, each
with its sample count; hit count; searches per question; backfill share
(scoped and unscoped cells are separate rows); embedding-call failures;
failed and refused searches with their codes; empty answers; the
service's `search failed` log lines; block reads of the store's tables.
- It also records the machine shape (client CPUs and memory; server
version, pgvector version and memory settings) and whether the cell ran
cold or warm.
- `instrument.test.mjs` — pins statement shape and call counts over the
real adapter and service from source, with no database. It never pins a
duration.
- `README.md` — the manual.

### Segment status

| segment (card) | status | seam |
|:--|:--|:--|
| embed | measured | adapter `embedder` option |
| vector statement | measured as `ranking` | adapter `pool` option; the
statement also carries the keyword leg for any query with keyword terms
(counted per cell) and the scope predicate |
| scope predicate | **NOT MEASURED in situ** | it is a conjunct of the
ranking statement's one WHERE. `--isolate-scope` adds a DERIVED
out-of-situ number: the same WHERE as a bare count minus the
source-and-generation WHERE as a bare count, run serially and timed by
the server. An in-situ number needs the store to time its statement
parts itself, a change under `knowledge-pgvector/src` (held by objectstack-ai#38692) |
| permission re-check | measured | service `dataEngine` option
(`permission_recheck` after ranking, `visible_ids` before it) |
| pool wait | measured (not on the card) | adapter `pool` option |

## Tests

- `pnpm --filter @objectstack/knowledge-pgvector test` at `8e3e522f`: 6
files passed, 8 skipped (the live-PostgreSQL files: no
`OS_TEST_POSTGRES_URL`); 29 tests passed, 93 skipped.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0. The
bench files are `.mjs` and outside the package's TS programs.
- Ablation: with `permission_recheck` reclassified on disk,
`bench/instrument.test.mjs` went red (1 failed / 4 passed); restored
with `git restore`.

<details><summary>Local smoke run — 5,000 passages, 1024 dims, 40
searches a cell (NOT a baseline, not quotable)</summary>

Machine: 4 vCPU, 15.7 GiB, shared container. PostgreSQL 16.15 with
pgvector **0.6.0** (Ubuntu package; the kit ships 0.8.7),
`shared_buffers` 512MB, pool 4, fake in-process embedder, warm. Its job
is to show the script runs the whole grid; it is not the A4 baseline.
Columns: scope · concurrency · n · total p50/p95 ms · pool wait p50 ·
ranking p50 · re-check p50 · backfill · `search failed` lines · rows in
scope.

```
1%   | 1  | 40 | 53.73 / 73.57     | 0.1     | 50.46  | 1.95 | 0 | 0 | 50
1%   | 20 | 40 | 434.59 / 625.09   | 350.72  | 71.83  | 2.21 | 0 | 0 | 50
10%  | 1  | 40 | 73.35 / 106.8     | 0.09    | 70.21  | 1.87 | 0 | 0 | 500
30%  | 1  | 40 | 114.04 / 205.01   | 0.08    | 111.08 | 1.73 | 0 | 0 | 1500
100% | 1  | 40 | 263.53 / 453.83   | 0.07    | 260.75 | 1.69 | 0 | 0 | 5000
100% | 20 | 40 | 1776.19 / 2117.96 | 1451.12 | 323.8  | 5.45 | 0 | 0 | 5000
none | 1  | 40 | 250.89 / 491.17   | 0.07    | 245.3  | 1.82 | 0 | 0 | -
none | 20 | 40 | 1295.42 / 1570.26 | 1046.31 | 241.46 | 1.56 | 0 | 0 | -
```

All 20 cells completed with 0 failed searches; the full table is in the
run's JSON.

</details>

## Acceptance notes

- **First files to read:**
1. `bench/instrument.mjs` — `classifyEngineRead`, which decides what
counts as the permission re-check, and `timedPool`, which reproduces
`pg.Pool#query`'s checkout, statement and release.
2. `bench/run.mjs` — `isolateScope`, the derived scope-predicate pass,
and its stated method.
3. `bench/instrument.test.mjs` — the pins over the real adapter and
service.
- The bench composes its own service over synthetic data (ObjectQL +
SqlDriver, no security plugin), so the re-check reads every row it asks
for. It cannot yet point at an already-indexed source in a kit
deployment (the BrightRule source on A4); part 2 has to decide that.
- At concurrency 10–20, the smoke run's time goes mostly to waiting for
one of the pool's 4 connections. That is the topic's B2 (pool size from
settings), not new scope.
- No changeset: no published file moves (`skip-changeset`).
- Seat routing (2026-11-30T08:16Z), part 2 composition: B — on A4 the
bench composes the source itself at 60k×1024; an existing-source option
(A) may follow after objectstack-ai#38700 only if needed.
- Seat routing (2026-11-30T08:16Z), scope predicate: keep the labelled
DERIVED number (`--isolate-scope`); no store seam under objectstack-ai#38692's files.

## Verification

Two-minute check, against any PostgreSQL where the role can `CREATE` and
the `vector` extension is available:

```bash
pnpm --filter '@objectstack/knowledge-pgvector...' build
node packages/plugins/knowledge-pgvector/bench/run.mjs --pg-url postgres://USER@HOST:5432/DB --passages 500 --scopes 10,none --concurrency 1,5 --searches 20 --isolate-scope
```

Expected: a markdown table with four rows, every `ok` equal to `n`, the
10% rows showing `… (derived)` in the last column and the unscoped rows
`NOT MEASURED`; the JSON path printed on stderr. Both schemas are
dropped at the end.

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

https://claude.ai/code/session_01JQwxbXQcnpisuAAJRr8yNr

<!-- signed: repo:objectstack@os-warren · os-warren ·
session_01JQwxbXQcnpisuAAJRr8yNr -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ement has a time limit, and its pool size is a setting (objectstack-ai#38726)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8VZtjriPRDBMFWChF2eLFkE)_

Fixes objectstack-ai#38718

Clause-②: yes
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:私有部署企业版在 PostgreSQL 上检索知识时,数据库忙、连接等不到或语句超时,助手会收到明确的「超时 /
暂不可用」拒绝,不再拿到「0 条命中」;检索语句默认最多跑 10 秒;连接池大小可以由运维通过设置调整。
- 为什么做:属于「私有部署企业版知识检索 10 人同时提问不超时」专题第一期,目标之一是出错不能变成空结果,首个用户是 BrightRule
制度问询。
- 出错会怎样:最坏情况是本来能跑完的超长检索(超过 10 秒)现在被拒绝为超时,运维可调大时限设置;改动只在知识检索的 PostgreSQL
适配器内,撤回即恢复原样。
- 要你做什么:无。

## What changes

Topic objectstack-ai#38703 row B2, in `@objectstack/knowledge-pgvector` only (no
change to `service-knowledge` or `core`).

1. **Coded refusals.** `search()` now answers every failure of the
store's database as an ADR-0112 refusal, judged by SQLSTATE (never by
the server's message, which `lc_messages` translates): `57014`
(statement past its limit, or cancelled) is `TIMEOUT` 504; class `53`
(`too_many_connections`, out of memory, disk full) is
`SERVICE_UNAVAILABLE` 503; no connection (the pool's wait timed out,
class `08`, `57P01`–`57P05`, a socket error) is `SERVICE_UNAVAILABLE`
503; any other SQLSTATE is `DATABASE_ERROR` 500. The message is one
sentence naming the source; the SQLSTATE, the driver text and the
setting to change go to `remedy` (operator text the service logs). An
already-coded error (the adapter's own refusals) and a non-database
error (the embedder's) pass through unchanged. New module
`src/errors.ts`.
- The pool's wait timeout carries no code at all, so `poolFromPg` now
marks every error its pool and connections throw (a non-enumerable
symbol; message, code and keys untouched, so write paths read exactly
what `pg` threw), and the classifier treats a marked uncoded error as
"no connection".
- Placement: the translation is one `try/catch` in `search()` around the
attempts loop (moved into a private `searchAttempts`); the ranking
statement's body is untouched (the objectstack-ai#38692 phase-1a pgvector PR follows
this one).
2. **Statement time limit.** The ranking statement runs through a new
`searchStatement` helper: its own transaction, `SET LOCAL
statement_timeout = N` first. Chosen form: `SET LOCAL` in a transaction,
so the limit lasts exactly one statement, touches no session state and
holds behind a transaction-mode pooler (the builder lock still needs
session mode; README says so). Default 10000 ms, the same bound the
Turso store uses for a remote request (objectstack-ai#38693); `statementTimeoutMs`
plugin/adapter option, else the setting
`OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`. Only the ranking statement is
limited; catalog reads, writes and builds are not.
3. **Pool size from a named setting.** `OS_KNOWLEDGE_POOL_MAX` (plugin
option `poolMax` wins), default **20** (raised from 4 in Rework 2 below,
on os-bob's measurement). Strict like `OS_DATABASE_POOL_MAX`: a value
that is not a positive integer stops the boot naming the setting; blank
reads as unset. The plugin reads it (as it already reads the URL from
the environment), so a composed boot (`os serve` hands `process.env`)
and a host that mounts the plugin directly read the same setting;
`resolveKnowledgeStore` in `core` needed no change. The boot line now
says the pool size, the limit and where each was read from.
- **Ratio to `max_connections = 200`** (README, "Pool size and time
limit"): `replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX +
builds running at once) + headroom ≤ max_connections`. With 20 kept as
headroom, platform pool at its default 5 and one build running, the
default of 20 fits up to 6 replicas (3 replicas = 60 store connections);
the ceiling is 84 with 2 replicas, 54 with 3, 39 with 4. A larger pool
moves waiting from the pool into the database; it does not make one
search faster. This is the setting key and ratio B12 (the delivery note)
carries.

## Why

Premise re-read on `origin/main` d2caaec before code: `codedRefusalOf`
(`knowledge-service.ts:4974`) accepts only a SCREAMING_SNAKE `code` with
an integer `status` 400–599; `searchRound` (`:3237-3249`) logs an
uncoded throw at `error` and `continue`s, and `search()` throws
`wholeRefusal` only when `refused` is non-empty (`:2561`). A `pg`
error's `code` is a SQLSTATE (`57014`) or absent, so a single-source
search answered `{ hits: [] }`. The ablation below reproduces exactly
that.

## Tests

- `src/__tests__/search-refusals.test.ts` (unit, runs everywhere, 14
cases): the statement shape (`BEGIN`, `SET LOCAL statement_timeout =
10000`, the ranking, `COMMIT`; the ranking never on a bare pooled query;
a given limit; a bad limit refused at construction); one case per error
class (statement timeout `57014`, cancel `57014` with a translated
server message, pool wait through `poolFromPg` at the ranking's connect
and at a pooled read, `53300`, `57P01`, `42P01`), each pinned on `code`
+ `status`; the embedder's uncoded error passed through by identity;
**through `KnowledgeService.search`: the caller is refused `TIMEOUT` 504
instead of an empty list**; the settings reader (precedence, blank,
strict refusals).
- `src/__tests__/search-refusals.live-postgres.test.ts` (live,
`OS_TEST_POSTGRES_URL`, no pgvector needed): a real `pg_sleep` past `SET
LOCAL statement_timeout` answers `57014` and classifies `TIMEOUT` 504,
and `SHOW statement_timeout` on the same pooled connection after the
transaction reads the session's own value; a real full pool (`max: 1`)
times out through `poolFromPg` and classifies `SERVICE_UNAVAILABLE` 503
on both `query` and `connect`. Pins codes, never durations.

<details><summary>Local readings at head 9a39db7</summary>

- `pnpm --filter @objectstack/knowledge-pgvector test`: exit 0, Test
Files 6 passed / 9 skipped (live files, no URL), Tests 38 passed / 95
skipped.
- `vitest run src/__tests__/search-refusals.live-postgres.test.ts` with
`OS_TEST_POSTGRES_URL` at a local PostgreSQL 16.15: exit 0, 2/2.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0
(incl. `check:test-typecheck`, 0 debt).
- `eslint --no-inline-config` on the five changed source/test files:
exit 0. `scripts/check-nul-bytes.mjs`: exit 0.
- `dispatch-gates.mjs --commands` (7 paths, 694 changed lines): 26 of 27
commands exit 0; `check-plugin-teardown-shape.mjs --self-test` exit 3 —
NOT MEASURED locally, reason: shallow clone cannot reach its pinned
fixture commit (the script says so); CI runs it.
- **Ablation** (fix committed first, restored with `git checkout HEAD
--`): with `search()` rethrowing the raw error, 8 of 14 cases go red,
and the `KnowledgeService` case receives `{ hits: [] }` — the defect as
filed. With `poolFromPg`'s marking removed, the two pool-wait cases go
red.

</details>

## Acceptance notes

- `Clause-②: yes` is copied from the claim. Behaviour that changes for a
caller: a database failure that used to read as zero hits from that
source is now a refusal (`refused[]`, or a whole-search refusal when it
was the only source); a search statement over 10 s is now stopped where
it used to run to completion.
- Out of scope, noted, not filed: an uncoded throw from something other
than the database (the embedder failing, a mis-sized query vector) is
still logged and skipped by `searchRound`, so it still reads as zero
hits for that source. The general fix sits in `service-knowledge`
(`searchRound` treating any uncoded throw as a refusal), which this card
was told not to touch (held by objectstack-ai#38700). carrier: objectstack-ai#38703 (topic owner) ·
noted, not filed.
- `connectTimeoutMs` (also the pool's wait) stays a plugin option only,
default 5000; the card asked for the pool size and the time limit, not
this.

## Verification

Two-minute check: `pnpm --filter @objectstack/knowledge-pgvector exec
vitest run src/__tests__/search-refusals.test.ts` — expect 14 passed,
among them "through KnowledgeService: the caller is refused TIMEOUT, not
answered an empty hit list".

Read first, by risk: `src/errors.ts` (the SQLSTATE table),
`src/pgvector-adapter.ts` `search()` / `searchStatement()`,
`src/plugin.ts` `poolFromPg` and `resolveStoreSettings`.

## Rework (L1 7272964718, docs only)

Head `4340f85d` adds the two should-fix doc edits and nothing else; nits
N1–N3 not taken this round.

- `content/docs/deployment/environment-variables.mdx` (Database &
Storage, beside `OS_DATABASE_POOL_MAX`): `OS_KNOWLEDGE_POOL_MAX`
(integer, `4`, per replica, plugin option wins, the sizing formula with
a link to the README section, a non-integer refuses the boot) and
`OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` (integer, `10000`, per search
statement, `SET LOCAL`, refused `TIMEOUT` past it, plugin option wins, a
non-integer refuses the boot).
- `content/docs/protocol/knowledge.mdx` §4.1: one sentence each for the
pool precedence (`poolMax`, else `OS_KNOWLEDGE_POOL_MAX`, else 4), the
ranking statement under `SET LOCAL statement_timeout` (default 10000
ms), and the three refusals by SQLSTATE.

Regen-provenance: 7272956301 · 9a39db7 → 4340f85 · `git diff
--name-only 9a39db7 4340f85` →
content/docs/deployment/environment-variables.mdx,
content/docs/protocol/knowledge.mdx (prose faces only, no code path
moved)

## Rework 2 (pool default 4 → 20, on new data)

Head `4f6b7d85`. The only behaviour change is `DEFAULT_POOL_MAX` 4 → 20
in `src/plugin.ts`; the rest is its pins and prose. Nits N1–N3 not
taken. `statement_timeout` stays 10000 ms.

Evidence (not this PR's bench reading): os-bob's measurement on the
card, objectstack-ai#38718 comment 7273601824 — local PostgreSQL 17 + pgvector 0.8.7,
59,949 indexed BrightRule clauses, end to end over MCP
`search_knowledge`, scoped, 15 questions in rotation:

> | 配置 | 20 并发:空结果 | 40 并发:空结果 |
> |---|---|---|
> | 混合检索 · 连接池 4(现默认) | 15 / 45 | 52 / 90 |
> | 混合检索 · 连接池 20 | 0 / 45 | 8 / 90 |
> | 只用向量 · 连接池 20 | 0 / 45 | 0 / 90 |
>
> 空结果全部来自等连接超时:平台日志里有 225 次 `timeout exceeded when trying to connect` …
**建议默认值从 4 改为 20**(不只是可配置)。… 语句时限 10 秒:单人串行时,只用向量的主语句 234–445 ms,混合检索
1.1–1.7 s,都远低于 10 秒。

(Those empty results are what this PR turns into `SERVICE_UNAVAILABLE`
refusals; the larger pool is what keeps them from happening at 20
concurrent callers.)

- `src/plugin.ts`: `DEFAULT_POOL_MAX = 20`; its docblock rewritten to
justify the move (the measurement, a lazy ceiling rather than a count
opened at boot, fits up to 6 replicas at `max_connections=200`, class 53
refusals past that), replacing the old "not moved" note. The two option
docblocks say 20.
- **Upgrade effect, stated in the changeset and README:** a deployment
with `OS_KNOWLEDGE_POOL_MAX` unset may now open up to 20 store
connections per replica under load instead of 4. With the README's
formula (platform pool 5, one build, 20 kept as headroom,
`max_connections=200`) a replica reaches up to 26, so up to 6 replicas
fit (6 × 26 = 156 ≤ 180; 7 × 26 = 182 does not); 3 replicas take 60
store connections. More replicas or a smaller server must set it lower
(`4` keeps the old size) or raise `max_connections`, otherwise the
server refuses connections (`too_many_connections`, class 53) and those
searches are refused `SERVICE_UNAVAILABLE`.
- Every pin of 4 moved together: `search-refusals.test.ts`
(`DEFAULT_POOL_MAX` and the blank-setting case), the README options and
settings tables, `environment-variables.mdx`'s `OS_KNOWLEDGE_POOL_MAX`
row, `knowledge.mdx` §4.1, the changeset.
- Local at `4f6b7d85`: `search-refusals.test.ts` 14/14, `tsc --noEmit`
exit 0.

Regen-provenance: 7272956301 · 4340f85 → 4f6b7d8 · `git diff
--name-only 4340f85 4f6b7d8` →
.changeset/knowledge-pgvector-coded-search-refusals.md,
content/docs/deployment/environment-variables.mdx,
content/docs/protocol/knowledge.mdx,
packages/plugins/knowledge-pgvector/README.md,
packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.test.ts,
packages/plugins/knowledge-pgvector/src/plugin.ts (NOT prose-only: one
constant and its docblock in `plugin.ts`, one test pin; the record does
not carry across this hop by itself)

## Human Minimum

- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
(not touched)
- [x] 2. Every name I added uses the casing for its kind.
- [x] 3. No formatter ran; eslint passes on the changed files.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` touched: n/a.
- [x] 7. No hand edits to `content/docs/references/`,
`packages/*/CHANGELOG.md` or `content/docs/releases/`.
- [x] 8. Title, body and comments are in English (the 维护者速读 block
excepted by AGENTS.md's Communication rule).

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

<!-- signed: repo:objectstack@os-warren · os-warren ·
session_01JQwxbYVKM5Jf2J5JbHJ8Aj -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…mode its store does not run (objectstack-ai#38722)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8QCBjsNDZa4iwo35VN5fKKg)_

Part of objectstack-ai#38692

Clause-②: no
Metadata-protocol: none

## 维护者速读

-
知识源声明了检索方式后,搜索就按它执行;没声明的按存储默认。存储不支持所声明的方式时,保存时直接报错并列出可选方式,启动后记一次错误日志,每次搜索都把它列为未检索,绝不悄悄换成别的方式。
- 属于知识管理专题「一期 a:检索方式」。
- 出错会是本该能搜的知识源被拒;未声明方式的知识源行为不变,可直接撤回。
- 无。

## Stack

Base: `main`. objectstack-ai#38700 (the facade split) has merged and `main` is merged
in. The spec PR objectstack-ai#38720 merged as f576dee and `main` is merged in, so
this diff is the service's own 15 files. The phase-0 ADR note (objectstack-ai#38714)
is merged too. Independent of the adapter PRs. The Studio form PR stacks
on this one.

## What changes

- New `knowledge-retrieval-mode.ts`: the effective mode is the source's
`source.retrieval.mode`, else the adapter's
`capabilities.retrieval.default`; an adapter reporting no modes is never
told one.
- The four refusal points for a declared mode the adapter does not list,
never searched another way:
1. save (`admitAuthoredSource`): `400 VALIDATION_ERROR`, listing the
modes the store runs;
2. registration in code (`registerSource`): the same refusal, only when
the adapter already resolves (startup registry reads). A published item
(`registerMetadataSource`, the loader) is not refused there: the loader
runs after every store has started, so a refusal would drop it whole; it
is registered and indexed, and points 3 and 4 refuse it (review M1);
3. once after boot (`reportUnsupportedRetrieval`, called at
`kernel:bootstrapped` beside `reportUnmountedAdapters`), at `error`;
4. every search (`planSearches`): listed in `refused` with
`SERVICE_UNAVAILABLE` (503), the code an unmounted adapter's source
already carries.
- Every search hands the store `AdapterSearchOptions.retrieval` and logs
the mode and its origin at `debug`; the caller's answer carries neither.
- `index_status` entries carry `retrieval` (declared, effective mode,
origin, the store's modes, refused), and the answer lists each mounted
store's modes (`details.adapters`) and the store a source naming none
binds to (`details.defaultAdapter`), the data the Studio form PR reads.
New service member `describeRetrieval`.
- Contract suite: service-level cases for every adapter (a listed mode
is handed through; an unlisted one is refused at registration in code
and at every search, and still indexes; a published item loaded after
its store started is registered, indexes, is named by the boot reading
and is refused on every search).
- Liveness row flips to `live`; protocol doc §3.1 and the save guard;
patch changeset.

## Tests

- New `retrieval-mode-38692.test.ts` (16 cases): resolution, refusal
text, each refusal point, debug log and its absence from the answer,
still indexes, the loader path (a published item with its store already
started), plugin hook, `index_status`.
- `service-knowledge`: 861 passed (26 files, at 1a7ba24); typecheck
clean. `knowledge-memory` 70 passed and `knowledge-turso` contract 110
passed against this head's suite. `knowledge-memory` contract 54 passed;
`knowledge-turso` 110 contract passed; live pgvector contract 55 passed.
- With each adapter PR merged in locally: turso 326 passed, pgvector
against live PostgreSQL 133 passed.

## Acceptance notes

- The per-search refusal code is reused rather than added:
`SERVICE_UNAVAILABLE` (503), the code an unmounted adapter's source
already carries. The ruling and the phase-0 note say only "with its
code"; open question C, confirmed by Warren on 2026-11-30 at 12:40Z
(「同意」): the refusal stays 503.
- Declared `Metadata-protocol: none`: what an author can write was added
by the spec PR; this PR reads it. The save refusal of a mode the store
does not run is the shape the ruling gives the key from birth, in the
same release.
- Facade gate: `knowledge-service.ts` 1681 lines of 1758; both new
members are one-call delegations.

## Verification

- Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/retrieval-mode-38692.test.ts` → 16 passed.
- Related local gates (26 of `dispatch-gates.mjs --commands`: docs,
liveness, changeset, facade, error-code, ledger): all green.

## Human Minimum

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

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

https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf

<!-- signed: repo:objectstack#2 · os-warren ·
session_01JQwxbaASqBozmmj1n5tbUf -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…odes its store runs (objectstack-ai#38730)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8QCBjsNDZa4iwo35VN5fKKg)_

Part of objectstack-ai#38692

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 管理员在 Studio
编辑知识源时,「检索方式」下拉只列出该知识源所用存储支持的方式,并写明「存储默认」是哪一种;存储未声明时显示「驱动未声明检索方式」。
- 属于知识管理专题「一期 a:检索方式」。
- 出错只会是下拉列错选项;保存时服务端仍会把不支持的方式拒掉,可直接撤回。
- 无。

## Stack

Base: `main`. Stacked on the service PR objectstack-ai#38722 (it reads
`index_status`'s `adapters` and `defaultAdapter`, which objectstack-ai#38722 adds) and
through it on objectstack-ai#38720; until those merge, this diff carries their
commits. Lands after both and after the phase-0 ADR note (objectstack-ai#38714).

## What changes

- The knowledge source form's `source.retrieval.mode` row names a new
widget, `knowledge-retrieval-mode` (spec form hint). A host whose
registry lacks the picker draws its unregistered-widget face (the JSON
editor), not a select; the three static `options` stay because the
form's generated translations carry their labels.
- `ResourceEditPage` loads, only for a form that declares the widget,
the store the draft binds to (its `adapter`, else `defaultAdapter`) and
the modes it reports, from `POST /api/settings/knowledge/index_status`
(`knowledgeRetrieval.ts`), into `WidgetContext.knowledgeRetrieval`.
- The picker: the store's listed modes plus a blank choice that names
the default ("Store default (Hybrid (both))"); a store that reports none
offers the default alone with "驱动未声明检索方式(STORE),此项请留空。"; a mode already
written that the store does not run is kept and flagged; no store answer
(refused read for an author who is not a platform administrator, store
not mounted, no host) offers the three modes and the save judges.
- en and zh strings in the studio namespace; registry cases in the two
widget registry tests; changeset (spec, app-shell, i18n patch).

## Tests

- New `KnowledgeRetrievalModeWidget-38692.test.tsx` (12): form row names
the widget, labelling, offered options per store shape, undeclared
sentence, flagged stored mode, fallbacks, writes and default removal,
disabled states, `storeRetrievalOf` parsing.
- Related UI suites: 180 files / 2,791 tests passed (widgets,
metadata-form, SchemaForm, i18n, console registry parity),
`ResourceEditPage*` 67 files / 342 passed; app-shell `tsc --noEmit` and
`tsconfig.test.json` clean before the main merge; spec form test 9
passed.

## Acceptance notes

- `index_status` is gated on `manage_platform_settings`; an author
without it gets the three-mode fallback, never an error card.
- The draft's `adapter` re-reads the store on change (one request per
distinct value).
- After merging `main` (with objectstack-ai#38700) the app-shell `tsc` reports one
error in `RecordDetailView.tsx` (`pinOverview`), outside this diff, from
a stale local build of a sibling package; not measured further here.

## Verification

- Two-minute check: `pnpm --dir ui exec vitest run
packages/app-shell/src/views/metadata-admin/KnowledgeRetrievalModeWidget-38692.test.tsx`
→ 12 passed.
- UI gates run: `check:i18n-keys`, `check:i18n-drift`,
`check:i18n-dead-keys`, `check-sdui-manifest`, `ui/scripts` vitest,
changeset gates: all green.

## Human Minimum

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

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

https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf

<!-- signed: repo:objectstack#2 · os-warren ·
session_01JQwxbaASqBozmmj1n5tbUf -->

---------

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/xl tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

service-knowledge: split knowledge-service.ts (5,411 lines, one class) into concern modules, move-only, so knowledge cards stop queueing on one file

3 participants