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

Filter by extension

Filter by extension

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

feat(service-knowledge): knowledge documents carry their organization, and a search hands the adapter the caller's organizations so it ranks only their documents

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

In a deployment with more than one organization, a knowledge search now ranks only the documents of the caller's organizations, so another organization's documents no longer take the top places. Which hits the caller gets back is still decided by re-reading each record as the caller, as before.

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

- `KnowledgeDocument.organizationId?`: the organization of the record a document was built from. The knowledge service sets it from the record's `organization_id` under the `group` and `isolated` tenancy postures. It is absent under `single`, for `file` and `http` sources, and for a record with no organization. `indexDocument` refuses a document that already carries one (it throws, naming the field).
- `AdapterSearchOptions.organizationIds?`: the caller's organizations. The knowledge service computes it from the caller's execution context and the deployment's tenancy posture: under `isolated` the active organization, under `group` every organization the caller is a member of. It is absent (no filter) under `single`, for the system identity, for `file` and `http` sources, and for an object outside the tenancy wall. `[]` means the caller has no organization behind a wall and must match nothing; it never means "no filter". An adapter that reads it ranks only the documents whose `organizationId` is in the set and filters before it ranks; a document with no `organizationId` is not ranked.

`docHash` now covers `organizationId` when a document has one. A document without one hashes exactly as before, so nothing changes under `single`.

`KnowledgeService` reads the deployment's effective tenancy posture from the kernel's `tenancy` service (`KnowledgeServicePlugin` wires it; new option `resolveTenancyPosture`). If the posture cannot be read, a search does not search any `object` source for that call and logs an error, and a reindex stops before writing and returns `ok: false` with the reason. `recordToDocument` takes the posture as an optional fifth argument. The `search_knowledge` tool refuses an `organizationIds` argument: the organizations are never taken from the caller.

`@objectstack/knowledge-memory` stores `organizationId` and filters by `organizationIds` before ranking. `runKnowledgeAdapterContract` (from `@objectstack/service-knowledge/testing`) now requires `implements.organizationIds`. It adds organization-filter cases for the adapter alone, and cases run through a real `KnowledgeService` under `isolated`, `group` and `single`.

What to do: under a `group` or `isolated` posture, run a complete reindex of each `object` source (`reindexSource` with no `limit`). Documents indexed before this change carry no organization, and a filtered search does not rank them until that reindex writes them again; their hash changes, so the reindex does not skip them. An adapter package reads `organizationIds` in its search, stores `organizationId` as given, and passes `implements: { listDocuments, organizationIds }` to the contract suite.
67 changes: 57 additions & 10 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,19 @@ registers itself with that name. Adapter config (endpoint, dataset id,
Canonical shapes shared by every adapter:

- `KnowledgeDocument` — one logical document (`id`, `sourceId`,
`sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`).
`docHash` is a hash of the assembled document — content, title and
metadata, in a stable key order, behind a version prefix (`v1:`). The
service computes it on every document it hands an adapter, and
`indexDocument` refuses a document that already carries one; the adapter
stores it and returns it as stored, and never computes or alters it.
`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](#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.
- `KnowledgeChunk` — adapter-produced chunk of a document. The framework
does **not** chunk; adapters do.
- `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`,
Expand Down Expand Up @@ -231,7 +238,10 @@ in their plugin options.

Every member past `upsert` / `search` / `delete` is optional (ADR-0161
K8): an adapter that lacks one keeps working, and the service does what it
did before that member existed. `listDocuments` lists the documents the
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](#organization-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
Expand All @@ -246,13 +256,14 @@ import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/test
runKnowledgeAdapterContract({
name: 'my-adapter',
makeAdapter: () => new MyAdapter(/* a fresh, empty store */),
implements: { listDocuments: true },
implements: { listDocuments: true, organizationIds: true },
});
```

It covers upsert / search / delete, `listDocuments` page boundaries and
`docHash` round-trips, and — through a real `KnowledgeService` — the skip and
the purge below. `implements` declares the optional members, and the suite
`docHash` round-trips, the organization filter, and — through a real
`KnowledgeService` — the skip and the purge below, and a search from one
organization under `isolated` and `group`. `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.
Expand Down Expand Up @@ -329,6 +340,42 @@ This is the same pattern as the existing permission-aware data tools
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.

### Source admission: exposure and field-level rules

A passage is built at index time, under a system context, from every
Expand Down
3 changes: 2 additions & 1 deletion content/docs/references/ai/knowledge-document.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ const result = KnowledgeChunkSchema.parse(data);
| **title** | `string` | optional | |
| **metadata** | `Record<string, any>` | optional (default: `{}`) | |
| **permissions** | `string[]` | optional | |
| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter |
| **organizationId** | `string` | optional | Organization of the record the document was assembled from; set by the knowledge service under a walled tenancy posture |
| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata, and organizationId when set); stored and returned as stored by the adapter |


---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ import { KnowledgeMemoryAdapter } from '../index';
runKnowledgeAdapterContract({
name: 'knowledge-memory',
makeAdapter: () => new KnowledgeMemoryAdapter('under_test'),
implements: { listDocuments: true },
implements: { listDocuments: true, organizationIds: true },
});
21 changes: 19 additions & 2 deletions packages/plugins/knowledge-memory/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
* stores each document's `docHash` as given and lists it back as stored, in
* document-id order, the cursor being the last id of the page before. It runs
* the contract suite of `@objectstack/service-knowledge/testing`.
*
* The first reader of the organization filter (ADR-0161 K8, item 9): it
* stores each document's `organizationId` as given and, when a search is
* handed `organizationIds`, ranks only the documents whose organization is in
* that set — the filter runs before the scoring, so `topK` is filled from them
* alone. An empty set ranks nothing; a document stored without an
* organization is not ranked by a filtered search.
*/
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
readonly id: string;
Expand Down Expand Up @@ -92,10 +99,17 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
const qNorm = vectorNorm(qVec);
if (qNorm === 0) return [];

// The organization filter first (ADR-0161 K8, item 9): absent → every
// document; present → only the documents of those organizations, so a
// document with none is out, and `[]` leaves nothing to rank.
const organizations = opts.organizationIds === undefined ? undefined : new Set(opts.organizationIds);
const inScope = organizations === undefined
? chunks
: chunks.filter((c) => c.organizationId !== undefined && organizations.has(c.organizationId));
const filter = opts.filter ?? {};
const filtered = Object.keys(filter).length
? chunks.filter((c) => matchesFilter(c.metadata, filter))
: chunks;
? inScope.filter((c) => matchesFilter(c.metadata, filter))
: inScope;

const scored = filtered.map((c) => ({
chunk: c,
Expand Down Expand Up @@ -126,6 +140,8 @@ interface ChunkRecord {
sourceRecordId?: string;
/** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */
docHash?: string;
/** The document's `organizationId`, stored as given (ADR-0161 K8, item 9). */
organizationId?: string;
content: string;
title?: string;
metadata: Record<string, unknown>;
Expand Down Expand Up @@ -167,6 +183,7 @@ function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
documentId: doc.id,
sourceRecordId: doc.sourceRecordId,
docHash: doc.docHash,
organizationId: doc.organizationId,
content,
title: doc.title,
metadata: doc.metadata ?? {},
Expand Down
Loading
Loading