From 6ee3b9648fddb59a6ef122dbfc5766d283a877cd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:36:41 +0000 Subject: [PATCH 01/23] refactor(service-knowledge): split KnowledgeService into concern facets (wip) Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- .../src/knowledge-service-admission.ts | 550 ++ .../src/knowledge-service-host.ts | 165 + .../src/knowledge-service-indexing.ts | 1419 +++++ .../src/knowledge-service-record-sync.ts | 875 +++ .../src/knowledge-service-search.ts | 1092 ++++ .../src/knowledge-service-sources.ts | 365 ++ .../src/knowledge-service-top-level.ts | 1066 ++++ .../src/knowledge-service.ts | 4729 ++--------------- 8 files changed, 5940 insertions(+), 4321 deletions(-) create mode 100644 packages/services/service-knowledge/src/knowledge-service-admission.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-host.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-indexing.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-record-sync.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-search.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-sources.ts create mode 100644 packages/services/service-knowledge/src/knowledge-service-top-level.ts diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts new file mode 100644 index 00000000000..b0d927eb6d4 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -0,0 +1,550 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] Save admission, tenancy and permission scoping: the bodies of + * `admitSources`, `admissionDeps`, `admitAuthoredSource`, + * `unmountedAdapterSaveText`, `reportGateFailure`, `readTenancyPosture`, + * `scopeByOrganization`, `sourcesForObject`, `applyPermissionFilter`, moved out of + * `knowledge-service.ts` whole. + * + * A MOVE, not a redesign. {@link KnowledgeAdmissionFacet} is a stateless facet of + * `KnowledgeService`: each static method is the body of the `KnowledgeService` + * member of the same name exactly as it stood (not re-indented, not edited). + * The member stays on the class as a one-call stub with its signature, so the + * published declaration, an instance spy and a subclass override are what they + * were. A public member keeps its docblock on the class, the contract; a + * private member's docblock moved here with its body. The state stays on + * `KnowledgeService`. + * + * A body reaches the service through `this`, typed as the part of + * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands + * it the host the class's static block builds once per service, whose methods call + * the service at call time and whose fields are getters (and a setter for a + * field a body assigns). A body that reads nothing of the service is called + * without one. `index.ts` re-exports nothing from this module. + */ + +import type { IDataEngine } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { + collectCredentialWriteResponseFields, + collectInternalWriteResponseFields, + registryObjectPackageDisabled, +} from '@objectstack/core'; +import type { TenancyPosture } from '@objectstack/spec/security'; +import { searchOrganizationIds } from './knowledge-organization-scope.js'; +import { + type KnowledgeAdmissionDeps, + type KnowledgeFieldSecurity, + type KnowledgeSourceAdmission, + type ObjectAdmission, + admitObject, + admitSourceFields, + affinityTargetRefusalText, + documentTitleField, + documentUnitRefusalText, + mayServeEarlierRuleTitle, +} from './knowledge-source-admission.js'; +import { type DocumentUnitVerdict, documentUnitOf } from './knowledge-search-scope.js'; +import { + AUTHORED_SOURCE_DOOR_WORDING, + type AbsentSourceReference, + type AdmittedSource, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + absentSourceReference, + describeName, + documentTitle, + errorText, + heldSourceSaveText, + objectSourcesFor, + operatorText, + unplacedSourceText, +} from './knowledge-service-top-level.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; + +export class KnowledgeAdmissionFacet { + /** + * [ADR-0090 D10 rule 1] The sources this caller's search may reach: a + * source over an object the caller's exposure decision refuses, or one + * serving a field the caller may not query, is not searched for that + * caller — see `knowledge-source-admission.ts` for the gates and why they are + * asked at source granularity. Computed once per (caller, object) per search. + * + * The system context bypasses, as it bypasses the row re-check. A caller + * with NO context, or a service with no data engine bound, cannot be judged + * and is served no source at all — never searched, so no passage of one can + * reach the caller through a hit the row re-check cannot place (a hit with + * no `sourceRecordId`). Fails CLOSED: a gate that throws refuses + * every source over that object, reported once at `error`. The objects' + * admissions are asked concurrently. + * + * An admitted source over which an index built under the earlier title + * rule could serve a field the gate does not ask about + * (`mayServeEarlierRuleTitle`) carries `proveIndex`: {@link planSearches} + * searches it only once its index is proven built under the current recipe. + * + * Each admitted source carries the organizations its search hands the + * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system + * context's bypass above covers that scope too: the system identity's + * search is handed no organization filter. + */ + static async admitSources( + this: Pick< + KnowledgeServiceHost, + 'admissionDeps' | 'label' | 'options' | 'reportGateFailure' | 'scopeByOrganization' + >, + sources: KnowledgeSource[], + ctx: ExecutionContext | undefined, + ): Promise { + if (ctx?.isSystem) return sources.map((source) => ({ source })); + const engine = this.options.dataEngine; + if (!ctx || !engine) { + if (sources.length > 0) { + this.options.logger?.warn?.( + !ctx + ? '[knowledge] retrieval with no ExecutionContext — no source is searched: a missing ' + + 'identity is not a grant of authority, so retrieval fails closed rather than searching the whole corpus unscoped. ' + + 'Pass the caller identity (or an explicit system context) to retrieve knowledge.' + : '[knowledge] no IDataEngine bound — no source is searched, to stay safe.', + ); + } + return []; + } + const deps = this.admissionDeps(engine); + const byObject = new Map>(); + for (const source of sources) { + const object = source.source.object; + if (byObject.has(object)) continue; + byObject.set( + object, + admitObject(object, ctx, deps).catch((err: unknown) => { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return undefined; + }), + ); + } + const out: AdmittedSource[] = []; + for (const source of sources) { + const objSource = source.source; + const objectAdmission = await byObject.get(objSource.object); + if (!objectAdmission) continue; // the gate threw: reported once, refused. + const verdict: KnowledgeSourceAdmission = objectAdmission.refused + ? { admitted: false, reason: objectAdmission.refused, object: objSource.object } + : admitSourceFields(objSource, objectAdmission); + if (verdict.admitted) { + // An index built under the earlier title rule could serve a field + // the gate no longer asks about: searched only once its index is + // proven built under the current recipe ({@link planSearches}). + out.push(mayServeEarlierRuleTitle(objSource, objectAdmission.schema) ? { source, proveIndex: true } : { source }); + } else { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + + `(object='${verdict.object}'${verdict.field ? `, field='${verdict.field}'` : ''}).`, + ); + } + } + return this.scopeByOrganization(out, ctx); + } + + /** What the source-admission gates read of the engine and the security service. */ + static admissionDeps(this: Pick, engine: IDataEngine): KnowledgeAdmissionDeps { + return { + readSchema: (object: string): unknown => { + const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; + return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; + }, + isObjectPackageDisabled: (object: string): boolean => + registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), + resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), + }; + } + + static async admitAuthoredSource( + this: Pick< + KnowledgeServiceHost, + 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' + >, + item: unknown, + ctx: ExecutionContext | undefined, + options?: { door?: 'save' | 'duplicate' }, + ): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { + if (ctx?.isSystem) return { admitted: true }; + const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save']; + const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; + const declared = body.source as + | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } + | null + | undefined; + const object = declared && typeof declared === 'object' ? declared.object : undefined; + if (typeof object !== 'string' || object === '') return { admitted: true }; + const names = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; + const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }; + const where = listed.where; + const objSource: ObjectKnowledgeSource = { + kind: 'object', + object, + content: [...names(listed.content), ...names(listed.contentFields)], + metadataFields: names(listed.metadataFields), + ...(where !== null && typeof where === 'object' && !Array.isArray(where) + ? { where: where as Record } + : {}), + }; + const named = `The knowledge source${describeName(body)} ${wording.notDone}`; + const refuse = (status: number, code: string, message: string, field?: string) => + ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); + const unavailable = (why: string) => + refuse( + 503, + 'SERVICE_UNAVAILABLE', + `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + + `allowed to search what their source indexes.${wording.tryAgain}`, + ); + // [ADR-0161 K8, the dated note on item 12, ◆ an author's save and point 4] + // A service the runtime composed and that this boot read as not enabled + // holds every source, so an author's save would be kept and never served: + // refused at each door that saves one, naming the half that is missing. + // The package duplicate (`door: 'duplicate'`) is not refused for it, and + // the engine's own write was admitted above. + if (this.held && options?.door !== 'duplicate') { + return refuse(503, 'SERVICE_UNAVAILABLE', `${named}: ${heldSourceSaveText(this.held)}`); + } + if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`); + // [ADR-0161 K4 ◆] A source that names no adapter where this deployment + // cannot place one is refused at its save as at its registration, so the + // author hears it: several adapters registered, none the deployment's. + const authoredAdapter = (item as { adapter?: unknown } | null | undefined)?.adapter; + const registeredAdapters = this.listAdapters(); + if (authoredAdapter === undefined && this.options.deploymentAdapter === undefined && registeredAdapters.length > 1) { + return refuse(400, 'VALIDATION_ERROR', `${named}: it ${unplacedSourceText(registeredAdapters)}`); + } + // [ADR-0161 K4] A source that names an adapter this deployment does not + // mount is refused at its save, so the author hears it there and not from + // the boot log or a search's 503. A save is served after every store's + // `start()`, so the adapters registered now are the deployment's. + if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { + return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); + } + const engine = this.options.dataEngine; + if (!engine) return unavailable('the knowledge service has no data engine'); + + // [ADR-0161 K4, row 4] A reference to nothing is a permanent mistake, named + // by the rule `os validate` reports, ahead of every permission arm. + let absent: AbsentSourceReference | undefined; + try { + absent = absentSourceReference(objSource, listed, engine, this.admissionDeps(engine)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (absent?.kind === 'object') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.object\` names '${object}', which is not an object of this organization (neither one it ` + + 'authored nor one an installed package registers), so the source indexes nothing ' + + `(\`${KNOWLEDGE_SOURCE_OBJECT_UNKNOWN}\`, the rule \`os validate\` reports). Name an object the organization ` + + `has (check the spelling), or install the package that provides '${object}' first${wording.thenAgain}.`, + ); + } + if (absent?.kind === 'field') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.${absent.key}\` names field '${absent.field}', which object '${object}' does not define, ` + + 'so the index reads nothing for it on any record ' + + `(\`${KNOWLEDGE_SOURCE_FIELD_UNKNOWN}\`, the rule \`os validate\` reports). Name a field of '${object}' ` + + `(check the spelling), or remove it from \`${absent.key}\`${wording.thenAgain}.`, + absent.field, + ); + } + + // [`source.documentBy`] A document unit that is no single-valued parent + // link is a permanent mistake too, judged on the object's definition alone + // by the parent-link rule the search scope reads. One not listed in + // `metadataFields` is left to the parse, which names that fix. + const documentBy = (declared as { documentBy?: unknown }).documentBy; + if (typeof documentBy === 'string' && objSource.metadataFields?.includes(documentBy)) { + let unit: DocumentUnitVerdict | undefined; + try { + const deps = this.admissionDeps(engine); + unit = deps.isObjectPackageDisabled(object) ? undefined : documentUnitOf(documentBy, deps.readSchema(object)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (unit !== undefined && !unit.unit) { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: ${documentUnitRefusalText(object, documentBy, unit)}${wording.thenAgain}.`, + documentBy, + ); + } + } + + // [`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)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + const verdict: KnowledgeSourceAdmission = admission.refused + ? { admitted: false, reason: admission.refused, object } + : admitSourceFields(objSource, admission); + if (verdict.admitted) return { admitted: true }; + switch (verdict.reason) { + case 'object-package-disabled': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: its object '${object}' belongs to a disabled package, and a disabled package's records are ` + + 'not indexed or searched. Enable the package, or index another object.', + ); + case 'object-api-not-served': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, its ` + + '`enable.apiMethods` list does not grant `list`, from which search derives, or it grants `list` beside ' + + "`enable.searchable: false`), and a knowledge search is a search over the object's records. " + + `Serve '${object}' for search: keep \`enable.apiEnabled\` true and, where it declares ` + + '`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object.', + ); + case 'system-object-not-ai-readable': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: '${object}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), ` + + 'so its records are not indexed for retrieval.', + ); + case 'field-not-queryable': { + const field = verdict.field ?? ''; + if (verdict.use === 'where') { + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + + 'hidden from you, or served to you masked), and the source would select its records by that field. ' + + `Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`, + field, + ); + } + const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + + 'to you masked), and the index would hold its text unmasked. ' + + (listedByAuthor + ? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.` + : "The source does not list it: it is the object's display field, which every document carries as its " + + `title. Have someone who may query it ${wording.byWhoMay}.`), + field, + ); + } + default: + return unavailable(`the security service did not answer which fields of '${object}' you may read`); + } + } + + /** + * Why a saved source naming `adapter`, which `mounted` does not hold, is + * refused, and what to write: the rule, then the remedies this deployment + * can take. Leaving `adapter` out is offered only where an omitted adapter + * would be placed ({@link adapterIdFor}). + */ + static unmountedAdapterSaveText( + this: Pick, + adapter: string, + mounted: readonly string[], + again: string, + ): string { + const deployment = this.options.deploymentAdapter; + const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1; + const remedies = [ + ...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]), + ...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []), + `mount the '${adapter}' store and ${again}`, + ]; + return ( + `it names adapter '${adapter}', which this deployment does not mount ` + + `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}), and a source's \`adapter\` must name a ` + + `mounted store. ${remedies.join(', or ').replace(/^./, (c) => c.toUpperCase())}.` + ); + } + + /** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ + static reportGateFailure(this: Pick, object: string, err: Error): void { + const report = + `[knowledge] the exposure or field-level read rules of object '${object}' could not be resolved ` + + `(${err.message}); no source over it is searched for this caller (fail-closed).`; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + } + + /** The deployment's effective tenancy posture, or `undefined` when no resolver is wired. Throws what the resolver throws. */ + static async readTenancyPosture(this: Pick): Promise { + return this.options.resolveTenancyPosture ? await this.options.resolveTenancyPosture() : undefined; + } + + /** + * [ADR-0161 K8, item 9] Pair each source {@link admitSources} admitted for + * a caller that is NOT the system identity (admission's own bypass answers + * that one before this runs) with the organizations its search hands the + * adapter (`searchOrganizationIds`): computed here, from the caller's + * execution context and the deployment's posture, never from anything the + * caller passes. + * + * The posture is read once per search, and only when a source is admitted. + * A posture that cannot be read leaves every source unsearched for this call (fail-closed: whether a wall stands is unknown), + * reported at `error`, `warn` as the fallback. + */ + static async scopeByOrganization( + this: Pick, + sources: AdmittedSource[], + ctx: ExecutionContext, + ): Promise { + if (sources.length === 0) return []; + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + const report = + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no source is searched ` + + 'for this caller (fail-closed).'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + return []; + } + return sources.map((entry) => { + const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(entry.source.source.object)); + return organizationIds === undefined ? entry : { ...entry, organizationIds }; + }); + } + + static sourcesForObject(this: Pick, object: string): KnowledgeSource[] { + return objectSourcesFor(this.handedSources(), object); + } + + /** + * Drop hits whose underlying ObjectQL record the caller can't read. A hit + * with no `sourceRecordId`, or of a source nobody registered, cannot be + * re-checked and is dropped. + * + * Identity handling (#2981): an **explicit** `isSystem` context (indexing / + * trusted server jobs) passes every hit through — it is a deliberate, + * authored elevation. A **missing** context, however, is NOT a grant of + * authority: with no identity we cannot prove the caller may read the + * rows, so we FAIL CLOSED and drop every hit (the + * same conservative posture as a missing data engine). This closes the + * agent/RAG fall-open where an omitted `ToolExecutionContext.actor` used to + * return unfiltered semantic search over the whole corpus. + * + * With `liveTitles` (record granularity), the same read — as the caller, in + * the same query — also reads the object's display field + * (`documentTitleField`, the field assembly takes the title from), and a + * surviving hit's `title` is the record's title as it reads now, not as it + * was indexed. The field gate (`admitSourceFields`) already asked that the + * caller may query that field. + */ + static async applyPermissionFilter( + this: Pick, + hits: KnowledgeHit[], + ctx: ExecutionContext | undefined, + liveTitles = false, + ): Promise { + // Explicit elevation → pass through (indexing / trusted jobs). + if (ctx?.isSystem) return hits; + // No identity, or no engine to re-check with → no hit can be proven + // readable. `admitSources` already kept every source out of the search; + // this holds the same line for any hit that reached here anyway. + if (!ctx || !this.options.dataEngine) return []; + + // Group hits by object so we make one query per object. + const byObject = new Map(); + for (const hit of hits) { + if (!hit.sourceRecordId) continue; + const source = this.handed(hit.sourceId); + if (!source) continue; + const objName = source.source.object; + const bucket = byObject.get(objName) ?? []; + bucket.push(hit); + byObject.set(objName, bucket); + } + + const allowed = new Set(); // `${object}#${recordId}` + const titles = new Map(); // `${object}#${recordId}` → the title as it reads now + for (const [object, group] of byObject) { + const ids = [...new Set(group.map((h) => h.sourceRecordId!).filter(Boolean))]; + if (ids.length === 0) continue; + const schema = liveTitles ? this.schemaFor(object) : undefined; + const withheld = new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ]); + const titleField = liveTitles ? documentTitleField(schema) : undefined; + const readsTitle = titleField !== undefined && titleField !== 'id' && !withheld.has(titleField); + try { + const rows = (await this.options.dataEngine.find(object, { + where: { id: { $in: ids } } as Record, + fields: readsTitle ? ['id', titleField] : ['id'], + context: ctx, + } as never)) as Array & { id?: string }>; + for (const row of rows) { + if (!row?.id) continue; + allowed.add(`${object}#${row.id}`); + if (!readsTitle) continue; + const title = documentTitle(row, schema, withheld); + if (title !== undefined) titles.set(`${object}#${row.id}`, title); + } + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] RLS lookup failed for object='${object}': ${(err as Error).message}; ` + + 'dropping that object\'s hits to stay safe.', + ); + } + } + + const out: KnowledgeHit[] = []; + for (const hit of hits) { + // A hit the re-check cannot place — no record id, or a source nobody + // registered — is not provably readable: dropped. + const source = this.handed(hit.sourceId); + if (!source || !hit.sourceRecordId) continue; + const key = `${source.source.object}#${hit.sourceRecordId}`; + if (!allowed.has(key)) continue; + const title = titles.get(key); + out.push(title === undefined ? hit : { ...hit, title }); + } + return out; + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-host.ts b/packages/services/service-knowledge/src/knowledge-service-host.ts new file mode 100644 index 00000000000..d033880a601 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-host.ts @@ -0,0 +1,165 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] What the facets of `KnowledgeService` (`knowledge-service-*.ts`) + * read of the service, and the one host per service that hands it to them. + * + * {@link KnowledgeServiceHost} names every member a moved body reads through `this`, + * each typed AS the class member (an indexed access on the class), so a change + * to a member's type on the class is a change here too, and a name the class + * does not have does not compile. `readonly` entries are methods and fields no + * body assigns; the others are fields a body assigns. Each facet method types + * its `this` as the `Pick` of this interface it reads. + * + * The host is filled by the factory `KnowledgeService`'s static block installs, + * the one place that can read the class's private members; it is built on the + * first call that needs it and kept for the service's life. A method goes as a + * closure that calls it on the service at call time, so an instance spy or a + * subclass override is still the one reached; a field goes as a getter (and a + * setter when a body assigns it), so a body reads and writes the service's own + * state. This module imports the class for types only, so it forms no + * evaluation cycle. `index.ts` re-exports nothing from it. + */ + +import type { KnowledgeService } from './knowledge-service.js'; + +/** Every `KnowledgeService` member a moved body reads, typed as the class member. */ +export interface KnowledgeServiceHost { + readonly adapterFor: KnowledgeService['adapterFor']; + readonly adapterIdFor: KnowledgeService['adapterIdFor']; + readonly adapterLabel: KnowledgeService['adapterLabel']; + readonly adapters: KnowledgeService['adapters']; + readonly admissionDeps: KnowledgeService['admissionDeps']; + readonly admitSources: KnowledgeService['admitSources']; + readonly affinityFactsOf: KnowledgeService['affinityFactsOf']; + readonly affinityOrderFor: KnowledgeService['affinityOrderFor']; + readonly answerByRecord: KnowledgeService['answerByRecord']; + readonly applyPermissionFilter: KnowledgeService['applyPermissionFilter']; + readonly armReconcile: KnowledgeService['armReconcile']; + readonly backlogReconciles: KnowledgeService['backlogReconciles']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; + readonly buildIfDue: KnowledgeService['buildIfDue']; + readonly buildUnderLease: KnowledgeService['buildUnderLease']; + readonly builds: KnowledgeService['builds']; + buildsStopped: KnowledgeService['buildsStopped']; + readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; + readonly checkFreshness: KnowledgeService['checkFreshness']; + readonly checkScope: KnowledgeService['checkScope']; + readonly clearRepairedFailures: KnowledgeService['clearRepairedFailures']; + readonly closeStaleBuild: KnowledgeService['closeStaleBuild']; + readonly completeBuild: KnowledgeService['completeBuild']; + readonly considerBacklogReconcile: KnowledgeService['considerBacklogReconcile']; + readonly coveredByBuild: KnowledgeService['coveredByBuild']; + readonly deadLettersOf: KnowledgeService['deadLettersOf']; + readonly defaultTopK: KnowledgeService['defaultTopK']; + readonly describeSources: KnowledgeService['describeSources']; + readonly dropUnverifiedHits: KnowledgeService['dropUnverifiedHits']; + enablementPending: KnowledgeService['enablementPending']; + readonly enqueueReconcile: KnowledgeService['enqueueReconcile']; + readonly faceOfKey: KnowledgeService['faceOfKey']; + readonly facedRefusals: KnowledgeService['facedRefusals']; + readonly forget: KnowledgeService['forget']; + readonly freshnessRepairs: KnowledgeService['freshnessRepairs']; + readonly getAdapter: KnowledgeService['getAdapter']; + readonly groupKeyOf: KnowledgeService['groupKeyOf']; + readonly handed: KnowledgeService['handed']; + readonly handedSources: KnowledgeService['handedSources']; + held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly listAdapters: KnowledgeService['listAdapters']; + readonly options: KnowledgeService['options']; + readonly pendingReconciles: KnowledgeService['pendingReconciles']; + readonly pendingRecordSyncs: KnowledgeService['pendingRecordSyncs']; + readonly planIndex: KnowledgeService['planIndex']; + readonly planSearches: KnowledgeService['planSearches']; + readonly prepareDocuments: KnowledgeService['prepareDocuments']; + readonly publishRecordSyncs: KnowledgeService['publishRecordSyncs']; + readonly readChunkTarget: KnowledgeService['readChunkTarget']; + readonly readIndexStateOf: KnowledgeService['readIndexStateOf']; + readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; + readonly readVisibleIds: KnowledgeService['readVisibleIds']; + readonly rebuildOf: KnowledgeService['rebuildOf']; + readonly reconcileExclusion: KnowledgeService['reconcileExclusion']; + readonly reconcileOf: KnowledgeService['reconcileOf']; + readonly reconcilePass: KnowledgeService['reconcilePass']; + reconcileTail: KnowledgeService['reconcileTail']; + readonly reconcileUnlistedReported: KnowledgeService['reconcileUnlistedReported']; + readonly recordBuildEnd: KnowledgeService['recordBuildEnd']; + readonly recordBuildProgress: KnowledgeService['recordBuildProgress']; + readonly recordBuildStart: KnowledgeService['recordBuildStart']; + recordSyncBacklog: KnowledgeService['recordSyncBacklog']; + readonly recordSyncPublisher: KnowledgeService['recordSyncPublisher']; + readonly recordSyncQueueView: KnowledgeService['recordSyncQueueView']; + readonly recordSyncTails: KnowledgeService['recordSyncTails']; + readonly recordSyncWaiting: KnowledgeService['recordSyncWaiting']; + readonly refuseUnplacedSource: KnowledgeService['refuseUnplacedSource']; + readonly registry: KnowledgeService['registry']; + readonly reindexTails: KnowledgeService['reindexTails']; + readonly reindexWith: KnowledgeService['reindexWith']; + readonly repairStale: KnowledgeService['repairStale']; + readonly reportGateFailure: KnowledgeService['reportGateFailure']; + readonly reportUnindexable: KnowledgeService['reportUnindexable']; + readonly reportWhereUnenforceable: KnowledgeService['reportWhereUnenforceable']; + readonly requestSourceReconcile: KnowledgeService['requestSourceReconcile']; + readonly requireEntry: KnowledgeService['requireEntry']; + readonly resolveRecordSync: KnowledgeService['resolveRecordSync']; + readonly resolveSearchTargets: KnowledgeService['resolveSearchTargets']; + readonly runningBuildIds: KnowledgeService['runningBuildIds']; + readonly schemaFor: KnowledgeService['schemaFor']; + readonly scopeAmbiguousReported: KnowledgeService['scopeAmbiguousReported']; + readonly scopeByOrganization: KnowledgeService['scopeByOrganization']; + readonly scopeIgnoredReported: KnowledgeService['scopeIgnoredReported']; + readonly searchByKey: KnowledgeService['searchByKey']; + readonly searchRound: KnowledgeService['searchRound']; + readonly searchWithRefusals: KnowledgeService['searchWithRefusals']; + readonly serializeRecordSync: KnowledgeService['serializeRecordSync']; + readonly sourceListeners: KnowledgeService['sourceListeners']; + readonly sourceRowCount: KnowledgeService['sourceRowCount']; + readonly sourceRows: KnowledgeService['sourceRows']; + readonly sourcesChanged: KnowledgeService['sourcesChanged']; + readonly sourcesForObject: KnowledgeService['sourcesForObject']; + readonly sourcesGroupableBy: KnowledgeService['sourcesGroupableBy']; + readonly sourcesInScope: KnowledgeService['sourcesInScope']; + readonly sourcesNarrowedToVisible: KnowledgeService['sourcesNarrowedToVisible']; + readonly storedCounts: KnowledgeService['storedCounts']; + readonly syncRecord: KnowledgeService['syncRecord']; + readonly syncRecordGroup: KnowledgeService['syncRecordGroup']; + readonly syncRow: KnowledgeService['syncRow']; + readonly syncRows: KnowledgeService['syncRows']; + readonly syncStateIdentity: KnowledgeService['syncStateIdentity']; + readonly syncStateRecorded: KnowledgeService['syncStateRecorded']; + readonly syncStateWriteFailed: KnowledgeService['syncStateWriteFailed']; + syncStateWriteReported: KnowledgeService['syncStateWriteReported']; + readonly unmountedAdapterSaveText: KnowledgeService['unmountedAdapterSaveText']; + readonly unprovenIndex: KnowledgeService['unprovenIndex']; + readonly walkObjectSource: KnowledgeService['walkObjectSource']; + readonly whereUnenforceableReported: KnowledgeService['whereUnenforceableReported']; + readonly writeSynced: KnowledgeService['writeSynced']; +} + +/** The host of each service: built on first use, kept for the service's life. */ +class KnowledgeServiceHostHolder { + private readonly hosts = new WeakMap(); + private build: ((service: KnowledgeService) => KnowledgeServiceHost) | undefined; + + /** Called once, from `KnowledgeService`'s static block. */ + install(build: (service: KnowledgeService) => KnowledgeServiceHost): void { + this.build = build; + } + + /** The host of `service`, built on first use. */ + of(service: KnowledgeService): KnowledgeServiceHost { + let host = this.hosts.get(service); + if (host === undefined) { + if (this.build === undefined) { + throw new Error('KnowledgeService has not installed its host factory'); + } + host = this.build(service); + this.hosts.set(service, host); + } + return host; + } +} + +/** The one holder; `KnowledgeService`'s static block installs its factory. */ +export const knowledgeServiceHost = new KnowledgeServiceHostHolder(); diff --git a/packages/services/service-knowledge/src/knowledge-service-indexing.ts b/packages/services/service-knowledge/src/knowledge-service-indexing.ts new file mode 100644 index 00000000000..beefad7b3d7 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-indexing.ts @@ -0,0 +1,1419 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] Build, index state and reconcile: the bodies of `planIndex`, + * `prepareDocuments`, `readChunkTarget`, `reindexSource`, `reindexWith`, + * `walkObjectSource`, `completeBuild`, `readIndexStateOf`, `buildRecord`, + * `rebuildSource`, `rebuildOf`, `buildUnderLease`, `syncStateIdentity`, + * `syncStateWriteFailed`, `storedCounts`, `recordBuildStart`, + * `recordBuildProgress`, `recordBuildEnd`, `closeStaleBuild`, + * `closeInterruptedBuilds`, `buildSourcesAtBoot`, `buildReloadedSource`, + * `buildIfDue`, `stopBuilds`, `reconcileSources`, `enqueueReconcile`, + * `reconcilePass`, `reconcileOf`, `reconcileExclusion`, `requestReconcile`, + * `armReconcile`, `cancelPendingReconcile`, moved out of `knowledge-service.ts` + * whole. + * + * A MOVE, not a redesign. {@link KnowledgeIndexingFacet} is a stateless facet of + * `KnowledgeService`: each static method is the body of the `KnowledgeService` + * member of the same name exactly as it stood (not re-indented, not edited). + * The member stays on the class as a one-call stub with its signature, so the + * published declaration, an instance spy and a subclass override are what they + * were. A public member keeps its docblock on the class, the contract; a + * private member's docblock moved here with its body. The state stays on + * `KnowledgeService`. + * + * A body reaches the service through `this`, typed as the part of + * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands + * it the host the class's static block builds once per service, whose methods call + * the service at call time and whose fields are getters (and a setter for a + * field a body assigns). A body that reads nothing of the service is called + * without one. `index.ts` re-exports nothing from this module. + */ + +import type { + AdapterContext, + IDataEngine, + IKnowledgeAdapter, + KnowledgeReindexOptions, + KnowledgeReindexResult, +} from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { TenancyPosture } from '@objectstack/spec/security'; +import { resolveSplit, splitDocument } from './split/index.js'; +import { indexExpectation } from './knowledge-index-fingerprint.js'; +import type { KnowledgeSourceEntry } from './knowledge-source-registry.js'; +import { + BUILD_LEASE_MS, + BUILD_PROGRESS_LOG_INTERVAL_MS, + BUILD_STALL_LIMIT_MS, + type KnowledgeBuildFence, + type KnowledgeBuildLock, + type KnowledgeBuildLockHandle, + type KnowledgeBuildProgress, + type KnowledgeBuildRecord, + type KnowledgeBuildTrigger, + type KnowledgeIndexReading, + type KnowledgeReconcileEntry, + type KnowledgeReconcileReport, + type KnowledgeReconcileRequest, + RECONCILE_MAX_WAIT_MS, + RECONCILE_QUIET_MS, + buildLockKey, + emptyBuildProgress, + fencedCall, + startBuildFence, +} from './knowledge-build.js'; +import { + type KnowledgeStoredBuildCounts, + type KnowledgeSyncStateIdentity, + type KnowledgeSyncStateStore, + nextBuildId, + storedBuildMessage, +} from './knowledge-sync-state.js'; +import { + type DurableBuild, + type IndexPlan, + MAX_REINDEX_FAILURES, + type PurgeDocumentsOutcome, + REINDEX_PAGE_SIZE, + chainAfter, + cloneBuildRecord, + describeValue, + errorText, + heldSourcesError, + isRecordId, + listAdapterDocuments, + operatorText, + purgeDocuments, + recordToDocument, + systemContext, +} from './knowledge-service-top-level.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; + +export class KnowledgeIndexingFacet { + /** + * What every adapter call for `source` carries, read now (ADR-0161 K7; K8, + * item 8): the split the service applies for this adapter — resolved from + * the source's `split`, the settings page's `knowledge.chunk_target` and the + * adapter's reported `embedding.maxInputTokens`, absent for an adapter that + * does not take chunks — and the index fingerprint and recipe hash computed + * over that same split, the adapter's descriptor and the source. One read + * feeds both, so the fingerprint is always the fingerprint of the split the + * documents were cut by. Never cached: the settings, the descriptor and the + * object definition may each change between two calls. + */ + static async planIndex( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + chunkTarget: () => Promise = () => this.readChunkTarget(), + ): Promise { + const split = adapter.capabilities?.chunks === true + ? resolveSplit({ + split: source.source.split, + chunkTarget: await chunkTarget(), + maxInputTokens: adapter.embedding?.maxInputTokens, + }) + : undefined; + const index = indexExpectation( + { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, + { source, schema: this.schemaFor(source.source.object) }, + ); + return { + source, + adapter, + ...(split === undefined ? {} : { split }), + index, + context: (reason) => ({ source, reason, index }), + }; + } + + /** + * The ONE place documents are split before an adapter sees them (ADR-0161 + * K1). An adapter that does not declare `capabilities.chunks` gets the + * documents as they are, without `chunks` — it splits them itself, as + * before. One that does gets each document with the passages of + * {@link splitDocument}, under the split {@link planIndex} resolved for + * this call: the source's `split`, the settings page's `knowledge.chunk_target`, and the + * adapter's reported `embedding.maxInputTokens` — read for this call, never + * cached. A document the split cannot index (a `whole` document over the + * budget) is answered in `failed`, never truncated; the caller removes it. + */ + static prepareDocuments( + plan: IndexPlan, + docs: KnowledgeDocument[], + ): { + ready: KnowledgeDocument[]; + failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }>; + } { + const split = plan.split; + if (split === undefined || docs.length === 0) return { ready: docs, failed: [] }; + const ready: KnowledgeDocument[] = []; + const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; + for (const doc of docs) { + const out = splitDocument(doc, split); + if (out.ok) ready.push({ ...doc, chunks: out.chunks }); + else failed.push({ documentId: doc.id, reason: out.reason, estimate: out.estimate, budget: out.budget }); + } + return { ready, failed }; + } + + /** The settings page's `knowledge.chunk_target`, read now; `undefined` when unset or unreadable. */ + static async readChunkTarget(this: Pick): Promise { + const resolve = this.options.resolveChunkTarget; + if (!resolve) return undefined; + try { + return await resolve(); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the settings page's knowledge.chunk_target could not be read (${errorText(err)}); ` + + "splitting by the source's own split.maxChars, else 800.", + ); + return undefined; + } + } + + static async reindexSource( + this: Pick, + sourceId: string, + opts: KnowledgeReindexOptions = {}, + ): Promise { + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.reindexWith(entry.handed, opts); + } + + /** + * {@link reindexSource}, with a sink a build's progress is reported to after + * each page, and the build's fence (`knowledge-build.ts`) the walk asks + * before each page. + */ + static async reindexWith( + this: Pick, + source: KnowledgeSource, + opts: KnowledgeReindexOptions, + progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, + ): Promise { + const adapter = this.adapterFor(source); + + const engine = this.options.dataEngine; + if (!engine) { + return { + ok: false, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: 'KnowledgeService has no IDataEngine bound; cannot walk the source.', + }; + } + + return chainAfter(this.reindexTails, source.name, () => + this.walkObjectSource(source, source.source, adapter, engine, opts, progress, fence), + ); + } + + /** + * The paged walk of {@link reindexSource}; runs inside that source's chain. + * Under a build's `fence` it stops before a page once the fence says so + * (and before `beginBuild`, before each purge deletion, and before its + * purge and completion), and stops waiting on a read, a + * write, the listing, the purge or `beginBuild` once the build is + * cancelled, so the source's chain is not held by such a call that never + * answers. Each page and each purge deletion restarts the fence's bound. + * The completion is not raced: the chain stays held until it settles (see + * {@link completeBuild}). + */ + static async walkObjectSource( + this: Pick< + KnowledgeServiceHost, + 'completeBuild' | 'label' | 'options' | 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | + 'recordSyncTails' | 'schemaFor' + >, + source: KnowledgeSource, + objSource: ObjectKnowledgeSource, + adapter: IKnowledgeAdapter, + engine: IDataEngine, + opts: KnowledgeReindexOptions, + progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, + ): Promise { + const object = objSource.object; + // `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A + // fractional cap is floored; a negative or non-finite one is refused + // rather than read as "nothing to do". + if (opts.limit !== undefined && !(typeof opts.limit === 'number' && Number.isFinite(opts.limit) && opts.limit >= 0)) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, + }; + } + const cap = opts.limit === undefined ? undefined : Math.floor(opts.limit); + // RLS-bypassing system context — this is a server-side admin op. + const context = systemContext(); + + if (opts.dryRun) { + const total = await engine.count(object, { where: objSource.where }, { context }); + return { + ok: true, + object, + discovered: cap === undefined ? total : Math.min(total, cap), + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: 'dryRun=true; no documents pushed.', + }; + } + + // The posture decides whether each document carries its record's + // organization (ADR-0161 K8, item 9); read once per walk. A posture that + // cannot be read stops the walk before any write: a document assembled + // without its organization would drop out of every walled search. + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + message: `reindex of source '${this.label(source)}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, + }; + } + + // One plan for the whole walk: the split every page is cut by, and the + // fingerprint and recipe hash every adapter call carries. + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('reindex'); + + // A complete walk is a build (K7, rule 3): the adapter is told before the + // first write, and may open a generation for a new fingerprint — or refuse. + const build = cap === undefined; + // A build cancelled, or whose lease was lost, while its walk waited its + // turn in the source's queue does not begin: `beginBuild` is where a store + // that keeps generations takes its builder lock (K7, rule 2). + const unbegun = fence?.stop(); + if (unbegun !== undefined) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${source.id}' stopped before its build began, and nothing was written: ${unbegun.message}`, + }; + } + if (build && typeof adapter.beginBuild === 'function') { + try { + await fencedCall(fence, adapter.beginBuild(ctx)); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, + }; + } + } + + // What the adapter holds before the walk: the skip's hashes, and the + // purge's candidates once the walk is complete. + // Raced against the build's bound like every call of the walk, so a store + // that never answers frees the source's chain. + let listing: Awaited>; + try { + listing = await fencedCall(fence, listAdapterDocuments(source, adapter, plan.index)); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' stopped before its first page: ${errorText(err)}`, + }; + } + const listed = listing.ok ? listing.documents : undefined; + const listingNote = listing.ok || listing.reason === undefined + ? undefined + : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; + if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${this.label(source)}': ${listingNote}`); + + const schema = this.schemaFor(object); + const seen = new Set(); + let discovered = 0; + let indexed = 0; + let skipped = 0; + // Documents the split could not index (a `whole` document over the + // embedder's budget): removed from the index, counted, and the first + // MAX_REINDEX_FAILURES named. + let failed = 0; + const failures: Array<{ documentId: string; reason: string }> = []; + let cursor: string | number | undefined; + for (let page = 1; ; page++) { + const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); + if (!(want > 0)) break; + const after = cursor === undefined ? '' : ` (after id '${cursor}')`; + const stopped = (what: string): KnowledgeReindexResult => ({ + ok: false, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures: [...failures], + message: `reindex of source '${this.label(source)}' stopped at page ${page}${after}: ${what}`, + }); + // A build that lost its lease, or was cancelled, reads and embeds no + // further page (the fence, `knowledge-build.ts`). + const halt = fence?.stop(); + if (halt !== undefined) return stopped(halt.message); + + const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; + let rows: Array>; + try { + rows = await fencedCall(fence, engine.find( + object, + { + where: + byCursor === undefined + ? objSource.where + : objSource.where === undefined ? byCursor : { $and: [objSource.where, byCursor] }, + orderBy: [{ field: 'id', order: 'asc' }], + limit: want, + }, + { context }, + )); + } catch (err) { + return stopped(`the read failed: ${errorText(err)}`); + } + // Only an EMPTY page ends the walk. A short page does not: `find` does + // not promise `min(limit, remaining)` rows — an `afterFind` hook may drop + // rows from a page — so rows after a short page can still exist. + // A read that answers no list is a failed read, never the end of the + // source: read as an empty page it would make a complete walk of nothing + // and hand every listed document to the purge. + if (!Array.isArray(rows)) { + return stopped(`the read answered ${describeValue(rows)} instead of a list of rows.`); + } + if (rows.length === 0) break; + + let docs: KnowledgeDocument[]; + try { + docs = rows.map((row) => recordToDocument(source, objSource, row, schema, posture)); + } catch (err) { + return stopped(`building the page's documents failed: ${errorText(err)}`); + } + // A document whose computed hash equals the one the adapter listed for it + // is unchanged: it is not written again. + const changed = listed === undefined + ? docs + : docs.filter((doc) => { + const stored = listed.get(doc.id); + return stored === undefined || stored !== doc.docHash; + }); + // One split per changed document, for an adapter that takes chunks. + const prepared = this.prepareDocuments(plan, changed); + if (prepared.ready.length > 0) { + try { + await fencedCall(fence, adapter.upsert(prepared.ready, ctx)); + } catch (err) { + return stopped(`the adapter upsert failed: ${operatorText(err)}`); + } + } + // A document the split cannot index is removed — an older passage of it + // must not keep answering for text the index no longer holds — and + // reported, never truncated. + if (prepared.failed.length > 0) { + try { + await fencedCall(fence, adapter.delete(prepared.failed.map((f) => f.documentId), ctx)); + } catch (err) { + return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); + } + for (const f of prepared.failed) { + failed += 1; + if (failures.length < MAX_REINDEX_FAILURES) failures.push({ documentId: f.documentId, reason: f.reason }); + } + } + for (const doc of docs) seen.add(doc.id); + discovered += rows.length; + indexed += prepared.ready.length; + skipped += docs.length - changed.length; + progress?.({ pages: page, discovered, indexed, skipped, failed }); + + // The next page continues after this page's last id. A last row with no + // id, or one that did not move past the cursor (an engine that ignored + // the `id > cursor` condition), ends the walk rather than looping on it. + const lastId = rows[rows.length - 1].id; + if (!isRecordId(lastId)) { + return stopped('the page was indexed, but its last row carries no id, so the walk cannot continue after it.'); + } + if (lastId === cursor) { + return stopped("the page was indexed, but its last row's id did not move past the cursor, so the walk cannot continue."); + } + cursor = lastId; + } + + // A build that lost its lease after its last page neither purges nor + // completes: another node may be building the source. + const halted = fence?.stop(); + if (halted !== undefined) { + return { + ok: false, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures: [...failures], + message: `reindex of source '${this.label(source)}' read every page, and stopped before its purge and completion: ${halted.message}`, + }; + } + + // The purge runs only after a COMPLETE walk: a `limit` walk saw part of + // the source, so "not seen" there means nothing (a failed page returned + // above; `dryRun` returned before the walk). + const failedNote = failed === 0 + ? undefined + : `${failed} document(s) cannot be indexed under the source's split and were removed from the index ` + + `(${failures.length === failed ? 'each' : `the first ${failures.length}`} named in failures).`; + const done: KnowledgeReindexResult = { + ok: true, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures, + ...(failedNote === undefined ? {} : { message: failedNote }), + }; + if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; + if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { + return build ? this.completeBuild(source, adapter, ctx, done, fence) : done; + } + + const candidates = [...listed.keys()].filter((id) => !seen.has(id)); + let purge: PurgeDocumentsOutcome; + try { + purge = await fencedCall(fence, purgeDocuments({ + source, + objSource, + adapter, + engine, + candidates, + // Each settled deletion (or confirmed keep) is progress: a large, + // healthy purge restarts the fence's bound as it goes. A build that + // lost its lease, or was cancelled, re-reads and deletes no further + // candidate: the fence is asked once the candidate's turn comes. + serialize: async (documentId, task) => { + const outcome = await chainAfter(this.recordSyncTails, documentId, () => { + const halt = fence?.stop(); + return halt === undefined ? task() : Promise.reject(new Error(halt.message)); + }); + fence?.progressed(); + return outcome; + }, + index: plan.index, + })); + } catch (err) { + return { + ...done, + ok: false, + message: `reindex of source '${this.label(source)}' walked every page, and stopped during its purge: ${errorText(err)}`, + }; + } + if (purge.failure !== undefined) { + const purgeHalt = fence?.stop(); + if (purgeHalt !== undefined) { + return { + ...done, + ok: false, + purged: purge.purged, + message: + `reindex of source '${source.id}' walked every page, and stopped during its purge after ` + + `${purge.purged} deletion(s): ${purgeHalt.message}`, + }; + } + return { + ...done, + ok: false, + purged: purge.purged, + message: + `reindex of source '${this.label(source)}' walked every page, but its purge stopped after ${purge.purged} ` + + `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, + }; + } + if (purge.foreign > 0) { + return this.completeBuild(source, adapter, ctx, { + ...done, + purged: purge.purged, + message: + `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + + `('${source.name}:' and the record id); they were kept, because no row can confirm them.` + + (failedNote === undefined ? '' : ` ${failedNote}`), + }, fence); + } + return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }, fence); + } + + /** + * The end of a complete build (ADR-0161 K8, item 8 c): the adapter's + * `completeBuild`, once, with the fingerprint and recipe hash the walk + * carried. An adapter without it records nothing. One that throws turns the + * walk's result into `ok: false`: every page was written, but the adapter + * did not record what it holds, so the next complete walk builds again. + * Under a build's `fence`, a build that must stop (its lease lost during + * the purge, or its bound passed) completes nothing. Once the completion + * begins it is not a page: the fence's bound is disarmed + * (`fence.completing()`) and the call is awaited however long it takes, so + * a switch that began still commits and the record never reads + * `timed-out` over it. The source's walk chain stays held until it settles, + * so no rebuild on this node begins a build beside it. + */ + static async completeBuild( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + ctx: AdapterContext, + done: KnowledgeReindexResult, + fence?: KnowledgeBuildFence, + ): Promise { + const halt = fence?.stop(); + if (halt !== undefined) { + return { + ...done, + ok: false, + message: `reindex of source '${this.label(source)}' walked every page, and stopped before its completion: ${halt.message}`, + }; + } + if (typeof adapter.completeBuild !== 'function') return done; + fence?.completing(); + try { + await adapter.completeBuild(ctx); + return done; + } catch (err) { + return { + ...done, + ok: false, + message: + `reindex of source '${this.label(source)}' walked every page, but the adapter did not complete the build ` + + `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, + }; + } + } + + /** {@link readIndexState} of one registered source; the reading names it by its face. */ + static async readIndexStateOf( + this: Pick, + entry: KnowledgeSourceEntry, + ): Promise { + const source = entry.handed; + const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({ + sourceId: entry.face, + state, + due, + detail, + ...(held === undefined ? {} : { held }), + }); + if (!this.options.dataEngine) { + return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); + } + try { + const adapter = this.adapterFor(source); + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('reindex'); + if (typeof adapter.indexStatus === 'function') { + const held = await adapter.indexStatus(ctx); + const expected = plan.index; + if (held.fingerprint === undefined && held.recipeHash === undefined && held.building !== true) { + return reading('nothing', true, 'the adapter holds nothing for the source: it has never been built.', held); + } + // A first build opened a generation and has not completed it (it is + // still running on some node, or it stopped part-way): there is no + // active generation yet, so no other fingerprint to speak of. + if (held.fingerprint === undefined) { + return reading( + 'nothing', + true, + 'a first build was started and has not completed (it is still running, or it stopped part-way): the adapter holds no complete index for the source.', + held, + ); + } + if (held.fingerprint !== expected.fingerprint) { + return reading( + 'new-fingerprint', + true, + 'the index was built under another fingerprint (embedding model, dimensions or split): it is built anew.', + held, + ); + } + if (held.recipeHash === undefined) { + return typeof adapter.completeBuild === 'function' + ? reading('no-recipe-hash', true, 'the index records no recipe hash: one complete rebuild records it.', held) + : reading( + 'no-recipe-hash', + false, + `the adapter '${adapter.id}' records no recipe hash and has no completeBuild, so a changed recipe ` + + "(the source's where, metadataFields, title rule or withheld fields) cannot be seen for it; nothing is rebuilt automatically.", + held, + ); + } + if (held.recipeHash !== expected.recipeHash) { + return reading( + 'recipe-changed', + true, + "the source's recipe changed since the last build (its where, metadataFields, title rule or withheld fields): it is rebuilt.", + held, + ); + } + return reading('current', false, 'the index is current: same fingerprint, same recipe hash.', held); + } + if (typeof adapter.listDocuments === 'function') { + const page = await adapter.listDocuments(ctx, { limit: 1 }); + const documents = Array.isArray(page?.documents) ? page.documents : undefined; + if (documents === undefined) { + return reading('unreadable', false, "the adapter's document listing answered no list of documents."); + } + return documents.length === 0 + ? reading('listed-empty', true, 'the adapter lists no document for the source: it has never been built.') + : reading( + 'listed-documents', + false, + `the adapter '${adapter.id}' holds documents and reports no index status, so whether they are current cannot be read; nothing is rebuilt automatically.`, + ); + } + return reading( + 'unknown', + false, + `the adapter '${adapter.id}' has neither indexStatus nor listDocuments, so whether the source was ever built cannot be read; ` + + 'nothing is built automatically, and an operator rebuild (os knowledge rebuild) is the way.', + ); + } catch (err) { + return reading('unreadable', false, `what the adapter holds could not be read (${operatorText(err)}).`); + } + } + + static buildRecord( + this: Pick, + sourceId: string, + ): KnowledgeBuildRecord | undefined { + const entry = this.registry.resolve(sourceId); + const record = entry === undefined ? undefined : this.builds.get(entry.key); + return record === undefined ? undefined : cloneBuildRecord(record); + } + + static async rebuildSource( + this: Pick, + sourceId: string, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, + ): Promise { + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.rebuildOf(entry, opts); + } + + /** + * {@link rebuildSource} of one registered source. The record names the + * source by its face; the build's lock and this node's record of it are + * held under its index key, which no two sources share. + * + * The durable record (`knowledge-sync-state.ts`) is written once the build + * holds the lease and walks: its start, its counts at most every + * {@link BUILD_PROGRESS_LOG_INTERVAL_MS}, and its end, which lands before + * this resolves. A build that does not run (`not-run`) writes nothing: the + * row keeps the build that ran. `onStarted` is told once, with the record, + * when the walk began and its start is recorded, or when the build ended + * without walking. + */ + static async rebuildOf( + this: Pick, + entry: KnowledgeSourceEntry, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, + ): Promise { + const running = this.builds.get(entry.key); + if (running?.status === 'running') { + const copy = cloneBuildRecord(running); + opts.onStarted?.(copy); + return copy; + } + const durable: DurableBuild = { chain: Promise.resolve() }; + try { + return await this.buildUnderLease(entry, opts, durable); + } finally { + await durable.chain; + if (durable.buildId !== undefined && this.runningBuildIds.get(entry.key) === durable.buildId) { + this.runningBuildIds.delete(entry.key); + } + } + } + + /** The body of {@link rebuildOf}; queues its durable writes on `durable.chain`. */ + static async buildUnderLease( + this: Pick< + KnowledgeServiceHost, + 'builds' | 'closeStaleBuild' | 'options' | 'readIndexStateOf' | 'recordBuildEnd' | 'recordBuildProgress' | + 'recordBuildStart' | 'reindexWith' + >, + entry: KnowledgeSourceEntry, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, + durable: DurableBuild, + ): Promise { + const source = entry.handed; + const record: KnowledgeBuildRecord = { + sourceId: entry.face, + trigger: opts.trigger, + status: 'running', + startedAt: new Date().toISOString(), + progress: emptyBuildProgress(), + }; + this.builds.set(entry.key, record); + const logger = this.options.logger; + const label = `[knowledge] build of source '${entry.face}' (${opts.trigger})`; + let announced = false; + const announce = (): void => { + if (announced) return; + announced = true; + opts.onStarted?.(cloneBuildRecord(record)); + }; + const finish = ( + status: Exclude, + message: string | undefined, + result?: KnowledgeReindexResult, + ): KnowledgeBuildRecord => { + record.status = status; + record.finishedAt = new Date().toISOString(); + if (message !== undefined) record.message = message; + if (result !== undefined) record.result = result; + if (status !== 'not-run') this.recordBuildEnd(entry, record, durable); + announce(); + return cloneBuildRecord(record); + }; + + let lock: KnowledgeBuildLock | undefined; + try { + lock = this.options.resolveBuildLock?.(); + } catch (err) { + const message = `the cluster service could not be read (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; + logger?.warn(`${label}: ${message}`); + return finish('not-run', message); + } + let handle: KnowledgeBuildLockHandle | null = null; + if (lock) { + try { + handle = await lock.acquire(buildLockKey(entry.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); + } catch (err) { + const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; + logger?.warn(`${label}: ${message}`); + return finish('not-run', message); + } + if (!handle) { + const message = 'another node holds the build of this source; this node built nothing.'; + logger?.info?.(`${label}: ${message}`); + return finish('not-run', message); + } + } + const fence = startBuildFence({ + handle, + leaseMs: BUILD_LEASE_MS, + stallMs: BUILD_STALL_LIMIT_MS, + onRenewFailure: (err, held) => { + logger?.warn( + `${label}: the cluster lease could not be renewed (${errorText(err)}). ` + + (held + ? 'Renewal is retried; the build stops before its next page if the lease lapses.' + : 'The lease is lost; the build stops before its next page.'), + ); + }, + }); + try { + // This node holds the source's lease (or is the only node): a build the + // record still reads `running` is one whose node stopped. + await this.closeStaleBuild(entry); + if (opts.trigger === 'boot' || opts.trigger === 'reload') { + const reading = await this.readIndexStateOf(entry); + if (!reading.due) { + const message = `nothing to build once the lock was held: ${reading.detail}`; + logger?.info?.(`${label}: ${message}`); + return finish('not-run', message); + } + } + await this.recordBuildStart(entry, record, durable); + announce(); + logger?.info?.( + `${label} started: every row the source's where matches is read, and the content fields of each one the ` + + 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.', + ); + let lastLogged = Date.now(); + const walk = this.reindexWith(source, {}, (step) => { + // A walk the build stopped waiting on writes no progress into its ended record. + if (record.status !== 'running') return; + fence.progressed(); + record.progress = { ...step }; + const now = Date.now(); + if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return; + lastLogged = now; + logger?.info?.( + `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` + + `${step.skipped} unchanged, ${step.failed} cannot be indexed.`, + ); + this.recordBuildProgress(entry, record, durable); + }, fence); + // Cancelled at the stall bound: the walk is no longer waited on (it + // stops at its next page if the call it waits on ever answers). + walk.catch(() => undefined); + const raced = await Promise.race([walk, fence.cancelled.then((stop) => ({ stop }))]); + if ('stop' in raced) { + logger?.warn( + `${label} was cancelled: ${raced.stop.message} The adapter keeps what it held; ` + + 'the next reconcile, boot or operator rebuild builds again.', + ); + return finish(raced.stop.reason, raced.stop.message); + } + const result = raced; + record.progress = { + pages: record.progress.pages, + discovered: result.discovered, + indexed: result.indexed, + skipped: result.skipped ?? 0, + failed: result.failed ?? 0, + }; + const totals = + `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` + + `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`; + const stop = result.ok ? undefined : fence.stop(); + if (!result.ok) { + logger?.warn( + `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` + + 'The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.', + ); + return finish(stop?.reason ?? 'failed', result.message, result); + } + logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`); + return finish('done', result.message, result); + } catch (err) { + const message = `the build threw: ${operatorText(err)}`; + logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.`); + return finish('failed', message); + } finally { + fence.close(); + // The build's end lands before its lease is released, so a node that + // takes the lease next never reads this finished build as `running`. + await durable.chain; + if (handle) { + try { + await handle.release(); + } catch (err) { + // The lease still frees itself on its TTL; the build itself ran. + logger?.warn(`${label}: the cluster lock could not be released (${errorText(err)}); it frees itself when its lease ends.`); + } + } + } + } + + /** The source as its sync-state row names it. */ + static syncStateIdentity( + this: Pick, + entry: KnowledgeSourceEntry, + ): KnowledgeSyncStateIdentity { + const adapter = this.boundAdapterId(entry.handed); + return { + key: entry.key, + source: entry.face, + ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), + ...(adapter === undefined ? {} : { adapter }), + object: entry.handed.source.object, + }; + } + + /** + * A sync-state write failed: the record no longer matches what happened, + * while everything else looks normal. Said once, at `error`, with what is + * lost and the fix; never thrown into the build or the sync it records. + */ + static syncStateWriteFailed( + this: Pick, + what: string, + err: unknown, + ): void { + if (this.syncStateWriteReported) { + this.options.logger?.debug?.(`[knowledge] ${what} (${errorText(err)}).`); + return; + } + this.syncStateWriteReported = true; + const report = + `[knowledge] ${what} (${errorText(err)}): the source's sync state in sys_knowledge_sync_state (its last build ` + + 'and its failed syncs, what index_status and Setup show on every node) no longer says what happened, and ' + + 'nothing else looks wrong. Check that schema sync ran for sys_knowledge_sync_state on the default datasource; ' + + 'the next build rewrites the row. Said once; later failures are logged at debug.'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + } + + /** The record's counts of a build record. */ + static storedCounts(record: KnowledgeBuildRecord): KnowledgeStoredBuildCounts { + return { + pages: record.progress.pages, + discovered: record.progress.discovered, + indexed: record.progress.indexed, + skipped: record.progress.skipped, + purged: record.result?.purged ?? null, + failed: record.progress.failed, + }; + } + + /** Record a build's start; the build waits for it, so every node reads `running` once the walk begins. */ + static async recordBuildStart( + this: Pick< + KnowledgeServiceHost, + 'options' | 'runningBuildIds' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' + >, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, + ): Promise { + const store = this.options.syncState; + if (!store) return; + const buildId = nextBuildId(); + durable.buildId = buildId; + this.runningBuildIds.set(entry.key, buildId); + try { + await store.startBuild(this.syncStateIdentity(entry), buildId, record.trigger, record.startedAt); + this.syncStateRecorded.add(entry.key); + } catch (err) { + this.syncStateWriteFailed(`the start of the build of source '${entry.face}' was not recorded`, err); + } + } + + /** Queue a running build's counts (the walk does not wait for it). */ + static recordBuildProgress( + this: Pick, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, + ): void { + const store = this.options.syncState; + const buildId = durable.buildId; + if (!store || buildId === undefined) return; + const counts = this.storedCounts(record); + durable.chain = durable.chain.then(async () => { + try { + await store.progressBuild(entry.key, buildId, counts); + } catch (err) { + this.syncStateWriteFailed(`the progress of the build of source '${entry.face}' was not recorded`, err); + } + }); + } + + /** Queue a build's end; {@link rebuildOf} resolves once it landed. */ + static recordBuildEnd( + this: Pick, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, + ): void { + const store = this.options.syncState; + const buildId = durable.buildId; + if (!store || buildId === undefined || record.status === 'running' || record.status === 'not-run') return; + const status = record.status; + const counts = this.storedCounts(record); + const finishedAt = record.finishedAt ?? new Date().toISOString(); + durable.chain = durable.chain.then(async () => { + try { + const landed = await store.finishBuild(entry.key, buildId, { + status, + finishedAt, + counts, + message: storedBuildMessage({ status, counts }), + }); + if (!landed) { + this.options.logger?.info?.( + `[knowledge] the end of the build of source '${entry.face}' (${status}) was not recorded: another build ` + + 'has taken the source over since, and the record keeps that one.', + ); + } + } catch (err) { + this.syncStateWriteFailed(`the end of the build of source '${entry.face}' was not recorded`, err); + } + }); + } + + /** + * Close the build the record reads `running` for `entry` as `interrupted`, + * when it is not one this node runs. Called by a node that holds the + * source's lease (or the only node), so no live build can be the one the + * record names. Never throws. + */ + static async closeStaleBuild( + this: Pick, + entry: KnowledgeSourceEntry, + ): Promise { + const store = this.options.syncState; + if (!store) return false; + try { + const state = await store.read(entry.key); + if (state?.build?.status !== 'running' || state.buildId === undefined) return false; + if (this.runningBuildIds.get(entry.key) === state.buildId) return false; + const closed = await store.closeInterrupted(entry.key, state.buildId, new Date().toISOString()); + if (closed) { + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': the ${state.build.trigger} build started ${state.build.startedAt} ` + + 'by a node that stopped before it ended is closed as interrupted.', + ); + } + return closed; + } catch (err) { + this.syncStateWriteFailed(`the interrupted build of source '${entry.face}' was not closed`, err); + return false; + } + } + + static async closeInterruptedBuilds( + this: Pick, + ): Promise { + const store = this.options.syncState; + if (!store) return 0; + let running: Awaited>; + try { + running = await store.runningBuilds(); + } catch (err) { + this.syncStateWriteFailed('the builds a stopped node left running could not be read at boot', err); + return 0; + } + let closed = 0; + for (const state of running) { + if (state.buildId === undefined) continue; + if (this.runningBuildIds.get(state.key) === state.buildId) continue; + let lock: KnowledgeBuildLock | undefined; + let handle: KnowledgeBuildLockHandle | null = null; + try { + lock = this.options.resolveBuildLock?.(); + if (lock) { + handle = await lock.acquire(buildLockKey(state.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); + if (!handle) continue; // A node is building it now. + } + } catch (err) { + // The lock, not the record: the build is left as it reads, and the + // next node that takes the source's lease closes it. + this.options.logger?.warn?.( + `[knowledge] the build of source '${state.source}' a stopped node may have left running was not closed at ` + + `boot: the cluster lock did not answer (${errorText(err)}). The next node that takes the source's build ` + + 'lease closes it.', + ); + continue; + } + try { + if (await store.closeInterrupted(state.key, state.buildId, new Date().toISOString())) closed++; + } catch (err) { + this.syncStateWriteFailed(`the interrupted build of source '${state.source}' was not closed at boot`, err); + } finally { + if (handle) await handle.release().catch(() => undefined); + } + } + if (closed > 0) { + this.options.logger?.info?.( + `[knowledge] ${closed} build(s) a stopped node left running are closed as interrupted in sys_knowledge_sync_state.`, + ); + } + return closed; + } + + static async buildSourcesAtBoot( + this: Pick, + ): Promise { + if (this.held) return; + let entries: KnowledgeSourceEntry[]; + try { + entries = this.registry.entries(); + } catch (err) { + this.options.logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); + return; + } + for (const entry of entries) { + if (this.buildsStopped) return; + await this.buildIfDue(entry, 'boot'); + } + } + + static async buildReloadedSource( + this: Pick, + key: string, + ): Promise { + const entry = this.registry.byIndexKey(key); + if (entry && !this.buildsStopped && !this.held) await this.buildIfDue(entry, 'reload'); + } + + /** One source of {@link buildSourcesAtBoot}. Never rejects. */ + static async buildIfDue( + this: Pick, + entry: KnowledgeSourceEntry, + trigger: KnowledgeBuildTrigger, + ): Promise { + const logger = this.options.logger; + const when = trigger === 'boot' ? 'at boot' : 'on reload'; + try { + if ((entry.authored.refresh?.onRecordChange ?? true) === false) { + logger?.debug?.(`[knowledge] source '${entry.face}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built ${when}.`); + return; + } + // A source whose adapter is not mounted is named once at boot, at + // `error`, by the boot's reading (`reportUnmountedAdapters`); the pass + // adds no second line for it. On reload no reading runs, so the line + // below is the one that names it. A source that names no adapter and + // cannot be placed is named by the same reading. + if (trigger === 'boot') { + const adapterId = this.boundAdapterId(entry.handed); + if (adapterId === undefined || !this.adapters.has(adapterId)) return; + } + const reading = await this.readIndexStateOf(entry); + if (reading.due) { + logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); + await this.rebuildOf(entry, { trigger }); + return; + } + const line = `[knowledge] source '${entry.face}' is not built ${when}: ${reading.detail}`; + // What cannot be seen or read is said once, at `warn` (K7: "the + // service says so once"); a source that is current, or whose adapter + // holds documents it reports no status for, is ordinary. + if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { + logger?.warn(line); + } else { + logger?.info?.(line); + } + } catch (err) { + logger?.warn(`[knowledge] source '${entry.face}': the build pass failed for it (${operatorText(err)}).`); + } + } + + static stopBuilds( + this: Pick, + ): void { + this.buildsStopped = true; + for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); + } + + static reconcileSources( + this: Pick, + opts: { sources?: string[] } = {}, + ): Promise { + const names = opts.sources; + // Held, the pass walks nothing: no store is called while not enabled. + return this.enqueueReconcile(() => + this.held + ? [] + : names === undefined + ? this.registry.entries() + : names.map((name) => this.registry.resolve(name)).filter((e): e is KnowledgeSourceEntry => e !== undefined), + ); + } + + /** Queue one reconcile pass over the entries `select` answers when its turn comes. */ + static enqueueReconcile( + this: Pick, + select: () => KnowledgeSourceEntry[], + ): Promise { + const pass = this.reconcileTail.then(() => this.reconcilePass(select)); + this.reconcileTail = pass.then(() => undefined, () => undefined); + return pass; + } + + /** One pass of {@link reconcileSources}; runs after the pass before it. */ + static async reconcilePass( + this: Pick, + select: () => KnowledgeSourceEntry[], + ): Promise { + const startedAt = new Date().toISOString(); + const report: KnowledgeReconcileReport = { startedAt, finishedAt: startedAt, sources: [], unfinished: [] }; + let entries: KnowledgeSourceEntry[]; + try { + entries = select(); + } catch (err) { + this.options.logger?.warn(`[knowledge] the reconcile could not list the sources (${operatorText(err)}); none was reconciled.`); + report.unfinished.push({ sourceId: '*', status: 'failed', message: `the sources could not be listed (${operatorText(err)})` }); + report.finishedAt = new Date().toISOString(); + return report; + } + for (const entry of entries) { + if (this.buildsStopped) break; + // A source removed while the pass ran is not walked. + if (this.registry.byIndexKey(entry.key) !== entry) continue; + const done = await this.reconcileOf(entry); + report.sources.push(done); + const status = done.record?.status; + if (status === 'failed' || status === 'lease-lost' || status === 'timed-out') { + report.unfinished.push({ sourceId: entry.face, status, ...(done.record?.message === undefined ? {} : { message: done.record.message }) }); + } + } + report.finishedAt = new Date().toISOString(); + return report; + } + + /** One source of a reconcile pass. Never rejects. */ + static async reconcileOf( + this: Pick< + KnowledgeServiceHost, + 'clearRepairedFailures' | 'options' | 'readIndexStateOf' | 'rebuildOf' | 'reconcileExclusion' | + 'reconcileUnlistedReported' + >, + entry: KnowledgeSourceEntry, + ): Promise { + const logger = this.options.logger; + const left = (why: string): KnowledgeReconcileEntry => ({ sourceId: entry.face, left: why }); + try { + const why = this.reconcileExclusion(entry); + if (why !== undefined) { + if (why.unlisted) { + if (!this.reconcileUnlistedReported.has(entry.key)) { + this.reconcileUnlistedReported.add(entry.key); + logger?.warn(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); + } + } else { + logger?.debug?.(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); + } + return left(why.text); + } + const reading = await this.readIndexStateOf(entry); + logger?.info?.( + reading.due + ? `[knowledge] source '${entry.face}' is built by the reconcile now: ${reading.detail}` + : `[knowledge] source '${entry.face}' is reconciled now (${reading.state}): ${reading.detail}`, + ); + const record = await this.rebuildOf(entry, { trigger: 'reconcile' }); + // [ADR-0161 K1] The reconcile is the failure count's reader: a walk that + // completed re-read every row, so the syncs that failed before it began + // are repaired or no longer apply. + if (record.status === 'done') await this.clearRepairedFailures(entry, record.startedAt); + return { sourceId: entry.face, record }; + } catch (err) { + const message = `the reconcile failed for it (${operatorText(err)}).`; + logger?.warn(`[knowledge] source '${entry.face}': ${message}`); + const now = new Date().toISOString(); + return { + sourceId: entry.face, + record: { sourceId: entry.face, trigger: 'reconcile', status: 'failed', startedAt: now, finishedAt: now, progress: emptyBuildProgress(), message }, + }; + } + } + + /** + * Why the reconcile does not walk `entry`, or `undefined` when it does. + * `unlisted` marks the one exclusion said at `warn`: a store that lists no + * documents. An adapter that is not mounted is walked, so its build fails + * and names it. + */ + static reconcileExclusion( + this: Pick, + entry: KnowledgeSourceEntry, + ): { text: string; unlisted: boolean } | undefined { + if ((entry.authored.refresh?.onRecordChange ?? true) === false) { + return { text: 'refresh.onRecordChange is false, so an external indexer owns its index.', unlisted: false }; + } + if (!this.options.dataEngine) { + return { text: 'no data engine is bound, so the source cannot be walked.', unlisted: false }; + } + const adapterId = this.boundAdapterId(entry.handed); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapter && typeof adapter.listDocuments !== 'function') { + return { + text: + `its adapter '${adapter.id}' does not list its documents (no listDocuments), so a walk could neither skip ` + + 'an unchanged document nor purge a stale one: it would send every document to the embedding provider again ' + + 'and remove nothing. Rows deleted or changed without an event stay as they are in its index until an ' + + 'operator rebuild (os knowledge rebuild).', + unlisted: true, + }; + } + return undefined; + } + + static requestReconcile( + this: Pick< + KnowledgeServiceHost, + 'armReconcile' | 'buildsStopped' | 'held' | 'options' | 'reconcileExclusion' | 'registry' + >, + object: string, + ): KnowledgeReconcileRequest { + const request: KnowledgeReconcileRequest = { scheduled: [], unreconcilable: [] }; + if (this.buildsStopped || this.held) return request; + for (const entry of this.registry.entries()) { + if (entry.handed.source.object !== object) continue; + const why = this.reconcileExclusion(entry); + if (why !== undefined) { + // An external indexer's index is not this service's to call stale. + if (why.unlisted || !this.options.dataEngine) request.unreconcilable.push(entry.face); + continue; + } + this.armReconcile(entry.key, Date.now()); + request.scheduled.push(entry.face); + } + return request; + } + + /** (Re)arm the pending reconcile of the source under `key`; `now` is when the request arrived. */ + static armReconcile( + this: Pick< + KnowledgeServiceHost, + 'armReconcile' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'pendingReconciles' | 'registry' + >, + key: string, + now: number, + ): void { + const pending = this.pendingReconciles.get(key); + const firstAt = pending?.firstAt ?? now; + if (pending) clearTimeout(pending.timer); + const wait = Math.max(0, Math.min(RECONCILE_QUIET_MS, firstAt + RECONCILE_MAX_WAIT_MS - now)); + const timer = setTimeout(() => { + this.pendingReconciles.delete(key); + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held) return; + // A build of the source running now may have read past the rows the + // write changed: wait for it, then walk again. + if (this.builds.get(key)?.status === 'running') { + this.armReconcile(key, Date.now()); + return; + } + void this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }).catch(() => undefined); + }, wait); + (timer as { unref?: () => void }).unref?.(); + this.pendingReconciles.set(key, { timer, firstAt }); + } + + /** Drop the pending reconcile of the source under `key`, if any. */ + static cancelPendingReconcile(this: Pick, key: string): void { + const pending = this.pendingReconciles.get(key); + if (!pending) return; + clearTimeout(pending.timer); + this.pendingReconciles.delete(key); + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts new file mode 100644 index 00000000000..89437f3737e --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts @@ -0,0 +1,875 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] Record sync, sync state and backlog: the bodies of `recordSources`, + * `hasDurableSyncState`, `syncStateOf`, `pendingRecordSyncs`, `recordSyncFailure`, + * `requestSourceReconcile`, `clearRepairedFailures`, `deadLettersOf`, + * `recordSyncQueued`, `enqueueRecordSync`, `publishRecordSyncs`, + * `processRecordSync`, `resolveRecordSync`, `coveredByBuild`, + * `processRecordSyncBatch`, `syncRecordGroup`, `recordSyncWaiting`, + * `sourceRowCount`, `considerBacklogReconcile`, `syncRows`, `handleRecordUpsert`, + * `syncRecord`, `syncRow`, `writeSynced`, `reportUnindexable`, + * `reportWhereUnenforceable`, `serializeRecordSync`, `schemaFor`, + * `handleRecordDelete`, moved out of `knowledge-service.ts` whole. + * + * A MOVE, not a redesign. {@link KnowledgeRecordSyncFacet} is a stateless facet of + * `KnowledgeService`: each static method is the body of the `KnowledgeService` + * member of the same name exactly as it stood (not re-indented, not edited). + * The member stays on the class as a one-call stub with its signature, so the + * published declaration, an instance spy and a subclass override are what they + * were. A public member keeps its docblock on the class, the contract; a + * private member's docblock moved here with its body. The state stays on + * `KnowledgeService`. + * + * A body reaches the service through `this`, typed as the part of + * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands + * it the host the class's static block builds once per service, whose methods call + * the service at call time and whose fields are getters (and a setter for a + * field a body assigns). A body that reads nothing of the service is called + * without one. `index.ts` re-exports nothing from this module. + */ + +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeSourceEntry } from './knowledge-source-registry.js'; +import { + type KnowledgeStoredBuild, + type KnowledgeSyncFailures, + type KnowledgeSyncStateStore, + storedBuildMessage, + syncFailureText, +} from './knowledge-sync-state.js'; +import { + KNOWLEDGE_RECORD_SYNC_QUEUE, + type KnowledgeRecordSyncBatchItem, + type KnowledgeRecordSyncBatchResult, + type KnowledgeRecordSyncMessage, + type KnowledgeRecordSyncOutcome, + type KnowledgeRecordSyncReason, + RECORD_SYNC_BACKLOG_READ_INTERVAL_MS, + RECORD_SYNC_BACKLOG_RETRY_MAX_MS, + RECORD_SYNC_BACKLOG_RETRY_MS, + RECORD_SYNC_BACKLOG_REWALK_MS, + RECORD_SYNC_BACKLOG_ROW_SHARE, + RECORD_SYNC_BACKLOG_THRESHOLD, + RECORD_SYNC_COVER_MARGIN_MS, + RECORD_SYNC_SOURCE_ROWS_TTL_MS, + readRecordSyncMessage, +} from './knowledge-record-sync-queue.js'; +import { + DEAD_LETTER_SCAN_MAX, + type KnowledgeRecordSyncQueueView, + type RecordSyncGroup, + chainAfter, + chainAfterAll, + describeValue, + documentIdFor, + errorText, + isRecordId, + objectSourcesFor, + recordToDocument, + rereadRow, + rereadRows, + systemContext, +} from './knowledge-service-top-level.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; + +export class KnowledgeRecordSyncFacet { + static async recordSources( + this: Pick< + KnowledgeServiceHost, + 'options' | 'registry' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' + >, + ): Promise { + const store = this.options.syncState; + if (!store) return; + for (const entry of this.registry.entries()) { + if (this.syncStateRecorded.has(entry.key)) continue; + try { + await store.ensure(this.syncStateIdentity(entry)); + this.syncStateRecorded.add(entry.key); + } catch (err) { + this.syncStateWriteFailed(`the sync-state row of source '${entry.face}' could not be written`, err); + } + } + } + + static hasDurableSyncState(this: Pick): boolean { + return this.options.syncState !== undefined; + } + + static async syncStateOf( + this: Pick, + sourceId: string, + ): Promise<{ build: KnowledgeStoredBuild | null; failures: KnowledgeSyncFailures }> { + const entry = this.requireEntry(sourceId); + const store = this.options.syncState; + if (store) { + const state = await store.read(entry.key); + return { build: state?.build ?? null, failures: state?.failures ?? { count: 0 } }; + } + const record = this.builds.get(entry.key); + if (!record || record.status === 'not-run') return { build: null, failures: { count: 0 } }; + const counts = this.storedCounts(record); + return { + build: { + trigger: record.trigger, + status: record.status, + startedAt: record.startedAt, + ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), + counts, + ...(record.status === 'running' ? {} : { message: storedBuildMessage({ status: record.status, counts }) }), + }, + failures: { count: 0 }, + }; + } + + static async pendingRecordSyncs(this: Pick): Promise { + const view = this.recordSyncQueueView; + if (!view || typeof view.getQueueSize !== 'function') return undefined; + return view.getQueueSize(KNOWLEDGE_RECORD_SYNC_QUEUE); + } + + static async recordSyncFailure( + this: Pick< + KnowledgeServiceHost, + 'options' | 'registry' | 'requestSourceReconcile' | 'syncStateIdentity' | 'syncStateRecorded' | + 'syncStateWriteFailed' + >, + data: unknown, + err: unknown, + attempts: { attempt: number; maxAttempts: number }, + ): Promise { + const message = readRecordSyncMessage(data); + if (!message) return; + const entry = this.registry.byIndexKey(message.source); + const store = this.options.syncState; + if (!entry || !store) return; + let written: Awaited>; + try { + written = await store.addFailure( + this.syncStateIdentity(entry), + new Date().toISOString(), + syncFailureText(message.recordId, attempts.attempt, attempts.maxAttempts, err), + ); + this.syncStateRecorded.add(entry.key); + } catch (writeErr) { + this.syncStateWriteFailed(`a failed sync of source '${entry.face}' was not counted`, writeErr); + return; + } + if (written.first) this.requestSourceReconcile(entry); + } + + /** Ask for a reconcile of one source, as a predicate write does ({@link requestReconcile}). */ + static requestSourceReconcile( + this: Pick, + entry: KnowledgeSourceEntry, + ): void { + if (this.buildsStopped || this.reconcileExclusion(entry) !== undefined) return; + this.armReconcile(entry.key, Date.now()); + this.options.logger?.info?.( + `[knowledge] source '${entry.face}' has its first failed sync: a reconcile of it is asked for, and starts once ` + + 'the quiet period passes.', + ); + } + + /** + * After a reconcile of `entry` that completed: clear the failures that + * failed before its walk began (`walkStartedAt`), and remove their dead + * letters from the queue. The walk re-read every row, so they are repaired + * or no longer apply. A dead letter that failed during the walk stays, and + * is still counted. Read from the queue's dead letters where syncs run + * through it; where they do not, the failures are cleared only when the + * newest of them came before the walk. Never throws. + */ + static async clearRepairedFailures( + this: Pick, + entry: KnowledgeSourceEntry, + walkStartedAt: string, + ): Promise { + const store = this.options.syncState; + if (!store) return; + const walkStart = Date.parse(walkStartedAt); + const view = this.recordSyncQueueView; + try { + for (let attempt = 0; attempt < 4; attempt++) { + const state = await store.read(entry.key); + if (!state) return; + let remaining: string[] | undefined; + if (view && typeof view.listFailed === 'function') { + const letters = await this.deadLettersOf(entry.key, view); + const repaired = letters.filter((l) => l.at < walkStart); + if (typeof view.purgeFailed === 'function') { + for (const letter of repaired) { + try { + await view.purgeFailed(letter.id); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}': the repaired dead letter '${letter.id}' could not be removed ` + + `from queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (${errorText(err)}); it stays listed there.`, + ); + } + } + } + remaining = letters.filter((l) => l.at >= walkStart).map((l) => new Date(l.at).toISOString()).sort(); + } else { + const last = state.failures.lastFailedAt === undefined ? NaN : Date.parse(state.failures.lastFailedAt); + if (state.failures.count === 0 || !(last < walkStart)) return; + remaining = []; + } + if (remaining.length === 0 && state.failures.count === 0) return; + const landed = await store.setFailures(entry.key, state.failureCountStored, remaining.length === 0 + ? { count: 0 } + : { + count: remaining.length, + firstFailedAt: remaining[0], + ...(state.failures.lastFailedAt === undefined ? {} : { lastFailedAt: state.failures.lastFailedAt }), + ...(state.failures.lastError === undefined ? {} : { lastError: state.failures.lastError }), + }); + if (landed) { + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': the reconcile repaired the syncs that failed before it began; ` + + `${remaining.length} failed during it and stay counted.`, + ); + return; + } + // A failure was counted meanwhile: read again. + } + } catch (err) { + this.syncStateWriteFailed(`the failures the reconcile of source '${entry.face}' repaired were not cleared`, err); + } + } + + /** + * Every dead letter on the record-sync queue that names the source under + * `key`, with when it failed, once each. + * + * Filtered here, not in the queue: `IQueueService.listFailed` takes a queue + * name and a page and no predicate, so no query can name the source. The + * pages are read by offset while letters may arrive, so a letter can be read + * on two pages; it is kept once, by its id. + */ + static async deadLettersOf( + key: string, + view: KnowledgeRecordSyncQueueView, + ): Promise> { + const byId = new Map(); + const page = 500; + for (let offset = 0; offset < DEAD_LETTER_SCAN_MAX; offset += page) { + const letters = await view.listFailed!(KNOWLEDGE_RECORD_SYNC_QUEUE, { limit: page, offset }); + for (const letter of letters) { + const named = readRecordSyncMessage(letter.data)?.source ?? (letter.metadata as { source?: unknown } | undefined)?.source; + if (named !== key || byId.has(letter.id)) continue; + const at = Date.parse(String(letter.completedAt ?? letter.updatedAt ?? letter.createdAt)); + byId.set(letter.id, Number.isNaN(at) ? 0 : at); + } + if (letters.length < page) break; + } + return [...byId].map(([id, at]) => ({ id, at })); + } + + static recordSyncQueued(this: Pick): boolean { + return this.recordSyncPublisher !== undefined; + } + + static enqueueRecordSync( + this: Pick, + object: string, + recordId: string | number, + reason: KnowledgeRecordSyncReason = 'event', + ): void { + if (!isRecordId(recordId) || this.held) return; + const sources = this.sourcesForObject(object); + if (sources.length === 0) return; + this.publishRecordSyncs(sources, object, String(recordId), reason); + } + + /** + * Publish one record-sync message per source in `sources`, once the unit + * open here commits ({@link enqueueRecordSync}). `onFailed` runs for each + * message that could not be published. + */ + static publishRecordSyncs( + this: Pick, + sources: KnowledgeSource[], + object: string, + recordId: string, + reason: KnowledgeRecordSyncReason, + onFailed?: () => void, + ): void { + const publish = this.recordSyncPublisher; + if (!publish) return; + const send = (): void => { + for (const source of sources) { + const message: KnowledgeRecordSyncMessage = { source: source.name, object, recordId, reason }; + void Promise.resolve() + .then(() => publish(message)) + .catch((err: unknown) => { + onFailed?.(); + const report = + `[knowledge] the sync of record '${recordId}' of source '${this.label(source)}' could not be queued ` + + `(${errorText(err)}): the write stands, and the record's document stays as it was until the record's ` + + 'next save, a search that finds it stale, or the reconcile.'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + }); + } + }; + const engine = this.options.dataEngine as { runAfterOpenUnitsCommit?(body: () => void): void } | undefined; + if (typeof engine?.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(send); + else send(); + } + + static async processRecordSync( + this: Pick, + data: unknown, + publishedAt?: number, + ): Promise { + const resolved = this.resolveRecordSync(data, publishedAt); + if ('outcome' in resolved) return resolved.outcome; + const { source, message, engine } = resolved; + // The source's adapter is resolved now ({@link adapterFor}): the one it + // names, else the deployment's store, else the only one registered. Where + // none can be resolved it throws its coded refusal — the named adapter is + // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or + // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so + // the message is retried: a store that registers late is met by a later + // attempt, and one that never does leaves a dead letter naming the source + // and the record. + const adapter = this.adapterFor(source); + await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => + this.syncRow(source, adapter, message.object, message.recordId, engine), + ); + return 'synced'; + } + + /** + * What every record-sync message is checked for before its row is read, + * on both of the worker's paths ({@link processRecordSync}, + * {@link processRecordSyncBatch}): an outcome that completes it without a + * sync — not a record-sync message, the service held, its source gone, its object no longer + * synced on record change, no data engine to re-read the row, or covered + * by a complete build that purged and began after it was published + * ({@link coveredByBuild}) — or the source, + * the message and the engine to sync it with. + */ + static resolveRecordSync( + this: Pick, + data: unknown, + publishedAt: number | undefined, + ): | { outcome: KnowledgeRecordSyncOutcome } + | { source: KnowledgeSource; message: KnowledgeRecordSyncMessage; engine: IDataEngine } { + const message = readRecordSyncMessage(data); + if (!message) { + this.options.logger?.warn?.( + `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, + ); + return { outcome: 'malformed' }; + } + // Held (ADR-0161 K8, ruling 7248214179): completed without a sync, and no + // store is called, on the per-message and the batch path alike. + if (this.held) return { outcome: 'not-synced' }; + const source = this.handed(message.source); + if (!source) { + this.options.logger?.debug?.( + `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, + ); + return { outcome: 'source-gone' }; + } + if (objectSourcesFor([source], message.object).length === 0) return { outcome: 'not-synced' }; + const engine = this.options.dataEngine; + if (!engine) { + this.options.logger?.warn?.( + `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + + 'bound to re-read the row.', + ); + return { outcome: 'not-synced' }; + } + if (this.coveredByBuild(source.name, publishedAt)) return { outcome: 'covered' }; + return { source, message, engine }; + } + + /** + * [#38413] Whether a complete build of the source under `key` already did + * what a message published at `publishedAt` asks for, so the message can + * complete without a read. All of these must hold: + * + * - the source's last build on this node finished `done` and its PURGE RAN + * (`result.purged` is a number). The walk writes the document of every + * row it reads and the purge deletes the document of every row it did + * not, so a message for a deleted row, or for a row that left `where`, is + * covered only by a build that purged. A build that ends `done` with + * `purged: null` (an adapter without `listDocuments`, or a listing that + * failed and the walk went on) deleted nothing, and covers nothing; + * - the reconcile walks the source ({@link reconcileExclusion}): a source + * whose index an external indexer owns, or whose store lists nothing, is + * never covered; + * - the build began at least {@link RECORD_SYNC_COVER_MARGIN_MS} after + * `publishedAt`. A message is published once its write committed, and + * the walk reads every row after it starts. + * + * A build running now, or one that did not finish, covers nothing. + */ + static coveredByBuild( + this: Pick, + key: string, + publishedAt: number | undefined, + ): boolean { + if (publishedAt === undefined || !Number.isFinite(publishedAt)) return false; + const build = this.builds.get(key); + if (build?.status !== 'done' || typeof build.result?.purged !== 'number' || build.result.ok === false) return false; + const entry = this.registry.byIndexKey(key); + if (!entry || this.reconcileExclusion(entry) !== undefined) return false; + const startedAt = Date.parse(build.startedAt); + return Number.isFinite(startedAt) && publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS; + } + + static async processRecordSyncBatch( + this: Pick, + batch: readonly KnowledgeRecordSyncBatchItem[], + ): Promise { + const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); + const groups = new Map(); + batch.forEach((item, index) => { + const resolved = this.resolveRecordSync(item?.data, item?.publishedAt); + if ('outcome' in resolved) { + results[index] = { ok: true, outcome: resolved.outcome }; + return; + } + const key = JSON.stringify([resolved.source.name, resolved.message.object]); + let group = groups.get(key); + if (!group) { + group = { source: resolved.source, object: resolved.message.object, engine: resolved.engine, items: [] }; + groups.set(key, group); + } + group.items.push({ index, recordId: resolved.message.recordId, publishedAt: item.publishedAt }); + }); + for (const group of groups.values()) { + await this.considerBacklogReconcile(group, batch.length); + } + for (const group of groups.values()) { + try { + await this.syncRecordGroup(group, results); + } catch (err) { + for (const item of group.items) results[item.index] ??= { ok: false, error: err }; + } + } + return results; + } + + /** One group of {@link processRecordSyncBatch}: writes each of its items' result. */ + static async syncRecordGroup( + this: Pick< + KnowledgeServiceHost, + 'adapterFor' | 'coveredByBuild' | 'label' | 'options' | 'recordSyncTails' | 'syncRow' | 'syncRows' + >, + group: RecordSyncGroup, + results: KnowledgeRecordSyncBatchResult[], + ): Promise { + const { source, object, engine } = group; + let adapter: IKnowledgeAdapter; + try { + adapter = this.adapterFor(source); + } catch (err) { + for (const item of group.items) results[item.index] = { ok: false, error: err }; + return; + } + const open: RecordSyncGroup['items'] = []; + for (const item of group.items) { + if (this.coveredByBuild(source.name, item.publishedAt)) results[item.index] = { ok: true, outcome: 'covered' }; + else open.push(item); + } + if (open.length === 0) return; + const recordIds = [...new Set(open.map((item) => item.recordId))]; + const failures = new Map(); + await chainAfterAll(this.recordSyncTails, recordIds.map((id) => documentIdFor(source.name, id)), async () => { + if (recordIds.length > 1) { + try { + await this.syncRows(source, adapter, object, recordIds, engine); + return; + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] a batch of ${recordIds.length} record syncs of source '${this.label(source)}' failed (${errorText(err)}); ` + + 'syncing them one by one, so a record that cannot be synced fails alone.', + ); + } + } + for (const recordId of recordIds) { + try { + await this.syncRow(source, adapter, object, recordId, engine); + } catch (err) { + failures.set(recordId, err); + } + } + }); + for (const item of open) { + results[item.index] = failures.has(item.recordId) + ? { ok: false, error: failures.get(item.recordId) } + : { ok: true, outcome: 'synced' }; + } + } + + /** + * [#38413] The record-sync queue's waiting count (`getQueueSize`), read at + * most once per {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}. `undefined` + * when the queue cannot count or the count failed. + */ + static async recordSyncWaiting( + this: Pick, + ): Promise { + const now = Date.now(); + const last = this.recordSyncBacklog; + if (last && now - last.at < RECORD_SYNC_BACKLOG_READ_INTERVAL_MS) return last.waiting; + let waiting: number | undefined; + try { + waiting = await this.pendingRecordSyncs(); + } catch { + waiting = undefined; + } + this.recordSyncBacklog = { at: now, waiting }; + return waiting; + } + + /** + * [#38413] The rows of the source under `key` (its `where`, counted as the + * system identity), kept for {@link RECORD_SYNC_SOURCE_ROWS_TTL_MS}. + * `undefined` when the count failed. + */ + static async sourceRowCount( + this: Pick, + key: string, + objSource: ObjectKnowledgeSource, + engine: IDataEngine, + ): Promise { + const now = Date.now(); + const last = this.sourceRows.get(key); + if (last && now - last.at < RECORD_SYNC_SOURCE_ROWS_TTL_MS) return last.rows; + let rows: number | undefined; + try { + const counted = await engine.count(objSource.object, { where: objSource.where }, { context: systemContext() }); + rows = typeof counted === 'number' && Number.isFinite(counted) ? counted : undefined; + } catch { + rows = undefined; + } + this.sourceRows.set(key, { at: now, rows }); + return rows; + } + + /** + * [#38413] Ask 2 of the batch path: schedule one reconcile of the group's + * source when its backlog is large enough that a walk beside the drain + * pays. The source's backlog is estimated as the queue's waiting count + * times the group's share of the batch in hand (the batch is the head of + * the queue). A reconcile is scheduled when that estimate reaches both + * {@link RECORD_SYNC_BACKLOG_THRESHOLD} and + * {@link RECORD_SYNC_BACKLOG_ROW_SHARE} of the source's rows, no backlog + * reconcile of the source is running, and the source is past its wait: + * {@link RECORD_SYNC_BACKLOG_REWALK_MS} after one that ended `done`, or a + * backoff from {@link RECORD_SYNC_BACKLOG_RETRY_MS} doubling to + * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} after one that did not. + * + * It is scheduled, never awaited: the batch, and every other source's + * syncs, go on while it walks, and the messages its build covers + * ({@link coveredByBuild}) complete without a read once it ends. A source + * the reconcile does not walk ({@link reconcileExclusion}) is never + * scheduled. Never rejects. + */ + static async considerBacklogReconcile( + this: Pick< + KnowledgeServiceHost, + 'backlogReconciles' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'options' | + 'reconcileExclusion' | 'recordSyncWaiting' | 'registry' | 'sourceRowCount' + >, + group: RecordSyncGroup, + batchLength: number, + ): Promise { + const key = group.source.name; + const objSource = group.source.source; + if (objSource.kind !== 'object' || batchLength <= 0) return; + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) return; + const state = this.backlogReconciles.get(key); + if (state && (state.running || Date.now() < state.notBefore)) return; + const waiting = await this.recordSyncWaiting(); + if (waiting === undefined) return; + const estimate = Math.round((waiting * group.items.length) / batchLength); + if (estimate < RECORD_SYNC_BACKLOG_THRESHOLD) return; + const rows = await this.sourceRowCount(key, objSource, group.engine); + if (rows === undefined || estimate < rows * RECORD_SYNC_BACKLOG_ROW_SHARE) return; + + const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; + this.backlogReconciles.set(key, next); + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + + 'reconcile of the source is scheduled; record syncs go on meanwhile, and those it covers complete without a ' + + 'read once it ends.', + ); + void this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }) + .then(() => undefined, () => undefined) + .then(() => { + next.running = false; + const build = this.builds.get(key); + if (build?.status === 'done' && typeof build.result?.purged === 'number') { + next.failures = 0; + next.notBefore = Date.now() + RECORD_SYNC_BACKLOG_REWALK_MS; + return; + } + next.failures++; + const wait = Math.min(RECORD_SYNC_BACKLOG_RETRY_MS * 2 ** (next.failures - 1), RECORD_SYNC_BACKLOG_RETRY_MAX_MS); + next.notBefore = Date.now() + wait; + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}': the reconcile scheduled for its record-sync backlog ended ` + + `${build?.status ?? 'without a build'}${build?.status === 'done' ? ' with no purge' : ''}, so its record syncs are ` + + `drained one by one; another is not scheduled for ${Math.round(wait / 60_000)} min.`, + ); + }); + } + + /** + * [#38413] The batch twin of {@link syncRow}: re-read the rows `recordIds` + * name under the source's `where` as the system identity, in one read + * ({@link rereadRows}), write the documents of the rows that came back in + * one `upsert` and delete those of the ids no row matched in one `delete`, + * under one index plan. A document the split cannot index is removed and + * reported, as {@link writeSynced} does. Throws what the re-read, a + * document build, the split, the embedding call or the store throws. + */ + static async syncRows( + this: Pick< + KnowledgeServiceHost, + 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | 'reportUnindexable' | 'schemaFor' + >, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordIds: string[], + engine: IDataEngine, + ): Promise { + const objSource = source.source; + const rows = await rereadRows(engine, objSource, recordIds); + const byId = new Map>(); + for (const row of rows) if (isRecordId(row.id)) byId.set(String(row.id), row); + const schema = this.schemaFor(object); + const posture = await this.readTenancyPosture(); + const docs: KnowledgeDocument[] = []; + const gone: string[] = []; + const recordOf = new Map(); + for (const recordId of recordIds) { + const row = byId.get(recordId); + if (row) { + const doc = recordToDocument(source, objSource, row, schema, posture); + recordOf.set(doc.id, recordId); + docs.push(doc); + } else { + gone.push(documentIdFor(source.name, recordId)); + } + } + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, docs); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); + const removed = [...gone, ...prepared.failed.map((f) => f.documentId)]; + if (removed.length > 0) await adapter.delete(removed, ctx); + for (const f of prepared.failed) this.reportUnindexable(source, adapter, f, recordOf.get(f.documentId) ?? f.documentId); + } + + static async handleRecordUpsert( + this: Pick, + object: string, + record: Record, + ): Promise { + if (this.held) return; + const recordId = record.id; + for (const source of this.sourcesForObject(object)) { + const sync = (): Promise => this.syncRecord(source, object, recordId, record); + await (isRecordId(recordId) + ? this.serializeRecordSync(documentIdFor(source.name, String(recordId)), sync) + : sync()); + } + } + + /** + * One source's inline sync of one row — see {@link handleRecordUpsert}. + * Never throws: a failure is one `warn` line. + */ + static async syncRecord( + this: Pick< + KnowledgeServiceHost, + 'adapterFor' | 'label' | 'options' | 'readTenancyPosture' | 'reportWhereUnenforceable' | 'schemaFor' | + 'syncRow' | 'writeSynced' + >, + source: KnowledgeSource, + object: string, + recordId: unknown, + payload: Record, + ): Promise { + const objSource = source.source; + try { + const adapter = this.adapterFor(source); + const engine = this.options.dataEngine; + if (!engine) { + if (objSource.where !== undefined) { + this.reportWhereUnenforceable(source); + return; + } + const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); + await this.writeSynced(source, adapter, doc, recordId); + return; + } + if (!isRecordId(recordId)) { + this.options.logger?.warn?.( + `[knowledge] event-sync skipped for source '${this.label(source)}': the event's record names no id, ` + + 'so the row cannot be re-read against the source.', + ); + return; + } + await this.syncRow(source, adapter, object, recordId, engine); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, + ); + } + } + + /** + * THE sync of one row's document, both paths' ({@link syncRecord} inline, + * {@link processRecordSync} from the queue): re-read the row under the + * source's `where` as the system identity ({@link rereadRow}) and write its + * document, or delete the document when no row matches. Throws what the + * re-read, the split, the embedding call or the store throws. + */ + static async syncRow( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordId: string | number, + engine: IDataEngine, + ): Promise { + const objSource = source.source; + const row = await rereadRow(engine, objSource, recordId); + if (row) { + const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); + await this.writeSynced(source, adapter, doc, recordId); + } else { + const plan = await this.planIndex(source, adapter); + await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); + } + } + + /** + * The event sync's write of one document: split as every path splits + * ({@link prepareDocuments}) and upserted. A document the split cannot + * index (a `whole` document over the embedder's budget) is removed from the + * index and reported at `error`: the write that triggered the sync + * succeeded and search keeps answering, so nothing else shows that this + * record is no longer findable. + */ + static async writeSynced( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + doc: KnowledgeDocument, + recordId: unknown, + ): Promise { + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, [doc]); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); + for (const f of prepared.failed) { + await adapter.delete([f.documentId], ctx); + this.reportUnindexable(source, adapter, f, recordId); + } + } + + /** Say, at `error`, that a record's document left the index because its split cannot index it ({@link writeSynced}, {@link syncRows}). */ + static reportUnindexable( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + f: { estimate: number; budget: number }, + recordId: unknown, + ): void { + const limit = adapter.embedding?.maxInputTokens; + const message = + `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + + `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + + `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + + `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; + // `warn` is the guaranteed channel when a host injects no `error`. + const logger = this.options.logger; + if (logger?.error) logger.error(message); + else logger?.warn?.(message); + } + + /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ + static reportWhereUnenforceable( + this: Pick, + source: KnowledgeSource, + ): void { + if (this.whereUnenforceableReported.has(source.name)) return; + this.whereUnenforceableReported.add(source.name); + this.options.logger?.warn?.( + `[knowledge] source '${this.label(source)}' declares a where filter and no data engine is bound: record events ` + + 'for it are not synced, because the filter cannot be judged without re-reading the row. ' + + 'Bind a data engine (the objectql service) to sync it.', + ); + } + + /** + * Run `task` after every earlier sync of the same document (`key`) has + * finished — an in-process promise chain per document, dropped once idle. + * Only the ORDER of syncs is held; each still re-reads the row itself, so a + * later sync never acts on what an earlier one read. A task that rejects + * does not break the chain (the sync paths never throw; this is a backstop). + */ + static serializeRecordSync( + this: Pick, + key: string, + task: () => Promise, + ): Promise { + return chainAfter(this.recordSyncTails, key, task).catch(() => undefined); + } + + /** + * The registered object definition, when the bound engine exposes one + * (`getSchema` is not on the `IDataEngine` contract; the ObjectQL engine + * carries it). `undefined` — nothing to withhold by — otherwise. + */ + static schemaFor(this: Pick, object: string): unknown { + try { + return (this.options.dataEngine as { getSchema?: (name: string) => unknown } | undefined) + ?.getSchema?.(object); + } catch { + return undefined; + } + } + + static async handleRecordDelete( + this: Pick< + KnowledgeServiceHost, + 'adapterFor' | 'held' | 'label' | 'options' | 'planIndex' | 'serializeRecordSync' | 'sourcesForObject' + >, + object: string, + recordId: string, + ): Promise { + if (this.held) return; + const targets = this.sourcesForObject(object); + for (const source of targets) { + const docId = documentIdFor(source.name, recordId); + await this.serializeRecordSync(docId, async () => { + try { + const adapter = this.adapterFor(source); + await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] event-sync delete failed for source '${this.label(source)}': ${(err as Error).message}`, + ); + } + }); + } + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts new file mode 100644 index 00000000000..116f843d920 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -0,0 +1,1092 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] Search and answer: the bodies of `search`, `searchWithRefusals`, + * `searchByKey`, `sourcesGroupableBy`, `groupKeyOf`, `affinityOrderFor`, + * `affinityFactsOf`, `answerByRecord`, `checkFreshness`, `dropUnverifiedHits`, + * `repairStale`, `planSearches`, `unprovenIndex`, `searchRound`, `sourcesInScope`, + * `sourcesNarrowedToVisible`, `readVisibleIds`, `checkScope`, + * `resolveSearchTargets`, moved out of `knowledge-service.ts` whole. + * + * A MOVE, not a redesign. {@link KnowledgeSearchFacet} is a stateless facet of + * `KnowledgeService`: each static method is the body of the `KnowledgeService` + * member of the same name exactly as it stood (not re-indented, not edited). + * The member stays on the class as a one-call stub with its signature, so the + * published declaration, an instance spy and a subclass override are what they + * were. A public member keeps its docblock on the class, the contract; a + * private member's docblock moved here with its body. The state stays on + * `KnowledgeService`. + * + * A body reaches the service through `this`, typed as the part of + * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands + * it the host the class's static block builds once per service, whose methods call + * the service at call time and whose fields are getters (and a setter for a + * field a body assigns). A body that reads nothing of the service is called + * without one. `index.ts` re-exports nothing from this module. + */ + +import type { + AdapterIndexStatus, + AdapterScopeTerm, + IDataEngine, + IKnowledgeAdapter, + KnowledgeSearchOptions, +} from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { TenancyPosture } from '@objectstack/spec/security'; +import { refusal } from './knowledge-tools.js'; +import { + type AffinityCallerFacts, + affinityFactNeeds, + orderByAffinity, + resolveAffinityFacts, +} from './knowledge-affinity.js'; +import { + SEARCH_VISIBLE_IDS_MAX, + type SearchScopeEntry, + narrowToVisible, + readSearchScope, + scopeCheck, + scopeTermsFor, +} from './knowledge-search-scope.js'; +import { + type AdmittedSource, + INDEX_NOT_PROVEN_CODE, + type IndexPlan, + type KnowledgeSearchRefusal, + type KnowledgeSearchReport, + SEARCH_FIRST_ROUND_FACTOR, + SEARCH_FRESHNESS_ROUNDS, + SEARCH_REFILL_FACTOR, + type SearchTarget, + UNPROVEN_CALLER_TEXT, + UNPROVEN_OPERATOR_TEXT, + type UnprovenEnd, + codedRefusalOf, + describeValue, + distinctGroups, + documentIdFor, + documentKeyOf, + errorText, + freshnessFields, + heldSourcesError, + isRecordId, + objectSourcesFor, + operatorText, + quotedName, + recordKeyOf, + recordToDocument, + stableJson, + systemContext, + wholeRefusal, +} from './knowledge-service-top-level.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; + +export class KnowledgeSearchFacet { + static async search( + this: Pick, + query: string, + opts: KnowledgeSearchOptions = {}, + ): Promise { + return (await this.searchWithRefusals(query, opts)).hits; + } + + static async searchWithRefusals( + this: Pick, + query: string, + opts: KnowledgeSearchOptions = {}, + ): Promise { + // [ADR-0161 K8, the dated note on item 12] Held: refused, never answered + // empty (K7 rule 5), naming the half that is missing. + if (this.held) throw heldSourcesError(this.held); + const report = await this.searchByKey(query, opts); + return { + hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), + refused: this.facedRefusals(report.refused), + }; + } + + /** + * {@link searchWithRefusals} with every source named by its index key, as + * an adapter's hit names it; the public member translates each to its face. + * A whole refusal thrown from here already names the sources by face. + */ + static async searchByKey( + this: Pick< + KnowledgeServiceHost, + 'admitSources' | 'affinityOrderFor' | 'answerByRecord' | 'applyPermissionFilter' | 'defaultTopK' | + 'dropUnverifiedHits' | 'facedRefusals' | 'groupKeyOf' | 'options' | 'planSearches' | 'resolveSearchTargets' | + 'searchRound' | 'sourcesGroupableBy' | 'sourcesInScope' | 'sourcesNarrowedToVisible' + >, + query: string, + opts: KnowledgeSearchOptions, + ): Promise { + const scope = readSearchScope(opts.scope); + const topK = opts.topK ?? this.defaultTopK; + const groupBy = opts.groupBy; + if (groupBy !== undefined) { + if (typeof groupBy !== 'string' || groupBy.length === 0) { + throw refusal('VALIDATION_ERROR', 400, '[knowledge] search groupBy must name a metadata field (a non-empty string).'); + } + if (opts.granularity === 'chunk') { + throw refusal( + 'VALIDATION_ERROR', + 400, + `[knowledge] search groupBy ${quotedName(groupBy)} groups records, so it cannot be combined with granularity 'chunk'. ` + + "Drop granularity, or pass granularity 'record'.", + ); + } + } + if (opts.granularity !== undefined && opts.granularity !== 'chunk' && opts.granularity !== 'record') { + throw refusal( + 'VALIDATION_ERROR', + 400, + `[knowledge] search granularity must be 'chunk' or 'record', got '${String(opts.granularity)}'.`, + ); + } + const byRecord = opts.granularity === 'record' || groupBy !== undefined; + const ctx = opts.executionContext; + let admitted: Array = + await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); + if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); + const engine = this.options.dataEngine; + const filtered = ctx !== undefined && ctx.isSystem !== true && engine !== undefined; + // A caller the re-check can remove hits for: each source ranks only the + // records they may read, when those are few enough to name. + if (filtered && admitted.length > 0) admitted = await this.sourcesNarrowedToVisible(admitted, ctx, engine); + if (admitted.length === 0) return { hits: [], refused: [] }; + const refused: KnowledgeSearchRefusal[] = []; + const sources = await this.planSearches(admitted, refused); + // The sources whose every hit is checked against its live record before + // it is served: the ones the earlier title rule could serve a field for. + const verified = new Set(sources.filter((target) => target.verifyHits === true).map((target) => target.source.name)); + const served = async (hits: KnowledgeHit[]): Promise => + verified.size === 0 ? hits : this.dropUnverifiedHits(hits, verified); + + const widened = byRecord || filtered; + const firstAsk = (_source: KnowledgeSource): number => + widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; + const groupOf = byRecord + ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) + : recordKeyOf; + const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); + if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); + const raw = [...first.values()].flatMap((answer) => answer.hits); + let kept = await served(await this.applyPermissionFilter(raw, ctx, byRecord)); + let removed = raw.length - kept.length; + + if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { + const saturated = sources.filter(({ source }) => { + const answer = first.get(source.name); + return widened && answer !== undefined && answer.answered >= firstAsk(source); + }); + if (saturated.length > 0) { + const refusedBefore = refused.length; + const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); + // A refilled source's second answer is a superset of its first: its + // first-round survivors are dropped and the whole answer re-checked. + const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); + const refilledKept = await served(await this.applyPermissionFilter(refilledHits, ctx, byRecord)); + const firstRaw = raw.filter((hit) => refill.has(hit.sourceId)).length; + const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; + kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; + removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); + // A source that refused the refill (its index changed between the two + // rounds) is refused for the whole search: its first-round hits are + // dropped, so no source is both answered and named as refused. + const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); + if (refusedInRefill.size > 0) { + kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); + if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(this.facedRefusals(refused)); + } + } + } + + if (removed > 0) { + this.options.logger?.debug?.( + `[knowledge] the permission re-check and the per-hit record check removed ${removed} hit(s); ` + + `${Math.min(byRecord ? distinctGroups(kept, groupOf) : kept.length, topK)} of topK=${topK} answered.`, + ); + } + kept.sort((a, b) => b.score - a.score); + // [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} ` + + `${groupBy === undefined ? 'records' : `${quotedName(groupBy)} groups`}: no more within the refill cap ` + + `(topK × ${SEARCH_REFILL_FACTOR} passages per source).`, + ); + } + return { hits: answer, refused }; + } + + /** + * The sources a `groupBy` search asks: each source that lists `groupBy` in + * its `metadataFields`. Any other source answers no hits for this search — + * its hits carry no group value, and a hit is never answered ungrouped. + */ + static sourcesGroupableBy( + this: Pick, + sources: T[], + groupBy: string, + ): T[] { + return sources.filter(({ source }) => { + if ((source.source.metadataFields ?? []).includes(groupBy)) return true; + this.options.logger?.debug?.( + `[knowledge] source '${this.label(source)}' not searched for groupBy ${quotedName(groupBy)}: ` + + 'the field is not one of its metadataFields.', + ); + return false; + }); + } + + /** + * The group a hit falls in under record granularity: with `groupBy`, the + * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — + * when the hit carries none); without it, the parent record its source's + * `documentBy` names, else the hit's record ({@link documentKeyOf}). + */ + static groupKeyOf( + this: Pick, + hit: KnowledgeHit, + groupBy: string | undefined, + ): string | undefined { + if (groupBy === undefined) return documentKeyOf(hit, this.handed(hit.sourceId)?.source.documentBy); + const value = hit.metadata?.[groupBy]; + if (value === undefined || value === null || value === '') return undefined; + 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. + */ + static async affinityOrderFor( + this: Pick, + 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. */ + static async affinityFactsOf( + this: Pick, + 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`, 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 + * + * The index is a copy, and a record may have changed since it was indexed. + * So each `object`-source hit about to be answered is checked against its + * record as it reads now — one system-context read per source, of the hits' + * records only (at most `topK`), `{ $and: [where, { id: { $in } }] }` + * projected to the fields assembly reads. A record that no longer exists or + * no longer matches `where`, or whose recomputed `docHash` differs from the + * hit's (the stored hash), is dropped — all of its passages — and its + * document repaired in the background ({@link repairStale}) unless the source + * opted out of the event sync (`refresh.onRecordChange: false`: an external + * indexer owns that index, so the service writes nothing to it and the hit + * is only dropped). A group whose + * lead was dropped falls back to its next passage, and the next groups move + * up; that is checked again, at most `SEARCH_FRESHNESS_ROUNDS` times, after + * which a hit still unchecked is not answered (`capped`, logged at `debug` + * by its own line). A hit whose adapter stores no + * hash is checked for membership only. A read that fails drops that + * source's checked hits (fail-closed), reported at `warn`. + * + * Not checked: a hit without a record id, and every hit when no data engine + * is bound. + */ + static async answerByRecord( + this: Pick, + 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) { + const key = groupOf(hit); + if (key === undefined) continue; + const members = groups.get(key); + if (members) members.push(hit); + else groups.set(key, [hit]); + } + const engine = this.options.dataEngine; + const checkKey = (hit: KnowledgeHit): string | undefined => + engine !== undefined && hit.sourceRecordId !== undefined && this.handed(hit.sourceId) !== undefined + ? `${hit.sourceId}#${hit.sourceRecordId}` + : undefined; + const fresh = new Set(); + const stale = new Set(); + const leads = (): KnowledgeHit[] => { + const out: KnowledgeHit[] = []; + for (const members of groups.values()) { + const lead = members.find((hit) => { + const key = checkKey(hit); + return key === undefined || !stale.has(key); + }); + if (lead) out.push(lead); + } + // 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(); + const unchecked = top.filter((hit) => { + const key = checkKey(hit); + return key !== undefined && !fresh.has(key); + }); + if (unchecked.length === 0) return { hits: top, capped: false }; + if (round === SEARCH_FRESHNESS_ROUNDS) { + this.options.logger?.debug?.( + `[knowledge] record-level search stopped checking freshness after ${SEARCH_FRESHNESS_ROUNDS} rounds; ` + + `${unchecked.length} unchecked hit(s) not answered.`, + ); + return { hits: top.filter((hit) => !unchecked.includes(hit)), capped: true }; + } + await this.checkFreshness(unchecked, fresh, stale); + } + } + + /** + * One round of the freshness check ({@link answerByRecord}): read the + * records `hits` name, one system-context read per source, and sort each + * record into `fresh` or `stale` (`sourceId#recordId`). + */ + static async checkFreshness( + this: Pick< + KnowledgeServiceHost, + 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' + >, + hits: KnowledgeHit[], + fresh: Set, + stale: Set, + ): Promise { + const engine = this.options.dataEngine; + if (!engine) return; + const bySource = new Map>(); + for (const hit of hits) { + const records = bySource.get(hit.sourceId) ?? new Map(); + if (!records.has(hit.sourceRecordId!)) records.set(hit.sourceRecordId!, hit); + bySource.set(hit.sourceId, records); + } + let posture: { value: TenancyPosture | undefined } | null | undefined; + for (const [sourceId, records] of bySource) { + const source = this.handed(sourceId)!; + const objSource = source.source; + const ids = [...records.keys()]; + const byId = { id: { $in: ids } }; + const schema = this.schemaFor(objSource.object); + let rows: unknown; + try { + if (posture === undefined) { + try { + posture = { value: await this.readTenancyPosture() }; + } catch (err) { + posture = null; + this.options.logger?.warn?.( + `[knowledge] the tenancy posture could not be read (${errorText(err)}); the freshness check of this ` + + 'search compares no document hash, only whether each record still belongs to its source.', + ); + } + } + const fields = freshnessFields(objSource, schema, posture?.value); + rows = await engine.find( + objSource.object, + { + where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, + ...(fields === undefined ? {} : { fields }), + }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) { + throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + } + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the freshness check of source '${sourceId}' could not read its records ` + + `(${errorText(err)}); its hits are not answered.`, + ); + for (const id of ids) stale.add(`${sourceId}#${id}`); + continue; + } + const byRow = new Map>(); + for (const row of rows as Array | null | undefined>) { + if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + } + for (const [recordId, hit] of records) { + const key = `${sourceId}#${recordId}`; + const docId = documentIdFor(sourceId, recordId); + const row = byRow.get(recordId); + const changed = + row !== undefined && + hit.docHash !== undefined && + posture !== null && + recordToDocument(source, objSource, row, schema, posture?.value).docHash !== hit.docHash; + if (row === undefined || changed) { + stale.add(key); + this.repairStale(source, objSource, recordId); + } else { + fresh.add(key); + if (hit.docHash !== undefined && posture !== null) this.freshnessRepairs.delete(docId); + } + } + } + } + + /** + * The hits of `verified` sources whose stored document is the one the + * current recipe assembles from the record as it reads now; every other hit + * of those sources is dropped. A hit of any other source passes untouched. + * + * Why: a source the earlier title rule could serve a field for + * (`mayServeEarlierRuleTitle`) is searched without the field gate's former + * `title` arm, and its index may still hold a document assembled under + * another recipe: one a build walked past and did not purge (a store with + * no `listDocuments`, `refresh.onRecordChange: false`, a purge candidate + * kept or listed under a foreign id), or one written between two builds + * while the object's display field was another field. The recipe hash + * cannot see either; this check reads the record. A hit survives only when + * its record still belongs to the source (one system read per source, + * `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly + * reads), its document id is the one the source derives from that record, + * and the `docHash` the store holds equals the one {@link recordToDocument} + * computes from the row under the current object definition (the title is + * part of it). Strict, unlike {@link checkFreshness}: a hit with no record + * id or no stored hash, a read that fails or answers no list, a posture + * that cannot be read and a hash that cannot be computed each drop the hit. + * + * The read decides only whether a hit survives: a surviving hit is returned + * as the store answered it, and nothing the read returned is put on it. A + * stale record's document is repaired in the background ({@link + * repairStale}), as the record-level check repairs it. + */ + static async dropUnverifiedHits( + this: Pick< + KnowledgeServiceHost, + 'faceOfKey' | 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' + >, + hits: KnowledgeHit[], + verified: ReadonlySet, + ): Promise { + const engine = this.options.dataEngine; + const checked = hits.filter((hit) => verified.has(hit.sourceId)); + if (checked.length === 0) return hits; + const passed = new Set(); + const dropped = (sourceId: string, count: number, why: string): void => { + if (count > 0) { + this.options.logger?.debug?.( + `[knowledge] ${count} hit(s) of source '${this.faceOfKey(sourceId)}' not served: ${why}`, + ); + } + }; + let posture: TenancyPosture | undefined; + let postureRead = true; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + postureRead = false; + this.options.logger?.warn?.( + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no hit of a source checked against its ` + + 'record is served this search (fail-closed).', + ); + } + const bySource = new Map(); + for (const hit of checked) bySource.set(hit.sourceId, [...(bySource.get(hit.sourceId) ?? []), hit]); + for (const [sourceId, sourceHits] of bySource) { + const source = this.handed(sourceId); + if (!engine || !postureRead || !source || source.source.kind !== 'object') { + dropped(sourceId, sourceHits.length, 'their records cannot be read to check them.'); + continue; + } + const objSource = source.source; + const usable = sourceHits.filter( + (hit) => isRecordId(hit.sourceRecordId) && typeof hit.docHash === 'string' && hit.docHash !== '', + ); + dropped(sourceId, sourceHits.length - usable.length, 'a hit names no record or carries no stored hash.'); + if (usable.length === 0) continue; + const ids = [...new Set(usable.map((hit) => String(hit.sourceRecordId)))]; + const byId = { id: { $in: ids } }; + const schema = this.schemaFor(objSource.object); + let rows: unknown; + try { + const fields = freshnessFields(objSource, schema, posture); + rows = await engine.find( + objSource.object, + { + where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, + ...(fields === undefined ? {} : { fields }), + }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the records of source '${this.faceOfKey(sourceId)}' could not be read to check its hits ` + + `(${errorText(err)}); none is served (fail-closed).`, + ); + continue; + } + const byRow = new Map>(); + for (const row of rows as Array | null | undefined>) { + if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + } + const current = new Map(); + for (const hit of usable) { + const recordId = String(hit.sourceRecordId); + if (hit.documentId !== documentIdFor(sourceId, recordId)) continue; + if (!current.has(recordId)) { + const row = byRow.get(recordId); + let hash: string | undefined; + if (row !== undefined) { + try { + hash = recordToDocument(source, objSource, row, schema, posture).docHash; + } catch { + hash = undefined; + } + } + current.set(recordId, hash); + if (row === undefined || (hash !== undefined && hash !== hit.docHash)) this.repairStale(source, objSource, recordId); + } + const hash = current.get(recordId); + if (hash !== undefined && hash === hit.docHash) { + passed.add(hit); + this.freshnessRepairs.delete(documentIdFor(sourceId, recordId)); + } + } + dropped( + sourceId, + usable.filter((hit) => !passed.has(hit)).length, + 'the record no longer belongs to the source, or the stored document is not the one the current recipe assembles from it.', + ); + } + return hits.filter((hit) => !verified.has(hit.sourceId) || passed.has(hit)); + } + + /** + * Repair the document of a record the freshness check found stale: the + * event sync's own path ({@link syncRecord}, serialized per document), run + * in system context, in this process and NOT awaited — the search that found + * it answers without it. Single-flight per document, and at most once per + * document until a later search finds its hash matching. Never throws into + * the search. The scheduled reconcile does not take it over: the reconcile + * walks whole sources, and this repairs one document now. That is the + * inline path. + * + * While record syncs run through the queue ({@link routeRecordSyncs}) the + * repair is a record-sync message with reason `freshness`, for this source + * alone: it survives a restart of the process that searched and is retried + * like any other sync. A message that could not be published is reported + * at `error` and the document is left to the next search that finds it + * stale. + * + * A source with `refresh.onRecordChange: false` is never repaired: it is + * asked through {@link objectSourcesFor}, the one predicate that keeps the + * service's writes out of a source an external indexer owns, so the stale + * hit is dropped from the answer and its index entry left to that indexer. + */ + static repairStale( + this: Pick< + KnowledgeServiceHost, + 'freshnessRepairs' | 'publishRecordSyncs' | 'recordSyncPublisher' | 'serializeRecordSync' | 'syncRecord' + >, + source: KnowledgeSource, + objSource: ObjectKnowledgeSource, + recordId: string, + ): void { + if (objectSourcesFor([source], objSource.object).length === 0) return; + const docId = documentIdFor(source.name, recordId); + if (this.freshnessRepairs.has(docId)) return; + this.freshnessRepairs.add(docId); + if (this.recordSyncPublisher) { + this.publishRecordSyncs([source], objSource.object, recordId, 'freshness', () => this.freshnessRepairs.delete(docId)); + return; + } + void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); + } + + /** + * Each admitted source paired with the adapter it binds to, resolved here + * once for the whole search, and the fingerprint its search carries + * ({@link planIndex}); a source whose adapter does not resolve carries the + * coded refusal instead and is refused by the round, never searched. + * + * A source admitted with `proveIndex` ({@link admitSources}) is searched + * only when its index is proven built under the current recipe + * ({@link unprovenIndex}); otherwise it is not searched and is added to + * `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), the operator told why at + * `warn`. Each says whether a rebuild ends the refusal: for a source no + * build can prove, neither promises one. The boot's build pass, a reload, + * the reconcile and the operator's rebuild are what build a source; a + * search never starts a build. + */ + static async planSearches( + this: Pick< + KnowledgeServiceHost, + 'adapterIdFor' | 'getAdapter' | 'label' | 'options' | 'planIndex' | 'readChunkTarget' | 'unprovenIndex' + >, + admitted: Array, + refused: KnowledgeSearchRefusal[], + ): Promise { + const out: SearchTarget[] = []; + // The settings page's chunk target, read at most once for the whole search. + let target: Promise | undefined; + const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); + for (const { proveIndex, ...entry } of admitted) { + // The adapter is resolved here, once per search: the proof below is read + // from this instance and both rounds search this instance, so a source + // cannot change binding between the check and the use. + let adapterId: string; + let adapter: IKnowledgeAdapter; + try { + adapterId = this.adapterIdFor(entry.source); + adapter = this.getAdapter(adapterId); + } catch (err) { + // Refused like an adapter that cannot serve, as the round refuses it; a + // source that needs the index proof is never searched without it. + out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); + continue; + } + const plan = await this.planIndex(entry.source, adapter, chunkTarget); + if (proveIndex === true) { + const unproven = await this.unprovenIndex(plan); + if (unproven !== undefined) { + const label = this.label(entry.source); + refused.push({ + sourceId: entry.source.name, + code: INDEX_NOT_PROVEN_CODE, + status: 409, + message: `Knowledge source '${label}' is not searched: its index is not proven built under the current recipe. ` + + UNPROVEN_CALLER_TEXT[unproven.ends], + }); + this.options.logger?.warn?.( + `[knowledge] source '${label}' not searched (${INDEX_NOT_PROVEN_CODE}): ${unproven.why} Its object declares ` + + "a field named 'title' the source does not serve, and a document indexed under the earlier title rule " + + "carries that field's value, so the source is searched only once its index is proven built under the " + + `current recipe. ${UNPROVEN_OPERATOR_TEXT[unproven.ends]}`, + ); + continue; + } + } + out.push({ + ...entry, + binding: { adapterId, adapter }, + fingerprint: plan.index.fingerprint, + ...(proveIndex === true ? { verifyHits: true as const } : {}), + }); + } + return out; + } + + /** + * Why `plan`'s source is not proven built under the current recipe, and + * what ends it, or `undefined` when it is proven: its adapter's + * `indexStatus` reports the fingerprint AND the recipe hash + * {@link planIndex} computes now, and the builds that record that hash + * purge what they did not walk. + * + * The recipe hash names the title rule (ADR-0161 K7), and an adapter + * records it only at `completeBuild`, the end of a complete build. A + * complete build rewrites every document whose title changed (`docHash` + * covers the title) and, when it purges, removes every document it did not + * walk. It does not purge, and still records the hash, for a source with + * `refresh.onRecordChange: false` and on an adapter with no + * `listDocuments` ({@link walkObjectSource}): a document it did not walk, + * such as one whose row left the source's `where`, keeps what it was + * assembled with. So those two shapes are never proven, before any read, + * whatever the hash reads; nor is an adapter with no `indexStatus` (nothing + * to read) or no `completeBuild` (nothing ever records a hash). + * + * The proof covers what the last complete build walked and purged. Read on + * every search that needs it, never cached: another node may rebuild, or + * drop, the index. Fails closed: a status that throws is not proven. + */ + static async unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { + const { adapter, index, source } = plan; + if ((source.refresh?.onRecordChange ?? true) === false) { + return { + ends: 'never', + why: + 'refresh.onRecordChange is false, so an external indexer owns its index: a build of it purges nothing, ' + + 'so a recorded recipe hash does not prove the index holds no document assembled under an earlier recipe.', + }; + } + if (typeof adapter.indexStatus !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' reports no index status (no indexStatus), so what its index was built under cannot be read.`, + }; + } + if (typeof adapter.completeBuild !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' has no completeBuild, so no build records a recipe hash for its index.`, + }; + } + if (typeof adapter.listDocuments !== 'function') { + return { + ends: 'never', + why: + `the adapter '${adapter.id}' does not list its documents (no listDocuments), so a complete build cannot purge a ` + + 'document it did not walk, and a recorded recipe hash does not prove the index holds none assembled under an ' + + 'earlier recipe.', + }; + } + let held: AdapterIndexStatus; + try { + held = await adapter.indexStatus(plan.context('search')); + } catch (err) { + return { ends: 'unreadable', why: `the adapter's index status could not be read (${operatorText(err)}).` }; + } + if (held?.fingerprint !== index.fingerprint) { + return { ends: 'rebuild', why: 'the index holds no complete build under the current fingerprint.' }; + } + if (held.recipeHash !== index.recipeHash) { + return { + ends: 'rebuild', + why: held.recipeHash === undefined + ? 'the index records no recipe hash: no complete build of it has completed.' + : "the index was last completed under another recipe (the source's where, metadataFields, title rule or withheld fields).", + }; + } + return undefined; + } + + /** + * One round of {@link search}: ask each source's adapter for `ask(source)` + * hits. Answers, per source that answered, the hits it serves and how many + * the adapter returned (`answered`, before a hit naming another source or + * outside the scope is dropped — what decides whether the adapter may hold + * more). A source whose adapter is unknown or throws is absent from the + * answer: a coded refusal (ADR-0112 `code` and `status`) is added to + * `refused`, anything else is logged. + * + * Under a scope, the adapter is handed the source's terms, and every hit it + * answers is checked against them ({@link scopeCheck}, fail closed). The first + * time the check drops a hit of an adapter, that is reported once for the + * adapter, at `warn`: it does not apply the scope before ranking, or answers + * hits without the document's metadata, so its scoped searches may answer + * fewer than `topK` (ADR-0161 K8, rule 2). How many hits were dropped is + * logged, never returned. + */ + static async searchRound( + this: Pick, + query: string, + sources: SearchTarget[], + ask: (source: KnowledgeSource) => number, + filter: Record | undefined, + refused: KnowledgeSearchRefusal[], + ): Promise> { + const out = new Map(); + for (const { source, organizationIds, fingerprint, scope, binding } of sources) { + // Refused like an adapter that cannot serve: the caller is told which + // source was not searched and why; the boot said so at `error` + // (`reportUnmountedAdapters`), so no line per search. The adapter was + // resolved once for the whole search ({@link planSearches}); a round + // searches that instance and never looks it up again. + if ('refusal' in binding) { + if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); + continue; + } + const { adapterId, adapter } = binding; + try { + const hits = await adapter.search(query, { + source, + topK: ask(source), + filter, + ...(organizationIds === undefined ? {} : { organizationIds }), + ...(fingerprint === undefined ? {} : { index: { fingerprint } }), + ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), + }); + // A hit is served as the source it was searched for. One whose + // `sourceId` names another source (an adapter answering from a store + // two sources share) is dropped: that source's admission was never + // asked for this hit, so serving it would skip the gates above. + const served: KnowledgeHit[] = []; + for (const hit of hits) if (hit.sourceId === source.name) served.push(hit); + const foreign = hits.length - served.length; + if (foreign > 0) { + this.options.logger?.warn?.( + `[knowledge] adapter '${adapterId}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + + 'another source; dropped — a hit is served only as the source it was searched for.', + ); + } + out.set(source.name, { + hits: scope === undefined ? served : this.checkScope(served, scope, source, adapterId), + answered: hits.length, + }); + } catch (err) { + const coded = codedRefusalOf(err); + if (coded !== undefined) { + // The caller reads the code and the adapter's one-sentence message; + // the operator reads its remedy (the SQL to run, say) here. + refused.push({ sourceId: source.name, ...coded }); + this.options.logger?.warn?.( + `[knowledge] source '${this.label(source)}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, + ); + continue; + } + this.options.logger?.error?.( + `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, + ); + } + } + return out; + } + + /** + * [ADR-0161 K8, item 17] Pair each admitted source with the terms `scope` + * gives it ({@link scopeTermsFor}): a `record` term for an entry naming the + * object the source indexes, a `metadata` term for an entry naming a parent + * object the source reaches through the one parent link it lists in + * `metadataFields`, read from the object's registered definition. A source + * no entry reaches is not + * searched, logged at `debug`. A source that lists two or more parent links + * to an entry's object is not reached by that entry, reported once per + * source and object at `warn`, naming the fields. + */ + static sourcesInScope( + this: Pick, + sources: T[], + scope: readonly SearchScopeEntry[], + ): Array { + const out: Array = []; + for (const entry of sources) { + const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); + for (const { object, fields } of ambiguous) { + const key = `${entry.source.name}\u0000${object}`; + if (this.scopeAmbiguousReported.has(key)) continue; + this.scopeAmbiguousReported.add(key); + this.options.logger?.warn?.( + `[knowledge] source '${this.label(entry.source)}' lists ${fields.length} fields pointing at '${object}' ` + + `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + + 'it is not told which field the scope means.', + ); + } + if (terms.length === 0) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' not searched: no entry of the search's scope reaches it.`, + ); + continue; + } + out.push({ ...entry, scope: terms }); + } + return out; + } + + /** + * Narrow each source's search to the records a non-system caller may read + * ({@link narrowToVisible}). Per source, the ids of the records it indexes + * that the caller may read are read first — as the caller, under the + * source's `where`, ids only, at most {@link SEARCH_VISIBLE_IDS_MAX} + 1 — + * once per object and `where` the search asks. When the caller may read no + * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a + * `record` term, intersected with the caller's own scope, so its adapter + * ranks only those rows and a narrow caller's answers are not crowded out of + * the refill cap by rows they could never be served. + * + * A source is searched as before — on the caller's own scope, its hits + * re-checked within the refill cap — when the caller may read more than + * that, when the caller's scope holds a parent (`metadata`) term, when the + * narrowing names no record (the caller may read none of what the source + * could answer: answered as before, no hit or the source's refusal, never a + * new kind of empty), or when the read fails (logged at `warn`). Nothing here decides access: every hit is + * still re-checked as the caller ({@link applyPermissionFilter}), and the + * organization filter each source carries is not touched. + */ + static async sourcesNarrowedToVisible( + this: Pick, + sources: T[], + ctx: ExecutionContext, + engine: IDataEngine, + ): Promise { + const reads = new Map>(); + const visibleOf = (objSource: ObjectKnowledgeSource): Promise => { + const key = JSON.stringify([objSource.object, objSource.where ?? null]); + let read = reads.get(key); + if (read === undefined) { + read = this.readVisibleIds(objSource, ctx, engine); + reads.set(key, read); + } + return read; + }; + const visible = sources.map((entry) => + entry.scope?.some((term) => term.kind !== 'record') === true + ? Promise.resolve(undefined) + : visibleOf(entry.source.source)); + const out: T[] = []; + for (const [i, entry] of sources.entries()) { + const ids = await visible[i]; + const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); + // A narrowing that names no record is not applied: the source is + // searched as before, so a caller who may read none of its records is + // answered as before too — no hit, or the source's refusal. + if (narrowed === undefined || narrowed.every((term) => term.ids.length === 0)) { + out.push(entry); + continue; + } + out.push({ ...entry, scope: narrowed }); + } + return out; + } + + /** + * The ids of the records of `objSource` the caller may read, read as the + * caller under the source's `where`; `undefined` when there are more than + * {@link SEARCH_VISIBLE_IDS_MAX} or the read fails. + */ + static async readVisibleIds( + this: Pick, + objSource: ObjectKnowledgeSource, + ctx: ExecutionContext, + engine: IDataEngine, + ): Promise { + let rows: unknown; + try { + // As the caller, in the query, as the permission re-read asks. + rows = await engine.find(objSource.object, { + ...(objSource.where === undefined ? {} : { where: objSource.where }), + fields: ['id'], + limit: SEARCH_VISIBLE_IDS_MAX + 1, + context: ctx, + } as never); + if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the caller's readable records of object='${objSource.object}' could not be read ` + + `(${errorText(err)}); its sources are searched unnarrowed, every hit re-checked.`, + ); + return undefined; + } + if (rows.length > SEARCH_VISIBLE_IDS_MAX) return undefined; + const ids: string[] = []; + for (const row of rows as Array<{ id?: unknown } | null | undefined>) { + const id = row?.id; + if ((typeof id === 'string' && id.length > 0) || typeof id === 'number') ids.push(String(id)); + } + return ids; + } + + /** + * The hits of `source` that some scope term holds for ({@link scopeCheck}); + * the rest are dropped, and the first time an adapter's answer loses a hit + * here it is reported once, at `warn` ({@link searchRound}). + */ + static checkScope( + this: Pick, + hits: KnowledgeHit[], + terms: readonly AdapterScopeTerm[], + source: KnowledgeSource, + adapterId: string, + ): KnowledgeHit[] { + const inScope = scopeCheck(terms); + const kept = hits.filter(inScope); + const dropped = hits.length - kept.length; + if (dropped > 0 && !this.scopeIgnoredReported.has(adapterId)) { + this.scopeIgnoredReported.add(adapterId); + this.options.logger?.warn?.( + `[knowledge] adapter '${adapterId}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + + "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + + "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + + 'Reported once for this adapter.', + ); + } + return kept; + } + + /** + * The sources a search asks: every source whose `aiExposed` is not `false`, + * or the ones `sourceIds` names — each read by the one rule, so a name + * several sources have refuses the search (`409 RESOURCE_CONFLICT`) and a + * name none has is skipped, reported at `warn`. + */ + static resolveSearchTargets( + this: Pick, + sourceIds?: string[], + ): KnowledgeSource[] { + if (!sourceIds || sourceIds.length === 0) { + return this.handedSources().filter((s) => s.aiExposed !== false); + } + const out = new Map(); + for (const id of sourceIds) { + const entry = this.registry.resolve(id); + if (entry) out.set(entry.key, entry.handed); + else this.options.logger?.warn?.(`[knowledge] search target '${id}' not registered; skipping.`); + } + return [...out.values()]; + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts new file mode 100644 index 00000000000..7659c9aaa0a --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -0,0 +1,365 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] Adapters, sources and enablement: the bodies of `settleEnablement`, + * `registerAdapter`, `getAdapter`, `adapterIdFor`, `boundAdapterId`, + * `refuseUnplacedSource`, `reportUnmountedAdapters`, `listAdapters`, + * `registerSource`, `registerMetadataSource`, `metadataSources`, + * `onSourcesChanged`, `sourcesChanged`, `unregisterSource`, `dropMetadataSource`, + * `forget`, `listSources`, `describeSources`, `getSource`, `describeSource`, + * `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry`, moved + * out of `knowledge-service.ts` whole. + * + * A MOVE, not a redesign. {@link KnowledgeSourcesFacet} is a stateless facet of + * `KnowledgeService`: each static method is the body of the `KnowledgeService` + * member of the same name exactly as it stood (not re-indented, not edited). + * The member stays on the class as a one-call stub with its signature, so the + * published declaration, an instance spy and a subclass override are what they + * were. A public member keeps its docblock on the class, the contract; a + * private member's docblock moved here with its body. The state stays on + * `KnowledgeService`. + * + * A body reaches the service through `this`, typed as the part of + * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands + * it the host the class's static block builds once per service, whose methods call + * the service at call time and whose fields are getters (and a setter for a + * field a body assigns). A body that reads nothing of the service is called + * without one. `index.ts` re-exports nothing from this module. + */ + +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { + type KnowledgeSourceEntry, + type KnowledgeSourceHolder, + codedError, + packageIdOfItem, + parseKnowledgeSource, +} from './knowledge-source-registry.js'; +import { + type KnowledgeHeldReading, + type KnowledgeSourceDescription, + UNMOUNTED_ADAPTER_CODE, + describeEntry, + describeName, + errorText, + noAdapterMountedError, + operatorText, + unmountedAdapterError, + unplacedSourceError, +} from './knowledge-service-top-level.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; + +export class KnowledgeSourcesFacet { + static settleEnablement( + this: Pick, + held: KnowledgeHeldReading | undefined, + ): void { + this.enablementPending = false; + this.held = held; + if (!held) return; + for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); + } + + static registerAdapter( + this: Pick, + id: string, + adapter: IKnowledgeAdapter, + ): void { + this.adapters.set(id, adapter); + this.options.logger?.info?.(`[knowledge] adapter registered: ${id}`); + } + + static getAdapter(this: Pick, id: string): IKnowledgeAdapter { + const adapter = this.adapters.get(id); + if (!adapter) throw unmountedAdapterError(id, this.listAdapters()); + return adapter; + } + + static adapterIdFor( + this: Pick, + source: KnowledgeSource, + ): string { + if (source.adapter !== undefined) return source.adapter; + const deployment = this.options.deploymentAdapter; + if (deployment !== undefined && this.adapters.has(deployment)) return deployment; + const registered = this.listAdapters(); + if (registered.length === 1) return registered[0]!; + if (registered.length === 0) throw noAdapterMountedError(this.label(source), deployment); + throw unplacedSourceError(this.label(source), registered); + } + + static boundAdapterId(this: Pick, source: KnowledgeSource): string | undefined { + try { + return this.adapterIdFor(source); + } catch { + return undefined; + } + } + + /** + * Refuse, at registration, a source that names no adapter where the answer + * cannot become one: several adapters are registered and the runtime marked + * none the deployment's (ADR-0161 K4 ◆). With a mark, or with one adapter + * or none registered yet, the source is taken and placed where it is used: + * a store registers in its own `start()`, after a source registered at + * `init()`, so "none yet" is no verdict (AGENTS.md, startup registry reads). + */ + static refuseUnplacedSource( + this: Pick, + source: KnowledgeSource, + door: string, + ): void { + if (source.adapter !== undefined || this.options.deploymentAdapter !== undefined) return; + const registered = this.listAdapters(); + if (registered.length < 2) return; + throw unplacedSourceError(source.name, registered, ` ${door} did not register it.`); + } + + static reportUnmountedAdapters( + this: Pick, + ): string[] { + const mounted = this.listAdapters(); + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.adapter === undefined) { + // [ADR-0161 K4 ◆] A source that names no adapter, which this boot + // cannot place: no adapter at all, or several and none the deployment's. + try { + this.adapterIdFor(source); + } catch (err) { + this.options.logger?.error?.(`${errorText(err)} Indexing and searching it answer that refusal.`); + named.push(id); + } + continue; + } + if (this.adapters.has(source.adapter)) continue; + this.options.logger?.error?.( + `[knowledge] source '${id}' names adapter '${source.adapter}', which is not mounted ` + + `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). Indexing and searching it answer ` + + `${UNMOUNTED_ADAPTER_CODE} until its adapter is one of those, or the '${source.adapter}' store is mounted.`, + ); + named.push(id); + } + return named; + } + + static listAdapters(this: Pick): string[] { + return [...this.adapters.keys()]; + } + + static registerSource( + this: Pick< + KnowledgeServiceHost, + 'adapterLabel' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, + source: KnowledgeSource, + ): void { + const parsed = parseKnowledgeSource(source); + if (!parsed.ok) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, + ); + } + this.refuseUnplacedSource(parsed.source, 'registerSource'); + const packageId = packageIdOfItem(parsed.source); + if (packageId !== undefined) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused source '${parsed.source.name}': it names package "${packageId}" ` + + '(`_packageId`), and a source registered in code belongs to no package. Ship the source in that ' + + "package's `knowledgeSources` collection, or drop the key.", + ); + } + const { entry, replaced } = this.registry.register(parsed.source, 'code'); + if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); + this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${this.adapterLabel(entry.authored)})`); + this.sourcesChanged(); + } + + static registerMetadataSource( + this: Pick< + KnowledgeServiceHost, + 'adapterLabel' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, + source: KnowledgeSource, + holder: KnowledgeSourceHolder = {}, + ): KnowledgeSourceEntry { + this.refuseUnplacedSource(source, 'The knowledge_source loader'); + const { entry, replaced } = this.registry.register(source, 'metadata', holder); + this.options.logger?.info?.( + `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + + `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, + ); + this.sourcesChanged(); + return entry; + } + + static metadataSources(this: Pick): KnowledgeSourceEntry[] { + return this.registry.entries().filter((entry) => entry.door === 'metadata'); + } + + static onSourcesChanged(this: Pick, listener: () => void): () => void { + this.sourceListeners.add(listener); + return () => { + this.sourceListeners.delete(listener); + }; + } + + static sourcesChanged(this: Pick): void { + for (const listener of [...this.sourceListeners]) { + try { + listener(); + } catch (err) { + this.options.logger?.warn?.(`[knowledge] a source-change listener failed (${errorText(err)}).`); + } + } + } + + static unregisterSource(this: Pick, sourceId: string): void { + const entry = this.registry.resolve(sourceId); + if (!entry) return; + if (entry.door === 'metadata') { + throw codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] source '${entry.face}' is a knowledge_source metadata item, so unregisterSource does not remove ` + + 'it: delete the item (Studio, the metadata API, or its package), and the knowledge service unregisters it ' + + 'and drops its index.', + ); + } + this.forget(entry); + } + + static async dropMetadataSource( + this: Pick< + KnowledgeServiceHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'forget' | 'held' | 'options' | 'registry' | + 'syncStateWriteFailed' + >, + key: string, + ): Promise { + const entry = this.registry.byIndexKey(key); + if (!entry || entry.door !== 'metadata') return undefined; + // Placed before the entry is forgotten: an unnamed adapter is placed + // among the adapters registered now, as every other use places it. + const adapterId = this.boundAdapterId(entry.handed); + this.forget(entry); + // The source's sync-state row goes with it (whatever its index does). + const store = this.options.syncState; + if (store) { + try { + await store.remove(entry.key); + } catch (err) { + this.syncStateWriteFailed(`the sync-state row of removed source '${entry.face}' could not be removed`, err); + } + } + const kept = (why: string): void => { + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + + `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, + ); + }; + if (this.held) { + kept('the knowledge service is not enabled at this boot, so no store is called.'); + return entry; + } + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (!adapter) { + kept( + adapterId === undefined + ? 'it names no adapter, and none could be placed for it.' + : `adapter '${adapterId}' is not mounted.`, + ); + return entry; + } + if (typeof adapter.dropSource !== 'function') { + kept(`adapter '${adapterId}' has no dropSource.`); + return entry; + } + try { + await adapter.dropSource({ source: entry.handed, reason: 'manual' }); + this.options.logger?.info?.(`[knowledge] source '${entry.face}' was removed and its index dropped.`); + } catch (err) { + kept(`dropSource failed (${operatorText(err)}).`); + } + return entry; + } + + /** Remove `entry` and what this node remembers of it. */ + static forget( + this: Pick< + KnowledgeServiceHost, + 'builds' | 'cancelPendingReconcile' | 'reconcileUnlistedReported' | 'registry' | 'sourcesChanged' | + 'syncStateRecorded' | 'whereUnenforceableReported' + >, + entry: KnowledgeSourceEntry, + ): void { + this.registry.remove(entry.key); + this.builds.delete(entry.key); + this.syncStateRecorded.delete(entry.key); + this.whereUnenforceableReported.delete(entry.key); + this.reconcileUnlistedReported.delete(entry.key); + this.cancelPendingReconcile(entry.key); + this.sourcesChanged(); + } + + static listSources(this: Pick): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.authored); + } + + static describeSources(this: Pick): KnowledgeSourceDescription[] { + return this.registry.entries().map(describeEntry); + } + + static getSource(this: Pick, sourceId: string): KnowledgeSource | undefined { + return this.registry.resolve(sourceId)?.authored; + } + + static describeSource( + this: Pick, + sourceId: string, + ): KnowledgeSourceDescription | undefined { + const entry = this.registry.resolve(sourceId); + return entry ? describeEntry(entry) : undefined; + } + + /** The handed source held under an index key. */ + static handed(this: Pick, key: string): KnowledgeSource | undefined { + return this.registry.byIndexKey(key)?.handed; + } + + static handedSources(this: Pick): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.handed); + } + + /** How a log line names a source's adapter: the one it names, else the one it is placed on now. */ + static adapterLabel(this: Pick, source: KnowledgeSource): string { + if (source.adapter !== undefined) return source.adapter; + const placed = this.boundAdapterId(source); + return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; + } + + static faceOfKey(this: Pick, key: string): string { + return this.registry.byIndexKey(key)?.face ?? key; + } + + /** + * The registered source `sourceId` names, read by the one rule + * (`KnowledgeSourceRegistry.resolve`): its face, else a bare name by + * ADR-0150 D3. Throws for a name no source has, listing the registered + * faces, and `409 RESOURCE_CONFLICT` for one that names several. + */ + static requireEntry(this: Pick, sourceId: string): KnowledgeSourceEntry { + const entry = this.registry.resolve(sourceId); + if (!entry) { + throw new Error( + `[knowledge] unknown source '${sourceId}'. Registered: [${this.registry.entries().map((e) => e.face).join(', ')}]`, + ); + } + return entry; + } +} diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts new file mode 100644 index 00000000000..2570c097777 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -0,0 +1,1066 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38660] The top-level declarations of `knowledge-service.ts` other than the + * class: the options, logger and held-reading shapes the service is built with, + * and the helpers, constants, refusal texts and record-to-document assembly its + * bodies use. Moved here whole, in their order, not edited, so the facets + * (`knowledge-service-*.ts`) import them without importing the class module. + * `knowledge-service.ts` re-exports what it exported before, under the same + * names; a declaration a facet or the facade reads gained `export`, and none of + * them is exported from the package entry (`index.ts` is unchanged). + */ + +import { createHash } from 'node:crypto'; +import type { + AdapterContext, + AdapterIndexExpectation, + AdapterScopeTerm, + IDataEngine, + IKnowledgeAdapter, + IQueueService, +} from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; +import { type TenancyPosture, postureEnforcesWall } from '@objectstack/spec/security'; +import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; +import { documentUnitValueOf } from './knowledge-tools.js'; +import type { ResolvedSplit } from './split/index.js'; +import type { KnowledgeSourceEntry } from './knowledge-source-registry.js'; +import { type KnowledgeTenancyPostureResolver, documentOrganizationId } from './knowledge-organization-scope.js'; +import { + type KnowledgeAdmissionDeps, + type KnowledgeFieldSecurity, + declaredFields, + documentTitleField, +} from './knowledge-source-admission.js'; +import type { KnowledgeBuildLock, KnowledgeBuildRecord } from './knowledge-build.js'; +import type { KnowledgeSyncStateStore } from './knowledge-sync-state.js'; + + +/** + * Minimal logger shape; falls back to no-op when none is provided. + */ +export interface KnowledgeLogger { + info?(msg: string, ...rest: unknown[]): void; + /** + * The GUARANTEED fallback channel (#9754). `error` stays optional — hosts do + * inject reduced sinks — so `warn` is where a durability report lands when + * `error` is absent, and a fallback that may itself be missing is not a + * fallback. Call sites keep the `logger?.warn?.(…)` spelling as the backstop + * for hosts the TYPE cannot reach; `SweepLogger` in plugin-email's + * `outbox-sweep.ts` carries the full reasoning and the measurement. + */ + warn(msg: string, ...rest: unknown[]): void; + error?(msg: string, ...rest: unknown[]): void; + debug?(msg: string, ...rest: unknown[]): void; +} + +/** + * Constructor options for `KnowledgeService`. + */ +/** + * [ADR-0161 K8, the dated note on item 12] Why a knowledge service the + * runtime composed is not enabled at this boot: each half that is missing. + * At least one member is set. Read once per boot, at `kernel:bootstrapped`, + * by `KnowledgeServicePlugin`, and handed to {@link KnowledgeService.settleEnablement}. + */ +export interface KnowledgeHeldReading { + /** + * Set when no embedder is available — none registered by a plugin, and the + * saved `ai.embedder_*` settings build none: why, as operator text (the + * settings that are missing or do not build one). Never a key. + */ + readonly embedder?: string; + /** Set when the deployment's store is not mounted: the id of its adapter, which nothing registered. */ + readonly store?: string; +} + +export interface KnowledgeServiceOptions { + /** Data engine used for RLS re-checks and bulk reindex walks. Optional in tests. */ + dataEngine?: IDataEngine; + /** Optional structured logger. */ + logger?: KnowledgeLogger; + /** + * [ADR-0161 K4 ◆] The deployment's adapter: the id of the store the + * runtime mounted beside this service for the `knowledge` capability + * (`pgvector` on PostgreSQL, `turso` otherwise — `resolveCapabilityArgument` + * in `@objectstack/core` sets it on the plugin it constructs). A source + * that names no `adapter` binds to it while an adapter of that id is + * registered. Only the runtime that mounts the store sets it: an adapter + * application code registers is never the deployment's by registering + * (`registerAdapter` takes no such mark). A service option, not an + * adapter-contract member (ADR-0161 K8, "What counts as a member"). + * Omitted (a host that mounts the service itself), a source that names + * no adapter binds to the only adapter registered. + */ + deploymentAdapter?: string; + /** + * [ADR-0161 K8, the dated note on item 12] The runtime composed this + * service, so it is enabled by configuration: until the boot's reading + * settles it ({@link KnowledgeService.settleEnablement}), the service hands + * out no tool definition, and once settled it either serves or holds its + * sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed` + * option. Omitted (a host that mounts the service itself), the service + * serves from the start, as it always has. + */ + enabledByConfiguration?: boolean; + /** + * The `security` service, resolved at search time, for the field gate + * (`knowledge-source-admission.ts`). Answers `undefined` when the host + * registers none: the contract's fallback then applies (every field + * declaring a `maskingRule` is not queryable). `KnowledgeServicePlugin` + * always wires it; omitted, the service reads as a host with no security + * service. + */ + resolveSecurity?: () => KnowledgeFieldSecurity | undefined; + /** + * The settings page's `knowledge.chunk_target`, read each time the service + * splits a batch of documents — never once at boot, so a value saved later + * applies to the next write. Answers `undefined` when nothing is stored or + * no settings service serves the namespace; the splitter then uses a + * source's own `split.maxChars`, else 800. A rejection is reported at `warn` + * and read as `undefined`. `KnowledgeServicePlugin` wires it to the + * `settings` service. + */ + resolveChunkTarget?: () => Promise; + /** + * The deployment's effective tenancy posture (ADR-0105 D1), read at each + * assembly and each search (ADR-0161 K8, item 9): under `group` and + * `isolated` a document assembled from a record carries the record's + * organization, and a search hands the adapter the caller's organizations + * (`knowledge-organization-scope.ts`). Answers `undefined` where no + * `tenancy` service is composed, and throws where one is registered but + * cannot be read. `KnowledgeServicePlugin` always wires it; omitted, the + * service reads as a `single`-posture deployment. + */ + resolveTenancyPosture?: KnowledgeTenancyPostureResolver; + /** + * The cluster lock a build runs under (`knowledge-build.ts`, "One node + * builds a source"), resolved each time a build starts. Answers `undefined` + * where no cluster service is composed: the composition is one node and the + * build runs without a lease. `KnowledgeServicePlugin` wires it to the + * `cluster` service's `lock`. + */ + resolveBuildLock?: () => KnowledgeBuildLock | undefined; + /** + * Each source's durable sync state (`knowledge-sync-state.ts`, + * `sys_knowledge_sync_state`): the last build and the record syncs that + * failed, one row per source, the same on every node. `index_status` + * answers from it. `KnowledgeServicePlugin` wires it wherever the object is + * registered and a data engine is bound. Omitted, the service keeps only + * this node's last build in memory, and `index_status` answers that. + */ + syncState?: KnowledgeSyncStateStore; + /** + * Default top-K when callers don't specify. The adapter may cap + * further; the service does not enforce an upper bound itself. + * @default 10 + */ + defaultTopK?: number; +} + +// ── Helpers ───────────────────────────────────────────────────────── + +/** A registered source with how a caller names it (`KnowledgeService.describeSources`). */ +export interface KnowledgeSourceDescription { + /** The source's face: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ + id: string; + /** The source as its author wrote it. */ + source: KnowledgeSource; + /** The package that holds it; absent for a source no package holds. */ + packageId?: string; + /** Which door it arrived through: a registration in code, or a `knowledge_source` metadata item. */ + door: KnowledgeSourceEntry['door']; +} + +export function describeEntry(entry: KnowledgeSourceEntry): KnowledgeSourceDescription { + return { + id: entry.face, + source: entry.authored, + ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), + door: entry.door, + }; +} + +/** ` 'NAME'` for a refusal about an input that carries a usable name (or its retired `id`), else nothing. */ +/** + * The door that asks {@link KnowledgeService.admitAuthoredSource}: `save` for + * a door that saves one item, `duplicate` for the package duplicate. + */ +type AuthoredSourceDoor = 'save' | 'duplicate'; + +/** + * What each door's caller is told: the source not done, the act that carries + * the identity, the retry after a verdict that could not be judged, the redo + * after a fix, and the act someone who may query the field performs. The + * `save` row is the save door's wording, unchanged. + */ +export const AUTHORED_SOURCE_DOOR_WORDING: Readonly< + Record +> = { + save: { + notDone: 'was not saved', + act: 'the save', + tryAgain: ' Nothing was written; try again.', + again: 'save it again', + thenAgain: '', + byWhoMay: 'save the source', + }, + duplicate: { + notDone: 'cannot be copied', + act: 'the duplicate', + tryAgain: ' Duplicate the package again.', + again: 'duplicate the package again', + thenAgain: ', then duplicate the package again', + byWhoMay: 'duplicate the package', + }, +}; + +/** The `os validate` rule ids the save door's "does not exist" arm reports (`@objectstack/lint`, `validate-knowledge-source.ts`). */ +export const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN = 'knowledge-source-object-unknown'; +export const KNOWLEDGE_SOURCE_FIELD_UNKNOWN = 'knowledge-source-field-unknown'; + +/** A saved source's reference to nothing: its object, or a member naming no field of it. */ +export type AbsentSourceReference = + | { kind: 'object' } + | { kind: 'field'; field: string; key: 'content' | 'contentFields' | 'metadataFields' }; + +/** + * [ADR-0161 K4, row 4] What a saved source names that does not exist, judged + * as `os validate` judges it (`knowledge-source-object-unknown`, + * `knowledge-source-field-unknown`): its `source.object` is no object the + * registry defines, or a `content` / `contentFields` / `metadataFields` + * member is neither a field the object declares nor `id` or a system column + * the registry injects on it (`resolveInjectedSystemColumns`). The fields a + * `where` reads are not judged here (the CLI rule does not judge them either). + * + * Decided from the object's registered DEFINITION alone, never from a + * permission answer: every door that asks this verdict admits only a + * `manage_metadata` holder, who is served every object definition whole on + * the metadata plane (ADR-0106 D4), so the verdict tells the author nothing + * they could not read. An object or a field that exists is never reported + * here, so every permission answer about it is the one it was. + * + * No verdict where none can be drawn: an engine with no schema registry (no + * registry is not no object), an object of a disabled package (that gate + * answers it, its definition may be withheld), and an object whose fields + * cannot be enumerated. Throws when a lookup throws; the caller refuses `503`. + */ +export function absentSourceReference( + objSource: ObjectKnowledgeSource, + listed: { content?: unknown; contentFields?: unknown; metadataFields?: unknown }, + engine: IDataEngine, + deps: KnowledgeAdmissionDeps, +): AbsentSourceReference | undefined { + if (typeof (engine as { getSchema?: unknown }).getSchema !== 'function') return undefined; + const schema = deps.readSchema(objSource.object); + if (deps.isObjectPackageDisabled(objSource.object) === true) return undefined; + if (schema === undefined || schema === null) return { kind: 'object' }; + const declared = declaredFields(schema); + if (!declared) return undefined; + const known = new Set([...declared.map(([name]) => name), ...resolveInjectedSystemColumns(schema).names]); + for (const key of ['content', 'contentFields', 'metadataFields'] as const) { + const members = listed[key]; + if (!Array.isArray(members)) continue; + for (const member of members) { + if (typeof member === 'string' && member !== '' && !known.has(member)) return { kind: 'field', field: member, key }; + } + } + return undefined; +} + +export function describeName(input: unknown): string { + const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown }; + const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined; + return shown === undefined ? '' : ` ${quotedName(shown)}`; +} + +/** + * A source that refused a search (ADR-0161 K7, rule 5): its adapter answered + * an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds + * another fingerprint than the one the search carried. + */ +export interface KnowledgeSearchRefusal { + sourceId: string; + /** The adapter's error code. */ + code: string; + /** The adapter's HTTP-shaped status. */ + status: number; + /** The adapter's message, which says what to do. */ + message: string; +} + +/** What {@link KnowledgeService.searchWithRefusals} answers. */ +export interface KnowledgeSearchReport { + /** The hits of the sources that answered, as {@link KnowledgeService.search} returns them. */ + hits: KnowledgeHit[]; + /** The sources that refused, each with its code; empty when none did. */ + refused: KnowledgeSearchRefusal[]; +} + +/** + * One source a search round asks: its organizations scope, the fingerprint its + * search carries, and the record scope's terms for it (ADR-0161 K8, item 17). + */ +/** A source {@link KnowledgeService.admitSources} admitted for a caller. */ +export interface AdmittedSource { + source: KnowledgeSource; + organizationIds?: string[]; + /** Searched only once its index is proven built under the current recipe (`mayServeEarlierRuleTitle`). */ + proveIndex?: true; +} + +/** What ends a refusal for want of a proof ({@link KnowledgeService.unprovenIndex}). */ +export type UnprovenEnd = 'rebuild' | 'never' | 'unreadable'; + +/** The second sentence of the caller's refusal, by what ends it. */ +export const UNPROVEN_CALLER_TEXT: Readonly> = { + rebuild: 'It answers again once a complete rebuild of the source has completed.', + never: 'No rebuild changes that for this source; an administrator can say why.', + unreadable: 'What its index holds could not be read; it is asked again on the next search.', +}; + +/** The last sentence of the operator's `warn` line, by what ends the refusal. */ +export const UNPROVEN_OPERATOR_TEXT: Readonly> = { + rebuild: + 'The boot pass, a source reload or the reconcile builds it where they run; os knowledge rebuild builds it now.', + never: + 'No rebuild can prove it for this source as it is configured, so nothing is rebuilt for it; it stays refused to ' + + 'every caller but the system context.', + unreadable: 'It is asked again on the next search.', +}; + +/** + * The code of a source refused because its index is not proven built under + * the current recipe: the one a generation-keeping adapter answers for an + * index built under another fingerprint, as the remedy is the same rebuild. + */ +export const INDEX_NOT_PROVEN_CODE = 'KNOWLEDGE_REBUILD_REQUIRED'; + +export interface SearchTarget { + source: KnowledgeSource; + /** + * The adapter the source binds to, resolved once per search + * ({@link KnowledgeService.planSearches}), or the coded refusal its + * resolution answered (`undefined`: an uncoded failure, skipped unsearched). + */ + binding: { adapterId: string; adapter: IKnowledgeAdapter } | { refusal: Omit | undefined }; + organizationIds?: string[]; + fingerprint?: string; + scope?: AdapterScopeTerm[]; + /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ + verifyHits?: true; +} + +/** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ +/** The code an index or search of a source whose adapter is not mounted answers. */ +export const UNMOUNTED_ADAPTER_CODE = 'SERVICE_UNAVAILABLE'; + +/** + * The refusal of a source whose adapter is not mounted: ADR-0112 + * `SERVICE_UNAVAILABLE` (503), naming the adapter and the ones that are. + */ +export function unmountedAdapterError(id: string, mounted: readonly string[]): Error { + return Object.assign( + new Error( + `[knowledge] adapter '${id}' is not mounted (mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). ` + + `Name one of those as the source's adapter, or mount the '${id}' store.`, + ), + { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, + ); +} + +/** + * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where no + * adapter is registered: ADR-0112 `SERVICE_UNAVAILABLE` (503), as for a named + * adapter that is not mounted. Names the deployment's store when the runtime + * marked one. + */ +export function noAdapterMountedError(source: string, deployment: string | undefined): Error { + return Object.assign( + new Error( + `[knowledge] source '${source}' names no adapter, and no adapter is mounted` + + `${deployment === undefined ? '' : ` (the deployment's store '${deployment}' is not mounted)`}. ` + + "Mount a knowledge store — `requires: ['knowledge']` mounts the deployment's — or name the source's adapter.", + ), + { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, + ); +} + +/** + * [ADR-0161 K8, the dated note on item 12] The refusal of a search, a build or + * a reindex while the service is not enabled: ADR-0112 `SERVICE_UNAVAILABLE` + * (503), naming each half that is missing and its remedy, as the refusal of + * an author's save names them. + */ +export function heldSourcesError(reading: KnowledgeHeldReading): Error { + return Object.assign(new Error(heldSourcesText(reading)), { code: UNMOUNTED_ADAPTER_CODE, status: 503 }); +} + +/** The sentence {@link heldSourcesError} answers, and the boot line names the same halves with. */ +export function heldSourcesText(reading: KnowledgeHeldReading): string { + const missing: string[] = []; + const remedy: string[] = []; + if (reading.embedder !== undefined) { + missing.push(`no embedder is configured (${reading.embedder})`); + remedy.push('save an embedder provider'); + } + if (reading.store !== undefined) { + missing.push(`the deployment's knowledge store '${reading.store}' is not mounted, for the reason the boot's log names`); + remedy.push("mount the deployment's knowledge store"); + } + return ( + `[knowledge] the knowledge service is not enabled on this deployment: ${missing.join(', and ')}. ` + + `Its sources are held: none is built, synced or searched. To enable it, ${remedy.join(' and ')}, then restart.` + ); +} + +/** + * [ADR-0161 K8, the dated note on item 12, point 4] Why an author's save of a + * `knowledge_source` is refused while the service is not enabled, after the + * source's subject: each half that is missing, and the ruled remedy for it — + * "save an embedder provider, restart, then save" with no embedder, "mount the + * deployment's knowledge store, restart, then save" where the store is not + * mounted (whose reason the boot's log names), both when both are missing. + * The embedder half carries its cause (a provider saved without its key, for + * example) in parentheses, beside the ruled words. + */ +export function heldSourceSaveText(reading: KnowledgeHeldReading): string { + const missing: string[] = []; + const remedy: string[] = []; + if (reading.embedder !== undefined) { + missing.push(`no embedder is configured (${reading.embedder})`); + remedy.push('save an embedder provider'); + } + if (reading.store !== undefined) { + missing.push(`the deployment's knowledge store '${reading.store}' is not mounted, for the reason the boot's log names`); + remedy.push("mount the deployment's knowledge store"); + } + return ( + `the knowledge service is not enabled on this deployment: ${missing.join(', and ')}. A source saved now would be ` + + `held, never built, synced or searched. To have it served, ${remedy.join(' and ')}, restart, then save the source. ` + + 'Nothing was written.' + ); +} + +/** + * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where several + * are registered and none is the deployment's: ADR-0112 `VALIDATION_ERROR` + * (400), naming the choices. The source must say which store holds it. + */ +export function unplacedSourceError(source: string, registered: readonly string[], tail = ''): Error { + return Object.assign(new Error(`[knowledge] source '${source}' ${unplacedSourceText(registered)}${tail}`), { + code: 'VALIDATION_ERROR', + status: 400, + }); +} + +/** Why a source that names no adapter cannot be placed among `registered`, and what to write. */ +export function unplacedSourceText(registered: readonly string[]): string { + return ( + `names no adapter, and ${registered.length} adapters are registered (${registered.join(', ')}) with none the ` + + "deployment's store, so which one holds its index cannot be told. Name one of " + + `${registered.map((id) => `'${id}'`).join(', ')} as the source's \`adapter\`.` + ); +} + +export function codedRefusalOf(err: unknown): Omit | undefined { + if (err === null || typeof err !== 'object') return undefined; + const { code, status } = err as { code?: unknown; status?: unknown }; + if (typeof code !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(code)) return undefined; + if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599) return undefined; + return { code, status, message: errorText(err) }; +} + +/** + * The refusal of a search no source could answer (ADR-0161 K7, rule 5): the + * first refusal's code and status — the one every refusal shares, when they + * share one — and a message naming each refused source with its code. The + * thrown error carries `refused`. + */ +export function wholeRefusal(refused: KnowledgeSearchRefusal[]): Error { + const [first] = refused; + const message = + `[knowledge] no source could be searched: ` + + refused.map((r) => `source '${r.sourceId}' refused (${r.code}): ${r.message}`).join('; '); + return Object.assign(new Error(message), { code: first.code, status: first.status, refused: [...refused] }); +} + +/** What {@link KnowledgeService.planIndex} resolves for one call against one source's adapter. */ +export interface IndexPlan { + source: KnowledgeSource; + adapter: IKnowledgeAdapter; + /** The split applied for an adapter that takes chunks; absent for one that does not. */ + split?: ResolvedSplit; + /** The fingerprint and recipe hash every adapter call carries. */ + index: AdapterIndexExpectation; + /** The adapter context of a call made for `reason`, carrying `index`. */ + context(reason: NonNullable): AdapterContext; +} + +/** One build's durable writes ({@link KnowledgeService.rebuildOf}): its id once its start is recorded, and their chain. */ +export interface DurableBuild { + buildId?: string; + chain: Promise; +} + +/** + * The part of the `queue` service the sync state reads while record syncs + * run through it: the pending count, and the dead letters a completed + * reconcile repairs (`IQueueService`). + */ +export type KnowledgeRecordSyncQueueView = Pick; + +/** The most dead letters a reconcile reads when it clears a source's repaired failures. */ +export const DEAD_LETTER_SCAN_MAX = 100_000; + +/** A copy of a build record, so a caller never holds the live one. */ +export function cloneBuildRecord(record: KnowledgeBuildRecord): KnowledgeBuildRecord { + return { ...record, progress: { ...record.progress } }; +} + +/** + * Rows one reindex page reads, and so the most documents one reindex `upsert` + * carries. A memory and request-size bound for the walk, not an embedder + * limit: an embedder that caps inputs per request splits a larger upsert into + * several requests itself (`OpenAIEmbedder` does). + */ +export const REINDEX_PAGE_SIZE = 100; + +/** + * The most documents one reindex result names in `failures`; `failed` counts + * them all. A source whose every document fails its split (a `whole` source + * over a small model's limit) answers a bounded result, not one entry per row. + */ +export const MAX_REINDEX_FAILURES = 20; + +/** + * Run `task` after every earlier task chained on the same `key` has settled — + * an in-process promise chain per key, dropped from `tails` once idle. + * Answers `task`'s own outcome (rejection included); the chain itself never + * rejects, so a failed task does not break the tasks queued behind it. + */ +export function chainAfter( + tails: Map>, + key: string, + task: () => Promise, +): Promise { + const previous = tails.get(key) ?? Promise.resolve(); + const outcome = previous.then(task); + const tail: Promise = outcome.then(() => undefined, () => undefined).finally(() => { + if (tails.get(key) === tail) tails.delete(key); + }); + tails.set(key, tail); + return outcome; +} + +/** + * [#38413] {@link chainAfter} over several keys at once: run `task` after + * every earlier task chained on any of `keys` has settled, and hold each of + * them until `task` settles. A record-sync batch holds the chain of every + * document it writes. + */ +export function chainAfterAll( + tails: Map>, + keys: readonly string[], + task: () => Promise, +): Promise { + const previous = Promise.all(keys.map((key) => tails.get(key) ?? Promise.resolve())); + const outcome = previous.then(task); + const settled = outcome.then(() => undefined, () => undefined); + for (const key of new Set(keys)) { + const tail: Promise = settled.finally(() => { + if (tails.get(key) === tail) tails.delete(key); + }); + tails.set(key, tail); + } + return outcome; +} + +/** [#38413] One group of a record-sync batch: the messages of one source over one object. */ +export interface RecordSyncGroup { + source: KnowledgeSource; + object: string; + engine: IDataEngine; + items: Array<{ index: number; recordId: string; publishedAt?: number }>; +} + +/** + * The sources whose per-record projection of `object` is kept in step + * with row changes — i.e. those the service may upsert into, delete from, or + * (since #4672) de-index on behalf of, in reaction to a row's lifecycle. + * + * One definition, deliberately: the event-sync path + * (`handleRecordUpsert` / `handleRecordDelete`) and the lifecycle reap guard + * (`knowledge-reap-guard.ts`) are the two halves of one responsibility, and a + * second copy of this predicate is exactly how they would drift into disagreeing + * about which sources a row's disappearance concerns. + * + * `refresh.onRecordChange: false` opts a source out of both halves: it declares + * that an external indexer owns the index, and the reap guard vetoes rows whose + * de-index fails — so honouring it here is also what keeps an opted-out source + * from ever holding up another package's retention. + */ +export function objectSourcesFor(sources: KnowledgeSource[], object: string): KnowledgeSource[] { + return sources.filter( + (source) => + source.source.object === object && + (source.refresh?.onRecordChange ?? true) !== false, + ); +} + +/** + * The RLS-bypassing system context of the service's own reads: the reindex + * walk, the event sync's re-read and the purge's, which decide index + * MEMBERSHIP (`where`), never what a caller may read — search re-checks every + * hit as the caller. + */ +export function systemContext(): ExecutionContext { + return { positions: [], permissions: [], systemPermissions: [], isSystem: true }; +} + +/** + * THE membership re-read: the row `recordId` names, read under the system + * context and the source's `where` — `find(object, { where: where AND id, + * limit: 1 })` — so the database answers whether the row belongs in the + * index, never an event payload or an earlier read. `undefined` when no row + * matches (none exists, or it does not match `where`). Throws what `find` + * throws, and throws when `find` answers no list: "no row" is a verdict the + * purge deletes on, so a malformed answer is never read as one. + * + * One definition for both of its readers, the event sync + * ({@link KnowledgeService.handleRecordUpsert}) and the purge + * ({@link purgeDocuments}): they decide the same question, and a second copy + * is how they would drift into answering it differently. + */ +export async function rereadRow( + engine: IDataEngine, + objSource: ObjectKnowledgeSource, + recordId: string | number, +): Promise | undefined> { + const byId = { id: recordId }; + const rows = await engine.find( + objSource.object, + { where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, limit: 1 }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) { + throw new Error(`the re-read of record '${String(recordId)}' answered ${describeValue(rows)} instead of a list of rows`); + } + return rows[0] as Record | undefined; +} + +/** + * [#38413] {@link rereadRow} for many records in one read: + * `find(object, { where: where AND id in ids, limit: ids.length })` under the + * system context. An id no row came back for does not match (none exists, or + * it does not match `where`). Throws what `find` throws, and throws when + * `find` answers no list. + */ +export async function rereadRows( + engine: IDataEngine, + objSource: ObjectKnowledgeSource, + recordIds: readonly string[], +): Promise>> { + const byIds = { id: { $in: [...recordIds] } }; + const rows = await engine.find( + objSource.object, + { where: objSource.where !== undefined ? { $and: [objSource.where, byIds] } : byIds, limit: recordIds.length }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) { + throw new Error(`the re-read of ${recordIds.length} records answered ${describeValue(rows)} instead of a list of rows`); + } + return rows as Array>; +} + +/** + * Entries one `listDocuments` call asks for. A memory bound per call, not a + * contract limit: the adapter may answer fewer. + */ +export const LIST_DOCUMENTS_PAGE_SIZE = 500; + +/** + * How many times `topK` a search asks each source for in its first + * round, when the permission re-check can remove hits ({@link + * KnowledgeService.search}). + */ +export const SEARCH_FIRST_ROUND_FACTOR = 5; + +/** + * How many times `topK` the one refill round asks a source for, when the + * survivors of the re-check name fewer than `topK` records — the cap on what a + * search reads: a caller who may read fewer than `topK` of the rows within the + * cap gets fewer than `topK` hits. + */ +export const SEARCH_REFILL_FACTOR = 20; + +/** + * How many times a record-level search re-runs the freshness check when hits + * it was about to answer turned out stale and others moved up + * ({@link KnowledgeService.search}). A hit still unchecked after the last + * round is not answered. + */ +export const SEARCH_FRESHNESS_ROUNDS = 3; + +/** What {@link listAdapterDocuments} learned: every listed id → its stored hash, or why there is no listing. */ +type AdapterListing = + | { ok: true; documents: Map } + /** `reason` is absent when the adapter has no `listDocuments`; present when the listing failed. */ + | { ok: false; reason?: string }; + +/** + * Read every page of the adapter's `listDocuments` for `source`. Never throws: + * an adapter without the method answers `{ ok: false }` with no reason, and a + * listing that throws or answers a malformed page or a cursor it already gave + * (a listing that would never end) answers `{ ok: false, reason }`. + */ +export async function listAdapterDocuments( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + index: AdapterIndexExpectation, +): Promise { + if (typeof adapter.listDocuments !== 'function') return { ok: false }; + const documents = new Map(); + const cursors = new Set(); + let cursor: string | undefined; + try { + for (;;) { + const page = await adapter.listDocuments( + { source, reason: 'reindex', index }, + cursor === undefined ? { limit: LIST_DOCUMENTS_PAGE_SIZE } : { cursor, limit: LIST_DOCUMENTS_PAGE_SIZE }, + ); + if (!page || !Array.isArray(page.documents)) return { ok: false, reason: 'a page carried no documents list' }; + for (const entry of page.documents) { + if (typeof entry?.documentId !== 'string') return { ok: false, reason: 'an entry carried no documentId' }; + documents.set(entry.documentId, typeof entry.docHash === 'string' ? entry.docHash : undefined); + } + if (page.nextCursor === undefined) return { ok: true, documents }; + if (cursors.has(page.nextCursor)) { + return { ok: false, reason: `the cursor '${page.nextCursor}' came back twice, so the listing would never end` }; + } + cursors.add(page.nextCursor); + cursor = page.nextCursor; + } + } catch (err) { + return { ok: false, reason: operatorText(err) }; + } +} + +/** Input of {@link purgeDocuments}. */ +export interface PurgeDocumentsInput { + source: KnowledgeSource; + objSource: ObjectKnowledgeSource; + adapter: IKnowledgeAdapter; + engine: IDataEngine; + /** Document ids believed stale: listed by the adapter, not produced from a current row. */ + candidates: Iterable; + /** + * Runs one candidate's confirm-and-delete after every earlier sync of that + * document has finished, answering the task's own outcome — the service + * passes its per-document record-sync chain, so an event sync of the same + * row can never land between the purge's re-read and its delete. + */ + serialize: (documentId: string, task: () => Promise) => Promise; + /** Diagnostics tag on the adapter's `delete`. @default 'reindex' */ + reason?: string; + /** The fingerprint and recipe hash the adapter's `delete` carries (ADR-0161 K8, item 8 a). */ + index?: AdapterIndexExpectation; +} + +/** Outcome of {@link purgeDocuments}. */ +export interface PurgeDocumentsOutcome { + /** Candidates deleted. */ + purged: number; + /** Candidates whose row the re-read found: kept. */ + kept: number; + /** Candidates whose id this source does not derive from a record id: kept, nothing can confirm them. */ + foreign: number; + /** Why the purge stopped early (a re-read or a delete that threw); absent when it went through every candidate. */ + failure?: string; +} + +/** + * The index purge (ADR-0161 K8, item 1): delete the candidates whose row is + * gone. Each candidate is confirmed by {@link rereadRow} — the event sync's + * own re-read, `where` AND id under the system context — and deleted only + * when that finds no row, so a document whose row was created, restored or + * came back into `where` since the candidates were computed is kept. Stops at + * the first re-read or delete that throws (a re-read that answers no list + * included), counting what it did before. + * + * Record ids are text. The knowledge service treats a record id as text: the + * record id is recovered from the document id as text, and the re-read asks + * for that text. A caller-supplied NUMERIC record id on driver-memory or + * driver-mongodb, which keep the id as given and do not equate `'5'` with + * `5`, is not supported. The re-read does not find such a row, so if its + * document is a candidate while the row exists (it was restored, or came back + * into `where`, after the walk read past it), the document is deleted; the row + * is untouched, and its document returns at the row's next event or the next + * complete reindex. Ids the platform mints are text on every driver. Asking + * again by the number is not done: on driver-sql the number is bound against + * the text `id` column, which MySQL compares numerically (`'05'` matches `5`) + * and SQL Server and Oracle reject outright, and the object schema does not + * say which ids are numeric. + * + * The caller decides when a purge may run at all (a complete reindex walk, + * which is also what the reconcile runs) and computes the candidates. + */ +export async function purgeDocuments(input: PurgeDocumentsInput): Promise { + const { source, objSource, adapter, engine } = input; + const prefix = `${source.name}:`; + const outcome: PurgeDocumentsOutcome = { purged: 0, kept: 0, foreign: 0 }; + for (const documentId of input.candidates) { + const recordId = documentId.startsWith(prefix) ? documentId.slice(prefix.length) : ''; + if (recordId === '') { + outcome.foreign++; + continue; + } + try { + const deleted = await input.serialize(documentId, async () => { + if (await rereadRow(engine, objSource, recordId)) return false; + await adapter.delete([documentId], { + source, + reason: input.reason ?? 'reindex', + ...(input.index === undefined ? {} : { index: input.index }), + }); + return true; + }); + if (deleted) outcome.purged++; + else outcome.kept++; + } catch (err) { + outcome.failure = `document '${documentId}': ${operatorText(err)}`; + return outcome; + } + } + return outcome; +} + +/** + * The version of the {@link computeDocHash} recipe, the hash's prefix. Bump it + * when what the hash covers or how it serializes changes: every stored hash + * then reads as changed, and the next complete reindex writes every document + * once. + * + * Not bumped for `organizationId` (ADR-0161 K8, item 9): the organization + * enters the hashed body only when the document carries one, so a document + * without one hashes as it did before, and only the documents that gained an + * organization read as changed — exactly the ones a complete reindex must + * write again for a walled search to rank them. + */ +export const DOC_HASH_VERSION = 'v1'; + +/** + * A document's `docHash` (ADR-0161 K8, item 2): SHA-256 over its content, + * title and metadata — and its organization, when it carries one (item 9) — + * serialized with object keys in a stable order, behind + * the {@link DOC_HASH_VERSION} prefix. The same assembled document gives the + * same hash on every machine, whatever order its metadata keys were built in. + */ +export function computeDocHash(doc: Pick): string { + const body = stableJson({ + content: doc.content, + title: doc.title ?? null, + metadata: doc.metadata ?? {}, + ...(doc.organizationId === undefined ? {} : { organizationId: doc.organizationId }), + }); + return `${DOC_HASH_VERSION}:${createHash('sha256').update(body).digest('hex')}`; +} + +/** `JSON.stringify` with every plain object's keys sorted, and a bigint as its decimal text. */ +export function stableJson(value: unknown): string { + return JSON.stringify(value, (_key, v: unknown) => { + if (typeof v === 'bigint') return v.toString(); + if (v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype) { + const sorted: Record = {}; + for (const k of Object.keys(v as Record).sort()) sorted[k] = (v as Record)[k]; + return sorted; + } + return v; + }); +} + +/** How a non-list answer is named in a refusal: `null`, `undefined`, or its `typeof`. */ +export function describeValue(value: unknown): string { + return value === null ? 'null' : value === undefined ? 'undefined' : `a value of type ${typeof value}`; +} + +/** A thrown value's text: an `Error`'s message, anything else as a string. */ +export function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** + * An adapter error as an operator reads it: its message, then its `remedy` + * when it carries one — operator text such as the SQL to run, which an adapter + * keeps out of the message (ADR-0161 K7, rule 5). For a reindex result and the + * log; a search caller reads the message alone. + */ +export function operatorText(err: unknown): string { + const remedy = err !== null && typeof err === 'object' ? (err as { remedy?: unknown }).remedy : undefined; + return typeof remedy === 'string' && remedy !== '' ? `${errorText(err)} ${remedy}` : errorText(err); +} + +/** A record id the event sync can re-read by: a non-empty string or a finite number. */ +export function isRecordId(value: unknown): value is string | number { + return (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value)); +} + +/** + * A document's `title` (ADR-0161 K5): the value of the object's display field + * ({@link documentTitleField}), read from the record when it is non-empty text + * or a finite number. `undefined` when the field is withheld (credential-class + * or `internal`), empty, or not one of those values. Not + * `resolveRecordDisplayName`: its `Record #` floor is a UI label, not + * index content. + */ +export function documentTitle( + record: Record, + schema: unknown, + withheld: ReadonlySet, +): string | undefined { + const field = documentTitleField(schema); + if (field === undefined || withheld.has(field)) return undefined; + const value = record[field]; + if (typeof value === 'string') return value.trim().length > 0 ? value : undefined; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return undefined; +} + +/** + * How many groups `hits` name, by `groupOf` — what {@link KnowledgeService.search} + * counts toward `topK` when it decides whether to refill: several passages of + * one record (or of one `groupBy` value) count once. A hit with no group + * counts for nothing. + */ +export function distinctGroups(hits: KnowledgeHit[], groupOf: (hit: KnowledgeHit) => string | undefined): number { + const keys = new Set(); + for (const hit of hits) { + const key = groupOf(hit); + if (key !== undefined) keys.add(key); + } + return keys.size; +} + +/** + * [`source.documentBy`] A hit's group under record granularity with no + * `groupBy`: the parent record its source's document unit names, keyed with + * the hit's source, so two sources never share a group however equal their + * parent ids. The parent is read from the hit itself, `metadata[documentBy]`, + * the value assembly stored beside the passage (the parse holds `documentBy` + * in `metadataFields`), so grouping reads no record: it runs over the hits the + * adapters already answered. A hit with no parent to group by — its source + * declares no `documentBy`, or the value is absent, null, empty, or not a + * string or a number — is its own record ({@link recordKeyOf}), never dropped. + * Values are compared as strings, as a scope term compares them. + */ +export function documentKeyOf(hit: KnowledgeHit, documentBy: string | undefined): string { + const parent = documentBy === undefined ? undefined : documentUnitValueOf(hit.metadata, documentBy); + return parent === undefined ? recordKeyOf(hit) : `parent:${hit.sourceId}#${String(parent)}`; +} + +/** A hit's record: its source and record id; a hit that names no record is its document. */ +export function recordKeyOf(hit: KnowledgeHit): string { + return hit.sourceRecordId !== undefined ? `record:${hit.sourceId}#${hit.sourceRecordId}` : `document:${hit.documentId}`; +} + +/** + * The projection of the freshness check's read: every field + * {@link recordToDocument} reads for `objSource` — `id`, the content and + * metadata fields, the title field, and `organization_id` under a walled + * posture. `undefined` (read the whole row, as the walk and the event sync + * do) when the object's fields cannot be enumerated, or when a field the source names is not one the object declares: + * assembly reads such a field off the whole row, and a projection that left it + * out would recompute a different hash and read every record as stale. + */ +export function freshnessFields( + objSource: ObjectKnowledgeSource, + schema: unknown, + posture: TenancyPosture | undefined, +): string[] | undefined { + const declared = declaredFields(schema); + if (declared === undefined) return undefined; + const names = new Set(declared.map(([name]) => name)); + const wanted = new Set(['id', ...objSource.content, ...(objSource.metadataFields ?? [])]); + const titleField = documentTitleField(schema); + if (titleField !== undefined) wanted.add(titleField); + if (posture !== undefined && postureEnforcesWall(posture)) wanted.add('organization_id'); + for (const name of wanted) if (name !== 'id' && !names.has(name)) return undefined; + return [...wanted]; +} + +/** + * A caller-supplied field name as a log line or refusal shows it: JSON-quoted + * (so a quote or line break in it cannot forge text around it) and cut at 64 + * characters. + */ +export function quotedName(name: string): string { + return JSON.stringify(name.length > 64 ? `${name.slice(0, 64)}…` : name); +} + +/** Deterministic document id derived from the source + record id. */ +export function documentIdFor(sourceId: string, recordId: string): string { + return `${sourceId}:${recordId}`; +} + +/** + * Project an ObjectQL record into a `KnowledgeDocument` per the + * source's `content` / `metadataFields` config. Pure function. + * + * `schema` (the record's registered object definition) names the fields an + * index never carries: credential-class fields (the set the engine masks on + * read) and `internal: true` fields (the set it omits), asked through the same + * collectors the write-response helper uses (`@objectstack/core`). They are + * SKIPPED when a source names one as content or metadata, rather than + * indexed masked: an index document is searchable text + * served to every reader the source admits, and a mask placeholder is no + * content. Without a schema nothing is withheld here (the engine's event body + * and read path still apply their own projection upstream). + * + * The `title` is the value of the object's display field ({@link + * documentTitle}); with no schema, of a field named `title`. + * + * `posture` (the deployment's effective tenancy posture) decides the + * document's `organizationId` (ADR-0161 K8, item 9): the record's + * `organization_id` under `group` and `isolated`, none under `single` or with + * no posture — `documentOrganizationId`. The organization enters `docHash` + * only when the document carries one. + */ +export function recordToDocument( + source: KnowledgeSource, + objSource: ObjectKnowledgeSource, + record: Record, + schema?: unknown, + posture?: TenancyPosture, +): KnowledgeDocument { + const withheld = new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ]); + const recordId = String(record.id ?? (record as any)._id ?? ''); + const contentParts: string[] = []; + for (const field of objSource.content) { + if (withheld.has(field)) continue; + const v = record[field]; + if (v != null) contentParts.push(String(v)); + } + const metadata: Record = {}; + for (const field of objSource.metadataFields ?? []) { + if (withheld.has(field)) continue; + if (record[field] !== undefined) metadata[field] = record[field]; + } + const doc: KnowledgeDocument = { + id: documentIdFor(source.name, recordId || `unknown-${Date.now()}`), + sourceId: source.name, + sourceRecordId: recordId || undefined, + content: contentParts.join('\n\n'), + title: documentTitle(record, schema, withheld), + metadata, + }; + const organizationId = documentOrganizationId(record, posture); + if (organizationId !== undefined) doc.organizationId = organizationId; + doc.docHash = computeDocHash(doc); + return doc; +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index d146025378b..095db815baa 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -1,243 +1,100 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { createHash } from 'node:crypto'; import type { AdapterContext, - AdapterIndexExpectation, - AdapterIndexStatus, AdapterScopeTerm, IDataEngine, IKnowledgeAdapter, IKnowledgeService, - IQueueService, KnowledgeReindexOptions, KnowledgeReindexResult, KnowledgeSearchOptions, } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { - KnowledgeDocument, - KnowledgeHit, - KnowledgeSource, - ObjectKnowledgeSource, -} from '@objectstack/spec/ai'; -import { - collectCredentialWriteResponseFields, - collectInternalWriteResponseFields, - registryObjectPackageDisabled, -} from '@objectstack/core'; -import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; -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 type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { TenancyPosture } from '@objectstack/spec/security'; +import { type KnowledgeTools, createKnowledgeTools } from './knowledge-tools.js'; +import type { AffinityCallerFacts } from './knowledge-affinity.js'; import { - KnowledgeSourceRegistry, - codedError, - packageIdOfItem, - parseKnowledgeSource, type KnowledgeSourceEntry, type KnowledgeSourceHolder, + KnowledgeSourceRegistry, } from './knowledge-source-registry.js'; -import { - documentOrganizationId, - searchOrganizationIds, - type KnowledgeTenancyPostureResolver, -} from './knowledge-organization-scope.js'; -import { - admitObject, - admitSourceFields, - mayServeEarlierRuleTitle, - declaredFields, - documentTitleField, - documentUnitRefusalText, - affinityTargetRefusalText, - type KnowledgeAdmissionDeps, - type KnowledgeFieldSecurity, - type KnowledgeSourceAdmission, - type ObjectAdmission, -} from './knowledge-source-admission.js'; -import { - documentUnitOf, - narrowToVisible, - readSearchScope, - scopeCheck, - scopeTermsFor, - SEARCH_VISIBLE_IDS_MAX, - type DocumentUnitVerdict, - type SearchScopeEntry, -} from './knowledge-search-scope.js'; -import { - BUILD_LEASE_MS, - BUILD_PROGRESS_LOG_INTERVAL_MS, - BUILD_STALL_LIMIT_MS, - buildLockKey, - emptyBuildProgress, - fencedCall, - RECONCILE_MAX_WAIT_MS, - RECONCILE_QUIET_MS, - startBuildFence, - type KnowledgeBuildFence, - type KnowledgeBuildLock, - type KnowledgeBuildLockHandle, - type KnowledgeBuildProgress, - type KnowledgeBuildRecord, - type KnowledgeBuildTrigger, - type KnowledgeIndexReading, - type KnowledgeReconcileEntry, - type KnowledgeReconcileReport, - type KnowledgeReconcileRequest, +import type { KnowledgeAdmissionDeps } from './knowledge-source-admission.js'; +import type { SearchScopeEntry } from './knowledge-search-scope.js'; +import type { + KnowledgeBuildFence, + KnowledgeBuildProgress, + KnowledgeBuildRecord, + KnowledgeBuildTrigger, + KnowledgeIndexReading, + KnowledgeReconcileEntry, + KnowledgeReconcileReport, + KnowledgeReconcileRequest, } from './knowledge-build.js'; -import { - nextBuildId, - storedBuildMessage, - syncFailureText, - type KnowledgeStoredBuild, - type KnowledgeStoredBuildCounts, - type KnowledgeSyncFailures, - type KnowledgeSyncStateIdentity, - type KnowledgeSyncStateStore, +import type { + KnowledgeStoredBuild, + KnowledgeStoredBuildCounts, + KnowledgeSyncFailures, + KnowledgeSyncStateIdentity, } from './knowledge-sync-state.js'; -import { - KNOWLEDGE_RECORD_SYNC_QUEUE, - readRecordSyncMessage, - RECORD_SYNC_BACKLOG_READ_INTERVAL_MS, - RECORD_SYNC_BACKLOG_RETRY_MAX_MS, - RECORD_SYNC_BACKLOG_RETRY_MS, - RECORD_SYNC_BACKLOG_REWALK_MS, - RECORD_SYNC_BACKLOG_ROW_SHARE, - RECORD_SYNC_BACKLOG_THRESHOLD, - RECORD_SYNC_SOURCE_ROWS_TTL_MS, - RECORD_SYNC_COVER_MARGIN_MS, - type KnowledgeRecordSyncBatchItem, - type KnowledgeRecordSyncBatchResult, - type KnowledgeRecordSyncMessage, - type KnowledgeRecordSyncOutcome, - type KnowledgeRecordSyncReason, +import type { + KnowledgeRecordSyncBatchItem, + KnowledgeRecordSyncBatchResult, + KnowledgeRecordSyncMessage, + KnowledgeRecordSyncOutcome, + KnowledgeRecordSyncReason, } from './knowledge-record-sync-queue.js'; - -/** - * Minimal logger shape; falls back to no-op when none is provided. - */ -export interface KnowledgeLogger { - info?(msg: string, ...rest: unknown[]): void; - /** - * The GUARANTEED fallback channel (#9754). `error` stays optional — hosts do - * inject reduced sinks — so `warn` is where a durability report lands when - * `error` is absent, and a fallback that may itself be missing is not a - * fallback. Call sites keep the `logger?.warn?.(…)` spelling as the backstop - * for hosts the TYPE cannot reach; `SweepLogger` in plugin-email's - * `outbox-sweep.ts` carries the full reasoning and the measurement. - */ - warn(msg: string, ...rest: unknown[]): void; - error?(msg: string, ...rest: unknown[]): void; - debug?(msg: string, ...rest: unknown[]): void; -} - -/** - * Constructor options for `KnowledgeService`. - */ -/** - * [ADR-0161 K8, the dated note on item 12] Why a knowledge service the - * runtime composed is not enabled at this boot: each half that is missing. - * At least one member is set. Read once per boot, at `kernel:bootstrapped`, - * by `KnowledgeServicePlugin`, and handed to {@link KnowledgeService.settleEnablement}. - */ -export interface KnowledgeHeldReading { - /** - * Set when no embedder is available — none registered by a plugin, and the - * saved `ai.embedder_*` settings build none: why, as operator text (the - * settings that are missing or do not build one). Never a key. - */ - readonly embedder?: string; - /** Set when the deployment's store is not mounted: the id of its adapter, which nothing registered. */ - readonly store?: string; -} - -export interface KnowledgeServiceOptions { - /** Data engine used for RLS re-checks and bulk reindex walks. Optional in tests. */ - dataEngine?: IDataEngine; - /** Optional structured logger. */ - logger?: KnowledgeLogger; - /** - * [ADR-0161 K4 ◆] The deployment's adapter: the id of the store the - * runtime mounted beside this service for the `knowledge` capability - * (`pgvector` on PostgreSQL, `turso` otherwise — `resolveCapabilityArgument` - * in `@objectstack/core` sets it on the plugin it constructs). A source - * that names no `adapter` binds to it while an adapter of that id is - * registered. Only the runtime that mounts the store sets it: an adapter - * application code registers is never the deployment's by registering - * (`registerAdapter` takes no such mark). A service option, not an - * adapter-contract member (ADR-0161 K8, "What counts as a member"). - * Omitted (a host that mounts the service itself), a source that names - * no adapter binds to the only adapter registered. - */ - deploymentAdapter?: string; - /** - * [ADR-0161 K8, the dated note on item 12] The runtime composed this - * service, so it is enabled by configuration: until the boot's reading - * settles it ({@link KnowledgeService.settleEnablement}), the service hands - * out no tool definition, and once settled it either serves or holds its - * sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed` - * option. Omitted (a host that mounts the service itself), the service - * serves from the start, as it always has. - */ - enabledByConfiguration?: boolean; - /** - * The `security` service, resolved at search time, for the field gate - * (`knowledge-source-admission.ts`). Answers `undefined` when the host - * registers none: the contract's fallback then applies (every field - * declaring a `maskingRule` is not queryable). `KnowledgeServicePlugin` - * always wires it; omitted, the service reads as a host with no security - * service. - */ - resolveSecurity?: () => KnowledgeFieldSecurity | undefined; - /** - * The settings page's `knowledge.chunk_target`, read each time the service - * splits a batch of documents — never once at boot, so a value saved later - * applies to the next write. Answers `undefined` when nothing is stored or - * no settings service serves the namespace; the splitter then uses a - * source's own `split.maxChars`, else 800. A rejection is reported at `warn` - * and read as `undefined`. `KnowledgeServicePlugin` wires it to the - * `settings` service. - */ - resolveChunkTarget?: () => Promise; - /** - * The deployment's effective tenancy posture (ADR-0105 D1), read at each - * assembly and each search (ADR-0161 K8, item 9): under `group` and - * `isolated` a document assembled from a record carries the record's - * organization, and a search hands the adapter the caller's organizations - * (`knowledge-organization-scope.ts`). Answers `undefined` where no - * `tenancy` service is composed, and throws where one is registered but - * cannot be read. `KnowledgeServicePlugin` always wires it; omitted, the - * service reads as a `single`-posture deployment. - */ - resolveTenancyPosture?: KnowledgeTenancyPostureResolver; - /** - * The cluster lock a build runs under (`knowledge-build.ts`, "One node - * builds a source"), resolved each time a build starts. Answers `undefined` - * where no cluster service is composed: the composition is one node and the - * build runs without a lease. `KnowledgeServicePlugin` wires it to the - * `cluster` service's `lock`. - */ - resolveBuildLock?: () => KnowledgeBuildLock | undefined; - /** - * Each source's durable sync state (`knowledge-sync-state.ts`, - * `sys_knowledge_sync_state`): the last build and the record syncs that - * failed, one row per source, the same on every node. `index_status` - * answers from it. `KnowledgeServicePlugin` wires it wherever the object is - * registered and a data engine is bound. Omitted, the service keeps only - * this node's last build in memory, and `index_status` answers that. - */ - syncState?: KnowledgeSyncStateStore; - /** - * Default top-K when callers don't specify. The adapter may cap - * further; the service does not enforce an upper bound itself. - * @default 10 - */ - defaultTopK?: number; -} +import type { + AdmittedSource, + DurableBuild, + IndexPlan, + KnowledgeHeldReading, + KnowledgeRecordSyncQueueView, + KnowledgeSearchRefusal, + KnowledgeSearchReport, + KnowledgeServiceOptions, + KnowledgeSourceDescription, + RecordSyncGroup, + SearchTarget, + UnprovenEnd, +} from './knowledge-service-top-level.js'; +import { KnowledgeSourcesFacet } from './knowledge-service-sources.js'; +import { KnowledgeIndexingFacet } from './knowledge-service-indexing.js'; +import { KnowledgeRecordSyncFacet } from './knowledge-service-record-sync.js'; +import { KnowledgeSearchFacet } from './knowledge-service-search.js'; +import { KnowledgeAdmissionFacet } from './knowledge-service-admission.js'; +import { knowledgeServiceHost } from './knowledge-service-host.js'; + +// [#38660] Every top-level declaration this module held beside the class lives in +// `knowledge-service-top-level.ts`; what it exported is still exported from here, under the same names. +export { + heldSourcesError, + heldSourcesText, + REINDEX_PAGE_SIZE, + MAX_REINDEX_FAILURES, + objectSourcesFor, + LIST_DOCUMENTS_PAGE_SIZE, + SEARCH_FIRST_ROUND_FACTOR, + SEARCH_REFILL_FACTOR, + SEARCH_FRESHNESS_ROUNDS, + purgeDocuments, + DOC_HASH_VERSION, + computeDocHash, + documentIdFor, + recordToDocument, +} from './knowledge-service-top-level.js'; +export type { + KnowledgeLogger, + KnowledgeHeldReading, + KnowledgeServiceOptions, + KnowledgeSourceDescription, + KnowledgeSearchRefusal, + KnowledgeSearchReport, + KnowledgeRecordSyncQueueView, + PurgeDocumentsInput, + PurgeDocumentsOutcome, +} from './knowledge-service-top-level.js'; /** * `KnowledgeService` — production `IKnowledgeService` implementation. @@ -366,10 +223,7 @@ export class KnowledgeService implements IKnowledgeService { * reads the state again. */ settleEnablement(held: KnowledgeHeldReading | undefined): void { - this.enablementPending = false; - this.held = held; - if (!held) return; - for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); + return KnowledgeSourcesFacet.settleEnablement.call(knowledgeServiceHost.of(this), held); } /** {@link settleEnablement}'s reading while the sources are held, else `undefined`. */ @@ -380,14 +234,11 @@ export class KnowledgeService implements IKnowledgeService { // ── Adapter registry ────────────────────────────────────────────── registerAdapter(id: string, adapter: IKnowledgeAdapter): void { - this.adapters.set(id, adapter); - this.options.logger?.info?.(`[knowledge] adapter registered: ${id}`); + return KnowledgeSourcesFacet.registerAdapter.call(knowledgeServiceHost.of(this), id, adapter); } getAdapter(id: string): IKnowledgeAdapter { - const adapter = this.adapters.get(id); - if (!adapter) throw unmountedAdapterError(id, this.listAdapters()); - return adapter; + return KnowledgeSourcesFacet.getAdapter.call(knowledgeServiceHost.of(this), id); } /** @@ -406,13 +257,7 @@ export class KnowledgeService implements IKnowledgeService { * in code at `init()`, so the answer is taken where it is used. */ adapterIdFor(source: KnowledgeSource): string { - if (source.adapter !== undefined) return source.adapter; - const deployment = this.options.deploymentAdapter; - if (deployment !== undefined && this.adapters.has(deployment)) return deployment; - const registered = this.listAdapters(); - if (registered.length === 1) return registered[0]!; - if (registered.length === 0) throw noAdapterMountedError(this.label(source), deployment); - throw unplacedSourceError(this.label(source), registered); + return KnowledgeSourcesFacet.adapterIdFor.call(knowledgeServiceHost.of(this), source); } /** The adapter `source` binds to ({@link adapterIdFor}), registered; throws the coded refusal otherwise. */ @@ -422,26 +267,11 @@ export class KnowledgeService implements IKnowledgeService { /** {@link adapterIdFor}, or `undefined` where it refuses: for a log line or a status answer. */ boundAdapterId(source: KnowledgeSource): string | undefined { - try { - return this.adapterIdFor(source); - } catch { - return undefined; - } + return KnowledgeSourcesFacet.boundAdapterId.call(knowledgeServiceHost.of(this), source); } - /** - * Refuse, at registration, a source that names no adapter where the answer - * cannot become one: several adapters are registered and the runtime marked - * none the deployment's (ADR-0161 K4 ◆). With a mark, or with one adapter - * or none registered yet, the source is taken and placed where it is used: - * a store registers in its own `start()`, after a source registered at - * `init()`, so "none yet" is no verdict (AGENTS.md, startup registry reads). - */ private refuseUnplacedSource(source: KnowledgeSource, door: string): void { - if (source.adapter !== undefined || this.options.deploymentAdapter !== undefined) return; - const registered = this.listAdapters(); - if (registered.length < 2) return; - throw unplacedSourceError(source.name, registered, ` ${door} did not register it.`); + return KnowledgeSourcesFacet.refuseUnplacedSource.call(knowledgeServiceHost.of(this), source, door); } /** @@ -452,33 +282,11 @@ export class KnowledgeService implements IKnowledgeService { * ({@link getAdapter}); the boot itself goes on. Answers the sources named. */ reportUnmountedAdapters(): string[] { - const mounted = this.listAdapters(); - const named: string[] = []; - for (const { id, source } of this.describeSources()) { - if (source.adapter === undefined) { - // [ADR-0161 K4 ◆] A source that names no adapter, which this boot - // cannot place: no adapter at all, or several and none the deployment's. - try { - this.adapterIdFor(source); - } catch (err) { - this.options.logger?.error?.(`${errorText(err)} Indexing and searching it answer that refusal.`); - named.push(id); - } - continue; - } - if (this.adapters.has(source.adapter)) continue; - this.options.logger?.error?.( - `[knowledge] source '${id}' names adapter '${source.adapter}', which is not mounted ` + - `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). Indexing and searching it answer ` + - `${UNMOUNTED_ADAPTER_CODE} until its adapter is one of those, or the '${source.adapter}' store is mounted.`, - ); - named.push(id); - } - return named; + return KnowledgeSourcesFacet.reportUnmountedAdapters.call(knowledgeServiceHost.of(this)); } listAdapters(): string[] { - return [...this.adapters.keys()]; + return KnowledgeSourcesFacet.listAdapters.call(knowledgeServiceHost.of(this)); } // ── Source registry ─────────────────────────────────────────────── @@ -500,29 +308,7 @@ export class KnowledgeService implements IKnowledgeService { * package-less slot is refused `409 RESOURCE_CONFLICT`, naming both doors. */ registerSource(source: KnowledgeSource): void { - const parsed = parseKnowledgeSource(source); - if (!parsed.ok) { - throw codedError( - 'VALIDATION_ERROR', - 400, - `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, - ); - } - this.refuseUnplacedSource(parsed.source, 'registerSource'); - const packageId = packageIdOfItem(parsed.source); - if (packageId !== undefined) { - throw codedError( - 'VALIDATION_ERROR', - 400, - `[knowledge] registerSource refused source '${parsed.source.name}': it names package "${packageId}" ` + - '(`_packageId`), and a source registered in code belongs to no package. Ship the source in that ' + - "package's `knowledgeSources` collection, or drop the key.", - ); - } - const { entry, replaced } = this.registry.register(parsed.source, 'code'); - if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); - this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${this.adapterLabel(entry.authored)})`); - this.sourcesChanged(); + return KnowledgeSourcesFacet.registerSource.call(knowledgeServiceHost.of(this), source); } /** @@ -533,20 +319,13 @@ export class KnowledgeService implements IKnowledgeService { * naming both doors. Called by `KnowledgeServicePlugin`'s loader, never by a * caller holding `IKnowledgeService`. */ - registerMetadataSource(source: KnowledgeSource, holder: KnowledgeSourceHolder = {}): KnowledgeSourceEntry { - this.refuseUnplacedSource(source, 'The knowledge_source loader'); - const { entry, replaced } = this.registry.register(source, 'metadata', holder); - this.options.logger?.info?.( - `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + - `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, - ); - this.sourcesChanged(); - return entry; + registerMetadataSource(source: KnowledgeSource, holder?: KnowledgeSourceHolder): KnowledgeSourceEntry { + return KnowledgeSourcesFacet.registerMetadataSource.call(knowledgeServiceHost.of(this), source, holder); } /** The sources that arrived through the metadata door, for the loader that owns them. */ metadataSources(): KnowledgeSourceEntry[] { - return this.registry.entries().filter((entry) => entry.door === 'metadata'); + return KnowledgeSourcesFacet.metadataSources.call(knowledgeServiceHost.of(this)); } /** @@ -556,20 +335,11 @@ export class KnowledgeService implements IKnowledgeService { * does not stop the others. Answers the unsubscribe. */ onSourcesChanged(listener: () => void): () => void { - this.sourceListeners.add(listener); - return () => { - this.sourceListeners.delete(listener); - }; + return KnowledgeSourcesFacet.onSourcesChanged.call(knowledgeServiceHost.of(this), listener); } private sourcesChanged(): void { - for (const listener of [...this.sourceListeners]) { - try { - listener(); - } catch (err) { - this.options.logger?.warn?.(`[knowledge] a source-change listener failed (${errorText(err)}).`); - } - } + return KnowledgeSourcesFacet.sourcesChanged.call(knowledgeServiceHost.of(this)); } /** @@ -579,18 +349,7 @@ export class KnowledgeService implements IKnowledgeService { * `sourceId` that names no source is a no-op. */ unregisterSource(sourceId: string): void { - const entry = this.registry.resolve(sourceId); - if (!entry) return; - if (entry.door === 'metadata') { - throw codedError( - 'RESOURCE_CONFLICT', - 409, - `[knowledge] source '${entry.face}' is a knowledge_source metadata item, so unregisterSource does not remove ` + - 'it: delete the item (Studio, the metadata API, or its package), and the knowledge service unregisters it ' + - 'and drops its index.', - ); - } - this.forget(entry); + return KnowledgeSourcesFacet.unregisterSource.call(knowledgeServiceHost.of(this), sourceId); } /** @@ -601,68 +360,17 @@ export class KnowledgeService implements IKnowledgeService { * `dropSource` that throws is reported the same way. Never throws. Answers * the removed entry, or `undefined` when the key held none. */ - async dropMetadataSource(key: string): Promise { - const entry = this.registry.byIndexKey(key); - if (!entry || entry.door !== 'metadata') return undefined; - // Placed before the entry is forgotten: an unnamed adapter is placed - // among the adapters registered now, as every other use places it. - const adapterId = this.boundAdapterId(entry.handed); - this.forget(entry); - // The source's sync-state row goes with it (whatever its index does). - const store = this.options.syncState; - if (store) { - try { - await store.remove(entry.key); - } catch (err) { - this.syncStateWriteFailed(`the sync-state row of removed source '${entry.face}' could not be removed`, err); - } - } - const kept = (why: string): void => { - this.options.logger?.warn?.( - `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + - `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, - ); - }; - if (this.held) { - kept('the knowledge service is not enabled at this boot, so no store is called.'); - return entry; - } - const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); - if (!adapter) { - kept( - adapterId === undefined - ? 'it names no adapter, and none could be placed for it.' - : `adapter '${adapterId}' is not mounted.`, - ); - return entry; - } - if (typeof adapter.dropSource !== 'function') { - kept(`adapter '${adapterId}' has no dropSource.`); - return entry; - } - try { - await adapter.dropSource({ source: entry.handed, reason: 'manual' }); - this.options.logger?.info?.(`[knowledge] source '${entry.face}' was removed and its index dropped.`); - } catch (err) { - kept(`dropSource failed (${operatorText(err)}).`); - } - return entry; + dropMetadataSource(key: string): Promise { + return KnowledgeSourcesFacet.dropMetadataSource.call(knowledgeServiceHost.of(this), key); } - /** Remove `entry` and what this node remembers of it. */ private forget(entry: KnowledgeSourceEntry): void { - this.registry.remove(entry.key); - this.builds.delete(entry.key); - this.syncStateRecorded.delete(entry.key); - this.whereUnenforceableReported.delete(entry.key); - this.reconcileUnlistedReported.delete(entry.key); - this.cancelPendingReconcile(entry.key); - this.sourcesChanged(); + return KnowledgeSourcesFacet.forget.call(knowledgeServiceHost.of(this), entry); } /** Every registered source, as its author wrote it (a package's source carries its `_packageId`). */ listSources(): KnowledgeSource[] { - return this.registry.entries().map((entry) => entry.authored); + return KnowledgeSourcesFacet.listSources.call(knowledgeServiceHost.of(this)); } /** @@ -671,7 +379,7 @@ export class KnowledgeService implements IKnowledgeService { * its holder. What `search_knowledge` lists and the operator's actions name. */ describeSources(): KnowledgeSourceDescription[] { - return this.registry.entries().map(describeEntry); + return KnowledgeSourcesFacet.describeSources.call(knowledgeServiceHost.of(this)); } /** @@ -685,29 +393,24 @@ export class KnowledgeService implements IKnowledgeService { /** The source `sourceId` names (a face, or a bare name by ADR-0150 D3), as its author wrote it. */ getSource(sourceId: string): KnowledgeSource | undefined { - return this.registry.resolve(sourceId)?.authored; + return KnowledgeSourcesFacet.getSource.call(knowledgeServiceHost.of(this), sourceId); } /** {@link getSource}, with the source's face and holder. */ describeSource(sourceId: string): KnowledgeSourceDescription | undefined { - const entry = this.registry.resolve(sourceId); - return entry ? describeEntry(entry) : undefined; + return KnowledgeSourcesFacet.describeSource.call(knowledgeServiceHost.of(this), sourceId); } - /** The handed source held under an index key. */ private handed(key: string): KnowledgeSource | undefined { - return this.registry.byIndexKey(key)?.handed; + return KnowledgeSourcesFacet.handed.call(knowledgeServiceHost.of(this), key); } private handedSources(): KnowledgeSource[] { - return this.registry.entries().map((entry) => entry.handed); + return KnowledgeSourcesFacet.handedSources.call(knowledgeServiceHost.of(this)); } - /** How a log line names a source's adapter: the one it names, else the one it is placed on now. */ private adapterLabel(source: KnowledgeSource): string { - if (source.adapter !== undefined) return source.adapter; - const placed = this.boundAdapterId(source); - return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; + return KnowledgeSourcesFacet.adapterLabel.call(knowledgeServiceHost.of(this), source); } /** How a log line or an answer names a handed source: its face. */ @@ -716,56 +419,17 @@ export class KnowledgeService implements IKnowledgeService { } private faceOfKey(key: string): string { - return this.registry.byIndexKey(key)?.face ?? key; + return KnowledgeSourcesFacet.faceOfKey.call(knowledgeServiceHost.of(this), key); } - /** - * What every adapter call for `source` carries, read now (ADR-0161 K7; K8, - * item 8): the split the service applies for this adapter — resolved from - * the source's `split`, the settings page's `knowledge.chunk_target` and the - * adapter's reported `embedding.maxInputTokens`, absent for an adapter that - * does not take chunks — and the index fingerprint and recipe hash computed - * over that same split, the adapter's descriptor and the source. One read - * feeds both, so the fingerprint is always the fingerprint of the split the - * documents were cut by. Never cached: the settings, the descriptor and the - * object definition may each change between two calls. - */ - private async planIndex( + private planIndex( source: KnowledgeSource, adapter: IKnowledgeAdapter, - chunkTarget: () => Promise = () => this.readChunkTarget(), + chunkTarget?: () => Promise, ): Promise { - const split = adapter.capabilities?.chunks === true - ? resolveSplit({ - split: source.source.split, - chunkTarget: await chunkTarget(), - maxInputTokens: adapter.embedding?.maxInputTokens, - }) - : undefined; - const index = indexExpectation( - { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, - { source, schema: this.schemaFor(source.source.object) }, - ); - return { - source, - adapter, - ...(split === undefined ? {} : { split }), - index, - context: (reason) => ({ source, reason, index }), - }; + return KnowledgeIndexingFacet.planIndex.call(knowledgeServiceHost.of(this), source, adapter, chunkTarget); } - /** - * The ONE place documents are split before an adapter sees them (ADR-0161 - * K1). An adapter that does not declare `capabilities.chunks` gets the - * documents as they are, without `chunks` — it splits them itself, as - * before. One that does gets each document with the passages of - * {@link splitDocument}, under the split {@link planIndex} resolved for - * this call: the source's `split`, the settings page's `knowledge.chunk_target`, and the - * adapter's reported `embedding.maxInputTokens` — read for this call, never - * cached. A document the split cannot index (a `whole` document over the - * budget) is answered in `failed`, never truncated; the caller removes it. - */ private prepareDocuments( plan: IndexPlan, docs: KnowledgeDocument[], @@ -773,31 +437,11 @@ export class KnowledgeService implements IKnowledgeService { ready: KnowledgeDocument[]; failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }>; } { - const split = plan.split; - if (split === undefined || docs.length === 0) return { ready: docs, failed: [] }; - const ready: KnowledgeDocument[] = []; - const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; - for (const doc of docs) { - const out = splitDocument(doc, split); - if (out.ok) ready.push({ ...doc, chunks: out.chunks }); - else failed.push({ documentId: doc.id, reason: out.reason, estimate: out.estimate, budget: out.budget }); - } - return { ready, failed }; + return KnowledgeIndexingFacet.prepareDocuments(plan, docs); } - /** The settings page's `knowledge.chunk_target`, read now; `undefined` when unset or unreadable. */ - private async readChunkTarget(): Promise { - const resolve = this.options.resolveChunkTarget; - if (!resolve) return undefined; - try { - return await resolve(); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the settings page's knowledge.chunk_target could not be read (${errorText(err)}); ` + - "splitting by the source's own split.maxChars, else 800.", - ); - return undefined; - } + private readChunkTarget(): Promise { + return KnowledgeIndexingFacet.readChunkTarget.call(knowledgeServiceHost.of(this)); } // ── Reindex ─────────────────────────────────────────────────────── @@ -879,59 +523,23 @@ export class KnowledgeService implements IKnowledgeService { * documents may remain) is not completed: the adapter keeps what it held, * and the next complete walk builds again. */ - async reindexSource( + reindexSource( sourceId: string, - opts: KnowledgeReindexOptions = {}, + opts?: KnowledgeReindexOptions, ): Promise { - const entry = this.requireEntry(sourceId); - if (this.held) throw heldSourcesError(this.held); - return this.reindexWith(entry.handed, opts); + return KnowledgeIndexingFacet.reindexSource.call(knowledgeServiceHost.of(this), sourceId, opts); } - /** - * {@link reindexSource}, with a sink a build's progress is reported to after - * each page, and the build's fence (`knowledge-build.ts`) the walk asks - * before each page. - */ - private async reindexWith( + private reindexWith( source: KnowledgeSource, opts: KnowledgeReindexOptions, progress?: (step: KnowledgeBuildProgress) => void, fence?: KnowledgeBuildFence, ): Promise { - const adapter = this.adapterFor(source); - - const engine = this.options.dataEngine; - if (!engine) { - return { - ok: false, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: 'KnowledgeService has no IDataEngine bound; cannot walk the source.', - }; - } - - return chainAfter(this.reindexTails, source.name, () => - this.walkObjectSource(source, source.source, adapter, engine, opts, progress, fence), - ); + return KnowledgeIndexingFacet.reindexWith.call(knowledgeServiceHost.of(this), source, opts, progress, fence); } - /** - * The paged walk of {@link reindexSource}; runs inside that source's chain. - * Under a build's `fence` it stops before a page once the fence says so - * (and before `beginBuild`, before each purge deletion, and before its - * purge and completion), and stops waiting on a read, a - * write, the listing, the purge or `beginBuild` once the build is - * cancelled, so the source's chain is not held by such a call that never - * answers. Each page and each purge deletion restarts the fence's bound. - * The completion is not raced: the chain stays held until it settles (see - * {@link completeBuild}). - */ - private async walkObjectSource( + private walkObjectSource( source: KnowledgeSource, objSource: ObjectKnowledgeSource, adapter: IKnowledgeAdapter, @@ -940,393 +548,26 @@ export class KnowledgeService implements IKnowledgeService { progress?: (step: KnowledgeBuildProgress) => void, fence?: KnowledgeBuildFence, ): Promise { - const object = objSource.object; - // `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A - // fractional cap is floored; a negative or non-finite one is refused - // rather than read as "nothing to do". - if (opts.limit !== undefined && !(typeof opts.limit === 'number' && Number.isFinite(opts.limit) && opts.limit >= 0)) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, - }; - } - const cap = opts.limit === undefined ? undefined : Math.floor(opts.limit); - // RLS-bypassing system context — this is a server-side admin op. - const context = systemContext(); - - if (opts.dryRun) { - const total = await engine.count(object, { where: objSource.where }, { context }); - return { - ok: true, - object, - discovered: cap === undefined ? total : Math.min(total, cap), - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: 'dryRun=true; no documents pushed.', - }; - } - - // The posture decides whether each document carries its record's - // organization (ADR-0161 K8, item 9); read once per walk. A posture that - // cannot be read stops the walk before any write: a document assembled - // without its organization would drop out of every walled search. - let posture: TenancyPosture | undefined; - try { - posture = await this.readTenancyPosture(); - } catch (err) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - message: `reindex of source '${this.label(source)}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, - }; - } - - // One plan for the whole walk: the split every page is cut by, and the - // fingerprint and recipe hash every adapter call carries. - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('reindex'); - - // A complete walk is a build (K7, rule 3): the adapter is told before the - // first write, and may open a generation for a new fingerprint — or refuse. - const build = cap === undefined; - // A build cancelled, or whose lease was lost, while its walk waited its - // turn in the source's queue does not begin: `beginBuild` is where a store - // that keeps generations takes its builder lock (K7, rule 2). - const unbegun = fence?.stop(); - if (unbegun !== undefined) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${source.id}' stopped before its build began, and nothing was written: ${unbegun.message}`, - }; - } - if (build && typeof adapter.beginBuild === 'function') { - try { - await fencedCall(fence, adapter.beginBuild(ctx)); - } catch (err) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, - }; - } - } - - // What the adapter holds before the walk: the skip's hashes, and the - // purge's candidates once the walk is complete. - // Raced against the build's bound like every call of the walk, so a store - // that never answers frees the source's chain. - let listing: Awaited>; - try { - listing = await fencedCall(fence, listAdapterDocuments(source, adapter, plan.index)); - } catch (err) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' stopped before its first page: ${errorText(err)}`, - }; - } - const listed = listing.ok ? listing.documents : undefined; - const listingNote = listing.ok || listing.reason === undefined - ? undefined - : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; - if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${this.label(source)}': ${listingNote}`); - - const schema = this.schemaFor(object); - const seen = new Set(); - let discovered = 0; - let indexed = 0; - let skipped = 0; - // Documents the split could not index (a `whole` document over the - // embedder's budget): removed from the index, counted, and the first - // MAX_REINDEX_FAILURES named. - let failed = 0; - const failures: Array<{ documentId: string; reason: string }> = []; - let cursor: string | number | undefined; - for (let page = 1; ; page++) { - const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); - if (!(want > 0)) break; - const after = cursor === undefined ? '' : ` (after id '${cursor}')`; - const stopped = (what: string): KnowledgeReindexResult => ({ - ok: false, - object, - discovered, - indexed, - skipped, - purged: null, - failed, - failures: [...failures], - message: `reindex of source '${this.label(source)}' stopped at page ${page}${after}: ${what}`, - }); - // A build that lost its lease, or was cancelled, reads and embeds no - // further page (the fence, `knowledge-build.ts`). - const halt = fence?.stop(); - if (halt !== undefined) return stopped(halt.message); - - const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; - let rows: Array>; - try { - rows = await fencedCall(fence, engine.find( - object, - { - where: - byCursor === undefined - ? objSource.where - : objSource.where === undefined ? byCursor : { $and: [objSource.where, byCursor] }, - orderBy: [{ field: 'id', order: 'asc' }], - limit: want, - }, - { context }, - )); - } catch (err) { - return stopped(`the read failed: ${errorText(err)}`); - } - // Only an EMPTY page ends the walk. A short page does not: `find` does - // not promise `min(limit, remaining)` rows — an `afterFind` hook may drop - // rows from a page — so rows after a short page can still exist. - // A read that answers no list is a failed read, never the end of the - // source: read as an empty page it would make a complete walk of nothing - // and hand every listed document to the purge. - if (!Array.isArray(rows)) { - return stopped(`the read answered ${describeValue(rows)} instead of a list of rows.`); - } - if (rows.length === 0) break; - - let docs: KnowledgeDocument[]; - try { - docs = rows.map((row) => recordToDocument(source, objSource, row, schema, posture)); - } catch (err) { - return stopped(`building the page's documents failed: ${errorText(err)}`); - } - // A document whose computed hash equals the one the adapter listed for it - // is unchanged: it is not written again. - const changed = listed === undefined - ? docs - : docs.filter((doc) => { - const stored = listed.get(doc.id); - return stored === undefined || stored !== doc.docHash; - }); - // One split per changed document, for an adapter that takes chunks. - const prepared = this.prepareDocuments(plan, changed); - if (prepared.ready.length > 0) { - try { - await fencedCall(fence, adapter.upsert(prepared.ready, ctx)); - } catch (err) { - return stopped(`the adapter upsert failed: ${operatorText(err)}`); - } - } - // A document the split cannot index is removed — an older passage of it - // must not keep answering for text the index no longer holds — and - // reported, never truncated. - if (prepared.failed.length > 0) { - try { - await fencedCall(fence, adapter.delete(prepared.failed.map((f) => f.documentId), ctx)); - } catch (err) { - return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); - } - for (const f of prepared.failed) { - failed += 1; - if (failures.length < MAX_REINDEX_FAILURES) failures.push({ documentId: f.documentId, reason: f.reason }); - } - } - for (const doc of docs) seen.add(doc.id); - discovered += rows.length; - indexed += prepared.ready.length; - skipped += docs.length - changed.length; - progress?.({ pages: page, discovered, indexed, skipped, failed }); - - // The next page continues after this page's last id. A last row with no - // id, or one that did not move past the cursor (an engine that ignored - // the `id > cursor` condition), ends the walk rather than looping on it. - const lastId = rows[rows.length - 1].id; - if (!isRecordId(lastId)) { - return stopped('the page was indexed, but its last row carries no id, so the walk cannot continue after it.'); - } - if (lastId === cursor) { - return stopped("the page was indexed, but its last row's id did not move past the cursor, so the walk cannot continue."); - } - cursor = lastId; - } - - // A build that lost its lease after its last page neither purges nor - // completes: another node may be building the source. - const halted = fence?.stop(); - if (halted !== undefined) { - return { - ok: false, - object, - discovered, - indexed, - skipped, - purged: null, - failed, - failures: [...failures], - message: `reindex of source '${this.label(source)}' read every page, and stopped before its purge and completion: ${halted.message}`, - }; - } - - // The purge runs only after a COMPLETE walk: a `limit` walk saw part of - // the source, so "not seen" there means nothing (a failed page returned - // above; `dryRun` returned before the walk). - const failedNote = failed === 0 - ? undefined - : `${failed} document(s) cannot be indexed under the source's split and were removed from the index ` + - `(${failures.length === failed ? 'each' : `the first ${failures.length}`} named in failures).`; - const done: KnowledgeReindexResult = { - ok: true, - object, - discovered, - indexed, - skipped, - purged: null, - failed, - failures, - ...(failedNote === undefined ? {} : { message: failedNote }), - }; - if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; - if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { - return build ? this.completeBuild(source, adapter, ctx, done, fence) : done; - } - - const candidates = [...listed.keys()].filter((id) => !seen.has(id)); - let purge: PurgeDocumentsOutcome; - try { - purge = await fencedCall(fence, purgeDocuments({ - source, - objSource, - adapter, - engine, - candidates, - // Each settled deletion (or confirmed keep) is progress: a large, - // healthy purge restarts the fence's bound as it goes. A build that - // lost its lease, or was cancelled, re-reads and deletes no further - // candidate: the fence is asked once the candidate's turn comes. - serialize: async (documentId, task) => { - const outcome = await chainAfter(this.recordSyncTails, documentId, () => { - const halt = fence?.stop(); - return halt === undefined ? task() : Promise.reject(new Error(halt.message)); - }); - fence?.progressed(); - return outcome; - }, - index: plan.index, - })); - } catch (err) { - return { - ...done, - ok: false, - message: `reindex of source '${this.label(source)}' walked every page, and stopped during its purge: ${errorText(err)}`, - }; - } - if (purge.failure !== undefined) { - const purgeHalt = fence?.stop(); - if (purgeHalt !== undefined) { - return { - ...done, - ok: false, - purged: purge.purged, - message: - `reindex of source '${source.id}' walked every page, and stopped during its purge after ` + - `${purge.purged} deletion(s): ${purgeHalt.message}`, - }; - } - return { - ...done, - ok: false, - purged: purge.purged, - message: - `reindex of source '${this.label(source)}' walked every page, but its purge stopped after ${purge.purged} ` + - `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, - }; - } - if (purge.foreign > 0) { - return this.completeBuild(source, adapter, ctx, { - ...done, - purged: purge.purged, - message: - `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + - `('${source.name}:' and the record id); they were kept, because no row can confirm them.` + - (failedNote === undefined ? '' : ` ${failedNote}`), - }, fence); - } - return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }, fence); + return KnowledgeIndexingFacet.walkObjectSource.call( + knowledgeServiceHost.of(this), + source, + objSource, + adapter, + engine, + opts, + progress, + fence, + ); } - /** - * The end of a complete build (ADR-0161 K8, item 8 c): the adapter's - * `completeBuild`, once, with the fingerprint and recipe hash the walk - * carried. An adapter without it records nothing. One that throws turns the - * walk's result into `ok: false`: every page was written, but the adapter - * did not record what it holds, so the next complete walk builds again. - * Under a build's `fence`, a build that must stop (its lease lost during - * the purge, or its bound passed) completes nothing. Once the completion - * begins it is not a page: the fence's bound is disarmed - * (`fence.completing()`) and the call is awaited however long it takes, so - * a switch that began still commits and the record never reads - * `timed-out` over it. The source's walk chain stays held until it settles, - * so no rebuild on this node begins a build beside it. - */ - private async completeBuild( + private completeBuild( source: KnowledgeSource, adapter: IKnowledgeAdapter, ctx: AdapterContext, done: KnowledgeReindexResult, fence?: KnowledgeBuildFence, ): Promise { - const halt = fence?.stop(); - if (halt !== undefined) { - return { - ...done, - ok: false, - message: `reindex of source '${this.label(source)}' walked every page, and stopped before its completion: ${halt.message}`, - }; - } - if (typeof adapter.completeBuild !== 'function') return done; - fence?.completing(); - try { - await adapter.completeBuild(ctx); - return done; - } catch (err) { - return { - ...done, - ok: false, - message: - `reindex of source '${this.label(source)}' walked every page, but the adapter did not complete the build ` + - `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, - }; - } + return KnowledgeIndexingFacet.completeBuild.call(knowledgeServiceHost.of(this), source, adapter, ctx, done, fence); } // ── The first build and the operator's rebuild (ADR-0161 K7) ────── @@ -1344,99 +585,13 @@ export class KnowledgeService implements IKnowledgeService { return this.readIndexStateOf(this.requireEntry(sourceId)); } - /** {@link readIndexState} of one registered source; the reading names it by its face. */ - private async readIndexStateOf(entry: KnowledgeSourceEntry): Promise { - const source = entry.handed; - const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({ - sourceId: entry.face, - state, - due, - detail, - ...(held === undefined ? {} : { held }), - }); - if (!this.options.dataEngine) { - return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); - } - try { - const adapter = this.adapterFor(source); - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('reindex'); - if (typeof adapter.indexStatus === 'function') { - const held = await adapter.indexStatus(ctx); - const expected = plan.index; - if (held.fingerprint === undefined && held.recipeHash === undefined && held.building !== true) { - return reading('nothing', true, 'the adapter holds nothing for the source: it has never been built.', held); - } - // A first build opened a generation and has not completed it (it is - // still running on some node, or it stopped part-way): there is no - // active generation yet, so no other fingerprint to speak of. - if (held.fingerprint === undefined) { - return reading( - 'nothing', - true, - 'a first build was started and has not completed (it is still running, or it stopped part-way): the adapter holds no complete index for the source.', - held, - ); - } - if (held.fingerprint !== expected.fingerprint) { - return reading( - 'new-fingerprint', - true, - 'the index was built under another fingerprint (embedding model, dimensions or split): it is built anew.', - held, - ); - } - if (held.recipeHash === undefined) { - return typeof adapter.completeBuild === 'function' - ? reading('no-recipe-hash', true, 'the index records no recipe hash: one complete rebuild records it.', held) - : reading( - 'no-recipe-hash', - false, - `the adapter '${adapter.id}' records no recipe hash and has no completeBuild, so a changed recipe ` + - "(the source's where, metadataFields, title rule or withheld fields) cannot be seen for it; nothing is rebuilt automatically.", - held, - ); - } - if (held.recipeHash !== expected.recipeHash) { - return reading( - 'recipe-changed', - true, - "the source's recipe changed since the last build (its where, metadataFields, title rule or withheld fields): it is rebuilt.", - held, - ); - } - return reading('current', false, 'the index is current: same fingerprint, same recipe hash.', held); - } - if (typeof adapter.listDocuments === 'function') { - const page = await adapter.listDocuments(ctx, { limit: 1 }); - const documents = Array.isArray(page?.documents) ? page.documents : undefined; - if (documents === undefined) { - return reading('unreadable', false, "the adapter's document listing answered no list of documents."); - } - return documents.length === 0 - ? reading('listed-empty', true, 'the adapter lists no document for the source: it has never been built.') - : reading( - 'listed-documents', - false, - `the adapter '${adapter.id}' holds documents and reports no index status, so whether they are current cannot be read; nothing is rebuilt automatically.`, - ); - } - return reading( - 'unknown', - false, - `the adapter '${adapter.id}' has neither indexStatus nor listDocuments, so whether the source was ever built cannot be read; ` + - 'nothing is built automatically, and an operator rebuild (os knowledge rebuild) is the way.', - ); - } catch (err) { - return reading('unreadable', false, `what the adapter holds could not be read (${operatorText(err)}).`); - } + private readIndexStateOf(entry: KnowledgeSourceEntry): Promise { + return KnowledgeIndexingFacet.readIndexStateOf.call(knowledgeServiceHost.of(this), entry); } /** The last build of `sourceId` on this node, or `undefined` when it ran none. */ buildRecord(sourceId: string): KnowledgeBuildRecord | undefined { - const entry = this.registry.resolve(sourceId); - const record = entry === undefined ? undefined : this.builds.get(entry.key); - return record === undefined ? undefined : cloneBuildRecord(record); + return KnowledgeIndexingFacet.buildRecord.call(knowledgeServiceHost.of(this), sourceId); } /** @@ -1468,336 +623,56 @@ export class KnowledgeService implements IKnowledgeService { * starts again. Never rejects for a registered source; throws for an * unknown one, as {@link reindexSource} does. */ - async rebuildSource( + rebuildSource( sourceId: string, opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, ): Promise { - const entry = this.requireEntry(sourceId); - if (this.held) throw heldSourcesError(this.held); - return this.rebuildOf(entry, opts); + return KnowledgeIndexingFacet.rebuildSource.call(knowledgeServiceHost.of(this), sourceId, opts); } - /** - * {@link rebuildSource} of one registered source. The record names the - * source by its face; the build's lock and this node's record of it are - * held under its index key, which no two sources share. - * - * The durable record (`knowledge-sync-state.ts`) is written once the build - * holds the lease and walks: its start, its counts at most every - * {@link BUILD_PROGRESS_LOG_INTERVAL_MS}, and its end, which lands before - * this resolves. A build that does not run (`not-run`) writes nothing: the - * row keeps the build that ran. `onStarted` is told once, with the record, - * when the walk began and its start is recorded, or when the build ended - * without walking. - */ - private async rebuildOf( + private rebuildOf( entry: KnowledgeSourceEntry, opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, ): Promise { - const running = this.builds.get(entry.key); - if (running?.status === 'running') { - const copy = cloneBuildRecord(running); - opts.onStarted?.(copy); - return copy; - } - const durable: DurableBuild = { chain: Promise.resolve() }; - try { - return await this.buildUnderLease(entry, opts, durable); - } finally { - await durable.chain; - if (durable.buildId !== undefined && this.runningBuildIds.get(entry.key) === durable.buildId) { - this.runningBuildIds.delete(entry.key); - } - } + return KnowledgeIndexingFacet.rebuildOf.call(knowledgeServiceHost.of(this), entry, opts); } - /** The body of {@link rebuildOf}; queues its durable writes on `durable.chain`. */ - private async buildUnderLease( + private buildUnderLease( entry: KnowledgeSourceEntry, opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, durable: DurableBuild, ): Promise { - const source = entry.handed; - const record: KnowledgeBuildRecord = { - sourceId: entry.face, - trigger: opts.trigger, - status: 'running', - startedAt: new Date().toISOString(), - progress: emptyBuildProgress(), - }; - this.builds.set(entry.key, record); - const logger = this.options.logger; - const label = `[knowledge] build of source '${entry.face}' (${opts.trigger})`; - let announced = false; - const announce = (): void => { - if (announced) return; - announced = true; - opts.onStarted?.(cloneBuildRecord(record)); - }; - const finish = ( - status: Exclude, - message: string | undefined, - result?: KnowledgeReindexResult, - ): KnowledgeBuildRecord => { - record.status = status; - record.finishedAt = new Date().toISOString(); - if (message !== undefined) record.message = message; - if (result !== undefined) record.result = result; - if (status !== 'not-run') this.recordBuildEnd(entry, record, durable); - announce(); - return cloneBuildRecord(record); - }; - - let lock: KnowledgeBuildLock | undefined; - try { - lock = this.options.resolveBuildLock?.(); - } catch (err) { - const message = `the cluster service could not be read (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; - logger?.warn(`${label}: ${message}`); - return finish('not-run', message); - } - let handle: KnowledgeBuildLockHandle | null = null; - if (lock) { - try { - handle = await lock.acquire(buildLockKey(entry.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); - } catch (err) { - const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; - logger?.warn(`${label}: ${message}`); - return finish('not-run', message); - } - if (!handle) { - const message = 'another node holds the build of this source; this node built nothing.'; - logger?.info?.(`${label}: ${message}`); - return finish('not-run', message); - } - } - const fence = startBuildFence({ - handle, - leaseMs: BUILD_LEASE_MS, - stallMs: BUILD_STALL_LIMIT_MS, - onRenewFailure: (err, held) => { - logger?.warn( - `${label}: the cluster lease could not be renewed (${errorText(err)}). ` + - (held - ? 'Renewal is retried; the build stops before its next page if the lease lapses.' - : 'The lease is lost; the build stops before its next page.'), - ); - }, - }); - try { - // This node holds the source's lease (or is the only node): a build the - // record still reads `running` is one whose node stopped. - await this.closeStaleBuild(entry); - if (opts.trigger === 'boot' || opts.trigger === 'reload') { - const reading = await this.readIndexStateOf(entry); - if (!reading.due) { - const message = `nothing to build once the lock was held: ${reading.detail}`; - logger?.info?.(`${label}: ${message}`); - return finish('not-run', message); - } - } - await this.recordBuildStart(entry, record, durable); - announce(); - logger?.info?.( - `${label} started: every row the source's where matches is read, and the content fields of each one the ` + - 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.', - ); - let lastLogged = Date.now(); - const walk = this.reindexWith(source, {}, (step) => { - // A walk the build stopped waiting on writes no progress into its ended record. - if (record.status !== 'running') return; - fence.progressed(); - record.progress = { ...step }; - const now = Date.now(); - if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return; - lastLogged = now; - logger?.info?.( - `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` + - `${step.skipped} unchanged, ${step.failed} cannot be indexed.`, - ); - this.recordBuildProgress(entry, record, durable); - }, fence); - // Cancelled at the stall bound: the walk is no longer waited on (it - // stops at its next page if the call it waits on ever answers). - walk.catch(() => undefined); - const raced = await Promise.race([walk, fence.cancelled.then((stop) => ({ stop }))]); - if ('stop' in raced) { - logger?.warn( - `${label} was cancelled: ${raced.stop.message} The adapter keeps what it held; ` + - 'the next reconcile, boot or operator rebuild builds again.', - ); - return finish(raced.stop.reason, raced.stop.message); - } - const result = raced; - record.progress = { - pages: record.progress.pages, - discovered: result.discovered, - indexed: result.indexed, - skipped: result.skipped ?? 0, - failed: result.failed ?? 0, - }; - const totals = - `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` + - `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`; - const stop = result.ok ? undefined : fence.stop(); - if (!result.ok) { - logger?.warn( - `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` + - 'The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.', - ); - return finish(stop?.reason ?? 'failed', result.message, result); - } - logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`); - return finish('done', result.message, result); - } catch (err) { - const message = `the build threw: ${operatorText(err)}`; - logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.`); - return finish('failed', message); - } finally { - fence.close(); - // The build's end lands before its lease is released, so a node that - // takes the lease next never reads this finished build as `running`. - await durable.chain; - if (handle) { - try { - await handle.release(); - } catch (err) { - // The lease still frees itself on its TTL; the build itself ran. - logger?.warn(`${label}: the cluster lock could not be released (${errorText(err)}); it frees itself when its lease ends.`); - } - } - } + return KnowledgeIndexingFacet.buildUnderLease.call(knowledgeServiceHost.of(this), entry, opts, durable); } // ── The durable sync state (`knowledge-sync-state.ts`) ──────────── - /** The source as its sync-state row names it. */ private syncStateIdentity(entry: KnowledgeSourceEntry): KnowledgeSyncStateIdentity { - const adapter = this.boundAdapterId(entry.handed); - return { - key: entry.key, - source: entry.face, - ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), - ...(adapter === undefined ? {} : { adapter }), - object: entry.handed.source.object, - }; + return KnowledgeIndexingFacet.syncStateIdentity.call(knowledgeServiceHost.of(this), entry); } - /** - * A sync-state write failed: the record no longer matches what happened, - * while everything else looks normal. Said once, at `error`, with what is - * lost and the fix; never thrown into the build or the sync it records. - */ private syncStateWriteFailed(what: string, err: unknown): void { - if (this.syncStateWriteReported) { - this.options.logger?.debug?.(`[knowledge] ${what} (${errorText(err)}).`); - return; - } - this.syncStateWriteReported = true; - const report = - `[knowledge] ${what} (${errorText(err)}): the source's sync state in sys_knowledge_sync_state (its last build ` + - 'and its failed syncs, what index_status and Setup show on every node) no longer says what happened, and ' + - 'nothing else looks wrong. Check that schema sync ran for sys_knowledge_sync_state on the default datasource; ' + - 'the next build rewrites the row. Said once; later failures are logged at debug.'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); + return KnowledgeIndexingFacet.syncStateWriteFailed.call(knowledgeServiceHost.of(this), what, err); } - /** The record's counts of a build record. */ private storedCounts(record: KnowledgeBuildRecord): KnowledgeStoredBuildCounts { - return { - pages: record.progress.pages, - discovered: record.progress.discovered, - indexed: record.progress.indexed, - skipped: record.progress.skipped, - purged: record.result?.purged ?? null, - failed: record.progress.failed, - }; + return KnowledgeIndexingFacet.storedCounts(record); } - /** Record a build's start; the build waits for it, so every node reads `running` once the walk begins. */ - private async recordBuildStart(entry: KnowledgeSourceEntry, record: KnowledgeBuildRecord, durable: DurableBuild): Promise { - const store = this.options.syncState; - if (!store) return; - const buildId = nextBuildId(); - durable.buildId = buildId; - this.runningBuildIds.set(entry.key, buildId); - try { - await store.startBuild(this.syncStateIdentity(entry), buildId, record.trigger, record.startedAt); - this.syncStateRecorded.add(entry.key); - } catch (err) { - this.syncStateWriteFailed(`the start of the build of source '${entry.face}' was not recorded`, err); - } + private recordBuildStart(entry: KnowledgeSourceEntry, record: KnowledgeBuildRecord, durable: DurableBuild): Promise { + return KnowledgeIndexingFacet.recordBuildStart.call(knowledgeServiceHost.of(this), entry, record, durable); } - /** Queue a running build's counts (the walk does not wait for it). */ private recordBuildProgress(entry: KnowledgeSourceEntry, record: KnowledgeBuildRecord, durable: DurableBuild): void { - const store = this.options.syncState; - const buildId = durable.buildId; - if (!store || buildId === undefined) return; - const counts = this.storedCounts(record); - durable.chain = durable.chain.then(async () => { - try { - await store.progressBuild(entry.key, buildId, counts); - } catch (err) { - this.syncStateWriteFailed(`the progress of the build of source '${entry.face}' was not recorded`, err); - } - }); + return KnowledgeIndexingFacet.recordBuildProgress.call(knowledgeServiceHost.of(this), entry, record, durable); } - /** Queue a build's end; {@link rebuildOf} resolves once it landed. */ private recordBuildEnd(entry: KnowledgeSourceEntry, record: KnowledgeBuildRecord, durable: DurableBuild): void { - const store = this.options.syncState; - const buildId = durable.buildId; - if (!store || buildId === undefined || record.status === 'running' || record.status === 'not-run') return; - const status = record.status; - const counts = this.storedCounts(record); - const finishedAt = record.finishedAt ?? new Date().toISOString(); - durable.chain = durable.chain.then(async () => { - try { - const landed = await store.finishBuild(entry.key, buildId, { - status, - finishedAt, - counts, - message: storedBuildMessage({ status, counts }), - }); - if (!landed) { - this.options.logger?.info?.( - `[knowledge] the end of the build of source '${entry.face}' (${status}) was not recorded: another build ` + - 'has taken the source over since, and the record keeps that one.', - ); - } - } catch (err) { - this.syncStateWriteFailed(`the end of the build of source '${entry.face}' was not recorded`, err); - } - }); + return KnowledgeIndexingFacet.recordBuildEnd.call(knowledgeServiceHost.of(this), entry, record, durable); } - /** - * Close the build the record reads `running` for `entry` as `interrupted`, - * when it is not one this node runs. Called by a node that holds the - * source's lease (or the only node), so no live build can be the one the - * record names. Never throws. - */ - private async closeStaleBuild(entry: KnowledgeSourceEntry): Promise { - const store = this.options.syncState; - if (!store) return false; - try { - const state = await store.read(entry.key); - if (state?.build?.status !== 'running' || state.buildId === undefined) return false; - if (this.runningBuildIds.get(entry.key) === state.buildId) return false; - const closed = await store.closeInterrupted(entry.key, state.buildId, new Date().toISOString()); - if (closed) { - this.options.logger?.info?.( - `[knowledge] source '${entry.face}': the ${state.build.trigger} build started ${state.build.startedAt} ` + - 'by a node that stopped before it ended is closed as interrupted.', - ); - } - return closed; - } catch (err) { - this.syncStateWriteFailed(`the interrupted build of source '${entry.face}' was not closed`, err); - return false; - } + private closeStaleBuild(entry: KnowledgeSourceEntry): Promise { + return KnowledgeIndexingFacet.closeStaleBuild.call(knowledgeServiceHost.of(this), entry); } /** @@ -1810,52 +685,8 @@ export class KnowledgeService implements IKnowledgeService { * previous process's. A row whose source is not registered here is closed * too: no node builds it. Answers how many were closed; never throws. */ - async closeInterruptedBuilds(): Promise { - const store = this.options.syncState; - if (!store) return 0; - let running: Awaited>; - try { - running = await store.runningBuilds(); - } catch (err) { - this.syncStateWriteFailed('the builds a stopped node left running could not be read at boot', err); - return 0; - } - let closed = 0; - for (const state of running) { - if (state.buildId === undefined) continue; - if (this.runningBuildIds.get(state.key) === state.buildId) continue; - let lock: KnowledgeBuildLock | undefined; - let handle: KnowledgeBuildLockHandle | null = null; - try { - lock = this.options.resolveBuildLock?.(); - if (lock) { - handle = await lock.acquire(buildLockKey(state.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); - if (!handle) continue; // A node is building it now. - } - } catch (err) { - // The lock, not the record: the build is left as it reads, and the - // next node that takes the source's lease closes it. - this.options.logger?.warn?.( - `[knowledge] the build of source '${state.source}' a stopped node may have left running was not closed at ` + - `boot: the cluster lock did not answer (${errorText(err)}). The next node that takes the source's build ` + - 'lease closes it.', - ); - continue; - } - try { - if (await store.closeInterrupted(state.key, state.buildId, new Date().toISOString())) closed++; - } catch (err) { - this.syncStateWriteFailed(`the interrupted build of source '${state.source}' was not closed at boot`, err); - } finally { - if (handle) await handle.release().catch(() => undefined); - } - } - if (closed > 0) { - this.options.logger?.info?.( - `[knowledge] ${closed} build(s) a stopped node left running are closed as interrupted in sys_knowledge_sync_state.`, - ); - } - return closed; + closeInterruptedBuilds(): Promise { + return KnowledgeIndexingFacet.closeInterruptedBuilds.call(knowledgeServiceHost.of(this)); } /** @@ -1863,23 +694,13 @@ export class KnowledgeService implements IKnowledgeService { * Setup lists every source, built or not. Rows this node has written are * not asked again. Never throws. */ - async recordSources(): Promise { - const store = this.options.syncState; - if (!store) return; - for (const entry of this.registry.entries()) { - if (this.syncStateRecorded.has(entry.key)) continue; - try { - await store.ensure(this.syncStateIdentity(entry)); - this.syncStateRecorded.add(entry.key); - } catch (err) { - this.syncStateWriteFailed(`the sync-state row of source '${entry.face}' could not be written`, err); - } - } + recordSources(): Promise { + return KnowledgeRecordSyncFacet.recordSources.call(knowledgeServiceHost.of(this)); } /** Whether each source's sync state is the durable record (`syncState` is wired), the same on every node. */ hasDurableSyncState(): boolean { - return this.options.syncState !== undefined; + return KnowledgeRecordSyncFacet.hasDurableSyncState.call(knowledgeServiceHost.of(this)); } /** @@ -1888,27 +709,8 @@ export class KnowledgeService implements IKnowledgeService { * the last build this node ran, and no failures. Throws when the record * cannot be read, and for an unknown source. */ - async syncStateOf(sourceId: string): Promise<{ build: KnowledgeStoredBuild | null; failures: KnowledgeSyncFailures }> { - const entry = this.requireEntry(sourceId); - const store = this.options.syncState; - if (store) { - const state = await store.read(entry.key); - return { build: state?.build ?? null, failures: state?.failures ?? { count: 0 } }; - } - const record = this.builds.get(entry.key); - if (!record || record.status === 'not-run') return { build: null, failures: { count: 0 } }; - const counts = this.storedCounts(record); - return { - build: { - trigger: record.trigger, - status: record.status, - startedAt: record.startedAt, - ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), - counts, - ...(record.status === 'running' ? {} : { message: storedBuildMessage({ status: record.status, counts }) }), - }, - failures: { count: 0 }, - }; + syncStateOf(sourceId: string): Promise<{ build: KnowledgeStoredBuild | null; failures: KnowledgeSyncFailures }> { + return KnowledgeRecordSyncFacet.syncStateOf.call(knowledgeServiceHost.of(this), sourceId); } /** @@ -1916,10 +718,8 @@ export class KnowledgeService implements IKnowledgeService { * source's together, read live. `undefined` while syncs run inline, or the * queue cannot count. Throws what the queue throws. */ - async pendingRecordSyncs(): Promise { - const view = this.recordSyncQueueView; - if (!view || typeof view.getQueueSize !== 'function') return undefined; - return view.getQueueSize(KNOWLEDGE_RECORD_SYNC_QUEUE); + pendingRecordSyncs(): Promise { + return KnowledgeRecordSyncFacet.pendingRecordSyncs.call(knowledgeServiceHost.of(this)); } /** @@ -1942,123 +742,20 @@ export class KnowledgeService implements IKnowledgeService { * outage heals without waiting for the daily run; later ones ask nothing. * A message whose source is gone counts nothing. Never rejects. */ - async recordSyncFailure(data: unknown, err: unknown, attempts: { attempt: number; maxAttempts: number }): Promise { - const message = readRecordSyncMessage(data); - if (!message) return; - const entry = this.registry.byIndexKey(message.source); - const store = this.options.syncState; - if (!entry || !store) return; - let written: Awaited>; - try { - written = await store.addFailure( - this.syncStateIdentity(entry), - new Date().toISOString(), - syncFailureText(message.recordId, attempts.attempt, attempts.maxAttempts, err), - ); - this.syncStateRecorded.add(entry.key); - } catch (writeErr) { - this.syncStateWriteFailed(`a failed sync of source '${entry.face}' was not counted`, writeErr); - return; - } - if (written.first) this.requestSourceReconcile(entry); + recordSyncFailure(data: unknown, err: unknown, attempts: { attempt: number; maxAttempts: number }): Promise { + return KnowledgeRecordSyncFacet.recordSyncFailure.call(knowledgeServiceHost.of(this), data, err, attempts); } - /** Ask for a reconcile of one source, as a predicate write does ({@link requestReconcile}). */ private requestSourceReconcile(entry: KnowledgeSourceEntry): void { - if (this.buildsStopped || this.reconcileExclusion(entry) !== undefined) return; - this.armReconcile(entry.key, Date.now()); - this.options.logger?.info?.( - `[knowledge] source '${entry.face}' has its first failed sync: a reconcile of it is asked for, and starts once ` + - 'the quiet period passes.', - ); + return KnowledgeRecordSyncFacet.requestSourceReconcile.call(knowledgeServiceHost.of(this), entry); } - /** - * After a reconcile of `entry` that completed: clear the failures that - * failed before its walk began (`walkStartedAt`), and remove their dead - * letters from the queue. The walk re-read every row, so they are repaired - * or no longer apply. A dead letter that failed during the walk stays, and - * is still counted. Read from the queue's dead letters where syncs run - * through it; where they do not, the failures are cleared only when the - * newest of them came before the walk. Never throws. - */ - private async clearRepairedFailures(entry: KnowledgeSourceEntry, walkStartedAt: string): Promise { - const store = this.options.syncState; - if (!store) return; - const walkStart = Date.parse(walkStartedAt); - const view = this.recordSyncQueueView; - try { - for (let attempt = 0; attempt < 4; attempt++) { - const state = await store.read(entry.key); - if (!state) return; - let remaining: string[] | undefined; - if (view && typeof view.listFailed === 'function') { - const letters = await this.deadLettersOf(entry.key, view); - const repaired = letters.filter((l) => l.at < walkStart); - if (typeof view.purgeFailed === 'function') { - for (const letter of repaired) { - try { - await view.purgeFailed(letter.id); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] source '${entry.face}': the repaired dead letter '${letter.id}' could not be removed ` + - `from queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (${errorText(err)}); it stays listed there.`, - ); - } - } - } - remaining = letters.filter((l) => l.at >= walkStart).map((l) => new Date(l.at).toISOString()).sort(); - } else { - const last = state.failures.lastFailedAt === undefined ? NaN : Date.parse(state.failures.lastFailedAt); - if (state.failures.count === 0 || !(last < walkStart)) return; - remaining = []; - } - if (remaining.length === 0 && state.failures.count === 0) return; - const landed = await store.setFailures(entry.key, state.failureCountStored, remaining.length === 0 - ? { count: 0 } - : { - count: remaining.length, - firstFailedAt: remaining[0], - ...(state.failures.lastFailedAt === undefined ? {} : { lastFailedAt: state.failures.lastFailedAt }), - ...(state.failures.lastError === undefined ? {} : { lastError: state.failures.lastError }), - }); - if (landed) { - this.options.logger?.info?.( - `[knowledge] source '${entry.face}': the reconcile repaired the syncs that failed before it began; ` + - `${remaining.length} failed during it and stay counted.`, - ); - return; - } - // A failure was counted meanwhile: read again. - } - } catch (err) { - this.syncStateWriteFailed(`the failures the reconcile of source '${entry.face}' repaired were not cleared`, err); - } + private clearRepairedFailures(entry: KnowledgeSourceEntry, walkStartedAt: string): Promise { + return KnowledgeRecordSyncFacet.clearRepairedFailures.call(knowledgeServiceHost.of(this), entry, walkStartedAt); } - /** - * Every dead letter on the record-sync queue that names the source under - * `key`, with when it failed, once each. - * - * Filtered here, not in the queue: `IQueueService.listFailed` takes a queue - * name and a page and no predicate, so no query can name the source. The - * pages are read by offset while letters may arrive, so a letter can be read - * on two pages; it is kept once, by its id. - */ - private async deadLettersOf(key: string, view: KnowledgeRecordSyncQueueView): Promise> { - const byId = new Map(); - const page = 500; - for (let offset = 0; offset < DEAD_LETTER_SCAN_MAX; offset += page) { - const letters = await view.listFailed!(KNOWLEDGE_RECORD_SYNC_QUEUE, { limit: page, offset }); - for (const letter of letters) { - const named = readRecordSyncMessage(letter.data)?.source ?? (letter.metadata as { source?: unknown } | undefined)?.source; - if (named !== key || byId.has(letter.id)) continue; - const at = Date.parse(String(letter.completedAt ?? letter.updatedAt ?? letter.createdAt)); - byId.set(letter.id, Number.isNaN(at) ? 0 : at); - } - if (letters.length < page) break; - } - return [...byId].map(([id, at]) => ({ id, at })); + private deadLettersOf(key: string, view: KnowledgeRecordSyncQueueView): Promise> { + return KnowledgeRecordSyncFacet.deadLettersOf(key, view); } /** @@ -2073,19 +770,8 @@ export class KnowledgeService implements IKnowledgeService { * Resolves when the pass is done; never rejects. Run in the * background by `KnowledgeServicePlugin`, so the boot never waits for it. */ - async buildSourcesAtBoot(): Promise { - if (this.held) return; - let entries: KnowledgeSourceEntry[]; - try { - entries = this.registry.entries(); - } catch (err) { - this.options.logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); - return; - } - for (const entry of entries) { - if (this.buildsStopped) return; - await this.buildIfDue(entry, 'boot'); - } + buildSourcesAtBoot(): Promise { + return KnowledgeIndexingFacet.buildSourcesAtBoot.call(knowledgeServiceHost.of(this)); } /** @@ -2095,47 +781,12 @@ export class KnowledgeService implements IKnowledgeService { * process runs (ADR-0161 K7, "What starts a rebuild": a source reload). * Never rejects; a key that holds no source is a no-op. */ - async buildReloadedSource(key: string): Promise { - const entry = this.registry.byIndexKey(key); - if (entry && !this.buildsStopped && !this.held) await this.buildIfDue(entry, 'reload'); + buildReloadedSource(key: string): Promise { + return KnowledgeIndexingFacet.buildReloadedSource.call(knowledgeServiceHost.of(this), key); } - /** One source of {@link buildSourcesAtBoot}. Never rejects. */ - private async buildIfDue(entry: KnowledgeSourceEntry, trigger: KnowledgeBuildTrigger): Promise { - const logger = this.options.logger; - const when = trigger === 'boot' ? 'at boot' : 'on reload'; - try { - if ((entry.authored.refresh?.onRecordChange ?? true) === false) { - logger?.debug?.(`[knowledge] source '${entry.face}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built ${when}.`); - return; - } - // A source whose adapter is not mounted is named once at boot, at - // `error`, by the boot's reading (`reportUnmountedAdapters`); the pass - // adds no second line for it. On reload no reading runs, so the line - // below is the one that names it. A source that names no adapter and - // cannot be placed is named by the same reading. - if (trigger === 'boot') { - const adapterId = this.boundAdapterId(entry.handed); - if (adapterId === undefined || !this.adapters.has(adapterId)) return; - } - const reading = await this.readIndexStateOf(entry); - if (reading.due) { - logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); - await this.rebuildOf(entry, { trigger }); - return; - } - const line = `[knowledge] source '${entry.face}' is not built ${when}: ${reading.detail}`; - // What cannot be seen or read is said once, at `warn` (K7: "the - // service says so once"); a source that is current, or whose adapter - // holds documents it reports no status for, is ordinary. - if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { - logger?.warn(line); - } else { - logger?.info?.(line); - } - } catch (err) { - logger?.warn(`[knowledge] source '${entry.face}': the build pass failed for it (${operatorText(err)}).`); - } + private buildIfDue(entry: KnowledgeSourceEntry, trigger: KnowledgeBuildTrigger): Promise { + return KnowledgeIndexingFacet.buildIfDue.call(knowledgeServiceHost.of(this), entry, trigger); } /** @@ -2144,8 +795,7 @@ export class KnowledgeService implements IKnowledgeService { * build already walking runs to its end. */ stopBuilds(): void { - this.buildsStopped = true; - for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); + return KnowledgeIndexingFacet.stopBuilds.call(knowledgeServiceHost.of(this)); } // ── The reconcile (ADR-0161 K1, K3 item 3) ─────────────────────── @@ -2187,119 +837,24 @@ export class KnowledgeService implements IKnowledgeService { * them); a name that resolves to no source is skipped. Never rejects; the * report names every walk that did not finish. */ - reconcileSources(opts: { sources?: string[] } = {}): Promise { - const names = opts.sources; - // Held, the pass walks nothing: no store is called while not enabled. - return this.enqueueReconcile(() => - this.held - ? [] - : names === undefined - ? this.registry.entries() - : names.map((name) => this.registry.resolve(name)).filter((e): e is KnowledgeSourceEntry => e !== undefined), - ); + reconcileSources(opts?: { sources?: string[] }): Promise { + return KnowledgeIndexingFacet.reconcileSources.call(knowledgeServiceHost.of(this), opts); } - /** Queue one reconcile pass over the entries `select` answers when its turn comes. */ private enqueueReconcile(select: () => KnowledgeSourceEntry[]): Promise { - const pass = this.reconcileTail.then(() => this.reconcilePass(select)); - this.reconcileTail = pass.then(() => undefined, () => undefined); - return pass; + return KnowledgeIndexingFacet.enqueueReconcile.call(knowledgeServiceHost.of(this), select); } - /** One pass of {@link reconcileSources}; runs after the pass before it. */ - private async reconcilePass(select: () => KnowledgeSourceEntry[]): Promise { - const startedAt = new Date().toISOString(); - const report: KnowledgeReconcileReport = { startedAt, finishedAt: startedAt, sources: [], unfinished: [] }; - let entries: KnowledgeSourceEntry[]; - try { - entries = select(); - } catch (err) { - this.options.logger?.warn(`[knowledge] the reconcile could not list the sources (${operatorText(err)}); none was reconciled.`); - report.unfinished.push({ sourceId: '*', status: 'failed', message: `the sources could not be listed (${operatorText(err)})` }); - report.finishedAt = new Date().toISOString(); - return report; - } - for (const entry of entries) { - if (this.buildsStopped) break; - // A source removed while the pass ran is not walked. - if (this.registry.byIndexKey(entry.key) !== entry) continue; - const done = await this.reconcileOf(entry); - report.sources.push(done); - const status = done.record?.status; - if (status === 'failed' || status === 'lease-lost' || status === 'timed-out') { - report.unfinished.push({ sourceId: entry.face, status, ...(done.record?.message === undefined ? {} : { message: done.record.message }) }); - } - } - report.finishedAt = new Date().toISOString(); - return report; + private reconcilePass(select: () => KnowledgeSourceEntry[]): Promise { + return KnowledgeIndexingFacet.reconcilePass.call(knowledgeServiceHost.of(this), select); } - /** One source of a reconcile pass. Never rejects. */ - private async reconcileOf(entry: KnowledgeSourceEntry): Promise { - const logger = this.options.logger; - const left = (why: string): KnowledgeReconcileEntry => ({ sourceId: entry.face, left: why }); - try { - const why = this.reconcileExclusion(entry); - if (why !== undefined) { - if (why.unlisted) { - if (!this.reconcileUnlistedReported.has(entry.key)) { - this.reconcileUnlistedReported.add(entry.key); - logger?.warn(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); - } - } else { - logger?.debug?.(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); - } - return left(why.text); - } - const reading = await this.readIndexStateOf(entry); - logger?.info?.( - reading.due - ? `[knowledge] source '${entry.face}' is built by the reconcile now: ${reading.detail}` - : `[knowledge] source '${entry.face}' is reconciled now (${reading.state}): ${reading.detail}`, - ); - const record = await this.rebuildOf(entry, { trigger: 'reconcile' }); - // [ADR-0161 K1] The reconcile is the failure count's reader: a walk that - // completed re-read every row, so the syncs that failed before it began - // are repaired or no longer apply. - if (record.status === 'done') await this.clearRepairedFailures(entry, record.startedAt); - return { sourceId: entry.face, record }; - } catch (err) { - const message = `the reconcile failed for it (${operatorText(err)}).`; - logger?.warn(`[knowledge] source '${entry.face}': ${message}`); - const now = new Date().toISOString(); - return { - sourceId: entry.face, - record: { sourceId: entry.face, trigger: 'reconcile', status: 'failed', startedAt: now, finishedAt: now, progress: emptyBuildProgress(), message }, - }; - } + private reconcileOf(entry: KnowledgeSourceEntry): Promise { + return KnowledgeIndexingFacet.reconcileOf.call(knowledgeServiceHost.of(this), entry); } - /** - * Why the reconcile does not walk `entry`, or `undefined` when it does. - * `unlisted` marks the one exclusion said at `warn`: a store that lists no - * documents. An adapter that is not mounted is walked, so its build fails - * and names it. - */ private reconcileExclusion(entry: KnowledgeSourceEntry): { text: string; unlisted: boolean } | undefined { - if ((entry.authored.refresh?.onRecordChange ?? true) === false) { - return { text: 'refresh.onRecordChange is false, so an external indexer owns its index.', unlisted: false }; - } - if (!this.options.dataEngine) { - return { text: 'no data engine is bound, so the source cannot be walked.', unlisted: false }; - } - const adapterId = this.boundAdapterId(entry.handed); - const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); - if (adapter && typeof adapter.listDocuments !== 'function') { - return { - text: - `its adapter '${adapter.id}' does not list its documents (no listDocuments), so a walk could neither skip ` + - 'an unchanged document nor purge a stale one: it would send every document to the embedding provider again ' + - 'and remove nothing. Rows deleted or changed without an event stay as they are in its index until an ' + - 'operator rebuild (os knowledge rebuild).', - unlisted: true, - }; - } - return undefined; + return KnowledgeIndexingFacet.reconcileExclusion.call(knowledgeServiceHost.of(this), entry); } /** @@ -2316,53 +871,15 @@ export class KnowledgeService implements IKnowledgeService { * owns is in neither. */ requestReconcile(object: string): KnowledgeReconcileRequest { - const request: KnowledgeReconcileRequest = { scheduled: [], unreconcilable: [] }; - if (this.buildsStopped || this.held) return request; - for (const entry of this.registry.entries()) { - if (entry.handed.source.object !== object) continue; - const why = this.reconcileExclusion(entry); - if (why !== undefined) { - // An external indexer's index is not this service's to call stale. - if (why.unlisted || !this.options.dataEngine) request.unreconcilable.push(entry.face); - continue; - } - this.armReconcile(entry.key, Date.now()); - request.scheduled.push(entry.face); - } - return request; + return KnowledgeIndexingFacet.requestReconcile.call(knowledgeServiceHost.of(this), object); } - /** (Re)arm the pending reconcile of the source under `key`; `now` is when the request arrived. */ private armReconcile(key: string, now: number): void { - const pending = this.pendingReconciles.get(key); - const firstAt = pending?.firstAt ?? now; - if (pending) clearTimeout(pending.timer); - const wait = Math.max(0, Math.min(RECONCILE_QUIET_MS, firstAt + RECONCILE_MAX_WAIT_MS - now)); - const timer = setTimeout(() => { - this.pendingReconciles.delete(key); - const entry = this.registry.byIndexKey(key); - if (!entry || this.buildsStopped || this.held) return; - // A build of the source running now may have read past the rows the - // write changed: wait for it, then walk again. - if (this.builds.get(key)?.status === 'running') { - this.armReconcile(key, Date.now()); - return; - } - void this.enqueueReconcile(() => { - const current = this.registry.byIndexKey(key); - return current === undefined ? [] : [current]; - }).catch(() => undefined); - }, wait); - (timer as { unref?: () => void }).unref?.(); - this.pendingReconciles.set(key, { timer, firstAt }); + return KnowledgeIndexingFacet.armReconcile.call(knowledgeServiceHost.of(this), key, now); } - /** Drop the pending reconcile of the source under `key`, if any. */ private cancelPendingReconcile(key: string): void { - const pending = this.pendingReconciles.get(key); - if (!pending) return; - clearTimeout(pending.timer); - this.pendingReconciles.delete(key); + return KnowledgeIndexingFacet.cancelPendingReconcile.call(knowledgeServiceHost.of(this), key); } // ── The `search_knowledge` AI tool (ADR-0149 D2) ────────────────── @@ -2475,8 +992,8 @@ export class KnowledgeService implements IKnowledgeService { * caller that must name them to its own caller (the `search_knowledge` tool) * reads {@link searchWithRefusals}. */ - async search(query: string, opts: KnowledgeSearchOptions = {}): Promise { - return (await this.searchWithRefusals(query, opts)).hits; + search(query: string, opts?: KnowledgeSearchOptions): Promise { + return KnowledgeSearchFacet.search.call(knowledgeServiceHost.of(this), query, opts); } /** @@ -2486,15 +1003,8 @@ export class KnowledgeService implements IKnowledgeService { * refused (the call refused whole, ADR-0161 K7, rule 5); the thrown error's * `refused` lists them all. */ - async searchWithRefusals(query: string, opts: KnowledgeSearchOptions = {}): Promise { - // [ADR-0161 K8, the dated note on item 12] Held: refused, never answered - // empty (K7 rule 5), naming the half that is missing. - if (this.held) throw heldSourcesError(this.held); - const report = await this.searchByKey(query, opts); - return { - hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), - refused: this.facedRefusals(report.refused), - }; + searchWithRefusals(query: string, opts?: KnowledgeSearchOptions): Promise { + return KnowledgeSearchFacet.searchWithRefusals.call(knowledgeServiceHost.of(this), query, opts); } /** The refusals of a search, each source named by its face. */ @@ -2502,911 +1012,102 @@ export class KnowledgeService implements IKnowledgeService { return refused.map((r) => ({ ...r, sourceId: this.faceOfKey(r.sourceId) })); } - /** - * {@link searchWithRefusals} with every source named by its index key, as - * an adapter's hit names it; the public member translates each to its face. - * A whole refusal thrown from here already names the sources by face. - */ - private async searchByKey(query: string, opts: KnowledgeSearchOptions): Promise { - const scope = readSearchScope(opts.scope); - const topK = opts.topK ?? this.defaultTopK; - const groupBy = opts.groupBy; - if (groupBy !== undefined) { - if (typeof groupBy !== 'string' || groupBy.length === 0) { - throw refusal('VALIDATION_ERROR', 400, '[knowledge] search groupBy must name a metadata field (a non-empty string).'); - } - if (opts.granularity === 'chunk') { - throw refusal( - 'VALIDATION_ERROR', - 400, - `[knowledge] search groupBy ${quotedName(groupBy)} groups records, so it cannot be combined with granularity 'chunk'. ` + - "Drop granularity, or pass granularity 'record'.", - ); - } - } - if (opts.granularity !== undefined && opts.granularity !== 'chunk' && opts.granularity !== 'record') { - throw refusal( - 'VALIDATION_ERROR', - 400, - `[knowledge] search granularity must be 'chunk' or 'record', got '${String(opts.granularity)}'.`, - ); - } - const byRecord = opts.granularity === 'record' || groupBy !== undefined; - const ctx = opts.executionContext; - let admitted: Array = - await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); - if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); - if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); - const engine = this.options.dataEngine; - const filtered = ctx !== undefined && ctx.isSystem !== true && engine !== undefined; - // A caller the re-check can remove hits for: each source ranks only the - // records they may read, when those are few enough to name. - if (filtered && admitted.length > 0) admitted = await this.sourcesNarrowedToVisible(admitted, ctx, engine); - if (admitted.length === 0) return { hits: [], refused: [] }; - const refused: KnowledgeSearchRefusal[] = []; - const sources = await this.planSearches(admitted, refused); - // The sources whose every hit is checked against its live record before - // it is served: the ones the earlier title rule could serve a field for. - const verified = new Set(sources.filter((target) => target.verifyHits === true).map((target) => target.source.name)); - const served = async (hits: KnowledgeHit[]): Promise => - verified.size === 0 ? hits : this.dropUnverifiedHits(hits, verified); - - const widened = byRecord || filtered; - const firstAsk = (_source: KnowledgeSource): number => - widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; - const groupOf = byRecord - ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) - : recordKeyOf; - const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); - if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); - const raw = [...first.values()].flatMap((answer) => answer.hits); - let kept = await served(await this.applyPermissionFilter(raw, ctx, byRecord)); - let removed = raw.length - kept.length; - - if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { - const saturated = sources.filter(({ source }) => { - const answer = first.get(source.name); - return widened && answer !== undefined && answer.answered >= firstAsk(source); - }); - if (saturated.length > 0) { - const refusedBefore = refused.length; - const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); - // A refilled source's second answer is a superset of its first: its - // first-round survivors are dropped and the whole answer re-checked. - const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); - const refilledKept = await served(await this.applyPermissionFilter(refilledHits, ctx, byRecord)); - const firstRaw = raw.filter((hit) => refill.has(hit.sourceId)).length; - const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; - kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; - removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); - // A source that refused the refill (its index changed between the two - // rounds) is refused for the whole search: its first-round hits are - // dropped, so no source is both answered and named as refused. - const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); - if (refusedInRefill.size > 0) { - kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); - if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(this.facedRefusals(refused)); - } - } - } - - if (removed > 0) { - this.options.logger?.debug?.( - `[knowledge] the permission re-check and the per-hit record check removed ${removed} hit(s); ` + - `${Math.min(byRecord ? distinctGroups(kept, groupOf) : kept.length, topK)} of topK=${topK} answered.`, - ); - } - kept.sort((a, b) => b.score - a.score); - // [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} ` + - `${groupBy === undefined ? 'records' : `${quotedName(groupBy)} groups`}: no more within the refill cap ` + - `(topK × ${SEARCH_REFILL_FACTOR} passages per source).`, - ); - } - return { hits: answer, refused }; + private searchByKey(query: string, opts: KnowledgeSearchOptions): Promise { + return KnowledgeSearchFacet.searchByKey.call(knowledgeServiceHost.of(this), query, opts); } - /** - * The sources a `groupBy` search asks: each source that lists `groupBy` in - * its `metadataFields`. Any other source answers no hits for this search — - * its hits carry no group value, and a hit is never answered ungrouped. - */ private sourcesGroupableBy(sources: T[], groupBy: string): T[] { - return sources.filter(({ source }) => { - if ((source.source.metadataFields ?? []).includes(groupBy)) return true; - this.options.logger?.debug?.( - `[knowledge] source '${this.label(source)}' not searched for groupBy ${quotedName(groupBy)}: ` + - 'the field is not one of its metadataFields.', - ); - return false; - }); + return (KnowledgeSearchFacet.sourcesGroupableBy).call(knowledgeServiceHost.of(this), sources, groupBy); } - /** - * The group a hit falls in under record granularity: with `groupBy`, the - * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — - * when the hit carries none); without it, the parent record its source's - * `documentBy` names, else the hit's record ({@link documentKeyOf}). - */ private groupKeyOf(hit: KnowledgeHit, groupBy: string | undefined): string | undefined { - if (groupBy === undefined) return documentKeyOf(hit, this.handed(hit.sourceId)?.source.documentBy); - const value = hit.metadata?.[groupBy]; - if (value === undefined || value === null || value === '') return undefined; - return `value:${stableJson(value)}`; + return KnowledgeSearchFacet.groupKeyOf.call(knowledgeServiceHost.of(this), hit, groupBy); } - /** - * [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( + private 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; - }; + return KnowledgeSearchFacet.affinityOrderFor.call(knowledgeServiceHost.of(this), kept, ctx); } - /** 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.', - ); - }, - ); + private affinityFactsOf(ctx: ExecutionContext, declaring: readonly KnowledgeSource[]): Promise { + return KnowledgeSearchFacet.affinityFactsOf.call(knowledgeServiceHost.of(this), ctx, declaring); } - /** - * The record-level answer: one hit per group, the group's best passage, - * 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 - * - * The index is a copy, and a record may have changed since it was indexed. - * So each `object`-source hit about to be answered is checked against its - * record as it reads now — one system-context read per source, of the hits' - * records only (at most `topK`), `{ $and: [where, { id: { $in } }] }` - * projected to the fields assembly reads. A record that no longer exists or - * no longer matches `where`, or whose recomputed `docHash` differs from the - * hit's (the stored hash), is dropped — all of its passages — and its - * document repaired in the background ({@link repairStale}) unless the source - * opted out of the event sync (`refresh.onRecordChange: false`: an external - * indexer owns that index, so the service writes nothing to it and the hit - * is only dropped). A group whose - * lead was dropped falls back to its next passage, and the next groups move - * up; that is checked again, at most `SEARCH_FRESHNESS_ROUNDS` times, after - * which a hit still unchecked is not answered (`capped`, logged at `debug` - * by its own line). A hit whose adapter stores no - * hash is checked for membership only. A read that fails drops that - * source's checked hits (fail-closed), reported at `warn`. - * - * Not checked: a hit without a record id, and every hit when no data engine - * is bound. - */ - private async answerByRecord( + private answerByRecord( hits: KnowledgeHit[], topK: number, groupOf: (hit: KnowledgeHit) => string | undefined, - order: (units: KnowledgeHit[]) => KnowledgeHit[] = (units) => units, + order?: (units: KnowledgeHit[]) => KnowledgeHit[], ): Promise<{ hits: KnowledgeHit[]; capped: boolean }> { - const groups = new Map(); - for (const hit of hits) { - const key = groupOf(hit); - if (key === undefined) continue; - const members = groups.get(key); - if (members) members.push(hit); - else groups.set(key, [hit]); - } - const engine = this.options.dataEngine; - const checkKey = (hit: KnowledgeHit): string | undefined => - engine !== undefined && hit.sourceRecordId !== undefined && this.handed(hit.sourceId) !== undefined - ? `${hit.sourceId}#${hit.sourceRecordId}` - : undefined; - const fresh = new Set(); - const stale = new Set(); - const leads = (): KnowledgeHit[] => { - const out: KnowledgeHit[] = []; - for (const members of groups.values()) { - const lead = members.find((hit) => { - const key = checkKey(hit); - return key === undefined || !stale.has(key); - }); - if (lead) out.push(lead); - } - // 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(); - const unchecked = top.filter((hit) => { - const key = checkKey(hit); - return key !== undefined && !fresh.has(key); - }); - if (unchecked.length === 0) return { hits: top, capped: false }; - if (round === SEARCH_FRESHNESS_ROUNDS) { - this.options.logger?.debug?.( - `[knowledge] record-level search stopped checking freshness after ${SEARCH_FRESHNESS_ROUNDS} rounds; ` + - `${unchecked.length} unchecked hit(s) not answered.`, - ); - return { hits: top.filter((hit) => !unchecked.includes(hit)), capped: true }; - } - await this.checkFreshness(unchecked, fresh, stale); - } + return KnowledgeSearchFacet.answerByRecord.call(knowledgeServiceHost.of(this), hits, topK, groupOf, order); } - /** - * One round of the freshness check ({@link answerByRecord}): read the - * records `hits` name, one system-context read per source, and sort each - * record into `fresh` or `stale` (`sourceId#recordId`). - */ - private async checkFreshness(hits: KnowledgeHit[], fresh: Set, stale: Set): Promise { - const engine = this.options.dataEngine; - if (!engine) return; - const bySource = new Map>(); - for (const hit of hits) { - const records = bySource.get(hit.sourceId) ?? new Map(); - if (!records.has(hit.sourceRecordId!)) records.set(hit.sourceRecordId!, hit); - bySource.set(hit.sourceId, records); - } - let posture: { value: TenancyPosture | undefined } | null | undefined; - for (const [sourceId, records] of bySource) { - const source = this.handed(sourceId)!; - const objSource = source.source; - const ids = [...records.keys()]; - const byId = { id: { $in: ids } }; - const schema = this.schemaFor(objSource.object); - let rows: unknown; - try { - if (posture === undefined) { - try { - posture = { value: await this.readTenancyPosture() }; - } catch (err) { - posture = null; - this.options.logger?.warn?.( - `[knowledge] the tenancy posture could not be read (${errorText(err)}); the freshness check of this ` + - 'search compares no document hash, only whether each record still belongs to its source.', - ); - } - } - const fields = freshnessFields(objSource, schema, posture?.value); - rows = await engine.find( - objSource.object, - { - where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, - ...(fields === undefined ? {} : { fields }), - }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) { - throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); - } - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the freshness check of source '${sourceId}' could not read its records ` + - `(${errorText(err)}); its hits are not answered.`, - ); - for (const id of ids) stale.add(`${sourceId}#${id}`); - continue; - } - const byRow = new Map>(); - for (const row of rows as Array | null | undefined>) { - if (row && isRecordId(row.id)) byRow.set(String(row.id), row); - } - for (const [recordId, hit] of records) { - const key = `${sourceId}#${recordId}`; - const docId = documentIdFor(sourceId, recordId); - const row = byRow.get(recordId); - const changed = - row !== undefined && - hit.docHash !== undefined && - posture !== null && - recordToDocument(source, objSource, row, schema, posture?.value).docHash !== hit.docHash; - if (row === undefined || changed) { - stale.add(key); - this.repairStale(source, objSource, recordId); - } else { - fresh.add(key); - if (hit.docHash !== undefined && posture !== null) this.freshnessRepairs.delete(docId); - } - } - } + private checkFreshness(hits: KnowledgeHit[], fresh: Set, stale: Set): Promise { + return KnowledgeSearchFacet.checkFreshness.call(knowledgeServiceHost.of(this), hits, fresh, stale); } - /** - * The hits of `verified` sources whose stored document is the one the - * current recipe assembles from the record as it reads now; every other hit - * of those sources is dropped. A hit of any other source passes untouched. - * - * Why: a source the earlier title rule could serve a field for - * (`mayServeEarlierRuleTitle`) is searched without the field gate's former - * `title` arm, and its index may still hold a document assembled under - * another recipe: one a build walked past and did not purge (a store with - * no `listDocuments`, `refresh.onRecordChange: false`, a purge candidate - * kept or listed under a foreign id), or one written between two builds - * while the object's display field was another field. The recipe hash - * cannot see either; this check reads the record. A hit survives only when - * its record still belongs to the source (one system read per source, - * `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly - * reads), its document id is the one the source derives from that record, - * and the `docHash` the store holds equals the one {@link recordToDocument} - * computes from the row under the current object definition (the title is - * part of it). Strict, unlike {@link checkFreshness}: a hit with no record - * id or no stored hash, a read that fails or answers no list, a posture - * that cannot be read and a hash that cannot be computed each drop the hit. - * - * The read decides only whether a hit survives: a surviving hit is returned - * as the store answered it, and nothing the read returned is put on it. A - * stale record's document is repaired in the background ({@link - * repairStale}), as the record-level check repairs it. - */ - private async dropUnverifiedHits(hits: KnowledgeHit[], verified: ReadonlySet): Promise { - const engine = this.options.dataEngine; - const checked = hits.filter((hit) => verified.has(hit.sourceId)); - if (checked.length === 0) return hits; - const passed = new Set(); - const dropped = (sourceId: string, count: number, why: string): void => { - if (count > 0) { - this.options.logger?.debug?.( - `[knowledge] ${count} hit(s) of source '${this.faceOfKey(sourceId)}' not served: ${why}`, - ); - } - }; - let posture: TenancyPosture | undefined; - let postureRead = true; - try { - posture = await this.readTenancyPosture(); - } catch (err) { - postureRead = false; - this.options.logger?.warn?.( - `[knowledge] the tenancy posture could not be read (${errorText(err)}); no hit of a source checked against its ` + - 'record is served this search (fail-closed).', - ); - } - const bySource = new Map(); - for (const hit of checked) bySource.set(hit.sourceId, [...(bySource.get(hit.sourceId) ?? []), hit]); - for (const [sourceId, sourceHits] of bySource) { - const source = this.handed(sourceId); - if (!engine || !postureRead || !source || source.source.kind !== 'object') { - dropped(sourceId, sourceHits.length, 'their records cannot be read to check them.'); - continue; - } - const objSource = source.source; - const usable = sourceHits.filter( - (hit) => isRecordId(hit.sourceRecordId) && typeof hit.docHash === 'string' && hit.docHash !== '', - ); - dropped(sourceId, sourceHits.length - usable.length, 'a hit names no record or carries no stored hash.'); - if (usable.length === 0) continue; - const ids = [...new Set(usable.map((hit) => String(hit.sourceRecordId)))]; - const byId = { id: { $in: ids } }; - const schema = this.schemaFor(objSource.object); - let rows: unknown; - try { - const fields = freshnessFields(objSource, schema, posture); - rows = await engine.find( - objSource.object, - { - where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, - ...(fields === undefined ? {} : { fields }), - }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the records of source '${this.faceOfKey(sourceId)}' could not be read to check its hits ` + - `(${errorText(err)}); none is served (fail-closed).`, - ); - continue; - } - const byRow = new Map>(); - for (const row of rows as Array | null | undefined>) { - if (row && isRecordId(row.id)) byRow.set(String(row.id), row); - } - const current = new Map(); - for (const hit of usable) { - const recordId = String(hit.sourceRecordId); - if (hit.documentId !== documentIdFor(sourceId, recordId)) continue; - if (!current.has(recordId)) { - const row = byRow.get(recordId); - let hash: string | undefined; - if (row !== undefined) { - try { - hash = recordToDocument(source, objSource, row, schema, posture).docHash; - } catch { - hash = undefined; - } - } - current.set(recordId, hash); - if (row === undefined || (hash !== undefined && hash !== hit.docHash)) this.repairStale(source, objSource, recordId); - } - const hash = current.get(recordId); - if (hash !== undefined && hash === hit.docHash) { - passed.add(hit); - this.freshnessRepairs.delete(documentIdFor(sourceId, recordId)); - } - } - dropped( - sourceId, - usable.filter((hit) => !passed.has(hit)).length, - 'the record no longer belongs to the source, or the stored document is not the one the current recipe assembles from it.', - ); - } - return hits.filter((hit) => !verified.has(hit.sourceId) || passed.has(hit)); + private dropUnverifiedHits(hits: KnowledgeHit[], verified: ReadonlySet): Promise { + return KnowledgeSearchFacet.dropUnverifiedHits.call(knowledgeServiceHost.of(this), hits, verified); } - /** - * Repair the document of a record the freshness check found stale: the - * event sync's own path ({@link syncRecord}, serialized per document), run - * in system context, in this process and NOT awaited — the search that found - * it answers without it. Single-flight per document, and at most once per - * document until a later search finds its hash matching. Never throws into - * the search. The scheduled reconcile does not take it over: the reconcile - * walks whole sources, and this repairs one document now. That is the - * inline path. - * - * While record syncs run through the queue ({@link routeRecordSyncs}) the - * repair is a record-sync message with reason `freshness`, for this source - * alone: it survives a restart of the process that searched and is retried - * like any other sync. A message that could not be published is reported - * at `error` and the document is left to the next search that finds it - * stale. - * - * A source with `refresh.onRecordChange: false` is never repaired: it is - * asked through {@link objectSourcesFor}, the one predicate that keeps the - * service's writes out of a source an external indexer owns, so the stale - * hit is dropped from the answer and its index entry left to that indexer. - */ private repairStale(source: KnowledgeSource, objSource: ObjectKnowledgeSource, recordId: string): void { - if (objectSourcesFor([source], objSource.object).length === 0) return; - const docId = documentIdFor(source.name, recordId); - if (this.freshnessRepairs.has(docId)) return; - this.freshnessRepairs.add(docId); - if (this.recordSyncPublisher) { - this.publishRecordSyncs([source], objSource.object, recordId, 'freshness', () => this.freshnessRepairs.delete(docId)); - return; - } - void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); + return KnowledgeSearchFacet.repairStale.call(knowledgeServiceHost.of(this), source, objSource, recordId); } - /** - * Each admitted source paired with the adapter it binds to, resolved here - * once for the whole search, and the fingerprint its search carries - * ({@link planIndex}); a source whose adapter does not resolve carries the - * coded refusal instead and is refused by the round, never searched. - * - * A source admitted with `proveIndex` ({@link admitSources}) is searched - * only when its index is proven built under the current recipe - * ({@link unprovenIndex}); otherwise it is not searched and is added to - * `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), the operator told why at - * `warn`. Each says whether a rebuild ends the refusal: for a source no - * build can prove, neither promises one. The boot's build pass, a reload, - * the reconcile and the operator's rebuild are what build a source; a - * search never starts a build. - */ - private async planSearches( + private planSearches( admitted: Array, refused: KnowledgeSearchRefusal[], ): Promise { - const out: SearchTarget[] = []; - // The settings page's chunk target, read at most once for the whole search. - let target: Promise | undefined; - const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); - for (const { proveIndex, ...entry } of admitted) { - // The adapter is resolved here, once per search: the proof below is read - // from this instance and both rounds search this instance, so a source - // cannot change binding between the check and the use. - let adapterId: string; - let adapter: IKnowledgeAdapter; - try { - adapterId = this.adapterIdFor(entry.source); - adapter = this.getAdapter(adapterId); - } catch (err) { - // Refused like an adapter that cannot serve, as the round refuses it; a - // source that needs the index proof is never searched without it. - out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); - continue; - } - const plan = await this.planIndex(entry.source, adapter, chunkTarget); - if (proveIndex === true) { - const unproven = await this.unprovenIndex(plan); - if (unproven !== undefined) { - const label = this.label(entry.source); - refused.push({ - sourceId: entry.source.name, - code: INDEX_NOT_PROVEN_CODE, - status: 409, - message: `Knowledge source '${label}' is not searched: its index is not proven built under the current recipe. ` + - UNPROVEN_CALLER_TEXT[unproven.ends], - }); - this.options.logger?.warn?.( - `[knowledge] source '${label}' not searched (${INDEX_NOT_PROVEN_CODE}): ${unproven.why} Its object declares ` + - "a field named 'title' the source does not serve, and a document indexed under the earlier title rule " + - "carries that field's value, so the source is searched only once its index is proven built under the " + - `current recipe. ${UNPROVEN_OPERATOR_TEXT[unproven.ends]}`, - ); - continue; - } - } - out.push({ - ...entry, - binding: { adapterId, adapter }, - fingerprint: plan.index.fingerprint, - ...(proveIndex === true ? { verifyHits: true as const } : {}), - }); - } - return out; + return KnowledgeSearchFacet.planSearches.call(knowledgeServiceHost.of(this), admitted, refused); } - /** - * Why `plan`'s source is not proven built under the current recipe, and - * what ends it, or `undefined` when it is proven: its adapter's - * `indexStatus` reports the fingerprint AND the recipe hash - * {@link planIndex} computes now, and the builds that record that hash - * purge what they did not walk. - * - * The recipe hash names the title rule (ADR-0161 K7), and an adapter - * records it only at `completeBuild`, the end of a complete build. A - * complete build rewrites every document whose title changed (`docHash` - * covers the title) and, when it purges, removes every document it did not - * walk. It does not purge, and still records the hash, for a source with - * `refresh.onRecordChange: false` and on an adapter with no - * `listDocuments` ({@link walkObjectSource}): a document it did not walk, - * such as one whose row left the source's `where`, keeps what it was - * assembled with. So those two shapes are never proven, before any read, - * whatever the hash reads; nor is an adapter with no `indexStatus` (nothing - * to read) or no `completeBuild` (nothing ever records a hash). - * - * The proof covers what the last complete build walked and purged. Read on - * every search that needs it, never cached: another node may rebuild, or - * drop, the index. Fails closed: a status that throws is not proven. - */ - private async unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { - const { adapter, index, source } = plan; - if ((source.refresh?.onRecordChange ?? true) === false) { - return { - ends: 'never', - why: - 'refresh.onRecordChange is false, so an external indexer owns its index: a build of it purges nothing, ' + - 'so a recorded recipe hash does not prove the index holds no document assembled under an earlier recipe.', - }; - } - if (typeof adapter.indexStatus !== 'function') { - return { - ends: 'never', - why: `the adapter '${adapter.id}' reports no index status (no indexStatus), so what its index was built under cannot be read.`, - }; - } - if (typeof adapter.completeBuild !== 'function') { - return { - ends: 'never', - why: `the adapter '${adapter.id}' has no completeBuild, so no build records a recipe hash for its index.`, - }; - } - if (typeof adapter.listDocuments !== 'function') { - return { - ends: 'never', - why: - `the adapter '${adapter.id}' does not list its documents (no listDocuments), so a complete build cannot purge a ` + - 'document it did not walk, and a recorded recipe hash does not prove the index holds none assembled under an ' + - 'earlier recipe.', - }; - } - let held: AdapterIndexStatus; - try { - held = await adapter.indexStatus(plan.context('search')); - } catch (err) { - return { ends: 'unreadable', why: `the adapter's index status could not be read (${operatorText(err)}).` }; - } - if (held?.fingerprint !== index.fingerprint) { - return { ends: 'rebuild', why: 'the index holds no complete build under the current fingerprint.' }; - } - if (held.recipeHash !== index.recipeHash) { - return { - ends: 'rebuild', - why: held.recipeHash === undefined - ? 'the index records no recipe hash: no complete build of it has completed.' - : "the index was last completed under another recipe (the source's where, metadataFields, title rule or withheld fields).", - }; - } - return undefined; + private unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { + return KnowledgeSearchFacet.unprovenIndex(plan); } - /** - * One round of {@link search}: ask each source's adapter for `ask(source)` - * hits. Answers, per source that answered, the hits it serves and how many - * the adapter returned (`answered`, before a hit naming another source or - * outside the scope is dropped — what decides whether the adapter may hold - * more). A source whose adapter is unknown or throws is absent from the - * answer: a coded refusal (ADR-0112 `code` and `status`) is added to - * `refused`, anything else is logged. - * - * Under a scope, the adapter is handed the source's terms, and every hit it - * answers is checked against them ({@link scopeCheck}, fail closed). The first - * time the check drops a hit of an adapter, that is reported once for the - * adapter, at `warn`: it does not apply the scope before ranking, or answers - * hits without the document's metadata, so its scoped searches may answer - * fewer than `topK` (ADR-0161 K8, rule 2). How many hits were dropped is - * logged, never returned. - */ - private async searchRound( + private searchRound( query: string, sources: SearchTarget[], ask: (source: KnowledgeSource) => number, filter: Record | undefined, refused: KnowledgeSearchRefusal[], ): Promise> { - const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding } of sources) { - // Refused like an adapter that cannot serve: the caller is told which - // source was not searched and why; the boot said so at `error` - // (`reportUnmountedAdapters`), so no line per search. The adapter was - // resolved once for the whole search ({@link planSearches}); a round - // searches that instance and never looks it up again. - if ('refusal' in binding) { - if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); - continue; - } - const { adapterId, adapter } = binding; - try { - const hits = await adapter.search(query, { - source, - topK: ask(source), - filter, - ...(organizationIds === undefined ? {} : { organizationIds }), - ...(fingerprint === undefined ? {} : { index: { fingerprint } }), - ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), - }); - // A hit is served as the source it was searched for. One whose - // `sourceId` names another source (an adapter answering from a store - // two sources share) is dropped: that source's admission was never - // asked for this hit, so serving it would skip the gates above. - const served: KnowledgeHit[] = []; - for (const hit of hits) if (hit.sourceId === source.name) served.push(hit); - const foreign = hits.length - served.length; - if (foreign > 0) { - this.options.logger?.warn?.( - `[knowledge] adapter '${adapterId}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + - 'another source; dropped — a hit is served only as the source it was searched for.', - ); - } - out.set(source.name, { - hits: scope === undefined ? served : this.checkScope(served, scope, source, adapterId), - answered: hits.length, - }); - } catch (err) { - const coded = codedRefusalOf(err); - if (coded !== undefined) { - // The caller reads the code and the adapter's one-sentence message; - // the operator reads its remedy (the SQL to run, say) here. - refused.push({ sourceId: source.name, ...coded }); - this.options.logger?.warn?.( - `[knowledge] source '${this.label(source)}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, - ); - continue; - } - this.options.logger?.error?.( - `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, - ); - } - } - return out; + return KnowledgeSearchFacet.searchRound.call(knowledgeServiceHost.of(this), query, sources, ask, filter, refused); } - /** - * [ADR-0161 K8, item 17] Pair each admitted source with the terms `scope` - * gives it ({@link scopeTermsFor}): a `record` term for an entry naming the - * object the source indexes, a `metadata` term for an entry naming a parent - * object the source reaches through the one parent link it lists in - * `metadataFields`, read from the object's registered definition. A source - * no entry reaches is not - * searched, logged at `debug`. A source that lists two or more parent links - * to an entry's object is not reached by that entry, reported once per - * source and object at `warn`, naming the fields. - */ private sourcesInScope( sources: T[], scope: readonly SearchScopeEntry[], ): Array { - const out: Array = []; - for (const entry of sources) { - const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); - for (const { object, fields } of ambiguous) { - const key = `${entry.source.name}\u0000${object}`; - if (this.scopeAmbiguousReported.has(key)) continue; - this.scopeAmbiguousReported.add(key); - this.options.logger?.warn?.( - `[knowledge] source '${this.label(entry.source)}' lists ${fields.length} fields pointing at '${object}' ` + - `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + - 'it is not told which field the scope means.', - ); - } - if (terms.length === 0) { - this.options.logger?.debug?.( - `[knowledge] source '${this.label(entry.source)}' not searched: no entry of the search's scope reaches it.`, - ); - continue; - } - out.push({ ...entry, scope: terms }); - } - return out; + return (KnowledgeSearchFacet.sourcesInScope).call(knowledgeServiceHost.of(this), sources, scope); } - /** - * Narrow each source's search to the records a non-system caller may read - * ({@link narrowToVisible}). Per source, the ids of the records it indexes - * that the caller may read are read first — as the caller, under the - * source's `where`, ids only, at most {@link SEARCH_VISIBLE_IDS_MAX} + 1 — - * once per object and `where` the search asks. When the caller may read no - * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a - * `record` term, intersected with the caller's own scope, so its adapter - * ranks only those rows and a narrow caller's answers are not crowded out of - * the refill cap by rows they could never be served. - * - * A source is searched as before — on the caller's own scope, its hits - * re-checked within the refill cap — when the caller may read more than - * that, when the caller's scope holds a parent (`metadata`) term, when the - * narrowing names no record (the caller may read none of what the source - * could answer: answered as before, no hit or the source's refusal, never a - * new kind of empty), or when the read fails (logged at `warn`). Nothing here decides access: every hit is - * still re-checked as the caller ({@link applyPermissionFilter}), and the - * organization filter each source carries is not touched. - */ - private async sourcesNarrowedToVisible( + private sourcesNarrowedToVisible( sources: T[], ctx: ExecutionContext, engine: IDataEngine, ): Promise { - const reads = new Map>(); - const visibleOf = (objSource: ObjectKnowledgeSource): Promise => { - const key = JSON.stringify([objSource.object, objSource.where ?? null]); - let read = reads.get(key); - if (read === undefined) { - read = this.readVisibleIds(objSource, ctx, engine); - reads.set(key, read); - } - return read; - }; - const visible = sources.map((entry) => - entry.scope?.some((term) => term.kind !== 'record') === true - ? Promise.resolve(undefined) - : visibleOf(entry.source.source)); - const out: T[] = []; - for (const [i, entry] of sources.entries()) { - const ids = await visible[i]; - const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); - // A narrowing that names no record is not applied: the source is - // searched as before, so a caller who may read none of its records is - // answered as before too — no hit, or the source's refusal. - if (narrowed === undefined || narrowed.every((term) => term.ids.length === 0)) { - out.push(entry); - continue; - } - out.push({ ...entry, scope: narrowed }); - } - return out; + return (KnowledgeSearchFacet.sourcesNarrowedToVisible).call(knowledgeServiceHost.of(this), sources, ctx, engine); } - /** - * The ids of the records of `objSource` the caller may read, read as the - * caller under the source's `where`; `undefined` when there are more than - * {@link SEARCH_VISIBLE_IDS_MAX} or the read fails. - */ - private async readVisibleIds( + private readVisibleIds( objSource: ObjectKnowledgeSource, ctx: ExecutionContext, engine: IDataEngine, ): Promise { - let rows: unknown; - try { - // As the caller, in the query, as the permission re-read asks. - rows = await engine.find(objSource.object, { - ...(objSource.where === undefined ? {} : { where: objSource.where }), - fields: ['id'], - limit: SEARCH_VISIBLE_IDS_MAX + 1, - context: ctx, - } as never); - if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the caller's readable records of object='${objSource.object}' could not be read ` + - `(${errorText(err)}); its sources are searched unnarrowed, every hit re-checked.`, - ); - return undefined; - } - if (rows.length > SEARCH_VISIBLE_IDS_MAX) return undefined; - const ids: string[] = []; - for (const row of rows as Array<{ id?: unknown } | null | undefined>) { - const id = row?.id; - if ((typeof id === 'string' && id.length > 0) || typeof id === 'number') ids.push(String(id)); - } - return ids; + return KnowledgeSearchFacet.readVisibleIds.call(knowledgeServiceHost.of(this), objSource, ctx, engine); } - /** - * The hits of `source` that some scope term holds for ({@link scopeCheck}); - * the rest are dropped, and the first time an adapter's answer loses a hit - * here it is reported once, at `warn` ({@link searchRound}). - */ private checkScope( hits: KnowledgeHit[], terms: readonly AdapterScopeTerm[], source: KnowledgeSource, adapterId: string, ): KnowledgeHit[] { - const inScope = scopeCheck(terms); - const kept = hits.filter(inScope); - const dropped = hits.length - kept.length; - if (dropped > 0 && !this.scopeIgnoredReported.has(adapterId)) { - this.scopeIgnoredReported.add(adapterId); - this.options.logger?.warn?.( - `[knowledge] adapter '${adapterId}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + - "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + - "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + - 'Reported once for this adapter.', - ); - } - return kept; + return KnowledgeSearchFacet.checkScope.call(knowledgeServiceHost.of(this), hits, terms, source, adapterId); } // ── Sync entrypoints (called by the host plugin's triggers and worker) ─── @@ -3426,7 +1127,7 @@ export class KnowledgeService implements IKnowledgeService { /** Whether record syncs run through the queue ({@link routeRecordSyncs}). */ get recordSyncQueued(): boolean { - return this.recordSyncPublisher !== undefined; + return KnowledgeRecordSyncFacet.recordSyncQueued.call(knowledgeServiceHost.of(this)); } /** @@ -3453,17 +1154,9 @@ export class KnowledgeService implements IKnowledgeService { * {@link handleRecordUpsert} / {@link handleRecordDelete} instead. */ enqueueRecordSync(object: string, recordId: string | number, reason: KnowledgeRecordSyncReason = 'event'): void { - if (!isRecordId(recordId) || this.held) return; - const sources = this.sourcesForObject(object); - if (sources.length === 0) return; - this.publishRecordSyncs(sources, object, String(recordId), reason); + return KnowledgeRecordSyncFacet.enqueueRecordSync.call(knowledgeServiceHost.of(this), object, recordId, reason); } - /** - * Publish one record-sync message per source in `sources`, once the unit - * open here commits ({@link enqueueRecordSync}). `onFailed` runs for each - * message that could not be published. - */ private publishRecordSyncs( sources: KnowledgeSource[], object: string, @@ -3471,27 +1164,14 @@ export class KnowledgeService implements IKnowledgeService { reason: KnowledgeRecordSyncReason, onFailed?: () => void, ): void { - const publish = this.recordSyncPublisher; - if (!publish) return; - const send = (): void => { - for (const source of sources) { - const message: KnowledgeRecordSyncMessage = { source: source.name, object, recordId, reason }; - void Promise.resolve() - .then(() => publish(message)) - .catch((err: unknown) => { - onFailed?.(); - const report = - `[knowledge] the sync of record '${recordId}' of source '${this.label(source)}' could not be queued ` + - `(${errorText(err)}): the write stands, and the record's document stays as it was until the record's ` + - 'next save, a search that finds it stale, or the reconcile.'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); - }); - } - }; - const engine = this.options.dataEngine as { runAfterOpenUnitsCommit?(body: () => void): void } | undefined; - if (typeof engine?.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(send); - else send(); + return KnowledgeRecordSyncFacet.publishRecordSyncs.call( + knowledgeServiceHost.of(this), + sources, + object, + recordId, + reason, + onFailed, + ); } /** @@ -3511,100 +1191,21 @@ export class KnowledgeService implements IKnowledgeService { * complete build which purged began after is answered `covered` without a * read ({@link coveredByBuild}). */ - async processRecordSync(data: unknown, publishedAt?: number): Promise { - const resolved = this.resolveRecordSync(data, publishedAt); - if ('outcome' in resolved) return resolved.outcome; - const { source, message, engine } = resolved; - // The source's adapter is resolved now ({@link adapterFor}): the one it - // names, else the deployment's store, else the only one registered. Where - // none can be resolved it throws its coded refusal — the named adapter is - // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or - // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so - // the message is retried: a store that registers late is met by a later - // attempt, and one that never does leaves a dead letter naming the source - // and the record. - const adapter = this.adapterFor(source); - await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => - this.syncRow(source, adapter, message.object, message.recordId, engine), - ); - return 'synced'; + processRecordSync(data: unknown, publishedAt?: number): Promise { + return KnowledgeRecordSyncFacet.processRecordSync.call(knowledgeServiceHost.of(this), data, publishedAt); } - /** - * What every record-sync message is checked for before its row is read, - * on both of the worker's paths ({@link processRecordSync}, - * {@link processRecordSyncBatch}): an outcome that completes it without a - * sync — not a record-sync message, the service held, its source gone, its object no longer - * synced on record change, no data engine to re-read the row, or covered - * by a complete build that purged and began after it was published - * ({@link coveredByBuild}) — or the source, - * the message and the engine to sync it with. - */ private resolveRecordSync( data: unknown, publishedAt: number | undefined, ): | { outcome: KnowledgeRecordSyncOutcome } | { source: KnowledgeSource; message: KnowledgeRecordSyncMessage; engine: IDataEngine } { - const message = readRecordSyncMessage(data); - if (!message) { - this.options.logger?.warn?.( - `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, - ); - return { outcome: 'malformed' }; - } - // Held (ADR-0161 K8, ruling 7248214179): completed without a sync, and no - // store is called, on the per-message and the batch path alike. - if (this.held) return { outcome: 'not-synced' }; - const source = this.handed(message.source); - if (!source) { - this.options.logger?.debug?.( - `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, - ); - return { outcome: 'source-gone' }; - } - if (objectSourcesFor([source], message.object).length === 0) return { outcome: 'not-synced' }; - const engine = this.options.dataEngine; - if (!engine) { - this.options.logger?.warn?.( - `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + - 'bound to re-read the row.', - ); - return { outcome: 'not-synced' }; - } - if (this.coveredByBuild(source.name, publishedAt)) return { outcome: 'covered' }; - return { source, message, engine }; + return KnowledgeRecordSyncFacet.resolveRecordSync.call(knowledgeServiceHost.of(this), data, publishedAt); } - /** - * [#38413] Whether a complete build of the source under `key` already did - * what a message published at `publishedAt` asks for, so the message can - * complete without a read. All of these must hold: - * - * - the source's last build on this node finished `done` and its PURGE RAN - * (`result.purged` is a number). The walk writes the document of every - * row it reads and the purge deletes the document of every row it did - * not, so a message for a deleted row, or for a row that left `where`, is - * covered only by a build that purged. A build that ends `done` with - * `purged: null` (an adapter without `listDocuments`, or a listing that - * failed and the walk went on) deleted nothing, and covers nothing; - * - the reconcile walks the source ({@link reconcileExclusion}): a source - * whose index an external indexer owns, or whose store lists nothing, is - * never covered; - * - the build began at least {@link RECORD_SYNC_COVER_MARGIN_MS} after - * `publishedAt`. A message is published once its write committed, and - * the walk reads every row after it starts. - * - * A build running now, or one that did not finish, covers nothing. - */ private coveredByBuild(key: string, publishedAt: number | undefined): boolean { - if (publishedAt === undefined || !Number.isFinite(publishedAt)) return false; - const build = this.builds.get(key); - if (build?.status !== 'done' || typeof build.result?.purged !== 'number' || build.result.ok === false) return false; - const entry = this.registry.byIndexKey(key); - if (!entry || this.reconcileExclusion(entry) !== undefined) return false; - const startedAt = Date.parse(build.startedAt); - return Number.isFinite(startedAt) && publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS; + return KnowledgeRecordSyncFacet.coveredByBuild.call(knowledgeServiceHost.of(this), key, publishedAt); } /** @@ -3630,229 +1231,43 @@ export class KnowledgeService implements IKnowledgeService { * the batch never waits for it, and once it ends `done` the messages it * covers complete without a read. Never rejects. */ - async processRecordSyncBatch( + processRecordSyncBatch( batch: readonly KnowledgeRecordSyncBatchItem[], ): Promise { - const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); - const groups = new Map(); - batch.forEach((item, index) => { - const resolved = this.resolveRecordSync(item?.data, item?.publishedAt); - if ('outcome' in resolved) { - results[index] = { ok: true, outcome: resolved.outcome }; - return; - } - const key = JSON.stringify([resolved.source.name, resolved.message.object]); - let group = groups.get(key); - if (!group) { - group = { source: resolved.source, object: resolved.message.object, engine: resolved.engine, items: [] }; - groups.set(key, group); - } - group.items.push({ index, recordId: resolved.message.recordId, publishedAt: item.publishedAt }); - }); - for (const group of groups.values()) { - await this.considerBacklogReconcile(group, batch.length); - } - for (const group of groups.values()) { - try { - await this.syncRecordGroup(group, results); - } catch (err) { - for (const item of group.items) results[item.index] ??= { ok: false, error: err }; - } - } - return results; + return KnowledgeRecordSyncFacet.processRecordSyncBatch.call(knowledgeServiceHost.of(this), batch); } - /** One group of {@link processRecordSyncBatch}: writes each of its items' result. */ - private async syncRecordGroup(group: RecordSyncGroup, results: KnowledgeRecordSyncBatchResult[]): Promise { - const { source, object, engine } = group; - let adapter: IKnowledgeAdapter; - try { - adapter = this.adapterFor(source); - } catch (err) { - for (const item of group.items) results[item.index] = { ok: false, error: err }; - return; - } - const open: RecordSyncGroup['items'] = []; - for (const item of group.items) { - if (this.coveredByBuild(source.name, item.publishedAt)) results[item.index] = { ok: true, outcome: 'covered' }; - else open.push(item); - } - if (open.length === 0) return; - const recordIds = [...new Set(open.map((item) => item.recordId))]; - const failures = new Map(); - await chainAfterAll(this.recordSyncTails, recordIds.map((id) => documentIdFor(source.name, id)), async () => { - if (recordIds.length > 1) { - try { - await this.syncRows(source, adapter, object, recordIds, engine); - return; - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] a batch of ${recordIds.length} record syncs of source '${this.label(source)}' failed (${errorText(err)}); ` + - 'syncing them one by one, so a record that cannot be synced fails alone.', - ); - } - } - for (const recordId of recordIds) { - try { - await this.syncRow(source, adapter, object, recordId, engine); - } catch (err) { - failures.set(recordId, err); - } - } - }); - for (const item of open) { - results[item.index] = failures.has(item.recordId) - ? { ok: false, error: failures.get(item.recordId) } - : { ok: true, outcome: 'synced' }; - } + private syncRecordGroup(group: RecordSyncGroup, results: KnowledgeRecordSyncBatchResult[]): Promise { + return KnowledgeRecordSyncFacet.syncRecordGroup.call(knowledgeServiceHost.of(this), group, results); } - /** - * [#38413] The record-sync queue's waiting count (`getQueueSize`), read at - * most once per {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}. `undefined` - * when the queue cannot count or the count failed. - */ - private async recordSyncWaiting(): Promise { - const now = Date.now(); - const last = this.recordSyncBacklog; - if (last && now - last.at < RECORD_SYNC_BACKLOG_READ_INTERVAL_MS) return last.waiting; - let waiting: number | undefined; - try { - waiting = await this.pendingRecordSyncs(); - } catch { - waiting = undefined; - } - this.recordSyncBacklog = { at: now, waiting }; - return waiting; + private recordSyncWaiting(): Promise { + return KnowledgeRecordSyncFacet.recordSyncWaiting.call(knowledgeServiceHost.of(this)); } - /** - * [#38413] The rows of the source under `key` (its `where`, counted as the - * system identity), kept for {@link RECORD_SYNC_SOURCE_ROWS_TTL_MS}. - * `undefined` when the count failed. - */ - private async sourceRowCount(key: string, objSource: ObjectKnowledgeSource, engine: IDataEngine): Promise { - const now = Date.now(); - const last = this.sourceRows.get(key); - if (last && now - last.at < RECORD_SYNC_SOURCE_ROWS_TTL_MS) return last.rows; - let rows: number | undefined; - try { - const counted = await engine.count(objSource.object, { where: objSource.where }, { context: systemContext() }); - rows = typeof counted === 'number' && Number.isFinite(counted) ? counted : undefined; - } catch { - rows = undefined; - } - this.sourceRows.set(key, { at: now, rows }); - return rows; + private sourceRowCount(key: string, objSource: ObjectKnowledgeSource, engine: IDataEngine): Promise { + return KnowledgeRecordSyncFacet.sourceRowCount.call(knowledgeServiceHost.of(this), key, objSource, engine); } - /** - * [#38413] Ask 2 of the batch path: schedule one reconcile of the group's - * source when its backlog is large enough that a walk beside the drain - * pays. The source's backlog is estimated as the queue's waiting count - * times the group's share of the batch in hand (the batch is the head of - * the queue). A reconcile is scheduled when that estimate reaches both - * {@link RECORD_SYNC_BACKLOG_THRESHOLD} and - * {@link RECORD_SYNC_BACKLOG_ROW_SHARE} of the source's rows, no backlog - * reconcile of the source is running, and the source is past its wait: - * {@link RECORD_SYNC_BACKLOG_REWALK_MS} after one that ended `done`, or a - * backoff from {@link RECORD_SYNC_BACKLOG_RETRY_MS} doubling to - * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} after one that did not. - * - * It is scheduled, never awaited: the batch, and every other source's - * syncs, go on while it walks, and the messages its build covers - * ({@link coveredByBuild}) complete without a read once it ends. A source - * the reconcile does not walk ({@link reconcileExclusion}) is never - * scheduled. Never rejects. - */ - private async considerBacklogReconcile(group: RecordSyncGroup, batchLength: number): Promise { - const key = group.source.name; - const objSource = group.source.source; - if (objSource.kind !== 'object' || batchLength <= 0) return; - const entry = this.registry.byIndexKey(key); - if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) return; - const state = this.backlogReconciles.get(key); - if (state && (state.running || Date.now() < state.notBefore)) return; - const waiting = await this.recordSyncWaiting(); - if (waiting === undefined) return; - const estimate = Math.round((waiting * group.items.length) / batchLength); - if (estimate < RECORD_SYNC_BACKLOG_THRESHOLD) return; - const rows = await this.sourceRowCount(key, objSource, group.engine); - if (rows === undefined || estimate < rows * RECORD_SYNC_BACKLOG_ROW_SHARE) return; - - const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; - this.backlogReconciles.set(key, next); - this.options.logger?.info?.( - `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + - 'reconcile of the source is scheduled; record syncs go on meanwhile, and those it covers complete without a ' + - 'read once it ends.', - ); - void this.enqueueReconcile(() => { - const current = this.registry.byIndexKey(key); - return current === undefined ? [] : [current]; - }) - .then(() => undefined, () => undefined) - .then(() => { - next.running = false; - const build = this.builds.get(key); - if (build?.status === 'done' && typeof build.result?.purged === 'number') { - next.failures = 0; - next.notBefore = Date.now() + RECORD_SYNC_BACKLOG_REWALK_MS; - return; - } - next.failures++; - const wait = Math.min(RECORD_SYNC_BACKLOG_RETRY_MS * 2 ** (next.failures - 1), RECORD_SYNC_BACKLOG_RETRY_MAX_MS); - next.notBefore = Date.now() + wait; - this.options.logger?.warn?.( - `[knowledge] source '${entry.face}': the reconcile scheduled for its record-sync backlog ended ` + - `${build?.status ?? 'without a build'}${build?.status === 'done' ? ' with no purge' : ''}, so its record syncs are ` + - `drained one by one; another is not scheduled for ${Math.round(wait / 60_000)} min.`, - ); - }); + private considerBacklogReconcile(group: RecordSyncGroup, batchLength: number): Promise { + return KnowledgeRecordSyncFacet.considerBacklogReconcile.call(knowledgeServiceHost.of(this), group, batchLength); } - /** - * [#38413] The batch twin of {@link syncRow}: re-read the rows `recordIds` - * name under the source's `where` as the system identity, in one read - * ({@link rereadRows}), write the documents of the rows that came back in - * one `upsert` and delete those of the ids no row matched in one `delete`, - * under one index plan. A document the split cannot index is removed and - * reported, as {@link writeSynced} does. Throws what the re-read, a - * document build, the split, the embedding call or the store throws. - */ - private async syncRows( + private syncRows( source: KnowledgeSource, adapter: IKnowledgeAdapter, object: string, recordIds: string[], engine: IDataEngine, ): Promise { - const objSource = source.source; - const rows = await rereadRows(engine, objSource, recordIds); - const byId = new Map>(); - for (const row of rows) if (isRecordId(row.id)) byId.set(String(row.id), row); - const schema = this.schemaFor(object); - const posture = await this.readTenancyPosture(); - const docs: KnowledgeDocument[] = []; - const gone: string[] = []; - const recordOf = new Map(); - for (const recordId of recordIds) { - const row = byId.get(recordId); - if (row) { - const doc = recordToDocument(source, objSource, row, schema, posture); - recordOf.set(doc.id, recordId); - docs.push(doc); - } else { - gone.push(documentIdFor(source.name, recordId)); - } - } - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('event-sync'); - const prepared = this.prepareDocuments(plan, docs); - if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); - const removed = [...gone, ...prepared.failed.map((f) => f.documentId)]; - if (removed.length > 0) await adapter.delete(removed, ctx); - for (const f of prepared.failed) this.reportUnindexable(source, adapter, f, recordOf.get(f.documentId) ?? f.documentId); + return KnowledgeRecordSyncFacet.syncRows.call( + knowledgeServiceHost.of(this), + source, + adapter, + object, + recordIds, + engine, + ); } /** @@ -3920,157 +1335,64 @@ export class KnowledgeService implements IKnowledgeService { * is awaited, so a write's sync can wait behind an earlier in-flight sync * of the same document; the index still ends consistent. */ - async handleRecordUpsert(object: string, record: Record): Promise { - if (this.held) return; - const recordId = record.id; - for (const source of this.sourcesForObject(object)) { - const sync = (): Promise => this.syncRecord(source, object, recordId, record); - await (isRecordId(recordId) - ? this.serializeRecordSync(documentIdFor(source.name, String(recordId)), sync) - : sync()); - } + handleRecordUpsert(object: string, record: Record): Promise { + return KnowledgeRecordSyncFacet.handleRecordUpsert.call(knowledgeServiceHost.of(this), object, record); } - /** - * One source's inline sync of one row — see {@link handleRecordUpsert}. - * Never throws: a failure is one `warn` line. - */ - private async syncRecord( + private syncRecord( source: KnowledgeSource, object: string, recordId: unknown, payload: Record, ): Promise { - const objSource = source.source; - try { - const adapter = this.adapterFor(source); - const engine = this.options.dataEngine; - if (!engine) { - if (objSource.where !== undefined) { - this.reportWhereUnenforceable(source); - return; - } - const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); - await this.writeSynced(source, adapter, doc, recordId); - return; - } - if (!isRecordId(recordId)) { - this.options.logger?.warn?.( - `[knowledge] event-sync skipped for source '${this.label(source)}': the event's record names no id, ` + - 'so the row cannot be re-read against the source.', - ); - return; - } - await this.syncRow(source, adapter, object, recordId, engine); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, - ); - } + return KnowledgeRecordSyncFacet.syncRecord.call(knowledgeServiceHost.of(this), source, object, recordId, payload); } - /** - * THE sync of one row's document, both paths' ({@link syncRecord} inline, - * {@link processRecordSync} from the queue): re-read the row under the - * source's `where` as the system identity ({@link rereadRow}) and write its - * document, or delete the document when no row matches. Throws what the - * re-read, the split, the embedding call or the store throws. - */ - private async syncRow( + private syncRow( source: KnowledgeSource, adapter: IKnowledgeAdapter, object: string, recordId: string | number, engine: IDataEngine, ): Promise { - const objSource = source.source; - const row = await rereadRow(engine, objSource, recordId); - if (row) { - const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); - await this.writeSynced(source, adapter, doc, recordId); - } else { - const plan = await this.planIndex(source, adapter); - await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); - } + return KnowledgeRecordSyncFacet.syncRow.call( + knowledgeServiceHost.of(this), + source, + adapter, + object, + recordId, + engine, + ); } - /** - * The event sync's write of one document: split as every path splits - * ({@link prepareDocuments}) and upserted. A document the split cannot - * index (a `whole` document over the embedder's budget) is removed from the - * index and reported at `error`: the write that triggered the sync - * succeeded and search keeps answering, so nothing else shows that this - * record is no longer findable. - */ - private async writeSynced( + private writeSynced( source: KnowledgeSource, adapter: IKnowledgeAdapter, doc: KnowledgeDocument, recordId: unknown, ): Promise { - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('event-sync'); - const prepared = this.prepareDocuments(plan, [doc]); - if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); - for (const f of prepared.failed) { - await adapter.delete([f.documentId], ctx); - this.reportUnindexable(source, adapter, f, recordId); - } + return KnowledgeRecordSyncFacet.writeSynced.call(knowledgeServiceHost.of(this), source, adapter, doc, recordId); } - /** Say, at `error`, that a record's document left the index because its split cannot index it ({@link writeSynced}, {@link syncRows}). */ private reportUnindexable( source: KnowledgeSource, adapter: IKnowledgeAdapter, f: { estimate: number; budget: number }, recordId: unknown, ): void { - const limit = adapter.embedding?.maxInputTokens; - const message = - `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + - `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + - `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + - `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; - // `warn` is the guaranteed channel when a host injects no `error`. - const logger = this.options.logger; - if (logger?.error) logger.error(message); - else logger?.warn?.(message); + return KnowledgeRecordSyncFacet.reportUnindexable.call(knowledgeServiceHost.of(this), source, adapter, f, recordId); } - /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ private reportWhereUnenforceable(source: KnowledgeSource): void { - if (this.whereUnenforceableReported.has(source.name)) return; - this.whereUnenforceableReported.add(source.name); - this.options.logger?.warn?.( - `[knowledge] source '${this.label(source)}' declares a where filter and no data engine is bound: record events ` + - 'for it are not synced, because the filter cannot be judged without re-reading the row. ' + - 'Bind a data engine (the objectql service) to sync it.', - ); + return KnowledgeRecordSyncFacet.reportWhereUnenforceable.call(knowledgeServiceHost.of(this), source); } - /** - * Run `task` after every earlier sync of the same document (`key`) has - * finished — an in-process promise chain per document, dropped once idle. - * Only the ORDER of syncs is held; each still re-reads the row itself, so a - * later sync never acts on what an earlier one read. A task that rejects - * does not break the chain (the sync paths never throw; this is a backstop). - */ private serializeRecordSync(key: string, task: () => Promise): Promise { - return chainAfter(this.recordSyncTails, key, task).catch(() => undefined); + return KnowledgeRecordSyncFacet.serializeRecordSync.call(knowledgeServiceHost.of(this), key, task); } - /** - * The registered object definition, when the bound engine exposes one - * (`getSchema` is not on the `IDataEngine` contract; the ObjectQL engine - * carries it). `undefined` — nothing to withhold by — otherwise. - */ private schemaFor(object: string): unknown { - try { - return (this.options.dataEngine as { getSchema?: (name: string) => unknown } | undefined) - ?.getSchema?.(object); - } catch { - return undefined; - } + return KnowledgeRecordSyncFacet.schemaFor.call(knowledgeServiceHost.of(this), object); } /** @@ -4079,151 +1401,29 @@ export class KnowledgeService implements IKnowledgeService { * ({@link serializeRecordSync}), so a delete cannot land between another * sync's re-read and its write. */ - async handleRecordDelete(object: string, recordId: string): Promise { - if (this.held) return; - const targets = this.sourcesForObject(object); - for (const source of targets) { - const docId = documentIdFor(source.name, recordId); - await this.serializeRecordSync(docId, async () => { - try { - const adapter = this.adapterFor(source); - await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] event-sync delete failed for source '${this.label(source)}': ${(err as Error).message}`, - ); - } - }); - } + handleRecordDelete(object: string, recordId: string): Promise { + return KnowledgeRecordSyncFacet.handleRecordDelete.call(knowledgeServiceHost.of(this), object, recordId); } // ── Internals ───────────────────────────────────────────────────── - /** - * The registered source `sourceId` names, read by the one rule - * (`KnowledgeSourceRegistry.resolve`): its face, else a bare name by - * ADR-0150 D3. Throws for a name no source has, listing the registered - * faces, and `409 RESOURCE_CONFLICT` for one that names several. - */ private requireEntry(sourceId: string): KnowledgeSourceEntry { - const entry = this.registry.resolve(sourceId); - if (!entry) { - throw new Error( - `[knowledge] unknown source '${sourceId}'. Registered: [${this.registry.entries().map((e) => e.face).join(', ')}]`, - ); - } - return entry; + return KnowledgeSourcesFacet.requireEntry.call(knowledgeServiceHost.of(this), sourceId); } - /** - * The sources a search asks: every source whose `aiExposed` is not `false`, - * or the ones `sourceIds` names — each read by the one rule, so a name - * several sources have refuses the search (`409 RESOURCE_CONFLICT`) and a - * name none has is skipped, reported at `warn`. - */ private resolveSearchTargets(sourceIds?: string[]): KnowledgeSource[] { - if (!sourceIds || sourceIds.length === 0) { - return this.handedSources().filter((s) => s.aiExposed !== false); - } - const out = new Map(); - for (const id of sourceIds) { - const entry = this.registry.resolve(id); - if (entry) out.set(entry.key, entry.handed); - else this.options.logger?.warn?.(`[knowledge] search target '${id}' not registered; skipping.`); - } - return [...out.values()]; + return KnowledgeSearchFacet.resolveSearchTargets.call(knowledgeServiceHost.of(this), sourceIds); } - /** - * [ADR-0090 D10 rule 1] The sources this caller's search may reach: a - * source over an object the caller's exposure decision refuses, or one - * serving a field the caller may not query, is not searched for that - * caller — see `knowledge-source-admission.ts` for the gates and why they are - * asked at source granularity. Computed once per (caller, object) per search. - * - * The system context bypasses, as it bypasses the row re-check. A caller - * with NO context, or a service with no data engine bound, cannot be judged - * and is served no source at all — never searched, so no passage of one can - * reach the caller through a hit the row re-check cannot place (a hit with - * no `sourceRecordId`). Fails CLOSED: a gate that throws refuses - * every source over that object, reported once at `error`. The objects' - * admissions are asked concurrently. - * - * An admitted source over which an index built under the earlier title - * rule could serve a field the gate does not ask about - * (`mayServeEarlierRuleTitle`) carries `proveIndex`: {@link planSearches} - * searches it only once its index is proven built under the current recipe. - * - * Each admitted source carries the organizations its search hands the - * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system - * context's bypass above covers that scope too: the system identity's - * search is handed no organization filter. - */ - private async admitSources( + private admitSources( sources: KnowledgeSource[], ctx: ExecutionContext | undefined, ): Promise { - if (ctx?.isSystem) return sources.map((source) => ({ source })); - const engine = this.options.dataEngine; - if (!ctx || !engine) { - if (sources.length > 0) { - this.options.logger?.warn?.( - !ctx - ? '[knowledge] retrieval with no ExecutionContext — no source is searched: a missing ' + - 'identity is not a grant of authority, so retrieval fails closed rather than searching the whole corpus unscoped. ' + - 'Pass the caller identity (or an explicit system context) to retrieve knowledge.' - : '[knowledge] no IDataEngine bound — no source is searched, to stay safe.', - ); - } - return []; - } - const deps = this.admissionDeps(engine); - const byObject = new Map>(); - for (const source of sources) { - const object = source.source.object; - if (byObject.has(object)) continue; - byObject.set( - object, - admitObject(object, ctx, deps).catch((err: unknown) => { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return undefined; - }), - ); - } - const out: AdmittedSource[] = []; - for (const source of sources) { - const objSource = source.source; - const objectAdmission = await byObject.get(objSource.object); - if (!objectAdmission) continue; // the gate threw: reported once, refused. - const verdict: KnowledgeSourceAdmission = objectAdmission.refused - ? { admitted: false, reason: objectAdmission.refused, object: objSource.object } - : admitSourceFields(objSource, objectAdmission); - if (verdict.admitted) { - // An index built under the earlier title rule could serve a field - // the gate no longer asks about: searched only once its index is - // proven built under the current recipe ({@link planSearches}). - out.push(mayServeEarlierRuleTitle(objSource, objectAdmission.schema) ? { source, proveIndex: true } : { source }); - } else { - this.options.logger?.debug?.( - `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + - `(object='${verdict.object}'${verdict.field ? `, field='${verdict.field}'` : ''}).`, - ); - } - } - return this.scopeByOrganization(out, ctx); + return KnowledgeAdmissionFacet.admitSources.call(knowledgeServiceHost.of(this), sources, ctx); } - /** What the source-admission gates read of the engine and the security service. */ private admissionDeps(engine: IDataEngine): KnowledgeAdmissionDeps { - return { - readSchema: (object: string): unknown => { - const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; - return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; - }, - isObjectPackageDisabled: (object: string): boolean => - registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), - resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), - }; + return KnowledgeAdmissionFacet.admissionDeps.call(knowledgeServiceHost.of(this), engine); } /** @@ -4289,1283 +1489,170 @@ export class KnowledgeService implements IKnowledgeService { * no "nothing was written": that door's own prefix says once that nothing * was copied. */ - async admitAuthoredSource( + admitAuthoredSource( item: unknown, ctx: ExecutionContext | undefined, options?: { door?: 'save' | 'duplicate' }, ): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { - if (ctx?.isSystem) return { admitted: true }; - const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save']; - const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; - const declared = body.source as - | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } - | null - | undefined; - const object = declared && typeof declared === 'object' ? declared.object : undefined; - if (typeof object !== 'string' || object === '') return { admitted: true }; - const names = (value: unknown): string[] => - Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; - const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }; - const where = listed.where; - const objSource: ObjectKnowledgeSource = { - kind: 'object', - object, - content: [...names(listed.content), ...names(listed.contentFields)], - metadataFields: names(listed.metadataFields), - ...(where !== null && typeof where === 'object' && !Array.isArray(where) - ? { where: where as Record } - : {}), - }; - const named = `The knowledge source${describeName(body)} ${wording.notDone}`; - const refuse = (status: number, code: string, message: string, field?: string) => - ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); - const unavailable = (why: string) => - refuse( - 503, - 'SERVICE_UNAVAILABLE', - `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + - `allowed to search what their source indexes.${wording.tryAgain}`, - ); - // [ADR-0161 K8, the dated note on item 12, ◆ an author's save and point 4] - // A service the runtime composed and that this boot read as not enabled - // holds every source, so an author's save would be kept and never served: - // refused at each door that saves one, naming the half that is missing. - // The package duplicate (`door: 'duplicate'`) is not refused for it, and - // the engine's own write was admitted above. - if (this.held && options?.door !== 'duplicate') { - return refuse(503, 'SERVICE_UNAVAILABLE', `${named}: ${heldSourceSaveText(this.held)}`); - } - if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`); - // [ADR-0161 K4 ◆] A source that names no adapter where this deployment - // cannot place one is refused at its save as at its registration, so the - // author hears it: several adapters registered, none the deployment's. - const authoredAdapter = (item as { adapter?: unknown } | null | undefined)?.adapter; - const registeredAdapters = this.listAdapters(); - if (authoredAdapter === undefined && this.options.deploymentAdapter === undefined && registeredAdapters.length > 1) { - return refuse(400, 'VALIDATION_ERROR', `${named}: it ${unplacedSourceText(registeredAdapters)}`); - } - // [ADR-0161 K4] A source that names an adapter this deployment does not - // mount is refused at its save, so the author hears it there and not from - // the boot log or a search's 503. A save is served after every store's - // `start()`, so the adapters registered now are the deployment's. - if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { - return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); - } - const engine = this.options.dataEngine; - if (!engine) return unavailable('the knowledge service has no data engine'); - - // [ADR-0161 K4, row 4] A reference to nothing is a permanent mistake, named - // by the rule `os validate` reports, ahead of every permission arm. - let absent: AbsentSourceReference | undefined; - try { - absent = absentSourceReference(objSource, listed, engine, this.admissionDeps(engine)); - } catch (err) { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return unavailable(operatorText(err)); - } - if (absent?.kind === 'object') { - return refuse( - 400, - 'VALIDATION_ERROR', - `${named}: \`source.object\` names '${object}', which is not an object of this organization (neither one it ` + - 'authored nor one an installed package registers), so the source indexes nothing ' + - `(\`${KNOWLEDGE_SOURCE_OBJECT_UNKNOWN}\`, the rule \`os validate\` reports). Name an object the organization ` + - `has (check the spelling), or install the package that provides '${object}' first${wording.thenAgain}.`, - ); - } - if (absent?.kind === 'field') { - return refuse( - 400, - 'VALIDATION_ERROR', - `${named}: \`source.${absent.key}\` names field '${absent.field}', which object '${object}' does not define, ` + - 'so the index reads nothing for it on any record ' + - `(\`${KNOWLEDGE_SOURCE_FIELD_UNKNOWN}\`, the rule \`os validate\` reports). Name a field of '${object}' ` + - `(check the spelling), or remove it from \`${absent.key}\`${wording.thenAgain}.`, - absent.field, - ); - } - - // [`source.documentBy`] A document unit that is no single-valued parent - // link is a permanent mistake too, judged on the object's definition alone - // by the parent-link rule the search scope reads. One not listed in - // `metadataFields` is left to the parse, which names that fix. - const documentBy = (declared as { documentBy?: unknown }).documentBy; - if (typeof documentBy === 'string' && objSource.metadataFields?.includes(documentBy)) { - let unit: DocumentUnitVerdict | undefined; - try { - const deps = this.admissionDeps(engine); - unit = deps.isObjectPackageDisabled(object) ? undefined : documentUnitOf(documentBy, deps.readSchema(object)); - } catch (err) { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return unavailable(operatorText(err)); - } - if (unit !== undefined && !unit.unit) { - return refuse( - 400, - 'VALIDATION_ERROR', - `${named}: ${documentUnitRefusalText(object, documentBy, unit)}${wording.thenAgain}.`, - documentBy, - ); - } - } - - // [`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)); - } catch (err) { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return unavailable(operatorText(err)); - } - const verdict: KnowledgeSourceAdmission = admission.refused - ? { admitted: false, reason: admission.refused, object } - : admitSourceFields(objSource, admission); - if (verdict.admitted) return { admitted: true }; - switch (verdict.reason) { - case 'object-package-disabled': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: its object '${object}' belongs to a disabled package, and a disabled package's records are ` + - 'not indexed or searched. Enable the package, or index another object.', - ); - case 'object-api-not-served': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, its ` + - '`enable.apiMethods` list does not grant `list`, from which search derives, or it grants `list` beside ' + - "`enable.searchable: false`), and a knowledge search is a search over the object's records. " + - `Serve '${object}' for search: keep \`enable.apiEnabled\` true and, where it declares ` + - '`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object.', - ); - case 'system-object-not-ai-readable': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: '${object}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), ` + - 'so its records are not indexed for retrieval.', - ); - case 'field-not-queryable': { - const field = verdict.field ?? ''; - if (verdict.use === 'where') { - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + - 'hidden from you, or served to you masked), and the source would select its records by that field. ' + - `Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`, - field, - ); - } - const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + - 'to you masked), and the index would hold its text unmasked. ' + - (listedByAuthor - ? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.` - : "The source does not list it: it is the object's display field, which every document carries as its " + - `title. Have someone who may query it ${wording.byWhoMay}.`), - field, - ); - } - default: - return unavailable(`the security service did not answer which fields of '${object}' you may read`); - } + return KnowledgeAdmissionFacet.admitAuthoredSource.call(knowledgeServiceHost.of(this), item, ctx, options); } - /** - * Why a saved source naming `adapter`, which `mounted` does not hold, is - * refused, and what to write: the rule, then the remedies this deployment - * can take. Leaving `adapter` out is offered only where an omitted adapter - * would be placed ({@link adapterIdFor}). - */ private unmountedAdapterSaveText(adapter: string, mounted: readonly string[], again: string): string { - const deployment = this.options.deploymentAdapter; - const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1; - const remedies = [ - ...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]), - ...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []), - `mount the '${adapter}' store and ${again}`, - ]; - return ( - `it names adapter '${adapter}', which this deployment does not mount ` + - `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}), and a source's \`adapter\` must name a ` + - `mounted store. ${remedies.join(', or ').replace(/^./, (c) => c.toUpperCase())}.` + return KnowledgeAdmissionFacet.unmountedAdapterSaveText.call( + knowledgeServiceHost.of(this), + adapter, + mounted, + again, ); } - /** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ private reportGateFailure(object: string, err: Error): void { - const report = - `[knowledge] the exposure or field-level read rules of object '${object}' could not be resolved ` + - `(${err.message}); no source over it is searched for this caller (fail-closed).`; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); + return KnowledgeAdmissionFacet.reportGateFailure.call(knowledgeServiceHost.of(this), object, err); } - /** The deployment's effective tenancy posture, or `undefined` when no resolver is wired. Throws what the resolver throws. */ - private async readTenancyPosture(): Promise { - return this.options.resolveTenancyPosture ? await this.options.resolveTenancyPosture() : undefined; + private readTenancyPosture(): Promise { + return KnowledgeAdmissionFacet.readTenancyPosture.call(knowledgeServiceHost.of(this)); } - /** - * [ADR-0161 K8, item 9] Pair each source {@link admitSources} admitted for - * a caller that is NOT the system identity (admission's own bypass answers - * that one before this runs) with the organizations its search hands the - * adapter (`searchOrganizationIds`): computed here, from the caller's - * execution context and the deployment's posture, never from anything the - * caller passes. - * - * The posture is read once per search, and only when a source is admitted. - * A posture that cannot be read leaves every source unsearched for this call (fail-closed: whether a wall stands is unknown), - * reported at `error`, `warn` as the fallback. - */ - private async scopeByOrganization( + private scopeByOrganization( sources: AdmittedSource[], ctx: ExecutionContext, ): Promise { - if (sources.length === 0) return []; - let posture: TenancyPosture | undefined; - try { - posture = await this.readTenancyPosture(); - } catch (err) { - const report = - `[knowledge] the tenancy posture could not be read (${errorText(err)}); no source is searched ` + - 'for this caller (fail-closed).'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); - return []; - } - return sources.map((entry) => { - const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(entry.source.source.object)); - return organizationIds === undefined ? entry : { ...entry, organizationIds }; - }); + return KnowledgeAdmissionFacet.scopeByOrganization.call(knowledgeServiceHost.of(this), sources, ctx); } private sourcesForObject(object: string): KnowledgeSource[] { - return objectSourcesFor(this.handedSources(), object); + return KnowledgeAdmissionFacet.sourcesForObject.call(knowledgeServiceHost.of(this), object); } - /** - * Drop hits whose underlying ObjectQL record the caller can't read. A hit - * with no `sourceRecordId`, or of a source nobody registered, cannot be - * re-checked and is dropped. - * - * Identity handling (#2981): an **explicit** `isSystem` context (indexing / - * trusted server jobs) passes every hit through — it is a deliberate, - * authored elevation. A **missing** context, however, is NOT a grant of - * authority: with no identity we cannot prove the caller may read the - * rows, so we FAIL CLOSED and drop every hit (the - * same conservative posture as a missing data engine). This closes the - * agent/RAG fall-open where an omitted `ToolExecutionContext.actor` used to - * return unfiltered semantic search over the whole corpus. - * - * With `liveTitles` (record granularity), the same read — as the caller, in - * the same query — also reads the object's display field - * (`documentTitleField`, the field assembly takes the title from), and a - * surviving hit's `title` is the record's title as it reads now, not as it - * was indexed. The field gate (`admitSourceFields`) already asked that the - * caller may query that field. - */ - private async applyPermissionFilter( + private applyPermissionFilter( hits: KnowledgeHit[], ctx: ExecutionContext | undefined, liveTitles = false, ): Promise { - // Explicit elevation → pass through (indexing / trusted jobs). - if (ctx?.isSystem) return hits; - // No identity, or no engine to re-check with → no hit can be proven - // readable. `admitSources` already kept every source out of the search; - // this holds the same line for any hit that reached here anyway. - if (!ctx || !this.options.dataEngine) return []; - - // Group hits by object so we make one query per object. - const byObject = new Map(); - for (const hit of hits) { - if (!hit.sourceRecordId) continue; - const source = this.handed(hit.sourceId); - if (!source) continue; - const objName = source.source.object; - const bucket = byObject.get(objName) ?? []; - bucket.push(hit); - byObject.set(objName, bucket); - } - - const allowed = new Set(); // `${object}#${recordId}` - const titles = new Map(); // `${object}#${recordId}` → the title as it reads now - for (const [object, group] of byObject) { - const ids = [...new Set(group.map((h) => h.sourceRecordId!).filter(Boolean))]; - if (ids.length === 0) continue; - const schema = liveTitles ? this.schemaFor(object) : undefined; - const withheld = new Set([ - ...collectCredentialWriteResponseFields(schema), - ...collectInternalWriteResponseFields(schema), - ]); - const titleField = liveTitles ? documentTitleField(schema) : undefined; - const readsTitle = titleField !== undefined && titleField !== 'id' && !withheld.has(titleField); - try { - const rows = (await this.options.dataEngine.find(object, { - where: { id: { $in: ids } } as Record, - fields: readsTitle ? ['id', titleField] : ['id'], - context: ctx, - } as never)) as Array & { id?: string }>; - for (const row of rows) { - if (!row?.id) continue; - allowed.add(`${object}#${row.id}`); - if (!readsTitle) continue; - const title = documentTitle(row, schema, withheld); - if (title !== undefined) titles.set(`${object}#${row.id}`, title); - } - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] RLS lookup failed for object='${object}': ${(err as Error).message}; ` + - 'dropping that object\'s hits to stay safe.', - ); - } - } - - const out: KnowledgeHit[] = []; - for (const hit of hits) { - // A hit the re-check cannot place — no record id, or a source nobody - // registered — is not provably readable: dropped. - const source = this.handed(hit.sourceId); - if (!source || !hit.sourceRecordId) continue; - const key = `${source.source.object}#${hit.sourceRecordId}`; - if (!allowed.has(key)) continue; - const title = titles.get(key); - out.push(title === undefined ? hit : { ...hit, title }); - } - return out; - } -} - -// ── Helpers ───────────────────────────────────────────────────────── - -/** A registered source with how a caller names it (`KnowledgeService.describeSources`). */ -export interface KnowledgeSourceDescription { - /** The source's face: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ - id: string; - /** The source as its author wrote it. */ - source: KnowledgeSource; - /** The package that holds it; absent for a source no package holds. */ - packageId?: string; - /** Which door it arrived through: a registration in code, or a `knowledge_source` metadata item. */ - door: KnowledgeSourceEntry['door']; -} - -function describeEntry(entry: KnowledgeSourceEntry): KnowledgeSourceDescription { - return { - id: entry.face, - source: entry.authored, - ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), - door: entry.door, - }; -} - -/** ` 'NAME'` for a refusal about an input that carries a usable name (or its retired `id`), else nothing. */ -/** - * The door that asks {@link KnowledgeService.admitAuthoredSource}: `save` for - * a door that saves one item, `duplicate` for the package duplicate. - */ -type AuthoredSourceDoor = 'save' | 'duplicate'; - -/** - * What each door's caller is told: the source not done, the act that carries - * the identity, the retry after a verdict that could not be judged, the redo - * after a fix, and the act someone who may query the field performs. The - * `save` row is the save door's wording, unchanged. - */ -const AUTHORED_SOURCE_DOOR_WORDING: Readonly< - Record -> = { - save: { - notDone: 'was not saved', - act: 'the save', - tryAgain: ' Nothing was written; try again.', - again: 'save it again', - thenAgain: '', - byWhoMay: 'save the source', - }, - duplicate: { - notDone: 'cannot be copied', - act: 'the duplicate', - tryAgain: ' Duplicate the package again.', - again: 'duplicate the package again', - thenAgain: ', then duplicate the package again', - byWhoMay: 'duplicate the package', - }, -}; - -/** The `os validate` rule ids the save door's "does not exist" arm reports (`@objectstack/lint`, `validate-knowledge-source.ts`). */ -const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN = 'knowledge-source-object-unknown'; -const KNOWLEDGE_SOURCE_FIELD_UNKNOWN = 'knowledge-source-field-unknown'; - -/** A saved source's reference to nothing: its object, or a member naming no field of it. */ -type AbsentSourceReference = - | { kind: 'object' } - | { kind: 'field'; field: string; key: 'content' | 'contentFields' | 'metadataFields' }; - -/** - * [ADR-0161 K4, row 4] What a saved source names that does not exist, judged - * as `os validate` judges it (`knowledge-source-object-unknown`, - * `knowledge-source-field-unknown`): its `source.object` is no object the - * registry defines, or a `content` / `contentFields` / `metadataFields` - * member is neither a field the object declares nor `id` or a system column - * the registry injects on it (`resolveInjectedSystemColumns`). The fields a - * `where` reads are not judged here (the CLI rule does not judge them either). - * - * Decided from the object's registered DEFINITION alone, never from a - * permission answer: every door that asks this verdict admits only a - * `manage_metadata` holder, who is served every object definition whole on - * the metadata plane (ADR-0106 D4), so the verdict tells the author nothing - * they could not read. An object or a field that exists is never reported - * here, so every permission answer about it is the one it was. - * - * No verdict where none can be drawn: an engine with no schema registry (no - * registry is not no object), an object of a disabled package (that gate - * answers it, its definition may be withheld), and an object whose fields - * cannot be enumerated. Throws when a lookup throws; the caller refuses `503`. - */ -function absentSourceReference( - objSource: ObjectKnowledgeSource, - listed: { content?: unknown; contentFields?: unknown; metadataFields?: unknown }, - engine: IDataEngine, - deps: KnowledgeAdmissionDeps, -): AbsentSourceReference | undefined { - if (typeof (engine as { getSchema?: unknown }).getSchema !== 'function') return undefined; - const schema = deps.readSchema(objSource.object); - if (deps.isObjectPackageDisabled(objSource.object) === true) return undefined; - if (schema === undefined || schema === null) return { kind: 'object' }; - const declared = declaredFields(schema); - if (!declared) return undefined; - const known = new Set([...declared.map(([name]) => name), ...resolveInjectedSystemColumns(schema).names]); - for (const key of ['content', 'contentFields', 'metadataFields'] as const) { - const members = listed[key]; - if (!Array.isArray(members)) continue; - for (const member of members) { - if (typeof member === 'string' && member !== '' && !known.has(member)) return { kind: 'field', field: member, key }; - } - } - return undefined; -} - -function describeName(input: unknown): string { - const { name, id } = (input ?? {}) as { name?: unknown; id?: unknown }; - const shown = typeof name === 'string' && name !== '' ? name : typeof id === 'string' && id !== '' ? id : undefined; - return shown === undefined ? '' : ` ${quotedName(shown)}`; -} - -/** - * A source that refused a search (ADR-0161 K7, rule 5): its adapter answered - * an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds - * another fingerprint than the one the search carried. - */ -export interface KnowledgeSearchRefusal { - sourceId: string; - /** The adapter's error code. */ - code: string; - /** The adapter's HTTP-shaped status. */ - status: number; - /** The adapter's message, which says what to do. */ - message: string; -} - -/** What {@link KnowledgeService.searchWithRefusals} answers. */ -export interface KnowledgeSearchReport { - /** The hits of the sources that answered, as {@link KnowledgeService.search} returns them. */ - hits: KnowledgeHit[]; - /** The sources that refused, each with its code; empty when none did. */ - refused: KnowledgeSearchRefusal[]; -} - -/** - * One source a search round asks: its organizations scope, the fingerprint its - * search carries, and the record scope's terms for it (ADR-0161 K8, item 17). - */ -/** A source {@link KnowledgeService.admitSources} admitted for a caller. */ -interface AdmittedSource { - source: KnowledgeSource; - organizationIds?: string[]; - /** Searched only once its index is proven built under the current recipe (`mayServeEarlierRuleTitle`). */ - proveIndex?: true; -} - -/** What ends a refusal for want of a proof ({@link KnowledgeService.unprovenIndex}). */ -type UnprovenEnd = 'rebuild' | 'never' | 'unreadable'; - -/** The second sentence of the caller's refusal, by what ends it. */ -const UNPROVEN_CALLER_TEXT: Readonly> = { - rebuild: 'It answers again once a complete rebuild of the source has completed.', - never: 'No rebuild changes that for this source; an administrator can say why.', - unreadable: 'What its index holds could not be read; it is asked again on the next search.', -}; - -/** The last sentence of the operator's `warn` line, by what ends the refusal. */ -const UNPROVEN_OPERATOR_TEXT: Readonly> = { - rebuild: - 'The boot pass, a source reload or the reconcile builds it where they run; os knowledge rebuild builds it now.', - never: - 'No rebuild can prove it for this source as it is configured, so nothing is rebuilt for it; it stays refused to ' + - 'every caller but the system context.', - unreadable: 'It is asked again on the next search.', -}; - -/** - * The code of a source refused because its index is not proven built under - * the current recipe: the one a generation-keeping adapter answers for an - * index built under another fingerprint, as the remedy is the same rebuild. - */ -const INDEX_NOT_PROVEN_CODE = 'KNOWLEDGE_REBUILD_REQUIRED'; - -interface SearchTarget { - source: KnowledgeSource; - /** - * The adapter the source binds to, resolved once per search - * ({@link KnowledgeService.planSearches}), or the coded refusal its - * resolution answered (`undefined`: an uncoded failure, skipped unsearched). - */ - binding: { adapterId: string; adapter: IKnowledgeAdapter } | { refusal: Omit | undefined }; - organizationIds?: string[]; - fingerprint?: string; - scope?: AdapterScopeTerm[]; - /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ - verifyHits?: true; -} - -/** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ -/** The code an index or search of a source whose adapter is not mounted answers. */ -const UNMOUNTED_ADAPTER_CODE = 'SERVICE_UNAVAILABLE'; - -/** - * The refusal of a source whose adapter is not mounted: ADR-0112 - * `SERVICE_UNAVAILABLE` (503), naming the adapter and the ones that are. - */ -function unmountedAdapterError(id: string, mounted: readonly string[]): Error { - return Object.assign( - new Error( - `[knowledge] adapter '${id}' is not mounted (mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). ` + - `Name one of those as the source's adapter, or mount the '${id}' store.`, - ), - { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, - ); -} - -/** - * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where no - * adapter is registered: ADR-0112 `SERVICE_UNAVAILABLE` (503), as for a named - * adapter that is not mounted. Names the deployment's store when the runtime - * marked one. - */ -function noAdapterMountedError(source: string, deployment: string | undefined): Error { - return Object.assign( - new Error( - `[knowledge] source '${source}' names no adapter, and no adapter is mounted` + - `${deployment === undefined ? '' : ` (the deployment's store '${deployment}' is not mounted)`}. ` + - "Mount a knowledge store — `requires: ['knowledge']` mounts the deployment's — or name the source's adapter.", - ), - { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, - ); -} - -/** - * [ADR-0161 K8, the dated note on item 12] The refusal of a search, a build or - * a reindex while the service is not enabled: ADR-0112 `SERVICE_UNAVAILABLE` - * (503), naming each half that is missing and its remedy, as the refusal of - * an author's save names them. - */ -export function heldSourcesError(reading: KnowledgeHeldReading): Error { - return Object.assign(new Error(heldSourcesText(reading)), { code: UNMOUNTED_ADAPTER_CODE, status: 503 }); -} - -/** The sentence {@link heldSourcesError} answers, and the boot line names the same halves with. */ -export function heldSourcesText(reading: KnowledgeHeldReading): string { - const missing: string[] = []; - const remedy: string[] = []; - if (reading.embedder !== undefined) { - missing.push(`no embedder is configured (${reading.embedder})`); - remedy.push('save an embedder provider'); - } - if (reading.store !== undefined) { - missing.push(`the deployment's knowledge store '${reading.store}' is not mounted, for the reason the boot's log names`); - remedy.push("mount the deployment's knowledge store"); - } - return ( - `[knowledge] the knowledge service is not enabled on this deployment: ${missing.join(', and ')}. ` + - `Its sources are held: none is built, synced or searched. To enable it, ${remedy.join(' and ')}, then restart.` - ); -} - -/** - * [ADR-0161 K8, the dated note on item 12, point 4] Why an author's save of a - * `knowledge_source` is refused while the service is not enabled, after the - * source's subject: each half that is missing, and the ruled remedy for it — - * "save an embedder provider, restart, then save" with no embedder, "mount the - * deployment's knowledge store, restart, then save" where the store is not - * mounted (whose reason the boot's log names), both when both are missing. - * The embedder half carries its cause (a provider saved without its key, for - * example) in parentheses, beside the ruled words. - */ -function heldSourceSaveText(reading: KnowledgeHeldReading): string { - const missing: string[] = []; - const remedy: string[] = []; - if (reading.embedder !== undefined) { - missing.push(`no embedder is configured (${reading.embedder})`); - remedy.push('save an embedder provider'); - } - if (reading.store !== undefined) { - missing.push(`the deployment's knowledge store '${reading.store}' is not mounted, for the reason the boot's log names`); - remedy.push("mount the deployment's knowledge store"); - } - return ( - `the knowledge service is not enabled on this deployment: ${missing.join(', and ')}. A source saved now would be ` + - `held, never built, synced or searched. To have it served, ${remedy.join(' and ')}, restart, then save the source. ` + - 'Nothing was written.' - ); -} - -/** - * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where several - * are registered and none is the deployment's: ADR-0112 `VALIDATION_ERROR` - * (400), naming the choices. The source must say which store holds it. - */ -function unplacedSourceError(source: string, registered: readonly string[], tail = ''): Error { - return Object.assign(new Error(`[knowledge] source '${source}' ${unplacedSourceText(registered)}${tail}`), { - code: 'VALIDATION_ERROR', - status: 400, - }); -} - -/** Why a source that names no adapter cannot be placed among `registered`, and what to write. */ -function unplacedSourceText(registered: readonly string[]): string { - return ( - `names no adapter, and ${registered.length} adapters are registered (${registered.join(', ')}) with none the ` + - "deployment's store, so which one holds its index cannot be told. Name one of " + - `${registered.map((id) => `'${id}'`).join(', ')} as the source's \`adapter\`.` - ); -} - -function codedRefusalOf(err: unknown): Omit | undefined { - if (err === null || typeof err !== 'object') return undefined; - const { code, status } = err as { code?: unknown; status?: unknown }; - if (typeof code !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(code)) return undefined; - if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599) return undefined; - return { code, status, message: errorText(err) }; -} - -/** - * The refusal of a search no source could answer (ADR-0161 K7, rule 5): the - * first refusal's code and status — the one every refusal shares, when they - * share one — and a message naming each refused source with its code. The - * thrown error carries `refused`. - */ -function wholeRefusal(refused: KnowledgeSearchRefusal[]): Error { - const [first] = refused; - const message = - `[knowledge] no source could be searched: ` + - refused.map((r) => `source '${r.sourceId}' refused (${r.code}): ${r.message}`).join('; '); - return Object.assign(new Error(message), { code: first.code, status: first.status, refused: [...refused] }); -} - -/** What {@link KnowledgeService.planIndex} resolves for one call against one source's adapter. */ -interface IndexPlan { - source: KnowledgeSource; - adapter: IKnowledgeAdapter; - /** The split applied for an adapter that takes chunks; absent for one that does not. */ - split?: ResolvedSplit; - /** The fingerprint and recipe hash every adapter call carries. */ - index: AdapterIndexExpectation; - /** The adapter context of a call made for `reason`, carrying `index`. */ - context(reason: NonNullable): AdapterContext; -} - -/** One build's durable writes ({@link KnowledgeService.rebuildOf}): its id once its start is recorded, and their chain. */ -interface DurableBuild { - buildId?: string; - chain: Promise; -} - -/** - * The part of the `queue` service the sync state reads while record syncs - * run through it: the pending count, and the dead letters a completed - * reconcile repairs (`IQueueService`). - */ -export type KnowledgeRecordSyncQueueView = Pick; - -/** The most dead letters a reconcile reads when it clears a source's repaired failures. */ -const DEAD_LETTER_SCAN_MAX = 100_000; - -/** A copy of a build record, so a caller never holds the live one. */ -function cloneBuildRecord(record: KnowledgeBuildRecord): KnowledgeBuildRecord { - return { ...record, progress: { ...record.progress } }; -} - -/** - * Rows one reindex page reads, and so the most documents one reindex `upsert` - * carries. A memory and request-size bound for the walk, not an embedder - * limit: an embedder that caps inputs per request splits a larger upsert into - * several requests itself (`OpenAIEmbedder` does). - */ -export const REINDEX_PAGE_SIZE = 100; - -/** - * The most documents one reindex result names in `failures`; `failed` counts - * them all. A source whose every document fails its split (a `whole` source - * over a small model's limit) answers a bounded result, not one entry per row. - */ -export const MAX_REINDEX_FAILURES = 20; - -/** - * Run `task` after every earlier task chained on the same `key` has settled — - * an in-process promise chain per key, dropped from `tails` once idle. - * Answers `task`'s own outcome (rejection included); the chain itself never - * rejects, so a failed task does not break the tasks queued behind it. - */ -function chainAfter( - tails: Map>, - key: string, - task: () => Promise, -): Promise { - const previous = tails.get(key) ?? Promise.resolve(); - const outcome = previous.then(task); - const tail: Promise = outcome.then(() => undefined, () => undefined).finally(() => { - if (tails.get(key) === tail) tails.delete(key); - }); - tails.set(key, tail); - return outcome; -} - -/** - * [#38413] {@link chainAfter} over several keys at once: run `task` after - * every earlier task chained on any of `keys` has settled, and hold each of - * them until `task` settles. A record-sync batch holds the chain of every - * document it writes. - */ -function chainAfterAll( - tails: Map>, - keys: readonly string[], - task: () => Promise, -): Promise { - const previous = Promise.all(keys.map((key) => tails.get(key) ?? Promise.resolve())); - const outcome = previous.then(task); - const settled = outcome.then(() => undefined, () => undefined); - for (const key of new Set(keys)) { - const tail: Promise = settled.finally(() => { - if (tails.get(key) === tail) tails.delete(key); - }); - tails.set(key, tail); - } - return outcome; -} - -/** [#38413] One group of a record-sync batch: the messages of one source over one object. */ -interface RecordSyncGroup { - source: KnowledgeSource; - object: string; - engine: IDataEngine; - items: Array<{ index: number; recordId: string; publishedAt?: number }>; -} - -/** - * The sources whose per-record projection of `object` is kept in step - * with row changes — i.e. those the service may upsert into, delete from, or - * (since #4672) de-index on behalf of, in reaction to a row's lifecycle. - * - * One definition, deliberately: the event-sync path - * (`handleRecordUpsert` / `handleRecordDelete`) and the lifecycle reap guard - * (`knowledge-reap-guard.ts`) are the two halves of one responsibility, and a - * second copy of this predicate is exactly how they would drift into disagreeing - * about which sources a row's disappearance concerns. - * - * `refresh.onRecordChange: false` opts a source out of both halves: it declares - * that an external indexer owns the index, and the reap guard vetoes rows whose - * de-index fails — so honouring it here is also what keeps an opted-out source - * from ever holding up another package's retention. - */ -export function objectSourcesFor(sources: KnowledgeSource[], object: string): KnowledgeSource[] { - return sources.filter( - (source) => - source.source.object === object && - (source.refresh?.onRecordChange ?? true) !== false, - ); -} - -/** - * The RLS-bypassing system context of the service's own reads: the reindex - * walk, the event sync's re-read and the purge's, which decide index - * MEMBERSHIP (`where`), never what a caller may read — search re-checks every - * hit as the caller. - */ -function systemContext(): ExecutionContext { - return { positions: [], permissions: [], systemPermissions: [], isSystem: true }; -} - -/** - * THE membership re-read: the row `recordId` names, read under the system - * context and the source's `where` — `find(object, { where: where AND id, - * limit: 1 })` — so the database answers whether the row belongs in the - * index, never an event payload or an earlier read. `undefined` when no row - * matches (none exists, or it does not match `where`). Throws what `find` - * throws, and throws when `find` answers no list: "no row" is a verdict the - * purge deletes on, so a malformed answer is never read as one. - * - * One definition for both of its readers, the event sync - * ({@link KnowledgeService.handleRecordUpsert}) and the purge - * ({@link purgeDocuments}): they decide the same question, and a second copy - * is how they would drift into answering it differently. - */ -async function rereadRow( - engine: IDataEngine, - objSource: ObjectKnowledgeSource, - recordId: string | number, -): Promise | undefined> { - const byId = { id: recordId }; - const rows = await engine.find( - objSource.object, - { where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, limit: 1 }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) { - throw new Error(`the re-read of record '${String(recordId)}' answered ${describeValue(rows)} instead of a list of rows`); - } - return rows[0] as Record | undefined; -} - -/** - * [#38413] {@link rereadRow} for many records in one read: - * `find(object, { where: where AND id in ids, limit: ids.length })` under the - * system context. An id no row came back for does not match (none exists, or - * it does not match `where`). Throws what `find` throws, and throws when - * `find` answers no list. - */ -async function rereadRows( - engine: IDataEngine, - objSource: ObjectKnowledgeSource, - recordIds: readonly string[], -): Promise>> { - const byIds = { id: { $in: [...recordIds] } }; - const rows = await engine.find( - objSource.object, - { where: objSource.where !== undefined ? { $and: [objSource.where, byIds] } : byIds, limit: recordIds.length }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) { - throw new Error(`the re-read of ${recordIds.length} records answered ${describeValue(rows)} instead of a list of rows`); - } - return rows as Array>; -} - -/** - * Entries one `listDocuments` call asks for. A memory bound per call, not a - * contract limit: the adapter may answer fewer. - */ -export const LIST_DOCUMENTS_PAGE_SIZE = 500; - -/** - * How many times `topK` a search asks each source for in its first - * round, when the permission re-check can remove hits ({@link - * KnowledgeService.search}). - */ -export const SEARCH_FIRST_ROUND_FACTOR = 5; - -/** - * How many times `topK` the one refill round asks a source for, when the - * survivors of the re-check name fewer than `topK` records — the cap on what a - * search reads: a caller who may read fewer than `topK` of the rows within the - * cap gets fewer than `topK` hits. - */ -export const SEARCH_REFILL_FACTOR = 20; - -/** - * How many times a record-level search re-runs the freshness check when hits - * it was about to answer turned out stale and others moved up - * ({@link KnowledgeService.search}). A hit still unchecked after the last - * round is not answered. - */ -export const SEARCH_FRESHNESS_ROUNDS = 3; - -/** What {@link listAdapterDocuments} learned: every listed id → its stored hash, or why there is no listing. */ -type AdapterListing = - | { ok: true; documents: Map } - /** `reason` is absent when the adapter has no `listDocuments`; present when the listing failed. */ - | { ok: false; reason?: string }; - -/** - * Read every page of the adapter's `listDocuments` for `source`. Never throws: - * an adapter without the method answers `{ ok: false }` with no reason, and a - * listing that throws or answers a malformed page or a cursor it already gave - * (a listing that would never end) answers `{ ok: false, reason }`. - */ -async function listAdapterDocuments( - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - index: AdapterIndexExpectation, -): Promise { - if (typeof adapter.listDocuments !== 'function') return { ok: false }; - const documents = new Map(); - const cursors = new Set(); - let cursor: string | undefined; - try { - for (;;) { - const page = await adapter.listDocuments( - { source, reason: 'reindex', index }, - cursor === undefined ? { limit: LIST_DOCUMENTS_PAGE_SIZE } : { cursor, limit: LIST_DOCUMENTS_PAGE_SIZE }, - ); - if (!page || !Array.isArray(page.documents)) return { ok: false, reason: 'a page carried no documents list' }; - for (const entry of page.documents) { - if (typeof entry?.documentId !== 'string') return { ok: false, reason: 'an entry carried no documentId' }; - documents.set(entry.documentId, typeof entry.docHash === 'string' ? entry.docHash : undefined); - } - if (page.nextCursor === undefined) return { ok: true, documents }; - if (cursors.has(page.nextCursor)) { - return { ok: false, reason: `the cursor '${page.nextCursor}' came back twice, so the listing would never end` }; - } - cursors.add(page.nextCursor); - cursor = page.nextCursor; - } - } catch (err) { - return { ok: false, reason: operatorText(err) }; - } -} - -/** Input of {@link purgeDocuments}. */ -export interface PurgeDocumentsInput { - source: KnowledgeSource; - objSource: ObjectKnowledgeSource; - adapter: IKnowledgeAdapter; - engine: IDataEngine; - /** Document ids believed stale: listed by the adapter, not produced from a current row. */ - candidates: Iterable; - /** - * Runs one candidate's confirm-and-delete after every earlier sync of that - * document has finished, answering the task's own outcome — the service - * passes its per-document record-sync chain, so an event sync of the same - * row can never land between the purge's re-read and its delete. - */ - serialize: (documentId: string, task: () => Promise) => Promise; - /** Diagnostics tag on the adapter's `delete`. @default 'reindex' */ - reason?: string; - /** The fingerprint and recipe hash the adapter's `delete` carries (ADR-0161 K8, item 8 a). */ - index?: AdapterIndexExpectation; -} - -/** Outcome of {@link purgeDocuments}. */ -export interface PurgeDocumentsOutcome { - /** Candidates deleted. */ - purged: number; - /** Candidates whose row the re-read found: kept. */ - kept: number; - /** Candidates whose id this source does not derive from a record id: kept, nothing can confirm them. */ - foreign: number; - /** Why the purge stopped early (a re-read or a delete that threw); absent when it went through every candidate. */ - failure?: string; -} - -/** - * The index purge (ADR-0161 K8, item 1): delete the candidates whose row is - * gone. Each candidate is confirmed by {@link rereadRow} — the event sync's - * own re-read, `where` AND id under the system context — and deleted only - * when that finds no row, so a document whose row was created, restored or - * came back into `where` since the candidates were computed is kept. Stops at - * the first re-read or delete that throws (a re-read that answers no list - * included), counting what it did before. - * - * Record ids are text. The knowledge service treats a record id as text: the - * record id is recovered from the document id as text, and the re-read asks - * for that text. A caller-supplied NUMERIC record id on driver-memory or - * driver-mongodb, which keep the id as given and do not equate `'5'` with - * `5`, is not supported. The re-read does not find such a row, so if its - * document is a candidate while the row exists (it was restored, or came back - * into `where`, after the walk read past it), the document is deleted; the row - * is untouched, and its document returns at the row's next event or the next - * complete reindex. Ids the platform mints are text on every driver. Asking - * again by the number is not done: on driver-sql the number is bound against - * the text `id` column, which MySQL compares numerically (`'05'` matches `5`) - * and SQL Server and Oracle reject outright, and the object schema does not - * say which ids are numeric. - * - * The caller decides when a purge may run at all (a complete reindex walk, - * which is also what the reconcile runs) and computes the candidates. - */ -export async function purgeDocuments(input: PurgeDocumentsInput): Promise { - const { source, objSource, adapter, engine } = input; - const prefix = `${source.name}:`; - const outcome: PurgeDocumentsOutcome = { purged: 0, kept: 0, foreign: 0 }; - for (const documentId of input.candidates) { - const recordId = documentId.startsWith(prefix) ? documentId.slice(prefix.length) : ''; - if (recordId === '') { - outcome.foreign++; - continue; - } - try { - const deleted = await input.serialize(documentId, async () => { - if (await rereadRow(engine, objSource, recordId)) return false; - await adapter.delete([documentId], { - source, - reason: input.reason ?? 'reindex', - ...(input.index === undefined ? {} : { index: input.index }), - }); - return true; - }); - if (deleted) outcome.purged++; - else outcome.kept++; - } catch (err) { - outcome.failure = `document '${documentId}': ${operatorText(err)}`; - return outcome; - } - } - return outcome; -} - -/** - * The version of the {@link computeDocHash} recipe, the hash's prefix. Bump it - * when what the hash covers or how it serializes changes: every stored hash - * then reads as changed, and the next complete reindex writes every document - * once. - * - * Not bumped for `organizationId` (ADR-0161 K8, item 9): the organization - * enters the hashed body only when the document carries one, so a document - * without one hashes as it did before, and only the documents that gained an - * organization read as changed — exactly the ones a complete reindex must - * write again for a walled search to rank them. - */ -export const DOC_HASH_VERSION = 'v1'; - -/** - * A document's `docHash` (ADR-0161 K8, item 2): SHA-256 over its content, - * title and metadata — and its organization, when it carries one (item 9) — - * serialized with object keys in a stable order, behind - * the {@link DOC_HASH_VERSION} prefix. The same assembled document gives the - * same hash on every machine, whatever order its metadata keys were built in. - */ -export function computeDocHash(doc: Pick): string { - const body = stableJson({ - content: doc.content, - title: doc.title ?? null, - metadata: doc.metadata ?? {}, - ...(doc.organizationId === undefined ? {} : { organizationId: doc.organizationId }), - }); - return `${DOC_HASH_VERSION}:${createHash('sha256').update(body).digest('hex')}`; -} - -/** `JSON.stringify` with every plain object's keys sorted, and a bigint as its decimal text. */ -function stableJson(value: unknown): string { - return JSON.stringify(value, (_key, v: unknown) => { - if (typeof v === 'bigint') return v.toString(); - if (v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype) { - const sorted: Record = {}; - for (const k of Object.keys(v as Record).sort()) sorted[k] = (v as Record)[k]; - return sorted; - } - return v; - }); -} - -/** How a non-list answer is named in a refusal: `null`, `undefined`, or its `typeof`. */ -function describeValue(value: unknown): string { - return value === null ? 'null' : value === undefined ? 'undefined' : `a value of type ${typeof value}`; -} - -/** A thrown value's text: an `Error`'s message, anything else as a string. */ -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err); -} - -/** - * An adapter error as an operator reads it: its message, then its `remedy` - * when it carries one — operator text such as the SQL to run, which an adapter - * keeps out of the message (ADR-0161 K7, rule 5). For a reindex result and the - * log; a search caller reads the message alone. - */ -function operatorText(err: unknown): string { - const remedy = err !== null && typeof err === 'object' ? (err as { remedy?: unknown }).remedy : undefined; - return typeof remedy === 'string' && remedy !== '' ? `${errorText(err)} ${remedy}` : errorText(err); -} - -/** A record id the event sync can re-read by: a non-empty string or a finite number. */ -function isRecordId(value: unknown): value is string | number { - return (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value)); -} - -/** - * A document's `title` (ADR-0161 K5): the value of the object's display field - * ({@link documentTitleField}), read from the record when it is non-empty text - * or a finite number. `undefined` when the field is withheld (credential-class - * or `internal`), empty, or not one of those values. Not - * `resolveRecordDisplayName`: its `Record #` floor is a UI label, not - * index content. - */ -function documentTitle( - record: Record, - schema: unknown, - withheld: ReadonlySet, -): string | undefined { - const field = documentTitleField(schema); - if (field === undefined || withheld.has(field)) return undefined; - const value = record[field]; - if (typeof value === 'string') return value.trim().length > 0 ? value : undefined; - if (typeof value === 'number' && Number.isFinite(value)) return String(value); - return undefined; -} - -/** - * How many groups `hits` name, by `groupOf` — what {@link KnowledgeService.search} - * counts toward `topK` when it decides whether to refill: several passages of - * one record (or of one `groupBy` value) count once. A hit with no group - * counts for nothing. - */ -function distinctGroups(hits: KnowledgeHit[], groupOf: (hit: KnowledgeHit) => string | undefined): number { - const keys = new Set(); - for (const hit of hits) { - const key = groupOf(hit); - if (key !== undefined) keys.add(key); - } - return keys.size; -} - -/** - * [`source.documentBy`] A hit's group under record granularity with no - * `groupBy`: the parent record its source's document unit names, keyed with - * the hit's source, so two sources never share a group however equal their - * parent ids. The parent is read from the hit itself, `metadata[documentBy]`, - * the value assembly stored beside the passage (the parse holds `documentBy` - * in `metadataFields`), so grouping reads no record: it runs over the hits the - * adapters already answered. A hit with no parent to group by — its source - * declares no `documentBy`, or the value is absent, null, empty, or not a - * string or a number — is its own record ({@link recordKeyOf}), never dropped. - * Values are compared as strings, as a scope term compares them. - */ -function documentKeyOf(hit: KnowledgeHit, documentBy: string | undefined): string { - const parent = documentBy === undefined ? undefined : documentUnitValueOf(hit.metadata, documentBy); - return parent === undefined ? recordKeyOf(hit) : `parent:${hit.sourceId}#${String(parent)}`; -} - -/** A hit's record: its source and record id; a hit that names no record is its document. */ -function recordKeyOf(hit: KnowledgeHit): string { - return hit.sourceRecordId !== undefined ? `record:${hit.sourceId}#${hit.sourceRecordId}` : `document:${hit.documentId}`; -} - -/** - * The projection of the freshness check's read: every field - * {@link recordToDocument} reads for `objSource` — `id`, the content and - * metadata fields, the title field, and `organization_id` under a walled - * posture. `undefined` (read the whole row, as the walk and the event sync - * do) when the object's fields cannot be enumerated, or when a field the source names is not one the object declares: - * assembly reads such a field off the whole row, and a projection that left it - * out would recompute a different hash and read every record as stale. - */ -function freshnessFields( - objSource: ObjectKnowledgeSource, - schema: unknown, - posture: TenancyPosture | undefined, -): string[] | undefined { - const declared = declaredFields(schema); - if (declared === undefined) return undefined; - const names = new Set(declared.map(([name]) => name)); - const wanted = new Set(['id', ...objSource.content, ...(objSource.metadataFields ?? [])]); - const titleField = documentTitleField(schema); - if (titleField !== undefined) wanted.add(titleField); - if (posture !== undefined && postureEnforcesWall(posture)) wanted.add('organization_id'); - for (const name of wanted) if (name !== 'id' && !names.has(name)) return undefined; - return [...wanted]; -} - -/** - * A caller-supplied field name as a log line or refusal shows it: JSON-quoted - * (so a quote or line break in it cannot forge text around it) and cut at 64 - * characters. - */ -function quotedName(name: string): string { - return JSON.stringify(name.length > 64 ? `${name.slice(0, 64)}…` : name); -} - -/** Deterministic document id derived from the source + record id. */ -export function documentIdFor(sourceId: string, recordId: string): string { - return `${sourceId}:${recordId}`; -} - -/** - * Project an ObjectQL record into a `KnowledgeDocument` per the - * source's `content` / `metadataFields` config. Pure function. - * - * `schema` (the record's registered object definition) names the fields an - * index never carries: credential-class fields (the set the engine masks on - * read) and `internal: true` fields (the set it omits), asked through the same - * collectors the write-response helper uses (`@objectstack/core`). They are - * SKIPPED when a source names one as content or metadata, rather than - * indexed masked: an index document is searchable text - * served to every reader the source admits, and a mask placeholder is no - * content. Without a schema nothing is withheld here (the engine's event body - * and read path still apply their own projection upstream). - * - * The `title` is the value of the object's display field ({@link - * documentTitle}); with no schema, of a field named `title`. - * - * `posture` (the deployment's effective tenancy posture) decides the - * document's `organizationId` (ADR-0161 K8, item 9): the record's - * `organization_id` under `group` and `isolated`, none under `single` or with - * no posture — `documentOrganizationId`. The organization enters `docHash` - * only when the document carries one. - */ -export function recordToDocument( - source: KnowledgeSource, - objSource: ObjectKnowledgeSource, - record: Record, - schema?: unknown, - posture?: TenancyPosture, -): KnowledgeDocument { - const withheld = new Set([ - ...collectCredentialWriteResponseFields(schema), - ...collectInternalWriteResponseFields(schema), - ]); - const recordId = String(record.id ?? (record as any)._id ?? ''); - const contentParts: string[] = []; - for (const field of objSource.content) { - if (withheld.has(field)) continue; - const v = record[field]; - if (v != null) contentParts.push(String(v)); - } - const metadata: Record = {}; - for (const field of objSource.metadataFields ?? []) { - if (withheld.has(field)) continue; - if (record[field] !== undefined) metadata[field] = record[field]; + return KnowledgeAdmissionFacet.applyPermissionFilter.call(knowledgeServiceHost.of(this), hits, ctx, liveTitles); + } + + // [#38660] The one place that reads this class's private members for its facets: the host each + // stub hands its body (`knowledge-service-host.ts`), built once per service on first use. + static { + knowledgeServiceHost.install((service) => ({ + adapterFor: (...a) => service.adapterFor(...a), + adapterIdFor: (...a) => service.adapterIdFor(...a), + adapterLabel: (...a) => service.adapterLabel(...a), + get adapters() { return service.adapters; }, + admissionDeps: (...a) => service.admissionDeps(...a), + admitSources: (...a) => service.admitSources(...a), + affinityFactsOf: (...a) => service.affinityFactsOf(...a), + affinityOrderFor: (...a) => service.affinityOrderFor(...a), + answerByRecord: (...a) => service.answerByRecord(...a), + applyPermissionFilter: (...a) => service.applyPermissionFilter(...a), + armReconcile: (...a) => service.armReconcile(...a), + get backlogReconciles() { return service.backlogReconciles; }, + boundAdapterId: (...a) => service.boundAdapterId(...a), + buildIfDue: (...a) => service.buildIfDue(...a), + buildUnderLease: (...a) => service.buildUnderLease(...a), + get builds() { return service.builds; }, + get buildsStopped() { return service.buildsStopped; }, + set buildsStopped(v) { service.buildsStopped = v; }, + cancelPendingReconcile: (...a) => service.cancelPendingReconcile(...a), + checkFreshness: (...a) => service.checkFreshness(...a), + checkScope: (...a) => service.checkScope(...a), + clearRepairedFailures: (...a) => service.clearRepairedFailures(...a), + closeStaleBuild: (...a) => service.closeStaleBuild(...a), + completeBuild: (...a) => service.completeBuild(...a), + considerBacklogReconcile: (...a) => service.considerBacklogReconcile(...a), + coveredByBuild: (...a) => service.coveredByBuild(...a), + deadLettersOf: (...a) => service.deadLettersOf(...a), + get defaultTopK() { return service.defaultTopK; }, + describeSources: (...a) => service.describeSources(...a), + dropUnverifiedHits: (...a) => service.dropUnverifiedHits(...a), + get enablementPending() { return service.enablementPending; }, + set enablementPending(v) { service.enablementPending = v; }, + enqueueReconcile: (...a) => service.enqueueReconcile(...a), + faceOfKey: (...a) => service.faceOfKey(...a), + facedRefusals: (...a) => service.facedRefusals(...a), + forget: (...a) => service.forget(...a), + get freshnessRepairs() { return service.freshnessRepairs; }, + getAdapter: (...a) => service.getAdapter(...a), + groupKeyOf: (...a) => service.groupKeyOf(...a), + handed: (...a) => service.handed(...a), + handedSources: (...a) => service.handedSources(...a), + get held() { return service.held; }, + set held(v) { service.held = v; }, + label: (...a) => service.label(...a), + listAdapters: (...a) => service.listAdapters(...a), + get options() { return service.options; }, + get pendingReconciles() { return service.pendingReconciles; }, + pendingRecordSyncs: (...a) => service.pendingRecordSyncs(...a), + planIndex: (...a) => service.planIndex(...a), + planSearches: (...a) => service.planSearches(...a), + prepareDocuments: (...a) => service.prepareDocuments(...a), + publishRecordSyncs: (...a) => service.publishRecordSyncs(...a), + readChunkTarget: (...a) => service.readChunkTarget(...a), + readIndexStateOf: (...a) => service.readIndexStateOf(...a), + readTenancyPosture: (...a) => service.readTenancyPosture(...a), + readVisibleIds: (...a) => service.readVisibleIds(...a), + rebuildOf: (...a) => service.rebuildOf(...a), + reconcileExclusion: (...a) => service.reconcileExclusion(...a), + reconcileOf: (...a) => service.reconcileOf(...a), + reconcilePass: (...a) => service.reconcilePass(...a), + get reconcileTail() { return service.reconcileTail; }, + set reconcileTail(v) { service.reconcileTail = v; }, + get reconcileUnlistedReported() { return service.reconcileUnlistedReported; }, + recordBuildEnd: (...a) => service.recordBuildEnd(...a), + recordBuildProgress: (...a) => service.recordBuildProgress(...a), + recordBuildStart: (...a) => service.recordBuildStart(...a), + get recordSyncBacklog() { return service.recordSyncBacklog; }, + set recordSyncBacklog(v) { service.recordSyncBacklog = v; }, + get recordSyncPublisher() { return service.recordSyncPublisher; }, + get recordSyncQueueView() { return service.recordSyncQueueView; }, + get recordSyncTails() { return service.recordSyncTails; }, + recordSyncWaiting: (...a) => service.recordSyncWaiting(...a), + refuseUnplacedSource: (...a) => service.refuseUnplacedSource(...a), + get registry() { return service.registry; }, + get reindexTails() { return service.reindexTails; }, + reindexWith: (...a) => service.reindexWith(...a), + repairStale: (...a) => service.repairStale(...a), + reportGateFailure: (...a) => service.reportGateFailure(...a), + reportUnindexable: (...a) => service.reportUnindexable(...a), + reportWhereUnenforceable: (...a) => service.reportWhereUnenforceable(...a), + requestSourceReconcile: (...a) => service.requestSourceReconcile(...a), + requireEntry: (...a) => service.requireEntry(...a), + resolveRecordSync: (...a) => service.resolveRecordSync(...a), + resolveSearchTargets: (...a) => service.resolveSearchTargets(...a), + get runningBuildIds() { return service.runningBuildIds; }, + schemaFor: (...a) => service.schemaFor(...a), + get scopeAmbiguousReported() { return service.scopeAmbiguousReported; }, + scopeByOrganization: (...a) => service.scopeByOrganization(...a), + get scopeIgnoredReported() { return service.scopeIgnoredReported; }, + searchByKey: (...a) => service.searchByKey(...a), + searchRound: (...a) => service.searchRound(...a), + searchWithRefusals: (...a) => service.searchWithRefusals(...a), + serializeRecordSync: (...a) => service.serializeRecordSync(...a), + get sourceListeners() { return service.sourceListeners; }, + sourceRowCount: (...a) => service.sourceRowCount(...a), + get sourceRows() { return service.sourceRows; }, + sourcesChanged: (...a) => service.sourcesChanged(...a), + sourcesForObject: (...a) => service.sourcesForObject(...a), + sourcesGroupableBy: (...a) => service.sourcesGroupableBy(...a), + sourcesInScope: (...a) => service.sourcesInScope(...a), + sourcesNarrowedToVisible: (...a) => service.sourcesNarrowedToVisible(...a), + storedCounts: (...a) => service.storedCounts(...a), + syncRecord: (...a) => service.syncRecord(...a), + syncRecordGroup: (...a) => service.syncRecordGroup(...a), + syncRow: (...a) => service.syncRow(...a), + syncRows: (...a) => service.syncRows(...a), + syncStateIdentity: (...a) => service.syncStateIdentity(...a), + get syncStateRecorded() { return service.syncStateRecorded; }, + syncStateWriteFailed: (...a) => service.syncStateWriteFailed(...a), + get syncStateWriteReported() { return service.syncStateWriteReported; }, + set syncStateWriteReported(v) { service.syncStateWriteReported = v; }, + unmountedAdapterSaveText: (...a) => service.unmountedAdapterSaveText(...a), + unprovenIndex: (...a) => service.unprovenIndex(...a), + walkObjectSource: (...a) => service.walkObjectSource(...a), + get whereUnenforceableReported() { return service.whereUnenforceableReported; }, + writeSynced: (...a) => service.writeSynced(...a), + })); } - const doc: KnowledgeDocument = { - id: documentIdFor(source.name, recordId || `unknown-${Date.now()}`), - sourceId: source.name, - sourceRecordId: recordId || undefined, - content: contentParts.join('\n\n'), - title: documentTitle(record, schema, withheld), - metadata, - }; - const organizationId = documentOrganizationId(record, posture); - if (organizationId !== undefined) doc.organizationId = organizationId; - doc.docHash = computeDocHash(doc); - return doc; } From 525fb38d9fd20506681199eb7162bae6ca325f40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:39:07 +0000 Subject: [PATCH 02/23] refactor(service-knowledge): register KnowledgeService in the facade gate Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- .changeset/38660-knowledge-service-split.md | 10 +++++++++ scripts/check-facade-delegation-only.mjs | 1 + scripts/facade-delegation-registry.json | 24 +++++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 .changeset/38660-knowledge-service-split.md diff --git a/.changeset/38660-knowledge-service-split.md b/.changeset/38660-knowledge-service-split.md new file mode 100644 index 00000000000..6699a14568f --- /dev/null +++ b/.changeset/38660-knowledge-service-split.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-knowledge': patch +--- + +refactor(service-knowledge): `KnowledgeService` keeps its members and forwards each to the module that owns its concern + +Clause-②: no +Metadata-protocol: none + +An internal move with no behaviour change. The bodies of `KnowledgeService` now live in five modules beside it (adapters and sources; build, index state and reconcile; record sync; search; save admission and scoping), and each member of the class forwards to its body in one call. Every member keeps its name, signature and docblock, so the package's public declaration is unchanged and nothing is added to or removed from the package entry. The published bundle's code moves between chunks; the published declaration file loses only the comments of private members and lists its declarations in another order. diff --git a/scripts/check-facade-delegation-only.mjs b/scripts/check-facade-delegation-only.mjs index 1b9b8cdb489..91dc5553869 100644 --- a/scripts/check-facade-delegation-only.mjs +++ b/scripts/check-facade-delegation-only.mjs @@ -227,6 +227,7 @@ const DECLARED_WATCH_HINTS = [ 'packages/objectql/src/engine.ts', 'packages/drivers/driver-sql/src/sql-driver.ts', 'packages/objectql/src/registry.ts', + 'packages/services/service-knowledge/src/knowledge-service.ts', ]; const CARD_REF = /^#[1-9][0-9]*$/; diff --git a/scripts/facade-delegation-registry.json b/scripts/facade-delegation-registry.json index 0b40c688413..ad74e8120ee 100644 --- a/scripts/facade-delegation-registry.json +++ b/scripts/facade-delegation-registry.json @@ -29,6 +29,11 @@ "file": "packages/objectql/src/registry.ts", "class": "SchemaRegistry", "card": "#33949" + }, + { + "file": "packages/services/service-knowledge/src/knowledge-service.ts", + "class": "KnowledgeService", + "card": "#38660" } ], "exceptions": [ @@ -160,6 +165,18 @@ "member": "judgePicklistArrival", "card": "#33949", "reason": "first-pass stay (the #33949 split codemod of PR #34285, kept in its branch history, not committed; the first pass of the engine codemod): bare-this: its body uses `this` other than as `this.member`, which needs the identity port (#30020 R1); a later pass on #33949 moves it, as the engine's fourth pass (#30055, #30020) moved the engine's" + }, + { + "file": "packages/services/service-knowledge/src/knowledge-service.ts", + "member": "constructor", + "card": "#38660", + "reason": "state-owning: gate reading, constructor logic (reads `defaultTopK` and `enabledByConfiguration` off the options into the instance's own fields with `??` and `===`; the state is the instance's)" + }, + { + "file": "packages/services/service-knowledge/src/knowledge-service.ts", + "member": "knowledgeTools", + "card": "#38660", + "reason": "bare-this: its body hands the service itself to `createKnowledgeTools(this)`, so the tool executor calls the service; a facet body is handed the host, not the service, so moving it would hand the executor the host" } ], "ceilings": [ @@ -190,6 +207,13 @@ "baseCommit": "c27f4ab0d6", "maxLines": 6426, "ruling": "6897467376" + }, + { + "file": "packages/services/service-knowledge/src/knowledge-service.ts", + "baseLines": 1658, + "baseCommit": "6ee3b9648f", + "maxLines": 1758, + "ruling": "6897467376" } ] } From 4c4a984345f27cd558be726c9ddf53ff36085b9f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:03:21 +0000 Subject: [PATCH 03/23] refactor(service-knowledge): facets as host-typed functions the census can read Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 8 +- .../src/knowledge-service-admission.ts | 930 ++++--- .../src/knowledge-service-host.ts | 142 +- .../src/knowledge-service-indexing.ts | 2450 +++++++++-------- .../src/knowledge-service-record-sync.ts | 1557 ++++++----- .../src/knowledge-service-search.ts | 1949 ++++++------- .../src/knowledge-service-sources.ts | 624 +++-- .../src/knowledge-service.ts | 10 +- scripts/tenant-audit-census.mjs | 6 + 9 files changed, 3923 insertions(+), 3753 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 7da4a341850..87f8f63a9b4 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -709,10 +709,10 @@ and CI refuses one that differs from what the tree produces. | `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 | -| `packages/services/service-knowledge/src/knowledge-service.ts#searchByKey` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitSources` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-admission.ts#applyPermissionFilter` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` | 1 | 46 | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts index b0d927eb6d4..5c5d0c96795 100644 --- a/packages/services/service-knowledge/src/knowledge-service-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -7,21 +7,23 @@ * `scopeByOrganization`, `sourcesForObject`, `applyPermissionFilter`, moved out of * `knowledge-service.ts` whole. * - * A MOVE, not a redesign. {@link KnowledgeAdmissionFacet} is a stateless facet of - * `KnowledgeService`: each static method is the body of the `KnowledgeService` - * member of the same name exactly as it stood (not re-indented, not edited). - * The member stays on the class as a one-call stub with its signature, so the - * published declaration, an instance spy and a subclass override are what they - * were. A public member keeps its docblock on the class, the contract; a - * private member's docblock moved here with its body. The state stays on - * `KnowledgeService`. + * A MOVE, not a redesign. Each function below is the body of the + * `KnowledgeService` member of the same name as it stood, re-indented one + * level and otherwise unedited (a line inside a string or template literal + * keeps its bytes). The member stays on the class as a one-call stub with its + * signature, so the published declaration, an instance spy and a subclass + * override are what they were; the class imports this module as + * `KnowledgeAdmissionFacet`. A public member keeps its docblock on the class, the + * contract; a private member's docblock moved here with its body. The state + * stays on `KnowledgeService`. * * A body reaches the service through `this`, typed as the part of - * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands - * it the host the class's static block builds once per service, whose methods call - * the service at call time and whose fields are getters (and a setter for a - * field a body assigns). A body that reads nothing of the service is called - * without one. `index.ts` re-exports nothing from this module. + * {@link KnowledgeAdmissionHost} it reads: the stub hands it the host the class's static + * block builds once per service (`knowledge-service-host.ts`), whose methods call the + * service at call time and whose fields are getters (and a setter for a field + * a body assigns). A body that reads nothing of the service is called without + * one. The module imports `knowledge-service.ts` for types only, so the two + * form no evaluation cycle. `index.ts` re-exports nothing from this module. */ import type { IDataEngine } from '@objectstack/spec/contracts'; @@ -62,489 +64,517 @@ import { operatorText, unplacedSourceText, } from './knowledge-service-top-level.js'; -import type { KnowledgeServiceHost } from './knowledge-service-host.js'; +import type { KnowledgeService } from './knowledge-service.js'; -export class KnowledgeAdmissionFacet { - /** - * [ADR-0090 D10 rule 1] The sources this caller's search may reach: a - * source over an object the caller's exposure decision refuses, or one - * serving a field the caller may not query, is not searched for that - * caller — see `knowledge-source-admission.ts` for the gates and why they are - * asked at source granularity. Computed once per (caller, object) per search. - * - * The system context bypasses, as it bypasses the row re-check. A caller - * with NO context, or a service with no data engine bound, cannot be judged - * and is served no source at all — never searched, so no passage of one can - * reach the caller through a hit the row re-check cannot place (a hit with - * no `sourceRecordId`). Fails CLOSED: a gate that throws refuses - * every source over that object, reported once at `error`. The objects' - * admissions are asked concurrently. - * - * An admitted source over which an index built under the earlier title - * rule could serve a field the gate does not ask about - * (`mayServeEarlierRuleTitle`) carries `proveIndex`: {@link planSearches} - * searches it only once its index is proven built under the current recipe. - * - * Each admitted source carries the organizations its search hands the - * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system - * context's bypass above covers that scope too: the system identity's - * search is handed no organization filter. - */ - static async admitSources( - this: Pick< - KnowledgeServiceHost, - 'admissionDeps' | 'label' | 'options' | 'reportGateFailure' | 'scopeByOrganization' - >, - sources: KnowledgeSource[], - ctx: ExecutionContext | undefined, - ): Promise { - if (ctx?.isSystem) return sources.map((source) => ({ source })); - const engine = this.options.dataEngine; - if (!ctx || !engine) { - if (sources.length > 0) { - this.options.logger?.warn?.( - !ctx - ? '[knowledge] retrieval with no ExecutionContext — no source is searched: a missing ' + - 'identity is not a grant of authority, so retrieval fails closed rather than searching the whole corpus unscoped. ' + - 'Pass the caller identity (or an explicit system context) to retrieve knowledge.' - : '[knowledge] no IDataEngine bound — no source is searched, to stay safe.', - ); - } - return []; - } - const deps = this.admissionDeps(engine); - const byObject = new Map>(); - for (const source of sources) { - const object = source.source.object; - if (byObject.has(object)) continue; - byObject.set( - object, - admitObject(object, ctx, deps).catch((err: unknown) => { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return undefined; - }), +/** + * The `KnowledgeService` members the bodies in this module read: every one + * of them, and no other. Each is typed AS the class member (an indexed + * access on the class), so a change to a member's type on the class is a change + * here too, and a name the class does not have does not compile. `readonly` + * members are methods and fields no body here assigns; the others are fields a + * body here assigns. + */ +export interface KnowledgeAdmissionHost { + readonly admissionDeps: KnowledgeService['admissionDeps']; + readonly handed: KnowledgeService['handed']; + readonly handedSources: KnowledgeService['handedSources']; + readonly held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly listAdapters: KnowledgeService['listAdapters']; + readonly options: KnowledgeService['options']; + readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; + readonly reportGateFailure: KnowledgeService['reportGateFailure']; + readonly schemaFor: KnowledgeService['schemaFor']; + readonly scopeByOrganization: KnowledgeService['scopeByOrganization']; + readonly unmountedAdapterSaveText: KnowledgeService['unmountedAdapterSaveText']; +} + +/** + * [ADR-0090 D10 rule 1] The sources this caller's search may reach: a + * source over an object the caller's exposure decision refuses, or one + * serving a field the caller may not query, is not searched for that + * caller — see `knowledge-source-admission.ts` for the gates and why they are + * asked at source granularity. Computed once per (caller, object) per search. + * + * The system context bypasses, as it bypasses the row re-check. A caller + * with NO context, or a service with no data engine bound, cannot be judged + * and is served no source at all — never searched, so no passage of one can + * reach the caller through a hit the row re-check cannot place (a hit with + * no `sourceRecordId`). Fails CLOSED: a gate that throws refuses + * every source over that object, reported once at `error`. The objects' + * admissions are asked concurrently. + * + * An admitted source over which an index built under the earlier title + * rule could serve a field the gate does not ask about + * (`mayServeEarlierRuleTitle`) carries `proveIndex`: {@link planSearches} + * searches it only once its index is proven built under the current recipe. + * + * Each admitted source carries the organizations its search hands the + * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system + * context's bypass above covers that scope too: the system identity's + * search is handed no organization filter. + */ +export async function admitSources( + this: Pick< + KnowledgeAdmissionHost, + 'admissionDeps' | 'label' | 'options' | 'reportGateFailure' | 'scopeByOrganization' + >, + sources: KnowledgeSource[], + ctx: ExecutionContext | undefined, +): Promise { + if (ctx?.isSystem) return sources.map((source) => ({ source })); + const engine = this.options.dataEngine; + if (!ctx || !engine) { + if (sources.length > 0) { + this.options.logger?.warn?.( + !ctx + ? '[knowledge] retrieval with no ExecutionContext — no source is searched: a missing ' + + 'identity is not a grant of authority, so retrieval fails closed rather than searching the whole corpus unscoped. ' + + 'Pass the caller identity (or an explicit system context) to retrieve knowledge.' + : '[knowledge] no IDataEngine bound — no source is searched, to stay safe.', ); } - const out: AdmittedSource[] = []; - for (const source of sources) { - const objSource = source.source; - const objectAdmission = await byObject.get(objSource.object); - if (!objectAdmission) continue; // the gate threw: reported once, refused. - const verdict: KnowledgeSourceAdmission = objectAdmission.refused - ? { admitted: false, reason: objectAdmission.refused, object: objSource.object } - : admitSourceFields(objSource, objectAdmission); - if (verdict.admitted) { - // An index built under the earlier title rule could serve a field - // the gate no longer asks about: searched only once its index is - // proven built under the current recipe ({@link planSearches}). - out.push(mayServeEarlierRuleTitle(objSource, objectAdmission.schema) ? { source, proveIndex: true } : { source }); - } else { - this.options.logger?.debug?.( - `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + - `(object='${verdict.object}'${verdict.field ? `, field='${verdict.field}'` : ''}).`, - ); - } + return []; + } + const deps = this.admissionDeps(engine); + const byObject = new Map>(); + for (const source of sources) { + const object = source.source.object; + if (byObject.has(object)) continue; + byObject.set( + object, + admitObject(object, ctx, deps).catch((err: unknown) => { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return undefined; + }), + ); + } + const out: AdmittedSource[] = []; + for (const source of sources) { + const objSource = source.source; + const objectAdmission = await byObject.get(objSource.object); + if (!objectAdmission) continue; // the gate threw: reported once, refused. + const verdict: KnowledgeSourceAdmission = objectAdmission.refused + ? { admitted: false, reason: objectAdmission.refused, object: objSource.object } + : admitSourceFields(objSource, objectAdmission); + if (verdict.admitted) { + // An index built under the earlier title rule could serve a field + // the gate no longer asks about: searched only once its index is + // proven built under the current recipe ({@link planSearches}). + out.push(mayServeEarlierRuleTitle(objSource, objectAdmission.schema) ? { source, proveIndex: true } : { source }); + } else { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + + `(object='${verdict.object}'${verdict.field ? `, field='${verdict.field}'` : ''}).`, + ); } - return this.scopeByOrganization(out, ctx); } + return this.scopeByOrganization(out, ctx); +} - /** What the source-admission gates read of the engine and the security service. */ - static admissionDeps(this: Pick, engine: IDataEngine): KnowledgeAdmissionDeps { - return { - readSchema: (object: string): unknown => { - const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; - return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; - }, - isObjectPackageDisabled: (object: string): boolean => - registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), - resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), - }; +/** What the source-admission gates read of the engine and the security service. */ +export function admissionDeps( + this: Pick, + engine: IDataEngine, +): KnowledgeAdmissionDeps { + return { + readSchema: (object: string): unknown => { + const getSchema = (engine as { getSchema?: (name: string) => unknown }).getSchema; + return typeof getSchema === 'function' ? getSchema.call(engine, object) : undefined; + }, + isObjectPackageDisabled: (object: string): boolean => + registryObjectPackageDisabled((engine as { registry?: unknown }).registry)(object), + resolveSecurity: (): KnowledgeFieldSecurity | undefined => this.options.resolveSecurity?.(), + }; +} + +/** The body of {@link KnowledgeService.admitAuthoredSource}; the member's docblock there is its contract. */ +export async function admitAuthoredSource( + this: Pick< + KnowledgeAdmissionHost, + 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' + >, + item: unknown, + ctx: ExecutionContext | undefined, + options?: { door?: 'save' | 'duplicate' }, +): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { + if (ctx?.isSystem) return { admitted: true }; + const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save']; + const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; + const declared = body.source as + | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } + | null + | undefined; + const object = declared && typeof declared === 'object' ? declared.object : undefined; + if (typeof object !== 'string' || object === '') return { admitted: true }; + const names = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; + const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }; + const where = listed.where; + const objSource: ObjectKnowledgeSource = { + kind: 'object', + object, + content: [...names(listed.content), ...names(listed.contentFields)], + metadataFields: names(listed.metadataFields), + ...(where !== null && typeof where === 'object' && !Array.isArray(where) + ? { where: where as Record } + : {}), + }; + const named = `The knowledge source${describeName(body)} ${wording.notDone}`; + const refuse = (status: number, code: string, message: string, field?: string) => + ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); + const unavailable = (why: string) => + refuse( + 503, + 'SERVICE_UNAVAILABLE', + `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + + `allowed to search what their source indexes.${wording.tryAgain}`, + ); + // [ADR-0161 K8, the dated note on item 12, ◆ an author's save and point 4] + // A service the runtime composed and that this boot read as not enabled + // holds every source, so an author's save would be kept and never served: + // refused at each door that saves one, naming the half that is missing. + // The package duplicate (`door: 'duplicate'`) is not refused for it, and + // the engine's own write was admitted above. + if (this.held && options?.door !== 'duplicate') { + return refuse(503, 'SERVICE_UNAVAILABLE', `${named}: ${heldSourceSaveText(this.held)}`); + } + if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`); + // [ADR-0161 K4 ◆] A source that names no adapter where this deployment + // cannot place one is refused at its save as at its registration, so the + // author hears it: several adapters registered, none the deployment's. + const authoredAdapter = (item as { adapter?: unknown } | null | undefined)?.adapter; + const registeredAdapters = this.listAdapters(); + if (authoredAdapter === undefined && this.options.deploymentAdapter === undefined && registeredAdapters.length > 1) { + return refuse(400, 'VALIDATION_ERROR', `${named}: it ${unplacedSourceText(registeredAdapters)}`); } + // [ADR-0161 K4] A source that names an adapter this deployment does not + // mount is refused at its save, so the author hears it there and not from + // the boot log or a search's 503. A save is served after every store's + // `start()`, so the adapters registered now are the deployment's. + if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { + return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); + } + const engine = this.options.dataEngine; + if (!engine) return unavailable('the knowledge service has no data engine'); - static async admitAuthoredSource( - this: Pick< - KnowledgeServiceHost, - 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' - >, - item: unknown, - ctx: ExecutionContext | undefined, - options?: { door?: 'save' | 'duplicate' }, - ): Promise<{ admitted: true } | { admitted: false; status: number; code: string; message: string; object: string; field?: string }> { - if (ctx?.isSystem) return { admitted: true }; - const wording = AUTHORED_SOURCE_DOOR_WORDING[options?.door === 'duplicate' ? 'duplicate' : 'save']; - const body = (item as { name?: unknown; source?: unknown } | null | undefined) ?? {}; - const declared = body.source as - | { object?: unknown; content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown } - | null - | undefined; - const object = declared && typeof declared === 'object' ? declared.object : undefined; - if (typeof object !== 'string' || object === '') return { admitted: true }; - const names = (value: unknown): string[] => - Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v !== '') : []; - const listed = declared as { content?: unknown; contentFields?: unknown; metadataFields?: unknown; where?: unknown }; - const where = listed.where; - const objSource: ObjectKnowledgeSource = { - kind: 'object', - object, - content: [...names(listed.content), ...names(listed.contentFields)], - metadataFields: names(listed.metadataFields), - ...(where !== null && typeof where === 'object' && !Array.isArray(where) - ? { where: where as Record } - : {}), - }; - const named = `The knowledge source${describeName(body)} ${wording.notDone}`; - const refuse = (status: number, code: string, message: string, field?: string) => - ({ admitted: false as const, status, code, message, object, ...(field === undefined ? {} : { field }) }); - const unavailable = (why: string) => - refuse( - 503, - 'SERVICE_UNAVAILABLE', - `${named}: whether you may search object '${object}' could not be judged (${why}), and an author must be ` + - `allowed to search what their source indexes.${wording.tryAgain}`, - ); - // [ADR-0161 K8, the dated note on item 12, ◆ an author's save and point 4] - // A service the runtime composed and that this boot read as not enabled - // holds every source, so an author's save would be kept and never served: - // refused at each door that saves one, naming the half that is missing. - // The package duplicate (`door: 'duplicate'`) is not refused for it, and - // the engine's own write was admitted above. - if (this.held && options?.door !== 'duplicate') { - return refuse(503, 'SERVICE_UNAVAILABLE', `${named}: ${heldSourceSaveText(this.held)}`); - } - if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: ${wording.act} carries no identity, and a missing identity is not a grant of authority.`); - // [ADR-0161 K4 ◆] A source that names no adapter where this deployment - // cannot place one is refused at its save as at its registration, so the - // author hears it: several adapters registered, none the deployment's. - const authoredAdapter = (item as { adapter?: unknown } | null | undefined)?.adapter; - const registeredAdapters = this.listAdapters(); - if (authoredAdapter === undefined && this.options.deploymentAdapter === undefined && registeredAdapters.length > 1) { - return refuse(400, 'VALIDATION_ERROR', `${named}: it ${unplacedSourceText(registeredAdapters)}`); - } - // [ADR-0161 K4] A source that names an adapter this deployment does not - // mount is refused at its save, so the author hears it there and not from - // the boot log or a search's 503. A save is served after every store's - // `start()`, so the adapters registered now are the deployment's. - if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { - return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); - } - const engine = this.options.dataEngine; - if (!engine) return unavailable('the knowledge service has no data engine'); + // [ADR-0161 K4, row 4] A reference to nothing is a permanent mistake, named + // by the rule `os validate` reports, ahead of every permission arm. + let absent: AbsentSourceReference | undefined; + try { + absent = absentSourceReference(objSource, listed, engine, this.admissionDeps(engine)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (absent?.kind === 'object') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.object\` names '${object}', which is not an object of this organization (neither one it ` + + 'authored nor one an installed package registers), so the source indexes nothing ' + + `(\`${KNOWLEDGE_SOURCE_OBJECT_UNKNOWN}\`, the rule \`os validate\` reports). Name an object the organization ` + + `has (check the spelling), or install the package that provides '${object}' first${wording.thenAgain}.`, + ); + } + if (absent?.kind === 'field') { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: \`source.${absent.key}\` names field '${absent.field}', which object '${object}' does not define, ` + + 'so the index reads nothing for it on any record ' + + `(\`${KNOWLEDGE_SOURCE_FIELD_UNKNOWN}\`, the rule \`os validate\` reports). Name a field of '${object}' ` + + `(check the spelling), or remove it from \`${absent.key}\`${wording.thenAgain}.`, + absent.field, + ); + } - // [ADR-0161 K4, row 4] A reference to nothing is a permanent mistake, named - // by the rule `os validate` reports, ahead of every permission arm. - let absent: AbsentSourceReference | undefined; + // [`source.documentBy`] A document unit that is no single-valued parent + // link is a permanent mistake too, judged on the object's definition alone + // by the parent-link rule the search scope reads. One not listed in + // `metadataFields` is left to the parse, which names that fix. + const documentBy = (declared as { documentBy?: unknown }).documentBy; + if (typeof documentBy === 'string' && objSource.metadataFields?.includes(documentBy)) { + let unit: DocumentUnitVerdict | undefined; try { - absent = absentSourceReference(objSource, listed, engine, this.admissionDeps(engine)); + const deps = this.admissionDeps(engine); + unit = deps.isObjectPackageDisabled(object) ? undefined : documentUnitOf(documentBy, deps.readSchema(object)); } catch (err) { this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); return unavailable(operatorText(err)); } - if (absent?.kind === 'object') { + if (unit !== undefined && !unit.unit) { return refuse( 400, 'VALIDATION_ERROR', - `${named}: \`source.object\` names '${object}', which is not an object of this organization (neither one it ` + - 'authored nor one an installed package registers), so the source indexes nothing ' + - `(\`${KNOWLEDGE_SOURCE_OBJECT_UNKNOWN}\`, the rule \`os validate\` reports). Name an object the organization ` + - `has (check the spelling), or install the package that provides '${object}' first${wording.thenAgain}.`, + `${named}: ${documentUnitRefusalText(object, documentBy, unit)}${wording.thenAgain}.`, + documentBy, ); } - if (absent?.kind === 'field') { - return refuse( - 400, - 'VALIDATION_ERROR', - `${named}: \`source.${absent.key}\` names field '${absent.field}', which object '${object}' does not define, ` + - 'so the index reads nothing for it on any record ' + - `(\`${KNOWLEDGE_SOURCE_FIELD_UNKNOWN}\`, the rule \`os validate\` reports). Name a field of '${object}' ` + - `(check the spelling), or remove it from \`${absent.key}\`${wording.thenAgain}.`, - absent.field, - ); - } - - // [`source.documentBy`] A document unit that is no single-valued parent - // link is a permanent mistake too, judged on the object's definition alone - // by the parent-link rule the search scope reads. One not listed in - // `metadataFields` is left to the parse, which names that fix. - const documentBy = (declared as { documentBy?: unknown }).documentBy; - if (typeof documentBy === 'string' && objSource.metadataFields?.includes(documentBy)) { - let unit: DocumentUnitVerdict | undefined; - try { - const deps = this.admissionDeps(engine); - unit = deps.isObjectPackageDisabled(object) ? undefined : documentUnitOf(documentBy, deps.readSchema(object)); - } catch (err) { - this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); - return unavailable(operatorText(err)); - } - if (unit !== undefined && !unit.unit) { - return refuse( - 400, - 'VALIDATION_ERROR', - `${named}: ${documentUnitRefusalText(object, documentBy, unit)}${wording.thenAgain}.`, - documentBy, - ); - } - } - - // [`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; + // [`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 { - admission = await admitObject(object, ctx, this.admissionDeps(engine)); + 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)); } - const verdict: KnowledgeSourceAdmission = admission.refused - ? { admitted: false, reason: admission.refused, object } - : admitSourceFields(objSource, admission); - if (verdict.admitted) return { admitted: true }; - switch (verdict.reason) { - case 'object-package-disabled': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: its object '${object}' belongs to a disabled package, and a disabled package's records are ` + - 'not indexed or searched. Enable the package, or index another object.', - ); - case 'object-api-not-served': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, its ` + - '`enable.apiMethods` list does not grant `list`, from which search derives, or it grants `list` beside ' + - "`enable.searchable: false`), and a knowledge search is a search over the object's records. " + - `Serve '${object}' for search: keep \`enable.apiEnabled\` true and, where it declares ` + - '`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object.', - ); - case 'system-object-not-ai-readable': - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: '${object}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), ` + - 'so its records are not indexed for retrieval.', - ); - case 'field-not-queryable': { - const field = verdict.field ?? ''; - if (verdict.use === 'where') { - return refuse( - 403, - 'PERMISSION_DENIED', - `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + - 'hidden from you, or served to you masked), and the source would select its records by that field. ' + - `Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`, - field, - ); - } - const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); + 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)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + const verdict: KnowledgeSourceAdmission = admission.refused + ? { admitted: false, reason: admission.refused, object } + : admitSourceFields(objSource, admission); + if (verdict.admitted) return { admitted: true }; + switch (verdict.reason) { + case 'object-package-disabled': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: its object '${object}' belongs to a disabled package, and a disabled package's records are ` + + 'not indexed or searched. Enable the package, or index another object.', + ); + case 'object-api-not-served': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, its ` + + '`enable.apiMethods` list does not grant `list`, from which search derives, or it grants `list` beside ' + + "`enable.searchable: false`), and a knowledge search is a search over the object's records. " + + `Serve '${object}' for search: keep \`enable.apiEnabled\` true and, where it declares ` + + '`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object.', + ); + case 'system-object-not-ai-readable': + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: '${object}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), ` + + 'so its records are not indexed for retrieval.', + ); + case 'field-not-queryable': { + const field = verdict.field ?? ''; + if (verdict.use === 'where') { return refuse( 403, 'PERMISSION_DENIED', - `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + - 'to you masked), and the index would hold its text unmasked. ' + - (listedByAuthor - ? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.` - : "The source does not list it: it is the object's display field, which every document carries as its " + - `title. Have someone who may query it ${wording.byWhoMay}.`), + `${named}: its \`where\` reads field '${field}' of object '${object}', which you may not query (it is ` + + 'hidden from you, or served to you masked), and the source would select its records by that field. ' + + `Remove the field from \`where\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.`, field, ); } - default: - return unavailable(`the security service did not answer which fields of '${object}' you may read`); + const listedByAuthor = objSource.content.includes(field) || (objSource.metadataFields ?? []).includes(field); + return refuse( + 403, + 'PERMISSION_DENIED', + `${named}: you may not query field '${field}' of object '${object}' (it is hidden from you, or served ` + + 'to you masked), and the index would hold its text unmasked. ' + + (listedByAuthor + ? `Remove the field from \`content\` and \`metadataFields\`${wording.thenAgain}, or have someone who may query it ${wording.byWhoMay}.` + : "The source does not list it: it is the object's display field, which every document carries as its " + + `title. Have someone who may query it ${wording.byWhoMay}.`), + field, + ); } + default: + return unavailable(`the security service did not answer which fields of '${object}' you may read`); } +} - /** - * Why a saved source naming `adapter`, which `mounted` does not hold, is - * refused, and what to write: the rule, then the remedies this deployment - * can take. Leaving `adapter` out is offered only where an omitted adapter - * would be placed ({@link adapterIdFor}). - */ - static unmountedAdapterSaveText( - this: Pick, - adapter: string, - mounted: readonly string[], - again: string, - ): string { - const deployment = this.options.deploymentAdapter; - const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1; - const remedies = [ - ...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]), - ...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []), - `mount the '${adapter}' store and ${again}`, - ]; - return ( - `it names adapter '${adapter}', which this deployment does not mount ` + - `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}), and a source's \`adapter\` must name a ` + - `mounted store. ${remedies.join(', or ').replace(/^./, (c) => c.toUpperCase())}.` - ); - } +/** + * Why a saved source naming `adapter`, which `mounted` does not hold, is + * refused, and what to write: the rule, then the remedies this deployment + * can take. Leaving `adapter` out is offered only where an omitted adapter + * would be placed ({@link adapterIdFor}). + */ +export function unmountedAdapterSaveText( + this: Pick, + adapter: string, + mounted: readonly string[], + again: string, +): string { + const deployment = this.options.deploymentAdapter; + const placeable = (deployment !== undefined && mounted.includes(deployment)) || mounted.length === 1; + const remedies = [ + ...(mounted.length === 0 ? [] : [`name one of ${mounted.map((id) => `'${id}'`).join(', ')} as its \`adapter\``]), + ...(placeable ? ["leave `adapter` out, and the deployment's store holds it"] : []), + `mount the '${adapter}' store and ${again}`, + ]; + return ( + `it names adapter '${adapter}', which this deployment does not mount ` + + `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}), and a source's \`adapter\` must name a ` + + `mounted store. ${remedies.join(', or ').replace(/^./, (c) => c.toUpperCase())}.` + ); +} + +/** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ +export function reportGateFailure(this: Pick, object: string, err: Error): void { + const report = + `[knowledge] the exposure or field-level read rules of object '${object}' could not be resolved ` + + `(${err.message}); no source over it is searched for this caller (fail-closed).`; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); +} - /** A gate lookup threw: every source over `object` is refused (fail-closed), reported once at `error`, `warn` as the fallback. */ - static reportGateFailure(this: Pick, object: string, err: Error): void { +/** The deployment's effective tenancy posture, or `undefined` when no resolver is wired. Throws what the resolver throws. */ +export async function readTenancyPosture( + this: Pick, +): Promise { + return this.options.resolveTenancyPosture ? await this.options.resolveTenancyPosture() : undefined; +} + +/** + * [ADR-0161 K8, item 9] Pair each source {@link admitSources} admitted for + * a caller that is NOT the system identity (admission's own bypass answers + * that one before this runs) with the organizations its search hands the + * adapter (`searchOrganizationIds`): computed here, from the caller's + * execution context and the deployment's posture, never from anything the + * caller passes. + * + * The posture is read once per search, and only when a source is admitted. + * A posture that cannot be read leaves every source unsearched for this call (fail-closed: whether a wall stands is unknown), + * reported at `error`, `warn` as the fallback. + */ +export async function scopeByOrganization( + this: Pick, + sources: AdmittedSource[], + ctx: ExecutionContext, +): Promise { + if (sources.length === 0) return []; + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { const report = - `[knowledge] the exposure or field-level read rules of object '${object}' could not be resolved ` + - `(${err.message}); no source over it is searched for this caller (fail-closed).`; + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no source is searched ` + + 'for this caller (fail-closed).'; if (this.options.logger?.error) this.options.logger.error(report); else this.options.logger?.warn?.(report); + return []; } + return sources.map((entry) => { + const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(entry.source.source.object)); + return organizationIds === undefined ? entry : { ...entry, organizationIds }; + }); +} - /** The deployment's effective tenancy posture, or `undefined` when no resolver is wired. Throws what the resolver throws. */ - static async readTenancyPosture(this: Pick): Promise { - return this.options.resolveTenancyPosture ? await this.options.resolveTenancyPosture() : undefined; - } +/** The body of {@link KnowledgeService.sourcesForObject}; the member's docblock there is its contract. */ +export function sourcesForObject(this: Pick, object: string): KnowledgeSource[] { + return objectSourcesFor(this.handedSources(), object); +} - /** - * [ADR-0161 K8, item 9] Pair each source {@link admitSources} admitted for - * a caller that is NOT the system identity (admission's own bypass answers - * that one before this runs) with the organizations its search hands the - * adapter (`searchOrganizationIds`): computed here, from the caller's - * execution context and the deployment's posture, never from anything the - * caller passes. - * - * The posture is read once per search, and only when a source is admitted. - * A posture that cannot be read leaves every source unsearched for this call (fail-closed: whether a wall stands is unknown), - * reported at `error`, `warn` as the fallback. - */ - static async scopeByOrganization( - this: Pick, - sources: AdmittedSource[], - ctx: ExecutionContext, - ): Promise { - if (sources.length === 0) return []; - let posture: TenancyPosture | undefined; - try { - posture = await this.readTenancyPosture(); - } catch (err) { - const report = - `[knowledge] the tenancy posture could not be read (${errorText(err)}); no source is searched ` + - 'for this caller (fail-closed).'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); - return []; - } - return sources.map((entry) => { - const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(entry.source.source.object)); - return organizationIds === undefined ? entry : { ...entry, organizationIds }; - }); - } +/** + * Drop hits whose underlying ObjectQL record the caller can't read. A hit + * with no `sourceRecordId`, or of a source nobody registered, cannot be + * re-checked and is dropped. + * + * Identity handling (#2981): an **explicit** `isSystem` context (indexing / + * trusted server jobs) passes every hit through — it is a deliberate, + * authored elevation. A **missing** context, however, is NOT a grant of + * authority: with no identity we cannot prove the caller may read the + * rows, so we FAIL CLOSED and drop every hit (the + * same conservative posture as a missing data engine). This closes the + * agent/RAG fall-open where an omitted `ToolExecutionContext.actor` used to + * return unfiltered semantic search over the whole corpus. + * + * With `liveTitles` (record granularity), the same read — as the caller, in + * the same query — also reads the object's display field + * (`documentTitleField`, the field assembly takes the title from), and a + * surviving hit's `title` is the record's title as it reads now, not as it + * was indexed. The field gate (`admitSourceFields`) already asked that the + * caller may query that field. + */ +export async function applyPermissionFilter( + this: Pick, + hits: KnowledgeHit[], + ctx: ExecutionContext | undefined, + liveTitles = false, +): Promise { + // Explicit elevation → pass through (indexing / trusted jobs). + if (ctx?.isSystem) return hits; + // No identity, or no engine to re-check with → no hit can be proven + // readable. `admitSources` already kept every source out of the search; + // this holds the same line for any hit that reached here anyway. + if (!ctx || !this.options.dataEngine) return []; - static sourcesForObject(this: Pick, object: string): KnowledgeSource[] { - return objectSourcesFor(this.handedSources(), object); + // Group hits by object so we make one query per object. + const byObject = new Map(); + for (const hit of hits) { + if (!hit.sourceRecordId) continue; + const source = this.handed(hit.sourceId); + if (!source) continue; + const objName = source.source.object; + const bucket = byObject.get(objName) ?? []; + bucket.push(hit); + byObject.set(objName, bucket); } - /** - * Drop hits whose underlying ObjectQL record the caller can't read. A hit - * with no `sourceRecordId`, or of a source nobody registered, cannot be - * re-checked and is dropped. - * - * Identity handling (#2981): an **explicit** `isSystem` context (indexing / - * trusted server jobs) passes every hit through — it is a deliberate, - * authored elevation. A **missing** context, however, is NOT a grant of - * authority: with no identity we cannot prove the caller may read the - * rows, so we FAIL CLOSED and drop every hit (the - * same conservative posture as a missing data engine). This closes the - * agent/RAG fall-open where an omitted `ToolExecutionContext.actor` used to - * return unfiltered semantic search over the whole corpus. - * - * With `liveTitles` (record granularity), the same read — as the caller, in - * the same query — also reads the object's display field - * (`documentTitleField`, the field assembly takes the title from), and a - * surviving hit's `title` is the record's title as it reads now, not as it - * was indexed. The field gate (`admitSourceFields`) already asked that the - * caller may query that field. - */ - static async applyPermissionFilter( - this: Pick, - hits: KnowledgeHit[], - ctx: ExecutionContext | undefined, - liveTitles = false, - ): Promise { - // Explicit elevation → pass through (indexing / trusted jobs). - if (ctx?.isSystem) return hits; - // No identity, or no engine to re-check with → no hit can be proven - // readable. `admitSources` already kept every source out of the search; - // this holds the same line for any hit that reached here anyway. - if (!ctx || !this.options.dataEngine) return []; - - // Group hits by object so we make one query per object. - const byObject = new Map(); - for (const hit of hits) { - if (!hit.sourceRecordId) continue; - const source = this.handed(hit.sourceId); - if (!source) continue; - const objName = source.source.object; - const bucket = byObject.get(objName) ?? []; - bucket.push(hit); - byObject.set(objName, bucket); - } - - const allowed = new Set(); // `${object}#${recordId}` - const titles = new Map(); // `${object}#${recordId}` → the title as it reads now - for (const [object, group] of byObject) { - const ids = [...new Set(group.map((h) => h.sourceRecordId!).filter(Boolean))]; - if (ids.length === 0) continue; - const schema = liveTitles ? this.schemaFor(object) : undefined; - const withheld = new Set([ - ...collectCredentialWriteResponseFields(schema), - ...collectInternalWriteResponseFields(schema), - ]); - const titleField = liveTitles ? documentTitleField(schema) : undefined; - const readsTitle = titleField !== undefined && titleField !== 'id' && !withheld.has(titleField); - try { - const rows = (await this.options.dataEngine.find(object, { - where: { id: { $in: ids } } as Record, - fields: readsTitle ? ['id', titleField] : ['id'], - context: ctx, - } as never)) as Array & { id?: string }>; - for (const row of rows) { - if (!row?.id) continue; - allowed.add(`${object}#${row.id}`); - if (!readsTitle) continue; - const title = documentTitle(row, schema, withheld); - if (title !== undefined) titles.set(`${object}#${row.id}`, title); - } - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] RLS lookup failed for object='${object}': ${(err as Error).message}; ` + - 'dropping that object\'s hits to stay safe.', - ); + const allowed = new Set(); // `${object}#${recordId}` + const titles = new Map(); // `${object}#${recordId}` → the title as it reads now + for (const [object, group] of byObject) { + const ids = [...new Set(group.map((h) => h.sourceRecordId!).filter(Boolean))]; + if (ids.length === 0) continue; + const schema = liveTitles ? this.schemaFor(object) : undefined; + const withheld = new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ]); + const titleField = liveTitles ? documentTitleField(schema) : undefined; + const readsTitle = titleField !== undefined && titleField !== 'id' && !withheld.has(titleField); + try { + const rows = (await this.options.dataEngine.find(object, { + where: { id: { $in: ids } } as Record, + fields: readsTitle ? ['id', titleField] : ['id'], + context: ctx, + } as never)) as Array & { id?: string }>; + for (const row of rows) { + if (!row?.id) continue; + allowed.add(`${object}#${row.id}`); + if (!readsTitle) continue; + const title = documentTitle(row, schema, withheld); + if (title !== undefined) titles.set(`${object}#${row.id}`, title); } + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] RLS lookup failed for object='${object}': ${(err as Error).message}; ` + + 'dropping that object\'s hits to stay safe.', + ); } + } - const out: KnowledgeHit[] = []; - for (const hit of hits) { - // A hit the re-check cannot place — no record id, or a source nobody - // registered — is not provably readable: dropped. - const source = this.handed(hit.sourceId); - if (!source || !hit.sourceRecordId) continue; - const key = `${source.source.object}#${hit.sourceRecordId}`; - if (!allowed.has(key)) continue; - const title = titles.get(key); - out.push(title === undefined ? hit : { ...hit, title }); - } - return out; + const out: KnowledgeHit[] = []; + for (const hit of hits) { + // A hit the re-check cannot place — no record id, or a source nobody + // registered — is not provably readable: dropped. + const source = this.handed(hit.sourceId); + if (!source || !hit.sourceRecordId) continue; + const key = `${source.source.object}#${hit.sourceRecordId}`; + if (!allowed.has(key)) continue; + const title = titles.get(key); + out.push(title === undefined ? hit : { ...hit, title }); } + return out; } diff --git a/packages/services/service-knowledge/src/knowledge-service-host.ts b/packages/services/service-knowledge/src/knowledge-service-host.ts index d033880a601..9e40213743c 100644 --- a/packages/services/service-knowledge/src/knowledge-service-host.ts +++ b/packages/services/service-knowledge/src/knowledge-service-host.ts @@ -1,15 +1,13 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#38660] What the facets of `KnowledgeService` (`knowledge-service-*.ts`) - * read of the service, and the one host per service that hands it to them. + * [#38660] The one host per `KnowledgeService` that its facets + * (`knowledge-service-*.ts`) are handed as `this`. * - * {@link KnowledgeServiceHost} names every member a moved body reads through `this`, - * each typed AS the class member (an indexed access on the class), so a change - * to a member's type on the class is a change here too, and a name the class - * does not have does not compile. `readonly` entries are methods and fields no - * body assigns; the others are fields a body assigns. Each facet method types - * its `this` as the `Pick` of this interface it reads. + * {@link KnowledgeServiceHost} is every facet's host at once: each facet declares, + * in its own module, the members its bodies read (its `...Host` interface, + * each member typed AS the class member), and each facet method types its + * `this` as the `Pick` of that interface it reads. * * The host is filled by the factory `KnowledgeService`'s static block installs, * the one place that can read the class's private members; it is built on the @@ -17,125 +15,23 @@ * closure that calls it on the service at call time, so an instance spy or a * subclass override is still the one reached; a field goes as a getter (and a * setter when a body assigns it), so a body reads and writes the service's own - * state. This module imports the class for types only, so it forms no - * evaluation cycle. `index.ts` re-exports nothing from it. + * state. This module imports the class and the facets for types only, so it + * forms no evaluation cycle. `index.ts` re-exports nothing from it. */ import type { KnowledgeService } from './knowledge-service.js'; +import type { KnowledgeSourcesHost } from './knowledge-service-sources.js'; +import type { KnowledgeIndexingHost } from './knowledge-service-indexing.js'; +import type { KnowledgeRecordSyncHost } from './knowledge-service-record-sync.js'; +import type { KnowledgeSearchHost } from './knowledge-service-search.js'; +import type { KnowledgeAdmissionHost } from './knowledge-service-admission.js'; -/** Every `KnowledgeService` member a moved body reads, typed as the class member. */ -export interface KnowledgeServiceHost { - readonly adapterFor: KnowledgeService['adapterFor']; - readonly adapterIdFor: KnowledgeService['adapterIdFor']; - readonly adapterLabel: KnowledgeService['adapterLabel']; - readonly adapters: KnowledgeService['adapters']; - readonly admissionDeps: KnowledgeService['admissionDeps']; - readonly admitSources: KnowledgeService['admitSources']; - readonly affinityFactsOf: KnowledgeService['affinityFactsOf']; - readonly affinityOrderFor: KnowledgeService['affinityOrderFor']; - readonly answerByRecord: KnowledgeService['answerByRecord']; - readonly applyPermissionFilter: KnowledgeService['applyPermissionFilter']; - readonly armReconcile: KnowledgeService['armReconcile']; - readonly backlogReconciles: KnowledgeService['backlogReconciles']; - readonly boundAdapterId: KnowledgeService['boundAdapterId']; - readonly buildIfDue: KnowledgeService['buildIfDue']; - readonly buildUnderLease: KnowledgeService['buildUnderLease']; - readonly builds: KnowledgeService['builds']; - buildsStopped: KnowledgeService['buildsStopped']; - readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; - readonly checkFreshness: KnowledgeService['checkFreshness']; - readonly checkScope: KnowledgeService['checkScope']; - readonly clearRepairedFailures: KnowledgeService['clearRepairedFailures']; - readonly closeStaleBuild: KnowledgeService['closeStaleBuild']; - readonly completeBuild: KnowledgeService['completeBuild']; - readonly considerBacklogReconcile: KnowledgeService['considerBacklogReconcile']; - readonly coveredByBuild: KnowledgeService['coveredByBuild']; - readonly deadLettersOf: KnowledgeService['deadLettersOf']; - readonly defaultTopK: KnowledgeService['defaultTopK']; - readonly describeSources: KnowledgeService['describeSources']; - readonly dropUnverifiedHits: KnowledgeService['dropUnverifiedHits']; - enablementPending: KnowledgeService['enablementPending']; - readonly enqueueReconcile: KnowledgeService['enqueueReconcile']; - readonly faceOfKey: KnowledgeService['faceOfKey']; - readonly facedRefusals: KnowledgeService['facedRefusals']; - readonly forget: KnowledgeService['forget']; - readonly freshnessRepairs: KnowledgeService['freshnessRepairs']; - readonly getAdapter: KnowledgeService['getAdapter']; - readonly groupKeyOf: KnowledgeService['groupKeyOf']; - readonly handed: KnowledgeService['handed']; - readonly handedSources: KnowledgeService['handedSources']; - held: KnowledgeService['held']; - readonly label: KnowledgeService['label']; - readonly listAdapters: KnowledgeService['listAdapters']; - readonly options: KnowledgeService['options']; - readonly pendingReconciles: KnowledgeService['pendingReconciles']; - readonly pendingRecordSyncs: KnowledgeService['pendingRecordSyncs']; - readonly planIndex: KnowledgeService['planIndex']; - readonly planSearches: KnowledgeService['planSearches']; - readonly prepareDocuments: KnowledgeService['prepareDocuments']; - readonly publishRecordSyncs: KnowledgeService['publishRecordSyncs']; - readonly readChunkTarget: KnowledgeService['readChunkTarget']; - readonly readIndexStateOf: KnowledgeService['readIndexStateOf']; - readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; - readonly readVisibleIds: KnowledgeService['readVisibleIds']; - readonly rebuildOf: KnowledgeService['rebuildOf']; - readonly reconcileExclusion: KnowledgeService['reconcileExclusion']; - readonly reconcileOf: KnowledgeService['reconcileOf']; - readonly reconcilePass: KnowledgeService['reconcilePass']; - reconcileTail: KnowledgeService['reconcileTail']; - readonly reconcileUnlistedReported: KnowledgeService['reconcileUnlistedReported']; - readonly recordBuildEnd: KnowledgeService['recordBuildEnd']; - readonly recordBuildProgress: KnowledgeService['recordBuildProgress']; - readonly recordBuildStart: KnowledgeService['recordBuildStart']; - recordSyncBacklog: KnowledgeService['recordSyncBacklog']; - readonly recordSyncPublisher: KnowledgeService['recordSyncPublisher']; - readonly recordSyncQueueView: KnowledgeService['recordSyncQueueView']; - readonly recordSyncTails: KnowledgeService['recordSyncTails']; - readonly recordSyncWaiting: KnowledgeService['recordSyncWaiting']; - readonly refuseUnplacedSource: KnowledgeService['refuseUnplacedSource']; - readonly registry: KnowledgeService['registry']; - readonly reindexTails: KnowledgeService['reindexTails']; - readonly reindexWith: KnowledgeService['reindexWith']; - readonly repairStale: KnowledgeService['repairStale']; - readonly reportGateFailure: KnowledgeService['reportGateFailure']; - readonly reportUnindexable: KnowledgeService['reportUnindexable']; - readonly reportWhereUnenforceable: KnowledgeService['reportWhereUnenforceable']; - readonly requestSourceReconcile: KnowledgeService['requestSourceReconcile']; - readonly requireEntry: KnowledgeService['requireEntry']; - readonly resolveRecordSync: KnowledgeService['resolveRecordSync']; - readonly resolveSearchTargets: KnowledgeService['resolveSearchTargets']; - readonly runningBuildIds: KnowledgeService['runningBuildIds']; - readonly schemaFor: KnowledgeService['schemaFor']; - readonly scopeAmbiguousReported: KnowledgeService['scopeAmbiguousReported']; - readonly scopeByOrganization: KnowledgeService['scopeByOrganization']; - readonly scopeIgnoredReported: KnowledgeService['scopeIgnoredReported']; - readonly searchByKey: KnowledgeService['searchByKey']; - readonly searchRound: KnowledgeService['searchRound']; - readonly searchWithRefusals: KnowledgeService['searchWithRefusals']; - readonly serializeRecordSync: KnowledgeService['serializeRecordSync']; - readonly sourceListeners: KnowledgeService['sourceListeners']; - readonly sourceRowCount: KnowledgeService['sourceRowCount']; - readonly sourceRows: KnowledgeService['sourceRows']; - readonly sourcesChanged: KnowledgeService['sourcesChanged']; - readonly sourcesForObject: KnowledgeService['sourcesForObject']; - readonly sourcesGroupableBy: KnowledgeService['sourcesGroupableBy']; - readonly sourcesInScope: KnowledgeService['sourcesInScope']; - readonly sourcesNarrowedToVisible: KnowledgeService['sourcesNarrowedToVisible']; - readonly storedCounts: KnowledgeService['storedCounts']; - readonly syncRecord: KnowledgeService['syncRecord']; - readonly syncRecordGroup: KnowledgeService['syncRecordGroup']; - readonly syncRow: KnowledgeService['syncRow']; - readonly syncRows: KnowledgeService['syncRows']; - readonly syncStateIdentity: KnowledgeService['syncStateIdentity']; - readonly syncStateRecorded: KnowledgeService['syncStateRecorded']; - readonly syncStateWriteFailed: KnowledgeService['syncStateWriteFailed']; - syncStateWriteReported: KnowledgeService['syncStateWriteReported']; - readonly unmountedAdapterSaveText: KnowledgeService['unmountedAdapterSaveText']; - readonly unprovenIndex: KnowledgeService['unprovenIndex']; - readonly walkObjectSource: KnowledgeService['walkObjectSource']; - readonly whereUnenforceableReported: KnowledgeService['whereUnenforceableReported']; - readonly writeSynced: KnowledgeService['writeSynced']; -} +/** What every facet reads of the service: the one host the static block builds. */ +export type KnowledgeServiceHost = KnowledgeSourcesHost & + KnowledgeIndexingHost & + KnowledgeRecordSyncHost & + KnowledgeSearchHost & + KnowledgeAdmissionHost; /** The host of each service: built on first use, kept for the service's life. */ class KnowledgeServiceHostHolder { diff --git a/packages/services/service-knowledge/src/knowledge-service-indexing.ts b/packages/services/service-knowledge/src/knowledge-service-indexing.ts index beefad7b3d7..a54344f999a 100644 --- a/packages/services/service-knowledge/src/knowledge-service-indexing.ts +++ b/packages/services/service-knowledge/src/knowledge-service-indexing.ts @@ -13,21 +13,23 @@ * `armReconcile`, `cancelPendingReconcile`, moved out of `knowledge-service.ts` * whole. * - * A MOVE, not a redesign. {@link KnowledgeIndexingFacet} is a stateless facet of - * `KnowledgeService`: each static method is the body of the `KnowledgeService` - * member of the same name exactly as it stood (not re-indented, not edited). - * The member stays on the class as a one-call stub with its signature, so the - * published declaration, an instance spy and a subclass override are what they - * were. A public member keeps its docblock on the class, the contract; a - * private member's docblock moved here with its body. The state stays on - * `KnowledgeService`. + * A MOVE, not a redesign. Each function below is the body of the + * `KnowledgeService` member of the same name as it stood, re-indented one + * level and otherwise unedited (a line inside a string or template literal + * keeps its bytes). The member stays on the class as a one-call stub with its + * signature, so the published declaration, an instance spy and a subclass + * override are what they were; the class imports this module as + * `KnowledgeIndexingFacet`. A public member keeps its docblock on the class, the + * contract; a private member's docblock moved here with its body. The state + * stays on `KnowledgeService`. * * A body reaches the service through `this`, typed as the part of - * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands - * it the host the class's static block builds once per service, whose methods call - * the service at call time and whose fields are getters (and a setter for a - * field a body assigns). A body that reads nothing of the service is called - * without one. `index.ts` re-exports nothing from this module. + * {@link KnowledgeIndexingHost} it reads: the stub hands it the host the class's static + * block builds once per service (`knowledge-service-host.ts`), whose methods call the + * service at call time and whose fields are getters (and a setter for a field + * a body assigns). A body that reads nothing of the service is called without + * one. The module imports `knowledge-service.ts` for types only, so the two + * form no evaluation cycle. `index.ts` re-exports nothing from this module. */ import type { @@ -88,202 +90,297 @@ import { recordToDocument, systemContext, } from './knowledge-service-top-level.js'; -import type { KnowledgeServiceHost } from './knowledge-service-host.js'; +import type { KnowledgeService } from './knowledge-service.js'; -export class KnowledgeIndexingFacet { - /** - * What every adapter call for `source` carries, read now (ADR-0161 K7; K8, - * item 8): the split the service applies for this adapter — resolved from - * the source's `split`, the settings page's `knowledge.chunk_target` and the - * adapter's reported `embedding.maxInputTokens`, absent for an adapter that - * does not take chunks — and the index fingerprint and recipe hash computed - * over that same split, the adapter's descriptor and the source. One read - * feeds both, so the fingerprint is always the fingerprint of the split the - * documents were cut by. Never cached: the settings, the descriptor and the - * object definition may each change between two calls. - */ - static async planIndex( - this: Pick, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - chunkTarget: () => Promise = () => this.readChunkTarget(), - ): Promise { - const split = adapter.capabilities?.chunks === true - ? resolveSplit({ - split: source.source.split, - chunkTarget: await chunkTarget(), - maxInputTokens: adapter.embedding?.maxInputTokens, - }) - : undefined; - const index = indexExpectation( - { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, - { source, schema: this.schemaFor(source.source.object) }, - ); - return { - source, - adapter, - ...(split === undefined ? {} : { split }), - index, - context: (reason) => ({ source, reason, index }), - }; - } +/** + * The `KnowledgeService` members the bodies in this module read: every one + * of them, and no other. Each is typed AS the class member (an indexed + * access on the class), so a change to a member's type on the class is a change + * here too, and a name the class does not have does not compile. `readonly` + * members are methods and fields no body here assigns; the others are fields a + * body here assigns. + */ +export interface KnowledgeIndexingHost { + readonly adapterFor: KnowledgeService['adapterFor']; + readonly adapters: KnowledgeService['adapters']; + readonly armReconcile: KnowledgeService['armReconcile']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; + readonly buildIfDue: KnowledgeService['buildIfDue']; + readonly buildUnderLease: KnowledgeService['buildUnderLease']; + readonly builds: KnowledgeService['builds']; + buildsStopped: KnowledgeService['buildsStopped']; + readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; + readonly clearRepairedFailures: KnowledgeService['clearRepairedFailures']; + readonly closeStaleBuild: KnowledgeService['closeStaleBuild']; + readonly completeBuild: KnowledgeService['completeBuild']; + readonly enqueueReconcile: KnowledgeService['enqueueReconcile']; + readonly held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly options: KnowledgeService['options']; + readonly pendingReconciles: KnowledgeService['pendingReconciles']; + readonly planIndex: KnowledgeService['planIndex']; + readonly prepareDocuments: KnowledgeService['prepareDocuments']; + readonly readChunkTarget: KnowledgeService['readChunkTarget']; + readonly readIndexStateOf: KnowledgeService['readIndexStateOf']; + readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; + readonly rebuildOf: KnowledgeService['rebuildOf']; + readonly reconcileExclusion: KnowledgeService['reconcileExclusion']; + readonly reconcileOf: KnowledgeService['reconcileOf']; + readonly reconcilePass: KnowledgeService['reconcilePass']; + reconcileTail: KnowledgeService['reconcileTail']; + readonly reconcileUnlistedReported: KnowledgeService['reconcileUnlistedReported']; + readonly recordBuildEnd: KnowledgeService['recordBuildEnd']; + readonly recordBuildProgress: KnowledgeService['recordBuildProgress']; + readonly recordBuildStart: KnowledgeService['recordBuildStart']; + readonly recordSyncTails: KnowledgeService['recordSyncTails']; + readonly registry: KnowledgeService['registry']; + readonly reindexTails: KnowledgeService['reindexTails']; + readonly reindexWith: KnowledgeService['reindexWith']; + readonly requireEntry: KnowledgeService['requireEntry']; + readonly runningBuildIds: KnowledgeService['runningBuildIds']; + readonly schemaFor: KnowledgeService['schemaFor']; + readonly storedCounts: KnowledgeService['storedCounts']; + readonly syncStateIdentity: KnowledgeService['syncStateIdentity']; + readonly syncStateRecorded: KnowledgeService['syncStateRecorded']; + readonly syncStateWriteFailed: KnowledgeService['syncStateWriteFailed']; + syncStateWriteReported: KnowledgeService['syncStateWriteReported']; + readonly walkObjectSource: KnowledgeService['walkObjectSource']; +} - /** - * The ONE place documents are split before an adapter sees them (ADR-0161 - * K1). An adapter that does not declare `capabilities.chunks` gets the - * documents as they are, without `chunks` — it splits them itself, as - * before. One that does gets each document with the passages of - * {@link splitDocument}, under the split {@link planIndex} resolved for - * this call: the source's `split`, the settings page's `knowledge.chunk_target`, and the - * adapter's reported `embedding.maxInputTokens` — read for this call, never - * cached. A document the split cannot index (a `whole` document over the - * budget) is answered in `failed`, never truncated; the caller removes it. - */ - static prepareDocuments( - plan: IndexPlan, - docs: KnowledgeDocument[], - ): { +/** + * What every adapter call for `source` carries, read now (ADR-0161 K7; K8, + * item 8): the split the service applies for this adapter — resolved from + * the source's `split`, the settings page's `knowledge.chunk_target` and the + * adapter's reported `embedding.maxInputTokens`, absent for an adapter that + * does not take chunks — and the index fingerprint and recipe hash computed + * over that same split, the adapter's descriptor and the source. One read + * feeds both, so the fingerprint is always the fingerprint of the split the + * documents were cut by. Never cached: the settings, the descriptor and the + * object definition may each change between two calls. + */ +export async function planIndex( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + chunkTarget: () => Promise = () => this.readChunkTarget(), +): Promise { + const split = adapter.capabilities?.chunks === true + ? resolveSplit({ + split: source.source.split, + chunkTarget: await chunkTarget(), + maxInputTokens: adapter.embedding?.maxInputTokens, + }) + : undefined; + const index = indexExpectation( + { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, + { source, schema: this.schemaFor(source.source.object) }, + ); + return { + source, + adapter, + ...(split === undefined ? {} : { split }), + index, + context: (reason) => ({ source, reason, index }), + }; +} + +/** + * The ONE place documents are split before an adapter sees them (ADR-0161 + * K1). An adapter that does not declare `capabilities.chunks` gets the + * documents as they are, without `chunks` — it splits them itself, as + * before. One that does gets each document with the passages of + * {@link splitDocument}, under the split {@link planIndex} resolved for + * this call: the source's `split`, the settings page's `knowledge.chunk_target`, and the + * adapter's reported `embedding.maxInputTokens` — read for this call, never + * cached. A document the split cannot index (a `whole` document over the + * budget) is answered in `failed`, never truncated; the caller removes it. + */ +export function prepareDocuments( + plan: IndexPlan, + docs: KnowledgeDocument[], +): { ready: KnowledgeDocument[]; failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }>; } { - const split = plan.split; - if (split === undefined || docs.length === 0) return { ready: docs, failed: [] }; - const ready: KnowledgeDocument[] = []; - const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; - for (const doc of docs) { - const out = splitDocument(doc, split); - if (out.ok) ready.push({ ...doc, chunks: out.chunks }); - else failed.push({ documentId: doc.id, reason: out.reason, estimate: out.estimate, budget: out.budget }); - } - return { ready, failed }; + const split = plan.split; + if (split === undefined || docs.length === 0) return { ready: docs, failed: [] }; + const ready: KnowledgeDocument[] = []; + const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; + for (const doc of docs) { + const out = splitDocument(doc, split); + if (out.ok) ready.push({ ...doc, chunks: out.chunks }); + else failed.push({ documentId: doc.id, reason: out.reason, estimate: out.estimate, budget: out.budget }); } + return { ready, failed }; +} - /** The settings page's `knowledge.chunk_target`, read now; `undefined` when unset or unreadable. */ - static async readChunkTarget(this: Pick): Promise { - const resolve = this.options.resolveChunkTarget; - if (!resolve) return undefined; - try { - return await resolve(); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the settings page's knowledge.chunk_target could not be read (${errorText(err)}); ` + - "splitting by the source's own split.maxChars, else 800.", - ); - return undefined; - } +/** The settings page's `knowledge.chunk_target`, read now; `undefined` when unset or unreadable. */ +export async function readChunkTarget(this: Pick): Promise { + const resolve = this.options.resolveChunkTarget; + if (!resolve) return undefined; + try { + return await resolve(); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the settings page's knowledge.chunk_target could not be read (${errorText(err)}); ` + + "splitting by the source's own split.maxChars, else 800.", + ); + return undefined; } +} - static async reindexSource( - this: Pick, - sourceId: string, - opts: KnowledgeReindexOptions = {}, - ): Promise { - const entry = this.requireEntry(sourceId); - if (this.held) throw heldSourcesError(this.held); - return this.reindexWith(entry.handed, opts); +/** The body of {@link KnowledgeService.reindexSource}; the member's docblock there is its contract. */ +export async function reindexSource( + this: Pick, + sourceId: string, + opts: KnowledgeReindexOptions = {}, +): Promise { + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.reindexWith(entry.handed, opts); +} + +/** + * {@link reindexSource}, with a sink a build's progress is reported to after + * each page, and the build's fence (`knowledge-build.ts`) the walk asks + * before each page. + */ +export async function reindexWith( + this: Pick, + source: KnowledgeSource, + opts: KnowledgeReindexOptions, + progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, +): Promise { + const adapter = this.adapterFor(source); + + const engine = this.options.dataEngine; + if (!engine) { + return { + ok: false, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: 'KnowledgeService has no IDataEngine bound; cannot walk the source.', + }; } - /** - * {@link reindexSource}, with a sink a build's progress is reported to after - * each page, and the build's fence (`knowledge-build.ts`) the walk asks - * before each page. - */ - static async reindexWith( - this: Pick, - source: KnowledgeSource, - opts: KnowledgeReindexOptions, - progress?: (step: KnowledgeBuildProgress) => void, - fence?: KnowledgeBuildFence, - ): Promise { - const adapter = this.adapterFor(source); + return chainAfter(this.reindexTails, source.name, () => + this.walkObjectSource(source, source.source, adapter, engine, opts, progress, fence), + ); +} - const engine = this.options.dataEngine; - if (!engine) { - return { - ok: false, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: 'KnowledgeService has no IDataEngine bound; cannot walk the source.', - }; - } +/** + * The paged walk of {@link reindexSource}; runs inside that source's chain. + * Under a build's `fence` it stops before a page once the fence says so + * (and before `beginBuild`, before each purge deletion, and before its + * purge and completion), and stops waiting on a read, a + * write, the listing, the purge or `beginBuild` once the build is + * cancelled, so the source's chain is not held by such a call that never + * answers. Each page and each purge deletion restarts the fence's bound. + * The completion is not raced: the chain stays held until it settles (see + * {@link completeBuild}). + */ +export async function walkObjectSource( + this: Pick< + KnowledgeIndexingHost, + 'completeBuild' | 'label' | 'options' | 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | + 'recordSyncTails' | 'schemaFor' + >, + source: KnowledgeSource, + objSource: ObjectKnowledgeSource, + adapter: IKnowledgeAdapter, + engine: IDataEngine, + opts: KnowledgeReindexOptions, + progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, +): Promise { + const object = objSource.object; + // `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A + // fractional cap is floored; a negative or non-finite one is refused + // rather than read as "nothing to do". + if (opts.limit !== undefined && !(typeof opts.limit === 'number' && Number.isFinite(opts.limit) && opts.limit >= 0)) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, + }; + } + const cap = opts.limit === undefined ? undefined : Math.floor(opts.limit); + // RLS-bypassing system context — this is a server-side admin op. + const context = systemContext(); - return chainAfter(this.reindexTails, source.name, () => - this.walkObjectSource(source, source.source, adapter, engine, opts, progress, fence), - ); + if (opts.dryRun) { + const total = await engine.count(object, { where: objSource.where }, { context }); + return { + ok: true, + object, + discovered: cap === undefined ? total : Math.min(total, cap), + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: 'dryRun=true; no documents pushed.', + }; } - /** - * The paged walk of {@link reindexSource}; runs inside that source's chain. - * Under a build's `fence` it stops before a page once the fence says so - * (and before `beginBuild`, before each purge deletion, and before its - * purge and completion), and stops waiting on a read, a - * write, the listing, the purge or `beginBuild` once the build is - * cancelled, so the source's chain is not held by such a call that never - * answers. Each page and each purge deletion restarts the fence's bound. - * The completion is not raced: the chain stays held until it settles (see - * {@link completeBuild}). - */ - static async walkObjectSource( - this: Pick< - KnowledgeServiceHost, - 'completeBuild' | 'label' | 'options' | 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | - 'recordSyncTails' | 'schemaFor' - >, - source: KnowledgeSource, - objSource: ObjectKnowledgeSource, - adapter: IKnowledgeAdapter, - engine: IDataEngine, - opts: KnowledgeReindexOptions, - progress?: (step: KnowledgeBuildProgress) => void, - fence?: KnowledgeBuildFence, - ): Promise { - const object = objSource.object; - // `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A - // fractional cap is floored; a negative or non-finite one is refused - // rather than read as "nothing to do". - if (opts.limit !== undefined && !(typeof opts.limit === 'number' && Number.isFinite(opts.limit) && opts.limit >= 0)) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, - }; - } - const cap = opts.limit === undefined ? undefined : Math.floor(opts.limit); - // RLS-bypassing system context — this is a server-side admin op. - const context = systemContext(); + // The posture decides whether each document carries its record's + // organization (ADR-0161 K8, item 9); read once per walk. A posture that + // cannot be read stops the walk before any write: a document assembled + // without its organization would drop out of every walled search. + let posture: TenancyPosture | undefined; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + message: `reindex of source '${this.label(source)}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, + }; + } - if (opts.dryRun) { - const total = await engine.count(object, { where: objSource.where }, { context }); - return { - ok: true, - object, - discovered: cap === undefined ? total : Math.min(total, cap), - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: 'dryRun=true; no documents pushed.', - }; - } + // One plan for the whole walk: the split every page is cut by, and the + // fingerprint and recipe hash every adapter call carries. + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('reindex'); - // The posture decides whether each document carries its record's - // organization (ADR-0161 K8, item 9); read once per walk. A posture that - // cannot be read stops the walk before any write: a document assembled - // without its organization would drop out of every walled search. - let posture: TenancyPosture | undefined; + // A complete walk is a build (K7, rule 3): the adapter is told before the + // first write, and may open a generation for a new fingerprint — or refuse. + const build = cap === undefined; + // A build cancelled, or whose lease was lost, while its walk waited its + // turn in the source's queue does not begin: `beginBuild` is where a store + // that keeps generations takes its builder lock (K7, rule 2). + const unbegun = fence?.stop(); + if (unbegun !== undefined) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${source.id}' stopped before its build began, and nothing was written: ${unbegun.message}`, + }; + } + if (build && typeof adapter.beginBuild === 'function') { try { - posture = await this.readTenancyPosture(); + await fencedCall(fence, adapter.beginBuild(ctx)); } catch (err) { return { ok: false, @@ -292,1128 +389,1095 @@ export class KnowledgeIndexingFacet { indexed: 0, skipped: 0, purged: null, - message: `reindex of source '${this.label(source)}' refused: the tenancy posture could not be read (${errorText(err)}); nothing was written.`, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, }; } + } - // One plan for the whole walk: the split every page is cut by, and the - // fingerprint and recipe hash every adapter call carries. - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('reindex'); + // What the adapter holds before the walk: the skip's hashes, and the + // purge's candidates once the walk is complete. + // Raced against the build's bound like every call of the walk, so a store + // that never answers frees the source's chain. + let listing: Awaited>; + try { + listing = await fencedCall(fence, listAdapterDocuments(source, adapter, plan.index)); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${this.label(source)}' stopped before its first page: ${errorText(err)}`, + }; + } + const listed = listing.ok ? listing.documents : undefined; + const listingNote = listing.ok || listing.reason === undefined + ? undefined + : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; + if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${this.label(source)}': ${listingNote}`); - // A complete walk is a build (K7, rule 3): the adapter is told before the - // first write, and may open a generation for a new fingerprint — or refuse. - const build = cap === undefined; - // A build cancelled, or whose lease was lost, while its walk waited its - // turn in the source's queue does not begin: `beginBuild` is where a store - // that keeps generations takes its builder lock (K7, rule 2). - const unbegun = fence?.stop(); - if (unbegun !== undefined) { - return { - ok: false, + const schema = this.schemaFor(object); + const seen = new Set(); + let discovered = 0; + let indexed = 0; + let skipped = 0; + // Documents the split could not index (a `whole` document over the + // embedder's budget): removed from the index, counted, and the first + // MAX_REINDEX_FAILURES named. + let failed = 0; + const failures: Array<{ documentId: string; reason: string }> = []; + let cursor: string | number | undefined; + for (let page = 1; ; page++) { + const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); + if (!(want > 0)) break; + const after = cursor === undefined ? '' : ` (after id '${cursor}')`; + const stopped = (what: string): KnowledgeReindexResult => ({ + ok: false, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures: [...failures], + message: `reindex of source '${this.label(source)}' stopped at page ${page}${after}: ${what}`, + }); + // A build that lost its lease, or was cancelled, reads and embeds no + // further page (the fence, `knowledge-build.ts`). + const halt = fence?.stop(); + if (halt !== undefined) return stopped(halt.message); + + const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; + let rows: Array>; + try { + rows = await fencedCall(fence, engine.find( object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${source.id}' stopped before its build began, and nothing was written: ${unbegun.message}`, - }; + { + where: + byCursor === undefined + ? objSource.where + : objSource.where === undefined ? byCursor : { $and: [objSource.where, byCursor] }, + orderBy: [{ field: 'id', order: 'asc' }], + limit: want, + }, + { context }, + )); + } catch (err) { + return stopped(`the read failed: ${errorText(err)}`); } - if (build && typeof adapter.beginBuild === 'function') { - try { - await fencedCall(fence, adapter.beginBuild(ctx)); - } catch (err) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, - }; - } + // Only an EMPTY page ends the walk. A short page does not: `find` does + // not promise `min(limit, remaining)` rows — an `afterFind` hook may drop + // rows from a page — so rows after a short page can still exist. + // A read that answers no list is a failed read, never the end of the + // source: read as an empty page it would make a complete walk of nothing + // and hand every listed document to the purge. + if (!Array.isArray(rows)) { + return stopped(`the read answered ${describeValue(rows)} instead of a list of rows.`); } + if (rows.length === 0) break; - // What the adapter holds before the walk: the skip's hashes, and the - // purge's candidates once the walk is complete. - // Raced against the build's bound like every call of the walk, so a store - // that never answers frees the source's chain. - let listing: Awaited>; + let docs: KnowledgeDocument[]; try { - listing = await fencedCall(fence, listAdapterDocuments(source, adapter, plan.index)); + docs = rows.map((row) => recordToDocument(source, objSource, row, schema, posture)); } catch (err) { - return { - ok: false, - object, - discovered: 0, - indexed: 0, - skipped: 0, - purged: null, - failed: 0, - failures: [], - message: `reindex of source '${this.label(source)}' stopped before its first page: ${errorText(err)}`, - }; + return stopped(`building the page's documents failed: ${errorText(err)}`); } - const listed = listing.ok ? listing.documents : undefined; - const listingNote = listing.ok || listing.reason === undefined - ? undefined - : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; - if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${this.label(source)}': ${listingNote}`); - - const schema = this.schemaFor(object); - const seen = new Set(); - let discovered = 0; - let indexed = 0; - let skipped = 0; - // Documents the split could not index (a `whole` document over the - // embedder's budget): removed from the index, counted, and the first - // MAX_REINDEX_FAILURES named. - let failed = 0; - const failures: Array<{ documentId: string; reason: string }> = []; - let cursor: string | number | undefined; - for (let page = 1; ; page++) { - const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); - if (!(want > 0)) break; - const after = cursor === undefined ? '' : ` (after id '${cursor}')`; - const stopped = (what: string): KnowledgeReindexResult => ({ - ok: false, - object, - discovered, - indexed, - skipped, - purged: null, - failed, - failures: [...failures], - message: `reindex of source '${this.label(source)}' stopped at page ${page}${after}: ${what}`, + // A document whose computed hash equals the one the adapter listed for it + // is unchanged: it is not written again. + const changed = listed === undefined + ? docs + : docs.filter((doc) => { + const stored = listed.get(doc.id); + return stored === undefined || stored !== doc.docHash; }); - // A build that lost its lease, or was cancelled, reads and embeds no - // further page (the fence, `knowledge-build.ts`). - const halt = fence?.stop(); - if (halt !== undefined) return stopped(halt.message); - - const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; - let rows: Array>; + // One split per changed document, for an adapter that takes chunks. + const prepared = this.prepareDocuments(plan, changed); + if (prepared.ready.length > 0) { try { - rows = await fencedCall(fence, engine.find( - object, - { - where: - byCursor === undefined - ? objSource.where - : objSource.where === undefined ? byCursor : { $and: [objSource.where, byCursor] }, - orderBy: [{ field: 'id', order: 'asc' }], - limit: want, - }, - { context }, - )); + await fencedCall(fence, adapter.upsert(prepared.ready, ctx)); } catch (err) { - return stopped(`the read failed: ${errorText(err)}`); - } - // Only an EMPTY page ends the walk. A short page does not: `find` does - // not promise `min(limit, remaining)` rows — an `afterFind` hook may drop - // rows from a page — so rows after a short page can still exist. - // A read that answers no list is a failed read, never the end of the - // source: read as an empty page it would make a complete walk of nothing - // and hand every listed document to the purge. - if (!Array.isArray(rows)) { - return stopped(`the read answered ${describeValue(rows)} instead of a list of rows.`); + return stopped(`the adapter upsert failed: ${operatorText(err)}`); } - if (rows.length === 0) break; - - let docs: KnowledgeDocument[]; + } + // A document the split cannot index is removed — an older passage of it + // must not keep answering for text the index no longer holds — and + // reported, never truncated. + if (prepared.failed.length > 0) { try { - docs = rows.map((row) => recordToDocument(source, objSource, row, schema, posture)); + await fencedCall(fence, adapter.delete(prepared.failed.map((f) => f.documentId), ctx)); } catch (err) { - return stopped(`building the page's documents failed: ${errorText(err)}`); - } - // A document whose computed hash equals the one the adapter listed for it - // is unchanged: it is not written again. - const changed = listed === undefined - ? docs - : docs.filter((doc) => { - const stored = listed.get(doc.id); - return stored === undefined || stored !== doc.docHash; - }); - // One split per changed document, for an adapter that takes chunks. - const prepared = this.prepareDocuments(plan, changed); - if (prepared.ready.length > 0) { - try { - await fencedCall(fence, adapter.upsert(prepared.ready, ctx)); - } catch (err) { - return stopped(`the adapter upsert failed: ${operatorText(err)}`); - } + return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); } - // A document the split cannot index is removed — an older passage of it - // must not keep answering for text the index no longer holds — and - // reported, never truncated. - if (prepared.failed.length > 0) { - try { - await fencedCall(fence, adapter.delete(prepared.failed.map((f) => f.documentId), ctx)); - } catch (err) { - return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); - } - for (const f of prepared.failed) { - failed += 1; - if (failures.length < MAX_REINDEX_FAILURES) failures.push({ documentId: f.documentId, reason: f.reason }); - } - } - for (const doc of docs) seen.add(doc.id); - discovered += rows.length; - indexed += prepared.ready.length; - skipped += docs.length - changed.length; - progress?.({ pages: page, discovered, indexed, skipped, failed }); - - // The next page continues after this page's last id. A last row with no - // id, or one that did not move past the cursor (an engine that ignored - // the `id > cursor` condition), ends the walk rather than looping on it. - const lastId = rows[rows.length - 1].id; - if (!isRecordId(lastId)) { - return stopped('the page was indexed, but its last row carries no id, so the walk cannot continue after it.'); + for (const f of prepared.failed) { + failed += 1; + if (failures.length < MAX_REINDEX_FAILURES) failures.push({ documentId: f.documentId, reason: f.reason }); } - if (lastId === cursor) { - return stopped("the page was indexed, but its last row's id did not move past the cursor, so the walk cannot continue."); - } - cursor = lastId; } + for (const doc of docs) seen.add(doc.id); + discovered += rows.length; + indexed += prepared.ready.length; + skipped += docs.length - changed.length; + progress?.({ pages: page, discovered, indexed, skipped, failed }); - // A build that lost its lease after its last page neither purges nor - // completes: another node may be building the source. - const halted = fence?.stop(); - if (halted !== undefined) { - return { - ok: false, - object, - discovered, - indexed, - skipped, - purged: null, - failed, - failures: [...failures], - message: `reindex of source '${this.label(source)}' read every page, and stopped before its purge and completion: ${halted.message}`, - }; + // The next page continues after this page's last id. A last row with no + // id, or one that did not move past the cursor (an engine that ignored + // the `id > cursor` condition), ends the walk rather than looping on it. + const lastId = rows[rows.length - 1].id; + if (!isRecordId(lastId)) { + return stopped('the page was indexed, but its last row carries no id, so the walk cannot continue after it.'); + } + if (lastId === cursor) { + return stopped("the page was indexed, but its last row's id did not move past the cursor, so the walk cannot continue."); } + cursor = lastId; + } - // The purge runs only after a COMPLETE walk: a `limit` walk saw part of - // the source, so "not seen" there means nothing (a failed page returned - // above; `dryRun` returned before the walk). - const failedNote = failed === 0 - ? undefined - : `${failed} document(s) cannot be indexed under the source's split and were removed from the index ` + - `(${failures.length === failed ? 'each' : `the first ${failures.length}`} named in failures).`; - const done: KnowledgeReindexResult = { - ok: true, + // A build that lost its lease after its last page neither purges nor + // completes: another node may be building the source. + const halted = fence?.stop(); + if (halted !== undefined) { + return { + ok: false, object, discovered, indexed, skipped, purged: null, failed, - failures, - ...(failedNote === undefined ? {} : { message: failedNote }), + failures: [...failures], + message: `reindex of source '${this.label(source)}' read every page, and stopped before its purge and completion: ${halted.message}`, }; - if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; - if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { - return build ? this.completeBuild(source, adapter, ctx, done, fence) : done; - } + } - const candidates = [...listed.keys()].filter((id) => !seen.has(id)); - let purge: PurgeDocumentsOutcome; - try { - purge = await fencedCall(fence, purgeDocuments({ - source, - objSource, - adapter, - engine, - candidates, - // Each settled deletion (or confirmed keep) is progress: a large, - // healthy purge restarts the fence's bound as it goes. A build that - // lost its lease, or was cancelled, re-reads and deletes no further - // candidate: the fence is asked once the candidate's turn comes. - serialize: async (documentId, task) => { - const outcome = await chainAfter(this.recordSyncTails, documentId, () => { - const halt = fence?.stop(); - return halt === undefined ? task() : Promise.reject(new Error(halt.message)); - }); - fence?.progressed(); - return outcome; - }, - index: plan.index, - })); - } catch (err) { - return { - ...done, - ok: false, - message: `reindex of source '${this.label(source)}' walked every page, and stopped during its purge: ${errorText(err)}`, - }; - } - if (purge.failure !== undefined) { - const purgeHalt = fence?.stop(); - if (purgeHalt !== undefined) { - return { - ...done, - ok: false, - purged: purge.purged, - message: - `reindex of source '${source.id}' walked every page, and stopped during its purge after ` + - `${purge.purged} deletion(s): ${purgeHalt.message}`, - }; - } + // The purge runs only after a COMPLETE walk: a `limit` walk saw part of + // the source, so "not seen" there means nothing (a failed page returned + // above; `dryRun` returned before the walk). + const failedNote = failed === 0 + ? undefined + : `${failed} document(s) cannot be indexed under the source's split and were removed from the index ` + + `(${failures.length === failed ? 'each' : `the first ${failures.length}`} named in failures).`; + const done: KnowledgeReindexResult = { + ok: true, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures, + ...(failedNote === undefined ? {} : { message: failedNote }), + }; + if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; + if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { + return build ? this.completeBuild(source, adapter, ctx, done, fence) : done; + } + + const candidates = [...listed.keys()].filter((id) => !seen.has(id)); + let purge: PurgeDocumentsOutcome; + try { + purge = await fencedCall(fence, purgeDocuments({ + source, + objSource, + adapter, + engine, + candidates, + // Each settled deletion (or confirmed keep) is progress: a large, + // healthy purge restarts the fence's bound as it goes. A build that + // lost its lease, or was cancelled, re-reads and deletes no further + // candidate: the fence is asked once the candidate's turn comes. + serialize: async (documentId, task) => { + const outcome = await chainAfter(this.recordSyncTails, documentId, () => { + const halt = fence?.stop(); + return halt === undefined ? task() : Promise.reject(new Error(halt.message)); + }); + fence?.progressed(); + return outcome; + }, + index: plan.index, + })); + } catch (err) { + return { + ...done, + ok: false, + message: `reindex of source '${this.label(source)}' walked every page, and stopped during its purge: ${errorText(err)}`, + }; + } + if (purge.failure !== undefined) { + const purgeHalt = fence?.stop(); + if (purgeHalt !== undefined) { return { ...done, ok: false, purged: purge.purged, message: - `reindex of source '${this.label(source)}' walked every page, but its purge stopped after ${purge.purged} ` + - `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, + `reindex of source '${source.id}' walked every page, and stopped during its purge after ` + + `${purge.purged} deletion(s): ${purgeHalt.message}`, }; } - if (purge.foreign > 0) { - return this.completeBuild(source, adapter, ctx, { - ...done, - purged: purge.purged, - message: - `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + - `('${source.name}:' and the record id); they were kept, because no row can confirm them.` + - (failedNote === undefined ? '' : ` ${failedNote}`), - }, fence); - } - return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }, fence); + return { + ...done, + ok: false, + purged: purge.purged, + message: + `reindex of source '${this.label(source)}' walked every page, but its purge stopped after ${purge.purged} ` + + `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, + }; + } + if (purge.foreign > 0) { + return this.completeBuild(source, adapter, ctx, { + ...done, + purged: purge.purged, + message: + `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + + `('${source.name}:' and the record id); they were kept, because no row can confirm them.` + + (failedNote === undefined ? '' : ` ${failedNote}`), + }, fence); } + return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }, fence); +} - /** - * The end of a complete build (ADR-0161 K8, item 8 c): the adapter's - * `completeBuild`, once, with the fingerprint and recipe hash the walk - * carried. An adapter without it records nothing. One that throws turns the - * walk's result into `ok: false`: every page was written, but the adapter - * did not record what it holds, so the next complete walk builds again. - * Under a build's `fence`, a build that must stop (its lease lost during - * the purge, or its bound passed) completes nothing. Once the completion - * begins it is not a page: the fence's bound is disarmed - * (`fence.completing()`) and the call is awaited however long it takes, so - * a switch that began still commits and the record never reads - * `timed-out` over it. The source's walk chain stays held until it settles, - * so no rebuild on this node begins a build beside it. - */ - static async completeBuild( - this: Pick, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - ctx: AdapterContext, - done: KnowledgeReindexResult, - fence?: KnowledgeBuildFence, - ): Promise { - const halt = fence?.stop(); - if (halt !== undefined) { - return { - ...done, - ok: false, - message: `reindex of source '${this.label(source)}' walked every page, and stopped before its completion: ${halt.message}`, - }; - } - if (typeof adapter.completeBuild !== 'function') return done; - fence?.completing(); - try { - await adapter.completeBuild(ctx); - return done; - } catch (err) { - return { - ...done, - ok: false, - message: - `reindex of source '${this.label(source)}' walked every page, but the adapter did not complete the build ` + - `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, - }; - } +/** + * The end of a complete build (ADR-0161 K8, item 8 c): the adapter's + * `completeBuild`, once, with the fingerprint and recipe hash the walk + * carried. An adapter without it records nothing. One that throws turns the + * walk's result into `ok: false`: every page was written, but the adapter + * did not record what it holds, so the next complete walk builds again. + * Under a build's `fence`, a build that must stop (its lease lost during + * the purge, or its bound passed) completes nothing. Once the completion + * begins it is not a page: the fence's bound is disarmed + * (`fence.completing()`) and the call is awaited however long it takes, so + * a switch that began still commits and the record never reads + * `timed-out` over it. The source's walk chain stays held until it settles, + * so no rebuild on this node begins a build beside it. + */ +export async function completeBuild( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + ctx: AdapterContext, + done: KnowledgeReindexResult, + fence?: KnowledgeBuildFence, +): Promise { + const halt = fence?.stop(); + if (halt !== undefined) { + return { + ...done, + ok: false, + message: `reindex of source '${this.label(source)}' walked every page, and stopped before its completion: ${halt.message}`, + }; } + if (typeof adapter.completeBuild !== 'function') return done; + fence?.completing(); + try { + await adapter.completeBuild(ctx); + return done; + } catch (err) { + return { + ...done, + ok: false, + message: + `reindex of source '${this.label(source)}' walked every page, but the adapter did not complete the build ` + + `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, + }; + } +} - /** {@link readIndexState} of one registered source; the reading names it by its face. */ - static async readIndexStateOf( - this: Pick, - entry: KnowledgeSourceEntry, - ): Promise { - const source = entry.handed; - const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({ - sourceId: entry.face, - state, - due, - detail, - ...(held === undefined ? {} : { held }), - }); - if (!this.options.dataEngine) { - return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); - } - try { - const adapter = this.adapterFor(source); - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('reindex'); - if (typeof adapter.indexStatus === 'function') { - const held = await adapter.indexStatus(ctx); - const expected = plan.index; - if (held.fingerprint === undefined && held.recipeHash === undefined && held.building !== true) { - return reading('nothing', true, 'the adapter holds nothing for the source: it has never been built.', held); - } - // A first build opened a generation and has not completed it (it is - // still running on some node, or it stopped part-way): there is no - // active generation yet, so no other fingerprint to speak of. - if (held.fingerprint === undefined) { - return reading( - 'nothing', - true, - 'a first build was started and has not completed (it is still running, or it stopped part-way): the adapter holds no complete index for the source.', - held, - ); - } - if (held.fingerprint !== expected.fingerprint) { - return reading( - 'new-fingerprint', - true, - 'the index was built under another fingerprint (embedding model, dimensions or split): it is built anew.', - held, - ); - } - if (held.recipeHash === undefined) { - return typeof adapter.completeBuild === 'function' - ? reading('no-recipe-hash', true, 'the index records no recipe hash: one complete rebuild records it.', held) - : reading( - 'no-recipe-hash', - false, - `the adapter '${adapter.id}' records no recipe hash and has no completeBuild, so a changed recipe ` + - "(the source's where, metadataFields, title rule or withheld fields) cannot be seen for it; nothing is rebuilt automatically.", - held, - ); - } - if (held.recipeHash !== expected.recipeHash) { - return reading( - 'recipe-changed', - true, - "the source's recipe changed since the last build (its where, metadataFields, title rule or withheld fields): it is rebuilt.", - held, - ); - } - return reading('current', false, 'the index is current: same fingerprint, same recipe hash.', held); +/** {@link readIndexState} of one registered source; the reading names it by its face. */ +export async function readIndexStateOf( + this: Pick, + entry: KnowledgeSourceEntry, +): Promise { + const source = entry.handed; + const reading = (state: KnowledgeIndexReading['state'], due: boolean, detail: string, held?: KnowledgeIndexReading['held']): KnowledgeIndexReading => ({ + sourceId: entry.face, + state, + due, + detail, + ...(held === undefined ? {} : { held }), + }); + if (!this.options.dataEngine) { + return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); + } + try { + const adapter = this.adapterFor(source); + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('reindex'); + if (typeof adapter.indexStatus === 'function') { + const held = await adapter.indexStatus(ctx); + const expected = plan.index; + if (held.fingerprint === undefined && held.recipeHash === undefined && held.building !== true) { + return reading('nothing', true, 'the adapter holds nothing for the source: it has never been built.', held); } - if (typeof adapter.listDocuments === 'function') { - const page = await adapter.listDocuments(ctx, { limit: 1 }); - const documents = Array.isArray(page?.documents) ? page.documents : undefined; - if (documents === undefined) { - return reading('unreadable', false, "the adapter's document listing answered no list of documents."); - } - return documents.length === 0 - ? reading('listed-empty', true, 'the adapter lists no document for the source: it has never been built.') + // A first build opened a generation and has not completed it (it is + // still running on some node, or it stopped part-way): there is no + // active generation yet, so no other fingerprint to speak of. + if (held.fingerprint === undefined) { + return reading( + 'nothing', + true, + 'a first build was started and has not completed (it is still running, or it stopped part-way): the adapter holds no complete index for the source.', + held, + ); + } + if (held.fingerprint !== expected.fingerprint) { + return reading( + 'new-fingerprint', + true, + 'the index was built under another fingerprint (embedding model, dimensions or split): it is built anew.', + held, + ); + } + if (held.recipeHash === undefined) { + return typeof adapter.completeBuild === 'function' + ? reading('no-recipe-hash', true, 'the index records no recipe hash: one complete rebuild records it.', held) : reading( - 'listed-documents', + 'no-recipe-hash', false, - `the adapter '${adapter.id}' holds documents and reports no index status, so whether they are current cannot be read; nothing is rebuilt automatically.`, + `the adapter '${adapter.id}' records no recipe hash and has no completeBuild, so a changed recipe ` + + "(the source's where, metadataFields, title rule or withheld fields) cannot be seen for it; nothing is rebuilt automatically.", + held, ); } - return reading( - 'unknown', - false, - `the adapter '${adapter.id}' has neither indexStatus nor listDocuments, so whether the source was ever built cannot be read; ` + - 'nothing is built automatically, and an operator rebuild (os knowledge rebuild) is the way.', - ); - } catch (err) { - return reading('unreadable', false, `what the adapter holds could not be read (${operatorText(err)}).`); + if (held.recipeHash !== expected.recipeHash) { + return reading( + 'recipe-changed', + true, + "the source's recipe changed since the last build (its where, metadataFields, title rule or withheld fields): it is rebuilt.", + held, + ); + } + return reading('current', false, 'the index is current: same fingerprint, same recipe hash.', held); } + if (typeof adapter.listDocuments === 'function') { + const page = await adapter.listDocuments(ctx, { limit: 1 }); + const documents = Array.isArray(page?.documents) ? page.documents : undefined; + if (documents === undefined) { + return reading('unreadable', false, "the adapter's document listing answered no list of documents."); + } + return documents.length === 0 + ? reading('listed-empty', true, 'the adapter lists no document for the source: it has never been built.') + : reading( + 'listed-documents', + false, + `the adapter '${adapter.id}' holds documents and reports no index status, so whether they are current cannot be read; nothing is rebuilt automatically.`, + ); + } + return reading( + 'unknown', + false, + `the adapter '${adapter.id}' has neither indexStatus nor listDocuments, so whether the source was ever built cannot be read; ` + + 'nothing is built automatically, and an operator rebuild (os knowledge rebuild) is the way.', + ); + } catch (err) { + return reading('unreadable', false, `what the adapter holds could not be read (${operatorText(err)}).`); } +} - static buildRecord( - this: Pick, - sourceId: string, - ): KnowledgeBuildRecord | undefined { - const entry = this.registry.resolve(sourceId); - const record = entry === undefined ? undefined : this.builds.get(entry.key); - return record === undefined ? undefined : cloneBuildRecord(record); - } +/** The body of {@link KnowledgeService.buildRecord}; the member's docblock there is its contract. */ +export function buildRecord( + this: Pick, + sourceId: string, +): KnowledgeBuildRecord | undefined { + const entry = this.registry.resolve(sourceId); + const record = entry === undefined ? undefined : this.builds.get(entry.key); + return record === undefined ? undefined : cloneBuildRecord(record); +} - static async rebuildSource( - this: Pick, - sourceId: string, - opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, - ): Promise { - const entry = this.requireEntry(sourceId); - if (this.held) throw heldSourcesError(this.held); - return this.rebuildOf(entry, opts); - } +/** The body of {@link KnowledgeService.rebuildSource}; the member's docblock there is its contract. */ +export async function rebuildSource( + this: Pick, + sourceId: string, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, +): Promise { + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.rebuildOf(entry, opts); +} - /** - * {@link rebuildSource} of one registered source. The record names the - * source by its face; the build's lock and this node's record of it are - * held under its index key, which no two sources share. - * - * The durable record (`knowledge-sync-state.ts`) is written once the build - * holds the lease and walks: its start, its counts at most every - * {@link BUILD_PROGRESS_LOG_INTERVAL_MS}, and its end, which lands before - * this resolves. A build that does not run (`not-run`) writes nothing: the - * row keeps the build that ran. `onStarted` is told once, with the record, - * when the walk began and its start is recorded, or when the build ended - * without walking. - */ - static async rebuildOf( - this: Pick, - entry: KnowledgeSourceEntry, - opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, - ): Promise { - const running = this.builds.get(entry.key); - if (running?.status === 'running') { - const copy = cloneBuildRecord(running); - opts.onStarted?.(copy); - return copy; - } - const durable: DurableBuild = { chain: Promise.resolve() }; - try { - return await this.buildUnderLease(entry, opts, durable); - } finally { - await durable.chain; - if (durable.buildId !== undefined && this.runningBuildIds.get(entry.key) === durable.buildId) { - this.runningBuildIds.delete(entry.key); - } +/** + * {@link rebuildSource} of one registered source. The record names the + * source by its face; the build's lock and this node's record of it are + * held under its index key, which no two sources share. + * + * The durable record (`knowledge-sync-state.ts`) is written once the build + * holds the lease and walks: its start, its counts at most every + * {@link BUILD_PROGRESS_LOG_INTERVAL_MS}, and its end, which lands before + * this resolves. A build that does not run (`not-run`) writes nothing: the + * row keeps the build that ran. `onStarted` is told once, with the record, + * when the walk began and its start is recorded, or when the build ended + * without walking. + */ +export async function rebuildOf( + this: Pick, + entry: KnowledgeSourceEntry, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, +): Promise { + const running = this.builds.get(entry.key); + if (running?.status === 'running') { + const copy = cloneBuildRecord(running); + opts.onStarted?.(copy); + return copy; + } + const durable: DurableBuild = { chain: Promise.resolve() }; + try { + return await this.buildUnderLease(entry, opts, durable); + } finally { + await durable.chain; + if (durable.buildId !== undefined && this.runningBuildIds.get(entry.key) === durable.buildId) { + this.runningBuildIds.delete(entry.key); } } +} - /** The body of {@link rebuildOf}; queues its durable writes on `durable.chain`. */ - static async buildUnderLease( - this: Pick< - KnowledgeServiceHost, - 'builds' | 'closeStaleBuild' | 'options' | 'readIndexStateOf' | 'recordBuildEnd' | 'recordBuildProgress' | - 'recordBuildStart' | 'reindexWith' - >, - entry: KnowledgeSourceEntry, - opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, - durable: DurableBuild, - ): Promise { - const source = entry.handed; - const record: KnowledgeBuildRecord = { - sourceId: entry.face, - trigger: opts.trigger, - status: 'running', - startedAt: new Date().toISOString(), - progress: emptyBuildProgress(), - }; - this.builds.set(entry.key, record); - const logger = this.options.logger; - const label = `[knowledge] build of source '${entry.face}' (${opts.trigger})`; - let announced = false; - const announce = (): void => { - if (announced) return; - announced = true; - opts.onStarted?.(cloneBuildRecord(record)); - }; - const finish = ( - status: Exclude, - message: string | undefined, - result?: KnowledgeReindexResult, - ): KnowledgeBuildRecord => { - record.status = status; - record.finishedAt = new Date().toISOString(); - if (message !== undefined) record.message = message; - if (result !== undefined) record.result = result; - if (status !== 'not-run') this.recordBuildEnd(entry, record, durable); - announce(); - return cloneBuildRecord(record); - }; +/** The body of {@link rebuildOf}; queues its durable writes on `durable.chain`. */ +export async function buildUnderLease( + this: Pick< + KnowledgeIndexingHost, + 'builds' | 'closeStaleBuild' | 'options' | 'readIndexStateOf' | 'recordBuildEnd' | 'recordBuildProgress' | + 'recordBuildStart' | 'reindexWith' + >, + entry: KnowledgeSourceEntry, + opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, + durable: DurableBuild, +): Promise { + const source = entry.handed; + const record: KnowledgeBuildRecord = { + sourceId: entry.face, + trigger: opts.trigger, + status: 'running', + startedAt: new Date().toISOString(), + progress: emptyBuildProgress(), + }; + this.builds.set(entry.key, record); + const logger = this.options.logger; + const label = `[knowledge] build of source '${entry.face}' (${opts.trigger})`; + let announced = false; + const announce = (): void => { + if (announced) return; + announced = true; + opts.onStarted?.(cloneBuildRecord(record)); + }; + const finish = ( + status: Exclude, + message: string | undefined, + result?: KnowledgeReindexResult, + ): KnowledgeBuildRecord => { + record.status = status; + record.finishedAt = new Date().toISOString(); + if (message !== undefined) record.message = message; + if (result !== undefined) record.result = result; + if (status !== 'not-run') this.recordBuildEnd(entry, record, durable); + announce(); + return cloneBuildRecord(record); + }; - let lock: KnowledgeBuildLock | undefined; + let lock: KnowledgeBuildLock | undefined; + try { + lock = this.options.resolveBuildLock?.(); + } catch (err) { + const message = `the cluster service could not be read (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; + logger?.warn(`${label}: ${message}`); + return finish('not-run', message); + } + let handle: KnowledgeBuildLockHandle | null = null; + if (lock) { try { - lock = this.options.resolveBuildLock?.(); + handle = await lock.acquire(buildLockKey(entry.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); } catch (err) { - const message = `the cluster service could not be read (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; + const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; logger?.warn(`${label}: ${message}`); return finish('not-run', message); } - let handle: KnowledgeBuildLockHandle | null = null; - if (lock) { - try { - handle = await lock.acquire(buildLockKey(entry.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); - } catch (err) { - const message = `the cluster lock did not answer (${errorText(err)}), so no node can prove it alone builds the source; nothing was built.`; - logger?.warn(`${label}: ${message}`); - return finish('not-run', message); - } - if (!handle) { - const message = 'another node holds the build of this source; this node built nothing.'; + if (!handle) { + const message = 'another node holds the build of this source; this node built nothing.'; + logger?.info?.(`${label}: ${message}`); + return finish('not-run', message); + } + } + const fence = startBuildFence({ + handle, + leaseMs: BUILD_LEASE_MS, + stallMs: BUILD_STALL_LIMIT_MS, + onRenewFailure: (err, held) => { + logger?.warn( + `${label}: the cluster lease could not be renewed (${errorText(err)}). ` + + (held + ? 'Renewal is retried; the build stops before its next page if the lease lapses.' + : 'The lease is lost; the build stops before its next page.'), + ); + }, + }); + try { + // This node holds the source's lease (or is the only node): a build the + // record still reads `running` is one whose node stopped. + await this.closeStaleBuild(entry); + if (opts.trigger === 'boot' || opts.trigger === 'reload') { + const reading = await this.readIndexStateOf(entry); + if (!reading.due) { + const message = `nothing to build once the lock was held: ${reading.detail}`; logger?.info?.(`${label}: ${message}`); return finish('not-run', message); } } - const fence = startBuildFence({ - handle, - leaseMs: BUILD_LEASE_MS, - stallMs: BUILD_STALL_LIMIT_MS, - onRenewFailure: (err, held) => { - logger?.warn( - `${label}: the cluster lease could not be renewed (${errorText(err)}). ` + - (held - ? 'Renewal is retried; the build stops before its next page if the lease lapses.' - : 'The lease is lost; the build stops before its next page.'), - ); - }, - }); - try { - // This node holds the source's lease (or is the only node): a build the - // record still reads `running` is one whose node stopped. - await this.closeStaleBuild(entry); - if (opts.trigger === 'boot' || opts.trigger === 'reload') { - const reading = await this.readIndexStateOf(entry); - if (!reading.due) { - const message = `nothing to build once the lock was held: ${reading.detail}`; - logger?.info?.(`${label}: ${message}`); - return finish('not-run', message); - } - } - await this.recordBuildStart(entry, record, durable); - announce(); + await this.recordBuildStart(entry, record, durable); + announce(); + logger?.info?.( + `${label} started: every row the source's where matches is read, and the content fields of each one the ` + + 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.', + ); + let lastLogged = Date.now(); + const walk = this.reindexWith(source, {}, (step) => { + // A walk the build stopped waiting on writes no progress into its ended record. + if (record.status !== 'running') return; + fence.progressed(); + record.progress = { ...step }; + const now = Date.now(); + if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return; + lastLogged = now; logger?.info?.( - `${label} started: every row the source's where matches is read, and the content fields of each one the ` + - 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.', + `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` + + `${step.skipped} unchanged, ${step.failed} cannot be indexed.`, ); - let lastLogged = Date.now(); - const walk = this.reindexWith(source, {}, (step) => { - // A walk the build stopped waiting on writes no progress into its ended record. - if (record.status !== 'running') return; - fence.progressed(); - record.progress = { ...step }; - const now = Date.now(); - if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return; - lastLogged = now; - logger?.info?.( - `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` + - `${step.skipped} unchanged, ${step.failed} cannot be indexed.`, - ); - this.recordBuildProgress(entry, record, durable); - }, fence); - // Cancelled at the stall bound: the walk is no longer waited on (it - // stops at its next page if the call it waits on ever answers). - walk.catch(() => undefined); - const raced = await Promise.race([walk, fence.cancelled.then((stop) => ({ stop }))]); - if ('stop' in raced) { - logger?.warn( - `${label} was cancelled: ${raced.stop.message} The adapter keeps what it held; ` + - 'the next reconcile, boot or operator rebuild builds again.', - ); - return finish(raced.stop.reason, raced.stop.message); - } - const result = raced; - record.progress = { - pages: record.progress.pages, - discovered: result.discovered, - indexed: result.indexed, - skipped: result.skipped ?? 0, - failed: result.failed ?? 0, - }; - const totals = - `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` + - `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`; - const stop = result.ok ? undefined : fence.stop(); - if (!result.ok) { - logger?.warn( - `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` + - 'The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.', - ); - return finish(stop?.reason ?? 'failed', result.message, result); - } - logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`); - return finish('done', result.message, result); - } catch (err) { - const message = `the build threw: ${operatorText(err)}`; - logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.`); - return finish('failed', message); - } finally { - fence.close(); - // The build's end lands before its lease is released, so a node that - // takes the lease next never reads this finished build as `running`. - await durable.chain; - if (handle) { - try { - await handle.release(); - } catch (err) { - // The lease still frees itself on its TTL; the build itself ran. - logger?.warn(`${label}: the cluster lock could not be released (${errorText(err)}); it frees itself when its lease ends.`); - } + this.recordBuildProgress(entry, record, durable); + }, fence); + // Cancelled at the stall bound: the walk is no longer waited on (it + // stops at its next page if the call it waits on ever answers). + walk.catch(() => undefined); + const raced = await Promise.race([walk, fence.cancelled.then((stop) => ({ stop }))]); + if ('stop' in raced) { + logger?.warn( + `${label} was cancelled: ${raced.stop.message} The adapter keeps what it held; ` + + 'the next reconcile, boot or operator rebuild builds again.', + ); + return finish(raced.stop.reason, raced.stop.message); + } + const result = raced; + record.progress = { + pages: record.progress.pages, + discovered: result.discovered, + indexed: result.indexed, + skipped: result.skipped ?? 0, + failed: result.failed ?? 0, + }; + const totals = + `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` + + `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`; + const stop = result.ok ? undefined : fence.stop(); + if (!result.ok) { + logger?.warn( + `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` + + 'The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.', + ); + return finish(stop?.reason ?? 'failed', result.message, result); + } + logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`); + return finish('done', result.message, result); + } catch (err) { + const message = `the build threw: ${operatorText(err)}`; + logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next reconcile, boot or operator rebuild builds again.`); + return finish('failed', message); + } finally { + fence.close(); + // The build's end lands before its lease is released, so a node that + // takes the lease next never reads this finished build as `running`. + await durable.chain; + if (handle) { + try { + await handle.release(); + } catch (err) { + // The lease still frees itself on its TTL; the build itself ran. + logger?.warn(`${label}: the cluster lock could not be released (${errorText(err)}); it frees itself when its lease ends.`); } } } +} - /** The source as its sync-state row names it. */ - static syncStateIdentity( - this: Pick, - entry: KnowledgeSourceEntry, - ): KnowledgeSyncStateIdentity { - const adapter = this.boundAdapterId(entry.handed); - return { - key: entry.key, - source: entry.face, - ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), - ...(adapter === undefined ? {} : { adapter }), - object: entry.handed.source.object, - }; - } +/** The source as its sync-state row names it. */ +export function syncStateIdentity( + this: Pick, + entry: KnowledgeSourceEntry, +): KnowledgeSyncStateIdentity { + const adapter = this.boundAdapterId(entry.handed); + return { + key: entry.key, + source: entry.face, + ...(entry.packageId === undefined ? {} : { packageId: entry.packageId }), + ...(adapter === undefined ? {} : { adapter }), + object: entry.handed.source.object, + }; +} - /** - * A sync-state write failed: the record no longer matches what happened, - * while everything else looks normal. Said once, at `error`, with what is - * lost and the fix; never thrown into the build or the sync it records. - */ - static syncStateWriteFailed( - this: Pick, - what: string, - err: unknown, - ): void { - if (this.syncStateWriteReported) { - this.options.logger?.debug?.(`[knowledge] ${what} (${errorText(err)}).`); - return; - } - this.syncStateWriteReported = true; - const report = - `[knowledge] ${what} (${errorText(err)}): the source's sync state in sys_knowledge_sync_state (its last build ` + - 'and its failed syncs, what index_status and Setup show on every node) no longer says what happened, and ' + - 'nothing else looks wrong. Check that schema sync ran for sys_knowledge_sync_state on the default datasource; ' + - 'the next build rewrites the row. Said once; later failures are logged at debug.'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); +/** + * A sync-state write failed: the record no longer matches what happened, + * while everything else looks normal. Said once, at `error`, with what is + * lost and the fix; never thrown into the build or the sync it records. + */ +export function syncStateWriteFailed( + this: Pick, + what: string, + err: unknown, +): void { + if (this.syncStateWriteReported) { + this.options.logger?.debug?.(`[knowledge] ${what} (${errorText(err)}).`); + return; } + this.syncStateWriteReported = true; + const report = + `[knowledge] ${what} (${errorText(err)}): the source's sync state in sys_knowledge_sync_state (its last build ` + + 'and its failed syncs, what index_status and Setup show on every node) no longer says what happened, and ' + + 'nothing else looks wrong. Check that schema sync ran for sys_knowledge_sync_state on the default datasource; ' + + 'the next build rewrites the row. Said once; later failures are logged at debug.'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); +} - /** The record's counts of a build record. */ - static storedCounts(record: KnowledgeBuildRecord): KnowledgeStoredBuildCounts { - return { - pages: record.progress.pages, - discovered: record.progress.discovered, - indexed: record.progress.indexed, - skipped: record.progress.skipped, - purged: record.result?.purged ?? null, - failed: record.progress.failed, - }; +/** The record's counts of a build record. */ +export function storedCounts(record: KnowledgeBuildRecord): KnowledgeStoredBuildCounts { + return { + pages: record.progress.pages, + discovered: record.progress.discovered, + indexed: record.progress.indexed, + skipped: record.progress.skipped, + purged: record.result?.purged ?? null, + failed: record.progress.failed, + }; +} + +/** Record a build's start; the build waits for it, so every node reads `running` once the walk begins. */ +export async function recordBuildStart( + this: Pick< + KnowledgeIndexingHost, + 'options' | 'runningBuildIds' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' + >, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, +): Promise { + const store = this.options.syncState; + if (!store) return; + const buildId = nextBuildId(); + durable.buildId = buildId; + this.runningBuildIds.set(entry.key, buildId); + try { + await store.startBuild(this.syncStateIdentity(entry), buildId, record.trigger, record.startedAt); + this.syncStateRecorded.add(entry.key); + } catch (err) { + this.syncStateWriteFailed(`the start of the build of source '${entry.face}' was not recorded`, err); } +} - /** Record a build's start; the build waits for it, so every node reads `running` once the walk begins. */ - static async recordBuildStart( - this: Pick< - KnowledgeServiceHost, - 'options' | 'runningBuildIds' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' - >, - entry: KnowledgeSourceEntry, - record: KnowledgeBuildRecord, - durable: DurableBuild, - ): Promise { - const store = this.options.syncState; - if (!store) return; - const buildId = nextBuildId(); - durable.buildId = buildId; - this.runningBuildIds.set(entry.key, buildId); +/** Queue a running build's counts (the walk does not wait for it). */ +export function recordBuildProgress( + this: Pick, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, +): void { + const store = this.options.syncState; + const buildId = durable.buildId; + if (!store || buildId === undefined) return; + const counts = this.storedCounts(record); + durable.chain = durable.chain.then(async () => { try { - await store.startBuild(this.syncStateIdentity(entry), buildId, record.trigger, record.startedAt); - this.syncStateRecorded.add(entry.key); + await store.progressBuild(entry.key, buildId, counts); } catch (err) { - this.syncStateWriteFailed(`the start of the build of source '${entry.face}' was not recorded`, err); + this.syncStateWriteFailed(`the progress of the build of source '${entry.face}' was not recorded`, err); } - } - - /** Queue a running build's counts (the walk does not wait for it). */ - static recordBuildProgress( - this: Pick, - entry: KnowledgeSourceEntry, - record: KnowledgeBuildRecord, - durable: DurableBuild, - ): void { - const store = this.options.syncState; - const buildId = durable.buildId; - if (!store || buildId === undefined) return; - const counts = this.storedCounts(record); - durable.chain = durable.chain.then(async () => { - try { - await store.progressBuild(entry.key, buildId, counts); - } catch (err) { - this.syncStateWriteFailed(`the progress of the build of source '${entry.face}' was not recorded`, err); - } - }); - } - - /** Queue a build's end; {@link rebuildOf} resolves once it landed. */ - static recordBuildEnd( - this: Pick, - entry: KnowledgeSourceEntry, - record: KnowledgeBuildRecord, - durable: DurableBuild, - ): void { - const store = this.options.syncState; - const buildId = durable.buildId; - if (!store || buildId === undefined || record.status === 'running' || record.status === 'not-run') return; - const status = record.status; - const counts = this.storedCounts(record); - const finishedAt = record.finishedAt ?? new Date().toISOString(); - durable.chain = durable.chain.then(async () => { - try { - const landed = await store.finishBuild(entry.key, buildId, { - status, - finishedAt, - counts, - message: storedBuildMessage({ status, counts }), - }); - if (!landed) { - this.options.logger?.info?.( - `[knowledge] the end of the build of source '${entry.face}' (${status}) was not recorded: another build ` + - 'has taken the source over since, and the record keeps that one.', - ); - } - } catch (err) { - this.syncStateWriteFailed(`the end of the build of source '${entry.face}' was not recorded`, err); - } - }); - } + }); +} - /** - * Close the build the record reads `running` for `entry` as `interrupted`, - * when it is not one this node runs. Called by a node that holds the - * source's lease (or the only node), so no live build can be the one the - * record names. Never throws. - */ - static async closeStaleBuild( - this: Pick, - entry: KnowledgeSourceEntry, - ): Promise { - const store = this.options.syncState; - if (!store) return false; +/** Queue a build's end; {@link rebuildOf} resolves once it landed. */ +export function recordBuildEnd( + this: Pick, + entry: KnowledgeSourceEntry, + record: KnowledgeBuildRecord, + durable: DurableBuild, +): void { + const store = this.options.syncState; + const buildId = durable.buildId; + if (!store || buildId === undefined || record.status === 'running' || record.status === 'not-run') return; + const status = record.status; + const counts = this.storedCounts(record); + const finishedAt = record.finishedAt ?? new Date().toISOString(); + durable.chain = durable.chain.then(async () => { try { - const state = await store.read(entry.key); - if (state?.build?.status !== 'running' || state.buildId === undefined) return false; - if (this.runningBuildIds.get(entry.key) === state.buildId) return false; - const closed = await store.closeInterrupted(entry.key, state.buildId, new Date().toISOString()); - if (closed) { + const landed = await store.finishBuild(entry.key, buildId, { + status, + finishedAt, + counts, + message: storedBuildMessage({ status, counts }), + }); + if (!landed) { this.options.logger?.info?.( - `[knowledge] source '${entry.face}': the ${state.build.trigger} build started ${state.build.startedAt} ` + - 'by a node that stopped before it ended is closed as interrupted.', + `[knowledge] the end of the build of source '${entry.face}' (${status}) was not recorded: another build ` + + 'has taken the source over since, and the record keeps that one.', ); } - return closed; } catch (err) { - this.syncStateWriteFailed(`the interrupted build of source '${entry.face}' was not closed`, err); - return false; + this.syncStateWriteFailed(`the end of the build of source '${entry.face}' was not recorded`, err); } - } + }); +} - static async closeInterruptedBuilds( - this: Pick, - ): Promise { - const store = this.options.syncState; - if (!store) return 0; - let running: Awaited>; - try { - running = await store.runningBuilds(); - } catch (err) { - this.syncStateWriteFailed('the builds a stopped node left running could not be read at boot', err); - return 0; - } - let closed = 0; - for (const state of running) { - if (state.buildId === undefined) continue; - if (this.runningBuildIds.get(state.key) === state.buildId) continue; - let lock: KnowledgeBuildLock | undefined; - let handle: KnowledgeBuildLockHandle | null = null; - try { - lock = this.options.resolveBuildLock?.(); - if (lock) { - handle = await lock.acquire(buildLockKey(state.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); - if (!handle) continue; // A node is building it now. - } - } catch (err) { - // The lock, not the record: the build is left as it reads, and the - // next node that takes the source's lease closes it. - this.options.logger?.warn?.( - `[knowledge] the build of source '${state.source}' a stopped node may have left running was not closed at ` + - `boot: the cluster lock did not answer (${errorText(err)}). The next node that takes the source's build ` + - 'lease closes it.', - ); - continue; - } - try { - if (await store.closeInterrupted(state.key, state.buildId, new Date().toISOString())) closed++; - } catch (err) { - this.syncStateWriteFailed(`the interrupted build of source '${state.source}' was not closed at boot`, err); - } finally { - if (handle) await handle.release().catch(() => undefined); - } - } - if (closed > 0) { +/** + * Close the build the record reads `running` for `entry` as `interrupted`, + * when it is not one this node runs. Called by a node that holds the + * source's lease (or the only node), so no live build can be the one the + * record names. Never throws. + */ +export async function closeStaleBuild( + this: Pick, + entry: KnowledgeSourceEntry, +): Promise { + const store = this.options.syncState; + if (!store) return false; + try { + const state = await store.read(entry.key); + if (state?.build?.status !== 'running' || state.buildId === undefined) return false; + if (this.runningBuildIds.get(entry.key) === state.buildId) return false; + const closed = await store.closeInterrupted(entry.key, state.buildId, new Date().toISOString()); + if (closed) { this.options.logger?.info?.( - `[knowledge] ${closed} build(s) a stopped node left running are closed as interrupted in sys_knowledge_sync_state.`, + `[knowledge] source '${entry.face}': the ${state.build.trigger} build started ${state.build.startedAt} ` + + 'by a node that stopped before it ended is closed as interrupted.', ); } return closed; + } catch (err) { + this.syncStateWriteFailed(`the interrupted build of source '${entry.face}' was not closed`, err); + return false; } +} - static async buildSourcesAtBoot( - this: Pick, - ): Promise { - if (this.held) return; - let entries: KnowledgeSourceEntry[]; +/** The body of {@link KnowledgeService.closeInterruptedBuilds}; the member's docblock there is its contract. */ +export async function closeInterruptedBuilds( + this: Pick, +): Promise { + const store = this.options.syncState; + if (!store) return 0; + let running: Awaited>; + try { + running = await store.runningBuilds(); + } catch (err) { + this.syncStateWriteFailed('the builds a stopped node left running could not be read at boot', err); + return 0; + } + let closed = 0; + for (const state of running) { + if (state.buildId === undefined) continue; + if (this.runningBuildIds.get(state.key) === state.buildId) continue; + let lock: KnowledgeBuildLock | undefined; + let handle: KnowledgeBuildLockHandle | null = null; try { - entries = this.registry.entries(); + lock = this.options.resolveBuildLock?.(); + if (lock) { + handle = await lock.acquire(buildLockKey(state.key), { ttlMs: BUILD_LEASE_MS, waitMs: 0 }); + if (!handle) continue; // A node is building it now. + } } catch (err) { - this.options.logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); - return; - } - for (const entry of entries) { - if (this.buildsStopped) return; - await this.buildIfDue(entry, 'boot'); + // The lock, not the record: the build is left as it reads, and the + // next node that takes the source's lease closes it. + this.options.logger?.warn?.( + `[knowledge] the build of source '${state.source}' a stopped node may have left running was not closed at ` + + `boot: the cluster lock did not answer (${errorText(err)}). The next node that takes the source's build ` + + 'lease closes it.', + ); + continue; } - } - - static async buildReloadedSource( - this: Pick, - key: string, - ): Promise { - const entry = this.registry.byIndexKey(key); - if (entry && !this.buildsStopped && !this.held) await this.buildIfDue(entry, 'reload'); - } - - /** One source of {@link buildSourcesAtBoot}. Never rejects. */ - static async buildIfDue( - this: Pick, - entry: KnowledgeSourceEntry, - trigger: KnowledgeBuildTrigger, - ): Promise { - const logger = this.options.logger; - const when = trigger === 'boot' ? 'at boot' : 'on reload'; try { - if ((entry.authored.refresh?.onRecordChange ?? true) === false) { - logger?.debug?.(`[knowledge] source '${entry.face}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built ${when}.`); - return; - } - // A source whose adapter is not mounted is named once at boot, at - // `error`, by the boot's reading (`reportUnmountedAdapters`); the pass - // adds no second line for it. On reload no reading runs, so the line - // below is the one that names it. A source that names no adapter and - // cannot be placed is named by the same reading. - if (trigger === 'boot') { - const adapterId = this.boundAdapterId(entry.handed); - if (adapterId === undefined || !this.adapters.has(adapterId)) return; - } - const reading = await this.readIndexStateOf(entry); - if (reading.due) { - logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); - await this.rebuildOf(entry, { trigger }); - return; - } - const line = `[knowledge] source '${entry.face}' is not built ${when}: ${reading.detail}`; - // What cannot be seen or read is said once, at `warn` (K7: "the - // service says so once"); a source that is current, or whose adapter - // holds documents it reports no status for, is ordinary. - if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { - logger?.warn(line); - } else { - logger?.info?.(line); - } + if (await store.closeInterrupted(state.key, state.buildId, new Date().toISOString())) closed++; } catch (err) { - logger?.warn(`[knowledge] source '${entry.face}': the build pass failed for it (${operatorText(err)}).`); + this.syncStateWriteFailed(`the interrupted build of source '${state.source}' was not closed at boot`, err); + } finally { + if (handle) await handle.release().catch(() => undefined); } } - - static stopBuilds( - this: Pick, - ): void { - this.buildsStopped = true; - for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); - } - - static reconcileSources( - this: Pick, - opts: { sources?: string[] } = {}, - ): Promise { - const names = opts.sources; - // Held, the pass walks nothing: no store is called while not enabled. - return this.enqueueReconcile(() => - this.held - ? [] - : names === undefined - ? this.registry.entries() - : names.map((name) => this.registry.resolve(name)).filter((e): e is KnowledgeSourceEntry => e !== undefined), + if (closed > 0) { + this.options.logger?.info?.( + `[knowledge] ${closed} build(s) a stopped node left running are closed as interrupted in sys_knowledge_sync_state.`, ); } + return closed; +} - /** Queue one reconcile pass over the entries `select` answers when its turn comes. */ - static enqueueReconcile( - this: Pick, - select: () => KnowledgeSourceEntry[], - ): Promise { - const pass = this.reconcileTail.then(() => this.reconcilePass(select)); - this.reconcileTail = pass.then(() => undefined, () => undefined); - return pass; +/** The body of {@link KnowledgeService.buildSourcesAtBoot}; the member's docblock there is its contract. */ +export async function buildSourcesAtBoot( + this: Pick, +): Promise { + if (this.held) return; + let entries: KnowledgeSourceEntry[]; + try { + entries = this.registry.entries(); + } catch (err) { + this.options.logger?.warn(`[knowledge] the boot build pass could not list the sources (${operatorText(err)}); none is built at boot.`); + return; + } + for (const entry of entries) { + if (this.buildsStopped) return; + await this.buildIfDue(entry, 'boot'); } +} - /** One pass of {@link reconcileSources}; runs after the pass before it. */ - static async reconcilePass( - this: Pick, - select: () => KnowledgeSourceEntry[], - ): Promise { - const startedAt = new Date().toISOString(); - const report: KnowledgeReconcileReport = { startedAt, finishedAt: startedAt, sources: [], unfinished: [] }; - let entries: KnowledgeSourceEntry[]; - try { - entries = select(); - } catch (err) { - this.options.logger?.warn(`[knowledge] the reconcile could not list the sources (${operatorText(err)}); none was reconciled.`); - report.unfinished.push({ sourceId: '*', status: 'failed', message: `the sources could not be listed (${operatorText(err)})` }); - report.finishedAt = new Date().toISOString(); - return report; +/** The body of {@link KnowledgeService.buildReloadedSource}; the member's docblock there is its contract. */ +export async function buildReloadedSource( + this: Pick, + key: string, +): Promise { + const entry = this.registry.byIndexKey(key); + if (entry && !this.buildsStopped && !this.held) await this.buildIfDue(entry, 'reload'); +} + +/** One source of {@link buildSourcesAtBoot}. Never rejects. */ +export async function buildIfDue( + this: Pick, + entry: KnowledgeSourceEntry, + trigger: KnowledgeBuildTrigger, +): Promise { + const logger = this.options.logger; + const when = trigger === 'boot' ? 'at boot' : 'on reload'; + try { + if ((entry.authored.refresh?.onRecordChange ?? true) === false) { + logger?.debug?.(`[knowledge] source '${entry.face}': refresh.onRecordChange is false, so an external indexer owns its index; it is not built ${when}.`); + return; } - for (const entry of entries) { - if (this.buildsStopped) break; - // A source removed while the pass ran is not walked. - if (this.registry.byIndexKey(entry.key) !== entry) continue; - const done = await this.reconcileOf(entry); - report.sources.push(done); - const status = done.record?.status; - if (status === 'failed' || status === 'lease-lost' || status === 'timed-out') { - report.unfinished.push({ sourceId: entry.face, status, ...(done.record?.message === undefined ? {} : { message: done.record.message }) }); - } + // A source whose adapter is not mounted is named once at boot, at + // `error`, by the boot's reading (`reportUnmountedAdapters`); the pass + // adds no second line for it. On reload no reading runs, so the line + // below is the one that names it. A source that names no adapter and + // cannot be placed is named by the same reading. + if (trigger === 'boot') { + const adapterId = this.boundAdapterId(entry.handed); + if (adapterId === undefined || !this.adapters.has(adapterId)) return; + } + const reading = await this.readIndexStateOf(entry); + if (reading.due) { + logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); + await this.rebuildOf(entry, { trigger }); + return; + } + const line = `[knowledge] source '${entry.face}' is not built ${when}: ${reading.detail}`; + // What cannot be seen or read is said once, at `warn` (K7: "the + // service says so once"); a source that is current, or whose adapter + // holds documents it reports no status for, is ordinary. + if (reading.state === 'unknown' || reading.state === 'unreadable' || reading.state === 'no-recipe-hash') { + logger?.warn(line); + } else { + logger?.info?.(line); } + } catch (err) { + logger?.warn(`[knowledge] source '${entry.face}': the build pass failed for it (${operatorText(err)}).`); + } +} + +/** The body of {@link KnowledgeService.stopBuilds}; the member's docblock there is its contract. */ +export function stopBuilds( + this: Pick, +): void { + this.buildsStopped = true; + for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); +} + +/** The body of {@link KnowledgeService.reconcileSources}; the member's docblock there is its contract. */ +export function reconcileSources( + this: Pick, + opts: { sources?: string[] } = {}, +): Promise { + const names = opts.sources; + // Held, the pass walks nothing: no store is called while not enabled. + return this.enqueueReconcile(() => + this.held + ? [] + : names === undefined + ? this.registry.entries() + : names.map((name) => this.registry.resolve(name)).filter((e): e is KnowledgeSourceEntry => e !== undefined), + ); +} + +/** Queue one reconcile pass over the entries `select` answers when its turn comes. */ +export function enqueueReconcile( + this: Pick, + select: () => KnowledgeSourceEntry[], +): Promise { + const pass = this.reconcileTail.then(() => this.reconcilePass(select)); + this.reconcileTail = pass.then(() => undefined, () => undefined); + return pass; +} + +/** One pass of {@link reconcileSources}; runs after the pass before it. */ +export async function reconcilePass( + this: Pick, + select: () => KnowledgeSourceEntry[], +): Promise { + const startedAt = new Date().toISOString(); + const report: KnowledgeReconcileReport = { startedAt, finishedAt: startedAt, sources: [], unfinished: [] }; + let entries: KnowledgeSourceEntry[]; + try { + entries = select(); + } catch (err) { + this.options.logger?.warn(`[knowledge] the reconcile could not list the sources (${operatorText(err)}); none was reconciled.`); + report.unfinished.push({ sourceId: '*', status: 'failed', message: `the sources could not be listed (${operatorText(err)})` }); report.finishedAt = new Date().toISOString(); return report; } + for (const entry of entries) { + if (this.buildsStopped) break; + // A source removed while the pass ran is not walked. + if (this.registry.byIndexKey(entry.key) !== entry) continue; + const done = await this.reconcileOf(entry); + report.sources.push(done); + const status = done.record?.status; + if (status === 'failed' || status === 'lease-lost' || status === 'timed-out') { + report.unfinished.push({ sourceId: entry.face, status, ...(done.record?.message === undefined ? {} : { message: done.record.message }) }); + } + } + report.finishedAt = new Date().toISOString(); + return report; +} - /** One source of a reconcile pass. Never rejects. */ - static async reconcileOf( - this: Pick< - KnowledgeServiceHost, - 'clearRepairedFailures' | 'options' | 'readIndexStateOf' | 'rebuildOf' | 'reconcileExclusion' | - 'reconcileUnlistedReported' - >, - entry: KnowledgeSourceEntry, - ): Promise { - const logger = this.options.logger; - const left = (why: string): KnowledgeReconcileEntry => ({ sourceId: entry.face, left: why }); - try { - const why = this.reconcileExclusion(entry); - if (why !== undefined) { - if (why.unlisted) { - if (!this.reconcileUnlistedReported.has(entry.key)) { - this.reconcileUnlistedReported.add(entry.key); - logger?.warn(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); - } - } else { - logger?.debug?.(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); +/** One source of a reconcile pass. Never rejects. */ +export async function reconcileOf( + this: Pick< + KnowledgeIndexingHost, + 'clearRepairedFailures' | 'options' | 'readIndexStateOf' | 'rebuildOf' | 'reconcileExclusion' | + 'reconcileUnlistedReported' + >, + entry: KnowledgeSourceEntry, +): Promise { + const logger = this.options.logger; + const left = (why: string): KnowledgeReconcileEntry => ({ sourceId: entry.face, left: why }); + try { + const why = this.reconcileExclusion(entry); + if (why !== undefined) { + if (why.unlisted) { + if (!this.reconcileUnlistedReported.has(entry.key)) { + this.reconcileUnlistedReported.add(entry.key); + logger?.warn(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); } - return left(why.text); + } else { + logger?.debug?.(`[knowledge] source '${entry.face}' is not reconciled: ${why.text}`); } - const reading = await this.readIndexStateOf(entry); - logger?.info?.( - reading.due - ? `[knowledge] source '${entry.face}' is built by the reconcile now: ${reading.detail}` - : `[knowledge] source '${entry.face}' is reconciled now (${reading.state}): ${reading.detail}`, - ); - const record = await this.rebuildOf(entry, { trigger: 'reconcile' }); - // [ADR-0161 K1] The reconcile is the failure count's reader: a walk that - // completed re-read every row, so the syncs that failed before it began - // are repaired or no longer apply. - if (record.status === 'done') await this.clearRepairedFailures(entry, record.startedAt); - return { sourceId: entry.face, record }; - } catch (err) { - const message = `the reconcile failed for it (${operatorText(err)}).`; - logger?.warn(`[knowledge] source '${entry.face}': ${message}`); - const now = new Date().toISOString(); - return { - sourceId: entry.face, - record: { sourceId: entry.face, trigger: 'reconcile', status: 'failed', startedAt: now, finishedAt: now, progress: emptyBuildProgress(), message }, - }; + return left(why.text); } + const reading = await this.readIndexStateOf(entry); + logger?.info?.( + reading.due + ? `[knowledge] source '${entry.face}' is built by the reconcile now: ${reading.detail}` + : `[knowledge] source '${entry.face}' is reconciled now (${reading.state}): ${reading.detail}`, + ); + const record = await this.rebuildOf(entry, { trigger: 'reconcile' }); + // [ADR-0161 K1] The reconcile is the failure count's reader: a walk that + // completed re-read every row, so the syncs that failed before it began + // are repaired or no longer apply. + if (record.status === 'done') await this.clearRepairedFailures(entry, record.startedAt); + return { sourceId: entry.face, record }; + } catch (err) { + const message = `the reconcile failed for it (${operatorText(err)}).`; + logger?.warn(`[knowledge] source '${entry.face}': ${message}`); + const now = new Date().toISOString(); + return { + sourceId: entry.face, + record: { sourceId: entry.face, trigger: 'reconcile', status: 'failed', startedAt: now, finishedAt: now, progress: emptyBuildProgress(), message }, + }; } +} - /** - * Why the reconcile does not walk `entry`, or `undefined` when it does. - * `unlisted` marks the one exclusion said at `warn`: a store that lists no - * documents. An adapter that is not mounted is walked, so its build fails - * and names it. - */ - static reconcileExclusion( - this: Pick, - entry: KnowledgeSourceEntry, - ): { text: string; unlisted: boolean } | undefined { - if ((entry.authored.refresh?.onRecordChange ?? true) === false) { - return { text: 'refresh.onRecordChange is false, so an external indexer owns its index.', unlisted: false }; - } - if (!this.options.dataEngine) { - return { text: 'no data engine is bound, so the source cannot be walked.', unlisted: false }; - } - const adapterId = this.boundAdapterId(entry.handed); - const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); - if (adapter && typeof adapter.listDocuments !== 'function') { - return { - text: - `its adapter '${adapter.id}' does not list its documents (no listDocuments), so a walk could neither skip ` + - 'an unchanged document nor purge a stale one: it would send every document to the embedding provider again ' + - 'and remove nothing. Rows deleted or changed without an event stay as they are in its index until an ' + - 'operator rebuild (os knowledge rebuild).', - unlisted: true, - }; - } - return undefined; +/** + * Why the reconcile does not walk `entry`, or `undefined` when it does. + * `unlisted` marks the one exclusion said at `warn`: a store that lists no + * documents. An adapter that is not mounted is walked, so its build fails + * and names it. + */ +export function reconcileExclusion( + this: Pick, + entry: KnowledgeSourceEntry, +): { text: string; unlisted: boolean } | undefined { + if ((entry.authored.refresh?.onRecordChange ?? true) === false) { + return { text: 'refresh.onRecordChange is false, so an external indexer owns its index.', unlisted: false }; } - - static requestReconcile( - this: Pick< - KnowledgeServiceHost, - 'armReconcile' | 'buildsStopped' | 'held' | 'options' | 'reconcileExclusion' | 'registry' - >, - object: string, - ): KnowledgeReconcileRequest { - const request: KnowledgeReconcileRequest = { scheduled: [], unreconcilable: [] }; - if (this.buildsStopped || this.held) return request; - for (const entry of this.registry.entries()) { - if (entry.handed.source.object !== object) continue; - const why = this.reconcileExclusion(entry); - if (why !== undefined) { - // An external indexer's index is not this service's to call stale. - if (why.unlisted || !this.options.dataEngine) request.unreconcilable.push(entry.face); - continue; - } - this.armReconcile(entry.key, Date.now()); - request.scheduled.push(entry.face); - } - return request; + if (!this.options.dataEngine) { + return { text: 'no data engine is bound, so the source cannot be walked.', unlisted: false }; } + const adapterId = this.boundAdapterId(entry.handed); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapter && typeof adapter.listDocuments !== 'function') { + return { + text: + `its adapter '${adapter.id}' does not list its documents (no listDocuments), so a walk could neither skip ` + + 'an unchanged document nor purge a stale one: it would send every document to the embedding provider again ' + + 'and remove nothing. Rows deleted or changed without an event stay as they are in its index until an ' + + 'operator rebuild (os knowledge rebuild).', + unlisted: true, + }; + } + return undefined; +} - /** (Re)arm the pending reconcile of the source under `key`; `now` is when the request arrived. */ - static armReconcile( - this: Pick< - KnowledgeServiceHost, - 'armReconcile' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'pendingReconciles' | 'registry' - >, - key: string, - now: number, - ): void { - const pending = this.pendingReconciles.get(key); - const firstAt = pending?.firstAt ?? now; - if (pending) clearTimeout(pending.timer); - const wait = Math.max(0, Math.min(RECONCILE_QUIET_MS, firstAt + RECONCILE_MAX_WAIT_MS - now)); - const timer = setTimeout(() => { - this.pendingReconciles.delete(key); - const entry = this.registry.byIndexKey(key); - if (!entry || this.buildsStopped || this.held) return; - // A build of the source running now may have read past the rows the - // write changed: wait for it, then walk again. - if (this.builds.get(key)?.status === 'running') { - this.armReconcile(key, Date.now()); - return; - } - void this.enqueueReconcile(() => { - const current = this.registry.byIndexKey(key); - return current === undefined ? [] : [current]; - }).catch(() => undefined); - }, wait); - (timer as { unref?: () => void }).unref?.(); - this.pendingReconciles.set(key, { timer, firstAt }); +/** The body of {@link KnowledgeService.requestReconcile}; the member's docblock there is its contract. */ +export function requestReconcile( + this: Pick< + KnowledgeIndexingHost, + 'armReconcile' | 'buildsStopped' | 'held' | 'options' | 'reconcileExclusion' | 'registry' + >, + object: string, +): KnowledgeReconcileRequest { + const request: KnowledgeReconcileRequest = { scheduled: [], unreconcilable: [] }; + if (this.buildsStopped || this.held) return request; + for (const entry of this.registry.entries()) { + if (entry.handed.source.object !== object) continue; + const why = this.reconcileExclusion(entry); + if (why !== undefined) { + // An external indexer's index is not this service's to call stale. + if (why.unlisted || !this.options.dataEngine) request.unreconcilable.push(entry.face); + continue; + } + this.armReconcile(entry.key, Date.now()); + request.scheduled.push(entry.face); } + return request; +} - /** Drop the pending reconcile of the source under `key`, if any. */ - static cancelPendingReconcile(this: Pick, key: string): void { - const pending = this.pendingReconciles.get(key); - if (!pending) return; - clearTimeout(pending.timer); +/** (Re)arm the pending reconcile of the source under `key`; `now` is when the request arrived. */ +export function armReconcile( + this: Pick< + KnowledgeIndexingHost, + 'armReconcile' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'pendingReconciles' | 'registry' + >, + key: string, + now: number, +): void { + const pending = this.pendingReconciles.get(key); + const firstAt = pending?.firstAt ?? now; + if (pending) clearTimeout(pending.timer); + const wait = Math.max(0, Math.min(RECONCILE_QUIET_MS, firstAt + RECONCILE_MAX_WAIT_MS - now)); + const timer = setTimeout(() => { this.pendingReconciles.delete(key); - } + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held) return; + // A build of the source running now may have read past the rows the + // write changed: wait for it, then walk again. + if (this.builds.get(key)?.status === 'running') { + this.armReconcile(key, Date.now()); + return; + } + void this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }).catch(() => undefined); + }, wait); + (timer as { unref?: () => void }).unref?.(); + this.pendingReconciles.set(key, { timer, firstAt }); +} + +/** Drop the pending reconcile of the source under `key`, if any. */ +export function cancelPendingReconcile(this: Pick, key: string): void { + const pending = this.pendingReconciles.get(key); + if (!pending) return; + clearTimeout(pending.timer); + this.pendingReconciles.delete(key); } diff --git a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts index 89437f3737e..e0648a07dd4 100644 --- a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts +++ b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts @@ -12,21 +12,23 @@ * `reportWhereUnenforceable`, `serializeRecordSync`, `schemaFor`, * `handleRecordDelete`, moved out of `knowledge-service.ts` whole. * - * A MOVE, not a redesign. {@link KnowledgeRecordSyncFacet} is a stateless facet of - * `KnowledgeService`: each static method is the body of the `KnowledgeService` - * member of the same name exactly as it stood (not re-indented, not edited). - * The member stays on the class as a one-call stub with its signature, so the - * published declaration, an instance spy and a subclass override are what they - * were. A public member keeps its docblock on the class, the contract; a - * private member's docblock moved here with its body. The state stays on - * `KnowledgeService`. + * A MOVE, not a redesign. Each function below is the body of the + * `KnowledgeService` member of the same name as it stood, re-indented one + * level and otherwise unedited (a line inside a string or template literal + * keeps its bytes). The member stays on the class as a one-call stub with its + * signature, so the published declaration, an instance spy and a subclass + * override are what they were; the class imports this module as + * `KnowledgeRecordSyncFacet`. A public member keeps its docblock on the class, the + * contract; a private member's docblock moved here with its body. The state + * stays on `KnowledgeService`. * * A body reaches the service through `this`, typed as the part of - * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands - * it the host the class's static block builds once per service, whose methods call - * the service at call time and whose fields are getters (and a setter for a - * field a body assigns). A body that reads nothing of the service is called - * without one. `index.ts` re-exports nothing from this module. + * {@link KnowledgeRecordSyncHost} it reads: the stub hands it the host the class's static + * block builds once per service (`knowledge-service-host.ts`), whose methods call the + * service at call time and whose fields are getters (and a setter for a field + * a body assigns). A body that reads nothing of the service is called without + * one. The module imports `knowledge-service.ts` for types only, so the two + * form no evaluation cycle. `index.ts` re-exports nothing from this module. */ import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; @@ -72,804 +74,871 @@ import { rereadRows, systemContext, } from './knowledge-service-top-level.js'; -import type { KnowledgeServiceHost } from './knowledge-service-host.js'; - -export class KnowledgeRecordSyncFacet { - static async recordSources( - this: Pick< - KnowledgeServiceHost, - 'options' | 'registry' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' - >, - ): Promise { - const store = this.options.syncState; - if (!store) return; - for (const entry of this.registry.entries()) { - if (this.syncStateRecorded.has(entry.key)) continue; - try { - await store.ensure(this.syncStateIdentity(entry)); - this.syncStateRecorded.add(entry.key); - } catch (err) { - this.syncStateWriteFailed(`the sync-state row of source '${entry.face}' could not be written`, err); - } - } - } +import type { KnowledgeService } from './knowledge-service.js'; - static hasDurableSyncState(this: Pick): boolean { - return this.options.syncState !== undefined; - } +/** + * The `KnowledgeService` members the bodies in this module read: every one + * of them, and no other. Each is typed AS the class member (an indexed + * access on the class), so a change to a member's type on the class is a change + * here too, and a name the class does not have does not compile. `readonly` + * members are methods and fields no body here assigns; the others are fields a + * body here assigns. + */ +export interface KnowledgeRecordSyncHost { + readonly adapterFor: KnowledgeService['adapterFor']; + readonly armReconcile: KnowledgeService['armReconcile']; + readonly backlogReconciles: KnowledgeService['backlogReconciles']; + readonly builds: KnowledgeService['builds']; + readonly buildsStopped: KnowledgeService['buildsStopped']; + readonly considerBacklogReconcile: KnowledgeService['considerBacklogReconcile']; + readonly coveredByBuild: KnowledgeService['coveredByBuild']; + readonly deadLettersOf: KnowledgeService['deadLettersOf']; + readonly enqueueReconcile: KnowledgeService['enqueueReconcile']; + readonly handed: KnowledgeService['handed']; + readonly held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly options: KnowledgeService['options']; + readonly pendingRecordSyncs: KnowledgeService['pendingRecordSyncs']; + readonly planIndex: KnowledgeService['planIndex']; + readonly prepareDocuments: KnowledgeService['prepareDocuments']; + readonly publishRecordSyncs: KnowledgeService['publishRecordSyncs']; + readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; + readonly reconcileExclusion: KnowledgeService['reconcileExclusion']; + recordSyncBacklog: KnowledgeService['recordSyncBacklog']; + readonly recordSyncPublisher: KnowledgeService['recordSyncPublisher']; + readonly recordSyncQueueView: KnowledgeService['recordSyncQueueView']; + readonly recordSyncTails: KnowledgeService['recordSyncTails']; + readonly recordSyncWaiting: KnowledgeService['recordSyncWaiting']; + readonly registry: KnowledgeService['registry']; + readonly reportUnindexable: KnowledgeService['reportUnindexable']; + readonly reportWhereUnenforceable: KnowledgeService['reportWhereUnenforceable']; + readonly requestSourceReconcile: KnowledgeService['requestSourceReconcile']; + readonly requireEntry: KnowledgeService['requireEntry']; + readonly resolveRecordSync: KnowledgeService['resolveRecordSync']; + readonly schemaFor: KnowledgeService['schemaFor']; + readonly serializeRecordSync: KnowledgeService['serializeRecordSync']; + readonly sourceRowCount: KnowledgeService['sourceRowCount']; + readonly sourceRows: KnowledgeService['sourceRows']; + readonly sourcesForObject: KnowledgeService['sourcesForObject']; + readonly storedCounts: KnowledgeService['storedCounts']; + readonly syncRecord: KnowledgeService['syncRecord']; + readonly syncRecordGroup: KnowledgeService['syncRecordGroup']; + readonly syncRow: KnowledgeService['syncRow']; + readonly syncRows: KnowledgeService['syncRows']; + readonly syncStateIdentity: KnowledgeService['syncStateIdentity']; + readonly syncStateRecorded: KnowledgeService['syncStateRecorded']; + readonly syncStateWriteFailed: KnowledgeService['syncStateWriteFailed']; + readonly whereUnenforceableReported: KnowledgeService['whereUnenforceableReported']; + readonly writeSynced: KnowledgeService['writeSynced']; +} - static async syncStateOf( - this: Pick, - sourceId: string, - ): Promise<{ build: KnowledgeStoredBuild | null; failures: KnowledgeSyncFailures }> { - const entry = this.requireEntry(sourceId); - const store = this.options.syncState; - if (store) { - const state = await store.read(entry.key); - return { build: state?.build ?? null, failures: state?.failures ?? { count: 0 } }; +/** The body of {@link KnowledgeService.recordSources}; the member's docblock there is its contract. */ +export async function recordSources( + this: Pick< + KnowledgeRecordSyncHost, + 'options' | 'registry' | 'syncStateIdentity' | 'syncStateRecorded' | 'syncStateWriteFailed' + >, +): Promise { + const store = this.options.syncState; + if (!store) return; + for (const entry of this.registry.entries()) { + if (this.syncStateRecorded.has(entry.key)) continue; + try { + await store.ensure(this.syncStateIdentity(entry)); + this.syncStateRecorded.add(entry.key); + } catch (err) { + this.syncStateWriteFailed(`the sync-state row of source '${entry.face}' could not be written`, err); } - const record = this.builds.get(entry.key); - if (!record || record.status === 'not-run') return { build: null, failures: { count: 0 } }; - const counts = this.storedCounts(record); - return { - build: { - trigger: record.trigger, - status: record.status, - startedAt: record.startedAt, - ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), - counts, - ...(record.status === 'running' ? {} : { message: storedBuildMessage({ status: record.status, counts }) }), - }, - failures: { count: 0 }, - }; } +} - static async pendingRecordSyncs(this: Pick): Promise { - const view = this.recordSyncQueueView; - if (!view || typeof view.getQueueSize !== 'function') return undefined; - return view.getQueueSize(KNOWLEDGE_RECORD_SYNC_QUEUE); - } +/** The body of {@link KnowledgeService.hasDurableSyncState}; the member's docblock there is its contract. */ +export function hasDurableSyncState(this: Pick): boolean { + return this.options.syncState !== undefined; +} - static async recordSyncFailure( - this: Pick< - KnowledgeServiceHost, - 'options' | 'registry' | 'requestSourceReconcile' | 'syncStateIdentity' | 'syncStateRecorded' | - 'syncStateWriteFailed' - >, - data: unknown, - err: unknown, - attempts: { attempt: number; maxAttempts: number }, - ): Promise { - const message = readRecordSyncMessage(data); - if (!message) return; - const entry = this.registry.byIndexKey(message.source); - const store = this.options.syncState; - if (!entry || !store) return; - let written: Awaited>; - try { - written = await store.addFailure( - this.syncStateIdentity(entry), - new Date().toISOString(), - syncFailureText(message.recordId, attempts.attempt, attempts.maxAttempts, err), - ); - this.syncStateRecorded.add(entry.key); - } catch (writeErr) { - this.syncStateWriteFailed(`a failed sync of source '${entry.face}' was not counted`, writeErr); - return; - } - if (written.first) this.requestSourceReconcile(entry); +/** The body of {@link KnowledgeService.syncStateOf}; the member's docblock there is its contract. */ +export async function syncStateOf( + this: Pick, + sourceId: string, +): Promise<{ build: KnowledgeStoredBuild | null; failures: KnowledgeSyncFailures }> { + const entry = this.requireEntry(sourceId); + const store = this.options.syncState; + if (store) { + const state = await store.read(entry.key); + return { build: state?.build ?? null, failures: state?.failures ?? { count: 0 } }; } + const record = this.builds.get(entry.key); + if (!record || record.status === 'not-run') return { build: null, failures: { count: 0 } }; + const counts = this.storedCounts(record); + return { + build: { + trigger: record.trigger, + status: record.status, + startedAt: record.startedAt, + ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), + counts, + ...(record.status === 'running' ? {} : { message: storedBuildMessage({ status: record.status, counts }) }), + }, + failures: { count: 0 }, + }; +} - /** Ask for a reconcile of one source, as a predicate write does ({@link requestReconcile}). */ - static requestSourceReconcile( - this: Pick, - entry: KnowledgeSourceEntry, - ): void { - if (this.buildsStopped || this.reconcileExclusion(entry) !== undefined) return; - this.armReconcile(entry.key, Date.now()); - this.options.logger?.info?.( - `[knowledge] source '${entry.face}' has its first failed sync: a reconcile of it is asked for, and starts once ` + - 'the quiet period passes.', +/** The body of {@link KnowledgeService.pendingRecordSyncs}; the member's docblock there is its contract. */ +export async function pendingRecordSyncs( + this: Pick, +): Promise { + const view = this.recordSyncQueueView; + if (!view || typeof view.getQueueSize !== 'function') return undefined; + return view.getQueueSize(KNOWLEDGE_RECORD_SYNC_QUEUE); +} + +/** The body of {@link KnowledgeService.recordSyncFailure}; the member's docblock there is its contract. */ +export async function recordSyncFailure( + this: Pick< + KnowledgeRecordSyncHost, + 'options' | 'registry' | 'requestSourceReconcile' | 'syncStateIdentity' | 'syncStateRecorded' | + 'syncStateWriteFailed' + >, + data: unknown, + err: unknown, + attempts: { attempt: number; maxAttempts: number }, +): Promise { + const message = readRecordSyncMessage(data); + if (!message) return; + const entry = this.registry.byIndexKey(message.source); + const store = this.options.syncState; + if (!entry || !store) return; + let written: Awaited>; + try { + written = await store.addFailure( + this.syncStateIdentity(entry), + new Date().toISOString(), + syncFailureText(message.recordId, attempts.attempt, attempts.maxAttempts, err), ); + this.syncStateRecorded.add(entry.key); + } catch (writeErr) { + this.syncStateWriteFailed(`a failed sync of source '${entry.face}' was not counted`, writeErr); + return; } + if (written.first) this.requestSourceReconcile(entry); +} - /** - * After a reconcile of `entry` that completed: clear the failures that - * failed before its walk began (`walkStartedAt`), and remove their dead - * letters from the queue. The walk re-read every row, so they are repaired - * or no longer apply. A dead letter that failed during the walk stays, and - * is still counted. Read from the queue's dead letters where syncs run - * through it; where they do not, the failures are cleared only when the - * newest of them came before the walk. Never throws. - */ - static async clearRepairedFailures( - this: Pick, - entry: KnowledgeSourceEntry, - walkStartedAt: string, - ): Promise { - const store = this.options.syncState; - if (!store) return; - const walkStart = Date.parse(walkStartedAt); - const view = this.recordSyncQueueView; - try { - for (let attempt = 0; attempt < 4; attempt++) { - const state = await store.read(entry.key); - if (!state) return; - let remaining: string[] | undefined; - if (view && typeof view.listFailed === 'function') { - const letters = await this.deadLettersOf(entry.key, view); - const repaired = letters.filter((l) => l.at < walkStart); - if (typeof view.purgeFailed === 'function') { - for (const letter of repaired) { - try { - await view.purgeFailed(letter.id); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] source '${entry.face}': the repaired dead letter '${letter.id}' could not be removed ` + - `from queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (${errorText(err)}); it stays listed there.`, - ); - } +/** Ask for a reconcile of one source, as a predicate write does ({@link requestReconcile}). */ +export function requestSourceReconcile( + this: Pick, + entry: KnowledgeSourceEntry, +): void { + if (this.buildsStopped || this.reconcileExclusion(entry) !== undefined) return; + this.armReconcile(entry.key, Date.now()); + this.options.logger?.info?.( + `[knowledge] source '${entry.face}' has its first failed sync: a reconcile of it is asked for, and starts once ` + + 'the quiet period passes.', + ); +} + +/** + * After a reconcile of `entry` that completed: clear the failures that + * failed before its walk began (`walkStartedAt`), and remove their dead + * letters from the queue. The walk re-read every row, so they are repaired + * or no longer apply. A dead letter that failed during the walk stays, and + * is still counted. Read from the queue's dead letters where syncs run + * through it; where they do not, the failures are cleared only when the + * newest of them came before the walk. Never throws. + */ +export async function clearRepairedFailures( + this: Pick, + entry: KnowledgeSourceEntry, + walkStartedAt: string, +): Promise { + const store = this.options.syncState; + if (!store) return; + const walkStart = Date.parse(walkStartedAt); + const view = this.recordSyncQueueView; + try { + for (let attempt = 0; attempt < 4; attempt++) { + const state = await store.read(entry.key); + if (!state) return; + let remaining: string[] | undefined; + if (view && typeof view.listFailed === 'function') { + const letters = await this.deadLettersOf(entry.key, view); + const repaired = letters.filter((l) => l.at < walkStart); + if (typeof view.purgeFailed === 'function') { + for (const letter of repaired) { + try { + await view.purgeFailed(letter.id); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}': the repaired dead letter '${letter.id}' could not be removed ` + + `from queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (${errorText(err)}); it stays listed there.`, + ); } } - remaining = letters.filter((l) => l.at >= walkStart).map((l) => new Date(l.at).toISOString()).sort(); - } else { - const last = state.failures.lastFailedAt === undefined ? NaN : Date.parse(state.failures.lastFailedAt); - if (state.failures.count === 0 || !(last < walkStart)) return; - remaining = []; - } - if (remaining.length === 0 && state.failures.count === 0) return; - const landed = await store.setFailures(entry.key, state.failureCountStored, remaining.length === 0 - ? { count: 0 } - : { - count: remaining.length, - firstFailedAt: remaining[0], - ...(state.failures.lastFailedAt === undefined ? {} : { lastFailedAt: state.failures.lastFailedAt }), - ...(state.failures.lastError === undefined ? {} : { lastError: state.failures.lastError }), - }); - if (landed) { - this.options.logger?.info?.( - `[knowledge] source '${entry.face}': the reconcile repaired the syncs that failed before it began; ` + - `${remaining.length} failed during it and stay counted.`, - ); - return; } - // A failure was counted meanwhile: read again. + remaining = letters.filter((l) => l.at >= walkStart).map((l) => new Date(l.at).toISOString()).sort(); + } else { + const last = state.failures.lastFailedAt === undefined ? NaN : Date.parse(state.failures.lastFailedAt); + if (state.failures.count === 0 || !(last < walkStart)) return; + remaining = []; } - } catch (err) { - this.syncStateWriteFailed(`the failures the reconcile of source '${entry.face}' repaired were not cleared`, err); + if (remaining.length === 0 && state.failures.count === 0) return; + const landed = await store.setFailures(entry.key, state.failureCountStored, remaining.length === 0 + ? { count: 0 } + : { + count: remaining.length, + firstFailedAt: remaining[0], + ...(state.failures.lastFailedAt === undefined ? {} : { lastFailedAt: state.failures.lastFailedAt }), + ...(state.failures.lastError === undefined ? {} : { lastError: state.failures.lastError }), + }); + if (landed) { + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': the reconcile repaired the syncs that failed before it began; ` + + `${remaining.length} failed during it and stay counted.`, + ); + return; + } + // A failure was counted meanwhile: read again. } + } catch (err) { + this.syncStateWriteFailed(`the failures the reconcile of source '${entry.face}' repaired were not cleared`, err); } +} - /** - * Every dead letter on the record-sync queue that names the source under - * `key`, with when it failed, once each. - * - * Filtered here, not in the queue: `IQueueService.listFailed` takes a queue - * name and a page and no predicate, so no query can name the source. The - * pages are read by offset while letters may arrive, so a letter can be read - * on two pages; it is kept once, by its id. - */ - static async deadLettersOf( - key: string, - view: KnowledgeRecordSyncQueueView, - ): Promise> { - const byId = new Map(); - const page = 500; - for (let offset = 0; offset < DEAD_LETTER_SCAN_MAX; offset += page) { - const letters = await view.listFailed!(KNOWLEDGE_RECORD_SYNC_QUEUE, { limit: page, offset }); - for (const letter of letters) { - const named = readRecordSyncMessage(letter.data)?.source ?? (letter.metadata as { source?: unknown } | undefined)?.source; - if (named !== key || byId.has(letter.id)) continue; - const at = Date.parse(String(letter.completedAt ?? letter.updatedAt ?? letter.createdAt)); - byId.set(letter.id, Number.isNaN(at) ? 0 : at); - } - if (letters.length < page) break; +/** + * Every dead letter on the record-sync queue that names the source under + * `key`, with when it failed, once each. + * + * Filtered here, not in the queue: `IQueueService.listFailed` takes a queue + * name and a page and no predicate, so no query can name the source. The + * pages are read by offset while letters may arrive, so a letter can be read + * on two pages; it is kept once, by its id. + */ +export async function deadLettersOf( + key: string, + view: KnowledgeRecordSyncQueueView, +): Promise> { + const byId = new Map(); + const page = 500; + for (let offset = 0; offset < DEAD_LETTER_SCAN_MAX; offset += page) { + const letters = await view.listFailed!(KNOWLEDGE_RECORD_SYNC_QUEUE, { limit: page, offset }); + for (const letter of letters) { + const named = readRecordSyncMessage(letter.data)?.source ?? (letter.metadata as { source?: unknown } | undefined)?.source; + if (named !== key || byId.has(letter.id)) continue; + const at = Date.parse(String(letter.completedAt ?? letter.updatedAt ?? letter.createdAt)); + byId.set(letter.id, Number.isNaN(at) ? 0 : at); } - return [...byId].map(([id, at]) => ({ id, at })); + if (letters.length < page) break; } + return [...byId].map(([id, at]) => ({ id, at })); +} - static recordSyncQueued(this: Pick): boolean { - return this.recordSyncPublisher !== undefined; - } +/** The body of {@link KnowledgeService.recordSyncQueued}; the member's docblock there is its contract. */ +export function recordSyncQueued(this: Pick): boolean { + return this.recordSyncPublisher !== undefined; +} - static enqueueRecordSync( - this: Pick, - object: string, - recordId: string | number, - reason: KnowledgeRecordSyncReason = 'event', - ): void { - if (!isRecordId(recordId) || this.held) return; - const sources = this.sourcesForObject(object); - if (sources.length === 0) return; - this.publishRecordSyncs(sources, object, String(recordId), reason); - } +/** The body of {@link KnowledgeService.enqueueRecordSync}; the member's docblock there is its contract. */ +export function enqueueRecordSync( + this: Pick, + object: string, + recordId: string | number, + reason: KnowledgeRecordSyncReason = 'event', +): void { + if (!isRecordId(recordId) || this.held) return; + const sources = this.sourcesForObject(object); + if (sources.length === 0) return; + this.publishRecordSyncs(sources, object, String(recordId), reason); +} - /** - * Publish one record-sync message per source in `sources`, once the unit - * open here commits ({@link enqueueRecordSync}). `onFailed` runs for each - * message that could not be published. - */ - static publishRecordSyncs( - this: Pick, - sources: KnowledgeSource[], - object: string, - recordId: string, - reason: KnowledgeRecordSyncReason, - onFailed?: () => void, - ): void { - const publish = this.recordSyncPublisher; - if (!publish) return; - const send = (): void => { - for (const source of sources) { - const message: KnowledgeRecordSyncMessage = { source: source.name, object, recordId, reason }; - void Promise.resolve() - .then(() => publish(message)) - .catch((err: unknown) => { - onFailed?.(); - const report = - `[knowledge] the sync of record '${recordId}' of source '${this.label(source)}' could not be queued ` + - `(${errorText(err)}): the write stands, and the record's document stays as it was until the record's ` + - 'next save, a search that finds it stale, or the reconcile.'; - if (this.options.logger?.error) this.options.logger.error(report); - else this.options.logger?.warn?.(report); - }); - } - }; - const engine = this.options.dataEngine as { runAfterOpenUnitsCommit?(body: () => void): void } | undefined; - if (typeof engine?.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(send); - else send(); - } +/** + * Publish one record-sync message per source in `sources`, once the unit + * open here commits ({@link enqueueRecordSync}). `onFailed` runs for each + * message that could not be published. + */ +export function publishRecordSyncs( + this: Pick, + sources: KnowledgeSource[], + object: string, + recordId: string, + reason: KnowledgeRecordSyncReason, + onFailed?: () => void, +): void { + const publish = this.recordSyncPublisher; + if (!publish) return; + const send = (): void => { + for (const source of sources) { + const message: KnowledgeRecordSyncMessage = { source: source.name, object, recordId, reason }; + void Promise.resolve() + .then(() => publish(message)) + .catch((err: unknown) => { + onFailed?.(); + const report = + `[knowledge] the sync of record '${recordId}' of source '${this.label(source)}' could not be queued ` + + `(${errorText(err)}): the write stands, and the record's document stays as it was until the record's ` + + 'next save, a search that finds it stale, or the reconcile.'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + }); + } + }; + const engine = this.options.dataEngine as { runAfterOpenUnitsCommit?(body: () => void): void } | undefined; + if (typeof engine?.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(send); + else send(); +} - static async processRecordSync( - this: Pick, - data: unknown, - publishedAt?: number, - ): Promise { - const resolved = this.resolveRecordSync(data, publishedAt); - if ('outcome' in resolved) return resolved.outcome; - const { source, message, engine } = resolved; - // The source's adapter is resolved now ({@link adapterFor}): the one it - // names, else the deployment's store, else the only one registered. Where - // none can be resolved it throws its coded refusal — the named adapter is - // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or - // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so - // the message is retried: a store that registers late is met by a later - // attempt, and one that never does leaves a dead letter naming the source - // and the record. - const adapter = this.adapterFor(source); - await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => - this.syncRow(source, adapter, message.object, message.recordId, engine), - ); - return 'synced'; - } +/** The body of {@link KnowledgeService.processRecordSync}; the member's docblock there is its contract. */ +export async function processRecordSync( + this: Pick, + data: unknown, + publishedAt?: number, +): Promise { + const resolved = this.resolveRecordSync(data, publishedAt); + if ('outcome' in resolved) return resolved.outcome; + const { source, message, engine } = resolved; + // The source's adapter is resolved now ({@link adapterFor}): the one it + // names, else the deployment's store, else the only one registered. Where + // none can be resolved it throws its coded refusal — the named adapter is + // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or + // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so + // the message is retried: a store that registers late is met by a later + // attempt, and one that never does leaves a dead letter naming the source + // and the record. + const adapter = this.adapterFor(source); + await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => + this.syncRow(source, adapter, message.object, message.recordId, engine), + ); + return 'synced'; +} - /** - * What every record-sync message is checked for before its row is read, - * on both of the worker's paths ({@link processRecordSync}, - * {@link processRecordSyncBatch}): an outcome that completes it without a - * sync — not a record-sync message, the service held, its source gone, its object no longer - * synced on record change, no data engine to re-read the row, or covered - * by a complete build that purged and began after it was published - * ({@link coveredByBuild}) — or the source, - * the message and the engine to sync it with. - */ - static resolveRecordSync( - this: Pick, - data: unknown, - publishedAt: number | undefined, - ): | { outcome: KnowledgeRecordSyncOutcome } +/** + * What every record-sync message is checked for before its row is read, + * on both of the worker's paths ({@link processRecordSync}, + * {@link processRecordSyncBatch}): an outcome that completes it without a + * sync — not a record-sync message, the service held, its source gone, its object no longer + * synced on record change, no data engine to re-read the row, or covered + * by a complete build that purged and began after it was published + * ({@link coveredByBuild}) — or the source, + * the message and the engine to sync it with. + */ +export function resolveRecordSync( + this: Pick, + data: unknown, + publishedAt: number | undefined, +): | { outcome: KnowledgeRecordSyncOutcome } | { source: KnowledgeSource; message: KnowledgeRecordSyncMessage; engine: IDataEngine } { - const message = readRecordSyncMessage(data); - if (!message) { - this.options.logger?.warn?.( - `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, - ); - return { outcome: 'malformed' }; - } - // Held (ADR-0161 K8, ruling 7248214179): completed without a sync, and no - // store is called, on the per-message and the batch path alike. - if (this.held) return { outcome: 'not-synced' }; - const source = this.handed(message.source); - if (!source) { - this.options.logger?.debug?.( - `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, - ); - return { outcome: 'source-gone' }; - } - if (objectSourcesFor([source], message.object).length === 0) return { outcome: 'not-synced' }; - const engine = this.options.dataEngine; - if (!engine) { - this.options.logger?.warn?.( - `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + - 'bound to re-read the row.', - ); - return { outcome: 'not-synced' }; - } - if (this.coveredByBuild(source.name, publishedAt)) return { outcome: 'covered' }; - return { source, message, engine }; + const message = readRecordSyncMessage(data); + if (!message) { + this.options.logger?.warn?.( + `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, + ); + return { outcome: 'malformed' }; } - - /** - * [#38413] Whether a complete build of the source under `key` already did - * what a message published at `publishedAt` asks for, so the message can - * complete without a read. All of these must hold: - * - * - the source's last build on this node finished `done` and its PURGE RAN - * (`result.purged` is a number). The walk writes the document of every - * row it reads and the purge deletes the document of every row it did - * not, so a message for a deleted row, or for a row that left `where`, is - * covered only by a build that purged. A build that ends `done` with - * `purged: null` (an adapter without `listDocuments`, or a listing that - * failed and the walk went on) deleted nothing, and covers nothing; - * - the reconcile walks the source ({@link reconcileExclusion}): a source - * whose index an external indexer owns, or whose store lists nothing, is - * never covered; - * - the build began at least {@link RECORD_SYNC_COVER_MARGIN_MS} after - * `publishedAt`. A message is published once its write committed, and - * the walk reads every row after it starts. - * - * A build running now, or one that did not finish, covers nothing. - */ - static coveredByBuild( - this: Pick, - key: string, - publishedAt: number | undefined, - ): boolean { - if (publishedAt === undefined || !Number.isFinite(publishedAt)) return false; - const build = this.builds.get(key); - if (build?.status !== 'done' || typeof build.result?.purged !== 'number' || build.result.ok === false) return false; - const entry = this.registry.byIndexKey(key); - if (!entry || this.reconcileExclusion(entry) !== undefined) return false; - const startedAt = Date.parse(build.startedAt); - return Number.isFinite(startedAt) && publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS; + // Held (ADR-0161 K8, ruling 7248214179): completed without a sync, and no + // store is called, on the per-message and the batch path alike. + if (this.held) return { outcome: 'not-synced' }; + const source = this.handed(message.source); + if (!source) { + this.options.logger?.debug?.( + `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, + ); + return { outcome: 'source-gone' }; } - - static async processRecordSyncBatch( - this: Pick, - batch: readonly KnowledgeRecordSyncBatchItem[], - ): Promise { - const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); - const groups = new Map(); - batch.forEach((item, index) => { - const resolved = this.resolveRecordSync(item?.data, item?.publishedAt); - if ('outcome' in resolved) { - results[index] = { ok: true, outcome: resolved.outcome }; - return; - } - const key = JSON.stringify([resolved.source.name, resolved.message.object]); - let group = groups.get(key); - if (!group) { - group = { source: resolved.source, object: resolved.message.object, engine: resolved.engine, items: [] }; - groups.set(key, group); - } - group.items.push({ index, recordId: resolved.message.recordId, publishedAt: item.publishedAt }); - }); - for (const group of groups.values()) { - await this.considerBacklogReconcile(group, batch.length); - } - for (const group of groups.values()) { - try { - await this.syncRecordGroup(group, results); - } catch (err) { - for (const item of group.items) results[item.index] ??= { ok: false, error: err }; - } - } - return results; + if (objectSourcesFor([source], message.object).length === 0) return { outcome: 'not-synced' }; + const engine = this.options.dataEngine; + if (!engine) { + this.options.logger?.warn?.( + `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + + 'bound to re-read the row.', + ); + return { outcome: 'not-synced' }; } + if (this.coveredByBuild(source.name, publishedAt)) return { outcome: 'covered' }; + return { source, message, engine }; +} - /** One group of {@link processRecordSyncBatch}: writes each of its items' result. */ - static async syncRecordGroup( - this: Pick< - KnowledgeServiceHost, - 'adapterFor' | 'coveredByBuild' | 'label' | 'options' | 'recordSyncTails' | 'syncRow' | 'syncRows' - >, - group: RecordSyncGroup, - results: KnowledgeRecordSyncBatchResult[], - ): Promise { - const { source, object, engine } = group; - let adapter: IKnowledgeAdapter; - try { - adapter = this.adapterFor(source); - } catch (err) { - for (const item of group.items) results[item.index] = { ok: false, error: err }; +/** + * [#38413] Whether a complete build of the source under `key` already did + * what a message published at `publishedAt` asks for, so the message can + * complete without a read. All of these must hold: + * + * - the source's last build on this node finished `done` and its PURGE RAN + * (`result.purged` is a number). The walk writes the document of every + * row it reads and the purge deletes the document of every row it did + * not, so a message for a deleted row, or for a row that left `where`, is + * covered only by a build that purged. A build that ends `done` with + * `purged: null` (an adapter without `listDocuments`, or a listing that + * failed and the walk went on) deleted nothing, and covers nothing; + * - the reconcile walks the source ({@link reconcileExclusion}): a source + * whose index an external indexer owns, or whose store lists nothing, is + * never covered; + * - the build began at least {@link RECORD_SYNC_COVER_MARGIN_MS} after + * `publishedAt`. A message is published once its write committed, and + * the walk reads every row after it starts. + * + * A build running now, or one that did not finish, covers nothing. + */ +export function coveredByBuild( + this: Pick, + key: string, + publishedAt: number | undefined, +): boolean { + if (publishedAt === undefined || !Number.isFinite(publishedAt)) return false; + const build = this.builds.get(key); + if (build?.status !== 'done' || typeof build.result?.purged !== 'number' || build.result.ok === false) return false; + const entry = this.registry.byIndexKey(key); + if (!entry || this.reconcileExclusion(entry) !== undefined) return false; + const startedAt = Date.parse(build.startedAt); + return Number.isFinite(startedAt) && publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS; +} + +/** The body of {@link KnowledgeService.processRecordSyncBatch}; the member's docblock there is its contract. */ +export async function processRecordSyncBatch( + this: Pick, + batch: readonly KnowledgeRecordSyncBatchItem[], +): Promise { + const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); + const groups = new Map(); + batch.forEach((item, index) => { + const resolved = this.resolveRecordSync(item?.data, item?.publishedAt); + if ('outcome' in resolved) { + results[index] = { ok: true, outcome: resolved.outcome }; return; } - const open: RecordSyncGroup['items'] = []; - for (const item of group.items) { - if (this.coveredByBuild(source.name, item.publishedAt)) results[item.index] = { ok: true, outcome: 'covered' }; - else open.push(item); - } - if (open.length === 0) return; - const recordIds = [...new Set(open.map((item) => item.recordId))]; - const failures = new Map(); - await chainAfterAll(this.recordSyncTails, recordIds.map((id) => documentIdFor(source.name, id)), async () => { - if (recordIds.length > 1) { - try { - await this.syncRows(source, adapter, object, recordIds, engine); - return; - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] a batch of ${recordIds.length} record syncs of source '${this.label(source)}' failed (${errorText(err)}); ` + - 'syncing them one by one, so a record that cannot be synced fails alone.', - ); - } - } - for (const recordId of recordIds) { - try { - await this.syncRow(source, adapter, object, recordId, engine); - } catch (err) { - failures.set(recordId, err); - } - } - }); - for (const item of open) { - results[item.index] = failures.has(item.recordId) - ? { ok: false, error: failures.get(item.recordId) } - : { ok: true, outcome: 'synced' }; + const key = JSON.stringify([resolved.source.name, resolved.message.object]); + let group = groups.get(key); + if (!group) { + group = { source: resolved.source, object: resolved.message.object, engine: resolved.engine, items: [] }; + groups.set(key, group); } + group.items.push({ index, recordId: resolved.message.recordId, publishedAt: item.publishedAt }); + }); + for (const group of groups.values()) { + await this.considerBacklogReconcile(group, batch.length); } - - /** - * [#38413] The record-sync queue's waiting count (`getQueueSize`), read at - * most once per {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}. `undefined` - * when the queue cannot count or the count failed. - */ - static async recordSyncWaiting( - this: Pick, - ): Promise { - const now = Date.now(); - const last = this.recordSyncBacklog; - if (last && now - last.at < RECORD_SYNC_BACKLOG_READ_INTERVAL_MS) return last.waiting; - let waiting: number | undefined; + for (const group of groups.values()) { try { - waiting = await this.pendingRecordSyncs(); - } catch { - waiting = undefined; + await this.syncRecordGroup(group, results); + } catch (err) { + for (const item of group.items) results[item.index] ??= { ok: false, error: err }; } - this.recordSyncBacklog = { at: now, waiting }; - return waiting; } + return results; +} - /** - * [#38413] The rows of the source under `key` (its `where`, counted as the - * system identity), kept for {@link RECORD_SYNC_SOURCE_ROWS_TTL_MS}. - * `undefined` when the count failed. - */ - static async sourceRowCount( - this: Pick, - key: string, - objSource: ObjectKnowledgeSource, - engine: IDataEngine, - ): Promise { - const now = Date.now(); - const last = this.sourceRows.get(key); - if (last && now - last.at < RECORD_SYNC_SOURCE_ROWS_TTL_MS) return last.rows; - let rows: number | undefined; - try { - const counted = await engine.count(objSource.object, { where: objSource.where }, { context: systemContext() }); - rows = typeof counted === 'number' && Number.isFinite(counted) ? counted : undefined; - } catch { - rows = undefined; - } - this.sourceRows.set(key, { at: now, rows }); - return rows; +/** One group of {@link processRecordSyncBatch}: writes each of its items' result. */ +export async function syncRecordGroup( + this: Pick< + KnowledgeRecordSyncHost, + 'adapterFor' | 'coveredByBuild' | 'label' | 'options' | 'recordSyncTails' | 'syncRow' | 'syncRows' + >, + group: RecordSyncGroup, + results: KnowledgeRecordSyncBatchResult[], +): Promise { + const { source, object, engine } = group; + let adapter: IKnowledgeAdapter; + try { + adapter = this.adapterFor(source); + } catch (err) { + for (const item of group.items) results[item.index] = { ok: false, error: err }; + return; } - - /** - * [#38413] Ask 2 of the batch path: schedule one reconcile of the group's - * source when its backlog is large enough that a walk beside the drain - * pays. The source's backlog is estimated as the queue's waiting count - * times the group's share of the batch in hand (the batch is the head of - * the queue). A reconcile is scheduled when that estimate reaches both - * {@link RECORD_SYNC_BACKLOG_THRESHOLD} and - * {@link RECORD_SYNC_BACKLOG_ROW_SHARE} of the source's rows, no backlog - * reconcile of the source is running, and the source is past its wait: - * {@link RECORD_SYNC_BACKLOG_REWALK_MS} after one that ended `done`, or a - * backoff from {@link RECORD_SYNC_BACKLOG_RETRY_MS} doubling to - * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} after one that did not. - * - * It is scheduled, never awaited: the batch, and every other source's - * syncs, go on while it walks, and the messages its build covers - * ({@link coveredByBuild}) complete without a read once it ends. A source - * the reconcile does not walk ({@link reconcileExclusion}) is never - * scheduled. Never rejects. - */ - static async considerBacklogReconcile( - this: Pick< - KnowledgeServiceHost, - 'backlogReconciles' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'options' | - 'reconcileExclusion' | 'recordSyncWaiting' | 'registry' | 'sourceRowCount' - >, - group: RecordSyncGroup, - batchLength: number, - ): Promise { - const key = group.source.name; - const objSource = group.source.source; - if (objSource.kind !== 'object' || batchLength <= 0) return; - const entry = this.registry.byIndexKey(key); - if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) return; - const state = this.backlogReconciles.get(key); - if (state && (state.running || Date.now() < state.notBefore)) return; - const waiting = await this.recordSyncWaiting(); - if (waiting === undefined) return; - const estimate = Math.round((waiting * group.items.length) / batchLength); - if (estimate < RECORD_SYNC_BACKLOG_THRESHOLD) return; - const rows = await this.sourceRowCount(key, objSource, group.engine); - if (rows === undefined || estimate < rows * RECORD_SYNC_BACKLOG_ROW_SHARE) return; - - const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; - this.backlogReconciles.set(key, next); - this.options.logger?.info?.( - `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + - 'reconcile of the source is scheduled; record syncs go on meanwhile, and those it covers complete without a ' + - 'read once it ends.', - ); - void this.enqueueReconcile(() => { - const current = this.registry.byIndexKey(key); - return current === undefined ? [] : [current]; - }) - .then(() => undefined, () => undefined) - .then(() => { - next.running = false; - const build = this.builds.get(key); - if (build?.status === 'done' && typeof build.result?.purged === 'number') { - next.failures = 0; - next.notBefore = Date.now() + RECORD_SYNC_BACKLOG_REWALK_MS; - return; - } - next.failures++; - const wait = Math.min(RECORD_SYNC_BACKLOG_RETRY_MS * 2 ** (next.failures - 1), RECORD_SYNC_BACKLOG_RETRY_MAX_MS); - next.notBefore = Date.now() + wait; + const open: RecordSyncGroup['items'] = []; + for (const item of group.items) { + if (this.coveredByBuild(source.name, item.publishedAt)) results[item.index] = { ok: true, outcome: 'covered' }; + else open.push(item); + } + if (open.length === 0) return; + const recordIds = [...new Set(open.map((item) => item.recordId))]; + const failures = new Map(); + await chainAfterAll(this.recordSyncTails, recordIds.map((id) => documentIdFor(source.name, id)), async () => { + if (recordIds.length > 1) { + try { + await this.syncRows(source, adapter, object, recordIds, engine); + return; + } catch (err) { this.options.logger?.warn?.( - `[knowledge] source '${entry.face}': the reconcile scheduled for its record-sync backlog ended ` + - `${build?.status ?? 'without a build'}${build?.status === 'done' ? ' with no purge' : ''}, so its record syncs are ` + - `drained one by one; another is not scheduled for ${Math.round(wait / 60_000)} min.`, + `[knowledge] a batch of ${recordIds.length} record syncs of source '${this.label(source)}' failed (${errorText(err)}); ` + + 'syncing them one by one, so a record that cannot be synced fails alone.', ); - }); - } - - /** - * [#38413] The batch twin of {@link syncRow}: re-read the rows `recordIds` - * name under the source's `where` as the system identity, in one read - * ({@link rereadRows}), write the documents of the rows that came back in - * one `upsert` and delete those of the ids no row matched in one `delete`, - * under one index plan. A document the split cannot index is removed and - * reported, as {@link writeSynced} does. Throws what the re-read, a - * document build, the split, the embedding call or the store throws. - */ - static async syncRows( - this: Pick< - KnowledgeServiceHost, - 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | 'reportUnindexable' | 'schemaFor' - >, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - object: string, - recordIds: string[], - engine: IDataEngine, - ): Promise { - const objSource = source.source; - const rows = await rereadRows(engine, objSource, recordIds); - const byId = new Map>(); - for (const row of rows) if (isRecordId(row.id)) byId.set(String(row.id), row); - const schema = this.schemaFor(object); - const posture = await this.readTenancyPosture(); - const docs: KnowledgeDocument[] = []; - const gone: string[] = []; - const recordOf = new Map(); + } + } for (const recordId of recordIds) { - const row = byId.get(recordId); - if (row) { - const doc = recordToDocument(source, objSource, row, schema, posture); - recordOf.set(doc.id, recordId); - docs.push(doc); - } else { - gone.push(documentIdFor(source.name, recordId)); + try { + await this.syncRow(source, adapter, object, recordId, engine); + } catch (err) { + failures.set(recordId, err); } } - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('event-sync'); - const prepared = this.prepareDocuments(plan, docs); - if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); - const removed = [...gone, ...prepared.failed.map((f) => f.documentId)]; - if (removed.length > 0) await adapter.delete(removed, ctx); - for (const f of prepared.failed) this.reportUnindexable(source, adapter, f, recordOf.get(f.documentId) ?? f.documentId); + }); + for (const item of open) { + results[item.index] = failures.has(item.recordId) + ? { ok: false, error: failures.get(item.recordId) } + : { ok: true, outcome: 'synced' }; } +} - static async handleRecordUpsert( - this: Pick, - object: string, - record: Record, - ): Promise { - if (this.held) return; - const recordId = record.id; - for (const source of this.sourcesForObject(object)) { - const sync = (): Promise => this.syncRecord(source, object, recordId, record); - await (isRecordId(recordId) - ? this.serializeRecordSync(documentIdFor(source.name, String(recordId)), sync) - : sync()); - } +/** + * [#38413] The record-sync queue's waiting count (`getQueueSize`), read at + * most once per {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}. `undefined` + * when the queue cannot count or the count failed. + */ +export async function recordSyncWaiting( + this: Pick, +): Promise { + const now = Date.now(); + const last = this.recordSyncBacklog; + if (last && now - last.at < RECORD_SYNC_BACKLOG_READ_INTERVAL_MS) return last.waiting; + let waiting: number | undefined; + try { + waiting = await this.pendingRecordSyncs(); + } catch { + waiting = undefined; } + this.recordSyncBacklog = { at: now, waiting }; + return waiting; +} - /** - * One source's inline sync of one row — see {@link handleRecordUpsert}. - * Never throws: a failure is one `warn` line. - */ - static async syncRecord( - this: Pick< - KnowledgeServiceHost, - 'adapterFor' | 'label' | 'options' | 'readTenancyPosture' | 'reportWhereUnenforceable' | 'schemaFor' | - 'syncRow' | 'writeSynced' - >, - source: KnowledgeSource, - object: string, - recordId: unknown, - payload: Record, - ): Promise { - const objSource = source.source; - try { - const adapter = this.adapterFor(source); - const engine = this.options.dataEngine; - if (!engine) { - if (objSource.where !== undefined) { - this.reportWhereUnenforceable(source); - return; - } - const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); - await this.writeSynced(source, adapter, doc, recordId); - return; - } - if (!isRecordId(recordId)) { - this.options.logger?.warn?.( - `[knowledge] event-sync skipped for source '${this.label(source)}': the event's record names no id, ` + - 'so the row cannot be re-read against the source.', - ); +/** + * [#38413] The rows of the source under `key` (its `where`, counted as the + * system identity), kept for {@link RECORD_SYNC_SOURCE_ROWS_TTL_MS}. + * `undefined` when the count failed. + */ +export async function sourceRowCount( + this: Pick, + key: string, + objSource: ObjectKnowledgeSource, + engine: IDataEngine, +): Promise { + const now = Date.now(); + const last = this.sourceRows.get(key); + if (last && now - last.at < RECORD_SYNC_SOURCE_ROWS_TTL_MS) return last.rows; + let rows: number | undefined; + try { + const counted = await engine.count(objSource.object, { where: objSource.where }, { context: systemContext() }); + rows = typeof counted === 'number' && Number.isFinite(counted) ? counted : undefined; + } catch { + rows = undefined; + } + this.sourceRows.set(key, { at: now, rows }); + return rows; +} + +/** + * [#38413] Ask 2 of the batch path: schedule one reconcile of the group's + * source when its backlog is large enough that a walk beside the drain + * pays. The source's backlog is estimated as the queue's waiting count + * times the group's share of the batch in hand (the batch is the head of + * the queue). A reconcile is scheduled when that estimate reaches both + * {@link RECORD_SYNC_BACKLOG_THRESHOLD} and + * {@link RECORD_SYNC_BACKLOG_ROW_SHARE} of the source's rows, no backlog + * reconcile of the source is running, and the source is past its wait: + * {@link RECORD_SYNC_BACKLOG_REWALK_MS} after one that ended `done`, or a + * backoff from {@link RECORD_SYNC_BACKLOG_RETRY_MS} doubling to + * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} after one that did not. + * + * It is scheduled, never awaited: the batch, and every other source's + * syncs, go on while it walks, and the messages its build covers + * ({@link coveredByBuild}) complete without a read once it ends. A source + * the reconcile does not walk ({@link reconcileExclusion}) is never + * scheduled. Never rejects. + */ +export async function considerBacklogReconcile( + this: Pick< + KnowledgeRecordSyncHost, + 'backlogReconciles' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'options' | + 'reconcileExclusion' | 'recordSyncWaiting' | 'registry' | 'sourceRowCount' + >, + group: RecordSyncGroup, + batchLength: number, +): Promise { + const key = group.source.name; + const objSource = group.source.source; + if (objSource.kind !== 'object' || batchLength <= 0) return; + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) return; + const state = this.backlogReconciles.get(key); + if (state && (state.running || Date.now() < state.notBefore)) return; + const waiting = await this.recordSyncWaiting(); + if (waiting === undefined) return; + const estimate = Math.round((waiting * group.items.length) / batchLength); + if (estimate < RECORD_SYNC_BACKLOG_THRESHOLD) return; + const rows = await this.sourceRowCount(key, objSource, group.engine); + if (rows === undefined || estimate < rows * RECORD_SYNC_BACKLOG_ROW_SHARE) return; + + const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; + this.backlogReconciles.set(key, next); + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + + 'reconcile of the source is scheduled; record syncs go on meanwhile, and those it covers complete without a ' + + 'read once it ends.', + ); + void this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }) + .then(() => undefined, () => undefined) + .then(() => { + next.running = false; + const build = this.builds.get(key); + if (build?.status === 'done' && typeof build.result?.purged === 'number') { + next.failures = 0; + next.notBefore = Date.now() + RECORD_SYNC_BACKLOG_REWALK_MS; return; } - await this.syncRow(source, adapter, object, recordId, engine); - } catch (err) { + next.failures++; + const wait = Math.min(RECORD_SYNC_BACKLOG_RETRY_MS * 2 ** (next.failures - 1), RECORD_SYNC_BACKLOG_RETRY_MAX_MS); + next.notBefore = Date.now() + wait; this.options.logger?.warn?.( - `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, + `[knowledge] source '${entry.face}': the reconcile scheduled for its record-sync backlog ended ` + + `${build?.status ?? 'without a build'}${build?.status === 'done' ? ' with no purge' : ''}, so its record syncs are ` + + `drained one by one; another is not scheduled for ${Math.round(wait / 60_000)} min.`, ); - } - } + }); +} - /** - * THE sync of one row's document, both paths' ({@link syncRecord} inline, - * {@link processRecordSync} from the queue): re-read the row under the - * source's `where` as the system identity ({@link rereadRow}) and write its - * document, or delete the document when no row matches. Throws what the - * re-read, the split, the embedding call or the store throws. - */ - static async syncRow( - this: Pick, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - object: string, - recordId: string | number, - engine: IDataEngine, - ): Promise { - const objSource = source.source; - const row = await rereadRow(engine, objSource, recordId); +/** + * [#38413] The batch twin of {@link syncRow}: re-read the rows `recordIds` + * name under the source's `where` as the system identity, in one read + * ({@link rereadRows}), write the documents of the rows that came back in + * one `upsert` and delete those of the ids no row matched in one `delete`, + * under one index plan. A document the split cannot index is removed and + * reported, as {@link writeSynced} does. Throws what the re-read, a + * document build, the split, the embedding call or the store throws. + */ +export async function syncRows( + this: Pick< + KnowledgeRecordSyncHost, + 'planIndex' | 'prepareDocuments' | 'readTenancyPosture' | 'reportUnindexable' | 'schemaFor' + >, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordIds: string[], + engine: IDataEngine, +): Promise { + const objSource = source.source; + const rows = await rereadRows(engine, objSource, recordIds); + const byId = new Map>(); + for (const row of rows) if (isRecordId(row.id)) byId.set(String(row.id), row); + const schema = this.schemaFor(object); + const posture = await this.readTenancyPosture(); + const docs: KnowledgeDocument[] = []; + const gone: string[] = []; + const recordOf = new Map(); + for (const recordId of recordIds) { + const row = byId.get(recordId); if (row) { - const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); - await this.writeSynced(source, adapter, doc, recordId); + const doc = recordToDocument(source, objSource, row, schema, posture); + recordOf.set(doc.id, recordId); + docs.push(doc); } else { - const plan = await this.planIndex(source, adapter); - await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); - } - } - - /** - * The event sync's write of one document: split as every path splits - * ({@link prepareDocuments}) and upserted. A document the split cannot - * index (a `whole` document over the embedder's budget) is removed from the - * index and reported at `error`: the write that triggered the sync - * succeeded and search keeps answering, so nothing else shows that this - * record is no longer findable. - */ - static async writeSynced( - this: Pick, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - doc: KnowledgeDocument, - recordId: unknown, - ): Promise { - const plan = await this.planIndex(source, adapter); - const ctx = plan.context('event-sync'); - const prepared = this.prepareDocuments(plan, [doc]); - if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); - for (const f of prepared.failed) { - await adapter.delete([f.documentId], ctx); - this.reportUnindexable(source, adapter, f, recordId); + gone.push(documentIdFor(source.name, recordId)); } } + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, docs); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); + const removed = [...gone, ...prepared.failed.map((f) => f.documentId)]; + if (removed.length > 0) await adapter.delete(removed, ctx); + for (const f of prepared.failed) this.reportUnindexable(source, adapter, f, recordOf.get(f.documentId) ?? f.documentId); +} - /** Say, at `error`, that a record's document left the index because its split cannot index it ({@link writeSynced}, {@link syncRows}). */ - static reportUnindexable( - this: Pick, - source: KnowledgeSource, - adapter: IKnowledgeAdapter, - f: { estimate: number; budget: number }, - recordId: unknown, - ): void { - const limit = adapter.embedding?.maxInputTokens; - const message = - `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + - `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + - `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + - `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; - // `warn` is the guaranteed channel when a host injects no `error`. - const logger = this.options.logger; - if (logger?.error) logger.error(message); - else logger?.warn?.(message); +/** The body of {@link KnowledgeService.handleRecordUpsert}; the member's docblock there is its contract. */ +export async function handleRecordUpsert( + this: Pick, + object: string, + record: Record, +): Promise { + if (this.held) return; + const recordId = record.id; + for (const source of this.sourcesForObject(object)) { + const sync = (): Promise => this.syncRecord(source, object, recordId, record); + await (isRecordId(recordId) + ? this.serializeRecordSync(documentIdFor(source.name, String(recordId)), sync) + : sync()); } +} - /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ - static reportWhereUnenforceable( - this: Pick, - source: KnowledgeSource, - ): void { - if (this.whereUnenforceableReported.has(source.name)) return; - this.whereUnenforceableReported.add(source.name); +/** + * One source's inline sync of one row — see {@link handleRecordUpsert}. + * Never throws: a failure is one `warn` line. + */ +export async function syncRecord( + this: Pick< + KnowledgeRecordSyncHost, + 'adapterFor' | 'label' | 'options' | 'readTenancyPosture' | 'reportWhereUnenforceable' | 'schemaFor' | 'syncRow' | + 'writeSynced' + >, + source: KnowledgeSource, + object: string, + recordId: unknown, + payload: Record, +): Promise { + const objSource = source.source; + try { + const adapter = this.adapterFor(source); + const engine = this.options.dataEngine; + if (!engine) { + if (objSource.where !== undefined) { + this.reportWhereUnenforceable(source); + return; + } + const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); + await this.writeSynced(source, adapter, doc, recordId); + return; + } + if (!isRecordId(recordId)) { + this.options.logger?.warn?.( + `[knowledge] event-sync skipped for source '${this.label(source)}': the event's record names no id, ` + + 'so the row cannot be re-read against the source.', + ); + return; + } + await this.syncRow(source, adapter, object, recordId, engine); + } catch (err) { this.options.logger?.warn?.( - `[knowledge] source '${this.label(source)}' declares a where filter and no data engine is bound: record events ` + - 'for it are not synced, because the filter cannot be judged without re-reading the row. ' + - 'Bind a data engine (the objectql service) to sync it.', + `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, ); } +} - /** - * Run `task` after every earlier sync of the same document (`key`) has - * finished — an in-process promise chain per document, dropped once idle. - * Only the ORDER of syncs is held; each still re-reads the row itself, so a - * later sync never acts on what an earlier one read. A task that rejects - * does not break the chain (the sync paths never throw; this is a backstop). - */ - static serializeRecordSync( - this: Pick, - key: string, - task: () => Promise, - ): Promise { - return chainAfter(this.recordSyncTails, key, task).catch(() => undefined); +/** + * THE sync of one row's document, both paths' ({@link syncRecord} inline, + * {@link processRecordSync} from the queue): re-read the row under the + * source's `where` as the system identity ({@link rereadRow}) and write its + * document, or delete the document when no row matches. Throws what the + * re-read, the split, the embedding call or the store throws. + */ +export async function syncRow( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordId: string | number, + engine: IDataEngine, +): Promise { + const objSource = source.source; + const row = await rereadRow(engine, objSource, recordId); + if (row) { + const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); + await this.writeSynced(source, adapter, doc, recordId); + } else { + const plan = await this.planIndex(source, adapter); + await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); } +} - /** - * The registered object definition, when the bound engine exposes one - * (`getSchema` is not on the `IDataEngine` contract; the ObjectQL engine - * carries it). `undefined` — nothing to withhold by — otherwise. - */ - static schemaFor(this: Pick, object: string): unknown { - try { - return (this.options.dataEngine as { getSchema?: (name: string) => unknown } | undefined) - ?.getSchema?.(object); - } catch { - return undefined; - } +/** + * The event sync's write of one document: split as every path splits + * ({@link prepareDocuments}) and upserted. A document the split cannot + * index (a `whole` document over the embedder's budget) is removed from the + * index and reported at `error`: the write that triggered the sync + * succeeded and search keeps answering, so nothing else shows that this + * record is no longer findable. + */ +export async function writeSynced( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + doc: KnowledgeDocument, + recordId: unknown, +): Promise { + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, [doc]); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); + for (const f of prepared.failed) { + await adapter.delete([f.documentId], ctx); + this.reportUnindexable(source, adapter, f, recordId); } +} - static async handleRecordDelete( - this: Pick< - KnowledgeServiceHost, - 'adapterFor' | 'held' | 'label' | 'options' | 'planIndex' | 'serializeRecordSync' | 'sourcesForObject' - >, - object: string, - recordId: string, - ): Promise { - if (this.held) return; - const targets = this.sourcesForObject(object); - for (const source of targets) { - const docId = documentIdFor(source.name, recordId); - await this.serializeRecordSync(docId, async () => { - try { - const adapter = this.adapterFor(source); - await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] event-sync delete failed for source '${this.label(source)}': ${(err as Error).message}`, - ); - } - }); - } +/** Say, at `error`, that a record's document left the index because its split cannot index it ({@link writeSynced}, {@link syncRows}). */ +export function reportUnindexable( + this: Pick, + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + f: { estimate: number; budget: number }, + recordId: unknown, +): void { + const limit = adapter.embedding?.maxInputTokens; + const message = + `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + + `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + + `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + + `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; + // `warn` is the guaranteed channel when a host injects no `error`. + const logger = this.options.logger; + if (logger?.error) logger.error(message); + else logger?.warn?.(message); +} + +/** The no-engine path cannot judge `where`: say so once per source, never once per event. */ +export function reportWhereUnenforceable( + this: Pick, + source: KnowledgeSource, +): void { + if (this.whereUnenforceableReported.has(source.name)) return; + this.whereUnenforceableReported.add(source.name); + this.options.logger?.warn?.( + `[knowledge] source '${this.label(source)}' declares a where filter and no data engine is bound: record events ` + + 'for it are not synced, because the filter cannot be judged without re-reading the row. ' + + 'Bind a data engine (the objectql service) to sync it.', + ); +} + +/** + * Run `task` after every earlier sync of the same document (`key`) has + * finished — an in-process promise chain per document, dropped once idle. + * Only the ORDER of syncs is held; each still re-reads the row itself, so a + * later sync never acts on what an earlier one read. A task that rejects + * does not break the chain (the sync paths never throw; this is a backstop). + */ +export function serializeRecordSync( + this: Pick, + key: string, + task: () => Promise, +): Promise { + return chainAfter(this.recordSyncTails, key, task).catch(() => undefined); +} + +/** + * The registered object definition, when the bound engine exposes one + * (`getSchema` is not on the `IDataEngine` contract; the ObjectQL engine + * carries it). `undefined` — nothing to withhold by — otherwise. + */ +export function schemaFor(this: Pick, object: string): unknown { + try { + return (this.options.dataEngine as { getSchema?: (name: string) => unknown } | undefined) + ?.getSchema?.(object); + } catch { + return undefined; + } +} + +/** The body of {@link KnowledgeService.handleRecordDelete}; the member's docblock there is its contract. */ +export async function handleRecordDelete( + this: Pick< + KnowledgeRecordSyncHost, + 'adapterFor' | 'held' | 'label' | 'options' | 'planIndex' | 'serializeRecordSync' | 'sourcesForObject' + >, + object: string, + recordId: string, +): Promise { + if (this.held) return; + const targets = this.sourcesForObject(object); + for (const source of targets) { + const docId = documentIdFor(source.name, recordId); + await this.serializeRecordSync(docId, async () => { + try { + const adapter = this.adapterFor(source); + await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] event-sync delete failed for source '${this.label(source)}': ${(err as Error).message}`, + ); + } + }); } } diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index 116f843d920..e2d2e8e440d 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -8,21 +8,23 @@ * `sourcesNarrowedToVisible`, `readVisibleIds`, `checkScope`, * `resolveSearchTargets`, moved out of `knowledge-service.ts` whole. * - * A MOVE, not a redesign. {@link KnowledgeSearchFacet} is a stateless facet of - * `KnowledgeService`: each static method is the body of the `KnowledgeService` - * member of the same name exactly as it stood (not re-indented, not edited). - * The member stays on the class as a one-call stub with its signature, so the - * published declaration, an instance spy and a subclass override are what they - * were. A public member keeps its docblock on the class, the contract; a - * private member's docblock moved here with its body. The state stays on - * `KnowledgeService`. + * A MOVE, not a redesign. Each function below is the body of the + * `KnowledgeService` member of the same name as it stood, re-indented one + * level and otherwise unedited (a line inside a string or template literal + * keeps its bytes). The member stays on the class as a one-call stub with its + * signature, so the published declaration, an instance spy and a subclass + * override are what they were; the class imports this module as + * `KnowledgeSearchFacet`. A public member keeps its docblock on the class, the + * contract; a private member's docblock moved here with its body. The state + * stays on `KnowledgeService`. * * A body reaches the service through `this`, typed as the part of - * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands - * it the host the class's static block builds once per service, whose methods call - * the service at call time and whose fields are getters (and a setter for a - * field a body assigns). A body that reads nothing of the service is called - * without one. `index.ts` re-exports nothing from this module. + * {@link KnowledgeSearchHost} it reads: the stub hands it the host the class's static + * block builds once per service (`knowledge-service-host.ts`), whose methods call the + * service at call time and whose fields are getters (and a setter for a field + * a body assigns). A body that reads nothing of the service is called without + * one. The module imports `knowledge-service.ts` for types only, so the two + * form no evaluation cycle. `index.ts` re-exports nothing from this module. */ import type { @@ -81,1012 +83,1065 @@ import { systemContext, wholeRefusal, } from './knowledge-service-top-level.js'; -import type { KnowledgeServiceHost } from './knowledge-service-host.js'; +import type { KnowledgeService } from './knowledge-service.js'; -export class KnowledgeSearchFacet { - static async search( - this: Pick, - query: string, - opts: KnowledgeSearchOptions = {}, - ): Promise { - return (await this.searchWithRefusals(query, opts)).hits; - } +/** + * The `KnowledgeService` members the bodies in this module read: every one + * of them, and no other. Each is typed AS the class member (an indexed + * access on the class), so a change to a member's type on the class is a change + * here too, and a name the class does not have does not compile. `readonly` + * members are methods and fields no body here assigns; the others are fields a + * body here assigns. + */ +export interface KnowledgeSearchHost { + readonly adapterIdFor: KnowledgeService['adapterIdFor']; + readonly admitSources: KnowledgeService['admitSources']; + readonly affinityFactsOf: KnowledgeService['affinityFactsOf']; + readonly affinityOrderFor: KnowledgeService['affinityOrderFor']; + readonly answerByRecord: KnowledgeService['answerByRecord']; + readonly applyPermissionFilter: KnowledgeService['applyPermissionFilter']; + readonly checkFreshness: KnowledgeService['checkFreshness']; + readonly checkScope: KnowledgeService['checkScope']; + readonly defaultTopK: KnowledgeService['defaultTopK']; + readonly dropUnverifiedHits: KnowledgeService['dropUnverifiedHits']; + readonly faceOfKey: KnowledgeService['faceOfKey']; + readonly facedRefusals: KnowledgeService['facedRefusals']; + readonly freshnessRepairs: KnowledgeService['freshnessRepairs']; + readonly getAdapter: KnowledgeService['getAdapter']; + readonly groupKeyOf: KnowledgeService['groupKeyOf']; + readonly handed: KnowledgeService['handed']; + readonly handedSources: KnowledgeService['handedSources']; + readonly held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly options: KnowledgeService['options']; + readonly planIndex: KnowledgeService['planIndex']; + readonly planSearches: KnowledgeService['planSearches']; + readonly publishRecordSyncs: KnowledgeService['publishRecordSyncs']; + readonly readChunkTarget: KnowledgeService['readChunkTarget']; + readonly readTenancyPosture: KnowledgeService['readTenancyPosture']; + readonly readVisibleIds: KnowledgeService['readVisibleIds']; + readonly recordSyncPublisher: KnowledgeService['recordSyncPublisher']; + readonly registry: KnowledgeService['registry']; + readonly repairStale: KnowledgeService['repairStale']; + readonly resolveSearchTargets: KnowledgeService['resolveSearchTargets']; + readonly schemaFor: KnowledgeService['schemaFor']; + readonly scopeAmbiguousReported: KnowledgeService['scopeAmbiguousReported']; + readonly scopeIgnoredReported: KnowledgeService['scopeIgnoredReported']; + readonly searchByKey: KnowledgeService['searchByKey']; + readonly searchRound: KnowledgeService['searchRound']; + readonly searchWithRefusals: KnowledgeService['searchWithRefusals']; + readonly serializeRecordSync: KnowledgeService['serializeRecordSync']; + readonly sourcesGroupableBy: KnowledgeService['sourcesGroupableBy']; + readonly sourcesInScope: KnowledgeService['sourcesInScope']; + readonly sourcesNarrowedToVisible: KnowledgeService['sourcesNarrowedToVisible']; + readonly syncRecord: KnowledgeService['syncRecord']; + readonly unprovenIndex: KnowledgeService['unprovenIndex']; +} - static async searchWithRefusals( - this: Pick, - query: string, - opts: KnowledgeSearchOptions = {}, - ): Promise { - // [ADR-0161 K8, the dated note on item 12] Held: refused, never answered - // empty (K7 rule 5), naming the half that is missing. - if (this.held) throw heldSourcesError(this.held); - const report = await this.searchByKey(query, opts); - return { - hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), - refused: this.facedRefusals(report.refused), - }; - } +/** The body of {@link KnowledgeService.search}; the member's docblock there is its contract. */ +export async function search( + this: Pick, + query: string, + opts: KnowledgeSearchOptions = {}, +): Promise { + return (await this.searchWithRefusals(query, opts)).hits; +} - /** - * {@link searchWithRefusals} with every source named by its index key, as - * an adapter's hit names it; the public member translates each to its face. - * A whole refusal thrown from here already names the sources by face. - */ - static async searchByKey( - this: Pick< - KnowledgeServiceHost, - 'admitSources' | 'affinityOrderFor' | 'answerByRecord' | 'applyPermissionFilter' | 'defaultTopK' | - 'dropUnverifiedHits' | 'facedRefusals' | 'groupKeyOf' | 'options' | 'planSearches' | 'resolveSearchTargets' | - 'searchRound' | 'sourcesGroupableBy' | 'sourcesInScope' | 'sourcesNarrowedToVisible' - >, - query: string, - opts: KnowledgeSearchOptions, - ): Promise { - const scope = readSearchScope(opts.scope); - const topK = opts.topK ?? this.defaultTopK; - const groupBy = opts.groupBy; - if (groupBy !== undefined) { - if (typeof groupBy !== 'string' || groupBy.length === 0) { - throw refusal('VALIDATION_ERROR', 400, '[knowledge] search groupBy must name a metadata field (a non-empty string).'); - } - if (opts.granularity === 'chunk') { - throw refusal( - 'VALIDATION_ERROR', - 400, - `[knowledge] search groupBy ${quotedName(groupBy)} groups records, so it cannot be combined with granularity 'chunk'. ` + - "Drop granularity, or pass granularity 'record'.", - ); - } +/** The body of {@link KnowledgeService.searchWithRefusals}; the member's docblock there is its contract. */ +export async function searchWithRefusals( + this: Pick, + query: string, + opts: KnowledgeSearchOptions = {}, +): Promise { + // [ADR-0161 K8, the dated note on item 12] Held: refused, never answered + // empty (K7 rule 5), naming the half that is missing. + if (this.held) throw heldSourcesError(this.held); + const report = await this.searchByKey(query, opts); + return { + hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), + refused: this.facedRefusals(report.refused), + }; +} + +/** + * {@link searchWithRefusals} with every source named by its index key, as + * an adapter's hit names it; the public member translates each to its face. + * A whole refusal thrown from here already names the sources by face. + */ +export async function searchByKey( + this: Pick< + KnowledgeSearchHost, + 'admitSources' | 'affinityOrderFor' | 'answerByRecord' | 'applyPermissionFilter' | 'defaultTopK' | + 'dropUnverifiedHits' | 'facedRefusals' | 'groupKeyOf' | 'options' | 'planSearches' | 'resolveSearchTargets' | + 'searchRound' | 'sourcesGroupableBy' | 'sourcesInScope' | 'sourcesNarrowedToVisible' + >, + query: string, + opts: KnowledgeSearchOptions, +): Promise { + const scope = readSearchScope(opts.scope); + const topK = opts.topK ?? this.defaultTopK; + const groupBy = opts.groupBy; + if (groupBy !== undefined) { + if (typeof groupBy !== 'string' || groupBy.length === 0) { + throw refusal('VALIDATION_ERROR', 400, '[knowledge] search groupBy must name a metadata field (a non-empty string).'); } - if (opts.granularity !== undefined && opts.granularity !== 'chunk' && opts.granularity !== 'record') { + if (opts.granularity === 'chunk') { throw refusal( 'VALIDATION_ERROR', 400, - `[knowledge] search granularity must be 'chunk' or 'record', got '${String(opts.granularity)}'.`, + `[knowledge] search groupBy ${quotedName(groupBy)} groups records, so it cannot be combined with granularity 'chunk'. ` + + "Drop granularity, or pass granularity 'record'.", ); } - const byRecord = opts.granularity === 'record' || groupBy !== undefined; - const ctx = opts.executionContext; - let admitted: Array = - await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); - if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); - if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); - const engine = this.options.dataEngine; - const filtered = ctx !== undefined && ctx.isSystem !== true && engine !== undefined; - // A caller the re-check can remove hits for: each source ranks only the - // records they may read, when those are few enough to name. - if (filtered && admitted.length > 0) admitted = await this.sourcesNarrowedToVisible(admitted, ctx, engine); - if (admitted.length === 0) return { hits: [], refused: [] }; - const refused: KnowledgeSearchRefusal[] = []; - const sources = await this.planSearches(admitted, refused); - // The sources whose every hit is checked against its live record before - // it is served: the ones the earlier title rule could serve a field for. - const verified = new Set(sources.filter((target) => target.verifyHits === true).map((target) => target.source.name)); - const served = async (hits: KnowledgeHit[]): Promise => - verified.size === 0 ? hits : this.dropUnverifiedHits(hits, verified); + } + if (opts.granularity !== undefined && opts.granularity !== 'chunk' && opts.granularity !== 'record') { + throw refusal( + 'VALIDATION_ERROR', + 400, + `[knowledge] search granularity must be 'chunk' or 'record', got '${String(opts.granularity)}'.`, + ); + } + const byRecord = opts.granularity === 'record' || groupBy !== undefined; + const ctx = opts.executionContext; + let admitted: Array = + await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); + if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); + const engine = this.options.dataEngine; + const filtered = ctx !== undefined && ctx.isSystem !== true && engine !== undefined; + // A caller the re-check can remove hits for: each source ranks only the + // records they may read, when those are few enough to name. + if (filtered && admitted.length > 0) admitted = await this.sourcesNarrowedToVisible(admitted, ctx, engine); + if (admitted.length === 0) return { hits: [], refused: [] }; + const refused: KnowledgeSearchRefusal[] = []; + const sources = await this.planSearches(admitted, refused); + // The sources whose every hit is checked against its live record before + // it is served: the ones the earlier title rule could serve a field for. + const verified = new Set(sources.filter((target) => target.verifyHits === true).map((target) => target.source.name)); + const served = async (hits: KnowledgeHit[]): Promise => + verified.size === 0 ? hits : this.dropUnverifiedHits(hits, verified); - const widened = byRecord || filtered; - const firstAsk = (_source: KnowledgeSource): number => - widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; - const groupOf = byRecord - ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) - : recordKeyOf; - const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); - if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); - const raw = [...first.values()].flatMap((answer) => answer.hits); - let kept = await served(await this.applyPermissionFilter(raw, ctx, byRecord)); - let removed = raw.length - kept.length; + const widened = byRecord || filtered; + const firstAsk = (_source: KnowledgeSource): number => + widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; + const groupOf = byRecord + ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) + : recordKeyOf; + const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); + if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); + const raw = [...first.values()].flatMap((answer) => answer.hits); + let kept = await served(await this.applyPermissionFilter(raw, ctx, byRecord)); + let removed = raw.length - kept.length; - if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { - const saturated = sources.filter(({ source }) => { - const answer = first.get(source.name); - return widened && answer !== undefined && answer.answered >= firstAsk(source); - }); - if (saturated.length > 0) { - const refusedBefore = refused.length; - const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); - // A refilled source's second answer is a superset of its first: its - // first-round survivors are dropped and the whole answer re-checked. - const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); - const refilledKept = await served(await this.applyPermissionFilter(refilledHits, ctx, byRecord)); - const firstRaw = raw.filter((hit) => refill.has(hit.sourceId)).length; - const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; - kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; - removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); - // A source that refused the refill (its index changed between the two - // rounds) is refused for the whole search: its first-round hits are - // dropped, so no source is both answered and named as refused. - const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); - if (refusedInRefill.size > 0) { - kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); - if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(this.facedRefusals(refused)); - } + if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { + const saturated = sources.filter(({ source }) => { + const answer = first.get(source.name); + return widened && answer !== undefined && answer.answered >= firstAsk(source); + }); + if (saturated.length > 0) { + const refusedBefore = refused.length; + const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); + // A refilled source's second answer is a superset of its first: its + // first-round survivors are dropped and the whole answer re-checked. + const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); + const refilledKept = await served(await this.applyPermissionFilter(refilledHits, ctx, byRecord)); + const firstRaw = raw.filter((hit) => refill.has(hit.sourceId)).length; + const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; + kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; + removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); + // A source that refused the refill (its index changed between the two + // rounds) is refused for the whole search: its first-round hits are + // dropped, so no source is both answered and named as refused. + const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); + if (refusedInRefill.size > 0) { + kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); + if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(this.facedRefusals(refused)); } } - - if (removed > 0) { - this.options.logger?.debug?.( - `[knowledge] the permission re-check and the per-hit record check removed ${removed} hit(s); ` + - `${Math.min(byRecord ? distinctGroups(kept, groupOf) : kept.length, topK)} of topK=${topK} answered.`, - ); - } - kept.sort((a, b) => b.score - a.score); - // [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} ` + - `${groupBy === undefined ? 'records' : `${quotedName(groupBy)} groups`}: no more within the refill cap ` + - `(topK × ${SEARCH_REFILL_FACTOR} passages per source).`, - ); - } - return { hits: answer, refused }; - } - - /** - * The sources a `groupBy` search asks: each source that lists `groupBy` in - * its `metadataFields`. Any other source answers no hits for this search — - * its hits carry no group value, and a hit is never answered ungrouped. - */ - static sourcesGroupableBy( - this: Pick, - sources: T[], - groupBy: string, - ): T[] { - return sources.filter(({ source }) => { - if ((source.source.metadataFields ?? []).includes(groupBy)) return true; - this.options.logger?.debug?.( - `[knowledge] source '${this.label(source)}' not searched for groupBy ${quotedName(groupBy)}: ` + - 'the field is not one of its metadataFields.', - ); - return false; - }); } - /** - * The group a hit falls in under record granularity: with `groupBy`, the - * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — - * when the hit carries none); without it, the parent record its source's - * `documentBy` names, else the hit's record ({@link documentKeyOf}). - */ - static groupKeyOf( - this: Pick, - hit: KnowledgeHit, - groupBy: string | undefined, - ): string | undefined { - if (groupBy === undefined) return documentKeyOf(hit, this.handed(hit.sourceId)?.source.documentBy); - const value = hit.metadata?.[groupBy]; - if (value === undefined || value === null || value === '') return undefined; - return `value:${stableJson(value)}`; + if (removed > 0) { + this.options.logger?.debug?.( + `[knowledge] the permission re-check and the per-hit record check removed ${removed} hit(s); ` + + `${Math.min(byRecord ? distinctGroups(kept, groupOf) : kept.length, topK)} of topK=${topK} answered.`, + ); } - - /** - * [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. - */ - static async affinityOrderFor( - this: Pick, - 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; - }; + kept.sort((a, b) => b.score - a.score); + // [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} ` + + `${groupBy === undefined ? 'records' : `${quotedName(groupBy)} groups`}: no more within the refill cap ` + + `(topK × ${SEARCH_REFILL_FACTOR} passages per source).`, + ); } + return { hits: answer, refused }; +} - /** The caller facts of one search ({@link affinityOrderFor}), only those the declaring sources' entries read. */ - static async affinityFactsOf( - this: Pick, - 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 sources a `groupBy` search asks: each source that lists `groupBy` in + * its `metadataFields`. Any other source answers no hits for this search — + * its hits carry no group value, and a hit is never answered ungrouped. + */ +export function sourcesGroupableBy( + this: Pick, + sources: T[], + groupBy: string, +): T[] { + return sources.filter(({ source }) => { + if ((source.source.metadataFields ?? []).includes(groupBy)) return true; + this.options.logger?.debug?.( + `[knowledge] source '${this.label(source)}' not searched for groupBy ${quotedName(groupBy)}: ` + + 'the field is not one of its metadataFields.', ); - } + return false; + }); +} + +/** + * The group a hit falls in under record granularity: with `groupBy`, the + * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — + * when the hit carries none); without it, the parent record its source's + * `documentBy` names, else the hit's record ({@link documentKeyOf}). + */ +export function groupKeyOf( + this: Pick, + hit: KnowledgeHit, + groupBy: string | undefined, +): string | undefined { + if (groupBy === undefined) return documentKeyOf(hit, this.handed(hit.sourceId)?.source.documentBy); + const value = hit.metadata?.[groupBy]; + if (value === undefined || value === null || value === '') return undefined; + return `value:${stableJson(value)}`; +} - /** - * The record-level answer: one hit per group, the group's best passage, - * 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 - * - * The index is a copy, and a record may have changed since it was indexed. - * So each `object`-source hit about to be answered is checked against its - * record as it reads now — one system-context read per source, of the hits' - * records only (at most `topK`), `{ $and: [where, { id: { $in } }] }` - * projected to the fields assembly reads. A record that no longer exists or - * no longer matches `where`, or whose recomputed `docHash` differs from the - * hit's (the stored hash), is dropped — all of its passages — and its - * document repaired in the background ({@link repairStale}) unless the source - * opted out of the event sync (`refresh.onRecordChange: false`: an external - * indexer owns that index, so the service writes nothing to it and the hit - * is only dropped). A group whose - * lead was dropped falls back to its next passage, and the next groups move - * up; that is checked again, at most `SEARCH_FRESHNESS_ROUNDS` times, after - * which a hit still unchecked is not answered (`capped`, logged at `debug` - * by its own line). A hit whose adapter stores no - * hash is checked for membership only. A read that fails drops that - * source's checked hits (fail-closed), reported at `warn`. - * - * Not checked: a hit without a record id, and every hit when no data engine - * is bound. - */ - static async answerByRecord( - this: Pick, - 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) { - const key = groupOf(hit); - if (key === undefined) continue; - const members = groups.get(key); - if (members) members.push(hit); - else groups.set(key, [hit]); +/** + * [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. + */ +export async function affinityOrderFor( + this: Pick, + 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.`); } - const engine = this.options.dataEngine; - const checkKey = (hit: KnowledgeHit): string | undefined => - engine !== undefined && hit.sourceRecordId !== undefined && this.handed(hit.sourceId) !== undefined - ? `${hit.sourceId}#${hit.sourceRecordId}` - : undefined; - const fresh = new Set(); - const stale = new Set(); - const leads = (): KnowledgeHit[] => { - const out: KnowledgeHit[] = []; - for (const members of groups.values()) { - const lead = members.find((hit) => { - const key = checkKey(hit); - return key === undefined || !stale.has(key); - }); - if (lead) out.push(lead); - } - // 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(); - const unchecked = top.filter((hit) => { + return ordered; + }; +} + +/** The caller facts of one search ({@link affinityOrderFor}), only those the declaring sources' entries read. */ +export async function affinityFactsOf( + this: Pick, + 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`, 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 + * + * The index is a copy, and a record may have changed since it was indexed. + * So each `object`-source hit about to be answered is checked against its + * record as it reads now — one system-context read per source, of the hits' + * records only (at most `topK`), `{ $and: [where, { id: { $in } }] }` + * projected to the fields assembly reads. A record that no longer exists or + * no longer matches `where`, or whose recomputed `docHash` differs from the + * hit's (the stored hash), is dropped — all of its passages — and its + * document repaired in the background ({@link repairStale}) unless the source + * opted out of the event sync (`refresh.onRecordChange: false`: an external + * indexer owns that index, so the service writes nothing to it and the hit + * is only dropped). A group whose + * lead was dropped falls back to its next passage, and the next groups move + * up; that is checked again, at most `SEARCH_FRESHNESS_ROUNDS` times, after + * which a hit still unchecked is not answered (`capped`, logged at `debug` + * by its own line). A hit whose adapter stores no + * hash is checked for membership only. A read that fails drops that + * source's checked hits (fail-closed), reported at `warn`. + * + * Not checked: a hit without a record id, and every hit when no data engine + * is bound. + */ +export async function answerByRecord( + this: Pick, + 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) { + const key = groupOf(hit); + if (key === undefined) continue; + const members = groups.get(key); + if (members) members.push(hit); + else groups.set(key, [hit]); + } + const engine = this.options.dataEngine; + const checkKey = (hit: KnowledgeHit): string | undefined => + engine !== undefined && hit.sourceRecordId !== undefined && this.handed(hit.sourceId) !== undefined + ? `${hit.sourceId}#${hit.sourceRecordId}` + : undefined; + const fresh = new Set(); + const stale = new Set(); + const leads = (): KnowledgeHit[] => { + const out: KnowledgeHit[] = []; + for (const members of groups.values()) { + const lead = members.find((hit) => { const key = checkKey(hit); - return key !== undefined && !fresh.has(key); + return key === undefined || !stale.has(key); }); - if (unchecked.length === 0) return { hits: top, capped: false }; - if (round === SEARCH_FRESHNESS_ROUNDS) { - this.options.logger?.debug?.( - `[knowledge] record-level search stopped checking freshness after ${SEARCH_FRESHNESS_ROUNDS} rounds; ` + - `${unchecked.length} unchecked hit(s) not answered.`, - ); - return { hits: top.filter((hit) => !unchecked.includes(hit)), capped: true }; - } - await this.checkFreshness(unchecked, fresh, stale); + if (lead) out.push(lead); } + // 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(); + const unchecked = top.filter((hit) => { + const key = checkKey(hit); + return key !== undefined && !fresh.has(key); + }); + if (unchecked.length === 0) return { hits: top, capped: false }; + if (round === SEARCH_FRESHNESS_ROUNDS) { + this.options.logger?.debug?.( + `[knowledge] record-level search stopped checking freshness after ${SEARCH_FRESHNESS_ROUNDS} rounds; ` + + `${unchecked.length} unchecked hit(s) not answered.`, + ); + return { hits: top.filter((hit) => !unchecked.includes(hit)), capped: true }; + } + await this.checkFreshness(unchecked, fresh, stale); } +} - /** - * One round of the freshness check ({@link answerByRecord}): read the - * records `hits` name, one system-context read per source, and sort each - * record into `fresh` or `stale` (`sourceId#recordId`). - */ - static async checkFreshness( - this: Pick< - KnowledgeServiceHost, - 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' - >, - hits: KnowledgeHit[], - fresh: Set, - stale: Set, - ): Promise { - const engine = this.options.dataEngine; - if (!engine) return; - const bySource = new Map>(); - for (const hit of hits) { - const records = bySource.get(hit.sourceId) ?? new Map(); - if (!records.has(hit.sourceRecordId!)) records.set(hit.sourceRecordId!, hit); - bySource.set(hit.sourceId, records); - } - let posture: { value: TenancyPosture | undefined } | null | undefined; - for (const [sourceId, records] of bySource) { - const source = this.handed(sourceId)!; - const objSource = source.source; - const ids = [...records.keys()]; - const byId = { id: { $in: ids } }; - const schema = this.schemaFor(objSource.object); - let rows: unknown; - try { - if (posture === undefined) { - try { - posture = { value: await this.readTenancyPosture() }; - } catch (err) { - posture = null; - this.options.logger?.warn?.( - `[knowledge] the tenancy posture could not be read (${errorText(err)}); the freshness check of this ` + - 'search compares no document hash, only whether each record still belongs to its source.', - ); - } - } - const fields = freshnessFields(objSource, schema, posture?.value); - rows = await engine.find( - objSource.object, - { - where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, - ...(fields === undefined ? {} : { fields }), - }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) { - throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); +/** + * One round of the freshness check ({@link answerByRecord}): read the + * records `hits` name, one system-context read per source, and sort each + * record into `fresh` or `stale` (`sourceId#recordId`). + */ +export async function checkFreshness( + this: Pick< + KnowledgeSearchHost, + 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' + >, + hits: KnowledgeHit[], + fresh: Set, + stale: Set, +): Promise { + const engine = this.options.dataEngine; + if (!engine) return; + const bySource = new Map>(); + for (const hit of hits) { + const records = bySource.get(hit.sourceId) ?? new Map(); + if (!records.has(hit.sourceRecordId!)) records.set(hit.sourceRecordId!, hit); + bySource.set(hit.sourceId, records); + } + let posture: { value: TenancyPosture | undefined } | null | undefined; + for (const [sourceId, records] of bySource) { + const source = this.handed(sourceId)!; + const objSource = source.source; + const ids = [...records.keys()]; + const byId = { id: { $in: ids } }; + const schema = this.schemaFor(objSource.object); + let rows: unknown; + try { + if (posture === undefined) { + try { + posture = { value: await this.readTenancyPosture() }; + } catch (err) { + posture = null; + this.options.logger?.warn?.( + `[knowledge] the tenancy posture could not be read (${errorText(err)}); the freshness check of this ` + + 'search compares no document hash, only whether each record still belongs to its source.', + ); } - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the freshness check of source '${sourceId}' could not read its records ` + - `(${errorText(err)}); its hits are not answered.`, - ); - for (const id of ids) stale.add(`${sourceId}#${id}`); - continue; } - const byRow = new Map>(); - for (const row of rows as Array | null | undefined>) { - if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + const fields = freshnessFields(objSource, schema, posture?.value); + rows = await engine.find( + objSource.object, + { + where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, + ...(fields === undefined ? {} : { fields }), + }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) { + throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); } - for (const [recordId, hit] of records) { - const key = `${sourceId}#${recordId}`; - const docId = documentIdFor(sourceId, recordId); - const row = byRow.get(recordId); - const changed = - row !== undefined && - hit.docHash !== undefined && - posture !== null && - recordToDocument(source, objSource, row, schema, posture?.value).docHash !== hit.docHash; - if (row === undefined || changed) { - stale.add(key); - this.repairStale(source, objSource, recordId); - } else { - fresh.add(key); - if (hit.docHash !== undefined && posture !== null) this.freshnessRepairs.delete(docId); - } + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the freshness check of source '${sourceId}' could not read its records ` + + `(${errorText(err)}); its hits are not answered.`, + ); + for (const id of ids) stale.add(`${sourceId}#${id}`); + continue; + } + const byRow = new Map>(); + for (const row of rows as Array | null | undefined>) { + if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + } + for (const [recordId, hit] of records) { + const key = `${sourceId}#${recordId}`; + const docId = documentIdFor(sourceId, recordId); + const row = byRow.get(recordId); + const changed = + row !== undefined && + hit.docHash !== undefined && + posture !== null && + recordToDocument(source, objSource, row, schema, posture?.value).docHash !== hit.docHash; + if (row === undefined || changed) { + stale.add(key); + this.repairStale(source, objSource, recordId); + } else { + fresh.add(key); + if (hit.docHash !== undefined && posture !== null) this.freshnessRepairs.delete(docId); } } } +} - /** - * The hits of `verified` sources whose stored document is the one the - * current recipe assembles from the record as it reads now; every other hit - * of those sources is dropped. A hit of any other source passes untouched. - * - * Why: a source the earlier title rule could serve a field for - * (`mayServeEarlierRuleTitle`) is searched without the field gate's former - * `title` arm, and its index may still hold a document assembled under - * another recipe: one a build walked past and did not purge (a store with - * no `listDocuments`, `refresh.onRecordChange: false`, a purge candidate - * kept or listed under a foreign id), or one written between two builds - * while the object's display field was another field. The recipe hash - * cannot see either; this check reads the record. A hit survives only when - * its record still belongs to the source (one system read per source, - * `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly - * reads), its document id is the one the source derives from that record, - * and the `docHash` the store holds equals the one {@link recordToDocument} - * computes from the row under the current object definition (the title is - * part of it). Strict, unlike {@link checkFreshness}: a hit with no record - * id or no stored hash, a read that fails or answers no list, a posture - * that cannot be read and a hash that cannot be computed each drop the hit. - * - * The read decides only whether a hit survives: a surviving hit is returned - * as the store answered it, and nothing the read returned is put on it. A - * stale record's document is repaired in the background ({@link - * repairStale}), as the record-level check repairs it. - */ - static async dropUnverifiedHits( - this: Pick< - KnowledgeServiceHost, - 'faceOfKey' | 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' - >, - hits: KnowledgeHit[], - verified: ReadonlySet, - ): Promise { - const engine = this.options.dataEngine; - const checked = hits.filter((hit) => verified.has(hit.sourceId)); - if (checked.length === 0) return hits; - const passed = new Set(); - const dropped = (sourceId: string, count: number, why: string): void => { - if (count > 0) { - this.options.logger?.debug?.( - `[knowledge] ${count} hit(s) of source '${this.faceOfKey(sourceId)}' not served: ${why}`, - ); - } - }; - let posture: TenancyPosture | undefined; - let postureRead = true; +/** + * The hits of `verified` sources whose stored document is the one the + * current recipe assembles from the record as it reads now; every other hit + * of those sources is dropped. A hit of any other source passes untouched. + * + * Why: a source the earlier title rule could serve a field for + * (`mayServeEarlierRuleTitle`) is searched without the field gate's former + * `title` arm, and its index may still hold a document assembled under + * another recipe: one a build walked past and did not purge (a store with + * no `listDocuments`, `refresh.onRecordChange: false`, a purge candidate + * kept or listed under a foreign id), or one written between two builds + * while the object's display field was another field. The recipe hash + * cannot see either; this check reads the record. A hit survives only when + * its record still belongs to the source (one system read per source, + * `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly + * reads), its document id is the one the source derives from that record, + * and the `docHash` the store holds equals the one {@link recordToDocument} + * computes from the row under the current object definition (the title is + * part of it). Strict, unlike {@link checkFreshness}: a hit with no record + * id or no stored hash, a read that fails or answers no list, a posture + * that cannot be read and a hash that cannot be computed each drop the hit. + * + * The read decides only whether a hit survives: a surviving hit is returned + * as the store answered it, and nothing the read returned is put on it. A + * stale record's document is repaired in the background ({@link + * repairStale}), as the record-level check repairs it. + */ +export async function dropUnverifiedHits( + this: Pick< + KnowledgeSearchHost, + 'faceOfKey' | 'freshnessRepairs' | 'handed' | 'options' | 'readTenancyPosture' | 'repairStale' | 'schemaFor' + >, + hits: KnowledgeHit[], + verified: ReadonlySet, +): Promise { + const engine = this.options.dataEngine; + const checked = hits.filter((hit) => verified.has(hit.sourceId)); + if (checked.length === 0) return hits; + const passed = new Set(); + const dropped = (sourceId: string, count: number, why: string): void => { + if (count > 0) { + this.options.logger?.debug?.( + `[knowledge] ${count} hit(s) of source '${this.faceOfKey(sourceId)}' not served: ${why}`, + ); + } + }; + let posture: TenancyPosture | undefined; + let postureRead = true; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + postureRead = false; + this.options.logger?.warn?.( + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no hit of a source checked against its ` + + 'record is served this search (fail-closed).', + ); + } + const bySource = new Map(); + for (const hit of checked) bySource.set(hit.sourceId, [...(bySource.get(hit.sourceId) ?? []), hit]); + for (const [sourceId, sourceHits] of bySource) { + const source = this.handed(sourceId); + if (!engine || !postureRead || !source || source.source.kind !== 'object') { + dropped(sourceId, sourceHits.length, 'their records cannot be read to check them.'); + continue; + } + const objSource = source.source; + const usable = sourceHits.filter( + (hit) => isRecordId(hit.sourceRecordId) && typeof hit.docHash === 'string' && hit.docHash !== '', + ); + dropped(sourceId, sourceHits.length - usable.length, 'a hit names no record or carries no stored hash.'); + if (usable.length === 0) continue; + const ids = [...new Set(usable.map((hit) => String(hit.sourceRecordId)))]; + const byId = { id: { $in: ids } }; + const schema = this.schemaFor(objSource.object); + let rows: unknown; try { - posture = await this.readTenancyPosture(); + const fields = freshnessFields(objSource, schema, posture); + rows = await engine.find( + objSource.object, + { + where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, + ...(fields === undefined ? {} : { fields }), + }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); } catch (err) { - postureRead = false; this.options.logger?.warn?.( - `[knowledge] the tenancy posture could not be read (${errorText(err)}); no hit of a source checked against its ` + - 'record is served this search (fail-closed).', + `[knowledge] the records of source '${this.faceOfKey(sourceId)}' could not be read to check its hits ` + + `(${errorText(err)}); none is served (fail-closed).`, ); + continue; } - const bySource = new Map(); - for (const hit of checked) bySource.set(hit.sourceId, [...(bySource.get(hit.sourceId) ?? []), hit]); - for (const [sourceId, sourceHits] of bySource) { - const source = this.handed(sourceId); - if (!engine || !postureRead || !source || source.source.kind !== 'object') { - dropped(sourceId, sourceHits.length, 'their records cannot be read to check them.'); - continue; - } - const objSource = source.source; - const usable = sourceHits.filter( - (hit) => isRecordId(hit.sourceRecordId) && typeof hit.docHash === 'string' && hit.docHash !== '', - ); - dropped(sourceId, sourceHits.length - usable.length, 'a hit names no record or carries no stored hash.'); - if (usable.length === 0) continue; - const ids = [...new Set(usable.map((hit) => String(hit.sourceRecordId)))]; - const byId = { id: { $in: ids } }; - const schema = this.schemaFor(objSource.object); - let rows: unknown; - try { - const fields = freshnessFields(objSource, schema, posture); - rows = await engine.find( - objSource.object, - { - where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, - ...(fields === undefined ? {} : { fields }), - }, - { context: systemContext() }, - ); - if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); - } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the records of source '${this.faceOfKey(sourceId)}' could not be read to check its hits ` + - `(${errorText(err)}); none is served (fail-closed).`, - ); - continue; - } - const byRow = new Map>(); - for (const row of rows as Array | null | undefined>) { - if (row && isRecordId(row.id)) byRow.set(String(row.id), row); - } - const current = new Map(); - for (const hit of usable) { - const recordId = String(hit.sourceRecordId); - if (hit.documentId !== documentIdFor(sourceId, recordId)) continue; - if (!current.has(recordId)) { - const row = byRow.get(recordId); - let hash: string | undefined; - if (row !== undefined) { - try { - hash = recordToDocument(source, objSource, row, schema, posture).docHash; - } catch { - hash = undefined; - } + const byRow = new Map>(); + for (const row of rows as Array | null | undefined>) { + if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + } + const current = new Map(); + for (const hit of usable) { + const recordId = String(hit.sourceRecordId); + if (hit.documentId !== documentIdFor(sourceId, recordId)) continue; + if (!current.has(recordId)) { + const row = byRow.get(recordId); + let hash: string | undefined; + if (row !== undefined) { + try { + hash = recordToDocument(source, objSource, row, schema, posture).docHash; + } catch { + hash = undefined; } - current.set(recordId, hash); - if (row === undefined || (hash !== undefined && hash !== hit.docHash)) this.repairStale(source, objSource, recordId); - } - const hash = current.get(recordId); - if (hash !== undefined && hash === hit.docHash) { - passed.add(hit); - this.freshnessRepairs.delete(documentIdFor(sourceId, recordId)); } + current.set(recordId, hash); + if (row === undefined || (hash !== undefined && hash !== hit.docHash)) this.repairStale(source, objSource, recordId); + } + const hash = current.get(recordId); + if (hash !== undefined && hash === hit.docHash) { + passed.add(hit); + this.freshnessRepairs.delete(documentIdFor(sourceId, recordId)); } - dropped( - sourceId, - usable.filter((hit) => !passed.has(hit)).length, - 'the record no longer belongs to the source, or the stored document is not the one the current recipe assembles from it.', - ); - } - return hits.filter((hit) => !verified.has(hit.sourceId) || passed.has(hit)); - } - - /** - * Repair the document of a record the freshness check found stale: the - * event sync's own path ({@link syncRecord}, serialized per document), run - * in system context, in this process and NOT awaited — the search that found - * it answers without it. Single-flight per document, and at most once per - * document until a later search finds its hash matching. Never throws into - * the search. The scheduled reconcile does not take it over: the reconcile - * walks whole sources, and this repairs one document now. That is the - * inline path. - * - * While record syncs run through the queue ({@link routeRecordSyncs}) the - * repair is a record-sync message with reason `freshness`, for this source - * alone: it survives a restart of the process that searched and is retried - * like any other sync. A message that could not be published is reported - * at `error` and the document is left to the next search that finds it - * stale. - * - * A source with `refresh.onRecordChange: false` is never repaired: it is - * asked through {@link objectSourcesFor}, the one predicate that keeps the - * service's writes out of a source an external indexer owns, so the stale - * hit is dropped from the answer and its index entry left to that indexer. - */ - static repairStale( - this: Pick< - KnowledgeServiceHost, - 'freshnessRepairs' | 'publishRecordSyncs' | 'recordSyncPublisher' | 'serializeRecordSync' | 'syncRecord' - >, - source: KnowledgeSource, - objSource: ObjectKnowledgeSource, - recordId: string, - ): void { - if (objectSourcesFor([source], objSource.object).length === 0) return; - const docId = documentIdFor(source.name, recordId); - if (this.freshnessRepairs.has(docId)) return; - this.freshnessRepairs.add(docId); - if (this.recordSyncPublisher) { - this.publishRecordSyncs([source], objSource.object, recordId, 'freshness', () => this.freshnessRepairs.delete(docId)); - return; } - void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); + dropped( + sourceId, + usable.filter((hit) => !passed.has(hit)).length, + 'the record no longer belongs to the source, or the stored document is not the one the current recipe assembles from it.', + ); } + return hits.filter((hit) => !verified.has(hit.sourceId) || passed.has(hit)); +} - /** - * Each admitted source paired with the adapter it binds to, resolved here - * once for the whole search, and the fingerprint its search carries - * ({@link planIndex}); a source whose adapter does not resolve carries the - * coded refusal instead and is refused by the round, never searched. - * - * A source admitted with `proveIndex` ({@link admitSources}) is searched - * only when its index is proven built under the current recipe - * ({@link unprovenIndex}); otherwise it is not searched and is added to - * `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), the operator told why at - * `warn`. Each says whether a rebuild ends the refusal: for a source no - * build can prove, neither promises one. The boot's build pass, a reload, - * the reconcile and the operator's rebuild are what build a source; a - * search never starts a build. - */ - static async planSearches( - this: Pick< - KnowledgeServiceHost, - 'adapterIdFor' | 'getAdapter' | 'label' | 'options' | 'planIndex' | 'readChunkTarget' | 'unprovenIndex' - >, - admitted: Array, - refused: KnowledgeSearchRefusal[], - ): Promise { - const out: SearchTarget[] = []; - // The settings page's chunk target, read at most once for the whole search. - let target: Promise | undefined; - const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); - for (const { proveIndex, ...entry } of admitted) { - // The adapter is resolved here, once per search: the proof below is read - // from this instance and both rounds search this instance, so a source - // cannot change binding between the check and the use. - let adapterId: string; - let adapter: IKnowledgeAdapter; - try { - adapterId = this.adapterIdFor(entry.source); - adapter = this.getAdapter(adapterId); - } catch (err) { - // Refused like an adapter that cannot serve, as the round refuses it; a - // source that needs the index proof is never searched without it. - out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); - continue; - } - const plan = await this.planIndex(entry.source, adapter, chunkTarget); - if (proveIndex === true) { - const unproven = await this.unprovenIndex(plan); - if (unproven !== undefined) { - const label = this.label(entry.source); - refused.push({ - sourceId: entry.source.name, - code: INDEX_NOT_PROVEN_CODE, - status: 409, - message: `Knowledge source '${label}' is not searched: its index is not proven built under the current recipe. ` + - UNPROVEN_CALLER_TEXT[unproven.ends], - }); - this.options.logger?.warn?.( - `[knowledge] source '${label}' not searched (${INDEX_NOT_PROVEN_CODE}): ${unproven.why} Its object declares ` + - "a field named 'title' the source does not serve, and a document indexed under the earlier title rule " + - "carries that field's value, so the source is searched only once its index is proven built under the " + - `current recipe. ${UNPROVEN_OPERATOR_TEXT[unproven.ends]}`, - ); - continue; - } - } - out.push({ - ...entry, - binding: { adapterId, adapter }, - fingerprint: plan.index.fingerprint, - ...(proveIndex === true ? { verifyHits: true as const } : {}), - }); - } - return out; +/** + * Repair the document of a record the freshness check found stale: the + * event sync's own path ({@link syncRecord}, serialized per document), run + * in system context, in this process and NOT awaited — the search that found + * it answers without it. Single-flight per document, and at most once per + * document until a later search finds its hash matching. Never throws into + * the search. The scheduled reconcile does not take it over: the reconcile + * walks whole sources, and this repairs one document now. That is the + * inline path. + * + * While record syncs run through the queue ({@link routeRecordSyncs}) the + * repair is a record-sync message with reason `freshness`, for this source + * alone: it survives a restart of the process that searched and is retried + * like any other sync. A message that could not be published is reported + * at `error` and the document is left to the next search that finds it + * stale. + * + * A source with `refresh.onRecordChange: false` is never repaired: it is + * asked through {@link objectSourcesFor}, the one predicate that keeps the + * service's writes out of a source an external indexer owns, so the stale + * hit is dropped from the answer and its index entry left to that indexer. + */ +export function repairStale( + this: Pick< + KnowledgeSearchHost, + 'freshnessRepairs' | 'publishRecordSyncs' | 'recordSyncPublisher' | 'serializeRecordSync' | 'syncRecord' + >, + source: KnowledgeSource, + objSource: ObjectKnowledgeSource, + recordId: string, +): void { + if (objectSourcesFor([source], objSource.object).length === 0) return; + const docId = documentIdFor(source.name, recordId); + if (this.freshnessRepairs.has(docId)) return; + this.freshnessRepairs.add(docId); + if (this.recordSyncPublisher) { + this.publishRecordSyncs([source], objSource.object, recordId, 'freshness', () => this.freshnessRepairs.delete(docId)); + return; } + void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); +} - /** - * Why `plan`'s source is not proven built under the current recipe, and - * what ends it, or `undefined` when it is proven: its adapter's - * `indexStatus` reports the fingerprint AND the recipe hash - * {@link planIndex} computes now, and the builds that record that hash - * purge what they did not walk. - * - * The recipe hash names the title rule (ADR-0161 K7), and an adapter - * records it only at `completeBuild`, the end of a complete build. A - * complete build rewrites every document whose title changed (`docHash` - * covers the title) and, when it purges, removes every document it did not - * walk. It does not purge, and still records the hash, for a source with - * `refresh.onRecordChange: false` and on an adapter with no - * `listDocuments` ({@link walkObjectSource}): a document it did not walk, - * such as one whose row left the source's `where`, keeps what it was - * assembled with. So those two shapes are never proven, before any read, - * whatever the hash reads; nor is an adapter with no `indexStatus` (nothing - * to read) or no `completeBuild` (nothing ever records a hash). - * - * The proof covers what the last complete build walked and purged. Read on - * every search that needs it, never cached: another node may rebuild, or - * drop, the index. Fails closed: a status that throws is not proven. - */ - static async unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { - const { adapter, index, source } = plan; - if ((source.refresh?.onRecordChange ?? true) === false) { - return { - ends: 'never', - why: - 'refresh.onRecordChange is false, so an external indexer owns its index: a build of it purges nothing, ' + - 'so a recorded recipe hash does not prove the index holds no document assembled under an earlier recipe.', - }; - } - if (typeof adapter.indexStatus !== 'function') { - return { - ends: 'never', - why: `the adapter '${adapter.id}' reports no index status (no indexStatus), so what its index was built under cannot be read.`, - }; - } - if (typeof adapter.completeBuild !== 'function') { - return { - ends: 'never', - why: `the adapter '${adapter.id}' has no completeBuild, so no build records a recipe hash for its index.`, - }; - } - if (typeof adapter.listDocuments !== 'function') { - return { - ends: 'never', - why: - `the adapter '${adapter.id}' does not list its documents (no listDocuments), so a complete build cannot purge a ` + - 'document it did not walk, and a recorded recipe hash does not prove the index holds none assembled under an ' + - 'earlier recipe.', - }; - } - let held: AdapterIndexStatus; +/** + * Each admitted source paired with the adapter it binds to, resolved here + * once for the whole search, and the fingerprint its search carries + * ({@link planIndex}); a source whose adapter does not resolve carries the + * coded refusal instead and is refused by the round, never searched. + * + * A source admitted with `proveIndex` ({@link admitSources}) is searched + * only when its index is proven built under the current recipe + * ({@link unprovenIndex}); otherwise it is not searched and is added to + * `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), the operator told why at + * `warn`. Each says whether a rebuild ends the refusal: for a source no + * build can prove, neither promises one. The boot's build pass, a reload, + * the reconcile and the operator's rebuild are what build a source; a + * search never starts a build. + */ +export async function planSearches( + this: Pick< + KnowledgeSearchHost, + 'adapterIdFor' | 'getAdapter' | 'label' | 'options' | 'planIndex' | 'readChunkTarget' | 'unprovenIndex' + >, + admitted: Array, + refused: KnowledgeSearchRefusal[], +): Promise { + const out: SearchTarget[] = []; + // The settings page's chunk target, read at most once for the whole search. + let target: Promise | undefined; + const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); + for (const { proveIndex, ...entry } of admitted) { + // The adapter is resolved here, once per search: the proof below is read + // from this instance and both rounds search this instance, so a source + // cannot change binding between the check and the use. + let adapterId: string; + let adapter: IKnowledgeAdapter; try { - held = await adapter.indexStatus(plan.context('search')); + adapterId = this.adapterIdFor(entry.source); + adapter = this.getAdapter(adapterId); } catch (err) { - return { ends: 'unreadable', why: `the adapter's index status could not be read (${operatorText(err)}).` }; - } - if (held?.fingerprint !== index.fingerprint) { - return { ends: 'rebuild', why: 'the index holds no complete build under the current fingerprint.' }; + // Refused like an adapter that cannot serve, as the round refuses it; a + // source that needs the index proof is never searched without it. + out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); + continue; } - if (held.recipeHash !== index.recipeHash) { - return { - ends: 'rebuild', - why: held.recipeHash === undefined - ? 'the index records no recipe hash: no complete build of it has completed.' - : "the index was last completed under another recipe (the source's where, metadataFields, title rule or withheld fields).", - }; - } - return undefined; - } - - /** - * One round of {@link search}: ask each source's adapter for `ask(source)` - * hits. Answers, per source that answered, the hits it serves and how many - * the adapter returned (`answered`, before a hit naming another source or - * outside the scope is dropped — what decides whether the adapter may hold - * more). A source whose adapter is unknown or throws is absent from the - * answer: a coded refusal (ADR-0112 `code` and `status`) is added to - * `refused`, anything else is logged. - * - * Under a scope, the adapter is handed the source's terms, and every hit it - * answers is checked against them ({@link scopeCheck}, fail closed). The first - * time the check drops a hit of an adapter, that is reported once for the - * adapter, at `warn`: it does not apply the scope before ranking, or answers - * hits without the document's metadata, so its scoped searches may answer - * fewer than `topK` (ADR-0161 K8, rule 2). How many hits were dropped is - * logged, never returned. - */ - static async searchRound( - this: Pick, - query: string, - sources: SearchTarget[], - ask: (source: KnowledgeSource) => number, - filter: Record | undefined, - refused: KnowledgeSearchRefusal[], - ): Promise> { - const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding } of sources) { - // Refused like an adapter that cannot serve: the caller is told which - // source was not searched and why; the boot said so at `error` - // (`reportUnmountedAdapters`), so no line per search. The adapter was - // resolved once for the whole search ({@link planSearches}); a round - // searches that instance and never looks it up again. - if ('refusal' in binding) { - if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); - continue; - } - const { adapterId, adapter } = binding; - try { - const hits = await adapter.search(query, { - source, - topK: ask(source), - filter, - ...(organizationIds === undefined ? {} : { organizationIds }), - ...(fingerprint === undefined ? {} : { index: { fingerprint } }), - ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), - }); - // A hit is served as the source it was searched for. One whose - // `sourceId` names another source (an adapter answering from a store - // two sources share) is dropped: that source's admission was never - // asked for this hit, so serving it would skip the gates above. - const served: KnowledgeHit[] = []; - for (const hit of hits) if (hit.sourceId === source.name) served.push(hit); - const foreign = hits.length - served.length; - if (foreign > 0) { - this.options.logger?.warn?.( - `[knowledge] adapter '${adapterId}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + - 'another source; dropped — a hit is served only as the source it was searched for.', - ); - } - out.set(source.name, { - hits: scope === undefined ? served : this.checkScope(served, scope, source, adapterId), - answered: hits.length, + const plan = await this.planIndex(entry.source, adapter, chunkTarget); + if (proveIndex === true) { + const unproven = await this.unprovenIndex(plan); + if (unproven !== undefined) { + const label = this.label(entry.source); + refused.push({ + sourceId: entry.source.name, + code: INDEX_NOT_PROVEN_CODE, + status: 409, + message: `Knowledge source '${label}' is not searched: its index is not proven built under the current recipe. ` + + UNPROVEN_CALLER_TEXT[unproven.ends], }); - } catch (err) { - const coded = codedRefusalOf(err); - if (coded !== undefined) { - // The caller reads the code and the adapter's one-sentence message; - // the operator reads its remedy (the SQL to run, say) here. - refused.push({ sourceId: source.name, ...coded }); - this.options.logger?.warn?.( - `[knowledge] source '${this.label(source)}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, - ); - continue; - } - this.options.logger?.error?.( - `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, - ); - } - } - return out; - } - - /** - * [ADR-0161 K8, item 17] Pair each admitted source with the terms `scope` - * gives it ({@link scopeTermsFor}): a `record` term for an entry naming the - * object the source indexes, a `metadata` term for an entry naming a parent - * object the source reaches through the one parent link it lists in - * `metadataFields`, read from the object's registered definition. A source - * no entry reaches is not - * searched, logged at `debug`. A source that lists two or more parent links - * to an entry's object is not reached by that entry, reported once per - * source and object at `warn`, naming the fields. - */ - static sourcesInScope( - this: Pick, - sources: T[], - scope: readonly SearchScopeEntry[], - ): Array { - const out: Array = []; - for (const entry of sources) { - const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); - for (const { object, fields } of ambiguous) { - const key = `${entry.source.name}\u0000${object}`; - if (this.scopeAmbiguousReported.has(key)) continue; - this.scopeAmbiguousReported.add(key); this.options.logger?.warn?.( - `[knowledge] source '${this.label(entry.source)}' lists ${fields.length} fields pointing at '${object}' ` + - `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + - 'it is not told which field the scope means.', - ); - } - if (terms.length === 0) { - this.options.logger?.debug?.( - `[knowledge] source '${this.label(entry.source)}' not searched: no entry of the search's scope reaches it.`, + `[knowledge] source '${label}' not searched (${INDEX_NOT_PROVEN_CODE}): ${unproven.why} Its object declares ` + + "a field named 'title' the source does not serve, and a document indexed under the earlier title rule " + + "carries that field's value, so the source is searched only once its index is proven built under the " + + `current recipe. ${UNPROVEN_OPERATOR_TEXT[unproven.ends]}`, ); continue; } - out.push({ ...entry, scope: terms }); } - return out; + out.push({ + ...entry, + binding: { adapterId, adapter }, + fingerprint: plan.index.fingerprint, + ...(proveIndex === true ? { verifyHits: true as const } : {}), + }); } + return out; +} - /** - * Narrow each source's search to the records a non-system caller may read - * ({@link narrowToVisible}). Per source, the ids of the records it indexes - * that the caller may read are read first — as the caller, under the - * source's `where`, ids only, at most {@link SEARCH_VISIBLE_IDS_MAX} + 1 — - * once per object and `where` the search asks. When the caller may read no - * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a - * `record` term, intersected with the caller's own scope, so its adapter - * ranks only those rows and a narrow caller's answers are not crowded out of - * the refill cap by rows they could never be served. - * - * A source is searched as before — on the caller's own scope, its hits - * re-checked within the refill cap — when the caller may read more than - * that, when the caller's scope holds a parent (`metadata`) term, when the - * narrowing names no record (the caller may read none of what the source - * could answer: answered as before, no hit or the source's refusal, never a - * new kind of empty), or when the read fails (logged at `warn`). Nothing here decides access: every hit is - * still re-checked as the caller ({@link applyPermissionFilter}), and the - * organization filter each source carries is not touched. - */ - static async sourcesNarrowedToVisible( - this: Pick, - sources: T[], - ctx: ExecutionContext, - engine: IDataEngine, - ): Promise { - const reads = new Map>(); - const visibleOf = (objSource: ObjectKnowledgeSource): Promise => { - const key = JSON.stringify([objSource.object, objSource.where ?? null]); - let read = reads.get(key); - if (read === undefined) { - read = this.readVisibleIds(objSource, ctx, engine); - reads.set(key, read); - } - return read; +/** + * Why `plan`'s source is not proven built under the current recipe, and + * what ends it, or `undefined` when it is proven: its adapter's + * `indexStatus` reports the fingerprint AND the recipe hash + * {@link planIndex} computes now, and the builds that record that hash + * purge what they did not walk. + * + * The recipe hash names the title rule (ADR-0161 K7), and an adapter + * records it only at `completeBuild`, the end of a complete build. A + * complete build rewrites every document whose title changed (`docHash` + * covers the title) and, when it purges, removes every document it did not + * walk. It does not purge, and still records the hash, for a source with + * `refresh.onRecordChange: false` and on an adapter with no + * `listDocuments` ({@link walkObjectSource}): a document it did not walk, + * such as one whose row left the source's `where`, keeps what it was + * assembled with. So those two shapes are never proven, before any read, + * whatever the hash reads; nor is an adapter with no `indexStatus` (nothing + * to read) or no `completeBuild` (nothing ever records a hash). + * + * The proof covers what the last complete build walked and purged. Read on + * every search that needs it, never cached: another node may rebuild, or + * drop, the index. Fails closed: a status that throws is not proven. + */ +export async function unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { + const { adapter, index, source } = plan; + if ((source.refresh?.onRecordChange ?? true) === false) { + return { + ends: 'never', + why: + 'refresh.onRecordChange is false, so an external indexer owns its index: a build of it purges nothing, ' + + 'so a recorded recipe hash does not prove the index holds no document assembled under an earlier recipe.', }; - const visible = sources.map((entry) => - entry.scope?.some((term) => term.kind !== 'record') === true - ? Promise.resolve(undefined) - : visibleOf(entry.source.source)); - const out: T[] = []; - for (const [i, entry] of sources.entries()) { - const ids = await visible[i]; - const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); - // A narrowing that names no record is not applied: the source is - // searched as before, so a caller who may read none of its records is - // answered as before too — no hit, or the source's refusal. - if (narrowed === undefined || narrowed.every((term) => term.ids.length === 0)) { - out.push(entry); - continue; - } - out.push({ ...entry, scope: narrowed }); - } - return out; } + if (typeof adapter.indexStatus !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' reports no index status (no indexStatus), so what its index was built under cannot be read.`, + }; + } + if (typeof adapter.completeBuild !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' has no completeBuild, so no build records a recipe hash for its index.`, + }; + } + if (typeof adapter.listDocuments !== 'function') { + return { + ends: 'never', + why: + `the adapter '${adapter.id}' does not list its documents (no listDocuments), so a complete build cannot purge a ` + + 'document it did not walk, and a recorded recipe hash does not prove the index holds none assembled under an ' + + 'earlier recipe.', + }; + } + let held: AdapterIndexStatus; + try { + held = await adapter.indexStatus(plan.context('search')); + } catch (err) { + return { ends: 'unreadable', why: `the adapter's index status could not be read (${operatorText(err)}).` }; + } + if (held?.fingerprint !== index.fingerprint) { + return { ends: 'rebuild', why: 'the index holds no complete build under the current fingerprint.' }; + } + if (held.recipeHash !== index.recipeHash) { + return { + ends: 'rebuild', + why: held.recipeHash === undefined + ? 'the index records no recipe hash: no complete build of it has completed.' + : "the index was last completed under another recipe (the source's where, metadataFields, title rule or withheld fields).", + }; + } + return undefined; +} - /** - * The ids of the records of `objSource` the caller may read, read as the - * caller under the source's `where`; `undefined` when there are more than - * {@link SEARCH_VISIBLE_IDS_MAX} or the read fails. - */ - static async readVisibleIds( - this: Pick, - objSource: ObjectKnowledgeSource, - ctx: ExecutionContext, - engine: IDataEngine, - ): Promise { - let rows: unknown; +/** + * One round of {@link search}: ask each source's adapter for `ask(source)` + * hits. Answers, per source that answered, the hits it serves and how many + * the adapter returned (`answered`, before a hit naming another source or + * outside the scope is dropped — what decides whether the adapter may hold + * more). A source whose adapter is unknown or throws is absent from the + * answer: a coded refusal (ADR-0112 `code` and `status`) is added to + * `refused`, anything else is logged. + * + * Under a scope, the adapter is handed the source's terms, and every hit it + * answers is checked against them ({@link scopeCheck}, fail closed). The first + * time the check drops a hit of an adapter, that is reported once for the + * adapter, at `warn`: it does not apply the scope before ranking, or answers + * hits without the document's metadata, so its scoped searches may answer + * fewer than `topK` (ADR-0161 K8, rule 2). How many hits were dropped is + * logged, never returned. + */ +export async function searchRound( + this: Pick, + query: string, + sources: SearchTarget[], + ask: (source: KnowledgeSource) => number, + filter: Record | undefined, + refused: KnowledgeSearchRefusal[], +): Promise> { + const out = new Map(); + for (const { source, organizationIds, fingerprint, scope, binding } of sources) { + // Refused like an adapter that cannot serve: the caller is told which + // source was not searched and why; the boot said so at `error` + // (`reportUnmountedAdapters`), so no line per search. The adapter was + // resolved once for the whole search ({@link planSearches}); a round + // searches that instance and never looks it up again. + if ('refusal' in binding) { + if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); + continue; + } + const { adapterId, adapter } = binding; try { - // As the caller, in the query, as the permission re-read asks. - rows = await engine.find(objSource.object, { - ...(objSource.where === undefined ? {} : { where: objSource.where }), - fields: ['id'], - limit: SEARCH_VISIBLE_IDS_MAX + 1, - context: ctx, - } as never); - if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + const hits = await adapter.search(query, { + source, + topK: ask(source), + filter, + ...(organizationIds === undefined ? {} : { organizationIds }), + ...(fingerprint === undefined ? {} : { index: { fingerprint } }), + ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), + }); + // A hit is served as the source it was searched for. One whose + // `sourceId` names another source (an adapter answering from a store + // two sources share) is dropped: that source's admission was never + // asked for this hit, so serving it would skip the gates above. + const served: KnowledgeHit[] = []; + for (const hit of hits) if (hit.sourceId === source.name) served.push(hit); + const foreign = hits.length - served.length; + if (foreign > 0) { + this.options.logger?.warn?.( + `[knowledge] adapter '${adapterId}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + + 'another source; dropped — a hit is served only as the source it was searched for.', + ); + } + out.set(source.name, { + hits: scope === undefined ? served : this.checkScope(served, scope, source, adapterId), + answered: hits.length, + }); } catch (err) { - this.options.logger?.warn?.( - `[knowledge] the caller's readable records of object='${objSource.object}' could not be read ` + - `(${errorText(err)}); its sources are searched unnarrowed, every hit re-checked.`, + const coded = codedRefusalOf(err); + if (coded !== undefined) { + // The caller reads the code and the adapter's one-sentence message; + // the operator reads its remedy (the SQL to run, say) here. + refused.push({ sourceId: source.name, ...coded }); + this.options.logger?.warn?.( + `[knowledge] source '${this.label(source)}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, + ); + continue; + } + this.options.logger?.error?.( + `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, ); - return undefined; } - if (rows.length > SEARCH_VISIBLE_IDS_MAX) return undefined; - const ids: string[] = []; - for (const row of rows as Array<{ id?: unknown } | null | undefined>) { - const id = row?.id; - if ((typeof id === 'string' && id.length > 0) || typeof id === 'number') ids.push(String(id)); - } - return ids; } + return out; +} - /** - * The hits of `source` that some scope term holds for ({@link scopeCheck}); - * the rest are dropped, and the first time an adapter's answer loses a hit - * here it is reported once, at `warn` ({@link searchRound}). - */ - static checkScope( - this: Pick, - hits: KnowledgeHit[], - terms: readonly AdapterScopeTerm[], - source: KnowledgeSource, - adapterId: string, - ): KnowledgeHit[] { - const inScope = scopeCheck(terms); - const kept = hits.filter(inScope); - const dropped = hits.length - kept.length; - if (dropped > 0 && !this.scopeIgnoredReported.has(adapterId)) { - this.scopeIgnoredReported.add(adapterId); +/** + * [ADR-0161 K8, item 17] Pair each admitted source with the terms `scope` + * gives it ({@link scopeTermsFor}): a `record` term for an entry naming the + * object the source indexes, a `metadata` term for an entry naming a parent + * object the source reaches through the one parent link it lists in + * `metadataFields`, read from the object's registered definition. A source + * no entry reaches is not + * searched, logged at `debug`. A source that lists two or more parent links + * to an entry's object is not reached by that entry, reported once per + * source and object at `warn`, naming the fields. + */ +export function sourcesInScope( + this: Pick, + sources: T[], + scope: readonly SearchScopeEntry[], +): Array { + const out: Array = []; + for (const entry of sources) { + const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); + for (const { object, fields } of ambiguous) { + const key = `${entry.source.name}\u0000${object}`; + if (this.scopeAmbiguousReported.has(key)) continue; + this.scopeAmbiguousReported.add(key); this.options.logger?.warn?.( - `[knowledge] adapter '${adapterId}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + - "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + - "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + - 'Reported once for this adapter.', + `[knowledge] source '${this.label(entry.source)}' lists ${fields.length} fields pointing at '${object}' ` + + `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + + 'it is not told which field the scope means.', ); } - return kept; + if (terms.length === 0) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' not searched: no entry of the search's scope reaches it.`, + ); + continue; + } + out.push({ ...entry, scope: terms }); } + return out; +} - /** - * The sources a search asks: every source whose `aiExposed` is not `false`, - * or the ones `sourceIds` names — each read by the one rule, so a name - * several sources have refuses the search (`409 RESOURCE_CONFLICT`) and a - * name none has is skipped, reported at `warn`. - */ - static resolveSearchTargets( - this: Pick, - sourceIds?: string[], - ): KnowledgeSource[] { - if (!sourceIds || sourceIds.length === 0) { - return this.handedSources().filter((s) => s.aiExposed !== false); +/** + * Narrow each source's search to the records a non-system caller may read + * ({@link narrowToVisible}). Per source, the ids of the records it indexes + * that the caller may read are read first — as the caller, under the + * source's `where`, ids only, at most {@link SEARCH_VISIBLE_IDS_MAX} + 1 — + * once per object and `where` the search asks. When the caller may read no + * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a + * `record` term, intersected with the caller's own scope, so its adapter + * ranks only those rows and a narrow caller's answers are not crowded out of + * the refill cap by rows they could never be served. + * + * A source is searched as before — on the caller's own scope, its hits + * re-checked within the refill cap — when the caller may read more than + * that, when the caller's scope holds a parent (`metadata`) term, when the + * narrowing names no record (the caller may read none of what the source + * could answer: answered as before, no hit or the source's refusal, never a + * new kind of empty), or when the read fails (logged at `warn`). Nothing here decides access: every hit is + * still re-checked as the caller ({@link applyPermissionFilter}), and the + * organization filter each source carries is not touched. + */ +export async function sourcesNarrowedToVisible( + this: Pick, + sources: T[], + ctx: ExecutionContext, + engine: IDataEngine, +): Promise { + const reads = new Map>(); + const visibleOf = (objSource: ObjectKnowledgeSource): Promise => { + const key = JSON.stringify([objSource.object, objSource.where ?? null]); + let read = reads.get(key); + if (read === undefined) { + read = this.readVisibleIds(objSource, ctx, engine); + reads.set(key, read); } - const out = new Map(); - for (const id of sourceIds) { - const entry = this.registry.resolve(id); - if (entry) out.set(entry.key, entry.handed); - else this.options.logger?.warn?.(`[knowledge] search target '${id}' not registered; skipping.`); + return read; + }; + const visible = sources.map((entry) => + entry.scope?.some((term) => term.kind !== 'record') === true + ? Promise.resolve(undefined) + : visibleOf(entry.source.source)); + const out: T[] = []; + for (const [i, entry] of sources.entries()) { + const ids = await visible[i]; + const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); + // A narrowing that names no record is not applied: the source is + // searched as before, so a caller who may read none of its records is + // answered as before too — no hit, or the source's refusal. + if (narrowed === undefined || narrowed.every((term) => term.ids.length === 0)) { + out.push(entry); + continue; } - return [...out.values()]; + out.push({ ...entry, scope: narrowed }); + } + return out; +} + +/** + * The ids of the records of `objSource` the caller may read, read as the + * caller under the source's `where`; `undefined` when there are more than + * {@link SEARCH_VISIBLE_IDS_MAX} or the read fails. + */ +export async function readVisibleIds( + this: Pick, + objSource: ObjectKnowledgeSource, + ctx: ExecutionContext, + engine: IDataEngine, +): Promise { + let rows: unknown; + try { + // As the caller, in the query, as the permission re-read asks. + rows = await engine.find(objSource.object, { + ...(objSource.where === undefined ? {} : { where: objSource.where }), + fields: ['id'], + limit: SEARCH_VISIBLE_IDS_MAX + 1, + context: ctx, + } as never); + if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the caller's readable records of object='${objSource.object}' could not be read ` + + `(${errorText(err)}); its sources are searched unnarrowed, every hit re-checked.`, + ); + return undefined; + } + if (rows.length > SEARCH_VISIBLE_IDS_MAX) return undefined; + const ids: string[] = []; + for (const row of rows as Array<{ id?: unknown } | null | undefined>) { + const id = row?.id; + if ((typeof id === 'string' && id.length > 0) || typeof id === 'number') ids.push(String(id)); + } + return ids; +} + +/** + * The hits of `source` that some scope term holds for ({@link scopeCheck}); + * the rest are dropped, and the first time an adapter's answer loses a hit + * here it is reported once, at `warn` ({@link searchRound}). + */ +export function checkScope( + this: Pick, + hits: KnowledgeHit[], + terms: readonly AdapterScopeTerm[], + source: KnowledgeSource, + adapterId: string, +): KnowledgeHit[] { + const inScope = scopeCheck(terms); + const kept = hits.filter(inScope); + const dropped = hits.length - kept.length; + if (dropped > 0 && !this.scopeIgnoredReported.has(adapterId)) { + this.scopeIgnoredReported.add(adapterId); + this.options.logger?.warn?.( + `[knowledge] adapter '${adapterId}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + + "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + + "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + + 'Reported once for this adapter.', + ); + } + return kept; +} + +/** + * The sources a search asks: every source whose `aiExposed` is not `false`, + * or the ones `sourceIds` names — each read by the one rule, so a name + * several sources have refuses the search (`409 RESOURCE_CONFLICT`) and a + * name none has is skipped, reported at `warn`. + */ +export function resolveSearchTargets( + this: Pick, + sourceIds?: string[], +): KnowledgeSource[] { + if (!sourceIds || sourceIds.length === 0) { + return this.handedSources().filter((s) => s.aiExposed !== false); + } + const out = new Map(); + for (const id of sourceIds) { + const entry = this.registry.resolve(id); + if (entry) out.set(entry.key, entry.handed); + else this.options.logger?.warn?.(`[knowledge] search target '${id}' not registered; skipping.`); } + return [...out.values()]; } diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index 7659c9aaa0a..ab24a10728a 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -10,21 +10,23 @@ * `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry`, moved * out of `knowledge-service.ts` whole. * - * A MOVE, not a redesign. {@link KnowledgeSourcesFacet} is a stateless facet of - * `KnowledgeService`: each static method is the body of the `KnowledgeService` - * member of the same name exactly as it stood (not re-indented, not edited). - * The member stays on the class as a one-call stub with its signature, so the - * published declaration, an instance spy and a subclass override are what they - * were. A public member keeps its docblock on the class, the contract; a - * private member's docblock moved here with its body. The state stays on - * `KnowledgeService`. + * A MOVE, not a redesign. Each function below is the body of the + * `KnowledgeService` member of the same name as it stood, re-indented one + * level and otherwise unedited (a line inside a string or template literal + * keeps its bytes). The member stays on the class as a one-call stub with its + * signature, so the published declaration, an instance spy and a subclass + * override are what they were; the class imports this module as + * `KnowledgeSourcesFacet`. A public member keeps its docblock on the class, the + * contract; a private member's docblock moved here with its body. The state + * stays on `KnowledgeService`. * * A body reaches the service through `this`, typed as the part of - * {@link KnowledgeServiceHost} it reads (`knowledge-service-host.ts`): the stub hands - * it the host the class's static block builds once per service, whose methods call - * the service at call time and whose fields are getters (and a setter for a - * field a body assigns). A body that reads nothing of the service is called - * without one. `index.ts` re-exports nothing from this module. + * {@link KnowledgeSourcesHost} it reads: the stub hands it the host the class's static + * block builds once per service (`knowledge-service-host.ts`), whose methods call the + * service at call time and whose fields are getters (and a setter for a field + * a body assigns). A body that reads nothing of the service is called without + * one. The module imports `knowledge-service.ts` for types only, so the two + * form no evaluation cycle. `index.ts` re-exports nothing from this module. */ import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; @@ -48,318 +50,366 @@ import { unmountedAdapterError, unplacedSourceError, } from './knowledge-service-top-level.js'; -import type { KnowledgeServiceHost } from './knowledge-service-host.js'; +import type { KnowledgeService } from './knowledge-service.js'; -export class KnowledgeSourcesFacet { - static settleEnablement( - this: Pick, - held: KnowledgeHeldReading | undefined, - ): void { - this.enablementPending = false; - this.held = held; - if (!held) return; - for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); - } +/** + * The `KnowledgeService` members the bodies in this module read: every one + * of them, and no other. Each is typed AS the class member (an indexed + * access on the class), so a change to a member's type on the class is a change + * here too, and a name the class does not have does not compile. `readonly` + * members are methods and fields no body here assigns; the others are fields a + * body here assigns. + */ +export interface KnowledgeSourcesHost { + readonly adapterIdFor: KnowledgeService['adapterIdFor']; + readonly adapterLabel: KnowledgeService['adapterLabel']; + readonly adapters: KnowledgeService['adapters']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; + readonly builds: KnowledgeService['builds']; + readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; + readonly describeSources: KnowledgeService['describeSources']; + enablementPending: KnowledgeService['enablementPending']; + readonly forget: KnowledgeService['forget']; + held: KnowledgeService['held']; + readonly label: KnowledgeService['label']; + readonly listAdapters: KnowledgeService['listAdapters']; + readonly options: KnowledgeService['options']; + readonly pendingReconciles: KnowledgeService['pendingReconciles']; + readonly reconcileUnlistedReported: KnowledgeService['reconcileUnlistedReported']; + readonly refuseUnplacedSource: KnowledgeService['refuseUnplacedSource']; + readonly registry: KnowledgeService['registry']; + readonly sourceListeners: KnowledgeService['sourceListeners']; + readonly sourcesChanged: KnowledgeService['sourcesChanged']; + readonly syncStateRecorded: KnowledgeService['syncStateRecorded']; + readonly syncStateWriteFailed: KnowledgeService['syncStateWriteFailed']; + readonly whereUnenforceableReported: KnowledgeService['whereUnenforceableReported']; +} - static registerAdapter( - this: Pick, - id: string, - adapter: IKnowledgeAdapter, - ): void { - this.adapters.set(id, adapter); - this.options.logger?.info?.(`[knowledge] adapter registered: ${id}`); - } +/** The body of {@link KnowledgeService.settleEnablement}; the member's docblock there is its contract. */ +export function settleEnablement( + this: Pick, + held: KnowledgeHeldReading | undefined, +): void { + this.enablementPending = false; + this.held = held; + if (!held) return; + for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); +} - static getAdapter(this: Pick, id: string): IKnowledgeAdapter { - const adapter = this.adapters.get(id); - if (!adapter) throw unmountedAdapterError(id, this.listAdapters()); - return adapter; - } +/** The body of {@link KnowledgeService.registerAdapter}; the member's docblock there is its contract. */ +export function registerAdapter( + this: Pick, + id: string, + adapter: IKnowledgeAdapter, +): void { + this.adapters.set(id, adapter); + this.options.logger?.info?.(`[knowledge] adapter registered: ${id}`); +} - static adapterIdFor( - this: Pick, - source: KnowledgeSource, - ): string { - if (source.adapter !== undefined) return source.adapter; - const deployment = this.options.deploymentAdapter; - if (deployment !== undefined && this.adapters.has(deployment)) return deployment; - const registered = this.listAdapters(); - if (registered.length === 1) return registered[0]!; - if (registered.length === 0) throw noAdapterMountedError(this.label(source), deployment); - throw unplacedSourceError(this.label(source), registered); - } +/** The body of {@link KnowledgeService.getAdapter}; the member's docblock there is its contract. */ +export function getAdapter(this: Pick, id: string): IKnowledgeAdapter { + const adapter = this.adapters.get(id); + if (!adapter) throw unmountedAdapterError(id, this.listAdapters()); + return adapter; +} - static boundAdapterId(this: Pick, source: KnowledgeSource): string | undefined { - try { - return this.adapterIdFor(source); - } catch { - return undefined; - } - } +/** The body of {@link KnowledgeService.adapterIdFor}; the member's docblock there is its contract. */ +export function adapterIdFor( + this: Pick, + source: KnowledgeSource, +): string { + if (source.adapter !== undefined) return source.adapter; + const deployment = this.options.deploymentAdapter; + if (deployment !== undefined && this.adapters.has(deployment)) return deployment; + const registered = this.listAdapters(); + if (registered.length === 1) return registered[0]!; + if (registered.length === 0) throw noAdapterMountedError(this.label(source), deployment); + throw unplacedSourceError(this.label(source), registered); +} - /** - * Refuse, at registration, a source that names no adapter where the answer - * cannot become one: several adapters are registered and the runtime marked - * none the deployment's (ADR-0161 K4 ◆). With a mark, or with one adapter - * or none registered yet, the source is taken and placed where it is used: - * a store registers in its own `start()`, after a source registered at - * `init()`, so "none yet" is no verdict (AGENTS.md, startup registry reads). - */ - static refuseUnplacedSource( - this: Pick, - source: KnowledgeSource, - door: string, - ): void { - if (source.adapter !== undefined || this.options.deploymentAdapter !== undefined) return; - const registered = this.listAdapters(); - if (registered.length < 2) return; - throw unplacedSourceError(source.name, registered, ` ${door} did not register it.`); +/** The body of {@link KnowledgeService.boundAdapterId}; the member's docblock there is its contract. */ +export function boundAdapterId( + this: Pick, + source: KnowledgeSource, +): string | undefined { + try { + return this.adapterIdFor(source); + } catch { + return undefined; } +} - static reportUnmountedAdapters( - this: Pick, - ): string[] { - const mounted = this.listAdapters(); - const named: string[] = []; - for (const { id, source } of this.describeSources()) { - if (source.adapter === undefined) { - // [ADR-0161 K4 ◆] A source that names no adapter, which this boot - // cannot place: no adapter at all, or several and none the deployment's. - try { - this.adapterIdFor(source); - } catch (err) { - this.options.logger?.error?.(`${errorText(err)} Indexing and searching it answer that refusal.`); - named.push(id); - } - continue; +/** + * Refuse, at registration, a source that names no adapter where the answer + * cannot become one: several adapters are registered and the runtime marked + * none the deployment's (ADR-0161 K4 ◆). With a mark, or with one adapter + * or none registered yet, the source is taken and placed where it is used: + * a store registers in its own `start()`, after a source registered at + * `init()`, so "none yet" is no verdict (AGENTS.md, startup registry reads). + */ +export function refuseUnplacedSource( + this: Pick, + source: KnowledgeSource, + door: string, +): void { + if (source.adapter !== undefined || this.options.deploymentAdapter !== undefined) return; + const registered = this.listAdapters(); + if (registered.length < 2) return; + throw unplacedSourceError(source.name, registered, ` ${door} did not register it.`); +} + +/** The body of {@link KnowledgeService.reportUnmountedAdapters}; the member's docblock there is its contract. */ +export function reportUnmountedAdapters( + this: Pick, +): string[] { + const mounted = this.listAdapters(); + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.adapter === undefined) { + // [ADR-0161 K4 ◆] A source that names no adapter, which this boot + // cannot place: no adapter at all, or several and none the deployment's. + try { + this.adapterIdFor(source); + } catch (err) { + this.options.logger?.error?.(`${errorText(err)} Indexing and searching it answer that refusal.`); + named.push(id); } - if (this.adapters.has(source.adapter)) continue; - this.options.logger?.error?.( - `[knowledge] source '${id}' names adapter '${source.adapter}', which is not mounted ` + - `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). Indexing and searching it answer ` + - `${UNMOUNTED_ADAPTER_CODE} until its adapter is one of those, or the '${source.adapter}' store is mounted.`, - ); - named.push(id); + continue; } - return named; + if (this.adapters.has(source.adapter)) continue; + this.options.logger?.error?.( + `[knowledge] source '${id}' names adapter '${source.adapter}', which is not mounted ` + + `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). Indexing and searching it answer ` + + `${UNMOUNTED_ADAPTER_CODE} until its adapter is one of those, or the '${source.adapter}' store is mounted.`, + ); + named.push(id); } + return named; +} - static listAdapters(this: Pick): string[] { - return [...this.adapters.keys()]; - } +/** The body of {@link KnowledgeService.listAdapters}; the member's docblock there is its contract. */ +export function listAdapters(this: Pick): string[] { + return [...this.adapters.keys()]; +} - static registerSource( - this: Pick< - KnowledgeServiceHost, - 'adapterLabel' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' - >, - source: KnowledgeSource, - ): void { - const parsed = parseKnowledgeSource(source); - if (!parsed.ok) { - throw codedError( - 'VALIDATION_ERROR', - 400, - `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, - ); - } - this.refuseUnplacedSource(parsed.source, 'registerSource'); - const packageId = packageIdOfItem(parsed.source); - if (packageId !== undefined) { - throw codedError( - 'VALIDATION_ERROR', - 400, - `[knowledge] registerSource refused source '${parsed.source.name}': it names package "${packageId}" ` + - '(`_packageId`), and a source registered in code belongs to no package. Ship the source in that ' + - "package's `knowledgeSources` collection, or drop the key.", - ); - } - const { entry, replaced } = this.registry.register(parsed.source, 'code'); - if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); - this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${this.adapterLabel(entry.authored)})`); - this.sourcesChanged(); +/** The body of {@link KnowledgeService.registerSource}; the member's docblock there is its contract. */ +export function registerSource( + this: Pick, + source: KnowledgeSource, +): void { + const parsed = parseKnowledgeSource(source); + if (!parsed.ok) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, + ); } - - static registerMetadataSource( - this: Pick< - KnowledgeServiceHost, - 'adapterLabel' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' - >, - source: KnowledgeSource, - holder: KnowledgeSourceHolder = {}, - ): KnowledgeSourceEntry { - this.refuseUnplacedSource(source, 'The knowledge_source loader'); - const { entry, replaced } = this.registry.register(source, 'metadata', holder); - this.options.logger?.info?.( - `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + - `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, + this.refuseUnplacedSource(parsed.source, 'registerSource'); + const packageId = packageIdOfItem(parsed.source); + if (packageId !== undefined) { + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] registerSource refused source '${parsed.source.name}': it names package "${packageId}" ` + + '(`_packageId`), and a source registered in code belongs to no package. Ship the source in that ' + + "package's `knowledgeSources` collection, or drop the key.", ); - this.sourcesChanged(); - return entry; } + const { entry, replaced } = this.registry.register(parsed.source, 'code'); + if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); + this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${this.adapterLabel(entry.authored)})`); + this.sourcesChanged(); +} - static metadataSources(this: Pick): KnowledgeSourceEntry[] { - return this.registry.entries().filter((entry) => entry.door === 'metadata'); - } +/** The body of {@link KnowledgeService.registerMetadataSource}; the member's docblock there is its contract. */ +export function registerMetadataSource( + this: Pick, + source: KnowledgeSource, + holder: KnowledgeSourceHolder = {}, +): KnowledgeSourceEntry { + this.refuseUnplacedSource(source, 'The knowledge_source loader'); + const { entry, replaced } = this.registry.register(source, 'metadata', holder); + this.options.logger?.info?.( + `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + + `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, + ); + this.sourcesChanged(); + return entry; +} - static onSourcesChanged(this: Pick, listener: () => void): () => void { - this.sourceListeners.add(listener); - return () => { - this.sourceListeners.delete(listener); - }; - } +/** The body of {@link KnowledgeService.metadataSources}; the member's docblock there is its contract. */ +export function metadataSources(this: Pick): KnowledgeSourceEntry[] { + return this.registry.entries().filter((entry) => entry.door === 'metadata'); +} - static sourcesChanged(this: Pick): void { - for (const listener of [...this.sourceListeners]) { - try { - listener(); - } catch (err) { - this.options.logger?.warn?.(`[knowledge] a source-change listener failed (${errorText(err)}).`); - } +/** The body of {@link KnowledgeService.onSourcesChanged}; the member's docblock there is its contract. */ +export function onSourcesChanged(this: Pick, listener: () => void): () => void { + this.sourceListeners.add(listener); + return () => { + this.sourceListeners.delete(listener); + }; +} + +/** The body of {@link KnowledgeService.sourcesChanged}; the member's docblock there is its contract. */ +export function sourcesChanged(this: Pick): void { + for (const listener of [...this.sourceListeners]) { + try { + listener(); + } catch (err) { + this.options.logger?.warn?.(`[knowledge] a source-change listener failed (${errorText(err)}).`); } } +} - static unregisterSource(this: Pick, sourceId: string): void { - const entry = this.registry.resolve(sourceId); - if (!entry) return; - if (entry.door === 'metadata') { - throw codedError( - 'RESOURCE_CONFLICT', - 409, - `[knowledge] source '${entry.face}' is a knowledge_source metadata item, so unregisterSource does not remove ` + - 'it: delete the item (Studio, the metadata API, or its package), and the knowledge service unregisters it ' + - 'and drops its index.', - ); - } - this.forget(entry); +/** The body of {@link KnowledgeService.unregisterSource}; the member's docblock there is its contract. */ +export function unregisterSource(this: Pick, sourceId: string): void { + const entry = this.registry.resolve(sourceId); + if (!entry) return; + if (entry.door === 'metadata') { + throw codedError( + 'RESOURCE_CONFLICT', + 409, + `[knowledge] source '${entry.face}' is a knowledge_source metadata item, so unregisterSource does not remove ` + + 'it: delete the item (Studio, the metadata API, or its package), and the knowledge service unregisters it ' + + 'and drops its index.', + ); } + this.forget(entry); +} - static async dropMetadataSource( - this: Pick< - KnowledgeServiceHost, - 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'forget' | 'held' | 'options' | 'registry' | - 'syncStateWriteFailed' - >, - key: string, - ): Promise { - const entry = this.registry.byIndexKey(key); - if (!entry || entry.door !== 'metadata') return undefined; - // Placed before the entry is forgotten: an unnamed adapter is placed - // among the adapters registered now, as every other use places it. - const adapterId = this.boundAdapterId(entry.handed); - this.forget(entry); - // The source's sync-state row goes with it (whatever its index does). - const store = this.options.syncState; - if (store) { - try { - await store.remove(entry.key); - } catch (err) { - this.syncStateWriteFailed(`the sync-state row of removed source '${entry.face}' could not be removed`, err); - } - } - const kept = (why: string): void => { - this.options.logger?.warn?.( - `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + - `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, - ); - }; - if (this.held) { - kept('the knowledge service is not enabled at this boot, so no store is called.'); - return entry; - } - const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); - if (!adapter) { - kept( - adapterId === undefined - ? 'it names no adapter, and none could be placed for it.' - : `adapter '${adapterId}' is not mounted.`, - ); - return entry; - } - if (typeof adapter.dropSource !== 'function') { - kept(`adapter '${adapterId}' has no dropSource.`); - return entry; - } +/** The body of {@link KnowledgeService.dropMetadataSource}; the member's docblock there is its contract. */ +export async function dropMetadataSource( + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'forget' | 'held' | 'options' | 'registry' | + 'syncStateWriteFailed' + >, + key: string, +): Promise { + const entry = this.registry.byIndexKey(key); + if (!entry || entry.door !== 'metadata') return undefined; + // Placed before the entry is forgotten: an unnamed adapter is placed + // among the adapters registered now, as every other use places it. + const adapterId = this.boundAdapterId(entry.handed); + this.forget(entry); + // The source's sync-state row goes with it (whatever its index does). + const store = this.options.syncState; + if (store) { try { - await adapter.dropSource({ source: entry.handed, reason: 'manual' }); - this.options.logger?.info?.(`[knowledge] source '${entry.face}' was removed and its index dropped.`); + await store.remove(entry.key); } catch (err) { - kept(`dropSource failed (${operatorText(err)}).`); + this.syncStateWriteFailed(`the sync-state row of removed source '${entry.face}' could not be removed`, err); } + } + const kept = (why: string): void => { + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + + `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, + ); + }; + if (this.held) { + kept('the knowledge service is not enabled at this boot, so no store is called.'); return entry; } - - /** Remove `entry` and what this node remembers of it. */ - static forget( - this: Pick< - KnowledgeServiceHost, - 'builds' | 'cancelPendingReconcile' | 'reconcileUnlistedReported' | 'registry' | 'sourcesChanged' | - 'syncStateRecorded' | 'whereUnenforceableReported' - >, - entry: KnowledgeSourceEntry, - ): void { - this.registry.remove(entry.key); - this.builds.delete(entry.key); - this.syncStateRecorded.delete(entry.key); - this.whereUnenforceableReported.delete(entry.key); - this.reconcileUnlistedReported.delete(entry.key); - this.cancelPendingReconcile(entry.key); - this.sourcesChanged(); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (!adapter) { + kept( + adapterId === undefined + ? 'it names no adapter, and none could be placed for it.' + : `adapter '${adapterId}' is not mounted.`, + ); + return entry; } - - static listSources(this: Pick): KnowledgeSource[] { - return this.registry.entries().map((entry) => entry.authored); + if (typeof adapter.dropSource !== 'function') { + kept(`adapter '${adapterId}' has no dropSource.`); + return entry; } - - static describeSources(this: Pick): KnowledgeSourceDescription[] { - return this.registry.entries().map(describeEntry); + try { + await adapter.dropSource({ source: entry.handed, reason: 'manual' }); + this.options.logger?.info?.(`[knowledge] source '${entry.face}' was removed and its index dropped.`); + } catch (err) { + kept(`dropSource failed (${operatorText(err)}).`); } + return entry; +} - static getSource(this: Pick, sourceId: string): KnowledgeSource | undefined { - return this.registry.resolve(sourceId)?.authored; - } +/** Remove `entry` and what this node remembers of it. */ +export function forget( + this: Pick< + KnowledgeSourcesHost, + 'builds' | 'cancelPendingReconcile' | 'reconcileUnlistedReported' | 'registry' | 'sourcesChanged' | + 'syncStateRecorded' | 'whereUnenforceableReported' + >, + entry: KnowledgeSourceEntry, +): void { + this.registry.remove(entry.key); + this.builds.delete(entry.key); + this.syncStateRecorded.delete(entry.key); + this.whereUnenforceableReported.delete(entry.key); + this.reconcileUnlistedReported.delete(entry.key); + this.cancelPendingReconcile(entry.key); + this.sourcesChanged(); +} - static describeSource( - this: Pick, - sourceId: string, - ): KnowledgeSourceDescription | undefined { - const entry = this.registry.resolve(sourceId); - return entry ? describeEntry(entry) : undefined; - } +/** The body of {@link KnowledgeService.listSources}; the member's docblock there is its contract. */ +export function listSources(this: Pick): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.authored); +} - /** The handed source held under an index key. */ - static handed(this: Pick, key: string): KnowledgeSource | undefined { - return this.registry.byIndexKey(key)?.handed; - } +/** The body of {@link KnowledgeService.describeSources}; the member's docblock there is its contract. */ +export function describeSources(this: Pick): KnowledgeSourceDescription[] { + return this.registry.entries().map(describeEntry); +} - static handedSources(this: Pick): KnowledgeSource[] { - return this.registry.entries().map((entry) => entry.handed); - } +/** The body of {@link KnowledgeService.getSource}; the member's docblock there is its contract. */ +export function getSource(this: Pick, sourceId: string): KnowledgeSource | undefined { + return this.registry.resolve(sourceId)?.authored; +} - /** How a log line names a source's adapter: the one it names, else the one it is placed on now. */ - static adapterLabel(this: Pick, source: KnowledgeSource): string { - if (source.adapter !== undefined) return source.adapter; - const placed = this.boundAdapterId(source); - return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; - } +/** The body of {@link KnowledgeService.describeSource}; the member's docblock there is its contract. */ +export function describeSource( + this: Pick, + sourceId: string, +): KnowledgeSourceDescription | undefined { + const entry = this.registry.resolve(sourceId); + return entry ? describeEntry(entry) : undefined; +} - static faceOfKey(this: Pick, key: string): string { - return this.registry.byIndexKey(key)?.face ?? key; - } +/** The handed source held under an index key. */ +export function handed(this: Pick, key: string): KnowledgeSource | undefined { + return this.registry.byIndexKey(key)?.handed; +} - /** - * The registered source `sourceId` names, read by the one rule - * (`KnowledgeSourceRegistry.resolve`): its face, else a bare name by - * ADR-0150 D3. Throws for a name no source has, listing the registered - * faces, and `409 RESOURCE_CONFLICT` for one that names several. - */ - static requireEntry(this: Pick, sourceId: string): KnowledgeSourceEntry { - const entry = this.registry.resolve(sourceId); - if (!entry) { - throw new Error( - `[knowledge] unknown source '${sourceId}'. Registered: [${this.registry.entries().map((e) => e.face).join(', ')}]`, - ); - } - return entry; +/** The body of {@link KnowledgeService.handedSources}; the member's docblock there is its contract. */ +export function handedSources(this: Pick): KnowledgeSource[] { + return this.registry.entries().map((entry) => entry.handed); +} + +/** How a log line names a source's adapter: the one it names, else the one it is placed on now. */ +export function adapterLabel(this: Pick, source: KnowledgeSource): string { + if (source.adapter !== undefined) return source.adapter; + const placed = this.boundAdapterId(source); + return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; +} + +/** The body of {@link KnowledgeService.faceOfKey}; the member's docblock there is its contract. */ +export function faceOfKey(this: Pick, key: string): string { + return this.registry.byIndexKey(key)?.face ?? key; +} + +/** + * The registered source `sourceId` names, read by the one rule + * (`KnowledgeSourceRegistry.resolve`): its face, else a bare name by + * ADR-0150 D3. Throws for a name no source has, listing the registered + * faces, and `409 RESOURCE_CONFLICT` for one that names several. + */ +export function requireEntry(this: Pick, sourceId: string): KnowledgeSourceEntry { + const entry = this.registry.resolve(sourceId); + if (!entry) { + throw new Error( + `[knowledge] unknown source '${sourceId}'. Registered: [${this.registry.entries().map((e) => e.face).join(', ')}]`, + ); } + return entry; } diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 095db815baa..1382ceaf226 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -59,12 +59,12 @@ import type { SearchTarget, UnprovenEnd, } from './knowledge-service-top-level.js'; -import { KnowledgeSourcesFacet } from './knowledge-service-sources.js'; -import { KnowledgeIndexingFacet } from './knowledge-service-indexing.js'; -import { KnowledgeRecordSyncFacet } from './knowledge-service-record-sync.js'; -import { KnowledgeSearchFacet } from './knowledge-service-search.js'; -import { KnowledgeAdmissionFacet } from './knowledge-service-admission.js'; import { knowledgeServiceHost } from './knowledge-service-host.js'; +import * as KnowledgeSourcesFacet from './knowledge-service-sources.js'; +import * as KnowledgeIndexingFacet from './knowledge-service-indexing.js'; +import * as KnowledgeRecordSyncFacet from './knowledge-service-record-sync.js'; +import * as KnowledgeSearchFacet from './knowledge-service-search.js'; +import * as KnowledgeAdmissionFacet from './knowledge-service-admission.js'; // [#38660] Every top-level declaration this module held beside the class lives in // `knowledge-service-top-level.ts`; what it exported is still exported from here, under the same names. diff --git a/scripts/tenant-audit-census.mjs b/scripts/tenant-audit-census.mjs index dfbc1707257..b9356f90f95 100644 --- a/scripts/tenant-audit-census.mjs +++ b/scripts/tenant-audit-census.mjs @@ -1757,6 +1757,12 @@ export const UNTYPED_RECEIVERS = [ engine: false, what: 'a knowledge search-index adapter -- `delete([documentId], { source })` de-indexes documents', }, + { + file: 'packages/services/service-knowledge/src/knowledge-service-record-sync.ts', + receiver: 'adapter', + engine: false, + what: 'a knowledge search-index adapter (`this.adapterFor(source)`, read through the facet host) -- `delete([docId], context)` de-indexes documents', + }, { file: 'packages/services/service-messaging/src/memory-http-outbox.ts', receiver: 'this', From bac87c0e96e2550f9777a43940a99311daa37b51 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:03:46 +0000 Subject: [PATCH 04/23] chore(service-knowledge): ceiling row measured on the split head Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- scripts/facade-delegation-registry.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/facade-delegation-registry.json b/scripts/facade-delegation-registry.json index ad74e8120ee..b95f7a70b2e 100644 --- a/scripts/facade-delegation-registry.json +++ b/scripts/facade-delegation-registry.json @@ -211,7 +211,7 @@ { "file": "packages/services/service-knowledge/src/knowledge-service.ts", "baseLines": 1658, - "baseCommit": "6ee3b9648f", + "baseCommit": "4c4a984345", "maxLines": 1758, "ruling": "6897467376" } From 1b7a98c75bee31e795419772c521112ee3c865cc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:12:52 +0000 Subject: [PATCH 05/23] docs(service-knowledge): name the facet modules in the host and top-level headers Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- .../services/service-knowledge/src/knowledge-service-host.ts | 3 ++- .../service-knowledge/src/knowledge-service-top-level.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/services/service-knowledge/src/knowledge-service-host.ts b/packages/services/service-knowledge/src/knowledge-service-host.ts index 9e40213743c..b581fe4d135 100644 --- a/packages/services/service-knowledge/src/knowledge-service-host.ts +++ b/packages/services/service-knowledge/src/knowledge-service-host.ts @@ -2,7 +2,8 @@ /** * [#38660] The one host per `KnowledgeService` that its facets - * (`knowledge-service-*.ts`) are handed as `this`. + * (`knowledge-service-sources.ts`, `-indexing.ts`, `-record-sync.ts`, + * `-search.ts` and `-admission.ts`) are handed as `this`. * * {@link KnowledgeServiceHost} is every facet's host at once: each facet declares, * in its own module, the members its bodies read (its `...Host` interface, diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index 2570c097777..21c8398272a 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -5,7 +5,8 @@ * class: the options, logger and held-reading shapes the service is built with, * and the helpers, constants, refusal texts and record-to-document assembly its * bodies use. Moved here whole, in their order, not edited, so the facets - * (`knowledge-service-*.ts`) import them without importing the class module. + * (`knowledge-service-host.ts` names them) import them without importing the + * class module. * `knowledge-service.ts` re-exports what it exported before, under the same * names; a declaration a facet or the facade reads gained `export`, and none of * them is exported from the package entry (`index.ts` is unchanged). From 6829ee13ccc0298477ab68c5460396efac7887ab Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:30:06 +0000 Subject: [PATCH 06/23] docs(service-knowledge): a private member with no docblock is named so on its facet body Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- .../service-knowledge/src/knowledge-service-admission.ts | 2 +- .../service-knowledge/src/knowledge-service-sources.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts index 5c5d0c96795..eef37eca116 100644 --- a/packages/services/service-knowledge/src/knowledge-service-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -481,7 +481,7 @@ export async function scopeByOrganization( }); } -/** The body of {@link KnowledgeService.sourcesForObject}; the member's docblock there is its contract. */ +/** The body of {@link KnowledgeService.sourcesForObject} (a private member with no docblock). */ export function sourcesForObject(this: Pick, object: string): KnowledgeSource[] { return objectSourcesFor(this.handedSources(), object); } diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index ab24a10728a..a46f5c61400 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -251,7 +251,7 @@ export function onSourcesChanged(this: Pick): void { for (const listener of [...this.sourceListeners]) { try { @@ -381,7 +381,7 @@ export function handed(this: Pick, key: string return this.registry.byIndexKey(key)?.handed; } -/** The body of {@link KnowledgeService.handedSources}; the member's docblock there is its contract. */ +/** The body of {@link KnowledgeService.handedSources} (a private member with no docblock). */ export function handedSources(this: Pick): KnowledgeSource[] { return this.registry.entries().map((entry) => entry.handed); } @@ -393,7 +393,7 @@ export function adapterLabel(this: Pick, return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; } -/** The body of {@link KnowledgeService.faceOfKey}; the member's docblock there is its contract. */ +/** The body of {@link KnowledgeService.faceOfKey} (a private member with no docblock). */ export function faceOfKey(this: Pick, key: string): string { return this.registry.byIndexKey(key)?.face ?? key; } From ad4f458a7cee52716072fa5581efa57f89d6d4e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 04:40:26 +0000 Subject: [PATCH 07/23] chore(spec): the knowledge_source liveness ledger cites the moved bodies at their modules Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude --- .changeset/38660-knowledge-service-split.md | 3 +++ packages/spec/liveness/knowledge_source.json | 16 ++++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.changeset/38660-knowledge-service-split.md b/.changeset/38660-knowledge-service-split.md index 6699a14568f..a084aa2049e 100644 --- a/.changeset/38660-knowledge-service-split.md +++ b/.changeset/38660-knowledge-service-split.md @@ -1,5 +1,6 @@ --- '@objectstack/service-knowledge': patch +'@objectstack/spec': patch --- refactor(service-knowledge): `KnowledgeService` keeps its members and forwards each to the module that owns its concern @@ -8,3 +9,5 @@ Clause-②: no Metadata-protocol: none An internal move with no behaviour change. The bodies of `KnowledgeService` now live in five modules beside it (adapters and sources; build, index state and reconcile; record sync; search; save admission and scoping), and each member of the class forwards to its body in one call. Every member keeps its name, signature and docblock, so the package's public declaration is unchanged and nothing is added to or removed from the package entry. The published bundle's code moves between chunks; the published declaration file loses only the comments of private members and lists its declarations in another order. + +`@objectstack/spec`'s `knowledge_source` liveness ledger cites each body at the module that now holds it. diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index e44ed13b954..f796c040986 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -33,7 +33,7 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#reindexWith — the adapter the source's documents are written to and searched in is resolved by this id; packages/services/service-knowledge/src/knowledge-service.ts#dropMetadataSource — the adapter asked to drop the index of a removed item.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-indexing.ts#reindexWith — the adapter the source's documents are written to and searched in is resolved by this id; packages/services/service-knowledge/src/knowledge-service-sources.ts#dropMetadataSource — the adapter asked to drop the index of a removed item.", "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": "Required until row 3b of topic #37000 makes it optional." }, @@ -56,14 +56,14 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#objectSourcesFor — a written or deleted record is matched to its sources by this object; packages/services/service-knowledge/src/knowledge-service.ts#walkObjectSource — the object a build walks; packages/services/service-knowledge/src/knowledge-reap-guard.ts#guardedObjectsFor — the object the lifecycle reap guard is registered for.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-top-level.ts#objectSourcesFor — a written or deleted record is matched to its sources by this object; packages/services/service-knowledge/src/knowledge-service-indexing.ts#walkObjectSource — the object a build walks; packages/services/service-knowledge/src/knowledge-reap-guard.ts#guardedObjectsFor — the object the lifecycle reap guard is registered for.", "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)." }, "content": { "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#recordToDocument — the listed fields, in order, are the document's text; packages/services/service-knowledge/src/knowledge-source-admission.ts#servedFieldsOf — each is a field the caller must be allowed to query before the source is searched for them.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-top-level.ts#recordToDocument — the listed fields, in order, are the document's text; packages/services/service-knowledge/src/knowledge-source-admission.ts#servedFieldsOf — each is a field the caller must be allowed to query before the source is searched for them.", "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": "A list of field names; the `'*'` member is refused at parse (ADR-0161 K5: embedding is egress)." }, @@ -76,14 +76,14 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#recordToDocument — each listed field's value is carried in the document's metadata; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a change to the list changes the recipe hash and starts one rebuild; packages/services/service-knowledge/src/knowledge-search-scope.ts — a parent scope and `groupBy` resolve against the listed fields.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-top-level.ts#recordToDocument — each listed field's value is carried in the document's metadata; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a change to the list changes the recipe hash and starts one rebuild; packages/services/service-knowledge/src/knowledge-search-scope.ts — a parent scope and `groupBy` resolve against the listed fields.", "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)." }, "documentBy": { "status": "live", "verifiedAt": "2026-11-29", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#documentKeyOf — a record-level search with no `groupBy` groups each hit of the source by the parent the field holds (read from the hit's stored metadata), one hit per parent; packages/services/service-knowledge/src/knowledge-tools.ts#hitOf — the `search_knowledge` hit carries that parent as `groupValue`; packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource — the save refuses a field that is not a single-valued parent link (`documentUnitOf`, the parent-link rule of knowledge-search-scope.ts).", + "evidence": "packages/services/service-knowledge/src/knowledge-service-top-level.ts#documentKeyOf — a record-level search with no `groupBy` groups each hit of the source by the parent the field holds (read from the hit's stored metadata), one hit per parent; packages/services/service-knowledge/src/knowledge-tools.ts#hitOf — the `search_knowledge` hit carries that parent as `groupValue`; packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses a field that is not a single-valued parent link (`documentUnitOf`, the parent-link rule of knowledge-search-scope.ts).", "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." }, @@ -91,7 +91,7 @@ "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`).", + "evidence": "packages/services/service-knowledge/src/knowledge-service-search.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-admission.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": { @@ -125,7 +125,7 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#walkObjectSource — a build indexes only the records the filter selects; packages/services/service-knowledge/src/knowledge-service.ts#syncRecord — a written record is re-read under it, and one that no longer matches is de-indexed; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a changed filter starts one rebuild.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-indexing.ts#walkObjectSource — a build indexes only the records the filter selects; packages/services/service-knowledge/src/knowledge-service-record-sync.ts#syncRecord — a written record is re-read under it, and one that no longer matches is de-indexed; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a changed filter starts one rebuild.", "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)." }, "split": { @@ -171,7 +171,7 @@ "status": "live", "verifiedAt": "2026-11-26", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#objectSourcesFor — `false` leaves the source out of the event sync and of the reap guard; packages/services/service-knowledge/src/knowledge-service.ts#buildIfDue — and out of the boot and reload builds: an external indexer owns its index.", + "evidence": "packages/services/service-knowledge/src/knowledge-service-top-level.ts#objectSourcesFor — `false` leaves the source out of the event sync and of the reap guard; packages/services/service-knowledge/src/knowledge-service-indexing.ts#buildIfDue — and out of the boot and reload builds: an external indexer owns its index.", "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)." }, "cron": { From 1ff58575674eb31c246ca3f6a40858c596158ceb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:32:22 +0000 Subject: [PATCH 08/23] feat(spec): source.retrieval.mode, AdapterCapabilities.retrieval and AdapterSearchOptions.retrieval (wip) --- .../src/__tests__/index-fingerprint.test.ts | 14 +++ .../services/service-knowledge/src/testing.ts | 91 +++++++++++++++++++ packages/spec/liveness/knowledge_source.json | 12 +++ .../src/ai/knowledge-source.metadata-form.ts | 20 ++++ packages/spec/src/ai/knowledge-source.test.ts | 43 +++++++++ packages/spec/src/ai/knowledge-source.zod.ts | 68 ++++++++++++++ .../spec/src/contracts/knowledge-adapter.ts | 49 +++++++++- 7 files changed, 294 insertions(+), 3 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 9061a06536f..2168abc0b70 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -170,3 +170,17 @@ describe('recipe hash (ADR-0161 K7)', () => { expect(computeRecipeHash({ source: source({ content: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); }); }); + +// `source.retrieval` is read on every search and by no build (ADR-0161, the +// dated note on retrieval modes): neither hash moves with it, so changing a +// source's retrieval mode rebuilds nothing. +describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { + it('changes neither the index fingerprint nor the recipe hash', () => { + const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); + const recipe = computeRecipeHash({ source: source() }); + for (const retrieval of [{}, { mode: 'vector' }, { mode: 'keyword' }, { mode: 'hybrid' }]) { + expect(computeIndexFingerprint({ source: source({ retrieval }), embedding, split })).toBe(fingerprint); + expect(computeRecipeHash({ source: source({ retrieval }) })).toBe(recipe); + } + }); +}); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 036bf9be61c..ba240142225 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -74,6 +74,11 @@ * whose figure and exception words one passage holds, among passages that * hold the question's characters one by one and none of its words: the * passage is ranked. + * + * An adapter that declares `retrieval` reports its modes and default + * (`capabilities.retrieval`), and the same fixture is searched under each + * mode it lists: `vector` leaves that passage out, `keyword` answers it + * alone, and the default handed explicitly answers what no mode answers. */ import { describe, expect, it, vi } from 'vitest'; @@ -86,6 +91,7 @@ import type { AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KNOWLEDGE_RETRIEVAL_MODES } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; import { KnowledgeService, type KnowledgeLogger } from './knowledge-service.js'; @@ -148,6 +154,17 @@ export interface KnowledgeAdapterContractOptions { * behaviour. Absent: `false`. */ keywordLeg?: boolean; + /** + * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * the adapter reports the modes it runs and its default, and its search + * honours `AdapterSearchOptions.retrieval`. The report is checked against + * the three modes, and each listed mode is asserted by behaviour: `vector` + * leaves out the passage only the keyword leg ranks, `keyword` ranks by + * the query's words alone, `hybrid` answers what the default answers when + * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * Absent: `false`. + */ + retrieval?: boolean; }; } @@ -510,6 +527,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.beginBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); + expect(adapter.capabilities?.retrieval !== undefined).toBe(opts.implements.retrieval === true); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -568,6 +586,79 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + if (opts.implements.retrieval === true) { + describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { + const adapter: IKnowledgeAdapter = await make(); + const report = adapter.capabilities?.retrieval; + expect(report).toBeDefined(); + if (report === undefined) return; + expect(report.modes.length).toBeGreaterThan(0); + expect(new Set(report.modes).size).toBe(report.modes.length); + for (const mode of report.modes) expect(KNOWLEDGE_RETRIEVAL_MODES).toContain(mode); + expect(report.modes).toContain(report.default); + }); + + /** + * The keyword-leg fixture: five passages hold the question's + * characters one by one (a bag-of-words embedder ranks them first by + * vector) and none of its words; one passage holds its figure and + * words, which the vector leg alone ranks below `topK`. + */ + const QUESTION = '出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗'; + async function seeded(): Promise<{ adapter: IKnowledgeAdapter; a: KnowledgeSource; listed: readonly string[]; byDefault: string }> { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('retrieval_modes'); + const spread = ['a', 'b', 'c', 'd', 'e'].map((n) => + doc(a, `spread_${n}`, `出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 ${n}`), + ); + await adapter.upsert([...spread, doc(a, 'clause', '采购单笔金额2000元以下除外,其余一律公开招标')], ctxOf(a)); + const report = adapter.capabilities?.retrieval; + return { adapter, a, listed: report?.modes ?? [], byDefault: report?.default ?? '' }; + } + const nonIncreasing = (hits: Array<{ score: number }>) => { + for (let i = 1; i < hits.length; i++) expect(hits[i - 1].score).toBeGreaterThanOrEqual(hits[i].score); + }; + + it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('vector')) return; + expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(hits.length).toBeGreaterThan(0); + expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); + nonIncreasing(hits); + }); + + it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('keyword')) return; + expect(opts.implements.keywordLeg, 'the keyword case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'keyword' } }); + expect(hits.map((h) => h.documentId)).toEqual([`${a.name}:clause`]); + // A query with no word any passage holds answers nothing under keyword alone. + expect(await adapter.search('zzqx', { source: a, topK: 3, retrieval: { mode: 'keyword' } })).toEqual([]); + }); + + it('`hybrid` ranks both legs; as the default it answers exactly what a search without the member answers', async () => { + const { adapter, a, listed, byDefault } = await seeded(); + if (!listed.includes('hybrid')) return; + const hybrid = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'hybrid' } }); + nonIncreasing(hybrid); + if (opts.implements.keywordLeg) expect(hybrid.map((h) => h.documentId)).toContain(`${a.name}:clause`); + if (byDefault === 'hybrid') { + expect(hybrid).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + } + }); + + it('the default mode, handed explicitly, answers exactly what a search without the member answers', async () => { + const { adapter, a, byDefault } = await seeded(); + const explicit = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: byDefault as 'vector' } }); + expect(explicit).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + }); + }); + } + if (opts.implements.organizationIds) { describe('organizationIds (ADR-0161 K8, item 9)', () => { /** B's document outranks A's; a third document carries no organization. */ diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index e44ed13b954..56fbab6004f 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -121,6 +121,18 @@ } } }, + "retrieval": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "children": { + "mode": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + } + } + }, "where": { "status": "live", "verifiedAt": "2026-11-26", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index d84610e3be3..1215e5f31b2 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -25,6 +25,8 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `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. + * - `source.retrieval.mode` is a select of the three modes, blank for the + * store's default; which modes the store runs is judged at save. * * 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. @@ -77,6 +79,24 @@ 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: 'retrieval', + label: 'Search', + type: 'composite', + helpText: 'How a search of this source finds passages. Leave it blank for the store\'s default. Changing it rebuilds nothing.', + fields: [ + { + field: 'mode', + label: 'Retrieval mode', + options: [ + { label: 'Vector only (by meaning)', value: 'vector' }, + { label: 'Keyword only (by words)', value: 'keyword' }, + { label: 'Hybrid (both)', value: 'hybrid' }, + ], + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + }, + ], + }, { 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 cf5c5b01ae0..663ecd5d07f 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -28,6 +28,7 @@ import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { ObjectStackDefinitionSchema } from '../stack.zod'; import { KNOWLEDGE_AFFINITY_MAX_PLACES, + KNOWLEDGE_RETRIEVAL_MODES, KnowledgeSourceSchema, type KnowledgeSource, type KnowledgeSourceParsed, @@ -415,3 +416,45 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller expect(issues.map(([code, path]) => [code, path])).toEqual([['unrecognized_keys', 'source.affinity.0']]); }); }); + +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { + const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); + + it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { + expect(KNOWLEDGE_RETRIEVAL_MODES).toEqual(['vector', 'keyword', 'hybrid']); + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({ mode })); + expect(r.success, mode).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({ mode }); + } + expect('retrieval' in KnowledgeSourceSchema.parse(SOURCE).source).toBe(false); + }); + + it('accepts `retrieval: {}`, which declares nothing and adds no default', () => { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({})); + expect(r.success).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({}); + }); + + it('refuses a mode outside the three, naming the three', () => { + const issues = issuesOf(withRetrieval({ mode: 'semantic' })); + expect(issues.map(([code, path]) => [code, path])).toEqual([['invalid_value', 'source.retrieval.mode']]); + expect(issues[0]![2]).toMatch(/^`knowledge_source.source.retrieval.mode` is 'vector', 'keyword' or 'hybrid', got 'semantic'/); + }); + + it('refuses an unknown key under `retrieval` — `vectorWeight` included, which this version does not carry — never drops it', () => { + for (const key of ['vectorWeight', 'keywordWeight', 'fusion']) { + const issues = issuesOf(withRetrieval({ mode: 'hybrid', [key]: 0.5 })); + expect(issues.map(([code, path]) => [code, path]), key).toEqual([['unrecognized_keys', 'source.retrieval']]); + } + }); + + it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + properties: { source: { properties: Record; additionalProperties?: unknown }> } }; + }; + const retrieval = json.properties.source.properties.retrieval; + expect(retrieval?.properties?.mode?.enum).toEqual(['vector', 'keyword', 'hybrid']); + expect(retrieval?.additionalProperties).toBe(false); + }); +}); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 50af210a137..64e6ef189c6 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -128,6 +128,60 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( }, )); +/** + * The retrieval modes a knowledge source may declare (ADR-0161, the dated note + * on retrieval modes; ruling 7270218011 on #38692): + * + * - `vector`: only the vector leg runs, ranking passages by meaning. + * - `keyword`: only the keyword leg runs, ranking passages by the words they + * hold. The embedder is not called and no query vector is made; passages of + * equal keyword score are ranked by passage id, so the answer is + * deterministic, and a question with no words to match answers nothing. It + * suits exact lookups: a document number, a clause number, a name. + * - `hybrid`: both legs run, merged by the store's fusion. + * + * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), + * never configuration; a source that declares a mode its store does not run is + * refused, never silently searched another way. + */ +export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; + +/** One of {@link KNOWLEDGE_RETRIEVAL_MODES}. */ +export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RETRIEVAL_MODES, { + error: (issue) => (typeof issue.input === 'string' + ? `\`knowledge_source.source.retrieval.mode\` is 'vector', 'keyword' or 'hybrid', got '${issue.input}'. ` + + 'Write `mode: \'vector\'` to rank by meaning alone, `mode: \'keyword\'` to rank by the words a passage holds ' + + '(no embedding call), or `mode: \'hybrid\'` for both; leave `mode` out for the store\'s default.' + : undefined), +})); + +/** + * How a source is searched (ADR-0161, the dated note on retrieval modes): + * which legs the store runs. A declaration of the source, read on every search + * and never by a build, so it enters neither the index fingerprint nor the + * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing + * and reads as the key left out. + */ +export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( + { + surface: 'this source\'s `retrieval`', + history: 'This shape is strict from birth — `retrieval` had no earlier spelling, so an unknown key here was never accepted.', + }, + { + /** + * Which legs run: `vector`, `keyword` or `hybrid` + * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default + * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and + * pgvector), today's behaviour. A store that does not list the mode + * refuses the source at save, at registration when its store already + * resolves, once after boot, and on every search (the source is listed as + * refused); a store that reports no modes accepts only the key left out. + */ + mode: KnowledgeRetrievalModeSchema.optional() + .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), + }, +)); + /** * `source.documentBy` must be one of `source.metadataFields`: a record-level * search groups each hit by the value the index stores beside its passage, @@ -449,6 +503,17 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( */ 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'), + /** + * [ADR-0161, the dated note on retrieval modes] How this source is + * searched: `retrieval.mode` names the legs the store runs + * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before + * it: the mode decides which passages the store ranks and their scores, + * then affinity re-orders them for the caller. Omitted: the store's + * default, as before this key. It enters neither the index fingerprint + * nor the recipe hash, so changing it rebuilds nothing. + */ + retrieval: KnowledgeRetrievalSchema.optional() + .describe('How this source is searched: mode vector, keyword or hybrid; omitted means the store\'s default, and changing it rebuilds nothing'), }, ).superRefine(refineObjectSource)); @@ -583,3 +648,6 @@ export type KnowledgeAffinityMode = z.input; export type KnowledgeAffinityModeParsed = z.infer; export type KnowledgeAffinityEntry = z.input; export type KnowledgeAffinityEntryParsed = z.infer; +export type KnowledgeRetrievalMode = z.input; +export type KnowledgeRetrieval = z.input; +export type KnowledgeRetrievalParsed = z.infer; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4728cd8b136..4d729a55900 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -4,7 +4,7 @@ import type { KnowledgeDocument, KnowledgeHit, } from '../ai/knowledge-document.zod'; -import type { KnowledgeSource } from '../ai/knowledge-source.zod'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '../ai/knowledge-source.zod'; /** * `IKnowledgeAdapter` — plugin-side contract. @@ -176,6 +176,26 @@ export interface AdapterSearchOptions { * answers it from that generation. Absent: no check. */ index?: { fingerprint: string }; + /** + * The retrieval mode this search runs (ADR-0161, the dated note on + * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * from the source's `source.retrieval.mode`, else the adapter's + * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, + * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). + * + * - `vector`: run only the vector leg. + * - `keyword`: run only the keyword leg. Do not call the embedder and make + * no query vector; rank passages of equal keyword score by passage id. + * A query with no terms to match answers no hits. + * - `hybrid`: run both legs and fuse them, as the adapter's default does. + * + * The service hands only a mode the adapter lists in + * `capabilities.retrieval.modes`, and never hands this member to an adapter + * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * Scores need only not increase with rank within one source's answer; under + * a one-leg mode they reflect rank alone. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; /** Trace id for correlation. */ traceId?: string; } @@ -244,6 +264,28 @@ export interface AdapterCapabilities { * `chunks`, and splits them itself. */ chunks?: boolean; + /** + * The retrieval modes the adapter runs, and which one it runs when a + * source declares none (ADR-0161, the dated note on retrieval modes). A + * report, not configuration: `default` is one of `modes`, and an adapter + * that lists `hybrid` honours the source's vector share when that arrives. + * + * The knowledge service refuses a source that declares a mode outside + * `modes` — at save, at registration when the adapter already resolves, + * once after boot, and on every search, where the source is listed as + * refused — and never searches it another way. Absent: the adapter reports + * no modes, and only a source that declares none is searched by it; the + * service is never told which legs it runs. + */ + retrieval?: AdapterRetrievalCapability; +} + +/** {@link AdapterCapabilities.retrieval}: the modes an adapter runs, and its default. */ +export interface AdapterRetrievalCapability { + /** The modes the adapter runs; not empty, no mode twice. */ + readonly modes: readonly KnowledgeRetrievalMode[]; + /** The mode it runs for a source that declares none; one of {@link modes}. */ + readonly default: KnowledgeRetrievalMode; } /** @@ -308,8 +350,9 @@ export interface IKnowledgeAdapter { readonly id: string; /** - * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5). - * Absent: whole documents only. + * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5), + * and the retrieval modes it runs. Absent: whole documents only, and no + * modes reported. */ readonly capabilities?: AdapterCapabilities; From 8dc9af75d4ff3f1c849ddefcd6e58ce8fae6da00 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:39:49 +0000 Subject: [PATCH 09/23] chore(spec): regenerate the generated artifacts for source.retrieval --- content/docs/protocol/knowledge.mdx | 10 +++++- .../docs/references/ai/knowledge-source.mdx | 34 +++++++++++++++++-- content/docs/references/index.mdx | 10 +++--- .../ai.md | 2 +- packages/spec/api-surface/ai.json | 6 ++++ packages/spec/api-surface/contracts.json | 1 + packages/spec/authorable-surface/ai.json | 2 ++ packages/spec/declaration-map/ai.json | 4 +++ packages/spec/export-origins/ai.json | 6 ++++ packages/spec/export-origins/contracts.json | 1 + packages/spec/json-schema.manifest/ai.json | 2 ++ .../liveness/state-counts/knowledge_source.md | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- 13 files changed, 71 insertions(+), 11 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 105eb543109..9b4c0e338d0 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -483,7 +483,10 @@ and [3.5 The split](#35-the-split). ```ts interface IKnowledgeAdapter { readonly id: string; - readonly capabilities?: { chunks?: boolean }; // takes the service's passages + readonly capabilities?: { + chunks?: boolean; // takes the service's passages + retrieval?: { modes: readonly ('vector' | 'keyword' | 'hybrid')[]; default: 'vector' | 'keyword' | 'hybrid' }; + }; // the retrieval modes it runs, and its default readonly embedding?: { // what its embedder is maxInputTokens?: number; // longest input it accepts model?: string; dimensions?: number; variant?: string; // what its vectors are @@ -523,6 +526,11 @@ caller's organizations; an adapter that reads it ranks only those organizations' documents, filtering before it ranks — see [Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a search to chosen records the same way — see [Record scope](#record-scope). +`capabilities.retrieval` reports the retrieval modes an adapter runs +(`vector`, `keyword`, `hybrid`) and the one it runs by default; it is a +report, not configuration. `AdapterSearchOptions.retrieval` carries the mode +a search runs, a per-request parameter like `topK`, and only ever a mode the +adapter lists. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 423e186a7ad..2e11a10f60a 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -23,8 +23,8 @@ See `content/docs/protocol/knowledge.mdx` for the design. ## TypeScript Usage ```typescript -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'; +import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeRetrievalSchema, KnowledgeRetrievalModeSchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeRetrieval, KnowledgeRetrievalMode, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data const result = KnowledgeAffinityCallerSchema.parse(data); @@ -76,6 +76,28 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +--- + +## KnowledgeRetrieval + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + + +--- + +## KnowledgeRetrievalMode + +### Allowed Values + +* `vector` +* `keyword` +* `hybrid` + + --- ## KnowledgeSource @@ -116,6 +138,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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 | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `KnowledgeSource.refresh` @@ -166,6 +189,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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 | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `ObjectKnowledgeSource.split` @@ -184,6 +208,12 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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 | +### Nested Shape: `ObjectKnowledgeSource.retrieval` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 920f1a62496..03b540df209 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 — 1745 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1747 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 | 105 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 17 | 107 | 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** | **1745** | 14 protocol modules | +| **Total** | **223** | **1747** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 105 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 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) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeRetrieval`, `KnowledgeRetrievalMode`, `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 5f25e0c458c..050f8f7f1d7 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/` | 121 | +| `ai/` | 122 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index b5f1388e297..0bfeb1ab566 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -132,6 +132,7 @@ "GetRecordContextOutputSchema (const)", "ImageContentSchema (const)", "KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KNOWLEDGE_RETRIEVAL_MODES (const)", "KnowledgeAffinityCaller (type)", "KnowledgeAffinityCallerParsed (type)", "KnowledgeAffinityCallerSchema (const)", @@ -150,6 +151,11 @@ "KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema (const)", "KnowledgeSource (type)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index f012c7992d5..dd0891c1994 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", + "AdapterRetrievalCapability (interface)", "AdapterScopeTerm (type)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 0ee44069dda..529db46b843 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -292,6 +292,7 @@ "ai/KnowledgeHit:title", "ai/KnowledgeRefreshPolicy:cron [RETIRED]", "ai/KnowledgeRefreshPolicy:onRecordChange", + "ai/KnowledgeRetrieval:mode", "ai/KnowledgeSource:_lock", "ai/KnowledgeSource:_lockDocsUrl", "ai/KnowledgeSource:_lockReason", @@ -391,6 +392,7 @@ "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", + "ai/ObjectKnowledgeSource:retrieval", "ai/ObjectKnowledgeSource:split", "ai/ObjectKnowledgeSource:where", "ai/ObjectQuerySource:aggregations", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 8a975cdd035..70474f71dfe 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -101,6 +101,10 @@ "KnowledgeHitSchema": "ai/KnowledgeHit", "KnowledgeRefreshPolicy": "ai/KnowledgeRefreshPolicy", "KnowledgeRefreshPolicySchema": "ai/KnowledgeRefreshPolicy", + "KnowledgeRetrieval": "ai/KnowledgeRetrieval", + "KnowledgeRetrievalMode": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalModeSchema": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalSchema": "ai/KnowledgeRetrieval", "KnowledgeSource": "ai/KnowledgeSource", "KnowledgeSourceSchema": "ai/KnowledgeSource", "KnowledgeSplit": "ai/KnowledgeSplit", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index e7d955f2f85..2114847e360 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -130,6 +130,7 @@ "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)", + "KNOWLEDGE_RETRIEVAL_MODES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_RETRIEVAL_MODES (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)", @@ -148,6 +149,11 @@ "KnowledgeRefreshPolicy": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval": "src/ai/knowledge-source.zod.ts#KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalSchema (const)", "KnowledgeSource": "src/ai/knowledge-source.zod.ts#KnowledgeSource (type)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 4d03a5d5c49..e2d26712da4 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", + "AdapterRetrievalCapability": "src/contracts/knowledge-adapter.ts#AdapterRetrievalCapability (interface)", "AdapterScopeTerm": "src/contracts/knowledge-adapter.ts#AdapterScopeTerm (type)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 4bc2c8920db..3f17e4320fe 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -54,6 +54,8 @@ "ai/KnowledgeDocument", "ai/KnowledgeHit", "ai/KnowledgeRefreshPolicy", + "ai/KnowledgeRetrieval", + "ai/KnowledgeRetrievalMode", "ai/KnowledgeSource", "ai/KnowledgeSplit", "ai/KnowledgeSplitStrategy", diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index a575042db63..1fcc479c9f3 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` | 26 | 0 | 0 | 6 | 0 | 32 | +| `knowledge_source` | 26 | 0 | 0 | 6 | 1 | 33 | diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 663ecd5d07f..af044bd5816 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -450,7 +450,7 @@ describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched }); it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { - const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as unknown as { properties: { source: { properties: Record; additionalProperties?: unknown }> } }; }; const retrieval = json.properties.source.properties.retrieval; From e582d5e89f67baebf3e2801116837abdb6abf872 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:45:45 +0000 Subject: [PATCH 10/23] chore(changeset): source.retrieval.mode and the adapter's retrieval report --- .../38692-knowledge-retrieval-mode-spec.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/38692-knowledge-retrieval-mode-spec.md diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md new file mode 100644 index 00000000000..c48981f369f --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +--- + +feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how it is searched: `source: { …, retrieval: { mode: 'vector' } }`. `vector` runs only the vector leg (ranking passages by meaning), `keyword` only the keyword leg (ranking passages by the words they hold, with no call to the embedder), and `hybrid` both, merged by the store's fusion. Leaving `mode` out, or writing `retrieval: {}`, keeps the store's default, which is today's behaviour. The key is read on every search and by no build, so it enters neither the index fingerprint nor the recipe hash: changing it rebuilds nothing. The parse refuses a mode outside the three, and any other key under `retrieval`, each with the fix. Studio's knowledge source form offers the key as a "Retrieval mode" select under "Search". + +`IKnowledgeAdapter` gains two optional members. `capabilities.retrieval: { modes, default }` is the adapter's report of the modes it runs and the one it runs when a source declares none; it is a report, not configuration. `AdapterSearchOptions.retrieval: { mode }` carries the mode a search runs, a per-request parameter like `topK`. An adapter that reports no modes keeps working unchanged; a source that names it may only leave `mode` out. + +The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. + +The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 9e576393c79ea0d5fedea54217b52e842cdaf15b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:50:00 +0000 Subject: [PATCH 11/23] test(service-knowledge): the vector-mode contract case reads the vector leg by a passage's own text --- packages/services/service-knowledge/src/testing.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index ba240142225..1eb8060fa13 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -625,9 +625,12 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption if (!listed.includes('vector')) return; expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); - expect(hits.length).toBeGreaterThan(0); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); + // The vector leg still runs: a passage's own text ranks that passage first. + const own = await adapter.search('出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 c', { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(own[0]?.documentId).toBe(`${a.name}:spread_c`); + nonIncreasing(own); }); it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { From 9c31e4489d7d35bc8fff77eeb29dd92ca266012e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:12:00 +0000 Subject: [PATCH 12/23] feat(service-knowledge): read a source's retrieval mode, and refuse a mode its store does not run The effective mode is the source's `source.retrieval.mode`, else the store's `capabilities.retrieval.default`; every search hands it to the store as `AdapterSearchOptions.retrieval` and logs it at debug with its origin, never in the caller's answer. A declared mode the store does not list is refused at the save (400 VALIDATION_ERROR, listing the store's modes), at registration when the store already resolves, once after boot at error (`reportUnsupportedRetrieval`), and on every search (`refused`, SERVICE_UNAVAILABLE); such a source still indexes. `index_status` carries each source's retrieval reading and each store's modes. The liveness row flips to live. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../38692-knowledge-retrieval-mode-service.md | 24 ++ content/docs/protocol/knowledge.mdx | 33 +- .../__tests__/retrieval-mode-38692.test.ts | 318 ++++++++++++++++++ .../services/service-knowledge/src/index.ts | 2 + .../src/knowledge-build-actions.ts | 26 +- .../src/knowledge-retrieval-mode.ts | 136 ++++++++ .../src/knowledge-service-admission.ts | 28 +- .../src/knowledge-service-plugin.ts | 4 +- .../src/knowledge-service-search.ts | 32 +- .../src/knowledge-service-sources.ts | 83 ++++- .../src/knowledge-service-top-level.ts | 13 +- .../src/knowledge-service.ts | 23 ++ .../services/service-knowledge/src/testing.ts | 57 +++- packages/spec/liveness/knowledge_source.json | 12 +- .../liveness/state-counts/knowledge_source.md | 2 +- 15 files changed, 777 insertions(+), 16 deletions(-) create mode 100644 .changeset/38692-knowledge-retrieval-mode-service.md create mode 100644 packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts create mode 100644 packages/services/service-knowledge/src/knowledge-retrieval-mode.ts diff --git a/.changeset/38692-knowledge-retrieval-mode-service.md b/.changeset/38692-knowledge-retrieval-mode-service.md new file mode 100644 index 00000000000..86abfb18dca --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-service.md @@ -0,0 +1,24 @@ +--- +'@objectstack/service-knowledge': patch +--- + +feat(service-knowledge): the knowledge service reads a source's retrieval mode + +A search of a knowledge source now runs in its effective retrieval mode: the +mode the source declares (`source.retrieval.mode`), else its store's default +(`capabilities.retrieval.default`). The mode is handed to the store on every +search and logged at `debug` with where it came from; it is not in what a +search answers the caller. `index_status` carries each source's `retrieval` +(the mode, its origin, the store's modes, a refusal) and each mounted store's +modes. + +A source that declares a mode its store does not run is never searched +another way. It is refused at its save (`400 VALIDATION_ERROR`, listing the +modes the store runs), at registration when its store is already registered, +once after boot at `error` (`reportUnsupportedRetrieval`), and on every search, +where it is listed in `refused` with `SERVICE_UNAVAILABLE` (503). It still +builds and syncs its index. A store that reports no modes (knowledge-memory) +takes only a source that leaves the mode out. + +Clause-②: no +Metadata-protocol: none diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..719d7d473b1 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -181,6 +181,32 @@ that name (ADR-0161 K4): `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is used, so a source registered before its store started finds it. +**How a source is searched: `source.retrieval.mode`** (ADR-0161, the dated +note on retrieval modes). `'vector'` ranks by meaning alone, `'keyword'` by +the question's words alone (the embedder is never called), `'hybrid'` runs +both and merges them; omitted (or `retrieval: {}`), the adapter's default +(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). +That is the effective mode, handed to the adapter on every search and logged +at `debug` with where it came from; it is not in what a search answers the +caller, and an administrator reads it in the source's `index_status`. A +source is never searched in a mode other than the one it declares, so a mode +its adapter does not list (an adapter that reports none, such as `memory`, +lists none) is refused at four points: + +1. its save (Studio, `/meta`, an MCP draft): `VALIDATION_ERROR` (400), + listing the modes the store runs; +2. its registration, when its adapter is already registered: the same + refusal. A store registers in its own `start()`, after a source + registered at `init()`, so "not registered yet" is no verdict; a package + install meets no save, so the next two points hold it; +3. once after boot, at `error`, naming the source and the modes; +4. every search: the source is listed in `refused`, `SERVICE_UNAVAILABLE` + (503), as a source whose adapter is not mounted is. + +The mode is read by search alone: it enters neither the index fingerprint nor +the recipe hash, so changing it rebuilds nothing, and a refused source still +builds and syncs its index. + **What mounts the service.** A stack that ships a `knowledge_source` — any item in its `knowledgeSources`, at the top level or in a package — is served the knowledge service and the deployment's store, exactly as @@ -252,7 +278,8 @@ and the MCP draft door: serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; an `adapter` naming no mounted store refuses it `400`, naming the - source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`, + source, the adapter and the mounted ones, and so does a + `source.retrieval.mode` the store does not run, listing the ones it does. The fields judged are the ones the source serves (`content`, `metadataFields`, the title field) and the ones its `where` reads. A verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`; nothing is written. @@ -1504,7 +1531,9 @@ followed (§4.1, §4.2) are the adapters to run in production. ### 7.1 Non-goals for Phase 1 -- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private. +- Reranker hooks, MMR — adapter-private. Which legs a search runs is not: + a source declares it (`source.retrieval.mode`, §3.1); how the legs are + weighted is not authorable yet. - Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller. diff --git a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts new file mode 100644 index 00000000000..bf60bc42504 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts @@ -0,0 +1,318 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38692 phase 1a] A source's retrieval mode (`source.retrieval.mode`) as the + * knowledge service reads it: the effective mode (the declaration, else the + * adapter's default), handed to the adapter on every search and logged at + * `debug`, never answered to the caller; and the four refusal points of a + * declared mode the adapter does not run (save, registration, the boot's + * reading, every search). Such a source is still indexed. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; +import { knowledgeIndexStatusActionHandler } from '../knowledge-build-actions.js'; +import { + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from '../knowledge-retrieval-mode.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as never; +const ALL_MODES: KnowledgeRetrievalMode[] = ['vector', 'keyword', 'hybrid']; + +function adapterOf( + id: string, + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }, +): IKnowledgeAdapter & { searchSpy: ReturnType; upsertSpy: ReturnType } { + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }): Promise => [ + { chunkId: `${opts.source.name}#c1`, documentId: `${opts.source.name}:d1`, sourceId: opts.source.name, snippet: 'x', score: 1 }, + ]); + const upsertSpy = vi.fn(async () => undefined); + return { + id, + upsert: upsertSpy, + delete: vi.fn(async () => undefined), + search: searchSpy, + ...(retrieval === undefined ? {} : { capabilities: { retrieval } }), + searchSpy, + upsertSpy, + } as never; +} + +function source(name: string, adapter: string, mode?: KnowledgeRetrievalMode | 'empty'): KnowledgeSource { + return { + name, + label: name, + adapter, + source: { + kind: 'object', + object: 'task', + content: ['title', 'notes'], + ...(mode === undefined ? {} : { retrieval: mode === 'empty' ? {} : { mode } }), + } as ObjectKnowledgeSource, + }; +} + +function logged() { + const lines: Array<[string, string]> = []; + return { + lines, + logger: { + debug: (m: string) => lines.push(['debug', m]), + info: (m: string) => lines.push(['info', m]), + warn: (m: string) => lines.push(['warn', m]), + error: (m: string) => lines.push(['error', m]), + }, + }; +} + +describe('resolveRetrievalMode — the effective mode and where it came from', () => { + const hybridStore = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const vectorOnly = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const silent = adapterOf('memory'); + + it('the declaration wins; none declared (or `retrieval: {}`) takes the adapter default', () => { + for (const mode of ALL_MODES) { + expect(resolveRetrievalMode(source('s', 'turso', mode), hybridStore)).toEqual({ refused: false, mode, from: 'source' }); + } + expect(resolveRetrievalMode(source('s', 'turso'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + expect(resolveRetrievalMode(source('s', 'turso', 'empty'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + }); + + it('a mode the adapter does not list is refused, never run another way', () => { + expect(resolveRetrievalMode(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + refused: true, + declared: 'keyword', + modes: ['vector'], + }); + }); + + it('an adapter that reports no modes is never told one: none declared searches as before, a declared one is refused', () => { + expect(resolveRetrievalMode(source('s', 'memory'), silent)).toEqual({ refused: false }); + expect(resolveRetrievalMode(source('s', 'memory', 'vector'), silent)).toEqual({ refused: true, declared: 'vector' }); + }); + + it('the refusal text names the declared mode, the modes the store runs and the remedies', () => { + expect(retrievalRefusalText('vec', 'keyword', vectorOnly)).toBe( + "its `retrieval.mode` is 'keyword', and the store 'vec' runs 'vector' (default 'vector'); a source is never " + + "searched in a mode other than the one it declares. Write one of 'vector' as `retrieval.mode`, or remove it " + + "for the store's default, or bind the source to a store that runs 'keyword'.", + ); + expect(retrievalRefusalText('memory', 'vector', silent)).toContain( + "the store 'memory' reports no retrieval modes, so a source on it may only leave `retrieval.mode` out", + ); + }); + + it('the operator reading carries the declaration, the effective mode, its origin and the store modes', () => { + expect(readRetrieval(source('s', 'turso'), hybridStore)).toEqual({ + mode: 'hybrid', + from: 'adapter', + modes: ALL_MODES, + default: 'hybrid', + }); + expect(readRetrieval(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + declared: 'keyword', + refused: true, + modes: ['vector'], + default: 'vector', + }); + expect(readRetrieval(source('s', 'memory'), silent)).toEqual({}); + }); +}); + +describe('the search hands the adapter its effective mode', () => { + it('declared, defaulted, and nothing at all for an adapter that reports no modes', async () => { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const turso = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const memory = adapterOf('memory'); + svc.registerAdapter('turso', turso); + svc.registerAdapter('memory', memory); + svc.registerSource(source('kw', 'turso', 'keyword')); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('plain', 'memory')); + + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report.refused).toEqual([]); + const modeOf = (name: string) => + turso.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.name === name)?.[1]?.retrieval; + expect(modeOf('kw')).toEqual({ mode: 'keyword' }); + expect(modeOf('dflt')).toEqual({ mode: 'hybrid' }); + expect(memory.searchSpy).toHaveBeenCalledOnce(); + expect('retrieval' in (memory.searchSpy.mock.calls[0]![1] as object)).toBe(false); + + // The mode and its origin are the operator's, at debug; the caller's answer carries neither. + const debug = lines.filter(([level]) => level === 'debug').map(([, m]) => m); + expect(debug).toContain("[knowledge] source 'kw' searched in 'keyword' mode (declared by the source)."); + expect(debug).toContain("[knowledge] source 'dflt' searched in 'hybrid' mode (the default of adapter 'turso')."); + expect(JSON.stringify(report)).not.toMatch(/keyword|hybrid|retrieval/); + }); +}); + +describe('a declared mode the adapter does not run — the four refusal points', () => { + function bootLike() { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const memory = adapterOf('memory'); + return { svc, vec, memory, lines }; + } + + it('1 · the save is refused 400 VALIDATION_ERROR, listing the modes the store runs', async () => { + const svc = new KnowledgeService({ dataEngine: {} as IDataEngine }); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const ctx = { userId: 'u1', positions: [], permissions: [] } as never; + const onVec = await svc.admitAuthoredSource(source('s1', 'vec', 'keyword'), ctx); + expect(onVec).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onVec as { message: string }).message).toContain("the store 'vec' runs 'vector' (default 'vector')"); + const onMemory = await svc.admitAuthoredSource(source('s2', 'memory', 'hybrid'), ctx); + expect(onMemory).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onMemory as { message: string }).message).toContain("the store 'memory' reports no retrieval modes"); + // A mode the store runs passes this point (the save goes on to its next check). + const ok = await svc.admitAuthoredSource(source('s3', 'vec', 'vector'), ctx); + expect((ok as { message?: string }).message ?? '').not.toContain('retrieval.mode'); + }); + + it('2 · registration refuses it only when its adapter already resolves', () => { + const { svc, vec } = bootLike(); + svc.registerAdapter('vec', vec); + let refused: unknown; + try { + svc.registerSource(source('s1', 'vec', 'keyword')); + } catch (err) { + refused = err; + } + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("registerSource refused source 's1': its `retrieval.mode` is 'keyword'"); + expect(svc.getSource('s1')).toBeUndefined(); + expect(() => svc.registerMetadataSource(source('s2', 'vec', 'hybrid'))).toThrow(/knowledge_source loader refused source 's2'/); + expect(svc.getSource('s2')).toBeUndefined(); + // A store not registered yet is no verdict: the source is taken. + svc.registerSource(source('s3', 'pgvector', 'keyword')); + expect(svc.getSource('s3')).toBeDefined(); + }); + + it('3 · the boot reading names it once at error; 4 · every search lists it in `refused`, never runs it at the default', async () => { + const { svc, vec, lines } = bootLike(); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('good', 'vec')); + svc.registerAdapter('vec', vec); + + expect(svc.reportUnsupportedRetrieval()).toEqual(['bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + expect(errors[0]).toContain(`answers ${RETRIEVAL_UNSUPPORTED_CODE}`); + + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(both.refused[0]!.message).toContain("Knowledge source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + // Never searched another way. + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['good']); + + const alone = await svc.search('q', { sourceIds: ['bad'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + }); + + it('a mode declared on an adapter that reports none is refused at every search the same way', async () => { + const { svc, memory } = bootLike(); + svc.registerSource(source('s1', 'memory', 'vector')); + svc.registerAdapter('memory', memory); + expect(svc.reportUnsupportedRetrieval()).toEqual(['s1']); + const alone = await svc.search('q', { sourceIds: ['s1'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + expect(memory.searchSpy).not.toHaveBeenCalled(); + }); + + it('such a source is still indexed: the mode is read by search alone', async () => { + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerAdapter('vec', vec); + const res = await svc.reindexSource('bad'); + expect(res.ok).toBe(true); + expect(res.indexed).toBe(1); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + }); + + it('a source on a store not mounted is named by the unmounted reading, not this one', () => { + const { svc } = bootLike(); + svc.registerSource(source('s1', 'pgvector', 'keyword')); + expect(svc.reportUnsupportedRetrieval()).toEqual([]); + expect(svc.describeRetrieval(svc.getSource('s1')!)).toBeUndefined(); + }); + + it('the plugin takes the reading at kernel:bootstrapped, beside the unmounted-adapter reading', async () => { + const reading = vi.spyOn(KnowledgeService.prototype, 'reportUnsupportedRetrieval'); + try { + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use( + new KnowledgeServicePlugin({ + sources: [source('bad', 'vec', 'keyword'), source('good', 'vec')], + enableEventSync: false, + buildAtBoot: false, + }), + ); + kernel.use({ + name: 'test.late-store', + init: async () => undefined, + start: async (ctx) => { + ctx.getService('knowledge').registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + }, + }); + await kernel.bootstrap(); + expect(reading).toHaveBeenCalledTimes(1); + expect(reading.mock.results[0]?.value).toEqual(['bad']); + await kernel.shutdown(); + } finally { + reading.mockRestore(); + } + }); +}); + +describe('index_status carries each source\'s retrieval and each store\'s modes', () => { + it('the effective mode and its origin, the refusal, and "reports none" as an absent member', async () => { + const svc = new KnowledgeService(); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('plain', 'memory')); + svc.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const answer = await knowledgeIndexStatusActionHandler(svc)({ + namespace: 'knowledge', + actionId: 'index_status', + values: {}, + payload: {}, + ctx: {}, + } as never); + const details = (answer as { details: { sources: Array<{ id: string; retrieval?: unknown }>; adapters: unknown } }).details; + const byId = Object.fromEntries(details.sources.map((s) => [s.id, s.retrieval])); + expect(byId.dflt).toEqual({ mode: 'hybrid', from: 'adapter', modes: ALL_MODES, default: 'hybrid' }); + expect(byId.bad).toEqual({ declared: 'keyword', refused: true, modes: ['vector'], default: 'vector' }); + expect(byId.plain).toEqual({}); + expect(details.adapters).toEqual([ + { id: 'turso', retrieval: { modes: ALL_MODES, default: 'hybrid' } }, + { id: 'vec', retrieval: { modes: ['vector'], default: 'vector' } }, + { id: 'memory' }, + ]); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 7b6e8f6ac82..0b68acfa628 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -64,10 +64,12 @@ export { knowledgeRebuildActionHandler, } from './knowledge-build-actions.js'; export type { + KnowledgeIndexStatusAdapter, KnowledgeIndexStatusBuild, KnowledgeIndexStatusEntry, KnowledgeIndexStatusQueue, } from './knowledge-build-actions.js'; +export type { KnowledgeRetrievalReading, RetrievalModeOrigin } from './knowledge-retrieval-mode.js'; export { KNOWLEDGE_SYNC_STATE_OBJECT, ObjectStoreKnowledgeSyncState } from './knowledge-sync-state.js'; export type { KnowledgeStoredBuild, diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index a8540c0f8bb..77cb3b00e74 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -47,6 +47,8 @@ import type { import type { KnowledgeService, KnowledgeSourceDescription } from './knowledge-service.js'; import type { KnowledgeStoredBuild, KnowledgeSyncFailures } from './knowledge-sync-state.js'; import { KNOWLEDGE_RECORD_SYNC_QUEUE } from './knowledge-record-sync-queue.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; +import type { KnowledgeRetrievalMode } from '@objectstack/spec/ai'; /** The `knowledge` settings action that starts a rebuild of one source. */ export const KNOWLEDGE_REBUILD_ACTION = 'rebuild'; @@ -66,6 +68,9 @@ export type KnowledgeBuildActionsService = Pick< | 'syncStateOf' | 'hasDurableSyncState' | 'pendingRecordSyncs' + | 'describeRetrieval' + | 'listAdapters' + | 'getAdapter' >; /** One source in an `index_status` answer. */ @@ -88,6 +93,19 @@ export interface KnowledgeIndexStatusEntry { failures: KnowledgeSyncFailures | null; /** Why the sync state could not be read; absent when it was. */ syncStateError?: string; + /** + * The source's retrieval mode (#38692 phase 1a): the mode its searches run + * and where it came from, the modes its adapter runs, and whether its + * searches are refused. Absent while its adapter is not placed or mounted. + */ + retrieval?: KnowledgeRetrievalReading; +} + +/** One mounted adapter in an `index_status` answer, and the retrieval modes it reports. */ +export interface KnowledgeIndexStatusAdapter { + id: string; + /** The modes it runs and its default; absent: it reports none (Studio shows "驱动未声明"). */ + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }; } /** @@ -327,6 +345,7 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions const sources: KnowledgeIndexStatusEntry[] = []; for (const source of targets) { const adapter = service.boundAdapterId(source.source); + const retrieval = service.describeRetrieval(source.source); sources.push({ id: source.id, label: source.source.label, @@ -334,8 +353,13 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ...(source.packageId === undefined ? {} : { packageId: source.packageId }), index: await service.readIndexState(source.id), ...(await readSyncState(service, source.id)), + ...(retrieval === undefined ? {} : { retrieval }), }); } + const adapters: KnowledgeIndexStatusAdapter[] = service.listAdapters().map((id) => { + const report = service.getAdapter(id).capabilities?.retrieval; + return { id, ...(report === undefined ? {} : { retrieval: { modes: [...report.modes], default: report.default } }) }; + }); const queue = await readQueue(service); const due = sources.filter((s) => s.index.due).length; const running = sources.filter((s) => s.build?.status === 'running').length; @@ -345,7 +369,7 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ok: true, severity: 'info', message: `${sources.length} source(s): ${due} need a build, ${running} building, ${failing} with failed syncs${pending}.`, - details: { sources, ...(queue === undefined ? {} : { queue }) }, + details: { sources, adapters, ...(queue === undefined ? {} : { queue }) }, }; }; } diff --git a/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts new file mode 100644 index 00000000000..55465193229 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts @@ -0,0 +1,136 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A source's retrieval mode (ADR-0161, the dated note on retrieval modes; + * ruling 7270218011 on #38692, phase 1a): which mode a search of the source + * runs, where that came from, and the refusal of a mode its adapter does not + * run. + * + * ## The effective mode + * + * The source's declaration (`source.retrieval.mode`), else the adapter's + * reported default (`capabilities.retrieval.default`). An adapter that + * reports no modes is never told one: a source on it that declares none is + * searched as before, and one that declares a mode is refused. + * + * ## The four refusal points + * + * A source that declares a mode its adapter does not list is refused, never + * searched another way: + * + * 1. at an author's save (Studio, REST, an MCP draft): `400 + * VALIDATION_ERROR`, listing the modes the adapter runs + * (`admitAuthoredSource`); + * 2. at registration, only when its adapter already resolves — a store + * registers in its own `start()`, after a source registered at `init()`, + * so "not registered yet" is no verdict (AGENTS.md, startup registry + * reads); a package install meets no save, so 3 and 4 hold it + * (`registerSource`, `registerMetadataSource`); + * 3. once after boot, at `error`, naming the source and the modes + * (`reportUnsupportedRetrieval`, beside `reportUnmountedAdapters`); + * 4. on every search: the source is listed in `refused` with + * {@link RETRIEVAL_UNSUPPORTED_CODE}, as a source whose adapter is not + * mounted is (`planSearches`). + * + * Such a source still builds and syncs its index: the mode is read by search + * alone, so changing it rebuilds nothing. + */ + +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; + +/** + * The code of a search refused because the source declares a mode its + * adapter does not run: the code a source whose adapter is not mounted is + * refused with, since in both the deployment cannot serve the source as + * written (`503`). + */ +export const RETRIEVAL_UNSUPPORTED_CODE = 'SERVICE_UNAVAILABLE'; + +/** Where a search's effective mode came from. */ +export type RetrievalModeOrigin = 'source' | 'adapter'; + +/** {@link resolveRetrievalMode}'s answer. */ +export type RetrievalResolution = + /** Searched in `mode`, from `from`; absent `mode`: the adapter reports no modes and none is declared. */ + | { refused: false; mode?: KnowledgeRetrievalMode; from?: RetrievalModeOrigin } + /** The source declares `declared`, which the adapter does not list (`modes`; absent: it reports none). */ + | { refused: true; declared: KnowledgeRetrievalMode; modes?: readonly KnowledgeRetrievalMode[] }; + +/** + * A source's retrieval as the operator reads it (the `index_status` entry's + * `retrieval`): never in a search's answer to the caller. + */ +export interface KnowledgeRetrievalReading { + /** The mode the source declares; absent: it declares none. */ + declared?: KnowledgeRetrievalMode; + /** The mode its searches run; absent when refused, or when the adapter reports no modes and none is declared. */ + mode?: KnowledgeRetrievalMode; + /** Where {@link mode} came from. */ + from?: RetrievalModeOrigin; + /** The modes its adapter runs; absent: the adapter reports none (Studio shows "驱动未声明"). */ + modes?: readonly KnowledgeRetrievalMode[]; + /** Its adapter's default mode; absent with {@link modes}. */ + default?: KnowledgeRetrievalMode; + /** Every search of it is refused with {@link RETRIEVAL_UNSUPPORTED_CODE}: it declares a mode its adapter does not run. */ + refused?: true; +} + +/** {@link KnowledgeRetrievalReading} of `source` on `adapter`. */ +export function readRetrieval(source: Pick, adapter: IKnowledgeAdapter): KnowledgeRetrievalReading { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + const resolved = resolveRetrievalMode(source, adapter); + return { + ...(declared === undefined ? {} : { declared }), + ...(resolved.refused ? { refused: true as const } : {}), + ...(!resolved.refused && resolved.mode !== undefined ? { mode: resolved.mode, from: resolved.from } : {}), + ...(report === undefined ? {} : { modes: [...report.modes], default: report.default }), + }; +} + +/** The mode `source` declares, if any (`retrieval: {}` declares none). */ +export function declaredRetrievalMode(source: Pick): KnowledgeRetrievalMode | undefined { + return source.source?.retrieval?.mode; +} + +/** The effective mode of a search of `source` on `adapter`, or the refusal (see the module header). */ +export function resolveRetrievalMode(source: Pick, adapter: IKnowledgeAdapter): RetrievalResolution { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + if (declared === undefined) { + return report === undefined ? { refused: false } : { refused: false, mode: report.default, from: 'adapter' }; + } + if (report === undefined || !report.modes.includes(declared)) { + return { refused: true, declared, ...(report === undefined ? {} : { modes: report.modes }) }; + } + return { refused: false, mode: declared, from: 'source' }; +} + +/** The modes an adapter runs, as a sentence part: `'vector', 'keyword' and 'hybrid' (default 'hybrid')`, or that it reports none. */ +export function adapterModesText(adapterId: string, modes: readonly KnowledgeRetrievalMode[] | undefined, byDefault?: KnowledgeRetrievalMode): string { + if (modes === undefined || modes.length === 0) return `the store '${adapterId}' reports no retrieval modes, so a source on it may only leave \`retrieval.mode\` out`; + const listed = modes.map((m) => `'${m}'`); + const joined = listed.length === 1 ? listed[0] : `${listed.slice(0, -1).join(', ')} and ${listed[listed.length - 1]}`; + return `the store '${adapterId}' runs ${joined}${byDefault === undefined ? '' : ` (default '${byDefault}')`}`; +} + +/** + * Why a source declaring `declared` is refused on `adapterId`, and what to + * write: the rule, then the remedies. One text for every point; each point + * puts its own subject before it and its own consequence after it. + */ +export function retrievalRefusalText( + adapterId: string, + declared: KnowledgeRetrievalMode, + adapter: IKnowledgeAdapter, +): string { + const report = adapter.capabilities?.retrieval; + const remedies = report === undefined || report.modes.length === 0 + ? 'Remove `retrieval.mode`, or bind the source to a store that runs it' + : `Write one of ${report.modes.map((m) => `'${m}'`).join(', ')} as \`retrieval.mode\`, or remove it for the store's default, or bind the source to a store that runs '${declared}'`; + return ( + `its \`retrieval.mode\` is '${declared}', and ${adapterModesText(adapterId, report?.modes, report?.default)}; ` + + `a source is never searched in a mode other than the one it declares. ${remedies}.` + ); +} diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts index eef37eca116..eb2b8aed082 100644 --- a/packages/services/service-knowledge/src/knowledge-service-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -65,6 +65,7 @@ import { unplacedSourceText, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -75,7 +76,9 @@ import type { KnowledgeService } from './knowledge-service.js'; * body here assigns. */ export interface KnowledgeAdmissionHost { + readonly adapters: KnowledgeService['adapters']; readonly admissionDeps: KnowledgeService['admissionDeps']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; readonly handed: KnowledgeService['handed']; readonly handedSources: KnowledgeService['handedSources']; readonly held: KnowledgeService['held']; @@ -192,7 +195,14 @@ export function admissionDeps( export async function admitAuthoredSource( this: Pick< KnowledgeAdmissionHost, - 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' + | 'adapters' + | 'admissionDeps' + | 'boundAdapterId' + | 'held' + | 'listAdapters' + | 'options' + | 'reportGateFailure' + | 'unmountedAdapterSaveText' >, item: unknown, ctx: ExecutionContext | undefined, @@ -255,6 +265,22 @@ export async function admitAuthoredSource( if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); } + // [ADR-0161, the dated note on retrieval modes; refusal point 1] A source + // that declares a retrieval mode its store does not run is refused at its + // save, listing the modes the store runs. The store is the one it names, + // else the deployment's: both are registered by now (above). A mode + // outside the three is the parse's to refuse. + const declaredMode = (declared as { retrieval?: { mode?: unknown } }).retrieval?.mode; + if (declaredMode === 'vector' || declaredMode === 'keyword' || declaredMode === 'hybrid') { + const adapterId = this.boundAdapterId({ adapter: typeof authoredAdapter === 'string' ? authoredAdapter : undefined } as KnowledgeSource); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId !== undefined && adapter !== undefined) { + const resolved = resolveRetrievalMode({ source: { retrieval: { mode: declaredMode } } } as KnowledgeSource, adapter); + if (resolved.refused) { + return refuse(400, 'VALIDATION_ERROR', `${named}: ${retrievalRefusalText(adapterId, declaredMode, adapter)}`); + } + } + } const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index db57d22e7a8..c129dc6dbc8 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -782,11 +782,13 @@ export class KnowledgeServicePlugin implements Plugin { } }); // Every store registers its adapter in its own start(), so the reading of - // which sources name an unmounted one is taken once all have started. + // which sources name an unmounted one, or a retrieval mode their store + // does not run, is taken once all have started. // Held, the one line of the held state names what is missing instead. ctx.hook('kernel:bootstrapped', () => { if (this.service?.heldReading()) return; this.service?.reportUnmountedAdapters(); + this.service?.reportUnsupportedRetrieval(); }); // [ADR-0161 K1] The daily reconcile. The job service may start after this // plugin: it is resolved once every plugin has started, when an absent diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index e2d2e8e440d..c55fa078483 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -38,6 +38,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { TenancyPosture } from '@objectstack/spec/security'; import { refusal } from './knowledge-tools.js'; +import { RETRIEVAL_UNSUPPORTED_CODE, resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; import { type AffinityCallerFacts, affinityFactNeeds, @@ -777,6 +778,33 @@ export async function planSearches( out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); continue; } + // [#38692 phase 1a] The effective retrieval mode: the source's + // declaration, else the adapter's default. A declared mode the adapter + // does not run is refused like an adapter that cannot serve, never + // searched another way; the boot said so at `error` + // (`reportUnsupportedRetrieval`). The mode and where it came from are the + // operator's, at `debug`, never the caller's answer. + const retrieval = resolveRetrievalMode(entry.source, adapter); + if (retrieval.refused) { + out.push({ + ...entry, + binding: { + refusal: { + code: RETRIEVAL_UNSUPPORTED_CODE, + status: 503, + message: `Knowledge source '${this.label(entry.source)}' is not searched: ` + + retrievalRefusalText(adapterId, retrieval.declared, adapter), + }, + }, + }); + continue; + } + if (retrieval.mode !== undefined) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' searched in '${retrieval.mode}' mode ` + + `(${retrieval.from === 'source' ? 'declared by the source' : `the default of adapter '${adapterId}'`}).`, + ); + } const plan = await this.planIndex(entry.source, adapter, chunkTarget); if (proveIndex === true) { const unproven = await this.unprovenIndex(plan); @@ -803,6 +831,7 @@ export async function planSearches( binding: { adapterId, adapter }, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}), + ...(retrieval.mode === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); } return out; @@ -908,7 +937,7 @@ export async function searchRound( refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding } of sources) { + for (const { source, organizationIds, fingerprint, scope, binding, retrieval } of sources) { // Refused like an adapter that cannot serve: the caller is told which // source was not searched and why; the boot said so at `error` // (`reportUnmountedAdapters`), so no line per search. The adapter was @@ -927,6 +956,7 @@ export async function searchRound( ...(organizationIds === undefined ? {} : { organizationIds }), ...(fingerprint === undefined ? {} : { index: { fingerprint } }), ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), + ...(retrieval === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index a46f5c61400..bf546185205 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -8,7 +8,10 @@ * `onSourcesChanged`, `sourcesChanged`, `unregisterSource`, `dropMetadataSource`, * `forget`, `listSources`, `describeSources`, `getSource`, `describeSource`, * `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry`, moved - * out of `knowledge-service.ts` whole. + * out of `knowledge-service.ts` whole. `reportUnsupportedRetrieval`, `describeRetrieval` and + * the registration refusal beside them were written here (#38692 phase 1a), the + * retrieval-mode counterparts of `reportUnmountedAdapters` and + * `refuseUnplacedSource`. * * A MOVE, not a redesign. Each function below is the body of the * `KnowledgeService` member of the same name as it stood, re-indented one @@ -51,6 +54,13 @@ import { unplacedSourceError, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { + type KnowledgeRetrievalReading, + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -187,6 +197,65 @@ export function reportUnmountedAdapters( return named; } +/** + * Refuse, at registration, a source that declares a retrieval mode its + * adapter does not run (#38692 phase 1a, refusal point 2) — only when that + * adapter already resolves: a store registers in its own `start()`, after a + * source registered at `init()`, so "not registered yet" is no verdict + * (AGENTS.md, startup registry reads). The boot's reading + * ({@link reportUnsupportedRetrieval}) and every search hold the rest. + */ +function refuseUnsupportedRetrieval( + this: Pick, + source: KnowledgeSource, + door: string, +): void { + if (source.source?.retrieval?.mode === undefined) return; + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) return; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) return; + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] ${door} refused source '${source.name}': ${retrievalRefusalText(adapterId, resolved.declared, adapter)}`, + ); +} + +/** The body of {@link KnowledgeService.reportUnsupportedRetrieval}; the member's docblock there is its contract. */ +export function reportUnsupportedRetrieval( + this: Pick, +): string[] { + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.source?.retrieval?.mode === undefined) continue; + // A source this boot cannot place, or whose adapter is not mounted, is + // named by `reportUnmountedAdapters`; its mode has no adapter to read. + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) continue; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) continue; + this.options.logger?.error?.( + `[knowledge] source '${id}' is not searched: ${retrievalRefusalText(adapterId, resolved.declared, adapter)} ` + + `Every search of it answers ${RETRIEVAL_UNSUPPORTED_CODE} until then; it is still indexed.`, + ); + named.push(id); + } + return named; +} + +/** The body of {@link KnowledgeService.describeRetrieval}; the member's docblock there is its contract. */ +export function describeRetrieval( + this: Pick, + source: KnowledgeSource, +): KnowledgeRetrievalReading | undefined { + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + return adapter === undefined ? undefined : readRetrieval(source, adapter); +} + /** The body of {@link KnowledgeService.listAdapters}; the member's docblock there is its contract. */ export function listAdapters(this: Pick): string[] { return [...this.adapters.keys()]; @@ -194,7 +263,10 @@ export function listAdapters(this: Pick): stri /** The body of {@link KnowledgeService.registerSource}; the member's docblock there is its contract. */ export function registerSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, ): void { const parsed = parseKnowledgeSource(source); @@ -206,6 +278,7 @@ export function registerSource( ); } this.refuseUnplacedSource(parsed.source, 'registerSource'); + refuseUnsupportedRetrieval.call(this, parsed.source, 'registerSource'); const packageId = packageIdOfItem(parsed.source); if (packageId !== undefined) { throw codedError( @@ -224,11 +297,15 @@ export function registerSource( /** The body of {@link KnowledgeService.registerMetadataSource}; the member's docblock there is its contract. */ export function registerMetadataSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, holder: KnowledgeSourceHolder = {}, ): KnowledgeSourceEntry { this.refuseUnplacedSource(source, 'The knowledge_source loader'); + refuseUnsupportedRetrieval.call(this, source, 'The knowledge_source loader'); const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index 21c8398272a..2c3f4df3094 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -22,7 +22,13 @@ import type { IQueueService, } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { + KnowledgeDocument, + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; import { type TenancyPosture, postureEnforcesWall } from '@objectstack/spec/security'; import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; @@ -353,6 +359,11 @@ export interface SearchTarget { scope?: AdapterScopeTerm[]; /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ verifyHits?: true; + /** + * The effective retrieval mode the adapter is told (`knowledge-retrieval-mode.ts`): + * absent where the adapter reports no modes and the source declares none. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 1382ceaf226..b490863ec70 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -22,6 +22,7 @@ import { } from './knowledge-source-registry.js'; import type { KnowledgeAdmissionDeps } from './knowledge-source-admission.js'; import type { SearchScopeEntry } from './knowledge-search-scope.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; import type { KnowledgeBuildFence, KnowledgeBuildProgress, @@ -285,6 +286,28 @@ export class KnowledgeService implements IKnowledgeService { return KnowledgeSourcesFacet.reportUnmountedAdapters.call(knowledgeServiceHost.of(this)); } + /** + * Say once, at `error`, which registered sources declare a retrieval mode + * (`source.retrieval.mode`) their mounted adapter does not run — the boot's + * reading, taken beside {@link reportUnmountedAdapters} (#38692 phase 1a, + * refusal point 3). Every search of such a source lists it in `refused`; + * it is still indexed. Answers the sources named. + */ + reportUnsupportedRetrieval(): string[] { + return KnowledgeSourcesFacet.reportUnsupportedRetrieval.call(knowledgeServiceHost.of(this)); + } + + /** + * `source`'s retrieval mode as the operator reads it: the mode it declares, + * the one its searches run and where that came from, the modes its adapter + * runs, and whether its searches are refused (`knowledge-retrieval-mode.ts`). + * `undefined` while its adapter is not placed or not mounted. For a status + * answer, never for a search's answer. + */ + describeRetrieval(source: KnowledgeSource): KnowledgeRetrievalReading | undefined { + return KnowledgeSourcesFacet.describeRetrieval.call(knowledgeServiceHost.of(this), source); + } + listAdapters(): string[] { return KnowledgeSourcesFacet.listAdapters.call(knowledgeServiceHost.of(this)); } diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 1eb8060fa13..99fc4436830 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -79,6 +79,10 @@ * (`capabilities.retrieval`), and the same fixture is searched under each * mode it lists: `vector` leaves that passage out, `keyword` answers it * alone, and the default handed explicitly answers what no mode answers. + * Through a real `KnowledgeService`, every adapter is handed the mode a + * source declares, or its own default, or nothing when it reports no modes; + * a declared mode it does not list is refused at registration and at every + * search, and the source still indexes. */ import { describe, expect, it, vi } from 'vitest'; @@ -90,7 +94,7 @@ import type { AdapterScopeTerm, AdapterSearchOptions, } from '@objectstack/spec/contracts'; -import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeDocument, KnowledgeRetrievalMode, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import { KNOWLEDGE_RETRIEVAL_MODES } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; @@ -707,6 +711,57 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + describe('the retrieval mode through KnowledgeService.search (#38692 phase 1a)', () => { + const ROWS: Row[] = [{ id: 'r1', body: 'alpine meadow harbour', status: 'published' }]; + const withMode = (id: string, mode?: KnowledgeRetrievalMode): KnowledgeSource => + objectSource(id, mode === undefined ? {} : { retrieval: { mode } }); + + it('no mode declared: the adapter is handed its own default, or nothing when it reports no modes', async () => { + const source = withMode('mode_default'); + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + const report = h.adapter.capabilities?.retrieval; + expect(lastOf(h.searched)?.retrieval).toEqual(report === undefined ? undefined : { mode: report.default }); + }); + + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + it(`'${mode}' declared: handed to the adapter when it lists it, refused at registration and at every search when it does not`, async () => { + const source = withMode(`mode_${mode}`, mode); + const probe: IKnowledgeAdapter = await make(); + const listed = probe.capabilities?.retrieval?.modes.includes(mode) === true; + if (listed) { + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + expect(lastOf(h.searched)?.retrieval).toEqual({ mode }); + return; + } + // Its adapter already registered: registration refuses it. + const refused = await serviceOver(make, ROWS, source).then( + () => undefined, + (err: unknown) => err, + ); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + // Registered before its store: it still indexes, and every search refuses it, never run another way. + const svc = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + svc.registerSource(source); + const adapter: IKnowledgeAdapter = await make(); + const search = vi.spyOn(adapter, 'search'); + svc.registerAdapter('under_test', adapter); + expect(await svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(svc.reportUnsupportedRetrieval()).toEqual([source.name]); + // The only source asked for is refused, so the search answers the refusal, naming it. + const alone = await svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((alone as { refused?: unknown }).refused).toEqual([ + expect.objectContaining({ sourceId: source.name, code: 'SERVICE_UNAVAILABLE', status: 503 }), + ]); + expect(search).not.toHaveBeenCalled(); + }); + } + }); + describe('the organization filter through KnowledgeService.search', () => { for (const posture of ['isolated', 'group'] as const) { it(`${posture}: a search from organization A never ranks or returns B's documents`, async () => { diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index ca269505e36..82de1c5c772 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -122,14 +122,18 @@ } }, "retrieval": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — the effective mode: the source's declaration, else the adapter's `capabilities.retrieval.default`; packages/services/service-knowledge/src/knowledge-service-search.ts#planSearches — every search resolves it, hands it to the adapter as `AdapterSearchOptions.retrieval` (`searchRound`) and refuses a mode the adapter does not list in `refused` (SERVICE_UNAVAILABLE); packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses it (400 VALIDATION_ERROR, listing the modes the store runs); packages/services/service-knowledge/src/knowledge-service-sources.ts#registerSource / #registerMetadataSource — registration refuses it when the adapter already resolves; packages/services/service-knowledge/src/knowledge-service-sources.ts#reportUnsupportedRetrieval — the boot's reading names it at `error`.", + "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": "Ruling 7270218011 on #38692, phase 1a (ADR-0161, the dated note on retrieval modes). Strict, `retrieval: {}` allowed. Read by search alone: enters neither the index fingerprint nor the recipe hash, so changing it rebuilds nothing, and a source whose mode is refused still indexes. knowledge-turso and knowledge-pgvector run each mode; an adapter that reports no modes (knowledge-memory) takes a source that leaves the mode out.", "children": { "mode": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — `vector`, `keyword` or `hybrid`, handed to the adapter as `AdapterSearchOptions.retrieval.mode`; omitted means the adapter's default." } } }, diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index 1fcc479c9f3..011bd5fd35d 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` | 26 | 0 | 0 | 6 | 1 | 33 | +| `knowledge_source` | 27 | 0 | 0 | 6 | 0 | 33 | From e8053716659c3d779cafe585328098641c1658bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:25:08 +0000 Subject: [PATCH 13/23] test(spec): pin KnowledgeRetrievalModeSchema as isomorphic (ADR-0122) Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- packages/spec/src/type-alias-convention.pin.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 79d059e5ed7..0cfb59e9f2d 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -393,6 +393,7 @@ export type Iso_ai_knowledgeDocument__KnowledgeDocumentSchema = Assert, z.infer< typeof M3.KnowledgeHitSchema > >>; // ai/knowledge-source.zod.ts +export type Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema = Assert, z.infer< typeof M4.KnowledgeRetrievalModeSchema > >>; export type Iso_ai_knowledgeSource__ObjectKnowledgeSourceSchema = Assert, z.infer< typeof M4.ObjectKnowledgeSourceSchema > >>; // ai/mcp.zod.ts From 14b8b7a4ae831f7a73d91ac2289bfa5be1152321 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:35:41 +0000 Subject: [PATCH 14/23] docs(knowledge): the adapter contract carries the retrieval mode; name its per-search refusal code ADR-0161's K2 row on the adapter surface no longer says "no hybrid toggle": the contract carries the modes an adapter runs and the mode a search runs in, which a source declares. Protocol doc 7.1 says the same. The contract doc of AdapterSearchOptions.retrieval names the refusal of a mode the adapter does not list: SERVICE_UNAVAILABLE in a search's refused, VALIDATION_ERROR at save and registration. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 4 +++- ...plit-record-return-knowledge-source-is-a-governed-type.md | 2 +- packages/spec/src/contracts/knowledge-adapter.ts | 5 +++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..685004cae35 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -1504,7 +1504,9 @@ followed (§4.1, §4.2) are the adapters to run in production. ### 7.1 Non-goals for Phase 1 -- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private. +- Reranker hooks, MMR — adapter-private. Which legs a search runs is not: + a source declares it (`source.retrieval.mode`, §3.1); how the legs are + weighted is not authorable yet. - Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller. diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index e8612d48a02..0f771225031 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -147,7 +147,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and still no configuration, no rerank and no hybrid toggle. | #37096, then each card that adds a member | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4d729a55900..0790d351e29 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -192,6 +192,11 @@ export interface AdapterSearchOptions { * The service hands only a mode the adapter lists in * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * A source declaring a mode its adapter does not list is never searched + * another way: the knowledge service lists it in a search's `refused` with + * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose + * adapter is not mounted is refused with there), and refuses it at its save + * and registration with `VALIDATION_ERROR` (400). * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From dc6954442644f2d099e90cfe4f96b16405e2d071 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:40:05 +0000 Subject: [PATCH 15/23] feat(service-knowledge): index_status names the store a source that names none binds to Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../__tests__/retrieval-mode-38692.test.ts | 19 ++++++++++++++++++- .../src/knowledge-build-actions.ts | 17 ++++++++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts index bf60bc42504..6556c7e1ac8 100644 --- a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts +++ b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts @@ -304,7 +304,11 @@ describe('index_status carries each source\'s retrieval and each store\'s modes' payload: {}, ctx: {}, } as never); - const details = (answer as { details: { sources: Array<{ id: string; retrieval?: unknown }>; adapters: unknown } }).details; + const details = (answer as { + details: { sources: Array<{ id: string; retrieval?: unknown }>; adapters: unknown; defaultAdapter?: string }; + }).details; + // Three stores and none marked the deployment's: a source naming none binds to none. + expect(details.defaultAdapter).toBeUndefined(); const byId = Object.fromEntries(details.sources.map((s) => [s.id, s.retrieval])); expect(byId.dflt).toEqual({ mode: 'hybrid', from: 'adapter', modes: ALL_MODES, default: 'hybrid' }); expect(byId.bad).toEqual({ declared: 'keyword', refused: true, modes: ['vector'], default: 'vector' }); @@ -315,4 +319,17 @@ describe('index_status carries each source\'s retrieval and each store\'s modes' { id: 'memory' }, ]); }); + + it('names the store a source that names none binds to: the deployment\'s, else the only one', async () => { + const marked = new KnowledgeService({ deploymentAdapter: 'turso' }); + marked.registerAdapter('memory', adapterOf('memory')); + marked.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + const only = new KnowledgeService(); + only.registerAdapter('memory', adapterOf('memory')); + const ask = { namespace: 'knowledge', actionId: 'index_status', values: {}, payload: {}, ctx: {} } as never; + const read = async (svc: KnowledgeService) => + ((await knowledgeIndexStatusActionHandler(svc)(ask)) as { details: { defaultAdapter?: string } }).details.defaultAdapter; + expect(await read(marked)).toBe('turso'); + expect(await read(only)).toBe('memory'); + }); }); diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index 77cb3b00e74..accd5719635 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -21,7 +21,10 @@ * build, with its counts while it runs and once it ended, and its record * syncs that failed and are not yet repaired. Beside the sources, the * record-sync messages waiting on the queue (`pendingRecordSyncs`, every - * source's together). + * source's together). [#38692 phase 1a] Each source's retrieval reading + * (`retrieval`: its effective mode and where it came from, the modes its + * store runs, a refusal), each mounted store's modes (`adapters`) and the + * store a source that names none binds to (`defaultAdapter`). * * Both run through the settings action door (`POST /api/settings/knowledge/ACTION`), * which gates an HTTP caller on the namespace's write permission, @@ -48,7 +51,7 @@ import type { KnowledgeService, KnowledgeSourceDescription } from './knowledge-s import type { KnowledgeStoredBuild, KnowledgeSyncFailures } from './knowledge-sync-state.js'; import { KNOWLEDGE_RECORD_SYNC_QUEUE } from './knowledge-record-sync-queue.js'; import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; -import type { KnowledgeRetrievalMode } from '@objectstack/spec/ai'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; /** The `knowledge` settings action that starts a rebuild of one source. */ export const KNOWLEDGE_REBUILD_ACTION = 'rebuild'; @@ -356,6 +359,9 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ...(retrieval === undefined ? {} : { retrieval }), }); } + // The store a source that names none binds to (ADR-0161 K4), for a form + // that shows a new source's retrieval modes before it names a store. + const defaultAdapter = service.boundAdapterId({ name: '', label: '' } as unknown as KnowledgeSource); const adapters: KnowledgeIndexStatusAdapter[] = service.listAdapters().map((id) => { const report = service.getAdapter(id).capabilities?.retrieval; return { id, ...(report === undefined ? {} : { retrieval: { modes: [...report.modes], default: report.default } }) }; @@ -369,7 +375,12 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ok: true, severity: 'info', message: `${sources.length} source(s): ${due} need a build, ${running} building, ${failing} with failed syncs${pending}.`, - details: { sources, adapters, ...(queue === undefined ? {} : { queue }) }, + details: { + sources, + adapters, + ...(defaultAdapter === undefined ? {} : { defaultAdapter }), + ...(queue === undefined ? {} : { queue }), + }, }; }; } From 08788c6156c1e92d49d4dbe5c5cbfe571b829675 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:32:14 +0000 Subject: [PATCH 16/23] fix(platform-objects): name the retrieval-mode choices in every locale; count the new isomorphic pin The knowledge source form's Search group and its Retrieval mode select get their translation bundle entries, translated in the ten locales, and the ADR-0122 pin count moves 880 -> 881 for KnowledgeRetrievalModeSchema. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../translations/ar.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/de.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/en.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/fr.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ja-JP.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ko.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/pt-BR.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ru.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 13 +++++++++++++ .../zh-Hant.metadata-forms.generated.ts | 13 +++++++++++++ packages/spec/src/type-alias-convention.pin.test.ts | 10 +++++++--- 12 files changed, 150 insertions(+), 3 deletions(-) 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 122b54abb87..077577dcfa0 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 @@ -3565,6 +3565,19 @@ export const arMetadataForms: NonNullable = { 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.retrieval": { + label: "البحث", + helpText: "كيف يعثر البحث في هذا المصدر على المقاطع. اتركه فارغًا لاستخدام الوضع الافتراضي للمخزن. تغييره لا يعيد بناء أي شيء." + }, + "source.retrieval.mode": { + label: "وضع الاسترجاع", + helpText: "فارغ: الوضع الافتراضي للمخزن (هجين في turso وpgvector). المتجه يرتّب المقاطع حسب المعنى؛ والكلمات المفتاحية حسب الكلمات التي تحتويها، دون استدعاء مزوّد التضمين، وهو ما يناسب أرقام المستندات أو البنود؛ والهجين يدمج الاثنين. يُرفض عند الحفظ أي وضع لا يشغّله المخزن.", + options: { + vector: "المتجه فقط (حسب المعنى)", + keyword: "الكلمات المفتاحية فقط (حسب الكلمات)", + hybrid: "هجين (كلاهما)" + } + }, "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.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index fa9fe31de92..31d44962244 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 @@ -3565,6 +3565,19 @@ export const deMetadataForms: NonNullable = { 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.retrieval": { + label: "Suche", + helpText: "Wie eine Suche in dieser Quelle Passagen findet. Leer lassen für den Standard des Speichers. Eine Änderung löst keinen Neuaufbau aus." + }, + "source.retrieval.mode": { + label: "Abrufmodus", + helpText: "Leer: der Standard des Speichers (hybrid bei turso und pgvector). Vektor ordnet Passagen nach Bedeutung; Stichwort nach den enthaltenen Wörtern, ohne Aufruf des Embedding-Anbieters, was zu Dokument- oder Klauselnummern passt; hybrid führt beides zusammen. Ein Modus, den der Speicher nicht ausführt, wird beim Speichern abgelehnt.", + options: { + vector: "Nur Vektor (nach Bedeutung)", + keyword: "Nur Stichwort (nach Wörtern)", + hybrid: "Hybrid (beides)" + } + }, "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/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index b857c9545f3..f6607bfb55f 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 @@ -3565,6 +3565,19 @@ export const enMetadataForms: NonNullable = { 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.retrieval": { + label: "Search", + helpText: "How a search of this source finds passages. Leave it blank for the store's default. Changing it rebuilds nothing." + }, + "source.retrieval.mode": { + label: "Retrieval mode", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + options: { + vector: "Vector only (by meaning)", + keyword: "Keyword only (by words)", + hybrid: "Hybrid (both)" + } + }, "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 9bea909628d..b859ff778ee 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 @@ -3565,6 +3565,19 @@ export const esESMetadataForms: NonNullable = 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.retrieval": { + label: "Búsqueda", + helpText: "Cómo una búsqueda en esta fuente encuentra pasajes. Déjalo vacío para usar el modo predeterminado del almacén. Cambiarlo no reconstruye nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperación", + helpText: "Vacío: el modo predeterminado del almacén (híbrido en turso y pgvector). Vectorial ordena los pasajes por su significado; palabra clave por las palabras que contienen, sin llamar al proveedor de embeddings, lo que sirve para números de documento o de cláusula; híbrido combina ambos. Un modo que el almacén no ejecuta se rechaza al guardar.", + options: { + vector: "Solo vectorial (por significado)", + keyword: "Solo palabra clave (por palabras)", + hybrid: "Híbrido (ambos)" + } + }, "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 d5b376fbe0b..1d5e5fa33f4 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 @@ -3565,6 +3565,19 @@ export const frMetadataForms: NonNullable = { 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.retrieval": { + label: "Recherche", + helpText: "Comment une recherche dans cette source trouve les passages. Laissez vide pour le mode par défaut du magasin. Le modifier ne reconstruit rien." + }, + "source.retrieval.mode": { + label: "Mode de recherche", + helpText: "Vide : le mode par défaut du magasin (hybride sur turso et pgvector). Vectoriel classe les passages par leur sens ; mot-clé par les mots qu'ils contiennent, sans appel au fournisseur d'embeddings, ce qui convient aux numéros de document ou de clause ; hybride fusionne les deux. Un mode que le magasin n'exécute pas est refusé à l'enregistrement.", + options: { + vector: "Vectoriel seul (par le sens)", + keyword: "Mot-clé seul (par les mots)", + hybrid: "Hybride (les deux)" + } + }, "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/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index fd74ec8dbac..199f97863e3 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 @@ -3565,6 +3565,19 @@ export const jaJPMetadataForms: NonNullable = 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.retrieval": { + label: "検索", + helpText: "このソースを検索するときのパッセージの探し方。空欄にするとストアの既定になります。変更しても再構築は行われません。" + }, + "source.retrieval.mode": { + label: "検索モード", + helpText: "空欄:ストアの既定(turso と pgvector ではハイブリッド)。ベクトルは意味でパッセージを順位付けし、キーワードは含まれる語句で順位付けします(埋め込みプロバイダーは呼び出さないため、文書番号や条項番号に向いています)。ハイブリッドは両方を統合します。ストアが実行しないモードは保存時に拒否されます。", + options: { + vector: "ベクトルのみ(意味で)", + keyword: "キーワードのみ(語句で)", + hybrid: "ハイブリッド(両方)" + } + }, "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 2b5de15d92f..92f3c7326ff 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 @@ -3565,6 +3565,19 @@ export const koMetadataForms: NonNullable = { 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.retrieval": { + label: "검색", + helpText: "이 소스를 검색할 때 구절을 찾는 방식입니다. 비워 두면 저장소의 기본값을 사용합니다. 변경해도 다시 빌드하지 않습니다." + }, + "source.retrieval.mode": { + label: "검색 방식", + helpText: "비워 두면 저장소의 기본값(turso와 pgvector에서는 하이브리드)을 사용합니다. 벡터는 의미로 구절의 순위를 매기고, 키워드는 구절에 담긴 단어로 순위를 매기며 임베딩 제공자를 호출하지 않아 문서 번호나 조항 번호에 적합합니다. 하이브리드는 둘을 합칩니다. 저장소가 실행하지 않는 방식은 저장 시 거부됩니다.", + options: { + vector: "벡터만(의미 기준)", + keyword: "키워드만(단어 기준)", + hybrid: "하이브리드(둘 다)" + } + }, "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.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index f359904d89f..63d3a209749 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 @@ -3565,6 +3565,19 @@ export const ptBRMetadataForms: NonNullable = 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.retrieval": { + label: "Busca", + helpText: "Como uma busca nesta fonte encontra trechos. Deixe em branco para usar o padrão do armazenamento. Alterar não reconstrói nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperação", + helpText: "Em branco: o padrão do armazenamento (híbrido no turso e no pgvector). Vetorial ordena os trechos pelo significado; palavra-chave pelas palavras que contêm, sem chamar o provedor de embeddings, o que serve para números de documento ou de cláusula; híbrido combina os dois. Um modo que o armazenamento não executa é recusado ao salvar.", + options: { + vector: "Somente vetorial (pelo significado)", + keyword: "Somente palavra-chave (pelas palavras)", + hybrid: "Híbrido (ambos)" + } + }, "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.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 88ff3a6b1bf..0937d28506d 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 @@ -3565,6 +3565,19 @@ export const ruMetadataForms: NonNullable = { 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.retrieval": { + label: "Поиск", + helpText: "Как поиск по этому источнику находит фрагменты. Оставьте пустым, чтобы использовать режим хранилища по умолчанию. Изменение ничего не перестраивает." + }, + "source.retrieval.mode": { + label: "Режим поиска", + helpText: "Пусто: режим хранилища по умолчанию (гибридный в turso и pgvector). Векторный упорядочивает фрагменты по смыслу; по ключевым словам — по содержащимся в них словам, без обращения к провайдеру эмбеддингов, что подходит для номеров документов или пунктов; гибридный объединяет оба. Режим, который хранилище не выполняет, отклоняется при сохранении.", + options: { + vector: "Только векторный (по смыслу)", + keyword: "Только ключевые слова (по словам)", + hybrid: "Гибридный (оба)" + } + }, "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-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 83afaf885ea..d527bd0cc50 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 @@ -3565,6 +3565,19 @@ export const zhCNMetadataForms: NonNullable = 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.retrieval": { + label: "检索", + helpText: "检索此来源时如何查找段落。留空则使用存储的默认方式。修改它不会触发重建。" + }, + "source.retrieval.mode": { + label: "检索方式", + helpText: "留空:使用存储的默认方式(turso 和 pgvector 为混合)。向量按含义对段落排序;关键词按段落包含的词语排序,不调用嵌入服务,适合文件编号或条款编号;混合则合并两者。存储不支持的方式在保存时会被拒绝。", + options: { + vector: "仅向量(按含义)", + keyword: "仅关键词(按词语)", + hybrid: "混合(两者)" + } + }, "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 cd7cc6e30cf..25d84eaf09e 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 @@ -3565,6 +3565,19 @@ export const zhHantMetadataForms: NonNullable 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.retrieval": { + label: "檢索", + helpText: "檢索此來源時如何查找段落。留空則使用儲存的預設方式。修改它不會觸發重建。" + }, + "source.retrieval.mode": { + label: "檢索方式", + helpText: "留空:使用儲存的預設方式(turso 和 pgvector 為混合)。向量依含義排序段落;關鍵字依段落包含的詞語排序,不呼叫嵌入服務,適合文件編號或條款編號;混合則合併兩者。儲存不支援的方式在儲存時會被拒絕。", + options: { + vector: "僅向量(依含義)", + keyword: "僅關鍵字(依詞語)", + hybrid: "混合(兩者)" + } + }, "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/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 0cfb59e9f2d..5b46eddeb02 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -305,7 +305,7 @@ import type * as M205 from './ai/object-query-source.zod.js'; import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 880 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -1848,7 +1848,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 880 isomorphic pins', () => { + it('still declares all 881 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2988,7 +2988,11 @@ describe('ADR-0122 type-alias convention', () => { // `RecordQuickActionsLocationSchema` (`ui/action.zod.ts`), the shared // location enum less `record`, with no default or transform // (Iso_ui_action__RecordQuickActionsLocationSchema). +1 added. - expect(pins).toHaveLength(880); + // 880 -> 881 is #38692: the mode a knowledge source's searches run in, + // `KnowledgeRetrievalModeSchema` (`ai/knowledge-source.zod.ts`), a plain + // enum with no default or transform + // (Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema). +1 added. + expect(pins).toHaveLength(881); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From 662a70ce23845913f3e7b729113deae09da89247 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:32:25 +0000 Subject: [PATCH 17/23] test(service-knowledge): keep the tracker id out of the contract suite's case title Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- packages/services/service-knowledge/src/testing.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 99fc4436830..24da72e465b 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -711,7 +711,8 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } - describe('the retrieval mode through KnowledgeService.search (#38692 phase 1a)', () => { + // objectstack#38692 phase 1a. + describe('the retrieval mode through KnowledgeService.search', () => { const ROWS: Row[] = [{ id: 'r1', body: 'alpine meadow harbour', status: 'published' }]; const withMode = (id: string, mode?: KnowledgeRetrievalMode): KnowledgeSource => objectSource(id, mode === undefined ? {} : { retrieval: { mode } }); From 7436d4f2e31fad5d3a79154b0a591dfa0bfad198 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:52:18 +0000 Subject: [PATCH 18/23] test(platform-objects): count the retrieval-mode rows in the translated metadata-form catalog Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 9058db36f9c..68ffe3980d7 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 @@ -1361,7 +1361,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // authored in all three locales. // 869 since #37792: the object form's `pinOverview` row (the record // page layout switch) — one row label, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(869); + // 871 since #38692: the `knowledge_source` form's `source.retrieval` + // group and its `mode` row (the retrieval mode) — two row labels, + // authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(871); } // ⭐ 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 From b15ac8df9799f66e3993ca40c44e6388c2884953 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:42:19 +0000 Subject: [PATCH 19/23] docs(spec): cite the ADR-0161 note of 2026-11-30 under K8 by its place; regenerate the spec artifacts after the merge of main The merge of main had left the ai shards of the generated spec artifacts without main's TurnEnd rows; check:generated --fix rewrites them from a fresh build. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/references/index.mdx | 9 +++++---- .../2026-07-unknown-key-strictness-ledger.counts/ai.md | 2 +- .../src/__tests__/index-fingerprint.test.ts | 4 ++-- packages/services/service-knowledge/src/testing.ts | 4 ++-- packages/spec/api-surface/ai.json | 4 ++++ packages/spec/authorable-surface/ai.json | 7 ++++++- packages/spec/declaration-map/ai.json | 4 +++- packages/spec/export-origins/ai.json | 4 ++++ packages/spec/json-schema.manifest/ai.json | 3 ++- packages/spec/liveness/knowledge_source.json | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 6 +++--- packages/spec/src/contracts/knowledge-adapter.ts | 6 +++--- 13 files changed, 37 insertions(+), 20 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 03b540df209..40f494a7901 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 — 1747 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1748 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 | 107 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 18 | 108 | 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** | **1747** | 14 protocol modules | +| **Total** | **224** | **1748** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 108 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -64,6 +64,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` | | [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` | | [`tool.zod.ts`](/docs/references/ai/tool) | `Tool` | +| [`turn-end.zod.ts`](/docs/references/ai/turn-end) | `TurnEnd` | | [`usage.zod.ts`](/docs/references/ai/usage) | `AIUsageRecord`, `TokenUsage` | --- 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 050f8f7f1d7..3ecff028bbc 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/` | 122 | +| `ai/` | 123 | diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 2168abc0b70..5ea16f03535 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -172,9 +172,9 @@ describe('recipe hash (ADR-0161 K7)', () => { }); // `source.retrieval` is read on every search and by no build (ADR-0161, the -// dated note on retrieval modes): neither hash moves with it, so changing a +// dated note of 2026-11-30 under K8): neither hash moves with it, so changing a // source's retrieval mode rebuilds nothing. -describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { +describe('retrieval mode (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('changes neither the index fingerprint nor the recipe hash', () => { const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); const recipe = computeRecipeHash({ source: source() }); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 1eb8060fa13..78f526856b2 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -155,7 +155,7 @@ export interface KnowledgeAdapterContractOptions { */ keywordLeg?: boolean; /** - * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * `capabilities.retrieval` (ADR-0161, the dated note of 2026-11-30 under K8): * the adapter reports the modes it runs and its default, and its search * honours `AdapterSearchOptions.retrieval`. The report is checked against * the three modes, and each listed mode is asserted by behaviour: `vector` @@ -587,7 +587,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption } if (opts.implements.retrieval === true) { - describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + describe('retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { const adapter: IKnowledgeAdapter = await make(); const report = adapter.capabilities?.retrieval; diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 0bfeb1ab566..c9ffbb4d6d6 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -296,6 +296,7 @@ "StructuredOutputConfigSchema (const)", "StructuredOutputFormat (type)", "StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE (const)", "TextContent (type)", "TextContentSchema (const)", "TokenBudgetConfig (type)", @@ -315,6 +316,9 @@ "ToolSchema (const)", "TransformPipelineStep (type)", "TransformPipelineStepSchema (const)", + "TurnEnd (type)", + "TurnEndParsed (type)", + "TurnEndSchema (const)", "agentForm (const)", "aiContextForm (const)", "aiContextWhereFields (function)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 529db46b843..ab5bb1bb688 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -577,6 +577,11 @@ "ai/Tool:protection", "ai/ToolCall:function", "ai/ToolCall:id", - "ai/ToolCall:type" + "ai/ToolCall:type", + "ai/TurnEnd:reason", + "ai/TurnEnd:resumable", + "ai/TurnEnd:resumesLeft", + "ai/TurnEnd:turnId", + "ai/TurnEnd:wrapUp" ] } diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 70474f71dfe..0d874a661cb 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -209,7 +209,9 @@ "ToolCallSchema": "ai/ToolCall", "ToolSchema": "ai/Tool", "TransformPipelineStep": "ai/TransformPipelineStep", - "TransformPipelineStepSchema": "ai/TransformPipelineStep" + "TransformPipelineStepSchema": "ai/TransformPipelineStep", + "TurnEnd": "ai/TurnEnd", + "TurnEndSchema": "ai/TurnEnd" }, "collisions": [] } diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 2114847e360..610779dc917 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -293,6 +293,7 @@ "StructuredOutputConfigSchema": "src/ai/agent.zod.ts#StructuredOutputConfigSchema (const)", "StructuredOutputFormat": "src/ai/agent.zod.ts#StructuredOutputFormat (type)", "StructuredOutputFormatSchema": "src/ai/agent.zod.ts#StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE": "src/ai/turn-end.zod.ts#TURN_END_PART_TYPE (const)", "TextContent": "src/ai/conversation.zod.ts#TextContent (type)", "TextContentSchema": "src/ai/conversation.zod.ts#TextContentSchema (const)", "TokenBudgetConfig": "src/ai/conversation.zod.ts#TokenBudgetConfig (type)", @@ -312,6 +313,9 @@ "ToolSchema": "src/ai/tool.zod.ts#ToolSchema (const)", "TransformPipelineStep": "src/ai/agent.zod.ts#TransformPipelineStep (type)", "TransformPipelineStepSchema": "src/ai/agent.zod.ts#TransformPipelineStepSchema (const)", + "TurnEnd": "src/ai/turn-end.zod.ts#TurnEnd (type)", + "TurnEndParsed": "src/ai/turn-end.zod.ts#TurnEndParsed (type)", + "TurnEndSchema": "src/ai/turn-end.zod.ts#TurnEndSchema (const)", "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 3f17e4320fe..56fd5331ef4 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -108,6 +108,7 @@ "ai/TokenUsageStats", "ai/Tool", "ai/ToolCall", - "ai/TransformPipelineStep" + "ai/TransformPipelineStep", + "ai/TurnEnd" ] } diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index ca269505e36..672e1a0b0e8 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,7 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index af044bd5816..1be90217149 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -417,7 +417,7 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller }); }); -describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note of 2026-11-30 under K8)', () => { const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 64e6ef189c6..a07a538429c 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -130,7 +130,7 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( /** * The retrieval modes a knowledge source may declare (ADR-0161, the dated note - * on retrieval modes; ruling 7270218011 on #38692): + * of 2026-11-30 under K8; ruling 7270218011 on #38692): * * - `vector`: only the vector leg runs, ranking passages by meaning. * - `keyword`: only the keyword leg runs, ranking passages by the words they @@ -156,7 +156,7 @@ export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RE })); /** - * How a source is searched (ADR-0161, the dated note on retrieval modes): + * How a source is searched (ADR-0161, the dated note of 2026-11-30 under K8): * which legs the store runs. A declaration of the source, read on every search * and never by a build, so it enters neither the index fingerprint nor the * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing @@ -504,7 +504,7 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( 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'), /** - * [ADR-0161, the dated note on retrieval modes] How this source is + * [ADR-0161, the dated note of 2026-11-30 under K8] How this source is * searched: `retrieval.mode` names the legs the store runs * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before * it: the mode decides which passages the store ranks and their scores, diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 0790d351e29..b1e074cb4d7 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -177,8 +177,8 @@ export interface AdapterSearchOptions { */ index?: { fingerprint: string }; /** - * The retrieval mode this search runs (ADR-0161, the dated note on - * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * The retrieval mode this search runs (ADR-0161, the dated note of + * 2026-11-30 under K8): the EFFECTIVE mode, which the knowledge service resolves * from the source's `source.retrieval.mode`, else the adapter's * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). @@ -271,7 +271,7 @@ export interface AdapterCapabilities { chunks?: boolean; /** * The retrieval modes the adapter runs, and which one it runs when a - * source declares none (ADR-0161, the dated note on retrieval modes). A + * source declares none (ADR-0161, the dated note of 2026-11-30 under K8). A * report, not configuration: `default` is one of `modes`, and an adapter * that lists `hybrid` honours the source's vector share when that arrives. * From a76dc2eb6c79427ed4e60684f2900faa94bd095a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:14:50 +0000 Subject: [PATCH 20/23] chore(changeset): the platform-objects translations of the retrieval-mode form ship as a patch Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .changeset/38692-knowledge-retrieval-mode-spec.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md index c48981f369f..754d85822e2 100644 --- a/.changeset/38692-knowledge-retrieval-mode-spec.md +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -1,6 +1,7 @@ --- '@objectstack/spec': minor '@objectstack/service-knowledge': minor +'@objectstack/platform-objects': patch --- feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs @@ -14,4 +15,6 @@ A `knowledge_source` may now declare how it is searched: `source: { …, retriev The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. +The Studio metadata-form translations (`@objectstack/platform-objects`) name the "Search" group and the "Retrieval mode" select and its three choices in every locale. + The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 75d7437697965789272958e77ee83334a65a8459 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 11:03:57 +0000 Subject: [PATCH 21/23] fix(spec): the retrieval key warns until the service reads it; the contract leaves the per-search code to the service The planned liveness row of source.retrieval warns an author (authorWarn and authorHint) until the knowledge service reads it. The texts that state the refusals name the knowledge service as the refuser; the contract's jsdoc no longer names the per-search refusal code. The shared suite's vector case no longer needs a keyword leg, so a vector-only store attests. The ADR K2 row says the member carries the effective mode, and the protocol doc's section 3.1 names the key. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 8 ++++++++ ...rd-return-knowledge-source-is-a-governed-type.md | 2 +- .../translations/en.metadata-forms.generated.ts | 2 +- packages/services/service-knowledge/src/testing.ts | 5 +++-- packages/spec/liveness/knowledge_source.json | 4 +++- .../spec/src/ai/knowledge-source.metadata-form.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 13 +++++++------ packages/spec/src/contracts/knowledge-adapter.ts | 6 ++---- 8 files changed, 26 insertions(+), 16 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 685004cae35..0a84154c23f 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -181,6 +181,14 @@ that name (ADR-0161 K4): `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is used, so a source registered before its store started finds it. +**How a source is searched: `source.retrieval.mode`** (ADR-0161, the dated +note of 2026-11-30 under K8). `'vector'` ranks by meaning alone, `'keyword'` +by the question's words alone (the embedder is never called), `'hybrid'` runs +both and merges them; omitted (or `retrieval: {}`), the adapter's default +(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). The +mode is read by search alone: it enters neither the index fingerprint nor the +recipe hash, so changing it rebuilds nothing. + **What mounts the service.** A stack that ships a `knowledge_source` — any item in its `knowledgeSources`, at the top level or in a package — is served the knowledge service and the deployment's store, exactly as diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 91e0d334663..c2348262641 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -150,7 +150,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`): the source's declaration, else the adapter's default; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | 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 f6607bfb55f..a888b4925f7 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 @@ -3571,7 +3571,7 @@ export const enMetadataForms: NonNullable = { }, "source.retrieval.mode": { label: "Retrieval mode", - helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.", options: { vector: "Vector only (by meaning)", keyword: "Keyword only (by words)", diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 78f526856b2..f4e41c3d050 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -161,7 +161,9 @@ export interface KnowledgeAdapterContractOptions { * the three modes, and each listed mode is asserted by behaviour: `vector` * leaves out the passage only the keyword leg ranks, `keyword` ranks by * the query's words alone, `hybrid` answers what the default answers when - * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * it is the default. The `keyword` case needs `keywordLeg`; the `vector` + * case holds for a store with no keyword leg too, so a vector-only store + * (`modes: ['vector']`) attests. * Absent: `false`. */ retrieval?: boolean; @@ -623,7 +625,6 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { const { adapter, a, listed } = await seeded(); if (!listed.includes('vector')) return; - expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index 672e1a0b0e8..f50d75d32b5 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,9 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "authorWarn": true, + "authorHint": "Keep it, but nothing reads it yet: until the knowledge service reads it, a source is searched in its store's default mode whatever it declares, and a mode the store does not run is not refused.", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it, and drop `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate). Enters neither the index fingerprint nor the recipe hash.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index 1215e5f31b2..75a86d7d7df 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -93,7 +93,7 @@ export const knowledgeSourceForm = defineMetadataForm({ { label: 'Keyword only (by words)', value: 'keyword' }, { label: 'Hybrid (both)', value: 'hybrid' }, ], - helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.', }, ], }, diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index a07a538429c..8f61e67cdb2 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -141,8 +141,8 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( * - `hybrid`: both legs run, merged by the store's fusion. * * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), - * never configuration; a source that declares a mode its store does not run is - * refused, never silently searched another way. + * never configuration. A source that declares a mode its store does not run is + * refused by the knowledge service, never silently searched another way. */ export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; @@ -172,10 +172,11 @@ export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( * Which legs run: `vector`, `keyword` or `hybrid` * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and - * pgvector), today's behaviour. A store that does not list the mode - * refuses the source at save, at registration when its store already - * resolves, once after boot, and on every search (the source is listed as - * refused); a store that reports no modes accepts only the key left out. + * pgvector), today's behaviour. The knowledge service refuses a source + * whose store does not list the mode: at save, at registration when its + * store already resolves, once after boot, and on every search (the source + * is listed as refused). A store that reports no modes takes only a source + * that leaves the key out. */ mode: KnowledgeRetrievalModeSchema.optional() .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index b1e074cb4d7..b62c7af7d17 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -193,10 +193,8 @@ export interface AdapterSearchOptions { * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. * A source declaring a mode its adapter does not list is never searched - * another way: the knowledge service lists it in a search's `refused` with - * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose - * adapter is not mounted is refused with there), and refuses it at its save - * and registration with `VALIDATION_ERROR` (400). + * another way: the knowledge service refuses it, at its save and its + * registration, and lists it in a search's `refused` with its code. * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From 1a7ba24040ea84633bcdd8042ff89ed616cc9645 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 12:38:22 +0000 Subject: [PATCH 22/23] Take a published knowledge source whatever its mode; restore the pgvector doc text The loader runs after every store has started, so refusing an unsupported retrieval mode there dropped the item whole: no index, no boot error line, no refused entry on a search, and an earlier version stayed live. A published item meets no save, so it is now registered and indexed as any other, and the boot's reading and every search refuse it. Registration in code keeps its refusal. Both paths are pinned in the unit file and in the adapter suite. Restores main's knowledge-pgvector text (pool size, statement timeout and coded refusals) that the last merge's resolution of the protocol doc lost. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../38692-knowledge-retrieval-mode-service.md | 7 ++- content/docs/protocol/knowledge.mdx | 26 ++++++---- .../__tests__/retrieval-mode-38692.test.ts | 48 +++++++++++++++++-- .../src/knowledge-retrieval-mode.ts | 12 +++-- .../src/knowledge-service-sources.ts | 13 ++++- .../services/service-knowledge/src/testing.ts | 18 ++++++- packages/spec/liveness/knowledge_source.json | 2 +- 7 files changed, 104 insertions(+), 22 deletions(-) diff --git a/.changeset/38692-knowledge-retrieval-mode-service.md b/.changeset/38692-knowledge-retrieval-mode-service.md index 86abfb18dca..2c301c3e399 100644 --- a/.changeset/38692-knowledge-retrieval-mode-service.md +++ b/.changeset/38692-knowledge-retrieval-mode-service.md @@ -14,10 +14,13 @@ modes. A source that declares a mode its store does not run is never searched another way. It is refused at its save (`400 VALIDATION_ERROR`, listing the -modes the store runs), at registration when its store is already registered, +modes the store runs), at registration in code (`registerSource`) when its +store is already registered, once after boot at `error` (`reportUnsupportedRetrieval`), and on every search, where it is listed in `refused` with `SERVICE_UNAVAILABLE` (503). It still -builds and syncs its index. A store that reports no modes (knowledge-memory) +builds and syncs its index: a published item (a package install, the stack's +`knowledgeSources`) meets no save and is registered and indexed as usual, and +the boot's reading and every search refuse it. A store that reports no modes (knowledge-memory) takes only a source that leaves the mode out. Clause-②: no diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b8f1a5007e..3bf79c03e44 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -195,10 +195,12 @@ lists none) is refused at four points: 1. its save (Studio, `/meta`, an MCP draft): `VALIDATION_ERROR` (400), listing the modes the store runs; -2. its registration, when its adapter is already registered: the same - refusal. A store registers in its own `start()`, after a source - registered at `init()`, so "not registered yet" is no verdict; a package - install meets no save, so the next two points hold it; +2. its registration in code (`registerSource`), when its adapter is already + registered: the same refusal. A store registers in its own `start()`, + after a source registered at `init()`, so "not registered yet" is no + verdict. A published item (a package install, the stack's + `knowledgeSources`) meets no save and is not refused by the loader: it is + registered and indexed, and the next two points hold it; 3. once after boot, at `error`, naming the source and the modes; 4. every search: the source is listed in `refused`, `SERVICE_UNAVAILABLE` (503), as a source whose adapter is not mounted is. @@ -771,10 +773,10 @@ service. It takes the service's passages, embeds them with the kernel's an exact scan. - **Which database.** The `url` option when it is given, else the platform - database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool - (`poolMax`, default 4; a connection that takes more than - `connectTimeoutMs`, default 5000, fails); no pooled connection waits on the - embedder. Where organizations + database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool, + per process, sized by `poolMax`, else the setting `OS_KNOWLEDGE_POOL_MAX`, + else 20 (a connection that takes more than `connectTimeoutMs`, default 5000, + fails); no pooled connection waits on the embedder. Where organizations have databases of their own, the store is still the ONE database the plugin connects to; organizations are kept apart by its `organization_id` column, which every search filters on before ranking. @@ -808,6 +810,14 @@ an exact scan. are one `WHERE`, run in both legs before either ranks. `queryPrefix` is put before every query before it is embedded, for a model that embeds questions and passages differently. + The ranking statement runs in a transaction of its own under + `SET LOCAL statement_timeout` (`statementTimeoutMs`, else + `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000 ms), so the limit holds no + session state. + A search the database fails is refused by its SQLSTATE, never answered + empty: `TIMEOUT` (504) for a statement stopped or cancelled, + `SERVICE_UNAVAILABLE` (503) when no connection or capacity was available, + `DATABASE_ERROR` (500) for any other database error. - **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is not embedded again; its row's metadata is rewritten. - **Rebuilds.** A write or a search under another fingerprint is refused diff --git a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts index 6556c7e1ac8..9d7d3ec7058 100644 --- a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts +++ b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts @@ -20,6 +20,7 @@ import type { } from '@objectstack/spec/ai'; import { KnowledgeService } from '../knowledge-service.js'; import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; +import { KnowledgeSourceLoader } from '../knowledge-source-loader.js'; import { knowledgeIndexStatusActionHandler } from '../knowledge-build-actions.js'; import { RETRIEVAL_UNSUPPORTED_CODE, @@ -185,7 +186,7 @@ describe('a declared mode the adapter does not run — the four refusal points', expect((ok as { message?: string }).message ?? '').not.toContain('retrieval.mode'); }); - it('2 · registration refuses it only when its adapter already resolves', () => { + it('2 · registration in code refuses it only when its adapter already resolves; the loader takes it', () => { const { svc, vec } = bootLike(); svc.registerAdapter('vec', vec); let refused: unknown; @@ -197,8 +198,9 @@ describe('a declared mode the adapter does not run — the four refusal points', expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); expect(String((refused as Error).message)).toContain("registerSource refused source 's1': its `retrieval.mode` is 'keyword'"); expect(svc.getSource('s1')).toBeUndefined(); - expect(() => svc.registerMetadataSource(source('s2', 'vec', 'hybrid'))).toThrow(/knowledge_source loader refused source 's2'/); - expect(svc.getSource('s2')).toBeUndefined(); + // A published item meets no save and is not refused by the loader: 3 and 4 hold it. + svc.registerMetadataSource(source('s2', 'vec', 'hybrid')); + expect(svc.getSource('s2')).toBeDefined(); // A store not registered yet is no verdict: the source is taken. svc.registerSource(source('s3', 'pgvector', 'keyword')); expect(svc.getSource('s3')).toBeDefined(); @@ -253,6 +255,46 @@ describe('a declared mode the adapter does not run — the four refusal points', expect(vec.upsertSpy).toHaveBeenCalledOnce(); }); + it('a published item (the loader, its store already started) is registered and indexed, named at error, refused on every search', async () => { + const { lines, logger } = logged(); + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ logger, dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + // The loader runs at kernel:ready and on metadata:reloaded, after every store's start(). + svc.registerAdapter('vec', vec); + const loader = new KnowledgeSourceLoader({ + service: svc, + logger, + readItems: async () => [source('pkg_bad', 'vec', 'keyword'), source('pkg_good', 'vec')], + namespaceOf: () => undefined, + buildOnReload: false, + }); + const pass = await loader.reconcile('boot'); + expect(pass.added.sort()).toEqual(['pkg_bad', 'pkg_good']); + expect(svc.getSource('pkg_bad')).toBeDefined(); + expect(lines.filter(([level, m]) => level === 'warn' && m.includes('pkg_bad'))).toEqual([]); + + // Still indexes: the mode is read by search alone. + expect(await svc.reindexSource('pkg_bad')).toMatchObject({ ok: true, indexed: 1 }); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + + // 3 · the boot reading names it at error. + expect(svc.reportUnsupportedRetrieval()).toEqual(['pkg_bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'pkg_bad' is not searched: its `retrieval.mode` is 'keyword'"); + + // 4 · every search lists it in `refused` and never runs it. + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['pkg_good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'pkg_bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['pkg_good']); + }); + it('a source on a store not mounted is named by the unmounted reading, not this one', () => { const { svc } = bootLike(); svc.registerSource(source('s1', 'pgvector', 'keyword')); diff --git a/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts index 033cbf0063d..b36da162126 100644 --- a/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts +++ b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts @@ -21,11 +21,13 @@ * 1. at an author's save (Studio, REST, an MCP draft): `400 * VALIDATION_ERROR`, listing the modes the adapter runs * (`admitAuthoredSource`); - * 2. at registration, only when its adapter already resolves — a store - * registers in its own `start()`, after a source registered at `init()`, - * so "not registered yet" is no verdict (AGENTS.md, startup registry - * reads); a package install meets no save, so 3 and 4 hold it - * (`registerSource`, `registerMetadataSource`); + * 2. at registration in code, only when its adapter already resolves — a + * store registers in its own `start()`, after a source registered at + * `init()`, so "not registered yet" is no verdict (AGENTS.md, startup + * registry reads) (`registerSource`). A published item (a package + * install, the stack's `knowledgeSources`) meets no save and is not + * refused by the loader: it is registered and indexed, and 3 and 4 hold + * it (`registerMetadataSource`); * 3. once after boot, at `error`, naming the source and the modes * (`reportUnsupportedRetrieval`, beside `reportUnmountedAdapters`); * 4. on every search: the source is listed in `refused` with diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index bf546185205..d82fce85087 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -198,12 +198,19 @@ export function reportUnmountedAdapters( } /** - * Refuse, at registration, a source that declares a retrieval mode its + * Refuse, at registration in code, a source that declares a retrieval mode its * adapter does not run (#38692 phase 1a, refusal point 2) — only when that * adapter already resolves: a store registers in its own `start()`, after a * source registered at `init()`, so "not registered yet" is no verdict * (AGENTS.md, startup registry reads). The boot's reading * ({@link reportUnsupportedRetrieval}) and every search hold the rest. + * + * The code door alone: a published `knowledge_source` item (a package + * install, the stack's `knowledgeSources`, a peer's write) meets no save, and + * the loader always runs after every store has started, so a refusal there + * would drop the item whole. It is registered and indexed as any other, and + * points 3 and 4 hold it: named at `error` after boot, refused on every + * search. */ function refuseUnsupportedRetrieval( this: Pick, @@ -305,7 +312,9 @@ export function registerMetadataSource( holder: KnowledgeSourceHolder = {}, ): KnowledgeSourceEntry { this.refuseUnplacedSource(source, 'The knowledge_source loader'); - refuseUnsupportedRetrieval.call(this, source, 'The knowledge_source loader'); + // A mode its store does not run is not refused here (see + // refuseUnsupportedRetrieval): the item is registered and indexed, and the + // boot's reading and every search refuse it. const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index cc95ba9d562..55202a5f3ca 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -728,7 +728,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { - it(`'${mode}' declared: handed to the adapter when it lists it, refused at registration and at every search when it does not`, async () => { + it(`'${mode}' declared: handed to the adapter when it lists it; when it does not, refused at registration in code and at every search, and a published item still indexes`, async () => { const source = withMode(`mode_${mode}`, mode); const probe: IKnowledgeAdapter = await make(); const listed = probe.capabilities?.retrieval?.modes.includes(mode) === true; @@ -760,6 +760,22 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect.objectContaining({ sourceId: source.name, code: 'SERVICE_UNAVAILABLE', status: 503 }), ]); expect(search).not.toHaveBeenCalled(); + + // A published item, loaded after its store started (the loader's door): never refused + // there, it is registered and indexes, and the boot's reading and every search refuse it. + const published = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + const store: IKnowledgeAdapter = await make(); + const storeSearch = vi.spyOn(store, 'search'); + published.registerAdapter('under_test', store); + published.registerMetadataSource(source); + expect(published.getSource(source.name)).toBeDefined(); + expect(await published.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(published.reportUnsupportedRetrieval()).toEqual([source.name]); + const refusedSearch = await published + .search('alpine meadow', { topK: 1, executionContext: SYSTEM }) + .catch((e: unknown) => e); + expect(refusedSearch).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(storeSearch).not.toHaveBeenCalled(); }); } }); diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index d55000a4891..3be78301bfd 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -125,7 +125,7 @@ "status": "live", "verifiedAt": "2026-11-30", "evidenceScope": "in-repo", - "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — the effective mode: the source's declaration, else the adapter's `capabilities.retrieval.default`; packages/services/service-knowledge/src/knowledge-service-search.ts#planSearches — every search resolves it, hands it to the adapter as `AdapterSearchOptions.retrieval` (`searchRound`) and refuses a mode the adapter does not list in `refused` (SERVICE_UNAVAILABLE); packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses it (400 VALIDATION_ERROR, listing the modes the store runs); packages/services/service-knowledge/src/knowledge-service-sources.ts#registerSource / #registerMetadataSource — registration refuses it when the adapter already resolves; packages/services/service-knowledge/src/knowledge-service-sources.ts#reportUnsupportedRetrieval — the boot's reading names it at `error`.", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — the effective mode: the source's declaration, else the adapter's `capabilities.retrieval.default`; packages/services/service-knowledge/src/knowledge-service-search.ts#planSearches — every search resolves it, hands it to the adapter as `AdapterSearchOptions.retrieval` (`searchRound`) and refuses a mode the adapter does not list in `refused` (SERVICE_UNAVAILABLE); packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses it (400 VALIDATION_ERROR, listing the modes the store runs); packages/services/service-knowledge/src/knowledge-service-sources.ts#registerSource — registration in code refuses it when the adapter already resolves (a published item is registered and indexed through #registerMetadataSource, and the next two refuse it); packages/services/service-knowledge/src/knowledge-service-sources.ts#reportUnsupportedRetrieval — the boot's reading names it at `error`.", "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": "Ruling 7270218011 on #38692, phase 1a (ADR-0161, the dated note of 2026-11-30 under K8). Strict, `retrieval: {}` allowed. Read by search alone: enters neither the index fingerprint nor the recipe hash, so changing it rebuilds nothing, and a source whose mode is refused still indexes. knowledge-turso and knowledge-pgvector run each mode; an adapter that reports no modes (knowledge-memory) takes a source that leaves the mode out.", "children": { From 25a6dee2cd0baa4160380ce75b03ac586ad768c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 13:36:18 +0000 Subject: [PATCH 23/23] Name the spec package in the service changeset: its liveness row flips to live Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .changeset/38692-knowledge-retrieval-mode-service.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/38692-knowledge-retrieval-mode-service.md b/.changeset/38692-knowledge-retrieval-mode-service.md index 2c301c3e399..8630e1cd1c3 100644 --- a/.changeset/38692-knowledge-retrieval-mode-service.md +++ b/.changeset/38692-knowledge-retrieval-mode-service.md @@ -1,5 +1,6 @@ --- '@objectstack/service-knowledge': patch +'@objectstack/spec': patch --- feat(service-knowledge): the knowledge service reads a source's retrieval mode