Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .changeset/37096-knowledge-list-skip-purge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
'@objectstack/spec': minor
'@objectstack/service-knowledge': patch
'@objectstack/knowledge-memory': patch
---

feat(service-knowledge): adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one adapter contract test suite

Clause-②: yes
Metadata-protocol: added
Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, the adapter contract or reindex; `skills/objectstack-ai/SKILL.md` teaches `KnowledgeSource` authoring only, which this change does not touch. `content/docs/protocol/knowledge.mdx` gains the members, the skip and the purge in this change.

Knowledge adapters can now list the documents they hold, and a full reindex uses that list to skip unchanged documents and to remove documents whose record is gone.

New, all optional, in `@objectstack/spec`:

- `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` returns `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }`: the documents the adapter holds for a source, one page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`.
- `KnowledgeDocument.docHash?`: a hash of the document's content, title and metadata, prefixed `v1:`. The knowledge service sets it on every document it hands an adapter; the adapter stores it and returns it unchanged. `indexDocument` refuses a document that already carries a `docHash` (it throws, naming the field).
- `KnowledgeReindexResult.skipped?` and `purged?`.

`KnowledgeService.reindexSource` for an `object` source, when the source's adapter implements `listDocuments`:

- does not send a document to the adapter again when its hash is unchanged, and counts it in `skipped`;
- after a full run (no `limit`, no `dryRun`, every page read), deletes each listed document whose record no longer exists or no longer matches the source's `where`. Before each deletion it reads the record again; a record that exists at that moment keeps its document. A deletion never overlaps a sync of the same record. `purged` counts the deletions. Known limit: on driver-mongodb and driver-memory, a record stored under a caller-supplied numeric id is not found by that re-read, so if it was restored during the run its document is deleted until the record's next change or the next full reindex.

`purged` is `null` when nothing was deleted because no removal ran: the adapter has no `listDocuments`, the run had a `limit` or `dryRun`, a page failed or answered no list of rows, the source sets `refresh.onRecordChange: false`, or the adapter's listing failed (the `message` says why). If a re-read or a deletion fails, the result is `ok: false` and `purged` counts the deletions made before it.

The record sync (on record create, update and restore) now leaves a document in place and logs a warning when the data engine answers its re-read with something other than a list of rows; it used to delete the document.

`@objectstack/service-knowledge/testing` (new, test-only, ESM only; it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`, a test suite any adapter package runs with its own factory: upsert, search and delete; `listDocuments` paging and `docHash` round-trips; and the skip and the removal through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite.

What to do: nothing. An adapter without `listDocuments` keeps working; its reindex sends every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the removal, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. A caller of `indexDocument` stops setting `docHash`.
104 changes: 92 additions & 12 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,12 @@ registers itself with that name. Adapter config (endpoint, dataset id,
Canonical shapes shared by every adapter:

- `KnowledgeDocument` — one logical document (`id`, `sourceId`,
`sourceRecordId?`, `content`, `metadata`, `permissions?`).
`sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`).
`docHash` is a hash of the assembled document — content, title and
metadata, in a stable key order, behind a version prefix (`v1:`). The
service computes it on every document it hands an adapter, and
`indexDocument` refuses a document that already carries one; the adapter
stores it and returns it as stored, and never computes or alters it.
- `KnowledgeChunk` — adapter-produced chunk of a document. The framework
does **not** chunk; adapters do.
- `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`,
Expand Down Expand Up @@ -200,7 +205,8 @@ interface IKnowledgeService {
the all-important `executionContext` (from the permission-aware tool
execution work — see `actions-as-tools.mdx`). `KnowledgeReindexOptions`
accepts `dryRun` and `limit`; `reindexSource` returns a
`KnowledgeReindexResult` (`indexed`, `discovered`, `ok`, …).
`KnowledgeReindexResult` (`indexed`, `discovered`, `skipped`, `purged`,
`ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge).

### 3.4 `IKnowledgeAdapter` (implemented by plugins)

Expand All @@ -210,6 +216,10 @@ interface IKnowledgeAdapter {
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
listDocuments?(
ctx: AdapterContext,
opts: { cursor?: string; limit: number },
): Promise<{ documents: { documentId: string; docHash?: string }[]; nextCursor?: string }>;
healthCheck?(): Promise<{ ok: boolean; message?: string }>;
}
```
Expand All @@ -219,6 +229,34 @@ management, no chunk strategy, no rerank toggles. Those are the
adapter's private concerns. Adapters that need extra knobs expose them
in their plugin options.

Every member past `upsert` / `search` / `delete` is optional (ADR-0161
K8): an adapter that lacks one keeps working, and the service does what it
did before that member existed. `listDocuments` lists the documents the
adapter holds for a source, a page of at most `limit` entries at a time, each
with the `docHash` it was stored with; `nextCursor` is absent once the
listing is complete. A document written while a listing runs may be missing
from it — the safe direction, since a missing entry is never purged.

**The contract test suite.** Every adapter package runs the same suite
against its own factory:

```ts
import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing';

runKnowledgeAdapterContract({
name: 'my-adapter',
makeAdapter: () => new MyAdapter(/* a fresh, empty store */),
implements: { listDocuments: true },
});
```

It covers upsert / search / delete, `listDocuments` page boundaries and
`docHash` round-trips, and — through a real `KnowledgeService` — the skip and
the purge below. `implements` declares the optional members, and the suite
checks the declaration against the adapter. `./testing` is a test-only,
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
`knowledge-memory` runs it as the reference implementation.

---

## 4. Plugin model
Expand Down Expand Up @@ -392,8 +430,7 @@ then rolls back, the index is wrong in one of two ways:

The row's next event or a `reindexSource` repairs a row that still exists. A
document built from an **insert** that rolled back has no row left to repair it
from, and a reindex removes no documents, so it stays until the index purge
([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands.
from; it stays until a complete reindex purges it (below).

`data.record.restored` is
published after the restore's own unit has committed.
Expand All @@ -412,12 +449,54 @@ published after the restore's own unit has committed.
than per-record events. A knowledge index is a per-record projection and
`matched: 40` names no record, so there is no upsert or delete to derive —
the service logs a warning naming the object and count instead of failing
silently. An explicit `reindexSource` refreshes the documents of rows that
still exist and match; it removes no documents, so those of deleted rows (or
of rows that stopped matching) stay until the index purge
([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands.
silently. A complete `reindexSource` refreshes the documents of rows that
still exist and match, and — over an adapter that implements
`listDocuments` — purges those of deleted rows and of rows that stopped
matching. Over an adapter that does not, they stay in the index.
</Callout>

### Reindex: skip and purge

A `reindexSource` of an `object` source over an adapter that implements
`listDocuments` first lists what the adapter holds for the source (document
id → stored `docHash`), then walks the object's rows page by page:

- **Skip.** A row whose document's computed `docHash` equals the listed one is
not written again; the result counts it in `skipped`. Every other document
is written (`indexed`). A listed entry without a `docHash` reads as changed.
- **Purge.** After a **complete** walk — no `limit`, no `dryRun`, no failed
page — every document listed before the walk that the walk did not see is a
candidate. Each candidate is confirmed by the same re-read the event sync
makes (the source's `where` AND the record id, under the system context) and
deleted only when that finds no row. A row created or restored during the
walk keeps its document: if it was listed, the re-read finds it; if it was
not, it was never a candidate. The purge of a document waits for any
in-flight event sync of the same document. `purged` counts the deletions.
- **Known limit: numeric record ids.** The purge reads the record id back from
the document id as text and re-reads by that text. On driver-mongodb and
driver-memory, which do not equate `'5'` with `5`, a row stored under a
caller-supplied numeric id is not found by that re-read; if such a row was
restored (or came back into `where`) after the walk read past it, its
document is deleted. The row itself is untouched, and its document returns at
the row's next event or the next complete reindex. Platform-minted ids are
text on every driver, so this needs a caller-supplied numeric id.
- **`purged: null`** means no purge ran: a walk with a `limit` or a `dryRun`,
a failed walk, a source with `refresh.onRecordChange: false` (an external
indexer owns its index), or an adapter without `listDocuments` — which also
skips nothing, the walk otherwise unchanged. A listing that fails skips and
purges nothing either, and the result's `message` says why.
- A listed document whose id is not one the source derives from a record
(`<sourceId>:<recordId>`) is never purged, since no row can confirm it; the
result's `message` counts such documents.

A re-read or delete that fails stops the purge — a re-read that answers no
list of rows counts as failed, never as "no row" — and the result is
`ok: false`, `purged` counts the deletions made before it, and the `message`
names the document. A walk page that answers no list of rows stops the walk
the same way, with `purged: null`, rather than ending it as if the source were
empty. The event sync shares that re-read: when it answers no list of rows, the
sync leaves the document in place and logs a warning, rather than deleting it.

### Retention deletes are covered by a reap guard

The platform's own predicate delete — `LifecycleService` reaping rows past
Expand Down Expand Up @@ -445,9 +524,10 @@ returns the ids it confirms. Rows it does not confirm stay put.
external indexer owns is never a reason to hold up another package's
retention.

Application-level predicate writes remain uncovered: de-indexing them needs an
adapter-side enumeration capability that no adapter declares today, and that
surface stays unbuilt until a real `object` source calls for it.
Application-level predicate writes are not de-indexed as they happen. Their
stale documents are removed by the next complete `reindexSource`, over an
adapter that implements `listDocuments` ([Reindex: skip and
purge](#reindex-skip-and-purge)); nothing runs that reindex on a schedule yet.

`file` / `http` sources rely on explicit `reindexSource` calls
(typically triggered by a cron job, a Console button, or a webhook).
Expand All @@ -467,7 +547,7 @@ up.
| `KnowledgeSourceSchema` | ✅ | object / file / http kinds |
| `KnowledgeDocument` / `Chunk` / `Hit` | ✅ | Canonical shapes |
| `IKnowledgeService` contract | ✅ | search / index / delete / reindex |
| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck |
| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments` with a contract test suite (`@objectstack/service-knowledge/testing`) |
| `service-knowledge` orchestrator | ✅ | Adapter routing, RLS wrapper, sync |
| `knowledge-memory` | ✅ | In-process; deterministic fake embedder |
| `knowledge-ragflow` | ✅ | Minimal REST adapter (datasets + chunks + retrieval) |
Expand Down
1 change: 1 addition & 0 deletions content/docs/references/ai/knowledge-document.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const result = KnowledgeChunkSchema.parse(data);
| **title** | `string` | optional | |
| **metadata** | `Record<string, any>` | optional (default: `{}`) | |
| **permissions** | `string[]` | optional | |
| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter |


---
Expand Down
14 changes: 14 additions & 0 deletions packages/plugins/knowledge-memory/src/__tests__/contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

// The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1), run against the
// reference adapter. Every adapter package runs the same suite with its own
// factory; a fresh adapter per case keeps the cases independent.

import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing';
import { KnowledgeMemoryAdapter } from '../index';

runKnowledgeAdapterContract({
name: 'knowledge-memory',
makeAdapter: () => new KnowledgeMemoryAdapter('under_test'),
implements: { listDocuments: true },
});
33 changes: 33 additions & 0 deletions packages/plugins/knowledge-memory/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type {
IKnowledgeAdapter,
IKnowledgeService,
AdapterContext,
AdapterListDocumentsOptions,
AdapterListDocumentsPage,
AdapterSearchOptions,
} from '@objectstack/spec/contracts';
import type {
Expand All @@ -20,6 +22,11 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
*
* Deterministic — same input always produces the same hits — so it's
* great for tests and reference implementations. **Don't use in prod.**
*
* The reference implementation of `listDocuments` (ADR-0161 K8, item 1): it
* stores each document's `docHash` as given and lists it back as stored, in
* document-id order, the cursor being the last id of the page before. It runs
* the contract suite of `@objectstack/service-knowledge/testing`.
*/
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
readonly id: string;
Expand Down Expand Up @@ -55,6 +62,29 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
);
}

async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise<AdapterListDocumentsPage> {
if (!Number.isInteger(opts.limit) || opts.limit < 1) {
throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`);
}
// One entry per document, from its first chunk (every chunk carries the
// document's hash), in id order so a cursor stays valid across writes.
const byDoc = new Map<string, string | undefined>();
for (const c of this.store.get(ctx.source.id) ?? []) {
if (!byDoc.has(c.documentId)) byDoc.set(c.documentId, c.docHash);
}
const ids = [...byDoc.keys()]
.filter((id) => opts.cursor === undefined || id > opts.cursor)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
const page = ids.slice(0, opts.limit);
return {
documents: page.map((documentId) => {
const docHash = byDoc.get(documentId);
return docHash === undefined ? { documentId } : { documentId, docHash };
}),
...(ids.length > page.length ? { nextCursor: page[page.length - 1] } : {}),
};
}

async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
const chunks = this.store.get(opts.source.id) ?? [];
if (chunks.length === 0) return [];
Expand Down Expand Up @@ -94,6 +124,8 @@ interface ChunkRecord {
chunkId: string;
documentId: string;
sourceRecordId?: string;
/** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */
docHash?: string;
content: string;
title?: string;
metadata: Record<string, unknown>;
Expand Down Expand Up @@ -134,6 +166,7 @@ function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
chunkId: `${doc.id}#${idx}`,
documentId: doc.id,
sourceRecordId: doc.sourceRecordId,
docHash: doc.docHash,
content,
title: doc.title,
metadata: doc.metadata ?? {},
Expand Down
9 changes: 8 additions & 1 deletion packages/plugins/knowledge-memory/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,15 @@ export default defineConfig({
{ find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') },
{ find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') },
{ find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') },
// `./testing` (the adapter contract suite) BEFORE the bare package, and both
// anchored: a string `find` matches by PREFIX, so the bare entry would
// resolve the subpath to `…/src/index.ts/testing` — ENOTDIR at run time.
{
find: '@objectstack/service-knowledge',
find: /^@objectstack\/service-knowledge\/testing$/,
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'),
},
{
find: /^@objectstack\/service-knowledge$/,
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'),
},
// #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place
Expand Down
6 changes: 6 additions & 0 deletions packages/plugins/knowledge-ragflow/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ export default defineConfig({
{ find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') },
{ find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') },
{ find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') },
// The published `./testing` subpath BEFORE the bare package, which is a
// PREFIX match with a FILE replacement (ENOTDIR otherwise).
{
find: /^@objectstack\/service-knowledge\/testing$/,
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'),
},
{
find: '@objectstack/service-knowledge',
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'),
Expand Down
8 changes: 7 additions & 1 deletion packages/services/service-knowledge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./testing": {
"import": {
"types": "./dist/testing.d.ts",
"default": "./dist/testing.js"
}
}
},
"scripts": {
"build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs",
"build": "rm -rf dist && tsup && node ../../../scripts/check-dts-emitted.mjs",
"test": "vitest run",
"typecheck": "tsc --noEmit && pnpm check:test-typecheck",
"check:test-typecheck": "tsx ../../../scripts/check-test-typecheck.mts --self-test && tsx ../../../scripts/check-test-typecheck.mts --package packages/services/service-knowledge --project tsconfig.test.json"
Expand Down
Loading
Loading