@equationalapplications/core-llm-wiki 9.16.2 → 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
@@ -3238,6 +3238,522 @@ async function callClassify(options, ctx, request) {
3238
3238
  return response;
3239
3239
  }
3240
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
+ }
3749
+ }
3750
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
3751
+ const r = typingOutcomeReceipt(base, factId, outcome);
3752
+ if (r) receipts.push(r);
3753
+ }
3754
+ return { normalized, drops, receipts, typedByClassifier };
3755
+ }
3756
+
3241
3757
  // src/services/IngestionService.ts
3242
3758
  var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
3243
3759
  function dedupDiagnostic(entityId, sourceRef, locator) {
@@ -3305,7 +3821,9 @@ var IngestionService = class {
3305
3821
  }
3306
3822
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3307
3823
  if (chunks2.length === 0) return zeroChunkResult();
3308
- 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;
3309
3827
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3310
3828
  if (diagnostic) {
3311
3829
  emitDiagnostic(this.options, {
@@ -3461,16 +3979,42 @@ var IngestionService = class {
3461
3979
  chunks: chunks2.length
3462
3980
  });
3463
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
+ }
3464
4008
  const insertedFacts = [];
3465
4009
  const deletedSourceFactIds = [];
3466
4010
  try {
3467
4011
  if (failedChunks === 0) {
3468
4012
  const fullResult = await this.db.withTransactionAsync(async (tx) => {
3469
- return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger);
4013
+ return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger, typing);
3470
4014
  });
3471
4015
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
3472
4016
  insertedFacts.push(...fullResult.insertedFacts);
3473
- if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
4017
+ if (hoistedState.mode !== "off" && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
3474
4018
  diagBuffer.push({
3475
4019
  entityId,
3476
4020
  operation: "ingest",
@@ -3483,7 +4027,7 @@ var IngestionService = class {
3483
4027
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
3484
4028
  const flat = [];
3485
4029
  for (const slot of orderedChunkFacts) flat.push(...slot.facts);
3486
- return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger);
4030
+ return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger, typing);
3487
4031
  });
3488
4032
  insertedFacts.push(...partialResult.insertedDescriptors);
3489
4033
  }
@@ -3535,6 +4079,7 @@ var IngestionService = class {
3535
4079
  failedChunks
3536
4080
  };
3537
4081
  if (failedChunks > 0) result.parseFailures = failures;
4082
+ if (engaged) result.typing = toIngestCounters(typing.counters);
3538
4083
  return result;
3539
4084
  } finally {
3540
4085
  releaseIngestLocks();
@@ -3744,10 +4289,11 @@ var IngestionService = class {
3744
4289
  * On the partial path the caller never invokes this method; the empty
3745
4290
  * arrays stay empty.
3746
4291
  */
3747
- 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) {
3748
4293
  const deletedSourceFactIds = [];
3749
4294
  const insertedFacts = [];
3750
4295
  const nodeTrust = /* @__PURE__ */ new Map();
4296
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3751
4297
  deletedSourceFactIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false));
3752
4298
  const titleIndex = /* @__PURE__ */ new Map();
3753
4299
  const existingFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx, sourceRef);
@@ -3761,6 +4307,7 @@ var IngestionService = class {
3761
4307
  let { mode, manifest } = ontologyState;
3762
4308
  const hostNodes = [];
3763
4309
  const rawEdgeRequests = [];
4310
+ const typedAtDoor = [];
3764
4311
  const now = Date.now();
3765
4312
  for (const { facts, ontology_updates } of orderedChunkFacts) {
3766
4313
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
@@ -3780,14 +4327,15 @@ var IngestionService = class {
3780
4327
  for (const fact of facts) {
3781
4328
  const ontologyFact = fact;
3782
4329
  const id = generateId("fact_");
3783
- const validationDrops = [];
3784
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
3785
- 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) {
3786
4334
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3787
4335
  }
3788
- hostNodes.push({
4336
+ const hostNode = {
3789
4337
  id,
3790
- type: ontologyFact.okf_type ?? "",
4338
+ type: "",
3791
4339
  title: fact.title,
3792
4340
  body: fact.body,
3793
4341
  // Forward the LLM-extracted tags/confidence through the
@@ -3799,18 +4347,20 @@ var IngestionService = class {
3799
4347
  // 'certain' as documented.
3800
4348
  tags: fact.tags,
3801
4349
  confidence: fact.confidence
3802
- });
4350
+ };
4351
+ hostNodes.push(hostNode);
4352
+ typedAtDoor.push({ node: hostNode, fact: ontologyFact, id, outcome, slotType: normalized.okf_type });
3803
4353
  const locator = factLedger.get(fact);
3804
4354
  if (locator?.verdict) {
3805
- const outcome = groundingOutcome(locator.verdict, now);
3806
- nodeTrust.set(id, outcome.trust);
3807
- if (outcome.diagnostic) {
4355
+ const outcome2 = groundingOutcome(locator.verdict, now);
4356
+ nodeTrust.set(id, outcome2.trust);
4357
+ if (outcome2.diagnostic) {
3808
4358
  diagBuffer.push({
3809
4359
  entityId,
3810
4360
  operation: "ingest",
3811
4361
  trigger: "call",
3812
- code: outcome.diagnostic.code,
3813
- 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 }
3814
4364
  });
3815
4365
  }
3816
4366
  }
@@ -3821,6 +4371,18 @@ var IngestionService = class {
3821
4371
  }
3822
4372
  }
3823
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
+ }
3824
4386
  const hostEdges = [];
3825
4387
  for (const req of rawEdgeRequests) {
3826
4388
  const resolveDrops = [];
@@ -3841,6 +4403,7 @@ var IngestionService = class {
3841
4403
  hostEdges.push({ type: e.edge_type, sourceId: e.source_id, targetId: e.target_id });
3842
4404
  }
3843
4405
  }
4406
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
3844
4407
  await this.upsertGraphCore(
3845
4408
  entityId,
3846
4409
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
@@ -3869,7 +4432,7 @@ var IngestionService = class {
3869
4432
  * Runs INSIDE the caller's `tx`. Does not open a nested transaction.
3870
4433
  * Returns `{ inserted, skippedDuplicate }` for observability.
3871
4434
  */
3872
- async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4435
+ async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
3873
4436
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
3874
4437
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
3875
4438
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
@@ -3880,6 +4443,7 @@ var IngestionService = class {
3880
4443
  for (const f of indexedFacts) {
3881
4444
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
3882
4445
  }
4446
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3883
4447
  const pendingEdges = [];
3884
4448
  let inserted = 0;
3885
4449
  let skippedDuplicate = 0;
@@ -3906,22 +4470,22 @@ var IngestionService = class {
3906
4470
  });
3907
4471
  }
3908
4472
  const ontologyFact = fact;
3909
- const validationDrops = [];
3910
- 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
+ );
3911
4482
  for (const drop of validationDrops) {
3912
4483
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3913
4484
  }
3914
- if (shouldEmitOntologyReceipt(mode)) {
3915
- for (const receipt of nodeTypeReceipts(
3916
- { entityId, operation: "ingest", trigger: "call" },
3917
- id,
3918
- ontologyFact.okf_type ?? "",
3919
- normalized.okf_type,
3920
- normalized.match
3921
- )) {
3922
- diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3923
- }
4485
+ for (const receipt of receipts) {
4486
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3924
4487
  }
4488
+ if (typedByClassifier && typing) typing.counters.typed++;
3925
4489
  if (normalized.edges.length > 0) {
3926
4490
  pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
3927
4491
  }
@@ -3982,51 +4546,6 @@ var IngestionService = class {
3982
4546
  }
3983
4547
  };
3984
4548
 
3985
- // src/utils/classifier.ts
3986
- var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3987
- function validateClassifierAnswer(response, key, question) {
3988
- try {
3989
- if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
3990
- const answers = response.answers;
3991
- if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
3992
- if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
3993
- const raw = answers[key];
3994
- if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
3995
- const a = raw;
3996
- if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
3997
- if (question.kind === "choice") {
3998
- if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
3999
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
4000
- const probs = a.probabilities;
4001
- if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
4002
- const probabilities = {};
4003
- for (const [k, v] of Object.entries(probs)) {
4004
- if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
4005
- probabilities[k] = v;
4006
- }
4007
- return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
4008
- }
4009
- if (question.kind === "binary") {
4010
- if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
4011
- return { ok: true, answer: { kind: "binary", probability: a.probability } };
4012
- }
4013
- const maxScore = question.levels.length - 1;
4014
- if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
4015
- return { ok: false, reason: "score_out_of_range" };
4016
- }
4017
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
4018
- if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
4019
- return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
4020
- } catch {
4021
- return { ok: false, reason: "malformed" };
4022
- }
4023
- }
4024
- function classifierStateForFact(fact) {
4025
- const parts = [fact.title, fact.body];
4026
- if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
4027
- return parts.join("\n\n");
4028
- }
4029
-
4030
4549
  // src/utils/shortlist.ts
4031
4550
  function shortlistScore(factTitle, factBody, row) {
4032
4551
  const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
@@ -4239,154 +4758,9 @@ var TemporalService = class {
4239
4758
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4240
4759
  const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4241
4760
  const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
4242
- 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));
4243
- }
4244
- };
4245
-
4246
- // src/utils/engineDefaults.ts
4247
- var DEFAULT_LIBRARIAN_STRATEGY = "ops";
4248
- var DEFAULT_MAINTENANCE_MODE = "deferred";
4249
- function resolveLibrarianStrategy(config) {
4250
- return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
4251
- }
4252
- function resolveMaintenanceMode(config) {
4253
- return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
4254
- }
4255
- var warnedDefaults = /* @__PURE__ */ new Set();
4256
- function warnOnce(message) {
4257
- if (warnedDefaults.has(message)) return;
4258
- warnedDefaults.add(message);
4259
- console.warn(message);
4260
- }
4261
- function formatConfigValue(value) {
4262
- try {
4263
- const json = JSON.stringify(value);
4264
- return json ?? String(value);
4265
- } catch {
4266
- return `[unserializable: ${typeof value}]`;
4267
- }
4268
- }
4269
- var isTypingMode = (v) => v === "auto" || v === "llm";
4270
- var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
4271
- function resolveSystemOneTyping(config, classifierCallOption) {
4272
- const systemOne = config?.systemOne;
4273
- const legacy = config?.ontology?.backfillClassifier;
4274
- const systemOneValid = isTypingMode(systemOne?.typing);
4275
- const legacyValid = isTypingMode(legacy);
4276
- if (systemOne?.typing !== void 0 && !systemOneValid) {
4277
- warnOnce(
4278
- `[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.`
4279
- );
4280
- }
4281
- if (legacy !== void 0 && !legacyValid) {
4282
- warnOnce(
4283
- `[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.`
4284
- );
4285
- }
4286
- if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
4287
- warnOnce(
4288
- `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
4289
- );
4290
- }
4291
- return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
4292
- }
4293
- function resolveSystemOneEdges(config) {
4294
- const edges = config?.systemOne?.edges;
4295
- if (edges !== void 0 && !isTypingMode(edges)) {
4296
- warnOnce(
4297
- `[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.`
4298
- );
4299
- return "llm";
4300
- }
4301
- return edges ?? "llm";
4302
- }
4303
- function resolveSystemOneResolve(config) {
4304
- const resolve = config?.systemOne?.resolve;
4305
- if (resolve !== void 0 && !isTypingMode(resolve)) {
4306
- warnOnce(
4307
- `[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.`
4308
- );
4309
- return "llm";
4310
- }
4311
- return resolve ?? "llm";
4312
- }
4313
- var DEFAULT_SHORTLIST_K = 10;
4314
- function resolveShortlistK(config) {
4315
- const k = config?.ontology?.shortlistK;
4316
- if (k === void 0) return DEFAULT_SHORTLIST_K;
4317
- if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
4318
- throw new Error(
4319
- `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
4320
- );
4321
- }
4322
- return k;
4323
- }
4324
- var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
4325
- function resolveTypingMinConfidence(config) {
4326
- const systemOneFloor = config?.systemOne?.minConfidence?.typing;
4327
- const legacyFloor = config?.ontology?.classifyMinConfidence;
4328
- const systemOneValid = isConfidenceFloor(systemOneFloor);
4329
- const legacyValid = isConfidenceFloor(legacyFloor);
4330
- if (systemOneFloor !== void 0 && !systemOneValid) {
4331
- warnOnce(
4332
- `[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.`
4333
- );
4334
- }
4335
- if (legacyFloor !== void 0 && !legacyValid) {
4336
- warnOnce(
4337
- `[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.`
4338
- );
4339
- }
4340
- return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
4341
- }
4342
- var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4343
- function resolveEdgesMinConfidence(config) {
4344
- if (resolveSystemOneEdges(config) !== "auto") return void 0;
4345
- const floor = config?.systemOne?.minConfidence?.edges;
4346
- if (isEdgesFloor(floor)) return floor;
4347
- warnOnce(
4348
- 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.`
4349
- );
4350
- return void 0;
4351
- }
4352
- function resolveResolveMinConfidence(config) {
4353
- if (resolveSystemOneResolve(config) !== "auto") return void 0;
4354
- const floor = config?.systemOne?.minConfidence?.resolve;
4355
- if (isEdgesFloor(floor)) return floor;
4356
- warnOnce(
4357
- 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.`
4358
- );
4359
- return void 0;
4360
- }
4361
- function resolveSystemOneHealScreen(config) {
4362
- const healScreen = config?.systemOne?.healScreen;
4363
- if (healScreen !== void 0 && !isTypingMode(healScreen)) {
4364
- warnOnce(
4365
- `[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.`
4366
- );
4367
- return "llm";
4368
- }
4369
- return healScreen ?? "llm";
4370
- }
4371
- function resolveSystemOneTypeOnWrite(config) {
4372
- const typeOnWrite = config?.systemOne?.typeOnWrite;
4373
- if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
4374
- warnOnce(
4375
- `[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.`
4376
- );
4377
- return "llm";
4378
- }
4379
- return typeOnWrite ?? "llm";
4380
- }
4381
- function resolveHealScreenMinConfidence(config) {
4382
- if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4383
- const floor = config?.systemOne?.minConfidence?.healScreen;
4384
- if (isEdgesFloor(floor)) return floor;
4385
- warnOnce(
4386
- 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.`
4387
- );
4388
- return void 0;
4389
- }
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
+ };
4390
4764
 
4391
4765
  // src/utils/embedding.ts
4392
4766
  function parseEmbedding(blob, text) {
@@ -4494,270 +4868,110 @@ var EdgeRepository = class extends BaseRepository {
4494
4868
  );
4495
4869
  totalChanges += result.changes;
4496
4870
  }
4497
- return totalChanges;
4498
- }
4499
- /**
4500
- * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
4501
- * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
4502
- * The anchor is validated (exists, right entity, not soft-deleted) but never gated
4503
- * by confidence/source_type — only nodes discovered beyond it are.
4504
- */
4505
- async getNeighborhood(entityId, sourceId, opts, tx) {
4506
- const executor = this.getExecutor(tx);
4507
- if (opts.edgeTypes && opts.edgeTypes.length === 0) {
4508
- const anchor = await executor.getFirstAsync(
4509
- `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
4510
- [sourceId, entityId]
4511
- );
4512
- return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4513
- }
4514
- const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4515
- const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4516
- const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4517
- const sql = `
4518
- WITH RECURSIVE walk(node_id, depth, visited) AS (
4519
- SELECT id, 0, ',' || id || ','
4520
- FROM ${this.prefix}entries
4521
- WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4522
-
4523
- UNION
4524
-
4525
- SELECT
4526
- CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4527
- w.depth + 1,
4528
- w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4529
- FROM walk w
4530
- JOIN ${this.prefix}edges e
4531
- ON e.entity_id = ?
4532
- AND (
4533
- (? != 'inbound' AND e.source_id = w.node_id) OR
4534
- (? != 'outbound' AND e.target_id = w.node_id)
4535
- )
4536
- AND (${edgeTypesClause})
4537
- JOIN ${this.prefix}entries n
4538
- ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4539
- AND n.entity_id = ?
4540
- AND n.deleted_at IS NULL
4541
- AND (
4542
- CASE n.confidence
4543
- WHEN 'tentative' THEN 0
4544
- WHEN 'inferred' THEN 1
4545
- WHEN 'certain' THEN 2
4546
- ELSE -1
4547
- END
4548
- ) >= ?
4549
- AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4550
- AND (? = 0 OR n.lifecycle_status != 'draft')
4551
- AND ${liveAtSql(opts.live.mode, "n.")}
4552
- WHERE w.depth < ?
4553
- AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4554
- )
4555
- SELECT node_id, MIN(depth) AS depth
4556
- FROM walk
4557
- GROUP BY node_id
4558
- ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4559
- LIMIT ?
4560
- `;
4561
- const params = [
4562
- sourceId,
4563
- entityId,
4564
- entityId,
4565
- opts.direction,
4566
- opts.direction,
4567
- ...opts.edgeTypes ?? [],
4568
- entityId,
4569
- minConfidenceRank,
4570
- ...opts.excludeSourceTypes,
4571
- opts.excludeDrafts === true ? 1 : 0,
4572
- opts.live.t,
4573
- opts.live.t,
4574
- opts.maxDepth,
4575
- opts.maxNodes
4576
- ];
4577
- const rows = await executor.getAllAsync(sql, params);
4578
- const nodeIds = rows.map((r) => r.node_id);
4579
- if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4580
- const valueRows = nodeIds.map(() => "(?)").join(", ");
4581
- const edgeRows = await executor.getAllAsync(
4582
- `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4583
- SELECT e.* FROM ${this.prefix}edges e
4584
- JOIN neighborhood ns ON e.source_id = ns.node_id
4585
- JOIN neighborhood nt ON e.target_id = nt.node_id
4586
- WHERE e.entity_id = ?`,
4587
- [...nodeIds, entityId]
4588
- );
4589
- return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4590
- }
4591
- };
4592
- function mapRowToEdge(row) {
4593
- return {
4594
- id: String(row.id),
4595
- entity_id: String(row.entity_id),
4596
- source_id: String(row.source_id),
4597
- target_id: String(row.target_id),
4598
- edge_type: String(row.edge_type),
4599
- created_at: Number(row.created_at)
4600
- };
4601
- }
4602
-
4603
- // src/services/BoundedLlmCall.ts
4604
- var DEFAULT_BATCH_SIZE = 10;
4605
- var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
4606
- var OUTPUT_BUDGET_FRACTION = 0.8;
4607
- var TRUNCATION_PATTERNS = [
4608
- /truncat/i,
4609
- /token limit/i,
4610
- /max(imum)?[ _-]?tokens?/i,
4611
- /output limit/i,
4612
- /length limit/i,
4613
- /finish[_ ]?reason/i
4614
- ];
4615
- var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
4616
- 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;
4617
- var CONTEXT_OVERFLOW_PATTERNS = [
4618
- /maximum context length/i,
4619
- /context[_ ]?length[_ ]?exceeded/i,
4620
- /prompt is too long/i,
4621
- /input (token count|is too long)/i,
4622
- /exceeds? the (available )?context( size)?/i,
4623
- // Tail requires a context-window clause (context|maximum), NOT bare `token`:
4624
- // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
4625
- // classify as input overflow (it would split the batch and stamp a cooldown).
4626
- /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4627
- /context limit/i,
4628
- // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
4629
- /\bcontext is full\b/i,
4630
- /too long for (the )?requested model/i,
4631
- // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4632
- // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
4633
- /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
4634
- ];
4635
- function isContextOverflowError(err) {
4636
- const message = getErrorMessage(err);
4637
- if (message === void 0) return false;
4638
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4639
- return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
4640
- }
4641
- function getErrorMessage(err) {
4642
- try {
4643
- return err instanceof Error ? err.message : String(err ?? "");
4644
- } catch {
4645
- return void 0;
4646
- }
4647
- }
4648
- function isTruncationError(err) {
4649
- const message = getErrorMessage(err);
4650
- if (message === void 0) return false;
4651
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4652
- if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4653
- return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4654
- }
4655
- function isConfigError(err) {
4656
- const message = getErrorMessage(err);
4657
- if (message === void 0) return false;
4658
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4659
- return EXCEEDS_LIMIT_PATTERN.test(message);
4660
- }
4661
- function initialBatchSize(maxOutputTokens) {
4662
- if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
4663
- return DEFAULT_BATCH_SIZE;
4664
- }
4665
- const estimate = Math.floor(
4666
- maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
4667
- );
4668
- return Math.max(DEFAULT_BATCH_SIZE, estimate);
4669
- }
4670
- var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4671
- async function runBatched(args) {
4672
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4673
- const results = [];
4674
- const skipped = [];
4675
- let batches = 0;
4676
- const settled = /* @__PURE__ */ new Set();
4677
- let budgetStop;
4678
- let batchSize = initialBatchSize(maxOutputTokens);
4679
- const trim = async (candidate) => {
4680
- const whole = await buildPrompt(candidate);
4681
- if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
4682
- return { batch: candidate, prompts: whole };
4683
- }
4684
- let low = 2;
4685
- let high = candidate.length - 1;
4686
- let best;
4687
- let bestPrompts;
4688
- while (low <= high) {
4689
- const mid = Math.floor((low + high) / 2);
4690
- const batch = candidate.slice(0, mid);
4691
- const prompts = await buildPrompt(batch);
4692
- if (promptLength(prompts) <= maxPromptChars) {
4693
- best = batch;
4694
- bestPrompts = prompts;
4695
- low = mid + 1;
4696
- } else {
4697
- high = mid - 1;
4698
- }
4699
- }
4700
- if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
4701
- const single = candidate.slice(0, 1);
4702
- return { batch: single, prompts: await buildPrompt(single) };
4703
- };
4704
- const onFailure = async (batch, err, attemptLevel, fromCall) => {
4705
- if (batch.length === 1) {
4706
- if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4707
- await attempt(batch, void 0, attemptLevel + 1);
4708
- } else {
4709
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
4710
- skipped.push({ item: batch[0], reason });
4711
- settled.add(batch[0]);
4712
- onSkip?.(batch[0], err);
4713
- }
4714
- return;
4715
- }
4716
- if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4717
- const mid = Math.ceil(batch.length / 2);
4718
- if (mid < batchSize) batchSize = mid;
4719
- let i = 0;
4720
- while (i < batch.length && !budgetStop) {
4721
- const size = Math.min(batchSize, batch.length - i);
4722
- const trimmed = await trim(batch.slice(i, i + size));
4723
- await attempt(trimmed.batch, trimmed.prompts);
4724
- i += trimmed.batch.length;
4725
- }
4726
- };
4727
- const attempt = async (batch, prebuilt, attemptLevel = 0) => {
4728
- if (budgetStop) return;
4729
- if (batch.length === 0) return;
4730
- const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
4731
- batches++;
4732
- let responseText;
4733
- try {
4734
- responseText = await call(prompts);
4735
- } catch (err) {
4736
- if (err instanceof WikiBudgetExhausted) {
4737
- budgetStop = { requiredEstimate: err.requiredEstimate };
4738
- return;
4739
- }
4740
- await onFailure(batch, err, attemptLevel, true);
4741
- return;
4742
- }
4743
- let result;
4744
- try {
4745
- result = parse(responseText, batch, prompts);
4746
- } catch (err) {
4747
- await onFailure(batch, err, attemptLevel, false);
4748
- return;
4749
- }
4750
- results.push(result);
4751
- for (const item of batch) settled.add(item);
4752
- };
4753
- let index = 0;
4754
- while (index < items.length && !budgetStop) {
4755
- const { batch, prompts } = await trim(items.slice(index, index + batchSize));
4756
- index += batch.length;
4757
- await attempt(batch, prompts, 0);
4871
+ return totalChanges;
4758
4872
  }
4759
- const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
4760
- 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
+ };
4761
4975
  }
4762
4976
 
4763
4977
  // src/db/schema.ts
@@ -5257,152 +5471,6 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
5257
5471
  });
5258
5472
  }
5259
5473
 
5260
- // src/services/typing/typeOnWrite.ts
5261
- var CLASSIFIER_MAX_CHOICES = 255;
5262
- function isManifestRepresentable(manifest) {
5263
- const slugs = manifest.node_types.map((n) => n.type);
5264
- return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
5265
- }
5266
- function canEngageWriteTyping(config, provider, mode, manifest) {
5267
- return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
5268
- }
5269
- function buildTypingQuestion(manifest) {
5270
- return {
5271
- kind: "choice",
5272
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
5273
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
5274
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
5275
- };
5276
- }
5277
- function volunteeredTypeResolves(rawOkfType, manifest) {
5278
- return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
5279
- }
5280
- async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
5281
- const question = buildTypingQuestion(manifest);
5282
- const rawConcurrency = options.config?.chunkConcurrency ?? 1;
5283
- const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
5284
- let stopped = false;
5285
- return withConcurrency(
5286
- facts.map((fact) => async () => {
5287
- if (stopped) return { kind: "unattempted" };
5288
- let response;
5289
- try {
5290
- response = await callClassify(
5291
- options,
5292
- { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
5293
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
5294
- );
5295
- } catch (err) {
5296
- if (err instanceof WikiBudgetExhausted) {
5297
- stopped = true;
5298
- return { kind: "unattempted" };
5299
- }
5300
- if (isContextOverflowError(err)) return { kind: "overflow_skip" };
5301
- return { kind: "threw" };
5302
- }
5303
- const checked = validateClassifierAnswer(response, "okf_type", question);
5304
- if (!checked.ok) return { kind: "invalid", reason: checked.reason };
5305
- if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
5306
- if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
5307
- if (checked.answer.confidence < floor) return { kind: "low_confidence" };
5308
- return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
5309
- }),
5310
- concurrency
5311
- );
5312
- }
5313
- function emptyTypingCounters() {
5314
- return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
5315
- }
5316
- function tallyTypingOutcome(c, o) {
5317
- switch (o.kind) {
5318
- case "unattempted":
5319
- c.unattempted++;
5320
- return;
5321
- case "accepted":
5322
- c.asked++;
5323
- return;
5324
- case "abstain":
5325
- c.asked++;
5326
- c.abstained++;
5327
- return;
5328
- case "low_confidence":
5329
- c.asked++;
5330
- c.lowConfidence++;
5331
- return;
5332
- case "invalid":
5333
- case "threw":
5334
- c.asked++;
5335
- c.invalid++;
5336
- return;
5337
- case "overflow_skip":
5338
- c.asked++;
5339
- c.skipped++;
5340
- return;
5341
- }
5342
- }
5343
- function typingOutcomeReceipt(base, factId, outcome) {
5344
- switch (outcome.kind) {
5345
- case "abstain":
5346
- return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
5347
- case "low_confidence":
5348
- return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
5349
- case "invalid":
5350
- return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
5351
- case "threw":
5352
- return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
5353
- case "overflow_skip":
5354
- return { ...base, code: "context_overflow_skipped", detail: { factId } };
5355
- default:
5356
- return null;
5357
- }
5358
- }
5359
- function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
5360
- const drops = [];
5361
- const receipts = [];
5362
- const emit = shouldEmitOntologyReceipt(mode);
5363
- let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5364
- if (emit) {
5365
- receipts.push(...nodeTypeReceipts(
5366
- base,
5367
- factId,
5368
- typeof fact.okf_type === "string" ? fact.okf_type : "",
5369
- normalized.okf_type,
5370
- normalized.match
5371
- ));
5372
- }
5373
- let typedByClassifier = false;
5374
- if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
5375
- const second = ontology?.validateAndNormalizeFact(
5376
- { ...fact, okf_type: outcome.okfType, edges: [] },
5377
- manifest,
5378
- { strict: false }
5379
- ) ?? { okf_type: null};
5380
- if (emit) {
5381
- receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
5382
- }
5383
- normalized = { okf_type: second.okf_type, edges: [] };
5384
- if (second.okf_type) {
5385
- typedByClassifier = true;
5386
- if (emit) {
5387
- receipts.push({
5388
- ...base,
5389
- code: "node_type_assigned",
5390
- detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
5391
- });
5392
- }
5393
- }
5394
- } else if (normalized.okf_type) {
5395
- if (emit) {
5396
- receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
5397
- }
5398
- }
5399
- if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
5400
- const r = typingOutcomeReceipt(base, factId, outcome);
5401
- if (r) receipts.push(r);
5402
- }
5403
- return { normalized, drops, receipts, typedByClassifier };
5404
- }
5405
-
5406
5474
  // src/services/librarian/constants.ts
5407
5475
  var FUZZY_THRESHOLD = 0.5;
5408
5476
  var MIN_TOKENS_TO_QUALIFY = 3;