Skip to content

feat(service-knowledge): register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted - #37265

Merged
objectstack-fleet[bot] merged 12 commits into
mainfrom
claude/issue-37094-open-embedder-settings
Nov 26, 2026
Merged

objectstack-fleet[bot] merged 12 commits into
mainfrom
claude/issue-37094-open-embedder-settings

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ
Fixes #37094

Clause-②: yes (widening) — @objectstack/embedder-openai gains one export, documentedMaxBatchSize(model): number | undefined
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:开源部署挂上知识服务后,管理员在设置页「嵌入服务」里保存服务商和密钥、重启,知识检索就能用上这个嵌入器;设置页提示改动需重启生效。
  • 为什么做:知识检索平台化专题的开源版嵌入器一项——此前设置页的嵌入配置在开源版没人读,应用只能自己写代码注册嵌入器。
  • 出错会怎样:没配置时照常启动,需要嵌入的检索和建索引会报错并点名缺哪项设置,不向外发任何请求;已有嵌入器(云版注册的)保持不动;保存的批量大小超过模型公布上限时按上限发送。可直接撤回。
  • 要你做的:无。

What changes

  • KnowledgeServicePlugin registers EMBEDDER_SERVICE from the ai.embedder_* settings (packages/services/service-knowledge/src/knowledge-service-plugin.ts). Read once, at kernel:bootstrapped:
    • Already registered → kept. One info line, settings not applied. A registration the sync accessor cannot hand out (an async factory) counts as registered too.
    • Saved and complete → an @objectstack/embedder-openai embedder for the saved provider. The saved Base URL applies to the custom and Azure providers; every other provider uses its preset endpoint. The boot line names the endpoint host. "Saved" = any layer but the manifest default (source !== 'default', the same reading plugin-email uses for branding.workspace_name); an OS_* override counts as saved. "Complete" = the settings page's own Test embedder check (aiTestEmbedderActionHandler), handed only the saved values: reused, not forked.
    • Batch size passed only when saved, held to the model's documented cap. Unsaved (default 64) → the embedder batches at the model's documented cap. Saved → Math.min(saved, documentedMaxBatchSize(model)) when the saved model has a documented cap, the saved size as saved otherwise (no saved model, or a model the table does not know).
    • Dimensions and batch size are read as positive integers, as numbers or as their decimal text (an OS_AI_EMBEDDER_DIMENSIONS=256 override). Any other saved value is refused: EMBEDDER_SERVICE is the UnconfiguredEmbedder, with a warn boot line naming the key.
    • Nothing configured (no provider saved, none saved, incomplete, settings service absent, or the ai namespace without the embedder keys) → an UnconfiguredEmbedder is registered: embed() (non-empty) and dimensions refuse with a message naming the missing settings, where to save them and that a restart is needed. Boot succeeds; nothing is sent. Boot line is info when nothing asked for an embedder, warn when saved settings do not build one.
    • The API key never reaches a log line or an error message. Pinned on the configured path, on incomplete settings and on a provider answering 401.
  • Restart note on the settings page: a description on embedder_provider in ai.manifest.ts ("Read when the server starts: a saved change to any embedder setting takes effect after the next restart."), and its help copy in all 11 locale bundles. The translations are required by the gate: settings-translation-coverage.test.ts reds a described field with no keys.KEY.help in any locale.
  • @objectstack/embedder-openai exports documentedMaxBatchSize(model): number | undefined (seat direction, issue comment 7156326561): the documented per-request cap, read from the SAME module table OpenAIEmbedder batches by. No copy, and the constructor now reads the table through the same function. OpenAIEmbedder is unchanged: an explicit maxBatchSize is still used as given, above the cap included (pinned).
  • Docs: content/docs/ai/knowledge-rag.mdx gains "Configuring the embedder from Settings".
  • Dependency edge (one, workspace, no external): @objectstack/service-knowledge → @objectstack/embedder-openai. Why this side: service-knowledge already depends on core (plugin contract) and service-settings (the settings reader and the reused completeness check), so the knowledge plugin needs exactly one new edge; a plugin in embedder-openai would need core and service-settings (two edges, a crypto library among the transitive ones) and a host would have to mount it by hand, which is the gap the card is about. Services depending on plugins has precedent (service-storage, service-print, service-automation). embedder-openai depends only on spec: no cycle.

Why kernel:bootstrapped (the phase measurement)

ObjectKernel.bootstrap() / LiteKernel.bootstrap() run every init(), then every start(), then kernel:ready handlers in plugin order, then kernel:bootstrapped once every kernel:ready handler has settled (plugin-lifecycle-events.ts). An embedder registered in init(), start() or any kernel:ready handler (where a settings-reading provider would register, since the settings engine binds in kernel:ready) is therefore visible at kernel:bootstrapped, regardless of plugin order. Pinned both ways: a host embedder registered at init and one registered in a kernel:ready handler are each kept. Only a registration in kernel:bootstrapped / kernel:listening or after boot would collide; the changeset says so. Settings are read after kernel:ready for the same reason the settings plugin documents: a read in the pre-bind window answers the default without consulting the store.

Cloud reading (cloud-confirm 7159003875 on #37094, read at cloud main packages/service-ai/src/plugin.ts): service-ai applies its embedder in a kernel:ready hook (bindSettings → applyEmbedder), so its boot-time registration comes before this placeholder exists. Every later ai settings save calls replaceService, never registerService, so it replaces the placeholder without throwing. A cold boot with a configured provider still logs the existing [AI] Failed to apply embedder settings warning, as it does on main with nothing registered; the placeholder does not make that worse. No cloud deployment mounts the open KnowledgeServicePlugin beside service-ai.

Tests

New top-level describe in the knowledge+settings harness file (src/__tests__/knowledge-settings-contribution.test.ts), through the real registration path: settings SAVED via SettingsService.setMany in a kernel:ready handler, provider reached through a stubbed global fetch, and an adapter that looks up EMBEDDER_SERVICE where it embeds. No hand-built embedder.

  • saved settings → indexDocument sends one POST https://api.openai.com/v1/embeddings with the saved key and model; nothing sent at boot; key in no log line
  • custom endpoint → the saved Base URL
  • pre-registered at init / at kernel:ready → same instance kept, zero requests, one info line
  • unsaved batch size on DashScope text-embedding-v3 → requests of 10, 10, 5 (not one of 25: the default 64 is not a saved value)
  • saved batch size 4 → requests of 4, 4, 1
  • pin (a) saved 64 on text-embedding-v3 (documented 10) → requests of 10, 10, 5, and the boot line names the saved 64
  • pin (b) saved 50 on a custom model with no documented cap → requests of 50, 10 (kept as saved)
  • embedder-openai: documentedMaxBatchSize answers 10 / 2048 / undefined (unknown, and a prototype key); the embedder with no maxBatchSize batches at exactly that value; an explicit maxBatchSize: 25 on a cap-10 model still sends 25
  • no settings → boot succeeds; indexDocument and the adapter's search reject naming ai.embedder_provider and the restart; KnowledgeService.search answers [] and logs that error per source; dimensions refuses; zero requests; boot line info
  • none saved → refusal says so; incomplete (provider without key) → the page check's own message, boot line warn
  • a preset provider uses its preset endpoint even when a Base URL is saved → one request to the preset endpoint; the boot line names endpoint=api.openai.com
  • OS_AI_EMBEDDER_DIMENSIONS=256 (arrives as text) → dimensions is 256 and the request carries dimensions: 256
  • OS_AI_EMBEDDER_DIMENSIONS=large → refused naming ai.embedder_dimensions, a warn boot line, zero requests
  • unsaved batch size on a custom model with no documented cap, 70 inputs → requests of 10 × 7
  • the API key in no log line and no error: incomplete settings (custom without a Base URL), and a provider answering 401

Ablations (one-shot, scripts/ablation-replace.mjs, each mutation landed and restored to blob == HEAD, git diff HEAD empty):

  • treating the manifest default as saved (if (!entry) return undefined;) → 1 failed / 15 passed: exactly "an unsaved batch size on a model with no documented cap is the embedder fallback, not the default 64".
  • clamp removed (the Math.min line → savedBatch) → 1 failed / 15 passed: exactly pin (a). The first attempt at this one was a no-op: the replacement text already occurred in the anchor, the tool refused before running, and it was re-run with a distinct replacement.
  • the Base URL provider check removed → 1 failed / 15 passed: exactly "a preset provider uses its preset endpoint even when a Base URL is saved".
  • decimal text not read as a number → 1 failed / 15 passed: exactly the '256' case.
  • a value that is not a positive integer dropped instead of refused → 1 failed / 15 passed: exactly the 'large' case.
  • the API key appended to the incomplete-settings refusal → 1 failed / 15 passed: exactly the key-not-logged case.

Acceptance notes

  • The clamp needed a surface widening, ruled by the seat (comment 7156326561, option A): one read-only export from embedder-openai. With no saved model the embedder uses its own default model; no cap is looked up for a model the plugin does not name, so the saved size passes as saved. The field's maximum (2048) equals that default model's documented cap.
  • Contract review owed: Clause-② is yes, so the seat's direction asks for a same-head contract review at the tier these paths require, on top of L1.
  • Declared beyond the named surface (mechanically forced): packages/services/service-knowledge/vitest.config.ts gains one alias for @objectstack/embedder-openai (without it check:test-source-alias reds: the tests would read the embedder's dist/); pnpm-lock.yaml records the new workspace edge.
  • Search reports, it does not throw. KnowledgeService.search already catches a per-source adapter failure, logs it at error and answers no hits from that source; with no embedder that logged error is the named reason. Indexing throws it. That catch lives in knowledge-service.ts, outside this card.
  • No open-edition adapter consumes EMBEDDER_SERVICE yet (knowledge-memory uses its own sparse vectors; knowledge-ragflow embeds server-side), so in the open edition today the registered embedder is used by custom adapters and by the coming pgvector adapter. The EMBEDDER_SERVICE doc comment in packages/spec/src/contracts/embedder.ts still says it is "Registered by @objectstack/service-ai"; spec prose was not touched here.
  • An unknown model with no saved batch size still gets the embedder's own fallback of 10 and its one construction warning, unchanged.

Verification

Two-minute check: pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-settings-contribution.test.ts -t 37094 → 16 passed.

Read first, by risk:

  1. knowledge-service-plugin.ts provideEmbedder() and embedderFromSettings(): the phase, the registered check, the saved-vs-default reading, the clamp.
  2. UnconfiguredEmbedder: a registered placeholder means EMBEDDER_SERVICE is never absent once the knowledge service is mounted.
  3. embedder-openai/src/index.ts documentedMaxBatchSize and the constructor's use of it.

Local readings, head fa818f4d (service-settings and the dispatch-gates run at f329965b; the later commits touch neither service-settings nor the derived gate set):

Package tests, typecheck, derived gates
  • pnpm --filter @objectstack/embedder-openai test → 31/31; build + typecheck (tsc + check:test-typecheck) exit 0.
  • pnpm --filter @objectstack/service-knowledge test → Test Files 8/8, Tests 186/186; typecheck exit 0, 0 errors.
  • pnpm --filter @objectstack/service-settings test → Test Files 77/77, Tests 1523/1523; typecheck exit 0 (head 35c742d2; the later commits do not touch service-settings).
  • Dependency closure built with declarations first.
  • node scripts/pm/dispatch-gates.mjs --commands (21 paths): 115 commands, each exit captured before any pipe: 114 exit 0, among them check:startup-registry-verdict, check:test-source-alias, check:undeclared-dep-imports, check:workspace-manifest-cycles, check:published-readme-links, check:dual-build-cjs-loads, check:settings-bind-window, check:doc-authoring, check:issue-citations, check:nul-bytes, check:changeset-fixed, check-empty-changeset, check-changeset-no-major, check-adr-0087-registration, check:type-check-coverage.
  • 1 exit 3, PREREQUISITE NOT MET, so NOT MEASURED here (CI runs it): check-plugin-teardown-shape --self-test (shallow clone cannot read its pinned fixture).
  • dispatch-gates --ran: 115 derived, 115 run, 0 unrun.
  • Repo-wide scans (pnpm lint) and dogfood are CI's (no ! in the title, no narrowing arm).

Signed: repo:objectstack#4 · os-justin · session_01QSeKYofJfCPWsxaVYkmaVF

Provenance

Opened by seat repo:objectstack#4 on the maintainer's authorization in the seat session (「#37094 开 PR 被拦:放行」). The developer's own pr_create in zone a4-K's dev session was refused twice by a permission check; the dev stopped without retrying and handed the material over. Branch claude/issue-37094-open-embedder-settings @ fa818f4d40749e28de09bbd747e9ca3c829f17ed.

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic. (spec untouched)
  • 2. Every name I added uses the casing for its kind.
  • 3. No formatter ran; pnpm lint passes. (No formatter ran; pnpm lint was not run locally — CI's run decides.)
  • 4. One issue, one branch off an up-to-date main, one pull request.
  • 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset.
  • 6. packages/spec touched: n/a.
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English (the 维护者速读 block is the fleet's required Chinese summary).
  • The Before Submitting list in CONTRIBUTING.md is done. (Not walked item by item; the local readings above are what ran.)

🤖 Generated with Claude Code

https://claude.ai/code/session_01QSeKYpEsWWE9Y5YtSsDgqZ

…olds a saved batch size to the model's documented cap

Claude-Session: https://claude.ai/code/session_01QSeKYofJfCPWsxaVYkmaVF
Co-authored-by: Claude <noreply@anthropic.com>
…ed cap; changeset names the export

Claude-Session: https://claude.ai/code/session_01QSeKYofJfCPWsxaVYkmaVF
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/l dependencies Pull requests that update a dependency file 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 25, 2026
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 3 package(s): @objectstack/embedder-openai, @objectstack/service-knowledge, @objectstack/service-settings, touching 24 documentable anchor(s). ⚠️ 2 changed file(s) yielded no anchor (packages/services/service-knowledge/package.json, packages/services/service-knowledge/vitest.config.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

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

  • content/docs/ai/knowledge-rag.mdx (via KnowledgeServicePlugin (symbol, a top-level class), documentedMaxBatchSize (symbol, a top-level function))
  • content/docs/automation/webhooks.mdx (via batchSize (symbol, a field of type EmbedderFromSettings))
  • content/docs/frontend/data-source.mdx (via batchSize (symbol, a field of type EmbedderFromSettings))
  • content/docs/protocol/kernel/config-resolution.mdx (via getNamespace (symbol, a method of interface EmbedderSettingsReader))
  • content/docs/protocol/knowledge.mdx (via KnowledgeServicePlugin (symbol, a top-level class))
  • content/docs/ui/views.mdx (via batchSize (symbol, a field of type EmbedderFromSettings))
What this run could not see
  • 2 changed file(s) yielded no anchor (packages/services/service-knowledge/package.json, packages/services/service-knowledge/vitest.config.ts) — pages documenting those are invisible to this run
  • 12 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 12 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 98bda0ac17dbde835e8be577d7d4238e6cf77201 → packageMentionDocs.

Which tree this was computed on

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

node scripts/docs-audit/affected-docs.mjs --json 98bda0ac17dbde835e8be577d7d4238e6cf77201

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

@objectstack-fleet

objectstack-fleet Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: f329965bd6888bfae8e6901e1ca230c8f37e81f9
Local-runs: probe — pins (a) and (b), the two ablations, the env-override and key-leak readings and the ObjectKernel phase reading could only be measured by running vitest at this head, in a throwaway worktree that is now removed
Scope: no hits (the paths decide no face; the Clause-②: yes (widening) line alone owes the review, so the owed tier is TIER_DEFAULT, declaration face; served at the higher tier) + packages/plugins/embedder-openai/src/index.ts, packages/services/service-knowledge/src/knowledge-service-plugin.ts, packages/services/service-knowledge/package.json, packages/services/service-knowledge/vitest.config.ts, packages/services/service-settings/src/manifests/ai.manifest.ts, the 11 bundles under packages/services/service-settings/src/translations/, .changeset/37094-open-embedder-from-settings.md, content/docs/ai/knowledge-rag.mdx, pnpm-lock.yaml, and the two test files

① Derived judgments

  • PR feat(service-knowledge): register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37265 for card Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094, epic 专题:知识检索平台化(应用写一份知识源配置就有可用的检索:开源、托管、企业版都能用) #37000, seat direction 7156326561 (option A). 21 files, +695/−5. Opened by the seat on the maintainer's authorization; the dev's facts are in the PR body.
  • record-recognisers --template --paths refuses to pick a face from the paths (no schema, no governed path) and defers to the changeset's Clause-②: line: yes (widening) ⇒ declaration face, TIER_DEFAULT.
  • Check-runs at this head, read 2026-11-25T09:49Z: 62 success, 9 skipped, 0 failed, 0 running. The skipped ones are opt-in or queue-only jobs (18.x upgrade harness, packed-tarball smoke, the two queue verdicts, the schedule gate, Temporal Conformance, UI Published Artifacts, Dogfood Verify CLI, one Dogfood matrix placeholder).
  • landing-k --pr 37265 against origin/main 376377cc0c54: K = 4, OK; no new locale pack under this label PR; no shared book moved. git merge-tree against that main is clean (tree 0e04038d1aab). Main moved pnpm-lock.yaml after the merge-base; it merges clean.
  • Local at this head: pnpm install --frozen-lockfile exit 0 (the lockfile agrees with the manifests); dependency closure built; knowledge-settings-contribution.test.ts -t 37094 11/11; service-knowledge 8 files, 181/181; embedder-openai 31/31.
  • Pin (a), saved 64 on text-embedding-v3 → 10, 10, 5 and the boot line names the saved 64: green. Pin (b), saved 50 on a custom model → 50, 10: green. The explicit maxBatchSize: 25 on a cap-10 model still sends 25, 5: green.
  • Ablation, clamp removed (Math.min(savedBatch, documentedCap) → savedBatch): 1 failed / 10 passed, exactly pin (a). Matches the body. Restored.
  • Ablation, manifest default counted as saved (if (!entry) return undefined;): 11 passed, 0 failed. It does NOT match the body, which reports 1 failed / 8 passed. See S2.
  • Phase, read in packages/core/src/kernel.ts (lines 618 to 642) and lite-kernel.ts (lines 146 to 156): both kernels await every kernel:ready handler, then dispatch kernel:bootstrapped, then kernel:listening; all three propagate a throw. plugin-lifecycle-events.ts says the same. So a registration in init(), start() or any kernel:ready handler is visible to this hook whatever the plugin order.
  • "Already registered → kept": init and kernel:ready are pinned on LiteKernel. On ObjectKernel I measured by probe: an async factory is kept (Service 'embedder' is async - use await is not the not-found message, so it reads as registered; one info line, no id); nothing registered → the placeholder; a registration in a later kernel:bootstrapped handler fails the boot with [Kernel] Service 'embedder' already registered, as the changeset warns.
  • API key: the pin is in the first Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094 case (lines.filter((l) => l.line.includes(API_KEY)) is empty), which covers the log lines of the configured path. By reading, no log line and no error built in this diff interpolates the key: the boot lines carry provider, model and batch size; the refusal reasons carry the page check's message, the settings read error or the embedder's constructor error, none of which holds the key. By probe: a saved key with incomplete settings, and a provider answering 401, put the key in no log line and no error text. OpenAIEmbedder's own request errors carry the base URL, the status and 200 characters of the response body, not the key.
  • i18n: ai.keys.embedder_provider.help is present in all 11 bundles (ar, de, en, es-ES, fr, ja-JP, ko, pt-BR, ru, zh-CN, zh-Hant); the en text equals the manifest description.
  • Dependency edge: embedder-openai depends on spec only; service-settings depends on neither of the other two; no cycle. check:workspace-manifest-cycles is green in CI.
  • Overlap, of the open PRs only feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations #37256 touches a file of this diff (knowledge-service-plugin.ts: one import and one constructor option in init()). git merge-tree of the two heads is clean. service-knowledge: one service-layer splitter (whole / recursive / markdown, Chinese-aware), the chunk channel and the split key #37098 has no PR yet.

② Semver level

  • Clause-②: yes (widening) holds: documentedMaxBatchSize(model): number | undefined is a new export of a published package, nothing is removed or tightened, and it is named in the body and in the changeset as the direction required.
  • Metadata-protocol: none holds: the diff adds a description to one existing specifier of the platform's own ai manifest and its help copy. No key, accepted value, default or metadata type changes for an author.
  • patch on service-knowledge, service-settings and embedder-openai is the level AGENTS.md Post-Task step 3 gives: none takes patch, and a non-protocol widening ships patch.
  • OpenAIEmbedder is unchanged for a caller, with one edge: the constructor now reads the table through hasOwnProperty, so a model named like an Object.prototype key (constructor) falls back to 10 where it used to take a function as its batch size. A correction, pinned.
  • The changeset carries the migration sentence for a host that registers the name after kernel:ready. That is the one behaviour change for an existing host; see S3.

③ Boundary flags

  • Seat direction 7156326561, all four conditions met: the body reads Clause-②: yes and names the export; the changeset names it and says an explicit maxBatchSize is unchanged; a pin reddens when the clamp goes (re-measured); a second pin keeps an unknown model's saved size.
  • Declared beyond the named surface: the vitest alias and the lockfile entry are both mechanically forced. Accepted.
  • "Search reports, it does not throw": accepted. The catch is in knowledge-service.ts, outside the diff; the logged error is the named reason (pinned).
  • "No open-edition adapter consumes EMBEDDER_SERVICE yet": confirmed, no other reader of the name exists under packages/.
  • The stale EMBEDDER_SERVICE doc comment in spec: N1.
  • Saved versus default: savedValue returns a value only when source is not default, so an OS_* override (source: 'env') counts. The completeness check is handed the saved map only; its payload is empty, so nothing unsaved reaches it. The map holds every saved ai key, not only the embedder ones (N5). The handler sends no request (read, and pinned by the zero-request assertions).
  • SQL push-down (Prime Directive 5): no query in this diff.

④ Design judgment

  • M1 (must-fix) — a credential-handling defect in how saved embedder settings are applied. Under the security-findings rules its mechanism is not recorded here; the finding and the required fix and pin were handed to the dev through the zone's dispatch. Closure is read at the next head.
  • S1 (should-fix) — an OS_AI_EMBEDDER_DIMENSIONS override is dropped without a line. The key has no default, so the settings service hands the env value over as a string ("256", source: 'env'); typeof saved.embedder_dimensions === 'number' is false; the embedder reports the model's default (measured: 1536) and sends no dimensions. An adapter then sizes its column from the wrong number. The body says an OS_* override counts as saved. Asked: accept a numeric string for the two number keys, or refuse it at warn; one case.
  • S2 (should-fix) — the saved-versus-default reading has no pin at this head, and the body's ablation line for it is stale. Since the clamp commit, a default 64 counted as saved is clamped to 10 on text-embedding-v3, the same 10, 10, 5 the case expects, so the mutation is green. The difference shows only on a model with no documented cap: measured, 70 inputs on my-gateway-model with no saved batch size send 10 × 7 at head and 64, 6 under the mutation. Asked: that case, and the body's ablation line corrected.
  • S3 (should-fix) — the cloud ordering claim is NOT MEASURED. The cloud source is not readable from this session (repository access was refused), so "cloud registers before kernel:bootstrapped" rests on the body alone. What this repository does say (packages/spec/CHANGELOG.md, entry 4f9e9d4): service-ai builds its embedder in bindSettings(), leaves the service unset when the provider is none, and on settings:changed "registers / replaces" it without a restart. With this PR a deployment that mounts the knowledge service and boots with no embedder has the placeholder under the name. If cloud's hot path calls registerService when it holds no embedder of its own, it now throws already registered; if it calls replaceService, it works. And if bindSettings() runs later than kernel:ready, the boot fails as measured above. Asked of the seat before landing: one reading in cloud of the phase bindSettings() runs in and of the call its hot path makes, recorded on the PR.
  • N1 — the EMBEDDER_SERVICE doc comment in packages/spec/src/contracts/embedder.ts still says the service is registered by service-ai and may be absent. A follow-up outside this surface.
  • N2 — the restart help is shown wherever the embedder section is, also where another plugin's embedder is kept and may apply changes without a restart.
  • N3 — any getService error other than not-found reads as "already registered", and the info line then says so. Right for an async factory; wider than the comment states.
  • N4 — the async-factory keep and the ObjectKernel path have no case; every Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094 case boots LiteKernel.
  • N5 — the completeness check is handed every saved ai key, chat provider keys included. It reads only embedder_*; the map could be narrowed to that prefix.
  • N6 — the API-key pin asserts the configured path's log lines only; the same assertion on the incomplete case and on a provider error would pin what the body claims for errors.
  • For the second lander of this file set (service-knowledge: one service-layer splitter (whole / recursive / markdown, Chinese-aware), the chunk channel and the split key #37098, feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations #37256): keep the documentedMaxBatchSize export and the constructor reading the table through it; keep the kernel:bootstrapped hook above the enableEventSync early return in start(), provideEmbedder and both import hunks; keep embedder_provider.description in ai.manifest.ts and embedder_provider.help in all 11 bundles (the coverage test reddens a described field with no help).

Implemented-by: claude/issue-37094-open-embedder-settings
Reviewed-by: session_01QSeKYpEsWWE9Y5YtSsDgqZ

VERDICT: FAIL

@objectstack-fleet

objectstack-fleet Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — REWORK · L1 · head f329965bd6888bfae8e6901e1ca230c8f37e81f9 · 2026-11-25T09:52Z

  • PR feat(service-knowledge): register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37265 for Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094, epic 专题:知识检索平台化(应用写一份知识源配置就有可用的检索:开源、托管、企业版都能用) #37000, zone a4-K. Fixes #37094; Clause-②: yes (widening); Metadata-protocol: none. Opened by the seat on the maintainer's authorization, because the dev's own pr_create was refused.
  • The os-dev report was relayed by zone a4-K at 2026-11-25T09:10Z because the dev's own post was refused; this L1 carries its facts, read from the PR body.
  • Size: 21 files, +695/−5. Every file is inside the card's surface or mechanically forced (the vitest alias, the lockfile entry).
  • Changeset: patch on service-knowledge, service-settings and embedder-openai. Correct by AGENTS.md Post-Task step 3: Metadata-protocol: none takes patch, and a non-protocol widening ships patch. Both declaration lines are in the body and in the changeset; the changeset names the export and says an explicit maxBatchSize is unchanged.
  • Check-runs at head, read 2026-11-25T09:49Z: 62 success, 9 skipped (opt-in and queue-only jobs), 0 failed, 0 running.
  • K = 4 against origin/main 376377cc0c54 (landing-k OK); git merge-tree against it is clean.
  • Local at head in a throwaway worktree (removed): frozen-lockfile install exit 0; the Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094 cases 11/11; service-knowledge 181/181; embedder-openai 31/31.
  • Phase: verified in both kernels. Every kernel:ready handler settles before kernel:bootstrapped is dispatched, in ObjectKernel and in LiteKernel. A registration at init, at kernel:ready (both pinned) or as an async factory (measured on ObjectKernel) is kept. A registration in a later kernel:bootstrapped handler fails the boot, as the changeset says.
  • Saved versus default: source !== 'default', an OS_* override counts; the page's own completeness check is handed saved values only and sends nothing.
  • Clamp: pins (a) and (b) are green; removing the clamp reddens exactly pin (a); an explicit maxBatchSize given straight to OpenAIEmbedder is used as given (pinned).
  • Placeholder: the refusals name the missing settings and the restart; no request is sent; the boot line is info when nothing asked for an embedder and warn when saved settings build none (both pinned).
  • API key: in no log line and no error. Pinned for the configured path's log lines; read and probed for the error paths (incomplete settings, a provider 401).
  • i18n: embedder_provider.help is in all 11 bundles. Dependency edge: no cycle; the lockfile is consistent.
  • Seat direction 7156326561: all four conditions are met.
  • Owed review tier: TIER_DEFAULT (declaration face). The review was served at CONTRACT_REVIEW_TIER; record written for this head: FAIL.
  • M1 (must-fix) — a credential-handling defect in how saved embedder settings are applied. Under the security-findings rules its mechanism is not recorded here; the finding and the required fix and pin were handed to the dev through the zone's dispatch. Closure is read at the next head.
  • S1 (should-fix) — OS_AI_EMBEDDER_DIMENSIONS reaches the plugin as a string and is dropped without a line; the embedder then reports the model's default dimensions (measured: 1536 for a requested 256).
  • S2 (should-fix) — the saved-versus-default reading is unpinned at this head: counting the default as saved leaves all 11 cases green, while the body reports 1 failed. The clamp commit hollowed that case. One case on a model with no documented cap closes it (10 × 7 at head, 64 + 6 under the mutation), and the body's ablation line needs correcting.
  • S3 (should-fix) — the cloud ordering claim is not measured: the cloud source cannot be read from this session. This repository's own CHANGELOG says service-ai leaves the service unset under none and "registers / replaces" it on a later save. With the placeholder under the name, a registerService on that path would now throw. The seat owes one reading in cloud (the phase of bindSettings(), and register or replace) before this lands.
  • N1 — the EMBEDDER_SERVICE doc comment in spec is stale; follow-up.
  • N2 — the restart help also shows where another plugin's embedder is kept.
  • N3 — any getService error other than not-found reads as "already registered".
  • N4 — no case for the async factory or for ObjectKernel.
  • N5 — the completeness check is handed every saved ai key, not only embedder_*.
  • N6 — the API-key assertion is on one case; repeat it on an error case.
  • Overlap: feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations #37256 touches knowledge-service-plugin.ts (one import, one constructor option); the two heads merge clean. service-knowledge: one service-layer splitter (whole / recursive / markdown, Chinese-aware), the chunk channel and the split key #37098 has no PR yet. Whichever lands second keeps: the documentedMaxBatchSize export and the constructor reading through it; the kernel:bootstrapped hook above the enableEventSync early return, with provideEmbedder and both import hunks; embedder_provider.description and its help in all 11 bundles.
  • Next: M1, S1 and S2 back to zone a4-K; the seat takes S3 to cloud; re-review at the new head.

… Azure; number keys read from text; boot line names the endpoint host

Claude-Session: https://claude.ai/code/session_01QSeKYofJfCPWsxaVYkmaVF
Co-authored-by: Claude <noreply@anthropic.com>
…r keys from text; changeset

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

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

Contract review

Served-tier: TIER_DEFAULT
Head-sha: fa818f4d40749e28de09bbd747e9ca3c829f17ed
Local-runs: probe — the five new cases and the six ablations could only be measured by running vitest at this head, in a throwaway worktree that is now removed
Scope: no hits (the paths decide no face; the Clause-②: yes (widening) line owes the review, declaration face) + packages/services/service-knowledge/src/knowledge-service-plugin.ts, packages/services/service-knowledge/src/tests/knowledge-settings-contribution.test.ts, .changeset/37094-open-embedder-from-settings.md, content/docs/ai/knowledge-rag.mdx
Security-touching: yes
Rule-change-verified: none

① Derived judgments

  • Delta review of PR feat(service-knowledge): register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37265 (card Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094) against the FAIL record for f329965b. The new head is three commits on f329965b: f8dd0ac7 (code and pins), 8e8243da (docs and changeset), fa818f4d (wording only). 4 files, +155/−13 over f329965b; the whole PR is 21 files, +837/−5 against its merge-base.
  • 8e8243da → fa818f4d changes no code: in knowledge-service-plugin.ts only a comment changes; in the test file one case name, one comment and one fixture URL; the changeset and the docs reword one sentence each. Every run below was taken at fa818f4d itself.
  • Local at this head: frozen-lockfile install exit 0; dependency closure built; knowledge-settings-contribution.test.ts -t 37094 16/16; service-knowledge 8 files, 186/186; embedder-openai 31/31.
  • Ablations, each landed alone, measured, and restored (git diff empty after each):
    • the Base URL provider check removed → 1 failed / 15 passed, exactly the pin "a preset provider uses its preset endpoint even when a Base URL is saved";
    • the manifest default counted as saved (if (!entry) return undefined;) → 1 failed / 15 passed, exactly the new case on a model with no documented cap;
    • the clamp removed → 1 failed / 15 passed, exactly pin (a);
    • decimal text no longer read as a number → 1 failed / 15 passed, exactly the '256' case;
    • a value that is not a positive integer dropped instead of refused → 1 failed / 15 passed, exactly the 'large' case;
    • the API key appended to the incomplete-settings refusal → 1 failed / 15 passed, exactly the extended key-not-logged case.
  • Check-runs at 8e8243da, read 2026-11-25T10:30Z: 62 success, 9 skipped, 0 failed. At fa818f4d, read 2026-11-25T10:56Z: 60 success, 9 skipped, 2 failed (Test UI (2/16) and its Test UI roll-up). The one failing case is examples/schema-catalog/test/kanban-column-cards-6939.test.tsx (the kanban board still showed its loading skeleton when waitFor gave up). No path of this PR is on that surface; the same shard is green at 8e8243da, whose code is identical, and on main 057cedfa9b6f. Read as a flake; a re-run of that job is owed before landing.
  • landing-k --pr 37265 against origin/main 057cedfa9b6f: K = 1, OK; label PR with no new locale pack; no shared book moved. git merge-tree of this head with that main is clean.
  • feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations #37256 has not merged (open, head 6e978db3). It still shares knowledge-service-plugin.ts; git merge-tree of the two heads is clean.

② Semver level

  • Clause-②: yes (widening) still holds: the delta adds no export and removes none; documentedMaxBatchSize is unchanged.
  • Metadata-protocol: none still holds: the delta touches no manifest key, default or accepted value.
  • patch on the three packages is unchanged and still right. The changeset's first bullet now states the Base URL rule, the endpoint host in the boot line and the number-key reading as behaviour.

③ Boundary flags

  • M1 (the credential-handling defect in how saved embedder settings are applied) is closed. Its pin exists, the case for the rule "a preset provider uses its preset endpoint even when a Base URL is saved", and it goes red under ablation of the guard (1 failed / 15 passed). The committed changeset, docs, comment, test name and commit messages state the rule only.
  • S1 is closed. positiveIntegerSetting() reads a number or its decimal text; any other value is refused into UnconfiguredEmbedder with a warn line naming the key; pins for '256' and 'large', each red under its own ablation. OS_AI_EMBEDDER_BATCH_SIZE reaches the plugin as a number, because the settings service coerces it by the key's numeric default; the text path matters for embedder_dimensions, and that is the key pinned.
  • S2 is closed. The new case (custom model, no saved batch size, 70 inputs → 10 × 7) is the one that reddens when the default is counted as saved.
  • N6 is closed. The key-not-logged assertion now covers the incomplete case and a provider answering 401, in log lines and in the error text.
  • S3 (should-fix) — the cloud ordering claim is still not measured. Unchanged from the prior record: one reading in cloud of the phase bindSettings() runs in and of the call its hot path makes (register or replace), recorded on the PR before landing. The seat owns it and holds landing for it. The dev owes nothing for it.
  • N1 to N5 are carried unchanged from the prior record: the stale EMBEDDER_SERVICE doc comment in spec; the restart help shown also where another plugin's embedder is kept; any getService error other than not-found read as registered; no case for the async factory or ObjectKernel; the completeness check handed every saved ai key.
  • N7 — Ollama at a host other than localhost cannot be set from Settings: the form offers no Base URL for it, and the plugin now follows the form. The Base URL field's description ("override for proxies or self-hosted gateways") reads wider than the two providers it is shown for. A follow-up on the form.
  • N8 — the Test embedder check does not read the two number keys, so it reports complete for a value the boot refuses. The boot's warn names the key.
  • SQL push-down (Prime Directive 5): no query in this diff.

④ Design judgment

  • Not owed on the declaration face.

Implemented-by: claude/issue-37094-open-embedder-settings
Reviewed-by: session_01QSeKYpEsWWE9Y5YtSsDgqZ

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head fa818f4d40749e28de09bbd747e9ca3c829f17ed · 2026-11-25T10:58Z

  • Delta L1 of PR feat(service-knowledge): register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37265 (card Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094) against the REWORK at f329965b. Three new commits: f8dd0ac7 (code and pins), 8e8243da (docs and changeset), fa818f4d (wording only, no code: one comment, one test name, one fixture URL, one sentence each in the changeset and the docs).
  • Size of the delta: 4 files, +155/−13. Every file was already in the PR; nothing new is outside the card's surface.
  • M1 (the credential-handling defect in how saved embedder settings are applied): closed. Its pin exists, named by its rule, "a preset provider uses its preset endpoint even when a Base URL is saved", and it goes red under ablation of the guard: 1 failed / 15 passed. The boot line now names the endpoint host. The changeset, the docs, the code comment, the test name and the commit messages state the rule only.
  • S1: closed. A number or its decimal text is read as the value; anything else is refused into UnconfiguredEmbedder with a warn line naming the key. Pins for '256' and 'large' each go red under their own ablation (1 failed / 15 passed each).
  • S2: closed. The new case (custom model, no saved batch size, 70 inputs → 10 × 7) goes red when the default counts as saved: 1 failed / 15 passed, as the zone reports.
  • N6: closed. The key-not-logged assertion now covers the incomplete case and a provider answering 401. Appending the key to the incomplete refusal reddens it: 1 failed / 15 passed.
  • Local at fa818f4d, in a throwaway worktree that is now removed: frozen-lockfile install exit 0; the Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094 cases 16/16; service-knowledge 186/186; embedder-openai 31/31. The clamp ablation still reddens exactly pin (a): 1 failed / 15 passed. Every reading was taken at fa818f4d; since 8e8243da → fa818f4d changes no code, they hold for 8e8243da too.
  • Check-runs at 8e8243da, read 2026-11-25T10:30Z: 62 success, 9 skipped, 0 failed, matching the zone. At fa818f4d, read 2026-11-25T10:56Z: 60 success, 9 skipped, 2 failed (Test UI (2/16) and its Test UI roll-up). The one failing case is examples/schema-catalog/test/kanban-column-cards-6939.test.tsx (the kanban board still showed its loading skeleton when waitFor gave up). No path of this PR is on that surface; the same shard is green at 8e8243da, whose code is identical, and on main 057cedfa9b6f. Read as a flake; a re-run of that job is owed before landing.
  • K = 1 against origin/main 057cedfa9b6f (landing-k OK). git merge-tree against it is clean.
  • feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations #37256 has not merged. It still shares knowledge-service-plugin.ts, and the two heads merge clean. The keep-list for the second lander from the prior L1 stands. The second lander also keeps BASE_URL_PROVIDERS, positiveIntegerSetting(), hostOf() and the endpoint= field of the boot line.
  • Declarations: Clause-②: yes (widening) and Metadata-protocol: none still hold, and patch on the three packages is unchanged. The delta adds no export and changes no manifest key.
  • Same-head contract review at TIER_DEFAULT (declaration face): PASS.
  • S3 (should-fix) — the cloud ordering claim is still not measured. The seat owes one cloud reading: the phase bindSettings() runs in, and whether its hot path registers or replaces. The seat holds landing until that reading is recorded on the PR. Nothing is owed by the dev.
  • N1 to N5 are carried from the prior L1 as follow-ups.
  • N7 — Ollama at a host other than localhost cannot be set from Settings, because the form offers no Base URL for it. The field's description reads wider than the two providers it is shown for. A follow-up on the form.
  • N8 — the Test embedder check does not read the number keys, so it reports complete for a value the boot refuses.
  • PR body: several lines are stale at this head (the Base URL line, the key pin, the test list, both ablation lines, the two-minute check count, the local-readings head and the provenance sha). The seat corrects them before marking the PR ready.
  • Next: the seat records the S3 cloud reading and corrects the body. The PR is still a draft.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head fa818f4d40749e28de09bbd747e9ca3c829f17ed · 2026-11-25T13:54Z

  • Same-head delta over the L1 ACCEPT 7160418676. The head is unchanged. This closes the S3 that record held open.
  • S3 closed — the cloud ordering is now measured. The reading is cloud-confirm 7159003875 on Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted #37094, which answers mailbox request 7158960504.
    • service-ai applies its embedder in a kernel:ready hook (bindSettings → applyEmbedder), so its boot-time registration comes before the kernel:bootstrapped placeholder.
    • A later ai settings save calls replaceService and never registerService. It replaces the placeholder without throwing.
    • A cold boot with a configured provider still logs the existing applyEmbedder warning, the same as on main. The placeholder does not make it worse.
    • No cloud deployment mounts the open KnowledgeServicePlugin beside service-ai.
    • This matches the PR's ordering claim. The seat added the reading to the PR body under that claim (read-back identical).
  • No must-fix, no should-fix.
  • Landing (zone a4-K):

Conflict in content/docs/ai/knowledge-rag.mdx resolved by keeping both
sections: "Configuring the embedder from Settings" (this branch) and
"Splitting documents into passages" (origin/main).

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

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head f6a93ede0566eb2738fffa91bb93b4e88b2236fa · 2026-11-26T00:05Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

Contract review

Served-tier: TIER_DEFAULT
Head-sha: f6a93ede0566eb2738fffa91bb93b4e88b2236fa
Local-runs: none
Scope: the declaration face of PR #37265 (Clause-②: yes (widening))

① Derived judgments

  • Merge-only delta over the PASS 7160409027. Head f6a93ede merges main 98bda0ac into fa818f4d. The PR's own changed lines are byte-identical across the merge (21 files, +837/−5), so every judgment in that record stands.

② Semver level

  • Unchanged.

③ Boundary flags

  • None new. Check-runs at this head: 62 success, 9 skipped, 0 failed.

④ Design judgment

  • Holds as it did at fa818f4d.

Reviewed-by: session_01QSeKYpEsWWE9Y5YtSsDgqZ

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

Landing · 2026-11-26T00:06Z · head f6a93ede. The merge with main is fresh, so K is 0. git merge-tree against origin/main is clean, and CI shows 62 success, 9 skipped and 0 failed. Merge-only L1 ACCEPT 7178386857 · TIER_DEFAULT PASS 7178396105. Not governed. Readying and arming auto-merge through the queue.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 26, 2026 00:07
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 26, 2026
Merged via the queue into main with commit b8c8c88 Nov 26, 2026
72 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-37094-open-embedder-settings branch November 26, 2026 00:30
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
… hit's title is the object's display field (objectstack-ai#37301)

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

Fixes objectstack-ai#36993
Fixes objectstack-ai#36994

Clause-②: no
Metadata-protocol: none

## 维护者速读
- 用户能看到什么变化:在挂了知识库的应用里,一个人能看的记录很少时,AI
检索不再返回空或只剩一两条,而是继续往后找,补满到要的条数;命中结果的标题改为取对象的名称字段(比如客户的「名称」、发票的编号),不再只认名为
title 的字段。
- 为什么做:知识检索平台化专题的第一、四阶段两张卡,同一个文件一起修;「按记录返回」那张卡要在这次的补齐逻辑上继续做。
-
出错会怎样:最坏是检索多读一轮、稍慢,或某条命中没有标题。权限检查只多不少:名称字段对某人不可查时,这个知识源对他不检索;旧索引里的标题还取自名为
title 的字段,所以在索引重建之前,title 字段对某人不可查时同样不检索。可以直接撤回。
- 要你做的:无。

## What changes

**Search refills after the permission filter (objectstack-ai#36993).**
`KnowledgeService.search` re-checks every object-source hit as the
caller *after* ranking, so a caller who may read few of the matching
rows was answered from what was left of `topK` ranked hits. Now:

- When the re-check can remove hits (a caller who is not the system
identity, with a data engine bound), each `object` source is asked for
`topK × SEARCH_FIRST_ROUND_FACTOR` (5).
- When the survivors name fewer than `topK` records (several passages of
one record count once: an object hit is its source and record id, any
other hit its document), every `object` source that answered as many
hits as it was asked (the only ones that may hold more) is asked once
more, for `topK × SEARCH_REFILL_FACTOR` (20, the cap). That round's
answer replaces the source's first-round hits; a source whose refill
throws keeps its first-round survivors. At most two rounds; an adapter
that caps `topK` answers fewer than asked and is never asked again.
- A `file` / `http` source is asked for `topK` once (the re-check never
removes its hits). The system identity gets one round of `topK`, no
refill. No context: object sources stay unsearched, as before (fail
closed).
- The answer is still at most `topK` chunk-level hits, sorted by score;
`search`'s return type is unchanged (`expectTypeOf` pin). The count the
re-check removed is logged at `debug` only, never returned.
- The adapter loop moved into a private `searchRound`, unchanged in
behaviour (foreign-source hits dropped and warned, a throwing adapter
logged and skipped).

**A hit's title is the object's display field (objectstack-ai#36994).**
`recordToDocument` read `record.title`. Per ADR-0161 K5 ("the title is
the object's display field"), it now reads the field
`documentTitleField(schema)` names: `resolveDisplayField` (ADR-0079:
`nameField`, its deprecated alias, else the derivation), and with no
object definition a field named `title`, as before. A withheld field
(credential-class or `internal`), an empty value, a value that is not
text or a finite number, a definition that resolves no display field, or
a `nameField` the definition does not declare gives no title.
`resolveRecordDisplayName` is not used: its `Record #id` floor is a UI
label.

The source admission's field gate (`servedFieldsOf`) asks about the same
field through the same `documentTitleField`. So a source whose object's
display field the caller may not query is not searched for that caller
at all. It also keeps asking about a declared field named `title`, as
before: documents indexed under the earlier rule carry that field's
value as their title and stay in the index until a complete reindex
writes them again, and nothing reindexes at boot. That arm is retired
once the index is proven rebuilt under the display-field rule (the
recipe hash that names the title rule, ADR-0161 K7, and the rebuild of a
stale source, objectstack-ai#37099); the code comment says so.

Docs: `content/docs/protocol/knowledge.mdx` states the refill and its
cap, and the display-field title (three places that said "the record
`title`"); `content/docs/ai/knowledge-rag.mdx` says the same in two
sentences. `content/docs/permissions/system-context.mdx` row 46 keys
`search` too (it now reads `isSystem`: the system identity skips the
over-fetch and the refill), and its generated register is regenerated
(`check:system-context-census --write`).

## Tests

`packages/services/service-knowledge`: `pnpm test` 8 files / 219 tests
passed at 4621738; `pnpm typecheck` exit 0 (incl.
`check:test-typecheck`). New pins in `knowledge-service.test.ts` (two
top-level describes) and `knowledge-source-admission.test.ts` (one):

- 100 hits, the caller may read 5 spread across them → those 5, best
first; asked `[s1, 25]` then `[s1, 100]`.
- A readable row beyond the cap → fewer than `topK`, never a third
round. Enough survivors → no refill. An adapter capping at 10 → asked
once. Several sources → only the saturated one refilled. The refill
decision counts records: topK 3, one source answers two passages of one
readable record, another holds a readable record past its first round
that outranks both → it is refilled and answers `[s1-c0, s1-c15, s2-a]`.
A failed refill keeps round one. System identity → one round of `topK`,
no re-check. No context → only the file source, asked `topK`. A file
source beside an object source → asked `topK` once.
- Removed count only in the `debug` log; answer and return type
unchanged.
- Title: explicit `nameField`; derived `name` over `title`; formula
(text) and autonumber name fields (a number value → its text); withheld
internal / secret name fields; empty, non-text, unresolvable and
undeclared-`nameField` cases; no definition → `title`; the event sync
and the reindex walk read the definition off the engine.
- Field gate: hiding the display field refuses the source even with
`title` visible; hiding a declared `title` that is not the display field
refuses it too (the adapter returns a stored hit carrying an old-rule
title, and the answer is empty); a caller who may query both gets the
hit.

<details><summary>Ablations: each committed first, mutated through
scripts/ablation-replace.mjs, restored to HEAD with git diff HEAD
empty</summary>

- Refill disabled (`if (false && filtered && kept.length < topK)`): 6
refill tests red, 5 green (the ones that pin "no refill").
- Title back to `record.title`: 5 title tests red.
- Field gate back to `title` only: both display-field gate tests red.
- Refill decision back to counting hits (`kept.length`): the
record-counting test red, 150 green.
- The declared-`title` arm deleted from the gate: its refusal pin red,
24 green.

</details>

## Acceptance notes

- **objectstack-ai#36993 point 2 is applied to the refill decision only.** The answer
stays at most `topK` chunk-level hits (`KnowledgeSearchOptions.topK` is
"Max number of hits to return"; `search_knowledge` returns "at most
`topK`" passages; the card: "what is returned stays chunk-level hits").
Counting records decides whether to refill, and with several sources
that changes the answer: another source's refill can outrank a second
passage of a record already counted (pinned above).
- **The declared `title` arm of the field gate is temporary.** Retire it
when the index is proven rebuilt under the display-field rule (ADR-0161
K7 recipe hash, objectstack-ai#37099).
- **Title egress** (the question raised on objectstack-ai#36994): ADR-0161 K5 declares
the title as the object's display field, so it is sent whether or not
the source lists that field among its content fields. It is withheld
when the field is credential-class or `internal`. The field-egress
declaration of cloud ADR-0119 does not exist yet; when it does,
`documentTitleField` is the one place assembly and the gate both read.
- The title enters `docHash`, so the first complete reindex after this
lands rewrites the documents whose title changed.
- Seat 4's objectstack-ai#37287 edits the same file; `scripts/pm/overlap-check.mjs`
merges this branch with its head cleanly (the search factors sit beside
`LIST_DOCUMENTS_PAGE_SIZE` to stay clear of its new constant).

## Verification

Files to read first:
`packages/services/service-knowledge/src/knowledge-service.ts`
(`search`, `searchRound`, `documentTitle`),
`knowledge-source-admission.ts` (`documentTitleField`,
`servedFieldsOf`).

Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/knowledge-service.test.ts -t refills` — 11
tests pass; the first shows a caller reading 5 of 100 hits getting all
5.

<details><summary>Local gate families: the derived list
(scripts/pm/dispatch-gates.mjs --commands, 98 commands, derived at
ecb0842), run in order; CI runs the full farm</summary>

- Rework round (4621738): package test 8 files / 219, typecheck 0,
eslint on the four changed source and test files 0, check:doc-anchors 0,
check:system-context-census 0, overlap-check clean against origin/main,
objectstack-ai#37287 and objectstack-ai#37265.


- 79 of 98 run: 76 exit 0; 3 PREREQUISITE NOT MET (not verdicts, NOT
MEASURED locally, CI builds them): check-plugin-teardown-shape
--self-test (shallow clone cannot reach its pinned fixture commit), spec
check:skill-examples (client-react dist not built),
check:dual-build-cjs-loads (hono / account dist not built).
- The remaining 19 (the repo-wide eslint-backed ratchets onward) were
still running when this was written: NOT MEASURED locally; their CI
check-runs are the reading.
- Also run: package typecheck (exit 0, incl. check:test-typecheck),
eslint on the four changed source and test files (exit 0),
check:doc-anchors (exit 0), check:system-context-census (exit 0 after
row 46 below), scripts/pm/overlap-check.mjs (clean against origin/main,
objectstack-ai#37287 and objectstack-ai#37265).

</details>

## Human Minimum

- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
- [x] 2. Every name I added uses the casing for its kind.
- [x] 3. No formatter ran; `pnpm lint` passes.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` touched: its generated artifacts are
regenerated and committed. (not touched)
- [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_01JQwxbWqwmAwx7eD4Xf3dv1

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

<!-- signed: repo:cloud#1 · os-warren · session_01JQwxbWqwmAwx7eD4Xf3dv1
-->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
… Chinese-aware), the chunk channel and the split key; KnowledgeChunk.metadata and knowledge.chunk_overlap retired (objectstack-ai#37287)

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ
Fixes objectstack-ai#37098

Clause-②: yes (narrowing) — widens the knowledge contract (the `split`
key, `chunks`, `headingPath`, the adapter's `capabilities` and
`embedding`, `IEmbedder.maxInputTokens`, the reindex `failed` /
`failures`) and narrows two accept sets: `KnowledgeChunk.metadata` is
refused, and `knowledge.chunk_overlap` is no longer a key of the
`knowledge` settings namespace
Metadata-protocol: narrowed
Skills-docs: follow-up objectstack-ai#37292 — `skills/objectstack-ai/SKILL.md` does
not yet teach `split` or name the two retired keys; that file is
governed and outside this claim. `content/docs/protocol/knowledge.mdx`
(new §3.5) and `content/docs/ai/knowledge-rag.mdx` document it here.

## 维护者速读
- 用户能看到什么变化:知识检索在建索引时由平台统一把文档切成片段,长制度按章、条切开,中文按句号问号断句,不会切在「3.2 条」「400.50
元」中间,也不切开表格。
- 为什么做:属于「知识检索平台化」专题第二阶段,让每种存储拿到的片段完全一致。
-
出错会怎样:整篇切法下超过模型上限的文档会从检索中移除并报失败,不会被截断;设置页的「片段重叠」一项被移除(它从未生效),片段上一个从未被使用的字段也被移除,写了它的代码会收到带修复说明的报错。
- 要你做什么:无。

## What changes

- **One splitter in the service**
(`packages/services/service-knowledge/src/split/`): `whole`, `recursive`
(blank line, line break, sentence end, semicolon, character;
Chinese-aware sentence rule; tables and list items kept whole while they
fit; short pieces merged up to `minChars`), and `markdown` (one section
per heading, the heading path embedded at each passage's start and
carried as `headingPath`).
- **The chunk channel, as ADR-0161 K8 item 5 settled it.**
`KnowledgeDocument.chunks?`, `KnowledgeChunk.headingPath?`, and
`IKnowledgeAdapter.capabilities?.chunks`. An adapter that declares it
gets every document with the service's passages; one that does not keeps
receiving whole documents. `indexDocument` refuses caller-supplied
`chunks`, as it refuses `docHash`.
- **The limit, per ADR-0161 K8 item 6.**
`IKnowledgeAdapter.embedding?.maxInputTokens` and
`IEmbedder.maxInputTokens?`, read at use, never cached.
`embedder-openai` reports its limit from the objectstack-ai#37093 table. A passage
keeps `maxChars` (`split.maxChars`, else `knowledge.chunk_target`, else
800) and, when a limit is known, `estimateTokens` within 80% of it (the
shared estimate, not forked).
- **`whole` over the budget is removed and reported, never truncated.**
`reindexSource` gains `failed` and `failures` (at most 20 named). The
event sync logs at `error` with source, record id, estimate and limit.
`indexDocument` throws.
- **The `split` key**, ADR-0161 K8 item 10:
`ObjectKnowledgeSource.split?: { strategy, maxChars?, minChars? }`, read
by the splitter.
- **`knowledge-memory` drops its own chunking.** It declares
`capabilities.chunks` and indexes the service's passages as given.
- **Settings.** `knowledge.chunk_target` gains its reader, through the
`settings` service at use, never at boot. It is now shown for the
in-memory adapter too. `knowledge.chunk_overlap` is retired the way the
Localization format keys were: removed from the manifest and its 11
translations, `version` 1 to 2, a stored row kept, a write refused `400
UNKNOWN_KEY`.
- `docHash` keeps its recipe: the passages are derived from `content`
and do not enter it.

## BREAKING

- `KnowledgeChunk.metadata`: FROM an optional record, accepted and
stripped, TO a `retiredKey()` tombstone (a parse refusal with the
prescription; `tsc` types it `never`). Nothing wrote or read it. Fix:
delete the key; filter on the document's `metadata`. ADR-0161 K8 item 5,
by seat direction 7158283273.
- `knowledge.chunk_overlap`: FROM a key of the `knowledge` settings
namespace TO no key (not shown or resolved; a write is refused `400
UNKNOWN_KEY`; a stored row is kept). Nothing read it. Fix: stop writing
it.

Retirement kit, per the `spec-property-retirement` skill, under protocol
major 18 (seat ruling A):
- the `retiredKey()` tombstone;
- `RETIRED_KEYS_BY_MAJOR[18]` row `ai/KnowledgeChunk:metadata`;
- D3 `knowledge-chunk-metadata-retired` and its `STEP18_RATIONALE`
fragment;
- the `[RETIRED]` line in `authorable-surface/ai.json`;
- the regenerated reference;
- the pin `packages/spec/src/ai/knowledge-document.test.ts`;
- the changeset's `adr-0087: registered` marker.

No D2 conversion: a chunk is a runtime contract shape, never stored in
stack metadata, so `os migrate meta` has no source to rewrite — the
`ActionDescriptor.isAsync` disposition. The settings key follows the
Localization format keys' retirement: specifier and 11 translations
removed, manifest `version: 2`, stored rows kept.

## Tests

- `split.test.ts`: six golden files (Chinese regulation with 章/条, a
Markdown table, a long unpunctuated run, mixed zh/en with quotes, 「3.2
条」 and 「400.50 元」, a Markdown heading tree), direct assertions of each
rule, and a seeded property test. Over 500 random documents with random
bounds, no passage's estimate exceeds the budget or the limit, no
passage exceeds `maxChars`, and `recursive` loses no text. A `whole`
property test runs 200 more.
- `contract-stubs.test.ts`: the contract suite against two stubs. One
declares no capability and is pinned to receive whole documents, never
`chunks`. The other declares `chunks` and stores passages as given.
- `testing.ts`: the suite gains the chunk-channel cases. With chunks,
the adapter receives exactly `splitDocument`'s passages and a hit is one
of them by id and text; `whole` over the budget is removed and reported;
caller chunks are refused. Without chunks, whole documents arrive.
`knowledge-memory` runs it with `chunks: true`.
- `chunk-channel.test.ts`: the event path at `error`; `indexDocument`
over the budget; the bounded `failures`; the `maxChars` precedence; the
descriptor read at use; and end to end, `chunk_target` saved after boot
cuts the next write through the real settings service.
- `openai-embedder.test.ts`: the reported limit.
`knowledge.manifest.test.ts`: `version` 2 and `chunk_overlap` absent.
- `packages/spec/src/ai/knowledge-document.test.ts`: the retired
`KnowledgeChunk.metadata` is refused at parse with the prescription
(also inside `KnowledgeDocument.chunks`), a chunk without it parses
clean, and authoring it is a `@ts-expect-error`.

The local readings sit in the os-dev report comment on this PR.

## Acceptance notes

- **`KnowledgeChunk.metadata` is retired here** (seat direction
7158283273, option B; registered under protocol major 18 by the seat's
ruling A). The claim was re-issued as `Metadata-protocol: narrowed`
(7158315677).
- **No refinement for `minChars` ≤ `maxChars`.** The published JSON
Schema cannot carry it, and the baseline that declares a dropped
refinement is outside this claim. A `minChars` above the effective
`maxChars` reads as `maxChars`, documented on the key.
- **A table that does not fit** is cut between rows, each piece
repeating the header. A list item that does not fit is cut as a
paragraph. The budget is the hard bound.
- **Re-splitting.** `docHash` does not cover passages, so a changed
`split`, `chunk_target` or limit re-splits a document only when the
document itself changes. The index fingerprint (ADR-0161 K7; objectstack-ai#37100)
rebuilds a source on a split change. The docs say so.
- **Merged with objectstack-ai#37256** (the organization filter) through
`scripts/pm/os-regen-merge.sh`, keeping both sides:
  - `organizationId` next to `chunks`;
  - the organization filter before ranking, over the service's passages;
  - `implements: { listDocuments, chunks, organizationIds }`;
  - `resolveTenancyPosture` next to `resolveChunkTarget`.
- **objectstack-ai#37265 still shares files**, a declared serial constraint: whichever
lands second merges main.
- Two test pins outside the claim's literal file list moved with the
ordered retirement, both deliberate tripwires on the manifest:
`settings-visibility-declaration.pin.test.ts` (90 to 87 predicates) and
`knowledge.manifest.test.ts`.

## Verification

Read first: `packages/services/service-knowledge/src/split/splitter.ts`
(the sentence rule, the block-aware merge, the even character cut);
`knowledge-service.ts` `prepareDocuments` / `writeSynced` and the walk's
failure branch; `packages/spec/src/contracts/knowledge-adapter.ts`.

Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/split.test.ts`. Expect 25 passed, then open
`src/__tests__/fixtures/split/regulation-zh.tight.golden.json` and see
each 章 title leading its own chapter.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ope, by the records a source indexes or by a parent through a listed lookup (objectstack-ai#37342)

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

Fixes objectstack-ai#37308

Clause-②: yes
Metadata-protocol: none

## 维护者速读

-
用户能看到什么变化:知识检索可以限定范围了:只在指定的几条记录里找,或者只在一份上级记录(比如一份制度)下面的条款里找,返回的前几条结果都来自范围内。
- 为什么做:属于「知识检索平台化」专题第三阶段,按您定的「也能指定上级对象(制度)」实现;之后给 AI 用的检索工具也会接上这个参数。
- 出错会怎样:范围只会缩小结果,不会放宽权限,每条结果仍按提问人的权限重新读取;最坏是限定范围后漏掉结果。没有数据迁移,撤回即可。
-
要你做什么:无需你操作。您已在卡片上同意的安全登记行已在(`d1ca7f01`)。开源向量库那个改动先合并了,本分支已合入主干,并让向量库也按范围过滤(在数据库里先筛再排序);由座位做差量复核后重新排队合并。「按记录返回」已合并并合入本分支;与开源向量库那个改动仍有文字冲突,后合并的一方处理。

## What changes

ADR-0161 K8 item 17, in the shape its dated note of 2026-11-25 (objectstack-ai#37324,
merged as `13ffe1c0`) gives it, built in one PR as the note says: the
member, its first reader in `knowledge-memory`, and the suite cases.

**`@objectstack/spec`** (types only, no metadata key):

- `KnowledgeSearchOptions.scope?: Array<{ object: string; ids: string[]
}>` (`packages/spec/src/contracts/knowledge-service.ts`): an option of
the service, not a contract member. Its TSDoc states the own-object and
parent readings, union, absent/empty, and the bounds with the coded
refusal.
- `AdapterSearchOptions.scope?: AdapterScopeTerm[]` and the exported
type `AdapterScopeTerm`
(`packages/spec/src/contracts/knowledge-adapter.ts`): `{ kind: 'record',
ids }` or `{ kind: 'metadata', field, ids }`. Its TSDoc states
absent/present/empty, the AND with `organizationIds` and `filter`, the
bounds an adapter can rely on (at most 10 terms, at most 500 ids each,
every id a non-empty string), and that the service checks every hit
after the answer, so an adapter returns the document's `metadata` on its
hits.
- Regenerated: `api-surface/contracts.json`,
`export-origins/contracts.json` (the new export).

**`@objectstack/service-knowledge`**:

- New `src/knowledge-search-scope.ts`:
- `readSearchScope`: the bounds, `SEARCH_SCOPE_MAX_ENTRIES = 10`,
`SEARCH_SCOPE_MAX_IDS = 500`. Past them it throws `code:
'VALIDATION_ERROR'`, `status: 400` (ADR-0112), naming the bound, before
anything else in `search` runs.
- `scopeTermsFor`: an entry naming the source's object gives a `record`
term. An entry naming another object gives a `metadata` term on the one
`metadataFields` member that is a `lookup` or `master_detail` field
whose `referenceTargetOf` is that object, read from the registered
definition. A `user` field, a withheld (credential-class or `internal`)
field, a field whose target cannot be read, two or more such fields, no
definition, and a `file` / `http` source all give nothing.
- `scopeCheck`: the hit check. It judges `sourceRecordId` or
`metadata[field]`, compares strings and numbers by `String(v)`, and
matches a list when any element matches. Anything else, or no value,
fails closed.
- `KnowledgeService.search`:
  - Validates first.
- `sourcesInScope` pairs each admitted source with its terms. A source
no entry reaches is not searched (debug). The two-lookup ambiguity is
logged once per source and object at `warn`, naming the fields.
- `searchRound` hands each adapter a copy of its terms and checks every
hit after the answer. The first drop for an adapter is logged once at
`warn`.
  - `answered` stays the adapter's own count.
- `src/testing.ts` (the contract suite):
  - New required `implements.scope`.
- Adapter-alone cases, run when `implements.scope` is true: a record
term filters before ranking (topK 1); a metadata term with a list value
returns the document's metadata; the number 7 matches `'7'`; terms are a
union; an empty list or a term with no ids ranks nothing; without the
member everything is ranked; with `organizationIds`, both apply.
- Cases through a real `KnowledgeService` for every adapter: an
own-object scope fills topK from in-scope passages; a parent scope works
through the listed lookup; an adapter with the member stripped answers
no out-of-scope hit, and the service logs once.
  - `serviceOver` gains `schemas`, `stripScope` and `logger`.

**`@objectstack/knowledge-memory`**: applies `scope` after the
organization filter and before scoring. It declares `implements.scope:
true`.

**`@objectstack/knowledge-pgvector`** (landed first, objectstack-ai#37337): applies
`scope` in the same inner `WHERE` as the organization filter, before
`ORDER BY` / `LIMIT`. A `record` term is `source_record_id =
ANY($n::text[])`; a `metadata` term holds when the stored jsonb value of
its field is a string or number equal to an id as text, or a list with
such an element. Ids and field names are bound parameters only. A scope
with no term that has ids answers `[]` before any query. Its live
contract run declares `implements.scope: true`.

**Docs**:

- `content/docs/protocol/knowledge.mdx`: a new "Record scope" section in
§5, a pointer in §3.4, the suite sample, and §4.1 / the adapter table
naming pgvector's record scope.
- `content/docs/ai/knowledge-rag.mdx`: a new "Searching inside chosen
records" section.

**Changeset**: patch for the four packages, with `Clause-②: yes` and
`Metadata-protocol: none`. The change adds no metadata key, and a
non-protocol widening ships patch.

## Tests

- New `src/__tests__/knowledge-search-scope.test.ts`: bounds (each
refusal, and the exact-bound acceptance), term building (each reading of
the note), and the hit check.
- `src/__tests__/knowledge-service.test.ts`, new describe "search scope
(ADR-0161 K8, item 17)":
- the card's acceptance: 20 records, two in scope, topK 5, a full page;
  - an ignoring adapter: no out-of-scope hit, one log;
  - an unreached object: no adapter asked, empty answer;
  - an unreadable scoped record yields no hit;
  - the bounds refuse before any adapter or engine call;
  - empty scope and empty ids answer nothing;
  - the two-lookup case logs once;
  - a numeric lookup value matches its string id;
- a parent scope makes no engine call naming the parent object, and an
adapter that widens the terms it was handed (more ids, an extra term)
still has every out-of-scope hit dropped; every round is handed the
service's own terms (review round 1);
- a scope with `groupBy`, and one with `granularity: 'record'`, over an
adapter that ignores the scope: every round is handed the record term
and no out-of-scope record answers (review round 2).
- The contract suite runs on `knowledge-memory` and both stubs.
- Mutation checks, run locally and reverted:
- `knowledge-memory` with its scope filter removed: 7 suite cases fail.
- `KnowledgeService` without the after-answer check: 7 cases fail across
the stubs and the service tests.
- Handing the adapter the live terms, or reading the parent object's
definition: the round-1 case fails.
- Skipping the scope under `groupBy`, skipping it under record
granularity, or the `groupBy` source filter rebuilding its entries
without the terms: the round-2 case fails.

**Local runs at `760716bc`** (after merging `main` at `98bda0ac`, which
brought objectstack-ai#37337):

- `pnpm --filter @objectstack/spec build` and `check:generated`: exit 0,
after the merge's deferred regeneration of `api-surface/contracts.json`
and `export-origins/contracts.json` (`4552e7c4`).
- `pnpm --filter @objectstack/service-knowledge typecheck` and
`check:test-typecheck`: exit 0. `test`: 13 files, 365 tests passed.
- `pnpm --filter @objectstack/knowledge-memory typecheck` and
`check:test-typecheck`: exit 0. `test`: 2 files, 56 tests passed.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0.
`test` against a local PostgreSQL 16 with pgvector,
`OS_TEST_POSTGRES_URL` set and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`: 4
files, 67 tests passed, every scope case of the suite among them (record
term, metadata term with a list, the number 7, union, empty, absent,
with `organizationIds`; through the service: own object, the parent
through the listed lookup, the member stripped). With the SQL scope
filter removed: 7 of them fail.
- `pnpm --filter @objectstack/core test:repo` (the census pin, at
`d1ca7f01`): 8 files, 110 tests passed.
- **Derived gates at `760716bc`.** `dispatch-gates --commands` derives
119 commands from the 19 changed paths (the 118 before, plus `pnpm
check:kernel-hook-pairs`). Each was run at this head with its output in
its own file and its exit code read before any pipe.
`check:dual-build-cjs-loads` first answered 3 (prerequisite not met: the
new `knowledge-pgvector` had no `dist/`); after `pnpm --filter
@objectstack/knowledge-pgvector build` it was run again, and the record
holds that run.

```text
Run reconciliation — 119 derived, 119 run, 0 NOT-MEASURED, 0 UNRUN.
✓ dispatch-gates --ran: 119 derived famil(ies) accounted for — 119 run, 0 NOT-MEASURED (a DERIVED zero — all 119 recorded an exit code and none of them is 3).
```

<details><summary>The 119 commands at <code>760716bc</code></summary>

| Command | Exit |
|:--|:--|
| `node scripts/check-adr-0087-registration.mjs --base origin/main` | 0
|
| `node scripts/check-adr-0087-registration.mjs --self-test` | 0 |
| `node scripts/check-adr-links.mjs` | 0 |
| `node scripts/check-adr-links.mjs --self-test` | 0 |
| `node scripts/check-changeset-no-major.mjs --base origin/main` | 0 |
| `node scripts/check-closing-keyword-parity.mjs` | 0 |
| `node scripts/check-closing-keyword-parity.mjs --self-test` | 0 |
| `node scripts/check-comment-mask-adoption.mjs` | 0 |
| `node scripts/check-comment-mask-adoption.mjs --self-test` | 0 |
| `node scripts/check-comment-mask-corpus.mjs` | 0 |
| `node scripts/check-dev-prereqs.mjs --self-test` | 0 |
| `node scripts/check-doc-route-spelling.mjs --advisory` | 0 |
| `node scripts/check-doc-route-spelling.mjs --self-test` | 0 |
| `node scripts/check-docs-section-name.mjs` | 0 |
| `node scripts/check-docs-section-name.mjs --self-test` | 0 |
| `node scripts/check-dts-emitted.mjs --self-test` | 0 |
| `node scripts/check-empty-changeset.mjs --base origin/main` | 0 |
| `node scripts/check-empty-changeset.mjs --self-test` | 0 |
| `node scripts/check-issue-citations.mjs` | 0 |
| `node scripts/check-plugin-teardown-shape.mjs` | 0 |
| `node scripts/check-plugin-teardown-shape.mjs --self-test` | 0 |
| `node scripts/check-section-landing-index.mjs` | 0 |
| `node scripts/check-section-landing-index.mjs --self-test` | 0 |
| `node scripts/check-tenant-audit-census.mjs` | 0 |
| `node scripts/check-tenant-audit-census.mjs --self-test` | 0 |
| `node scripts/ci/assert-turbo-remote-cache.mjs --self-test` | 0 |
| `node scripts/ci/plan-test-core-shards.mjs --self-test` | 0 |
| `node scripts/ci/prune-turbo-cache.mjs --self-test` | 0 |
| `node scripts/ci/snapshot-next.mjs --self-test` | 0 |
| `node scripts/docs-audit/check-affected-docs.mjs` | 0 |
| `node scripts/docs-audit/check-drift-comment.mjs` | 0 |
| `node scripts/pm/check-governed-queue-guard.mjs --self-test` | 0 |
| `node scripts/pm/release-rehearsal-clone.mjs --self-test` | 0 |
| `node scripts/release-pending-publish.mjs --self-test` | 0 |
| `pnpm --filter @objectstack/lint run check:doc-formula-expressions` |
0 |
| `pnpm --filter @objectstack/lint run check:doc-security-posture` | 0 |
| `pnpm --filter @objectstack/spec run check:api-surface` | 0 |
| `pnpm --filter @objectstack/spec run check:authorable-surface` | 0 |
| `pnpm --filter @objectstack/spec run check:browser-reachable-entries`
| 0 |
| `pnpm --filter @objectstack/spec run check:docs` | 0 |
| `pnpm --filter @objectstack/spec run check:dual-source-exports` | 0 |
| `pnpm --filter @objectstack/spec run check:duration-unit-keys` | 0 |
| `pnpm --filter @objectstack/spec run check:empty-state` | 0 |
| `pnpm --filter @objectstack/spec run check:entry-nameability` | 0 |
| `pnpm --filter @objectstack/spec run check:error-code-provenance` | 0
|
| `pnpm --filter @objectstack/spec run check:export-origins` | 0 |
| `pnpm --filter @objectstack/spec run check:exported-any` | 0 |
| `pnpm --filter @objectstack/spec run check:generated` | 0 |
| `pnpm --filter @objectstack/spec run check:liveness` | 0 |
| `pnpm --filter @objectstack/spec run check:llms-txt` | 0 |
| `pnpm --filter @objectstack/spec run check:skill-examples` | 0 |
| `pnpm --filter @objectstack/spec run check:skill-refs` | 0 |
| `pnpm --filter @objectstack/spec run check:strictness-ledger` | 0 |
| `pnpm --filter @objectstack/spec run check:variant-docs` | 0 |
| `pnpm --filter @objectstack/spec run check:yaml-examples` | 0 |
| `pnpm check:adr-anchors` | 0 |
| `pnpm check:adr-symbol-anchors` | 0 |
| `pnpm check:changeset-gate-self-tests` | 0 |
| `pnpm check:ci-filter-parity` | 0 |
| `pnpm check:closed-ceremony-text` | 0 |
| `pnpm check:corpus-claim-drift` | 0 |
| `pnpm check:cross-package-test-inputs` | 0 |
| `pnpm check:dispatcher-error-vocabulary` | 0 |
| `pnpm check:doc-anchors` | 0 |
| `pnpm check:doc-authoring` | 0 |
| `pnpm check:doc-frontmatter` | 0 |
| `pnpm check:docs-audit-scope` | 0 |
| `pnpm check:docs-redirects` | 0 |
| `pnpm check:docs-single-h1` | 0 |
| `pnpm check:docs-spec-enumerations` | 0 |
| `pnpm check:docs-transcript-drift` | 0 |
| `pnpm check:driver-memory-census` | 0 |
| `pnpm check:dts-closure` | 0 |
| `pnpm check:engine-double-contract` | 0 |
| `pnpm check:error-status-conformance` | 0 |
| `pnpm check:gitlink-declared` | 0 |
| `pnpm check:init-service-contract` | 0 |
| `pnpm check:issue-citations` | 0 |
| `pnpm check:kernel-hook-pairs` | 0 |
| `pnpm check:keyed-text-bounds` | 0 |
| `pnpm check:lean-entry-closure` | 0 |
| `pnpm check:logger-receiver-detach` | 0 |
| `pnpm check:merge-driver` | 0 |
| `pnpm check:nul-bytes` | 0 |
| `pnpm check:object-def-param-keys` | 0 |
| `pnpm check:objectql-double-limit` | 0 |
| `pnpm check:optional-error-sink` | 0 |
| `pnpm check:org-identifier` | 0 |
| `pnpm check:package-naming` | 0 |
| `pnpm check:page-declaration-shape` | 0 |
| `pnpm check:platform-object-tenancy-census` | 0 |
| `pnpm check:pm-expected-skips` | 0 |
| `pnpm check:pm-prior-rulings` | 0 |
| `pnpm check:published-files` | 0 |
| `pnpm check:published-readme-links` | 0 |
| `pnpm check:query-options-erasure` | 0 |
| `pnpm check:react-page-adapter-contract` | 0 |
| `pnpm check:refd-timer-probe` | 0 |
| `pnpm check:registry-log-declared` | 0 |
| `pnpm check:rest-log-spy-declared` | 0 |
| `pnpm check:role-word` | 0 |
| `pnpm check:settings-bind-window` | 0 |
| `pnpm check:skill-identifier-liveness` | 0 |
| `pnpm check:slot-lookup` | 0 |
| `pnpm check:sourcemap-no-sources-content` | 0 |
| `pnpm check:spec-docblock-symbol-anchors` | 0 |
| `pnpm check:spec-parsed-alias` | 0 |
| `pnpm check:startup-registry-verdict` | 0 |
| `pnpm check:system-context-census` | 0 |
| `pnpm check:test-source-alias` | 0 |
| `pnpm check:tier-file-adoption` | 0 |
| `pnpm check:type-check-coverage` | 0 |
| `pnpm check:type-check-debt` | 0 |
| `pnpm check:undeclared-dep-imports` | 0 |
| `pnpm check:vendor-version-stamps` | 0 |
| `pnpm check:vouch-for-reference-callers` | 0 |
| `pnpm check:watch-hint-literal` | 0 |
| `pnpm check:where-matcher` | 0 |
| `pnpm check:dual-build-cjs-loads` | 0 |

</details>

Earlier heads ran the 118 then derived, all exit 0: `857a2e20` (after
three prerequisites were met) and `ca5a0c11`.

## Acceptance notes

**The five points carried from objectstack-ai#37329's contract review:**

1. **Metadata on hits.** The requirement that an adapter return the
document's `metadata` is stated on `AdapterSearchOptions.scope` and on
`KnowledgeHit.metadata`
(`packages/spec/src/ai/knowledge-document.zod.ts`, added in the merge of
`main` under the seat's claim amendment, review ruling (b)). It is
pinned: the suite's metadata-term case and the parent case through the
service both assert `hit.metadata.policy`.
2. **Ids compared as strings.** Pinned on `scopeCheck`, on the adapter
in the suite, and through the service (a lookup stored as the number 7
matches `'7'`). Only strings and numbers compare. An object, `null` or a
boolean never matches, so `'[object Object]'` cannot be matched by
accident.
3. **An empty scope or an entry with no ids.** It is answered empty,
never refused and never read as "no scope", and no adapter is asked. Why
empty rather than refused: it reads as an empty set reads everywhere
else in this contract (`organizationIds: []`). A caller that computes
ids (the records on screen, a policy's children) then needs no special
case for "none". The tool argument (objectstack-ai#37311) can still refuse at its own
door.
4. **Bounds.** 10 entries and 500 ids per entry are stated on both
TSDocs and pinned. The 500 ids of one term fit one `IN` list, and a
search hands at most 5,000 ids in all. ⚑ This PR owes a ceiling-tier
contract review (CONTRACT_REVIEW_TIER) for the new member.
5. **The opaque `filter`.** Finding for the seat to file:
`KnowledgeSearchOptions.filter` / `AdapterSearchOptions.filter` has no
producer in this tree. The one non-test caller of
`IKnowledgeService.search`, `createKnowledgeTools`, passes none, and the
service gives it no guarantee after the answer. This PR leaves it
unchanged and builds nothing from it. Whether it retires is its own
card. Carrier: none · noted, not filed. Dedupe words: knowledge opaque
filter, AdapterSearchOptions filter retire, KnowledgeSearchOptions
filter producer.

**What the note left to this PR, decided here:**

- **Refill.** `answered` stays the adapter's own count, so whether a
source may hold more is still judged on what it returned. The refill
after the permission filter counts records among the hits that passed
both checks.
- A person's search over an ignoring adapter therefore still reaches
in-scope hits through the refill.
- The system identity gets one round, and may answer fewer than topK
(pinned).
- **Log levels.**
- An adapter whose hits the check drops: `warn`, once per adapter. It is
a deployment defect, and rule 2 says nothing is skipped silently.
- Two lookups to one parent: `warn`, once per source and object. It is
an authoring defect.
- A source a scope does not reach: `debug`, per search, because it is
normal under a scope.
  - Counts appear in logs only, never in the answer.
- **Entry shape.** An entry with another key (for example `field`) is
refused rather than ignored. A `field` key is the note's deferred
alternative, so it fails loud instead of silently reading as something
else. An id that is not a non-empty string is refused: the contract
types ids as strings, and a stored numeric value still matches its
string id.

**Surface and overlap:**

- Outside the claimed file list: the two generated spec artifacts
(`api-surface/contracts.json`, `export-origins/contracts.json`),
required by `check:generated` for the new export.
- `packages/spec/src/ai/knowledge-document.zod.ts`: one TSDoc sentence,
inside the claim as the seat amended it.
- `packages/core/src/security/second-object-read-exposure.pin.test.ts`:
one `CALLERS` row, kind `not-a-served-read`, for
`knowledge-search-scope.ts`, in its own commit `d1ca7f01`, after the
maintainer approved it on the card thread (2026-11-25 22:48Z). The
census pin requires every caller of `referenceTargetOf` to be
classified; the seat's review agrees with the kind. The row cites the
service case that a parent-scoped search makes no engine call naming the
parent object. Run at `d1ca7f01`: `pnpm --filter @objectstack/core
test:repo`, 8 files, 110 tests passed.
- No `scripts/adr-anchors` entry: review ruling (c), not owed.
- `knowledge-ragflow` does not run the suite and ignores `scope` (objectstack-ai#37004
retires it). The service's check keeps its answers in scope. A parent
scope answers nothing from it if its hits carry no metadata.
- objectstack-ai#37337 (objectstack-ai#37100, pgvector) merged before this PR's queue run, and
`main` is merged again at `93c70347`. `searchWithRefusals` validates the
scope first; the admitted sources are filtered by the scope, then by
`groupBy`, then planned (`planSearches` carries each source's terms
beside its fingerprint, `SearchTarget.scope`), and `searchRound` hands
the adapter both `index` and `scope`. The suite's `implements`, the
stubs, `knowledge-memory` and the protocol sample declare the generation
keys and `scope`.
- objectstack-ai#37335 (record-level return) merged first, and `main` was merged into
this branch at `67f11a57`. `search()` validates the scope, `groupBy` and
`granularity` first, then filters the admitted sources by the scope
(`sourcesInScope`) and then by `groupBy` (`sourcesGroupableBy`). Every
round of the record-level path goes through `searchRound`, so every
round is handed the terms and checked.
- `packages/plugins/knowledge-pgvector/**`: inside the claim as the seat
widened it after objectstack-ai#37337 landed (objectstack-ai#37308 item 4): the scope filter in
`search()`, `implements.scope`, and nothing else.
- `overlap-check` at `760716bc`: `main`, objectstack-ai#37265 and objectstack-ai#37187 merge
cleanly.

## Verification

Read first:

1. `packages/services/service-knowledge/src/knowledge-search-scope.ts`:
the whole module (bounds, term building, hit check).
2. `KnowledgeService.search` / `sourcesInScope` / `searchRound` /
`checkScope` in `knowledge-service.ts`: the three-line change at the top
of `search`, and the check after the answer.
3. The two TSDocs in `packages/spec/src/contracts/`.

Two-minute check: run `pnpm --filter @objectstack/service-knowledge exec
vitest run --maxWorkers=2 src/__tests__/knowledge-search-scope.test.ts
src/__tests__/knowledge-service.test.ts -t scope`. Then open the "search
scope" describe and read the acceptance case "20 records, two of them in
scope, topK 5".

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

<!-- signed: repo:cloud#1 · os-warren · session_01JQwxbZmjM1KubX3ZAoJPPm
-->

---------

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

dependencies Pull requests that update a dependency file documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Open edition: register EMBEDDER_SERVICE from the ai.embedder_* settings when the knowledge service is mounted

2 participants