diff --git a/.changeset/38503-knowledge-affinity.md b/.changeset/38503-knowledge-affinity.md new file mode 100644 index 00000000000..4065b1ebfb4 --- /dev/null +++ b/.changeset/38503-knowledge-affinity.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/platform-objects': minor +'@objectstack/core': minor +'@objectstack/runtime': patch +--- + +feat(knowledge): a knowledge source orders its hits for the person asking, `source.affinity` (`nearest` by business unit, `boost` by places) + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how its hits are ordered for the caller: `affinity: [{ field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, { field: 'owner', caller: 'user', mode: 'boost', places: 3 }]`. `nearest` puts the hits of the caller's own primary business unit first, then those of each parent unit in order, then every other hit. `boost` lets a hit whose field holds the caller's user id (`caller: 'user'`) or one of their units (`caller: 'business_unit'`) pass up to `places` hits that match nothing; `places` is a whole number from 1 to 20 (`KNOWLEDGE_AFFINITY_MAX_PLACES`, the most hits one `search_knowledge` answer carries). Several entries add. + +It re-orders by position and never by score: each hit keeps the `score` its store answered, only that source's hits move among the places they hold, nothing is dropped or added, and the move happens before the cut to `topK` (inside the refill cap, under chunk and record granularity alike). A source without `affinity`, and every search by the system identity, answers exactly as before. The caller's facts are resolved at most once per search, only when a hit in the list belongs to a source that declares an entry, and only the facts its entries read: `user` is the search's own user id and reads no row; `business_unit` reads the caller's user row and each unit up the chain as the caller may read them (a unit they may not read ends the chain), and no organization row. A fault reading the units leaves them out and keeps the `user` fact. A fact is never a tool argument or a value a client supplies. `affinity` enters neither the index fingerprint nor the recipe hash, so it rebuilds nothing (listing a new field in `metadataFields` for it does). + +The parse refuses, each with the fix: a `field` not listed in `metadataFields`; a `mode` other than `boost` or `nearest` (`filter` is answered that narrowing is the search scope and who may read a record is sharing); a `caller` other than `user` or `business_unit`; a second `nearest`; `nearest` with `caller: 'user'`; `places` missing on a `boost`, present on a `nearest`, or outside 1 to 20. Saving a source through Studio, the metadata API or MCP also refuses a `field` that does not point at `sys_user` (for `user`) or `sys_business_unit` (for `business_unit`). Studio's knowledge source form offers the key as an "Order for the asker" JSON field. + +`@objectstack/core` now exports `resolveCallerIdentity` (with `CallerIdentity`, `CallerBusinessUnit`, `CallerRecordReader` and `CALLER_UNIT_CHAIN_MAX_DEPTH`), the one resolver of the caller's own user, organization and business-unit chain that the MCP door's `get_current_user` already used; `@objectstack/runtime` now imports it from there, with no change in behaviour; through the runtime's wildcard re-export of `@objectstack/core`, the same five names are now also reachable from the root of `@objectstack/runtime`. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 34403f9c681..9e88a9beea9 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -120,8 +120,9 @@ export default defineStack({ Retrieval is a plain service call — no AI runtime required. Resolve the `knowledge` service and call `search`. Hits are re-checked against the caller's -`ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come -back. Because the re-check runs after ranking, for a caller other than the +`ExecutionContext` (RLS), sorted by score, re-ordered for the caller when their +source declares an [order for the asker](#ordering-hits-for-the-asker), and +capped at `topK` before they come back. Because the re-check runs after ranking, for a caller other than the system identity the service asks each source for more hits than `topK`, and asks once more when too few records survive, so a caller who may read few of the matching records still gets up to `topK` hits @@ -180,6 +181,34 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you installed ([Connect an MCP Client](/docs/ai/connect-mcp)). +### Ordering hits for the asker + +A source can put the hits related to the person asking first, without +filtering any out: "the policies of my own company first, then the group's". +Declare `affinity` on the source, naming fields it lists in `metadataFields`: + +```ts +source: { + kind: 'object', + object: 'policy', + content: ['title', 'body'], + metadataFields: ['business_unit', 'owner'], + affinity: [ + { field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, // own unit, then each parent, then the rest + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, // an owned policy passes up to 3 others + ], +}, +``` + +The platform reads who is asking from the search's own identity (the user, and +their primary business unit with its parents up to the root, as far as they may +read them), so no tool argument and no model supplies it. Only that source's +hits move, by position: each keeps the `score` its store answered, nothing is +dropped, and a source without `affinity` answers exactly as before. `places` is +a whole number from 1 to 20, and a source declares at most one `nearest`. The +rules, and every refusal, are in +[the protocol](/docs/protocol/knowledge#ordering-for-the-asker). + ## Searching inside chosen records Pass `scope` to search only inside some records: the records a source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 00f26d3aec0..7da4a341850 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -190,6 +190,7 @@ One of the largest consumers of the flag; | 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` | | 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` | | 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | 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. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save. Lose at the package move-in door: the same admission asked for the caller, for each selected knowledge source the move saves again under the package | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources`, `handlePackagesRequest` | +| 46a | Knowledge search under the system identity is not ordered for the asker: a source's `affinity` entries move nothing | service-knowledge | Get: every hit in the order its store answered, and no read of a user or business unit. Lose: nothing a user held. The system identity is no person, so it has no unit to order by; every other caller's user id and unit chain are read as that caller may read them | `resolveAffinityFacts` | | 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` | | 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` | | 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` | @@ -707,6 +708,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b | | `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 | | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | +| `packages/services/service-knowledge/src/knowledge-affinity.ts#resolveAffinityFacts` | 1 | 46a | | `packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 07cd81ffcb8..105eb543109 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -1013,6 +1013,85 @@ until a complete reindex writes it again. How many hits the scope removed is logged, never returned, and an entry that reaches no source answers the same empty result a source withheld from the caller gives. +### Ordering for the asker + +A source may declare how its hits are ordered for the person asking +(`source.affinity`, ADR-0161's dated note of 2026-11-29 under K1): "the +policies of my own unit first". Each entry compares a field the source lists +in `metadataFields` with a fact the platform resolves about the caller. + +```ts +source: { + kind: 'object', + object: 'policy', + content: ['title', 'body'], + metadataFields: ['business_unit', 'owner'], + affinity: [ + // The caller's own unit first, then each parent unit in order, then the rest. + { field: 'business_unit', caller: 'business_unit', mode: 'nearest' }, + // A policy the caller owns passes up to 3 hits that match nothing. + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, + ], +}, +``` + +- **The caller facts** are a closed list of two. `user` is the caller's user + id, for a field that points at `sys_user` (a `user` field, or a lookup to + it). `business_unit` is the caller's primary business unit, then each parent + unit up to the root, for a lookup to `sys_business_unit`. A fact is + resolved at most once per search, only when a hit in the list belongs to a + source that declares an entry, and only if such an entry reads it. `user` + is the search's own user id and reads no row. `business_unit` is read by + the one resolver that also answers the MCP door's `get_current_user`: the + caller's user row for the primary unit, then each unit up the chain, every + read as the caller, so a unit the caller may not read ends the chain below + it. No organization row is read. A fault reading the units, other than a + refusal, leaves them out for that search and keeps the `user` fact. A fact + is never a tool argument, a `search` option, or a value a client or a model + supplies. The system identity has no + facts, and a caller with no primary unit has no chain: an entry that finds + no fact matches nothing. +- **`nearest`** parts the source's hits into tiers: the caller's own unit + first, then each parent in order, then every other hit together, a hit with + no value among them. A multi-value lookup takes its nearest element. A + source declares at most one, and its `caller` is `business_unit`. +- **`boost`** takes `places`, a whole number from 1 to 20 (the most hits one + `search_knowledge` answer carries). Inside a tier, with its hits numbered + from 1 in their order, a hit's key is its number minus the `places` of every + `boost` entry it matches; the tier is ordered by key, a tie going to the + larger sum, then to the earlier number. So a hit matching `places: 3` + passes at most three hits of its tier that match nothing. Several entries + add. +- **By position, never by score.** The search runs as it always did up to + its answer: the rounds, the scope check, the permission re-check and the + record-level grouping. The re-order then works on the units that could be + answered (passages, records or `groupBy` groups, each judged on the hit that + stands for it), before the cut to `topK`, so it reads no more passages than + the refill cap already allows. Only one source's units move, among the + places they hold: a hit of another source never moves. A hit keeps the + `score` its store answered, so an answer may no longer be in descending + `score`. Nothing in the answer says a hit moved; the count goes to the + `debug` log. +- **Never an access decision.** Nothing is dropped and nothing is admitted: + a hit outside the caller's unit is ordered later. Narrowing a search is the + [record scope](#record-scope); who may read a record is sharing, so there is + no `filter` mode. An entry is judged on the values the index stores, like a + scope term, and a document indexed before its source listed the field + matches nothing until a complete reindex writes it again. +- **No rebuild.** `affinity` enters neither the index fingerprint nor the + recipe hash. Listing a new field in `metadataFields` for it does change the + recipe hash, as it always did. +- **Refused when it is written**, each with a sentence that names the fix: a + `field` not listed in `metadataFields`, a `mode` other than `boost` and + `nearest` (`filter` is answered that narrowing is the search scope and + visibility is sharing), a caller fact outside the two, a second `nearest`, + `nearest` with `caller: 'user'`, `places` missing on a `boost`, present on a + `nearest`, or not a whole number from 1 to 20. Saving a source also refuses + a `field` that does not point at the object its `caller` names. A unit + read that fails for a reason other than a refusal leaves the units out of + that search, logged once at `warn`; its `business_unit` entries then match + nothing, and its `user` entries still apply. + ### 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-source.mdx b/content/docs/references/ai/knowledge-source.mdx index dd87a25e817..423e186a7ad 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -23,13 +23,47 @@ See `content/docs/protocol/knowledge.mdx` for the design. ## TypeScript Usage ```typescript -import { KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data -const result = KnowledgeRefreshPolicySchema.parse(data); +const result = KnowledgeAffinityCallerSchema.parse(data); ``` +--- + +## KnowledgeAffinityCaller + +### Allowed Values + +* `user` +* `business_unit` + + +--- + +## KnowledgeAffinityEntry + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field listed in metadataFields, compared with the caller fact | +| **caller** | `Enum<'user' \| 'business_unit'>` | ✅ | The caller fact compared: user or business_unit | +| **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | +| **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | + + +--- + +## KnowledgeAffinityMode + +### Allowed Values + +* `boost` +* `nearest` + + --- ## KnowledgeRefreshPolicy @@ -81,6 +115,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | +| **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | ### Nested Shape: `KnowledgeSource.refresh` @@ -130,6 +165,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | +| **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | ### Nested Shape: `ObjectKnowledgeSource.split` @@ -139,6 +175,15 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | | **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars | +### Nested Shape: `ObjectKnowledgeSource.affinity[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **field** | `string` | ✅ | A field listed in metadataFields, compared with the caller fact | +| **caller** | `Enum<'user' \| 'business_unit'>` | ✅ | The caller fact compared: user or business_unit | +| **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | +| **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 251bd5a0b69..920f1a62496 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1742 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1745 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 102 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 17 | 105 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 187 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **223** | **1742** | 14 protocol modules | +| **Total** | **223** | **1745** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 102 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 105 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -55,7 +55,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`draft-review.zod.ts`](/docs/references/ai/draft-review) | `DraftReviewItem`, `DraftReviewLinks`, `DraftReviewList`, `DraftReviewVerdict`, `DraftReviewVerdictRefusal` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 3bf684e33e2..5f25e0c458c 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 120 | +| `ai/` | 121 | diff --git a/packages/core/src/caller-identity.ts b/packages/core/src/caller-identity.ts new file mode 100644 index 00000000000..becaeb0e26e --- /dev/null +++ b/packages/core/src/caller-identity.ts @@ -0,0 +1,181 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The caller's own identity facts (#38363), resolved by one function that + * every door asking "who is the caller" calls: the `/mcp` door's + * `get_current_user` (`@objectstack/runtime`) and the knowledge service's + * affinity ordering (`@objectstack/service-knowledge`). Moved here from the + * runtime's MCP domain unchanged, so the knowledge service, which does not + * depend on the runtime, can call it. + */ + +/** + * [#38363] The most business units {@link resolveCallerIdentity} reads up a + * parent chain: the primary unit and at most this many minus one above it. A + * real org tree is far shallower; the cap bounds the reads a broken tree (a + * parent link that loops past the cycle check, or a runaway import) can cost. + */ +export const CALLER_UNIT_CHAIN_MAX_DEPTH = 32; + +/** [#38363] One business unit of {@link CallerIdentity}: the fields of its row the caller read. */ +export interface CallerBusinessUnit { + id: string; + name?: string; + kind?: string; +} + +/** + * [#38363] Who is signed in, as the caller may read it about themselves. The + * structural twin of `McpCurrentUser` (`@objectstack/mcp`), which the + * `get_current_user` tool renders. + */ +export interface CallerIdentity { + user?: { id: string; name?: string }; + organization?: { id: string; name?: string }; + businessUnits?: CallerBusinessUnit[]; + businessUnitNote?: string; +} + +/** + * [#38363] Read one record by id AS the caller: the row with the fields the + * caller may read, or `undefined` when there is none they may read. A refusal + * may also arrive as a throw: {@link resolveCallerIdentity} reads a `401`, + * `403` or `404` throw as "not readable" for the fact it was reading, and + * lets every other throw through. + */ +export type CallerRecordReader = ( + object: string, + id: string, + fields: readonly string[], +) => Promise | undefined>; + +/** A non-empty string value of `row[key]`, or `undefined`. */ +function textOf(row: Record | undefined, key: string): string | undefined { + const v = row?.[key]; + return typeof v === 'string' && v.trim() !== '' ? v : undefined; +} + +/** The statuses a read refuses with when the caller may not read the row or the object. */ +const CALLER_READ_REFUSAL_STATUSES: ReadonlySet = new Set([401, 403, 404]); + +/** + * {@link CallerRecordReader}, with a refusal read as "not readable". Only a + * refusal: a throw carrying any other status, or none (a driver fault, an + * outage), is rethrown, so the tool answers the coded failure instead of + * telling the model that its caller's permissions hide a unit they may well + * read. + */ +async function readOrUndefined( + read: CallerRecordReader, + object: string, + id: string, + fields: readonly string[], +): Promise | undefined> { + try { + return await read(object, id, fields); + } catch (err) { + const e = err as { status?: unknown; statusCode?: unknown } | null; + const status = typeof e?.status === 'number' ? e.status : e?.statusCode; + if (typeof status === 'number' && CALLER_READ_REFUSAL_STATUSES.has(status)) return undefined; + throw err; + } +} + +/** + * [#38363] The ONE resolver of the caller's own identity facts, for any door + * that tells a model who is asking (`get_current_user` on `/mcp`) and for the + * knowledge service, which orders a source's hits by a declared `affinity` + * against the same answer (ADR-0161, the dated note of 2026-11-29 under K1). + * It lives here, below both the runtime and the knowledge service, so both + * call this one function. It takes the + * caller's `ExecutionContext` and a reader that runs AS that caller, and + * never reads with a system or elevated context, so it can answer only what + * the caller could read for themselves through the data API: + * + * - **user** — `ec.userId`, and the `name` of their `sys_user` row; + * - **organization** — `ec.tenantId` (the session's active organization), and + * the `name` of its `sys_organization` row; + * - **businessUnits** — the unit their `sys_user.primary_business_unit_id` + * names (the projection of the `is_primary` membership plugin-sharing keeps, + * ADR-0057 addendum D12, which the sharing rules keyed on the primary unit + * read too), then each `parent_business_unit_id` up to the root. The + * `IBusinessUnitGraphService` contract walks descendants only, so the walk + * is here, one gated read per unit, cycle-safe and capped at + * {@link CALLER_UNIT_CHAIN_MAX_DEPTH}. + * + * A unit the caller may not read is left out, never named, and the chain ends + * below it; `businessUnitNote` says so, and says when no unit is recorded or + * the primary unit field is not readable, so a missing unit never reads as + * "no unit". A deployment with no business units answers the user and the + * organization, with the note that no unit is recorded. Nothing about any + * other user is read, and nothing is written. + */ +export async function resolveCallerIdentity( + ec: { userId?: unknown; tenantId?: unknown } | undefined, + read: CallerRecordReader, +): Promise { + const userId = typeof ec?.userId === 'string' && ec.userId !== '' ? ec.userId : undefined; + if (!userId) { + return { businessUnitNote: 'This connection is not signed in as a user, so it has no user or business unit.' }; + } + const out: CallerIdentity = {}; + + const userRow = await readOrUndefined(read, 'sys_user', userId, ['id', 'name', 'primary_business_unit_id']); + const userName = textOf(userRow, 'name'); + out.user = { id: userId, ...(userName ? { name: userName } : {}) }; + + const orgId = typeof ec?.tenantId === 'string' && ec.tenantId !== '' ? ec.tenantId : undefined; + if (orgId) { + const orgName = textOf(await readOrUndefined(read, 'sys_organization', orgId, ['id', 'name']), 'name'); + out.organization = { id: orgId, ...(orgName ? { name: orgName } : {}) }; + } + + // A field the caller may not read is masked off the row (absent), while + // one with no value is present and empty: the two answer differently. + if (!userRow || !Object.prototype.hasOwnProperty.call(userRow, 'primary_business_unit_id')) { + out.businessUnitNote = 'Your primary business unit is not readable with your permissions.'; + return out; + } + const primary = userRow.primary_business_unit_id; + let nextId = typeof primary === 'string' && primary !== '' ? primary : undefined; + if (!nextId) { + out.businessUnitNote = 'No primary business unit is recorded for you.'; + return out; + } + + const units: CallerBusinessUnit[] = []; + const seen = new Set(); + let note: string | undefined; + while (nextId) { + if (seen.has(nextId)) { + note = 'The parent units loop back on themselves, so the chain ends at the last unit before the loop.'; + break; + } + if (units.length >= CALLER_UNIT_CHAIN_MAX_DEPTH) { + note = `The chain is cut at ${CALLER_UNIT_CHAIN_MAX_DEPTH} units; the units above them are not listed.`; + break; + } + seen.add(nextId); + const row = await readOrUndefined(read, 'sys_business_unit', nextId, ['id', 'name', 'kind', 'parent_business_unit_id']); + if (!row) { + note = units.length === 0 + ? 'Your primary business unit is not readable with your permissions.' + : 'The chain ends here: the next unit up is not readable with your permissions.'; + break; + } + const name = textOf(row, 'name'); + const kind = textOf(row, 'kind'); + units.push({ id: nextId, ...(name ? { name } : {}), ...(kind ? { kind } : {}) }); + // As for the primary unit: a parent link masked off the row (absent) + // is not readable, while one present and empty is the top of the tree. + if (!Object.prototype.hasOwnProperty.call(row, 'parent_business_unit_id')) { + note = 'The chain ends here: the next unit up is not readable with your permissions.'; + break; + } + const parent = row.parent_business_unit_id; + nextId = typeof parent === 'string' && parent !== '' ? parent : undefined; + } + if (units.length > 0) out.businessUnits = units; + if (note) out.businessUnitNote = note; + return out; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 168bb376cc0..e303192e7be 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -63,6 +63,7 @@ export * from './organization-locale.js'; // the dataset tools (`@objectstack/service-analytics`) and the MCP record // tools (`@objectstack/mcp`), which cannot import each other. export * from './sentence-locale.js'; +export * from './caller-identity.js'; // [ADR-0160 D3] The one envelope a record-material tool answer is built in // (`get_record_context`, `@objectstack/service-record-context`). export * from './record-material-envelope.js'; diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 35e41d627a2..886ecf528b5 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -276,6 +276,22 @@ const CALLERS: Record = { 'Pinned by `packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts` (a parent-scoped ' + 'search makes no engine call naming the parent object) and `knowledge-search-scope.test.ts`', }, + // [#38503] A knowledge source's `affinity` (ADR-0161, the dated note of 2026-11-29 under K1). + 'packages/services/service-knowledge/src/knowledge-source-admission.ts': { + kind: 'not-a-served-read', + reason: + "the save door's affinity arm (`affinityTargetRefusalText`) names the object an entry's field points at only to " + + "compare that name with the fixed platform object its `caller` names (`sys_user` or `sys_business_unit`); it " + + 'reads no record of the target and serves nothing of it. The feature does read rows of those two objects, and no ' + + "other: `resolveAffinityFacts` (`knowledge-affinity.ts`) reads the caller's own `sys_user` row and each " + + "`sys_business_unit` row up their chain, by id, as the caller through `engine.find` with the search's " + + 'ExecutionContext, only when an entry reads `business_unit`. Those targets are FIXED platform objects, never the ' + + 'authored target this pin holds (its header names fixed-object reads as outside it); the reads serve nothing to ' + + 'the caller but an order among hits that each passed their own re-check, and the target refusal keeps an entry ' + + 'from naming any other object. Pinned by ' + + '`packages/services/service-knowledge/src/__tests__/affinity-38503.test.ts` (a refused save makes no engine call; ' + + 'a `user`-only source reads no row; a `business_unit` source reads its user row and units alone, as the caller)', + }, 'packages/qa/scenarios/src/score/scenario-graph.ts': { kind: 'not-a-served-read', reason: diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index e6f31b3d59c..3ee50bbe66f 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const arMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index a836fbcb84a..d1f3a002d10 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -64,6 +64,8 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 29dbd2f0fb0..8175e7cdf3a 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const deMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 28ac339ebc5..6f2fc9759e8 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -99,6 +99,8 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index c8a96098508..1a122e0d54e 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const enMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 15aac59cbd3..8ce8b42c465 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const esESMetadataForms: NonNullable = label: "Unidad de documento", helpText: "Opcional. El campo que vincula cada registro con el registro padre del que forma parte (una cláusula con su política): un campo de búsqueda o maestro-detalle, de un solo valor, que también figure en Campos de filtro. Una búsqueda por registros devuelve entonces un resultado por padre en lugar de uno por registro; un registro sin padre es su propio resultado. Definirlo no reconstruye nada; añadir el campo a Campos de filtro sí lo hace." }, + "source.affinity": { + label: "Orden según quien pregunta", + helpText: "Opcional. Enumera entradas que suben en la respuesta los resultados relacionados con quien pregunta; por ejemplo, [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] pone primero su propia unidad, luego sus unidades superiores y después el resto, y [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] deja que un resultado suyo adelante hasta 3 otros (de 1 a 20). Cada campo debe figurar en los campos de filtro y apuntar a usuarios (caller user) o a unidades de negocio (caller business_unit); como máximo un nearest. No se descarta ningún resultado ni cambia su puntuación, y configurarlo no reconstruye nada.\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Registros que indexar", helpText: "Un filtro ObjectQL sobre el objeto, por ejemplo {\"status\": {\"$ne\": \"done\"}}. Solo se indexan los registros que coinciden. En blanco: todos los registros." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index c1b916cc638..7029b01f849 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const frMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 20b9153766f..406686dccbf 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -120,6 +120,8 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 62ac863d396..a46a739cf0b 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const jaJPMetadataForms: NonNullable = label: "ドキュメント単位", helpText: "任意。各レコードを、それが属する親レコードに結び付けるフィールド(例:条項が属する規程)。単一値の参照または主従フィールドで、フィルターフィールドにも含める必要があります。レコード単位の検索では、レコードごとではなく親レコードごとに 1 件のヒットを返します。親のないレコードはそれ自体で 1 件のヒットになります。この設定だけでは再構築されませんが、フィールドをフィルターフィールドに新たに追加すると再構築されます。" }, + "source.affinity": { + label: "質問者に合わせた並び順", + helpText: "任意。質問者に関係するヒットを上位に移すエントリを並べます。例:[{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] は質問者自身の部門を先頭に、次に上位部門を順に、最後にその他を並べ、[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] は質問者が所有するヒットを最大 3 件分上に移します(1〜20)。各フィールドはフィルターフィールドに含まれ、ユーザー(caller が user)またはビジネスユニット(caller が business_unit)を指す必要があります。nearest は 1 つまでです。ヒットを除外することもスコアを変えることもなく、設定しても再構築は行われません。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "インデックス化するレコード", helpText: "オブジェクトに対する ObjectQL フィルター。例:{\"status\": {\"$ne\": \"done\"}}。一致するレコードだけがインデックス化されます。空欄:すべてのレコード。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 4efc74483ed..be1a817a7ac 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const koMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 821ea0c5048..9d818854b76 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -64,6 +64,8 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 242ac01424d..8b57fd2cc53 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1357,7 +1357,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // locales. // 867: the `knowledge_source` form's `documentBy` row (the document // unit) — one row label, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(867); + // 868: its `affinity` row (the order for the asker) — one row label, + // authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(868); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 6236c748675..e0d43f2ebd4 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const ptBRMetadataForms: NonNullable = label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index e49643f4ed4..8e80cc43845 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -76,6 +76,8 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 2b772bbc273..c6eed74bf64 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const ruMetadataForms: NonNullable = { label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index e5e166a1f7d..aaabf6a75fd 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -64,6 +64,8 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index dd72f013647..3923e718042 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const zhCNMetadataForms: NonNullable = label: "文档单位", helpText: "可选。把每条记录关联到它所属父记录的字段(例如条款所属的制度):须是单值的查找或主从字段,并且同时列在筛选字段中。按记录检索时,每个父记录只返回一条命中,而不是每条记录一条;没有父记录的记录单独作为一条命中。设置它不会触发重建;把该字段首次加入筛选字段则会。" }, + "source.affinity": { + label: "按提问人排序", + helpText: "可选。列出把与提问人相关的命中往前排的条目,例如 [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] 先排提问人本单位,再按上级单位逐级,最后其余;[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] 让提问人负责的命中最多越过 3 条其他命中(1 到 20)。每个字段须列在筛选字段中,并指向用户(caller 为 user)或业务单位(caller 为 business_unit);nearest 最多一条。不会丢弃命中,也不改分数,设置它不会触发重建。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "要索引的记录", helpText: "对该对象的 ObjectQL 筛选条件,例如 {\"status\": {\"$ne\": \"done\"}}。只有匹配的记录会被索引。留空:所有记录。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 716c3804ae6..6bb3564911b 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3557,6 +3557,10 @@ export const zhHantMetadataForms: NonNullable label: "Document unit", helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." }, + "source.affinity": { + label: "Order for the asker", + helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 56b23425f36..464e92ba410 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -62,6 +62,8 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.label": "1b63ae2e002930a6", "metadataForms.knowledge_source.fields.refresh.onRecordChange.helpText": "ef6f113e883733b7", "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", + "metadataForms.knowledge_source.fields.source.affinity.helpText": "22f9526747c66a8c", + "metadataForms.knowledge_source.fields.source.affinity.label": "5cfac91912f628fc", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 180101f0a64..51d3de7a8ec 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -37,7 +37,7 @@ import { // [ADR-0131 D3 · D12 items 7–8 · D11] The walled refusal every door that writes // the environment's metadata asks, read through this transport's one posture read. import { packageResolutionClosure, walledCatalogWriteVerdict } from '@objectstack/metadata-core'; -import { shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, userTextLocalesOf } from '@objectstack/core'; +import { shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, userTextLocalesOf, resolveCallerIdentity, type CallerIdentity } from '@objectstack/core'; import { readEffectiveTenancyPosture } from './activation-gate.js'; import { buildApiError } from '../error-envelope.js'; import * as actionExec from '../action-execution.js'; @@ -1030,173 +1030,16 @@ function actionCallDoorWiring( }; } -/** - * [#38363] The most business units {@link resolveCallerIdentity} reads up a - * parent chain: the primary unit and at most this many minus one above it. A - * real org tree is far shallower; the cap bounds the reads a broken tree (a - * parent link that loops past the cycle check, or a runaway import) can cost. - */ -export const CALLER_UNIT_CHAIN_MAX_DEPTH = 32; - -/** [#38363] One business unit of {@link CallerIdentity}: the fields of its row the caller read. */ -export interface CallerBusinessUnit { - id: string; - name?: string; - kind?: string; -} - -/** - * [#38363] Who is signed in, as the caller may read it about themselves. The - * structural twin of `McpCurrentUser` (`@objectstack/mcp`), which the - * `get_current_user` tool renders. - */ -export interface CallerIdentity { - user?: { id: string; name?: string }; - organization?: { id: string; name?: string }; - businessUnits?: CallerBusinessUnit[]; - businessUnitNote?: string; -} - -/** - * [#38363] Read one record by id AS the caller: the row with the fields the - * caller may read, or `undefined` when there is none they may read. A refusal - * may also arrive as a throw: {@link resolveCallerIdentity} reads a `401`, - * `403` or `404` throw as "not readable" for the fact it was reading, and - * lets every other throw through. - */ -export type CallerRecordReader = ( - object: string, - id: string, - fields: readonly string[], -) => Promise | undefined>; - -/** A non-empty string value of `row[key]`, or `undefined`. */ -function textOf(row: Record | undefined, key: string): string | undefined { - const v = row?.[key]; - return typeof v === 'string' && v.trim() !== '' ? v : undefined; -} - -/** The statuses a read refuses with when the caller may not read the row or the object. */ -const CALLER_READ_REFUSAL_STATUSES: ReadonlySet = new Set([401, 403, 404]); - -/** - * {@link CallerRecordReader}, with a refusal read as "not readable". Only a - * refusal: a throw carrying any other status, or none (a driver fault, an - * outage), is rethrown, so the tool answers the coded failure instead of - * telling the model that its caller's permissions hide a unit they may well - * read. - */ -async function readOrUndefined( - read: CallerRecordReader, - object: string, - id: string, - fields: readonly string[], -): Promise | undefined> { - try { - return await read(object, id, fields); - } catch (err) { - const e = err as { status?: unknown; statusCode?: unknown } | null; - const status = typeof e?.status === 'number' ? e.status : e?.statusCode; - if (typeof status === 'number' && CALLER_READ_REFUSAL_STATUSES.has(status)) return undefined; - throw err; - } -} - -/** - * [#38363] The ONE resolver of the caller's own identity facts, for any door - * that tells a model who is asking (`get_current_user` on `/mcp` today; a - * retrieval ranking by the asker reads the same answer). It takes the - * caller's `ExecutionContext` and a reader that runs AS that caller, and - * never reads with a system or elevated context, so it can answer only what - * the caller could read for themselves through the data API: - * - * - **user** — `ec.userId`, and the `name` of their `sys_user` row; - * - **organization** — `ec.tenantId` (the session's active organization), and - * the `name` of its `sys_organization` row; - * - **businessUnits** — the unit their `sys_user.primary_business_unit_id` - * names (the projection of the `is_primary` membership plugin-sharing keeps, - * ADR-0057 addendum D12, which the sharing rules keyed on the primary unit - * read too), then each `parent_business_unit_id` up to the root. The - * `IBusinessUnitGraphService` contract walks descendants only, so the walk - * is here, one gated read per unit, cycle-safe and capped at - * {@link CALLER_UNIT_CHAIN_MAX_DEPTH}. - * - * A unit the caller may not read is left out, never named, and the chain ends - * below it; `businessUnitNote` says so, and says when no unit is recorded or - * the primary unit field is not readable, so a missing unit never reads as - * "no unit". A deployment with no business units answers the user and the - * organization, with the note that no unit is recorded. Nothing about any - * other user is read, and nothing is written. - */ -export async function resolveCallerIdentity( - ec: { userId?: unknown; tenantId?: unknown } | undefined, - read: CallerRecordReader, -): Promise { - const userId = typeof ec?.userId === 'string' && ec.userId !== '' ? ec.userId : undefined; - if (!userId) { - return { businessUnitNote: 'This connection is not signed in as a user, so it has no user or business unit.' }; - } - const out: CallerIdentity = {}; - - const userRow = await readOrUndefined(read, 'sys_user', userId, ['id', 'name', 'primary_business_unit_id']); - const userName = textOf(userRow, 'name'); - out.user = { id: userId, ...(userName ? { name: userName } : {}) }; - - const orgId = typeof ec?.tenantId === 'string' && ec.tenantId !== '' ? ec.tenantId : undefined; - if (orgId) { - const orgName = textOf(await readOrUndefined(read, 'sys_organization', orgId, ['id', 'name']), 'name'); - out.organization = { id: orgId, ...(orgName ? { name: orgName } : {}) }; - } - - // A field the caller may not read is masked off the row (absent), while - // one with no value is present and empty: the two answer differently. - if (!userRow || !Object.prototype.hasOwnProperty.call(userRow, 'primary_business_unit_id')) { - out.businessUnitNote = 'Your primary business unit is not readable with your permissions.'; - return out; - } - const primary = userRow.primary_business_unit_id; - let nextId = typeof primary === 'string' && primary !== '' ? primary : undefined; - if (!nextId) { - out.businessUnitNote = 'No primary business unit is recorded for you.'; - return out; - } - - const units: CallerBusinessUnit[] = []; - const seen = new Set(); - let note: string | undefined; - while (nextId) { - if (seen.has(nextId)) { - note = 'The parent units loop back on themselves, so the chain ends at the last unit before the loop.'; - break; - } - if (units.length >= CALLER_UNIT_CHAIN_MAX_DEPTH) { - note = `The chain is cut at ${CALLER_UNIT_CHAIN_MAX_DEPTH} units; the units above them are not listed.`; - break; - } - seen.add(nextId); - const row = await readOrUndefined(read, 'sys_business_unit', nextId, ['id', 'name', 'kind', 'parent_business_unit_id']); - if (!row) { - note = units.length === 0 - ? 'Your primary business unit is not readable with your permissions.' - : 'The chain ends here: the next unit up is not readable with your permissions.'; - break; - } - const name = textOf(row, 'name'); - const kind = textOf(row, 'kind'); - units.push({ id: nextId, ...(name ? { name } : {}), ...(kind ? { kind } : {}) }); - // As for the primary unit: a parent link masked off the row (absent) - // is not readable, while one present and empty is the top of the tree. - if (!Object.prototype.hasOwnProperty.call(row, 'parent_business_unit_id')) { - note = 'The chain ends here: the next unit up is not readable with your permissions.'; - break; - } - const parent = row.parent_business_unit_id; - nextId = typeof parent === 'string' && parent !== '' ? parent : undefined; - } - if (units.length > 0) out.businessUnits = units; - if (note) out.businessUnitNote = note; - return out; -} +// [#38363] The caller's identity resolver lives in `@objectstack/core` +// (`caller-identity.ts`), so the knowledge service's affinity ordering calls +// the same function `get_current_user` does; re-exported for this door's tests. +export { + CALLER_UNIT_CHAIN_MAX_DEPTH, + resolveCallerIdentity, + type CallerBusinessUnit, + type CallerIdentity, + type CallerRecordReader, +} from '@objectstack/core'; /** * Build a principal-bound {@link McpDataBridge}: every method runs AS the diff --git a/packages/services/service-knowledge/src/__tests__/affinity-38503.test.ts b/packages/services/service-knowledge/src/__tests__/affinity-38503.test.ts new file mode 100644 index 00000000000..3492411aa2e --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/affinity-38503.test.ts @@ -0,0 +1,394 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `source.affinity` — a knowledge source orders its own hits for the caller + * (ADR-0161, the dated note of 2026-11-29 under K1), by position and never by + * score. + * + * - **The order** ({@link orderByAffinity}): per source, among the places that + * source's units hold; `nearest` tiers by the caller's unit chain; inside a + * tier the key is number minus the matched `places`, a tie to the larger + * sum, then the earlier number; every hit keeps its adapter's `score`. + * - **The reader** (`KnowledgeService.search`): the re-order runs before the + * cut to `topK`, under chunk and record granularity; a source without the + * key answers exactly as before; the caller's facts are resolved once per + * search, only when a searched source declares an entry, through the one + * resolver, every read as the caller; the system identity has none; a unit + * the caller may not read ends the chain; nothing is dropped. + * - **The save door**: a `field` that does not point at the object its + * `caller` names is refused `400 VALIDATION_ERROR`, naming the fix. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeAffinityEntry, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService, recordToDocument } from '../knowledge-service.js'; +import { computeIndexFingerprint, computeRecipeHash } from '../knowledge-index-fingerprint.js'; +import { orderByAffinity, type AffinityCallerFacts } from '../knowledge-affinity.js'; + +const ADA: ExecutionContext = { userId: 'u_ada', tenantId: 'org_1', positions: ['member'], permissions: [], isSystem: false }; +const SYSTEM: ExecutionContext = { positions: [], permissions: [], isSystem: true }; + +// ── The order, as a pure function ────────────────────────────────────────── + +/** A unit standing as a hit of `sourceId` with `metadata`, named `id` for the assertions. */ +const unit = (id: string, metadata: Record = {}, sourceId = 'S'): KnowledgeHit => ({ + chunkId: `${id}#0`, + documentId: id, + sourceId, + sourceRecordId: id, + score: 0, + snippet: id, + metadata, +}); +const ids = (units: readonly KnowledgeHit[]): string[] => units.map((u) => u.documentId); +const order = (units: KnowledgeHit[], entries: Record, facts: AffinityCallerFacts) => + orderByAffinity(units, (u) => u, (sourceId) => entries[sourceId], facts); + +const BU_FACTS: AffinityCallerFacts = { user: 'u_ada', businessUnits: ['bu_team', 'bu_dept', 'bu_root'] }; +const NEAREST: KnowledgeAffinityEntry = { field: 'bu', caller: 'business_unit', mode: 'nearest' }; +const BOOST_OWNER = (places: number): KnowledgeAffinityEntry => ({ field: 'owner', caller: 'user', mode: 'boost', places }); + +describe('orderByAffinity — by position, per source, never by score', () => { + it('boost: a match passes at most `places` units that match nothing', () => { + const list = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => unit(id, { owner: id === 'f' ? 'u_ada' : 'u_lin' })); + // f is number 6, key 6 - 3 = 3: it passes d and e, and stops behind c (key 3 tie, the larger sum wins). + expect(ids(order(list, { S: [BOOST_OWNER(3)] }, BU_FACTS).units)).toEqual(['a', 'b', 'f', 'c', 'd', 'e']); + // places 20 (the bound) on a 6-unit list: first. + expect(ids(order(list, { S: [BOOST_OWNER(20)] }, BU_FACTS).units)).toEqual(['f', 'a', 'b', 'c', 'd', 'e']); + }); + + it('a tie goes to the larger sum, then to the earlier number', () => { + const list = [ + unit('a'), + unit('b'), + unit('c', { owner: 'u_ada' }), // key 3 - 1 = 2, sum 1 + unit('d', { owner: 'u_ada', bu: 'bu_dept' }), // key 4 - 2 = 2, sum 2 + ]; + const entries = { S: [BOOST_OWNER(1), { field: 'bu', caller: 'business_unit', mode: 'boost', places: 1 } as KnowledgeAffinityEntry] }; + // a (key 1), then c and d both at key 2: d has the larger sum. b is key 2, sum 0: after both. + expect(ids(order(list, entries, BU_FACTS).units)).toEqual(['a', 'd', 'c', 'b']); + }); + + it('several entries add: a unit matching two boosts sums their places', () => { + const list = ['a', 'b', 'c', 'd', 'e'].map((id) => unit(id, id === 'e' ? { owner: 'u_ada', bu: 'bu_root' } : {})); + const entries = { S: [BOOST_OWNER(2), { field: 'bu', caller: 'business_unit', mode: 'boost', places: 2 } as KnowledgeAffinityEntry] }; + expect(ids(order(list, entries, BU_FACTS).units)).toEqual(['e', 'a', 'b', 'c', 'd']); + }); + + it('nearest: own unit first, then each parent in order, then every other unit, no value among them', () => { + const list = [ + unit('other', { bu: 'bu_sibling' }), + unit('root', { bu: 'bu_root' }), + unit('none', {}), + unit('team', { bu: 'bu_team' }), + unit('dept', { bu: 'bu_dept' }), + unit('team2', { bu: 'bu_team' }), + ]; + expect(ids(order(list, { S: [NEAREST] }, BU_FACTS).units)).toEqual(['team', 'team2', 'dept', 'root', 'other', 'none']); + }); + + it('nearest with a multiple lookup takes its nearest element; boost inside a tier keeps the tier', () => { + const list = [ + unit('x', { bu: ['bu_sibling', 'bu_root'] }), + unit('y', { bu: ['bu_dept', 'bu_root'] }), + unit('z', { bu: 'bu_sibling', owner: 'u_ada' }), + ]; + // y is in the dept tier (its nearest element), x in the root tier, z in the others' tier: a boost never lifts it out. + expect(ids(order(list, { S: [NEAREST, BOOST_OWNER(20)] }, BU_FACTS).units)).toEqual(['y', 'x', 'z']); + }); + + it('per source: another source\'s units keep their places, and a number compares as a scope term does', () => { + const list = [unit('t1', {}, 'T'), unit('s1', { bu: 7 }, 'S'), unit('t2', {}, 'T'), unit('s2', { bu: 'bu_team' }, 'S')]; + const facts: AffinityCallerFacts = { businessUnits: ['bu_team', '7'] }; + const out = order(list, { S: [NEAREST] }, facts); + // s2 (own unit) takes s1's place; T's units stand where they stood. + expect(ids(out.units)).toEqual(['t1', 's2', 't2', 's1']); + expect(out.moved).toBe(2); + }); + + it('an entry that finds no fact matches nothing: no facts, no move; the input is not mutated', () => { + const list = [unit('a', { bu: 'bu_dept' }), unit('b', { bu: 'bu_team', owner: 'u_ada' })]; + const out = order(list, { S: [NEAREST, BOOST_OWNER(5)] }, { businessUnits: [] }); + expect(ids(out.units)).toEqual(['a', 'b']); + expect(out.moved).toBe(0); + expect(ids(list)).toEqual(['a', 'b']); + }); +}); + +// ── The reader: KnowledgeService.search ──────────────────────────────────── + +type Row = Record & { id: string }; + +/** A policy source over `policy`: content `body`, metadata `bu` and `owner`. */ +function policySource(name: string, affinity?: KnowledgeAffinityEntry[]): KnowledgeSource { + return { + name, + label: name, + adapter: 'memory', + source: { + kind: 'object', + object: 'policy', + content: ['body'], + metadataFields: ['bu', 'owner'], + ...(affinity ? { affinity } : {}), + } as ObjectKnowledgeSource, + }; +} + +/** The org: Ada sits in bu_team, under bu_dept, under bu_root; bu_sibling is bu_dept's sibling. */ +const UNITS: Row[] = [ + { id: 'bu_team', name: 'Team', kind: 'team', parent_business_unit_id: 'bu_dept' }, + { id: 'bu_dept', name: 'Dept', kind: 'department', parent_business_unit_id: 'bu_root' }, + { id: 'bu_root', name: 'Group', kind: 'company', parent_business_unit_id: null }, + { id: 'bu_sibling', name: 'Sibling', kind: 'department', parent_business_unit_id: 'bu_root' }, +]; +const USERS: Row[] = [{ id: 'u_ada', name: 'Ada', primary_business_unit_id: 'bu_team' }]; + +/** Ten policies, best first by score p1 … p10: the caller's own unit's policies rank 8th and 9th. */ +const POLICIES = (): Row[] => [ + { id: 'p1', body: 'one', bu: 'bu_sibling', owner: 'u_lin' }, + { id: 'p2', body: 'two', bu: 'bu_root', owner: 'u_lin' }, + { id: 'p3', body: 'three', bu: 'bu_sibling', owner: 'u_lin' }, + { id: 'p4', body: 'four', bu: 'bu_dept', owner: 'u_lin' }, + { id: 'p5', body: 'five', bu: 'bu_sibling', owner: 'u_lin' }, + { id: 'p6', body: 'six', bu: 'bu_sibling', owner: 'u_lin' }, + { id: 'p7', body: 'seven', bu: null, owner: 'u_ada' }, + { id: 'p8', body: 'eight', bu: 'bu_team', owner: 'u_lin' }, + { id: 'p9', body: 'nine', bu: 'bu_team', owner: 'u_lin' }, + { id: 'p10', body: 'ten', bu: 'bu_sibling', owner: 'u_lin' }, +]; + +function indexHit(source: KnowledgeSource, row: Row, n: number, score: number): KnowledgeHit { + const doc = recordToDocument(source, source.source as ObjectKnowledgeSource, row); + return { + chunkId: `${doc.id}#${n}`, + documentId: doc.id, + sourceId: source.name, + sourceRecordId: row.id, + score, + snippet: `${String(row.body)} (${n})`, + metadata: doc.metadata, + docHash: doc.docHash, + }; +} + +interface EngineOptions { + /** Ids the caller's reads refuse, with the status of the throw. */ + refuse?: Record; +} + +/** An engine keyed by object: `policy` rows, and the identity rows the resolver reads. */ +function orgEngine(policies: Row[], opts: EngineOptions = {}) { + const tables: Record = { policy: policies, sys_user: USERS, sys_business_unit: UNITS, sys_organization: [{ id: 'org_1', name: 'Org' }] }; + const matches = (row: Row, where: Record = {}): boolean => + Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Record[]).every((w) => matches(row, w)); + if (v !== null && typeof v === 'object') return (v as { $in: string[] }).$in.includes(row[k] as string); + return row[k] === v; + }); + const identityReads: Array<{ object: string; id: unknown; context: unknown }> = []; + const find = vi.fn(async (object: string, q: { where?: Record; fields?: string[]; limit?: number; context?: unknown }) => { + if (object !== 'policy') { + const id = q.where?.id; + identityReads.push({ object, id, context: q.context }); + const status = typeof id === 'string' ? opts.refuse?.[id] : undefined; + if (status !== undefined) throw Object.assign(new Error(`refused ${String(id)}`), { status }); + } + const rows = (tables[object] ?? []).filter((r) => matches(r, q.where)); + const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows; + return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r })); + }); + return { engine: { find } as unknown as IDataEngine, identityReads }; +} + +function searchSetup(sources: KnowledgeSource[], engineOpts: EngineOptions = {}, answerless: readonly string[] = []) { + const table = POLICIES(); + const corpus = Object.fromEntries( + sources.map((s) => [s.name, answerless.includes(s.name) ? [] : table.map((r, i) => indexHit(s, r, 0, 1 - i / 20))]), + ); + const adapter = { + id: 'memory', + upsert: vi.fn(async () => undefined), + delete: vi.fn(async () => undefined), + search: vi.fn(async (_q: string, o: { source: KnowledgeSource; topK: number }) => + [...(corpus[o.source.name] ?? [])].sort((a, b) => b.score - a.score).slice(0, o.topK)), + } as unknown as IKnowledgeAdapter; + const { engine, identityReads } = orgEngine(table, engineOpts); + const warn = vi.fn(); + const debug = vi.fn(); + const svc = new KnowledgeService({ dataEngine: engine, logger: { debug, warn } }); + svc.registerAdapter('memory', adapter); + for (const s of sources) svc.registerSource(s); + return { svc, identityReads, warn, debug }; +} + +const records = (hits: KnowledgeHit[]): string[] => hits.map((h) => h.sourceRecordId!); + +describe('KnowledgeService.search — a declared affinity re-orders before the cut to topK', () => { + it('nearest, chunk granularity, topK 5: the caller\'s own unit first, then the parents, units from below topK brought up', async () => { + const { svc, identityReads } = searchSetup([policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])]); + const out = await svc.search('q', { topK: 5, executionContext: ADA }); + expect(records(out)).toEqual(['p8', 'p9', 'p4', 'p2', 'p1']); + // A hit keeps the score its adapter answered: the answer is no longer in descending score. + expect(out.map((h) => h.score)).toEqual([1 - 7 / 20, 1 - 8 / 20, 1 - 3 / 20, 1 - 1 / 20, 1]); + // The facts were read once, as the caller: their user row (for the primary unit) and each unit of their + // chain. No organization row: no entry reads it. + expect(identityReads.map((r) => `${r.object}:${String(r.id)}`)).toEqual([ + 'sys_user:u_ada', 'sys_business_unit:bu_team', 'sys_business_unit:bu_dept', 'sys_business_unit:bu_root', + ]); + expect(identityReads.every((r) => r.context === ADA)).toBe(true); + }); + + it('boost by the caller\'s user: a match passes at most `places` hits, and a user-only source reads no row', async () => { + const { svc, identityReads } = searchSetup([policySource('policies', [{ field: 'owner', caller: 'user', mode: 'boost', places: 3 }])]); + // p7 is number 7, key 4: it passes p4, p5 and p6, and stops behind p3 (key 3). + expect(records(await svc.search('q', { topK: 5, executionContext: ADA }))).toEqual(['p1', 'p2', 'p3', 'p7', 'p4']); + // `user` is the search's own userId: no sys_user, sys_organization or sys_business_unit row is read. + expect(identityReads).toEqual([]); + }); + + it('no hit of a declaring source in the list: no fact is read', async () => { + const { svc, identityReads } = searchSetup( + [policySource('policies'), policySource('ordered', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])], + {}, + ['ordered'], + ); + const out = await svc.search('q', { topK: 5, sourceIds: ['policies', 'ordered'], executionContext: ADA }); + expect(records(out)).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + expect(identityReads).toEqual([]); + }); + + it('record granularity: each record stands as one unit, re-ordered before the cut', async () => { + const { svc } = searchSetup([policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])]); + const out = await svc.search('q', { topK: 3, granularity: 'record', executionContext: ADA }); + expect(records(out)).toEqual(['p8', 'p9', 'p4']); + }); + + it('a source without affinity answers exactly as before, and no identity is read', async () => { + const plain = searchSetup([policySource('policies')]); + const out = await plain.svc.search('q', { topK: 5, executionContext: ADA }); + expect(records(out)).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + expect(plain.identityReads).toEqual([]); + // Another source's affinity moves none of this source's hits. + const mixed = searchSetup([policySource('policies'), policySource('ordered', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])]); + const both = await mixed.svc.search('q', { topK: 20, sourceIds: ['policies', 'ordered'], executionContext: ADA }); + const plainHits = both.filter((h) => h.sourceId === 'policies'); + expect(records(plainHits)).toEqual(records(await plain.svc.search('q', { topK: 10, executionContext: ADA }))); + }); + + it('the system identity has no facts: no re-order and no identity read', async () => { + const { svc, identityReads } = searchSetup([policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])]); + expect(records(await svc.search('q', { topK: 5, executionContext: SYSTEM }))).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + expect(identityReads).toEqual([]); + }); + + it('a unit the caller may not read ends the chain below it: its parents are not their units', async () => { + const { svc } = searchSetup([policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])], { refuse: { bu_dept: 403 } }); + // The chain is bu_team alone: p8 and p9 first, every other hit in the adapter's order after them. + expect(records(await svc.search('q', { topK: 5, executionContext: ADA }))).toEqual(['p8', 'p9', 'p1', 'p2', 'p3']); + }); + + it('a unit read that fails for another reason leaves the units out, keeps the user boost, and says so once at warn', async () => { + const { svc, warn } = searchSetup( + [policySource('policies', [ + { field: 'bu', caller: 'business_unit', mode: 'nearest' }, + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, + ])], + { refuse: { u_ada: 500 } }, + ); + // No chain: every hit sits in the last nearest tier, where the user boost still lifts p7 as in the boost-only case. + expect(records(await svc.search('q', { topK: 5, executionContext: ADA }))).toEqual(['p1', 'p2', 'p3', 'p7', 'p4']); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toContain("could not resolve the caller's business units for the affinity of 'policies'"); + }); + + it('nothing is dropped: a hit outside the caller\'s units is ordered later, never removed', async () => { + const { svc } = searchSetup([policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }])]); + const out = await svc.search('q', { topK: 10, executionContext: ADA }); + expect([...records(out)].sort()).toEqual(POLICIES().map((r) => r.id).sort()); + expect(records(out)).toEqual(['p8', 'p9', 'p4', 'p2', 'p1', 'p3', 'p5', 'p6', 'p7', 'p10']); + }); +}); + +describe('affinity changes no index: neither the fingerprint nor the recipe hash reads it', () => { + it('the same hashes with and without the key; the recipe hash still reads metadataFields (control)', () => { + const plain = policySource('policies'); + const ordered = policySource('policies', [{ field: 'bu', caller: 'business_unit', mode: 'nearest' }]); + const embedding = { model: 'text-embedding-3-small', dimensions: 1536 }; + const split = { strategy: 'whole' as const, maxChars: 800, minChars: 200 }; + expect(computeIndexFingerprint({ source: ordered, embedding, split })).toBe(computeIndexFingerprint({ source: plain, embedding, split })); + const schema = { name: 'policy', fields: { body: { type: 'textarea' }, bu: { type: 'lookup', reference: 'sys_business_unit' }, owner: { type: 'user' } } }; + expect(computeRecipeHash({ source: ordered, schema })).toBe(computeRecipeHash({ source: plain, schema })); + const fewer = { ...plain, source: { ...plain.source, metadataFields: ['bu'] } } as KnowledgeSource; + expect(computeRecipeHash({ source: fewer, schema })).not.toBe(computeRecipeHash({ source: plain, schema })); + }); +}); + +// ── The save door ────────────────────────────────────────────────────────── + +describe('the save door refuses an affinity field that does not point at its caller\'s object', () => { + const POLICY = { + name: 'policy', + fields: { + body: { type: 'textarea' }, + title: { type: 'text' }, + owner: { type: 'user' }, + approver: { type: 'lookup', reference: 'sys_user' }, + bu: { type: 'lookup', reference: 'sys_business_unit' }, + bus: { type: 'lookup', reference: 'sys_business_unit', multiple: true }, + project: { type: 'lookup', reference: 'project' }, + }, + }; + function saveSetup() { + const engine = { + find: vi.fn(async () => []), + getSchema: (name: string) => (name === POLICY.name ? POLICY : undefined), + registry: { isObjectPackageDisabled: () => false }, + } as unknown as IDataEngine; + const svc = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, error: () => undefined } }); + svc.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }); + return Object.assign(svc, { find: (engine as unknown as { find: ReturnType }).find }); + } + const item = (affinity: unknown[], metadataFields = ['owner', 'approver', 'bu', 'bus', 'project', 'title']) => ({ + name: 'policies', + label: 'Policies', + adapter: 'memory', + source: { kind: 'object', object: 'policy', content: ['body'], metadataFields, affinity }, + }); + type Refusal = { admitted: false; status: number; code: string; message: string; field?: string }; + + it.each([ + ['business_unit on a lookup to project', { field: 'project', caller: 'business_unit', mode: 'nearest' }, "a field that points at 'project'", "points at 'sys_business_unit'"], + ['business_unit on a user field', { field: 'owner', caller: 'business_unit', mode: 'boost', places: 2 }, "a field that points at 'sys_user'", "write `caller: 'user'`"], + ['a nearest on a user field: pointed at a boost, never at nearest with caller user', { field: 'owner', caller: 'business_unit', mode: 'nearest' }, "a field that points at 'sys_user'", "write a `boost` entry with `caller: 'user'` and `places`"], + ['user on a lookup to sys_business_unit', { field: 'bu', caller: 'user', mode: 'boost', places: 2 }, "a field that points at 'sys_business_unit'", "write `caller: 'business_unit'`"], + ['user on a text field', { field: 'title', caller: 'user', mode: 'boost', places: 1 }, 'a `text` field that points at no object', "points at 'sys_user'"], + ])('refuses %s, 400 VALIDATION_ERROR, naming the field and the fix', async (_what, entry, why, fix) => { + const svc = saveSetup(); + const verdict = (await svc.admitAuthoredSource(item([entry]), ADA)) as Refusal; + expect(verdict).toMatchObject({ admitted: false, status: 400, code: 'VALIDATION_ERROR', field: entry.field }); + // The door compares the target's name with its caller's object: it reads no record of the target. + expect(svc.find).not.toHaveBeenCalled(); + expect(verdict.message).toContain(`\`source.affinity[0]\` compares field '${entry.field}' of object 'policy'`); + expect(verdict.message).toContain(why); + expect(verdict.message).toContain(fix); + }); + + it('admits a user field, a lookup to sys_user, and a single or multiple lookup to sys_business_unit', async () => { + const svc = saveSetup(); + const sound = [ + { field: 'owner', caller: 'user', mode: 'boost', places: 3 }, + { field: 'approver', caller: 'user', mode: 'boost', places: 1 }, + { field: 'bu', caller: 'business_unit', mode: 'nearest' }, + { field: 'bus', caller: 'business_unit', mode: 'boost', places: 2 }, + ]; + expect(await svc.admitAuthoredSource(item(sound), ADA)).toEqual({ admitted: true }); + }); + + it('a field metadataFields does not list is left to the parse, which names that fix', async () => { + expect(await saveSetup().admitAuthoredSource(item([{ field: 'project', caller: 'user', mode: 'boost', places: 1 }], ['owner']), ADA)) + .toEqual({ admitted: true }); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-affinity.ts b/packages/services/service-knowledge/src/knowledge-affinity.ts new file mode 100644 index 00000000000..743cc14118e --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-affinity.ts @@ -0,0 +1,193 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161, the dated note of 2026-11-29 under K1] `source.affinity`: a + * source orders its own hits for the caller, by position and never by score. + * + * Two halves, both pure but for the one resolver call: + * + * - {@link resolveAffinityFacts} — the caller facts an entry may read, a + * closed list of two: `user` (the caller's user id) and `business_unit` + * (their primary business unit, then each parent up to the root). Each is + * resolved only when a declared entry reads it, at most once per search: `user` is + * the search's own `userId` (no read), and the chain comes from the one + * resolver of the caller's identity (`resolveCallerIdentity`, + * `@objectstack/core`), whose every read runs AS the caller, so a unit the + * caller may not read ends the chain below it. The system identity is no + * caller in this sense and has no facts; a caller with no primary unit has + * no chain. A fact is never a tool argument, a `search` option, or a value + * a client or a model supplies. + * - {@link orderByAffinity} — the re-order of the units a search could answer + * (passages, records or `groupBy` groups, each standing as one hit), best + * first by the adapters' scores, before the cut to `topK`: + * 1. per source: a source's units are re-ordered among the places they hold + * in the list, and a unit of another source never moves; + * 2. a unit is judged on the hit that stands for it: that hit's source and + * its `metadata[field]`; + * 3. `nearest` parts the source's units into tiers: the caller's own unit + * first, then each parent in order, then every other unit together (a + * hit with no value among them); + * 4. inside a tier, its units numbered from 1 in their order, a unit's key + * is its number minus the sum of `places` of the `boost` entries it + * matches; the tier is ordered by key, a tie to the larger sum, then to + * the earlier number; + * 5. a hit keeps its adapter's `score`: no score is written. + * + * Values are compared as a scope term compares them: a stored string or + * number matches when `String(value)` is the fact, a list (a lookup declared + * `multiple: true`) when an element does, and `nearest` takes the nearest + * element. An entry that finds no fact matches nothing. Nothing is dropped or + * admitted, and nothing in the answer says a hit moved. + */ + +import { resolveCallerIdentity, type CallerRecordReader } from '@objectstack/core'; +import type { KnowledgeAffinityEntry, KnowledgeHit } from '@objectstack/spec/ai'; + +/** The caller facts an affinity entry reads (the note's closed list of two). */ +export interface AffinityCallerFacts { + /** The caller's user id, when they are a signed-in user. */ + user?: string; + /** The caller's primary business unit, then each parent up to the root, as far as the caller may read. */ + businessUnits: readonly string[]; +} + +/** No facts: the system identity, a caller with no user, or a resolve that failed. */ +export const NO_AFFINITY_FACTS: AffinityCallerFacts = Object.freeze({ businessUnits: Object.freeze([]) as readonly string[] }); + +/** The caller context the facts are read from (a subset of `ExecutionContext`). */ +export interface AffinityCaller { + userId?: unknown; + isSystem?: unknown; +} + +/** Which caller facts a search's declared entries read: only those are resolved. */ +export interface AffinityFactNeeds { + /** An entry reads `caller: 'user'`: the search's own `userId`, no read. */ + user: boolean; + /** An entry reads `caller: 'business_unit'`: the user row's primary unit, then each unit up the chain. */ + businessUnit: boolean; +} + +/** The facts the given entries read (the declared entries of the sources with a hit in the list). */ +export function affinityFactNeeds(entries: Iterable): AffinityFactNeeds { + const needs: AffinityFactNeeds = { user: false, businessUnit: false }; + for (const entry of entries) { + if (entry.caller === 'user') needs.user = true; + else if (entry.caller === 'business_unit') needs.businessUnit = true; + } + return needs; +} + +/** + * The caller's facts, at most one resolve per search, and only those `needs` + * names. `user` is the caller's own `userId`, read from the context and never + * from a row. `business_unit` is the one resolver's chain (`resolveCallerIdentity`), + * handed the user id alone so it reads no organization row: the user row for + * the primary unit, then each unit up the chain, every read AS the caller. A + * fault on those reads other than a refusal is handed to `onUnitFault` and + * leaves the chain empty, keeping the `user` fact; with no `onUnitFault` it + * is thrown. The system identity, and a caller with no user, have no facts. + */ +export async function resolveAffinityFacts( + caller: AffinityCaller | undefined, + read: CallerRecordReader, + needs: AffinityFactNeeds, + onUnitFault?: (err: unknown) => void, +): Promise { + if (!caller || caller.isSystem === true) return NO_AFFINITY_FACTS; + const userId = typeof caller.userId === 'string' && caller.userId !== '' ? caller.userId : undefined; + if (userId === undefined) return NO_AFFINITY_FACTS; + let businessUnits: readonly string[] = []; + if (needs.businessUnit) { + try { + const identity = await resolveCallerIdentity({ userId }, read); + businessUnits = (identity.businessUnits ?? []).map((unit) => unit.id); + } catch (err) { + if (onUnitFault === undefined) throw err; + onUnitFault(err); + } + } + return { ...(needs.user ? { user: userId } : {}), businessUnits }; +} + +/** The elements of a stored value a fact is compared with: strings and numbers, as `String(value)`. */ +function elementsOf(value: unknown): string[] { + const list = Array.isArray(value) ? value : [value]; + const out: string[] = []; + for (const element of list) { + if (typeof element === 'string' || typeof element === 'number') out.push(String(element)); + } + return out; +} + +/** Whether a `boost` entry matches the stored value. */ +function boostMatches(entry: KnowledgeAffinityEntry, elements: readonly string[], facts: AffinityCallerFacts): boolean { + if (entry.caller === 'user') return facts.user !== undefined && elements.includes(facts.user); + return elements.some((element) => facts.businessUnits.includes(element)); +} + +/** The tier of a unit under a `nearest` entry: the chain index of its nearest element, else the chain's length. */ +function nearestTier(elements: readonly string[], chain: readonly string[]): number { + let tier = chain.length; + for (const element of elements) { + const at = chain.indexOf(element); + if (at !== -1 && at < tier) tier = at; + } + return tier; +} + +/** + * Re-order `units` by the affinity their sources declare, per source among + * the places that source's units hold. `hitOf` names the hit standing for a + * unit; `entriesOf` answers a hit's source's entries (by the `sourceId` the + * hit carries). Answers the list (a new array; `units` is not mutated) and + * how many units now stand at another place, for the `debug` log. + */ +export function orderByAffinity( + units: readonly T[], + hitOf: (unit: T) => KnowledgeHit, + entriesOf: (sourceId: string) => readonly KnowledgeAffinityEntry[] | undefined, + facts: AffinityCallerFacts, +): { units: T[]; moved: number } { + const out = [...units]; + const placesBySource = new Map(); + units.forEach((unit, i) => { + const sourceId = hitOf(unit).sourceId; + const entries = entriesOf(sourceId); + if (!entries || entries.length === 0) return; + const places = placesBySource.get(sourceId); + if (places) places.push(i); + else placesBySource.set(sourceId, [i]); + }); + let moved = 0; + for (const [sourceId, places] of placesBySource) { + const entries = entriesOf(sourceId)!; + const nearest = entries.find((entry) => entry.mode === 'nearest'); + const boosts = entries.filter((entry) => entry.mode === 'boost'); + const judged = places.map((place) => { + const metadata = hitOf(units[place]!).metadata ?? {}; + const tier = nearest ? nearestTier(elementsOf(metadata[nearest.field]), facts.businessUnits) : 0; + let sum = 0; + for (const entry of boosts) { + if (boostMatches(entry, elementsOf(metadata[entry.field]), facts)) sum += entry.places ?? 0; + } + return { place, tier, sum, number: 0, key: 0 }; + }); + // Number each unit from 1 inside its tier, in the order the list holds them. + const countInTier = new Map(); + for (const unit of judged) { + const number = (countInTier.get(unit.tier) ?? 0) + 1; + countInTier.set(unit.tier, number); + unit.number = number; + unit.key = number - unit.sum; + } + const ordered = [...judged].sort((a, b) => + a.tier - b.tier || a.key - b.key || b.sum - a.sum || a.number - b.number); + ordered.forEach((unit, i) => { + const place = places[i]!; + if (unit.place !== place) moved++; + out[place] = units[unit.place]!; + }); + } + return { units: out, moved }; +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 683f46c1a7a..d146025378b 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -31,6 +31,7 @@ import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; import { createKnowledgeTools, documentUnitValueOf, refusal, type KnowledgeTools } from './knowledge-tools.js'; import { resolveSplit, splitDocument, type ResolvedSplit } from './split/index.js'; import { indexExpectation } from './knowledge-index-fingerprint.js'; +import { affinityFactNeeds, orderByAffinity, resolveAffinityFacts, type AffinityCallerFacts } from './knowledge-affinity.js'; import { KnowledgeSourceRegistry, codedError, @@ -51,6 +52,7 @@ import { declaredFields, documentTitleField, documentUnitRefusalText, + affinityTargetRefusalText, type KnowledgeAdmissionDeps, type KnowledgeFieldSecurity, type KnowledgeSourceAdmission, @@ -2595,8 +2597,13 @@ export class KnowledgeService implements IKnowledgeService { ); } kept.sort((a, b) => b.score - a.score); - if (!byRecord) return { hits: kept.slice(0, topK), refused }; - const { hits: answer, capped } = await this.answerByRecord(kept, topK, groupOf); + // [ADR-0161, the dated note of 2026-11-29 under K1] A source that declares + // `affinity` re-orders its own units for the caller, by position, before + // the cut to `topK`; the rounds, the refill and the re-check above are + // unchanged, and so is every source that declares none. + const order = await this.affinityOrderFor(kept, ctx); + if (!byRecord) return { hits: order(kept).slice(0, topK), refused }; + const { hits: answer, capped } = await this.answerByRecord(kept, topK, groupOf, order); if (answer.length < topK && !capped) { this.options.logger?.debug?.( `[knowledge] record-level search answered ${answer.length} of topK=${topK} ` + @@ -2636,9 +2643,83 @@ export class KnowledgeService implements IKnowledgeService { return `value:${stableJson(value)}`; } + /** + * [ADR-0161, the dated note of 2026-11-29 under K1] The affinity order of + * one search ({@link orderByAffinity}): the identity when no hit in the list + * belongs to a source that declares `affinity`, else a function that + * re-orders a best-first list of units, each standing as its hit, per source + * among the places that source's units hold. + * + * The caller's facts are resolved here, at most once per search, and only + * those a declared entry of a source with a hit in the list reads + * ({@link affinityFactNeeds}): `user` is the search's own `ctx.userId` and + * costs no read; `business_unit` reads the caller's user row for its primary + * unit and each unit up the chain, by id AS the caller through the data + * engine (permissions, row-level security and field masking), so a unit the + * caller may not read ends their chain below it. No organization row is + * read. The system identity has no facts. A unit read that fails for a + * reason other than a refusal leaves the units out, reported once at `warn`, + * and keeps the `user` fact: the order is a convenience, and every hit it + * would have moved is still answered. How many units moved goes to the + * `debug` log, never to the answer. + */ + private async affinityOrderFor( + kept: readonly KnowledgeHit[], + ctx: ExecutionContext | undefined, + ): Promise<(units: KnowledgeHit[]) => KnowledgeHit[]> { + const identity = (units: KnowledgeHit[]): KnowledgeHit[] => units; + if (ctx === undefined) return identity; + const entriesOf = (sourceId: string) => this.handed(sourceId)?.source.affinity; + const declaring = new Map(); + for (const hit of kept) { + if (declaring.has(hit.sourceId) || (entriesOf(hit.sourceId)?.length ?? 0) === 0) continue; + declaring.set(hit.sourceId, this.handed(hit.sourceId)!); + } + if (declaring.size === 0) return identity; + const facts = await this.affinityFactsOf(ctx, [...declaring.values()]); + return (units) => { + const { units: ordered, moved } = orderByAffinity(units, (hit) => hit, entriesOf, facts); + if (moved > 0) { + this.options.logger?.debug?.(`[knowledge] affinity re-ordered ${moved} of ${units.length} unit(s) for the caller.`); + } + return ordered; + }; + } + + /** The caller facts of one search ({@link affinityOrderFor}), only those the declaring sources' entries read. */ + private async affinityFactsOf(ctx: ExecutionContext, declaring: readonly KnowledgeSource[]): Promise { + const engine = this.options.dataEngine; + const needs = affinityFactNeeds(declaring.flatMap((source) => source.source.affinity ?? [])); + return resolveAffinityFacts( + ctx, + async (object, id, fields) => { + if (engine === undefined) return undefined; + const rows = (await engine.find(object, { + where: { id } as Record, + fields: [...fields], + limit: 1, + context: ctx, + } as never)) as Array> | undefined; + const row = Array.isArray(rows) ? rows[0] : undefined; + return row && typeof row === 'object' ? row : undefined; + }, + needs, + (err) => { + this.options.logger?.warn?.( + `[knowledge] could not resolve the caller's business units for the affinity of ` + + `${declaring.map((source) => `'${this.label(source)}'`).join(', ')}: ${(err as Error).message}; ` + + 'their business-unit entries match nothing for this search.', + ); + }, + ); + } + + /** * The record-level answer: one hit per group, the group's best passage, - * best group first, at most `topK`. `hits` is sorted best first. + * best group first, at most `topK`, after `order` re-orders the groups for + * the caller (a source's `affinity`, {@link affinityOrderFor}) ahead of the + * cut. `hits` is sorted best first. * * ## The freshness check * @@ -2667,6 +2748,7 @@ export class KnowledgeService implements IKnowledgeService { hits: KnowledgeHit[], topK: number, groupOf: (hit: KnowledgeHit) => string | undefined, + order: (units: KnowledgeHit[]) => KnowledgeHit[] = (units) => units, ): Promise<{ hits: KnowledgeHit[]; capped: boolean }> { const groups = new Map(); for (const hit of hits) { @@ -2692,7 +2774,8 @@ export class KnowledgeService implements IKnowledgeService { }); if (lead) out.push(lead); } - return out.sort((a, b) => b.score - a.score).slice(0, topK); + // Each group stands as one unit, judged on its lead (the affinity order). + return order(out.sort((a, b) => b.score - a.score)).slice(0, topK); }; for (let round = 0; ; round++) { const top = leads(); @@ -4155,7 +4238,8 @@ export class KnowledgeService implements IKnowledgeService { * * `item` is the body as the door hands it to the protocol, not yet parsed. * What is read of it is `source.object`, `source.content`, - * `source.metadataFields` and the fields `source.where` reads (and `source.contentFields`, the spelling the + * `source.metadataFields`, `source.documentBy`, each `source.affinity` entry + * and the fields `source.where` reads (and `source.contentFields`, the spelling the * ADR-0087 kit renames to `content`, so a converted save is judged on the * fields it will index). An item with no object to judge is admitted here: * the protocol's parse refuses it with the schema's own prescription. @@ -4171,7 +4255,12 @@ export class KnowledgeService implements IKnowledgeService { * lists and that is not a single-valued parent link of the object * (`documentUnitOf`: a `lookup` or `master_detail` field, not `multiple`, * neither credential-class nor `internal`) is refused `400 - * VALIDATION_ERROR`, naming the field and the fix. A source whose `adapter` names no + * VALIDATION_ERROR`, naming the field and the fix; then a `source.affinity` + * entry whose listed `field` does not point at the object its `caller` + * names (`sys_user` for `user`, `sys_business_unit` for `business_unit`, + * {@link affinityTargetRefusalText}) is refused `400 VALIDATION_ERROR`, + * naming the field and the fix, judged on the definition alone with no + * record read. A source whose `adapter` names no * adapter this deployment mounts is refused `400 VALIDATION_ERROR`, naming * the source, the adapter and the mounted ones; an omitted `adapter` is not * (it is placed by {@link adapterIdFor}). That check is this door's only: @@ -4320,6 +4409,31 @@ export class KnowledgeService implements IKnowledgeService { } } + // [`source.affinity`] An entry whose field does not point at the object + // its caller fact names would match nothing: a permanent mistake, judged + // on the object's definition alone. A field not listed in + // `metadataFields` is left to the parse, which names that fix. + const affinity = (declared as { affinity?: unknown }).affinity; + if (Array.isArray(affinity) && affinity.length > 0) { + let schema: unknown; + try { + const deps = this.admissionDeps(engine); + schema = deps.isObjectPackageDisabled(object) ? undefined : deps.readSchema(object); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (schema !== undefined) { + for (const [i, entry] of affinity.entries()) { + if (entry === null || typeof entry !== 'object') continue; + const field = (entry as { field?: unknown }).field; + if (typeof field !== 'string' || !objSource.metadataFields?.includes(field)) continue; + const text = affinityTargetRefusalText(object, schema, entry as { field?: unknown; caller?: unknown; mode?: unknown }, i); + if (text !== undefined) return refuse(400, 'VALIDATION_ERROR', `${named}: ${text}${wording.thenAgain}.`, field); + } + } + } + let admission: ObjectAdmission; try { admission = await admitObject(object, ctx, this.admissionDeps(engine)); diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index 7054685acee..10a4bea52f4 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -104,6 +104,7 @@ import { FieldReferenceSchema, canServeApiOperation, isAiReadExposed, + referenceTargetOf, resolveDisplayField, type EnableLike, type TitleEligibleFieldDef, @@ -422,3 +423,56 @@ export function documentUnitRefusalText( `belongs to no one document. ${fix}; it must hold one parent (not \`multiple\`)`; } } + +/** The object each `source.affinity` caller fact is compared with: the field must point at it. */ +export const AFFINITY_CALLER_TARGETS: Readonly> = Object.freeze({ + user: 'sys_user', + business_unit: 'sys_business_unit', +}); + +/** + * [`source.affinity`, ADR-0161, the dated note of 2026-11-29 under K1] The + * save-time refusal of an affinity entry whose `field` does not point at the + * object its `caller` names (`sys_user` for `user`, `sys_business_unit` for + * `business_unit`): such an entry compares a value that is never the caller's + * id, so it would match nothing. Judged on the object's definition alone, + * through the spec's one answer for a field's target (`referenceTargetOf`). + * Answers `undefined` when the entry is sound, or when the object or the + * field is not declared (the "does not exist" arm judges that). The remedy + * it offers is one the parse admits: a `nearest` entry is pointed at a + * `boost`, since `nearest` takes `caller: 'business_unit'` alone. The + * sentence ends without its full stop, so the door can add its own remedy. + */ +export function affinityTargetRefusalText( + object: string, + schema: unknown, + entry: { field?: unknown; caller?: unknown; mode?: unknown }, + index: number, +): string | undefined { + const { field, caller, mode } = entry; + if (typeof field !== 'string' || (caller !== 'user' && caller !== 'business_unit')) return undefined; + const def = declaredFields(schema)?.find(([name]) => name === field)?.[1]; + if (def === undefined) return undefined; + const expected = AFFINITY_CALLER_TARGETS[caller]; + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + target = undefined; + } + if (target === expected) return undefined; + const type = (def as { type?: unknown } | null)?.type; + const what = target === undefined + ? `${typeof type === 'string' ? `a \`${type}\` field` : 'a field'} that points at no object` + : `a field that points at '${target}'`; + return `\`source.affinity[${index}]\` compares field '${field}' of object '${object}' with the caller's ` + + `${caller === 'user' ? 'user id' : 'business units'}, but '${field}' is ${what}, so its value is never the caller's and ` + + `the entry would match nothing. Name a field of '${object}' that points at '${expected}' ` + + `(${caller === 'user' ? "a `user` field, or a lookup to 'sys_user'" : "a lookup to 'sys_business_unit'"}), ` + + `also listed in \`metadataFields\`, or ${caller === 'user' + ? "write `caller: 'business_unit'` for a field that points at 'sys_business_unit'" + : mode === 'nearest' + ? "write a `boost` entry with `caller: 'user'` and `places` for a field that points at 'sys_user' " + + '(`nearest` orders by business unit only)' + : "write `caller: 'user'` for a field that points at 'sys_user'"}`; +} diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index 5bc9ef1545d..9cab070bb5a 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -184,10 +184,11 @@ export interface SearchKnowledgeRefusedSource { /** A `search_knowledge` answer. */ export interface SearchKnowledgeOutput { /** - * The hits, most relevant first, at most `topK`: passages, or one per - * record under `granularity: 'record'` (one per parent record, for a source - * that declares `documentBy`, its document unit), or one per group under - * `groupBy`. + * The hits, most relevant first (a source that declares `affinity` orders + * its own hits for the asker among the places they hold), at most `topK`: + * passages, or one per record under `granularity: 'record'` (one per parent + * record, for a source that declares `documentBy`, its document unit), or + * one per group under `groupBy`. * No count of what the permission re-check or the scope removed, and * nothing derived from one (ADR-0161 K9, rule 6). */ diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index fbc00deb6cc..b5f1388e297 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -131,6 +131,16 @@ "GetRecordContextOutputParsed (type)", "GetRecordContextOutputSchema (const)", "ImageContentSchema (const)", + "KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KnowledgeAffinityCaller (type)", + "KnowledgeAffinityCallerParsed (type)", + "KnowledgeAffinityCallerSchema (const)", + "KnowledgeAffinityEntry (type)", + "KnowledgeAffinityEntryParsed (type)", + "KnowledgeAffinityEntrySchema (const)", + "KnowledgeAffinityMode (type)", + "KnowledgeAffinityModeParsed (type)", + "KnowledgeAffinityModeSchema (const)", "KnowledgeChunk (type)", "KnowledgeChunkSchema (const)", "KnowledgeDocument (type)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 8d3bf84cbd8..0ee44069dda 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -260,6 +260,10 @@ "ai/ImageContent:imageUrl", "ai/ImageContent:metadata", "ai/ImageContent:type", + "ai/KnowledgeAffinityEntry:caller", + "ai/KnowledgeAffinityEntry:field", + "ai/KnowledgeAffinityEntry:mode", + "ai/KnowledgeAffinityEntry:places", "ai/KnowledgeChunk:content", "ai/KnowledgeChunk:documentId", "ai/KnowledgeChunk:headingPath", @@ -380,6 +384,7 @@ "ai/ModelSelectionCriteria:minContextWindow", "ai/ModelSelectionCriteria:provider", "ai/ModelSelectionCriteria:tags", + "ai/ObjectKnowledgeSource:affinity", "ai/ObjectKnowledgeSource:content", "ai/ObjectKnowledgeSource:contentFields [RETIRED]", "ai/ObjectKnowledgeSource:documentBy", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 5c53d6cc8af..8a975cdd035 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -87,6 +87,12 @@ "GetRecordContextOutput": "ai/GetRecordContextOutput", "GetRecordContextOutputSchema": "ai/GetRecordContextOutput", "ImageContentSchema": "ai/ImageContent", + "KnowledgeAffinityCaller": "ai/KnowledgeAffinityCaller", + "KnowledgeAffinityCallerSchema": "ai/KnowledgeAffinityCaller", + "KnowledgeAffinityEntry": "ai/KnowledgeAffinityEntry", + "KnowledgeAffinityEntrySchema": "ai/KnowledgeAffinityEntry", + "KnowledgeAffinityMode": "ai/KnowledgeAffinityMode", + "KnowledgeAffinityModeSchema": "ai/KnowledgeAffinityMode", "KnowledgeChunk": "ai/KnowledgeChunk", "KnowledgeChunkSchema": "ai/KnowledgeChunk", "KnowledgeDocument": "ai/KnowledgeDocument", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index a6408ee88e9..e1fbc947acb 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 283, - "droppedRefinementSites": 1245, + "publishedSchemasWithDroppedRefinements": 284, + "droppedRefinementSites": 1252, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -77,14 +77,21 @@ "runtimeFilter.lazy" ] }, + "ai/KnowledgeAffinityEntry": { + "sites": [ + "" + ] + }, "ai/KnowledgeSource": { "sites": [ - "source" + "source", + "source.affinity.element" ] }, "ai/ObjectKnowledgeSource": { "sites": [ - "" + "", + "affinity.element" ] }, "ai/ObjectQuerySource": { @@ -199,6 +206,7 @@ "manifest.jobs.element", "manifest.jobs.element.schedule.options[0].timezone", "manifest.knowledgeSources.element.source", + "manifest.knowledgeSources.element.source.affinity.element", "manifest.mappings.element", "manifest.mappings.element.connectorSource.paging", "manifest.navigationContributions.element.items.element.lazy", @@ -399,6 +407,7 @@ "data.options[1].manifest.jobs.element", "data.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.options[1].manifest.knowledgeSources.element.source", + "data.options[1].manifest.knowledgeSources.element.source.affinity.element", "data.options[1].manifest.mappings.element", "data.options[1].manifest.mappings.element.connectorSource.paging", "data.options[1].manifest.objectExtensions.element", @@ -584,6 +593,7 @@ "options[1].manifest.jobs.element", "options[1].manifest.jobs.element.schedule.options[0].timezone", "options[1].manifest.knowledgeSources.element.source", + "options[1].manifest.knowledgeSources.element.source.affinity.element", "options[1].manifest.mappings.element", "options[1].manifest.mappings.element.connectorSource.paging", "options[1].manifest.objectExtensions.element", @@ -693,6 +703,7 @@ "data.packages.element.options[1].manifest.jobs.element", "data.packages.element.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.packages.element.options[1].manifest.knowledgeSources.element.source", + "data.packages.element.options[1].manifest.knowledgeSources.element.source.affinity.element", "data.packages.element.options[1].manifest.mappings.element", "data.packages.element.options[1].manifest.mappings.element.connectorSource.paging", "data.packages.element.options[1].manifest.objectExtensions.element", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index d5129c141cd..e7d955f2f85 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -129,6 +129,16 @@ "GetRecordContextOutputParsed": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputParsed (type)", "GetRecordContextOutputSchema": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputSchema (const)", "ImageContentSchema": "src/ai/conversation.zod.ts#ImageContentSchema (const)", + "KNOWLEDGE_AFFINITY_MAX_PLACES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KnowledgeAffinityCaller": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCaller (type)", + "KnowledgeAffinityCallerParsed": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerParsed (type)", + "KnowledgeAffinityCallerSchema": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerSchema (const)", + "KnowledgeAffinityEntry": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityEntry (type)", + "KnowledgeAffinityEntryParsed": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityEntryParsed (type)", + "KnowledgeAffinityEntrySchema": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityEntrySchema (const)", + "KnowledgeAffinityMode": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityMode (type)", + "KnowledgeAffinityModeParsed": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityModeParsed (type)", + "KnowledgeAffinityModeSchema": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityModeSchema (const)", "KnowledgeChunk": "src/ai/knowledge-document.zod.ts#KnowledgeChunk (type)", "KnowledgeChunkSchema": "src/ai/knowledge-document.zod.ts#KnowledgeChunkSchema (const)", "KnowledgeDocument": "src/ai/knowledge-document.zod.ts#KnowledgeDocument (type)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 4045da724c8..4bc2c8920db 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -47,6 +47,9 @@ "ai/GetRecordContextInput", "ai/GetRecordContextOutput", "ai/ImageContent", + "ai/KnowledgeAffinityCaller", + "ai/KnowledgeAffinityEntry", + "ai/KnowledgeAffinityMode", "ai/KnowledgeChunk", "ai/KnowledgeDocument", "ai/KnowledgeHit", diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index 6dd4e79b535..e44ed13b954 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -87,6 +87,40 @@ "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", "note": "Must be one of `metadataFields` (refused at parse otherwise). Enters neither the index fingerprint nor the recipe hash: adding it rebuilds nothing." }, + "affinity": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#affinityOrderFor — a search re-orders the source's units for the caller before the cut to `topK` (chunk granularity in `searchByKey`, record granularity in `answerByRecord`), by `orderByAffinity` (packages/services/service-knowledge/src/knowledge-affinity.ts), against the caller facts `resolveAffinityFacts` reads through `resolveCallerIdentity` (packages/core/src/caller-identity.ts) as the caller; packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource — the save refuses a `field` whose reference target is not the object its `caller` names (`affinityTargetRefusalText`).", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Each `field` must be one of `metadataFields` and at most one entry is `nearest` (refused at parse otherwise). By position, never by score; enters neither the index fingerprint nor the recipe hash: adding it rebuilds nothing.", + "children": { + "field": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-affinity.ts#orderByAffinity — each entry reads the hit's stored `metadata[field]` (strings and numbers, a list by element); packages/services/service-knowledge/src/knowledge-source-admission.ts#affinityTargetRefusalText — the save judges the field's reference target." + }, + "caller": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-affinity.ts#orderByAffinity — `user` compares the caller's user id, `business_unit` the caller's unit chain (packages/services/service-knowledge/src/knowledge-affinity.ts#resolveAffinityFacts, through packages/core/src/caller-identity.ts#resolveCallerIdentity)." + }, + "mode": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-affinity.ts#orderByAffinity — `nearest` parts the source's units into tiers by the chain, `boost` adds `places` to a matching unit's sum." + }, + "places": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-affinity.ts#orderByAffinity — a matching `boost` unit's key is its number in its tier minus the sum of its entries' `places`." + } + } + }, "where": { "status": "live", "verifiedAt": "2026-11-26", diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index 2164603fe91..a575042db63 100644 --- a/packages/spec/liveness/state-counts/knowledge_source.md +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `knowledge_source` | 22 | 0 | 0 | 6 | 0 | 28 | +| `knowledge_source` | 26 | 0 | 0 | 6 | 0 | 32 | diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index cacab98090b..d84610e3be3 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -22,6 +22,9 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `source.where` is the JSON editor (the `report.metadata-form.ts` * `runtimeFilter` precedent): a `where` is an ObjectQL filter object, which * the `filter-builder` widget does not write (it writes a view's rule list). + * - `source.affinity` is the JSON editor too: a list of `{ field, caller, + * mode, places? }` entries whose cross-key rules (a `field` listed in + * `metadataFields`, `places` on a `boost` alone) no list widget states. * * ADR-0161 K5 and K10 rule 5: embedding is egress, so `content` offers named * fields only, and its help says beside it what a build sends and to whom. @@ -73,6 +76,7 @@ export const knowledgeSourceForm = defineMetadataForm({ }, { field: 'metadataFields', label: 'Filter fields', widget: 'field-multi', dependsOn: 'object', helpText: 'Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query.' }, { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does.' }, + { field: 'affinity', label: 'Order for the asker', widget: 'json', helpText: 'Optional. Lists entries that move hits related to the person asking up the answer, for example [{"field": "business_unit", "caller": "business_unit", "mode": "nearest"}] puts their own unit first, then its parent units, then the rest, and [{"field": "owner", "caller": "user", "mode": "boost", "places": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing.' }, { field: 'where', label: 'Records to index', widget: 'json', helpText: 'An ObjectQL filter on the object, for example {"status": {"$ne": "done"}}. Only the records it matches are indexed. Blank: every record.' }, { field: 'split', diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index a35db590229..cf5c5b01ae0 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -27,6 +27,7 @@ import { DEFAULT_METADATA_TYPE_REGISTRY } from '../kernel/metadata-plugin.zod'; import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { ObjectStackDefinitionSchema } from '../stack.zod'; import { + KNOWLEDGE_AFFINITY_MAX_PLACES, KnowledgeSourceSchema, type KnowledgeSource, type KnowledgeSourceParsed, @@ -328,3 +329,89 @@ describe('KnowledgeSourceSchema — `source.documentBy`, the document unit, is o ).toEqual([['invalid_type', 'source.documentBy']]); }); }); + +describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller (ADR-0161, the dated note of 2026-11-29)', () => { + const POLICIES: KnowledgeSource = { + name: 'policies', + label: 'Policies', + source: { kind: 'object', object: 'policy', content: ['body'], metadataFields: ['business_unit', 'owner'] }, + }; + const withAffinity = (affinity: unknown): unknown => ({ ...POLICIES, source: { ...POLICIES.source, affinity } }); + const NEAREST = { field: 'business_unit', caller: 'business_unit', mode: 'nearest' }; + const BOOST = { field: 'owner', caller: 'user', mode: 'boost', places: 3 }; + + it('positive control: a nearest and a boost entry parse and are kept as written; absent stays absent', () => { + const parsed = KnowledgeSourceSchema.parse(withAffinity([NEAREST, BOOST])); + expect(parsed.source.affinity).toEqual([NEAREST, BOOST]); + expect('affinity' in KnowledgeSourceSchema.parse(POLICIES).source).toBe(false); + // Several boosts add: no second-boost rule. + expect(KnowledgeSourceSchema.safeParse(withAffinity([BOOST, { ...BOOST, places: 1 }])).success).toBe(true); + }); + + it('states the places bound on the key: 20, the most hits one search_knowledge answer carries', () => { + expect(KNOWLEDGE_AFFINITY_MAX_PLACES).toBe(20); + expect(KnowledgeSourceSchema.safeParse(withAffinity([{ ...BOOST, places: 20 }])).success).toBe(true); + const issues = issuesOf(withAffinity([{ ...BOOST, places: 21 }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['too_big', 'source.affinity.0.places']]); + expect(issues[0]![2]).toMatch(/^`places` is at most 20/); + expect(issues[0]![2]).toContain('write a `nearest` entry instead'); + }); + + it('refuses places that is not a positive whole number', () => { + for (const places of [0, -1, 1.5, '3']) { + const issues = issuesOf(withAffinity([{ ...BOOST, places }])); + expect(issues.map(([, path]) => path), `places: ${String(places)}`).toEqual(['source.affinity.0.places']); + expect(issues[0]![2]).toContain('`places` is a whole number from 1 to 20'); + } + }); + + it('refuses mode: filter with the sentence that narrowing is the search scope and visibility is sharing', () => { + const issues = issuesOf(withAffinity([{ ...NEAREST, mode: 'filter' }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['invalid_value', 'source.affinity.0.mode']]); + expect(issues[0]![2]).toContain('there is no `filter` mode'); + expect(issues[0]![2]).toContain('Narrowing what a search reads is the search scope'); + expect(issues[0]![2]).toContain('who may read a record is sharing'); + // Any other mode names the two. + expect(issuesOf(withAffinity([{ ...NEAREST, mode: 'decay' }]))[0]![2]).toMatch(/is `boost` or `nearest`, got 'decay'/); + }); + + it('refuses a caller fact outside the closed list of two', () => { + const issues = issuesOf(withAffinity([{ ...BOOST, caller: 'organization' }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['invalid_value', 'source.affinity.0.caller']]); + expect(issues[0]![2]).toContain("names 'organization', which is not a fact the platform resolves"); + }); + + it('refuses places missing on a boost and present on a nearest, each naming the fix', () => { + const { places: _p, ...bare } = BOOST; + const missing = issuesOf(withAffinity([bare])); + expect(missing.map(([code, path]) => [code, path])).toEqual([['custom', 'source.affinity.0.places']]); + expect(missing[0]![2]).toContain('A `boost` entry of `knowledge_source.source.affinity` takes `places`'); + const extra = issuesOf(withAffinity([{ ...NEAREST, places: 2 }])); + expect(extra.map(([code, path]) => [code, path])).toEqual([['custom', 'source.affinity.0.places']]); + expect(extra[0]![2]).toContain('A `nearest` entry of `knowledge_source.source.affinity` takes no `places`'); + }); + + it('refuses nearest with a caller other than business_unit', () => { + const issues = issuesOf(withAffinity([{ ...NEAREST, field: 'owner', caller: 'user' }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['custom', 'source.affinity.0.caller']]); + expect(issues[0]![2]).toContain("its `caller` is 'business_unit', not 'user'"); + }); + + it('refuses a second nearest, naming both entries', () => { + const issues = issuesOf(withAffinity([NEAREST, BOOST, NEAREST])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['custom', 'source.affinity.2.mode']]); + expect(issues[0]![2]).toContain('declares a second `nearest` entry (entries 0 and 2)'); + }); + + it('refuses a field that metadataFields does not list, naming the field and the fix', () => { + const issues = issuesOf(withAffinity([{ ...NEAREST, field: 'department' }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['custom', 'source.affinity.0.field']]); + expect(issues[0]![2]).toMatch(/^`knowledge_source\.source\.affinity\[0\]\.field` names 'department', which is not one of `source\.metadataFields`/); + expect(issues[0]![2]).toContain("Add 'department' to `metadataFields`"); + }); + + it('refuses an unknown key on an entry, never drops it', () => { + const issues = issuesOf(withAffinity([{ ...BOOST, weight: 0.5 }])); + expect(issues.map(([code, path]) => [code, path])).toEqual([['unrecognized_keys', 'source.affinity.0']]); + }); +}); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 8281b04e505..50af210a137 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -154,6 +154,173 @@ function refuseDocumentByOutsideMetadataFields( }); } +/** + * The most units one `boost` entry of `source.affinity` lets a matching hit + * pass ({@link KnowledgeAffinityEntrySchema}`.places`). It is the most hits one + * `search_knowledge` answer carries (that tool's `topK` bound): a match passes + * at most one whole answer's worth of hits, so a boost brings a match into an + * answer from at most one answer's length below it, and it never becomes + * "matches first", which is what `nearest` is for. + */ +export const KNOWLEDGE_AFFINITY_MAX_PLACES = 20; + +/** The prescription for `mode: 'filter'` (ADR-0161, the dated note of 2026-11-29 under K1). */ +const AFFINITY_NO_FILTER = + '`knowledge_source.source.affinity[].mode` is `boost` or `nearest`: there is no `filter` mode, because an ' + + 'affinity entry only re-orders the hits a caller may already read. Narrowing what a search reads is the search ' + + 'scope (the `scope` of a search), and who may read a record is sharing. Write `mode: \'boost\'` with `places` to ' + + 'lift the matching hits, or `mode: \'nearest\'` to put the caller\'s own business unit first.'; + +/** The facts about the caller an affinity entry may read: a closed list (ADR-0161, the dated note of 2026-11-29). */ +export const KnowledgeAffinityCallerSchema = lazySchema(() => z.enum(['user', 'business_unit'], { + error: (issue) => (typeof issue.input === 'string' + ? `\`knowledge_source.source.affinity[].caller\` names '${issue.input}', which is not a fact the platform resolves ` + + 'about the caller. Write `caller: \'user\'` (the caller\'s user id, for a field that points at sys_user) or ' + + '`caller: \'business_unit\'` (the caller\'s primary business unit, then each parent up to the root, for a field ' + + 'that points at sys_business_unit).' + : undefined), +})); + +/** How an affinity entry re-orders: `boost` lifts a match by `places`, `nearest` tiers by the unit chain. */ +export const KnowledgeAffinityModeSchema = lazySchema(() => z.enum(['boost', 'nearest'], { + error: (issue) => (issue.input === 'filter' + ? AFFINITY_NO_FILTER + : typeof issue.input === 'string' + ? `\`knowledge_source.source.affinity[].mode\` is \`boost\` or \`nearest\`, got '${issue.input}'. ` + + 'Write `mode: \'boost\'` with `places`, or `mode: \'nearest\'`.' + : undefined), +})); + +/** + * `places` is a `boost` entry's and only a `boost` entry's, and `nearest` + * reads the business-unit chain, so it takes `caller: 'business_unit'`. + */ +function refuseAffinityEntryShape( + value: { mode?: string; caller?: string; places?: number }, + ctx: z.RefinementCtx, +): void { + if (value.mode === 'boost' && value.places === undefined) { + ctx.addIssue({ + code: 'custom', + path: ['places'], + message: + 'A `boost` entry of `knowledge_source.source.affinity` takes `places`: how many hits that match nothing a ' + + `matching hit may pass. Write a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}, for example \`places: 3\`.`, + }); + } + if (value.mode === 'nearest' && value.places !== undefined) { + ctx.addIssue({ + code: 'custom', + path: ['places'], + message: + 'A `nearest` entry of `knowledge_source.source.affinity` takes no `places`: it puts the hits of the caller\'s own ' + + 'business unit first, then those of each parent unit in order, then every other hit. Remove `places`, or write ' + + '`mode: \'boost\'` to lift matching hits by a number of places.', + }); + } + if (value.mode === 'nearest' && value.caller !== undefined && value.caller !== 'business_unit') { + ctx.addIssue({ + code: 'custom', + path: ['caller'], + message: + `A \`nearest\` entry of \`knowledge_source.source.affinity\` reads the caller's business-unit chain, so its \`caller\` is ` + + `'business_unit', not '${value.caller}'. Write \`caller: 'business_unit'\` on a field that points at sys_business_unit, ` + + 'or write `mode: \'boost\'` with `places` to lift the hits that match the caller\'s user.', + }); + } +} + +/** + * One entry of `source.affinity` (ADR-0161, the dated note of 2026-11-29 under + * K1): which field of the indexed object is compared with which fact about + * the caller, and how a match re-orders the hits. + */ +export const KnowledgeAffinityEntrySchema = lazySchema(() => strictObject( + { + surface: 'this affinity entry', + history: 'This shape is strict from birth — `affinity` had no earlier spelling, so an unknown key here was never accepted.', + }, + { + /** A member of `source.metadataFields`: the entry reads the value the index stores beside each passage. */ + field: z.string().min(1).describe('A field listed in metadataFields, compared with the caller fact'), + /** + * The fact about the caller: `user` (their user id; `field` points at + * `sys_user`) or `business_unit` (their primary business unit, then each + * parent up to the root; `field` points at `sys_business_unit`). + */ + caller: KnowledgeAffinityCallerSchema.describe('The caller fact compared: user or business_unit'), + /** `boost` (lift a match by `places`) or `nearest` (tier by the unit chain; at most one per source). */ + mode: KnowledgeAffinityModeSchema.describe('boost lifts a match by places; nearest puts the caller\'s own unit first, then its parents'), + /** + * A `boost` entry's lift: a matching hit passes at most this many hits of + * its tier that match nothing. A whole number from 1 to + * {@link KNOWLEDGE_AFFINITY_MAX_PLACES} (20, the most hits one + * `search_knowledge` answer carries). Refused on a `nearest` entry. + */ + places: z.number({ error: () => `\`places\` is a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}.` }) + .int({ error: () => `\`places\` is a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}, for example \`places: 3\`.` }) + .min(1, { error: () => `\`places\` is a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}: a boost of no places lifts nothing. Write at least \`places: 1\`, or remove the entry.` }) + .max(KNOWLEDGE_AFFINITY_MAX_PLACES, { + error: () => `\`places\` is at most ${KNOWLEDGE_AFFINITY_MAX_PLACES}, the most hits one search_knowledge answer carries: ` + + 'a match already passes a whole answer\'s worth of hits at that number. Write a smaller number; to put the ' + + 'caller\'s own business unit first, write a `nearest` entry instead.', + }) + .optional() + .describe(`boost only: how many non-matching hits a match may pass, 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}`), + }, +).superRefine(refuseAffinityEntryShape)); + +/** + * The cross-key rules of `source.affinity`: each `field` is one of + * `source.metadataFields` (the entry reads the value the index stores beside + * each passage, and the index stores only the listed fields), and a source + * declares at most one `nearest`. + */ +function refuseAffinityOutsideMetadataFields( + value: { affinity?: Array<{ field?: string; mode?: string }>; metadataFields?: string[] }, + ctx: z.RefinementCtx, +): void { + const entries = value.affinity; + if (entries === undefined) return; + const listed = value.metadataFields ?? []; + let nearest = -1; + entries.forEach((entry, i) => { + if (typeof entry?.field === 'string' && entry.field !== '' && !listed.includes(entry.field)) { + ctx.addIssue({ + code: 'custom', + path: ['affinity', i, 'field'], + message: + `\`knowledge_source.source.affinity[${i}].field\` names '${entry.field}', which is not one of \`source.metadataFields\` ` + + `(${listed.length === 0 ? 'the list is empty' : listed.map((f) => `'${f}'`).join(', ')}): an affinity entry ` + + 'compares the value the index stores beside each passage, and the index stores only the listed fields, so no ' + + `hit would ever match. Add '${entry.field}' to \`metadataFields\` (adding it rebuilds the index), or name a field listed there.`, + }); + } + if (entry?.mode !== 'nearest') return; + if (nearest === -1) { + nearest = i; + return; + } + ctx.addIssue({ + code: 'custom', + path: ['affinity', i, 'mode'], + message: + `\`knowledge_source.source.affinity\` declares a second \`nearest\` entry (entries ${nearest} and ${i}): a source ` + + 'orders its hits by at most one business-unit chain. Keep one `nearest` entry, and write the other as ' + + '`mode: \'boost\'` with `places`.', + }); + }); +} + +/** Both cross-key rules of the object arm. */ +function refineObjectSource( + value: { documentBy?: string; metadataFields?: string[]; affinity?: Array<{ field?: string; mode?: string }> }, + ctx: z.RefinementCtx, +): void { + refuseDocumentByOutsideMetadataFields(value, ctx); + refuseAffinityOutsideMetadataFields(value, ctx); +} + /** * What a source indexes: the records of one object (ADR-0161 K4, "Referencing * objects"). `kind` keeps one arm; the `file` and `http` arms retired with @@ -257,8 +424,33 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( */ split: KnowledgeSplitSchema.optional() .describe('How the service cuts this object\'s documents into passages; omitted means recursive'), + /** + * [ADR-0161, the dated note of 2026-11-29 under K1] How this source's hits + * are ordered for the caller: each entry compares a field the source lists + * in {@link metadataFields} with a fact the platform resolves about the + * caller (`user`, or the `business_unit` chain), and a match moves the hit + * up. `nearest` puts the hits of the caller's own unit first, then those of + * each parent unit in order, then every other hit; `boost` lets a matching + * hit pass up to `places` hits that match nothing. Several entries add. + * + * It re-orders by position and never by score, and only this source's hits + * among the places they hold: a hit keeps the `score` its store answered, + * a hit of another source never moves, and no hit is dropped or admitted + * (narrowing is the search scope; who may read a record is sharing). The + * fact is never a tool argument or a value a client supplies. A source + * without the key is answered exactly as before. It enters neither the + * index fingerprint nor the recipe hash, so adding it rebuilds nothing; + * listing a new field in `metadataFields` for it does. + * + * Each `field` must be one of {@link metadataFields}, and at most one + * entry is `nearest`. Saving a source also refuses a `field` whose + * reference target is not the one its `caller` names (`sys_user` for + * `user`, `sys_business_unit` for `business_unit`). + */ + affinity: z.array(KnowledgeAffinityEntrySchema).optional() + .describe('How this source\'s hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score'), }, -).superRefine(refuseDocumentByOutsideMetadataFields)); +).superRefine(refineObjectSource)); /** * Canonical KnowledgeSource — the one schema of the governed metadata type @@ -385,3 +577,9 @@ export type ObjectKnowledgeSource = z.input; export type KnowledgeSource = z.input; /** Post-parse shape of {@link KnowledgeSource} — defaults applied (ADR-0122). */ export type KnowledgeSourceParsed = z.infer; +export type KnowledgeAffinityCaller = z.input; +export type KnowledgeAffinityCallerParsed = z.infer; +export type KnowledgeAffinityMode = z.input; +export type KnowledgeAffinityModeParsed = z.infer; +export type KnowledgeAffinityEntry = z.input; +export type KnowledgeAffinityEntryParsed = z.infer; diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index e4a6b8348a1..264164535d0 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -199,7 +199,11 @@ export interface IKnowledgeService { /** * Run a search across one or more sources. Results are * permission-filtered before being returned (see - * `KnowledgeSearchOptions.executionContext`). + * `KnowledgeSearchOptions.executionContext`). They come back best first by + * their adapters' scores, except that a source declaring `source.affinity` + * re-orders its own hits for the caller, by position, before the cut to + * `topK` (ADR-0161, the dated note of 2026-11-29 under K1): each hit keeps + * its adapter's `score`, so an answer may then not be in descending score. */ search(query: string, opts?: KnowledgeSearchOptions): Promise; }