From 6ee3b9648fddb59a6ef122dbfc5766d283a877cd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:36:41 +0000 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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": {