@equationalapplications/core-llm-wiki 9.8.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.
@@ -2292,46 +2292,29 @@ Return ONLY a valid JSON object matching this schema:
2292
2292
  }
2293
2293
  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).
2294
2294
  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.`;
2295
- var TITLE_CATALOG_MAX_ENTRIES = 200;
2296
- function buildTitleCatalogBlock(rows) {
2297
- const byKey = /* @__PURE__ */ new Map();
2298
- for (const r of rows) {
2299
- if (typeof r.title !== "string" || r.title.length === 0) continue;
2300
- if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
2301
- byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
2302
- }
2303
- const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
2304
- const CHAR_BUDGET = 8e3;
2305
- const listed = [];
2306
- let used = 0;
2307
- for (const r of typed) {
2308
- const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2309
- if (line.length + 1 > CHAR_BUDGET) continue;
2310
- if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
2311
- if (used + line.length + 1 > CHAR_BUDGET) continue;
2312
- listed.push(r);
2313
- used += line.length + 1;
2314
- }
2315
- const truncated = typed.length > listed.length;
2316
- if (typed.length === 0) {
2317
- return [
2318
- "TITLE CATALOG: this memory contains no typed nodes yet.",
2319
- 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2320
- ].join("\n");
2295
+ function formatCatalogLine(r) {
2296
+ return `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2297
+ }
2298
+ function buildCandidateSections(facts, rowsByFact) {
2299
+ 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.';
2300
+ const sections = [];
2301
+ for (const fact of facts) {
2302
+ const rows = rowsByFact.get(fact.id);
2303
+ if (!rows || rows.length === 0) continue;
2304
+ sections.push(
2305
+ [
2306
+ `CANDIDATE TARGETS for fact ${JSON.stringify(fact.id)}: typed nodes in this memory, ranked by title overlap:`,
2307
+ ...rows.map(formatCatalogLine)
2308
+ ].join("\n")
2309
+ );
2321
2310
  }
2322
- if (listed.length === 0) {
2311
+ if (sections.length === 0) {
2323
2312
  return [
2324
- "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
2313
+ "CANDIDATE TARGETS: this memory contains no typed nodes yet.",
2325
2314
  'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2326
2315
  ].join("\n");
2327
2316
  }
2328
- const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
2329
- return [
2330
- "TITLE CATALOG: existing typed nodes in this memory include:",
2331
- catalog,
2332
- ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
2333
- '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.'
2334
- ].join("\n");
2317
+ return [...sections, footer].join("\n\n");
2335
2318
  }
2336
2319
  var GROUNDING_SOURCE = {
2337
2320
  ingest: { key: "facts", source: "the document chunk" },
@@ -2663,7 +2646,7 @@ The following document anchors are provided for contradiction detection only. Do
2663
2646
  ...corpusField
2664
2647
  };
2665
2648
  }
2666
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
2649
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, candidateSections) {
2667
2650
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
2668
2651
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2669
2652
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -2673,13 +2656,13 @@ The following document anchors are provided for contradiction detection only. Do
2673
2656
  ${JSON.stringify(facts, null, 2)}`
2674
2657
  };
2675
2658
  }
2676
- const effective = titleCatalog !== void 0 ? `${template}
2677
-
2678
- ${titleCatalog}` : template;
2659
+ const factsBlock = `Facts:
2660
+ ${JSON.stringify(facts, null, 2)}`;
2679
2661
  return {
2680
- systemPrompt: this.appendOntology(effective, ontologyContext),
2681
- userPrompt: `Facts:
2682
- ${JSON.stringify(facts, null, 2)}`
2662
+ systemPrompt: this.appendOntology(template, ontologyContext),
2663
+ userPrompt: candidateSections !== void 0 ? `${factsBlock}
2664
+
2665
+ ${candidateSections}` : factsBlock
2683
2666
  };
2684
2667
  }
2685
2668
  /** Ops extract (spec §5.2): events only — no existing facts. */
@@ -3980,6 +3963,17 @@ function resolveSystemOneTyping(config, classifierCallOption) {
3980
3963
  }
3981
3964
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3982
3965
  }
3966
+ var DEFAULT_SHORTLIST_K = 10;
3967
+ function resolveShortlistK(config) {
3968
+ const k = config?.ontology?.shortlistK;
3969
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
3970
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
3971
+ throw new Error(
3972
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
3973
+ );
3974
+ }
3975
+ return k;
3976
+ }
3983
3977
  var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3984
3978
  function resolveTypingMinConfidence(config) {
3985
3979
  const systemOneFloor = config?.systemOne?.minConfidence?.typing;
@@ -4044,6 +4038,52 @@ function classifierStateForFact(fact) {
4044
4038
  return parts.join("\n\n");
4045
4039
  }
4046
4040
 
4041
+ // src/utils/shortlist.ts
4042
+ function shortlistScore(factTitle, factBody, row) {
4043
+ const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
4044
+ const rowTokens = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
4045
+ return jaccardScore(factTokens, rowTokens);
4046
+ }
4047
+ function createShortlistScorer(rows) {
4048
+ const rowTokens = /* @__PURE__ */ new Map();
4049
+ const tokensOfRow = (row) => {
4050
+ let t = rowTokens.get(row);
4051
+ if (!t) {
4052
+ t = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
4053
+ rowTokens.set(row, t);
4054
+ }
4055
+ return t;
4056
+ };
4057
+ for (const r of rows) tokensOfRow(r);
4058
+ const factTokens = /* @__PURE__ */ new WeakMap();
4059
+ return (fact, row) => {
4060
+ let ft = factTokens.get(fact);
4061
+ if (!ft) {
4062
+ ft = /* @__PURE__ */ new Set([...titleTokens(fact.title), ...titleTokens(fact.body)]);
4063
+ factTokens.set(fact, ft);
4064
+ }
4065
+ return jaccardScore(ft, tokensOfRow(row));
4066
+ };
4067
+ }
4068
+ function buildShortlist(fact, rows, k, score = (f, r) => shortlistScore(f.title, f.body, r)) {
4069
+ if (typeof k !== "number" || Number.isNaN(k) || !Number.isInteger(k)) {
4070
+ throw new Error(`buildShortlist: k must be a non-negative integer, got ${String(k)}`);
4071
+ }
4072
+ if (k <= 0) return [];
4073
+ const byKey = /* @__PURE__ */ new Map();
4074
+ for (const r of rows) {
4075
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
4076
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
4077
+ byKey.set(normalizeTitleKey(r.title), r);
4078
+ }
4079
+ const scored = [...byKey.values()].map((row) => ({ row, score: score(fact, row) }));
4080
+ scored.sort((a, b) => {
4081
+ if (a.score !== b.score) return b.score - a.score;
4082
+ return a.row.title < b.row.title ? -1 : a.row.title > b.row.title ? 1 : 0;
4083
+ });
4084
+ return scored.slice(0, k).map((s) => s.row);
4085
+ }
4086
+
4047
4087
  // src/utils/temporal.ts
4048
4088
  function liveAtSql(mode, alias = "") {
4049
4089
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -8463,6 +8503,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8463
8503
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
8464
8504
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
8465
8505
  }
8506
+ const shortlistK = resolveShortlistK(this.options.config);
8466
8507
  const trigger = options?.trigger ?? "call";
8467
8508
  const now = Date.now();
8468
8509
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -8510,7 +8551,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8510
8551
  meter: options?.meter,
8511
8552
  trigger,
8512
8553
  batchSize: escalated.length,
8513
- recheckCutoff
8554
+ recheckCutoff,
8555
+ shortlistK
8514
8556
  });
8515
8557
  return {
8516
8558
  scanned: classifierRun.result.scanned,
@@ -8531,7 +8573,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8531
8573
  promptOverride: options?.promptOverride,
8532
8574
  meter: options?.meter,
8533
8575
  trigger,
8534
- recheckCutoff
8576
+ recheckCutoff,
8577
+ shortlistK
8535
8578
  });
8536
8579
  }
8537
8580
  /**
@@ -8559,19 +8602,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
8559
8602
  */
8560
8603
  async _runGenerativeBackfill(entityId, candidates, runOpts) {
8561
8604
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
8605
+ const shortlistK = runOpts.shortlistK;
8606
+ if (shortlistK === void 0) {
8607
+ throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
8608
+ }
8562
8609
  const ontologyService = this.ontologyService;
8563
8610
  const now = Date.now();
8564
8611
  const recheckCutoff = runOpts.recheckCutoff;
8565
8612
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
8566
- const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
8567
- const titleCatalog = buildTitleCatalogBlock(titleRows);
8613
+ const shortlistRows = await this.entryRepo.findShortlistRowsByEntityId(entityId);
8568
8614
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
8569
- const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
8570
- facts.map(toPromptShape),
8571
- runOpts.promptOverride,
8572
- ontologyContext,
8573
- titleCatalog
8574
- );
8615
+ const shortlistScorer = createShortlistScorer(shortlistRows);
8616
+ const shortlistCache = /* @__PURE__ */ new Map();
8617
+ const buildPrompt = (facts) => {
8618
+ const rowsByFact = /* @__PURE__ */ new Map();
8619
+ for (const f of facts) {
8620
+ let rows = shortlistCache.get(f.id);
8621
+ if (!rows) {
8622
+ rows = buildShortlist({ title: f.title, body: f.body }, shortlistRows, shortlistK, shortlistScorer);
8623
+ shortlistCache.set(f.id, rows);
8624
+ }
8625
+ rowsByFact.set(f.id, rows);
8626
+ }
8627
+ return this.promptService.buildOntologyBackfillPrompt(
8628
+ facts.map(toPromptShape),
8629
+ runOpts.promptOverride,
8630
+ ontologyContext,
8631
+ buildCandidateSections(facts, rowsByFact)
8632
+ );
8633
+ };
8575
8634
  const outcome = await runBatched({
8576
8635
  items: candidates,
8577
8636
  buildPrompt,
@@ -11550,5 +11609,5 @@ var WriteService = class {
11550
11609
  };
11551
11610
 
11552
11611
  export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11553
- //# sourceMappingURL=chunk-EN37KODZ.mjs.map
11554
- //# sourceMappingURL=chunk-EN37KODZ.mjs.map
11612
+ //# sourceMappingURL=chunk-RPE6OMUZ.mjs.map
11613
+ //# sourceMappingURL=chunk-RPE6OMUZ.mjs.map