diff --git a/.changeset/knowledge-affinity-places-bound-one-entry.md b/.changeset/knowledge-affinity-places-bound-one-entry.md new file mode 100644 index 00000000000..51643e59b50 --- /dev/null +++ b/.changeset/knowledge-affinity-places-bound-one-entry.md @@ -0,0 +1,13 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +--- + +fix(spec): the `places` bound of `source.affinity` is stated as one entry's + +Clause-②: no +Metadata-protocol: none + +Who sees it: an author writing a `boost` entry of a knowledge source's `source.affinity`. The jsdoc of `KNOWLEDGE_AFFINITY_MAX_PLACES` and the refusal of `places` above 20 said a match "never becomes matches first" and passes "one whole answer's worth of hits". That is true of one entry only: entries add, so a hit that matches two `boost` entries (two on one field included) passes their summed places. The jsdoc and the refusal now say the bound is one entry's and that it equals the largest `topK` of `search_knowledge`. No accepted value changes. + +`@objectstack/service-knowledge` adds test pins that the places bound equals `SEARCH_KNOWLEDGE_MAX_TOP_K`, that an affinity entry and a scope term read a stored value alike, and that the `user` fact agrees with `resolveCallerIdentity`; `NO_AFFINITY_FACTS`' jsdoc no longer names a failed resolve, which keeps the `user` fact. diff --git a/.changeset/knowledge-source-document-by-tsdoc.md b/.changeset/knowledge-source-document-by-tsdoc.md new file mode 100644 index 00000000000..46c392ec86f --- /dev/null +++ b/.changeset/knowledge-source-document-by-tsdoc.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +docs(spec): `documentBy` TSDoc names where a code-registered or packaged source is judged + +Clause-②: no +Metadata-protocol: none + +The TSDoc of `source.documentBy` said a source registered in code or installed with a package "does not judge it yet" by the parent-link rule. For a packaged source that is no longer true: `os validate` and the publish gate judge it (`knowledge-source-document-by-not-parent-link`), and the sentence now says so. A source registered in code is in no stack collection, so neither judges it, and the sentence says that too. TSDoc only: no schema, `.describe()` or generated output change. 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 256087742ca..d7103ab8d38 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 @@ -287,8 +287,9 @@ const CALLERS: Record = { "`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 ' + + 'the caller but an order among hits that each passed their own re-check. What keeps the reads to those two ' + + "objects for every source, saved through the door or not, is the reader itself: it never follows an entry's " + + "field; the target refusal only keeps a source saved through this door from naming another 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)', }, diff --git a/packages/services/service-knowledge/src/__tests__/affinity-pins-38615.test.ts b/packages/services/service-knowledge/src/__tests__/affinity-pins-38615.test.ts new file mode 100644 index 00000000000..3d6e3dac2ae --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/affinity-pins-38615.test.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Equalities the affinity order (ADR-0161, the dated note of 2026-11-29 + * under K1) states but no code shares, pinned so that neither side moves + * alone, and the one bound it states with what that bound covers: + * + * - `KNOWLEDGE_AFFINITY_MAX_PLACES` (spec) is the largest `topK` of the + * `search_knowledge` tool (`SEARCH_KNOWLEDGE_MAX_TOP_K`, this package): the + * jsdoc and the refusal of `places` name the one as the other. + * - An affinity entry compares a stored value with a caller fact as a scope + * term compares it with its ids (`elementsOf` of `knowledge-affinity.ts` + * against `valueInIds` of `knowledge-search-scope.ts`): strings and numbers + * as `String(value)`, a list by any element, anything else never. + * - The `user` fact is the user the one resolver of the caller's identity + * (`resolveCallerIdentity`, `@objectstack/core`) answers: the order reads it + * from the context under its own copy of that resolver's guard. + * - The places bound is one entry's: two `boost` entries on one field add. + */ + +import { describe, expect, it } from 'vitest'; +import { resolveCallerIdentity, type CallerRecordReader } from '@objectstack/core'; +import { KNOWLEDGE_AFFINITY_MAX_PLACES, type KnowledgeAffinityEntry, type KnowledgeHit } from '@objectstack/spec/ai'; +import { SEARCH_KNOWLEDGE_MAX_TOP_K } from '../knowledge-tools.js'; +import { elementsOf, orderByAffinity, resolveAffinityFacts } from '../knowledge-affinity.js'; +import { valueInIds } from '../knowledge-search-scope.js'; + +describe('affinity pins — the stated equalities hold', () => { + it('the places bound of one boost entry is the largest topK of search_knowledge', () => { + expect(KNOWLEDGE_AFFINITY_MAX_PLACES).toBe(SEARCH_KNOWLEDGE_MAX_TOP_K); + }); + + it('an affinity entry and a scope term read a stored value alike', () => { + const values: unknown[] = [ + 'bu_1', '', 7, 0, -0, 7.5, Number.NaN, Number.POSITIVE_INFINITY, true, false, null, undefined, + {}, { id: 'bu_1' }, [], ['bu_1', 7, null, {}, true], [['bu_1']], [7.5, 'x'], + ]; + const ids = ['bu_1', '', '7', '0', '7.5', 'NaN', 'Infinity', 'true', 'false', 'null', 'undefined', '[object Object]', 'x']; + for (const value of values) { + for (const id of ids) { + expect(valueInIds(value, new Set([id])), `${JSON.stringify(value)} against '${id}'`) + .toBe(elementsOf(value).includes(id)); + } + } + }); + + it('the user fact is the user resolveCallerIdentity answers, for every shape of userId', async () => { + const read: CallerRecordReader = async () => undefined; + for (const userId of ['u_ada', '', ' ', 7, 0, null, undefined, true, {}, ['u_ada']]) { + const facts = await resolveAffinityFacts({ userId, isSystem: false }, read, { user: true, businessUnit: false }); + const identity = await resolveCallerIdentity({ userId }, read); + expect(facts.user, `userId: ${JSON.stringify(userId)}`).toBe(identity.user?.id); + } + }); +}); + +describe('affinity pins — the places bound is one entry\'s', () => { + const unit = (id: string, owner: string): KnowledgeHit => ({ + chunkId: `${id}#0`, documentId: id, sourceId: 'S', sourceRecordId: id, score: 0, snippet: id, metadata: { owner }, + }); + const boost: KnowledgeAffinityEntry = { field: 'owner', caller: 'user', mode: 'boost', places: KNOWLEDGE_AFFINITY_MAX_PLACES }; + const placeOfMatch = (entries: KnowledgeAffinityEntry[]): number => { + const list = Array.from({ length: 45 }, (_, i) => unit(`u${i + 1}`, i === 44 ? 'u_ada' : 'u_lin')); + const { units } = orderByAffinity(list, (u) => u, () => entries, { user: 'u_ada', businessUnits: [] }); + return units.findIndex((u) => u.documentId === 'u45'); + }; + + it('two boosts on one field at the bound each: the match passes 40 units, not 20', () => { + // u45 is number 45. One entry: key 25, it stands before u25 (the key tie goes to the larger sum). + expect(placeOfMatch([boost])).toBe(24); + // The same (field, caller) pair twice: key 5, it passes 40 units and stands fifth. + expect(placeOfMatch([boost, boost])).toBe(4); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-affinity.ts b/packages/services/service-knowledge/src/knowledge-affinity.ts index 743cc14118e..f07fa98b590 100644 --- a/packages/services/service-knowledge/src/knowledge-affinity.ts +++ b/packages/services/service-knowledge/src/knowledge-affinity.ts @@ -51,7 +51,7 @@ export interface AffinityCallerFacts { businessUnits: readonly string[]; } -/** No facts: the system identity, a caller with no user, or a resolve that failed. */ +/** No facts: no caller, the system identity, or a caller with no user (a failed unit read keeps the `user` fact). */ 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`). */ @@ -111,7 +111,7 @@ export async function resolveAffinityFacts( } /** The elements of a stored value a fact is compared with: strings and numbers, as `String(value)`. */ -function elementsOf(value: unknown): string[] { +export function elementsOf(value: unknown): string[] { const list = Array.isArray(value) ? value : [value]; const out: string[] = []; for (const element of list) { diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index 63938ff9d93..fcfd4124160 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -290,7 +290,7 @@ export function scopeCheck(terms: readonly AdapterScopeTerm[]): (hit: KnowledgeH * number matches when `String(value)` is one of them, a list when any element * does (a `multiple: true` lookup), anything else never. */ -function valueInIds(value: unknown, ids: ReadonlySet): boolean { +export function valueInIds(value: unknown, ids: ReadonlySet): boolean { if (Array.isArray(value)) return value.some((element) => scalarInIds(element, ids)); return scalarInIds(value, ids); } diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 1be90217149..24caa7bd292 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -349,15 +349,23 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller 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', () => { + it('states the places bound on the key: 20 on one entry, the largest topK of search_knowledge', () => { 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]).toMatch(/^`places` is at most 20 on one entry, the largest `topK` of search_knowledge/); expect(issues[0]![2]).toContain('write a `nearest` entry instead'); }); + it('the bound is one entry\'s: two boosts on one field at the bound parse, and their lift adds to 40', () => { + // The same (field, caller) pair twice is not refused (ADR-0161: "Several entries add"); the + // jsdoc and the refusal say the bound is one entry's. The order that sums them is pinned in + // service-knowledge (affinity-pins-38615.test.ts, 'two boosts on one field'). + const twice = [{ ...BOOST, places: KNOWLEDGE_AFFINITY_MAX_PLACES }, { ...BOOST, places: KNOWLEDGE_AFFINITY_MAX_PLACES }]; + expect(KnowledgeSourceSchema.parse(withAffinity(twice)).source.affinity).toEqual(twice); + }); + 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 }])); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 8f61e67cdb2..e8b0efd6a0c 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -211,11 +211,17 @@ 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. + * pass ({@link KnowledgeAffinityEntrySchema}`.places`). It equals the largest + * `topK` of the `search_knowledge` tool, so one entry lifts a match by at most + * the longest answer that tool gives (at its default `topK` of 5, twenty + * places are four answers' worth). + * + * The bound is one entry's, not a source's: entries add, so a hit that + * matches several `boost` entries (two on one field included) passes the sum + * of their `places`, which may exceed it. To put the caller's own business + * unit first whatever the number of places, write a `nearest` entry: it takes + * `caller: 'business_unit'` only, so a match on the caller's user is lifted + * by `boost` alone. */ export const KNOWLEDGE_AFFINITY_MAX_PLACES = 20; @@ -309,15 +315,16 @@ export const KnowledgeAffinityEntrySchema = lazySchema(() => strictObject( /** * 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. + * {@link KNOWLEDGE_AFFINITY_MAX_PLACES} (20, the largest `topK` of + * `search_knowledge`); the bound is this entry's, and a hit matching + * several `boost` entries passes their sum. 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 ' + error: () => `\`places\` is at most ${KNOWLEDGE_AFFINITY_MAX_PLACES} on one entry, the largest \`topK\` of search_knowledge: ` + + 'at that number one entry lifts a match by the longest answer that tool gives. Write a smaller number; to put the ' + 'caller\'s own business unit first, write a `nearest` entry instead.', }) .optional() @@ -462,8 +469,10 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * index stores beside each passage. Saving a source also refuses a field * that is not a single-valued parent link: a `lookup` or `master_detail` * field (never `multiple: true`), not credential-class or `internal`. A - * source registered in code or installed with a package meets no save, - * so that rule does not judge it yet. + * source installed with a package meets no save; `os validate` and the + * publish gate judge it by the same rule + * (`knowledge-source-document-by-not-parent-link`). A source registered in + * code is in no stack collection and meets neither, so no rule judges it. */ documentBy: z.string().optional() .describe('Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent'), @@ -486,7 +495,10 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * 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. + * hit pass up to `places` hits that match nothing. Several entries add: + * a hit matching two `boost` entries (on one field or two) passes the sum + * of their `places`, so {@link KNOWLEDGE_AFFINITY_MAX_PLACES} bounds one + * entry, not the lift of a source. * * 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,