@equationalapplications/core-llm-wiki 9.5.0 → 9.5.2

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/testing.js CHANGED
@@ -725,6 +725,7 @@ var SEVERITY = {
725
725
  grounding_failed: "warn",
726
726
  classification_low_confidence: "info",
727
727
  classification_invalid: "warn",
728
+ context_overflow_skipped: "warn",
728
729
  llm_usage: "info",
729
730
  librarian_gate: "info",
730
731
  librarian_op_rejected: "warn",
@@ -770,6 +771,7 @@ var MESSAGE = {
770
771
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
771
772
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
772
773
  classification_invalid: "A classifier answer was invalid and was not applied.",
774
+ context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
773
775
  llm_usage: "An LLM call completed; token usage attached.",
774
776
  librarian_gate: "Librarian gate outcome counts for one pass.",
775
777
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
@@ -2412,6 +2414,47 @@ Return ONLY a valid JSON object matching this schema:
2412
2414
  }
2413
2415
  If no manifest type fits a fact, omit that fact from "classifications" entirely \u2014 do not guess.
2414
2416
  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.`;
2417
+ var TITLE_CATALOG_MAX_ENTRIES = 200;
2418
+ function buildTitleCatalogBlock(rows) {
2419
+ const byKey = /* @__PURE__ */ new Map();
2420
+ for (const r of rows) {
2421
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
2422
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
2423
+ byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
2424
+ }
2425
+ const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
2426
+ const CHAR_BUDGET = 8e3;
2427
+ const listed = [];
2428
+ let used = 0;
2429
+ for (const r of typed) {
2430
+ const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2431
+ if (line.length + 1 > CHAR_BUDGET) continue;
2432
+ if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
2433
+ if (used + line.length + 1 > CHAR_BUDGET) continue;
2434
+ listed.push(r);
2435
+ used += line.length + 1;
2436
+ }
2437
+ const truncated = typed.length > listed.length;
2438
+ if (typed.length === 0) {
2439
+ return [
2440
+ "TITLE CATALOG: this memory contains no typed nodes yet.",
2441
+ 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2442
+ ].join("\n");
2443
+ }
2444
+ if (listed.length === 0) {
2445
+ return [
2446
+ "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
2447
+ 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2448
+ ].join("\n");
2449
+ }
2450
+ const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
2451
+ return [
2452
+ "TITLE CATALOG: existing typed nodes in this memory include:",
2453
+ catalog,
2454
+ ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
2455
+ '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.'
2456
+ ].join("\n");
2457
+ }
2415
2458
  var GROUNDING_SOURCE = {
2416
2459
  ingest: { key: "facts", source: "the document chunk" },
2417
2460
  librarian: { key: "facts", source: 'the "summary" text of the events' },
@@ -2742,7 +2785,7 @@ The following document anchors are provided for contradiction detection only. Do
2742
2785
  ...corpusField
2743
2786
  };
2744
2787
  }
2745
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext) {
2788
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
2746
2789
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
2747
2790
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2748
2791
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -2752,8 +2795,11 @@ The following document anchors are provided for contradiction detection only. Do
2752
2795
  ${JSON.stringify(facts, null, 2)}`
2753
2796
  };
2754
2797
  }
2798
+ const effective = titleCatalog !== void 0 ? `${template}
2799
+
2800
+ ${titleCatalog}` : template;
2755
2801
  return {
2756
- systemPrompt: this.appendOntology(template, ontologyContext),
2802
+ systemPrompt: this.appendOntology(effective, ontologyContext),
2757
2803
  userPrompt: `Facts:
2758
2804
  ${JSON.stringify(facts, null, 2)}`
2759
2805
  };
@@ -2846,6 +2892,26 @@ var DEFAULT_CHUNK_OVERLAP = 400;
2846
2892
  function estimateTokens(text) {
2847
2893
  return Math.ceil(text.length / 4);
2848
2894
  }
2895
+ var UsageMeter = class {
2896
+ constructor(budget) {
2897
+ this.used = 0;
2898
+ this.estimated = false;
2899
+ if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
2900
+ throw new TypeError("tokenBudget must be a finite number >= 0");
2901
+ }
2902
+ this.budget = budget;
2903
+ }
2904
+ get remaining() {
2905
+ return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
2906
+ }
2907
+ fits(estimate) {
2908
+ return estimate <= this.remaining;
2909
+ }
2910
+ record(r) {
2911
+ this.used += r.inputTokens + r.outputTokens;
2912
+ if (r.estimated) this.estimated = true;
2913
+ }
2914
+ };
2849
2915
  var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
2850
2916
  constructor(requiredEstimate, remaining) {
2851
2917
  super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
@@ -2894,6 +2960,31 @@ async function callLlm(options, ctx, prompts) {
2894
2960
  }
2895
2961
  return text;
2896
2962
  }
2963
+ async function callClassify(options, ctx, request) {
2964
+ const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
2965
+ if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
2966
+ throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
2967
+ }
2968
+ const provider = options.llmProvider;
2969
+ if (typeof provider.classify !== "function") {
2970
+ throw new TypeError("callClassify requires a provider with classify()");
2971
+ }
2972
+ const response = await provider.classify(request);
2973
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
2974
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
2975
+ const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
2976
+ ctx.meter?.record(record);
2977
+ if (options.config?.reportLlmUsage === true) {
2978
+ emitDiagnostic(options, {
2979
+ code: "llm_usage",
2980
+ operation: ctx.operation,
2981
+ trigger: ctx.trigger,
2982
+ entityId: ctx.entityId,
2983
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
2984
+ });
2985
+ }
2986
+ return response;
2987
+ }
2897
2988
 
2898
2989
  // src/services/IngestionService.ts
2899
2990
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
@@ -3961,6 +4052,29 @@ var TRUNCATION_PATTERNS = [
3961
4052
  /finish[_ ]?reason/i
3962
4053
  ];
3963
4054
  var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
4055
+ var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
4056
+ var CONTEXT_OVERFLOW_PATTERNS = [
4057
+ /maximum context length/i,
4058
+ /context[_ ]?length[_ ]?exceeded/i,
4059
+ /prompt is too long/i,
4060
+ /input (token count|is too long)/i,
4061
+ /exceeds? the (available )?context( size)?/i,
4062
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
4063
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
4064
+ // classify as input overflow (it would split the batch and stamp a cooldown).
4065
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4066
+ /context limit/i,
4067
+ /too long for (the )?requested model/i,
4068
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4069
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
4070
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
4071
+ ];
4072
+ function isContextOverflowError(err) {
4073
+ const message = getErrorMessage(err);
4074
+ if (message === void 0) return false;
4075
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4076
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
4077
+ }
3964
4078
  function getErrorMessage(err) {
3965
4079
  try {
3966
4080
  return err instanceof Error ? err.message : String(err ?? "");
@@ -3971,12 +4085,14 @@ function getErrorMessage(err) {
3971
4085
  function isTruncationError(err) {
3972
4086
  const message = getErrorMessage(err);
3973
4087
  if (message === void 0) return false;
4088
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3974
4089
  if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
3975
4090
  return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
3976
4091
  }
3977
4092
  function isConfigError(err) {
3978
4093
  const message = getErrorMessage(err);
3979
4094
  if (message === void 0) return false;
4095
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3980
4096
  return EXCEEDS_LIMIT_PATTERN.test(message);
3981
4097
  }
3982
4098
  function initialBatchSize(maxOutputTokens) {
@@ -3990,7 +4106,7 @@ function initialBatchSize(maxOutputTokens) {
3990
4106
  }
3991
4107
  var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
3992
4108
  async function runBatched(args) {
3993
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
4109
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
3994
4110
  const results = [];
3995
4111
  const skipped = [];
3996
4112
  let batches = 0;
@@ -4024,17 +4140,17 @@ async function runBatched(args) {
4024
4140
  };
4025
4141
  const onFailure = async (batch, err, attemptLevel, fromCall) => {
4026
4142
  if (batch.length === 1) {
4027
- if (fromCall && isTruncationError(err) && attemptLevel < 3) {
4143
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4028
4144
  await attempt(batch, void 0, attemptLevel + 1);
4029
4145
  } else {
4030
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) ? "call_error" : "non_convergent";
4146
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
4031
4147
  skipped.push({ item: batch[0], reason });
4032
4148
  settled.add(batch[0]);
4033
4149
  onSkip?.(batch[0], err);
4034
4150
  }
4035
4151
  return;
4036
4152
  }
4037
- if (fromCall && !isTruncationError(err)) throw err;
4153
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4038
4154
  const mid = Math.ceil(batch.length / 2);
4039
4155
  if (mid < batchSize) batchSize = mid;
4040
4156
  let i = 0;
@@ -4759,6 +4875,8 @@ function parseValidFrom(v) {
4759
4875
  var OPS_MAX_EVENTS_PER_PASS = 50;
4760
4876
  var OPS_MAX_EXTRACT_CHARS = 24e3;
4761
4877
  var RESOLVE_RESERVE_FACTOR = 2;
4878
+ var MIN_SEGMENT_CHARS = 500;
4879
+ var MAX_SEGMENT_CALLS = 8;
4762
4880
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
4763
4881
  async function selectBatch(deps, entityId, wm, meter, guidance) {
4764
4882
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
@@ -4782,9 +4900,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
4782
4900
  }
4783
4901
  return { batch };
4784
4902
  }
4903
+ function splitSummary(summary) {
4904
+ const mid = Math.floor(summary.length / 2);
4905
+ let cut = -1;
4906
+ for (let d = 0; d <= mid; d++) {
4907
+ if (/\s/.test(summary[mid - d] ?? "")) {
4908
+ cut = mid - d;
4909
+ break;
4910
+ }
4911
+ if (/\s/.test(summary[mid + d] ?? "")) {
4912
+ cut = mid + d;
4913
+ break;
4914
+ }
4915
+ }
4916
+ if (cut <= 0 || cut >= summary.length - 1) cut = mid;
4917
+ return [summary.slice(0, cut), summary.slice(cut)];
4918
+ }
4919
+ function dedupeByType(xs) {
4920
+ const seen = /* @__PURE__ */ new Set();
4921
+ return xs.filter((x) => seen.has(x.type) ? false : (seen.add(x.type), true));
4922
+ }
4923
+ function normalizeOntologyUpdates(raw) {
4924
+ if (typeof raw !== "object" || raw === null) return void 0;
4925
+ const r = raw;
4926
+ const pick = (v) => (Array.isArray(v) ? v : []).filter(
4927
+ (x) => !!x && typeof x === "object" && typeof x.type === "string" && x.type.length > 0
4928
+ );
4929
+ const node_types = pick(r.node_types);
4930
+ const edge_types = pick(r.edge_types);
4931
+ return {
4932
+ ...node_types.length ? { node_types } : {},
4933
+ ...edge_types.length ? { edge_types } : {}
4934
+ };
4935
+ }
4936
+ function mergeOutcomes(a, b) {
4937
+ if (a.groundingCorpus === null !== (b.groundingCorpus === null)) {
4938
+ throw new Error("ops extract: merge corpus invariant violated (only one half has a grounding corpus)");
4939
+ }
4940
+ const partOffset = a.groundingCorpus?.length ?? a.batch.length;
4941
+ const indexOffset = a.factItems;
4942
+ const candidates = [
4943
+ ...a.candidates,
4944
+ ...b.candidates.map((c) => ({
4945
+ ...c,
4946
+ index: c.index + indexOffset,
4947
+ sourcePartIndex: c.sourcePartIndex === null ? null : c.sourcePartIndex + partOffset
4948
+ }))
4949
+ ];
4950
+ let ontologyUpdates;
4951
+ if (a.ontologyUpdates || b.ontologyUpdates) {
4952
+ const nodes = dedupeByType([...a.ontologyUpdates?.node_types ?? [], ...b.ontologyUpdates?.node_types ?? []]);
4953
+ const edges = dedupeByType([...a.ontologyUpdates?.edge_types ?? [], ...b.ontologyUpdates?.edge_types ?? []]);
4954
+ ontologyUpdates = {
4955
+ ...nodes.length ? { node_types: nodes } : {},
4956
+ ...edges.length ? { edge_types: edges } : {}
4957
+ };
4958
+ }
4959
+ const shiftedDiags = b.diagnostics.map((d) => {
4960
+ const detail = d.detail;
4961
+ if (typeof detail?.itemIndex !== "number") return d;
4962
+ const off = d.code === "fact_rejected" ? a.factItems : d.code === "task_rejected" ? a.taskItems : 0;
4963
+ return off ? { ...d, detail: { ...detail, itemIndex: detail.itemIndex + off } } : d;
4964
+ });
4965
+ return {
4966
+ batch: [...a.batch, ...b.batch],
4967
+ candidates,
4968
+ tasks: [...a.tasks, ...b.tasks],
4969
+ ...ontologyUpdates ? { ontologyUpdates } : {},
4970
+ groundingCorpus: a.groundingCorpus || b.groundingCorpus ? [...a.groundingCorpus ?? [], ...b.groundingCorpus ?? []] : null,
4971
+ diagnostics: [...a.diagnostics, ...shiftedDiags],
4972
+ skippedEvents: a.skippedEvents + b.skippedEvents,
4973
+ factItems: a.factItems + b.factItems,
4974
+ taskItems: a.taskItems + b.taskItems
4975
+ };
4976
+ }
4977
+ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch) {
4978
+ try {
4979
+ return await extractOnce(deps, ctx, ontologyContext, batch);
4980
+ } catch (err) {
4981
+ if (!isContextOverflowError(err)) throw err;
4982
+ if (batch.length > 1) {
4983
+ const mid = Math.ceil(batch.length / 2);
4984
+ const a = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(0, mid));
4985
+ const b = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(mid));
4986
+ return mergeOutcomes(a, b);
4987
+ }
4988
+ const lone = batch[0];
4989
+ const skipDiag = () => ({
4990
+ entityId: ctx.entityId,
4991
+ operation: "librarian",
4992
+ trigger: ctx.trigger,
4993
+ code: "context_overflow_skipped",
4994
+ detail: { sourceRef: lone.event.id }
4995
+ });
4996
+ const segLabel = (label, n) => label.includes("#") ? `${label}.${n}` : `${label}#${n}`;
4997
+ let segCalls = 0;
4998
+ const extractSegment = async (label, text, alreadyOverflowed) => {
4999
+ if (!alreadyOverflowed) {
5000
+ if (segCalls >= MAX_SEGMENT_CALLS) return null;
5001
+ segCalls++;
5002
+ try {
5003
+ return await extractOnce(deps, ctx, ontologyContext, [{ label, at: lone.at, event: { ...lone.event, summary: text } }]);
5004
+ } catch (e) {
5005
+ if (!isContextOverflowError(e)) throw e;
5006
+ }
5007
+ }
5008
+ if (text.length < 2 * MIN_SEGMENT_CHARS) return null;
5009
+ const [h1, h2] = splitSummary(text);
5010
+ if (h1.length < MIN_SEGMENT_CHARS || h2.length < MIN_SEGMENT_CHARS) return null;
5011
+ const a = await extractSegment(segLabel(label, 1), h1, false);
5012
+ const b = await extractSegment(segLabel(label, 2), h2, false);
5013
+ if (a === "partial" || b === "partial") return "partial";
5014
+ if (!a && !b) return null;
5015
+ if (!a || !b) return "partial";
5016
+ return mergeOutcomes(a, b);
5017
+ };
5018
+ const merged = await extractSegment(lone.label, lone.event.summary, true);
5019
+ if (!merged || merged === "partial") {
5020
+ const corpus = deps.promptService.buildOpsExtractPrompt([lone], ontologyContext, ctx.guidance).groundingCorpus ?? null;
5021
+ return {
5022
+ batch: [lone],
5023
+ candidates: [],
5024
+ tasks: [],
5025
+ groundingCorpus: corpus,
5026
+ diagnostics: [skipDiag()],
5027
+ skippedEvents: 1,
5028
+ factItems: 0,
5029
+ taskItems: 0
5030
+ };
5031
+ }
5032
+ return { ...merged, batch: [lone] };
5033
+ }
5034
+ }
4785
5035
  async function runExtract(deps, ctx, batch) {
5036
+ const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
5037
+ const out = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch);
5038
+ if (out.skippedEvents > 0 && out.skippedEvents === out.batch.length) {
5039
+ const probe = deps.promptService.buildOpsExtractPrompt(
5040
+ [{ ...batch[0], event: { ...batch[0].event, summary: "x" } }],
5041
+ ontologyContext,
5042
+ ctx.guidance
5043
+ );
5044
+ try {
5045
+ await callLlm(deps.options, { operation: "librarian", entityId: ctx.entityId, trigger: ctx.trigger, meter: void 0 }, probe);
5046
+ } catch (e) {
5047
+ if (!isContextOverflowError(e)) throw e;
5048
+ throw new Error(`ops extract: all ${out.skippedEvents} selected events were skipped for context overflow and a minimal probe also overflowed (fixed prompt part exceeds the model window?)`);
5049
+ }
5050
+ }
5051
+ return out;
5052
+ }
5053
+ async function extractOnce(deps, ctx, ontologyContext, batch) {
4786
5054
  const { entityId, trigger } = ctx;
4787
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4788
5055
  const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
4789
5056
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
4790
5057
  const parsed = parseJsonResponse(text);
@@ -4826,13 +5093,17 @@ async function runExtract(deps, ctx, batch) {
4826
5093
  if (task) tasks.push(task);
4827
5094
  else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
4828
5095
  });
5096
+ const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
4829
5097
  return {
4830
5098
  batch,
4831
5099
  candidates,
4832
5100
  tasks,
4833
- ...parsed.ontology_updates ? { ontologyUpdates: parsed.ontology_updates } : {},
5101
+ ...ontologyUpdates ? { ontologyUpdates } : {},
4834
5102
  groundingCorpus: prompt.groundingCorpus ?? null,
4835
- diagnostics
5103
+ diagnostics,
5104
+ skippedEvents: 0,
5105
+ factItems: Array.isArray(parsed.facts) ? parsed.facts.length : 0,
5106
+ taskItems: Array.isArray(parsed.tasks) ? parsed.tasks.length : 0
4836
5107
  };
4837
5108
  }
4838
5109
 
@@ -4972,7 +5243,7 @@ function validateOp(raw, aliases) {
4972
5243
  }
4973
5244
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
4974
5245
  async function runResolve(deps, ctx, ambiguous) {
4975
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
5246
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
4976
5247
  if (ambiguous.length === 0) return out;
4977
5248
  const { entityId, trigger } = ctx;
4978
5249
  const outcome = await runBatched({
@@ -4994,6 +5265,9 @@ async function runResolve(deps, ctx, ambiguous) {
4994
5265
  if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
4995
5266
  return { batch, ops: parsed.ops };
4996
5267
  },
5268
+ onSkip: (g, err) => {
5269
+ if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
5270
+ },
4997
5271
  maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
4998
5272
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
4999
5273
  });
@@ -5232,6 +5506,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5232
5506
  }
5233
5507
  diagnostics.push(gateDiagnostic);
5234
5508
  const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
5509
+ for (const itemIndex of res.overflowSkipped) {
5510
+ diagnostics.push({
5511
+ entityId,
5512
+ operation: "librarian",
5513
+ trigger,
5514
+ code: "context_overflow_skipped",
5515
+ detail: { itemIndex }
5516
+ // (index into the merged extract batch)
5517
+ });
5518
+ }
5235
5519
  if (res.budgetStop) {
5236
5520
  diagnostics.discard();
5237
5521
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -5262,7 +5546,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5262
5546
  }
5263
5547
  }
5264
5548
  deps.searchService.evictCache(entityId);
5265
- const last = sel.batch[sel.batch.length - 1].event;
5549
+ const last = ex.batch[ex.batch.length - 1].event;
5266
5550
  return {
5267
5551
  processedThrough: { at: last.created_at, id: last.id },
5268
5552
  factsWritten: written.length + updatedIds.length
@@ -5973,7 +6257,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
5973
6257
  async runOntologyBackfill(entityId, options) {
5974
6258
  this.jobManager.acquireLock("ontologyBackfill", entityId);
5975
6259
  try {
5976
- return await this.doRunOntologyBackfill(entityId, options);
6260
+ return await this.doRunOntologyBackfill(entityId, {
6261
+ ...options,
6262
+ meter: new UsageMeter(options?.tokenBudget)
6263
+ });
5977
6264
  } finally {
5978
6265
  this.jobManager.releaseLock("ontologyBackfill", entityId);
5979
6266
  }
@@ -6562,7 +6849,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
6562
6849
  },
6563
6850
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6564
6851
  maxPromptChars: HEAL_MAX_PROMPT_CHARS,
6852
+ // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
6853
+ supportsEscalation: true,
6565
6854
  onSkip: (fact, err) => {
6855
+ if (isContextOverflowError(err)) {
6856
+ emitDiagnostic(this.options, {
6857
+ entityId,
6858
+ operation: "heal",
6859
+ trigger,
6860
+ code: "context_overflow_skipped",
6861
+ detail: { factId: fact.id }
6862
+ });
6863
+ return;
6864
+ }
6566
6865
  console.warn(
6567
6866
  `[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
6568
6867
  );
@@ -6734,20 +7033,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
6734
7033
  if (classifierMode === "auto" && typeof classify === "function") {
6735
7034
  const slugs = effectiveManifest.node_types.map((n) => n.type);
6736
7035
  if (slugs.length > 0 && slugs.length <= 255) {
6737
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
7036
+ return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
6738
7037
  }
6739
7038
  }
6740
7039
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
7040
+ const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
7041
+ const titleCatalog = buildTitleCatalogBlock(titleRows);
6741
7042
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
6742
7043
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
6743
7044
  facts.map(toPromptShape),
6744
7045
  options?.promptOverride,
6745
- ontologyContext
7046
+ ontologyContext,
7047
+ titleCatalog
6746
7048
  );
6747
7049
  const outcome = await runBatched({
6748
7050
  items: candidates,
6749
7051
  buildPrompt,
6750
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call" }, prompts),
7052
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
6751
7053
  parse: (responseText, batch) => {
6752
7054
  const parsed = parseJsonResponse(responseText);
6753
7055
  return {
@@ -6759,6 +7061,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
6759
7061
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6760
7062
  maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
6761
7063
  onSkip: (fact, err) => {
7064
+ if (isContextOverflowError(err)) {
7065
+ emitDiagnostic(this.options, {
7066
+ entityId,
7067
+ operation: "ontologyBackfill",
7068
+ trigger: "call",
7069
+ code: "context_overflow_skipped",
7070
+ detail: { factId: fact.id }
7071
+ });
7072
+ return;
7073
+ }
6762
7074
  console.warn(
6763
7075
  `[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
6764
7076
  );
@@ -6789,7 +7101,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
6789
7101
  edgesAdded,
6790
7102
  skipped: outcome.skipped.length,
6791
7103
  remaining: 0,
6792
- deferred: counts2.deferred
7104
+ deferred: counts2.deferred,
7105
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
6793
7106
  };
6794
7107
  }
6795
7108
  if (outcome.skipped.length > 0) {
@@ -6812,7 +7125,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
6812
7125
  edgesAdded,
6813
7126
  skipped: outcome.skipped.length,
6814
7127
  remaining: counts.eligible,
6815
- deferred: counts.deferred
7128
+ deferred: counts.deferred,
7129
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
6816
7130
  };
6817
7131
  }
6818
7132
  /**
@@ -6821,8 +7135,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6821
7135
  * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
6822
7136
  * No edges are proposed.
6823
7137
  */
6824
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
6825
- const provider = this.options.llmProvider;
7138
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
6826
7139
  const rawMin = this.options.config?.ontology?.classifyMinConfidence;
6827
7140
  const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
6828
7141
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
@@ -6832,12 +7145,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
6832
7145
  options: manifest.node_types.map((n) => n.type),
6833
7146
  instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
6834
7147
  };
7148
+ let stopped;
6835
7149
  const outcomes = await withConcurrency(
6836
7150
  candidates.map((fact) => async () => {
7151
+ if (stopped) return { fact, kind: "unattempted" };
6837
7152
  let response;
6838
7153
  try {
6839
- response = await provider.classify({ state: classifierStateForFact(fact), questions: { okf_type: question } });
6840
- } catch {
7154
+ response = await callClassify(
7155
+ this.options,
7156
+ { operation: "ontologyBackfill", entityId, trigger: "call", meter },
7157
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
7158
+ );
7159
+ } catch (err) {
7160
+ if (err instanceof WikiBudgetExhausted) {
7161
+ stopped ?? (stopped = err);
7162
+ return { fact, kind: "unattempted" };
7163
+ }
7164
+ if (isContextOverflowError(err)) return { fact, kind: "overflow_skip" };
6841
7165
  return { fact, kind: "threw" };
6842
7166
  }
6843
7167
  const checked = validateClassifierAnswer(response, "okf_type", question);
@@ -6848,8 +7172,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
6848
7172
  }),
6849
7173
  concurrency
6850
7174
  );
6851
- const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
6852
- const skipped = outcomes.length - attempted.length;
7175
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
7176
+ const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
7177
+ const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
6853
7178
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
6854
7179
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
6855
7180
  let typed = 0;
@@ -6878,22 +7203,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
6878
7203
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
6879
7204
  } else if (o.kind === "threw") {
6880
7205
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: "classify_threw" } });
7206
+ } else if (o.kind === "overflow_skip") {
7207
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id } });
6881
7208
  }
6882
7209
  }
6883
7210
  diagBuffer.flush(this.options);
6884
7211
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
6885
7212
  if (aborted) {
6886
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred };
7213
+ return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
6887
7214
  }
6888
7215
  this.searchService.evictCache(entityId);
6889
7216
  return {
6890
- scanned: candidates.length,
7217
+ scanned: candidates.length - unattemptedCount,
6891
7218
  typed,
6892
7219
  failedValidation,
6893
7220
  edgesAdded,
6894
7221
  skipped,
6895
7222
  remaining: counts.eligible,
6896
- deferred: counts.deferred
7223
+ deferred: counts.deferred,
7224
+ ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
6897
7225
  };
6898
7226
  }
6899
7227
  /**