@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/README.md CHANGED
@@ -60,7 +60,7 @@ The [Node.js quickstart](https://equationalapplications.github.io/expo-llm-wiki/
60
60
  | [@equationalapplications/core-okf](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/okf/README.md) | Zero-dependency Open Knowledge Format (OKF) v0.1 + v0.2 primitives — parse and produce interoperable knowledge bundles. |
61
61
  | [@equationalapplications/schema-org-llm-wiki](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/schema-org/README.md) | Curated schema.org warm-agent ontology manifest |
62
62
  | [@equationalapplications/schema-software-org](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/schema-software-org/README.md) | Software-organization executive ontology manifest — 21 node types, 42 edges, warm-agent superset, data-only |
63
- | [@equationalapplications/mcp-server](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/mcp-server/README.md) | MCP server exposing SynapseTree memory tools to coding agents |
63
+ | [@equationalapplications/mcp-server](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/mcp-server/README.md) | MCP server exposing hosted cloud memory tools to coding agents |
64
64
 
65
65
  ## License
66
66
 
@@ -2251,6 +2251,47 @@ Return ONLY a valid JSON object matching this schema:
2251
2251
  }
2252
2252
  If no manifest type fits a fact, omit that fact from "classifications" entirely \u2014 do not guess.
2253
2253
  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.`;
2254
+ var TITLE_CATALOG_MAX_ENTRIES = 200;
2255
+ function buildTitleCatalogBlock(rows) {
2256
+ const byKey = /* @__PURE__ */ new Map();
2257
+ for (const r of rows) {
2258
+ if (typeof r.title !== "string" || r.title.length === 0) continue;
2259
+ if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
2260
+ byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
2261
+ }
2262
+ const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
2263
+ const CHAR_BUDGET = 8e3;
2264
+ const listed = [];
2265
+ let used = 0;
2266
+ for (const r of typed) {
2267
+ const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
2268
+ if (line.length + 1 > CHAR_BUDGET) continue;
2269
+ if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
2270
+ if (used + line.length + 1 > CHAR_BUDGET) continue;
2271
+ listed.push(r);
2272
+ used += line.length + 1;
2273
+ }
2274
+ const truncated = typed.length > listed.length;
2275
+ if (typed.length === 0) {
2276
+ return [
2277
+ "TITLE CATALOG: this memory contains no typed nodes yet.",
2278
+ 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2279
+ ].join("\n");
2280
+ }
2281
+ if (listed.length === 0) {
2282
+ return [
2283
+ "TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
2284
+ 'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
2285
+ ].join("\n");
2286
+ }
2287
+ const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
2288
+ return [
2289
+ "TITLE CATALOG: existing typed nodes in this memory include:",
2290
+ catalog,
2291
+ ...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
2292
+ '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.'
2293
+ ].join("\n");
2294
+ }
2254
2295
  var GROUNDING_SOURCE = {
2255
2296
  ingest: { key: "facts", source: "the document chunk" },
2256
2297
  librarian: { key: "facts", source: 'the "summary" text of the events' },
@@ -2581,7 +2622,7 @@ The following document anchors are provided for contradiction detection only. Do
2581
2622
  ...corpusField
2582
2623
  };
2583
2624
  }
2584
- buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext) {
2625
+ buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
2585
2626
  const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
2586
2627
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2587
2628
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
@@ -2591,8 +2632,11 @@ The following document anchors are provided for contradiction detection only. Do
2591
2632
  ${JSON.stringify(facts, null, 2)}`
2592
2633
  };
2593
2634
  }
2635
+ const effective = titleCatalog !== void 0 ? `${template}
2636
+
2637
+ ${titleCatalog}` : template;
2594
2638
  return {
2595
- systemPrompt: this.appendOntology(template, ontologyContext),
2639
+ systemPrompt: this.appendOntology(effective, ontologyContext),
2596
2640
  userPrompt: `Facts:
2597
2641
  ${JSON.stringify(facts, null, 2)}`
2598
2642
  };
@@ -2696,6 +2740,7 @@ var SEVERITY = {
2696
2740
  grounding_failed: "warn",
2697
2741
  classification_low_confidence: "info",
2698
2742
  classification_invalid: "warn",
2743
+ context_overflow_skipped: "warn",
2699
2744
  llm_usage: "info",
2700
2745
  librarian_gate: "info",
2701
2746
  librarian_op_rejected: "warn",
@@ -2741,6 +2786,7 @@ var MESSAGE = {
2741
2786
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
2742
2787
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
2743
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.",
2744
2790
  llm_usage: "An LLM call completed; token usage attached.",
2745
2791
  librarian_gate: "Librarian gate outcome counts for one pass.",
2746
2792
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
@@ -2928,6 +2974,31 @@ async function callLlm(options, ctx, prompts) {
2928
2974
  }
2929
2975
  return text;
2930
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
+ }
2931
3002
 
2932
3003
  // src/services/IngestionService.ts
2933
3004
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
@@ -4553,6 +4624,29 @@ var TRUNCATION_PATTERNS = [
4553
4624
  /finish[_ ]?reason/i
4554
4625
  ];
4555
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
+ }
4556
4650
  function getErrorMessage(err) {
4557
4651
  try {
4558
4652
  return err instanceof Error ? err.message : String(err ?? "");
@@ -4563,12 +4657,14 @@ function getErrorMessage(err) {
4563
4657
  function isTruncationError(err) {
4564
4658
  const message = getErrorMessage(err);
4565
4659
  if (message === void 0) return false;
4660
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4566
4661
  if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4567
4662
  return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4568
4663
  }
4569
4664
  function isConfigError(err) {
4570
4665
  const message = getErrorMessage(err);
4571
4666
  if (message === void 0) return false;
4667
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
4572
4668
  return EXCEEDS_LIMIT_PATTERN.test(message);
4573
4669
  }
4574
4670
  function initialBatchSize(maxOutputTokens) {
@@ -4582,7 +4678,7 @@ function initialBatchSize(maxOutputTokens) {
4582
4678
  }
4583
4679
  var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4584
4680
  async function runBatched(args) {
4585
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
4681
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4586
4682
  const results = [];
4587
4683
  const skipped = [];
4588
4684
  let batches = 0;
@@ -4616,17 +4712,17 @@ async function runBatched(args) {
4616
4712
  };
4617
4713
  const onFailure = async (batch, err, attemptLevel, fromCall) => {
4618
4714
  if (batch.length === 1) {
4619
- if (fromCall && isTruncationError(err) && attemptLevel < 3) {
4715
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4620
4716
  await attempt(batch, void 0, attemptLevel + 1);
4621
4717
  } else {
4622
- 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";
4623
4719
  skipped.push({ item: batch[0], reason });
4624
4720
  settled.add(batch[0]);
4625
4721
  onSkip?.(batch[0], err);
4626
4722
  }
4627
4723
  return;
4628
4724
  }
4629
- if (fromCall && !isTruncationError(err)) throw err;
4725
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4630
4726
  const mid = Math.ceil(batch.length / 2);
4631
4727
  if (mid < batchSize) batchSize = mid;
4632
4728
  let i = 0;
@@ -5871,6 +5967,8 @@ function parseValidFrom(v) {
5871
5967
  var OPS_MAX_EVENTS_PER_PASS = 50;
5872
5968
  var OPS_MAX_EXTRACT_CHARS = 24e3;
5873
5969
  var RESOLVE_RESERVE_FACTOR = 2;
5970
+ var MIN_SEGMENT_CHARS = 500;
5971
+ var MAX_SEGMENT_CALLS = 8;
5874
5972
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5875
5973
  async function selectBatch(deps, entityId, wm, meter, guidance) {
5876
5974
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
@@ -5894,9 +5992,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
5894
5992
  }
5895
5993
  return { batch };
5896
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
+ }
5897
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) {
5898
6146
  const { entityId, trigger } = ctx;
5899
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5900
6147
  const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
5901
6148
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
5902
6149
  const parsed = parseJsonResponse(text);
@@ -5938,13 +6185,17 @@ async function runExtract(deps, ctx, batch) {
5938
6185
  if (task) tasks.push(task);
5939
6186
  else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
5940
6187
  });
6188
+ const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
5941
6189
  return {
5942
6190
  batch,
5943
6191
  candidates,
5944
6192
  tasks,
5945
- ...parsed.ontology_updates ? { ontologyUpdates: parsed.ontology_updates } : {},
6193
+ ...ontologyUpdates ? { ontologyUpdates } : {},
5946
6194
  groundingCorpus: prompt.groundingCorpus ?? null,
5947
- 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
5948
6199
  };
5949
6200
  }
5950
6201
 
@@ -6071,7 +6322,7 @@ function validateOp(raw, aliases) {
6071
6322
  }
6072
6323
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
6073
6324
  async function runResolve(deps, ctx, ambiguous) {
6074
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
6325
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
6075
6326
  if (ambiguous.length === 0) return out;
6076
6327
  const { entityId, trigger } = ctx;
6077
6328
  const outcome = await runBatched({
@@ -6093,6 +6344,9 @@ async function runResolve(deps, ctx, ambiguous) {
6093
6344
  if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
6094
6345
  return { batch, ops: parsed.ops };
6095
6346
  },
6347
+ onSkip: (g, err) => {
6348
+ if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
6349
+ },
6096
6350
  maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
6097
6351
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
6098
6352
  });
@@ -6331,6 +6585,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6331
6585
  }
6332
6586
  diagnostics.push(gateDiagnostic);
6333
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
+ }
6334
6598
  if (res.budgetStop) {
6335
6599
  diagnostics.discard();
6336
6600
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -6361,7 +6625,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6361
6625
  }
6362
6626
  }
6363
6627
  deps.searchService.evictCache(entityId);
6364
- const last = sel.batch[sel.batch.length - 1].event;
6628
+ const last = ex.batch[ex.batch.length - 1].event;
6365
6629
  return {
6366
6630
  processedThrough: { at: last.created_at, id: last.id },
6367
6631
  factsWritten: written.length + updatedIds.length
@@ -7072,7 +7336,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7072
7336
  async runOntologyBackfill(entityId, options) {
7073
7337
  this.jobManager.acquireLock("ontologyBackfill", entityId);
7074
7338
  try {
7075
- return await this.doRunOntologyBackfill(entityId, options);
7339
+ return await this.doRunOntologyBackfill(entityId, {
7340
+ ...options,
7341
+ meter: new UsageMeter(options?.tokenBudget)
7342
+ });
7076
7343
  } finally {
7077
7344
  this.jobManager.releaseLock("ontologyBackfill", entityId);
7078
7345
  }
@@ -7661,7 +7928,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
7661
7928
  },
7662
7929
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
7663
7930
  maxPromptChars: HEAL_MAX_PROMPT_CHARS,
7931
+ // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
7932
+ supportsEscalation: true,
7664
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
+ }
7665
7944
  console.warn(
7666
7945
  `[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
7667
7946
  );
@@ -7833,20 +8112,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
7833
8112
  if (classifierMode === "auto" && typeof classify === "function") {
7834
8113
  const slugs = effectiveManifest.node_types.map((n) => n.type);
7835
8114
  if (slugs.length > 0 && slugs.length <= 255) {
7836
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
8115
+ return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
7837
8116
  }
7838
8117
  }
7839
8118
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
8119
+ const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
8120
+ const titleCatalog = buildTitleCatalogBlock(titleRows);
7840
8121
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
7841
8122
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
7842
8123
  facts.map(toPromptShape),
7843
8124
  options?.promptOverride,
7844
- ontologyContext
8125
+ ontologyContext,
8126
+ titleCatalog
7845
8127
  );
7846
8128
  const outcome = await runBatched({
7847
8129
  items: candidates,
7848
8130
  buildPrompt,
7849
- 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),
7850
8132
  parse: (responseText, batch) => {
7851
8133
  const parsed = parseJsonResponse(responseText);
7852
8134
  return {
@@ -7858,6 +8140,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
7858
8140
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
7859
8141
  maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
7860
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
+ }
7861
8153
  console.warn(
7862
8154
  `[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
7863
8155
  );
@@ -7888,7 +8180,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7888
8180
  edgesAdded,
7889
8181
  skipped: outcome.skipped.length,
7890
8182
  remaining: 0,
7891
- deferred: counts2.deferred
8183
+ deferred: counts2.deferred,
8184
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
7892
8185
  };
7893
8186
  }
7894
8187
  if (outcome.skipped.length > 0) {
@@ -7911,7 +8204,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7911
8204
  edgesAdded,
7912
8205
  skipped: outcome.skipped.length,
7913
8206
  remaining: counts.eligible,
7914
- deferred: counts.deferred
8207
+ deferred: counts.deferred,
8208
+ ...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
7915
8209
  };
7916
8210
  }
7917
8211
  /**
@@ -7920,8 +8214,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7920
8214
  * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
7921
8215
  * No edges are proposed.
7922
8216
  */
7923
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
7924
- const provider = this.options.llmProvider;
8217
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
7925
8218
  const rawMin = this.options.config?.ontology?.classifyMinConfidence;
7926
8219
  const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
7927
8220
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
@@ -7931,12 +8224,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
7931
8224
  options: manifest.node_types.map((n) => n.type),
7932
8225
  instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7933
8226
  };
8227
+ let stopped;
7934
8228
  const outcomes = await withConcurrency(
7935
8229
  candidates.map((fact) => async () => {
8230
+ if (stopped) return { fact, kind: "unattempted" };
7936
8231
  let response;
7937
8232
  try {
7938
- response = await provider.classify({ state: classifierStateForFact(fact), questions: { okf_type: question } });
7939
- } 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" };
7940
8244
  return { fact, kind: "threw" };
7941
8245
  }
7942
8246
  const checked = validateClassifierAnswer(response, "okf_type", question);
@@ -7947,8 +8251,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7947
8251
  }),
7948
8252
  concurrency
7949
8253
  );
7950
- const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
7951
- 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;
7952
8257
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
7953
8258
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
7954
8259
  let typed = 0;
@@ -7977,22 +8282,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
7977
8282
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
7978
8283
  } else if (o.kind === "threw") {
7979
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 } });
7980
8287
  }
7981
8288
  }
7982
8289
  diagBuffer.flush(this.options);
7983
8290
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7984
8291
  if (aborted) {
7985
- 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 } } : {} };
7986
8293
  }
7987
8294
  this.searchService.evictCache(entityId);
7988
8295
  return {
7989
- scanned: candidates.length,
8296
+ scanned: candidates.length - unattemptedCount,
7990
8297
  typed,
7991
8298
  failedValidation,
7992
8299
  edgesAdded,
7993
8300
  skipped,
7994
8301
  remaining: counts.eligible,
7995
- deferred: counts.deferred
8302
+ deferred: counts.deferred,
8303
+ ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
7996
8304
  };
7997
8305
  }
7998
8306
  /**
@@ -10720,6 +11028,6 @@ var WriteService = class {
10720
11028
  }
10721
11029
  };
10722
11030
 
10723
- 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 };
10724
- //# sourceMappingURL=chunk-ZVVZACYI.mjs.map
10725
- //# sourceMappingURL=chunk-ZVVZACYI.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