@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/index.js CHANGED
@@ -30,6 +30,8 @@ var SEVERITY = {
30
30
  grounding_failed: "warn",
31
31
  classification_low_confidence: "info",
32
32
  classification_invalid: "warn",
33
+ classification_abstained: "info",
34
+ node_type_assigned: "info",
33
35
  context_overflow_skipped: "warn",
34
36
  llm_usage: "info",
35
37
  librarian_gate: "info",
@@ -38,6 +40,7 @@ var SEVERITY = {
38
40
  resolve_failed: "warn",
39
41
  read_budget: "info",
40
42
  event_retention_held: "info",
43
+ ontology_backfill_held: "info",
41
44
  prune_checkpoint_incomplete: "warn",
42
45
  erase_secure_delete_off: "error",
43
46
  erase_entity_skipped: "warn",
@@ -76,6 +79,8 @@ var MESSAGE = {
76
79
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
77
80
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
78
81
  classification_invalid: "A classifier answer was invalid and was not applied.",
82
+ classification_abstained: "The typing model declined to classify the fact; it was not typed.",
83
+ node_type_assigned: "A typing run assigned an ontology node type to the fact.",
79
84
  context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
80
85
  llm_usage: "An LLM call completed; token usage attached.",
81
86
  librarian_gate: "Librarian gate outcome counts for one pass.",
@@ -84,6 +89,7 @@ var MESSAGE = {
84
89
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
85
90
  read_budget: "A read was packed to a token budget.",
86
91
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
92
+ ontology_backfill_held: "Ontology backfill was held because another job held the entity\u2019s lock.",
87
93
  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.",
88
94
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
89
95
  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.",
@@ -4517,6 +4523,10 @@ function resolveNodeType(raw, manifest) {
4517
4523
  const hit = manifest.node_types.find((n) => n.type.toLowerCase() === slug.toLowerCase());
4518
4524
  return hit?.type ?? null;
4519
4525
  }
4526
+ var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
4527
+ function isReservedAbstainSlug(raw) {
4528
+ return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
4529
+ }
4520
4530
  function resolveEdgeDefinitions(rawEdgeType, manifest) {
4521
4531
  const slug = rawEdgeType.trim();
4522
4532
  if (!slug) return [];
@@ -7879,6 +7889,74 @@ function toGroundingAnchor(anchor) {
7879
7889
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
7880
7890
  var DEFAULT_CHUNK_OVERLAP = 400;
7881
7891
 
7892
+ // src/utils/contextCaps.ts
7893
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7894
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
7895
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
7896
+
7897
+ // src/config/context.ts
7898
+ var DEFAULT_CHARS_PER_TOKEN = 4;
7899
+ var DEFAULT_SAFETY_FRACTION = 0.9;
7900
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7901
+ var OP_FLOOR = {
7902
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7903
+ heal: HEAL_MAX_PROMPT_CHARS,
7904
+ extract: OPS_MAX_EXTRACT_CHARS
7905
+ };
7906
+ function bad(key, value, why) {
7907
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
7908
+ }
7909
+ function resolveContextBudget(config) {
7910
+ const context = config?.context;
7911
+ if (!context || context.budget === void 0) {
7912
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
7913
+ }
7914
+ if (context.budget !== "legacy" && context.budget !== "declared") {
7915
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
7916
+ }
7917
+ if (context.budget === "legacy") {
7918
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
7919
+ }
7920
+ const window = context.contextWindowTokens;
7921
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
7922
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
7923
+ }
7924
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
7925
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
7926
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
7927
+ }
7928
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
7929
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
7930
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
7931
+ }
7932
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
7933
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
7934
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
7935
+ }
7936
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
7937
+ }
7938
+ function declaredPromptCap(budget, op) {
7939
+ const derived = Math.floor(
7940
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
7941
+ );
7942
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
7943
+ return Math.max(OP_FLOOR.heal, derived);
7944
+ }
7945
+ function resolveMaxPromptChars(budget, op) {
7946
+ if (budget.mode !== "declared") {
7947
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
7948
+ }
7949
+ if (op === "extract") {
7950
+ const resolveDerived = declaredPromptCap(budget, "resolve");
7951
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
7952
+ return Math.max(OP_FLOOR.extract, extractDerived);
7953
+ }
7954
+ return declaredPromptCap(budget, op);
7955
+ }
7956
+ function resolveDefaultChunkLength(budget) {
7957
+ return DEFAULT_MAX_CHUNK_LENGTH;
7958
+ }
7959
+
7882
7960
  // src/utils/usage.ts
7883
7961
  function estimateTokens(text) {
7884
7962
  return Math.ceil(text.length / 4);
@@ -8019,7 +8097,7 @@ var IngestionService = class {
8019
8097
  if (!sourceRef) throw new Error("Invalid sourceRef");
8020
8098
  const sourceHash = normalizeSourceHash(params.sourceHash);
8021
8099
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
8022
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
8100
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
8023
8101
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
8024
8102
  const chunkOverlap = Math.min(
8025
8103
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -8805,6 +8883,9 @@ function resolveLibrarianStrategy(config) {
8805
8883
  function resolveMaintenanceMode(config) {
8806
8884
  return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
8807
8885
  }
8886
+ function resolveContextBudgetOrThrow(config) {
8887
+ return resolveContextBudget(config);
8888
+ }
8808
8889
  function changedDefaultWarnings(config) {
8809
8890
  const warnings = [];
8810
8891
  const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
@@ -8833,6 +8914,61 @@ function warnChangedDefaultsOnce(config) {
8833
8914
  console.warn(message);
8834
8915
  }
8835
8916
  }
8917
+ function warnOnce(message) {
8918
+ if (warnedDefaults.has(message)) return;
8919
+ warnedDefaults.add(message);
8920
+ console.warn(message);
8921
+ }
8922
+ function formatConfigValue(value) {
8923
+ try {
8924
+ const json = JSON.stringify(value);
8925
+ return json ?? String(value);
8926
+ } catch {
8927
+ return `[unserializable: ${typeof value}]`;
8928
+ }
8929
+ }
8930
+ var isTypingMode = (v) => v === "auto" || v === "llm";
8931
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
8932
+ function resolveSystemOneTyping(config, classifierCallOption) {
8933
+ const systemOne = config?.systemOne;
8934
+ const legacy = config?.ontology?.backfillClassifier;
8935
+ const systemOneValid = isTypingMode(systemOne?.typing);
8936
+ const legacyValid = isTypingMode(legacy);
8937
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
8938
+ warnOnce(
8939
+ `[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.`
8940
+ );
8941
+ }
8942
+ if (legacy !== void 0 && !legacyValid) {
8943
+ warnOnce(
8944
+ `[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.`
8945
+ );
8946
+ }
8947
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
8948
+ warnOnce(
8949
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
8950
+ );
8951
+ }
8952
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
8953
+ }
8954
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
8955
+ function resolveTypingMinConfidence(config) {
8956
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
8957
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
8958
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
8959
+ const legacyValid = isConfidenceFloor(legacyFloor);
8960
+ if (systemOneFloor !== void 0 && !systemOneValid) {
8961
+ warnOnce(
8962
+ `[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.`
8963
+ );
8964
+ }
8965
+ if (legacyFloor !== void 0 && !legacyValid) {
8966
+ warnOnce(
8967
+ `[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.`
8968
+ );
8969
+ }
8970
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
8971
+ }
8836
8972
 
8837
8973
  // src/repositories/VectorRemovalRepository.ts
8838
8974
  var CHUNK2 = 500;
@@ -9756,18 +9892,18 @@ function parseValidFrom(v) {
9756
9892
 
9757
9893
  // src/services/librarian/ops/extract.ts
9758
9894
  var OPS_MAX_EVENTS_PER_PASS = 50;
9759
- var OPS_MAX_EXTRACT_CHARS = 24e3;
9760
9895
  var RESOLVE_RESERVE_FACTOR = 2;
9761
9896
  var MIN_SEGMENT_CHARS = 500;
9762
9897
  var MAX_SEGMENT_CALLS = 8;
9763
9898
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
9764
- async function selectBatch(deps, entityId, wm, meter, guidance) {
9899
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
9765
9900
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
9766
9901
  if (events.length === 0) return { batch: [] };
9902
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
9767
9903
  let n = 0;
9768
9904
  let chars = 0;
9769
9905
  for (const e of events) {
9770
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
9906
+ if (n > 0 && chars + e.summary.length > extractCap) break;
9771
9907
  chars += e.summary.length;
9772
9908
  n++;
9773
9909
  }
@@ -10093,7 +10229,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
10093
10229
  }
10094
10230
 
10095
10231
  // src/services/librarian/ops/resolve.ts
10096
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
10097
10232
  function validateOp(raw, aliases) {
10098
10233
  if (!raw || typeof raw !== "object") return null;
10099
10234
  const r = raw;
@@ -10112,7 +10247,7 @@ function validateOp(raw, aliases) {
10112
10247
  return update;
10113
10248
  }
10114
10249
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
10115
- async function runResolve(deps, ctx, ambiguous) {
10250
+ async function runResolve(deps, ctx, ambiguous, budget) {
10116
10251
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
10117
10252
  if (ambiguous.length === 0) return out;
10118
10253
  const { entityId, trigger } = ctx;
@@ -10138,7 +10273,7 @@ async function runResolve(deps, ctx, ambiguous) {
10138
10273
  onSkip: (g, err) => {
10139
10274
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
10140
10275
  },
10141
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
10276
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
10142
10277
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
10143
10278
  });
10144
10279
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -10347,7 +10482,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10347
10482
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
10348
10483
  await deps.seedWatermark(entityId);
10349
10484
  const wm = await deps.getWatermark(entityId);
10350
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
10485
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
10351
10486
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
10352
10487
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
10353
10488
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -10375,7 +10510,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10375
10510
  });
10376
10511
  }
10377
10512
  diagnostics.push(gateDiagnostic);
10378
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
10513
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
10379
10514
  for (const itemIndex of res.overflowSkipped) {
10380
10515
  diagnostics.push({
10381
10516
  entityId,
@@ -10442,8 +10577,8 @@ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HIST
10442
10577
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
10443
10578
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
10444
10579
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10580
+ var CLASSIFIER_MAX_CHOICES = 255;
10445
10581
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
10446
- var HEAL_MAX_PROMPT_CHARS = 4e4;
10447
10582
  var HEAL_BATCH_SIZE = 25;
10448
10583
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10449
10584
  var MAX_EMBED_ATTEMPTS = 5;
@@ -11135,6 +11270,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
11135
11270
  this.jobManager.releaseLock("ontologyBackfill", entityId);
11136
11271
  }
11137
11272
  }
11273
+ /**
11274
+ * Scheduler read view (specs/system-one-config §8): untyped facts still
11275
+ * eligible for typing this pass — outside the 7-day recheck cooldown — or 0
11276
+ * when ontology is off for the entity (nothing is ever eligible there).
11277
+ * Read-only: never materializes a seed manifest, never writes.
11278
+ */
11279
+ async pendingOntologyBackfill(entityId) {
11280
+ const ontologyService = this.ontologyService;
11281
+ if (!ontologyService) return 0;
11282
+ const { mode } = await ontologyService.getEffectiveState(entityId);
11283
+ if (mode === "off") return 0;
11284
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, Date.now() - ONTOLOGY_BACKFILL_RECHECK_MS);
11285
+ return counts.eligible;
11286
+ }
11287
+ /**
11288
+ * Emit `ontology_backfill_held` (severity `info`) when the scheduler found
11289
+ * the entity's `ontologyBackfill` lock held by another job. The lock state
11290
+ * names no content, so the fixed template carries all the information a
11291
+ * host needs; `JobManager.isBlocked` does not identify the blocker and the
11292
+ * diagnostic detail surface stays identifier-typed.
11293
+ */
11294
+ noteOntologyBackfillHeld(entityId) {
11295
+ emitDiagnostic(this.options, {
11296
+ code: "ontology_backfill_held",
11297
+ operation: "ontologyBackfill",
11298
+ trigger: "call",
11299
+ entityId
11300
+ });
11301
+ }
11138
11302
  /**
11139
11303
  * Re-embed facts, honouring per-row failure markers and exponential backoff.
11140
11304
  *
@@ -11718,7 +11882,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11718
11882
  };
11719
11883
  },
11720
11884
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
11721
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
11885
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
11722
11886
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
11723
11887
  supportsEscalation: true,
11724
11888
  onSkip: (fact, err) => {
@@ -11881,45 +12045,120 @@ DROP TRIGGER IF EXISTS ${ad};`);
11881
12045
  if (!Number.isInteger(batchSize) || batchSize < 1) {
11882
12046
  throw new Error("Invalid batchSize: must be an integer >= 1");
11883
12047
  }
12048
+ if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
12049
+ throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
12050
+ }
12051
+ const trigger = options?.trigger ?? "call";
11884
12052
  const now = Date.now();
11885
12053
  const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
11886
- const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0 };
12054
+ const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
11887
12055
  const ontologyService = this.ontologyService;
11888
12056
  if (!ontologyService) {
11889
12057
  return { ...zeroed, remaining: 0, deferred: 0 };
11890
12058
  }
11891
12059
  const { mode, manifest: effectiveManifest } = await ontologyService.getEffectiveState(entityId);
11892
12060
  if (mode === "off") {
11893
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
11894
- return { ...zeroed, remaining: 0, deferred: counts2.deferred };
12061
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
12062
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
11895
12063
  }
11896
12064
  const candidates = await this.entryRepo.findUntypedByEntityId(entityId, batchSize, recheckCutoff);
11897
12065
  if (candidates.length === 0) {
11898
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
11899
- return { ...zeroed, remaining: counts2.eligible, deferred: counts2.deferred };
12066
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
12067
+ return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
11900
12068
  }
11901
- const classifierMode = options?.classifier ?? this.options.config?.ontology?.backfillClassifier ?? "llm";
12069
+ const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
11902
12070
  const classify = this.options.llmProvider.classify;
11903
12071
  if (classifierMode === "auto" && typeof classify === "function") {
11904
12072
  const slugs = effectiveManifest.node_types.map((n) => n.type);
11905
- if (slugs.length > 0 && slugs.length <= 255) {
11906
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
12073
+ if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
12074
+ const classifierRun = await this._runClassifierBackfill(
12075
+ entityId,
12076
+ candidates,
12077
+ effectiveManifest,
12078
+ now,
12079
+ recheckCutoff,
12080
+ options?.meter,
12081
+ trigger
12082
+ );
12083
+ if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
12084
+ return classifierRun.result;
12085
+ }
12086
+ if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
12087
+ const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
12088
+ if (liveMode === "off") {
12089
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
12090
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
12091
+ }
12092
+ const escalated = classifierRun.escalated;
12093
+ const generative = await this._runGenerativeBackfill(entityId, escalated, {
12094
+ promptOverride: options?.promptOverride,
12095
+ meter: options?.meter,
12096
+ trigger,
12097
+ batchSize: escalated.length
12098
+ });
12099
+ return {
12100
+ scanned: classifierRun.result.scanned,
12101
+ typed: classifierRun.result.typed + generative.typed,
12102
+ failedValidation: classifierRun.result.failedValidation + generative.failedValidation,
12103
+ edgesAdded: classifierRun.result.edgesAdded + generative.edgesAdded,
12104
+ abstained: classifierRun.result.abstained + generative.abstained,
12105
+ skipped: classifierRun.result.skipped + generative.skipped,
12106
+ remaining: generative.remaining,
12107
+ deferred: generative.deferred,
12108
+ ...generative.budgetStop ? { budgetStop: generative.budgetStop } : {}
12109
+ };
12110
+ }
12111
+ return classifierRun.result;
11907
12112
  }
11908
12113
  }
12114
+ return this._runGenerativeBackfill(entityId, candidates, {
12115
+ promptOverride: options?.promptOverride,
12116
+ meter: options?.meter,
12117
+ trigger
12118
+ });
12119
+ }
12120
+ /**
12121
+ * Low-confidence routing (specs/system-one-config §4): `'leave'` (default)
12122
+ * keeps classifier abstains/low-confidence facts untyped and
12123
+ * cooldown-stamped; `'llm'` escalates them to the generative step. Invalid
12124
+ * config warns once and is treated as unset. Cost/quality setting, not a
12125
+ * safety mechanism — it cannot catch a confidently wrong classifier.
12126
+ */
12127
+ resolveSystemOneOnLowConfidence() {
12128
+ const raw = this.options.config?.systemOne?.onLowConfidence;
12129
+ if (raw !== void 0 && raw !== "leave" && raw !== "llm") {
12130
+ warnOnce(
12131
+ `[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.`
12132
+ );
12133
+ return "leave";
12134
+ }
12135
+ return raw ?? "leave";
12136
+ }
12137
+ /**
12138
+ * Generative-mode backfill step: the original `generateText` pass over
12139
+ * `candidates`. Also the escalation target of the classifier step (§4) —
12140
+ * there `candidates` holds only the escalated facts and `batchSize` is
12141
+ * sized to send them in one batch.
12142
+ */
12143
+ async _runGenerativeBackfill(entityId, candidates, runOpts) {
12144
+ runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
12145
+ const ontologyService = this.ontologyService;
12146
+ const now = Date.now();
12147
+ const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
11909
12148
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
11910
12149
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
11911
12150
  const titleCatalog = buildTitleCatalogBlock(titleRows);
11912
12151
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
11913
12152
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
11914
12153
  facts.map(toPromptShape),
11915
- options?.promptOverride,
12154
+ runOpts.promptOverride,
11916
12155
  ontologyContext,
11917
12156
  titleCatalog
11918
12157
  );
11919
12158
  const outcome = await runBatched({
11920
12159
  items: candidates,
11921
12160
  buildPrompt,
11922
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
12161
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: runOpts.trigger, meter: runOpts.meter }, prompts),
11923
12162
  parse: (responseText, batch) => {
11924
12163
  const parsed = parseJsonResponse(responseText);
11925
12164
  return {
@@ -11935,7 +12174,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11935
12174
  emitDiagnostic(this.options, {
11936
12175
  entityId,
11937
12176
  operation: "ontologyBackfill",
11938
- trigger: "call",
12177
+ trigger: runOpts.trigger,
11939
12178
  code: "context_overflow_skipped",
11940
12179
  detail: { factId: fact.id }
11941
12180
  });
@@ -11950,9 +12189,12 @@ DROP TRIGGER IF EXISTS ${ad};`);
11950
12189
  let failedValidation = 0;
11951
12190
  let edgesAdded = 0;
11952
12191
  let scanned = 0;
12192
+ let abstained = 0;
11953
12193
  let abortedOntologyOff = false;
12194
+ const diagBuffer = new DiagnosticBuffer();
12195
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger: runOpts.trigger };
11954
12196
  for (const batchResult of outcome.results) {
11955
- const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now);
12197
+ const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now, "llm", runOpts.trigger);
11956
12198
  if (applied.abortedOntologyOff) {
11957
12199
  abortedOntologyOff = true;
11958
12200
  break;
@@ -11960,8 +12202,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
11960
12202
  typed += applied.typed;
11961
12203
  failedValidation += applied.failedValidation;
11962
12204
  edgesAdded += applied.edgesAdded;
12205
+ for (const factId of applied.omittedIds) {
12206
+ abstained += 1;
12207
+ diagBuffer.push({
12208
+ ...diagBase,
12209
+ code: "classification_abstained",
12210
+ detail: { factId, writer: "llm" }
12211
+ });
12212
+ }
11963
12213
  scanned += batchResult.batch.length;
11964
12214
  }
12215
+ diagBuffer.flush(this.options);
11965
12216
  if (abortedOntologyOff) {
11966
12217
  const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
11967
12218
  return {
@@ -11969,6 +12220,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11969
12220
  typed,
11970
12221
  failedValidation,
11971
12222
  edgesAdded,
12223
+ abstained,
11972
12224
  skipped: outcome.skipped.length,
11973
12225
  remaining: 0,
11974
12226
  deferred: counts2.deferred,
@@ -11993,6 +12245,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11993
12245
  typed,
11994
12246
  failedValidation,
11995
12247
  edgesAdded,
12248
+ abstained,
11996
12249
  skipped: outcome.skipped.length,
11997
12250
  remaining: counts.eligible,
11998
12251
  deferred: counts.deferred,
@@ -12000,20 +12253,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
12000
12253
  };
12001
12254
  }
12002
12255
  /**
12003
- * Classifier-mode backfill (spec §7.3): one `choice` question per untyped
12004
- * fact over the effective manifest's node-type slugs. Accepted answers go
12005
- * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
12006
- * No edges are proposed.
12256
+ * Classifier-mode backfill (spec §7.3, S1-0 §5): one `choice` question per
12257
+ * untyped fact over the effective manifest's node-type slugs plus the
12258
+ * reserved abstain sentinel. Accepted answers go through
12259
+ * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
12260
+ * are proposed. Abstains and low-confidence answers are cooldown-stamped
12261
+ * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
12262
+ * returned un-stamped in `escalated` for the generative step. Always
12263
+ * returns the `OntologyBackfillResult` for its step plus escalation state.
12007
12264
  */
12008
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
12009
- const rawMin = this.options.config?.ontology?.classifyMinConfidence;
12010
- const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
12265
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
12266
+ const minConfidence = resolveTypingMinConfidence(this.options.config);
12011
12267
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
12012
12268
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
12013
12269
  const question = {
12014
12270
  kind: "choice",
12015
- options: manifest.node_types.map((n) => n.type),
12016
- instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
12271
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
12272
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
12273
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
12017
12274
  };
12018
12275
  let stopped;
12019
12276
  const outcomes = await withConcurrency(
@@ -12023,7 +12280,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12023
12280
  try {
12024
12281
  response = await callClassify(
12025
12282
  this.options,
12026
- { operation: "ontologyBackfill", entityId, trigger: "call", meter },
12283
+ { operation: "ontologyBackfill", entityId, trigger, meter },
12027
12284
  { state: classifierStateForFact(fact), questions: { okf_type: question } }
12028
12285
  );
12029
12286
  } catch (err) {
@@ -12037,37 +12294,47 @@ DROP TRIGGER IF EXISTS ${ad};`);
12037
12294
  const checked = validateClassifierAnswer(response, "okf_type", question);
12038
12295
  if (!checked.ok) return { fact, kind: "invalid", reason: checked.reason };
12039
12296
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
12297
+ if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
12040
12298
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
12041
12299
  return { fact, kind: "accepted", okfType: checked.answer.choice };
12042
12300
  }),
12043
12301
  concurrency
12044
12302
  );
12045
- const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
12303
+ const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
12304
+ const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
12305
+ const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
12306
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
12046
12307
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
12047
12308
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
12048
12309
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
12049
12310
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
12311
+ const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
12050
12312
  let typed = 0;
12051
12313
  let failedValidation = 0;
12052
12314
  let edgesAdded = 0;
12053
- let aborted = false;
12315
+ let abortedOntologyOff = false;
12054
12316
  if (attempted.length > 0) {
12055
12317
  const applied = await this._applyOntologyBackfillBatch(
12056
12318
  entityId,
12057
12319
  { batch: attempted, classifications, ontologyUpdates: void 0 },
12058
- now
12320
+ now,
12321
+ "classifier",
12322
+ trigger
12059
12323
  );
12060
- aborted = applied.abortedOntologyOff;
12061
- if (!aborted) {
12324
+ abortedOntologyOff = applied.abortedOntologyOff;
12325
+ if (!abortedOntologyOff) {
12062
12326
  typed = applied.typed;
12063
12327
  failedValidation = invalidCount + applied.failedValidation;
12064
12328
  edgesAdded = applied.edgesAdded;
12065
12329
  }
12066
12330
  }
12067
12331
  const diagBuffer = new DiagnosticBuffer();
12068
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
12332
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
12069
12333
  for (const o of outcomes) {
12070
- if (o.kind === "low_confidence") {
12334
+ if (o.kind === "abstain") {
12335
+ if (isEscalated(o)) continue;
12336
+ diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
12337
+ } else if (o.kind === "low_confidence") {
12071
12338
  diagBuffer.push({ ...diagBase, code: "classification_low_confidence", detail: { factId: o.fact.id, reason: "below_threshold" } });
12072
12339
  } else if (o.kind === "invalid") {
12073
12340
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
@@ -12079,19 +12346,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
12079
12346
  }
12080
12347
  diagBuffer.flush(this.options);
12081
12348
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
12082
- if (aborted) {
12083
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
12349
+ const budgetStop = stopped ? { requiredEstimate: stopped.requiredEstimate } : void 0;
12350
+ if (abortedOntologyOff) {
12351
+ return {
12352
+ result: { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, abstained: 0, skipped, remaining: 0, deferred: counts.deferred, ...budgetStop ? { budgetStop } : {} },
12353
+ escalated: [],
12354
+ abortedOntologyOff
12355
+ };
12084
12356
  }
12085
12357
  this.searchService.evictCache(entityId);
12086
12358
  return {
12087
- scanned: candidates.length - unattemptedCount,
12088
- typed,
12089
- failedValidation,
12090
- edgesAdded,
12091
- skipped,
12092
- remaining: counts.eligible,
12093
- deferred: counts.deferred,
12094
- ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
12359
+ result: {
12360
+ scanned: candidates.length - unattemptedCount,
12361
+ typed,
12362
+ failedValidation,
12363
+ edgesAdded,
12364
+ abstained: abstainCount,
12365
+ skipped,
12366
+ remaining: counts.eligible,
12367
+ deferred: counts.deferred,
12368
+ ...budgetStop ? { budgetStop } : {}
12369
+ },
12370
+ escalated,
12371
+ abortedOntologyOff: false
12095
12372
  };
12096
12373
  }
12097
12374
  /**
@@ -12100,15 +12377,18 @@ DROP TRIGGER IF EXISTS ${ad};`);
12100
12377
  * the mid-flight `mode === 'off'` abort check keep the shape they had when a
12101
12378
  * pass was a single call.
12102
12379
  */
12103
- async _applyOntologyBackfillBatch(entityId, batchResult, now) {
12380
+ async _applyOntologyBackfillBatch(entityId, batchResult, now, writer, trigger) {
12104
12381
  const ontologyService = this.ontologyService;
12105
12382
  const { batch, classifications, ontologyUpdates } = batchResult;
12106
12383
  let typed = 0;
12107
12384
  let failedValidation = 0;
12108
12385
  let edgesAdded = 0;
12109
12386
  let abortedOntologyOff = false;
12387
+ const typedIds = [];
12388
+ const omittedIds = [];
12389
+ const classifiedIds = /* @__PURE__ */ new Set();
12110
12390
  const diagBuffer = new DiagnosticBuffer();
12111
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
12391
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
12112
12392
  await this.db.withTransactionAsync(async (tx) => {
12113
12393
  let { mode: txMode, manifest } = await ontologyService.getEffectiveState(entityId, tx);
12114
12394
  if (txMode === "off") {
@@ -12133,6 +12413,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12133
12413
  continue;
12134
12414
  }
12135
12415
  applied.add(fact.id);
12416
+ classifiedIds.add(fact.id);
12136
12417
  const validationDrops = [];
12137
12418
  const normalized = ontologyService.validateAndNormalizeFact(
12138
12419
  {
@@ -12154,8 +12435,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
12154
12435
  continue;
12155
12436
  }
12156
12437
  const result = await this.entryRepo.updateOkfType(fact.id, entityId, normalized.okf_type, tx);
12157
- if (result.changes === 0) continue;
12438
+ if (result.changes === 0) {
12439
+ omittedIds.push(fact.id);
12440
+ continue;
12441
+ }
12158
12442
  typed++;
12443
+ typedIds.push(fact.id);
12444
+ diagBuffer.push({
12445
+ ...diagBase,
12446
+ code: "node_type_assigned",
12447
+ detail: { factId: fact.id, okfType: normalized.okf_type, writer }
12448
+ });
12159
12449
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
12160
12450
  if (normalized.edges.length > 0) {
12161
12451
  pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
@@ -12181,8 +12471,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
12181
12471
  }
12182
12472
  await this.entryRepo.markOntologyChecked(batch.map((f) => f.id), entityId, now, tx);
12183
12473
  });
12474
+ if (!abortedOntologyOff) {
12475
+ for (const fact of batch) {
12476
+ if (!classifiedIds.has(fact.id)) omittedIds.push(fact.id);
12477
+ }
12478
+ }
12184
12479
  diagBuffer.flush(this.options);
12185
- return { typed, failedValidation, edgesAdded, abortedOntologyOff };
12480
+ return { typed, failedValidation, edgesAdded, abortedOntologyOff, typedIds, omittedIds };
12186
12481
  }
12187
12482
  _validatePruneDuration(value, name) {
12188
12483
  if (value !== null && value !== void 0 && (typeof value !== "number" || !isFinite(value) || value < 0)) {
@@ -12242,6 +12537,14 @@ DROP TRIGGER IF EXISTS ${ad};`);
12242
12537
  _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
12243
12538
  var MaintenanceService = _MaintenanceService;
12244
12539
 
12540
+ // src/utils/config/ontologyJobDefaults.ts
12541
+ var DEFAULT_ONTOLOGY_JOB_BATCH_SIZE = 50;
12542
+ function resolveOntologyJobDefaults(ontology) {
12543
+ const raw = ontology?.schedulerBatchSize;
12544
+ const batchSize = typeof raw === "number" && Number.isInteger(raw) && raw >= 1 ? raw : DEFAULT_ONTOLOGY_JOB_BATCH_SIZE;
12545
+ return { batchSize };
12546
+ }
12547
+
12245
12548
  // src/services/MaintenanceScheduler.ts
12246
12549
  var MaintenanceScheduler = class {
12247
12550
  constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
@@ -12254,6 +12557,8 @@ var MaintenanceScheduler = class {
12254
12557
  this.jobManager = jobManager;
12255
12558
  this.vectorRemovalService = vectorRemovalService;
12256
12559
  this.vectorRemovalRepo = vectorRemovalRepo;
12560
+ /** Batch size for scheduler-driven ontology passes; resolved once (spec §8). */
12561
+ this.schedulerBatchSize = resolveOntologyJobDefaults(this.options.config?.ontology).batchSize;
12257
12562
  }
12258
12563
  /**
12259
12564
  * Entities with **any** pending work only, sorted by `pendingEvents` desc
@@ -12286,14 +12591,16 @@ var MaintenanceScheduler = class {
12286
12591
  const healDue = eventCount - healCheckpoint >= autoHealThreshold;
12287
12592
  const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
12288
12593
  const owedCount = owed.get(entityId) ?? 0;
12289
- if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
12594
+ const ontologyBackfillPending = await this.maintenanceService.pendingOntologyBackfill(entityId);
12595
+ if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0 || ontologyBackfillPending > 0) {
12290
12596
  out.push({
12291
12597
  entityId,
12292
12598
  pendingEvents,
12293
12599
  pendingTokensEstimate: Math.ceil(chars / 4),
12294
12600
  healDue,
12295
12601
  reembedPending,
12296
- ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
12602
+ ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {},
12603
+ ...ontologyBackfillPending > 0 ? { pendingOntologyBackfill: ontologyBackfillPending } : {}
12297
12604
  });
12298
12605
  }
12299
12606
  }
@@ -12320,15 +12627,16 @@ var MaintenanceScheduler = class {
12320
12627
  const meter = new UsageMeter(opts.tokenBudget);
12321
12628
  const budget = opts.tokenBudget;
12322
12629
  const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
12323
- const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
12630
+ const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions", "ontologyBackfill"]);
12324
12631
  const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
12325
- const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
12632
+ const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending || (p.pendingOntologyBackfill ?? 0) > 0);
12326
12633
  const states = pending.map((p) => ({
12327
12634
  p,
12328
- report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
12635
+ report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false, ontologyBackfillPasses: 0, typed: 0 },
12329
12636
  librarian: jobs.has("librarian") && p.pendingEvents > 0,
12330
12637
  heal: jobs.has("heal") && p.healDue,
12331
- reembed: jobs.has("reembed") && p.reembedPending
12638
+ reembed: jobs.has("reembed") && p.reembedPending,
12639
+ ontology: jobs.has("ontologyBackfill") && (p.pendingOntologyBackfill ?? 0) > 0
12332
12640
  }));
12333
12641
  let stopped = { reason: "complete" };
12334
12642
  let tooSmall = null;
@@ -12348,12 +12656,12 @@ var MaintenanceScheduler = class {
12348
12656
  var _a;
12349
12657
  ((_a = st.report).searchUnavailable ?? (_a.searchUnavailable = [])).push(job);
12350
12658
  };
12351
- const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed, 0);
12659
+ const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed + +s.ontology, 0);
12352
12660
  rounds: for (; ; ) {
12353
12661
  let progressed = false;
12354
12662
  const openAtStart = openJobs();
12355
12663
  for (const st of states) {
12356
- if (!st.librarian && !st.heal && !st.reembed) continue;
12664
+ if (!st.librarian && !st.heal && !st.reembed && !st.ontology) continue;
12357
12665
  if (Date.now() >= deadline) {
12358
12666
  stopped = { reason: "deadline" };
12359
12667
  break rounds;
@@ -12445,6 +12753,42 @@ var MaintenanceScheduler = class {
12445
12753
  else throw err;
12446
12754
  }
12447
12755
  }
12756
+ if (st.ontology) {
12757
+ if (Date.now() >= deadline) {
12758
+ stopped = { reason: "deadline" };
12759
+ break rounds;
12760
+ }
12761
+ st.ontology = false;
12762
+ if (this.jobManager.isBlocked("ontologyBackfill", entityId)) {
12763
+ markBusy(st, "ontologyBackfill");
12764
+ this.maintenanceService.noteOntologyBackfillHeld(entityId);
12765
+ progressed = true;
12766
+ continue;
12767
+ }
12768
+ this.jobManager.acquireLock("ontologyBackfill", entityId);
12769
+ let r;
12770
+ try {
12771
+ r = await this.maintenanceService.doRunOntologyBackfill(entityId, {
12772
+ meter,
12773
+ batchSize: this.schedulerBatchSize
12774
+ });
12775
+ } finally {
12776
+ this.jobManager.releaseLock("ontologyBackfill", entityId);
12777
+ }
12778
+ st.report.ontologyBackfillPasses++;
12779
+ st.report.typed += r.typed;
12780
+ progressed = true;
12781
+ if (r.budgetStop) {
12782
+ if (classify("ontologyBackfill", entityId, r.budgetStop.requiredEstimate) === "exhausted") {
12783
+ stopped = exhaustedStop();
12784
+ break rounds;
12785
+ }
12786
+ continue;
12787
+ }
12788
+ if (r.remaining === 0 || r.typed === 0) {
12789
+ continue;
12790
+ }
12791
+ }
12448
12792
  }
12449
12793
  if (!progressed && openJobs() === openAtStart) break;
12450
12794
  }
@@ -14739,7 +15083,8 @@ var OntologyService = class {
14739
15083
  return buildOntologyPromptAppendix(mode, manifestJson);
14740
15084
  }
14741
15085
  async mergeEmergentUpdates(entityId, updates, tx) {
14742
- const merged = await this.metadataRepo.mergeManifestUpdates(entityId, updates, tx);
15086
+ const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
15087
+ const merged = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
14743
15088
  this.invalidateCache(entityId);
14744
15089
  return merged;
14745
15090
  }
@@ -15294,6 +15639,7 @@ var WikiMemory = class {
15294
15639
  this.db = withSerializedTransactions(db);
15295
15640
  this.options = options;
15296
15641
  warnChangedDefaultsOnce(options.config);
15642
+ resolveContextBudgetOrThrow(options.config);
15297
15643
  this.prefix = options.config?.tablePrefix ?? "llm_wiki_";
15298
15644
  if (!TABLE_PREFIX_PATTERN.test(this.prefix)) {
15299
15645
  throw new Error(
@@ -16334,6 +16680,13 @@ var WikiMemory = class {
16334
16680
  }
16335
16681
  for (const entry of entries) {
16336
16682
  validateManifest(entry.manifest);
16683
+ for (const nodeType of entry.manifest.node_types ?? []) {
16684
+ if (isReservedAbstainSlug(nodeType.type)) {
16685
+ throw new Error(
16686
+ `Invalid node type '${nodeType.type}': '${ONTOLOGY_ABSTAIN_SENTINEL}' is reserved for classifier abstention and cannot be declared in a manifest`
16687
+ );
16688
+ }
16689
+ }
16337
16690
  }
16338
16691
  const written = [];
16339
16692
  const skipped = [];
@@ -17403,6 +17756,11 @@ function parseOkfBundle(entityId, files, options) {
17403
17756
  };
17404
17757
  }
17405
17758
 
17759
+ // src/utils/contextBudget.ts
17760
+ function estimateTokensWith(budget, text) {
17761
+ return Math.ceil(text.length / budget.charsPerToken);
17762
+ }
17763
+
17406
17764
  // src/librarianPrompt.ts
17407
17765
  var DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = `You are a careful memory synthesis assistant.
17408
17766
  Use only the retrieved context when answering the request.
@@ -17447,12 +17805,15 @@ function createWiki(db, options) {
17447
17805
  return new WikiMemory(db, options);
17448
17806
  }
17449
17807
 
17808
+ exports.CLASSIFIER_MAX_CHOICES = CLASSIFIER_MAX_CHOICES;
17450
17809
  exports.CheckpointIncompleteError = CheckpointIncompleteError;
17451
17810
  exports.DEFAULT_CHUNK_OVERLAP = DEFAULT_CHUNK_OVERLAP;
17452
17811
  exports.DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT;
17453
17812
  exports.DEFAULT_MAX_CHUNK_LENGTH = DEFAULT_MAX_CHUNK_LENGTH;
17454
17813
  exports.DEFAULT_MAX_EMBED_CHARS = DEFAULT_MAX_EMBED_CHARS;
17814
+ exports.DEFAULT_ONTOLOGY_JOB_BATCH_SIZE = DEFAULT_ONTOLOGY_JOB_BATCH_SIZE;
17455
17815
  exports.DEFAULT_SETUP_BUDGET_MS = DEFAULT_SETUP_BUDGET_MS;
17816
+ exports.DEFAULT_TYPING_MIN_CONFIDENCE = DEFAULT_TYPING_MIN_CONFIDENCE;
17456
17817
  exports.EMBED_CHARS_CEILING = EMBED_CHARS_CEILING;
17457
17818
  exports.EraseStepError = EraseStepError;
17458
17819
  exports.HEAL_ANCHORS_PER_CANDIDATE = HEAL_ANCHORS_PER_CANDIDATE;
@@ -17461,6 +17822,7 @@ exports.HEAL_MAX_FACT_BODY_CHARS_L3 = HEAL_MAX_FACT_BODY_CHARS_L3;
17461
17822
  exports.HEAL_MAX_TASKS = HEAL_MAX_TASKS;
17462
17823
  exports.HEAL_RECHECK_MS = HEAL_RECHECK_MS;
17463
17824
  exports.HOOK_TIMEOUT_MARKER = HOOK_TIMEOUT_MARKER;
17825
+ exports.ONTOLOGY_ABSTAIN_SENTINEL = ONTOLOGY_ABSTAIN_SENTINEL;
17464
17826
  exports.ONTOLOGY_BACKFILL_BATCH_SIZE = ONTOLOGY_BACKFILL_BATCH_SIZE;
17465
17827
  exports.ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS;
17466
17828
  exports.ONTOLOGY_BACKFILL_RECHECK_MS = ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -17486,18 +17848,27 @@ exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
17486
17848
  exports.chunkText = chunkText;
17487
17849
  exports.configureRandomSource = configureRandomSource;
17488
17850
  exports.createWiki = createWiki;
17851
+ exports.estimateTokensWith = estimateTokensWith;
17489
17852
  exports.formatContext = formatContext;
17490
17853
  exports.formatGraphContext = formatGraphContext;
17491
17854
  exports.formatMemoryDump = formatMemoryDump;
17492
17855
  exports.formatOkfBundle = formatOkfBundle;
17493
17856
  exports.hydrateLibrarianPrompt = hydrateLibrarianPrompt;
17857
+ exports.isReservedAbstainSlug = isReservedAbstainSlug;
17494
17858
  exports.isWikiSearchUnavailableError = isWikiSearchUnavailableError;
17495
17859
  exports.mapLibrarianOptionsToReadOptions = mapLibrarianOptionsToReadOptions;
17496
17860
  exports.parseEmbedding = parseEmbedding;
17497
17861
  exports.parseOkfBundle = parseOkfBundle;
17862
+ exports.resolveContextBudget = resolveContextBudget;
17863
+ exports.resolveDefaultChunkLength = resolveDefaultChunkLength;
17864
+ exports.resolveMaxPromptChars = resolveMaxPromptChars;
17865
+ exports.resolveOntologyJobDefaults = resolveOntologyJobDefaults;
17866
+ exports.resolveSystemOneTyping = resolveSystemOneTyping;
17867
+ exports.resolveTypingMinConfidence = resolveTypingMinConfidence;
17498
17868
  exports.safeSlice = safeSlice;
17499
17869
  exports.validUsage = validUsage;
17500
17870
  exports.validateLibrarianPromptTemplate = validateLibrarianPromptTemplate;
17501
17871
  exports.validateManifest = validateManifest;
17872
+ exports.warnOnce = warnOnce;
17502
17873
  //# sourceMappingURL=index.js.map
17503
17874
  //# sourceMappingURL=index.js.map