@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 +1 -1
- package/dist/{chunk-ZVVZACYI.mjs → chunk-7HJXGKQO.mjs} +337 -29
- package/dist/chunk-7HJXGKQO.mjs.map +1 -0
- package/dist/index.d.mts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +335 -26
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-CTCRwhs0.d.mts → testing-BA6CedgZ.d.mts} +25 -3
- package/dist/{testing-CTCRwhs0.d.ts → testing-BA6CedgZ.d.ts} +25 -3
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +354 -26
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-ZVVZACYI.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -30,6 +30,7 @@ var SEVERITY = {
|
|
|
30
30
|
grounding_failed: "warn",
|
|
31
31
|
classification_low_confidence: "info",
|
|
32
32
|
classification_invalid: "warn",
|
|
33
|
+
context_overflow_skipped: "warn",
|
|
33
34
|
llm_usage: "info",
|
|
34
35
|
librarian_gate: "info",
|
|
35
36
|
librarian_op_rejected: "warn",
|
|
@@ -75,6 +76,7 @@ var MESSAGE = {
|
|
|
75
76
|
grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
|
|
76
77
|
classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
|
|
77
78
|
classification_invalid: "A classifier answer was invalid and was not applied.",
|
|
79
|
+
context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
|
|
78
80
|
llm_usage: "An LLM call completed; token usage attached.",
|
|
79
81
|
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
80
82
|
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
@@ -7457,6 +7459,47 @@ Return ONLY a valid JSON object matching this schema:
|
|
|
7457
7459
|
}
|
|
7458
7460
|
If no manifest type fits a fact, omit that fact from "classifications" entirely \u2014 do not guess.
|
|
7459
7461
|
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.`;
|
|
7462
|
+
var TITLE_CATALOG_MAX_ENTRIES = 200;
|
|
7463
|
+
function buildTitleCatalogBlock(rows) {
|
|
7464
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
7465
|
+
for (const r of rows) {
|
|
7466
|
+
if (typeof r.title !== "string" || r.title.length === 0) continue;
|
|
7467
|
+
if (typeof r.okf_type !== "string" || r.okf_type.length === 0) continue;
|
|
7468
|
+
byKey.set(normalizeTitleKey(r.title), { title: r.title, okf_type: r.okf_type });
|
|
7469
|
+
}
|
|
7470
|
+
const typed = [...byKey.values()].sort((a, b) => a.title < b.title ? -1 : a.title > b.title ? 1 : 0);
|
|
7471
|
+
const CHAR_BUDGET = 8e3;
|
|
7472
|
+
const listed = [];
|
|
7473
|
+
let used = 0;
|
|
7474
|
+
for (const r of typed) {
|
|
7475
|
+
const line = `- ${JSON.stringify(r.title)} (${r.okf_type})`;
|
|
7476
|
+
if (line.length + 1 > CHAR_BUDGET) continue;
|
|
7477
|
+
if (listed.length >= TITLE_CATALOG_MAX_ENTRIES) break;
|
|
7478
|
+
if (used + line.length + 1 > CHAR_BUDGET) continue;
|
|
7479
|
+
listed.push(r);
|
|
7480
|
+
used += line.length + 1;
|
|
7481
|
+
}
|
|
7482
|
+
const truncated = typed.length > listed.length;
|
|
7483
|
+
if (typed.length === 0) {
|
|
7484
|
+
return [
|
|
7485
|
+
"TITLE CATALOG: this memory contains no typed nodes yet.",
|
|
7486
|
+
'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
|
|
7487
|
+
].join("\n");
|
|
7488
|
+
}
|
|
7489
|
+
if (listed.length === 0) {
|
|
7490
|
+
return [
|
|
7491
|
+
"TITLE CATALOG: existing typed nodes exist in this memory, but none fit the catalog budget.",
|
|
7492
|
+
'A fact classified in this same response is a valid "target_title" once typed. Otherwise omit "edges" rather than invent a target_title.'
|
|
7493
|
+
].join("\n");
|
|
7494
|
+
}
|
|
7495
|
+
const catalog = listed.map((r) => `- ${JSON.stringify(r.title)} (${r.okf_type})`).join("\n");
|
|
7496
|
+
return [
|
|
7497
|
+
"TITLE CATALOG: existing typed nodes in this memory include:",
|
|
7498
|
+
catalog,
|
|
7499
|
+
...truncated ? ["(This list is truncated; more typed nodes exist than are shown here.)"] : [],
|
|
7500
|
+
'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.'
|
|
7501
|
+
].join("\n");
|
|
7502
|
+
}
|
|
7460
7503
|
var GROUNDING_SOURCE = {
|
|
7461
7504
|
ingest: { key: "facts", source: "the document chunk" },
|
|
7462
7505
|
librarian: { key: "facts", source: 'the "summary" text of the events' },
|
|
@@ -7733,7 +7776,7 @@ The following document anchors are provided for contradiction detection only. Do
|
|
|
7733
7776
|
...corpusField
|
|
7734
7777
|
};
|
|
7735
7778
|
}
|
|
7736
|
-
buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext) {
|
|
7779
|
+
buildOntologyBackfillPrompt(facts, runtimeOverride, ontologyContext, titleCatalog) {
|
|
7737
7780
|
const template = runtimeOverride ?? this.globalOverrides?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT;
|
|
7738
7781
|
const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
|
|
7739
7782
|
if (hasFacts || this.hasOntologyPlaceholders(template)) {
|
|
@@ -7743,8 +7786,11 @@ The following document anchors are provided for contradiction detection only. Do
|
|
|
7743
7786
|
${JSON.stringify(facts, null, 2)}`
|
|
7744
7787
|
};
|
|
7745
7788
|
}
|
|
7789
|
+
const effective = titleCatalog !== void 0 ? `${template}
|
|
7790
|
+
|
|
7791
|
+
${titleCatalog}` : template;
|
|
7746
7792
|
return {
|
|
7747
|
-
systemPrompt: this.appendOntology(
|
|
7793
|
+
systemPrompt: this.appendOntology(effective, ontologyContext),
|
|
7748
7794
|
userPrompt: `Facts:
|
|
7749
7795
|
${JSON.stringify(facts, null, 2)}`
|
|
7750
7796
|
};
|
|
@@ -7905,6 +7951,31 @@ async function callLlm(options, ctx, prompts) {
|
|
|
7905
7951
|
}
|
|
7906
7952
|
return text;
|
|
7907
7953
|
}
|
|
7954
|
+
async function callClassify(options, ctx, request) {
|
|
7955
|
+
const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
|
|
7956
|
+
if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
|
|
7957
|
+
throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
|
|
7958
|
+
}
|
|
7959
|
+
const provider = options.llmProvider;
|
|
7960
|
+
if (typeof provider.classify !== "function") {
|
|
7961
|
+
throw new TypeError("callClassify requires a provider with classify()");
|
|
7962
|
+
}
|
|
7963
|
+
const response = await provider.classify(request);
|
|
7964
|
+
const reported = validUsage(response?.usage) ? response.usage : void 0;
|
|
7965
|
+
const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
|
|
7966
|
+
const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
|
|
7967
|
+
ctx.meter?.record(record);
|
|
7968
|
+
if (options.config?.reportLlmUsage === true) {
|
|
7969
|
+
emitDiagnostic(options, {
|
|
7970
|
+
code: "llm_usage",
|
|
7971
|
+
operation: ctx.operation,
|
|
7972
|
+
trigger: ctx.trigger,
|
|
7973
|
+
entityId: ctx.entityId,
|
|
7974
|
+
detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
|
|
7975
|
+
});
|
|
7976
|
+
}
|
|
7977
|
+
return response;
|
|
7978
|
+
}
|
|
7908
7979
|
|
|
7909
7980
|
// src/services/IngestionService.ts
|
|
7910
7981
|
var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
|
|
@@ -9335,6 +9406,29 @@ var TRUNCATION_PATTERNS = [
|
|
|
9335
9406
|
/finish[_ ]?reason/i
|
|
9336
9407
|
];
|
|
9337
9408
|
var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
|
|
9409
|
+
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;
|
|
9410
|
+
var CONTEXT_OVERFLOW_PATTERNS = [
|
|
9411
|
+
/maximum context length/i,
|
|
9412
|
+
/context[_ ]?length[_ ]?exceeded/i,
|
|
9413
|
+
/prompt is too long/i,
|
|
9414
|
+
/input (token count|is too long)/i,
|
|
9415
|
+
/exceeds? the (available )?context( size)?/i,
|
|
9416
|
+
// Tail requires a context-window clause (context|maximum), NOT bare `token`:
|
|
9417
|
+
// a 429 body like "input exceeds the tokens-per-minute limit" must NOT
|
|
9418
|
+
// classify as input overflow (it would split the batch and stamp a cooldown).
|
|
9419
|
+
/(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
|
|
9420
|
+
/context limit/i,
|
|
9421
|
+
/too long for (the )?requested model/i,
|
|
9422
|
+
// vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
|
|
9423
|
+
// "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
|
|
9424
|
+
/max[_ ]?tokens?.{0,40}too large.{0,80}context/i
|
|
9425
|
+
];
|
|
9426
|
+
function isContextOverflowError(err) {
|
|
9427
|
+
const message = getErrorMessage(err);
|
|
9428
|
+
if (message === void 0) return false;
|
|
9429
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9430
|
+
return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
|
|
9431
|
+
}
|
|
9338
9432
|
function getErrorMessage(err) {
|
|
9339
9433
|
try {
|
|
9340
9434
|
return err instanceof Error ? err.message : String(err ?? "");
|
|
@@ -9345,12 +9439,14 @@ function getErrorMessage(err) {
|
|
|
9345
9439
|
function isTruncationError(err) {
|
|
9346
9440
|
const message = getErrorMessage(err);
|
|
9347
9441
|
if (message === void 0) return false;
|
|
9442
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9348
9443
|
if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
|
|
9349
9444
|
return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
|
|
9350
9445
|
}
|
|
9351
9446
|
function isConfigError(err) {
|
|
9352
9447
|
const message = getErrorMessage(err);
|
|
9353
9448
|
if (message === void 0) return false;
|
|
9449
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9354
9450
|
return EXCEEDS_LIMIT_PATTERN.test(message);
|
|
9355
9451
|
}
|
|
9356
9452
|
function initialBatchSize(maxOutputTokens) {
|
|
@@ -9364,7 +9460,7 @@ function initialBatchSize(maxOutputTokens) {
|
|
|
9364
9460
|
}
|
|
9365
9461
|
var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
|
|
9366
9462
|
async function runBatched(args) {
|
|
9367
|
-
const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip } = args;
|
|
9463
|
+
const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
|
|
9368
9464
|
const results = [];
|
|
9369
9465
|
const skipped = [];
|
|
9370
9466
|
let batches = 0;
|
|
@@ -9398,17 +9494,17 @@ async function runBatched(args) {
|
|
|
9398
9494
|
};
|
|
9399
9495
|
const onFailure = async (batch, err, attemptLevel, fromCall) => {
|
|
9400
9496
|
if (batch.length === 1) {
|
|
9401
|
-
if (fromCall && isTruncationError(err) && attemptLevel < 3) {
|
|
9497
|
+
if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
|
|
9402
9498
|
await attempt(batch, void 0, attemptLevel + 1);
|
|
9403
9499
|
} else {
|
|
9404
|
-
const reason = fromCall && !isTruncationError(err) && !isConfigError(err) ? "call_error" : "non_convergent";
|
|
9500
|
+
const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
|
|
9405
9501
|
skipped.push({ item: batch[0], reason });
|
|
9406
9502
|
settled.add(batch[0]);
|
|
9407
9503
|
onSkip?.(batch[0], err);
|
|
9408
9504
|
}
|
|
9409
9505
|
return;
|
|
9410
9506
|
}
|
|
9411
|
-
if (fromCall && !isTruncationError(err)) throw err;
|
|
9507
|
+
if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
|
|
9412
9508
|
const mid = Math.ceil(batch.length / 2);
|
|
9413
9509
|
if (mid < batchSize) batchSize = mid;
|
|
9414
9510
|
let i = 0;
|
|
@@ -9662,6 +9758,8 @@ function parseValidFrom(v) {
|
|
|
9662
9758
|
var OPS_MAX_EVENTS_PER_PASS = 50;
|
|
9663
9759
|
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
9664
9760
|
var RESOLVE_RESERVE_FACTOR = 2;
|
|
9761
|
+
var MIN_SEGMENT_CHARS = 500;
|
|
9762
|
+
var MAX_SEGMENT_CALLS = 8;
|
|
9665
9763
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
9666
9764
|
async function selectBatch(deps, entityId, wm, meter, guidance) {
|
|
9667
9765
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
@@ -9685,9 +9783,158 @@ async function selectBatch(deps, entityId, wm, meter, guidance) {
|
|
|
9685
9783
|
}
|
|
9686
9784
|
return { batch };
|
|
9687
9785
|
}
|
|
9786
|
+
function splitSummary(summary) {
|
|
9787
|
+
const mid = Math.floor(summary.length / 2);
|
|
9788
|
+
let cut = -1;
|
|
9789
|
+
for (let d = 0; d <= mid; d++) {
|
|
9790
|
+
if (/\s/.test(summary[mid - d] ?? "")) {
|
|
9791
|
+
cut = mid - d;
|
|
9792
|
+
break;
|
|
9793
|
+
}
|
|
9794
|
+
if (/\s/.test(summary[mid + d] ?? "")) {
|
|
9795
|
+
cut = mid + d;
|
|
9796
|
+
break;
|
|
9797
|
+
}
|
|
9798
|
+
}
|
|
9799
|
+
if (cut <= 0 || cut >= summary.length - 1) cut = mid;
|
|
9800
|
+
return [summary.slice(0, cut), summary.slice(cut)];
|
|
9801
|
+
}
|
|
9802
|
+
function dedupeByType(xs) {
|
|
9803
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9804
|
+
return xs.filter((x) => seen.has(x.type) ? false : (seen.add(x.type), true));
|
|
9805
|
+
}
|
|
9806
|
+
function normalizeOntologyUpdates(raw) {
|
|
9807
|
+
if (typeof raw !== "object" || raw === null) return void 0;
|
|
9808
|
+
const r = raw;
|
|
9809
|
+
const pick = (v) => (Array.isArray(v) ? v : []).filter(
|
|
9810
|
+
(x) => !!x && typeof x === "object" && typeof x.type === "string" && x.type.length > 0
|
|
9811
|
+
);
|
|
9812
|
+
const node_types = pick(r.node_types);
|
|
9813
|
+
const edge_types = pick(r.edge_types);
|
|
9814
|
+
return {
|
|
9815
|
+
...node_types.length ? { node_types } : {},
|
|
9816
|
+
...edge_types.length ? { edge_types } : {}
|
|
9817
|
+
};
|
|
9818
|
+
}
|
|
9819
|
+
function mergeOutcomes(a, b) {
|
|
9820
|
+
if (a.groundingCorpus === null !== (b.groundingCorpus === null)) {
|
|
9821
|
+
throw new Error("ops extract: merge corpus invariant violated (only one half has a grounding corpus)");
|
|
9822
|
+
}
|
|
9823
|
+
const partOffset = a.groundingCorpus?.length ?? a.batch.length;
|
|
9824
|
+
const indexOffset = a.factItems;
|
|
9825
|
+
const candidates = [
|
|
9826
|
+
...a.candidates,
|
|
9827
|
+
...b.candidates.map((c) => ({
|
|
9828
|
+
...c,
|
|
9829
|
+
index: c.index + indexOffset,
|
|
9830
|
+
sourcePartIndex: c.sourcePartIndex === null ? null : c.sourcePartIndex + partOffset
|
|
9831
|
+
}))
|
|
9832
|
+
];
|
|
9833
|
+
let ontologyUpdates;
|
|
9834
|
+
if (a.ontologyUpdates || b.ontologyUpdates) {
|
|
9835
|
+
const nodes = dedupeByType([...a.ontologyUpdates?.node_types ?? [], ...b.ontologyUpdates?.node_types ?? []]);
|
|
9836
|
+
const edges = dedupeByType([...a.ontologyUpdates?.edge_types ?? [], ...b.ontologyUpdates?.edge_types ?? []]);
|
|
9837
|
+
ontologyUpdates = {
|
|
9838
|
+
...nodes.length ? { node_types: nodes } : {},
|
|
9839
|
+
...edges.length ? { edge_types: edges } : {}
|
|
9840
|
+
};
|
|
9841
|
+
}
|
|
9842
|
+
const shiftedDiags = b.diagnostics.map((d) => {
|
|
9843
|
+
const detail = d.detail;
|
|
9844
|
+
if (typeof detail?.itemIndex !== "number") return d;
|
|
9845
|
+
const off = d.code === "fact_rejected" ? a.factItems : d.code === "task_rejected" ? a.taskItems : 0;
|
|
9846
|
+
return off ? { ...d, detail: { ...detail, itemIndex: detail.itemIndex + off } } : d;
|
|
9847
|
+
});
|
|
9848
|
+
return {
|
|
9849
|
+
batch: [...a.batch, ...b.batch],
|
|
9850
|
+
candidates,
|
|
9851
|
+
tasks: [...a.tasks, ...b.tasks],
|
|
9852
|
+
...ontologyUpdates ? { ontologyUpdates } : {},
|
|
9853
|
+
groundingCorpus: a.groundingCorpus || b.groundingCorpus ? [...a.groundingCorpus ?? [], ...b.groundingCorpus ?? []] : null,
|
|
9854
|
+
diagnostics: [...a.diagnostics, ...shiftedDiags],
|
|
9855
|
+
skippedEvents: a.skippedEvents + b.skippedEvents,
|
|
9856
|
+
factItems: a.factItems + b.factItems,
|
|
9857
|
+
taskItems: a.taskItems + b.taskItems
|
|
9858
|
+
};
|
|
9859
|
+
}
|
|
9860
|
+
async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch) {
|
|
9861
|
+
try {
|
|
9862
|
+
return await extractOnce(deps, ctx, ontologyContext, batch);
|
|
9863
|
+
} catch (err) {
|
|
9864
|
+
if (!isContextOverflowError(err)) throw err;
|
|
9865
|
+
if (batch.length > 1) {
|
|
9866
|
+
const mid = Math.ceil(batch.length / 2);
|
|
9867
|
+
const a = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(0, mid));
|
|
9868
|
+
const b = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch.slice(mid));
|
|
9869
|
+
return mergeOutcomes(a, b);
|
|
9870
|
+
}
|
|
9871
|
+
const lone = batch[0];
|
|
9872
|
+
const skipDiag = () => ({
|
|
9873
|
+
entityId: ctx.entityId,
|
|
9874
|
+
operation: "librarian",
|
|
9875
|
+
trigger: ctx.trigger,
|
|
9876
|
+
code: "context_overflow_skipped",
|
|
9877
|
+
detail: { sourceRef: lone.event.id }
|
|
9878
|
+
});
|
|
9879
|
+
const segLabel = (label, n) => label.includes("#") ? `${label}.${n}` : `${label}#${n}`;
|
|
9880
|
+
let segCalls = 0;
|
|
9881
|
+
const extractSegment = async (label, text, alreadyOverflowed) => {
|
|
9882
|
+
if (!alreadyOverflowed) {
|
|
9883
|
+
if (segCalls >= MAX_SEGMENT_CALLS) return null;
|
|
9884
|
+
segCalls++;
|
|
9885
|
+
try {
|
|
9886
|
+
return await extractOnce(deps, ctx, ontologyContext, [{ label, at: lone.at, event: { ...lone.event, summary: text } }]);
|
|
9887
|
+
} catch (e) {
|
|
9888
|
+
if (!isContextOverflowError(e)) throw e;
|
|
9889
|
+
}
|
|
9890
|
+
}
|
|
9891
|
+
if (text.length < 2 * MIN_SEGMENT_CHARS) return null;
|
|
9892
|
+
const [h1, h2] = splitSummary(text);
|
|
9893
|
+
if (h1.length < MIN_SEGMENT_CHARS || h2.length < MIN_SEGMENT_CHARS) return null;
|
|
9894
|
+
const a = await extractSegment(segLabel(label, 1), h1, false);
|
|
9895
|
+
const b = await extractSegment(segLabel(label, 2), h2, false);
|
|
9896
|
+
if (a === "partial" || b === "partial") return "partial";
|
|
9897
|
+
if (!a && !b) return null;
|
|
9898
|
+
if (!a || !b) return "partial";
|
|
9899
|
+
return mergeOutcomes(a, b);
|
|
9900
|
+
};
|
|
9901
|
+
const merged = await extractSegment(lone.label, lone.event.summary, true);
|
|
9902
|
+
if (!merged || merged === "partial") {
|
|
9903
|
+
const corpus = deps.promptService.buildOpsExtractPrompt([lone], ontologyContext, ctx.guidance).groundingCorpus ?? null;
|
|
9904
|
+
return {
|
|
9905
|
+
batch: [lone],
|
|
9906
|
+
candidates: [],
|
|
9907
|
+
tasks: [],
|
|
9908
|
+
groundingCorpus: corpus,
|
|
9909
|
+
diagnostics: [skipDiag()],
|
|
9910
|
+
skippedEvents: 1,
|
|
9911
|
+
factItems: 0,
|
|
9912
|
+
taskItems: 0
|
|
9913
|
+
};
|
|
9914
|
+
}
|
|
9915
|
+
return { ...merged, batch: [lone] };
|
|
9916
|
+
}
|
|
9917
|
+
}
|
|
9688
9918
|
async function runExtract(deps, ctx, batch) {
|
|
9919
|
+
const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
|
|
9920
|
+
const out = await extractWithOverflowRetry(deps, ctx, ontologyContext, batch);
|
|
9921
|
+
if (out.skippedEvents > 0 && out.skippedEvents === out.batch.length) {
|
|
9922
|
+
const probe = deps.promptService.buildOpsExtractPrompt(
|
|
9923
|
+
[{ ...batch[0], event: { ...batch[0].event, summary: "x" } }],
|
|
9924
|
+
ontologyContext,
|
|
9925
|
+
ctx.guidance
|
|
9926
|
+
);
|
|
9927
|
+
try {
|
|
9928
|
+
await callLlm(deps.options, { operation: "librarian", entityId: ctx.entityId, trigger: ctx.trigger, meter: void 0 }, probe);
|
|
9929
|
+
} catch (e) {
|
|
9930
|
+
if (!isContextOverflowError(e)) throw e;
|
|
9931
|
+
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?)`);
|
|
9932
|
+
}
|
|
9933
|
+
}
|
|
9934
|
+
return out;
|
|
9935
|
+
}
|
|
9936
|
+
async function extractOnce(deps, ctx, ontologyContext, batch) {
|
|
9689
9937
|
const { entityId, trigger } = ctx;
|
|
9690
|
-
const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
9691
9938
|
const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
|
|
9692
9939
|
const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
|
|
9693
9940
|
const parsed = parseJsonResponse(text);
|
|
@@ -9729,13 +9976,17 @@ async function runExtract(deps, ctx, batch) {
|
|
|
9729
9976
|
if (task) tasks.push(task);
|
|
9730
9977
|
else diagnostics.push({ ...base, code: "task_rejected", detail: { itemIndex: index, reason: taskRejectionReason(raw) } });
|
|
9731
9978
|
});
|
|
9979
|
+
const ontologyUpdates = normalizeOntologyUpdates(parsed.ontology_updates);
|
|
9732
9980
|
return {
|
|
9733
9981
|
batch,
|
|
9734
9982
|
candidates,
|
|
9735
9983
|
tasks,
|
|
9736
|
-
...
|
|
9984
|
+
...ontologyUpdates ? { ontologyUpdates } : {},
|
|
9737
9985
|
groundingCorpus: prompt.groundingCorpus ?? null,
|
|
9738
|
-
diagnostics
|
|
9986
|
+
diagnostics,
|
|
9987
|
+
skippedEvents: 0,
|
|
9988
|
+
factItems: Array.isArray(parsed.facts) ? parsed.facts.length : 0,
|
|
9989
|
+
taskItems: Array.isArray(parsed.tasks) ? parsed.tasks.length : 0
|
|
9739
9990
|
};
|
|
9740
9991
|
}
|
|
9741
9992
|
|
|
@@ -9862,7 +10113,7 @@ function validateOp(raw, aliases) {
|
|
|
9862
10113
|
}
|
|
9863
10114
|
var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
|
|
9864
10115
|
async function runResolve(deps, ctx, ambiguous) {
|
|
9865
|
-
const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
|
|
10116
|
+
const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
|
|
9866
10117
|
if (ambiguous.length === 0) return out;
|
|
9867
10118
|
const { entityId, trigger } = ctx;
|
|
9868
10119
|
const outcome = await runBatched({
|
|
@@ -9884,6 +10135,9 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
9884
10135
|
if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
|
|
9885
10136
|
return { batch, ops: parsed.ops };
|
|
9886
10137
|
},
|
|
10138
|
+
onSkip: (g, err) => {
|
|
10139
|
+
if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
|
|
10140
|
+
},
|
|
9887
10141
|
maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
9888
10142
|
maxOutputTokens: deps.options.llmProvider.maxOutputTokens
|
|
9889
10143
|
});
|
|
@@ -10122,6 +10376,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10122
10376
|
}
|
|
10123
10377
|
diagnostics.push(gateDiagnostic);
|
|
10124
10378
|
const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
|
|
10379
|
+
for (const itemIndex of res.overflowSkipped) {
|
|
10380
|
+
diagnostics.push({
|
|
10381
|
+
entityId,
|
|
10382
|
+
operation: "librarian",
|
|
10383
|
+
trigger,
|
|
10384
|
+
code: "context_overflow_skipped",
|
|
10385
|
+
detail: { itemIndex }
|
|
10386
|
+
// (index into the merged extract batch)
|
|
10387
|
+
});
|
|
10388
|
+
}
|
|
10125
10389
|
if (res.budgetStop) {
|
|
10126
10390
|
diagnostics.discard();
|
|
10127
10391
|
return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
|
|
@@ -10152,7 +10416,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10152
10416
|
}
|
|
10153
10417
|
}
|
|
10154
10418
|
deps.searchService.evictCache(entityId);
|
|
10155
|
-
const last =
|
|
10419
|
+
const last = ex.batch[ex.batch.length - 1].event;
|
|
10156
10420
|
return {
|
|
10157
10421
|
processedThrough: { at: last.created_at, id: last.id },
|
|
10158
10422
|
factsWritten: written.length + updatedIds.length
|
|
@@ -10863,7 +11127,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
10863
11127
|
async runOntologyBackfill(entityId, options) {
|
|
10864
11128
|
this.jobManager.acquireLock("ontologyBackfill", entityId);
|
|
10865
11129
|
try {
|
|
10866
|
-
return await this.doRunOntologyBackfill(entityId,
|
|
11130
|
+
return await this.doRunOntologyBackfill(entityId, {
|
|
11131
|
+
...options,
|
|
11132
|
+
meter: new UsageMeter(options?.tokenBudget)
|
|
11133
|
+
});
|
|
10867
11134
|
} finally {
|
|
10868
11135
|
this.jobManager.releaseLock("ontologyBackfill", entityId);
|
|
10869
11136
|
}
|
|
@@ -11452,7 +11719,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11452
11719
|
},
|
|
11453
11720
|
maxOutputTokens: this.options.llmProvider.maxOutputTokens,
|
|
11454
11721
|
maxPromptChars: HEAL_MAX_PROMPT_CHARS,
|
|
11722
|
+
// heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
|
|
11723
|
+
supportsEscalation: true,
|
|
11455
11724
|
onSkip: (fact, err) => {
|
|
11725
|
+
if (isContextOverflowError(err)) {
|
|
11726
|
+
emitDiagnostic(this.options, {
|
|
11727
|
+
entityId,
|
|
11728
|
+
operation: "heal",
|
|
11729
|
+
trigger,
|
|
11730
|
+
code: "context_overflow_skipped",
|
|
11731
|
+
detail: { factId: fact.id }
|
|
11732
|
+
});
|
|
11733
|
+
return;
|
|
11734
|
+
}
|
|
11456
11735
|
console.warn(
|
|
11457
11736
|
`[WikiMemory] heal skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
|
|
11458
11737
|
);
|
|
@@ -11624,20 +11903,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11624
11903
|
if (classifierMode === "auto" && typeof classify === "function") {
|
|
11625
11904
|
const slugs = effectiveManifest.node_types.map((n) => n.type);
|
|
11626
11905
|
if (slugs.length > 0 && slugs.length <= 255) {
|
|
11627
|
-
return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff);
|
|
11906
|
+
return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
|
|
11628
11907
|
}
|
|
11629
11908
|
}
|
|
11630
11909
|
const ontologyContext = await ontologyService.buildPromptContext(entityId);
|
|
11910
|
+
const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
|
|
11911
|
+
const titleCatalog = buildTitleCatalogBlock(titleRows);
|
|
11631
11912
|
const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
|
|
11632
11913
|
const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
|
|
11633
11914
|
facts.map(toPromptShape),
|
|
11634
11915
|
options?.promptOverride,
|
|
11635
|
-
ontologyContext
|
|
11916
|
+
ontologyContext,
|
|
11917
|
+
titleCatalog
|
|
11636
11918
|
);
|
|
11637
11919
|
const outcome = await runBatched({
|
|
11638
11920
|
items: candidates,
|
|
11639
11921
|
buildPrompt,
|
|
11640
|
-
call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call" }, prompts),
|
|
11922
|
+
call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
|
|
11641
11923
|
parse: (responseText, batch) => {
|
|
11642
11924
|
const parsed = parseJsonResponse(responseText);
|
|
11643
11925
|
return {
|
|
@@ -11649,6 +11931,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11649
11931
|
maxOutputTokens: this.options.llmProvider.maxOutputTokens,
|
|
11650
11932
|
maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
|
|
11651
11933
|
onSkip: (fact, err) => {
|
|
11934
|
+
if (isContextOverflowError(err)) {
|
|
11935
|
+
emitDiagnostic(this.options, {
|
|
11936
|
+
entityId,
|
|
11937
|
+
operation: "ontologyBackfill",
|
|
11938
|
+
trigger: "call",
|
|
11939
|
+
code: "context_overflow_skipped",
|
|
11940
|
+
detail: { factId: fact.id }
|
|
11941
|
+
});
|
|
11942
|
+
return;
|
|
11943
|
+
}
|
|
11652
11944
|
console.warn(
|
|
11653
11945
|
`[WikiMemory] ontology backfill skipped ${entityId}/${fact.id}: response could not be bounded: ${formatSkipError(err)}`
|
|
11654
11946
|
);
|
|
@@ -11679,7 +11971,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11679
11971
|
edgesAdded,
|
|
11680
11972
|
skipped: outcome.skipped.length,
|
|
11681
11973
|
remaining: 0,
|
|
11682
|
-
deferred: counts2.deferred
|
|
11974
|
+
deferred: counts2.deferred,
|
|
11975
|
+
...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
|
|
11683
11976
|
};
|
|
11684
11977
|
}
|
|
11685
11978
|
if (outcome.skipped.length > 0) {
|
|
@@ -11702,7 +11995,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11702
11995
|
edgesAdded,
|
|
11703
11996
|
skipped: outcome.skipped.length,
|
|
11704
11997
|
remaining: counts.eligible,
|
|
11705
|
-
deferred: counts.deferred
|
|
11998
|
+
deferred: counts.deferred,
|
|
11999
|
+
...outcome.budgetStop ? { budgetStop: outcome.budgetStop } : {}
|
|
11706
12000
|
};
|
|
11707
12001
|
}
|
|
11708
12002
|
/**
|
|
@@ -11711,8 +12005,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11711
12005
|
* through `_applyOntologyBackfillBatch` exactly like LLM classifications.
|
|
11712
12006
|
* No edges are proposed.
|
|
11713
12007
|
*/
|
|
11714
|
-
async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff) {
|
|
11715
|
-
const provider = this.options.llmProvider;
|
|
12008
|
+
async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
|
|
11716
12009
|
const rawMin = this.options.config?.ontology?.classifyMinConfidence;
|
|
11717
12010
|
const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
|
|
11718
12011
|
const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
|
|
@@ -11722,12 +12015,23 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11722
12015
|
options: manifest.node_types.map((n) => n.type),
|
|
11723
12016
|
instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
|
|
11724
12017
|
};
|
|
12018
|
+
let stopped;
|
|
11725
12019
|
const outcomes = await withConcurrency(
|
|
11726
12020
|
candidates.map((fact) => async () => {
|
|
12021
|
+
if (stopped) return { fact, kind: "unattempted" };
|
|
11727
12022
|
let response;
|
|
11728
12023
|
try {
|
|
11729
|
-
response = await
|
|
11730
|
-
|
|
12024
|
+
response = await callClassify(
|
|
12025
|
+
this.options,
|
|
12026
|
+
{ operation: "ontologyBackfill", entityId, trigger: "call", meter },
|
|
12027
|
+
{ state: classifierStateForFact(fact), questions: { okf_type: question } }
|
|
12028
|
+
);
|
|
12029
|
+
} catch (err) {
|
|
12030
|
+
if (err instanceof WikiBudgetExhausted) {
|
|
12031
|
+
stopped ?? (stopped = err);
|
|
12032
|
+
return { fact, kind: "unattempted" };
|
|
12033
|
+
}
|
|
12034
|
+
if (isContextOverflowError(err)) return { fact, kind: "overflow_skip" };
|
|
11731
12035
|
return { fact, kind: "threw" };
|
|
11732
12036
|
}
|
|
11733
12037
|
const checked = validateClassifierAnswer(response, "okf_type", question);
|
|
@@ -11738,8 +12042,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11738
12042
|
}),
|
|
11739
12043
|
concurrency
|
|
11740
12044
|
);
|
|
11741
|
-
const attempted = outcomes.filter((o) => o.kind !== "threw").map((o) => o.fact);
|
|
11742
|
-
const
|
|
12045
|
+
const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
|
|
12046
|
+
const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
|
|
12047
|
+
const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
|
|
11743
12048
|
const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
|
|
11744
12049
|
const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
|
|
11745
12050
|
let typed = 0;
|
|
@@ -11768,22 +12073,25 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
11768
12073
|
diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
|
|
11769
12074
|
} else if (o.kind === "threw") {
|
|
11770
12075
|
diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: "classify_threw" } });
|
|
12076
|
+
} else if (o.kind === "overflow_skip") {
|
|
12077
|
+
diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id } });
|
|
11771
12078
|
}
|
|
11772
12079
|
}
|
|
11773
12080
|
diagBuffer.flush(this.options);
|
|
11774
12081
|
const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
|
|
11775
12082
|
if (aborted) {
|
|
11776
|
-
return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred };
|
|
12083
|
+
return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
|
|
11777
12084
|
}
|
|
11778
12085
|
this.searchService.evictCache(entityId);
|
|
11779
12086
|
return {
|
|
11780
|
-
scanned: candidates.length,
|
|
12087
|
+
scanned: candidates.length - unattemptedCount,
|
|
11781
12088
|
typed,
|
|
11782
12089
|
failedValidation,
|
|
11783
12090
|
edgesAdded,
|
|
11784
12091
|
skipped,
|
|
11785
12092
|
remaining: counts.eligible,
|
|
11786
|
-
deferred: counts.deferred
|
|
12093
|
+
deferred: counts.deferred,
|
|
12094
|
+
...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
|
|
11787
12095
|
};
|
|
11788
12096
|
}
|
|
11789
12097
|
/**
|
|
@@ -17188,6 +17496,7 @@ exports.mapLibrarianOptionsToReadOptions = mapLibrarianOptionsToReadOptions;
|
|
|
17188
17496
|
exports.parseEmbedding = parseEmbedding;
|
|
17189
17497
|
exports.parseOkfBundle = parseOkfBundle;
|
|
17190
17498
|
exports.safeSlice = safeSlice;
|
|
17499
|
+
exports.validUsage = validUsage;
|
|
17191
17500
|
exports.validateLibrarianPromptTemplate = validateLibrarianPromptTemplate;
|
|
17192
17501
|
exports.validateManifest = validateManifest;
|
|
17193
17502
|
//# sourceMappingURL=index.js.map
|