Skip to content

feat(service-knowledge): search answers records, not passages — granularity, groupBy and a freshness check - #37335

Merged
objectstack-fleet[bot] merged 9 commits into
mainfrom
claude/project-thread-oc6nsu
Nov 25, 2026
Merged

objectstack-fleet[bot] merged 9 commits into
mainfrom
claude/project-thread-oc6nsu

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

Requested by Warren · project thread

Fixes #37103

Clause-②: yes (widening)
Metadata-protocol: added
Skills-docs: none — no page under skills/** teaches the knowledge search options or the hit's shape (the one knowledge eval asks about source authoring); content/docs/ai/knowledge-rag.mdx and content/docs/protocol/knowledge.mdx teach them, updated here.

维护者速读

  • 用户能看到什么变化:应用检索知识时可以选「按记录返回」:同一份制度命中多个片段只返回一条(取最高分),也可以按某个字段分组(比如按制度)直接得到「哪几份制度」;默认行为不变。
  • 为什么做:知识检索平台化专题第二阶段,让制度问询先找到「哪几份制度」再交给模型,应用不用再自己去重。
  • 出错会怎样:只影响主动选了按记录返回的检索;建索引后被删、改过或不再符合条件的记录不会返回旧片段,并在后台自动修一次索引;可直接撤回本改动。
  • 要你做什么:无。

What changes

  • KnowledgeSearchOptions (packages/spec/src/contracts/knowledge-service.ts) gains granularity?: 'chunk' | 'record' (default chunk: the same hits, asks and reads as today, no extra read; on knowledge-memory each hit now also carries docHash and, when its passage has one, headingPath, the K8 items 3 and 14 members) and groupBy?: string. The return type stays KnowledgeHit[].
  • KnowledgeHitSchema gains docHash? (ADR-0161 K8 item 3) and headingPath? (item 14); knowledge-memory returns both on its hits.
  • KnowledgeService.search() under record granularity:
    • one hit per record, its best passage; topK counts records. Every source is asked topK × 5 and the saturated ones refilled once at topK × 20 when fewer than topK groups survive (the existing refill of service-knowledge: search returns a short page after the permission filter instead of refilling #36993, widened to every source and caller in this mode). That refill is the stated cap; fewer records within it answer fewer, logged at debug.
    • groupBy groups by metadata[groupBy]; same value = one group across sources; an object source without the field in metadataFields is not searched; a record with no value is not answered; file / http sources group by document. groupBy implies record mode; with granularity: 'chunk' it is refused (VALIDATION_ERROR, 400, never ignored), as are an empty groupBy and an unknown granularity; the caller's groupBy is JSON-quoted and cut at 64 characters in log lines and refusals.
    • The permission re-read stays one query as the caller and also reads the display field (documentTitleField, the resolveDisplayField reading shared with service-knowledge: a knowledge hit's title is read from a hard-coded title field #36994); a caller's hit carries the live title. The system identity is not re-checked, so its hits keep the indexed title (equal whenever the hash matched).
    • Freshness: only for the hits about to be answered, one system-context read per source, { $and: [where, { id: { $in } }] }, projected to the fields assembly reads (the whole row when the source names a field the object does not declare), its system context in the trailing options argument. Deleted / out-of-where / recomputed-docHash-differs ⇒ dropped, next group moves up (at most SEARCH_FRESHNESS_ROUNDS = 3 rounds; unchecked after that ⇒ not answered). Repair: syncRecord through the per-document serialization (service-knowledge: record-change sync ignores the source where, and a restored record never re-enters the index #36991's path), not awaited, system context, single-flight, once per document until a later search finds its hash matching; never throws into the search. A source with refresh.onRecordChange: false (external indexer) is never repaired: repairStale asks objectSourcesFor first, and the stale hit is only dropped. A hit without a stored hash is checked for membership only. A failed freshness read drops that source's checked hits (fail-closed), warn.
  • Contract suite (@objectstack/service-knowledge/testing): an adapter with listDocuments must return each hit's stored docHash (plus a record-level freshness case through a real service); an adapter that takes chunks must return headingPath. The chunk stub in contract-stubs.test.ts now carries headingPath.
  • Docs: content/docs/protocol/knowledge.mdx gains "Records, not passages"; content/docs/ai/knowledge-rag.mdx shows granularity / groupBy; content/docs/references/ai/knowledge-document.mdx and packages/spec/authorable-surface/ai.json regenerated.

Why

Epic #37000 phase 2 row 10, ADR-0161 K1 (record-level return; the service groups, K8 item 13 stays out). Out of scope as the card says: search_knowledge tool arguments (row 12), grouping inside the adapter, the scope filter (row 11).

Acceptance notes

  • Reading choice, stated: card item 3's "File and http sources group by documentId" is applied under groupBy too (a file document is its own group beside the field's values), and the rule "a source without it answers no hits" applies to object sources.
  • Reading choice, stated: freshness and the live title run only under record granularity, so the default chunk mode is today's behaviour (card item 1).
  • Coordination: knowledge-pgvector: an open vector store on PostgreSQL — tables, exact search, listing, chunks #37100 (knowledge-pgvector) runs the contract suite; with listDocuments it now owes docHash on hits, and with chunks headingPath. Told to that thread.
  • Declaration corrected from the claim's Metadata-protocol: none to added (and @objectstack/spec to minor): Check Changeset reads the two new KnowledgeHit keys in authorable-surface/ai.json as authorable keys added. Seat told to align the claim.
  • freshnessRepairs holds one entry per stale document until its hash is seen matching; a record deleted for good keeps its entry for the process lifetime (bounded by distinct stale records seen). Row 15 moves repair to the queue.

Tests

Local runs at f5c87f7
  • pnpm --filter @objectstack/service-knowledge test → Test Files 11 passed, Tests 296 passed (275 before; +20 record-level cases in knowledge-service.test.ts, +1 contract headingPath case on the chunk stub).
  • pnpm --filter @objectstack/knowledge-memory exec vitest run --maxWorkers=2 → Tests 37 passed (contract: hit docHash, record-level freshness through a real service with background repair, headingPath).
  • pnpm --filter @objectstack/knowledge-ragflow exec vitest run --maxWorkers=2 → Tests 10 passed.
  • pnpm --filter @objectstack/service-knowledge typecheck, pnpm --filter @objectstack/knowledge-memory typecheck → exit 0, test-typecheck OK.
  • pnpm --filter @objectstack/spec check:generated → 1 stale (check:docs), fixed with --fix, re-check green; other 13 green.
  • check:system-context-census, check:where-matcher, check:doc-anchors → green (the first two were red in CI at 4267fda and are fixed: the contract double no longer reads isSystem, and the record-level suite's table engine refuses operators it does not implement).
  • eslint on the changed .ts files → exit 0. check:doc-authoring, check:durability-log-level, check:startup-registry-verdict, check:adr-anchors, check:adr-0087-registration, check:pm-skill-id-lint, check-nul-bytes → exit 0.
  • Ablation (restored, git diff HEAD empty): hash compare replaced by false → 2 freshness cases red; grouping map read disabled → 3 grouping cases red. Review round (at f5c87f7): repair skip removed → the external-indexer case red; SEARCH_FRESHNESS_ROUNDS 3 → 50 → the round-cap case red; undeclared-field filter restored → the undeclared-field case red; title dropped from the projection → 2 cases red; the cap-aware debug guard removed → the round-cap case red.
  • NOT MEASURED locally: the full pnpm test / repo check:* farm (117 derived commands) — declared to CI.

Verification

Two-minute check: pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/knowledge-service.test.ts -t "record-level" → 20 passed.

Read first: knowledge-service.ts answerByRecord + checkFreshness (drop/repair decisions), search() (refill widening under record mode), applyPermissionFilter (live title projection).

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic.
  • 2. Every name I added uses the casing for its kind.
  • 3. No formatter ran; eslint on changed files passes (repo pnpm lint in CI).
  • 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: its generated artifacts are regenerated and committed.
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb


Generated by Claude Code

…and the hit's docHash/headingPath

Claude-Session: https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb
Co-authored-by: Claude <noreply@anthropic.com>
…; regenerated reference

Claude-Session: https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation protocol:ai 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/knowledge-memory, @objectstack/service-knowledge, @objectstack/spec, touching 24 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/spec/authorable-surface/ai.json), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

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

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

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

Coarse fallback — 176 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 13ffe1c04565150c174e88806c2fc32d70a04cc8 → packageMentionDocs.

Which tree this was computed on

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

node scripts/docs-audit/affected-docs.mjs --json 13ffe1c04565150c174e88806c2fc32d70a04cc8

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

…rotocol added, spec minor

Claude-Session: https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb
Co-authored-by: Claude <noreply@anthropic.com>
…whole, with no isSystem read

The system-context census counts every non-test isSystem read, and the
published contract suite's engine double is not a platform behaviour. The
double now answers an id-pinned read with a context (the permission re-read
and the freshness check) as whole rows behind the case's wall, without
telling the system identity apart; a walled record-level case fails closed.

Claude-Session: https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb
Co-authored-by: Claude <noreply@anthropic.com>
…s what it does not implement

The WHERE-matcher conformance gate reads a double that treats an unknown
`$` key as a field name as silently wrong. `tableEngine` now throws on any
combinator but `$and` and on any operator but `$in`.

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

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbW5anP6GDaVi5LKi2U

席位核对

REWORK — two blocking items in knowledge-service.ts and two test gaps; the spec face itself is as ADR-0161 decided it. Fix list at the end.

Head-sha: 7d6c76da8af461bc776fe921cc345fd0f9e50be2

Reviewed at the PR's current head. The dispatch named 9652c238ae84a1e149e85c371dff3f646129b199; the head moved twice during the review (4267fda877cff7abecba4524cc948d2e0c047e4e: changeset kind and level, knowledge-rag.mdx; then 7d6c76da: two test doubles). knowledge-service.ts, packages/spec/** and knowledge-memory are byte-identical across the three heads.

形态

  • Open, draft, base main, first line Fixes #37103; no closing keyword beside any other card. Fixes is right: all six What items are built.
  • Not governed surface: check-governed-merges.mjs --pr 37335 reads 0 of 12 paths on the register, 901 changed lines, under the 3000 threshold. Ordinary queue landing once accepted.
  • Declarations: PR body and changeset both read Clause-②: yes (widening) · Metadata-protocol: added; @objectstack/spec minor, service-knowledge and knowledge-memory patch. The claim comment 7170014803 was revised from none to added at 18:08Z. added is forced by the gate, not a judgement call: packages/spec/authorable-surface/ai.json gains two ai/KnowledgeHit:* rows and check-changeset-no-major.mjs refuses none beside a moved baseline.
  • Skills-docs: none holds. Read skills/**: the knowledge text (skills/objectstack-ai/SKILL.md, its eval skills-tools-knowledge.json) teaches source authoring and the search_knowledge tool, whose arguments and hit projection this PR leaves alone (row 12). No page teaches KnowledgeSearchOptions or the KnowledgeHit shape.
  • One changeset names all three published packages touched. No content/docs/releases/ path. No file outside the claim's surface (knowledge-memory is the adapter K8 rule 1 names; the claim line was not widened to say so, recorded as a deviation).

前提实测

门禁 check-runs (at 7d6c76da, read 18:24Z)

  • 13 success, 9 skipped, 25 in progress, 0 failed. Lint & Repo Gates and TypeScript Type Check: not measured (still running). At 4267fda8 both had concluded failure, with Lint · repo & tooling gates, Lint · CI, release & engine gates and Test UI; the two later commits answer the lint reds, and whether they clear is not measured.
  • Local, at 7d6c76da: service-knowledge vitest 292/292 (11 files), knowledge-memory 37/37.

断言与消融 (17 single-line ablations on knowledge-service.ts and knowledge-memory/src/index.ts, run at 4267fda8, tree restored)

  • 16 turn the suite red: hash compare off (2 + 1 contract), where dropped from the freshness read, single-flight off, the groupBy + chunk refusal off, ungroupable source searched, live title off, widening off, read failure failing open, freshness run in chunk mode (5 red, among them the pre-existing permission and refill cases: the default path is pinned by the old suite as well as the new case), grouping off, repair entry never cleared, projection dropped, refill off, no-value record answered ungrouped, knowledge-memory without docHash (2), without headingPath (1).
  • 1 stays green: SEARCH_FRESHNESS_ROUNDS 3 → 50. The round cap has no case. Fix 3.
  • Chunk default: the service path is unchanged by read (same asks, same fields: ['id'] re-read, same refill predicate, same hit objects) and by the ablation above. The answer is not byte-identical for a knowledge-memory deployment in one respect the PR body does not say: every hit now also carries docHash and, when its passage has one, headingPath, in chunk mode too. That is K8 items 3 and 14 as decided; the body's "byte-for-byte" should say it.
  • Refusals: groupBy + granularity: 'chunk', an empty groupBy and an unknown granularity throw a bare Error; the case asserts the message by regex. No code, no status (ADR-0112; the same package's tool layer refuses with VALIDATION_ERROR / 400). Fix 2.
  • Bounds, by read and probe: per source at most topK × 5 then one refill at topK × 20; freshness at most 3 reads per source per search, each of at most topK ids; at most 3 × topK repairs started per search, each single-flight per document through serializeRecordSync, in system context, never awaited, never as the caller. freshnessRepairs keeps one string per document found stale and never seen matching again (the body states it).

逐句核的散文面

  • Changeset: each of the five bullets read against the code and true, with the two exceptions below. protocol/knowledge.mdx "Records, not passages" (three paragraphs) and the KnowledgeHit and KnowledgeSearchOptions sentences: true, same exceptions. ai/knowledge-rag.mdx: the example and the closing paragraph are true. references/ai/knowledge-document.mdx: generated, two rows, matches the schema.
  • Exception a: "the hit's title is the record's title as it reads now" holds for a caller the re-check reads for. The system identity gets no re-read, so its title is the indexed one (equal whenever the hash matched; not for an adapter that stores no hash).
  • Exception b: "Its document is repaired in the background" is unconditional in the changeset, the docs and the granularity jsdoc. See fix 1: the sentence and the code must agree with the source's refresh key.

接受的偏差

  • Repair "once per document until a later search finds its hash matching" is the card's own item 5. Its residue (a second missed change before any search sees the first repair matching is not repaired by this path; a repair that fails is not retried) goes to row 15 with the queue.
  • groupBy on a file / http source groups by document: the dev's stated reading of card item 3, accepted.
  • A posture that cannot be read makes the check membership-only for that search (logged at warn), while a failed freshness read answers nothing. Accepted for now; row 15 or the reconcile card may close it.
  • "Container run per AGENTS.md" read as the local package runs, repeated here at the current head.

范围外去向

落地条款

  • Clause-② declared and the path limb hit: no queue before a VERDICT: PASS contract record on the landing head. The record below is FAIL.

Fix list

  1. must-fix — repairStale calls syncRecord directly and so skips the one predicate (objectSourcesFor) that keeps the service's writes out of a source with refresh.onRecordChange: false. Probe: such a source, one hit deleted and one changed, record-level search ⇒ one adapter.delete and one adapter.upsert. The hit is still dropped; the repair is skipped for that source, with a case, and the three texts say so.
  2. must-fix (checklist, 拒收断言) — the three argument refusals in search() carry code: 'VALIDATION_ERROR' and status: 400, and the case asserts both.
  3. should-fix — a case for the round cap: more stale leads than three rounds can clear, asserting three reads, the unchecked hits unanswered, and the debug line (the "no more within the refill cap" line also fires there and names the wrong reason).
  4. should-fix — freshnessFields drops a field the schema does not declare from the projection while the walk and the repair hash the whole row, so a source that names such a field has every record-level hit read as stale, repaired to the same hash, and never answered. Probe: metadataFields: ['policy', 'created_at'] over a schema without created_at ⇒ 0 hits, 1 repair. Read the whole row when any wanted field is undeclared, and give the suite one engine double that honours fields on the system read; today both doubles answer it whole, so the sentence "the recomputed hash is the one assembly would compute" is unpinned.
  5. nit — the freshness read passes its context inside the query with as never; rereadRow in the same file uses the trailing options argument the IDataEngine contract now declares.
  6. nit — PR body: "byte-for-byte" for the default (see above), and the test block is pinned to 9652c238.

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 7d6c76da8af461bc776fe921cc345fd0f9e50be2
Local-runs: probe — the package suites, 17 ablations and 5 probe cases were run in a scratch worktree because the dispatch asked whether the claimed tests fail without the change; nothing was pushed.
Scope: packages/spec/src/contracts/knowledge-service.ts, packages/spec/src/ai/knowledge-document.zod.ts + packages/spec/authorable-surface/ai.json, packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/testing.ts, packages/plugins/knowledge-memory/src/index.ts
Security-touching: yes
Rule-change-verified: yes

① Derived judgments

  • KnowledgeHit.docHash? is ADR-0161 K8 item 3 ("The stored hash of the hit's document", first reader service-knowledge: search returns records, not chunks — granularity and groupBy #37103) and KnowledgeHit.headingPath? is item 14 ("The heading path of the chunk the hit came from, in the chunk's shape", first reader service-knowledge: search returns records, not chunks — granularity and groupBy #37103). Both are in the closed table, so K8 rule 5 asks for no dated note. Shapes match rule 3: an optional string; an optional list of strings, outermost first, the shape of KnowledgeChunk.headingPath.
  • K8 rule 1: each member lands with its reader and a suite case. docHash is read by checkFreshness; the suite gains two cases under implements.listDocuments and one under implements.chunks. headingPath is carried through and read by the caller; the service does nothing else with it, which is what item 14 and card item 6 decide.
  • K8 rule 2 holds at run time: both keys are optional in the schema, and an adapter that returns no hash gets a membership-only check (pinned). The suite ties the hash on hits to listDocuments and adds no separate implements key; an adapter that lists stored hashes can return them, so the tie is sound.
  • Item 13 respected: no grouping member on the adapter contract; grouping is in the service, with K1's reason for not pushing it down.
  • granularity and groupBy are options of IKnowledgeService, which K8 names as non-members landing with their reader under ADR-0049. The return type is unchanged (K9 rule 3). No tool argument is added (K9 rule 2 leaves that to row 12).
  • Epic rulings: the answer's content still comes from the index copy the caller was admitted to, plus a title read as the caller in the one re-read; the system read of the freshness check only removes hits. The count the permission filter removed stays in a debug line.

② Semver level

  • Clause-②: yes (widening): two optional options on a published interface and two optional keys on a published schema. Nothing narrows; an existing caller and an existing adapter compile and behave as before.
  • Metadata-protocol: added with @objectstack/spec at minor: the authorable-surface baseline moved by two rows, which the level axis reads as added keys. The other two packages at patch satisfy "at least one package minor".
  • Additive for adapters outside this repository: nothing under cloud/ runs the contract suite today; knowledge-pgvector (knowledge-pgvector: an open vector store on PostgreSQL — tables, exact search, listing, chunks #37100) meets the new cases when it first runs it.

③ Boundary flags

④ Design judgment

packages/spec/src/contracts/knowledge-service.ts

  • must-fix — the granularity text promises that a stale record's "document is repaired in the background", and the implementation does that for every object source, including one whose published refresh.onRecordChange: false hands its index to an external indexer. The service's event sync, reap guard and purge all stand down for that key; this path does not. Either the contract sentence gains the exception and the code honours it, or the key no longer means what knowledge-source.zod.ts says. Fix 1 above.
  • should-fix — "passing it with granularity: 'chunk' is refused" names no code. The refusal is a bare Error; give it the coded shape the package's tool layer already uses, so row 12 forwards one refusal and not two. Fix 2 above.
  • The rest holds against the code and the card's acceptance scenes: topK counts groups; one group across sources; a source without the field is not asked; a record with no value is not answered; file / http by document.

packages/spec/src/ai/knowledge-document.zod.ts

  • Holds. Both descriptions are true of knowledge-memory and of what the service compares. "Absent when the adapter stores no hash" is the membership-only arm.

packages/spec/authorable-surface/ai.json

  • Generated; two rows, in order.

packages/services/service-knowledge/src/knowledge-service.ts

  • must-fix — as above (the repair and refresh.onRecordChange).
  • should-fix — the projection of the freshness read can differ from what assembly hashed (fix 4), and no double honours fields on that read.
  • should-fix — the three-round cap is unpinned (fix 3).
  • nit — query.context with as never (fix 5).

packages/services/service-knowledge/src/testing.ts, packages/plugins/knowledge-memory/src/index.ts

  • Hold. The adapter returns both keys as stored and copies the path; the suite cases fail without them.

Implemented-by: session_01JQwxbZmvWffL8FZzRX8ZSb
Reviewed-by: session_01JQwxbW5anP6GDaVi5LKi2U

VERDICT: FAIL

- The background repair asks objectSourcesFor first, so a source with
  refresh.onRecordChange: false (an external indexer owns its index) is
  never written; its stale hit is only dropped.
- The three search() argument refusals carry code VALIDATION_ERROR and
  status 400, the package's tool-layer shape.
- The freshness read takes the whole row when the source names a field the
  object does not declare, so the recomputed hash is the one assembly stored;
  its system context moves to the trailing options argument.
- The round cap answers its own debug line, not the refill-cap one; a
  caller-supplied groupBy is JSON-quoted and cut in log lines and refusals.
- Cases: the external-indexer source, the coded refusals, the round cap, an
  undeclared field, and a projected read through an engine double that
  honours fields on the system read. Texts say the exceptions.

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

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbW5anP6GDaVi5LKi2U

席位核对

ACCEPT — the six items of the round-1 record (PR comment 7170913599) are closed at this head, each pinned by a case that fails without it. Landing waits for the checks still running.

Head-sha: f5c87f799f149ee271233ee9ed72e7ce05224850

Delta review: one commit on 7d6c76da8af461bc776fe921cc345fd0f9e50be2, 8 files, +192 / -70. Read whole against that head; the rest of the PR stands as read in round 1.

形态

  • Open, draft, base main, first line Fixes #37103, the only closing keyword in the body. Body and changeset read Clause-②: yes (widening) · Metadata-protocol: added · Skills-docs: none; @objectstack/spec minor, the other two patch. Unchanged since round 1.
  • Not governed surface: check-governed-merges.mjs --pr 37335 reads 0 of 13 paths on the register, 1026 changed lines, under the 3000 threshold.
  • The delta opens no new scope. refusal gains export in knowledge-tools.ts and is not re-exported from the package's index.ts, so the published surface of @objectstack/service-knowledge does not move. testing.ts: the permission branch of the engine double is back to main's shape (ids only, context in the query); what remains against main is the $in match, the bound waived for a read that pins ids, and the three new suite cases.

门禁 check-runs (at f5c87f79, read after the push)

  • 27 success, 12 skipped, 32 in progress, 0 failed. Lint & Repo Gates: success. TypeScript Type Check: not measured (its jobs are still running). All-green: not measured.
  • Local at f5c87f79: service-knowledge vitest 296/296 (11 files), knowledge-memory 37/37.

逐项核对与消融 (7 single-line ablations at this head, tree restored)

  1. Repair and the source's refresh opt-out — repairStale asks objectSourcesFor first. The new case (an opted-out source with one changed and one deleted record beside an owned source) sees no delete and one upsert, the owned one. Guard removed: that case red.
  2. Coded refusals — the three argument refusals throw through refusal('VALIDATION_ERROR', 400, …); the case asserts code, status and the message for each. One refusal un-coded: red.
  3. Round cap — answerByRecord answers { hits, capped }; the case asserts three reads of one id each, no hit, the round-cap debug line, and the refill-cap line absent. Cap 3 → 50: red. capped ignored: red.
  4. Projection — freshnessFields answers "whole row" when a wanted field is not declared; the suite's table engine now honours fields on system reads. Two cases: an undeclared metadata field (whole-row read, hit answered, no repair) and a declared set (projected read, hit answered, no repair). Old filter restored: red. Title field dropped from the projection: 2 red.
  5. Context — the freshness read passes its system context in the trailing options, no cast; the case asserts both arguments exactly. Context put back in the query: 3 red.
  6. Body — test block pinned to f5c87f79; the chunk default is described as the same hits, with docHash and headingPath added on knowledge-memory.
  • Also done: a caller-supplied groupBy is shown JSON-quoted and cut at 64 characters in the refusal and both log lines.

逐句核的散文面 (delta sentences)

  • Changeset: the granularity parenthesis on the default, the coded-refusal sentence, "at most three rounds; a hit still unchecked after them is not answered", the opt-out sentence, the whole-row sentence, and the two title sentences — each true of the code.
  • protocol/knowledge.mdx: the refusal parenthesis, the round sentence, the opt-out exception and the title sentence — true. ai/knowledge-rag.mdx: the opt-out clause — true.
  • Both round-1 exceptions (the system identity's title; the unconditional repair) are now stated as the code behaves.

接受的偏差 (unchanged from round 1)

  • Repair once per document until a later search sees its hash matching: the card's item 5; the residue goes to row 15.
  • A posture that cannot be read makes the check membership-only for that search, logged at warn.
  • groupBy on a file / http source groups by document.
  • The claim's file-surface line does not name packages/plugins/knowledge-memory; K8 rule 1 names that adapter as the suite's first runner.

范围外去向 (unchanged)

落地条款

  • Clause-② declared and the path limb hit: the contract record below is PASS at this head. Queue only when every check at the landing head is green or an expected skip; a head that moves past prose owes a fresh record.

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: f5c87f799f149ee271233ee9ed72e7ce05224850
Local-runs: probe — the two package suites and 7 ablations were run in a scratch worktree to confirm each round-1 fix is pinned; nothing was pushed.
Scope: packages/spec/src/contracts/knowledge-service.ts, packages/spec/src/ai/knowledge-document.zod.ts + packages/spec/authorable-surface/ai.json, packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/knowledge-tools.ts, packages/services/service-knowledge/src/testing.ts, packages/plugins/knowledge-memory/src/index.ts
Security-touching: yes
Rule-change-verified: yes

① Derived judgments

  • Round 1 stands: KnowledgeHit.docHash? and headingPath? are ADR-0161 K8 items 3 and 14 in their decided shapes, each landing with its reader and a suite case; item 13 stays out; granularity and groupBy are service options that K8 names as non-members. The delta adds no member, no key and no option.
  • The delta changes two contract sentences in knowledge-service.ts: the repair now excepts a source with refresh.onRecordChange: false, and the refusal names code: 'VALIDATION_ERROR', status: 400. Both are true of the code and pinned.

② Semver level

  • Unchanged: Clause-②: yes (widening), Metadata-protocol: added, spec minor, the two packages patch. A thrown refusal that gains code and status is still an Error with the same message stem; the options are new in this PR, so no released behaviour narrows.
  • refusal is exported from a module, not from the package entry: no published export is added.

③ Boundary flags

④ Design judgment

packages/spec/src/contracts/knowledge-service.ts

  • Round-1 must-fix closed: the granularity text and the code agree with the published meaning of refresh.onRecordChange: false; the service writes nothing to such an index on this path either.
  • Round-1 should-fix closed: the refusal is coded and the text says so.

packages/spec/src/ai/knowledge-document.zod.ts, packages/spec/authorable-surface/ai.json

  • Untouched by the delta; hold as in round 1.

packages/services/service-knowledge/src/knowledge-service.ts

  • The three round-1 findings are closed and pinned (opt-out guard, projection, round cap), and the nit on the context argument with them.
  • nit — the refill-cap debug line is silenced when the round cap ended the answer, which is right; a search that hits both caps reports only the round cap. No effect on the answer.

packages/services/service-knowledge/src/knowledge-tools.ts

  • One word, export, on refusal: one refusal shape for the tool layer and the service. Holds.

packages/services/service-knowledge/src/testing.ts, packages/plugins/knowledge-memory/src/index.ts

  • Hold. The double's permission branch matches main again, so the suite's existing cases read as before.

Findings open at this head: none at must-fix or should-fix; one nit, accepted.

Implemented-by: session_01JQwxbZmvWffL8FZzRX8ZSb
Reviewed-by: session_01JQwxbW5anP6GDaVi5LKi2U

VERDICT: PASS

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 25, 2026 19:03
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit 3801775 Nov 25, 2026
75 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-oc6nsu branch November 25, 2026 19:36
os-warren pushed a commit that referenced this pull request Nov 25, 2026
The record-level search landed on main (#37335). search() keeps both source
filters: the record scope first, then groupBy, each after the scope and
groupBy options are validated.

KnowledgeHit.metadata now says an adapter returns the document's metadata on
each hit, which the service's scope check reads (review ruling (b)).

Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm
Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…QL, and the index fingerprint (objectstack-ai#37100) (objectstack-ai#37337)

Fixes objectstack-ai#37100

Clause-②: yes
Metadata-protocol: none

## 维护者速读

- 自建部署的知识库可以直接用自己的 PostgreSQL(装 pgvector
扩展)存向量做检索,不再需要另外的向量服务;换了嵌入模型或切分方式后,旧索引会被明确拒绝并提示重建,而不是悄悄返回混杂的结果。
- 属于「知识检索」专题,补上开源向量库这一块,并为后续的新代际重建和其他存储打好统一的指纹规则。
- 数据库没装扩展或没权限时,系统照常启动,知识源返回「暂不可用」;要执行的 SQL
和数据库报错只给运维看(健康检查、启动日志),不会出现在用户的检索回答里。新包默认不启用,撤回只需不注册该插件。
- 本 PR 改了 CI 工作流文件,需要你批准。新加的两步 CI
只在完整跑批和合并队列里运行(队列里不卡合并),席位无权在分支上手动触发;本地已用 CI 同一镜像(pgvector 0.8.7)跑通。如需在
CI 里看到绿灯,可在分支上手动触发一次 ci.yml。

## What changes

**New package `@objectstack/knowledge-pgvector`** (Apache-2.0) —
`KnowledgePgvectorPlugin` registers `PgvectorKnowledgeAdapter` (id
`pgvector`).

- Storage in its own schema `os_knowledge` (option `schema`):
`knowledge_generation` (source_id, generation, fingerprint, recipe_hash,
dim, model, state, created_at) and one passage table per width,
`knowledge_vec_dWIDTH` (source_id, generation, chunk_id, document_id,
source_record_id, organization_id, content, title, heading_path,
doc_hash, chunk_hash, metadata jsonb, embedding vector(WIDTH)). Object
tables live in the connection's `current_schema()`, and the driver's
introspection / `os migrate plan` read only that schema, so these tables
can neither collide with an object table nor be reported as drift.
- Database: the `url` option, else `OS_DATABASE_URL` / legacy
`DATABASE_URL` when it is `postgres://`; its own `pg.Pool` (`poolMax`,
default 4; `connectTimeoutMs`, default 5000, so an unreachable host does
not hold boot). Every embed runs before a connection is checked out for
the write. The kernel's embedder is read at each call, never cached. Two
deployments sharing one database set their own `schema` (README). With
per-organization databases the store is still the one database the
plugin connects to; isolation is the `organization_id` column, filtered
in SQL.
- Not ready (no `vector` extension and no right to create it, or no
right to create the schema): nothing is created past the failing step,
the plugin still registers, boot continues, `healthCheck` answers `ok:
false` and the boot warning carries the SQL, every call answers `503
SERVICE_UNAVAILABLE`; the next call retries (no restart). An unreachable
database is diagnosed as unreachable, with no SQL.
- What a caller reads: every refusal's `message` is one sentence (no
driver text, SQL or schema name). Operator text travels in the error's
`remedy`, shown by `healthCheck`, the boot warning, a reindex result and
the service's `warn` log — never in `refused[].message` or a thrown
search refusal. The contract TSDoc of `beginBuild` states this
convention.
- Search: the embedder is resolved before the fingerprint is compared
(no embedder ⇒ 503, never a 409 on a healthy index); exact cosine scan
via the extension's own schema-qualified cosine-distance operator and
`vector` type (no HNSW, so 3072 dims work); organization filter and
metadata-equality `filter` in the same `WHERE`, before `ORDER BY
distance LIMIT topK`; a passage with cosine similarity not above 0 is
not a hit. Hits carry the stored `docHash` (K8 item 3, read by objectstack-ai#37103's
record-level freshness check) and the passage's `headingPath` (item 14).
`queryPrefix` option is prepended to queries only.
- Writes: takes the service's chunks (`capabilities.chunks`);
`chunk_hash` per passage; an unchanged passage is not re-embedded (row
metadata rewritten, the UPDATE checked for its row: one removed by a
concurrent write makes the batch plan again, so the passage is embedded,
not lost); stale chunks of a document deleted in the same transaction.
- `listDocuments` on the write-target generation, byte order (`COLLATE
"C"`) for both the order and the cursor.
- Fingerprint: a write or search under another fingerprint, or with an
embedder of another width, is refused `409 KNOWLEDGE_REBUILD_REQUIRED`;
`beginBuild` under the stored fingerprint is a no-op, under another it
is refused and its `remedy` (the convention is stated once on
`IKnowledgeAdapter`) (carried into the reindex result) is the exact
statements that clear the source: one `DELETE` per existing passage
table, then the generation row (second-generation builds are objectstack-ai#37101). A
first generation never adopts leftovers: opening it deletes the source's
passage rows left without a generation row, in the same transaction,
only by the call whose insert opened it; `completeBuild` records the
recipe hash; `indexStatus` reads both back.
- README: options, database/schema, setup SQL, HNSW as an operator step
with the 2,000-dimension limit, rebuilds, and that stored text is as
sensitive as the record and is in backups.

**K8 item 8 (ADR-0161 K7), whole, as the Execution note asks**

- `@objectstack/service-knowledge`: `computeIndexFingerprint` (model,
variant, dimensions from the adapter's `embedding` descriptor; resolved
split + `SPLIT_ALGORITHM_VERSION`; content recipe +
`ASSEMBLY_RULE_VERSION`) and `computeRecipeHash` (`where`,
`metadataFields`, title field + `TITLE_RULE_VERSION`, withheld fields),
SHA-256 over sorted-key JSON, pinned by `index-fingerprint.test.ts`.
Every adapter call carries them (`AdapterContext.index`,
`AdapterSearchOptions.index`). `indexExpectation` is exported. A
complete reindex calls `beginBuild` before listing or writing (refusal ⇒
`ok: false`, nothing written, the adapter's `remedy` in the message) and
`completeBuild` after the purge (a throw ⇒ `ok: false`); a capped or
dry-run walk calls neither. The repair of a stale record (objectstack-ai#37103's
`repairStale`) goes through the event-sync path, whose upsert/delete
carry `index`. The chunk-target setting is read once per search.
- `@objectstack/spec/contracts`:
`AdapterEmbeddingDescriptor.model/dimensions/variant`,
`AdapterIndexExpectation`, `AdapterIndexStatus`,
`IKnowledgeAdapter.indexStatus?/beginBuild?/completeBuild?`,
`IEmbedder.model?`. All optional.
- Coded refusal through search (card comment, K7 rule 5):
`KnowledgeService.search` keeps its signature (K9 rule 3); a source
refused with a coded error (SCREAMING code + 4xx/5xx status) is dropped
from the answer and logged by name; when no source answers, the refusal
is thrown with its code/status and `refused` naming each source. A
source that answers the first round and refuses the refill is refused
for the whole search (its first-round hits dropped), so no source is
both answered and named as refused.
`KnowledgeService.searchWithRefusals` returns `{ hits, refused }`;
`search_knowledge` adds `refused` (sources the caller can see only) when
non-empty.
- `knowledge-memory` is the reference: active + under-construction
generations, switch at `completeBuild`, all flags true in its contract
run.
- `embedder-openai`: `model` is public and reported.
- Contract suite: `implements` gains `indexStatus`, `builds`,
`refusesOtherFingerprint`, `generations` with 9 cases (carry,
fingerprint vs recipe-hash variation, build pair, status, search
refusal, write refusal, through-service named/whole refusal, generation
switch, rebuild after recipe change).
- `KNOWLEDGE_REBUILD_REQUIRED` registered in the error-code ledger under
service-knowledge (the suite asserts it), knowledge-memory and
knowledge-pgvector; generated references regenerated.

**CI (Tier H — `.github/workflows/ci.yml`)**: `Temporal Conformance`
never runs on `pull_request`; it runs on the full battery and, for an
entry whose diff hits the `temporal_live` paths (this one does), in the
merge queue, where it is advisory, not a required check. No existing
step of `Temporal Conformance (live PG + MySQL)` runs this package, so
two steps are added after the runtime leg (build
`@objectstack/knowledge-pgvector...`, then `vitest run live-postgres`
with `OS_TEST_POSTGRES_URL` and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`, so a
missing server is red, never a skip); `service-knowledge/src/testing.ts`
joins the `temporal_live` merge-queue paths; the build-step count
comment says five. The job's image is already pgvector's (objectstack-ai#37095).

## Why

Card objectstack-ai#37100 (ADR-0161 Execution row 8a): the open, self-hosted vector
store, and the fingerprint that keeps two models' vectors from ever
being ranked against each other.

## Open question

`searchWithRefusals` is a class method of `KnowledgeService`, not a
member of `IKnowledgeService` (K9 rule 3 keeps `search`'s signature and
return type). `search_knowledge` reads it structurally. Options: (A)
keep it on the class (this PR); (B) add an optional
`IKnowledgeService.searchWithRefusals?` member in a follow-up with its
own K9 dated note. Recommendation A until a second consumer needs it.

## Deviations from the card

- `title` and `heading_path` columns beyond the card's list: hits return
the document title and, since objectstack-ai#37103 landed, the passage's
`headingPath`.
- The generation table also holds `recipe_hash` (K8 item 8 c).
- Store keying by package is objectstack-ai#37304's (ruling 7168239918, Q1 = B);
nothing built for it here.

## Tests

At head `065c98ff` (main merged at `83fef223`, after objectstack-ai#37335 landed as
`38017753`):

- `@objectstack/knowledge-pgvector`, live, against the CI job's own
image (`mirror.gcr.io/pgvector/pgvector:0.8.7-pg16@sha256:484e8380…`,
run locally in Docker), the CI step's exact command (`pnpm --filter
@objectstack/knowledge-pgvector exec vitest run live-postgres`,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`): `Test Files 3 passed (3)`, `Tests 47
passed (47)` (contract suite 34, acceptance 11, real-driver reindex 2).
The whole package against PostgreSQL 16 + pgvector 0.6: `Test Files 4
passed (4)`, `Tests 57 passed (57)` (the above plus 10 unit cases; one
of them now also pins `listDocuments` answering 503 with no embedder).
- `@objectstack/service-knowledge`: `Test Files 12 passed (12)`, `Tests
315 passed (315)` (one case pins that a refusal's `remedy` reaches the
`warn` log and never `refused[].message` or the thrown message).
`@objectstack/knowledge-memory`: `46 passed`.
`@objectstack/embedder-openai`: `31 passed`. `typecheck` (source and
tests) green for all four; eslint clean.

<details><summary>Ablations of the review fixes (one-shot, each
restored; each fails exactly one case)</summary>

- fingerprint compared before the embedder is resolved: the not-ready
"no embedder ⇒ 503" case fails.
- leftover passage rows not deleted when a first generation opens: the
acceptance "never adopts passages left behind" case fails (the passage
is not re-embedded).
- the unchanged-passage UPDATE not checked for its row: the acceptance
concurrent-write case fails (the passage is lost).
- a refused `beginBuild` ignored by the service: the service stub "stops
before any listing or write" case fails.
- a throwing `completeBuild` swallowed: the service stub `ok: false`
case fails.
- the kernel embedder cached by the plugin: the plugin "re-registered
embedder is reported at once" case fails.
- (round 2) `listDocuments` compares before resolving the embedder: the
not-ready no-embedder case fails; the service hands the `remedy` to the
caller: the remedy-boundary case fails.

Earlier ablations (organization filter, chunk-hash skip, search
fingerprint check) and the docHash/headingPath ablation (3 suite cases
fail) are unchanged.

</details>

<details><summary>Local derived gates (dispatch-gates --commands, 167
commands)</summary>

At `7027f457`: 166 exit 0 (the round-2 delta at `065c98ff` re-ran
typecheck, eslint, api-surface, spec docs, engine-double, tenant-audit
and system-context censuses: all green). One NOT MEASURED (exit 3, a
prerequisite refusal left to CI): `check-plugin-teardown-shape
--self-test` (needs a full clone). The push hook's commit-trailer check
is green (the two new commits carry the model-free trailer pair).

</details>

## Acceptance notes

| Acceptance | Where |
|:--|:--|
| 3072-dim works | `acceptance.live-postgres.test.ts` — stores and ranks
3072-wide vectors (column type read back as `vector(3072)`) |
| two orgs never see each other's hits (adapter + service) | adapter:
`acceptance…` two organizations case; service: contract suite
organization cases under `isolated` / `group` |
| missing extension → readable error with SQL, boot continues |
`not-ready.test.ts` (adapter refusal text, healthCheck false, plugin
start resolves and warns, recovery after the SQL runs) |
| same content re-indexed → no embed call | `acceptance…` unchanged
passage case (adapter) and second complete reindex case (service) |
| changed fingerprint → rebuild-needed error, old rows not served |
contract suite search/write refusal cases; `acceptance…` changed
embedding model case through the service; `acceptance…` printed
statements run as printed, and a first generation that never adopts rows
left behind (L1 must-fix 2) |
| contract suite passes in CI on real PG |
`contract.live-postgres.test.ts` in the new Temporal Conformance step |
| reindex over a real driver, mixed-case and numeric-looking ids
(comment 7145881825) | `reindex-real-driver.live-postgres.test.ts` — 227
records over 3 walk pages, each indexed once, second reindex writes and
embeds nothing |

## Verification

Two-minute check: `OS_TEST_POSTGRES_URL=postgres://… pnpm --filter
@objectstack/knowledge-pgvector exec vitest run` against any PostgreSQL
with pgvector available — expect `Test Files 4 passed`, `Tests 57
passed`.

CI evidence for the two new live steps: the relay lets a seat dispatch
no `ci.yml` run, so the reading above (the CI image by digest, the
step's exact command) stands in for it. A maintainer who wants it in CI
can run `ci.yml` by `workflow_dispatch` on this branch; the job is
advisory in the merge queue either way.

Read first:
`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (`upsert`,
`search`, `ready`),
`packages/services/service-knowledge/src/knowledge-service.ts` (walk
build calls, `searchWithRefusals`), `.github/workflows/ci.yml` (the two
new steps).

Overlap: objectstack-ai#37335 (objectstack-ai#37103) landed first; main is merged here (`83fef223`),
keeping both intents in `knowledge-service.ts` (record-level answers and
freshness repair from main, the refusal report from here), `testing.ts`
and `knowledge-memory/src/index.ts`.

## 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.
- [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 by [Claude
Code](https://claude.ai/code/session_01JQwxbX5BF433x8ooJNQVRp)_

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

---------

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

documentation Improvements or additions to documentation protocol:ai size/xl 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.

service-knowledge: search returns records, not chunks — granularity and groupBy

2 participants