@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.
@@ -781,6 +781,10 @@ function resolveNodeType(raw, manifest) {
781
781
  const hit = manifest.node_types.find((n) => n.type.toLowerCase() === slug.toLowerCase());
782
782
  return hit?.type ?? null;
783
783
  }
784
+ var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
785
+ function isReservedAbstainSlug(raw) {
786
+ return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
787
+ }
784
788
  function resolveEdgeDefinitions(rawEdgeType, manifest) {
785
789
  const slug = rawEdgeType.trim();
786
790
  if (!slug) return [];
@@ -2725,6 +2729,74 @@ function toGroundingAnchor(anchor) {
2725
2729
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
2726
2730
  var DEFAULT_CHUNK_OVERLAP = 400;
2727
2731
 
2732
+ // src/utils/contextCaps.ts
2733
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
2734
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
2735
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
2736
+
2737
+ // src/config/context.ts
2738
+ var DEFAULT_CHARS_PER_TOKEN = 4;
2739
+ var DEFAULT_SAFETY_FRACTION = 0.9;
2740
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
2741
+ var OP_FLOOR = {
2742
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
2743
+ heal: HEAL_MAX_PROMPT_CHARS,
2744
+ extract: OPS_MAX_EXTRACT_CHARS
2745
+ };
2746
+ function bad(key, value, why) {
2747
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
2748
+ }
2749
+ function resolveContextBudget(config) {
2750
+ const context = config?.context;
2751
+ if (!context || context.budget === void 0) {
2752
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2753
+ }
2754
+ if (context.budget !== "legacy" && context.budget !== "declared") {
2755
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
2756
+ }
2757
+ if (context.budget === "legacy") {
2758
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2759
+ }
2760
+ const window = context.contextWindowTokens;
2761
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
2762
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
2763
+ }
2764
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
2765
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
2766
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
2767
+ }
2768
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
2769
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
2770
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
2771
+ }
2772
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
2773
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
2774
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
2775
+ }
2776
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
2777
+ }
2778
+ function declaredPromptCap(budget, op) {
2779
+ const derived = Math.floor(
2780
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
2781
+ );
2782
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
2783
+ return Math.max(OP_FLOOR.heal, derived);
2784
+ }
2785
+ function resolveMaxPromptChars(budget, op) {
2786
+ if (budget.mode !== "declared") {
2787
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
2788
+ }
2789
+ if (op === "extract") {
2790
+ const resolveDerived = declaredPromptCap(budget, "resolve");
2791
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
2792
+ return Math.max(OP_FLOOR.extract, extractDerived);
2793
+ }
2794
+ return declaredPromptCap(budget, op);
2795
+ }
2796
+ function resolveDefaultChunkLength(budget) {
2797
+ return DEFAULT_MAX_CHUNK_LENGTH;
2798
+ }
2799
+
2728
2800
  // src/utils/diagnostics.ts
2729
2801
  var SEVERITY = {
2730
2802
  ingest_chunk_failed: "warn",
@@ -2740,6 +2812,8 @@ var SEVERITY = {
2740
2812
  grounding_failed: "warn",
2741
2813
  classification_low_confidence: "info",
2742
2814
  classification_invalid: "warn",
2815
+ classification_abstained: "info",
2816
+ node_type_assigned: "info",
2743
2817
  context_overflow_skipped: "warn",
2744
2818
  llm_usage: "info",
2745
2819
  librarian_gate: "info",
@@ -2748,6 +2822,7 @@ var SEVERITY = {
2748
2822
  resolve_failed: "warn",
2749
2823
  read_budget: "info",
2750
2824
  event_retention_held: "info",
2825
+ ontology_backfill_held: "info",
2751
2826
  prune_checkpoint_incomplete: "warn",
2752
2827
  erase_secure_delete_off: "error",
2753
2828
  erase_entity_skipped: "warn",
@@ -2786,6 +2861,8 @@ var MESSAGE = {
2786
2861
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
2787
2862
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
2788
2863
  classification_invalid: "A classifier answer was invalid and was not applied.",
2864
+ classification_abstained: "The typing model declined to classify the fact; it was not typed.",
2865
+ node_type_assigned: "A typing run assigned an ontology node type to the fact.",
2789
2866
  context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
2790
2867
  llm_usage: "An LLM call completed; token usage attached.",
2791
2868
  librarian_gate: "Librarian gate outcome counts for one pass.",
@@ -2794,6 +2871,7 @@ var MESSAGE = {
2794
2871
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2795
2872
  read_budget: "A read was packed to a token budget.",
2796
2873
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2874
+ ontology_backfill_held: "Ontology backfill was held because another job held the entity\u2019s lock.",
2797
2875
  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.",
2798
2876
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
2799
2877
  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.",
@@ -3042,7 +3120,7 @@ var IngestionService = class {
3042
3120
  if (!sourceRef) throw new Error("Invalid sourceRef");
3043
3121
  const sourceHash = normalizeSourceHash(params.sourceHash);
3044
3122
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
3045
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
3123
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
3046
3124
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
3047
3125
  const chunkOverlap = Math.min(
3048
3126
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -3662,6 +3740,102 @@ var IngestionService = class {
3662
3740
  }
3663
3741
  };
3664
3742
 
3743
+ // src/utils/engineDefaults.ts
3744
+ var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3745
+ var DEFAULT_MAINTENANCE_MODE = "deferred";
3746
+ function resolveLibrarianStrategy(config) {
3747
+ return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
3748
+ }
3749
+ function resolveMaintenanceMode(config) {
3750
+ return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3751
+ }
3752
+ function resolveContextBudgetOrThrow(config) {
3753
+ return resolveContextBudget(config);
3754
+ }
3755
+ function changedDefaultWarnings(config) {
3756
+ const warnings = [];
3757
+ const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
3758
+ if (hasThreshold && config?.maintenance === void 0) {
3759
+ warnings.push(
3760
+ "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
3761
+ );
3762
+ }
3763
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
3764
+ warnings.push(
3765
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
3766
+ );
3767
+ }
3768
+ if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
3769
+ warnings.push(
3770
+ "[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
3771
+ );
3772
+ }
3773
+ return warnings;
3774
+ }
3775
+ var warnedDefaults = /* @__PURE__ */ new Set();
3776
+ function warnChangedDefaultsOnce(config) {
3777
+ for (const message of changedDefaultWarnings(config)) {
3778
+ if (warnedDefaults.has(message)) continue;
3779
+ warnedDefaults.add(message);
3780
+ console.warn(message);
3781
+ }
3782
+ }
3783
+ function warnOnce(message) {
3784
+ if (warnedDefaults.has(message)) return;
3785
+ warnedDefaults.add(message);
3786
+ console.warn(message);
3787
+ }
3788
+ function formatConfigValue(value) {
3789
+ try {
3790
+ const json = JSON.stringify(value);
3791
+ return json ?? String(value);
3792
+ } catch {
3793
+ return `[unserializable: ${typeof value}]`;
3794
+ }
3795
+ }
3796
+ var isTypingMode = (v) => v === "auto" || v === "llm";
3797
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3798
+ function resolveSystemOneTyping(config, classifierCallOption) {
3799
+ const systemOne = config?.systemOne;
3800
+ const legacy = config?.ontology?.backfillClassifier;
3801
+ const systemOneValid = isTypingMode(systemOne?.typing);
3802
+ const legacyValid = isTypingMode(legacy);
3803
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
3804
+ warnOnce(
3805
+ `[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.`
3806
+ );
3807
+ }
3808
+ if (legacy !== void 0 && !legacyValid) {
3809
+ warnOnce(
3810
+ `[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.`
3811
+ );
3812
+ }
3813
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
3814
+ warnOnce(
3815
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
3816
+ );
3817
+ }
3818
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3819
+ }
3820
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3821
+ function resolveTypingMinConfidence(config) {
3822
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
3823
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
3824
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
3825
+ const legacyValid = isConfidenceFloor(legacyFloor);
3826
+ if (systemOneFloor !== void 0 && !systemOneValid) {
3827
+ warnOnce(
3828
+ `[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.`
3829
+ );
3830
+ }
3831
+ if (legacyFloor !== void 0 && !legacyValid) {
3832
+ warnOnce(
3833
+ `[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.`
3834
+ );
3835
+ }
3836
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3837
+ }
3838
+
3665
3839
  // src/utils/classifier.ts
3666
3840
  var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3667
3841
  function validateClassifierAnswer(response, key, question) {
@@ -3837,44 +4011,6 @@ var TemporalService = class {
3837
4011
  }
3838
4012
  };
3839
4013
 
3840
- // src/utils/engineDefaults.ts
3841
- var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3842
- var DEFAULT_MAINTENANCE_MODE = "deferred";
3843
- function resolveLibrarianStrategy(config) {
3844
- return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
3845
- }
3846
- function resolveMaintenanceMode(config) {
3847
- return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3848
- }
3849
- function changedDefaultWarnings(config) {
3850
- const warnings = [];
3851
- const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
3852
- if (hasThreshold && config?.maintenance === void 0) {
3853
- warnings.push(
3854
- "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
3855
- );
3856
- }
3857
- if (config?.prompts?.librarianSystemPrompt !== void 0) {
3858
- warnings.push(
3859
- "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
3860
- );
3861
- }
3862
- if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
3863
- warnings.push(
3864
- "[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
3865
- );
3866
- }
3867
- return warnings;
3868
- }
3869
- var warnedDefaults = /* @__PURE__ */ new Set();
3870
- function warnChangedDefaultsOnce(config) {
3871
- for (const message of changedDefaultWarnings(config)) {
3872
- if (warnedDefaults.has(message)) continue;
3873
- warnedDefaults.add(message);
3874
- console.warn(message);
3875
- }
3876
- }
3877
-
3878
4014
  // src/repositories/VectorRemovalRepository.ts
3879
4015
  var CHUNK = 500;
3880
4016
  function removalBackoffMs(attempts) {
@@ -5965,18 +6101,18 @@ function parseValidFrom(v) {
5965
6101
 
5966
6102
  // src/services/librarian/ops/extract.ts
5967
6103
  var OPS_MAX_EVENTS_PER_PASS = 50;
5968
- var OPS_MAX_EXTRACT_CHARS = 24e3;
5969
6104
  var RESOLVE_RESERVE_FACTOR = 2;
5970
6105
  var MIN_SEGMENT_CHARS = 500;
5971
6106
  var MAX_SEGMENT_CALLS = 8;
5972
6107
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5973
- async function selectBatch(deps, entityId, wm, meter, guidance) {
6108
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
5974
6109
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
5975
6110
  if (events.length === 0) return { batch: [] };
6111
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
5976
6112
  let n = 0;
5977
6113
  let chars = 0;
5978
6114
  for (const e of events) {
5979
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
6115
+ if (n > 0 && chars + e.summary.length > extractCap) break;
5980
6116
  chars += e.summary.length;
5981
6117
  n++;
5982
6118
  }
@@ -6302,7 +6438,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
6302
6438
  }
6303
6439
 
6304
6440
  // src/services/librarian/ops/resolve.ts
6305
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
6306
6441
  function validateOp(raw, aliases) {
6307
6442
  if (!raw || typeof raw !== "object") return null;
6308
6443
  const r = raw;
@@ -6321,7 +6456,7 @@ function validateOp(raw, aliases) {
6321
6456
  return update;
6322
6457
  }
6323
6458
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
6324
- async function runResolve(deps, ctx, ambiguous) {
6459
+ async function runResolve(deps, ctx, ambiguous, budget) {
6325
6460
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
6326
6461
  if (ambiguous.length === 0) return out;
6327
6462
  const { entityId, trigger } = ctx;
@@ -6347,7 +6482,7 @@ async function runResolve(deps, ctx, ambiguous) {
6347
6482
  onSkip: (g, err) => {
6348
6483
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
6349
6484
  },
6350
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
6485
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
6351
6486
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
6352
6487
  });
6353
6488
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -6556,7 +6691,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6556
6691
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
6557
6692
  await deps.seedWatermark(entityId);
6558
6693
  const wm = await deps.getWatermark(entityId);
6559
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
6694
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
6560
6695
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
6561
6696
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
6562
6697
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -6584,7 +6719,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6584
6719
  });
6585
6720
  }
6586
6721
  diagnostics.push(gateDiagnostic);
6587
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
6722
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
6588
6723
  for (const itemIndex of res.overflowSkipped) {
6589
6724
  diagnostics.push({
6590
6725
  entityId,
@@ -6651,8 +6786,8 @@ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HIST
6651
6786
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
6652
6787
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
6653
6788
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
6789
+ var CLASSIFIER_MAX_CHOICES = 255;
6654
6790
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
6655
- var HEAL_MAX_PROMPT_CHARS = 4e4;
6656
6791
  var HEAL_BATCH_SIZE = 25;
6657
6792
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
6658
6793
  var MAX_EMBED_ATTEMPTS = 5;
@@ -7344,6 +7479,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
7344
7479
  this.jobManager.releaseLock("ontologyBackfill", entityId);
7345
7480
  }
7346
7481
  }
7482
+ /**
7483
+ * Scheduler read view (specs/system-one-config §8): untyped facts still
7484
+ * eligible for typing this pass — outside the 7-day recheck cooldown — or 0
7485
+ * when ontology is off for the entity (nothing is ever eligible there).
7486
+ * Read-only: never materializes a seed manifest, never writes.
7487
+ */
7488
+ async pendingOntologyBackfill(entityId) {
7489
+ const ontologyService = this.ontologyService;
7490
+ if (!ontologyService) return 0;
7491
+ const { mode } = await ontologyService.getEffectiveState(entityId);
7492
+ if (mode === "off") return 0;
7493
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, Date.now() - ONTOLOGY_BACKFILL_RECHECK_MS);
7494
+ return counts.eligible;
7495
+ }
7496
+ /**
7497
+ * Emit `ontology_backfill_held` (severity `info`) when the scheduler found
7498
+ * the entity's `ontologyBackfill` lock held by another job. The lock state
7499
+ * names no content, so the fixed template carries all the information a
7500
+ * host needs; `JobManager.isBlocked` does not identify the blocker and the
7501
+ * diagnostic detail surface stays identifier-typed.
7502
+ */
7503
+ noteOntologyBackfillHeld(entityId) {
7504
+ emitDiagnostic(this.options, {
7505
+ code: "ontology_backfill_held",
7506
+ operation: "ontologyBackfill",
7507
+ trigger: "call",
7508
+ entityId
7509
+ });
7510
+ }
7347
7511
  /**
7348
7512
  * Re-embed facts, honouring per-row failure markers and exponential backoff.
7349
7513
  *
@@ -7927,7 +8091,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7927
8091
  };
7928
8092
  },
7929
8093
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
7930
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
8094
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
7931
8095
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
7932
8096
  supportsEscalation: true,
7933
8097
  onSkip: (fact, err) => {
@@ -8090,45 +8254,120 @@ DROP TRIGGER IF EXISTS ${ad};`);
8090
8254
  if (!Number.isInteger(batchSize) || batchSize < 1) {
8091
8255
  throw new Error("Invalid batchSize: must be an integer >= 1");
8092
8256
  }
8257
+ if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
8258
+ throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
8259
+ }
8260
+ const trigger = options?.trigger ?? "call";
8093
8261
  const now = Date.now();
8094
8262
  const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
8095
- const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0 };
8263
+ const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
8096
8264
  const ontologyService = this.ontologyService;
8097
8265
  if (!ontologyService) {
8098
8266
  return { ...zeroed, remaining: 0, deferred: 0 };
8099
8267
  }
8100
8268
  const { mode, manifest: effectiveManifest } = await ontologyService.getEffectiveState(entityId);
8101
8269
  if (mode === "off") {
8102
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8103
- return { ...zeroed, remaining: 0, deferred: counts2.deferred };
8270
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8271
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
8104
8272
  }
8105
8273
  const candidates = await this.entryRepo.findUntypedByEntityId(entityId, batchSize, recheckCutoff);
8106
8274
  if (candidates.length === 0) {
8107
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8108
- return { ...zeroed, remaining: counts2.eligible, deferred: counts2.deferred };
8275
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8276
+ return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
8109
8277
  }
8110
- const classifierMode = options?.classifier ?? this.options.config?.ontology?.backfillClassifier ?? "llm";
8278
+ const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
8111
8279
  const classify = this.options.llmProvider.classify;
8112
8280
  if (classifierMode === "auto" && typeof classify === "function") {
8113
8281
  const slugs = effectiveManifest.node_types.map((n) => n.type);
8114
- if (slugs.length > 0 && slugs.length <= 255) {
8115
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
8282
+ if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
8283
+ const classifierRun = await this._runClassifierBackfill(
8284
+ entityId,
8285
+ candidates,
8286
+ effectiveManifest,
8287
+ now,
8288
+ recheckCutoff,
8289
+ options?.meter,
8290
+ trigger
8291
+ );
8292
+ if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
8293
+ return classifierRun.result;
8294
+ }
8295
+ if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
8296
+ const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
8297
+ if (liveMode === "off") {
8298
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8299
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
8300
+ }
8301
+ const escalated = classifierRun.escalated;
8302
+ const generative = await this._runGenerativeBackfill(entityId, escalated, {
8303
+ promptOverride: options?.promptOverride,
8304
+ meter: options?.meter,
8305
+ trigger,
8306
+ batchSize: escalated.length
8307
+ });
8308
+ return {
8309
+ scanned: classifierRun.result.scanned,
8310
+ typed: classifierRun.result.typed + generative.typed,
8311
+ failedValidation: classifierRun.result.failedValidation + generative.failedValidation,
8312
+ edgesAdded: classifierRun.result.edgesAdded + generative.edgesAdded,
8313
+ abstained: classifierRun.result.abstained + generative.abstained,
8314
+ skipped: classifierRun.result.skipped + generative.skipped,
8315
+ remaining: generative.remaining,
8316
+ deferred: generative.deferred,
8317
+ ...generative.budgetStop ? { budgetStop: generative.budgetStop } : {}
8318
+ };
8319
+ }
8320
+ return classifierRun.result;
8116
8321
  }
8117
8322
  }
8323
+ return this._runGenerativeBackfill(entityId, candidates, {
8324
+ promptOverride: options?.promptOverride,
8325
+ meter: options?.meter,
8326
+ trigger
8327
+ });
8328
+ }
8329
+ /**
8330
+ * Low-confidence routing (specs/system-one-config §4): `'leave'` (default)
8331
+ * keeps classifier abstains/low-confidence facts untyped and
8332
+ * cooldown-stamped; `'llm'` escalates them to the generative step. Invalid
8333
+ * config warns once and is treated as unset. Cost/quality setting, not a
8334
+ * safety mechanism — it cannot catch a confidently wrong classifier.
8335
+ */
8336
+ resolveSystemOneOnLowConfidence() {
8337
+ const raw = this.options.config?.systemOne?.onLowConfidence;
8338
+ if (raw !== void 0 && raw !== "leave" && raw !== "llm") {
8339
+ warnOnce(
8340
+ `[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.`
8341
+ );
8342
+ return "leave";
8343
+ }
8344
+ return raw ?? "leave";
8345
+ }
8346
+ /**
8347
+ * Generative-mode backfill step: the original `generateText` pass over
8348
+ * `candidates`. Also the escalation target of the classifier step (§4) —
8349
+ * there `candidates` holds only the escalated facts and `batchSize` is
8350
+ * sized to send them in one batch.
8351
+ */
8352
+ async _runGenerativeBackfill(entityId, candidates, runOpts) {
8353
+ runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
8354
+ const ontologyService = this.ontologyService;
8355
+ const now = Date.now();
8356
+ const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
8118
8357
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
8119
8358
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
8120
8359
  const titleCatalog = buildTitleCatalogBlock(titleRows);
8121
8360
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
8122
8361
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
8123
8362
  facts.map(toPromptShape),
8124
- options?.promptOverride,
8363
+ runOpts.promptOverride,
8125
8364
  ontologyContext,
8126
8365
  titleCatalog
8127
8366
  );
8128
8367
  const outcome = await runBatched({
8129
8368
  items: candidates,
8130
8369
  buildPrompt,
8131
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
8370
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: runOpts.trigger, meter: runOpts.meter }, prompts),
8132
8371
  parse: (responseText, batch) => {
8133
8372
  const parsed = parseJsonResponse(responseText);
8134
8373
  return {
@@ -8144,7 +8383,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8144
8383
  emitDiagnostic(this.options, {
8145
8384
  entityId,
8146
8385
  operation: "ontologyBackfill",
8147
- trigger: "call",
8386
+ trigger: runOpts.trigger,
8148
8387
  code: "context_overflow_skipped",
8149
8388
  detail: { factId: fact.id }
8150
8389
  });
@@ -8159,9 +8398,12 @@ DROP TRIGGER IF EXISTS ${ad};`);
8159
8398
  let failedValidation = 0;
8160
8399
  let edgesAdded = 0;
8161
8400
  let scanned = 0;
8401
+ let abstained = 0;
8162
8402
  let abortedOntologyOff = false;
8403
+ const diagBuffer = new DiagnosticBuffer();
8404
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger: runOpts.trigger };
8163
8405
  for (const batchResult of outcome.results) {
8164
- const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now);
8406
+ const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now, "llm", runOpts.trigger);
8165
8407
  if (applied.abortedOntologyOff) {
8166
8408
  abortedOntologyOff = true;
8167
8409
  break;
@@ -8169,8 +8411,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
8169
8411
  typed += applied.typed;
8170
8412
  failedValidation += applied.failedValidation;
8171
8413
  edgesAdded += applied.edgesAdded;
8414
+ for (const factId of applied.omittedIds) {
8415
+ abstained += 1;
8416
+ diagBuffer.push({
8417
+ ...diagBase,
8418
+ code: "classification_abstained",
8419
+ detail: { factId, writer: "llm" }
8420
+ });
8421
+ }
8172
8422
  scanned += batchResult.batch.length;
8173
8423
  }
8424
+ diagBuffer.flush(this.options);
8174
8425
  if (abortedOntologyOff) {
8175
8426
  const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8176
8427
  return {
@@ -8178,6 +8429,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8178
8429
  typed,
8179
8430
  failedValidation,
8180
8431
  edgesAdded,
8432
+ abstained,
8181
8433
  skipped: outcome.skipped.length,
8182
8434
  remaining: 0,
8183
8435
  deferred: counts2.deferred,
@@ -8202,6 +8454,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8202
8454
  typed,
8203
8455
  failedValidation,
8204
8456
  edgesAdded,
8457
+ abstained,
8205
8458
  skipped: outcome.skipped.length,
8206
8459
  remaining: counts.eligible,
8207
8460
  deferred: counts.deferred,
@@ -8209,20 +8462,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
8209
8462
  };
8210
8463
  }
8211
8464
  /**
8212
- * Classifier-mode backfill (spec §7.3): one `choice` question per untyped
8213
- * fact over the effective manifest's node-type slugs. Accepted answers go
8214
- * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
8215
- * No edges are proposed.
8465
+ * Classifier-mode backfill (spec §7.3, S1-0 §5): one `choice` question per
8466
+ * untyped fact over the effective manifest's node-type slugs plus the
8467
+ * reserved abstain sentinel. Accepted answers go through
8468
+ * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
8469
+ * are proposed. Abstains and low-confidence answers are cooldown-stamped
8470
+ * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
8471
+ * returned un-stamped in `escalated` for the generative step. Always
8472
+ * returns the `OntologyBackfillResult` for its step plus escalation state.
8216
8473
  */
8217
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
8218
- const rawMin = this.options.config?.ontology?.classifyMinConfidence;
8219
- const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
8474
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
8475
+ const minConfidence = resolveTypingMinConfidence(this.options.config);
8220
8476
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
8221
8477
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
8222
8478
  const question = {
8223
8479
  kind: "choice",
8224
- options: manifest.node_types.map((n) => n.type),
8225
- instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
8480
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
8481
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
8482
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
8226
8483
  };
8227
8484
  let stopped;
8228
8485
  const outcomes = await withConcurrency(
@@ -8232,7 +8489,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8232
8489
  try {
8233
8490
  response = await callClassify(
8234
8491
  this.options,
8235
- { operation: "ontologyBackfill", entityId, trigger: "call", meter },
8492
+ { operation: "ontologyBackfill", entityId, trigger, meter },
8236
8493
  { state: classifierStateForFact(fact), questions: { okf_type: question } }
8237
8494
  );
8238
8495
  } catch (err) {
@@ -8246,37 +8503,47 @@ DROP TRIGGER IF EXISTS ${ad};`);
8246
8503
  const checked = validateClassifierAnswer(response, "okf_type", question);
8247
8504
  if (!checked.ok) return { fact, kind: "invalid", reason: checked.reason };
8248
8505
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
8506
+ if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
8249
8507
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
8250
8508
  return { fact, kind: "accepted", okfType: checked.answer.choice };
8251
8509
  }),
8252
8510
  concurrency
8253
8511
  );
8254
- const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
8512
+ const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
8513
+ const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
8514
+ const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
8515
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
8255
8516
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
8256
8517
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
8257
8518
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
8258
8519
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
8520
+ const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
8259
8521
  let typed = 0;
8260
8522
  let failedValidation = 0;
8261
8523
  let edgesAdded = 0;
8262
- let aborted = false;
8524
+ let abortedOntologyOff = false;
8263
8525
  if (attempted.length > 0) {
8264
8526
  const applied = await this._applyOntologyBackfillBatch(
8265
8527
  entityId,
8266
8528
  { batch: attempted, classifications, ontologyUpdates: void 0 },
8267
- now
8529
+ now,
8530
+ "classifier",
8531
+ trigger
8268
8532
  );
8269
- aborted = applied.abortedOntologyOff;
8270
- if (!aborted) {
8533
+ abortedOntologyOff = applied.abortedOntologyOff;
8534
+ if (!abortedOntologyOff) {
8271
8535
  typed = applied.typed;
8272
8536
  failedValidation = invalidCount + applied.failedValidation;
8273
8537
  edgesAdded = applied.edgesAdded;
8274
8538
  }
8275
8539
  }
8276
8540
  const diagBuffer = new DiagnosticBuffer();
8277
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
8541
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
8278
8542
  for (const o of outcomes) {
8279
- if (o.kind === "low_confidence") {
8543
+ if (o.kind === "abstain") {
8544
+ if (isEscalated(o)) continue;
8545
+ diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
8546
+ } else if (o.kind === "low_confidence") {
8280
8547
  diagBuffer.push({ ...diagBase, code: "classification_low_confidence", detail: { factId: o.fact.id, reason: "below_threshold" } });
8281
8548
  } else if (o.kind === "invalid") {
8282
8549
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
@@ -8288,19 +8555,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
8288
8555
  }
8289
8556
  diagBuffer.flush(this.options);
8290
8557
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8291
- if (aborted) {
8292
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
8558
+ const budgetStop = stopped ? { requiredEstimate: stopped.requiredEstimate } : void 0;
8559
+ if (abortedOntologyOff) {
8560
+ return {
8561
+ result: { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, abstained: 0, skipped, remaining: 0, deferred: counts.deferred, ...budgetStop ? { budgetStop } : {} },
8562
+ escalated: [],
8563
+ abortedOntologyOff
8564
+ };
8293
8565
  }
8294
8566
  this.searchService.evictCache(entityId);
8295
8567
  return {
8296
- scanned: candidates.length - unattemptedCount,
8297
- typed,
8298
- failedValidation,
8299
- edgesAdded,
8300
- skipped,
8301
- remaining: counts.eligible,
8302
- deferred: counts.deferred,
8303
- ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
8568
+ result: {
8569
+ scanned: candidates.length - unattemptedCount,
8570
+ typed,
8571
+ failedValidation,
8572
+ edgesAdded,
8573
+ abstained: abstainCount,
8574
+ skipped,
8575
+ remaining: counts.eligible,
8576
+ deferred: counts.deferred,
8577
+ ...budgetStop ? { budgetStop } : {}
8578
+ },
8579
+ escalated,
8580
+ abortedOntologyOff: false
8304
8581
  };
8305
8582
  }
8306
8583
  /**
@@ -8309,15 +8586,18 @@ DROP TRIGGER IF EXISTS ${ad};`);
8309
8586
  * the mid-flight `mode === 'off'` abort check keep the shape they had when a
8310
8587
  * pass was a single call.
8311
8588
  */
8312
- async _applyOntologyBackfillBatch(entityId, batchResult, now) {
8589
+ async _applyOntologyBackfillBatch(entityId, batchResult, now, writer, trigger) {
8313
8590
  const ontologyService = this.ontologyService;
8314
8591
  const { batch, classifications, ontologyUpdates } = batchResult;
8315
8592
  let typed = 0;
8316
8593
  let failedValidation = 0;
8317
8594
  let edgesAdded = 0;
8318
8595
  let abortedOntologyOff = false;
8596
+ const typedIds = [];
8597
+ const omittedIds = [];
8598
+ const classifiedIds = /* @__PURE__ */ new Set();
8319
8599
  const diagBuffer = new DiagnosticBuffer();
8320
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
8600
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
8321
8601
  await this.db.withTransactionAsync(async (tx) => {
8322
8602
  let { mode: txMode, manifest } = await ontologyService.getEffectiveState(entityId, tx);
8323
8603
  if (txMode === "off") {
@@ -8342,6 +8622,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8342
8622
  continue;
8343
8623
  }
8344
8624
  applied.add(fact.id);
8625
+ classifiedIds.add(fact.id);
8345
8626
  const validationDrops = [];
8346
8627
  const normalized = ontologyService.validateAndNormalizeFact(
8347
8628
  {
@@ -8363,8 +8644,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
8363
8644
  continue;
8364
8645
  }
8365
8646
  const result = await this.entryRepo.updateOkfType(fact.id, entityId, normalized.okf_type, tx);
8366
- if (result.changes === 0) continue;
8647
+ if (result.changes === 0) {
8648
+ omittedIds.push(fact.id);
8649
+ continue;
8650
+ }
8367
8651
  typed++;
8652
+ typedIds.push(fact.id);
8653
+ diagBuffer.push({
8654
+ ...diagBase,
8655
+ code: "node_type_assigned",
8656
+ detail: { factId: fact.id, okfType: normalized.okf_type, writer }
8657
+ });
8368
8658
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
8369
8659
  if (normalized.edges.length > 0) {
8370
8660
  pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
@@ -8390,8 +8680,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
8390
8680
  }
8391
8681
  await this.entryRepo.markOntologyChecked(batch.map((f) => f.id), entityId, now, tx);
8392
8682
  });
8683
+ if (!abortedOntologyOff) {
8684
+ for (const fact of batch) {
8685
+ if (!classifiedIds.has(fact.id)) omittedIds.push(fact.id);
8686
+ }
8687
+ }
8393
8688
  diagBuffer.flush(this.options);
8394
- return { typed, failedValidation, edgesAdded, abortedOntologyOff };
8689
+ return { typed, failedValidation, edgesAdded, abortedOntologyOff, typedIds, omittedIds };
8395
8690
  }
8396
8691
  _validatePruneDuration(value, name) {
8397
8692
  if (value !== null && value !== void 0 && (typeof value !== "number" || !isFinite(value) || value < 0)) {
@@ -11028,6 +11323,6 @@ var WriteService = class {
11028
11323
  }
11029
11324
  };
11030
11325
 
11031
- export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11032
- //# sourceMappingURL=chunk-QIS2SGUM.mjs.map
11033
- //# sourceMappingURL=chunk-QIS2SGUM.mjs.map
11326
+ export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11327
+ //# sourceMappingURL=chunk-6UTHJFXH.mjs.map
11328
+ //# sourceMappingURL=chunk-6UTHJFXH.mjs.map