Skip to content

Commit 3801775

Browse files
feat(service-knowledge): search answers records, not passages — granularity, groupBy and a freshness check (#37335)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8KwgBifx8qqSVYdsjkfntXZ)_ 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 #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 #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 (#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: #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 <details><summary>Local runs at f5c87f7</summary> - `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. </details> ## 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 - [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; eslint on changed files passes (repo `pnpm lint` in CI). - [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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbZmvWffL8FZzRX8ZSb)_ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbZmvWffL8FZzRX8ZSb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 68250f6 commit 3801775

13 files changed

Lines changed: 985 additions & 41 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-knowledge': patch
4+
'@objectstack/knowledge-memory': patch
5+
---
6+
7+
feat(service-knowledge): a search can answer records, not passages — `granularity` and `groupBy`, with a freshness check
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: added
11+
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.
12+
13+
ADR-0161 K1 (record-level return), K8 items 3 and 14.
14+
15+
- **`KnowledgeSearchOptions.granularity`** (`'chunk' | 'record'`, default `'chunk'`, which answers the same hits as before; on `knowledge-memory` each hit now also carries `docHash` and, when its passage has one, `headingPath`). Under `'record'` a search answers one hit per record, the record's best-scoring passage, and `topK` counts records. Every source is then asked for `topK × 5` passages, for every caller, and refilled once at `topK × 20` when fewer than `topK` records survive the permission re-check — the cap; fewer records within it answer fewer hits, logged at `debug`. A `file` / `http` hit is grouped by its document. The return type is still `KnowledgeHit[]`.
16+
- **`KnowledgeSearchOptions.groupBy`** names a metadata field and groups by its value — "which policies", not "which clauses" — keeping the best hit of each group, the value in the hit's `metadata`. It implies record granularity and is refused with `granularity: 'chunk'`; that refusal, an empty `groupBy` and an unknown `granularity` carry `code: 'VALIDATION_ERROR'`, `status: 400`. Hits with the same value form one group whichever source they come from. An `object` source that does not list the field in its `metadataFields` is not searched for that search, and a record with no value for it is not answered: a hit is never answered ungrouped.
17+
- **The freshness check.** Each record-level hit about to be answered is checked against its record as it reads now: one system-context read per source, of only those records, `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly reads. A record that was deleted or left `where` since it was indexed, or whose recomputed `docHash` differs from the hit's, is not answered, and the next record moves up (at most three rounds; a hit still unchecked after them is not answered). Its document is repaired in the background through the event sync's path, single-flight, once per document until a later search finds its hash matching; the repair never throws into the search. A source with `refresh.onRecordChange: false` (an external indexer owns its index) is never repaired: its stale hit is only not answered. When the source names a field the object does not declare, that read takes the whole row instead, as assembly did. A hit whose adapter stores no hash is checked for membership only; a freshness read that fails answers none of that source's checked hits, reported at `warn`.
18+
- **The live title.** Under record granularity the permission re-check — still one query, as the caller — also reads the object's display field, and a caller's hit carries the record's `title` as it reads now. The system identity is not re-checked, so its hits carry the indexed title (the same whenever the hash matched).
19+
- **`KnowledgeHit.docHash?` and `KnowledgeHit.headingPath?`** (`@objectstack/spec/ai`): the stored hash of the hit's document, returned as stored, and the heading path of the passage the hit came from. `knowledge-memory` returns both. The adapter contract suite (`@objectstack/service-knowledge/testing`) now asks an adapter that implements `listDocuments` to return each hit's stored `docHash` (and pins the record-level freshness check through a real service), and an adapter that takes chunks to return each passage's `headingPath`.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,28 @@ const hits = await knowledge.search('proposals about ACME', {
6464
topK: 5,
6565
executionContext, // the caller's context — retrieval drops any hit RLS would hide
6666
});
67-
// hits: KnowledgeHit[] — each { chunkId, documentId, sourceId, sourceRecordId?, score, snippet, title? }
67+
// hits: KnowledgeHit[] — each { chunkId, documentId, sourceId, sourceRecordId?, score, snippet, title?, docHash?, headingPath? }
6868
```
6969

70+
By default a hit is a passage, so one record with several matching passages
71+
can take several of the `topK` places. Pass `granularity: 'record'` to get one
72+
hit per record (its best passage), or `groupBy: '<metadata field>'` to get one
73+
hit per value of that field — "which policies", not "which clauses":
74+
75+
```ts
76+
const policies = await knowledge.search('parental leave', {
77+
groupBy: 'policy', // a field the source lists in metadataFields; implies granularity: 'record'
78+
topK: 5, // counts groups, not passages
79+
executionContext,
80+
});
81+
```
82+
83+
A record-level hit is checked against its record as it reads now: a record
84+
deleted, out of the source's `where`, or changed since it was indexed is not
85+
returned (its index entry is repaired in the background, unless the source
86+
sets `refresh.onRecordChange: false` for an external indexer). The rules are in
87+
[the protocol](/docs/protocol/knowledge#records-not-passages).
88+
7089
<Callout type="info">
7190
**In-product chat ships in ObjectOS.** Exposing this retrieval to a chat UI as
7291
the `search_knowledge` tool — the `ask` / `build` personas, the `/api/v1/ai/*`

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ Canonical shapes shared by every adapter:
186186
document's `metadata`. The chunk's former `metadata` key, which nothing wrote
187187
or read, is retired, and a chunk that carries one is refused with the fix.
188188
- `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`,
189-
`snippet`, `sourceRecordId?`, `metadata`).
189+
`snippet`, `sourceRecordId?`, `metadata`, and `docHash?` and
190+
`headingPath?`: the stored hash of the hit's document and the heading path
191+
of its passage, both as the adapter stores them).
190192

191193
The `sourceRecordId` field is the linchpin of permission-aware
192194
retrieval: when a hit references an ObjectQL record, the
@@ -209,6 +211,42 @@ every source for the system identity. The answer is at most `topK` hits.
209211
How many hits the re-check removed is logged at `debug`, never returned to
210212
the caller.
211213

214+
#### Records, not passages
215+
216+
A search answers passages by default (`granularity: 'chunk'`): several
217+
passages of one record can take several of the `topK` places. With
218+
`granularity: 'record'` it answers records: one hit per record, the record's
219+
best-scoring passage, and `topK` counts records. Every source is then asked
220+
for `topK × 5` passages, for every caller, and refilled once at `topK × 20`
221+
when fewer than `topK` records survive; that is the cap, and fewer records
222+
within it means fewer hits, logged at `debug`. A `file` or `http` hit is
223+
grouped by its document.
224+
225+
`groupBy` names a metadata field and groups by its value instead — "which
226+
policies", not "which clauses" — with the best hit of each group and the
227+
value in the hit's `metadata`; it implies record granularity, and is refused
228+
with `granularity: 'chunk'` (`VALIDATION_ERROR`, 400, as are an empty
229+
`groupBy` and an unknown `granularity`). Hits with the same value are one group whichever
230+
source they come from. An `object` source that does not list the field in
231+
its `metadataFields` is not searched, and a record with no value for it is
232+
not answered: a hit is never answered ungrouped.
233+
234+
Each record-level hit is checked against its record as it reads now, one
235+
system-context read per source of only the records about to be answered
236+
(the source's `where` AND their ids). A record that was deleted or left
237+
`where` since it was indexed, or whose document hash computed now differs
238+
from the hit's `docHash`, is not answered, and the next record moves up (at
239+
most three rounds; a hit still unchecked after them is not answered). Its
240+
document is repaired in the background, through the event sync's path, once
241+
until its hash matches again — except in a source with
242+
`refresh.onRecordChange: false`, whose index an external indexer owns: the
243+
service writes nothing there, and the hit is only not answered. A hit whose
244+
adapter stores no hash is checked for membership only. Record granularity
245+
also reads the display field in the permission re-check (as the caller, in
246+
the same query), so a caller's hit carries the record's `title` as it reads
247+
now; the system identity is not re-checked, so its hits carry the indexed
248+
title (the same whenever the hash matched).
249+
212250
A hit's `title` is the value of the object's display field (ADR-0079
213251
`resolveDisplayField`: `nameField`, else the derived title field), set
214252
when the document is built. It is empty when that field is a
@@ -244,9 +282,11 @@ interface IKnowledgeService {
244282
}
245283
```
246284

247-
`KnowledgeSearchOptions` includes `sourceIds`, `topK`, `filter`, and
285+
`KnowledgeSearchOptions` includes `sourceIds`, `topK`, `filter`,
286+
`granularity`, `groupBy`, and
248287
the all-important `executionContext` (from the permission-aware tool
249-
execution work — see `actions-as-tools.mdx`). `KnowledgeReindexOptions`
288+
execution work — see `actions-as-tools.mdx`). See
289+
[Records, not passages](#records-not-passages) for `granularity` and `groupBy`. `KnowledgeReindexOptions`
250290
accepts `dryRun` and `limit`; `reindexSource` returns a
251291
`KnowledgeReindexResult` (`indexed`, `discovered`, `skipped`, `purged`,
252292
`failed`, `failures`, `ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge)

‎content/docs/references/ai/knowledge-document.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,8 @@ const result = KnowledgeChunkSchema.parse(data);
9494
| **snippet** | `string` | ✅ | |
9595
| **title** | `string` | optional | |
9696
| **metadata** | `Record<string, any>` | optional (default: `{}`) | |
97+
| **docHash** | `string` | optional | Stored docHash of the hit's document, returned as stored by the adapter |
98+
| **headingPath** | `string[]` | optional | Headings the hit's chunk sits under, outermost first |
9799

98100

99101
---

‎packages/plugins/knowledge-memory/src/index.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
4040
* that set — the filter runs before the scoring, so `topK` is filled from them
4141
* alone. An empty set ranks nothing; a document stored without an
4242
* organization is not ranked by a filtered search.
43+
*
44+
* Each hit carries its document's stored `docHash` (ADR-0161 K8, item 3),
45+
* which the service's record-level freshness check compares, and the heading
46+
* path of its passage when the passage has one (item 14).
4347
*/
4448
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
4549
readonly id: string;
@@ -116,6 +120,8 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
116120
snippet: chunk.content,
117121
title: chunk.title,
118122
metadata: chunk.metadata,
123+
...(chunk.docHash === undefined ? {} : { docHash: chunk.docHash }),
124+
...(chunk.headingPath === undefined ? {} : { headingPath: [...chunk.headingPath] }),
119125
}));
120126
}
121127

@@ -136,6 +142,10 @@ interface ChunkRecord {
136142
sourceRecordId?: string;
137143
/** The document's `organizationId`, stored as given (ADR-0161 K8, item 9). */
138144
organizationId?: string;
145+
/** The document's `docHash`, returned on each hit as stored (ADR-0161 K8, item 3). */
146+
docHash?: string;
147+
/** The passage's heading path, returned on its hits (ADR-0161 K8, item 14). */
148+
headingPath?: string[];
139149
content: string;
140150
title?: string;
141151
metadata: Record<string, unknown>;
@@ -148,7 +158,8 @@ interface ChunkRecord {
148158
* `chunks`, one passage holding the whole text. Never split here.
149159
*/
150160
function embedPassages(doc: KnowledgeDocument): ChunkRecord[] {
151-
const passages = doc.chunks ?? [{ id: `${doc.id}#0`, content: doc.content }];
161+
const passages: Array<{ id: string; content: string; headingPath?: string[] }> =
162+
doc.chunks ?? [{ id: `${doc.id}#0`, content: doc.content }];
152163
return passages
153164
.filter((p) => p.content.trim() !== '')
154165
.map((p) => {
@@ -158,6 +169,8 @@ function embedPassages(doc: KnowledgeDocument): ChunkRecord[] {
158169
documentId: doc.id,
159170
sourceRecordId: doc.sourceRecordId,
160171
organizationId: doc.organizationId,
172+
docHash: doc.docHash,
173+
headingPath: p.headingPath,
161174
content: p.content,
162175
title: doc.title,
163176
metadata: doc.metadata ?? {},

‎packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ interface Passage {
2222
chunkId: string;
2323
documentId: string;
2424
sourceRecordId?: string;
25+
headingPath?: string[];
2526
text: string;
2627
}
2728

@@ -51,6 +52,7 @@ function rank(passages: Passage[], query: string, opts: AdapterSearchOptions): K
5152
sourceRecordId: p.sourceRecordId,
5253
score,
5354
snippet: p.text,
55+
...(p.headingPath === undefined ? {} : { headingPath: p.headingPath }),
5456
}));
5557
}
5658

@@ -72,6 +74,7 @@ class StubAdapter implements IKnowledgeAdapter {
7274
chunkId: c.id,
7375
documentId: doc.id,
7476
sourceRecordId: doc.sourceRecordId,
77+
...(c.headingPath === undefined ? {} : { headingPath: c.headingPath }),
7578
text: c.content,
7679
})));
7780
} else {

0 commit comments

Comments
 (0)