Skip to content

Commit 7abf25f

Browse files
fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules per source (#36850)
Fixes #36839 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:受限用户(以及代其提问的 AI)检索知识库时,若某个知识源包含他无权查看的字段,或其对象未对接口开放、所属包已停用、是未声明 AI 可读的系统对象,该知识源对他不再返回任何结果;有权限的用户与系统任务不受影响。 - 为什么做:属于「MCP 问数」主线,在知识检索对 MCP 客户开放之前,先堵住低权限用户借 AI 读到其本无权看到的字段内容这一安全缺口。 - 出错会怎样:最坏情况是受限用户检索不到本该能看到的知识源(只会更严,不会更松);改动可直接回滚。 - 要你做什么:无。 ## What changes Option D of the ruling recorded on #36650 (comment 7121194365, quoted in #36839's body): in the knowledge service, at source granularity, fail closed, no new spec key. Governing text: ADR-0090 D10 rule 1, ADR-0049. - **Defect class / location / function.** Missing field-level and API-exposure enforcement on a row-serving door: `KnowledgeService.search` (`packages/services/service-knowledge/src/knowledge-service.ts`) re-checked an object-source hit only with a row read of its id under the caller's context, while the passage it returns is built at index time, under a system context, from every `contentFields` member, the record `title` and the source's `metadataFields`. - **New `knowledge-source-admission.ts`**, asked by a new private `admitSources` step before any adapter is searched, for a non-system caller with a data engine bound, once per (caller, object) per search: 1. disabled package: core's `registryObjectPackageDisabled` over the engine's registry (the predicate the data route and the analytics door ask; no injected hook needed, so no new dependency on metadata-protocol); 2. API exposure: `canServeApiOperation(enable, 'search')` (`@objectstack/spec/data`), the decision and operation the cross-object search asks; 3. `sys_*` objects: served only when `isAiReadExposed` answers true (`enable.aiReadable: true`), the MCP record tools' posture; 4. field gate: every field the source serves (`contentFields`, `'*'` = every declared field except `id`; `metadataFields`; `title`), less the credential-class and `internal` fields `recordToDocument` never indexes, must be in the `security` service's `getQueryableFields` answer; absent it or `undefined`, `getReadableFields` less every `maskingRule` field; with no `security` service, every field except the `maskingRule` ones (the contract's fallback, `ISecurityService.getQueryableFields`). A source failing any gate is not searched for that caller. Queryable rather than readable: a passage carries the unmasked value and the search matches on it. - **Fail closed.** A schema read, package probe or field answer that throws refuses every source over that object (logged at `error`, `warn` as fallback); a `security` service answering neither field question refuses too. The system context bypasses, as it bypasses the row re-check; the no-context and no-engine paths are unchanged (they already drop every object-source hit). - **Wiring.** `KnowledgeServicePlugin` passes a new optional `resolveSecurity` option resolving `security` per search (plugin order free). Only a missing answer or the kernel's not-registered refusal (`isServiceNotRegisteredError`) reads as "no security service"; any other throw from that lookup refuses the object's sources, reported at `error` once per object per search. `KnowledgeFieldSecurity` is exported as a type. - **Objects nobody can judge, and hit origin (review round 1).** A caller with no execution context, or a service with no data engine bound, is searched no `object` source at all (before, an object-source hit with no `sourceRecordId` reached it). An admitted object source's hit with no `sourceRecordId` cannot be re-checked and is dropped. `KnowledgeService.search` drops a hit whose reported `sourceId` names another source than the one searched. Object admissions are asked concurrently, and the `sys_*` posture also reads the schema's own name. - **Not in this PR: `@objectstack/knowledge-ragflow`.** A RAGFlow-side chunk filter added in review round 1 was removed again under the maintainer's ruling recorded on #36839 (comment 7134290286, option B): the documented RAGFlow API returns no chunk metadata, so the filter could not act, and the package is retired whole on its own card. This PR changes nothing in that package. - **Pins and claims brought true.** `row-serving-door-exposure.pin.test.ts` now holds knowledge retrieval BY NAME (`HELD_BY_NAME`: the door imports its decision site, which asks the exposure decision and `getQueryableFields`, and the behaviour pin exists) instead of naming it unconstrained. The `mcp-http-identity` note in `authz-conformance.matrix.ts` states the knowledge-service enforcement its "RLS / FLS / tenant apply exactly as on REST /data" claim relies on once a tool serves knowledge search. `content/docs/protocol/knowledge.mdx` §5 (new "Source admission" subsection), §7.1 and §9 state the gates and the narrowing. `content/docs/permissions/system-context.mdx` row 46 now names `admitSources` (its new system-context bypass read), with the generated register regenerated by `check-system-context-census.mjs --write`. ## Tests - New `packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts` (22), through the real `KnowledgeService`, refusal and preservation per gate: a member who reads the row but not `salary_note` gets no hit from the source naming it and the adapter is never asked to search it, while a manager and the system context get it; `title` and `metadataFields` hidden each refuse; `'*'` refuses on one hidden field and does not ask about credential / `internal` fields; a masked field via the `getReadableFields` fallback; no security service ⇒ `maskingRule` fallback; a throwing field answer and an unanswering service fail closed; the answer is asked once per object; `apiEnabled: false` dropped for an end-user context and kept for the system context; an `apiMethods` whitelist without `search` refused and one with `list` admitted; a disabled package's object dropped and kept for system; a `sys_*` object without `aiReadable` dropped, with it kept; a throwing schema read fails closed; an http source is untouched. Two more drive `KnowledgeServicePlugin` on a real `LiteKernel` with a registered `security` service (refusal + preservation) and without one (fallback admits). - **Red before / green after.** With `knowledge-service.ts` and `knowledge-service-plugin.ts` restored to the base `f77d078d` (blob match confirmed), the new file ran 14 failed / 2 passed (the 2 are pure preservation legs); restored to HEAD (blob match, `git diff HEAD` empty) it runs 16 / 16. - Review round 1 added 6 pins to that file: no context and no engine each search no object source; an admitted object source's hit without `sourceRecordId` is dropped; a hit naming another source is dropped; a `security` lookup throwing anything but the not-registered miss fails closed with one `error` log (system preserved); and `isServiceNotRegisteredError`'s discrimination. Red before: with the service and plugin restored to round-1 head `774652cd63` (the lookup back to swallowing every throw), the file ran 5 failed / 17 passed (the 5 behaviour pins); restores matched HEAD. Three fixtures in `knowledge-service.test.ts` that searched an object source with no context now pass the system context or register the http source their hit names. - `row-serving-door-exposure.pin.test.ts` (core `repo` project) 4 / 4; with `knowledge-service.ts` restored to base, the new held-by-name test is red (1 failed / 3 passed), restored blob matches HEAD. <details><summary>Local runs on head 5cc0e97 (after merging origin/main at 305fe60)</summary> - Under `os-verify-lock`, VERDICT command-exit 0: `pnpm --filter '@objectstack/service-knowledge^...' --filter '@objectstack/lint...' build`, then `@objectstack/service-knowledge` test (5 files / 71 tests), typecheck (`tsc --noEmit` + `check:test-typecheck` OK) and build (`check-dts-emitted` 2/2); core `repo` project `row-serving-door-exposure.pin.test.ts` 4 / 4. - `node scripts/pm/dispatch-gates.mjs --commands` on 5cc0e97: 105 derived; 103 exit 0. NOT MEASURED, PREREQUISITE NOT MET (exit 3; they read dists of packages outside this diff, not built in this worktree): `pnpm --filter @objectstack/spec run check:skill-examples`, `pnpm check:dual-build-cjs-loads`. `--ran` with exit codes: 105 derived, 103 run, 2 NOT-MEASURED, 0 UNRUN. - The merge conflicted on `content/docs/permissions/system-context.mdx` rows 45/46 (main changed row 45, this PR row 46); resolved by keeping both changes, and `check-system-context-census.mjs --write` reported the register already current. - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: exit 0, no anchored file in the change set. </details> ## Acceptance notes - `metadataFields` is gated beside `contentFields` and `title`: a hit's `metadata` serves those values, so leaving them out would keep the same leak; the card's Expected 2 names `contentFields` and `title`. - `title` is required only when the object declares a `title` field (or its schema is unknown), because `recordToDocument` serves the record's `title` whatever the source names. - A `security` service whose field answer is `undefined` on both methods refuses the source (fail closed) rather than falling to the object's own projection. - No published accept set narrows: no spec key, value or schema changes. What narrows is runtime results for restricted callers, stated in the changeset. ## Verification Read first, by risk: `packages/services/service-knowledge/src/knowledge-source-admission.ts` (`admitObject`, `servedFieldsOf`, `admitSourceFields`), the `admitSources` hunk in `knowledge-service.ts`, then the plugin's `resolveSecurity` wiring. Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-source-admission.test.ts` — expect 22 passed. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYoxFNWhVjbZhqgBjKQ)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYoxFNWhVjbZhqgBjKQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9c57bd2 commit 7abf25f

12 files changed

Lines changed: 952 additions & 32 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules before it searches a source
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A knowledge passage is built at index time, under a system context, from every `contentFields` member of its source, the record `title` and the source's `metadataFields`. Knowledge search re-checked only that the caller may read each hit's row, so a caller who could read a row but not one of those fields was served that field's text, and an object the API does not serve was served as passages. `KnowledgeService.search` now decides, for a non-system caller and once per object per search, whether each `object` source may be searched at all:
11+
12+
- the object's owning package is not disabled;
13+
- the spec's exposure decision serves the object for the `search` operation (`enable.apiEnabled: false`, or an `enable.apiMethods` whitelist that does not grant `search`, refuses);
14+
- a `sys_*` object declares `enable.aiReadable: true`;
15+
- every field the source serves (each `contentFields` member, `'*'` meaning every declared field except `id`; each `metadataFields` member; `title`), less the credential-class and `internal` fields an index never carries, is one the caller may query, per the `security` service's `getQueryableFields` (absent it, `getReadableFields` less every field declaring a `maskingRule`; with no `security` service, every field except those declaring a `maskingRule`).
16+
17+
A source that fails any gate is not searched for that caller. Every gate fails closed: a lookup that throws, or a `security` service that answers neither field question, keeps the source out. `KnowledgeServicePlugin` wires the `security` service, resolved per search: a missing answer or the kernel's not-registered refusal reads as "no security service"; any other throw from that lookup (a registration that cannot be used) refuses the sources, reported at `error` once per object per search. A host constructing `KnowledgeService` directly passes it as the new optional `resolveSecurity` option. The system context bypasses the gates, as it bypasses the row re-check.
18+
19+
Three adjacent holes close with it. A caller with no execution context, or a service with no data engine bound, is now searched no `object` source at all, where before an object-source hit carrying no `sourceRecordId` was served to it. An admitted object source's hit with no `sourceRecordId` cannot be re-checked and is dropped. `KnowledgeService.search` drops a hit whose reported `sourceId` names another source than the one searched; it sees only what an adapter reports.
20+
21+
**Narrowing for restricted callers.** A caller who may read a source's rows but not one of the fields the source serves now gets no hits from that source, where before it got passages carrying that field's text. A caller of an `apiEnabled: false` object, of an object whose `apiMethods` do not grant `search`, of a disabled package's object, or of a `sys_*` object without `enable.aiReadable: true` now gets no hits from its sources. No metadata key changes. To keep a source searchable for restricted callers, declare its `contentFields` / `metadataFields` from fields every intended reader may query and move sensitive fields into a separate source.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you
7373

7474
## What you get for free
7575

76-
- **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. File / HTTP hits pass through (ACL is the adapter's problem).
76+
- **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. Before a source is searched, the caller's field-level read rules and the object's API exposure are asked too: a source serving a field the caller may not query is not searched for them (see [the protocol's source admission](/docs/protocol/knowledge#source-admission-exposure-and-field-level-rules)). File / HTTP hits pass through (ACL is the adapter's problem).
7777
- **Inline event sync.** When records on indexed objects change, the kernel's `IRealtimeService` events drive `KnowledgeService.handleRecordUpsert/Delete` automatically. No cron, no queue (yet — Phase 2).
7878
- **Adapter swap, zero caller changes.** Move from `memory` to `ragflow` to a custom adapter without touching your `search` calls, the `search_knowledge` tool, or any agent prompt.
7979

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ One of the largest consumers of the flag;
189189
| 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` |
190190
| 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` |
191191
| 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` |
192-
| 46 | Knowledge search returns hits unfiltered | service-knowledge | Lose: the permission filter over search results | `applyPermissionFilter` |
192+
| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources` |
193193
| 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` |
194194
| 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` |
195195
| 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` |
@@ -700,6 +700,7 @@ and CI refuses one that differs from what the tree produces.
700700
| `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b |
701701
| `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 |
702702
| `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 |
703+
| `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 |
703704
| `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 |
704705
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b |
705706
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b |

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,9 @@ search_knowledge tool
267267
│ ToolExecutionContext { actor: U, … }
268268
▼
269269
IKnowledgeService.search(q, { executionContext, sourceIds })
270+
│
271+
├─► per object source: may U reach it? (exposure + field-level rules,
272+
│ see below) ── a refused source is not searched for U
270273
│
271274
├─► adapter.search(q, …) ──► returns raw hits with sourceRecordId
272275
│
@@ -286,6 +289,50 @@ This is the same pattern as the existing permission-aware data tools
286289
No matter how aggressive an adapter's retrieval is, the user never
287290
sees a chunk extracted from a record they can't read.
288291

292+
### Source admission: exposure and field-level rules
293+
294+
A passage is built at index time, under a system context, from every
295+
`contentFields` member of its source, the record `title` and the source's
296+
`metadataFields`. A row re-check alone would therefore serve a caller the text
297+
of a field a field-level rule hides from them. So before an `object` source is
298+
searched for a non-system caller, the service asks, once per object per search:
299+
300+
- **Disabled package** — an object whose owning package is disabled is not
301+
searched.
302+
- **API exposure** — the spec's one exposure decision for the `search`
303+
operation, the one the cross-object search asks: `enable.apiEnabled: false`,
304+
or an `enable.apiMethods` whitelist that does not grant `search` (granting
305+
`list` does), keeps the object's sources out of the search.
306+
- **System objects** — a `sys_*` object is searched only when it declares
307+
`enable.aiReadable: true` (the AI read tools' posture).
308+
- **Field-level rules** — every field the source serves (each `contentFields`
309+
member, `'*'` meaning every field the object declares except `id`; each `metadataFields`
310+
member; `title`), less the credential-class and `internal: true` fields an
311+
index never carries, must be one the caller may **query**, per the `security`
312+
service's `getQueryableFields`. Without that answer: its `getReadableFields`
313+
less every field declaring a `maskingRule`; with no `security` service at
314+
all: every field except those declaring a `maskingRule`. Queryable, not
315+
merely readable, because a passage carries the unmasked value.
316+
317+
The answer is per **source**, not per field: when one served field is hidden
318+
from the caller, that source is not searched for them at all — its passages
319+
mix the hidden field's text into one unit that cannot be partially withheld.
320+
To keep a source searchable for restricted callers, declare its
321+
`contentFields` / `metadataFields` from fields every intended reader may query,
322+
and put sensitive fields in a separate source. Every gate fails closed: a
323+
lookup that throws — the `security` service lookup included, unless the kernel
324+
answers that no `security` service is registered — or a `security` service
325+
that answers neither field question, keeps the source out of that caller's
326+
search. The system context bypasses these gates as it bypasses the row
327+
re-check. A caller with no execution context, or a service with no data engine
328+
bound, is searched no `object` source at all; an `object` source's hit with no
329+
`sourceRecordId` cannot be re-checked and is dropped; and the service drops a
330+
hit whose reported `sourceId` names another source than the one searched. That
331+
check sees only the `sourceId` an adapter reports: an adapter that labels
332+
another source's passage with the searched source's id is not caught by it, so
333+
two sources must not share one adapter-side store. A restricted caller's empty
334+
answer is this narrowing, not a missing index.
335+
289336
For `file` and `http` sources (no underlying ObjectQL record), the
290337
adapter is responsible for honouring an opaque `permissions` field on
291338
each document. Sources that need fine-grained ACLs should be declared
@@ -383,7 +430,9 @@ up.
383430
### 7.1 Non-goals for Phase 1
384431

385432
- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private.
386-
- Field-level masking — Phase 1 enforces row-level only.
433+
- Field-level masking inside a passage. A source serving a field the caller
434+
may not query is not searched for that caller at all (§5, source
435+
admission); a passage is never re-projected or redacted per caller.
387436
- Cost / quota enforcement — Phase 2.
388437
- Multi-tenant index isolation — defer to adapter capability matrix.
389438

@@ -404,10 +453,13 @@ internally (RAGFlow, Dify, Vectara).
404453

405454
## 9. Open questions
406455

407-
- **Where does chunk-level ACL live?** Currently the framework checks
408-
row-level ACLs by re-querying via `dataEngine.find`. Field-level
409-
masking would require either (a) re-running `select` projections or
410-
(b) standardising a `redact` step. Deferred.
456+
- **Where does chunk-level ACL live?** The framework checks row-level
457+
ACLs by re-querying via `dataEngine.find`, and field-level rules at
458+
source granularity (§5): a source serving a field the caller may not
459+
query is not searched for them. Finer grain — serving such a caller a
460+
passage with the hidden field's text removed — would require either
461+
(a) indexing one passage per field-visibility class or (b) standardising
462+
a `redact` step. Deferred.
411463
- **Multiple adapters per source.** Useful for mirroring (e.g. write
412464
to RAGFlow and pgvector simultaneously) but adds significant
413465
complexity. Not in Phase 1.

‎packages/core/src/security/row-serving-door-exposure.pin.test.ts‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,12 @@
3232
* `find`, or one that reads as the system behind its own token. Read on
3333
* `origin/main` at cb3bb933, the doors of that kind are the share-link door
3434
* (`plugin-sharing`, gated by its own opt-in public-sharing policy) and
35-
* knowledge retrieval (`service-knowledge`, an admin-declared source with no
36-
* HTTP door in this repository). They are named here, not held.
35+
* knowledge retrieval (`service-knowledge`). The share-link door is named
36+
* here, not held. Knowledge retrieval is HELD, by name, in
37+
* {@link HELD_BY_NAME}: its passages are built under a system context and
38+
* served to any caller of the knowledge search (the MCP door's
39+
* `search_knowledge` will be one once it serves the tool), so it asks the exposure decision and the
40+
* caller's queryable fields per source itself (`knowledge-source-admission.ts`).
3741
*
3842
* The scan surface and its prefilter follow
3943
* `operation-private-keys.pin.test.ts` in this directory: git's authored-file
@@ -136,6 +140,26 @@ const CALLERS: Record<string, Classification> = {
136140
},
137141
};
138142

143+
/**
144+
* Doors of the family the discriminator cannot see — they re-check rows through
145+
* the engine middleware with the caller's context and never call
146+
* `canReadObject` themselves — held BY NAME: the door file must import its
147+
* decision site, the decision site must ask the exposure decision and the
148+
* caller's queryable fields, and the behaviour pin must exist.
149+
*/
150+
const HELD_BY_NAME: Record<string, Extract<Classification, { kind: 'door' }>> = {
151+
'packages/services/service-knowledge/src/knowledge-service.ts': {
152+
kind: 'door',
153+
door: 'knowledge retrieval (`IKnowledgeService.search`, which every door serving `search_knowledge` will build on)',
154+
operation: 'search',
155+
decisionSite: 'packages/services/service-knowledge/src/knowledge-source-admission.ts',
156+
pin: 'packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts',
157+
},
158+
};
159+
160+
/** A CALL of the query-side field answer, `svc.getQueryableFields(`. */
161+
const queryableFieldsCall = (): RegExp => /\.getQueryableFields!?\s*\(/;
162+
139163
const SCAN_TIMEOUT_MS = 60_000;
140164

141165
function git(args: string[]): string[] {
@@ -229,6 +253,32 @@ describe('[#22640] every row-serving door outside the data routes asks the expos
229253
SCAN_TIMEOUT_MS,
230254
);
231255

256+
it(
257+
'each door held by name imports its decision site, which asks the decision and the queryable fields, and its pin exists',
258+
() => {
259+
expect(Object.keys(HELD_BY_NAME).filter((file) => file in CALLERS)).toEqual([]);
260+
for (const [file, door] of Object.entries(HELD_BY_NAME)) {
261+
expect(existsSync(join(REPO_ROOT, file)), `the door file of ${door.door} is missing: ${file}`).toBe(true);
262+
const site = door.decisionSite.slice(door.decisionSite.lastIndexOf('/') + 1).replace(/\.ts$/, '.js');
263+
expect(
264+
codeLines(file).some((line) => line.includes(`from './${site}'`)),
265+
`${file} does not import its decision site ${door.decisionSite}`,
266+
).toBe(true);
267+
expect(calls(door.decisionSite, decisionCall), `${door.door} does not ask the exposure decision in ${door.decisionSite}`).toBe(true);
268+
expect(
269+
readFileSync(join(REPO_ROOT, door.decisionSite), 'utf8'),
270+
`${door.decisionSite} does not import the decision from the spec`,
271+
).toMatch(/from '@objectstack\/spec\/data'/);
272+
expect(
273+
calls(door.decisionSite, queryableFieldsCall),
274+
`${door.door} does not ask the caller's queryable fields in ${door.decisionSite}`,
275+
).toBe(true);
276+
expect(existsSync(join(REPO_ROOT, door.pin)), `the behaviour pin of ${door.door} is missing: ${door.pin}`).toBe(true);
277+
}
278+
},
279+
SCAN_TIMEOUT_MS,
280+
);
281+
232282
it(
233283
'the scan cannot pass vacuously: the prefilter reaches every classified file and the matcher fires on each',
234284
() => {

0 commit comments

Comments
 (0)