Skip to content

Commit 69dd4b0

Browse files
os-billclaude
andauthored
fix(spec): affinity places bound stated as one entry's, pins for its equalities; documentBy TSDoc (#39362)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg4s1PPcLLiwuWxN49pMYoyN)_ Fixes #38615 Fixes #38858 ## What changes Two commits, one per card. **#38615 (affinity review follow-ups N1, N2, N6, N7)** - **N1 (reword route).** `KNOWLEDGE_AFFINITY_MAX_PLACES`' jsdoc, the `places` jsdoc, the `affinity` jsdoc and the `places` max refusal now say the bound is one entry's and equals the largest `topK` of `search_knowledge`; entries add, so a hit matching two `boost` entries (two on one field included) passes their sum. No bound or refusal is added: ADR-0161's "Several entries add" stands, so no ADR note is owed. Cases: the spec parses two boosts on one field at 20 each; service-knowledge orders them as a 40-place lift (fifth place on a 45-unit list, against 25th for one entry). - **N2.** New `affinity-pins-38615.test.ts` pins `KNOWLEDGE_AFFINITY_MAX_PLACES === SEARCH_KNOWLEDGE_MAX_TOP_K`, and `elementsOf` (affinity) against `valueInIds` (scope term, which calls `scalarInIds`) over a table of value shapes. Both helpers become module exports (not package exports). - **N7.** The same file pins the `user` fact of `resolveAffinityFacts` against `resolveCallerIdentity(...).user?.id` for every shape of `userId`. `NO_AFFINITY_FACTS`' jsdoc drops "or a resolve that failed". - **N6.** The `knowledge-source-admission.ts` CALLERS row of `second-object-read-exposure.pin.test.ts` now credits the reader (it never follows an entry's field) with keeping reads to `sys_user` and `sys_business_unit` for every source; the target refusal only covers sources saved through that door. **#38858.** The `documentBy` TSDoc says `os validate` and the publish gate judge a code-registered or package-installed source (`knowledge-source-document-by-not-parent-link`), in place of "does not judge it yet". TSDoc only. ## Why Contract-review nits carried from PR #38606 (7257817094, 7259099085), and a stale TSDoc sentence noted on PR #38855. ## Verification - `packages/spec`: `vitest run src/ai/knowledge-source.test.ts` 53/53, `tsc --noEmit` clean. - `packages/services/service-knowledge`: full suite 33 files / 907 tests green before the pin file was extended; after: the pin file 4/4, `affinity-38503` + `knowledge-search-scope` green; `tsc --noEmit` clean. - `packages/core`: `second-object-read-exposure.pin.test.ts` 4/4. - `gen:schema` + `gen:docs` leave the tree unchanged (no generated output moves). `check:test-source-alias` OK, eslint clean on the changed files, `overlap-check` clean against main. Clause-②: no Metadata-protocol: none ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. (Two cards folded on one file per the claim, one commit each.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Regenerated; nothing moved.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1cbcf46 commit 69dd4b0

8 files changed

Lines changed: 137 additions & 19 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/service-knowledge': patch
4+
---
5+
6+
fix(spec): the `places` bound of `source.affinity` is stated as one entry's
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
`@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.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
docs(spec): `documentBy` TSDoc names where a code-registered or packaged source is judged
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -287,8 +287,9 @@ const CALLERS: Record<string, Classification> = {
287287
"`sys_business_unit` row up their chain, by id, as the caller through `engine.find` with the search's " +
288288
'ExecutionContext, only when an entry reads `business_unit`. Those targets are FIXED platform objects, never the ' +
289289
'authored target this pin holds (its header names fixed-object reads as outside it); the reads serve nothing to ' +
290-
'the caller but an order among hits that each passed their own re-check, and the target refusal keeps an entry ' +
291-
'from naming any other object. Pinned by ' +
290+
'the caller but an order among hits that each passed their own re-check. What keeps the reads to those two ' +
291+
"objects for every source, saved through the door or not, is the reader itself: it never follows an entry's " +
292+
"field; the target refusal only keeps a source saved through this door from naming another object. Pinned by " +
292293
'`packages/services/service-knowledge/src/__tests__/affinity-38503.test.ts` (a refused save makes no engine call; ' +
293294
'a `user`-only source reads no row; a `business_unit` source reads its user row and units alone, as the caller)',
294295
},
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Equalities the affinity order (ADR-0161, the dated note of 2026-11-29
5+
* under K1) states but no code shares, pinned so that neither side moves
6+
* alone, and the one bound it states with what that bound covers:
7+
*
8+
* - `KNOWLEDGE_AFFINITY_MAX_PLACES` (spec) is the largest `topK` of the
9+
* `search_knowledge` tool (`SEARCH_KNOWLEDGE_MAX_TOP_K`, this package): the
10+
* jsdoc and the refusal of `places` name the one as the other.
11+
* - An affinity entry compares a stored value with a caller fact as a scope
12+
* term compares it with its ids (`elementsOf` of `knowledge-affinity.ts`
13+
* against `valueInIds` of `knowledge-search-scope.ts`): strings and numbers
14+
* as `String(value)`, a list by any element, anything else never.
15+
* - The `user` fact is the user the one resolver of the caller's identity
16+
* (`resolveCallerIdentity`, `@objectstack/core`) answers: the order reads it
17+
* from the context under its own copy of that resolver's guard.
18+
* - The places bound is one entry's: two `boost` entries on one field add.
19+
*/
20+
21+
import { describe, expect, it } from 'vitest';
22+
import { resolveCallerIdentity, type CallerRecordReader } from '@objectstack/core';
23+
import { KNOWLEDGE_AFFINITY_MAX_PLACES, type KnowledgeAffinityEntry, type KnowledgeHit } from '@objectstack/spec/ai';
24+
import { SEARCH_KNOWLEDGE_MAX_TOP_K } from '../knowledge-tools.js';
25+
import { elementsOf, orderByAffinity, resolveAffinityFacts } from '../knowledge-affinity.js';
26+
import { valueInIds } from '../knowledge-search-scope.js';
27+
28+
describe('affinity pins — the stated equalities hold', () => {
29+
it('the places bound of one boost entry is the largest topK of search_knowledge', () => {
30+
expect(KNOWLEDGE_AFFINITY_MAX_PLACES).toBe(SEARCH_KNOWLEDGE_MAX_TOP_K);
31+
});
32+
33+
it('an affinity entry and a scope term read a stored value alike', () => {
34+
const values: unknown[] = [
35+
'bu_1', '', 7, 0, -0, 7.5, Number.NaN, Number.POSITIVE_INFINITY, true, false, null, undefined,
36+
{}, { id: 'bu_1' }, [], ['bu_1', 7, null, {}, true], [['bu_1']], [7.5, 'x'],
37+
];
38+
const ids = ['bu_1', '', '7', '0', '7.5', 'NaN', 'Infinity', 'true', 'false', 'null', 'undefined', '[object Object]', 'x'];
39+
for (const value of values) {
40+
for (const id of ids) {
41+
expect(valueInIds(value, new Set([id])), `${JSON.stringify(value)} against '${id}'`)
42+
.toBe(elementsOf(value).includes(id));
43+
}
44+
}
45+
});
46+
47+
it('the user fact is the user resolveCallerIdentity answers, for every shape of userId', async () => {
48+
const read: CallerRecordReader = async () => undefined;
49+
for (const userId of ['u_ada', '', ' ', 7, 0, null, undefined, true, {}, ['u_ada']]) {
50+
const facts = await resolveAffinityFacts({ userId, isSystem: false }, read, { user: true, businessUnit: false });
51+
const identity = await resolveCallerIdentity({ userId }, read);
52+
expect(facts.user, `userId: ${JSON.stringify(userId)}`).toBe(identity.user?.id);
53+
}
54+
});
55+
});
56+
57+
describe('affinity pins — the places bound is one entry\'s', () => {
58+
const unit = (id: string, owner: string): KnowledgeHit => ({
59+
chunkId: `${id}#0`, documentId: id, sourceId: 'S', sourceRecordId: id, score: 0, snippet: id, metadata: { owner },
60+
});
61+
const boost: KnowledgeAffinityEntry = { field: 'owner', caller: 'user', mode: 'boost', places: KNOWLEDGE_AFFINITY_MAX_PLACES };
62+
const placeOfMatch = (entries: KnowledgeAffinityEntry[]): number => {
63+
const list = Array.from({ length: 45 }, (_, i) => unit(`u${i + 1}`, i === 44 ? 'u_ada' : 'u_lin'));
64+
const { units } = orderByAffinity(list, (u) => u, () => entries, { user: 'u_ada', businessUnits: [] });
65+
return units.findIndex((u) => u.documentId === 'u45');
66+
};
67+
68+
it('two boosts on one field at the bound each: the match passes 40 units, not 20', () => {
69+
// u45 is number 45. One entry: key 25, it stands before u25 (the key tie goes to the larger sum).
70+
expect(placeOfMatch([boost])).toBe(24);
71+
// The same (field, caller) pair twice: key 5, it passes 40 units and stands fifth.
72+
expect(placeOfMatch([boost, boost])).toBe(4);
73+
});
74+
});

‎packages/services/service-knowledge/src/knowledge-affinity.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ export interface AffinityCallerFacts {
5151
businessUnits: readonly string[];
5252
}
5353

54-
/** No facts: the system identity, a caller with no user, or a resolve that failed. */
54+
/** No facts: no caller, the system identity, or a caller with no user (a failed unit read keeps the `user` fact). */
5555
export const NO_AFFINITY_FACTS: AffinityCallerFacts = Object.freeze({ businessUnits: Object.freeze([]) as readonly string[] });
5656

5757
/** The caller context the facts are read from (a subset of `ExecutionContext`). */
@@ -111,7 +111,7 @@ export async function resolveAffinityFacts(
111111
}
112112

113113
/** The elements of a stored value a fact is compared with: strings and numbers, as `String(value)`. */
114-
function elementsOf(value: unknown): string[] {
114+
export function elementsOf(value: unknown): string[] {
115115
const list = Array.isArray(value) ? value : [value];
116116
const out: string[] = [];
117117
for (const element of list) {

‎packages/services/service-knowledge/src/knowledge-search-scope.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ export function scopeCheck(terms: readonly AdapterScopeTerm[]): (hit: KnowledgeH
290290
* number matches when `String(value)` is one of them, a list when any element
291291
* does (a `multiple: true` lookup), anything else never.
292292
*/
293-
function valueInIds(value: unknown, ids: ReadonlySet<string>): boolean {
293+
export function valueInIds(value: unknown, ids: ReadonlySet<string>): boolean {
294294
if (Array.isArray(value)) return value.some((element) => scalarInIds(element, ids));
295295
return scalarInIds(value, ids);
296296
}

‎packages/spec/src/ai/knowledge-source.test.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,15 +349,23 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller
349349
expect(KnowledgeSourceSchema.safeParse(withAffinity([BOOST, { ...BOOST, places: 1 }])).success).toBe(true);
350350
});
351351

352-
it('states the places bound on the key: 20, the most hits one search_knowledge answer carries', () => {
352+
it('states the places bound on the key: 20 on one entry, the largest topK of search_knowledge', () => {
353353
expect(KNOWLEDGE_AFFINITY_MAX_PLACES).toBe(20);
354354
expect(KnowledgeSourceSchema.safeParse(withAffinity([{ ...BOOST, places: 20 }])).success).toBe(true);
355355
const issues = issuesOf(withAffinity([{ ...BOOST, places: 21 }]));
356356
expect(issues.map(([code, path]) => [code, path])).toEqual([['too_big', 'source.affinity.0.places']]);
357-
expect(issues[0]![2]).toMatch(/^`places` is at most 20/);
357+
expect(issues[0]![2]).toMatch(/^`places` is at most 20 on one entry, the largest `topK` of search_knowledge/);
358358
expect(issues[0]![2]).toContain('write a `nearest` entry instead');
359359
});
360360

361+
it('the bound is one entry\'s: two boosts on one field at the bound parse, and their lift adds to 40', () => {
362+
// The same (field, caller) pair twice is not refused (ADR-0161: "Several entries add"); the
363+
// jsdoc and the refusal say the bound is one entry's. The order that sums them is pinned in
364+
// service-knowledge (affinity-pins-38615.test.ts, 'two boosts on one field').
365+
const twice = [{ ...BOOST, places: KNOWLEDGE_AFFINITY_MAX_PLACES }, { ...BOOST, places: KNOWLEDGE_AFFINITY_MAX_PLACES }];
366+
expect(KnowledgeSourceSchema.parse(withAffinity(twice)).source.affinity).toEqual(twice);
367+
});
368+
361369
it('refuses places that is not a positive whole number', () => {
362370
for (const places of [0, -1, 1.5, '3']) {
363371
const issues = issuesOf(withAffinity([{ ...BOOST, places }]));

‎packages/spec/src/ai/knowledge-source.zod.ts‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -211,11 +211,17 @@ function refuseDocumentByOutsideMetadataFields(
211211

212212
/**
213213
* The most units one `boost` entry of `source.affinity` lets a matching hit
214-
* pass ({@link KnowledgeAffinityEntrySchema}`.places`). It is the most hits one
215-
* `search_knowledge` answer carries (that tool's `topK` bound): a match passes
216-
* at most one whole answer's worth of hits, so a boost brings a match into an
217-
* answer from at most one answer's length below it, and it never becomes
218-
* "matches first", which is what `nearest` is for.
214+
* pass ({@link KnowledgeAffinityEntrySchema}`.places`). It equals the largest
215+
* `topK` of the `search_knowledge` tool, so one entry lifts a match by at most
216+
* the longest answer that tool gives (at its default `topK` of 5, twenty
217+
* places are four answers' worth).
218+
*
219+
* The bound is one entry's, not a source's: entries add, so a hit that
220+
* matches several `boost` entries (two on one field included) passes the sum
221+
* of their `places`, which may exceed it. To put the caller's own business
222+
* unit first whatever the number of places, write a `nearest` entry: it takes
223+
* `caller: 'business_unit'` only, so a match on the caller's user is lifted
224+
* by `boost` alone.
219225
*/
220226
export const KNOWLEDGE_AFFINITY_MAX_PLACES = 20;
221227

@@ -309,15 +315,16 @@ export const KnowledgeAffinityEntrySchema = lazySchema(() => strictObject(
309315
/**
310316
* A `boost` entry's lift: a matching hit passes at most this many hits of
311317
* its tier that match nothing. A whole number from 1 to
312-
* {@link KNOWLEDGE_AFFINITY_MAX_PLACES} (20, the most hits one
313-
* `search_knowledge` answer carries). Refused on a `nearest` entry.
318+
* {@link KNOWLEDGE_AFFINITY_MAX_PLACES} (20, the largest `topK` of
319+
* `search_knowledge`); the bound is this entry's, and a hit matching
320+
* several `boost` entries passes their sum. Refused on a `nearest` entry.
314321
*/
315322
places: z.number({ error: () => `\`places\` is a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}.` })
316323
.int({ error: () => `\`places\` is a whole number from 1 to ${KNOWLEDGE_AFFINITY_MAX_PLACES}, for example \`places: 3\`.` })
317324
.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.` })
318325
.max(KNOWLEDGE_AFFINITY_MAX_PLACES, {
319-
error: () => `\`places\` is at most ${KNOWLEDGE_AFFINITY_MAX_PLACES}, the most hits one search_knowledge answer carries: `
320-
+ 'a match already passes a whole answer\'s worth of hits at that number. Write a smaller number; to put the '
326+
error: () => `\`places\` is at most ${KNOWLEDGE_AFFINITY_MAX_PLACES} on one entry, the largest \`topK\` of search_knowledge: `
327+
+ 'at that number one entry lifts a match by the longest answer that tool gives. Write a smaller number; to put the '
321328
+ 'caller\'s own business unit first, write a `nearest` entry instead.',
322329
})
323330
.optional()
@@ -462,8 +469,10 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject(
462469
* index stores beside each passage. Saving a source also refuses a field
463470
* that is not a single-valued parent link: a `lookup` or `master_detail`
464471
* field (never `multiple: true`), not credential-class or `internal`. A
465-
* source registered in code or installed with a package meets no save,
466-
* so that rule does not judge it yet.
472+
* source installed with a package meets no save; `os validate` and the
473+
* publish gate judge it by the same rule
474+
* (`knowledge-source-document-by-not-parent-link`). A source registered in
475+
* code is in no stack collection and meets neither, so no rule judges it.
467476
*/
468477
documentBy: z.string().optional()
469478
.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(
486495
* caller (`user`, or the `business_unit` chain), and a match moves the hit
487496
* up. `nearest` puts the hits of the caller's own unit first, then those of
488497
* each parent unit in order, then every other hit; `boost` lets a matching
489-
* hit pass up to `places` hits that match nothing. Several entries add.
498+
* hit pass up to `places` hits that match nothing. Several entries add:
499+
* a hit matching two `boost` entries (on one field or two) passes the sum
500+
* of their `places`, so {@link KNOWLEDGE_AFFINITY_MAX_PLACES} bounds one
501+
* entry, not the lift of a source.
490502
*
491503
* It re-orders by position and never by score, and only this source's hits
492504
* among the places they hold: a hit keeps the `score` its store answered,

0 commit comments

Comments
 (0)