Skip to content

Commit f9fda2a

Browse files
feat(service-knowledge): documents carry their organization, and search hands the adapter the caller's organizations (#37256)
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ Fixes #37097 repo:objectstack#4 · os-justin · session_01QSeKYkS1d2QkEUgqhneuU1 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. `content/docs/protocol/knowledge.mdx` gains the members and an "Organization scope" section here. ## 维护者速读 - 多组织部署里,知识检索只在提问人所属组织的文档里排名,别的组织的文档不再挤占前几名;单组织部署无感。 - 属于「知识检索平台化」专题第二阶段:索引文档记下所属组织,检索时由平台按部署的租户形态算出提问人的组织交给存储先过滤。 - 出错时最坏是某些文档在检索里排不上(尚未重建索引的旧文档在多组织形态下要等一次完整重建);能否返回仍由按提问人身份回查记录决定,可直接撤回本改动。 - 无。 ## What changes ADR-0161 K8, item 9, with `knowledge-memory` as its first reader: 1. **`KnowledgeDocument.organizationId?`** (`packages/spec/src/ai/knowledge-document.zod.ts`). The service sets it when it assembles a document from a record: the record's `organization_id` under the `group` and `isolated` postures. It is absent under `single`, for `file` / `http` sources and for a record with no organization. `indexDocument` refuses a caller-supplied value, as it refuses a caller-supplied `docHash`. The TSDoc also says that an adapter storing `docHash` stores `organizationId` from the same version on. 2. **`AdapterSearchOptions.organizationIds?`** (`packages/spec/src/contracts/knowledge-adapter.ts`). The service computes it per `object` source in `knowledge-organization-scope.ts` and derives nothing itself: - the posture is the effective one, `classifyAdmissionTenancyPosture` over the kernel's `tenancy` service. `KnowledgeServicePlugin` wires it as the new `resolveTenancyPosture` option, next to `resolveSecurity`; the mount logic is untouched. The wiring is pinned through real kernels (`LiteKernel` and `ObjectKernel`): walled, no `tenancy` service, and a `tenancy` service that cannot be read; - the organization set is `computeTenantLayer0Verdict` (`@objectstack/core`) for the source's object, over the context's `tenantId` / `accessible_org_ids`. `isolated` gives the active organization and `group` the deduplicated membership set. A `deny` verdict becomes `[]`; `none` (an object outside tenancy, or with no `organization_id` column) gives no filter; - no filter under `single`, for the system identity and for `file` / `http` sources. The TSDoc spells out the three cases: absent means no filter, a set means filter before ranking, `[]` means rank nothing (never "no filter"). 3. **`knowledge-memory`** stores `organizationId` and filters by `organizationIds` before it scores, so `topK` is filled from in-scope documents only. 4. **The permission re-read is unchanged** and remains the access decision. Nothing new is logged or returned about how many hits a filter removed. 5. **`docHash`** covers `organizationId` only when the document has one. `DOC_HASH_VERSION` stays `v1`, so a document without an organization hashes byte-for-byte as before (pinned against the old recipe). 6. **A posture that cannot be read** (a `tenancy` service is registered but unreadable): a search leaves every `object` source unsearched for that call and logs at `error`; a reindex stops before writing and returns `ok: false` with the reason. An event sync logs at `warn` with the reason and leaves the stored document as it was (no upsert, no delete; pinned). 7. **Contract suite** (`@objectstack/service-knowledge/testing`): `implements.organizationIds` is required, which is fine because the suite has not been released yet. It adds adapter-only cases and cases through a real `KnowledgeService` under `isolated`, `group` and `single`, plus the upgrade case for documents indexed before this change. ### PM mechanism assumptions, measured - **Computed server-side only.** `KnowledgeSearchOptions` has no organization member, and the service builds `organizationIds` itself. A caller's opaque `filter: { organizationIds: [...] }` stays inside `filter` (pinned), and `search_knowledge`'s closed input set refuses an `organizationIds` argument (pinned). The only callers are the MCP bridges through `knowledgeTools()`; no REST route reaches `search`. - **`[]` and absent are different.** `[]` filters to nothing in the TSDoc, in `knowledge-memory` and in the suite. Under `isolated` with no active organization, and under `group` with no membership, the adapter is handed `[]` (pinned). - **Documents indexed before this change** carry no `organizationId`. Behind a wall a filtered search excludes them until a complete reindex writes them again. Their hash changes once the organization is included, so that reindex does not skip them. Under `single` nothing changes. This is documented in the TSDoc, the protocol doc and the changeset, and tested in the contract suite ("a document indexed without its organization is not ranked behind a wall until a complete reindex writes it again"). - **`runKnowledgeAdapterContract` was extended**, not a memory-only test. ## Tests <details><summary>Local runs on the final head 6e978db (origin/main d62f9e9 merged; two commits since 3df745d add tests and a TSDoc sentence)</summary> - `pnpm --filter @objectstack/knowledge-memory exec vitest run`: Test Files 2 passed, Tests 29 passed. - `pnpm --filter @objectstack/service-knowledge exec vitest run`: Test Files 8 passed, Tests 197 passed. - `pnpm --filter @objectstack/service-knowledge --filter @objectstack/knowledge-memory run typecheck`: exit 0 (tsc + test-typecheck, 0 debt). - `pnpm --filter @objectstack/spec build && … check:generated`: "All 14 generated artifacts are up to date". Before the merge, one artifact was stale (`check:docs`) and was regenerated with `--fix`. That diff is the `organizationId` row and the `docHash` description in `content/docs/references/ai/knowledge-document.mdx`. `authorable-surface/ai.json` gained `ai/KnowledgeDocument:organizationId` from the spec build. </details> <details><summary>Derived gate families (dispatch-gates --commands, 117), with --ran reconciliation</summary> - Run at a8d8915: 113 exit 0. `pnpm check:system-context-census` exited 1 because the new organization scoping held two system-identity elevation reads with no row on the system-context page. Fixed at 44494ec by moving the scoping under `admitSources`' existing system bypass (row 46). The system identity's search therefore skips the organization filter through the one read the page already documents, and the census reads OK (202 sites, register matches). - Re-run at 44494ec, all exit 0: system-context-census, startup-registry-verdict, type-check-coverage, type-check-debt, test-source-alias, cross-package-test-inputs, undeclared-dep-imports, issue-citations, optional-error-sink, logger-receiver-detach, nul-bytes, doc-authoring, engine-double-contract, tenant-chokepoint, tenant-audit-census, org-identifier. - NOT MEASURED (exit 3, prerequisite): `check-plugin-teardown-shape.mjs --self-test` needs a deeper clone (the same exit 3 on the main base d7f299c); `check:skill-examples` needs `@objectstack/client-react` built; `check:dual-build-cjs-loads` needs every package's dist. These are left to CI. - `dispatch-gates --ran`: 117 derived, 114 run, 3 NOT-MEASURED, 0 UNRUN. - After 3df745d only a test file and a TSDoc comment changed; the full set ran in CI at 6e978db (60 success, 10 skipped, 0 failed). </details> <details><summary>Ablations (scripts/ablation-replace.mjs; each mutation proven on disk and restored to the HEAD blob)</summary> - Memory adapter filter disabled (`organizations` forced `undefined`): 6 contract cases red (the 3 adapter-only filter cases, both service cases under isolated and group, and the upgrade case). Restored to blob 70dc64b. - `organizationId` dropped from the hashed body: 2 red (the contract upgrade case, and the service hash pin). Restored to fe7502a. - The service stops handing `organizationIds` to the adapter: 4 contract cases and 5 service cases red. Restored to fe7502a. - The plugin's `resolveTenancyPosture` wiring replaced by `async () => undefined`: 3 service cases red (both walled kernel cases and the unreadable case); the no-tenancy case stays green. Restored. </details> ## Acceptance notes - **K8 item 2's wording.** It lists the hashed parts as "content, title, metadata". Here the hash also covers `organizationId`, but only when the document has one. Without that, a complete reindex would skip every document indexed before this change, and those documents would never gain their organization behind a wall. Documents without an organization keep their exact `v1` hash. The contract review (7157191417, M1) asks for a dated note on ADR-0161 to land first; that note is PR #37263, merged first as `8032d958f2`. - The object facts handed to `computeTenantLayer0Verdict` come from the engine's `getSchema`: `tenancy.enabled: false` or `systemFields.tenant: false`, and whether an `organization_id` field exists. Unknown schema means the object is treated as walled. External (federated) objects are not special-cased, so `externalOrganizationScopeUndeclared` is `false`. Platform-admin crossing is not applied to ranking (`isPlatformAdmin: false`). The re-read still decides access either way. - `recordToDocument` takes the posture as an optional fifth argument, so existing calls behave as before. - The system-context page's row 46 ("Knowledge search returns hits unfiltered, and searches every source") still describes the system bypass accurately: through `admitSources`, the same bypass now also skips the organization filter. The row's prose does not mention organizations. The page is outside this card's file surface, so it is left unchanged and its owner can choose to add that. ## Verification Two-minute check: `pnpm --filter @objectstack/knowledge-memory exec vitest run src/__tests__/contract.test.ts` should report 21 tests passed, including "isolated: a search from organization A never ranks or returns B's documents" and "group: …". Read first: 1. `packages/services/service-knowledge/src/knowledge-organization-scope.ts`: the posture-to-organizations mapping (risk: a wrong verdict input widens or empties the ranking scope). 2. `packages/services/service-knowledge/src/knowledge-service.ts`: `scopeByOrganization`, plus `computeDocHash` / `recordToDocument` (risk: the hash change decides what a reindex rewrites). 3. `packages/plugins/knowledge-memory/src/index.ts`, `search` (risk: filtering after scoring instead of before). --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYkS1d2QkEUgqhneuU1)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a7292a5 commit f9fda2a

15 files changed

Lines changed: 899 additions & 44 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-knowledge': patch
4+
'@objectstack/knowledge-memory': patch
5+
---
6+
7+
feat(service-knowledge): knowledge documents carry their organization, and a search hands the adapter the caller's organizations so it ranks only their documents
8+
9+
Clause-②: yes
10+
Metadata-protocol: added
11+
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.
12+
13+
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.
14+
15+
New, both optional, in `@objectstack/spec`:
16+
17+
- `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).
18+
- `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.
19+
20+
`docHash` now covers `organizationId` when a document has one. A document without one hashes exactly as before, so nothing changes under `single`.
21+
22+
`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.
23+
24+
`@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`.
25+
26+
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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -158,12 +158,19 @@ registers itself with that name. Adapter config (endpoint, dataset id,
158158
Canonical shapes shared by every adapter:
159159

160160
- `KnowledgeDocument` — one logical document (`id`, `sourceId`,
161-
`sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`).
162-
`docHash` is a hash of the assembled document — content, title and
163-
metadata, in a stable key order, behind a version prefix (`v1:`). The
164-
service computes it on every document it hands an adapter, and
165-
`indexDocument` refuses a document that already carries one; the adapter
166-
stores it and returns it as stored, and never computes or alters it.
161+
`sourceRecordId?`, `content`, `metadata`, `permissions?`,
162+
`organizationId?`, `docHash?`). `organizationId` is the organization of
163+
the record the document was assembled from: the service sets it from the
164+
record's `organization_id` under a walled tenancy posture (`group` or
165+
`isolated`), and leaves it absent under `single`, for `file` / `http`
166+
sources and for a record with no organization — see
167+
[Organization scope](#organization-scope). `docHash` is a hash of the
168+
assembled document — content, title and metadata, and the organization
169+
when the document has one, in a stable key order, behind a version prefix
170+
(`v1:`). The service computes both on every document it hands an adapter,
171+
and `indexDocument` refuses a document that already carries either; the
172+
adapter stores them and returns `docHash` as stored, and never computes or
173+
alters either.
167174
- `KnowledgeChunk` — adapter-produced chunk of a document. The framework
168175
does **not** chunk; adapters do.
169176
- `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`,
@@ -231,7 +238,10 @@ in their plugin options.
231238

232239
Every member past `upsert` / `search` / `delete` is optional (ADR-0161
233240
K8): an adapter that lacks one keeps working, and the service does what it
234-
did before that member existed. `listDocuments` lists the documents the
241+
did before that member existed. `AdapterSearchOptions.organizationIds` is the
242+
caller's organizations; an adapter that reads it ranks only those
243+
organizations' documents, filtering before it ranks — see
244+
[Organization scope](#organization-scope). `listDocuments` lists the documents the
235245
adapter holds for a source, a page of at most `limit` entries at a time, each
236246
with the `docHash` it was stored with; `nextCursor` is absent once the
237247
listing is complete. A document written while a listing runs may be missing
@@ -246,13 +256,14 @@ import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/test
246256
runKnowledgeAdapterContract({
247257
name: 'my-adapter',
248258
makeAdapter: () => new MyAdapter(/* a fresh, empty store */),
249-
implements: { listDocuments: true },
259+
implements: { listDocuments: true, organizationIds: true },
250260
});
251261
```
252262

253263
It covers upsert / search / delete, `listDocuments` page boundaries and
254-
`docHash` round-trips, and — through a real `KnowledgeService` — the skip and
255-
the purge below. `implements` declares the optional members, and the suite
264+
`docHash` round-trips, the organization filter, and — through a real
265+
`KnowledgeService` — the skip and the purge below, and a search from one
266+
organization under `isolated` and `group`. `implements` declares the optional members, and the suite
256267
checks the declaration against the adapter. `./testing` is a test-only,
257268
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
258269
`knowledge-memory` runs it as the reference implementation.
@@ -329,6 +340,42 @@ This is the same pattern as the existing permission-aware data tools
329340
No matter how aggressive an adapter's retrieval is, the user never
330341
sees a chunk extracted from a record they can't read.
331342

343+
### Organization scope
344+
345+
In a deployment with more than one organization, the adapter ranks only the
346+
caller's organizations' documents (ADR-0161 K8, item 9). Without that, the
347+
best-ranked passages could all belong to another organization, and the
348+
re-read above would empty those places. The filter decides what is ranked;
349+
the re-read still decides what is returned.
350+
351+
- **At assembly.** Under the `group` and `isolated` tenancy postures, a
352+
document built from a record carries the record's `organization_id` as
353+
`organizationId`. Under `single`, for `file` / `http` sources and for a
354+
record with no organization, it carries none.
355+
- **At search.** For each `object` source, the service hands the adapter
356+
`organizationIds`, the organizations the tenancy wall gives the caller for
357+
that object: under `isolated` the caller's active organization, under
358+
`group` every organization the caller holds a membership in. The service
359+
computes the set from the caller's execution context and the deployment's
360+
posture. No tool argument or search option supplies it, and
361+
`search_knowledge` refuses an `organizationIds` argument.
362+
- **No filter** (`organizationIds` absent) under `single`, for the system
363+
identity, for a `file` / `http` source, and for an object outside the wall
364+
(tenancy disabled, or no `organization_id` column). The adapter ranks every
365+
document of the source, as before.
366+
- **An empty set** (`[]`) is a caller with no organization behind a wall, for
367+
example no active organization under `isolated`. The adapter ranks
368+
nothing; an empty set never means "no filter".
369+
- **A posture that cannot be read**: a search leaves every `object` source
370+
unsearched for that call and logs it at `error`. A reindex stops before
371+
writing anything and says why.
372+
373+
**Documents indexed before this change** carry no `organizationId`. Behind a
374+
wall, a filtered search does not rank them until a complete reindex writes
375+
them again. The organization is part of `docHash`, so the reindex does not
376+
skip them. Under `single` nothing changes: a document without an organization
377+
hashes as before, and the reindex skips it as before.
378+
332379
### Source admission: exposure and field-level rules
333380

334381
A passage is built at index time, under a system context, from every

‎content/docs/references/ai/knowledge-document.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ const result = KnowledgeChunkSchema.parse(data);
6060
| **title** | `string` | optional | |
6161
| **metadata** | `Record<string, any>` | optional (default: `{}`) | |
6262
| **permissions** | `string[]` | optional | |
63-
| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter |
63+
| **organizationId** | `string` | optional | Organization of the record the document was assembled from; set by the knowledge service under a walled tenancy posture |
64+
| **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 |
6465

6566

6667
---

‎packages/plugins/knowledge-memory/src/__tests__/contract.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@ import { KnowledgeMemoryAdapter } from '../index';
1010
runKnowledgeAdapterContract({
1111
name: 'knowledge-memory',
1212
makeAdapter: () => new KnowledgeMemoryAdapter('under_test'),
13-
implements: { listDocuments: true },
13+
implements: { listDocuments: true, organizationIds: true },
1414
});

‎packages/plugins/knowledge-memory/src/index.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
2727
* stores each document's `docHash` as given and lists it back as stored, in
2828
* document-id order, the cursor being the last id of the page before. It runs
2929
* the contract suite of `@objectstack/service-knowledge/testing`.
30+
*
31+
* The first reader of the organization filter (ADR-0161 K8, item 9): it
32+
* stores each document's `organizationId` as given and, when a search is
33+
* handed `organizationIds`, ranks only the documents whose organization is in
34+
* that set — the filter runs before the scoring, so `topK` is filled from them
35+
* alone. An empty set ranks nothing; a document stored without an
36+
* organization is not ranked by a filtered search.
3037
*/
3138
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
3239
readonly id: string;
@@ -92,10 +99,17 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
9299
const qNorm = vectorNorm(qVec);
93100
if (qNorm === 0) return [];
94101

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

100114
const scored = filtered.map((c) => ({
101115
chunk: c,
@@ -126,6 +140,8 @@ interface ChunkRecord {
126140
sourceRecordId?: string;
127141
/** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */
128142
docHash?: string;
143+
/** The document's `organizationId`, stored as given (ADR-0161 K8, item 9). */
144+
organizationId?: string;
129145
content: string;
130146
title?: string;
131147
metadata: Record<string, unknown>;
@@ -167,6 +183,7 @@ function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
167183
documentId: doc.id,
168184
sourceRecordId: doc.sourceRecordId,
169185
docHash: doc.docHash,
186+
organizationId: doc.organizationId,
170187
content,
171188
title: doc.title,
172189
metadata: doc.metadata ?? {},

0 commit comments

Comments
 (0)