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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/38503-knowledge-affinity.md
Original file line number Diff line number Diff line change
@@ -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`.
33 changes: 31 additions & 2 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -180,6 +181,34 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you
installed ([Connect an MCP Client](/docs/ai/connect-mcp)).
</Callout>

### 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`.
Expand Down
2 changes: 2 additions & 0 deletions content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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 |
Expand Down
79 changes: 79 additions & 0 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading