@equationalapplications/core-llm-wiki 9.5.1 → 9.5.3

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.",
@@ -2890,6 +2892,26 @@ var DEFAULT_CHUNK_OVERLAP = 400;
2890
2892
  function estimateTokens(text) {
2891
2893
  return Math.ceil(text.length / 4);
2892
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
+ };
2893
2915
  var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
2894
2916
  constructor(requiredEstimate, remaining) {
2895
2917
  super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
@@ -2938,6 +2960,31 @@ async function callLlm(options, ctx, prompts) {
2938
2960
  }
2939
2961
  return text;
2940
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
+ }
2941
2988
 
2942
2989
  // src/services/IngestionService.ts
2943
2990
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
@@ -4005,6 +4052,29 @@ var TRUNCATION_PATTERNS = [
4005
4052
  /finish[_ ]?reason/i
4006
4053
  ];
4007
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
+ }
4008
4078
  function getErrorMessage(err) {
4009
4079
  try {
4010
4080
  return err instanceof Error ? err.message : String(err ?? "");
@@ -4015,12 +4085,14 @@ function getErrorMessage(err) {
4015
4085
  function isTruncationError(err) {
4016
4086
  const message = getErrorMessage(err);
4017
4087
  if (message === void 0) return false;
4088
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4018
4089
  if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4019
4090
  return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4020
4091
  }
4021
4092
  function isConfigError(err) {
4022
4093
  const message = getErrorMessage(err);
4023
4094
  if (message === void 0) return false;
4095
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4024
4096
  return EXCEEDS_LIMIT_PATTERN.test(message);
4025
4097
  }
4026
4098
  function initialBatchSize(maxOutputTokens) {
@@ -4034,7 +4106,7 @@ function initialBatchSize(maxOutputTokens) {
4034
4106
  }
4035
4107
  var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4036
4108
  async function runBatched(args) {
4037
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
4109
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4038
4110
  const results = [];
4039
4111
  const skipped = [];
4040
4112
  let batches = 0;
@@ -4068,17 +4140,17 @@ async function runBatched(args) {
4068
4140
  };
4069
4141
  const onFailure = async (batch, err, attemptLevel, fromCall) => {
4070
4142
  if (batch.length === 1) {
4071
- if (fromCall && isTruncationError(err) && attemptLevel < 3) {
4143
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4072
4144
  await attempt(batch, void 0, attemptLevel + 1);
4073
4145
  } else {
4074
- 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";
4075
4147
  skipped.push({ item: batch[0], reason });
4076
4148
  settled.add(batch[0]);
4077
4149
  onSkip?.(batch[0], err);
4078
4150
  }
4079
4151
  return;
4080
4152
  }
4081
- if (fromCall && !isTruncationError(err)) throw err;
4153
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4082
4154
  const mid = Math.ceil(batch.length / 2);
4083
4155
  if (mid < batchSize) batchSize = mid;
4084
4156
  let i = 0;
@@ -4803,6 +4875,8 @@ function parseValidFrom(v) {
4803
4875
  var OPS_MAX_EVENTS_PER_PASS = 50;
4804
4876
  var OPS_MAX_EXTRACT_CHARS = 24e3;
4805
4877
  var RESOLVE_RESERVE_FACTOR = 2;
4878
+ var MIN_SEGMENT_CHARS = 500;
4879
+ var MAX_SEGMENT_CALLS = 8;
4806
4880
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
4807
4881
  async function selectBatch(deps, entityId, wm, meter, guidance) {
4808
4882
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
@@ -4826,9 +4900,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
4826
4900
  }
4827
4901
  return { batch };
4828
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, probe) {
4978
+ try {
4979
+ return await extractOnce(deps, ctx, ontologyContext, batch);
4980
+ } catch (err) {
4981
+ if (!isContextOverflowError(err)) throw err;
4982
+ if (!probe.checked) {
4983
+ probe.checked = true;
4984
+ const probePrompt = deps.promptService.buildOpsExtractPrompt(
4985
+ [{ ...batch[0], event: { ...batch[0].event, summary: "x" } }],
4986
+ ontologyContext,
4987
+ ctx.guidance
4988
+ );
4989
+ try {
4990
+ await callLlm(deps.options, { operation: "librarian", entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter }, probePrompt);
4991
+ } catch (e) {
4992
+ if (!isContextOverflowError(e)) throw e;
4993
+ throw new Error("ops extract: minimal-prompt probe also overflowed (fixed prompt part exceeds the model window?)");
4994
+ }
4995
+ }
4996
+ if (batch.length > 1) {
4997
+ const mid = Math.ceil(batch.length / 2);
4998
+ const a = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(0, mid), probe);
4999
+ const b = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(mid), probe);
5000
+ return mergeOutcomes(a, b);
5001
+ }
5002
+ const lone = batch[0];
5003
+ const skipDiag = () => ({
5004
+ entityId: ctx.entityId,
5005
+ operation: "librarian",
5006
+ trigger: ctx.trigger,
5007
+ code: "context_overflow_skipped",
5008
+ detail: { sourceRef: lone.event.id }
5009
+ });
5010
+ const segLabel = (label, n) => label.includes("#") ? `${label}.${n}` : `${label}#${n}`;
5011
+ let segCalls = 0;
5012
+ const extractSegment = async (label, text, alreadyOverflowed) => {
5013
+ if (!alreadyOverflowed) {
5014
+ if (segCalls >= MAX_SEGMENT_CALLS) return null;
5015
+ segCalls++;
5016
+ try {
5017
+ return await extractOnce(deps, ctx, ontologyContext, [{ label, at: lone.at, event: { ...lone.event, summary: text } }]);
5018
+ } catch (e) {
5019
+ if (!isContextOverflowError(e)) throw e;
5020
+ }
5021
+ }
5022
+ if (text.length < 2 * MIN_SEGMENT_CHARS) return null;
5023
+ const [h1, h2] = splitSummary(text);
5024
+ if (h1.length < MIN_SEGMENT_CHARS || h2.length < MIN_SEGMENT_CHARS) return null;
5025
+ const a = await extractSegment(segLabel(label, 1), h1, false);
5026
+ const b = await extractSegment(segLabel(label, 2), h2, false);
5027
+ if (a === "partial" || b === "partial") return "partial";
5028
+ if (!a && !b) return null;
5029
+ if (!a || !b) return "partial";
5030
+ return mergeOutcomes(a, b);
5031
+ };
5032
+ const merged = await extractSegment(lone.label, lone.event.summary, true);
5033
+ if (!merged || merged === "partial") {
5034
+ const corpus = deps.promptService.buildOpsExtractPrompt([lone], ontologyContext, ctx.guidance).groundingCorpus ?? null;
5035
+ return {
5036
+ batch: [lone],
5037
+ candidates: [],
5038
+ tasks: [],
5039
+ groundingCorpus: corpus,
5040
+ diagnostics: [skipDiag()],
5041
+ skippedEvents: 1,
5042
+ factItems: 0,
5043
+ taskItems: 0
5044
+ };
5045
+ }
5046
+ return { ...merged, batch: [lone] };
5047
+ }
5048
+ }
4829
5049
  async function runExtract(deps, ctx, batch) {
5050
+ const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
5051
+ return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
5052
+ }
5053
+ async function extractOnce(deps, ctx, ontologyContext, batch) {
4830
5054
  const { entityId, trigger } = ctx;
4831
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4832
5055
  const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
4833
5056
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
4834
5057
  const parsed = parseJsonResponse(text);
@@ -4870,13 +5093,17 @@ async function runExtract(deps, ctx, batch) {
4870
5093
  if (task) tasks.push(task);
4871
5094
  else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
4872
5095
  });
5096
+ const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
4873
5097
  return {
4874
5098
  batch,
4875
5099
  candidates,
4876
5100
  tasks,
4877
- ...parsed.ontology_updates ? { ontologyUpdates: parsed.ontology_updates } : {},
5101
+ ...ontologyUpdates ? { ontologyUpdates } : {},
4878
5102
  groundingCorpus: prompt.groundingCorpus ?? null,
4879
- 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
4880
5107
  };
4881
5108
  }
4882
5109
 
@@ -5016,7 +5243,7 @@ function validateOp(raw, aliases) {
5016
5243
  }
5017
5244
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5018
5245
  async function runResolve(deps, ctx, ambiguous) {
5019
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
5246
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
5020
5247
  if (ambiguous.length === 0) return out;
5021
5248
  const { entityId, trigger } = ctx;
5022
5249
  const outcome = await runBatched({
@@ -5038,6 +5265,9 @@ async function runResolve(deps, ctx, ambiguous) {
5038
5265
  if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
5039
5266
  return { batch, ops: parsed.ops };
5040
5267
  },
5268
+ onSkip: (g, err) => {
5269
+ if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
5270
+ },
5041
5271
  maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
5042
5272
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
5043
5273
  });
@@ -5276,6 +5506,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5276
5506
  }
5277
5507
  diagnostics.push(gateDiagnostic);
5278
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
+ }
5279
5519
  if (res.budgetStop) {
5280
5520
  diagnostics.discard();
5281
5521
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -5306,7 +5546,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5306
5546
  }
5307
5547
  }
5308
5548
  deps.searchService.evictCache(entityId);
5309
- const last = sel.batch[sel.batch.length - 1].event;
5549
+ const last = ex.batch[ex.batch.length - 1].event;
5310
5550
  return {
5311
5551
  processedThrough: { at: last.created_at, id: last.id },
5312
5552
  factsWritten: written.length + updatedIds.length
@@ -6017,7 +6257,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
6017
6257
  async runOntologyBackfill(entityId, options) {
6018
6258
  this.jobManager.acquireLock("ontologyBackfill", entityId);
6019
6259
  try {
6020
- return await this.doRunOntologyBackfill(entityId, options);
6260
+ return await this.doRunOntologyBackfill(entityId, {
6261
+ ...options,
6262
+ meter: new UsageMeter(options?.tokenBudget)
6263
+ });
6021
6264
  } finally {
6022
6265
  this.jobManager.releaseLock("ontologyBackfill", entityId);
6023
6266
  }
@@ -6606,7 +6849,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
6606
6849
  },
6607
6850
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6608
6851
  maxPromptChars: HEAL_MAX_PROMPT_CHARS,
6852
+ // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
6853
+ supportsEscalation: true,
6609
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
+ }
6610
6865
  console.warn(
6611
6866
  `[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
6612
6867
  );
@@ -6778,7 +7033,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6778
7033
  if (classifierMode === "auto" && typeof classify === "function") {
6779
7034
  const slugs = effectiveManifest.node_types.map((n) => n.type);
6780
7035
  if (slugs.length > 0 && slugs.length <= 255) {
6781
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
7036
+ return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
6782
7037
  }
6783
7038
  }
6784
7039
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
@@ -6794,7 +7049,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6794
7049
  const outcome = await runBatched({
6795
7050
  items: candidates,
6796
7051
  buildPrompt,
6797
- 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),
6798
7053
  parse: (responseText, batch) => {
6799
7054
  const parsed = parseJsonResponse(responseText);
6800
7055
  return {
@@ -6806,6 +7061,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
6806
7061
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6807
7062
  maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
6808
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
+ }
6809
7074
  console.warn(
6810
7075
  `[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
6811
7076
  );
@@ -6836,7 +7101,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
6836
7101
  edgesAdded,
6837
7102
  skipped: outcome.skipped.length,
6838
7103
  remaining: 0,
6839
- deferred: counts2.deferred
7104
+ deferred: counts2.deferred,
7105
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
6840
7106
  };
6841
7107
  }
6842
7108
  if (outcome.skipped.length > 0) {
@@ -6859,7 +7125,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
6859
7125
  edgesAdded,
6860
7126
  skipped: outcome.skipped.length,
6861
7127
  remaining: counts.eligible,
6862
- deferred: counts.deferred
7128
+ deferred: counts.deferred,
7129
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
6863
7130
  };
6864
7131
  }
6865
7132
  /**
@@ -6868,8 +7135,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6868
7135
  * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
6869
7136
  * No edges are proposed.
6870
7137
  */
6871
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
6872
- const provider = this.options.llmProvider;
7138
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
6873
7139
  const rawMin = this.options.config?.ontology?.classifyMinConfidence;
6874
7140
  const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
6875
7141
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
@@ -6879,12 +7145,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
6879
7145
  options: manifest.node_types.map((n) => n.type),
6880
7146
  instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
6881
7147
  };
7148
+ let stopped;
6882
7149
  const outcomes = await withConcurrency(
6883
7150
  candidates.map((fact) => async () => {
7151
+ if (stopped) return { fact, kind: "unattempted" };
6884
7152
  let response;
6885
7153
  try {
6886
- response = await provider.classify({ state: classifierStateForFact(fact), questions: { okf_type: question } });
6887
- } 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" };
6888
7165
  return { fact, kind: "threw" };
6889
7166
  }
6890
7167
  const checked = validateClassifierAnswer(response, "okf_type", question);
@@ -6895,8 +7172,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
6895
7172
  }),
6896
7173
  concurrency
6897
7174
  );
6898
- const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
6899
- 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;
6900
7178
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
6901
7179
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
6902
7180
  let typed = 0;
@@ -6925,22 +7203,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
6925
7203
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
6926
7204
  } else if (o.kind === "threw") {
6927
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 } });
6928
7208
  }
6929
7209
  }
6930
7210
  diagBuffer.flush(this.options);
6931
7211
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
6932
7212
  if (aborted) {
6933
- 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 } } : {} };
6934
7214
  }
6935
7215
  this.searchService.evictCache(entityId);
6936
7216
  return {
6937
- scanned: candidates.length,
7217
+ scanned: candidates.length - unattemptedCount,
6938
7218
  typed,
6939
7219
  failedValidation,
6940
7220
  edgesAdded,
6941
7221
  skipped,
6942
7222
  remaining: counts.eligible,
6943
- deferred: counts.deferred
7223
+ deferred: counts.deferred,
7224
+ ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
6944
7225
  };
6945
7226
  }
6946
7227
  /**