@equationalapplications/core-llm-wiki 9.14.1 → 9.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,6 +15,299 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
15
15
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
16
16
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
17
17
 
18
+ // src/utils/chunkingDefaults.ts
19
+ var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
20
+ var DEFAULT_CHUNK_OVERLAP = 400;
21
+
22
+ // src/utils/contextCaps.ts
23
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
24
+ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
25
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
26
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
27
+
28
+ // src/config/context.ts
29
+ var DEFAULT_CHARS_PER_TOKEN = 4;
30
+ var DEFAULT_SAFETY_FRACTION = 0.9;
31
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
32
+ var OP_FLOOR = {
33
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
34
+ heal: HEAL_MAX_PROMPT_CHARS,
35
+ extract: OPS_MAX_EXTRACT_CHARS,
36
+ backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
37
+ };
38
+ function bad(key, value, why) {
39
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
40
+ }
41
+ function resolveContextBudget(config) {
42
+ const context = config?.context;
43
+ if (!context || context.budget === void 0) {
44
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
45
+ }
46
+ if (context.budget !== "legacy" && context.budget !== "declared") {
47
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
48
+ }
49
+ if (context.budget === "legacy") {
50
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
51
+ }
52
+ const window = context.contextWindowTokens;
53
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
54
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
55
+ }
56
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
57
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
58
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
59
+ }
60
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
61
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
62
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
63
+ }
64
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
65
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
66
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
67
+ }
68
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
69
+ }
70
+ function declaredPromptCap(budget, op) {
71
+ const derived = Math.floor(
72
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
73
+ );
74
+ return Math.max(OP_FLOOR[op], derived);
75
+ }
76
+ function resolveMaxPromptChars(budget, op) {
77
+ if (budget.mode !== "declared") {
78
+ return OP_FLOOR[op];
79
+ }
80
+ if (op === "extract") {
81
+ const resolveDerived = declaredPromptCap(budget, "resolve");
82
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
83
+ return Math.max(OP_FLOOR.extract, extractDerived);
84
+ }
85
+ return declaredPromptCap(budget, op);
86
+ }
87
+ function resolveDefaultChunkLength(budget) {
88
+ return DEFAULT_MAX_CHUNK_LENGTH;
89
+ }
90
+
91
+ // src/utils/engineDefaults.ts
92
+ var DEFAULT_LIBRARIAN_STRATEGY = "ops";
93
+ var DEFAULT_MAINTENANCE_MODE = "deferred";
94
+ function resolveLibrarianStrategy(config) {
95
+ return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
96
+ }
97
+ function resolveMaintenanceMode(config) {
98
+ return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
99
+ }
100
+ function resolveContextBudgetOrThrow(config) {
101
+ return resolveContextBudget(config);
102
+ }
103
+ function changedDefaultWarnings(config) {
104
+ const warnings = [];
105
+ const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
106
+ if (hasThreshold && config?.maintenance === void 0) {
107
+ warnings.push(
108
+ "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
109
+ );
110
+ }
111
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
112
+ warnings.push(
113
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
114
+ );
115
+ }
116
+ if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
117
+ warnings.push(
118
+ "[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
119
+ );
120
+ }
121
+ return warnings;
122
+ }
123
+ var warnedDefaults = /* @__PURE__ */ new Set();
124
+ function warnChangedDefaultsOnce(config) {
125
+ for (const message of changedDefaultWarnings(config)) {
126
+ if (warnedDefaults.has(message)) continue;
127
+ warnedDefaults.add(message);
128
+ console.warn(message);
129
+ }
130
+ }
131
+ function warnOnce(message) {
132
+ if (warnedDefaults.has(message)) return;
133
+ warnedDefaults.add(message);
134
+ console.warn(message);
135
+ }
136
+ function formatConfigValue(value) {
137
+ try {
138
+ const json = JSON.stringify(value);
139
+ return json ?? String(value);
140
+ } catch {
141
+ return `[unserializable: ${typeof value}]`;
142
+ }
143
+ }
144
+ var isTypingMode = (v) => v === "auto" || v === "llm";
145
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
146
+ function resolveSystemOneTyping(config, classifierCallOption) {
147
+ const systemOne = config?.systemOne;
148
+ const legacy = config?.ontology?.backfillClassifier;
149
+ const systemOneValid = isTypingMode(systemOne?.typing);
150
+ const legacyValid = isTypingMode(legacy);
151
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
152
+ warnOnce(
153
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
154
+ );
155
+ }
156
+ if (legacy !== void 0 && !legacyValid) {
157
+ warnOnce(
158
+ `[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
159
+ );
160
+ }
161
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
162
+ warnOnce(
163
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
164
+ );
165
+ }
166
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
167
+ }
168
+ function resolveSystemOneEdges(config) {
169
+ const edges = config?.systemOne?.edges;
170
+ if (edges !== void 0 && !isTypingMode(edges)) {
171
+ warnOnce(
172
+ `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
173
+ );
174
+ return "llm";
175
+ }
176
+ return edges ?? "llm";
177
+ }
178
+ function resolveSystemOneResolve(config) {
179
+ const resolve = config?.systemOne?.resolve;
180
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
181
+ warnOnce(
182
+ `[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
183
+ );
184
+ return "llm";
185
+ }
186
+ return resolve ?? "llm";
187
+ }
188
+ var DEFAULT_SHORTLIST_K = 10;
189
+ function resolveShortlistK(config) {
190
+ const k = config?.ontology?.shortlistK;
191
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
192
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
193
+ throw new Error(
194
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
195
+ );
196
+ }
197
+ return k;
198
+ }
199
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
200
+ function resolveTypingMinConfidence(config) {
201
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
202
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
203
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
204
+ const legacyValid = isConfidenceFloor(legacyFloor);
205
+ if (systemOneFloor !== void 0 && !systemOneValid) {
206
+ warnOnce(
207
+ `[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
208
+ );
209
+ }
210
+ if (legacyFloor !== void 0 && !legacyValid) {
211
+ warnOnce(
212
+ `[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
213
+ );
214
+ }
215
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
216
+ }
217
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
218
+ function resolveEdgesMinConfidence(config) {
219
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
220
+ const floor = config?.systemOne?.minConfidence?.edges;
221
+ if (isEdgesFloor(floor)) return floor;
222
+ warnOnce(
223
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
224
+ );
225
+ return void 0;
226
+ }
227
+ function resolveResolveMinConfidence(config) {
228
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
229
+ const floor = config?.systemOne?.minConfidence?.resolve;
230
+ if (isEdgesFloor(floor)) return floor;
231
+ warnOnce(
232
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
233
+ );
234
+ return void 0;
235
+ }
236
+ function resolveSystemOneHealScreen(config) {
237
+ const healScreen = config?.systemOne?.healScreen;
238
+ if (healScreen !== void 0 && !isTypingMode(healScreen)) {
239
+ warnOnce(
240
+ `[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
241
+ );
242
+ return "llm";
243
+ }
244
+ return healScreen ?? "llm";
245
+ }
246
+ function resolveSystemOneTypeOnWrite(config) {
247
+ const typeOnWrite = config?.systemOne?.typeOnWrite;
248
+ if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
249
+ warnOnce(
250
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnWrite\` is ${formatConfigValue(typeOnWrite)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
251
+ );
252
+ return "llm";
253
+ }
254
+ return typeOnWrite ?? "llm";
255
+ }
256
+ function resolveHealScreenMinConfidence(config) {
257
+ if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
258
+ const floor = config?.systemOne?.minConfidence?.healScreen;
259
+ if (isEdgesFloor(floor)) return floor;
260
+ warnOnce(
261
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
262
+ );
263
+ return void 0;
264
+ }
265
+
266
+ // src/utils/classifier.ts
267
+ var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
268
+ function validateClassifierAnswer(response, key, question) {
269
+ try {
270
+ if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
271
+ const answers = response.answers;
272
+ if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
273
+ if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
274
+ const raw = answers[key];
275
+ if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
276
+ const a = raw;
277
+ if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
278
+ if (question.kind === "choice") {
279
+ if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
280
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
281
+ const probs = a.probabilities;
282
+ if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
283
+ const probabilities = {};
284
+ for (const [k, v] of Object.entries(probs)) {
285
+ if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
286
+ probabilities[k] = v;
287
+ }
288
+ return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
289
+ }
290
+ if (question.kind === "binary") {
291
+ if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
292
+ return { ok: true, answer: { kind: "binary", probability: a.probability } };
293
+ }
294
+ const maxScore = question.levels.length - 1;
295
+ if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
296
+ return { ok: false, reason: "score_out_of_range" };
297
+ }
298
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
299
+ if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
300
+ return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
301
+ } catch {
302
+ return { ok: false, reason: "malformed" };
303
+ }
304
+ }
305
+ function classifierStateForFact(fact) {
306
+ const parts = [fact.title, fact.body];
307
+ if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
308
+ return parts.join("\n\n");
309
+ }
310
+
18
311
  // src/utils/diagnostics.ts
19
312
  var SEVERITY = {
20
313
  ingest_chunk_failed: "warn",
@@ -38,6 +331,8 @@ var SEVERITY = {
38
331
  llm_usage: "info",
39
332
  librarian_gate: "info",
40
333
  librarian_op_rejected: "warn",
334
+ librarian_rewritten: "info",
335
+ librarian_superseded: "info",
41
336
  contradicts_document: "warn",
42
337
  resolve_failed: "warn",
43
338
  read_budget: "info",
@@ -93,6 +388,8 @@ var MESSAGE = {
93
388
  llm_usage: "An LLM call completed; token usage attached.",
94
389
  librarian_gate: "Librarian gate outcome counts for one pass.",
95
390
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
391
+ librarian_rewritten: "The librarian rewrote an engine-inferred fact in place; the previous text was not kept.",
392
+ librarian_superseded: "The librarian ended a fact\u2019s validity with a replacement fact.",
96
393
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
97
394
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
98
395
  read_budget: "A read was packed to a token budget.",
@@ -231,43 +528,117 @@ var DiagnosticBuffer = class {
231
528
  if (codes.includes(input.code)) emitDiagnostic(options, input);
232
529
  }
233
530
  }
234
- discard() {
235
- this.items = [];
531
+ discard() {
532
+ this.items = [];
533
+ }
534
+ };
535
+ function edgeDropDiagnostic(drop, ctx) {
536
+ const detail = { reason: drop.reason };
537
+ const factId = ctx.factId ?? drop.sourceId;
538
+ if (factId) detail.factId = factId;
539
+ if (drop.edgeType) detail.edgeType = drop.edgeType;
540
+ if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
541
+ if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
542
+ if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
543
+ return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
544
+ }
545
+
546
+ // src/utils/usage.ts
547
+ function estimateTokens(text) {
548
+ return Math.ceil(text.length / 4);
549
+ }
550
+ var UsageMeter = class {
551
+ constructor(budget) {
552
+ this.used = 0;
553
+ this.estimated = false;
554
+ if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
555
+ throw new TypeError("tokenBudget must be a finite number >= 0");
556
+ }
557
+ this.budget = budget;
558
+ }
559
+ get remaining() {
560
+ return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
561
+ }
562
+ fits(estimate) {
563
+ return estimate <= this.remaining;
564
+ }
565
+ record(r) {
566
+ this.used += r.inputTokens + r.outputTokens;
567
+ if (r.estimated) this.estimated = true;
568
+ }
569
+ };
570
+ var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
571
+ constructor(requiredEstimate, remaining) {
572
+ super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
573
+ this.name = "WikiBudgetExhausted";
574
+ this.requiredEstimate = requiredEstimate;
575
+ this.remaining = remaining;
576
+ Object.setPrototypeOf(this, _WikiBudgetExhausted.prototype);
577
+ }
578
+ };
579
+
580
+ // src/utils/llmCall.ts
581
+ function validUsage(u) {
582
+ if (!u || typeof u !== "object") return false;
583
+ const { inputTokens, outputTokens } = u;
584
+ return [inputTokens, outputTokens].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0);
585
+ }
586
+ async function callLlm(options, ctx, prompts) {
587
+ const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
588
+ if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
589
+ throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
590
+ }
591
+ const provider = options.llmProvider;
592
+ const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
593
+ let text;
594
+ let reported;
595
+ if (typeof provider.generateTextWithUsage === "function") {
596
+ const result = await provider.generateTextWithUsage(params);
597
+ if (!result || typeof result.text !== "string") {
598
+ throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
599
+ }
600
+ text = result.text;
601
+ reported = validUsage(result.usage) ? result.usage : void 0;
602
+ } else {
603
+ text = await provider.generateText(params);
604
+ }
605
+ const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
606
+ ctx.meter?.record(record);
607
+ if (options.config?.reportLlmUsage === true) {
608
+ emitDiagnostic(options, {
609
+ code: "llm_usage",
610
+ operation: ctx.operation,
611
+ trigger: ctx.trigger,
612
+ entityId: ctx.entityId,
613
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
614
+ });
236
615
  }
237
- };
238
- function edgeDropDiagnostic(drop, ctx) {
239
- const detail = { reason: drop.reason };
240
- const factId = ctx.factId ?? drop.sourceId;
241
- if (factId) detail.factId = factId;
242
- if (drop.edgeType) detail.edgeType = drop.edgeType;
243
- if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
244
- if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
245
- if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
246
- return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
616
+ return text;
247
617
  }
248
-
249
- // src/repositories/rowMappers.ts
250
- function parseJsonArray(s, fallback) {
251
- if (Array.isArray(s)) return s;
252
- if (typeof s === "string" && s.length > 0) {
253
- try {
254
- const p = JSON.parse(s);
255
- if (Array.isArray(p)) return p;
256
- } catch {
257
- }
618
+ async function callClassify(options, ctx, request) {
619
+ const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
620
+ if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
621
+ throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
258
622
  }
259
- return fallback;
260
- }
261
- function parseJsonObject(s, fallback = null) {
262
- if (s && typeof s === "object" && !Array.isArray(s)) return s;
263
- if (typeof s === "string" && s.length > 0) {
264
- try {
265
- const p = JSON.parse(s);
266
- if (p && typeof p === "object" && !Array.isArray(p)) return p;
267
- } catch {
268
- }
623
+ const provider = options.llmProvider;
624
+ if (typeof provider.classify !== "function") {
625
+ throw new TypeError("callClassify requires a provider with classify()");
269
626
  }
270
- return fallback;
627
+ const response = await provider.classify(request);
628
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
629
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
630
+ const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
631
+ ctx.meter?.record(record);
632
+ if (options.config?.reportLlmUsage === true) {
633
+ emitDiagnostic(options, {
634
+ code: "llm_usage",
635
+ operation: ctx.operation,
636
+ trigger: ctx.trigger,
637
+ entityId: ctx.entityId,
638
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
639
+ });
640
+ }
641
+ return response;
271
642
  }
272
643
 
273
644
  // src/db/sqliteCodes.ts
@@ -477,19 +848,234 @@ var WikiMigrationRequiredError = class _WikiMigrationRequiredError extends Error
477
848
  Error.captureStackTrace(this, _WikiMigrationRequiredError);
478
849
  }
479
850
  }
480
- };
481
- var WikiSearchUnavailableError = class extends Error {
482
- constructor(message = "Keyword search is temporarily unavailable", cause) {
483
- super(message, cause !== void 0 ? { cause } : void 0);
484
- this.name = "WikiSearchUnavailableError";
851
+ };
852
+ var WikiSearchUnavailableError = class extends Error {
853
+ constructor(message = "Keyword search is temporarily unavailable", cause) {
854
+ super(message, cause !== void 0 ? { cause } : void 0);
855
+ this.name = "WikiSearchUnavailableError";
856
+ }
857
+ };
858
+ function isWikiSearchUnavailableError(err) {
859
+ try {
860
+ return err instanceof WikiSearchUnavailableError;
861
+ } catch {
862
+ return false;
863
+ }
864
+ }
865
+
866
+ // src/utils/ontology.ts
867
+ function emptyManifest() {
868
+ return { node_types: [], edge_types: [] };
869
+ }
870
+ function normalizeTitleKey(title) {
871
+ return title.trim().toLowerCase().replace(/\s+/g, " ");
872
+ }
873
+ function normalizeSlug(raw) {
874
+ return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
875
+ }
876
+ function resolveNodeTypeMatch(raw, manifest) {
877
+ const slug = typeof raw === "string" ? raw.trim() : "";
878
+ if (!slug) return null;
879
+ const lowered = slug.toLowerCase();
880
+ const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
881
+ if (exact) return { slug: exact.type, via: "exact" };
882
+ const normalized = normalizeSlug(slug);
883
+ if (!normalized) return null;
884
+ const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
885
+ return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
886
+ }
887
+ function resolveNodeType(raw, manifest) {
888
+ return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
889
+ }
890
+ var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
891
+ function isReservedAbstainSlug(raw) {
892
+ return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
893
+ }
894
+ function resolveEdgeDefinitions(rawEdgeType, manifest) {
895
+ const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
896
+ if (!slug) return [];
897
+ const lowered = slug.toLowerCase();
898
+ const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
899
+ if (exact.length > 0) return exact;
900
+ const normalized = normalizeSlug(slug);
901
+ if (!normalized) return [];
902
+ const names = new Set(
903
+ manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
904
+ );
905
+ if (names.size !== 1) return [];
906
+ return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
907
+ }
908
+ function edgeTripleKey(type, sourceType, targetType) {
909
+ return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
910
+ }
911
+ function typeSatisfies(declaredType, concreteType, manifest) {
912
+ const concrete = concreteType.trim().toLowerCase();
913
+ const declared = declaredType.trim().toLowerCase();
914
+ if (!concrete || !declared) return false;
915
+ if (declared === concrete) return true;
916
+ const def = (manifest.node_types ?? []).find(
917
+ (n) => typeof n?.type === "string" && n.type.trim().toLowerCase() === concrete
918
+ );
919
+ const parent = typeof def?.parent_type === "string" ? def.parent_type.trim().toLowerCase() : "";
920
+ return parent !== "" && parent === declared;
921
+ }
922
+ function edgeTripleAllowed(manifest, edgeType, sourceType, targetType) {
923
+ const wanted = edgeType.trim().toLowerCase();
924
+ return (manifest.edge_types ?? []).some((d) => typeof d?.type === "string" && d.type.trim().toLowerCase() === wanted && typeof d.source_type === "string" && typeSatisfies(d.source_type, sourceType, manifest) && typeof d.target_type === "string" && typeSatisfies(d.target_type, targetType, manifest));
925
+ }
926
+ function validateManifest(manifest) {
927
+ const nodeSlugs = /* @__PURE__ */ new Set();
928
+ for (const node of manifest.node_types ?? []) {
929
+ const type = node.type?.trim();
930
+ if (!type) throw new Error("Ontology node type slug must be non-empty");
931
+ const key = type.toLowerCase();
932
+ if (nodeSlugs.has(key)) throw new Error(`Duplicate node type: ${type}`);
933
+ nodeSlugs.add(key);
934
+ }
935
+ const parentOf = /* @__PURE__ */ new Map();
936
+ for (const node of manifest.node_types ?? []) {
937
+ const parent = typeof node.parent_type === "string" ? node.parent_type.trim().toLowerCase() : void 0;
938
+ parentOf.set(node.type.trim().toLowerCase(), parent);
939
+ }
940
+ for (const node of manifest.node_types ?? []) {
941
+ if (node.parent_type === void 0) continue;
942
+ if (typeof node.parent_type !== "string" || !node.parent_type.trim()) {
943
+ throw new Error(`Ontology parent_type must be a non-empty string when present: ${node.type}`);
944
+ }
945
+ const parentSlug = node.parent_type.trim().toLowerCase();
946
+ if (parentSlug === node.type.trim().toLowerCase()) {
947
+ throw new Error(`Self-parent: ${node.type}`);
948
+ }
949
+ if (!nodeSlugs.has(parentSlug)) {
950
+ throw new Error(`Parent type not found: ${node.parent_type}`);
951
+ }
952
+ const grandparent = parentOf.get(parentSlug);
953
+ if (grandparent) {
954
+ throw new Error(`Parent chain too deep: ${node.type} \u2192 ${node.parent_type} \u2192 ${grandparent}`);
955
+ }
956
+ }
957
+ const edgeKeys = /* @__PURE__ */ new Set();
958
+ const edgeNames = /* @__PURE__ */ new Map();
959
+ for (const edge of manifest.edge_types ?? []) {
960
+ const edgeType = edge.type?.trim();
961
+ const sourceType = edge.source_type?.trim();
962
+ const targetType = edge.target_type?.trim();
963
+ if (!edgeType) throw new Error("Ontology edge type slug must be non-empty");
964
+ if (!sourceType || !targetType || !nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
965
+ throw new Error(`Edge type ${edgeType} references unknown node type`);
966
+ }
967
+ const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
968
+ if (edgeKeys.has(edgeKey)) {
969
+ throw new Error(`Duplicate edge definition: ${edgeType} (${sourceType} \u2192 ${targetType})`);
970
+ }
971
+ edgeKeys.add(edgeKey);
972
+ const canonical = edgeNames.get(edgeType.toLowerCase());
973
+ if (canonical === void 0) {
974
+ edgeNames.set(edgeType.toLowerCase(), edgeType);
975
+ } else if (canonical !== edgeType) {
976
+ throw new Error(`Inconsistent casing for edge type: ${edgeType} conflicts with ${canonical}`);
977
+ }
978
+ }
979
+ }
980
+ function buildDeclaresParentIndex(nodes) {
981
+ const declaresParent = /* @__PURE__ */ new Map();
982
+ for (const n of nodes) {
983
+ const slug = typeof n?.type === "string" ? n.type.trim().toLowerCase() : "";
984
+ if (!slug || declaresParent.has(slug)) continue;
985
+ declaresParent.set(slug, n?.parent_type !== void 0);
986
+ }
987
+ return declaresParent;
988
+ }
989
+ function mergeOntologyUpdates(current, updates) {
990
+ const node_types = [...current.node_types];
991
+ const edge_types = [...current.edge_types];
992
+ const rejected = [];
993
+ const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
994
+ const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
995
+ const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
996
+ const declaresParent = buildDeclaresParentIndex([
997
+ ...current.node_types,
998
+ ...updates.node_types ?? []
999
+ ]);
1000
+ for (const node of updates.node_types ?? []) {
1001
+ const type = node?.type?.trim();
1002
+ if (!type) {
1003
+ rejected.push("invalid_shape");
1004
+ continue;
1005
+ }
1006
+ const key = type.toLowerCase();
1007
+ if (nodeSlugs.has(key)) {
1008
+ rejected.push("duplicate_node_type");
1009
+ continue;
1010
+ }
1011
+ const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
1012
+ const parentSlug = rawParent.toLowerCase();
1013
+ const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
1014
+ node_types.push({
1015
+ type,
1016
+ description: String(node.description ?? ""),
1017
+ ...keepParent ? { parent_type: rawParent } : {}
1018
+ });
1019
+ nodeSlugs.add(key);
1020
+ }
1021
+ for (const edge of updates.edge_types ?? []) {
1022
+ const rawEdgeType = edge?.type?.trim();
1023
+ const sourceType = edge?.source_type?.trim();
1024
+ const targetType = edge?.target_type?.trim();
1025
+ if (!rawEdgeType || !sourceType || !targetType) {
1026
+ rejected.push("invalid_shape");
1027
+ continue;
1028
+ }
1029
+ const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
1030
+ const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
1031
+ if (edgeKeys.has(edgeKey)) {
1032
+ rejected.push("duplicate_edge");
1033
+ continue;
1034
+ }
1035
+ if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
1036
+ rejected.push("unknown_endpoint");
1037
+ continue;
1038
+ }
1039
+ edgeNames.set(edgeType.toLowerCase(), edgeType);
1040
+ edge_types.push({
1041
+ type: edgeType,
1042
+ source_type: sourceType,
1043
+ target_type: targetType,
1044
+ description: String(edge.description ?? "")
1045
+ });
1046
+ edgeKeys.add(edgeKey);
1047
+ }
1048
+ return { manifest: { node_types, edge_types }, rejected };
1049
+ }
1050
+ function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
1051
+ const strict = opts?.strict === true;
1052
+ const entityId = opts?.entityId ?? "";
1053
+ const drops = opts?.drops;
1054
+ const drop = (reason, edgeType) => {
1055
+ drops?.push({ reason, sourceId: null, edgeType, sourceNodeType: sourceType, targetNodeType: null });
1056
+ };
1057
+ if (!Array.isArray(edges)) {
1058
+ if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", "");
1059
+ drop("invalid_shape", null);
1060
+ return [];
485
1061
  }
486
- };
487
- function isWikiSearchUnavailableError(err) {
488
- try {
489
- return err instanceof WikiSearchUnavailableError;
490
- } catch {
491
- return false;
1062
+ const valid = [];
1063
+ for (const edge of edges) {
1064
+ if (typeof edge?.edge_type !== "string" || typeof edge?.target_title !== "string") {
1065
+ if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", String(edge?.edge_type ?? ""));
1066
+ drop("invalid_shape", typeof edge?.edge_type === "string" ? edge.edge_type : null);
1067
+ continue;
1068
+ }
1069
+ const defs = resolveEdgeDefinitions(edge.edge_type, manifest);
1070
+ const match = defs.find((d) => typeSatisfies(d.source_type, sourceType, manifest));
1071
+ if (!match) {
1072
+ if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", edge.edge_type);
1073
+ drop("type_not_in_manifest", edge.edge_type);
1074
+ continue;
1075
+ }
1076
+ valid.push({ edge_type: match.type, target_title: edge.target_title });
492
1077
  }
1078
+ return valid;
493
1079
  }
494
1080
 
495
1081
  // src/utils/pure.ts
@@ -982,28 +1568,358 @@ function factRejectionReason(raw) {
982
1568
  if (!clip(fact.title, 80)) return "missing_title";
983
1569
  return "missing_body";
984
1570
  }
985
- function taskRejectionReason(raw) {
986
- const task = raw;
987
- if (typeof task?.description !== "string") return "invalid_shape";
988
- return "missing_description";
1571
+ function taskRejectionReason(raw) {
1572
+ const task = raw;
1573
+ if (typeof task?.description !== "string") return "invalid_shape";
1574
+ return "missing_description";
1575
+ }
1576
+ function normalizeSourceRef(value) {
1577
+ if (typeof value !== "string") return null;
1578
+ const cleaned = value.replace(/[^A-Za-z0-9._\- ]/g, "").trim().slice(0, 255).trimEnd();
1579
+ return cleaned.length > 0 ? cleaned : null;
1580
+ }
1581
+ function normalizeSourceHash(value) {
1582
+ if (typeof value !== "string") return null;
1583
+ return /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : null;
1584
+ }
1585
+ function titleTokens(title) {
1586
+ return new Set(title.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((t) => t.length >= 3));
1587
+ }
1588
+ function jaccardScore(a, b) {
1589
+ if (a.size === 0 && b.size === 0) return 0;
1590
+ const intersection = new Set([...a].filter((x) => b.has(x)));
1591
+ const union = /* @__PURE__ */ new Set([...a, ...b]);
1592
+ return intersection.size / union.size;
1593
+ }
1594
+
1595
+ // src/services/BoundedLlmCall.ts
1596
+ var DEFAULT_BATCH_SIZE = 10;
1597
+ var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
1598
+ var OUTPUT_BUDGET_FRACTION = 0.8;
1599
+ var TRUNCATION_PATTERNS = [
1600
+ /truncat/i,
1601
+ /token limit/i,
1602
+ /max(imum)?[ _-]?tokens?/i,
1603
+ /output limit/i,
1604
+ /length limit/i,
1605
+ /finish[_ ]?reason/i
1606
+ ];
1607
+ var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
1608
+ 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;
1609
+ var CONTEXT_OVERFLOW_PATTERNS = [
1610
+ /maximum context length/i,
1611
+ /context[_ ]?length[_ ]?exceeded/i,
1612
+ /prompt is too long/i,
1613
+ /input (token count|is too long)/i,
1614
+ /exceeds? the (available )?context( size)?/i,
1615
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
1616
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
1617
+ // classify as input overflow (it would split the batch and stamp a cooldown).
1618
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
1619
+ /context limit/i,
1620
+ // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
1621
+ /\bcontext is full\b/i,
1622
+ /too long for (the )?requested model/i,
1623
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
1624
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
1625
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
1626
+ ];
1627
+ function isContextOverflowError(err) {
1628
+ const message = getErrorMessage(err);
1629
+ if (message === void 0) return false;
1630
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
1631
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
1632
+ }
1633
+ function getErrorMessage(err) {
1634
+ try {
1635
+ return err instanceof Error ? err.message : String(err ?? "");
1636
+ } catch {
1637
+ return void 0;
1638
+ }
1639
+ }
1640
+ function isTruncationError(err) {
1641
+ const message = getErrorMessage(err);
1642
+ if (message === void 0) return false;
1643
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
1644
+ if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
1645
+ return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
1646
+ }
1647
+ function isConfigError(err) {
1648
+ const message = getErrorMessage(err);
1649
+ if (message === void 0) return false;
1650
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
1651
+ return EXCEEDS_LIMIT_PATTERN.test(message);
1652
+ }
1653
+ function initialBatchSize(maxOutputTokens) {
1654
+ if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
1655
+ return DEFAULT_BATCH_SIZE;
1656
+ }
1657
+ const estimate = Math.floor(
1658
+ maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
1659
+ );
1660
+ return Math.max(DEFAULT_BATCH_SIZE, estimate);
1661
+ }
1662
+ var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
1663
+ async function runBatched(args) {
1664
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
1665
+ const results = [];
1666
+ const skipped = [];
1667
+ let batches = 0;
1668
+ const settled = /* @__PURE__ */ new Set();
1669
+ let budgetStop;
1670
+ let batchSize = initialBatchSize(maxOutputTokens);
1671
+ const trim = async (candidate) => {
1672
+ const whole = await buildPrompt(candidate);
1673
+ if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
1674
+ return { batch: candidate, prompts: whole };
1675
+ }
1676
+ let low = 2;
1677
+ let high = candidate.length - 1;
1678
+ let best;
1679
+ let bestPrompts;
1680
+ while (low <= high) {
1681
+ const mid = Math.floor((low + high) / 2);
1682
+ const batch = candidate.slice(0, mid);
1683
+ const prompts = await buildPrompt(batch);
1684
+ if (promptLength(prompts) <= maxPromptChars) {
1685
+ best = batch;
1686
+ bestPrompts = prompts;
1687
+ low = mid + 1;
1688
+ } else {
1689
+ high = mid - 1;
1690
+ }
1691
+ }
1692
+ if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
1693
+ const single = candidate.slice(0, 1);
1694
+ return { batch: single, prompts: await buildPrompt(single) };
1695
+ };
1696
+ const onFailure = async (batch, err, attemptLevel, fromCall) => {
1697
+ if (batch.length === 1) {
1698
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
1699
+ await attempt(batch, void 0, attemptLevel + 1);
1700
+ } else {
1701
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
1702
+ skipped.push({ item: batch[0], reason });
1703
+ settled.add(batch[0]);
1704
+ onSkip?.(batch[0], err);
1705
+ }
1706
+ return;
1707
+ }
1708
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
1709
+ const mid = Math.ceil(batch.length / 2);
1710
+ if (mid < batchSize) batchSize = mid;
1711
+ let i = 0;
1712
+ while (i < batch.length && !budgetStop) {
1713
+ const size = Math.min(batchSize, batch.length - i);
1714
+ const trimmed = await trim(batch.slice(i, i + size));
1715
+ await attempt(trimmed.batch, trimmed.prompts);
1716
+ i += trimmed.batch.length;
1717
+ }
1718
+ };
1719
+ const attempt = async (batch, prebuilt, attemptLevel = 0) => {
1720
+ if (budgetStop) return;
1721
+ if (batch.length === 0) return;
1722
+ const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
1723
+ batches++;
1724
+ let responseText;
1725
+ try {
1726
+ responseText = await call(prompts);
1727
+ } catch (err) {
1728
+ if (err instanceof WikiBudgetExhausted) {
1729
+ budgetStop = { requiredEstimate: err.requiredEstimate };
1730
+ return;
1731
+ }
1732
+ await onFailure(batch, err, attemptLevel, true);
1733
+ return;
1734
+ }
1735
+ let result;
1736
+ try {
1737
+ result = parse(responseText, batch, prompts);
1738
+ } catch (err) {
1739
+ await onFailure(batch, err, attemptLevel, false);
1740
+ return;
1741
+ }
1742
+ results.push(result);
1743
+ for (const item of batch) settled.add(item);
1744
+ };
1745
+ let index = 0;
1746
+ while (index < items.length && !budgetStop) {
1747
+ const { batch, prompts } = await trim(items.slice(index, index + batchSize));
1748
+ index += batch.length;
1749
+ await attempt(batch, prompts, 0);
1750
+ }
1751
+ const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
1752
+ return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
1753
+ }
1754
+
1755
+ // src/services/typing/typeOnWrite.ts
1756
+ var CLASSIFIER_MAX_CHOICES = 255;
1757
+ function isManifestRepresentable(manifest) {
1758
+ const slugs = manifest.node_types.map((n) => n.type);
1759
+ return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
1760
+ }
1761
+ function canEngageWriteTyping(config, provider, mode, manifest) {
1762
+ return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
1763
+ }
1764
+ function buildTypingQuestion(manifest) {
1765
+ return {
1766
+ kind: "choice",
1767
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
1768
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
1769
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
1770
+ };
1771
+ }
1772
+ function volunteeredTypeResolves(rawOkfType, manifest) {
1773
+ return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
1774
+ }
1775
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
1776
+ const question = buildTypingQuestion(manifest);
1777
+ const rawConcurrency = options.config?.chunkConcurrency ?? 1;
1778
+ const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
1779
+ let stopped = false;
1780
+ return withConcurrency(
1781
+ facts.map((fact) => async () => {
1782
+ if (stopped) return { kind: "unattempted" };
1783
+ let response;
1784
+ try {
1785
+ response = await callClassify(
1786
+ options,
1787
+ { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
1788
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
1789
+ );
1790
+ } catch (err) {
1791
+ if (err instanceof WikiBudgetExhausted) {
1792
+ stopped = true;
1793
+ return { kind: "unattempted" };
1794
+ }
1795
+ if (isContextOverflowError(err)) return { kind: "overflow_skip" };
1796
+ return { kind: "threw" };
1797
+ }
1798
+ const checked = validateClassifierAnswer(response, "okf_type", question);
1799
+ if (!checked.ok) return { kind: "invalid", reason: checked.reason };
1800
+ if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
1801
+ if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
1802
+ if (checked.answer.confidence < floor) return { kind: "low_confidence" };
1803
+ return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
1804
+ }),
1805
+ concurrency
1806
+ );
1807
+ }
1808
+ function emptyTypingCounters() {
1809
+ return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
989
1810
  }
990
- function normalizeSourceRef(value) {
991
- if (typeof value !== "string") return null;
992
- const cleaned = value.replace(/[^A-Za-z0-9._\- ]/g, "").trim().slice(0, 255).trimEnd();
993
- return cleaned.length > 0 ? cleaned : null;
1811
+ function tallyTypingOutcome(c, o) {
1812
+ switch (o.kind) {
1813
+ case "unattempted":
1814
+ c.unattempted++;
1815
+ return;
1816
+ case "accepted":
1817
+ c.asked++;
1818
+ return;
1819
+ case "abstain":
1820
+ c.asked++;
1821
+ c.abstained++;
1822
+ return;
1823
+ case "low_confidence":
1824
+ c.asked++;
1825
+ c.lowConfidence++;
1826
+ return;
1827
+ case "invalid":
1828
+ case "threw":
1829
+ c.asked++;
1830
+ c.invalid++;
1831
+ return;
1832
+ case "overflow_skip":
1833
+ c.asked++;
1834
+ c.skipped++;
1835
+ return;
1836
+ }
994
1837
  }
995
- function normalizeSourceHash(value) {
996
- if (typeof value !== "string") return null;
997
- return /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : null;
1838
+ function typingOutcomeReceipt(base, factId, outcome) {
1839
+ switch (outcome.kind) {
1840
+ case "abstain":
1841
+ return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
1842
+ case "low_confidence":
1843
+ return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
1844
+ case "invalid":
1845
+ return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
1846
+ case "threw":
1847
+ return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
1848
+ case "overflow_skip":
1849
+ return { ...base, code: "context_overflow_skipped", detail: { factId } };
1850
+ default:
1851
+ return null;
1852
+ }
998
1853
  }
999
- function titleTokens(title) {
1000
- return new Set(title.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((t) => t.length >= 3));
1854
+ function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
1855
+ const drops = [];
1856
+ const receipts = [];
1857
+ const emit = shouldEmitOntologyReceipt(mode);
1858
+ let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
1859
+ if (emit) {
1860
+ receipts.push(...nodeTypeReceipts(
1861
+ base,
1862
+ factId,
1863
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
1864
+ normalized.okf_type,
1865
+ normalized.match
1866
+ ));
1867
+ }
1868
+ let typedByClassifier = false;
1869
+ if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
1870
+ const second = ontology?.validateAndNormalizeFact(
1871
+ { ...fact, okf_type: outcome.okfType, edges: [] },
1872
+ manifest,
1873
+ { strict: false }
1874
+ ) ?? { okf_type: null};
1875
+ if (emit) {
1876
+ receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
1877
+ }
1878
+ normalized = { okf_type: second.okf_type, edges: [] };
1879
+ if (second.okf_type) {
1880
+ typedByClassifier = true;
1881
+ if (emit) {
1882
+ receipts.push({
1883
+ ...base,
1884
+ code: "node_type_assigned",
1885
+ detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
1886
+ });
1887
+ }
1888
+ }
1889
+ } else if (normalized.okf_type) {
1890
+ if (emit) {
1891
+ receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
1892
+ }
1893
+ }
1894
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
1895
+ const r = typingOutcomeReceipt(base, factId, outcome);
1896
+ if (r) receipts.push(r);
1897
+ }
1898
+ return { normalized, drops, receipts, typedByClassifier };
1001
1899
  }
1002
- function jaccardScore(a, b) {
1003
- if (a.size === 0 && b.size === 0) return 0;
1004
- const intersection = new Set([...a].filter((x) => b.has(x)));
1005
- const union = /* @__PURE__ */ new Set([...a, ...b]);
1006
- return intersection.size / union.size;
1900
+
1901
+ // src/repositories/rowMappers.ts
1902
+ function parseJsonArray(s, fallback) {
1903
+ if (Array.isArray(s)) return s;
1904
+ if (typeof s === "string" && s.length > 0) {
1905
+ try {
1906
+ const p = JSON.parse(s);
1907
+ if (Array.isArray(p)) return p;
1908
+ } catch {
1909
+ }
1910
+ }
1911
+ return fallback;
1912
+ }
1913
+ function parseJsonObject(s, fallback = null) {
1914
+ if (s && typeof s === "object" && !Array.isArray(s)) return s;
1915
+ if (typeof s === "string" && s.length > 0) {
1916
+ try {
1917
+ const p = JSON.parse(s);
1918
+ if (p && typeof p === "object" && !Array.isArray(p)) return p;
1919
+ } catch {
1920
+ }
1921
+ }
1922
+ return fallback;
1007
1923
  }
1008
1924
 
1009
1925
  // src/db/schema.ts
@@ -4563,233 +5479,18 @@ var EdgeRepository = class extends BaseRepository {
4563
5479
  WHERE e.entity_id = ?`,
4564
5480
  [...nodeIds, entityId]
4565
5481
  );
4566
- return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4567
- }
4568
- };
4569
- function mapRowToEdge(row) {
4570
- return {
4571
- id: String(row.id),
4572
- entity_id: String(row.entity_id),
4573
- source_id: String(row.source_id),
4574
- target_id: String(row.target_id),
4575
- edge_type: String(row.edge_type),
4576
- created_at: Number(row.created_at)
4577
- };
4578
- }
4579
-
4580
- // src/utils/ontology.ts
4581
- function emptyManifest() {
4582
- return { node_types: [], edge_types: [] };
4583
- }
4584
- function normalizeTitleKey(title) {
4585
- return title.trim().toLowerCase().replace(/\s+/g, " ");
4586
- }
4587
- function normalizeSlug(raw) {
4588
- return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
4589
- }
4590
- function resolveNodeTypeMatch(raw, manifest) {
4591
- const slug = typeof raw === "string" ? raw.trim() : "";
4592
- if (!slug) return null;
4593
- const lowered = slug.toLowerCase();
4594
- const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
4595
- if (exact) return { slug: exact.type, via: "exact" };
4596
- const normalized = normalizeSlug(slug);
4597
- if (!normalized) return null;
4598
- const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
4599
- return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
4600
- }
4601
- function resolveNodeType(raw, manifest) {
4602
- return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
4603
- }
4604
- var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
4605
- function isReservedAbstainSlug(raw) {
4606
- return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
4607
- }
4608
- function resolveEdgeDefinitions(rawEdgeType, manifest) {
4609
- const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
4610
- if (!slug) return [];
4611
- const lowered = slug.toLowerCase();
4612
- const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
4613
- if (exact.length > 0) return exact;
4614
- const normalized = normalizeSlug(slug);
4615
- if (!normalized) return [];
4616
- const names = new Set(
4617
- manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
4618
- );
4619
- if (names.size !== 1) return [];
4620
- return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
4621
- }
4622
- function edgeTripleKey(type, sourceType, targetType) {
4623
- return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
4624
- }
4625
- function typeSatisfies(declaredType, concreteType, manifest) {
4626
- const concrete = concreteType.trim().toLowerCase();
4627
- const declared = declaredType.trim().toLowerCase();
4628
- if (!concrete || !declared) return false;
4629
- if (declared === concrete) return true;
4630
- const def = (manifest.node_types ?? []).find(
4631
- (n) => typeof n?.type === "string" && n.type.trim().toLowerCase() === concrete
4632
- );
4633
- const parent = typeof def?.parent_type === "string" ? def.parent_type.trim().toLowerCase() : "";
4634
- return parent !== "" && parent === declared;
4635
- }
4636
- function edgeTripleAllowed(manifest, edgeType, sourceType, targetType) {
4637
- const wanted = edgeType.trim().toLowerCase();
4638
- return (manifest.edge_types ?? []).some((d) => typeof d?.type === "string" && d.type.trim().toLowerCase() === wanted && typeof d.source_type === "string" && typeSatisfies(d.source_type, sourceType, manifest) && typeof d.target_type === "string" && typeSatisfies(d.target_type, targetType, manifest));
4639
- }
4640
- function validateManifest(manifest) {
4641
- const nodeSlugs = /* @__PURE__ */ new Set();
4642
- for (const node of manifest.node_types ?? []) {
4643
- const type = node.type?.trim();
4644
- if (!type) throw new Error("Ontology node type slug must be non-empty");
4645
- const key = type.toLowerCase();
4646
- if (nodeSlugs.has(key)) throw new Error(`Duplicate node type: ${type}`);
4647
- nodeSlugs.add(key);
4648
- }
4649
- const parentOf = /* @__PURE__ */ new Map();
4650
- for (const node of manifest.node_types ?? []) {
4651
- const parent = typeof node.parent_type === "string" ? node.parent_type.trim().toLowerCase() : void 0;
4652
- parentOf.set(node.type.trim().toLowerCase(), parent);
4653
- }
4654
- for (const node of manifest.node_types ?? []) {
4655
- if (node.parent_type === void 0) continue;
4656
- if (typeof node.parent_type !== "string" || !node.parent_type.trim()) {
4657
- throw new Error(`Ontology parent_type must be a non-empty string when present: ${node.type}`);
4658
- }
4659
- const parentSlug = node.parent_type.trim().toLowerCase();
4660
- if (parentSlug === node.type.trim().toLowerCase()) {
4661
- throw new Error(`Self-parent: ${node.type}`);
4662
- }
4663
- if (!nodeSlugs.has(parentSlug)) {
4664
- throw new Error(`Parent type not found: ${node.parent_type}`);
4665
- }
4666
- const grandparent = parentOf.get(parentSlug);
4667
- if (grandparent) {
4668
- throw new Error(`Parent chain too deep: ${node.type} \u2192 ${node.parent_type} \u2192 ${grandparent}`);
4669
- }
4670
- }
4671
- const edgeKeys = /* @__PURE__ */ new Set();
4672
- const edgeNames = /* @__PURE__ */ new Map();
4673
- for (const edge of manifest.edge_types ?? []) {
4674
- const edgeType = edge.type?.trim();
4675
- const sourceType = edge.source_type?.trim();
4676
- const targetType = edge.target_type?.trim();
4677
- if (!edgeType) throw new Error("Ontology edge type slug must be non-empty");
4678
- if (!sourceType || !targetType || !nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
4679
- throw new Error(`Edge type ${edgeType} references unknown node type`);
4680
- }
4681
- const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
4682
- if (edgeKeys.has(edgeKey)) {
4683
- throw new Error(`Duplicate edge definition: ${edgeType} (${sourceType} \u2192 ${targetType})`);
4684
- }
4685
- edgeKeys.add(edgeKey);
4686
- const canonical = edgeNames.get(edgeType.toLowerCase());
4687
- if (canonical === void 0) {
4688
- edgeNames.set(edgeType.toLowerCase(), edgeType);
4689
- } else if (canonical !== edgeType) {
4690
- throw new Error(`Inconsistent casing for edge type: ${edgeType} conflicts with ${canonical}`);
4691
- }
4692
- }
4693
- }
4694
- function buildDeclaresParentIndex(nodes) {
4695
- const declaresParent = /* @__PURE__ */ new Map();
4696
- for (const n of nodes) {
4697
- const slug = typeof n?.type === "string" ? n.type.trim().toLowerCase() : "";
4698
- if (!slug || declaresParent.has(slug)) continue;
4699
- declaresParent.set(slug, n?.parent_type !== void 0);
4700
- }
4701
- return declaresParent;
4702
- }
4703
- function mergeOntologyUpdates(current, updates) {
4704
- const node_types = [...current.node_types];
4705
- const edge_types = [...current.edge_types];
4706
- const rejected = [];
4707
- const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
4708
- const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
4709
- const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
4710
- const declaresParent = buildDeclaresParentIndex([
4711
- ...current.node_types,
4712
- ...updates.node_types ?? []
4713
- ]);
4714
- for (const node of updates.node_types ?? []) {
4715
- const type = node?.type?.trim();
4716
- if (!type) {
4717
- rejected.push("invalid_shape");
4718
- continue;
4719
- }
4720
- const key = type.toLowerCase();
4721
- if (nodeSlugs.has(key)) {
4722
- rejected.push("duplicate_node_type");
4723
- continue;
4724
- }
4725
- const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
4726
- const parentSlug = rawParent.toLowerCase();
4727
- const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
4728
- node_types.push({
4729
- type,
4730
- description: String(node.description ?? ""),
4731
- ...keepParent ? { parent_type: rawParent } : {}
4732
- });
4733
- nodeSlugs.add(key);
4734
- }
4735
- for (const edge of updates.edge_types ?? []) {
4736
- const rawEdgeType = edge?.type?.trim();
4737
- const sourceType = edge?.source_type?.trim();
4738
- const targetType = edge?.target_type?.trim();
4739
- if (!rawEdgeType || !sourceType || !targetType) {
4740
- rejected.push("invalid_shape");
4741
- continue;
4742
- }
4743
- const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
4744
- const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
4745
- if (edgeKeys.has(edgeKey)) {
4746
- rejected.push("duplicate_edge");
4747
- continue;
4748
- }
4749
- if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
4750
- rejected.push("unknown_endpoint");
4751
- continue;
4752
- }
4753
- edgeNames.set(edgeType.toLowerCase(), edgeType);
4754
- edge_types.push({
4755
- type: edgeType,
4756
- source_type: sourceType,
4757
- target_type: targetType,
4758
- description: String(edge.description ?? "")
4759
- });
4760
- edgeKeys.add(edgeKey);
5482
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4761
5483
  }
4762
- return { manifest: { node_types, edge_types }, rejected };
4763
- }
4764
- function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
4765
- const strict = opts?.strict === true;
4766
- const entityId = opts?.entityId ?? "";
4767
- const drops = opts?.drops;
4768
- const drop = (reason, edgeType) => {
4769
- drops?.push({ reason, sourceId: null, edgeType, sourceNodeType: sourceType, targetNodeType: null });
5484
+ };
5485
+ function mapRowToEdge(row) {
5486
+ return {
5487
+ id: String(row.id),
5488
+ entity_id: String(row.entity_id),
5489
+ source_id: String(row.source_id),
5490
+ target_id: String(row.target_id),
5491
+ edge_type: String(row.edge_type),
5492
+ created_at: Number(row.created_at)
4770
5493
  };
4771
- if (!Array.isArray(edges)) {
4772
- if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", "");
4773
- drop("invalid_shape", null);
4774
- return [];
4775
- }
4776
- const valid = [];
4777
- for (const edge of edges) {
4778
- if (typeof edge?.edge_type !== "string" || typeof edge?.target_title !== "string") {
4779
- if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", String(edge?.edge_type ?? ""));
4780
- drop("invalid_shape", typeof edge?.edge_type === "string" ? edge.edge_type : null);
4781
- continue;
4782
- }
4783
- const defs = resolveEdgeDefinitions(edge.edge_type, manifest);
4784
- const match = defs.find((d) => typeSatisfies(d.source_type, sourceType, manifest));
4785
- if (!match) {
4786
- if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", edge.edge_type);
4787
- drop("type_not_in_manifest", edge.edge_type);
4788
- continue;
4789
- }
4790
- valid.push({ edge_type: match.type, target_title: edge.target_title });
4791
- }
4792
- return valid;
4793
5494
  }
4794
5495
 
4795
5496
  // src/repositories/MetadataRepository.ts
@@ -7739,16 +8440,36 @@ ${guidanceSection(guidance)}`;
7739
8440
  } while (out !== prev);
7740
8441
  return out;
7741
8442
  }
7742
- buildSystemPrompt(template, variables, ontologyContext) {
8443
+ /** Write-site variant (ingest, librarian, ops extract). Body identical to the backfill variant by design (specs/type-on-write §5). */
8444
+ buildWriteSystemPrompt(template, variables, ontologyContext) {
8445
+ const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
8446
+ const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
8447
+ const shouldHydrate = Object.keys(variables).some(
8448
+ (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
8449
+ ) || ontologyContext != null && hasOntologyPlaceholders;
8450
+ const hydrated = shouldHydrate ? this.hydrate(effective, {
8451
+ ...variables,
8452
+ ...ontologyContext ? { ontologyManifest: ontologyContext.ontologyManifest, ontologyModeInstructions: ontologyContext.ontologyModeInstructions } : {}
8453
+ }) : effective;
8454
+ return hasOntologyPlaceholders ? hydrated : this.appendWriteOntology(hydrated, ontologyContext);
8455
+ }
8456
+ appendWriteOntology(systemPrompt, ctx) {
8457
+ if (!ctx) return systemPrompt;
8458
+ return `${systemPrompt}
8459
+
8460
+ ${ctx.ontologyModeInstructions}`;
8461
+ }
8462
+ /** Backfill-site variant. Body identical to the write variant by design (specs/type-on-write §5). */
8463
+ buildBackfillSystemPrompt(template, variables, ontologyContext) {
7743
8464
  const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
7744
8465
  const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
7745
8466
  const shouldHydrate = Object.keys(variables).some(
7746
8467
  (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
7747
8468
  ) || ontologyContext != null && hasOntologyPlaceholders;
7748
8469
  const hydrated = shouldHydrate ? this.hydrate(effective, { ...variables, ...ontologyContext ?? {} }) : effective;
7749
- return hasOntologyPlaceholders ? hydrated : this.appendOntology(hydrated, ontologyContext);
8470
+ return hasOntologyPlaceholders ? hydrated : this.appendBackfillOntology(hydrated, ontologyContext);
7750
8471
  }
7751
- appendOntology(systemPrompt, ctx) {
8472
+ appendBackfillOntology(systemPrompt, ctx) {
7752
8473
  if (!ctx) return systemPrompt;
7753
8474
  return `${systemPrompt}
7754
8475
 
@@ -7759,13 +8480,13 @@ ${ctx.ontologyModeInstructions}`;
7759
8480
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
7760
8481
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
7761
8482
  return {
7762
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
8483
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
7763
8484
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
7764
8485
  ${documentChunk}`
7765
8486
  };
7766
8487
  }
7767
8488
  return {
7768
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
8489
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "ingest"),
7769
8490
  userPrompt: `Document Chunk:
7770
8491
  ${documentChunk}`
7771
8492
  };
@@ -7778,7 +8499,7 @@ ${documentChunk}`
7778
8499
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
7779
8500
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
7780
8501
  return {
7781
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
8502
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
7782
8503
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
7783
8504
  ${JSON.stringify(events, null, 2)}
7784
8505
 
@@ -7788,7 +8509,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
7788
8509
  };
7789
8510
  }
7790
8511
  return {
7791
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
8512
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "librarian"),
7792
8513
  userPrompt: `Events:
7793
8514
  ${JSON.stringify(events, null, 2)}
7794
8515
 
@@ -7879,7 +8600,7 @@ The following document anchors are provided for contradiction detection only. Do
7879
8600
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
7880
8601
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
7881
8602
  return {
7882
- systemPrompt: this.buildSystemPrompt(template, { facts }, ontologyContext),
8603
+ systemPrompt: this.buildBackfillSystemPrompt(template, { facts }, ontologyContext),
7883
8604
  userPrompt: hasFacts ? "Please classify the facts." : `Facts:
7884
8605
  ${JSON.stringify(facts, null, 2)}`
7885
8606
  };
@@ -7887,7 +8608,7 @@ ${JSON.stringify(facts, null, 2)}`
7887
8608
  const factsBlock = `Facts:
7888
8609
  ${JSON.stringify(facts, null, 2)}`;
7889
8610
  return {
7890
- systemPrompt: this.appendOntology(template, ontologyContext),
8611
+ systemPrompt: this.appendBackfillOntology(template, ontologyContext),
7891
8612
  userPrompt: candidateSections !== void 0 ? `${factsBlock}
7892
8613
 
7893
8614
  ${candidateSections}` : factsBlock
@@ -7898,7 +8619,7 @@ ${candidateSections}` : factsBlock
7898
8619
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
7899
8620
  const grounding = this.groundingFor("librarian");
7900
8621
  return {
7901
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
8622
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
7902
8623
  userPrompt: `Events:
7903
8624
  ${lines.join("\n")}`,
7904
8625
  // Corpus entries are one-per-batch-event in batch order (summaries are
@@ -7919,13 +8640,14 @@ ${JSON.stringify({ items })}` };
7919
8640
  * placeholders and leaves data placeholders verbatim; heal never receives
7920
8641
  * ontology context, matching `buildHealPrompt`.
7921
8642
  */
7922
- buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
8643
+ buildInstructionTemplates(writeContext, librarianStrategy, guidance, backfillContext, ingestContext) {
7923
8644
  const o = this.globalOverrides;
8645
+ const backfill = backfillContext !== void 0 ? backfillContext : writeContext ? { ontologyManifest: writeContext.ontologyManifest, ontologyModeInstructions: writeContext.ontologyModeInstructions } : null;
7924
8646
  return {
7925
- ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
7926
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
8647
+ ingest: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ingestContext !== void 0 ? ingestContext : writeContext), guidance), "ingest"),
8648
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, writeContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, writeContext), guidance), "librarian"),
7927
8649
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
7928
- ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
8650
+ ontologyBackfill: this.buildBackfillSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, backfill)
7929
8651
  };
7930
8652
  }
7931
8653
  };
@@ -7935,213 +8657,42 @@ function applyBodyTruncation(candidates, attemptLevel, bodyTruncationChars) {
7935
8657
  }
7936
8658
  const shapedCandidates = [];
7937
8659
  const degraded = [];
7938
- for (const c of candidates) {
7939
- if (typeof c !== "object" || c === null) {
7940
- shapedCandidates.push(c);
7941
- continue;
7942
- }
7943
- const fact = c;
7944
- const body = typeof fact.body === "string" ? fact.body : "";
7945
- if (body.length <= bodyTruncationChars) {
7946
- shapedCandidates.push(c);
7947
- continue;
7948
- }
7949
- if (typeof fact.id !== "string") {
7950
- shapedCandidates.push(c);
7951
- continue;
7952
- }
7953
- const originalBodyChars = body.length;
7954
- const prefix = safeSlice(body, 0, bodyTruncationChars);
7955
- const truncatedBodyChars = prefix.length;
7956
- const truncated = `${prefix}\u2026[truncated at ${truncatedBodyChars} chars, original was ${originalBodyChars}]`;
7957
- shapedCandidates.push({ ...fact, body: truncated });
7958
- degraded.push({ id: fact.id, originalBodyChars, truncatedBodyChars });
7959
- }
7960
- return { shapedCandidates, degraded };
7961
- }
7962
- function summaryOf(event) {
7963
- return event?.summary;
7964
- }
7965
- function toGroundingAnchor(anchor) {
7966
- if (typeof anchor !== "object" || anchor === null) return anchor;
7967
- const a = anchor;
7968
- return {
7969
- id: a.id,
7970
- title: a.title,
7971
- source_ref: a.source_ref,
7972
- body: typeof a.body === "string" ? safeSlice(a.body, 0, HEAL_ANCHOR_BODY_CHARS) : ""
7973
- };
7974
- }
7975
-
7976
- // src/utils/chunkingDefaults.ts
7977
- var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
7978
- var DEFAULT_CHUNK_OVERLAP = 400;
7979
-
7980
- // src/utils/contextCaps.ts
7981
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7982
- var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
7983
- var HEAL_MAX_PROMPT_CHARS = 4e4;
7984
- var OPS_MAX_EXTRACT_CHARS = 24e3;
7985
-
7986
- // src/config/context.ts
7987
- var DEFAULT_CHARS_PER_TOKEN = 4;
7988
- var DEFAULT_SAFETY_FRACTION = 0.9;
7989
- var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7990
- var OP_FLOOR = {
7991
- resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7992
- heal: HEAL_MAX_PROMPT_CHARS,
7993
- extract: OPS_MAX_EXTRACT_CHARS,
7994
- backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
7995
- };
7996
- function bad(key, value, why) {
7997
- return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
7998
- }
7999
- function resolveContextBudget(config) {
8000
- const context = config?.context;
8001
- if (!context || context.budget === void 0) {
8002
- return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
8003
- }
8004
- if (context.budget !== "legacy" && context.budget !== "declared") {
8005
- throw bad("budget", context.budget, "'legacy' or 'declared'");
8006
- }
8007
- if (context.budget === "legacy") {
8008
- return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
8009
- }
8010
- const window = context.contextWindowTokens;
8011
- if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
8012
- throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
8013
- }
8014
- const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
8015
- if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
8016
- throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
8017
- }
8018
- const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
8019
- if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
8020
- throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
8021
- }
8022
- const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
8023
- if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
8024
- throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
8025
- }
8026
- return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
8027
- }
8028
- function declaredPromptCap(budget, op) {
8029
- const derived = Math.floor(
8030
- (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
8031
- );
8032
- return Math.max(OP_FLOOR[op], derived);
8033
- }
8034
- function resolveMaxPromptChars(budget, op) {
8035
- if (budget.mode !== "declared") {
8036
- return OP_FLOOR[op];
8037
- }
8038
- if (op === "extract") {
8039
- const resolveDerived = declaredPromptCap(budget, "resolve");
8040
- const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
8041
- return Math.max(OP_FLOOR.extract, extractDerived);
8042
- }
8043
- return declaredPromptCap(budget, op);
8044
- }
8045
- function resolveDefaultChunkLength(budget) {
8046
- return DEFAULT_MAX_CHUNK_LENGTH;
8047
- }
8048
-
8049
- // src/utils/usage.ts
8050
- function estimateTokens(text) {
8051
- return Math.ceil(text.length / 4);
8052
- }
8053
- var UsageMeter = class {
8054
- constructor(budget) {
8055
- this.used = 0;
8056
- this.estimated = false;
8057
- if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
8058
- throw new TypeError("tokenBudget must be a finite number >= 0");
8059
- }
8060
- this.budget = budget;
8061
- }
8062
- get remaining() {
8063
- return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
8064
- }
8065
- fits(estimate) {
8066
- return estimate <= this.remaining;
8067
- }
8068
- record(r) {
8069
- this.used += r.inputTokens + r.outputTokens;
8070
- if (r.estimated) this.estimated = true;
8071
- }
8072
- };
8073
- var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
8074
- constructor(requiredEstimate, remaining) {
8075
- super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
8076
- this.name = "WikiBudgetExhausted";
8077
- this.requiredEstimate = requiredEstimate;
8078
- this.remaining = remaining;
8079
- Object.setPrototypeOf(this, _WikiBudgetExhausted.prototype);
8080
- }
8081
- };
8082
-
8083
- // src/utils/llmCall.ts
8084
- function validUsage(u) {
8085
- if (!u || typeof u !== "object") return false;
8086
- const { inputTokens, outputTokens } = u;
8087
- return [inputTokens, outputTokens].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0);
8088
- }
8089
- async function callLlm(options, ctx, prompts) {
8090
- const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
8091
- if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
8092
- throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
8093
- }
8094
- const provider = options.llmProvider;
8095
- const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
8096
- let text;
8097
- let reported;
8098
- if (typeof provider.generateTextWithUsage === "function") {
8099
- const result = await provider.generateTextWithUsage(params);
8100
- if (!result || typeof result.text !== "string") {
8101
- throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
8102
- }
8103
- text = result.text;
8104
- reported = validUsage(result.usage) ? result.usage : void 0;
8105
- } else {
8106
- text = await provider.generateText(params);
8107
- }
8108
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
8109
- ctx.meter?.record(record);
8110
- if (options.config?.reportLlmUsage === true) {
8111
- emitDiagnostic(options, {
8112
- code: "llm_usage",
8113
- operation: ctx.operation,
8114
- trigger: ctx.trigger,
8115
- entityId: ctx.entityId,
8116
- detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
8117
- });
8118
- }
8119
- return text;
8120
- }
8121
- async function callClassify(options, ctx, request) {
8122
- const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
8123
- if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
8124
- throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
8125
- }
8126
- const provider = options.llmProvider;
8127
- if (typeof provider.classify !== "function") {
8128
- throw new TypeError("callClassify requires a provider with classify()");
8129
- }
8130
- const response = await provider.classify(request);
8131
- const reported = validUsage(response?.usage) ? response.usage : void 0;
8132
- const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
8133
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
8134
- ctx.meter?.record(record);
8135
- if (options.config?.reportLlmUsage === true) {
8136
- emitDiagnostic(options, {
8137
- code: "llm_usage",
8138
- operation: ctx.operation,
8139
- trigger: ctx.trigger,
8140
- entityId: ctx.entityId,
8141
- detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
8142
- });
8660
+ for (const c of candidates) {
8661
+ if (typeof c !== "object" || c === null) {
8662
+ shapedCandidates.push(c);
8663
+ continue;
8664
+ }
8665
+ const fact = c;
8666
+ const body = typeof fact.body === "string" ? fact.body : "";
8667
+ if (body.length <= bodyTruncationChars) {
8668
+ shapedCandidates.push(c);
8669
+ continue;
8670
+ }
8671
+ if (typeof fact.id !== "string") {
8672
+ shapedCandidates.push(c);
8673
+ continue;
8674
+ }
8675
+ const originalBodyChars = body.length;
8676
+ const prefix = safeSlice(body, 0, bodyTruncationChars);
8677
+ const truncatedBodyChars = prefix.length;
8678
+ const truncated = `${prefix}\u2026[truncated at ${truncatedBodyChars} chars, original was ${originalBodyChars}]`;
8679
+ shapedCandidates.push({ ...fact, body: truncated });
8680
+ degraded.push({ id: fact.id, originalBodyChars, truncatedBodyChars });
8143
8681
  }
8144
- return response;
8682
+ return { shapedCandidates, degraded };
8683
+ }
8684
+ function summaryOf(event) {
8685
+ return event?.summary;
8686
+ }
8687
+ function toGroundingAnchor(anchor) {
8688
+ if (typeof anchor !== "object" || anchor === null) return anchor;
8689
+ const a = anchor;
8690
+ return {
8691
+ id: a.id,
8692
+ title: a.title,
8693
+ source_ref: a.source_ref,
8694
+ body: typeof a.body === "string" ? safeSlice(a.body, 0, HEAL_ANCHOR_BODY_CHARS) : ""
8695
+ };
8145
8696
  }
8146
8697
 
8147
8698
  // src/services/IngestionService.ts
@@ -8211,7 +8762,7 @@ var IngestionService = class {
8211
8762
  }
8212
8763
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
8213
8764
  if (chunks2.length === 0) return zeroChunkResult();
8214
- const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
8765
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
8215
8766
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
8216
8767
  if (diagnostic) {
8217
8768
  emitDiagnostic(this.options, {
@@ -8888,51 +9439,6 @@ var IngestionService = class {
8888
9439
  }
8889
9440
  };
8890
9441
 
8891
- // src/utils/classifier.ts
8892
- var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
8893
- function validateClassifierAnswer(response, key, question) {
8894
- try {
8895
- if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
8896
- const answers = response.answers;
8897
- if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
8898
- if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
8899
- const raw = answers[key];
8900
- if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
8901
- const a = raw;
8902
- if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
8903
- if (question.kind === "choice") {
8904
- if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
8905
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
8906
- const probs = a.probabilities;
8907
- if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
8908
- const probabilities = {};
8909
- for (const [k, v] of Object.entries(probs)) {
8910
- if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
8911
- probabilities[k] = v;
8912
- }
8913
- return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
8914
- }
8915
- if (question.kind === "binary") {
8916
- if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
8917
- return { ok: true, answer: { kind: "binary", probability: a.probability } };
8918
- }
8919
- const maxScore = question.levels.length - 1;
8920
- if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
8921
- return { ok: false, reason: "score_out_of_range" };
8922
- }
8923
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
8924
- if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
8925
- return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
8926
- } catch {
8927
- return { ok: false, reason: "malformed" };
8928
- }
8929
- }
8930
- function classifierStateForFact(fact) {
8931
- const parts = [fact.title, fact.body];
8932
- if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
8933
- return parts.join("\n\n");
8934
- }
8935
-
8936
9442
  // src/utils/shortlist.ts
8937
9443
  function shortlistScore(factTitle, factBody, row) {
8938
9444
  const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
@@ -9068,193 +9574,28 @@ var TemporalService = class {
9068
9574
  async expire(entityId, factId, options) {
9069
9575
  const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
9070
9576
  await this.db.withTransactionAsync(async (tx) => {
9071
- const old = await this.entryRepo.findTemporalRow(factId, tx);
9072
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
9073
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
9074
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
9075
- if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
9076
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
9077
- const start = old.valid_from ?? old.created_at;
9078
- if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
9079
- const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
9080
- if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
9081
- });
9082
- await this.searchService.syncEntries(entityId, [factId]);
9083
- this.searchService.evictCache(entityId);
9084
- }
9085
- async history(entityId, factId) {
9086
- const start = await this.entryRepo.findTemporalRow(factId);
9087
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
9088
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
9089
- const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
9090
- return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
9091
- }
9092
- };
9093
-
9094
- // src/utils/engineDefaults.ts
9095
- var DEFAULT_LIBRARIAN_STRATEGY = "ops";
9096
- var DEFAULT_MAINTENANCE_MODE = "deferred";
9097
- function resolveLibrarianStrategy(config) {
9098
- return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
9099
- }
9100
- function resolveMaintenanceMode(config) {
9101
- return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
9102
- }
9103
- function resolveContextBudgetOrThrow(config) {
9104
- return resolveContextBudget(config);
9105
- }
9106
- function changedDefaultWarnings(config) {
9107
- const warnings = [];
9108
- const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
9109
- if (hasThreshold && config?.maintenance === void 0) {
9110
- warnings.push(
9111
- "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
9112
- );
9113
- }
9114
- if (config?.prompts?.librarianSystemPrompt !== void 0) {
9115
- warnings.push(
9116
- "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
9117
- );
9118
- }
9119
- if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
9120
- warnings.push(
9121
- "[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
9122
- );
9123
- }
9124
- return warnings;
9125
- }
9126
- var warnedDefaults = /* @__PURE__ */ new Set();
9127
- function warnChangedDefaultsOnce(config) {
9128
- for (const message of changedDefaultWarnings(config)) {
9129
- if (warnedDefaults.has(message)) continue;
9130
- warnedDefaults.add(message);
9131
- console.warn(message);
9132
- }
9133
- }
9134
- function warnOnce(message) {
9135
- if (warnedDefaults.has(message)) return;
9136
- warnedDefaults.add(message);
9137
- console.warn(message);
9138
- }
9139
- function formatConfigValue(value) {
9140
- try {
9141
- const json = JSON.stringify(value);
9142
- return json ?? String(value);
9143
- } catch {
9144
- return `[unserializable: ${typeof value}]`;
9145
- }
9146
- }
9147
- var isTypingMode = (v) => v === "auto" || v === "llm";
9148
- var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
9149
- function resolveSystemOneTyping(config, classifierCallOption) {
9150
- const systemOne = config?.systemOne;
9151
- const legacy = config?.ontology?.backfillClassifier;
9152
- const systemOneValid = isTypingMode(systemOne?.typing);
9153
- const legacyValid = isTypingMode(legacy);
9154
- if (systemOne?.typing !== void 0 && !systemOneValid) {
9155
- warnOnce(
9156
- `[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9157
- );
9158
- }
9159
- if (legacy !== void 0 && !legacyValid) {
9160
- warnOnce(
9161
- `[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9162
- );
9163
- }
9164
- if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
9165
- warnOnce(
9166
- `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
9167
- );
9168
- }
9169
- return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
9170
- }
9171
- function resolveSystemOneEdges(config) {
9172
- const edges = config?.systemOne?.edges;
9173
- if (edges !== void 0 && !isTypingMode(edges)) {
9174
- warnOnce(
9175
- `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9176
- );
9177
- return "llm";
9178
- }
9179
- return edges ?? "llm";
9180
- }
9181
- function resolveSystemOneResolve(config) {
9182
- const resolve = config?.systemOne?.resolve;
9183
- if (resolve !== void 0 && !isTypingMode(resolve)) {
9184
- warnOnce(
9185
- `[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9186
- );
9187
- return "llm";
9188
- }
9189
- return resolve ?? "llm";
9190
- }
9191
- var DEFAULT_SHORTLIST_K = 10;
9192
- function resolveShortlistK(config) {
9193
- const k = config?.ontology?.shortlistK;
9194
- if (k === void 0) return DEFAULT_SHORTLIST_K;
9195
- if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
9196
- throw new Error(
9197
- `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
9198
- );
9199
- }
9200
- return k;
9201
- }
9202
- var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
9203
- function resolveTypingMinConfidence(config) {
9204
- const systemOneFloor = config?.systemOne?.minConfidence?.typing;
9205
- const legacyFloor = config?.ontology?.classifyMinConfidence;
9206
- const systemOneValid = isConfidenceFloor(systemOneFloor);
9207
- const legacyValid = isConfidenceFloor(legacyFloor);
9208
- if (systemOneFloor !== void 0 && !systemOneValid) {
9209
- warnOnce(
9210
- `[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
9211
- );
9212
- }
9213
- if (legacyFloor !== void 0 && !legacyValid) {
9214
- warnOnce(
9215
- `[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
9216
- );
9217
- }
9218
- return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
9219
- }
9220
- var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
9221
- function resolveEdgesMinConfidence(config) {
9222
- if (resolveSystemOneEdges(config) !== "auto") return void 0;
9223
- const floor = config?.systemOne?.minConfidence?.edges;
9224
- if (isEdgesFloor(floor)) return floor;
9225
- warnOnce(
9226
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
9227
- );
9228
- return void 0;
9229
- }
9230
- function resolveResolveMinConfidence(config) {
9231
- if (resolveSystemOneResolve(config) !== "auto") return void 0;
9232
- const floor = config?.systemOne?.minConfidence?.resolve;
9233
- if (isEdgesFloor(floor)) return floor;
9234
- warnOnce(
9235
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
9236
- );
9237
- return void 0;
9238
- }
9239
- function resolveSystemOneHealScreen(config) {
9240
- const healScreen = config?.systemOne?.healScreen;
9241
- if (healScreen !== void 0 && !isTypingMode(healScreen)) {
9242
- warnOnce(
9243
- `[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
9244
- );
9245
- return "llm";
9577
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
9578
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
9579
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
9580
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
9581
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
9582
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
9583
+ const start = old.valid_from ?? old.created_at;
9584
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
9585
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
9586
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
9587
+ });
9588
+ await this.searchService.syncEntries(entityId, [factId]);
9589
+ this.searchService.evictCache(entityId);
9246
9590
  }
9247
- return healScreen ?? "llm";
9248
- }
9249
- function resolveHealScreenMinConfidence(config) {
9250
- if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
9251
- const floor = config?.systemOne?.minConfidence?.healScreen;
9252
- if (isEdgesFloor(floor)) return floor;
9253
- warnOnce(
9254
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
9255
- );
9256
- return void 0;
9257
- }
9591
+ async history(entityId, factId) {
9592
+ const start = await this.entryRepo.findTemporalRow(factId);
9593
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
9594
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
9595
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
9596
+ return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
9597
+ }
9598
+ };
9258
9599
 
9259
9600
  // src/repositories/VectorRemovalRepository.ts
9260
9601
  var CHUNK2 = 500;
@@ -9815,166 +10156,6 @@ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
9815
10156
  return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
9816
10157
  }
9817
10158
 
9818
- // src/services/BoundedLlmCall.ts
9819
- var DEFAULT_BATCH_SIZE = 10;
9820
- var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
9821
- var OUTPUT_BUDGET_FRACTION = 0.8;
9822
- var TRUNCATION_PATTERNS = [
9823
- /truncat/i,
9824
- /token limit/i,
9825
- /max(imum)?[ _-]?tokens?/i,
9826
- /output limit/i,
9827
- /length limit/i,
9828
- /finish[_ ]?reason/i
9829
- ];
9830
- var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
9831
- 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;
9832
- var CONTEXT_OVERFLOW_PATTERNS = [
9833
- /maximum context length/i,
9834
- /context[_ ]?length[_ ]?exceeded/i,
9835
- /prompt is too long/i,
9836
- /input (token count|is too long)/i,
9837
- /exceeds? the (available )?context( size)?/i,
9838
- // Tail requires a context-window clause (context|maximum), NOT bare `token`:
9839
- // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
9840
- // classify as input overflow (it would split the batch and stamp a cooldown).
9841
- /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
9842
- /context limit/i,
9843
- // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
9844
- /\bcontext is full\b/i,
9845
- /too long for (the )?requested model/i,
9846
- // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
9847
- // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
9848
- /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
9849
- ];
9850
- function isContextOverflowError(err) {
9851
- const message = getErrorMessage(err);
9852
- if (message === void 0) return false;
9853
- if (RATE_LIMIT_PATTERN.test(message)) return false;
9854
- return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
9855
- }
9856
- function getErrorMessage(err) {
9857
- try {
9858
- return err instanceof Error ? err.message : String(err ?? "");
9859
- } catch {
9860
- return void 0;
9861
- }
9862
- }
9863
- function isTruncationError(err) {
9864
- const message = getErrorMessage(err);
9865
- if (message === void 0) return false;
9866
- if (RATE_LIMIT_PATTERN.test(message)) return false;
9867
- if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
9868
- return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
9869
- }
9870
- function isConfigError(err) {
9871
- const message = getErrorMessage(err);
9872
- if (message === void 0) return false;
9873
- if (RATE_LIMIT_PATTERN.test(message)) return false;
9874
- return EXCEEDS_LIMIT_PATTERN.test(message);
9875
- }
9876
- function initialBatchSize(maxOutputTokens) {
9877
- if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
9878
- return DEFAULT_BATCH_SIZE;
9879
- }
9880
- const estimate = Math.floor(
9881
- maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
9882
- );
9883
- return Math.max(DEFAULT_BATCH_SIZE, estimate);
9884
- }
9885
- var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
9886
- async function runBatched(args) {
9887
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
9888
- const results = [];
9889
- const skipped = [];
9890
- let batches = 0;
9891
- const settled = /* @__PURE__ */ new Set();
9892
- let budgetStop;
9893
- let batchSize = initialBatchSize(maxOutputTokens);
9894
- const trim = async (candidate) => {
9895
- const whole = await buildPrompt(candidate);
9896
- if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
9897
- return { batch: candidate, prompts: whole };
9898
- }
9899
- let low = 2;
9900
- let high = candidate.length - 1;
9901
- let best;
9902
- let bestPrompts;
9903
- while (low <= high) {
9904
- const mid = Math.floor((low + high) / 2);
9905
- const batch = candidate.slice(0, mid);
9906
- const prompts = await buildPrompt(batch);
9907
- if (promptLength(prompts) <= maxPromptChars) {
9908
- best = batch;
9909
- bestPrompts = prompts;
9910
- low = mid + 1;
9911
- } else {
9912
- high = mid - 1;
9913
- }
9914
- }
9915
- if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
9916
- const single = candidate.slice(0, 1);
9917
- return { batch: single, prompts: await buildPrompt(single) };
9918
- };
9919
- const onFailure = async (batch, err, attemptLevel, fromCall) => {
9920
- if (batch.length === 1) {
9921
- if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
9922
- await attempt(batch, void 0, attemptLevel + 1);
9923
- } else {
9924
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
9925
- skipped.push({ item: batch[0], reason });
9926
- settled.add(batch[0]);
9927
- onSkip?.(batch[0], err);
9928
- }
9929
- return;
9930
- }
9931
- if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
9932
- const mid = Math.ceil(batch.length / 2);
9933
- if (mid < batchSize) batchSize = mid;
9934
- let i = 0;
9935
- while (i < batch.length && !budgetStop) {
9936
- const size = Math.min(batchSize, batch.length - i);
9937
- const trimmed = await trim(batch.slice(i, i + size));
9938
- await attempt(trimmed.batch, trimmed.prompts);
9939
- i += trimmed.batch.length;
9940
- }
9941
- };
9942
- const attempt = async (batch, prebuilt, attemptLevel = 0) => {
9943
- if (budgetStop) return;
9944
- if (batch.length === 0) return;
9945
- const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
9946
- batches++;
9947
- let responseText;
9948
- try {
9949
- responseText = await call(prompts);
9950
- } catch (err) {
9951
- if (err instanceof WikiBudgetExhausted) {
9952
- budgetStop = { requiredEstimate: err.requiredEstimate };
9953
- return;
9954
- }
9955
- await onFailure(batch, err, attemptLevel, true);
9956
- return;
9957
- }
9958
- let result;
9959
- try {
9960
- result = parse(responseText, batch, prompts);
9961
- } catch (err) {
9962
- await onFailure(batch, err, attemptLevel, false);
9963
- return;
9964
- }
9965
- results.push(result);
9966
- for (const item of batch) settled.add(item);
9967
- };
9968
- let index = 0;
9969
- while (index < items.length && !budgetStop) {
9970
- const { batch, prompts } = await trim(items.slice(index, index + batchSize));
9971
- index += batch.length;
9972
- await attempt(batch, prompts, 0);
9973
- }
9974
- const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
9975
- return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
9976
- }
9977
-
9978
10159
  // src/services/librarian/constants.ts
9979
10160
  var FUZZY_THRESHOLD = 0.5;
9980
10161
  var MIN_TOKENS_TO_QUALIFY = 3;
@@ -9992,7 +10173,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
9992
10173
  tags: typeof rest.tags === "string" ? JSON.parse(rest.tags) : rest.tags
9993
10174
  };
9994
10175
  });
9995
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
10176
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
10177
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
10178
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
9996
10179
  const promptEvents = events.reverse();
9997
10180
  const librarianGrounding = deps.promptService.groundingFor("librarian");
9998
10181
  const { systemPrompt, userPrompt, groundingCorpus: librarianCorpus = [] } = deps.promptService.buildLibrarianPrompt(
@@ -10038,6 +10221,22 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
10038
10221
  if (valid) validTasks.push(valid);
10039
10222
  else diagBuffer.push({ ...diagBase, code: "task_rejected", detail: { itemIndex, reason: taskRejectionReason(raw) } });
10040
10223
  });
10224
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
10225
+ const typingOutcomes = /* @__PURE__ */ new Map();
10226
+ if (engaged && typingState && typingCounters) {
10227
+ const asked = validFacts.filter((f) => !volunteeredTypeResolves(f.okf_type, typingState.manifest));
10228
+ const outcomes = await classifyFactsForWrite(
10229
+ deps.options,
10230
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
10231
+ asked,
10232
+ typingState.manifest,
10233
+ resolveTypingMinConfidence(deps.options.config)
10234
+ );
10235
+ asked.forEach((f, i) => {
10236
+ typingOutcomes.set(f, outcomes[i]);
10237
+ tallyTypingOutcome(typingCounters, outcomes[i]);
10238
+ });
10239
+ }
10041
10240
  const now = Date.now();
10042
10241
  const insertedFacts = [];
10043
10242
  await deps.db.withTransactionAsync(async (tx) => {
@@ -10084,20 +10283,18 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
10084
10283
  }
10085
10284
  const ontologyFact = fact;
10086
10285
  const id = generateId("fact_");
10087
- const validationDrops = [];
10088
- const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
10286
+ const { normalized, drops: validationDrops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
10287
+ deps.ontologyService,
10288
+ ontologyFact,
10289
+ manifest,
10290
+ mode,
10291
+ typingOutcomes.get(fact),
10292
+ diagBase,
10293
+ id
10294
+ );
10089
10295
  for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
10090
- if (shouldEmitOntologyReceipt(mode)) {
10091
- for (const receipt of nodeTypeReceipts(
10092
- { entityId, operation: "librarian", trigger },
10093
- id,
10094
- ontologyFact.okf_type ?? "",
10095
- normalized.okf_type,
10096
- normalized.match
10097
- )) {
10098
- diagBuffer.push(receipt);
10099
- }
10100
- }
10296
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
10297
+ if (typedByClassifier && typingCounters) typingCounters.typed++;
10101
10298
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
10102
10299
  if (grounding?.diagnostic) {
10103
10300
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -10177,7 +10374,7 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
10177
10374
  }
10178
10375
  deps.searchService.evictCache(entityId);
10179
10376
  const processedThrough = events.length > 0 ? { at: events[events.length - 1].created_at, id: events[events.length - 1].id } : null;
10180
- const out = { processedThrough, factsWritten: insertedFacts.length };
10377
+ const out = { processedThrough, factsWritten: insertedFacts.length, ...typingCounters ? { typing: typingCounters } : {} };
10181
10378
  return out;
10182
10379
  };
10183
10380
 
@@ -10204,7 +10401,7 @@ var RESOLVE_RESERVE_FACTOR = 2;
10204
10401
  var MIN_SEGMENT_CHARS = 500;
10205
10402
  var MAX_SEGMENT_CALLS = 8;
10206
10403
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
10207
- async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
10404
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget, engaged = false) {
10208
10405
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
10209
10406
  if (events.length === 0) return { batch: [] };
10210
10407
  const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
@@ -10217,7 +10414,7 @@ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
10217
10414
  }
10218
10415
  let batch = labelEvents(events.slice(0, n));
10219
10416
  if (meter && meter.budget !== void 0) {
10220
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
10417
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
10221
10418
  for (; ; ) {
10222
10419
  const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
10223
10420
  if (meter.fits(need)) break;
@@ -10373,8 +10570,8 @@ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe
10373
10570
  return { ...merged, batch: [lone] };
10374
10571
  }
10375
10572
  }
10376
- async function runExtract(deps, ctx, batch) {
10377
- const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
10573
+ async function runExtract(deps, ctx, batch, engaged = false) {
10574
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(ctx.entityId, { engaged }) ?? null;
10378
10575
  return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
10379
10576
  }
10380
10577
  async function extractOnce(deps, ctx, ontologyContext, batch) {
@@ -10687,6 +10884,7 @@ async function applyOps(deps, ctx, input) {
10687
10884
  const failed = new Set(input.failed);
10688
10885
  const written = [];
10689
10886
  const updatedIds = [];
10887
+ const supersededIds = [];
10690
10888
  const now = Date.now();
10691
10889
  await deps.db.withTransactionAsync(async (tx) => {
10692
10890
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
@@ -10712,19 +10910,17 @@ async function applyOps(deps, ctx, input) {
10712
10910
  const title = overrides?.title ?? fact.title;
10713
10911
  const body = overrides?.body ?? fact.body;
10714
10912
  const id = generateId("fact_");
10715
- const drops = [];
10716
- const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
10717
- if (shouldEmitOntologyReceipt(mode)) {
10718
- for (const receipt of nodeTypeReceipts(
10719
- { entityId, operation: "librarian", trigger },
10720
- id,
10721
- typeof fact.okf_type === "string" ? fact.okf_type : "",
10722
- normalized.okf_type,
10723
- normalized.match
10724
- )) {
10725
- input.diagnostics.push(receipt);
10726
- }
10727
- }
10913
+ const { normalized, drops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
10914
+ deps.ontologyService,
10915
+ fact,
10916
+ manifest,
10917
+ mode,
10918
+ input.typing?.outcomes.get(g),
10919
+ diagBase,
10920
+ id
10921
+ );
10922
+ for (const receipt of doorReceipts) input.diagnostics.push(receipt);
10923
+ if (typedByClassifier && input.typing) input.typing.counters.typed++;
10728
10924
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
10729
10925
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
10730
10926
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -10809,6 +11005,7 @@ async function applyOps(deps, ctx, input) {
10809
11005
  titleIndex.delete(normalizeTitleKey(existing.title));
10810
11006
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
10811
11007
  updatedIds.push(existing.id);
11008
+ input.diagnostics.push({ ...diagBase, code: "librarian_rewritten", detail: { factId: existing.id } });
10812
11009
  continue;
10813
11010
  }
10814
11011
  }
@@ -10822,6 +11019,8 @@ async function applyOps(deps, ctx, input) {
10822
11019
  const newId = await insert(g, false, supersedeFrom, overrides);
10823
11020
  try {
10824
11021
  await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
11022
+ supersededIds.push(op.targetId);
11023
+ input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
10825
11024
  } catch (err) {
10826
11025
  if (!(err instanceof WikiSupersedeError)) throw err;
10827
11026
  input.diagnostics.push({
@@ -10861,7 +11060,7 @@ async function applyOps(deps, ctx, input) {
10861
11060
  await deps.taskRepo.upsert(taskObj, tx);
10862
11061
  }
10863
11062
  });
10864
- return { written, updatedIds };
11063
+ return { written, updatedIds, supersededIds };
10865
11064
  }
10866
11065
 
10867
11066
  // src/services/librarian/ops/index.ts
@@ -10870,7 +11069,9 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10870
11069
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
10871
11070
  await deps.seedWatermark(entityId);
10872
11071
  const wm = await deps.getWatermark(entityId);
10873
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
11072
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
11073
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
11074
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config), engaged);
10874
11075
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
10875
11076
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
10876
11077
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -10878,7 +11079,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10878
11079
  }
10879
11080
  let ex;
10880
11081
  try {
10881
- ex = await runExtract(deps, ctx, sel.batch);
11082
+ ex = await runExtract(deps, ctx, sel.batch, engaged);
10882
11083
  } catch (err) {
10883
11084
  if (err instanceof WikiBudgetExhausted) {
10884
11085
  return { processedThrough: null, factsWritten: 0, budgetStop: { requiredEstimate: err.requiredEstimate } };
@@ -10923,7 +11124,33 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10923
11124
  diagnostics.discard();
10924
11125
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
10925
11126
  }
10926
- const { written, updatedIds } = await applyOps(deps, ctx, {
11127
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
11128
+ const typingOutcomes = /* @__PURE__ */ new Map();
11129
+ if (engaged && typingState && typingCounters) {
11130
+ const failed = new Set(res.failed);
11131
+ const rejected = new Set(res.rejected);
11132
+ const asked = gated.filter((g) => {
11133
+ if (g.decision.kind === "noop") return false;
11134
+ if (volunteeredTypeResolves(g.candidate.fact.okf_type, typingState.manifest)) return false;
11135
+ if (g.decision.kind === "add" || failed.has(g)) return true;
11136
+ const op = res.ops.get(g);
11137
+ if (rejected.has(g) || !op) return true;
11138
+ return op.op !== "NOOP";
11139
+ });
11140
+ const outcomes = await classifyFactsForWrite(
11141
+ deps.options,
11142
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
11143
+ asked.map((g) => g.candidate.fact),
11144
+ typingState.manifest,
11145
+ resolveTypingMinConfidence(deps.options.config)
11146
+ );
11147
+ asked.forEach((g, n) => {
11148
+ typingOutcomes.set(g, outcomes[n]);
11149
+ tallyTypingOutcome(typingCounters, outcomes[n]);
11150
+ });
11151
+ }
11152
+ const { written, updatedIds, supersededIds } = await applyOps(deps, ctx, {
11153
+ typing: typingCounters ? { outcomes: typingOutcomes, counters: typingCounters } : void 0,
10927
11154
  gated,
10928
11155
  ops: res.ops,
10929
11156
  rejected: res.rejected,
@@ -10952,7 +11179,10 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10952
11179
  const last = ex.batch[ex.batch.length - 1].event;
10953
11180
  return {
10954
11181
  processedThrough: { at: last.created_at, id: last.id },
10955
- factsWritten: written.length + updatedIds.length
11182
+ factsWritten: written.length + updatedIds.length,
11183
+ ...typingCounters ? { typing: typingCounters } : {},
11184
+ rewrittenIds: updatedIds,
11185
+ supersededIds
10956
11186
  };
10957
11187
  };
10958
11188
 
@@ -10974,7 +11204,6 @@ async function runLibrarianStrategy(deps, ctx) {
10974
11204
  var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
10975
11205
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
10976
11206
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10977
- var CLASSIFIER_MAX_CHOICES = 255;
10978
11207
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
10979
11208
  var HEAL_BATCH_SIZE = 25;
10980
11209
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -12562,8 +12791,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12562
12791
  const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
12563
12792
  const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
12564
12793
  if (classifierMode === "auto" && typeof classify === "function") {
12565
- const slugs = effectiveManifest.node_types.map((n) => n.type);
12566
- if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
12794
+ if (isManifestRepresentable(effectiveManifest)) {
12567
12795
  const classifierRun = await this._runClassifierBackfill(
12568
12796
  entityId,
12569
12797
  candidates,
@@ -12812,12 +13040,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12812
13040
  const minConfidence = resolveTypingMinConfidence(this.options.config);
12813
13041
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
12814
13042
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
12815
- const question = {
12816
- kind: "choice",
12817
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
12818
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
12819
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
12820
- };
13043
+ const question = buildTypingQuestion(manifest);
12821
13044
  const edgeScreen = /* @__PURE__ */ new Map();
12822
13045
  if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
12823
13046
  const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
@@ -13305,8 +13528,8 @@ var MaintenanceScheduler = class {
13305
13528
  * `budget_too_small` > `complete`. `budget_too_small` means a job's smallest
13306
13529
  * unit needs more than the WHOLE budget — that job is skipped this run and
13307
13530
  * the run continues; `budget_exhausted` means a unit needs more than what
13308
- * REMAINS — the run stops. The token budget meters `generateText` calls
13309
- * only; embeddings are never metered.
13531
+ * REMAINS — the run stops. The token budget meters generation and classify
13532
+ * calls; embeddings are never metered.
13310
13533
  */
13311
13534
  async run(opts = {}) {
13312
13535
  if (opts.deadlineMs !== void 0 && (typeof opts.deadlineMs !== "number" || !Number.isFinite(opts.deadlineMs) || opts.deadlineMs < 0)) {
@@ -13387,7 +13610,12 @@ var MaintenanceScheduler = class {
13387
13610
  }
13388
13611
  st.report.librarianPasses++;
13389
13612
  st.report.factsWritten += r.factsWritten;
13613
+ if (r.typing) st.report.typedOnWrite = (st.report.typedOnWrite ?? 0) + r.typing.typed;
13390
13614
  progressed = true;
13615
+ if ((r.typing?.unattempted ?? 0) > 0) {
13616
+ stopped = exhaustedStop();
13617
+ break rounds;
13618
+ }
13391
13619
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
13392
13620
  if (await this.eventRepo.countAfter(entityId, wm) === 0) st.librarian = false;
13393
13621
  continue;
@@ -15723,6 +15951,33 @@ function buildOntologyPromptAppendix(mode, manifestJson) {
15723
15951
  ].filter(Boolean).join("\n");
15724
15952
  return { ontologyManifest: manifestJson, ontologyModeInstructions };
15725
15953
  }
15954
+ var WRITE_FACT_ONTOLOGY_FIELDS = `
15955
+ Each fact may optionally include:
15956
+ - "okf_type": string \u2014 must be one of the node_types in the manifest
15957
+ - "edges": [{ "edge_type": string, "target_title": string }] \u2014 target_title must match another fact's title in this response or existing memory
15958
+ - An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.
15959
+ Each node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \`target_title\`.`;
15960
+ var WRITE_EMERGENT_EXTRA = `
15961
+ You may also return "ontology_updates" to propose new types:
15962
+ "ontology_updates": {
15963
+ "node_types": [{ "type": "slug", "description": "...", "parent_type": "optional existing slug" }],
15964
+ "edge_types": [{ "type": "slug", "source_type": "...", "target_type": "...", "description": "..." }]
15965
+ }
15966
+ Only propose types not already in the manifest. Do not redefine existing types.`;
15967
+ function buildWriteOntologyAppendix(mode, manifestJson) {
15968
+ const strictRules = mode === "strict" ? "STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly." : "EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.";
15969
+ const fallback = "If okf_type or an edge is invalid, omit them rather than inventing unlisted types.";
15970
+ const ontologyModeInstructions = [
15971
+ "## Ontology constraints",
15972
+ strictRules,
15973
+ fallback,
15974
+ WRITE_FACT_ONTOLOGY_FIELDS,
15975
+ mode === "emergent" ? WRITE_EMERGENT_EXTRA : "",
15976
+ "Manifest:",
15977
+ manifestJson
15978
+ ].filter(Boolean).join("\n");
15979
+ return { site: "write", ontologyManifest: manifestJson, ontologyModeInstructions };
15980
+ }
15726
15981
 
15727
15982
  // src/services/OntologyService.ts
15728
15983
  var OntologyService = class {
@@ -15771,6 +16026,17 @@ var OntologyService = class {
15771
16026
  const manifestJson = JSON.stringify(manifest, null, 2);
15772
16027
  return buildOntologyPromptAppendix(mode, manifestJson);
15773
16028
  }
16029
+ /**
16030
+ * Ontology prompt context for the WRITE builders (specs/type-on-write §5).
16031
+ * `null` when the mode is `'off'` or when write-time typing is `engaged`
16032
+ * (the classifier types the fact, so the manifest leaves the write prompt).
16033
+ * Backfill keeps `buildPromptContext`.
16034
+ */
16035
+ async buildWritePromptContext(entityId, opts) {
16036
+ const { mode, manifest } = await this.getEffectiveState(entityId);
16037
+ if (mode === "off" || opts.engaged) return null;
16038
+ return buildWriteOntologyAppendix(mode, JSON.stringify(manifest, null, 2));
16039
+ }
15774
16040
  async mergeEmergentUpdates(entityId, updates, tx) {
15775
16041
  const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
15776
16042
  const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
@@ -16841,7 +17107,11 @@ var WikiMemory = class {
16841
17107
  */
16842
17108
  async getInstructions(entityId) {
16843
17109
  assertEntityId2(entityId);
16844
- const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
17110
+ const state = await this.ontologyService.getEffectiveState(entityId);
17111
+ const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);
17112
+ const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });
17113
+ const ingestContext = engaged ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false }) : writeContext;
17114
+ const backfillContext = await this.ontologyService.buildPromptContext(entityId);
16845
17115
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
16846
17116
  if (diagnostic) {
16847
17117
  emitDiagnostic(this.options, {
@@ -16852,7 +17122,7 @@ var WikiMemory = class {
16852
17122
  detail: diagnostic.detail
16853
17123
  });
16854
17124
  }
16855
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
17125
+ return this.promptService.buildInstructionTemplates(writeContext, resolveLibrarianStrategy(this.options.config), guidance, backfillContext, ingestContext);
16856
17126
  }
16857
17127
  /**
16858
17128
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -18612,6 +18882,7 @@ exports.resolveResolveMinConfidence = resolveResolveMinConfidence;
18612
18882
  exports.resolveSystemOneEdges = resolveSystemOneEdges;
18613
18883
  exports.resolveSystemOneHealScreen = resolveSystemOneHealScreen;
18614
18884
  exports.resolveSystemOneResolve = resolveSystemOneResolve;
18885
+ exports.resolveSystemOneTypeOnWrite = resolveSystemOneTypeOnWrite;
18615
18886
  exports.resolveSystemOneTyping = resolveSystemOneTyping;
18616
18887
  exports.resolveTypingMinConfidence = resolveTypingMinConfidence;
18617
18888
  exports.safeSlice = safeSlice;