@equationalapplications/core-llm-wiki 9.5.3 → 9.7.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
@@ -725,6 +725,8 @@ var SEVERITY = {
725
725
  grounding_failed: "warn",
726
726
  classification_low_confidence: "info",
727
727
  classification_invalid: "warn",
728
+ classification_abstained: "info",
729
+ node_type_assigned: "info",
728
730
  context_overflow_skipped: "warn",
729
731
  llm_usage: "info",
730
732
  librarian_gate: "info",
@@ -733,6 +735,7 @@ var SEVERITY = {
733
735
  resolve_failed: "warn",
734
736
  read_budget: "info",
735
737
  event_retention_held: "info",
738
+ ontology_backfill_held: "info",
736
739
  prune_checkpoint_incomplete: "warn",
737
740
  erase_secure_delete_off: "error",
738
741
  erase_entity_skipped: "warn",
@@ -771,6 +774,8 @@ var MESSAGE = {
771
774
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
772
775
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
773
776
  classification_invalid: "A classifier answer was invalid and was not applied.",
777
+ classification_abstained: "The typing model declined to classify the fact; it was not typed.",
778
+ node_type_assigned: "A typing run assigned an ontology node type to the fact.",
774
779
  context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
775
780
  llm_usage: "An LLM call completed; token usage attached.",
776
781
  librarian_gate: "Librarian gate outcome counts for one pass.",
@@ -779,6 +784,7 @@ var MESSAGE = {
779
784
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
780
785
  read_budget: "A read was packed to a token budget.",
781
786
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
787
+ ontology_backfill_held: "Ontology backfill was held because another job held the entity\u2019s lock.",
782
788
  prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
783
789
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
784
790
  erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow-table text rows were emptied (fts5 %_config and %_data ids 1 and 10 are intentionally kept) and the name stays listed until an FTS5-capable open drops it.",
@@ -1264,6 +1270,10 @@ var BaseRepository = class {
1264
1270
  function normalizeTitleKey(title) {
1265
1271
  return title.trim().toLowerCase().replace(/\s+/g, " ");
1266
1272
  }
1273
+ var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
1274
+ function isReservedAbstainSlug(raw) {
1275
+ return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
1276
+ }
1267
1277
  function typeSatisfies(declaredType, concreteType, manifest) {
1268
1278
  const concrete = concreteType.trim().toLowerCase();
1269
1279
  const declared = declaredType.trim().toLowerCase();
@@ -2888,6 +2898,74 @@ function toGroundingAnchor(anchor) {
2888
2898
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
2889
2899
  var DEFAULT_CHUNK_OVERLAP = 400;
2890
2900
 
2901
+ // src/utils/contextCaps.ts
2902
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
2903
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
2904
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
2905
+
2906
+ // src/config/context.ts
2907
+ var DEFAULT_CHARS_PER_TOKEN = 4;
2908
+ var DEFAULT_SAFETY_FRACTION = 0.9;
2909
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
2910
+ var OP_FLOOR = {
2911
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
2912
+ heal: HEAL_MAX_PROMPT_CHARS,
2913
+ extract: OPS_MAX_EXTRACT_CHARS
2914
+ };
2915
+ function bad(key, value, why) {
2916
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
2917
+ }
2918
+ function resolveContextBudget(config) {
2919
+ const context = config?.context;
2920
+ if (!context || context.budget === void 0) {
2921
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2922
+ }
2923
+ if (context.budget !== "legacy" && context.budget !== "declared") {
2924
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
2925
+ }
2926
+ if (context.budget === "legacy") {
2927
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2928
+ }
2929
+ const window = context.contextWindowTokens;
2930
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
2931
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
2932
+ }
2933
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
2934
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
2935
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
2936
+ }
2937
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
2938
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
2939
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
2940
+ }
2941
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
2942
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
2943
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
2944
+ }
2945
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
2946
+ }
2947
+ function declaredPromptCap(budget, op) {
2948
+ const derived = Math.floor(
2949
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
2950
+ );
2951
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
2952
+ return Math.max(OP_FLOOR.heal, derived);
2953
+ }
2954
+ function resolveMaxPromptChars(budget, op) {
2955
+ if (budget.mode !== "declared") {
2956
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
2957
+ }
2958
+ if (op === "extract") {
2959
+ const resolveDerived = declaredPromptCap(budget, "resolve");
2960
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
2961
+ return Math.max(OP_FLOOR.extract, extractDerived);
2962
+ }
2963
+ return declaredPromptCap(budget, op);
2964
+ }
2965
+ function resolveDefaultChunkLength(budget) {
2966
+ return DEFAULT_MAX_CHUNK_LENGTH;
2967
+ }
2968
+
2891
2969
  // src/utils/usage.ts
2892
2970
  function estimateTokens(text) {
2893
2971
  return Math.ceil(text.length / 4);
@@ -3028,7 +3106,7 @@ var IngestionService = class {
3028
3106
  if (!sourceRef) throw new Error("Invalid sourceRef");
3029
3107
  const sourceHash = normalizeSourceHash(params.sourceHash);
3030
3108
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
3031
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
3109
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
3032
3110
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
3033
3111
  const chunkOverlap = Math.min(
3034
3112
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -3826,6 +3904,62 @@ function resolveLibrarianStrategy(config) {
3826
3904
  function resolveMaintenanceMode(config) {
3827
3905
  return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3828
3906
  }
3907
+ var warnedDefaults = /* @__PURE__ */ new Set();
3908
+ function warnOnce(message) {
3909
+ if (warnedDefaults.has(message)) return;
3910
+ warnedDefaults.add(message);
3911
+ console.warn(message);
3912
+ }
3913
+ function formatConfigValue(value) {
3914
+ try {
3915
+ const json = JSON.stringify(value);
3916
+ return json ?? String(value);
3917
+ } catch {
3918
+ return `[unserializable: ${typeof value}]`;
3919
+ }
3920
+ }
3921
+ var isTypingMode = (v) => v === "auto" || v === "llm";
3922
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3923
+ function resolveSystemOneTyping(config, classifierCallOption) {
3924
+ const systemOne = config?.systemOne;
3925
+ const legacy = config?.ontology?.backfillClassifier;
3926
+ const systemOneValid = isTypingMode(systemOne?.typing);
3927
+ const legacyValid = isTypingMode(legacy);
3928
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
3929
+ warnOnce(
3930
+ `[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.`
3931
+ );
3932
+ }
3933
+ if (legacy !== void 0 && !legacyValid) {
3934
+ warnOnce(
3935
+ `[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.`
3936
+ );
3937
+ }
3938
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
3939
+ warnOnce(
3940
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
3941
+ );
3942
+ }
3943
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3944
+ }
3945
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3946
+ function resolveTypingMinConfidence(config) {
3947
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
3948
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
3949
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
3950
+ const legacyValid = isConfidenceFloor(legacyFloor);
3951
+ if (systemOneFloor !== void 0 && !systemOneValid) {
3952
+ warnOnce(
3953
+ `[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.`
3954
+ );
3955
+ }
3956
+ if (legacyFloor !== void 0 && !legacyValid) {
3957
+ warnOnce(
3958
+ `[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.`
3959
+ );
3960
+ }
3961
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3962
+ }
3829
3963
 
3830
3964
  // src/utils/embedding.ts
3831
3965
  function parseEmbedding(blob, text) {
@@ -4873,18 +5007,18 @@ function parseValidFrom(v) {
4873
5007
 
4874
5008
  // src/services/librarian/ops/extract.ts
4875
5009
  var OPS_MAX_EVENTS_PER_PASS = 50;
4876
- var OPS_MAX_EXTRACT_CHARS = 24e3;
4877
5010
  var RESOLVE_RESERVE_FACTOR = 2;
4878
5011
  var MIN_SEGMENT_CHARS = 500;
4879
5012
  var MAX_SEGMENT_CALLS = 8;
4880
5013
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
4881
- async function selectBatch(deps, entityId, wm, meter, guidance) {
5014
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
4882
5015
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
4883
5016
  if (events.length === 0) return { batch: [] };
5017
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
4884
5018
  let n = 0;
4885
5019
  let chars = 0;
4886
5020
  for (const e of events) {
4887
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
5021
+ if (n > 0 && chars + e.summary.length > extractCap) break;
4888
5022
  chars += e.summary.length;
4889
5023
  n++;
4890
5024
  }
@@ -5223,7 +5357,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
5223
5357
  }
5224
5358
 
5225
5359
  // src/services/librarian/ops/resolve.ts
5226
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
5227
5360
  function validateOp(raw, aliases) {
5228
5361
  if (!raw || typeof raw !== "object") return null;
5229
5362
  const r = raw;
@@ -5242,7 +5375,7 @@ function validateOp(raw, aliases) {
5242
5375
  return update;
5243
5376
  }
5244
5377
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5245
- async function runResolve(deps, ctx, ambiguous) {
5378
+ async function runResolve(deps, ctx, ambiguous, budget) {
5246
5379
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
5247
5380
  if (ambiguous.length === 0) return out;
5248
5381
  const { entityId, trigger } = ctx;
@@ -5268,7 +5401,7 @@ async function runResolve(deps, ctx, ambiguous) {
5268
5401
  onSkip: (g, err) => {
5269
5402
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
5270
5403
  },
5271
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
5404
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
5272
5405
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
5273
5406
  });
5274
5407
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -5477,7 +5610,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5477
5610
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5478
5611
  await deps.seedWatermark(entityId);
5479
5612
  const wm = await deps.getWatermark(entityId);
5480
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
5613
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
5481
5614
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5482
5615
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5483
5616
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5505,7 +5638,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5505
5638
  });
5506
5639
  }
5507
5640
  diagnostics.push(gateDiagnostic);
5508
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
5641
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
5509
5642
  for (const itemIndex of res.overflowSkipped) {
5510
5643
  diagnostics.push({
5511
5644
  entityId,
@@ -5572,8 +5705,8 @@ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HIST
5572
5705
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
5573
5706
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
5574
5707
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
5708
+ var CLASSIFIER_MAX_CHOICES = 255;
5575
5709
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
5576
- var HEAL_MAX_PROMPT_CHARS = 4e4;
5577
5710
  var HEAL_BATCH_SIZE = 25;
5578
5711
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
5579
5712
  var MAX_EMBED_ATTEMPTS = 5;
@@ -6265,6 +6398,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
6265
6398
  this.jobManager.releaseLock("ontologyBackfill", entityId);
6266
6399
  }
6267
6400
  }
6401
+ /**
6402
+ * Scheduler read view (specs/system-one-config §8): untyped facts still
6403
+ * eligible for typing this pass — outside the 7-day recheck cooldown — or 0
6404
+ * when ontology is off for the entity (nothing is ever eligible there).
6405
+ * Read-only: never materializes a seed manifest, never writes.
6406
+ */
6407
+ async pendingOntologyBackfill(entityId) {
6408
+ const ontologyService = this.ontologyService;
6409
+ if (!ontologyService) return 0;
6410
+ const { mode } = await ontologyService.getEffectiveState(entityId);
6411
+ if (mode === "off") return 0;
6412
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, Date.now() - ONTOLOGY_BACKFILL_RECHECK_MS);
6413
+ return counts.eligible;
6414
+ }
6415
+ /**
6416
+ * Emit `ontology_backfill_held` (severity `info`) when the scheduler found
6417
+ * the entity's `ontologyBackfill` lock held by another job. The lock state
6418
+ * names no content, so the fixed template carries all the information a
6419
+ * host needs; `JobManager.isBlocked` does not identify the blocker and the
6420
+ * diagnostic detail surface stays identifier-typed.
6421
+ */
6422
+ noteOntologyBackfillHeld(entityId) {
6423
+ emitDiagnostic(this.options, {
6424
+ code: "ontology_backfill_held",
6425
+ operation: "ontologyBackfill",
6426
+ trigger: "call",
6427
+ entityId
6428
+ });
6429
+ }
6268
6430
  /**
6269
6431
  * Re-embed facts, honouring per-row failure markers and exponential backoff.
6270
6432
  *
@@ -6848,7 +7010,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6848
7010
  };
6849
7011
  },
6850
7012
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6851
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
7013
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
6852
7014
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
6853
7015
  supportsEscalation: true,
6854
7016
  onSkip: (fact, err) => {
@@ -7011,45 +7173,120 @@ DROP TRIGGER IF EXISTS ${ad};`);
7011
7173
  if (!Number.isInteger(batchSize) || batchSize < 1) {
7012
7174
  throw new Error("Invalid batchSize: must be an integer >= 1");
7013
7175
  }
7176
+ if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
7177
+ throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
7178
+ }
7179
+ const trigger = options?.trigger ?? "call";
7014
7180
  const now = Date.now();
7015
7181
  const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
7016
- const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0 };
7182
+ const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
7017
7183
  const ontologyService = this.ontologyService;
7018
7184
  if (!ontologyService) {
7019
7185
  return { ...zeroed, remaining: 0, deferred: 0 };
7020
7186
  }
7021
7187
  const { mode, manifest: effectiveManifest } = await ontologyService.getEffectiveState(entityId);
7022
7188
  if (mode === "off") {
7023
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7024
- return { ...zeroed, remaining: 0, deferred: counts2.deferred };
7189
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7190
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
7025
7191
  }
7026
7192
  const candidates = await this.entryRepo.findUntypedByEntityId(entityId, batchSize, recheckCutoff);
7027
7193
  if (candidates.length === 0) {
7028
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7029
- return { ...zeroed, remaining: counts2.eligible, deferred: counts2.deferred };
7194
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7195
+ return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
7030
7196
  }
7031
- const classifierMode = options?.classifier ?? this.options.config?.ontology?.backfillClassifier ?? "llm";
7197
+ const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
7032
7198
  const classify = this.options.llmProvider.classify;
7033
7199
  if (classifierMode === "auto" && typeof classify === "function") {
7034
7200
  const slugs = effectiveManifest.node_types.map((n) => n.type);
7035
- if (slugs.length > 0 && slugs.length <= 255) {
7036
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
7201
+ if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
7202
+ const classifierRun = await this._runClassifierBackfill(
7203
+ entityId,
7204
+ candidates,
7205
+ effectiveManifest,
7206
+ now,
7207
+ recheckCutoff,
7208
+ options?.meter,
7209
+ trigger
7210
+ );
7211
+ if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
7212
+ return classifierRun.result;
7213
+ }
7214
+ if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
7215
+ const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
7216
+ if (liveMode === "off") {
7217
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7218
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
7219
+ }
7220
+ const escalated = classifierRun.escalated;
7221
+ const generative = await this._runGenerativeBackfill(entityId, escalated, {
7222
+ promptOverride: options?.promptOverride,
7223
+ meter: options?.meter,
7224
+ trigger,
7225
+ batchSize: escalated.length
7226
+ });
7227
+ return {
7228
+ scanned: classifierRun.result.scanned,
7229
+ typed: classifierRun.result.typed + generative.typed,
7230
+ failedValidation: classifierRun.result.failedValidation + generative.failedValidation,
7231
+ edgesAdded: classifierRun.result.edgesAdded + generative.edgesAdded,
7232
+ abstained: classifierRun.result.abstained + generative.abstained,
7233
+ skipped: classifierRun.result.skipped + generative.skipped,
7234
+ remaining: generative.remaining,
7235
+ deferred: generative.deferred,
7236
+ ...generative.budgetStop ? { budgetStop: generative.budgetStop } : {}
7237
+ };
7238
+ }
7239
+ return classifierRun.result;
7037
7240
  }
7038
7241
  }
7242
+ return this._runGenerativeBackfill(entityId, candidates, {
7243
+ promptOverride: options?.promptOverride,
7244
+ meter: options?.meter,
7245
+ trigger
7246
+ });
7247
+ }
7248
+ /**
7249
+ * Low-confidence routing (specs/system-one-config §4): `'leave'` (default)
7250
+ * keeps classifier abstains/low-confidence facts untyped and
7251
+ * cooldown-stamped; `'llm'` escalates them to the generative step. Invalid
7252
+ * config warns once and is treated as unset. Cost/quality setting, not a
7253
+ * safety mechanism — it cannot catch a confidently wrong classifier.
7254
+ */
7255
+ resolveSystemOneOnLowConfidence() {
7256
+ const raw = this.options.config?.systemOne?.onLowConfidence;
7257
+ if (raw !== void 0 && raw !== "leave" && raw !== "llm") {
7258
+ warnOnce(
7259
+ `[core-llm-wiki] systemOne: \`systemOne.onLowConfidence\` is ${formatConfigValue(raw)}, which is not 'leave' or 'llm'. The key is treated as unset; the default ('leave') applies.`
7260
+ );
7261
+ return "leave";
7262
+ }
7263
+ return raw ?? "leave";
7264
+ }
7265
+ /**
7266
+ * Generative-mode backfill step: the original `generateText` pass over
7267
+ * `candidates`. Also the escalation target of the classifier step (§4) —
7268
+ * there `candidates` holds only the escalated facts and `batchSize` is
7269
+ * sized to send them in one batch.
7270
+ */
7271
+ async _runGenerativeBackfill(entityId, candidates, runOpts) {
7272
+ runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
7273
+ const ontologyService = this.ontologyService;
7274
+ const now = Date.now();
7275
+ const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
7039
7276
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
7040
7277
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
7041
7278
  const titleCatalog = buildTitleCatalogBlock(titleRows);
7042
7279
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
7043
7280
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
7044
7281
  facts.map(toPromptShape),
7045
- options?.promptOverride,
7282
+ runOpts.promptOverride,
7046
7283
  ontologyContext,
7047
7284
  titleCatalog
7048
7285
  );
7049
7286
  const outcome = await runBatched({
7050
7287
  items: candidates,
7051
7288
  buildPrompt,
7052
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
7289
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: runOpts.trigger, meter: runOpts.meter }, prompts),
7053
7290
  parse: (responseText, batch) => {
7054
7291
  const parsed = parseJsonResponse(responseText);
7055
7292
  return {
@@ -7065,7 +7302,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7065
7302
  emitDiagnostic(this.options, {
7066
7303
  entityId,
7067
7304
  operation: "ontologyBackfill",
7068
- trigger: "call",
7305
+ trigger: runOpts.trigger,
7069
7306
  code: "context_overflow_skipped",
7070
7307
  detail: { factId: fact.id }
7071
7308
  });
@@ -7080,9 +7317,12 @@ DROP TRIGGER IF EXISTS ${ad};`);
7080
7317
  let failedValidation = 0;
7081
7318
  let edgesAdded = 0;
7082
7319
  let scanned = 0;
7320
+ let abstained = 0;
7083
7321
  let abortedOntologyOff = false;
7322
+ const diagBuffer = new DiagnosticBuffer();
7323
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger: runOpts.trigger };
7084
7324
  for (const batchResult of outcome.results) {
7085
- const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now);
7325
+ const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now, "llm", runOpts.trigger);
7086
7326
  if (applied.abortedOntologyOff) {
7087
7327
  abortedOntologyOff = true;
7088
7328
  break;
@@ -7090,8 +7330,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
7090
7330
  typed += applied.typed;
7091
7331
  failedValidation += applied.failedValidation;
7092
7332
  edgesAdded += applied.edgesAdded;
7333
+ for (const factId of applied.omittedIds) {
7334
+ abstained += 1;
7335
+ diagBuffer.push({
7336
+ ...diagBase,
7337
+ code: "classification_abstained",
7338
+ detail: { factId, writer: "llm" }
7339
+ });
7340
+ }
7093
7341
  scanned += batchResult.batch.length;
7094
7342
  }
7343
+ diagBuffer.flush(this.options);
7095
7344
  if (abortedOntologyOff) {
7096
7345
  const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7097
7346
  return {
@@ -7099,6 +7348,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7099
7348
  typed,
7100
7349
  failedValidation,
7101
7350
  edgesAdded,
7351
+ abstained,
7102
7352
  skipped: outcome.skipped.length,
7103
7353
  remaining: 0,
7104
7354
  deferred: counts2.deferred,
@@ -7123,6 +7373,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7123
7373
  typed,
7124
7374
  failedValidation,
7125
7375
  edgesAdded,
7376
+ abstained,
7126
7377
  skipped: outcome.skipped.length,
7127
7378
  remaining: counts.eligible,
7128
7379
  deferred: counts.deferred,
@@ -7130,20 +7381,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
7130
7381
  };
7131
7382
  }
7132
7383
  /**
7133
- * Classifier-mode backfill (spec §7.3): one `choice` question per untyped
7134
- * fact over the effective manifest's node-type slugs. Accepted answers go
7135
- * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
7136
- * No edges are proposed.
7384
+ * Classifier-mode backfill (spec §7.3, S1-0 §5): one `choice` question per
7385
+ * untyped fact over the effective manifest's node-type slugs plus the
7386
+ * reserved abstain sentinel. Accepted answers go through
7387
+ * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
7388
+ * are proposed. Abstains and low-confidence answers are cooldown-stamped
7389
+ * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
7390
+ * returned un-stamped in `escalated` for the generative step. Always
7391
+ * returns the `OntologyBackfillResult` for its step plus escalation state.
7137
7392
  */
7138
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
7139
- const rawMin = this.options.config?.ontology?.classifyMinConfidence;
7140
- const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
7393
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
7394
+ const minConfidence = resolveTypingMinConfidence(this.options.config);
7141
7395
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
7142
7396
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
7143
7397
  const question = {
7144
7398
  kind: "choice",
7145
- options: manifest.node_types.map((n) => n.type),
7146
- instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7399
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
7400
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
7401
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7147
7402
  };
7148
7403
  let stopped;
7149
7404
  const outcomes = await withConcurrency(
@@ -7153,7 +7408,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7153
7408
  try {
7154
7409
  response = await callClassify(
7155
7410
  this.options,
7156
- { operation: "ontologyBackfill", entityId, trigger: "call", meter },
7411
+ { operation: "ontologyBackfill", entityId, trigger, meter },
7157
7412
  { state: classifierStateForFact(fact), questions: { okf_type: question } }
7158
7413
  );
7159
7414
  } catch (err) {
@@ -7167,37 +7422,47 @@ DROP TRIGGER IF EXISTS ${ad};`);
7167
7422
  const checked = validateClassifierAnswer(response, "okf_type", question);
7168
7423
  if (!checked.ok) return { fact, kind: "invalid", reason: checked.reason };
7169
7424
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
7425
+ if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
7170
7426
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
7171
7427
  return { fact, kind: "accepted", okfType: checked.answer.choice };
7172
7428
  }),
7173
7429
  concurrency
7174
7430
  );
7175
- const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
7431
+ const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
7432
+ const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
7433
+ const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
7434
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
7176
7435
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
7177
7436
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
7178
7437
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
7179
7438
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
7439
+ const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
7180
7440
  let typed = 0;
7181
7441
  let failedValidation = 0;
7182
7442
  let edgesAdded = 0;
7183
- let aborted = false;
7443
+ let abortedOntologyOff = false;
7184
7444
  if (attempted.length > 0) {
7185
7445
  const applied = await this._applyOntologyBackfillBatch(
7186
7446
  entityId,
7187
7447
  { batch: attempted, classifications, ontologyUpdates: void 0 },
7188
- now
7448
+ now,
7449
+ "classifier",
7450
+ trigger
7189
7451
  );
7190
- aborted = applied.abortedOntologyOff;
7191
- if (!aborted) {
7452
+ abortedOntologyOff = applied.abortedOntologyOff;
7453
+ if (!abortedOntologyOff) {
7192
7454
  typed = applied.typed;
7193
7455
  failedValidation = invalidCount + applied.failedValidation;
7194
7456
  edgesAdded = applied.edgesAdded;
7195
7457
  }
7196
7458
  }
7197
7459
  const diagBuffer = new DiagnosticBuffer();
7198
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
7460
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
7199
7461
  for (const o of outcomes) {
7200
- if (o.kind === "low_confidence") {
7462
+ if (o.kind === "abstain") {
7463
+ if (isEscalated(o)) continue;
7464
+ diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
7465
+ } else if (o.kind === "low_confidence") {
7201
7466
  diagBuffer.push({ ...diagBase, code: "classification_low_confidence", detail: { factId: o.fact.id, reason: "below_threshold" } });
7202
7467
  } else if (o.kind === "invalid") {
7203
7468
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
@@ -7209,19 +7474,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
7209
7474
  }
7210
7475
  diagBuffer.flush(this.options);
7211
7476
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7212
- if (aborted) {
7213
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
7477
+ const budgetStop = stopped ? { requiredEstimate: stopped.requiredEstimate } : void 0;
7478
+ if (abortedOntologyOff) {
7479
+ return {
7480
+ result: { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, abstained: 0, skipped, remaining: 0, deferred: counts.deferred, ...budgetStop ? { budgetStop } : {} },
7481
+ escalated: [],
7482
+ abortedOntologyOff
7483
+ };
7214
7484
  }
7215
7485
  this.searchService.evictCache(entityId);
7216
7486
  return {
7217
- scanned: candidates.length - unattemptedCount,
7218
- typed,
7219
- failedValidation,
7220
- edgesAdded,
7221
- skipped,
7222
- remaining: counts.eligible,
7223
- deferred: counts.deferred,
7224
- ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
7487
+ result: {
7488
+ scanned: candidates.length - unattemptedCount,
7489
+ typed,
7490
+ failedValidation,
7491
+ edgesAdded,
7492
+ abstained: abstainCount,
7493
+ skipped,
7494
+ remaining: counts.eligible,
7495
+ deferred: counts.deferred,
7496
+ ...budgetStop ? { budgetStop } : {}
7497
+ },
7498
+ escalated,
7499
+ abortedOntologyOff: false
7225
7500
  };
7226
7501
  }
7227
7502
  /**
@@ -7230,15 +7505,18 @@ DROP TRIGGER IF EXISTS ${ad};`);
7230
7505
  * the mid-flight `mode === 'off'` abort check keep the shape they had when a
7231
7506
  * pass was a single call.
7232
7507
  */
7233
- async _applyOntologyBackfillBatch(entityId, batchResult, now) {
7508
+ async _applyOntologyBackfillBatch(entityId, batchResult, now, writer, trigger) {
7234
7509
  const ontologyService = this.ontologyService;
7235
7510
  const { batch, classifications, ontologyUpdates } = batchResult;
7236
7511
  let typed = 0;
7237
7512
  let failedValidation = 0;
7238
7513
  let edgesAdded = 0;
7239
7514
  let abortedOntologyOff = false;
7515
+ const typedIds = [];
7516
+ const omittedIds = [];
7517
+ const classifiedIds = /* @__PURE__ */ new Set();
7240
7518
  const diagBuffer = new DiagnosticBuffer();
7241
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
7519
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
7242
7520
  await this.db.withTransactionAsync(async (tx) => {
7243
7521
  let { mode: txMode, manifest } = await ontologyService.getEffectiveState(entityId, tx);
7244
7522
  if (txMode === "off") {
@@ -7263,6 +7541,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7263
7541
  continue;
7264
7542
  }
7265
7543
  applied.add(fact.id);
7544
+ classifiedIds.add(fact.id);
7266
7545
  const validationDrops = [];
7267
7546
  const normalized = ontologyService.validateAndNormalizeFact(
7268
7547
  {
@@ -7284,8 +7563,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
7284
7563
  continue;
7285
7564
  }
7286
7565
  const result = await this.entryRepo.updateOkfType(fact.id, entityId, normalized.okf_type, tx);
7287
- if (result.changes === 0) continue;
7566
+ if (result.changes === 0) {
7567
+ omittedIds.push(fact.id);
7568
+ continue;
7569
+ }
7288
7570
  typed++;
7571
+ typedIds.push(fact.id);
7572
+ diagBuffer.push({
7573
+ ...diagBase,
7574
+ code: "node_type_assigned",
7575
+ detail: { factId: fact.id, okfType: normalized.okf_type, writer }
7576
+ });
7289
7577
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
7290
7578
  if (normalized.edges.length > 0) {
7291
7579
  pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
@@ -7311,8 +7599,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
7311
7599
  }
7312
7600
  await this.entryRepo.markOntologyChecked(batch.map((f) => f.id), entityId, now, tx);
7313
7601
  });
7602
+ if (!abortedOntologyOff) {
7603
+ for (const fact of batch) {
7604
+ if (!classifiedIds.has(fact.id)) omittedIds.push(fact.id);
7605
+ }
7606
+ }
7314
7607
  diagBuffer.flush(this.options);
7315
- return { typed, failedValidation, edgesAdded, abortedOntologyOff };
7608
+ return { typed, failedValidation, edgesAdded, abortedOntologyOff, typedIds, omittedIds };
7316
7609
  }
7317
7610
  _validatePruneDuration(value, name) {
7318
7611
  if (value !== null && value !== void 0 && (typeof value !== "number" || !isFinite(value) || value < 0)) {