@equationalapplications/core-llm-wiki 9.16.1 → 9.17.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/testing.js CHANGED
@@ -3105,13 +3105,19 @@ var UsageMeter = class {
3105
3105
  constructor(budget) {
3106
3106
  this.used = 0;
3107
3107
  this.estimated = false;
3108
+ this.heldTokens = 0;
3108
3109
  if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
3109
3110
  throw new TypeError("tokenBudget must be a finite number >= 0");
3110
3111
  }
3111
3112
  this.budget = budget;
3112
3113
  }
3114
+ /** Tokens held by in-flight reservations. */
3115
+ get reserved() {
3116
+ return this.heldTokens;
3117
+ }
3118
+ /** budget - used - reserved, clamped at 0; Infinity when unbounded. */
3113
3119
  get remaining() {
3114
- return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
3120
+ return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used - this.heldTokens);
3115
3121
  }
3116
3122
  fits(estimate) {
3117
3123
  return estimate <= this.remaining;
@@ -3120,6 +3126,33 @@ var UsageMeter = class {
3120
3126
  this.used += r.inputTokens + r.outputTokens;
3121
3127
  if (r.estimated) this.estimated = true;
3122
3128
  }
3129
+ /**
3130
+ * Admit a call on `estimate` (throws WikiBudgetExhausted when it does not
3131
+ * fit the unreserved remainder) and hold `max(estimate, hold)` tokens until
3132
+ * settle/release.
3133
+ */
3134
+ reserve(estimate, hold) {
3135
+ if (!this.fits(estimate)) throw new WikiBudgetExhausted(estimate, this.remaining);
3136
+ const handle = { _brand: "UsageReservation", hold: Math.max(estimate, hold ?? estimate), open: true };
3137
+ this.heldTokens += handle.hold;
3138
+ return handle;
3139
+ }
3140
+ /** Free the hold, then charge the real usage. A closed handle is a no-op. */
3141
+ settle(handle, actual) {
3142
+ if (!this.close(handle)) return;
3143
+ this.record(actual);
3144
+ }
3145
+ /** Free the hold and charge nothing. A closed handle is a no-op. */
3146
+ release(handle) {
3147
+ this.close(handle);
3148
+ }
3149
+ close(handle) {
3150
+ const h = handle;
3151
+ if (!h.open) return false;
3152
+ h.open = false;
3153
+ this.heldTokens -= h.hold;
3154
+ return true;
3155
+ }
3123
3156
  };
3124
3157
  var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
3125
3158
  constructor(requiredEstimate, remaining) {
@@ -3132,6 +3165,7 @@ var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
3132
3165
  };
3133
3166
 
3134
3167
  // src/utils/llmCall.ts
3168
+ var CLASSIFY_HOLD_FACTOR = 2;
3135
3169
  function validUsage(u) {
3136
3170
  if (!u || typeof u !== "object") return false;
3137
3171
  const { inputTokens, outputTokens } = u;
@@ -3139,25 +3173,29 @@ function validUsage(u) {
3139
3173
  }
3140
3174
  async function callLlm(options, ctx, prompts) {
3141
3175
  const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
3142
- if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
3143
- throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
3144
- }
3145
3176
  const provider = options.llmProvider;
3146
3177
  const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
3147
3178
  let text;
3148
- let reported;
3149
- if (typeof provider.generateTextWithUsage === "function") {
3150
- const result = await provider.generateTextWithUsage(params);
3151
- if (!result || typeof result.text !== "string") {
3152
- throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
3153
- }
3154
- text = result.text;
3155
- reported = validUsage(result.usage) ? result.usage : void 0;
3156
- } else {
3157
- text = await provider.generateText(params);
3179
+ let record;
3180
+ const reservation = ctx.meter?.reserve(promptEstimate);
3181
+ try {
3182
+ let reported;
3183
+ if (typeof provider.generateTextWithUsage === "function") {
3184
+ const result = await provider.generateTextWithUsage(params);
3185
+ if (!result || typeof result.text !== "string") {
3186
+ throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
3187
+ }
3188
+ text = result.text;
3189
+ reported = validUsage(result.usage) ? result.usage : void 0;
3190
+ } else {
3191
+ text = await provider.generateText(params);
3192
+ }
3193
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
3194
+ } catch (err) {
3195
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
3196
+ throw err;
3158
3197
  }
3159
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
3160
- ctx.meter?.record(record);
3198
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
3161
3199
  if (options.config?.reportLlmUsage === true) {
3162
3200
  emitDiagnostic(options, {
3163
3201
  code: "llm_usage",
@@ -3171,28 +3209,549 @@ async function callLlm(options, ctx, prompts) {
3171
3209
  }
3172
3210
  async function callClassify(options, ctx, request) {
3173
3211
  const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
3174
- if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
3175
- throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
3212
+ const provider = options.llmProvider;
3213
+ let response;
3214
+ let record;
3215
+ const reservation = ctx.meter?.reserve(inputEstimate, inputEstimate * CLASSIFY_HOLD_FACTOR);
3216
+ try {
3217
+ if (typeof provider.classify !== "function") {
3218
+ throw new TypeError("callClassify requires a provider with classify()");
3219
+ }
3220
+ response = await provider.classify(request);
3221
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
3222
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
3223
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
3224
+ } catch (err) {
3225
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
3226
+ throw err;
3227
+ }
3228
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
3229
+ if (options.config?.reportLlmUsage === true) {
3230
+ emitDiagnostic(options, {
3231
+ code: "llm_usage",
3232
+ operation: ctx.operation,
3233
+ trigger: ctx.trigger,
3234
+ entityId: ctx.entityId,
3235
+ detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
3236
+ });
3237
+ }
3238
+ return response;
3239
+ }
3240
+
3241
+ // src/utils/engineDefaults.ts
3242
+ var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3243
+ var DEFAULT_MAINTENANCE_MODE = "deferred";
3244
+ function resolveLibrarianStrategy(config) {
3245
+ return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
3246
+ }
3247
+ function resolveMaintenanceMode(config) {
3248
+ return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3249
+ }
3250
+ var warnedDefaults = /* @__PURE__ */ new Set();
3251
+ function warnOnce(message) {
3252
+ if (warnedDefaults.has(message)) return;
3253
+ warnedDefaults.add(message);
3254
+ console.warn(message);
3255
+ }
3256
+ function formatConfigValue(value) {
3257
+ try {
3258
+ const json = JSON.stringify(value);
3259
+ return json ?? String(value);
3260
+ } catch {
3261
+ return `[unserializable: ${typeof value}]`;
3262
+ }
3263
+ }
3264
+ var isTypingMode = (v) => v === "auto" || v === "llm";
3265
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3266
+ function resolveSystemOneTyping(config, classifierCallOption) {
3267
+ const systemOne = config?.systemOne;
3268
+ const legacy = config?.ontology?.backfillClassifier;
3269
+ const systemOneValid = isTypingMode(systemOne?.typing);
3270
+ const legacyValid = isTypingMode(legacy);
3271
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
3272
+ warnOnce(
3273
+ `[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.`
3274
+ );
3275
+ }
3276
+ if (legacy !== void 0 && !legacyValid) {
3277
+ warnOnce(
3278
+ `[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.`
3279
+ );
3280
+ }
3281
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
3282
+ warnOnce(
3283
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
3284
+ );
3285
+ }
3286
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3287
+ }
3288
+ function resolveSystemOneEdges(config) {
3289
+ const edges = config?.systemOne?.edges;
3290
+ if (edges !== void 0 && !isTypingMode(edges)) {
3291
+ warnOnce(
3292
+ `[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.`
3293
+ );
3294
+ return "llm";
3295
+ }
3296
+ return edges ?? "llm";
3297
+ }
3298
+ function resolveSystemOneResolve(config) {
3299
+ const resolve = config?.systemOne?.resolve;
3300
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
3301
+ warnOnce(
3302
+ `[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.`
3303
+ );
3304
+ return "llm";
3305
+ }
3306
+ return resolve ?? "llm";
3307
+ }
3308
+ var DEFAULT_SHORTLIST_K = 10;
3309
+ function resolveShortlistK(config) {
3310
+ const k = config?.ontology?.shortlistK;
3311
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
3312
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
3313
+ throw new Error(
3314
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
3315
+ );
3316
+ }
3317
+ return k;
3318
+ }
3319
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3320
+ function resolveTypingMinConfidence(config) {
3321
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
3322
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
3323
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
3324
+ const legacyValid = isConfidenceFloor(legacyFloor);
3325
+ if (systemOneFloor !== void 0 && !systemOneValid) {
3326
+ warnOnce(
3327
+ `[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.`
3328
+ );
3329
+ }
3330
+ if (legacyFloor !== void 0 && !legacyValid) {
3331
+ warnOnce(
3332
+ `[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.`
3333
+ );
3334
+ }
3335
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3336
+ }
3337
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
3338
+ function resolveEdgesMinConfidence(config) {
3339
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
3340
+ const floor = config?.systemOne?.minConfidence?.edges;
3341
+ if (isEdgesFloor(floor)) return floor;
3342
+ warnOnce(
3343
+ 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.`
3344
+ );
3345
+ return void 0;
3346
+ }
3347
+ function resolveResolveMinConfidence(config) {
3348
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
3349
+ const floor = config?.systemOne?.minConfidence?.resolve;
3350
+ if (isEdgesFloor(floor)) return floor;
3351
+ warnOnce(
3352
+ 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.`
3353
+ );
3354
+ return void 0;
3355
+ }
3356
+ function resolveSystemOneHealScreen(config) {
3357
+ const healScreen = config?.systemOne?.healScreen;
3358
+ if (healScreen !== void 0 && !isTypingMode(healScreen)) {
3359
+ warnOnce(
3360
+ `[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.`
3361
+ );
3362
+ return "llm";
3363
+ }
3364
+ return healScreen ?? "llm";
3365
+ }
3366
+ function resolveSystemOneTypeOnWrite(config) {
3367
+ const typeOnWrite = config?.systemOne?.typeOnWrite;
3368
+ if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
3369
+ warnOnce(
3370
+ `[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.`
3371
+ );
3372
+ return "llm";
3373
+ }
3374
+ return typeOnWrite ?? "llm";
3375
+ }
3376
+ function resolveSystemOneTypeOnIngest(config) {
3377
+ const typeOnIngest = config?.systemOne?.typeOnIngest;
3378
+ if (typeOnIngest !== void 0 && !isTypingMode(typeOnIngest)) {
3379
+ warnOnce(
3380
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnIngest\` is ${formatConfigValue(typeOnIngest)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3381
+ );
3382
+ return "llm";
3383
+ }
3384
+ return typeOnIngest ?? "llm";
3385
+ }
3386
+ function resolveHealScreenMinConfidence(config) {
3387
+ if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
3388
+ const floor = config?.systemOne?.minConfidence?.healScreen;
3389
+ if (isEdgesFloor(floor)) return floor;
3390
+ warnOnce(
3391
+ 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.`
3392
+ );
3393
+ return void 0;
3394
+ }
3395
+
3396
+ // src/utils/classifier.ts
3397
+ var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3398
+ function validateClassifierAnswer(response, key, question) {
3399
+ try {
3400
+ if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
3401
+ const answers = response.answers;
3402
+ if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
3403
+ if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
3404
+ const raw = answers[key];
3405
+ if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
3406
+ const a = raw;
3407
+ if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
3408
+ if (question.kind === "choice") {
3409
+ if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
3410
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3411
+ const probs = a.probabilities;
3412
+ if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
3413
+ const probabilities = {};
3414
+ for (const [k, v] of Object.entries(probs)) {
3415
+ if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
3416
+ probabilities[k] = v;
3417
+ }
3418
+ return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
3419
+ }
3420
+ if (question.kind === "binary") {
3421
+ if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
3422
+ return { ok: true, answer: { kind: "binary", probability: a.probability } };
3423
+ }
3424
+ const maxScore = question.levels.length - 1;
3425
+ if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
3426
+ return { ok: false, reason: "score_out_of_range" };
3427
+ }
3428
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3429
+ if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
3430
+ return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
3431
+ } catch {
3432
+ return { ok: false, reason: "malformed" };
3433
+ }
3434
+ }
3435
+ function classifierStateForFact(fact) {
3436
+ const parts = [fact.title, fact.body];
3437
+ if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
3438
+ return parts.join("\n\n");
3439
+ }
3440
+
3441
+ // src/services/BoundedLlmCall.ts
3442
+ var DEFAULT_BATCH_SIZE = 10;
3443
+ var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
3444
+ var OUTPUT_BUDGET_FRACTION = 0.8;
3445
+ var TRUNCATION_PATTERNS = [
3446
+ /truncat/i,
3447
+ /token limit/i,
3448
+ /max(imum)?[ _-]?tokens?/i,
3449
+ /output limit/i,
3450
+ /length limit/i,
3451
+ /finish[_ ]?reason/i
3452
+ ];
3453
+ var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
3454
+ 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;
3455
+ var CONTEXT_OVERFLOW_PATTERNS = [
3456
+ /maximum context length/i,
3457
+ /context[_ ]?length[_ ]?exceeded/i,
3458
+ /prompt is too long/i,
3459
+ /input (token count|is too long)/i,
3460
+ /exceeds? the (available )?context( size)?/i,
3461
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
3462
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
3463
+ // classify as input overflow (it would split the batch and stamp a cooldown).
3464
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
3465
+ /context limit/i,
3466
+ // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
3467
+ /\bcontext is full\b/i,
3468
+ /too long for (the )?requested model/i,
3469
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
3470
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
3471
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
3472
+ ];
3473
+ function isContextOverflowError(err) {
3474
+ const message = getErrorMessage(err);
3475
+ if (message === void 0) return false;
3476
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3477
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
3478
+ }
3479
+ function getErrorMessage(err) {
3480
+ try {
3481
+ return err instanceof Error ? err.message : String(err ?? "");
3482
+ } catch {
3483
+ return void 0;
3484
+ }
3485
+ }
3486
+ function isTruncationError(err) {
3487
+ const message = getErrorMessage(err);
3488
+ if (message === void 0) return false;
3489
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3490
+ if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
3491
+ return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
3492
+ }
3493
+ function isConfigError(err) {
3494
+ const message = getErrorMessage(err);
3495
+ if (message === void 0) return false;
3496
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3497
+ return EXCEEDS_LIMIT_PATTERN.test(message);
3498
+ }
3499
+ function initialBatchSize(maxOutputTokens) {
3500
+ if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
3501
+ return DEFAULT_BATCH_SIZE;
3502
+ }
3503
+ const estimate = Math.floor(
3504
+ maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
3505
+ );
3506
+ return Math.max(DEFAULT_BATCH_SIZE, estimate);
3507
+ }
3508
+ var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
3509
+ async function runBatched(args) {
3510
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
3511
+ const results = [];
3512
+ const skipped = [];
3513
+ let batches = 0;
3514
+ const settled = /* @__PURE__ */ new Set();
3515
+ let budgetStop;
3516
+ let batchSize = initialBatchSize(maxOutputTokens);
3517
+ const trim = async (candidate) => {
3518
+ const whole = await buildPrompt(candidate);
3519
+ if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
3520
+ return { batch: candidate, prompts: whole };
3521
+ }
3522
+ let low = 2;
3523
+ let high = candidate.length - 1;
3524
+ let best;
3525
+ let bestPrompts;
3526
+ while (low <= high) {
3527
+ const mid = Math.floor((low + high) / 2);
3528
+ const batch = candidate.slice(0, mid);
3529
+ const prompts = await buildPrompt(batch);
3530
+ if (promptLength(prompts) <= maxPromptChars) {
3531
+ best = batch;
3532
+ bestPrompts = prompts;
3533
+ low = mid + 1;
3534
+ } else {
3535
+ high = mid - 1;
3536
+ }
3537
+ }
3538
+ if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
3539
+ const single = candidate.slice(0, 1);
3540
+ return { batch: single, prompts: await buildPrompt(single) };
3541
+ };
3542
+ const onFailure = async (batch, err, attemptLevel, fromCall) => {
3543
+ if (batch.length === 1) {
3544
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
3545
+ await attempt(batch, void 0, attemptLevel + 1);
3546
+ } else {
3547
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
3548
+ skipped.push({ item: batch[0], reason });
3549
+ settled.add(batch[0]);
3550
+ onSkip?.(batch[0], err);
3551
+ }
3552
+ return;
3553
+ }
3554
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
3555
+ const mid = Math.ceil(batch.length / 2);
3556
+ if (mid < batchSize) batchSize = mid;
3557
+ let i = 0;
3558
+ while (i < batch.length && !budgetStop) {
3559
+ const size = Math.min(batchSize, batch.length - i);
3560
+ const trimmed = await trim(batch.slice(i, i + size));
3561
+ await attempt(trimmed.batch, trimmed.prompts);
3562
+ i += trimmed.batch.length;
3563
+ }
3564
+ };
3565
+ const attempt = async (batch, prebuilt, attemptLevel = 0) => {
3566
+ if (budgetStop) return;
3567
+ if (batch.length === 0) return;
3568
+ const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
3569
+ batches++;
3570
+ let responseText;
3571
+ try {
3572
+ responseText = await call(prompts);
3573
+ } catch (err) {
3574
+ if (err instanceof WikiBudgetExhausted) {
3575
+ budgetStop = { requiredEstimate: err.requiredEstimate };
3576
+ return;
3577
+ }
3578
+ await onFailure(batch, err, attemptLevel, true);
3579
+ return;
3580
+ }
3581
+ let result;
3582
+ try {
3583
+ result = parse(responseText, batch, prompts);
3584
+ } catch (err) {
3585
+ await onFailure(batch, err, attemptLevel, false);
3586
+ return;
3587
+ }
3588
+ results.push(result);
3589
+ for (const item of batch) settled.add(item);
3590
+ };
3591
+ let index = 0;
3592
+ while (index < items.length && !budgetStop) {
3593
+ const { batch, prompts } = await trim(items.slice(index, index + batchSize));
3594
+ index += batch.length;
3595
+ await attempt(batch, prompts, 0);
3596
+ }
3597
+ const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
3598
+ return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
3599
+ }
3600
+
3601
+ // src/services/typing/typeOnWrite.ts
3602
+ var CLASSIFIER_MAX_CHOICES = 255;
3603
+ function isManifestRepresentable(manifest) {
3604
+ const slugs = manifest.node_types.map((n) => n.type);
3605
+ return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
3606
+ }
3607
+ function typingEngages(site, provider, mode, manifest) {
3608
+ return site === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
3609
+ }
3610
+ function canEngageWriteTyping(config, provider, mode, manifest) {
3611
+ return typingEngages(resolveSystemOneTypeOnWrite(config), provider, mode, manifest);
3612
+ }
3613
+ function canEngageIngestTyping(config, provider, mode, manifest) {
3614
+ return typingEngages(resolveSystemOneTypeOnIngest(config), provider, mode, manifest);
3615
+ }
3616
+ function buildTypingQuestion(manifest) {
3617
+ return {
3618
+ kind: "choice",
3619
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
3620
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
3621
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
3622
+ };
3623
+ }
3624
+ function volunteeredTypeResolves(rawOkfType, manifest) {
3625
+ return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
3626
+ }
3627
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor, opts) {
3628
+ const question = buildTypingQuestion(manifest);
3629
+ const rawConcurrency = opts?.concurrency ?? options.config?.chunkConcurrency ?? 1;
3630
+ const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
3631
+ let stopped = false;
3632
+ return withConcurrency(
3633
+ facts.map((fact) => async () => {
3634
+ if (stopped) return { kind: "unattempted" };
3635
+ let response;
3636
+ try {
3637
+ response = await callClassify(
3638
+ options,
3639
+ { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
3640
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
3641
+ );
3642
+ } catch (err) {
3643
+ if (err instanceof WikiBudgetExhausted) {
3644
+ stopped = true;
3645
+ return { kind: "unattempted" };
3646
+ }
3647
+ if (isContextOverflowError(err)) return { kind: "overflow_skip" };
3648
+ return { kind: "threw" };
3649
+ }
3650
+ const checked = validateClassifierAnswer(response, "okf_type", question);
3651
+ if (!checked.ok) return { kind: "invalid", reason: checked.reason };
3652
+ if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
3653
+ if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
3654
+ if (checked.answer.confidence < floor) return { kind: "low_confidence" };
3655
+ return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
3656
+ }),
3657
+ concurrency
3658
+ );
3659
+ }
3660
+ function toIngestCounters(c) {
3661
+ const { unattempted: _unattempted, ...rest } = c;
3662
+ return rest;
3663
+ }
3664
+ function emptyTypingCounters() {
3665
+ return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
3666
+ }
3667
+ function tallyTypingOutcome(c, o) {
3668
+ switch (o.kind) {
3669
+ case "unattempted":
3670
+ c.unattempted++;
3671
+ return;
3672
+ case "accepted":
3673
+ c.asked++;
3674
+ return;
3675
+ case "abstain":
3676
+ c.asked++;
3677
+ c.abstained++;
3678
+ return;
3679
+ case "low_confidence":
3680
+ c.asked++;
3681
+ c.lowConfidence++;
3682
+ return;
3683
+ case "invalid":
3684
+ case "threw":
3685
+ c.asked++;
3686
+ c.invalid++;
3687
+ return;
3688
+ case "overflow_skip":
3689
+ c.asked++;
3690
+ c.skipped++;
3691
+ return;
3692
+ }
3693
+ }
3694
+ function typingOutcomeReceipt(base, factId, outcome) {
3695
+ switch (outcome.kind) {
3696
+ case "abstain":
3697
+ return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
3698
+ case "low_confidence":
3699
+ return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
3700
+ case "invalid":
3701
+ return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
3702
+ case "threw":
3703
+ return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
3704
+ case "overflow_skip":
3705
+ return { ...base, code: "context_overflow_skipped", detail: { factId } };
3706
+ default:
3707
+ return null;
3708
+ }
3709
+ }
3710
+ function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
3711
+ const drops = [];
3712
+ const receipts = [];
3713
+ const emit = shouldEmitOntologyReceipt(mode);
3714
+ let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
3715
+ if (emit) {
3716
+ receipts.push(...nodeTypeReceipts(
3717
+ base,
3718
+ factId,
3719
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
3720
+ normalized.okf_type,
3721
+ normalized.match
3722
+ ));
3723
+ }
3724
+ let typedByClassifier = false;
3725
+ if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
3726
+ const second = ontology?.validateAndNormalizeFact(
3727
+ { ...fact, okf_type: outcome.okfType, edges: [] },
3728
+ manifest,
3729
+ { strict: false }
3730
+ ) ?? { okf_type: null};
3731
+ if (emit) {
3732
+ receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
3733
+ }
3734
+ normalized = { okf_type: second.okf_type, edges: [] };
3735
+ if (second.okf_type) {
3736
+ typedByClassifier = true;
3737
+ if (emit) {
3738
+ receipts.push({
3739
+ ...base,
3740
+ code: "node_type_assigned",
3741
+ detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
3742
+ });
3743
+ }
3744
+ }
3745
+ } else if (normalized.okf_type) {
3746
+ if (emit) {
3747
+ receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
3748
+ }
3176
3749
  }
3177
- const provider = options.llmProvider;
3178
- if (typeof provider.classify !== "function") {
3179
- throw new TypeError("callClassify requires a provider with classify()");
3180
- }
3181
- const response = await provider.classify(request);
3182
- const reported = validUsage(response?.usage) ? response.usage : void 0;
3183
- const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
3184
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
3185
- ctx.meter?.record(record);
3186
- if (options.config?.reportLlmUsage === true) {
3187
- emitDiagnostic(options, {
3188
- code: "llm_usage",
3189
- operation: ctx.operation,
3190
- trigger: ctx.trigger,
3191
- entityId: ctx.entityId,
3192
- detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
3193
- });
3750
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
3751
+ const r = typingOutcomeReceipt(base, factId, outcome);
3752
+ if (r) receipts.push(r);
3194
3753
  }
3195
- return response;
3754
+ return { normalized, drops, receipts, typedByClassifier };
3196
3755
  }
3197
3756
 
3198
3757
  // src/services/IngestionService.ts
@@ -3262,7 +3821,9 @@ var IngestionService = class {
3262
3821
  }
3263
3822
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3264
3823
  if (chunks2.length === 0) return zeroChunkResult();
3265
- const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
3824
+ const hoistedState = await this.ontologyService?.getEffectiveState(entityId) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
3825
+ const engaged = this.ontologyService !== void 0 && canEngageIngestTyping(this.options.config, this.options.llmProvider, hoistedState.mode, hoistedState.manifest);
3826
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
3266
3827
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3267
3828
  if (diagnostic) {
3268
3829
  emitDiagnostic(this.options, {
@@ -3418,16 +3979,42 @@ var IngestionService = class {
3418
3979
  chunks: chunks2.length
3419
3980
  });
3420
3981
  }
3982
+ const typing = { outcomes: /* @__PURE__ */ new Map(), counters: emptyTypingCounters() };
3983
+ let hashHeldElsewhere = false;
3984
+ if (engaged && failedChunks === 0 && onDuplicateHash === "ingest") {
3985
+ const holder = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
3986
+ hashHeldElsewhere = holder !== null && holder !== sourceRef;
3987
+ }
3988
+ if (engaged && !hashHeldElsewhere) {
3989
+ const asked = [];
3990
+ for (const slot of orderedChunkFacts) {
3991
+ for (const fact of slot.facts) {
3992
+ if (!volunteeredTypeResolves(fact.okf_type, hoistedState.manifest)) asked.push(fact);
3993
+ }
3994
+ }
3995
+ const outcomes = await classifyFactsForWrite(
3996
+ this.options,
3997
+ { entityId, trigger: "call", operation: "ingest" },
3998
+ asked,
3999
+ hoistedState.manifest,
4000
+ resolveTypingMinConfidence(this.options.config),
4001
+ { concurrency: chunkConcurrency }
4002
+ );
4003
+ asked.forEach((fact, i) => {
4004
+ typing.outcomes.set(fact, outcomes[i]);
4005
+ tallyTypingOutcome(typing.counters, outcomes[i]);
4006
+ });
4007
+ }
3421
4008
  const insertedFacts = [];
3422
4009
  const deletedSourceFactIds = [];
3423
4010
  try {
3424
4011
  if (failedChunks === 0) {
3425
4012
  const fullResult = await this.db.withTransactionAsync(async (tx) => {
3426
- return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger);
4013
+ return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger, typing);
3427
4014
  });
3428
4015
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
3429
4016
  insertedFacts.push(...fullResult.insertedFacts);
3430
- if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
4017
+ if (hoistedState.mode !== "off" && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
3431
4018
  diagBuffer.push({
3432
4019
  entityId,
3433
4020
  operation: "ingest",
@@ -3440,7 +4027,7 @@ var IngestionService = class {
3440
4027
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
3441
4028
  const flat = [];
3442
4029
  for (const slot of orderedChunkFacts) flat.push(...slot.facts);
3443
- return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger);
4030
+ return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger, typing);
3444
4031
  });
3445
4032
  insertedFacts.push(...partialResult.insertedDescriptors);
3446
4033
  }
@@ -3492,6 +4079,7 @@ var IngestionService = class {
3492
4079
  failedChunks
3493
4080
  };
3494
4081
  if (failedChunks > 0) result.parseFailures = failures;
4082
+ if (engaged) result.typing = toIngestCounters(typing.counters);
3495
4083
  return result;
3496
4084
  } finally {
3497
4085
  releaseIngestLocks();
@@ -3701,10 +4289,11 @@ var IngestionService = class {
3701
4289
  * On the partial path the caller never invokes this method; the empty
3702
4290
  * arrays stay empty.
3703
4291
  */
3704
- async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4292
+ async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
3705
4293
  const deletedSourceFactIds = [];
3706
4294
  const insertedFacts = [];
3707
4295
  const nodeTrust = /* @__PURE__ */ new Map();
4296
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3708
4297
  deletedSourceFactIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false));
3709
4298
  const titleIndex = /* @__PURE__ */ new Map();
3710
4299
  const existingFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx, sourceRef);
@@ -3718,6 +4307,7 @@ var IngestionService = class {
3718
4307
  let { mode, manifest } = ontologyState;
3719
4308
  const hostNodes = [];
3720
4309
  const rawEdgeRequests = [];
4310
+ const typedAtDoor = [];
3721
4311
  const now = Date.now();
3722
4312
  for (const { facts, ontology_updates } of orderedChunkFacts) {
3723
4313
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
@@ -3737,14 +4327,15 @@ var IngestionService = class {
3737
4327
  for (const fact of facts) {
3738
4328
  const ontologyFact = fact;
3739
4329
  const id = generateId("fact_");
3740
- const validationDrops = [];
3741
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
3742
- for (const drop of validationDrops) {
4330
+ const outcome = typing?.outcomes.get(fact);
4331
+ const slot = normalizeForWrite(this.ontologyService, ontologyFact, manifest, mode, outcome, diagBase, id);
4332
+ const normalized = slot.normalized;
4333
+ for (const drop of slot.drops) {
3743
4334
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3744
4335
  }
3745
- hostNodes.push({
4336
+ const hostNode = {
3746
4337
  id,
3747
- type: ontologyFact.okf_type ?? "",
4338
+ type: "",
3748
4339
  title: fact.title,
3749
4340
  body: fact.body,
3750
4341
  // Forward the LLM-extracted tags/confidence through the
@@ -3756,18 +4347,20 @@ var IngestionService = class {
3756
4347
  // 'certain' as documented.
3757
4348
  tags: fact.tags,
3758
4349
  confidence: fact.confidence
3759
- });
4350
+ };
4351
+ hostNodes.push(hostNode);
4352
+ typedAtDoor.push({ node: hostNode, fact: ontologyFact, id, outcome, slotType: normalized.okf_type });
3760
4353
  const locator = factLedger.get(fact);
3761
4354
  if (locator?.verdict) {
3762
- const outcome = groundingOutcome(locator.verdict, now);
3763
- nodeTrust.set(id, outcome.trust);
3764
- if (outcome.diagnostic) {
4355
+ const outcome2 = groundingOutcome(locator.verdict, now);
4356
+ nodeTrust.set(id, outcome2.trust);
4357
+ if (outcome2.diagnostic) {
3765
4358
  diagBuffer.push({
3766
4359
  entityId,
3767
4360
  operation: "ingest",
3768
4361
  trigger: "call",
3769
- code: outcome.diagnostic.code,
3770
- detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
4362
+ code: outcome2.diagnostic.code,
4363
+ detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome2.diagnostic.reason }
3771
4364
  });
3772
4365
  }
3773
4366
  }
@@ -3778,6 +4371,18 @@ var IngestionService = class {
3778
4371
  }
3779
4372
  }
3780
4373
  }
4374
+ const doorReceipts = [];
4375
+ for (const { node, fact, id, outcome, slotType } of typedAtDoor) {
4376
+ const final = normalizeForWrite(this.ontologyService, fact, manifest, mode, outcome, diagBase, id);
4377
+ for (const receipt of final.receipts) {
4378
+ doorReceipts.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
4379
+ }
4380
+ node.type = final.normalized.okf_type ?? "";
4381
+ if (final.typedByClassifier && typing) typing.counters.typed++;
4382
+ if (outcome?.kind === "accepted" && final.normalized.okf_type !== slotType) {
4383
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: final.normalized.okf_type });
4384
+ }
4385
+ }
3781
4386
  const hostEdges = [];
3782
4387
  for (const req of rawEdgeRequests) {
3783
4388
  const resolveDrops = [];
@@ -3798,6 +4403,7 @@ var IngestionService = class {
3798
4403
  hostEdges.push({ type: e.edge_type, sourceId: e.source_id, targetId: e.target_id });
3799
4404
  }
3800
4405
  }
4406
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
3801
4407
  await this.upsertGraphCore(
3802
4408
  entityId,
3803
4409
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
@@ -3826,7 +4432,7 @@ var IngestionService = class {
3826
4432
  * Runs INSIDE the caller's `tx`. Does not open a nested transaction.
3827
4433
  * Returns `{ inserted, skippedDuplicate }` for observability.
3828
4434
  */
3829
- async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4435
+ async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
3830
4436
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
3831
4437
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
3832
4438
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
@@ -3837,6 +4443,7 @@ var IngestionService = class {
3837
4443
  for (const f of indexedFacts) {
3838
4444
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
3839
4445
  }
4446
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3840
4447
  const pendingEdges = [];
3841
4448
  let inserted = 0;
3842
4449
  let skippedDuplicate = 0;
@@ -3863,22 +4470,22 @@ var IngestionService = class {
3863
4470
  });
3864
4471
  }
3865
4472
  const ontologyFact = fact;
3866
- const validationDrops = [];
3867
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
4473
+ const { normalized, drops: validationDrops, receipts, typedByClassifier } = normalizeForWrite(
4474
+ this.ontologyService,
4475
+ ontologyFact,
4476
+ manifest,
4477
+ mode,
4478
+ typing?.outcomes.get(fact),
4479
+ diagBase,
4480
+ id
4481
+ );
3868
4482
  for (const drop of validationDrops) {
3869
4483
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3870
4484
  }
3871
- if (shouldEmitOntologyReceipt(mode)) {
3872
- for (const receipt of nodeTypeReceipts(
3873
- { entityId, operation: "ingest", trigger: "call" },
3874
- id,
3875
- ontologyFact.okf_type ?? "",
3876
- normalized.okf_type,
3877
- normalized.match
3878
- )) {
3879
- diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3880
- }
4485
+ for (const receipt of receipts) {
4486
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3881
4487
  }
4488
+ if (typedByClassifier && typing) typing.counters.typed++;
3882
4489
  if (normalized.edges.length > 0) {
3883
4490
  pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
3884
4491
  }
@@ -3939,51 +4546,6 @@ var IngestionService = class {
3939
4546
  }
3940
4547
  };
3941
4548
 
3942
- // src/utils/classifier.ts
3943
- var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3944
- function validateClassifierAnswer(response, key, question) {
3945
- try {
3946
- if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
3947
- const answers = response.answers;
3948
- if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
3949
- if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
3950
- const raw = answers[key];
3951
- if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
3952
- const a = raw;
3953
- if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
3954
- if (question.kind === "choice") {
3955
- if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
3956
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3957
- const probs = a.probabilities;
3958
- if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
3959
- const probabilities = {};
3960
- for (const [k, v] of Object.entries(probs)) {
3961
- if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
3962
- probabilities[k] = v;
3963
- }
3964
- return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
3965
- }
3966
- if (question.kind === "binary") {
3967
- if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
3968
- return { ok: true, answer: { kind: "binary", probability: a.probability } };
3969
- }
3970
- const maxScore = question.levels.length - 1;
3971
- if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
3972
- return { ok: false, reason: "score_out_of_range" };
3973
- }
3974
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3975
- if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
3976
- return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
3977
- } catch {
3978
- return { ok: false, reason: "malformed" };
3979
- }
3980
- }
3981
- function classifierStateForFact(fact) {
3982
- const parts = [fact.title, fact.body];
3983
- if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
3984
- return parts.join("\n\n");
3985
- }
3986
-
3987
4549
  // src/utils/shortlist.ts
3988
4550
  function shortlistScore(factTitle, factBody, row) {
3989
4551
  const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
@@ -4196,154 +4758,9 @@ var TemporalService = class {
4196
4758
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4197
4759
  const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4198
4760
  const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
4199
- 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));
4200
- }
4201
- };
4202
-
4203
- // src/utils/engineDefaults.ts
4204
- var DEFAULT_LIBRARIAN_STRATEGY = "ops";
4205
- var DEFAULT_MAINTENANCE_MODE = "deferred";
4206
- function resolveLibrarianStrategy(config) {
4207
- return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
4208
- }
4209
- function resolveMaintenanceMode(config) {
4210
- return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
4211
- }
4212
- var warnedDefaults = /* @__PURE__ */ new Set();
4213
- function warnOnce(message) {
4214
- if (warnedDefaults.has(message)) return;
4215
- warnedDefaults.add(message);
4216
- console.warn(message);
4217
- }
4218
- function formatConfigValue(value) {
4219
- try {
4220
- const json = JSON.stringify(value);
4221
- return json ?? String(value);
4222
- } catch {
4223
- return `[unserializable: ${typeof value}]`;
4224
- }
4225
- }
4226
- var isTypingMode = (v) => v === "auto" || v === "llm";
4227
- var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
4228
- function resolveSystemOneTyping(config, classifierCallOption) {
4229
- const systemOne = config?.systemOne;
4230
- const legacy = config?.ontology?.backfillClassifier;
4231
- const systemOneValid = isTypingMode(systemOne?.typing);
4232
- const legacyValid = isTypingMode(legacy);
4233
- if (systemOne?.typing !== void 0 && !systemOneValid) {
4234
- warnOnce(
4235
- `[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.`
4236
- );
4237
- }
4238
- if (legacy !== void 0 && !legacyValid) {
4239
- warnOnce(
4240
- `[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.`
4241
- );
4242
- }
4243
- if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
4244
- warnOnce(
4245
- `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
4246
- );
4247
- }
4248
- return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
4249
- }
4250
- function resolveSystemOneEdges(config) {
4251
- const edges = config?.systemOne?.edges;
4252
- if (edges !== void 0 && !isTypingMode(edges)) {
4253
- warnOnce(
4254
- `[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.`
4255
- );
4256
- return "llm";
4257
- }
4258
- return edges ?? "llm";
4259
- }
4260
- function resolveSystemOneResolve(config) {
4261
- const resolve = config?.systemOne?.resolve;
4262
- if (resolve !== void 0 && !isTypingMode(resolve)) {
4263
- warnOnce(
4264
- `[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.`
4265
- );
4266
- return "llm";
4267
- }
4268
- return resolve ?? "llm";
4269
- }
4270
- var DEFAULT_SHORTLIST_K = 10;
4271
- function resolveShortlistK(config) {
4272
- const k = config?.ontology?.shortlistK;
4273
- if (k === void 0) return DEFAULT_SHORTLIST_K;
4274
- if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
4275
- throw new Error(
4276
- `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
4277
- );
4278
- }
4279
- return k;
4280
- }
4281
- var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
4282
- function resolveTypingMinConfidence(config) {
4283
- const systemOneFloor = config?.systemOne?.minConfidence?.typing;
4284
- const legacyFloor = config?.ontology?.classifyMinConfidence;
4285
- const systemOneValid = isConfidenceFloor(systemOneFloor);
4286
- const legacyValid = isConfidenceFloor(legacyFloor);
4287
- if (systemOneFloor !== void 0 && !systemOneValid) {
4288
- warnOnce(
4289
- `[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.`
4290
- );
4291
- }
4292
- if (legacyFloor !== void 0 && !legacyValid) {
4293
- warnOnce(
4294
- `[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.`
4295
- );
4296
- }
4297
- return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
4298
- }
4299
- var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4300
- function resolveEdgesMinConfidence(config) {
4301
- if (resolveSystemOneEdges(config) !== "auto") return void 0;
4302
- const floor = config?.systemOne?.minConfidence?.edges;
4303
- if (isEdgesFloor(floor)) return floor;
4304
- warnOnce(
4305
- 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.`
4306
- );
4307
- return void 0;
4308
- }
4309
- function resolveResolveMinConfidence(config) {
4310
- if (resolveSystemOneResolve(config) !== "auto") return void 0;
4311
- const floor = config?.systemOne?.minConfidence?.resolve;
4312
- if (isEdgesFloor(floor)) return floor;
4313
- warnOnce(
4314
- 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.`
4315
- );
4316
- return void 0;
4317
- }
4318
- function resolveSystemOneHealScreen(config) {
4319
- const healScreen = config?.systemOne?.healScreen;
4320
- if (healScreen !== void 0 && !isTypingMode(healScreen)) {
4321
- warnOnce(
4322
- `[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.`
4323
- );
4324
- return "llm";
4325
- }
4326
- return healScreen ?? "llm";
4327
- }
4328
- function resolveSystemOneTypeOnWrite(config) {
4329
- const typeOnWrite = config?.systemOne?.typeOnWrite;
4330
- if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
4331
- warnOnce(
4332
- `[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.`
4333
- );
4334
- return "llm";
4335
- }
4336
- return typeOnWrite ?? "llm";
4337
- }
4338
- function resolveHealScreenMinConfidence(config) {
4339
- if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4340
- const floor = config?.systemOne?.minConfidence?.healScreen;
4341
- if (isEdgesFloor(floor)) return floor;
4342
- warnOnce(
4343
- 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.`
4344
- );
4345
- return void 0;
4346
- }
4761
+ 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));
4762
+ }
4763
+ };
4347
4764
 
4348
4765
  // src/utils/embedding.ts
4349
4766
  function parseEmbedding(blob, text) {
@@ -4451,270 +4868,110 @@ var EdgeRepository = class extends BaseRepository {
4451
4868
  );
4452
4869
  totalChanges += result.changes;
4453
4870
  }
4454
- return totalChanges;
4455
- }
4456
- /**
4457
- * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
4458
- * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
4459
- * The anchor is validated (exists, right entity, not soft-deleted) but never gated
4460
- * by confidence/source_type — only nodes discovered beyond it are.
4461
- */
4462
- async getNeighborhood(entityId, sourceId, opts, tx) {
4463
- const executor = this.getExecutor(tx);
4464
- if (opts.edgeTypes && opts.edgeTypes.length === 0) {
4465
- const anchor = await executor.getFirstAsync(
4466
- `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
4467
- [sourceId, entityId]
4468
- );
4469
- return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4470
- }
4471
- const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4472
- const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4473
- const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4474
- const sql = `
4475
- WITH RECURSIVE walk(node_id, depth, visited) AS (
4476
- SELECT id, 0, ',' || id || ','
4477
- FROM ${this.prefix}entries
4478
- WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4479
-
4480
- UNION
4481
-
4482
- SELECT
4483
- CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4484
- w.depth + 1,
4485
- w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4486
- FROM walk w
4487
- JOIN ${this.prefix}edges e
4488
- ON e.entity_id = ?
4489
- AND (
4490
- (? != 'inbound' AND e.source_id = w.node_id) OR
4491
- (? != 'outbound' AND e.target_id = w.node_id)
4492
- )
4493
- AND (${edgeTypesClause})
4494
- JOIN ${this.prefix}entries n
4495
- ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4496
- AND n.entity_id = ?
4497
- AND n.deleted_at IS NULL
4498
- AND (
4499
- CASE n.confidence
4500
- WHEN 'tentative' THEN 0
4501
- WHEN 'inferred' THEN 1
4502
- WHEN 'certain' THEN 2
4503
- ELSE -1
4504
- END
4505
- ) >= ?
4506
- AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4507
- AND (? = 0 OR n.lifecycle_status != 'draft')
4508
- AND ${liveAtSql(opts.live.mode, "n.")}
4509
- WHERE w.depth < ?
4510
- AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4511
- )
4512
- SELECT node_id, MIN(depth) AS depth
4513
- FROM walk
4514
- GROUP BY node_id
4515
- ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4516
- LIMIT ?
4517
- `;
4518
- const params = [
4519
- sourceId,
4520
- entityId,
4521
- entityId,
4522
- opts.direction,
4523
- opts.direction,
4524
- ...opts.edgeTypes ?? [],
4525
- entityId,
4526
- minConfidenceRank,
4527
- ...opts.excludeSourceTypes,
4528
- opts.excludeDrafts === true ? 1 : 0,
4529
- opts.live.t,
4530
- opts.live.t,
4531
- opts.maxDepth,
4532
- opts.maxNodes
4533
- ];
4534
- const rows = await executor.getAllAsync(sql, params);
4535
- const nodeIds = rows.map((r) => r.node_id);
4536
- if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4537
- const valueRows = nodeIds.map(() => "(?)").join(", ");
4538
- const edgeRows = await executor.getAllAsync(
4539
- `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4540
- SELECT e.* FROM ${this.prefix}edges e
4541
- JOIN neighborhood ns ON e.source_id = ns.node_id
4542
- JOIN neighborhood nt ON e.target_id = nt.node_id
4543
- WHERE e.entity_id = ?`,
4544
- [...nodeIds, entityId]
4545
- );
4546
- return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4547
- }
4548
- };
4549
- function mapRowToEdge(row) {
4550
- return {
4551
- id: String(row.id),
4552
- entity_id: String(row.entity_id),
4553
- source_id: String(row.source_id),
4554
- target_id: String(row.target_id),
4555
- edge_type: String(row.edge_type),
4556
- created_at: Number(row.created_at)
4557
- };
4558
- }
4559
-
4560
- // src/services/BoundedLlmCall.ts
4561
- var DEFAULT_BATCH_SIZE = 10;
4562
- var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
4563
- var OUTPUT_BUDGET_FRACTION = 0.8;
4564
- var TRUNCATION_PATTERNS = [
4565
- /truncat/i,
4566
- /token limit/i,
4567
- /max(imum)?[ _-]?tokens?/i,
4568
- /output limit/i,
4569
- /length limit/i,
4570
- /finish[_ ]?reason/i
4571
- ];
4572
- var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
4573
- 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;
4574
- var CONTEXT_OVERFLOW_PATTERNS = [
4575
- /maximum context length/i,
4576
- /context[_ ]?length[_ ]?exceeded/i,
4577
- /prompt is too long/i,
4578
- /input (token count|is too long)/i,
4579
- /exceeds? the (available )?context( size)?/i,
4580
- // Tail requires a context-window clause (context|maximum), NOT bare `token`:
4581
- // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
4582
- // classify as input overflow (it would split the batch and stamp a cooldown).
4583
- /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4584
- /context limit/i,
4585
- // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
4586
- /\bcontext is full\b/i,
4587
- /too long for (the )?requested model/i,
4588
- // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4589
- // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
4590
- /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
4591
- ];
4592
- function isContextOverflowError(err) {
4593
- const message = getErrorMessage(err);
4594
- if (message === void 0) return false;
4595
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4596
- return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
4597
- }
4598
- function getErrorMessage(err) {
4599
- try {
4600
- return err instanceof Error ? err.message : String(err ?? "");
4601
- } catch {
4602
- return void 0;
4603
- }
4604
- }
4605
- function isTruncationError(err) {
4606
- const message = getErrorMessage(err);
4607
- if (message === void 0) return false;
4608
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4609
- if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4610
- return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4611
- }
4612
- function isConfigError(err) {
4613
- const message = getErrorMessage(err);
4614
- if (message === void 0) return false;
4615
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4616
- return EXCEEDS_LIMIT_PATTERN.test(message);
4617
- }
4618
- function initialBatchSize(maxOutputTokens) {
4619
- if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
4620
- return DEFAULT_BATCH_SIZE;
4621
- }
4622
- const estimate = Math.floor(
4623
- maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
4624
- );
4625
- return Math.max(DEFAULT_BATCH_SIZE, estimate);
4626
- }
4627
- var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4628
- async function runBatched(args) {
4629
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4630
- const results = [];
4631
- const skipped = [];
4632
- let batches = 0;
4633
- const settled = /* @__PURE__ */ new Set();
4634
- let budgetStop;
4635
- let batchSize = initialBatchSize(maxOutputTokens);
4636
- const trim = async (candidate) => {
4637
- const whole = await buildPrompt(candidate);
4638
- if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
4639
- return { batch: candidate, prompts: whole };
4640
- }
4641
- let low = 2;
4642
- let high = candidate.length - 1;
4643
- let best;
4644
- let bestPrompts;
4645
- while (low <= high) {
4646
- const mid = Math.floor((low + high) / 2);
4647
- const batch = candidate.slice(0, mid);
4648
- const prompts = await buildPrompt(batch);
4649
- if (promptLength(prompts) <= maxPromptChars) {
4650
- best = batch;
4651
- bestPrompts = prompts;
4652
- low = mid + 1;
4653
- } else {
4654
- high = mid - 1;
4655
- }
4656
- }
4657
- if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
4658
- const single = candidate.slice(0, 1);
4659
- return { batch: single, prompts: await buildPrompt(single) };
4660
- };
4661
- const onFailure = async (batch, err, attemptLevel, fromCall) => {
4662
- if (batch.length === 1) {
4663
- if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4664
- await attempt(batch, void 0, attemptLevel + 1);
4665
- } else {
4666
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
4667
- skipped.push({ item: batch[0], reason });
4668
- settled.add(batch[0]);
4669
- onSkip?.(batch[0], err);
4670
- }
4671
- return;
4672
- }
4673
- if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4674
- const mid = Math.ceil(batch.length / 2);
4675
- if (mid < batchSize) batchSize = mid;
4676
- let i = 0;
4677
- while (i < batch.length && !budgetStop) {
4678
- const size = Math.min(batchSize, batch.length - i);
4679
- const trimmed = await trim(batch.slice(i, i + size));
4680
- await attempt(trimmed.batch, trimmed.prompts);
4681
- i += trimmed.batch.length;
4682
- }
4683
- };
4684
- const attempt = async (batch, prebuilt, attemptLevel = 0) => {
4685
- if (budgetStop) return;
4686
- if (batch.length === 0) return;
4687
- const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
4688
- batches++;
4689
- let responseText;
4690
- try {
4691
- responseText = await call(prompts);
4692
- } catch (err) {
4693
- if (err instanceof WikiBudgetExhausted) {
4694
- budgetStop = { requiredEstimate: err.requiredEstimate };
4695
- return;
4696
- }
4697
- await onFailure(batch, err, attemptLevel, true);
4698
- return;
4699
- }
4700
- let result;
4701
- try {
4702
- result = parse(responseText, batch, prompts);
4703
- } catch (err) {
4704
- await onFailure(batch, err, attemptLevel, false);
4705
- return;
4706
- }
4707
- results.push(result);
4708
- for (const item of batch) settled.add(item);
4709
- };
4710
- let index = 0;
4711
- while (index < items.length && !budgetStop) {
4712
- const { batch, prompts } = await trim(items.slice(index, index + batchSize));
4713
- index += batch.length;
4714
- await attempt(batch, prompts, 0);
4871
+ return totalChanges;
4715
4872
  }
4716
- const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
4717
- return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
4873
+ /**
4874
+ * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
4875
+ * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
4876
+ * The anchor is validated (exists, right entity, not soft-deleted) but never gated
4877
+ * by confidence/source_type — only nodes discovered beyond it are.
4878
+ */
4879
+ async getNeighborhood(entityId, sourceId, opts, tx) {
4880
+ const executor = this.getExecutor(tx);
4881
+ if (opts.edgeTypes && opts.edgeTypes.length === 0) {
4882
+ const anchor = await executor.getFirstAsync(
4883
+ `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
4884
+ [sourceId, entityId]
4885
+ );
4886
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4887
+ }
4888
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4889
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4890
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4891
+ const sql = `
4892
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
4893
+ SELECT id, 0, ',' || id || ','
4894
+ FROM ${this.prefix}entries
4895
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4896
+
4897
+ UNION
4898
+
4899
+ SELECT
4900
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4901
+ w.depth + 1,
4902
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4903
+ FROM walk w
4904
+ JOIN ${this.prefix}edges e
4905
+ ON e.entity_id = ?
4906
+ AND (
4907
+ (? != 'inbound' AND e.source_id = w.node_id) OR
4908
+ (? != 'outbound' AND e.target_id = w.node_id)
4909
+ )
4910
+ AND (${edgeTypesClause})
4911
+ JOIN ${this.prefix}entries n
4912
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4913
+ AND n.entity_id = ?
4914
+ AND n.deleted_at IS NULL
4915
+ AND (
4916
+ CASE n.confidence
4917
+ WHEN 'tentative' THEN 0
4918
+ WHEN 'inferred' THEN 1
4919
+ WHEN 'certain' THEN 2
4920
+ ELSE -1
4921
+ END
4922
+ ) >= ?
4923
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4924
+ AND (? = 0 OR n.lifecycle_status != 'draft')
4925
+ AND ${liveAtSql(opts.live.mode, "n.")}
4926
+ WHERE w.depth < ?
4927
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4928
+ )
4929
+ SELECT node_id, MIN(depth) AS depth
4930
+ FROM walk
4931
+ GROUP BY node_id
4932
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4933
+ LIMIT ?
4934
+ `;
4935
+ const params = [
4936
+ sourceId,
4937
+ entityId,
4938
+ entityId,
4939
+ opts.direction,
4940
+ opts.direction,
4941
+ ...opts.edgeTypes ?? [],
4942
+ entityId,
4943
+ minConfidenceRank,
4944
+ ...opts.excludeSourceTypes,
4945
+ opts.excludeDrafts === true ? 1 : 0,
4946
+ opts.live.t,
4947
+ opts.live.t,
4948
+ opts.maxDepth,
4949
+ opts.maxNodes
4950
+ ];
4951
+ const rows = await executor.getAllAsync(sql, params);
4952
+ const nodeIds = rows.map((r) => r.node_id);
4953
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4954
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
4955
+ const edgeRows = await executor.getAllAsync(
4956
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4957
+ SELECT e.* FROM ${this.prefix}edges e
4958
+ JOIN neighborhood ns ON e.source_id = ns.node_id
4959
+ JOIN neighborhood nt ON e.target_id = nt.node_id
4960
+ WHERE e.entity_id = ?`,
4961
+ [...nodeIds, entityId]
4962
+ );
4963
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4964
+ }
4965
+ };
4966
+ function mapRowToEdge(row) {
4967
+ return {
4968
+ id: String(row.id),
4969
+ entity_id: String(row.entity_id),
4970
+ source_id: String(row.source_id),
4971
+ target_id: String(row.target_id),
4972
+ edge_type: String(row.edge_type),
4973
+ created_at: Number(row.created_at)
4974
+ };
4718
4975
  }
4719
4976
 
4720
4977
  // src/db/schema.ts
@@ -5214,152 +5471,6 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
5214
5471
  });
5215
5472
  }
5216
5473
 
5217
- // src/services/typing/typeOnWrite.ts
5218
- var CLASSIFIER_MAX_CHOICES = 255;
5219
- function isManifestRepresentable(manifest) {
5220
- const slugs = manifest.node_types.map((n) => n.type);
5221
- return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
5222
- }
5223
- function canEngageWriteTyping(config, provider, mode, manifest) {
5224
- return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
5225
- }
5226
- function buildTypingQuestion(manifest) {
5227
- return {
5228
- kind: "choice",
5229
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
5230
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
5231
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
5232
- };
5233
- }
5234
- function volunteeredTypeResolves(rawOkfType, manifest) {
5235
- return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
5236
- }
5237
- async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
5238
- const question = buildTypingQuestion(manifest);
5239
- const rawConcurrency = options.config?.chunkConcurrency ?? 1;
5240
- const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
5241
- let stopped = false;
5242
- return withConcurrency(
5243
- facts.map((fact) => async () => {
5244
- if (stopped) return { kind: "unattempted" };
5245
- let response;
5246
- try {
5247
- response = await callClassify(
5248
- options,
5249
- { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
5250
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
5251
- );
5252
- } catch (err) {
5253
- if (err instanceof WikiBudgetExhausted) {
5254
- stopped = true;
5255
- return { kind: "unattempted" };
5256
- }
5257
- if (isContextOverflowError(err)) return { kind: "overflow_skip" };
5258
- return { kind: "threw" };
5259
- }
5260
- const checked = validateClassifierAnswer(response, "okf_type", question);
5261
- if (!checked.ok) return { kind: "invalid", reason: checked.reason };
5262
- if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
5263
- if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
5264
- if (checked.answer.confidence < floor) return { kind: "low_confidence" };
5265
- return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
5266
- }),
5267
- concurrency
5268
- );
5269
- }
5270
- function emptyTypingCounters() {
5271
- return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
5272
- }
5273
- function tallyTypingOutcome(c, o) {
5274
- switch (o.kind) {
5275
- case "unattempted":
5276
- c.unattempted++;
5277
- return;
5278
- case "accepted":
5279
- c.asked++;
5280
- return;
5281
- case "abstain":
5282
- c.asked++;
5283
- c.abstained++;
5284
- return;
5285
- case "low_confidence":
5286
- c.asked++;
5287
- c.lowConfidence++;
5288
- return;
5289
- case "invalid":
5290
- case "threw":
5291
- c.asked++;
5292
- c.invalid++;
5293
- return;
5294
- case "overflow_skip":
5295
- c.asked++;
5296
- c.skipped++;
5297
- return;
5298
- }
5299
- }
5300
- function typingOutcomeReceipt(base, factId, outcome) {
5301
- switch (outcome.kind) {
5302
- case "abstain":
5303
- return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
5304
- case "low_confidence":
5305
- return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
5306
- case "invalid":
5307
- return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
5308
- case "threw":
5309
- return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
5310
- case "overflow_skip":
5311
- return { ...base, code: "context_overflow_skipped", detail: { factId } };
5312
- default:
5313
- return null;
5314
- }
5315
- }
5316
- function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
5317
- const drops = [];
5318
- const receipts = [];
5319
- const emit = shouldEmitOntologyReceipt(mode);
5320
- let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5321
- if (emit) {
5322
- receipts.push(...nodeTypeReceipts(
5323
- base,
5324
- factId,
5325
- typeof fact.okf_type === "string" ? fact.okf_type : "",
5326
- normalized.okf_type,
5327
- normalized.match
5328
- ));
5329
- }
5330
- let typedByClassifier = false;
5331
- if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
5332
- const second = ontology?.validateAndNormalizeFact(
5333
- { ...fact, okf_type: outcome.okfType, edges: [] },
5334
- manifest,
5335
- { strict: false }
5336
- ) ?? { okf_type: null};
5337
- if (emit) {
5338
- receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
5339
- }
5340
- normalized = { okf_type: second.okf_type, edges: [] };
5341
- if (second.okf_type) {
5342
- typedByClassifier = true;
5343
- if (emit) {
5344
- receipts.push({
5345
- ...base,
5346
- code: "node_type_assigned",
5347
- detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
5348
- });
5349
- }
5350
- }
5351
- } else if (normalized.okf_type) {
5352
- if (emit) {
5353
- receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
5354
- }
5355
- }
5356
- if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
5357
- const r = typingOutcomeReceipt(base, factId, outcome);
5358
- if (r) receipts.push(r);
5359
- }
5360
- return { normalized, drops, receipts, typedByClassifier };
5361
- }
5362
-
5363
5474
  // src/services/librarian/constants.ts
5364
5475
  var FUZZY_THRESHOLD = 0.5;
5365
5476
  var MIN_TOKENS_TO_QUALIFY = 3;