diff --git a/.changeset/37097-knowledge-organization-filter.md b/.changeset/37097-knowledge-organization-filter.md new file mode 100644 index 00000000000..a54756a1668 --- /dev/null +++ b/.changeset/37097-knowledge-organization-filter.md @@ -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. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 40f1dffc4ea..74fd8327535 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -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`, @@ -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 @@ -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. @@ -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 diff --git a/content/docs/references/ai/knowledge-document.mdx b/content/docs/references/ai/knowledge-document.mdx index 34ab2a70204..ec59f18705e 100644 --- a/content/docs/references/ai/knowledge-document.mdx +++ b/content/docs/references/ai/knowledge-document.mdx @@ -60,7 +60,8 @@ const result = KnowledgeChunkSchema.parse(data); | **title** | `string` | optional | | | **metadata** | `Record` | 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 | --- diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index 5a01432e5d9..85e574c0531 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -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 }, }); diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 2e8e3b69a0d..70dc64b28dc 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -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; @@ -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, @@ -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; @@ -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 ?? {}, diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index a9adc919921..485634c77e4 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1,6 +1,9 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel, ObjectKernel } from '@objectstack/core'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; import { DOC_HASH_VERSION, KnowledgeService, @@ -1188,3 +1191,278 @@ describe('KnowledgeService — the event sync on an unreadable re-read', () => { expect(String(warn.mock.calls[0][0])).toMatch(/event-sync failed for source 's1': the re-read of record 'r1' answered undefined instead of a list of rows/); }); }); + +// ADR-0161 K8, item 9: a document assembled from a record carries the record's +// organization under a walled tenancy posture, and a search hands the adapter +// the caller's organizations, computed by the service from the caller's +// execution context and the deployment's posture (ADR-0105 D1). +describe('KnowledgeService — documents carry their organization (ADR-0161 K8, item 9)', () => { + const src = objectSource('s1', 'task'); + const objSrc = src.source as ObjectKnowledgeSource; + const row = { id: 'r1', title: 'A', notes: 'B', status: 'open', organization_id: 'org_a' }; + + it.each([ + ['group', 'org_a'], + ['isolated', 'org_a'], + ['single', undefined], + [undefined, undefined], + ] as const)('recordToDocument under %s sets organizationId %s', (posture, expected) => { + const doc = recordToDocument(src, objSrc, row, undefined, posture); + expect(doc.organizationId).toBe(expected); + expect(doc.docHash).toBe(computeDocHash(doc)); + }); + + it('a record with no organization gives a document with none, under a walled posture too', () => { + expect(recordToDocument(src, objSrc, { ...row, organization_id: null }, undefined, 'isolated')).not.toHaveProperty('organizationId'); + expect(recordToDocument(src, objSrc, { ...row, organization_id: '' }, undefined, 'group')).not.toHaveProperty('organizationId'); + }); + + it('the organization enters docHash only when set: a document without one hashes by the recipe it had before', async () => { + const { createHash } = await import('node:crypto'); + const body = { content: 'Body', title: 'T', metadata: { status: 'open' } }; + // The pre-organization recipe, spelled out: sorted keys, `v1:` prefix. + const before = `v1:${createHash('sha256').update(JSON.stringify({ content: 'Body', metadata: { status: 'open' }, title: 'T' })).digest('hex')}`; + expect(computeDocHash(body)).toBe(before); + expect(computeDocHash({ ...body, organizationId: undefined })).toBe(before); + expect(computeDocHash({ ...body, organizationId: 'org_a' })).not.toBe(before); + expect(computeDocHash({ ...body, organizationId: 'org_a' })).not.toBe(computeDocHash({ ...body, organizationId: 'org_b' })); + }); + + it('indexDocument refuses a caller-supplied organizationId, and writes nothing', async () => { + const adapter = makeAdapter('memory'); + const svc = new KnowledgeService(); + svc.registerAdapter('memory', adapter); + svc.registerSource(src); + await expect( + svc.indexDocument('s1', { id: 'd1', sourceId: 's1', content: 'x', organizationId: 'org_b' }), + ).rejects.toThrow(/organizationId/); + expect(adapter.upsertSpy).not.toHaveBeenCalled(); + }); + + it('the reindex walk and the event sync stamp the organization under a walled posture', async () => { + const adapter = makeAdapter('memory'); + const find = vi.fn(async (_o: string, q: { where?: Record }) => + (q.where && '$and' in q.where) || (q.where && 'id' in q.where && typeof q.where.id === 'object') ? [] : [row]); + const svc = new KnowledgeService({ + dataEngine: { find, count: vi.fn() } as unknown as IDataEngine, + resolveTenancyPosture: async () => 'isolated', + }); + svc.registerAdapter('memory', adapter); + svc.registerSource(src); + expect(await svc.reindexSource('s1')).toMatchObject({ ok: true, indexed: 1 }); + expect((adapter.upsertSpy.mock.calls[0][0] as KnowledgeDocument[])[0].organizationId).toBe('org_a'); + await svc.handleRecordUpsert('task', row); + expect((adapter.upsertSpy.mock.calls[adapter.upsertSpy.mock.calls.length - 1][0] as KnowledgeDocument[])[0].organizationId).toBe('org_a'); + }); + + it('a reindex whose posture cannot be read writes nothing and says why', async () => { + const adapter = makeAdapter('memory'); + const find = vi.fn(async () => [row]); + const svc = new KnowledgeService({ + dataEngine: { find, count: vi.fn() } as unknown as IDataEngine, + resolveTenancyPosture: async () => { + throw new Error('tenancy store down'); + }, + }); + svc.registerAdapter('memory', adapter); + svc.registerSource(src); + const result = await svc.reindexSource('s1'); + expect(result).toMatchObject({ ok: false, indexed: 0, purged: null }); + expect(result.message).toContain('tenancy posture'); + expect(adapter.upsertSpy).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe('KnowledgeService — search hands the adapter the caller\'s organizations (ADR-0161 K8, item 9)', () => { + const person = (extra: Record) => + ({ userId: 'u1', positions: [], permissions: [], systemPermissions: [], isSystem: false, ...extra }) as never; + + function searchSetup(opts: { + posture?: () => Promise<'single' | 'group' | 'isolated' | undefined>; + schema?: unknown; + logger?: { warn: ReturnType; error: ReturnType }; + } = {}) { + const adapter = makeAdapter('memory'); + const engine = { + find: vi.fn(async () => []), + getSchema: vi.fn(() => opts.schema), + } as unknown as IDataEngine; + const options: ConstructorParameters[0] = { dataEngine: engine }; + if (opts.posture) options.resolveTenancyPosture = opts.posture; + if (opts.logger) options.logger = opts.logger as unknown as NonNullable['logger']; + const svc = new KnowledgeService(options); + svc.registerAdapter('memory', adapter); + svc.registerSource(objectSource('s1', 'task')); + svc.registerSource({ + id: 'web', label: 'Web', adapter: 'memory', + source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], + }); + const handed = (sourceId: string) => + adapter.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.id === sourceId)?.[1] as + | Record + | undefined; + return { svc, adapter, handed }; + } + + it('isolated: the caller\'s active organization, never their other memberships', async () => { + const h = searchSetup({ posture: async () => 'isolated' }); + await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a', 'org_b'] }) }); + expect(h.handed('s1')?.organizationIds).toEqual(['org_a']); + }); + + it('group: every organization the caller holds a membership in, once each', async () => { + const h = searchSetup({ posture: async () => 'group' }); + await h.svc.search('q', { executionContext: person({ tenantId: 'org_c', accessible_org_ids: ['org_a', 'org_c', 'org_a'] }) }); + expect(h.handed('s1')?.organizationIds).toEqual(['org_a', 'org_c']); + }); + + it.each([ + ['isolated with no active organization', 'isolated', { accessible_org_ids: ['org_a'] }], + ['group with no membership', 'group', { tenantId: 'org_a', accessible_org_ids: [] }], + ] as const)('%s: an empty set, never "no filter"', async (_label, posture, ctx) => { + const h = searchSetup({ posture: async () => posture }); + await h.svc.search('q', { executionContext: person(ctx) }); + expect(h.handed('s1')?.organizationIds).toEqual([]); + }); + + it.each([ + ['the single posture', async () => 'single' as const, person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] })], + ['no tenancy service', async () => undefined, person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] })], + ['the system identity', async () => 'isolated' as const, { positions: [], permissions: [], isSystem: true } as never], + ])('%s: no filter is handed', async (_label, posture, ctx) => { + const h = searchSetup({ posture }); + await h.svc.search('q', { executionContext: ctx }); + expect(h.handed('s1')).toBeDefined(); + expect(h.handed('s1')).not.toHaveProperty('organizationIds'); + }); + + it('a file / http source is never handed a filter: its documents carry no organization', async () => { + const h = searchSetup({ posture: async () => 'isolated' }); + await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }) }); + expect(h.handed('web')).not.toHaveProperty('organizationIds'); + }); + + it.each([ + ['tenancy disabled', { name: 'task', tenancy: { enabled: false }, fields: { organization_id: {}, notes: {} } }], + ['no organization column', { name: 'task', fields: { notes: {}, title: {}, status: {} } }], + ])('an object outside the wall (%s) is handed no filter', async (_label, schema) => { + const h = searchSetup({ posture: async () => 'isolated', schema }); + await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }) }); + expect(h.handed('s1')).toBeDefined(); + expect(h.handed('s1')).not.toHaveProperty('organizationIds'); + }); + + it('a caller-supplied filter is passed opaquely and never becomes the organization set', async () => { + const h = searchSetup({ posture: async () => 'isolated' }); + await h.svc.search('q', { + filter: { organizationIds: ['org_b'] }, + executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }), + }); + expect(h.handed('s1')?.organizationIds).toEqual(['org_a']); + }); + + it('a posture that cannot be read leaves every object source unsearched, says so at error, and still searches file / http', async () => { + const logger = { warn: vi.fn(), error: vi.fn() }; + const h = searchSetup({ + posture: async () => { + throw new Error('tenancy store down'); + }, + logger, + }); + await h.svc.search('q', { executionContext: person({ tenantId: 'org_a', accessible_org_ids: ['org_a'] }) }); + expect(h.handed('s1')).toBeUndefined(); + expect(h.handed('web')).toBeDefined(); + expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('tenancy posture could not be read')); + }); +}); + +// The plugin's `resolveTenancyPosture` wiring is the only production reader of +// the posture (ADR-0161 K8, item 9): broken, every deployment reads as +// `single`, no document is stamped and no filter is handed, silently. So the +// wiring is driven through real kernels with a `tenancy` service: `LiteKernel` +// (no async accessor: the sync leg) and `ObjectKernel` (`getServiceAsync`). +describe('KnowledgeServicePlugin reads the tenancy posture from the kernel (ADR-0161 K8, item 9)', () => { + const PERSON = { + userId: 'u1', tenantId: 'org_a', accessible_org_ids: ['org_a'], positions: [], permissions: [], systemPermissions: [], isSystem: false, + } as never; + + class FakeHostPlugin implements Plugin { + name = 'test.fake.host'; + version = '1.0.0'; + type = 'standard' as const; + constructor(private readonly tenancy: unknown) {} + async init(ctx: PluginContext): Promise { + ctx.registerService('objectql', { find: vi.fn(async () => []) }); + if (this.tenancy !== undefined) ctx.registerService('tenancy', this.tenancy); + } + } + + async function boot(Kernel: typeof LiteKernel | typeof ObjectKernel, tenancy: unknown) { + // `ObjectKernel` refuses to start without a `data` service; this harness composes none. + const kernel = Kernel === ObjectKernel + ? new ObjectKernel({ skipSystemValidation: true, logger: { level: 'silent' }, gracefulShutdown: false }) + : new LiteKernel(); + await kernel.use(new FakeHostPlugin(tenancy)); + await kernel.use(new KnowledgeServicePlugin({ enableEventSync: false, sources: [objectSource('s1', 'task')] })); + await kernel.bootstrap(); + const svc = kernel instanceof ObjectKernel + ? await kernel.getServiceAsync('knowledge') + : kernel.getService('knowledge'); + const adapter = makeAdapter('memory'); + svc.registerAdapter('memory', adapter); + return { kernel, svc, adapter }; + } + + it.each([ + ['LiteKernel', LiteKernel], + ['ObjectKernel', ObjectKernel], + ] as const)('%s: a walled posture hands the adapter the caller\'s organizations', async (_name, Kernel) => { + const { kernel, svc, adapter } = await boot(Kernel, { posture: 'isolated' }); + await svc.search('q', { executionContext: PERSON }); + expect(adapter.searchSpy).toHaveBeenCalledOnce(); + expect(adapter.searchSpy.mock.calls[0][1]).toMatchObject({ organizationIds: ['org_a'] }); + await kernel.shutdown(); + }); + + it('no `tenancy` service registered: no wall exists, and no filter is handed', async () => { + const { kernel, svc, adapter } = await boot(LiteKernel, undefined); + await svc.search('q', { executionContext: PERSON }); + expect(adapter.searchSpy).toHaveBeenCalledOnce(); + expect(adapter.searchSpy.mock.calls[0][1]).not.toHaveProperty('organizationIds'); + await kernel.shutdown(); + }); + + it('a `tenancy` service that is registered but cannot be read: no object source is searched', async () => { + const unreadable = Object.defineProperty({}, 'posture', { + get: () => { + throw new Error('tenancy store down'); + }, + }); + const { kernel, svc, adapter } = await boot(LiteKernel, unreadable); + expect(await svc.search('q', { executionContext: PERSON })).toEqual([]); + expect(adapter.searchSpy).not.toHaveBeenCalled(); + await kernel.shutdown(); + }); +}); + +describe('KnowledgeService — an event sync whose tenancy posture cannot be read (ADR-0161 K8, item 9)', () => { + it('logs at warn and leaves the stored document as it was: no upsert, no delete', async () => { + const adapter = makeAdapter('memory'); + const row = { id: 'r1', title: 'A', notes: 'B', status: 'open', organization_id: 'org_a' }; + const warn = vi.fn(); + const svc = new KnowledgeService({ + dataEngine: { find: vi.fn(async () => [row]) } as unknown as IDataEngine, + logger: { warn }, + resolveTenancyPosture: async () => { + throw new Error('tenancy store down'); + }, + }); + svc.registerAdapter('memory', adapter); + svc.registerSource(objectSource('s1', 'task')); + await svc.handleRecordUpsert('task', row); + expect(adapter.upsertSpy).not.toHaveBeenCalled(); + expect(adapter.deleteSpy).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('tenancy store down')); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index d4c8ce7e857..f285b59ea30 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -187,6 +187,9 @@ describe('search_knowledge — malformed arguments', () => { // (which would answer no passage, i.e. "nothing matched"). [{ query: 'q', sourceIds: [] }, 'sourceIds'], [{ query: 'q', sources: ['policy_clauses'] }, 'sources'], + // The organizations a search is scoped to are the service's to compute + // from the caller's identity (ADR-0161 K8, item 9): never an argument. + [{ query: 'q', organizationIds: ['org_b'] }, 'organizationIds'], ])('refuses %j with VALIDATION_ERROR naming %s, and searches nothing', async (input, named) => { const { service, adapter } = setup(); const err = await service.knowledgeTools().searchKnowledge(input, caller).catch((e) => e); diff --git a/packages/services/service-knowledge/src/knowledge-organization-scope.ts b/packages/services/service-knowledge/src/knowledge-organization-scope.ts new file mode 100644 index 00000000000..3add71b278f --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-organization-scope.ts @@ -0,0 +1,105 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K8, item 9] The organization half of a knowledge document and of a + * search: which organization a document assembled from a record belongs to, + * and which organizations a caller's search hands the adapter + * (`AdapterSearchOptions.organizationIds`). + * + * Neither is re-derived here. The posture is the deployment's EFFECTIVE one, + * classified by `classifyAdmissionTenancyPosture` (`@objectstack/core`) from + * the kernel's `tenancy` service — the reading the wall itself is handed, never + * `OS_TENANCY_POSTURE` (ADR-0093 D4/D5). The caller's organizations are the + * Layer 0 verdict `computeTenantLayer0Verdict` (`@objectstack/core`, ADR-0131 + * D8) answers for the source's object, over the organizations the execution + * context carries (`tenantId`, `accessible_org_ids`, resolved by + * `resolveAuthzContext`). So the ranking scope an adapter is handed is the + * same organization set the wall gives the caller's own read of that object + * (ADR-0105 D1: `isolated` → the active organization; `group` → every + * organization the caller holds a membership in). + * + * The filter is a ranking scope only. The access decision stays the service's + * re-read of every object-source hit as the caller (K8, item 9; ADR-0090 D10). + */ + +import { + computeTenantLayer0Verdict, + isOutsideEveryOrganization, + organizationIdOf, +} from '@objectstack/core'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { isTenancyDisabled } from '@objectstack/spec/data'; +import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; +import { declaredFields } from './knowledge-source-admission.js'; + +/** + * How the service reads the deployment's effective tenancy posture: the + * posture, `undefined` for a composition with no `tenancy` service (no wall + * exists there, so it reads as `single`), and a throw for a `tenancy` service + * that is registered but cannot be read. `KnowledgeServicePlugin` passes + * `classifyAdmissionTenancyPosture` over the kernel's `tenancy` service. + */ +export type KnowledgeTenancyPostureResolver = () => Promise; + +/** + * The organization of a document assembled from `record` (K8, item 9): the + * record's `organization_id` under a walled posture (`group`, `isolated`), and + * `undefined` under `single` (or no posture) and for a record that carries + * none. + */ +export function documentOrganizationId( + record: Record, + posture: TenancyPosture | undefined, +): string | undefined { + if (posture === undefined || !postureEnforcesWall(posture)) return undefined; + return organizationIdOf(record.organization_id) ?? undefined; +} + +/** + * The organizations a search of an `object` source over an object with + * definition `schema` hands the adapter, for a caller with context `ctx` + * (K8, item 9). `ctx` is never the system identity: the service's source + * admission answers that one, with no filter, before asking here. + * + * - `undefined` — no filter: the `single` posture (or no posture), and an + * object the wall does not scope (tenancy disabled, or no `organization_id` + * column), whose documents carry no organization. + * - the active organization (`isolated`) or the deduplicated membership set + * (`group`), as the Layer 0 verdict names them; + * - `[]` — the wall denies: no active organization under `isolated`, an empty + * membership set under `group`. Ranks nothing; never "no filter". + * + * An object whose definition the engine cannot give is read as one the wall + * scopes (the wall's own fail-toward-isolation default). + */ +export function searchOrganizationIds( + ctx: ExecutionContext, + posture: TenancyPosture | undefined, + schema: unknown, +): string[] | undefined { + if (posture === undefined || !postureEnforcesWall(posture)) return undefined; + const fields = declaredFields(schema); + const verdict = computeTenantLayer0Verdict({ + tenancyPosture: posture, + organizationId: ctx.tenantId, + accessibleOrgIds: ctx.accessible_org_ids, + outsideEveryOrganization: isOutsideEveryOrganization(ctx), + objectHasOrgIdField: fields === undefined ? undefined : fields.some(([name]) => name === 'organization_id'), + externalOrganizationScopeUndeclared: false, + tenancyDisabled: + isTenancyDisabled(schema) + || (schema as { systemFields?: { tenant?: unknown } } | null | undefined)?.systemFields?.tenant === false, + posturePermitsCrossTenant: false, + isPlatformAdmin: false, + }); + switch (verdict.kind) { + case 'none': + return undefined; + case 'deny': + return []; + case 'organization': + return [verdict.organizationId]; + case 'organizations': + return [...verdict.organizationIds]; + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 86662c72f49..14098547beb 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -1,6 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import type { Plugin, PluginContext } from '@objectstack/core'; +import { classifyAdmissionTenancyPosture } from '@objectstack/core'; import type { IDataEngine, IRealtimeService, @@ -166,6 +167,25 @@ export class KnowledgeServicePlugin implements Plugin { throw err; } }, + // [ADR-0161 K8, item 9] The EFFECTIVE tenancy posture, read per assembly + // and per search from the kernel's `tenancy` service, classified the way + // every admission seam classifies it: never registered → `undefined` (no + // wall exists); registered and unreadable → a throw, which the service + // answers fail-closed. The async accessor first, so a factory-registered + // service resolves; the sync leg serves a `LiteKernel`-shaped host. + resolveTenancyPosture: () => + classifyAdmissionTenancyPosture(async () => { + const kernel = typeof ctx.getKernel === 'function' ? ctx.getKernel() : undefined; + if (kernel && typeof kernel.getServiceAsync === 'function') { + return kernel.getServiceAsync<{ posture?: string; isolationActive?: boolean }>('tenancy'); + } + try { + return ctx.getService<{ posture?: string; isolationActive?: boolean }>('tenancy'); + } catch (err) { + if (isServiceNotRegisteredError(err, 'tenancy')) return undefined; + throw err; + } + }), }); for (const source of this.options.sources ?? []) { diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index bd3540564c7..6f1bfe1e476 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -21,7 +21,13 @@ import { collectInternalWriteResponseFields, registryObjectPackageDisabled, } from '@objectstack/core'; +import type { TenancyPosture } from '@objectstack/spec/security'; import { createKnowledgeTools, type KnowledgeTools } from './knowledge-tools.js'; +import { + documentOrganizationId, + searchOrganizationIds, + type KnowledgeTenancyPostureResolver, +} from './knowledge-organization-scope.js'; import { admitObject, admitSourceFields, @@ -65,6 +71,17 @@ export interface KnowledgeServiceOptions { * service. */ resolveSecurity?: () => KnowledgeFieldSecurity | undefined; + /** + * The deployment's effective tenancy posture (ADR-0105 D1), read at each + * assembly and each search (ADR-0161 K8, item 9): under `group` and + * `isolated` a document assembled from a record carries the record's + * organization, and a search hands the adapter the caller's organizations + * (`knowledge-organization-scope.ts`). Answers `undefined` where no + * `tenancy` service is composed, and throws where one is registered but + * cannot be read. `KnowledgeServicePlugin` always wires it; omitted, the + * service reads as a `single`-posture deployment. + */ + resolveTenancyPosture?: KnowledgeTenancyPostureResolver; /** * Default top-K when callers don't specify. The adapter may cap * further; the service does not enforce an upper bound itself. @@ -170,6 +187,16 @@ export class KnowledgeService implements IKnowledgeService { 'from the content, title and metadata; omit it.', ); } + // `organizationId` is the service's too (ADR-0161 K8, item 9): it is the + // organization of the record a document was assembled from. A caller's own + // value would place a document inside an organization's ranking scope on + // the caller's word alone. + if (doc.organizationId !== undefined) { + throw new Error( + `[knowledge] indexDocument refused document '${doc.id}': organizationId is set by the knowledge service ` + + "from the record a document is assembled from; omit it.", + ); + } await adapter.upsert([{ ...doc, docHash: computeDocHash(doc) }], { source, reason: 'manual' }); } @@ -323,6 +350,25 @@ export class KnowledgeService implements IKnowledgeService { }; } + // The posture decides whether each document carries its record's + // organization (ADR-0161 K8, item 9); read once per walk. A posture that + // cannot be read stops the walk before any write: a document assembled + // without its organization would drop out of every walled search. + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + message: `reindex of source '${source.id}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, + }; + } + // What the adapter holds before the walk: the skip's hashes, and the // purge's candidates once the walk is complete. const listing = await listAdapterDocuments(source, adapter); @@ -383,7 +429,7 @@ export class KnowledgeService implements IKnowledgeService { let docs: KnowledgeDocument[]; try { - docs = rows.map((row) => recordToDocument(source, objSource, row, schema)); + docs = rows.map((row) => recordToDocument(source, objSource, row, schema, posture)); } catch (err) { return stopped(`building the page's documents failed: ${errorText(err)}`); } @@ -478,7 +524,7 @@ export class KnowledgeService implements IKnowledgeService { if (sources.length === 0) return []; const rawHits: KnowledgeHit[] = []; - for (const source of sources) { + for (const { source, organizationIds } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { this.options.logger?.warn?.( @@ -491,6 +537,7 @@ export class KnowledgeService implements IKnowledgeService { source, topK, filter: opts.filter, + ...(organizationIds === undefined ? {} : { organizationIds }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store @@ -605,7 +652,7 @@ export class KnowledgeService implements IKnowledgeService { this.reportWhereUnenforceable(source); return; } - const doc = recordToDocument(source, objSource, payload, this.schemaFor(object)); + const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); await adapter.upsert([doc], { source, reason: 'event-sync' }); return; } @@ -618,7 +665,7 @@ export class KnowledgeService implements IKnowledgeService { } const row = await rereadRow(engine, objSource, recordId); if (row) { - const doc = recordToDocument(source, objSource, row, this.schemaFor(object)); + const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); await adapter.upsert([doc], { source, reason: 'event-sync' }); } else { await adapter.delete([documentIdFor(source.id, String(recordId))], { source, reason: 'event-sync' }); @@ -728,15 +775,20 @@ export class KnowledgeService implements IKnowledgeService { * hit with no `sourceRecordId`). Fails CLOSED: a gate that throws refuses * every source over that object, reported once at `error`. The objects' * admissions are asked concurrently. + * + * Each admitted source carries the organizations its search hands the + * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system + * context's bypass above covers that scope too: the system identity's + * search is handed no organization filter. */ private async admitSources( sources: KnowledgeSource[], ctx: ExecutionContext | undefined, - ): Promise { - if (ctx?.isSystem) return sources; + ): Promise> { + if (ctx?.isSystem) return sources.map((source) => ({ source })); const engine = this.options.dataEngine; if (!ctx || !engine) { - const kept = sources.filter((source) => source.source.kind !== 'object'); + const kept = sources.filter((source) => source.source.kind !== 'object').map((source) => ({ source })); if (kept.length < sources.length) { this.options.logger?.warn?.( !ctx @@ -791,7 +843,7 @@ export class KnowledgeService implements IKnowledgeService { ); } } - return out; + return this.scopeByOrganization(out, ctx); } /** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ @@ -803,6 +855,54 @@ export class KnowledgeService implements IKnowledgeService { else this.options.logger?.warn?.(report); } + /** The deployment's effective tenancy posture, or `undefined` when no resolver is wired. Throws what the resolver throws. */ + private async readTenancyPosture(): Promise { + return this.options.resolveTenancyPosture ? await this.options.resolveTenancyPosture() : undefined; + } + + /** + * [ADR-0161 K8, item 9] Pair each source {@link admitSources} admitted for + * a caller that is NOT the system identity (admission's own bypass answers + * that one before this runs) with the organizations its search hands the + * adapter (`searchOrganizationIds`): computed here, from the caller's + * execution context and the deployment's posture, never from anything the + * caller passes. A `file` / `http` source gets none — its documents carry no + * organization, and the adapter owns its ACL. + * + * The posture is read once per search, and only when an `object` source is + * admitted. A posture that cannot be read leaves every `object` source + * unsearched for this call (fail-closed: whether a wall stands is unknown), + * reported at `error`, `warn` as the fallback. + */ + private async scopeByOrganization( + sources: KnowledgeSource[], + ctx: ExecutionContext, + ): Promise> { + if (!sources.some((source) => source.source.kind === 'object')) { + return sources.map((source) => ({ source })); + } + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + const report = + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no object source is searched ` + + 'for this caller (fail-closed).'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + return sources.filter((source) => source.source.kind !== 'object').map((source) => ({ source })); + } + return sources.map((source) => { + if (source.source.kind !== 'object') return { source }; + const organizationIds = searchOrganizationIds( + ctx, + posture, + this.schemaFor((source.source as ObjectKnowledgeSource).object), + ); + return organizationIds === undefined ? { source } : { source, organizationIds }; + }); + } + private sourcesForObject(object: string): KnowledgeSource[] { return objectSourcesFor([...this.sources.values()], object); } @@ -1114,17 +1214,29 @@ export async function purgeDocuments(input: PurgeDocumentsInput): Promise): string { - const body = stableJson({ content: doc.content, title: doc.title ?? null, metadata: doc.metadata ?? {} }); +export function computeDocHash(doc: Pick): string { + const body = stableJson({ + content: doc.content, + title: doc.title ?? null, + metadata: doc.metadata ?? {}, + ...(doc.organizationId === undefined ? {} : { organizationId: doc.organizationId }), + }); return `${DOC_HASH_VERSION}:${createHash('sha256').update(body).digest('hex')}`; } @@ -1174,12 +1286,19 @@ export function documentIdFor(sourceId: string, recordId: string): string { * served to every reader the source admits, and a mask placeholder is no * content. Without a schema nothing is withheld here (the engine's event body * and read path still apply their own projection upstream). + * + * `posture` (the deployment's effective tenancy posture) decides the + * document's `organizationId` (ADR-0161 K8, item 9): the record's + * `organization_id` under `group` and `isolated`, none under `single` or with + * no posture — `documentOrganizationId`. The organization enters `docHash` + * only when the document carries one. */ export function recordToDocument( source: KnowledgeSource, objSource: ObjectKnowledgeSource, record: Record, schema?: unknown, + posture?: TenancyPosture, ): KnowledgeDocument { const withheld = new Set([ ...collectCredentialWriteResponseFields(schema), @@ -1212,6 +1331,8 @@ export function recordToDocument( title: typeof record.title === 'string' && !withheld.has('title') ? record.title : undefined, metadata, }; + const organizationId = documentOrganizationId(record, posture); + if (organizationId !== undefined) doc.organizationId = organizationId; doc.docHash = computeDocHash(doc); return doc; } diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index e0f71586f32..68fb890e4fd 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -128,7 +128,7 @@ export interface ObjectAdmission { } /** Field names an object declares (record or array form); `undefined` when the schema carries none. */ -function declaredFields(schema: unknown): Array<[string, unknown]> | undefined { +export function declaredFields(schema: unknown): Array<[string, unknown]> | undefined { const fields = (schema as { fields?: unknown } | null | undefined)?.fields; if (Array.isArray(fields)) { return fields diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index b5b03dba734..3d5368037b4 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -10,7 +10,7 @@ * runKnowledgeAdapterContract({ * name: 'knowledge-memory', * makeAdapter: () => new KnowledgeMemoryAdapter(), - * implements: { listDocuments: true }, + * implements: { listDocuments: true, organizationIds: true }, * }); * ``` * @@ -21,16 +21,23 @@ * optional `listDocuments` (page boundaries at 0, one page and one page + 1; * `docHash` returned as stored); and, through a real `KnowledgeService` over a * small data-engine double, the skip of unchanged documents and the purge of - * documents the source no longer has. + * documents the source no longer has; and the organization filter + * (ADR-0161 K8, item 9) — on the adapter alone, and through a real + * `KnowledgeService` under the `isolated`, `group` and `single` postures. * * Every optional member is DECLARED by the caller in `implements`, and the * suite asserts the declaration against the adapter: a member an adapter lacks * runs the case that pins the service's behaviour without it, never nothing. + * `organizationIds` is a search option, not a method, so its declaration is + * asserted by behaviour: the cases it turns on fail for an adapter that + * ignores the option. */ import { describe, expect, it } from 'vitest'; -import type { IDataEngine, IKnowledgeAdapter, AdapterContext } from '@objectstack/spec/contracts'; +import type { IDataEngine, IKnowledgeAdapter, AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { TenancyPosture } from '@objectstack/spec/security'; import { KnowledgeService } from './knowledge-service.js'; /** Input of {@link runKnowledgeAdapterContract}. */ @@ -46,6 +53,12 @@ export interface KnowledgeAdapterContractOptions { /** The optional members this adapter implements; checked against the adapter. */ implements: { listDocuments: boolean; + /** + * The adapter's search honours `AdapterSearchOptions.organizationIds` + * (ADR-0161 K8, item 9): it ranks only the documents of the organizations + * it is handed, filtering before it ranks. + */ + organizationIds: boolean; }; } @@ -65,7 +78,13 @@ function ctxOf(source: KnowledgeSource): AdapterContext { return { source, reason: 'manual' }; } -function doc(source: KnowledgeSource, n: string, content: string, docHash?: string): KnowledgeDocument { +function doc( + source: KnowledgeSource, + n: string, + content: string, + docHash?: string, + organizationId?: string, +): KnowledgeDocument { return { id: `${source.id}:${n}`, sourceId: source.id, @@ -74,6 +93,7 @@ function doc(source: KnowledgeSource, n: string, content: string, docHash?: stri title: `Title ${n}`, metadata: { status: 'published' }, ...(docHash === undefined ? {} : { docHash }), + ...(organizationId === undefined ? {} : { organizationId }), }; } @@ -101,12 +121,16 @@ type Row = Record; /** * A data-engine double serving `find` / `count` the way the knowledge service - * calls them (the paged walk and the membership re-read), over rows the case - * mutates directly. It refuses — by a throw — any `where` shape it does not - * implement, so a service change it cannot answer turns the suite red rather - * than being answered wrongly. + * calls them (the paged walk, the membership re-read and the search's + * permission re-read), over rows the case mutates directly. It refuses — by a + * throw — any `where` shape it does not implement, so a service change it + * cannot answer turns the suite red rather than being answered wrongly. + * + * The permission re-read (`where: { id: { $in } }`, the caller's context in + * the query) answers the rows `wall` admits for that context; without a + * `wall`, every row. */ -function rowsEngine(rows: Row[]): IDataEngine { +function rowsEngine(rows: Row[], wall?: (row: Row, context: ExecutionContext) => boolean): IDataEngine { const matches = (row: Row, where: Record | undefined): boolean => { if (!where) return true; for (const [key, value] of Object.entries(where)) { @@ -129,7 +153,17 @@ function rowsEngine(rows: Row[]): IDataEngine { return true; }; return { - find: async (_object: string, query: { where?: Record; limit?: number }) => { + find: async ( + _object: string, + query: { where?: Record; limit?: number; context?: ExecutionContext }, + ) => { + const inIds = (query?.where?.id as { $in?: unknown } | undefined)?.$in; + if (query?.context !== undefined && Array.isArray(inIds) && Object.keys(query.where ?? {}).length === 1) { + const ctx = query.context; + return rows + .filter((r) => inIds.includes(r.id) && (wall === undefined || wall(r, ctx))) + .map((r) => ({ id: r.id })); + } if (typeof query?.limit !== 'number' || !(query.limit > 0)) throw new Error('engine double: an unbounded find'); return rows .filter((r) => matches(r, query.where)) @@ -142,10 +176,27 @@ function rowsEngine(rows: Row[]): IDataEngine { } as unknown as IDataEngine; } -/** A `KnowledgeService` over `adapter` and `rows`, with the adapter's `upsert` counted. */ -async function serviceOver(make: () => IKnowledgeAdapter | Promise, rows: Row[], source: KnowledgeSource) { +/** What {@link serviceOver} composes beside the adapter and the rows. */ +interface ServiceSetup { + /** The deployment's tenancy posture, read at each call; absent → no `tenancy` service. */ + posture?: () => TenancyPosture | undefined; + /** The permission re-read's wall ({@link rowsEngine}). */ + wall?: (row: Row, context: ExecutionContext) => boolean; +} + +/** + * A `KnowledgeService` over `adapter` and `rows`, with the adapter's `upsert` + * counted and the options of every `search` it is handed recorded. + */ +async function serviceOver( + make: () => IKnowledgeAdapter | Promise, + rows: Row[], + source: KnowledgeSource, + setup: ServiceSetup = {}, +) { const adapter: IKnowledgeAdapter = await make(); const upserted: string[][] = []; + const searched: AdapterSearchOptions[] = []; // Delegation, not a prototype proxy: an adapter with `#private` fields only // answers when its methods are called on the adapter itself. const counting: IKnowledgeAdapter = { @@ -154,16 +205,56 @@ async function serviceOver(make: () => IKnowledgeAdapter | Promise d.id)); return adapter.upsert(docs, ctx); }, - search: (query, searchOpts) => adapter.search(query, searchOpts), + search: (query, searchOpts) => { + searched.push(searchOpts); + return adapter.search(query, searchOpts); + }, delete: (ids, ctx) => adapter.delete(ids, ctx), ...(typeof adapter.listDocuments === 'function' ? { listDocuments: (ctx: AdapterContext, listOpts: { cursor?: string; limit: number }) => adapter.listDocuments!(ctx, listOpts) } : {}), }; - const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + const posture = setup.posture; + const svc = new KnowledgeService({ + dataEngine: rowsEngine(rows, setup.wall), + ...(posture === undefined ? {} : { resolveTenancyPosture: async () => posture() }), + }); svc.registerAdapter('under_test', counting); svc.registerSource(source); - return { adapter, svc, upserted }; + return { adapter, svc, upserted, searched }; +} + +/** The last element of `list`, or `undefined` when it is empty. */ +function lastOf(list: readonly T[]): T | undefined { + return list.length === 0 ? undefined : list[list.length - 1]; +} + +/** Two organizations' rows in one source: `rb` (organization B) outranks `ra` (A) for {@link ORG_QUERY}. */ +const orgRows = (): Row[] => [ + { id: 'ra', body: 'alpine meadow harbour', status: 'published', organization_id: 'org_a' }, + { id: 'rb', body: 'alpine meadow alpine meadow', status: 'published', organization_id: 'org_b' }, +]; +const ORG_QUERY = 'alpine meadow'; + +/** A person in organization A only, active there. */ +const CALLER_A: ExecutionContext = { + userId: 'u_a', tenantId: 'org_a', accessible_org_ids: ['org_a'], positions: [], permissions: [], systemPermissions: [], isSystem: false, +} as ExecutionContext; +/** A person in organizations A and C, active in C: under `group` they reach A; under `isolated` only C. */ +const CALLER_AC: ExecutionContext = { + userId: 'u_ac', tenantId: 'org_c', accessible_org_ids: ['org_a', 'org_c'], positions: [], permissions: [], systemPermissions: [], isSystem: false, +} as ExecutionContext; +const SYSTEM: ExecutionContext = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as ExecutionContext; + +/** + * The wall each posture puts on the permission re-read (ADR-0105 D1), as the + * double's `wall`. The service never re-reads for the system identity, so the + * wall is asked about persons only. + */ +function wallOf(posture: TenancyPosture): (row: Row, context: ExecutionContext) => boolean { + if (posture === 'isolated') return (row, ctx) => row.organization_id === ctx.tenantId; + if (posture === 'group') return (row, ctx) => (ctx.accessible_org_ids ?? []).includes(String(row.organization_id)); + return () => true; } const rowsOf = (n: number): Row[] => @@ -219,6 +310,110 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); }); + if (opts.implements.organizationIds) { + describe('organizationIds (ADR-0161 K8, item 9)', () => { + /** B's document outranks A's; a third document carries no organization. */ + async function seeded(): Promise<{ adapter: IKnowledgeAdapter; a: KnowledgeSource }> { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('org'); + await adapter.upsert( + [ + doc(a, 'a1', 'alpine meadow harbour', undefined, 'org_a'), + doc(a, 'b1', 'alpine meadow alpine meadow', undefined, 'org_b'), + doc(a, 'n1', 'alpine meadow', undefined), + ], + ctxOf(a), + ); + return { adapter, a }; + } + + it("ranks only the documents of the organizations it is handed, filtering before it ranks", async () => { + const { adapter, a } = await seeded(); + // topK 1: a filter applied after ranking would keep B's better hit and drop it, answering nothing. + const top = await adapter.search(ORG_QUERY, { source: a, topK: 1, organizationIds: ['org_a'] }); + expect(top.map((h) => h.documentId)).toEqual([`${a.id}:a1`]); + const all = await adapter.search(ORG_QUERY, { source: a, topK: 5, organizationIds: ['org_a'] }); + expect(all.map((h) => h.documentId)).toEqual([`${a.id}:a1`]); + }); + + it('ranks the documents of every organization in the set, and none stored without one', async () => { + const { adapter, a } = await seeded(); + const hits = await adapter.search(ORG_QUERY, { source: a, topK: 5, organizationIds: ['org_a', 'org_b'] }); + expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.id}:a1`, `${a.id}:b1`]); + }); + + it('an empty set ranks nothing — it is never read as "no filter"', async () => { + const { adapter, a } = await seeded(); + expect(await adapter.search(ORG_QUERY, { source: a, topK: 5, organizationIds: [] })).toEqual([]); + }); + + it('without the option every document is ranked, as before', async () => { + const { adapter, a } = await seeded(); + const hits = await adapter.search(ORG_QUERY, { source: a, topK: 5 }); + expect(hits.map((h) => h.documentId).sort()).toEqual([`${a.id}:a1`, `${a.id}:b1`, `${a.id}:n1`]); + }); + }); + } + + describe('the organization filter through KnowledgeService.search', () => { + for (const posture of ['isolated', 'group'] as const) { + it(`${posture}: a search from organization A never ranks or returns B's documents`, async () => { + const rows = orgRows(); + const source = objectSource(`org_${posture}`); + const h = await serviceOver(make, rows, source, { posture: () => posture, wall: wallOf(posture) }); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + const caller = posture === 'isolated' ? CALLER_A : CALLER_AC; + const hits = await h.svc.search(ORG_QUERY, { topK: 1, executionContext: caller }); + // The service hands the adapter the caller's organizations, by the posture. + expect(lastOf(h.searched)?.organizationIds).toEqual(posture === 'isolated' ? ['org_a'] : ['org_a', 'org_c']); + expect(hits.map((x) => x.documentId)).not.toContain(`${source.id}:rb`); + if (opts.implements.organizationIds) { + // Filtered before ranking: B's better document does not take A's place. + expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:ra`]); + } + }); + } + + it('isolated: a caller with no active organization is handed an empty set, and gets nothing', async () => { + const source = objectSource('org_none'); + const h = await serviceOver(make, orgRows(), source, { posture: () => 'isolated', wall: wallOf('isolated') }); + await h.svc.reindexSource(source.id); + const nobody = { ...CALLER_A, tenantId: undefined, accessible_org_ids: [] } as ExecutionContext; + expect(await h.svc.search(ORG_QUERY, { topK: 5, executionContext: nobody })).toEqual([]); + expect(lastOf(h.searched)?.organizationIds).toEqual([]); + }); + + it('single posture and the system identity: no filter is handed, and the results are as before', async () => { + const source = objectSource('org_single'); + const single = await serviceOver(make, orgRows(), source, { posture: () => 'single' }); + await single.svc.reindexSource(source.id); + const hits = await single.svc.search(ORG_QUERY, { topK: 1, executionContext: CALLER_A }); + expect(lastOf(single.searched)).not.toHaveProperty('organizationIds'); + expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:rb`]); + + const walled = await serviceOver(make, orgRows(), source, { posture: () => 'isolated', wall: wallOf('isolated') }); + await walled.svc.reindexSource(source.id); + const asSystem = await walled.svc.search(ORG_QUERY, { topK: 1, executionContext: SYSTEM }); + expect(lastOf(walled.searched)).not.toHaveProperty('organizationIds'); + expect(asSystem.map((x) => x.documentId)).toEqual([`${source.id}:rb`]); + }); + + if (opts.implements.organizationIds) { + it('a document indexed without its organization is not ranked behind a wall until a complete reindex writes it again', async () => { + let posture: TenancyPosture = 'single'; + const source = objectSource('org_upgrade'); + const h = await serviceOver(make, orgRows(), source, { posture: () => posture, wall: wallOf('isolated') }); + await h.svc.reindexSource(source.id); // under `single`: no document carries an organization + posture = 'isolated'; + expect(await h.svc.search(ORG_QUERY, { topK: 5, executionContext: CALLER_A })).toEqual([]); + // The organization enters the hash, so the reindex writes both documents again rather than skipping them. + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + const hits = await h.svc.search(ORG_QUERY, { topK: 5, executionContext: CALLER_A }); + expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:ra`]); + }); + } + }); + if (opts.implements.listDocuments) { describe('listDocuments', () => { it.each([ diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 29dda225bd9..c21ad15359c 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -249,6 +249,7 @@ "ai/KnowledgeDocument:docHash", "ai/KnowledgeDocument:id", "ai/KnowledgeDocument:metadata", + "ai/KnowledgeDocument:organizationId", "ai/KnowledgeDocument:permissions", "ai/KnowledgeDocument:sourceId", "ai/KnowledgeDocument:sourceRecordId", diff --git a/packages/spec/src/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index 7ef0f986574..c83d3aac22e 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -49,8 +49,25 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ */ permissions: z.array(z.string()).optional(), /** - * A hash of the assembled document — its content, title and metadata, in a - * stable key order, behind a version prefix (ADR-0161 K8, item 2). Set by + * The organization the document belongs to (ADR-0161 K8, item 9). Set by the + * knowledge service when it assembles a document from a record: the + * record's `organization_id`, under a walled tenancy posture (`group` or + * `isolated`, ADR-0105 D1). Absent for `file` / `http` sources, under the + * `single` posture, and for a record that carries no organization; a + * caller-supplied value is refused by `indexDocument`. Stored by the adapter + * and read by its search: when the search is handed + * `AdapterSearchOptions.organizationIds`, only documents whose organization + * is in that set are ranked, so a document without one is not. An adapter + * that stores `docHash` stores `organizationId` from the same version on; + * otherwise, once it starts reading this field, a complete reindex skips its + * documents and a walled search never ranks them. + */ + organizationId: z.string().optional() + .describe('Organization of the record the document was assembled from; set by the knowledge service under a walled tenancy posture'), + /** + * A hash of the assembled document — its content, title and metadata, and its + * `organizationId` when it has one, in a stable key order, behind a version + * prefix (ADR-0161 K8, item 2). Set by * the knowledge service on every document it hands an adapter; a * caller-supplied value is refused by `indexDocument`. Stored by the adapter * and returned as stored by `listDocuments`; an unchanged hash lets a @@ -58,7 +75,7 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ * or alter it. */ docHash: z.string().optional() - .describe('Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter'), + .describe('Service-computed hash of the assembled document (content, title, metadata, and organizationId when set); stored and returned as stored by the adapter'), })); /** diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 6c415fc0093..a50365d5e8f 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -45,6 +45,30 @@ export interface AdapterSearchOptions { topK: number; /** Adapter-specific filter (e.g. `{ status: 'active' }`). */ filter?: Record; + /** + * The caller's organizations (ADR-0161 K8, item 9), computed by the knowledge + * service from the caller's identity and the deployment's tenancy posture + * (ADR-0105 D1) — never taken from a caller's input: under `isolated` the + * caller's active organization, under `group` the organizations the caller + * holds a membership in. + * + * - **Absent** (`undefined`): no organization filter — the `single` posture, + * the system identity, a `file` / `http` source, an object outside + * tenancy. Rank every document of the source, as before this member. + * - **Present**: rank only the documents whose + * `KnowledgeDocument.organizationId` is in the set, and filter BEFORE + * ranking, so `topK` is filled from those documents alone. A document + * stored without an `organizationId` (one indexed before this member + * existed, until a complete reindex writes it again) is not ranked. + * - **Empty** (`[]`): rank nothing — a caller with no organization behind a + * wall. Never read as "no filter". + * + * A ranking scope, not the access decision: the service still re-reads every + * object-source hit as the caller. An adapter that ignores this member keeps + * working; other organizations' documents then take ranking places that the + * re-read empties. + */ + organizationIds?: string[]; /** Trace id for correlation. */ traceId?: string; }