@equationalapplications/core-llm-wiki 9.9.0 → 9.11.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. */
@@ -2768,6 +2751,7 @@ var DEFAULT_CHUNK_OVERLAP = 400;
2768
2751
 
2769
2752
  // src/utils/contextCaps.ts
2770
2753
  var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
2754
+ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
2771
2755
  var HEAL_MAX_PROMPT_CHARS = 4e4;
2772
2756
  var OPS_MAX_EXTRACT_CHARS = 24e3;
2773
2757
 
@@ -2778,7 +2762,8 @@ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
2778
2762
  var OP_FLOOR = {
2779
2763
  resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
2780
2764
  heal: HEAL_MAX_PROMPT_CHARS,
2781
- extract: OPS_MAX_EXTRACT_CHARS
2765
+ extract: OPS_MAX_EXTRACT_CHARS,
2766
+ backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
2782
2767
  };
2783
2768
  function bad(key, value, why) {
2784
2769
  return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
@@ -2816,12 +2801,11 @@ function declaredPromptCap(budget, op) {
2816
2801
  const derived = Math.floor(
2817
2802
  (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
2818
2803
  );
2819
- if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
2820
- return Math.max(OP_FLOOR.heal, derived);
2804
+ return Math.max(OP_FLOOR[op], derived);
2821
2805
  }
2822
2806
  function resolveMaxPromptChars(budget, op) {
2823
2807
  if (budget.mode !== "declared") {
2824
- return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
2808
+ return OP_FLOOR[op];
2825
2809
  }
2826
2810
  if (op === "extract") {
2827
2811
  const resolveDerived = declaredPromptCap(budget, "resolve");
@@ -3980,6 +3964,17 @@ function resolveSystemOneTyping(config, classifierCallOption) {
3980
3964
  }
3981
3965
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3982
3966
  }
3967
+ var DEFAULT_SHORTLIST_K = 10;
3968
+ function resolveShortlistK(config) {
3969
+ const k = config?.ontology?.shortlistK;
3970
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
3971
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
3972
+ throw new Error(
3973
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
3974
+ );
3975
+ }
3976
+ return k;
3977
+ }
3983
3978
  var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3984
3979
  function resolveTypingMinConfidence(config) {
3985
3980
  const systemOneFloor = config?.systemOne?.minConfidence?.typing;
@@ -4044,6 +4039,52 @@ function classifierStateForFact(fact) {
4044
4039
  return parts.join("\n\n");
4045
4040
  }
4046
4041
 
4042
+ // src/utils/shortlist.ts
4043
+ function shortlistScore(factTitle, factBody, row) {
4044
+ const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
4045
+ const rowTokens = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
4046
+ return jaccardScore(factTokens, rowTokens);
4047
+ }
4048
+ function createShortlistScorer(rows) {
4049
+ const rowTokens = /* @__PURE__ */ new Map();
4050
+ const tokensOfRow = (row) => {
4051
+ let t = rowTokens.get(row);
4052
+ if (!t) {
4053
+ t = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
4054
+ rowTokens.set(row, t);
4055
+ }
4056
+ return t;
4057
+ };
4058
+ for (const r of rows) tokensOfRow(r);
4059
+ const factTokens = /* @__PURE__ */ new WeakMap();
4060
+ return (fact, row) => {
4061
+ let ft = factTokens.get(fact);
4062
+ if (!ft) {
4063
+ ft = /* @__PURE__ */ new Set([...titleTokens(fact.title), ...titleTokens(fact.body)]);
4064
+ factTokens.set(fact, ft);
4065
+ }
4066
+ return jaccardScore(ft, tokensOfRow(row));
4067
+ };
4068
+ }
4069
+ function buildShortlist(fact, rows, k, score = (f, r) => shortlistScore(f.title, f.body, r)) {
4070
+ if (typeof k !== "number" || Number.isNaN(k) || !Number.isInteger(k)) {
4071
+ throw new Error(`buildShortlist: k must be a non-negative integer, got ${String(k)}`);
4072
+ }
4073
+ if (k <= 0) return [];
4074
+ const byKey = /* @__PURE__ */ new Map();
4075
+ for (const r of rows) {
4076
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
4077
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
4078
+ byKey.set(normalizeTitleKey(r.title), r);
4079
+ }
4080
+ const scored = [...byKey.values()].map((row) => ({ row, score: score(fact, row) }));
4081
+ scored.sort((a, b) => {
4082
+ if (a.score !== b.score) return b.score - a.score;
4083
+ return a.row.title < b.row.title ? -1 : a.row.title > b.row.title ? 1 : 0;
4084
+ });
4085
+ return scored.slice(0, k).map((s) => s.row);
4086
+ }
4087
+
4047
4088
  // src/utils/temporal.ts
4048
4089
  function liveAtSql(mode, alias = "") {
4049
4090
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -6987,7 +7028,6 @@ async function runLibrarianStrategy(deps, ctx) {
6987
7028
  // src/services/MaintenanceService.ts
6988
7029
  var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
6989
7030
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
6990
- var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
6991
7031
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
6992
7032
  var CLASSIFIER_MAX_CHOICES = 255;
6993
7033
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
@@ -8463,6 +8503,8 @@ 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);
8507
+ const maxPromptChars = resolveMaxPromptChars(resolveContextBudget(this.options.config), "backfill");
8466
8508
  const trigger = options?.trigger ?? "call";
8467
8509
  const now = Date.now();
8468
8510
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -8510,7 +8552,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8510
8552
  meter: options?.meter,
8511
8553
  trigger,
8512
8554
  batchSize: escalated.length,
8513
- recheckCutoff
8555
+ recheckCutoff,
8556
+ shortlistK,
8557
+ maxPromptChars
8514
8558
  });
8515
8559
  return {
8516
8560
  scanned: classifierRun.result.scanned,
@@ -8531,7 +8575,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8531
8575
  promptOverride: options?.promptOverride,
8532
8576
  meter: options?.meter,
8533
8577
  trigger,
8534
- recheckCutoff
8578
+ recheckCutoff,
8579
+ shortlistK,
8580
+ maxPromptChars
8535
8581
  });
8536
8582
  }
8537
8583
  /**
@@ -8559,19 +8605,39 @@ DROP TRIGGER IF EXISTS ${ad};`);
8559
8605
  */
8560
8606
  async _runGenerativeBackfill(entityId, candidates, runOpts) {
8561
8607
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
8608
+ const shortlistK = runOpts.shortlistK;
8609
+ if (shortlistK === void 0) {
8610
+ throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
8611
+ }
8612
+ const maxPromptChars = runOpts.maxPromptChars;
8613
+ if (maxPromptChars === void 0) {
8614
+ throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
8615
+ }
8562
8616
  const ontologyService = this.ontologyService;
8563
8617
  const now = Date.now();
8564
8618
  const recheckCutoff = runOpts.recheckCutoff;
8565
8619
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
8566
- const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
8567
- const titleCatalog = buildTitleCatalogBlock(titleRows);
8620
+ const shortlistRows = await this.entryRepo.findShortlistRowsByEntityId(entityId);
8568
8621
  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
- );
8622
+ const shortlistScorer = createShortlistScorer(shortlistRows);
8623
+ const shortlistCache = /* @__PURE__ */ new Map();
8624
+ const buildPrompt = (facts) => {
8625
+ const rowsByFact = /* @__PURE__ */ new Map();
8626
+ for (const f of facts) {
8627
+ let rows = shortlistCache.get(f.id);
8628
+ if (!rows) {
8629
+ rows = buildShortlist({ title: f.title, body: f.body }, shortlistRows, shortlistK, shortlistScorer);
8630
+ shortlistCache.set(f.id, rows);
8631
+ }
8632
+ rowsByFact.set(f.id, rows);
8633
+ }
8634
+ return this.promptService.buildOntologyBackfillPrompt(
8635
+ facts.map(toPromptShape),
8636
+ runOpts.promptOverride,
8637
+ ontologyContext,
8638
+ buildCandidateSections(facts, rowsByFact)
8639
+ );
8640
+ };
8575
8641
  const outcome = await runBatched({
8576
8642
  items: candidates,
8577
8643
  buildPrompt,
@@ -8585,7 +8651,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8585
8651
  };
8586
8652
  },
8587
8653
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
8588
- maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
8654
+ maxPromptChars,
8589
8655
  onSkip: (fact, err) => {
8590
8656
  if (isContextOverflowError(err)) {
8591
8657
  emitDiagnostic(this.options, {
@@ -11550,5 +11616,5 @@ var WriteService = class {
11550
11616
  };
11551
11617
 
11552
11618
  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
11619
+ //# sourceMappingURL=chunk-QUVPQVJ6.mjs.map
11620
+ //# sourceMappingURL=chunk-QUVPQVJ6.mjs.map