@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.
@@ -127,6 +127,11 @@ interface OntologyConfig {
127
127
  * (no edges are proposed); `'llm'` always uses `generateText`. Default `'llm'`.
128
128
  */
129
129
  backfillClassifier?: 'auto' | 'llm';
130
+ /**
131
+ * Maximum number of candidate typed nodes (titles) shortlisted per fact in
132
+ * the backfill shortlist. Must be a finite integer >= 1; anything else throws. Default 10.
133
+ */
134
+ shortlistK?: number;
130
135
  /** Minimum classifier confidence to apply a node type. Finite, in [0, 1]. Default 0.5. */
131
136
  classifyMinConfidence?: number;
132
137
  /**
@@ -1634,11 +1639,11 @@ interface WikiInstructions {
1634
1639
  librarian: string;
1635
1640
  heal: string;
1636
1641
  /**
1637
- * Template only: the run-time prompt additionally carries a TITLE CATALOG
1638
- * of the entity's typed node titles (appended after this text, before the
1639
- * ontology block) whenever a catalog is built — see
1640
- * `buildTitleCatalogBlock` and the data-scope note in the ontology-backfill
1641
- * spec Errata (PR #425).
1642
+ * Template only: the run-time user prompt additionally carries per-fact
1643
+ * CANDIDATE TARGETS sections (a top-k shortlist of the entity's typed node
1644
+ * titles, after the Facts JSON) — see `buildCandidateSections` and the
1645
+ * Errata in `specs/backfill-shortlist-wiring/spec.md`, which supersede the
1646
+ * earlier title-catalog data-scope note (PR #425).
1642
1647
  */
1643
1648
  ontologyBackfill: string;
1644
1649
  }
@@ -2321,6 +2326,17 @@ declare class EntryRepository extends BaseRepository {
2321
2326
  title: string;
2322
2327
  okf_type: string | null;
2323
2328
  }>>;
2329
+ /**
2330
+ * Shortlist scoring rows (id, title, okf_type, body) over all live typed
2331
+ * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL
2332
+ * in results because the query excludes untyped rows.
2333
+ */
2334
+ findShortlistRowsByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{
2335
+ id: string;
2336
+ title: string;
2337
+ okf_type: string;
2338
+ body: string;
2339
+ }>>;
2324
2340
  /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */
2325
2341
  countHealCandidatesByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{
2326
2342
  eligible: number;
@@ -3552,7 +3568,7 @@ declare class PromptService {
3552
3568
  degraded: DegradedRecord[];
3553
3569
  groundingCorpus?: string[];
3554
3570
  };
3555
- buildOntologyBackfillPrompt(facts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, titleCatalog?: string): {
3571
+ buildOntologyBackfillPrompt(facts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, candidateSections?: string): {
3556
3572
  systemPrompt: string;
3557
3573
  userPrompt: string;
3558
3574
  };
@@ -127,6 +127,11 @@ interface OntologyConfig {
127
127
  * (no edges are proposed); `'llm'` always uses `generateText`. Default `'llm'`.
128
128
  */
129
129
  backfillClassifier?: 'auto' | 'llm';
130
+ /**
131
+ * Maximum number of candidate typed nodes (titles) shortlisted per fact in
132
+ * the backfill shortlist. Must be a finite integer >= 1; anything else throws. Default 10.
133
+ */
134
+ shortlistK?: number;
130
135
  /** Minimum classifier confidence to apply a node type. Finite, in [0, 1]. Default 0.5. */
131
136
  classifyMinConfidence?: number;
132
137
  /**
@@ -1634,11 +1639,11 @@ interface WikiInstructions {
1634
1639
  librarian: string;
1635
1640
  heal: string;
1636
1641
  /**
1637
- * Template only: the run-time prompt additionally carries a TITLE CATALOG
1638
- * of the entity's typed node titles (appended after this text, before the
1639
- * ontology block) whenever a catalog is built — see
1640
- * `buildTitleCatalogBlock` and the data-scope note in the ontology-backfill
1641
- * spec Errata (PR #425).
1642
+ * Template only: the run-time user prompt additionally carries per-fact
1643
+ * CANDIDATE TARGETS sections (a top-k shortlist of the entity's typed node
1644
+ * titles, after the Facts JSON) — see `buildCandidateSections` and the
1645
+ * Errata in `specs/backfill-shortlist-wiring/spec.md`, which supersede the
1646
+ * earlier title-catalog data-scope note (PR #425).
1642
1647
  */
1643
1648
  ontologyBackfill: string;
1644
1649
  }
@@ -2321,6 +2326,17 @@ declare class EntryRepository extends BaseRepository {
2321
2326
  title: string;
2322
2327
  okf_type: string | null;
2323
2328
  }>>;
2329
+ /**
2330
+ * Shortlist scoring rows (id, title, okf_type, body) over all live typed
2331
+ * facts. Same filters as findTitleIndexByEntityId; okf_type is never NULL
2332
+ * in results because the query excludes untyped rows.
2333
+ */
2334
+ findShortlistRowsByEntityId(entityId: string, tx?: SQLiteAdapter): Promise<Array<{
2335
+ id: string;
2336
+ title: string;
2337
+ okf_type: string;
2338
+ body: string;
2339
+ }>>;
2324
2340
  /** Counts live mutable facts: eligible (past cooldown) vs deferred (in cooldown). */
2325
2341
  countHealCandidatesByEntityId(entityId: string, recheckCutoff: number, tx?: SQLiteAdapter): Promise<{
2326
2342
  eligible: number;
@@ -3552,7 +3568,7 @@ declare class PromptService {
3552
3568
  degraded: DegradedRecord[];
3553
3569
  groundingCorpus?: string[];
3554
3570
  };
3555
- buildOntologyBackfillPrompt(facts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, titleCatalog?: string): {
3571
+ buildOntologyBackfillPrompt(facts: unknown[], runtimeOverride?: string, ontologyContext?: OntologyPromptContext | null, candidateSections?: string): {
3556
3572
  systemPrompt: string;
3557
3573
  userPrompt: string;
3558
3574
  };
@@ -1,2 +1,2 @@
1
- export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-CDSfjx8j.mjs';
1
+ export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-DnYjL2QD.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-CDSfjx8j.js';
1
+ export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-DnYjL2QD.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -2486,46 +2486,29 @@ Return ONLY a valid JSON object matching this schema:
2486
2486
  }
2487
2487
  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).
2488
2488
  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.`;
2489
- var TITLE_CATALOG_MAX_ENTRIES = 200;
2490
- function buildTitleCatalogBlock(rows) {
2491
- const byKey = /* @__PURE__ */ new Map();
2492
- for (const r of rows) {
2493
- if (typeof r.title !== "string" || r.title.length === 0) continue;
2494
- if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
2495
- byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
2496
- }
2497
- const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
2498
- const CHAR_BUDGET = 8e3;
2499
- const listed = [];
2500
- let used = 0;
2501
- for (const r of typed) {
2502
- const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2503
- if (line.length + 1 > CHAR_BUDGET) continue;
2504
- if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
2505
- if (used + line.length + 1 > CHAR_BUDGET) continue;
2506
- listed.push(r);
2507
- used += line.length + 1;
2508
- }
2509
- const truncated = typed.length > listed.length;
2510
- if (typed.length === 0) {
2511
- return [
2512
- "TITLE CATALOG: this memory contains no typed nodes yet.",
2513
- 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2514
- ].join("\n");
2489
+ function formatCatalogLine(r) {
2490
+ return `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2491
+ }
2492
+ function buildCandidateSections(facts, rowsByFact) {
2493
+ 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.';
2494
+ const sections = [];
2495
+ for (const fact of facts) {
2496
+ const rows = rowsByFact.get(fact.id);
2497
+ if (!rows || rows.length === 0) continue;
2498
+ sections.push(
2499
+ [
2500
+ `CANDIDATE TARGETS for fact ${JSON.stringify(fact.id)}: typed nodes in this memory, ranked by title overlap:`,
2501
+ ...rows.map(formatCatalogLine)
2502
+ ].join("\n")
2503
+ );
2515
2504
  }
2516
- if (listed.length === 0) {
2505
+ if (sections.length === 0) {
2517
2506
  return [
2518
- "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
2507
+ "CANDIDATE TARGETS: this memory contains no typed nodes yet.",
2519
2508
  'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2520
2509
  ].join("\n");
2521
2510
  }
2522
- const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
2523
- return [
2524
- "TITLE CATALOG: existing typed nodes in this memory include:",
2525
- catalog,
2526
- ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
2527
- '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.'
2528
- ].join("\n");
2511
+ return [...sections, footer].join("\n\n");
2529
2512
  }
2530
2513
  var GROUNDING_SOURCE = {
2531
2514
  ingest: { key: "facts", source: "the document chunk" },
@@ -2857,7 +2840,7 @@ The following document anchors are provided for contradiction detection only. Do
2857
2840
  ...corpusField
2858
2841
  };
2859
2842
  }
2860
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
2843
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, candidateSections) {
2861
2844
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
2862
2845
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2863
2846
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -2867,13 +2850,13 @@ The following document anchors are provided for contradiction detection only. Do
2867
2850
  ${JSON.stringify(facts, null, 2)}`
2868
2851
  };
2869
2852
  }
2870
- const effective = titleCatalog !== void 0 ? `${template}
2871
-
2872
- ${titleCatalog}` : template;
2853
+ const factsBlock = `Facts:
2854
+ ${JSON.stringify(facts, null, 2)}`;
2873
2855
  return {
2874
- systemPrompt: this.appendOntology(effective, ontologyContext),
2875
- userPrompt: `Facts:
2876
- ${JSON.stringify(facts, null, 2)}`
2856
+ systemPrompt: this.appendOntology(template, ontologyContext),
2857
+ userPrompt: candidateSections !== void 0 ? `${factsBlock}
2858
+
2859
+ ${candidateSections}` : factsBlock
2877
2860
  };
2878
2861
  }
2879
2862
  /** Ops extract (spec §5.2): events only — no existing facts. */
@@ -3915,6 +3898,52 @@ function classifierStateForFact(fact) {
3915
3898
  return parts.join("\n\n");
3916
3899
  }
3917
3900
 
3901
+ // src/utils/shortlist.ts
3902
+ function shortlistScore(factTitle, factBody, row) {
3903
+ const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
3904
+ const rowTokens = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
3905
+ return jaccardScore(factTokens, rowTokens);
3906
+ }
3907
+ function createShortlistScorer(rows) {
3908
+ const rowTokens = /* @__PURE__ */ new Map();
3909
+ const tokensOfRow = (row) => {
3910
+ let t = rowTokens.get(row);
3911
+ if (!t) {
3912
+ t = /* @__PURE__ */ new Set([...titleTokens(row.title), ...titleTokens(row.body ?? "")]);
3913
+ rowTokens.set(row, t);
3914
+ }
3915
+ return t;
3916
+ };
3917
+ for (const r of rows) tokensOfRow(r);
3918
+ const factTokens = /* @__PURE__ */ new WeakMap();
3919
+ return (fact, row) => {
3920
+ let ft = factTokens.get(fact);
3921
+ if (!ft) {
3922
+ ft = /* @__PURE__ */ new Set([...titleTokens(fact.title), ...titleTokens(fact.body)]);
3923
+ factTokens.set(fact, ft);
3924
+ }
3925
+ return jaccardScore(ft, tokensOfRow(row));
3926
+ };
3927
+ }
3928
+ function buildShortlist(fact, rows, k, score = (f, r) => shortlistScore(f.title, f.body, r)) {
3929
+ if (typeof k !== "number" || Number.isNaN(k) || !Number.isInteger(k)) {
3930
+ throw new Error(`buildShortlist: k must be a non-negative integer, got ${String(k)}`);
3931
+ }
3932
+ if (k <= 0) return [];
3933
+ const byKey = /* @__PURE__ */ new Map();
3934
+ for (const r of rows) {
3935
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
3936
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
3937
+ byKey.set(normalizeTitleKey(r.title), r);
3938
+ }
3939
+ const scored = [...byKey.values()].map((row) => ({ row, score: score(fact, row) }));
3940
+ scored.sort((a, b) => {
3941
+ if (a.score !== b.score) return b.score - a.score;
3942
+ return a.row.title < b.row.title ? -1 : a.row.title > b.row.title ? 1 : 0;
3943
+ });
3944
+ return scored.slice(0, k).map((s) => s.row);
3945
+ }
3946
+
3918
3947
  // src/utils/temporal.ts
3919
3948
  function liveAtSql(mode, alias = "") {
3920
3949
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -4086,6 +4115,17 @@ function resolveSystemOneTyping(config, classifierCallOption) {
4086
4115
  }
4087
4116
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
4088
4117
  }
4118
+ var DEFAULT_SHORTLIST_K = 10;
4119
+ function resolveShortlistK(config) {
4120
+ const k = config?.ontology?.shortlistK;
4121
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
4122
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
4123
+ throw new Error(
4124
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
4125
+ );
4126
+ }
4127
+ return k;
4128
+ }
4089
4129
  var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
4090
4130
  function resolveTypingMinConfidence(config) {
4091
4131
  const systemOneFloor = config?.systemOne?.minConfidence?.typing;
@@ -7363,6 +7403,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7363
7403
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
7364
7404
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
7365
7405
  }
7406
+ const shortlistK = resolveShortlistK(this.options.config);
7366
7407
  const trigger = options?.trigger ?? "call";
7367
7408
  const now = Date.now();
7368
7409
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -7410,7 +7451,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7410
7451
  meter: options?.meter,
7411
7452
  trigger,
7412
7453
  batchSize: escalated.length,
7413
- recheckCutoff
7454
+ recheckCutoff,
7455
+ shortlistK
7414
7456
  });
7415
7457
  return {
7416
7458
  scanned: classifierRun.result.scanned,
@@ -7431,7 +7473,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7431
7473
  promptOverride: options?.promptOverride,
7432
7474
  meter: options?.meter,
7433
7475
  trigger,
7434
- recheckCutoff
7476
+ recheckCutoff,
7477
+ shortlistK
7435
7478
  });
7436
7479
  }
7437
7480
  /**
@@ -7459,19 +7502,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
7459
7502
  */
7460
7503
  async _runGenerativeBackfill(entityId, candidates, runOpts) {
7461
7504
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
7505
+ const shortlistK = runOpts.shortlistK;
7506
+ if (shortlistK === void 0) {
7507
+ throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
7508
+ }
7462
7509
  const ontologyService = this.ontologyService;
7463
7510
  const now = Date.now();
7464
7511
  const recheckCutoff = runOpts.recheckCutoff;
7465
7512
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
7466
- const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
7467
- const titleCatalog = buildTitleCatalogBlock(titleRows);
7513
+ const shortlistRows = await this.entryRepo.findShortlistRowsByEntityId(entityId);
7468
7514
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
7469
- const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
7470
- facts.map(toPromptShape),
7471
- runOpts.promptOverride,
7472
- ontologyContext,
7473
- titleCatalog
7474
- );
7515
+ const shortlistScorer = createShortlistScorer(shortlistRows);
7516
+ const shortlistCache = /* @__PURE__ */ new Map();
7517
+ const buildPrompt = (facts) => {
7518
+ const rowsByFact = /* @__PURE__ */ new Map();
7519
+ for (const f of facts) {
7520
+ let rows = shortlistCache.get(f.id);
7521
+ if (!rows) {
7522
+ rows = buildShortlist({ title: f.title, body: f.body }, shortlistRows, shortlistK, shortlistScorer);
7523
+ shortlistCache.set(f.id, rows);
7524
+ }
7525
+ rowsByFact.set(f.id, rows);
7526
+ }
7527
+ return this.promptService.buildOntologyBackfillPrompt(
7528
+ facts.map(toPromptShape),
7529
+ runOpts.promptOverride,
7530
+ ontologyContext,
7531
+ buildCandidateSections(facts, rowsByFact)
7532
+ );
7533
+ };
7475
7534
  const outcome = await runBatched({
7476
7535
  items: candidates,
7477
7536
  buildPrompt,