@equationalapplications/core-llm-wiki 9.5.3 → 9.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -725,6 +725,8 @@ var SEVERITY = {
725
725
  grounding_failed: "warn",
726
726
  classification_low_confidence: "info",
727
727
  classification_invalid: "warn",
728
+ classification_abstained: "info",
729
+ node_type_assigned: "info",
728
730
  context_overflow_skipped: "warn",
729
731
  llm_usage: "info",
730
732
  librarian_gate: "info",
@@ -733,6 +735,7 @@ var SEVERITY = {
733
735
  resolve_failed: "warn",
734
736
  read_budget: "info",
735
737
  event_retention_held: "info",
738
+ ontology_backfill_held: "info",
736
739
  prune_checkpoint_incomplete: "warn",
737
740
  erase_secure_delete_off: "error",
738
741
  erase_entity_skipped: "warn",
@@ -771,6 +774,8 @@ var MESSAGE = {
771
774
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
772
775
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
773
776
  classification_invalid: "A classifier answer was invalid and was not applied.",
777
+ classification_abstained: "The typing model declined to classify the fact; it was not typed.",
778
+ node_type_assigned: "A typing run assigned an ontology node type to the fact.",
774
779
  context_overflow_skipped: "An item (fact or event) was skipped because the model input exceeded its context window.",
775
780
  llm_usage: "An LLM call completed; token usage attached.",
776
781
  librarian_gate: "Librarian gate outcome counts for one pass.",
@@ -779,6 +784,7 @@ var MESSAGE = {
779
784
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
780
785
  read_budget: "A read was packed to a token budget.",
781
786
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
787
+ ontology_backfill_held: "Ontology backfill was held because another job held the entity\u2019s lock.",
782
788
  prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
783
789
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
784
790
  erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow-table text rows were emptied (fts5 %_config and %_data ids 1 and 10 are intentionally kept) and the name stays listed until an FTS5-capable open drops it.",
@@ -1264,6 +1270,10 @@ var BaseRepository = class {
1264
1270
  function normalizeTitleKey(title) {
1265
1271
  return title.trim().toLowerCase().replace(/\s+/g, " ");
1266
1272
  }
1273
+ var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
1274
+ function isReservedAbstainSlug(raw) {
1275
+ return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
1276
+ }
1267
1277
  function typeSatisfies(declaredType, concreteType, manifest) {
1268
1278
  const concrete = concreteType.trim().toLowerCase();
1269
1279
  const declared = declaredType.trim().toLowerCase();
@@ -3826,6 +3836,62 @@ function resolveLibrarianStrategy(config) {
3826
3836
  function resolveMaintenanceMode(config) {
3827
3837
  return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3828
3838
  }
3839
+ var warnedDefaults = /* @__PURE__ */ new Set();
3840
+ function warnOnce(message) {
3841
+ if (warnedDefaults.has(message)) return;
3842
+ warnedDefaults.add(message);
3843
+ console.warn(message);
3844
+ }
3845
+ function formatConfigValue(value) {
3846
+ try {
3847
+ const json = JSON.stringify(value);
3848
+ return json ?? String(value);
3849
+ } catch {
3850
+ return `[unserializable: ${typeof value}]`;
3851
+ }
3852
+ }
3853
+ var isTypingMode = (v) => v === "auto" || v === "llm";
3854
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3855
+ function resolveSystemOneTyping(config, classifierCallOption) {
3856
+ const systemOne = config?.systemOne;
3857
+ const legacy = config?.ontology?.backfillClassifier;
3858
+ const systemOneValid = isTypingMode(systemOne?.typing);
3859
+ const legacyValid = isTypingMode(legacy);
3860
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
3861
+ warnOnce(
3862
+ `[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.`
3863
+ );
3864
+ }
3865
+ if (legacy !== void 0 && !legacyValid) {
3866
+ warnOnce(
3867
+ `[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.`
3868
+ );
3869
+ }
3870
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
3871
+ warnOnce(
3872
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
3873
+ );
3874
+ }
3875
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3876
+ }
3877
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3878
+ function resolveTypingMinConfidence(config) {
3879
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
3880
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
3881
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
3882
+ const legacyValid = isConfidenceFloor(legacyFloor);
3883
+ if (systemOneFloor !== void 0 && !systemOneValid) {
3884
+ warnOnce(
3885
+ `[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.`
3886
+ );
3887
+ }
3888
+ if (legacyFloor !== void 0 && !legacyValid) {
3889
+ warnOnce(
3890
+ `[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.`
3891
+ );
3892
+ }
3893
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3894
+ }
3829
3895
 
3830
3896
  // src/utils/embedding.ts
3831
3897
  function parseEmbedding(blob, text) {
@@ -5572,6 +5638,7 @@ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HIST
5572
5638
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
5573
5639
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
5574
5640
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
5641
+ var CLASSIFIER_MAX_CHOICES = 255;
5575
5642
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
5576
5643
  var HEAL_MAX_PROMPT_CHARS = 4e4;
5577
5644
  var HEAL_BATCH_SIZE = 25;
@@ -6265,6 +6332,35 @@ DROP TRIGGER IF EXISTS ${ad};`);
6265
6332
  this.jobManager.releaseLock("ontologyBackfill", entityId);
6266
6333
  }
6267
6334
  }
6335
+ /**
6336
+ * Scheduler read view (specs/system-one-config §8): untyped facts still
6337
+ * eligible for typing this pass — outside the 7-day recheck cooldown — or 0
6338
+ * when ontology is off for the entity (nothing is ever eligible there).
6339
+ * Read-only: never materializes a seed manifest, never writes.
6340
+ */
6341
+ async pendingOntologyBackfill(entityId) {
6342
+ const ontologyService = this.ontologyService;
6343
+ if (!ontologyService) return 0;
6344
+ const { mode } = await ontologyService.getEffectiveState(entityId);
6345
+ if (mode === "off") return 0;
6346
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, Date.now() - ONTOLOGY_BACKFILL_RECHECK_MS);
6347
+ return counts.eligible;
6348
+ }
6349
+ /**
6350
+ * Emit `ontology_backfill_held` (severity `info`) when the scheduler found
6351
+ * the entity's `ontologyBackfill` lock held by another job. The lock state
6352
+ * names no content, so the fixed template carries all the information a
6353
+ * host needs; `JobManager.isBlocked` does not identify the blocker and the
6354
+ * diagnostic detail surface stays identifier-typed.
6355
+ */
6356
+ noteOntologyBackfillHeld(entityId) {
6357
+ emitDiagnostic(this.options, {
6358
+ code: "ontology_backfill_held",
6359
+ operation: "ontologyBackfill",
6360
+ trigger: "call",
6361
+ entityId
6362
+ });
6363
+ }
6268
6364
  /**
6269
6365
  * Re-embed facts, honouring per-row failure markers and exponential backoff.
6270
6366
  *
@@ -7011,45 +7107,120 @@ DROP TRIGGER IF EXISTS ${ad};`);
7011
7107
  if (!Number.isInteger(batchSize) || batchSize < 1) {
7012
7108
  throw new Error("Invalid batchSize: must be an integer >= 1");
7013
7109
  }
7110
+ if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
7111
+ throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
7112
+ }
7113
+ const trigger = options?.trigger ?? "call";
7014
7114
  const now = Date.now();
7015
7115
  const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
7016
- const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0 };
7116
+ const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
7017
7117
  const ontologyService = this.ontologyService;
7018
7118
  if (!ontologyService) {
7019
7119
  return { ...zeroed, remaining: 0, deferred: 0 };
7020
7120
  }
7021
7121
  const { mode, manifest: effectiveManifest } = await ontologyService.getEffectiveState(entityId);
7022
7122
  if (mode === "off") {
7023
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7024
- return { ...zeroed, remaining: 0, deferred: counts2.deferred };
7123
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7124
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
7025
7125
  }
7026
7126
  const candidates = await this.entryRepo.findUntypedByEntityId(entityId, batchSize, recheckCutoff);
7027
7127
  if (candidates.length === 0) {
7028
- const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7029
- return { ...zeroed, remaining: counts2.eligible, deferred: counts2.deferred };
7128
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7129
+ return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
7030
7130
  }
7031
- const classifierMode = options?.classifier ?? this.options.config?.ontology?.backfillClassifier ?? "llm";
7131
+ const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
7032
7132
  const classify = this.options.llmProvider.classify;
7033
7133
  if (classifierMode === "auto" && typeof classify === "function") {
7034
7134
  const slugs = effectiveManifest.node_types.map((n) => n.type);
7035
- if (slugs.length > 0 && slugs.length <= 255) {
7036
- return this._runClassifierBackfill(entityId, candidates, effectiveManifest, now, recheckCutoff, options?.meter);
7135
+ if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
7136
+ const classifierRun = await this._runClassifierBackfill(
7137
+ entityId,
7138
+ candidates,
7139
+ effectiveManifest,
7140
+ now,
7141
+ recheckCutoff,
7142
+ options?.meter,
7143
+ trigger
7144
+ );
7145
+ if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
7146
+ return classifierRun.result;
7147
+ }
7148
+ if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
7149
+ const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
7150
+ if (liveMode === "off") {
7151
+ const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7152
+ return { ...zeroed, remaining: 0, deferred: counts.deferred };
7153
+ }
7154
+ const escalated = classifierRun.escalated;
7155
+ const generative = await this._runGenerativeBackfill(entityId, escalated, {
7156
+ promptOverride: options?.promptOverride,
7157
+ meter: options?.meter,
7158
+ trigger,
7159
+ batchSize: escalated.length
7160
+ });
7161
+ return {
7162
+ scanned: classifierRun.result.scanned,
7163
+ typed: classifierRun.result.typed + generative.typed,
7164
+ failedValidation: classifierRun.result.failedValidation + generative.failedValidation,
7165
+ edgesAdded: classifierRun.result.edgesAdded + generative.edgesAdded,
7166
+ abstained: classifierRun.result.abstained + generative.abstained,
7167
+ skipped: classifierRun.result.skipped + generative.skipped,
7168
+ remaining: generative.remaining,
7169
+ deferred: generative.deferred,
7170
+ ...generative.budgetStop ? { budgetStop: generative.budgetStop } : {}
7171
+ };
7172
+ }
7173
+ return classifierRun.result;
7037
7174
  }
7038
7175
  }
7176
+ return this._runGenerativeBackfill(entityId, candidates, {
7177
+ promptOverride: options?.promptOverride,
7178
+ meter: options?.meter,
7179
+ trigger
7180
+ });
7181
+ }
7182
+ /**
7183
+ * Low-confidence routing (specs/system-one-config §4): `'leave'` (default)
7184
+ * keeps classifier abstains/low-confidence facts untyped and
7185
+ * cooldown-stamped; `'llm'` escalates them to the generative step. Invalid
7186
+ * config warns once and is treated as unset. Cost/quality setting, not a
7187
+ * safety mechanism — it cannot catch a confidently wrong classifier.
7188
+ */
7189
+ resolveSystemOneOnLowConfidence() {
7190
+ const raw = this.options.config?.systemOne?.onLowConfidence;
7191
+ if (raw !== void 0 && raw !== "leave" && raw !== "llm") {
7192
+ warnOnce(
7193
+ `[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.`
7194
+ );
7195
+ return "leave";
7196
+ }
7197
+ return raw ?? "leave";
7198
+ }
7199
+ /**
7200
+ * Generative-mode backfill step: the original `generateText` pass over
7201
+ * `candidates`. Also the escalation target of the classifier step (§4) —
7202
+ * there `candidates` holds only the escalated facts and `batchSize` is
7203
+ * sized to send them in one batch.
7204
+ */
7205
+ async _runGenerativeBackfill(entityId, candidates, runOpts) {
7206
+ runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
7207
+ const ontologyService = this.ontologyService;
7208
+ const now = Date.now();
7209
+ const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
7039
7210
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
7040
7211
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
7041
7212
  const titleCatalog = buildTitleCatalogBlock(titleRows);
7042
7213
  const toPromptShape = (f) => ({ id: f.id, title: f.title, body: f.body, tags: f.tags });
7043
7214
  const buildPrompt = (facts) => this.promptService.buildOntologyBackfillPrompt(
7044
7215
  facts.map(toPromptShape),
7045
- options?.promptOverride,
7216
+ runOpts.promptOverride,
7046
7217
  ontologyContext,
7047
7218
  titleCatalog
7048
7219
  );
7049
7220
  const outcome = await runBatched({
7050
7221
  items: candidates,
7051
7222
  buildPrompt,
7052
- call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: "call", meter: options?.meter }, prompts),
7223
+ call: (prompts) => callLlm(this.options, { operation: "ontologyBackfill", entityId, trigger: runOpts.trigger, meter: runOpts.meter }, prompts),
7053
7224
  parse: (responseText, batch) => {
7054
7225
  const parsed = parseJsonResponse(responseText);
7055
7226
  return {
@@ -7065,7 +7236,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7065
7236
  emitDiagnostic(this.options, {
7066
7237
  entityId,
7067
7238
  operation: "ontologyBackfill",
7068
- trigger: "call",
7239
+ trigger: runOpts.trigger,
7069
7240
  code: "context_overflow_skipped",
7070
7241
  detail: { factId: fact.id }
7071
7242
  });
@@ -7080,9 +7251,12 @@ DROP TRIGGER IF EXISTS ${ad};`);
7080
7251
  let failedValidation = 0;
7081
7252
  let edgesAdded = 0;
7082
7253
  let scanned = 0;
7254
+ let abstained = 0;
7083
7255
  let abortedOntologyOff = false;
7256
+ const diagBuffer = new DiagnosticBuffer();
7257
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger: runOpts.trigger };
7084
7258
  for (const batchResult of outcome.results) {
7085
- const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now);
7259
+ const applied = await this._applyOntologyBackfillBatch(entityId, batchResult, now, "llm", runOpts.trigger);
7086
7260
  if (applied.abortedOntologyOff) {
7087
7261
  abortedOntologyOff = true;
7088
7262
  break;
@@ -7090,8 +7264,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
7090
7264
  typed += applied.typed;
7091
7265
  failedValidation += applied.failedValidation;
7092
7266
  edgesAdded += applied.edgesAdded;
7267
+ for (const factId of applied.omittedIds) {
7268
+ abstained += 1;
7269
+ diagBuffer.push({
7270
+ ...diagBase,
7271
+ code: "classification_abstained",
7272
+ detail: { factId, writer: "llm" }
7273
+ });
7274
+ }
7093
7275
  scanned += batchResult.batch.length;
7094
7276
  }
7277
+ diagBuffer.flush(this.options);
7095
7278
  if (abortedOntologyOff) {
7096
7279
  const counts2 = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7097
7280
  return {
@@ -7099,6 +7282,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7099
7282
  typed,
7100
7283
  failedValidation,
7101
7284
  edgesAdded,
7285
+ abstained,
7102
7286
  skipped: outcome.skipped.length,
7103
7287
  remaining: 0,
7104
7288
  deferred: counts2.deferred,
@@ -7123,6 +7307,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7123
7307
  typed,
7124
7308
  failedValidation,
7125
7309
  edgesAdded,
7310
+ abstained,
7126
7311
  skipped: outcome.skipped.length,
7127
7312
  remaining: counts.eligible,
7128
7313
  deferred: counts.deferred,
@@ -7130,20 +7315,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
7130
7315
  };
7131
7316
  }
7132
7317
  /**
7133
- * Classifier-mode backfill (spec §7.3): one `choice` question per untyped
7134
- * fact over the effective manifest's node-type slugs. Accepted answers go
7135
- * through `_applyOntologyBackfillBatch` exactly like LLM classifications.
7136
- * No edges are proposed.
7318
+ * Classifier-mode backfill (spec §7.3, S1-0 §5): one `choice` question per
7319
+ * untyped fact over the effective manifest's node-type slugs plus the
7320
+ * reserved abstain sentinel. Accepted answers go through
7321
+ * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
7322
+ * are proposed. Abstains and low-confidence answers are cooldown-stamped
7323
+ * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
7324
+ * returned un-stamped in `escalated` for the generative step. Always
7325
+ * returns the `OntologyBackfillResult` for its step plus escalation state.
7137
7326
  */
7138
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter) {
7139
- const rawMin = this.options.config?.ontology?.classifyMinConfidence;
7140
- const minConfidence = typeof rawMin === "number" && Number.isFinite(rawMin) && rawMin >= 0 && rawMin <= 1 ? rawMin : 0.5;
7327
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
7328
+ const minConfidence = resolveTypingMinConfidence(this.options.config);
7141
7329
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
7142
7330
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
7143
7331
  const question = {
7144
7332
  kind: "choice",
7145
- options: manifest.node_types.map((n) => n.type),
7146
- instructions: "Choose the ontology node type that best describes this fact.\n" + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7333
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
7334
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
7335
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7147
7336
  };
7148
7337
  let stopped;
7149
7338
  const outcomes = await withConcurrency(
@@ -7153,7 +7342,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7153
7342
  try {
7154
7343
  response = await callClassify(
7155
7344
  this.options,
7156
- { operation: "ontologyBackfill", entityId, trigger: "call", meter },
7345
+ { operation: "ontologyBackfill", entityId, trigger, meter },
7157
7346
  { state: classifierStateForFact(fact), questions: { okf_type: question } }
7158
7347
  );
7159
7348
  } catch (err) {
@@ -7167,37 +7356,47 @@ DROP TRIGGER IF EXISTS ${ad};`);
7167
7356
  const checked = validateClassifierAnswer(response, "okf_type", question);
7168
7357
  if (!checked.ok) return { fact, kind: "invalid", reason: checked.reason };
7169
7358
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
7359
+ if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
7170
7360
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
7171
7361
  return { fact, kind: "accepted", okfType: checked.answer.choice };
7172
7362
  }),
7173
7363
  concurrency
7174
7364
  );
7175
- const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted").map((o) => o.fact);
7365
+ const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
7366
+ const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
7367
+ const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
7368
+ const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
7176
7369
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
7177
7370
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
7178
7371
  const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
7179
7372
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
7373
+ const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
7180
7374
  let typed = 0;
7181
7375
  let failedValidation = 0;
7182
7376
  let edgesAdded = 0;
7183
- let aborted = false;
7377
+ let abortedOntologyOff = false;
7184
7378
  if (attempted.length > 0) {
7185
7379
  const applied = await this._applyOntologyBackfillBatch(
7186
7380
  entityId,
7187
7381
  { batch: attempted, classifications, ontologyUpdates: void 0 },
7188
- now
7382
+ now,
7383
+ "classifier",
7384
+ trigger
7189
7385
  );
7190
- aborted = applied.abortedOntologyOff;
7191
- if (!aborted) {
7386
+ abortedOntologyOff = applied.abortedOntologyOff;
7387
+ if (!abortedOntologyOff) {
7192
7388
  typed = applied.typed;
7193
7389
  failedValidation = invalidCount + applied.failedValidation;
7194
7390
  edgesAdded = applied.edgesAdded;
7195
7391
  }
7196
7392
  }
7197
7393
  const diagBuffer = new DiagnosticBuffer();
7198
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
7394
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
7199
7395
  for (const o of outcomes) {
7200
- if (o.kind === "low_confidence") {
7396
+ if (o.kind === "abstain") {
7397
+ if (isEscalated(o)) continue;
7398
+ diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
7399
+ } else if (o.kind === "low_confidence") {
7201
7400
  diagBuffer.push({ ...diagBase, code: "classification_low_confidence", detail: { factId: o.fact.id, reason: "below_threshold" } });
7202
7401
  } else if (o.kind === "invalid") {
7203
7402
  diagBuffer.push({ ...diagBase, code: "classification_invalid", detail: { factId: o.fact.id, reason: o.reason } });
@@ -7209,19 +7408,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
7209
7408
  }
7210
7409
  diagBuffer.flush(this.options);
7211
7410
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7212
- if (aborted) {
7213
- return { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped, remaining: 0, deferred: counts.deferred, ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {} };
7411
+ const budgetStop = stopped ? { requiredEstimate: stopped.requiredEstimate } : void 0;
7412
+ if (abortedOntologyOff) {
7413
+ return {
7414
+ result: { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, abstained: 0, skipped, remaining: 0, deferred: counts.deferred, ...budgetStop ? { budgetStop } : {} },
7415
+ escalated: [],
7416
+ abortedOntologyOff
7417
+ };
7214
7418
  }
7215
7419
  this.searchService.evictCache(entityId);
7216
7420
  return {
7217
- scanned: candidates.length - unattemptedCount,
7218
- typed,
7219
- failedValidation,
7220
- edgesAdded,
7221
- skipped,
7222
- remaining: counts.eligible,
7223
- deferred: counts.deferred,
7224
- ...stopped ? { budgetStop: { requiredEstimate: stopped.requiredEstimate } } : {}
7421
+ result: {
7422
+ scanned: candidates.length - unattemptedCount,
7423
+ typed,
7424
+ failedValidation,
7425
+ edgesAdded,
7426
+ abstained: abstainCount,
7427
+ skipped,
7428
+ remaining: counts.eligible,
7429
+ deferred: counts.deferred,
7430
+ ...budgetStop ? { budgetStop } : {}
7431
+ },
7432
+ escalated,
7433
+ abortedOntologyOff: false
7225
7434
  };
7226
7435
  }
7227
7436
  /**
@@ -7230,15 +7439,18 @@ DROP TRIGGER IF EXISTS ${ad};`);
7230
7439
  * the mid-flight `mode === 'off'` abort check keep the shape they had when a
7231
7440
  * pass was a single call.
7232
7441
  */
7233
- async _applyOntologyBackfillBatch(entityId, batchResult, now) {
7442
+ async _applyOntologyBackfillBatch(entityId, batchResult, now, writer, trigger) {
7234
7443
  const ontologyService = this.ontologyService;
7235
7444
  const { batch, classifications, ontologyUpdates } = batchResult;
7236
7445
  let typed = 0;
7237
7446
  let failedValidation = 0;
7238
7447
  let edgesAdded = 0;
7239
7448
  let abortedOntologyOff = false;
7449
+ const typedIds = [];
7450
+ const omittedIds = [];
7451
+ const classifiedIds = /* @__PURE__ */ new Set();
7240
7452
  const diagBuffer = new DiagnosticBuffer();
7241
- const diagBase = { entityId, operation: "ontologyBackfill", trigger: "call" };
7453
+ const diagBase = { entityId, operation: "ontologyBackfill", trigger };
7242
7454
  await this.db.withTransactionAsync(async (tx) => {
7243
7455
  let { mode: txMode, manifest } = await ontologyService.getEffectiveState(entityId, tx);
7244
7456
  if (txMode === "off") {
@@ -7263,6 +7475,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7263
7475
  continue;
7264
7476
  }
7265
7477
  applied.add(fact.id);
7478
+ classifiedIds.add(fact.id);
7266
7479
  const validationDrops = [];
7267
7480
  const normalized = ontologyService.validateAndNormalizeFact(
7268
7481
  {
@@ -7284,8 +7497,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
7284
7497
  continue;
7285
7498
  }
7286
7499
  const result = await this.entryRepo.updateOkfType(fact.id, entityId, normalized.okf_type, tx);
7287
- if (result.changes === 0) continue;
7500
+ if (result.changes === 0) {
7501
+ omittedIds.push(fact.id);
7502
+ continue;
7503
+ }
7288
7504
  typed++;
7505
+ typedIds.push(fact.id);
7506
+ diagBuffer.push({
7507
+ ...diagBase,
7508
+ code: "node_type_assigned",
7509
+ detail: { factId: fact.id, okfType: normalized.okf_type, writer }
7510
+ });
7289
7511
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
7290
7512
  if (normalized.edges.length > 0) {
7291
7513
  pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
@@ -7311,8 +7533,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
7311
7533
  }
7312
7534
  await this.entryRepo.markOntologyChecked(batch.map((f) => f.id), entityId, now, tx);
7313
7535
  });
7536
+ if (!abortedOntologyOff) {
7537
+ for (const fact of batch) {
7538
+ if (!classifiedIds.has(fact.id)) omittedIds.push(fact.id);
7539
+ }
7540
+ }
7314
7541
  diagBuffer.flush(this.options);
7315
- return { typed, failedValidation, edgesAdded, abortedOntologyOff };
7542
+ return { typed, failedValidation, edgesAdded, abortedOntologyOff, typedIds, omittedIds };
7316
7543
  }
7317
7544
  _validatePruneDuration(value, name) {
7318
7545
  if (value !== null && value !== void 0 && (typeof value !== "number" || !isFinite(value) || value < 0)) {