| title | Knowledge protocol — RAG as metadata |
|---|---|
| navTitle | Knowledge Protocol |
| description | Pluggable RAG / knowledge retrieval for ObjectStack agents — protocol + adapter model. |
ObjectStack does not ship its own RAG engine. The market has many mature options (RAGFlow, LlamaIndex, Dify, Vectara, pgvector + custom pipelines) and competing with them on chunking, embeddings, hybrid retrieval, and rerankers is not where the framework can add value.
Instead, the framework defines a thin Knowledge Protocol — a
spec-level contract for knowledge sources, documents, hits, and the
service that orchestrates them — and ships individual adapters as
plugins. This mirrors the same pattern already proven by
IDataEngine / driver plugins (driver-sql, driver-mongodb,
driver-memory) and IStorageService / S3 + local FS adapters.
This document describes the why, the contract, the plugin model, and the MVP scope that ships in Phase 1.
Building our own RAG engine would force us to compete on three fronts where dedicated projects already win:
- Document understanding — PDF/scan/table extraction (DeepDoc, LlamaParse).
- Retrieval quality — hybrid vector + BM25, MMR, rerankers.
- Operations — knowledge base UI, embedding cost tracking, batch reindex jobs.
We have nothing distinctive to add to those layers. We do have distinctive value to add around them:
- Metadata-native sources. ObjectQL objects are first-class knowledge sources. Records become documents automatically, with no ETL.
- Permission-aware retrieval. Every search is scoped to the
caller's
ExecutionContextso RLS naturally applies — the same policy that protects REST and ObjectQL queries also protects what the LLM can read. - Realtime sync. ObjectQL
data.record.*events drive incremental reindex without manual cron jobs. - Unified audit + observability. Knowledge searches participate in the same trace / audit pipeline as REST, ObjectQL, and tool calls.
The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins.
┌──────────────────────────────────────────────────────────────────────┐
│ @objectstack/spec │
│ │
│ KnowledgeSourceSchema KnowledgeDocumentSchema KnowledgeHitSchema│
│ IKnowledgeService IKnowledgeAdapter │
└──────────────────────────────────────────────────────────────────────┘
▲ ▲
│ depends on implements │
│ │
┌─────────────┴────────────────────────┐ ┌────────────────┴─────────────┐
│ @objectstack/service-knowledge │ │ Adapter plugins (one per │
│ │ │ backend, npm-published) │
│ • Source registry (metadata) │ │ │
│ • Ingest router → adapter.upsert │ │ • knowledge-memory │
│ • Search router → adapter.search │ │ (dev/test only) │
│ • Permission wrapper (RLS filter) │ │ • knowledge-ragflow │
│ • Event sync (record.* → upsert) │ │ (reference impl, REST) │
│ • Audit + metrics │ │ • knowledge-pgvector │
│ │ │ (PostgreSQL + pgvector) │
│ │ │ • knowledge-turso │
│ │ │ (libSQL file, local) │
│ Registers `knowledge` service │ │ (llamaindex / dify: planned)│
└──────────────────────────────────────┘ └──────────────────────────────┘
▲
│ consumes
│
┌─────────────┴────────────────────────┐
│ ObjectOS in-product AI runtime │
│ │
│ • search_knowledge tool │
│ • Threads ToolExecutionContext │
│ • Wires into AI conversation loop │
└──────────────────────────────────────┘
Every box above is independently versioned. Adding a new backend is
one plugin package — zero changes to spec, service-knowledge, or
any AI consumer.
A KnowledgeSource describes what to index and which adapter to
use. It is stored as metadata (versioned, environment-scoped) just
like a view or a flow.
Three source kinds:
| Kind | Origin | Example use case |
|---|---|---|
object |
An ObjectQL object — each record becomes a document | Customer notes, KB articles |
file |
A folder in IStorageService |
Onboarded PDFs, uploads |
http |
A list of remote URLs | External docs, RSS, sitemaps |
kind is the discriminator, and each kind carries its own keys — a key from one
kind is rejected on another:
// object — content comes from the named fields of each matching record
source: {
kind: 'object',
object: 'kb_article',
contentFields: ['title', 'body'], // at least one, required
metadataFields: ['category', 'author'], // optional, carried onto the document
where: { status: 'published' }, // optional ObjectQL filter
split: { strategy: 'markdown', maxChars: 600 }, // optional; see 3.5
}
// file — every object under a storage prefix
source: {
kind: 'file',
prefix: 'knowledge/handbook/',
mimeTypes: ['application/pdf', 'text/markdown'], // optional; omit to take all
}
// http — an explicit URL list (each must be a valid URL)
source: {
kind: 'http',
urls: ['https://docs.example.com/guide', 'https://docs.example.com/faq'],
userAgent: 'ObjectStack-KnowledgeBot/1.0', // optional
}Every source binds to a named adapter id (e.g. 'ragflow',
'memory'). The adapter id is resolved at runtime by the plugin that
registers itself with that name. Adapter config (endpoint, dataset id,
…) is passed through opaquely.
Canonical shapes shared by every adapter:
KnowledgeDocument— one logical document (id,sourceId,sourceRecordId?,content,metadata,permissions?,organizationId?,docHash?).organizationIdis the organization of the record the document was assembled from: the service sets it from the record'sorganization_idunder a walled tenancy posture (grouporisolated), and leaves it absent undersingle, forfile/httpsources and for a record with no organization — see Organization scope.docHashis a hash of the assembled document — content, title and metadata, and the organization when the document has one, in a stable key order, behind a version prefix (v1:). The service computes both on every document it hands an adapter, andindexDocumentrefuses a document that already carries either; the adapter stores them and returnsdocHashas stored, and never computes or alters either.KnowledgeDocument.chunks?— the document's passages, cut by the service's splitter (see 3.5 The split). Set by the service, and only on a document handed to an adapter that declarescapabilities.chunks;indexDocumentrefuses a document that already carries them. Derived fromcontent, so not part ofdocHash.KnowledgeChunk— one passage:id(the service sets it to${documentId}#${index}, so a hit'schunkIdis the same on every adapter),documentId,index,content(what the adapter embeds and returns as a snippet), andheadingPath?(the headings it sits under, outermost first, under themarkdownstrategy). The adapter indexes each passage as given and does not split it again. A passage has nometadataof its own: it takes its document'smetadata. The chunk's formermetadatakey, which nothing wrote or read, is retired, and a chunk that carries one is refused with the fix.KnowledgeHit— a search result (chunkId,documentId,score,snippet,sourceRecordId?,metadata, anddocHash?andheadingPath?: the stored hash of the hit's document and the heading path of its passage, both as the adapter stores them).
The sourceRecordId field is the linchpin of permission-aware
retrieval: when a hit references an ObjectQL record, the
KnowledgeService re-checks it through dataEngine.find with the
caller's ExecutionContext and drops hits the user is not allowed to
read. A hit that the user could not have queried directly is never
returned.
The re-check runs after ranking, so the service asks for more than it
answers. For a caller who is not the system identity, each object
source is asked for topK × 5 hits. When the hits that survive the
re-check name fewer than topK records (several passages of one record
count once), every object source that answered as many hits as it was
asked is asked once more, for topK × 20. That is the cap: a caller who may
read fewer than topK of the rows within the cap gets fewer than topK
hits. An
adapter that answers fewer than it was asked (one that caps topK) is not
asked again. A file or http source is asked for topK once, and so is
every source for the system identity. The answer is at most topK hits.
How many hits the re-check removed is logged at debug, never returned to
the caller.
A search answers passages by default (granularity: 'chunk'): several
passages of one record can take several of the topK places. With
granularity: 'record' it answers records: 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; that is the cap, and fewer records
within it means fewer hits, logged at debug. A file or http hit is
grouped by its document.
groupBy names a metadata field and groups by its value instead — "which
policies", not "which clauses" — with the best hit of each group and the
value in the hit's metadata; it implies record granularity, and is refused
with granularity: 'chunk' (VALIDATION_ERROR, 400, as are an empty
groupBy and an unknown granularity). Hits with the same value are one group whichever
source they come from. An object source that does not list the field in
its metadataFields is not searched, and a record with no value for it is
not answered: a hit is never answered ungrouped.
Each record-level hit is checked against its record as it reads now, one
system-context read per source of only the records about to be answered
(the source's where AND their ids). A record that was deleted or left
where since it was indexed, or whose document hash computed now differs
from the hit's docHash, 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, once
until its hash matches again — except in a source with
refresh.onRecordChange: false, whose index an external indexer owns: the
service writes nothing there, and the hit is only not answered. A hit whose
adapter stores no hash is checked for membership only. Record granularity
also reads the display field in the permission re-check (as the caller, in
the same query), so 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).
A hit's title is the value of the object's display field (ADR-0079
resolveDisplayField: nameField, else the derived title field), set
when the document is built. It is empty when that field is a
credential-class or internal field, when the value is empty, and when
the object resolves no display field. A source over an object with no
registered definition reads a field named title. Documents indexed
before this rule carry the value of a field named title until a complete
reindex writes them again, so the source admission below still asks about a
declared title field as well as the display field.
interface IKnowledgeService {
// Adapters
registerAdapter(id: string, adapter: IKnowledgeAdapter): void;
getAdapter(id: string): IKnowledgeAdapter;
listAdapters(): string[];
// Sources
registerSource(source: KnowledgeSource): void;
unregisterSource(sourceId: string): void;
listSources(): KnowledgeSource[];
getSource(sourceId: string): KnowledgeSource | undefined;
// Documents
indexDocument(sourceId: string, doc: KnowledgeDocument): Promise<void>;
deleteDocument(sourceId: string, documentId: string): Promise<void>;
reindexSource(sourceId: string, opts?: KnowledgeReindexOptions): Promise<KnowledgeReindexResult>;
// Search
search(query: string, opts?: KnowledgeSearchOptions): Promise<KnowledgeHit[]>;
}KnowledgeSearchOptions includes sourceIds, topK, filter,
granularity, groupBy, and
the all-important executionContext (from the permission-aware tool
execution work — see actions-as-tools.mdx). See
Records, not passages for granularity and groupBy. KnowledgeReindexOptions
accepts dryRun and limit; reindexSource returns a
KnowledgeReindexResult (indexed, discovered, skipped, purged,
failed, failures, ok, …) — see Reindex: skip and purge
and 3.5 The split.
interface IKnowledgeAdapter {
readonly id: string;
readonly capabilities?: { chunks?: boolean }; // takes the service's passages
readonly embedding?: { // what its embedder is
maxInputTokens?: number; // longest input it accepts
model?: string; dimensions?: number; variant?: string; // what its vectors are
};
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 }>;
indexStatus?(ctx: AdapterContext): Promise<{ fingerprint?: string; recipeHash?: string; building?: boolean }>;
beginBuild?(ctx: AdapterContext): Promise<void>; // with completeBuild, as a pair
completeBuild?(ctx: AdapterContext): Promise<void>;
healthCheck?(): Promise<{ ok: boolean; message?: string }>;
}The adapter contract carries what an adapter reports, never how it
is configured: no embedding configuration, no rerank toggles. Those are the
adapter's private concerns; adapters that need extra knobs expose them in
their plugin options. The split is the service's (ADR-0161 K1): an adapter
that declares capabilities.chunks receives every document with the
service's passages and indexes them as given; one that does not receives
whole documents, without chunks, and splits them itself, as before.
embedding.maxInputTokens reports the longest input the adapter's embedder
accepts (an adapter fills it from IEmbedder.maxInputTokens); the service
reads it each time it splits, never once at boot, because the embedder may
register later — an adapter that resolves its embedder late serves it from a
getter.
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. AdapterSearchOptions.organizationIds is the
caller's organizations; an adapter that reads it ranks only those
organizations' documents, filtering before it ranks — see
Organization scope. AdapterSearchOptions.scope holds a
search to chosen records the same way — see Record scope.
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.
indexStatus, beginBuild and completeBuild carry the index fingerprint —
see §3.6.
The contract test suite. Every adapter package runs the same suite against its own factory:
import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing';
runKnowledgeAdapterContract({
name: 'my-adapter',
makeAdapter: () => new MyAdapter(/* a fresh, empty store */),
implements: {
listDocuments: true, chunks: true, organizationIds: true,
indexStatus: true, builds: true, refusesOtherFingerprint: true, generations: true,
scope: true,
},
});It covers upsert / search / delete, listDocuments page boundaries and
docHash round-trips, the organization filter, and — through a real
KnowledgeService — the skip and the purge below, a search from one
organization under isolated and group, and the chunk channel: an adapter
that takes chunks receives the service's passages and indexes them unchanged,
one that does not keeps receiving whole documents, and a whole document over
the embedder's budget is removed and reported; and the index fingerprint of
§3.6 — that every call carries one, that a write or a search under another
is refused by code, a complete reindex as one build, and, for an adapter that
keeps generations, the switch at the end of a build. 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; knowledge-pgvector
runs it against a live PostgreSQL in CI; knowledge-turso runs it on libSQL
:memory: and on a file: URL in its own unit tests.
The knowledge service cuts documents into passages once, in one splitter,
and hands the same passages to every adapter that declares
capabilities.chunks — so one source gives the same passages on each of
them. The object source's split key chooses how:
split: {
strategy: 'recursive', // 'whole' | 'recursive' | 'markdown'
maxChars: 600, // optional: longest passage, in characters
minChars: 200, // optional: merge adjacent pieces shorter than this (default 200)
}| Strategy | How it cuts |
|---|---|
whole |
One passage per document. |
recursive (the default) |
At blank lines, then line breaks, then sentence ends, then semicolons, then characters — each next level only for a piece still too long. A Markdown table or list item is one unit while it fits; a table that does not fit is cut between rows, each piece repeating the header row. Adjacent pieces are merged while the merged piece is shorter than minChars; a short title block leads the text after it. |
markdown |
One section per heading (a # inside a code fence is no heading), each cut as recursive cuts. Every passage begins with its heading path (Policy > Transport > Air), which counts toward its length and is embedded with it, and carries it as headingPath. A heading with no text of its own joins the next passage. |
Sentence ends, for Chinese and English text. 。?! end a sentence
wherever they stand. . ? ! end one only before whitespace or the end of the
text, so 「3.2 条」 and 「400.50 元」 stay whole. An end mark followed by a
closing quote or bracket ends nothing, so the split never falls right after a
closing quote or bracket: 「他说:“好。”然后」 stays one sentence. ; ends a
clause wherever it stands, ; only before whitespace.
How long a passage may be. maxChars is the source's split.maxChars,
else the settings page's Knowledge → Target chunk size
(knowledge.chunk_target), else 800. And when the adapter reports its
embedder's maxInputTokens, every passage's token estimate (the shared
estimateTokens from @objectstack/spec/shared) also stays within 80% of
that limit. A passage keeps both bounds, so the effective length is the
smaller one; with no limit known, only maxChars applies. A minChars above
the effective maxChars reads as maxChars. The splitter never overlaps
passages.
whole over the limit. A whole document whose estimate is over the 80%
budget is removed from the index and reported, never truncated:
reindexSource counts it in failed and names it in failures
([{ documentId, reason }], at most 20; failed counts them all), the event
sync logs it at error with the source, the record id, the estimate and the
limit, and indexDocument throws. With no limit known nothing is checked.
The estimate runs high on purpose — on Chinese text about 1.4× a real
tokenizer — so a whole document's usable length is about 60% of the
model's limit; choose recursive or markdown for longer documents.
A split change is a new index. docHash covers the assembled document,
not its passages, so the skip alone would keep an unchanged document under
its old passages. The index fingerprint (§3.6) hashes the resolved split, so
changing split, chunk_target or the embedder's limit changes the
fingerprint: the source's stored index is refused until a complete reindex
rebuilds it.
Vectors from two embedding models — or from two splits of the same text —
are not comparable, and ranking one against the other answers with noise
that looks like an answer (ADR-0161 K7). So every index is built under one
fingerprint, which the knowledge service computes and hands to the
adapter on every call (AdapterContext.index, AdapterSearchOptions.index):
| Component | Read from |
|---|---|
embedding model, variant, dimensions |
the adapter's embedding descriptor — what it reports for the embedder it calls (IEmbedder.model, IEmbedder.dimensions) |
| split configuration and the splitter's version | the split the service applies, as resolved; absent for an adapter that splits for itself |
| content recipe | the object, the ordered content list, and the assembly rule's version |
Beside it rides a recipe hash of what assembly reads but no vector
depends on: the source's where, its metadataFields, the title field and
the fields an index may not carry. Both are SHA-256 over values in a fixed
order, so the same source and the same adapter give the same hashes on every
machine; no key on a source sets either. An adapter that reports no
embedding descriptor gives the fingerprint no model, so a model change
cannot be seen for it.
What the adapter does with it. A write or a search carrying a
fingerprint other than the one the source's stored index was built under is
refused KNOWLEDGE_REBUILD_REQUIRED (409), never written into or answered
from that index. A source that holds nothing takes the first fingerprint it
is handed. A complete reindex is one build: the service calls beginBuild
before it lists or writes anything, and completeBuild once every row is
written and the purge is done; completeBuild records the recipe hash,
which indexStatus reads back. An adapter that keeps generations
(knowledge-memory does) builds a new fingerprint's index beside the active
one and switches to it at completeBuild; until then the old one answers
its own fingerprint. An adapter that does not refuses beginBuild under a
new fingerprint and says how to clear the source so it can be built afresh.
What a caller sees. KnowledgeService.search over several sources
answers from the sources it can search, and logs each refused one by name; it
throws the refusal (with its code and status, and refused naming every
source) only when no source could be searched. The search_knowledge tool
adds a refused list naming each refused source, so an agent never reads a
source that needs a rebuild as one with nothing to say.
Adapters ship as standalone npm packages, registered via the standard
defineStack({ plugins: [...] }) flow:
import { KnowledgeServicePlugin } from '@objectstack/service-knowledge';
import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory';
import { KnowledgeRagflowPlugin } from '@objectstack/knowledge-ragflow';
import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector';
import { KnowledgeTursoPlugin } from '@objectstack/knowledge-turso';
defineStack({
plugins: [
new KnowledgeServicePlugin(),
new KnowledgeMemoryPlugin(), // dev / test
new KnowledgeRagflowPlugin({ // production
endpoint: process.env.RAGFLOW_URL!,
apiKey: process.env.RAGFLOW_KEY!,
}),
new KnowledgePgvectorPlugin(), // self-hosted, PostgreSQL + pgvector
new KnowledgeTursoPlugin(), // local / not on PostgreSQL, a libSQL file
],
});The plugins are also usable directly against the kernel:
kernel.use(new KnowledgeServicePlugin()).
Each plugin:
- Implements
IKnowledgeAdapter. - In
start(), looks upctx.getService('knowledge')and callsregisterAdapter(id, this). - Owns its own dependencies (SDK, fetch client, embedder).
- Owns its own lifecycle / health checks.
Multiple adapters can co-exist; sources pick which one to use via the
adapter field.
@objectstack/knowledge-pgvector keeps a source's passages and vectors in
PostgreSQL with the pgvector
extension, for a self-hosted deployment that wants no separate vector
service. It takes the service's passages, embeds them with the kernel's
embedder service (or the embedder it is given), and answers a search by
an exact scan.
- Which database. The
urloption when it is given, else the platform database when that is PostgreSQL (OS_DATABASE_URL). Its own small pool (poolMax, default 4; a connection that takes more thanconnectTimeoutMs, default 5000, fails); no pooled connection waits on the embedder. Where organizations have databases of their own, the store is still the ONE database the plugin connects to; organizations are kept apart by itsorganization_idcolumn, which every search filters on before ranking. - Where the tables are. In their own schema,
os_knowledge(optionschema):knowledge_generation, one row per source and generation, and one passage table per vector width,knowledge_vec_d<width>. Object tables live in the connection's own schema, and the platform's drift checks read only that one — so no store table can collide with an object table or be reported as drift. - When the database is not ready. Without the
vectorextension — and the right to create it — or the right to create the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL a database owner runs (CREATE EXTENSION IF NOT EXISTS vector;and the schema's DDL),healthCheckanswersok: falsewith that SQL, and every call answersSERVICE_UNAVAILABLEuntil the SQL has run. No restart is needed after. A database it cannot reach is reported as unreachable, with no SQL. A caller reads one sentence; the driver's text and the SQL go only to the operator — the health check, the boot warning and the log. - Search. An exact scan by cosine distance, so any width works —
including a 3072-wide model. The organization filter, the
record scope and the metadata
filter(equality per key) run in the sameWHERE, before ranking.queryPrefixis put before every query before it is embedded, for a model that embeds questions and passages differently. - Re-embedding. A passage whose text is unchanged (its
chunk_hash) is not embedded again; its row's metadata is rewritten. - Rebuilds. A write or a search under another fingerprint is refused
(§3.6).
beginBuildunder a new fingerprint opens a generation beside the active one, so a complete reindex rebuilds the source with nothing cleared by hand. The walk and the event-sync writes of the build carry the new fingerprint and land in the new generation only. A search during the build is refusedKNOWLEDGE_REBUILD_REQUIRED, saying the source is being rebuilt.completeBuildmakes the new generation active and retires the old one in one transaction. It then deletes the old one's passages in batches (deleteBatchSize, default 1,000) and its row last; a deletion that stops is finished by the next build. One builder per source: a PostgreSQL advisory lock, held on a connection of its own frombeginBuildtocompleteBuild. A second builder is refusedLOCK_CONFLICT(409). The lock is freed at completion, when the process or its connection dies, or afterbuildLockIdleMs(15 minutes) without a call of the build (event-sync writes do not count). It is a session lock, so the store needs a direct or session-mode connection, never a transaction-mode pooler. A stopped build is resumed by the nextbeginBuildunder the same fingerprint, with what it wrote. A generation never takes over passage rows left without a generation row: they are deleted before any generation opens. - An approximate index is an operator's step. The store creates no
HNSW or IVFFlat index; add one by hand when a table outgrows an exact scan
(
CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding vector_cosine_ops);). pgvector's HNSW index takes at most 2,000 dimensions, so a 3072-wide table stays on the exact scan. - The text is stored. Each row holds its passage's text: it is as sensitive as the record it came from, and it is in every backup of the database.
@objectstack/knowledge-turso keeps a source's passages and vectors in a
libSQL database of its own, with
libSQL's native vectors (F32_BLOB, vector32, vector_distance_cos): the
store for local development and for a deployment not on PostgreSQL. It takes
the service's passages, embeds them with the kernel's embedder service (or
the embedder it is given), and answers a search by an exact scan.
- Which database. The
urloption (file:,:memory:or alibsql://Turso URL), elseknowledge.dbunder the project's.objectstack/data/, beside the platform database. Never the platform's own file: two engines writing one SQLite file in one process lose rows, so a URL namingobjectstack.db,dev.db,standalone.dbor the fileOS_DATABASE_URLnames is refused. On a file the store sets WAL and a busy timeout (busyTimeoutMs, default 5000); in one process every call of the store runs its database work one at a time. - Tables.
knowledge_generation, one row per source and generation (fingerprint, recipe hash, width, model, active or being built; at most one of each per source, by a unique index — a second build joins the one under way when its fingerprint is the same, and replaces it otherwise, so the first builder's writes are then refused), and one passage table per source and generation,knowledge_<source>_g<n>, its vector column sized for that generation. A source id that is not snake_case is refused before any SQL. - Search. An exact scan by cosine distance; the organization filter, the
record scope and the metadata
filter(JSON equality per key) run in the sameWHERE, before ranking. The store creates no DiskANN index:vector_top_kranks before it filters, and with one, 1,000 vectors of 1,536 dimensions grew a file from 8.2 MB to 329 MB and took 21.8 s to index. Without it the same 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and about 50 ms. A larger source belongs onknowledge-pgvector. - Rebuilds. A changed fingerprint is refused (§3.6). A complete reindex
under a new fingerprint builds a new generation table beside the active
one, which keeps answering its own fingerprint, and switches at the end of
the build; the old table is dropped. A build of a third fingerprint
abandons one left unfinished. A table of the package's earlier releases
(
knowledge_<source>with exactly their columns) is never served: a search answersKNOWLEDGE_REBUILD_REQUIRED, and the table is dropped when the first complete reindex finishes. A table of any other shape under one of the store's names is neither served nor dropped. - Re-embedding. A passage whose text is unchanged (its
chunk_hash) is not embedded again within a generation. - When it cannot run. A database that cannot be opened, or a platform
with no native libSQL build (there is none for Windows on ARM): the plugin
still registers and boot goes on; it warns with the reason,
healthCheckanswersok: false, and every call answersSERVICE_UNAVAILABLE. - The text is stored. Each row holds its passage's text, as sensitive as the record it came from, and in every copy of the file.
caller (user U)
│
▼
search_knowledge tool
│ ToolExecutionContext { actor: U, … }
▼
IKnowledgeService.search(q, { executionContext, sourceIds })
│
├─► per object source: may U reach it? (exposure + field-level rules,
│ see below) ── a refused source is not searched for U
│
├─► adapter.search(q, …) ──► returns raw hits with sourceRecordId
│
├─► group hits by underlying object
│
├─► for each group: dataEngine.find(object, { where: { id IN [...] },
│ context: U.ctx })
│ ── RLS engages, returns only the rows U can see
│
├─► drop hits whose sourceRecordId was filtered out
│
└─► return surviving hits to the caller
This is the same pattern as the existing permission-aware data tools
(see actions-as-tools.mdx).
No matter how aggressive an adapter's retrieval is, the user never
sees a chunk extracted from a record they can't read.
In a deployment with more than one organization, the adapter ranks only the caller's organizations' documents (ADR-0161 K8, item 9). Without that, the best-ranked passages could all belong to another organization, and the re-read above would empty those places. The filter decides what is ranked; the re-read still decides what is returned.
- At assembly. Under the
groupandisolatedtenancy postures, a document built from a record carries the record'sorganization_idasorganizationId. Undersingle, forfile/httpsources and for a record with no organization, it carries none. - At search. For each
objectsource, the service hands the adapterorganizationIds, the organizations the tenancy wall gives the caller for that object: underisolatedthe caller's active organization, undergroupevery organization the caller holds a membership in. The service computes the set from the caller's execution context and the deployment's posture. No tool argument or search option supplies it, andsearch_knowledgerefuses anorganizationIdsargument. - No filter (
organizationIdsabsent) undersingle, for the system identity, for afile/httpsource, and for an object outside the wall (tenancy disabled, or noorganization_idcolumn). The adapter ranks every document of the source, as before. - An empty set (
[]) is a caller with no organization behind a wall, for example no active organization underisolated. The adapter ranks nothing; an empty set never means "no filter". - A posture that cannot be read: a search leaves every
objectsource unsearched for that call and logs it aterror. A reindex stops before writing anything and says why.
Documents indexed before this change carry no organizationId. Behind a
wall, a filtered search does not rank them until a complete reindex writes
them again. The organization is part of docHash, so the reindex does not
skip them. Under single nothing changes: a document without an organization
hashes as before, and the reindex skips it as before.
A search can be held to chosen records (ADR-0161 K8, item 17): "only inside
this policy". KnowledgeSearchOptions.scope is a list of { object, ids }
entries.
const hits = await knowledge.search('notice period', {
topK: 5,
scope: [{ object: 'policy', ids: [policyId] }],
executionContext: ctx,
});- The object a source indexes. An entry naming it holds that source to those records.
- A parent object. An entry naming another object reaches a source that
lists, in its
metadataFields, alookupormaster_detailfield pointing at that object. The source is then held to the documents whose stored value of that field is one of the ids (any one of them, for a lookup declaredmultiple). Auserfield is not a parent link. A source that lists no such field is not reached by the entry, and neither is one that lists two or more of them (logged once atwarn, naming the fields). A parent two hops away (policy → chapter → clause) is not reached. - Several entries are a union. A source no entry reaches is not searched,
and a
file/httpsource answers nothing under a scope. - Empty.
scope: [], or an entry whoseidsis empty, answers no hits; it never means "no scope". Withoutscope, nothing changes. - Bounds. At most 10 entries, each with at most 500 ids;
objectand every id a non-empty string, and no other key on an entry. Past them the call is refused before any adapter is asked, withcode: 'VALIDATION_ERROR',status: 400and a message naming the bound.
The service turns the entries into terms for each source and hands them to the
adapter as AdapterSearchOptions.scope: { kind: 'record', ids }, judged on
the document's sourceRecordId, or { kind: 'metadata', field, ids }, judged
on its stored metadata[field], values compared as strings. An adapter that
reads the member filters before it ranks, so topK is filled from in-scope
documents; organizationIds, scope and the opaque filter all apply.
Whatever the adapter does, the service checks every hit after it answers and
drops a hit no term holds for, a hit without the value included, so an adapter
returns the document's metadata on its hits. An adapter written before the
member keeps working: out-of-scope documents then take ranking places, its
scoped searches may answer fewer than topK, and the service logs that once
for the adapter. The contract suite pins both halves: each term kind on the
adapter alone, and the service's check over the adapter with the member
stripped.
The scope is judged on the index copy and only narrows. Every hit is still
re-read as the caller, so a caller who cannot read a scoped record gets
nothing from it. Source admission already requires each metadataFields
member to be queryable by the caller, and the parent record is never read. A
document indexed before its source listed the lookup is in no parent scope
until a complete reindex writes it again. How many hits the scope removed is
logged, never returned, and an entry that reaches no source answers the same
empty result a source withheld from the caller gives.
A passage is built at index time, under a system context, from every
contentFields member of its source, the object's display field (the
title) and the source's metadataFields. A row re-check alone would therefore serve a caller the text
of a field a field-level rule hides from them. So before an object source is
searched for a non-system caller, the service asks, once per object per search:
- Disabled package — an object whose owning package is disabled is not searched.
- API exposure — the spec's one exposure decision for the
searchoperation, the one the cross-object search asks:enable.apiEnabled: false, or anenable.apiMethodswhitelist that does not grantsearch(grantinglistdoes), keeps the object's sources out of the search. - System objects — a
sys_*object is searched only when it declaresenable.aiReadable: true(the AI read tools' posture). - Field-level rules — every field the source serves (each
contentFieldsmember,'*'meaning every field the object declares exceptid; eachmetadataFieldsmember; the display field the title is read from, and a declaredtitlefield), less the credential-class andinternal: truefields an index never carries, must be one the caller may query, per thesecurityservice'sgetQueryableFields. Without that answer: itsgetReadableFieldsless every field declaring amaskingRule; with nosecurityservice at all: every field except those declaring amaskingRule. Queryable, not merely readable, because a passage carries the unmasked value.
The answer is per source, not per field: when one served field is hidden
from the caller, that source is not searched for them at all — its passages
mix the hidden field's text into one unit that cannot be partially withheld.
To keep a source searchable for restricted callers, declare its
contentFields / metadataFields from fields every intended reader may query,
and put sensitive fields in a separate source. Every gate fails closed: a
lookup that throws — the security service lookup included, unless the kernel
answers that no security service is registered — or a security service
that answers neither field question, keeps the source out of that caller's
search. The system context bypasses these gates as it bypasses the row
re-check. A caller with no execution context, or a service with no data engine
bound, is searched no object source at all; an object source's hit with no
sourceRecordId cannot be re-checked and is dropped; and the service drops a
hit whose reported sourceId names another source than the one searched. That
check sees only the sourceId an adapter reports: an adapter that labels
another source's passage with the searched source's id is not caught by it, so
two sources must not share one adapter-side store. A restricted caller's empty
answer is this narrowing, not a missing index.
For file and http sources (no underlying ObjectQL record), the
adapter is responsible for honouring an opaque permissions field on
each document. Sources that need fine-grained ACLs should be declared
with a permissions mapping function at index time.
For object sources, KnowledgeService subscribes to the ObjectQL engine's
data.record.created, data.record.updated, data.record.restored and
data.record.deleted events. A bare record.* event is not part of the
vocabulary: no producer emits one, and the subscription ignores it.
A source's where decides which rows it indexes on every path — the event
sync as well as reindexSource. For a created, updated or restored row, with a
data engine bound, each source re-reads the row under the system context:
find(object, { where: { $and: [where, { id }] }, limit: 1 }) (just { id }
when the source has no where).
- A row comes back — the document is built from the re-read row, not from
the event's
after, so a write result that omits a field (a projected result, a formula the write did not return) cannot leave the document short. The same field rules as a reindex apply: the fields the source lists and the object's display field as the title, never a credential-class orinternalfield. - No row comes back — the row does not match (a draft, or a row that stopped matching), and its document is deleted. Deleting an absent document changes nothing.
- A restored row (a recycle-bin restore) takes the same path, so it re-enters the index only if it matches.
- No data engine bound — nothing can be re-read: a source without
wherebuilds the document from the event'safter, and a source withwhereis not synced, which the service logs once per source as a warning.
A delete removes the document named by the event's required recordId. Syncs
of one document run one after another in the process, so two events for the
same row cannot interleave: each re-reads after the previous one finished, and
the last leaves the index agreeing with the database. Because the sync is
inline, a write's sync can wait behind an earlier in-flight sync of the same
document (on a single-connection pool, up to the pool's acquire timeout); the
index still ends consistent.
When the sync runs. The engine publishes data.record.created and
data.record.updated from inside the write, after its after* hooks — before
any unit of work around the write commits (the write's own unit, opened when a
metadata hook can abort it, or a caller's engine.transaction(…)). The
in-process realtime service awaits each subscriber, so the re-read runs inside
the same open transaction and sees the row the write just made. If that unit
then rolls back, the index is wrong in one of two ways:
- The uncommitted row matched — the document stays built from a row that never committed.
- The uncommitted row did not match — the document was deleted, so the committed row, which may still match, is missing from the index.
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; it stays until a complete reindex purges it (below).
data.record.restored is
published after the restore's own unit has committed.
- MVP (Phase 1): synchronous, inline with the originating mutation. Fast for low-volume dev / demo. Indexing failures are logged but do not block the originating write.
- Phase 2: async via
service-queuefor batching, retries, and back-pressure.
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
docHashequals the listed one is not written again; the result counts it inskipped. Every other document is written (indexed). A listed entry without adocHashreads as changed. - Purge. After a complete walk — no
limit, nodryRun, 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'swhereAND 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.purgedcounts 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'with5, 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 intowhere) 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: nullmeans no purge ran: a walk with alimitor adryRun, a failed walk, a source withrefresh.onRecordChange: false(an external indexer owns its index), or an adapter withoutlistDocuments— which also skips nothing, the walk otherwise unchanged. A listing that fails skips and purges nothing either, and the result'smessagesays 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'smessagecounts 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.
The platform's own predicate delete — LifecycleService reaping rows past
their retention window — is the one bulk path that is handled, and it is
handled at the source rather than after the fact
(#4672).
For every object an object source projects, the plugin registers an ADR-0057
reap guard with the lifecycle service. The sweep hands the guard the
candidate rows before deleting them; the guard deletes each row's document and
returns the ids it confirms. Rows it does not confirm stay put.
- Failure direction. If
adapter.deletefails, the row is kept and retried on the next sweep. A row may outlive its index entry; an index entry must never outlive its row, because an orphan still consumes atopKslot ahead of the permission filter and is read straight through by anisSystemcaller. - Composition. Guards from different packages compose by intersection, so this one cannot displace another registrar's cleanup (or be displaced by it).
- Batching is the sweep's: 500 rows per batch, 20 batches per sweep, the backlog draining across sweeps.
- Opt-out.
refresh.onRecordChange: falseon a source — orenableEventSync: falseon the plugin — turns off inline index sync in both directions, event subscription and reap-time de-index alike. An index an external indexer owns is never a reason to hold up another package's retention.
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); 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).
Phase 1 ships the protocol, the orchestrator, two adapters, and the AI
tool wiring. It is not production-grade — it is "production-shaped":
the surface is stable, the unique value-add (permission-aware
retrieval) works end-to-end, and a real adapter (ragflow) is wired
up.
| Component | In Phase 1 | Notes |
|---|---|---|
KnowledgeSourceSchema |
✅ | object / file / http kinds |
KnowledgeDocument / Chunk / Hit |
✅ | Canonical shapes |
IKnowledgeService contract |
✅ | search / index / delete / reindex |
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) |
search_knowledge AI tool |
✅ | Threads ToolExecutionContext |
Event-driven sync for object sources |
✅ (sync) | MVP synchronous; queue in Phase 2 |
| Console source-management UI | ⏳ Phase 2 | |
| Async indexer (queue) | ⏳ Phase 2 | |
| Audit + metrics | ⏳ Phase 2 | |
knowledge-llamaindex |
⏳ Phase 2 | |
knowledge-dify |
⏳ Phase 3 / community | |
knowledge-pgvector |
✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |
knowledge-turso |
✅ | A libSQL file of its own; exact scan, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) |
- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private.
- Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller.
- Cost / quota enforcement — Phase 2.
- Multi-tenant index isolation — defer to adapter capability matrix.
packages/spec/src/ai/embedding.zod.ts already defines
EmbeddingModelSchema and VectorStoreSchema. Those primitives
describe configuration; the Knowledge Protocol describes behaviour.
Adapters may consume EmbeddingModel / VectorStore references from a
KnowledgeSource.embedding field (when supplied), but they are free to
ignore them when the underlying backend manages embeddings
internally (RAGFlow, Dify, Vectara).
- Where does chunk-level ACL live? The framework checks row-level
ACLs by re-querying via
dataEngine.find, and field-level rules at source granularity (§5): a source serving a field the caller may not query is not searched for them. Finer grain — serving such a caller a passage with the hidden field's text removed — would require either (a) indexing one passage per field-visibility class or (b) standardising aredactstep. Deferred. - Multiple adapters per source. Useful for mirroring (e.g. write to RAGFlow and pgvector simultaneously) but adds significant complexity. Not in Phase 1.
- Embedding cost attribution. Belongs in
service-analytics. The Knowledge Protocol simply emits typed events.
actions-as-tools.mdx— theExecutionContextthreading the Knowledge Protocol reuses.architecture.mdx— overall service / plugin layering.packages/spec/src/ai/embedding.zod.ts— pre-existing embedding / vector store primitives the protocol composes with.