Skip to content

Latest commit

 

History

History
979 lines (846 loc) · 51.8 KB

knowledge.mdx

File metadata and controls

979 lines (846 loc) · 51.8 KB
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.

The Knowledge Protocol contract and the `service-knowledge` orchestrator are open framework mechanisms. The AI **consumer** that wires the `search_knowledge` tool into an in-product chat loop (shown below) ships in **ObjectOS**. On the open-source framework, reach your data through `@objectstack/mcp` (BYO-AI) instead: its door serves the same `search_knowledge` tool wherever the knowledge service is installed, searching only the sources whose `aiExposed` is not `false`, as the caller.

This document describes the why, the contract, the plugin model, and the MVP scope that ships in Phase 1.


1. Why a protocol, not a built-in engine

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:

  1. Metadata-native sources. ObjectQL objects are first-class knowledge sources. Records become documents automatically, with no ETL.
  2. Permission-aware retrieval. Every search is scoped to the caller's ExecutionContext so RLS naturally applies — the same policy that protects REST and ObjectQL queries also protects what the LLM can read.
  3. Realtime sync. ObjectQL data.record.* events drive incremental reindex without manual cron jobs.
  4. 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.


2. Architectural overview

┌──────────────────────────────────────────────────────────────────────┐
│                          @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) │
│  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.


3. Protocol surface

3.1 KnowledgeSource (declarative metadata)

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.

3.2 KnowledgeDocument, KnowledgeChunk, KnowledgeHit

Canonical shapes shared by every adapter:

  • KnowledgeDocument — one logical document (id, sourceId, sourceRecordId?, content, metadata, permissions?, organizationId?, docHash?). organizationId is the organization of the record the document was assembled from: the service sets it from the record's organization_id under a walled tenancy posture (group or isolated), and leaves it absent under single, for file / http sources and for a record with no organization — see Organization scope. docHash is 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, and indexDocument refuses a document that already carries either; the adapter stores them and returns docHash as 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 declares capabilities.chunks; indexDocument refuses a document that already carries them. Derived from content, so not part of docHash.
  • KnowledgeChunk — one passage: id (the service sets it to ${documentId}#${index}, so a hit's chunkId is the same on every adapter), documentId, index, content (what the adapter embeds and returns as a snippet), and headingPath? (the headings it sits under, outermost first, under the markdown strategy). The adapter indexes each passage as given and does not split it again. A passage has no metadata of its own: it takes its document's metadata. The chunk's former metadata key, 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, and docHash? and headingPath?: 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.

Records, not passages

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.

3.3 IKnowledgeService (consumed by the ObjectOS AI runtime, REST, Console)

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.

3.4 IKnowledgeAdapter (implemented by plugins)

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.

3.5 The split

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.

3.6 The index fingerprint

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.


4. Plugin model

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';

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
  ],
});

The plugins are also usable directly against the kernel: kernel.use(new KnowledgeServicePlugin()).

Each plugin:

  1. Implements IKnowledgeAdapter.
  2. In start(), looks up ctx.getService('knowledge') and calls registerAdapter(id, this).
  3. Owns its own dependencies (SDK, fetch client, embedder).
  4. Owns its own lifecycle / health checks.

Multiple adapters can co-exist; sources pick which one to use via the adapter field.

4.1 knowledge-pgvector — the open vector store on PostgreSQL

@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 url option 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 than connectTimeoutMs, 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 its organization_id column, which every search filters on before ranking.
  • Where the tables are. In their own schema, os_knowledge (option schema): 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 vector extension — 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), healthCheck answers ok: false with that SQL, and every call answers SERVICE_UNAVAILABLE until 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 same WHERE, before ranking. queryPrefix is 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 changed fingerprint is refused (§3.6). This store does not yet build a second generation beside the first: beginBuild under a new fingerprint is refused, and the reindex result carries the exact statements that clear the source — one DELETE per passage table, then the generation row — after which a complete reindex builds it afresh. A first generation never takes over passage rows left behind without a generation row: they are deleted when it 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.

5. Permission-aware retrieval (the unique value-add)

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.

Organization scope

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 group and isolated tenancy postures, a document built from a record carries the record's organization_id as organizationId. Under single, for file / http sources and for a record with no organization, it carries none.
  • At search. For each object source, the service hands the adapter organizationIds, the organizations the tenancy wall gives the caller for that object: under isolated the caller's active organization, under group every 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, and search_knowledge refuses an organizationIds argument.
  • No filter (organizationIds absent) under single, for the system identity, for a file / http source, and for an object outside the wall (tenancy disabled, or no organization_id column). 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 under isolated. The adapter ranks nothing; an empty set never means "no filter".
  • A posture that cannot be read: a search leaves every object source unsearched for that call and logs it at error. 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.

Record scope

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, a lookup or master_detail field 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 declared multiple). A user field 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 at warn, 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 / http source answers nothing under a scope.
  • Empty. scope: [], or an entry whose ids is empty, answers no hits; it never means "no scope". Without scope, nothing changes.
  • Bounds. At most 10 entries, each with at most 500 ids; object and every id a non-empty string, and no other key on an entry. Past them the call is refused before any adapter is asked, with code: 'VALIDATION_ERROR', status: 400 and 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.

Source admission: exposure and field-level rules

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 search operation, the one the cross-object search asks: enable.apiEnabled: false, or an enable.apiMethods whitelist that does not grant search (granting list does), keeps the object's sources out of the search.
  • System objects — a sys_* object is searched only when it declares enable.aiReadable: true (the AI read tools' posture).
  • Field-level rules — every field the source serves (each contentFields member, '*' meaning every field the object declares except id; each metadataFields member; the display field the title is read from, and a declared title field), less the credential-class and internal: true fields an index never carries, must be one the caller may query, per the security service's getQueryableFields. Without that answer: its getReadableFields less every field declaring a maskingRule; with no security service at all: every field except those declaring a maskingRule. 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.


6. Sync model

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 or internal field.
  • 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 where builds the document from the event's after, and a source with where is 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-queue for batching, retries, and back-pressure.
**A predicate write leaves the index stale.** A `multi: true` update/delete reaches `updateMany` / `deleteMany`, which report only an affected row count, so it publishes the aggregate `data.records.updated` / `data.records.deleted` ([#4639](#4639)) rather 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. 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.

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 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.delete fails, 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 a topK slot ahead of the permission filter and is read straight through by an isSystem caller.
  • 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: false on a source — or enableEventSync: false on 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).


7. MVP (Phase 1) scope

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)

7.1 Non-goals for Phase 1

  • 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.

8. Compatibility with existing Embedding primitives

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).


9. Open questions

  • 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 a redact step. 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.

10. Related documents

  • actions-as-tools.mdx — the ExecutionContext threading 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.