@equationalapplications/core-llm-wiki 9.9.0 → 9.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-CDSfjx8j.mjs';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-CDSfjx8j.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-DnYjL2QD.mjs';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-DnYjL2QD.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-CDSfjx8j.js';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-CDSfjx8j.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-DnYjL2QD.js';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-DnYjL2QD.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -3584,6 +3584,18 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3584
3584
  );
3585
3585
  return rows.map((r) => ({ id: r.id, title: r.title, okf_type: r.okf_type ?? null }));
3586
3586
  }
3587
+ /**
3588
+ * Shortlist scoring rows (id, title, okf_type, body) over all live typed
3589
+ * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL
3590
+ * in results because the query excludes untyped rows.
3591
+ */
3592
+ async findShortlistRowsByEntityId(entityId, tx) {
3593
+ const executor = this.getExecutor(tx);
3594
+ return executor.getAllAsync(
3595
+ `SELECT id, title, okf_type, body FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND okf_type IS NOT NULL`,
3596
+ [entityId]
3597
+ );
3598
+ }
3587
3599
  /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */
3588
3600
  async countHealCandidatesByEntityId(entityId, recheckCutoff, tx) {
3589
3601
  const executor = this.getExecutor(tx);
@@ -7557,46 +7569,29 @@ Return ONLY a valid JSON object matching this schema:
7557
7569
  }
7558
7570
  If no manifest type fits a fact, assign the closest type the fact is an example of; omit that fact from "classifications" only when no type applies even broadly. Use the manifest slug EXACTLY as spelled (spelling variants are folded to the manifest form).
7559
7571
  When echoing an existing fact's title verbatim into "target_title", preserve every JSON escape sequence (\\", \\n, \\\\, \\/) exactly as it appeared in the input body \u2014 do not strip backslashes, do not add unescaped quotes. Do not return markdown, just raw JSON.`;
7560
- var TITLE_CATALOG_MAX_ENTRIES = 200;
7561
- function buildTitleCatalogBlock(rows) {
7562
- const byKey = /* @__PURE__ */ new Map();
7563
- for (const r of rows) {
7564
- if (typeof r.title !== "string" || r.title.length === 0) continue;
7565
- if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
7566
- byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
7567
- }
7568
- const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
7569
- const CHAR_BUDGET = 8e3;
7570
- const listed = [];
7571
- let used = 0;
7572
- for (const r of typed) {
7573
- const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
7574
- if (line.length + 1 > CHAR_BUDGET) continue;
7575
- if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
7576
- if (used + line.length + 1 > CHAR_BUDGET) continue;
7577
- listed.push(r);
7578
- used += line.length + 1;
7579
- }
7580
- const truncated = typed.length > listed.length;
7581
- if (typed.length === 0) {
7582
- return [
7583
- "TITLE CATALOG: this memory contains no typed nodes yet.",
7584
- 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
7585
- ].join("\n");
7572
+ function formatCatalogLine(r) {
7573
+ return `- ${JSON.stringify(r.title)} (${r.okf_type})`;
7574
+ }
7575
+ function buildCandidateSections(facts, rowsByFact) {
7576
+ const footer = 'A "target_title" may be copied verbatim from the candidates above for its fact, or be another fact classified in this same response. Any other existing typed node in this memory is also a valid "target_title", even if not listed here. If no valid target exists, omit "edges" rather than invent a target_title.';
7577
+ const sections = [];
7578
+ for (const fact of facts) {
7579
+ const rows = rowsByFact.get(fact.id);
7580
+ if (!rows || rows.length === 0) continue;
7581
+ sections.push(
7582
+ [
7583
+ `CANDIDATE TARGETS for fact ${JSON.stringify(fact.id)}: typed nodes in this memory, ranked by title overlap:`,
7584
+ ...rows.map(formatCatalogLine)
7585
+ ].join("\n")
7586
+ );
7586
7587
  }
7587
- if (listed.length === 0) {
7588
+ if (sections.length === 0) {
7588
7589
  return [
7589
- "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
7590
+ "CANDIDATE TARGETS: this memory contains no typed nodes yet.",
7590
7591
  'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
7591
7592
  ].join("\n");
7592
7593
  }
7593
- const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
7594
- return [
7595
- "TITLE CATALOG: existing typed nodes in this memory include:",
7596
- catalog,
7597
- ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
7598
- 'A "target_title" may be copied verbatim from this catalog, or be another fact classified in this same response. If no valid target exists, omit "edges" rather than invent a target_title.'
7599
- ].join("\n");
7594
+ return [...sections, footer].join("\n\n");
7600
7595
  }
7601
7596
  var GROUNDING_SOURCE = {
7602
7597
  ingest: { key: "facts", source: "the document chunk" },
@@ -7874,7 +7869,7 @@ The following document anchors are provided for contradiction detection only. Do
7874
7869
  ...corpusField
7875
7870
  };
7876
7871
  }
7877
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
7872
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, candidateSections) {
7878
7873
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
7879
7874
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
7880
7875
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -7884,13 +7879,13 @@ The following document anchors are provided for contradiction detection only. Do
7884
7879
  ${JSON.stringify(facts, null, 2)}`
7885
7880
  };
7886
7881
  }
7887
- const effective = titleCatalog !== void 0 ? `${template}
7888
-
7889
- ${titleCatalog}` : template;
7882
+ const factsBlock = `Facts:
7883
+ ${JSON.stringify(facts, null, 2)}`;
7890
7884
  return {
7891
- systemPrompt: this.appendOntology(effective, ontologyContext),
7892
- userPrompt: `Facts:
7893
- ${JSON.stringify(facts, null, 2)}`
7885
+ systemPrompt: this.appendOntology(template, ontologyContext),
7886
+ userPrompt: candidateSections !== void 0 ? `${factsBlock}
7887
+
7888
+ ${candidateSections}` : factsBlock
7894
7889
  };
7895
7890
  }
7896
7891
  /** Ops extract (spec §5.2): events only — no existing facts. */
@@ -8932,6 +8927,52 @@ function classifierStateForFact(fact) {
8932
8927
  return parts.join("\n\n");
8933
8928
  }
8934
8929
 
8930
+ // src/utils/shortlist.ts
8931
+ function shortlistScore(factTitle, factBody, row) {
8932
+ const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
8933
+ const rowTokens = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
8934
+ return jaccardScore(factTokens, rowTokens);
8935
+ }
8936
+ function createShortlistScorer(rows) {
8937
+ const rowTokens = /* @__PURE__ */ new Map();
8938
+ const tokensOfRow = (row) => {
8939
+ let t = rowTokens.get(row);
8940
+ if (!t) {
8941
+ t = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
8942
+ rowTokens.set(row, t);
8943
+ }
8944
+ return t;
8945
+ };
8946
+ for (const r of rows) tokensOfRow(r);
8947
+ const factTokens = /* @__PURE__ */ new WeakMap();
8948
+ return (fact, row) => {
8949
+ let ft = factTokens.get(fact);
8950
+ if (!ft) {
8951
+ ft = /* @__PURE__ */ new Set([...titleTokens(fact.title), ...titleTokens(fact.body)]);
8952
+ factTokens.set(fact, ft);
8953
+ }
8954
+ return jaccardScore(ft, tokensOfRow(row));
8955
+ };
8956
+ }
8957
+ function buildShortlist(fact, rows, k, score = (f, r) => shortlistScore(f.title, f.body, r)) {
8958
+ if (typeof k !== "number" || Number.isNaN(k) || !Number.isInteger(k)) {
8959
+ throw new Error(`buildShortlist: k must be a non-negative integer, got ${String(k)}`);
8960
+ }
8961
+ if (k <= 0) return [];
8962
+ const byKey = /* @__PURE__ */ new Map();
8963
+ for (const r of rows) {
8964
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
8965
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
8966
+ byKey.set(normalizeTitleKey(r.title), r);
8967
+ }
8968
+ const scored = [...byKey.values()].map((row) => ({ row, score: score(fact, row) }));
8969
+ scored.sort((a, b) => {
8970
+ if (a.score !== b.score) return b.score - a.score;
8971
+ return a.row.title < b.row.title ? -1 : a.row.title > b.row.title ? 1 : 0;
8972
+ });
8973
+ return scored.slice(0, k).map((s) => s.row);
8974
+ }
8975
+
8935
8976
  // src/services/TemporalService.ts
8936
8977
  var HISTORY_MAX_DEPTH = 100;
8937
8978
  var TemporalService = class {
@@ -9121,6 +9162,17 @@ function resolveSystemOneTyping(config, classifierCallOption) {
9121
9162
  }
9122
9163
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
9123
9164
  }
9165
+ var DEFAULT_SHORTLIST_K = 10;
9166
+ function resolveShortlistK(config) {
9167
+ const k = config?.ontology?.shortlistK;
9168
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
9169
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
9170
+ throw new Error(
9171
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
9172
+ );
9173
+ }
9174
+ return k;
9175
+ }
9124
9176
  var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
9125
9177
  function resolveTypingMinConfidence(config) {
9126
9178
  const systemOneFloor = config?.systemOne?.minConfidence?.typing;
@@ -12261,6 +12313,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12261
12313
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
12262
12314
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
12263
12315
  }
12316
+ const shortlistK = resolveShortlistK(this.options.config);
12264
12317
  const trigger = options?.trigger ?? "call";
12265
12318
  const now = Date.now();
12266
12319
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -12308,7 +12361,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12308
12361
  meter: options?.meter,
12309
12362
  trigger,
12310
12363
  batchSize: escalated.length,
12311
- recheckCutoff
12364
+ recheckCutoff,
12365
+ shortlistK
12312
12366
  });
12313
12367
  return {
12314
12368
  scanned: classifierRun.result.scanned,
@@ -12329,7 +12383,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12329
12383
  promptOverride: options?.promptOverride,
12330
12384
  meter: options?.meter,
12331
12385
  trigger,
12332
- recheckCutoff
12386
+ recheckCutoff,
12387
+ shortlistK
12333
12388
  });
12334
12389
  }
12335
12390
  /**
@@ -12357,19 +12412,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
12357
12412
  */
12358
12413
  async _runGenerativeBackfill(entityId, candidates, runOpts) {
12359
12414
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
12415
+ const shortlistK = runOpts.shortlistK;
12416
+ if (shortlistK === void 0) {
12417
+ throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
12418
+ }
12360
12419
  const ontologyService = this.ontologyService;
12361
12420
  const now = Date.now();
12362
12421
  const recheckCutoff = runOpts.recheckCutoff;
12363
12422
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
12364
- const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
12365
- const titleCatalog = buildTitleCatalogBlock(titleRows);
12423
+ const shortlistRows = await this.entryRepo.findShortlistRowsByEntityId(entityId);
12366
12424
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
12367
- const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
12368
- facts.map(toPromptShape),
12369
- runOpts.promptOverride,
12370
- ontologyContext,
12371
- titleCatalog
12372
- );
12425
+ const shortlistScorer = createShortlistScorer(shortlistRows);
12426
+ const shortlistCache = /* @__PURE__ */ new Map();
12427
+ const buildPrompt = (facts) => {
12428
+ const rowsByFact = /* @__PURE__ */ new Map();
12429
+ for (const f of facts) {
12430
+ let rows = shortlistCache.get(f.id);
12431
+ if (!rows) {
12432
+ rows = buildShortlist({ title: f.title, body: f.body }, shortlistRows, shortlistK, shortlistScorer);
12433
+ shortlistCache.set(f.id, rows);
12434
+ }
12435
+ rowsByFact.set(f.id, rows);
12436
+ }
12437
+ return this.promptService.buildOntologyBackfillPrompt(
12438
+ facts.map(toPromptShape),
12439
+ runOpts.promptOverride,
12440
+ ontologyContext,
12441
+ buildCandidateSections(facts, rowsByFact)
12442
+ );
12443
+ };
12373
12444
  const outcome = await runBatched({
12374
12445
  items: candidates,
12375
12446
  buildPrompt,