@equationalapplications/core-llm-wiki 9.5.1 → 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.
@@ -2740,6 +2740,7 @@ var SEVERITY = {
2740
2740
  grounding_failed: "warn",
2741
2741
  classification_low_confidence: "info",
2742
2742
  classification_invalid: "warn",
2743
+ context_overflow_skipped: "warn",
2743
2744
  llm_usage: "info",
2744
2745
  librarian_gate: "info",
2745
2746
  librarian_op_rejected: "warn",
@@ -2785,6 +2786,7 @@ var MESSAGE = {
2785
2786
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
2786
2787
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
2787
2788
  classification_invalid: "A classifier answer was invalid and was not applied.",
2789
+ context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
2788
2790
  llm_usage: "An LLM call completed; token usage attached.",
2789
2791
  librarian_gate: "Librarian gate outcome counts for one pass.",
2790
2792
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
@@ -2972,6 +2974,31 @@ async function callLlm(options, ctx, prompts) {
2972
2974
  }
2973
2975
  return text;
2974
2976
  }
2977
+ async function callClassify(options, ctx, request) {
2978
+ const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
2979
+ if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
2980
+ throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
2981
+ }
2982
+ const provider = options.llmProvider;
2983
+ if (typeof provider.classify !== "function") {
2984
+ throw new TypeError("callClassify requires a provider with classify()");
2985
+ }
2986
+ const response = await provider.classify(request);
2987
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
2988
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
2989
+ const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
2990
+ ctx.meter?.record(record);
2991
+ if (options.config?.reportLlmUsage === true) {
2992
+ emitDiagnostic(options, {
2993
+ code: "llm_usage",
2994
+ operation: ctx.operation,
2995
+ trigger: ctx.trigger,
2996
+ entityId: ctx.entityId,
2997
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
2998
+ });
2999
+ }
3000
+ return response;
3001
+ }
2975
3002
 
2976
3003
  // src/services/IngestionService.ts
2977
3004
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
@@ -4597,6 +4624,29 @@ var TRUNCATION_PATTERNS = [
4597
4624
  /finish[_ ]?reason/i
4598
4625
  ];
4599
4626
  var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
4627
+ 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;
4628
+ var CONTEXT_OVERFLOW_PATTERNS = [
4629
+ /maximum context length/i,
4630
+ /context[_ ]?length[_ ]?exceeded/i,
4631
+ /prompt is too long/i,
4632
+ /input (token count|is too long)/i,
4633
+ /exceeds? the (available )?context( size)?/i,
4634
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
4635
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
4636
+ // classify as input overflow (it would split the batch and stamp a cooldown).
4637
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4638
+ /context limit/i,
4639
+ /too long for (the )?requested model/i,
4640
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4641
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
4642
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
4643
+ ];
4644
+ function isContextOverflowError(err) {
4645
+ const message = getErrorMessage(err);
4646
+ if (message === void 0) return false;
4647
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4648
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
4649
+ }
4600
4650
  function getErrorMessage(err) {
4601
4651
  try {
4602
4652
  return err instanceof Error ? err.message : String(err ?? "");
@@ -4607,12 +4657,14 @@ function getErrorMessage(err) {
4607
4657
  function isTruncationError(err) {
4608
4658
  const message = getErrorMessage(err);
4609
4659
  if (message === void 0) return false;
4660
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4610
4661
  if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4611
4662
  return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4612
4663
  }
4613
4664
  function isConfigError(err) {
4614
4665
  const message = getErrorMessage(err);
4615
4666
  if (message === void 0) return false;
4667
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4616
4668
  return EXCEEDS_LIMIT_PATTERN.test(message);
4617
4669
  }
4618
4670
  function initialBatchSize(maxOutputTokens) {
@@ -4626,7 +4678,7 @@ function initialBatchSize(maxOutputTokens) {
4626
4678
  }
4627
4679
  var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4628
4680
  async function runBatched(args) {
4629
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
4681
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4630
4682
  const results = [];
4631
4683
  const skipped = [];
4632
4684
  let batches = 0;
@@ -4660,17 +4712,17 @@ async function runBatched(args) {
4660
4712
  };
4661
4713
  const onFailure = async (batch, err, attemptLevel, fromCall) => {
4662
4714
  if (batch.length === 1) {
4663
- if (fromCall && isTruncationError(err) && attemptLevel < 3) {
4715
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4664
4716
  await attempt(batch, void 0, attemptLevel + 1);
4665
4717
  } else {
4666
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) ? "call_error" : "non_convergent";
4718
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
4667
4719
  skipped.push({ item: batch[0], reason });
4668
4720
  settled.add(batch[0]);
4669
4721
  onSkip?.(batch[0], err);
4670
4722
  }
4671
4723
  return;
4672
4724
  }
4673
- if (fromCall && !isTruncationError(err)) throw err;
4725
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4674
4726
  const mid = Math.ceil(batch.length / 2);
4675
4727
  if (mid < batchSize) batchSize = mid;
4676
4728
  let i = 0;
@@ -5915,6 +5967,8 @@ function parseValidFrom(v) {
5915
5967
  var OPS_MAX_EVENTS_PER_PASS = 50;
5916
5968
  var OPS_MAX_EXTRACT_CHARS = 24e3;
5917
5969
  var RESOLVE_RESERVE_FACTOR = 2;
5970
+ var MIN_SEGMENT_CHARS = 500;
5971
+ var MAX_SEGMENT_CALLS = 8;
5918
5972
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5919
5973
  async function selectBatch(deps, entityId, wm, meter, guidance) {
5920
5974
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
@@ -5938,9 +5992,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
5938
5992
  }
5939
5993
  return { batch };
5940
5994
  }
5995
+ function splitSummary(summary) {
5996
+ const mid = Math.floor(summary.length / 2);
5997
+ let cut = -1;
5998
+ for (let d = 0; d <= mid; d++) {
5999
+ if (/\s/.test(summary[mid - d] ?? "")) {
6000
+ cut = mid - d;
6001
+ break;
6002
+ }
6003
+ if (/\s/.test(summary[mid + d] ?? "")) {
6004
+ cut = mid + d;
6005
+ break;
6006
+ }
6007
+ }
6008
+ if (cut <= 0 || cut >= summary.length - 1) cut = mid;
6009
+ return [summary.slice(0, cut), summary.slice(cut)];
6010
+ }
6011
+ function dedupeByType(xs) {
6012
+ const seen = /* @__PURE__ */ new Set();
6013
+ return xs.filter((x) => seen.has(x.type) ? false : (seen.add(x.type), true));
6014
+ }
6015
+ function normalizeOntologyUpdates(raw) {
6016
+ if (typeof raw !== "object" || raw === null) return void 0;
6017
+ const r = raw;
6018
+ const pick = (v) => (Array.isArray(v) ? v : []).filter(
6019
+ (x) => !!x && typeof x === "object" && typeof x.type === "string" && x.type.length > 0
6020
+ );
6021
+ const node_types = pick(r.node_types);
6022
+ const edge_types = pick(r.edge_types);
6023
+ return {
6024
+ ...node_types.length ? { node_types } : {},
6025
+ ...edge_types.length ? { edge_types } : {}
6026
+ };
6027
+ }
6028
+ function mergeOutcomes(a, b) {
6029
+ if (a.groundingCorpus === null !== (b.groundingCorpus === null)) {
6030
+ throw new Error("ops extract: merge corpus invariant violated (only one half has a grounding corpus)");
6031
+ }
6032
+ const partOffset = a.groundingCorpus?.length ?? a.batch.length;
6033
+ const indexOffset = a.factItems;
6034
+ const candidates = [
6035
+ ...a.candidates,
6036
+ ...b.candidates.map((c) => ({
6037
+ ...c,
6038
+ index: c.index + indexOffset,
6039
+ sourcePartIndex: c.sourcePartIndex === null ? null : c.sourcePartIndex + partOffset
6040
+ }))
6041
+ ];
6042
+ let ontologyUpdates;
6043
+ if (a.ontologyUpdates || b.ontologyUpdates) {
6044
+ const nodes = dedupeByType([...a.ontologyUpdates?.node_types ?? [], ...b.ontologyUpdates?.node_types ?? []]);
6045
+ const edges = dedupeByType([...a.ontologyUpdates?.edge_types ?? [], ...b.ontologyUpdates?.edge_types ?? []]);
6046
+ ontologyUpdates = {
6047
+ ...nodes.length ? { node_types: nodes } : {},
6048
+ ...edges.length ? { edge_types: edges } : {}
6049
+ };
6050
+ }
6051
+ const shiftedDiags = b.diagnostics.map((d) => {
6052
+ const detail = d.detail;
6053
+ if (typeof detail?.itemIndex !== "number") return d;
6054
+ const off = d.code === "fact_rejected" ? a.factItems : d.code === "task_rejected" ? a.taskItems : 0;
6055
+ return off ? { ...d, detail: { ...detail, itemIndex: detail.itemIndex + off } } : d;
6056
+ });
6057
+ return {
6058
+ batch: [...a.batch, ...b.batch],
6059
+ candidates,
6060
+ tasks: [...a.tasks, ...b.tasks],
6061
+ ...ontologyUpdates ? { ontologyUpdates } : {},
6062
+ groundingCorpus: a.groundingCorpus || b.groundingCorpus ? [...a.groundingCorpus ?? [], ...b.groundingCorpus ?? []] : null,
6063
+ diagnostics: [...a.diagnostics, ...shiftedDiags],
6064
+ skippedEvents: a.skippedEvents + b.skippedEvents,
6065
+ factItems: a.factItems + b.factItems,
6066
+ taskItems: a.taskItems + b.taskItems
6067
+ };
6068
+ }
6069
+ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch) {
6070
+ try {
6071
+ return await extractOnce(deps, ctx, ontologyContext, batch);
6072
+ } catch (err) {
6073
+ if (!isContextOverflowError(err)) throw err;
6074
+ if (batch.length > 1) {
6075
+ const mid = Math.ceil(batch.length / 2);
6076
+ const a = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(0, mid));
6077
+ const b = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(mid));
6078
+ return mergeOutcomes(a, b);
6079
+ }
6080
+ const lone = batch[0];
6081
+ const skipDiag = () => ({
6082
+ entityId: ctx.entityId,
6083
+ operation: "librarian",
6084
+ trigger: ctx.trigger,
6085
+ code: "context_overflow_skipped",
6086
+ detail: { sourceRef: lone.event.id }
6087
+ });
6088
+ const segLabel = (label, n) => label.includes("#") ? `${label}.${n}` : `${label}#${n}`;
6089
+ let segCalls = 0;
6090
+ const extractSegment = async (label, text, alreadyOverflowed) => {
6091
+ if (!alreadyOverflowed) {
6092
+ if (segCalls >= MAX_SEGMENT_CALLS) return null;
6093
+ segCalls++;
6094
+ try {
6095
+ return await extractOnce(deps, ctx, ontologyContext, [{ label, at: lone.at, event: { ...lone.event, summary: text } }]);
6096
+ } catch (e) {
6097
+ if (!isContextOverflowError(e)) throw e;
6098
+ }
6099
+ }
6100
+ if (text.length < 2 * MIN_SEGMENT_CHARS) return null;
6101
+ const [h1, h2] = splitSummary(text);
6102
+ if (h1.length < MIN_SEGMENT_CHARS || h2.length < MIN_SEGMENT_CHARS) return null;
6103
+ const a = await extractSegment(segLabel(label, 1), h1, false);
6104
+ const b = await extractSegment(segLabel(label, 2), h2, false);
6105
+ if (a === "partial" || b === "partial") return "partial";
6106
+ if (!a && !b) return null;
6107
+ if (!a || !b) return "partial";
6108
+ return mergeOutcomes(a, b);
6109
+ };
6110
+ const merged = await extractSegment(lone.label, lone.event.summary, true);
6111
+ if (!merged || merged === "partial") {
6112
+ const corpus = deps.promptService.buildOpsExtractPrompt([lone], ontologyContext, ctx.guidance).groundingCorpus ?? null;
6113
+ return {
6114
+ batch: [lone],
6115
+ candidates: [],
6116
+ tasks: [],
6117
+ groundingCorpus: corpus,
6118
+ diagnostics: [skipDiag()],
6119
+ skippedEvents: 1,
6120
+ factItems: 0,
6121
+ taskItems: 0
6122
+ };
6123
+ }
6124
+ return { ...merged, batch: [lone] };
6125
+ }
6126
+ }
5941
6127
  async function runExtract(deps, ctx, batch) {
6128
+ const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
6129
+ const out = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch);
6130
+ if (out.skippedEvents > 0 && out.skippedEvents === out.batch.length) {
6131
+ const probe = deps.promptService.buildOpsExtractPrompt(
6132
+ [{ ...batch[0], event: { ...batch[0].event, summary: "x" } }],
6133
+ ontologyContext,
6134
+ ctx.guidance
6135
+ );
6136
+ try {
6137
+ await callLlm(deps.options, { operation: "librarian", entityId: ctx.entityId, trigger: ctx.trigger, meter: void 0 }, probe);
6138
+ } catch (e) {
6139
+ if (!isContextOverflowError(e)) throw e;
6140
+ 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?)`);
6141
+ }
6142
+ }
6143
+ return out;
6144
+ }
6145
+ async function extractOnce(deps, ctx, ontologyContext, batch) {
5942
6146
  const { entityId, trigger } = ctx;
5943
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5944
6147
  const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
5945
6148
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
5946
6149
  const parsed = parseJsonResponse(text);
@@ -5982,13 +6185,17 @@ async function runExtract(deps, ctx, batch) {
5982
6185
  if (task) tasks.push(task);
5983
6186
  else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
5984
6187
  });
6188
+ const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
5985
6189
  return {
5986
6190
  batch,
5987
6191
  candidates,
5988
6192
  tasks,
5989
- ...parsed.ontology_updates ? { ontologyUpdates: parsed.ontology_updates } : {},
6193
+ ...ontologyUpdates ? { ontologyUpdates } : {},
5990
6194
  groundingCorpus: prompt.groundingCorpus ?? null,
5991
- diagnostics
6195
+ diagnostics,
6196
+ skippedEvents: 0,
6197
+ factItems: Array.isArray(parsed.facts) ? parsed.facts.length : 0,
6198
+ taskItems: Array.isArray(parsed.tasks) ? parsed.tasks.length : 0
5992
6199
  };
5993
6200
  }
5994
6201
 
@@ -6115,7 +6322,7 @@ function validateOp(raw, aliases) {
6115
6322
  }
6116
6323
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
6117
6324
  async function runResolve(deps, ctx, ambiguous) {
6118
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
6325
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
6119
6326
  if (ambiguous.length === 0) return out;
6120
6327
  const { entityId, trigger } = ctx;
6121
6328
  const outcome = await runBatched({
@@ -6137,6 +6344,9 @@ async function runResolve(deps, ctx, ambiguous) {
6137
6344
  if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
6138
6345
  return { batch, ops: parsed.ops };
6139
6346
  },
6347
+ onSkip: (g, err) => {
6348
+ if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
6349
+ },
6140
6350
  maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
6141
6351
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
6142
6352
  });
@@ -6375,6 +6585,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6375
6585
  }
6376
6586
  diagnostics.push(gateDiagnostic);
6377
6587
  const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
6588
+ for (const itemIndex of res.overflowSkipped) {
6589
+ diagnostics.push({
6590
+ entityId,
6591
+ operation: "librarian",
6592
+ trigger,
6593
+ code: "context_overflow_skipped",
6594
+ detail: { itemIndex }
6595
+ // (index into the merged extract batch)
6596
+ });
6597
+ }
6378
6598
  if (res.budgetStop) {
6379
6599
  diagnostics.discard();
6380
6600
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -6405,7 +6625,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6405
6625
  }
6406
6626
  }
6407
6627
  deps.searchService.evictCache(entityId);
6408
- const last = sel.batch[sel.batch.length - 1].event;
6628
+ const last = ex.batch[ex.batch.length - 1].event;
6409
6629
  return {
6410
6630
  processedThrough: { at: last.created_at, id: last.id },
6411
6631
  factsWritten: written.length + updatedIds.length
@@ -7116,7 +7336,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7116
7336
  async runOntologyBackfill(entityId, options) {
7117
7337
  this.jobManager.acquireLock("ontologyBackfill", entityId);
7118
7338
  try {
7119
- return await this.doRunOntologyBackfill(entityId, options);
7339
+ return await this.doRunOntologyBackfill(entityId, {
7340
+ ...options,
7341
+ meter: new UsageMeter(options?.tokenBudget)
7342
+ });
7120
7343
  } finally {
7121
7344
  this.jobManager.releaseLock("ontologyBackfill", entityId);
7122
7345
  }
@@ -7705,7 +7928,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
7705
7928
  },
7706
7929
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
7707
7930
  maxPromptChars: HEAL_MAX_PROMPT_CHARS,
7931
+ // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
7932
+ supportsEscalation: true,
7708
7933
  onSkip: (fact, err) => {
7934
+ if (isContextOverflowError(err)) {
7935
+ emitDiagnostic(this.options, {
7936
+ entityId,
7937
+ operation: "heal",
7938
+ trigger,
7939
+ code: "context_overflow_skipped",
7940
+ detail: { factId: fact.id }
7941
+ });
7942
+ return;
7943
+ }
7709
7944
  console.warn(
7710
7945
  `[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
7711
7946
  );
@@ -7877,7 +8112,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7877
8112
  if (classifierMode === "auto" && typeof classify === "function") {
7878
8113
  const slugs = effectiveManifest.node_types.map((n) => n.type);
7879
8114
  if (slugs.length > 0 && slugs.length <= 255) {
7880
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
8115
+ return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
7881
8116
  }
7882
8117
  }
7883
8118
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
@@ -7893,7 +8128,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7893
8128
  const outcome = await runBatched({
7894
8129
  items: candidates,
7895
8130
  buildPrompt,
7896
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call" }, prompts),
8131
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
7897
8132
  parse: (responseText, batch) => {
7898
8133
  const parsed = parseJsonResponse(responseText);
7899
8134
  return {
@@ -7905,6 +8140,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
7905
8140
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
7906
8141
  maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
7907
8142
  onSkip: (fact, err) => {
8143
+ if (isContextOverflowError(err)) {
8144
+ emitDiagnostic(this.options, {
8145
+ entityId,
8146
+ operation: "ontologyBackfill",
8147
+ trigger: "call",
8148
+ code: "context_overflow_skipped",
8149
+ detail: { factId: fact.id }
8150
+ });
8151
+ return;
8152
+ }
7908
8153
  console.warn(
7909
8154
  `[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
7910
8155
  );
@@ -7935,7 +8180,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7935
8180
  edgesAdded,
7936
8181
  skipped: outcome.skipped.length,
7937
8182
  remaining: 0,
7938
- deferred: counts2.deferred
8183
+ deferred: counts2.deferred,
8184
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
7939
8185
  };
7940
8186
  }
7941
8187
  if (outcome.skipped.length > 0) {
@@ -7958,7 +8204,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7958
8204
  edgesAdded,
7959
8205
  skipped: outcome.skipped.length,
7960
8206
  remaining: counts.eligible,
7961
- deferred: counts.deferred
8207
+ deferred: counts.deferred,
8208
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
7962
8209
  };
7963
8210
  }
7964
8211
  /**
@@ -7967,8 +8214,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7967
8214
  * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
7968
8215
  * No edges are proposed.
7969
8216
  */
7970
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
7971
- const provider = this.options.llmProvider;
8217
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
7972
8218
  const rawMin = this.options.config?.ontology?.classifyMinConfidence;
7973
8219
  const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
7974
8220
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
@@ -7978,12 +8224,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
7978
8224
  options: manifest.node_types.map((n) => n.type),
7979
8225
  instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7980
8226
  };
8227
+ let stopped;
7981
8228
  const outcomes = await withConcurrency(
7982
8229
  candidates.map((fact) => async () => {
8230
+ if (stopped) return { fact, kind: "unattempted" };
7983
8231
  let response;
7984
8232
  try {
7985
- response = await provider.classify({ state: classifierStateForFact(fact), questions: { okf_type: question } });
7986
- } catch {
8233
+ response = await callClassify(
8234
+ this.options,
8235
+ { operation: "ontologyBackfill", entityId, trigger: "call", meter },
8236
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
8237
+ );
8238
+ } catch (err) {
8239
+ if (err instanceof WikiBudgetExhausted) {
8240
+ stopped ?? (stopped = err);
8241
+ return { fact, kind: "unattempted" };
8242
+ }
8243
+ if (isContextOverflowError(err)) return { fact, kind: "overflow_skip" };
7987
8244
  return { fact, kind: "threw" };
7988
8245
  }
7989
8246
  const checked = validateClassifierAnswer(response, "okf_type", question);
@@ -7994,8 +8251,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7994
8251
  }),
7995
8252
  concurrency
7996
8253
  );
7997
- const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
7998
- const skipped = outcomes.length - attempted.length;
8254
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
8255
+ const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
8256
+ const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
7999
8257
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
8000
8258
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
8001
8259
  let typed = 0;
@@ -8024,22 +8282,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
8024
8282
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
8025
8283
  } else if (o.kind === "threw") {
8026
8284
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: "classify_threw" } });
8285
+ } else if (o.kind === "overflow_skip") {
8286
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id } });
8027
8287
  }
8028
8288
  }
8029
8289
  diagBuffer.flush(this.options);
8030
8290
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8031
8291
  if (aborted) {
8032
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred };
8292
+ return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
8033
8293
  }
8034
8294
  this.searchService.evictCache(entityId);
8035
8295
  return {
8036
- scanned: candidates.length,
8296
+ scanned: candidates.length - unattemptedCount,
8037
8297
  typed,
8038
8298
  failedValidation,
8039
8299
  edgesAdded,
8040
8300
  skipped,
8041
8301
  remaining: counts.eligible,
8042
- deferred: counts.deferred
8302
+ deferred: counts.deferred,
8303
+ ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
8043
8304
  };
8044
8305
  }
8045
8306
  /**
@@ -10767,6 +11028,6 @@ var WriteService = class {
10767
11028
  }
10768
11029
  };
10769
11030
 
10770
- export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, 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_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, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
10771
- //# sourceMappingURL=chunk-Q6ZS2RKS.mjs.map
10772
- //# sourceMappingURL=chunk-Q6ZS2RKS.mjs.map
11031
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, 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_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, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11032
+ //# sourceMappingURL=chunk-7HJXGKQO.mjs.map
11033
+ //# sourceMappingURL=chunk-7HJXGKQO.mjs.map