@equationalapplications/core-llm-wiki 9.14.0 → 9.15.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
@@ -733,6 +733,8 @@ var SEVERITY = {
733
733
  llm_usage: "info",
734
734
  librarian_gate: "info",
735
735
  librarian_op_rejected: "warn",
736
+ librarian_rewritten: "info",
737
+ librarian_superseded: "info",
736
738
  contradicts_document: "warn",
737
739
  resolve_failed: "warn",
738
740
  read_budget: "info",
@@ -788,6 +790,8 @@ var MESSAGE = {
788
790
  llm_usage: "An LLM call completed; token usage attached.",
789
791
  librarian_gate: "Librarian gate outcome counts for one pass.",
790
792
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
793
+ librarian_rewritten: "The librarian rewrote an engine-inferred fact in place; the previous text was not kept.",
794
+ librarian_superseded: "The librarian ended a fact\u2019s validity with a replacement fact.",
791
795
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
792
796
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
793
797
  read_budget: "A read was packed to a token budget.",
@@ -1321,6 +1325,17 @@ function normalizeTitleKey(title) {
1321
1325
  function normalizeSlug(raw) {
1322
1326
  return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
1323
1327
  }
1328
+ function resolveNodeTypeMatch(raw, manifest) {
1329
+ const slug = typeof raw === "string" ? raw.trim() : "";
1330
+ if (!slug) return null;
1331
+ const lowered = slug.toLowerCase();
1332
+ const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
1333
+ if (exact) return { slug: exact.type, via: "exact" };
1334
+ const normalized = normalizeSlug(slug);
1335
+ if (!normalized) return null;
1336
+ const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
1337
+ return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
1338
+ }
1324
1339
  var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
1325
1340
  function isReservedAbstainSlug(raw) {
1326
1341
  return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
@@ -2710,16 +2725,36 @@ ${guidanceSection(guidance)}`;
2710
2725
  } while (out !== prev);
2711
2726
  return out;
2712
2727
  }
2713
- buildSystemPrompt(template, variables, ontologyContext) {
2728
+ /** Write-site variant (ingest, librarian, ops extract). Body identical to the backfill variant by design (specs/type-on-write §5). */
2729
+ buildWriteSystemPrompt(template, variables, ontologyContext) {
2730
+ const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
2731
+ const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
2732
+ const shouldHydrate = Object.keys(variables).some(
2733
+ (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
2734
+ ) || ontologyContext != null && hasOntologyPlaceholders;
2735
+ const hydrated = shouldHydrate ? this.hydrate(effective, {
2736
+ ...variables,
2737
+ ...ontologyContext ? { ontologyManifest: ontologyContext.ontologyManifest, ontologyModeInstructions: ontologyContext.ontologyModeInstructions } : {}
2738
+ }) : effective;
2739
+ return hasOntologyPlaceholders ? hydrated : this.appendWriteOntology(hydrated, ontologyContext);
2740
+ }
2741
+ appendWriteOntology(systemPrompt, ctx) {
2742
+ if (!ctx) return systemPrompt;
2743
+ return `${systemPrompt}
2744
+
2745
+ ${ctx.ontologyModeInstructions}`;
2746
+ }
2747
+ /** Backfill-site variant. Body identical to the write variant by design (specs/type-on-write §5). */
2748
+ buildBackfillSystemPrompt(template, variables, ontologyContext) {
2714
2749
  const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
2715
2750
  const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
2716
2751
  const shouldHydrate = Object.keys(variables).some(
2717
2752
  (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
2718
2753
  ) || ontologyContext != null && hasOntologyPlaceholders;
2719
2754
  const hydrated = shouldHydrate ? this.hydrate(effective, { ...variables, ...ontologyContext ?? {} }) : effective;
2720
- return hasOntologyPlaceholders ? hydrated : this.appendOntology(hydrated, ontologyContext);
2755
+ return hasOntologyPlaceholders ? hydrated : this.appendBackfillOntology(hydrated, ontologyContext);
2721
2756
  }
2722
- appendOntology(systemPrompt, ctx) {
2757
+ appendBackfillOntology(systemPrompt, ctx) {
2723
2758
  if (!ctx) return systemPrompt;
2724
2759
  return `${systemPrompt}
2725
2760
 
@@ -2730,13 +2765,13 @@ ${ctx.ontologyModeInstructions}`;
2730
2765
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
2731
2766
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
2732
2767
  return {
2733
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2768
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2734
2769
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
2735
2770
  ${documentChunk}`
2736
2771
  };
2737
2772
  }
2738
2773
  return {
2739
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
2774
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "ingest"),
2740
2775
  userPrompt: `Document Chunk:
2741
2776
  ${documentChunk}`
2742
2777
  };
@@ -2749,7 +2784,7 @@ ${documentChunk}`
2749
2784
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
2750
2785
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
2751
2786
  return {
2752
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2787
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2753
2788
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
2754
2789
  ${JSON.stringify(events, null, 2)}
2755
2790
 
@@ -2759,7 +2794,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
2759
2794
  };
2760
2795
  }
2761
2796
  return {
2762
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
2797
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "librarian"),
2763
2798
  userPrompt: `Events:
2764
2799
  ${JSON.stringify(events, null, 2)}
2765
2800
 
@@ -2850,7 +2885,7 @@ The following document anchors are provided for contradiction detection only. Do
2850
2885
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2851
2886
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
2852
2887
  return {
2853
- systemPrompt: this.buildSystemPrompt(template, { facts }, ontologyContext),
2888
+ systemPrompt: this.buildBackfillSystemPrompt(template, { facts }, ontologyContext),
2854
2889
  userPrompt: hasFacts ? "Please classify the facts." : `Facts:
2855
2890
  ${JSON.stringify(facts, null, 2)}`
2856
2891
  };
@@ -2858,7 +2893,7 @@ ${JSON.stringify(facts, null, 2)}`
2858
2893
  const factsBlock = `Facts:
2859
2894
  ${JSON.stringify(facts, null, 2)}`;
2860
2895
  return {
2861
- systemPrompt: this.appendOntology(template, ontologyContext),
2896
+ systemPrompt: this.appendBackfillOntology(template, ontologyContext),
2862
2897
  userPrompt: candidateSections !== void 0 ? `${factsBlock}
2863
2898
 
2864
2899
  ${candidateSections}` : factsBlock
@@ -2869,7 +2904,7 @@ ${candidateSections}` : factsBlock
2869
2904
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2870
2905
  const grounding = this.groundingFor("librarian");
2871
2906
  return {
2872
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2907
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2873
2908
  userPrompt: `Events:
2874
2909
  ${lines.join("\n")}`,
2875
2910
  // Corpus entries are one-per-batch-event in batch order (summaries are
@@ -2890,13 +2925,14 @@ ${JSON.stringify({ items })}` };
2890
2925
  * placeholders and leaves data placeholders verbatim; heal never receives
2891
2926
  * ontology context, matching `buildHealPrompt`.
2892
2927
  */
2893
- buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2928
+ buildInstructionTemplates(writeContext, librarianStrategy, guidance, backfillContext, ingestContext) {
2894
2929
  const o = this.globalOverrides;
2930
+ const backfill = backfillContext !== void 0 ? backfillContext : writeContext ? { ontologyManifest: writeContext.ontologyManifest, ontologyModeInstructions: writeContext.ontologyModeInstructions } : null;
2895
2931
  return {
2896
- ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2897
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
2932
+ ingest: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ingestContext !== void 0 ? ingestContext : writeContext), guidance), "ingest"),
2933
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, writeContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, writeContext), guidance), "librarian"),
2898
2934
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2899
- ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2935
+ ontologyBackfill: this.buildBackfillSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, backfill)
2900
2936
  };
2901
2937
  }
2902
2938
  };
@@ -3182,7 +3218,7 @@ var IngestionService = class {
3182
3218
  }
3183
3219
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3184
3220
  if (chunks2.length === 0) return zeroChunkResult();
3185
- const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
3221
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
3186
3222
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3187
3223
  if (diagnostic) {
3188
3224
  emitDiagnostic(this.options, {
@@ -4199,6 +4235,16 @@ function resolveSystemOneHealScreen(config) {
4199
4235
  }
4200
4236
  return healScreen ?? "llm";
4201
4237
  }
4238
+ function resolveSystemOneTypeOnWrite(config) {
4239
+ const typeOnWrite = config?.systemOne?.typeOnWrite;
4240
+ if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
4241
+ warnOnce(
4242
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnWrite\` is ${formatConfigValue(typeOnWrite)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4243
+ );
4244
+ return "llm";
4245
+ }
4246
+ return typeOnWrite ?? "llm";
4247
+ }
4202
4248
  function resolveHealScreenMinConfidence(config) {
4203
4249
  if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4204
4250
  const floor = config?.systemOne?.minConfidence?.healScreen;
@@ -4446,6 +4492,8 @@ var CONTEXT_OVERFLOW_PATTERNS = [
4446
4492
  // classify as input overflow (it would split the batch and stamp a cooldown).
4447
4493
  /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4448
4494
  /context limit/i,
4495
+ // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
4496
+ /\bcontext is full\b/i,
4449
4497
  /too long for (the )?requested model/i,
4450
4498
  // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4451
4499
  // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
@@ -5050,6 +5098,152 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
5050
5098
  });
5051
5099
  }
5052
5100
 
5101
+ // src/services/typing/typeOnWrite.ts
5102
+ var CLASSIFIER_MAX_CHOICES = 255;
5103
+ function isManifestRepresentable(manifest) {
5104
+ const slugs = manifest.node_types.map((n) => n.type);
5105
+ return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
5106
+ }
5107
+ function canEngageWriteTyping(config, provider, mode, manifest) {
5108
+ return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
5109
+ }
5110
+ function buildTypingQuestion(manifest) {
5111
+ return {
5112
+ kind: "choice",
5113
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
5114
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
5115
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
5116
+ };
5117
+ }
5118
+ function volunteeredTypeResolves(rawOkfType, manifest) {
5119
+ return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
5120
+ }
5121
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
5122
+ const question = buildTypingQuestion(manifest);
5123
+ const rawConcurrency = options.config?.chunkConcurrency ?? 1;
5124
+ const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
5125
+ let stopped = false;
5126
+ return withConcurrency(
5127
+ facts.map((fact) => async () => {
5128
+ if (stopped) return { kind: "unattempted" };
5129
+ let response;
5130
+ try {
5131
+ response = await callClassify(
5132
+ options,
5133
+ { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
5134
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
5135
+ );
5136
+ } catch (err) {
5137
+ if (err instanceof WikiBudgetExhausted) {
5138
+ stopped = true;
5139
+ return { kind: "unattempted" };
5140
+ }
5141
+ if (isContextOverflowError(err)) return { kind: "overflow_skip" };
5142
+ return { kind: "threw" };
5143
+ }
5144
+ const checked = validateClassifierAnswer(response, "okf_type", question);
5145
+ if (!checked.ok) return { kind: "invalid", reason: checked.reason };
5146
+ if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
5147
+ if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
5148
+ if (checked.answer.confidence < floor) return { kind: "low_confidence" };
5149
+ return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
5150
+ }),
5151
+ concurrency
5152
+ );
5153
+ }
5154
+ function emptyTypingCounters() {
5155
+ return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
5156
+ }
5157
+ function tallyTypingOutcome(c, o) {
5158
+ switch (o.kind) {
5159
+ case "unattempted":
5160
+ c.unattempted++;
5161
+ return;
5162
+ case "accepted":
5163
+ c.asked++;
5164
+ return;
5165
+ case "abstain":
5166
+ c.asked++;
5167
+ c.abstained++;
5168
+ return;
5169
+ case "low_confidence":
5170
+ c.asked++;
5171
+ c.lowConfidence++;
5172
+ return;
5173
+ case "invalid":
5174
+ case "threw":
5175
+ c.asked++;
5176
+ c.invalid++;
5177
+ return;
5178
+ case "overflow_skip":
5179
+ c.asked++;
5180
+ c.skipped++;
5181
+ return;
5182
+ }
5183
+ }
5184
+ function typingOutcomeReceipt(base, factId, outcome) {
5185
+ switch (outcome.kind) {
5186
+ case "abstain":
5187
+ return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
5188
+ case "low_confidence":
5189
+ return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
5190
+ case "invalid":
5191
+ return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
5192
+ case "threw":
5193
+ return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
5194
+ case "overflow_skip":
5195
+ return { ...base, code: "context_overflow_skipped", detail: { factId } };
5196
+ default:
5197
+ return null;
5198
+ }
5199
+ }
5200
+ function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
5201
+ const drops = [];
5202
+ const receipts = [];
5203
+ const emit = shouldEmitOntologyReceipt(mode);
5204
+ let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5205
+ if (emit) {
5206
+ receipts.push(...nodeTypeReceipts(
5207
+ base,
5208
+ factId,
5209
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
5210
+ normalized.okf_type,
5211
+ normalized.match
5212
+ ));
5213
+ }
5214
+ let typedByClassifier = false;
5215
+ if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
5216
+ const second = ontology?.validateAndNormalizeFact(
5217
+ { ...fact, okf_type: outcome.okfType, edges: [] },
5218
+ manifest,
5219
+ { strict: false }
5220
+ ) ?? { okf_type: null};
5221
+ if (emit) {
5222
+ receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
5223
+ }
5224
+ normalized = { okf_type: second.okf_type, edges: [] };
5225
+ if (second.okf_type) {
5226
+ typedByClassifier = true;
5227
+ if (emit) {
5228
+ receipts.push({
5229
+ ...base,
5230
+ code: "node_type_assigned",
5231
+ detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
5232
+ });
5233
+ }
5234
+ }
5235
+ } else if (normalized.okf_type) {
5236
+ if (emit) {
5237
+ receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
5238
+ }
5239
+ }
5240
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
5241
+ const r = typingOutcomeReceipt(base, factId, outcome);
5242
+ if (r) receipts.push(r);
5243
+ }
5244
+ return { normalized, drops, receipts, typedByClassifier };
5245
+ }
5246
+
5053
5247
  // src/services/librarian/constants.ts
5054
5248
  var FUZZY_THRESHOLD = 0.5;
5055
5249
  var MIN_TOKENS_TO_QUALIFY = 3;
@@ -5067,7 +5261,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5067
5261
  tags: typeof rest.tags === "string" ? JSON.parse(rest.tags) : rest.tags
5068
5262
  };
5069
5263
  });
5070
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5264
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
5265
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
5266
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
5071
5267
  const promptEvents = events.reverse();
5072
5268
  const librarianGrounding = deps.promptService.groundingFor("librarian");
5073
5269
  const { systemPrompt, userPrompt, groundingCorpus: librarianCorpus = [] } = deps.promptService.buildLibrarianPrompt(
@@ -5113,6 +5309,22 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5113
5309
  if (valid) validTasks.push(valid);
5114
5310
  else diagBuffer.push({ ...diagBase, code: "task_rejected", detail: { itemIndex, reason: taskRejectionReason(raw) } });
5115
5311
  });
5312
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
5313
+ const typingOutcomes = /* @__PURE__ */ new Map();
5314
+ if (engaged && typingState && typingCounters) {
5315
+ const asked = validFacts.filter((f) => !volunteeredTypeResolves(f.okf_type, typingState.manifest));
5316
+ const outcomes = await classifyFactsForWrite(
5317
+ deps.options,
5318
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
5319
+ asked,
5320
+ typingState.manifest,
5321
+ resolveTypingMinConfidence(deps.options.config)
5322
+ );
5323
+ asked.forEach((f, i) => {
5324
+ typingOutcomes.set(f, outcomes[i]);
5325
+ tallyTypingOutcome(typingCounters, outcomes[i]);
5326
+ });
5327
+ }
5116
5328
  const now = Date.now();
5117
5329
  const insertedFacts = [];
5118
5330
  await deps.db.withTransactionAsync(async (tx) => {
@@ -5159,20 +5371,18 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5159
5371
  }
5160
5372
  const ontologyFact = fact;
5161
5373
  const id = generateId("fact_");
5162
- const validationDrops = [];
5163
- const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
5374
+ const { normalized, drops: validationDrops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
5375
+ deps.ontologyService,
5376
+ ontologyFact,
5377
+ manifest,
5378
+ mode,
5379
+ typingOutcomes.get(fact),
5380
+ diagBase,
5381
+ id
5382
+ );
5164
5383
  for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
5165
- if (shouldEmitOntologyReceipt(mode)) {
5166
- for (const receipt of nodeTypeReceipts(
5167
- { entityId, operation: "librarian", trigger },
5168
- id,
5169
- ontologyFact.okf_type ?? "",
5170
- normalized.okf_type,
5171
- normalized.match
5172
- )) {
5173
- diagBuffer.push(receipt);
5174
- }
5175
- }
5384
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
5385
+ if (typedByClassifier && typingCounters) typingCounters.typed++;
5176
5386
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
5177
5387
  if (grounding?.diagnostic) {
5178
5388
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -5252,7 +5462,7 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5252
5462
  }
5253
5463
  deps.searchService.evictCache(entityId);
5254
5464
  const processedThrough = events.length > 0 ? { at: events[events.length - 1].created_at, id: events[events.length - 1].id } : null;
5255
- const out = { processedThrough, factsWritten: insertedFacts.length };
5465
+ const out = { processedThrough, factsWritten: insertedFacts.length, ...typingCounters ? { typing: typingCounters } : {} };
5256
5466
  return out;
5257
5467
  };
5258
5468
 
@@ -5279,7 +5489,7 @@ var RESOLVE_RESERVE_FACTOR = 2;
5279
5489
  var MIN_SEGMENT_CHARS = 500;
5280
5490
  var MAX_SEGMENT_CALLS = 8;
5281
5491
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5282
- async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
5492
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget, engaged = false) {
5283
5493
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
5284
5494
  if (events.length === 0) return { batch: [] };
5285
5495
  const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
@@ -5292,7 +5502,7 @@ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
5292
5502
  }
5293
5503
  let batch = labelEvents(events.slice(0, n));
5294
5504
  if (meter && meter.budget !== void 0) {
5295
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5505
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
5296
5506
  for (; ; ) {
5297
5507
  const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
5298
5508
  if (meter.fits(need)) break;
@@ -5448,8 +5658,8 @@ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe
5448
5658
  return { ...merged, batch: [lone] };
5449
5659
  }
5450
5660
  }
5451
- async function runExtract(deps, ctx, batch) {
5452
- const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
5661
+ async function runExtract(deps, ctx, batch, engaged = false) {
5662
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(ctx.entityId, { engaged }) ?? null;
5453
5663
  return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
5454
5664
  }
5455
5665
  async function extractOnce(deps, ctx, ontologyContext, batch) {
@@ -5775,6 +5985,7 @@ async function applyOps(deps, ctx, input) {
5775
5985
  const failed = new Set(input.failed);
5776
5986
  const written = [];
5777
5987
  const updatedIds = [];
5988
+ const supersededIds = [];
5778
5989
  const now = Date.now();
5779
5990
  await deps.db.withTransactionAsync(async (tx) => {
5780
5991
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
@@ -5800,19 +6011,17 @@ async function applyOps(deps, ctx, input) {
5800
6011
  const title = overrides?.title ?? fact.title;
5801
6012
  const body = overrides?.body ?? fact.body;
5802
6013
  const id = generateId("fact_");
5803
- const drops = [];
5804
- const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5805
- if (shouldEmitOntologyReceipt(mode)) {
5806
- for (const receipt of nodeTypeReceipts(
5807
- { entityId, operation: "librarian", trigger },
5808
- id,
5809
- typeof fact.okf_type === "string" ? fact.okf_type : "",
5810
- normalized.okf_type,
5811
- normalized.match
5812
- )) {
5813
- input.diagnostics.push(receipt);
5814
- }
5815
- }
6014
+ const { normalized, drops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
6015
+ deps.ontologyService,
6016
+ fact,
6017
+ manifest,
6018
+ mode,
6019
+ input.typing?.outcomes.get(g),
6020
+ diagBase,
6021
+ id
6022
+ );
6023
+ for (const receipt of doorReceipts) input.diagnostics.push(receipt);
6024
+ if (typedByClassifier && input.typing) input.typing.counters.typed++;
5816
6025
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
5817
6026
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
5818
6027
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -5897,6 +6106,7 @@ async function applyOps(deps, ctx, input) {
5897
6106
  titleIndex.delete(normalizeTitleKey(existing.title));
5898
6107
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
5899
6108
  updatedIds.push(existing.id);
6109
+ input.diagnostics.push({ ...diagBase, code: "librarian_rewritten", detail: { factId: existing.id } });
5900
6110
  continue;
5901
6111
  }
5902
6112
  }
@@ -5910,6 +6120,8 @@ async function applyOps(deps, ctx, input) {
5910
6120
  const newId = await insert(g, false, supersedeFrom, overrides);
5911
6121
  try {
5912
6122
  await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
6123
+ supersededIds.push(op.targetId);
6124
+ input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
5913
6125
  } catch (err) {
5914
6126
  if (!(err instanceof WikiSupersedeError)) throw err;
5915
6127
  input.diagnostics.push({
@@ -5949,7 +6161,7 @@ async function applyOps(deps, ctx, input) {
5949
6161
  await deps.taskRepo.upsert(taskObj, tx);
5950
6162
  }
5951
6163
  });
5952
- return { written, updatedIds };
6164
+ return { written, updatedIds, supersededIds };
5953
6165
  }
5954
6166
 
5955
6167
  // src/services/librarian/ops/index.ts
@@ -5958,7 +6170,9 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5958
6170
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5959
6171
  await deps.seedWatermark(entityId);
5960
6172
  const wm = await deps.getWatermark(entityId);
5961
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
6173
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
6174
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
6175
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config), engaged);
5962
6176
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5963
6177
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5964
6178
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5966,7 +6180,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5966
6180
  }
5967
6181
  let ex;
5968
6182
  try {
5969
- ex = await runExtract(deps, ctx, sel.batch);
6183
+ ex = await runExtract(deps, ctx, sel.batch, engaged);
5970
6184
  } catch (err) {
5971
6185
  if (err instanceof WikiBudgetExhausted) {
5972
6186
  return { processedThrough: null, factsWritten: 0, budgetStop: { requiredEstimate: err.requiredEstimate } };
@@ -6011,7 +6225,33 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6011
6225
  diagnostics.discard();
6012
6226
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
6013
6227
  }
6014
- const { written, updatedIds } = await applyOps(deps, ctx, {
6228
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
6229
+ const typingOutcomes = /* @__PURE__ */ new Map();
6230
+ if (engaged && typingState && typingCounters) {
6231
+ const failed = new Set(res.failed);
6232
+ const rejected = new Set(res.rejected);
6233
+ const asked = gated.filter((g) => {
6234
+ if (g.decision.kind === "noop") return false;
6235
+ if (volunteeredTypeResolves(g.candidate.fact.okf_type, typingState.manifest)) return false;
6236
+ if (g.decision.kind === "add" || failed.has(g)) return true;
6237
+ const op = res.ops.get(g);
6238
+ if (rejected.has(g) || !op) return true;
6239
+ return op.op !== "NOOP";
6240
+ });
6241
+ const outcomes = await classifyFactsForWrite(
6242
+ deps.options,
6243
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
6244
+ asked.map((g) => g.candidate.fact),
6245
+ typingState.manifest,
6246
+ resolveTypingMinConfidence(deps.options.config)
6247
+ );
6248
+ asked.forEach((g, n) => {
6249
+ typingOutcomes.set(g, outcomes[n]);
6250
+ tallyTypingOutcome(typingCounters, outcomes[n]);
6251
+ });
6252
+ }
6253
+ const { written, updatedIds, supersededIds } = await applyOps(deps, ctx, {
6254
+ typing: typingCounters ? { outcomes: typingOutcomes, counters: typingCounters } : void 0,
6015
6255
  gated,
6016
6256
  ops: res.ops,
6017
6257
  rejected: res.rejected,
@@ -6040,7 +6280,10 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6040
6280
  const last = ex.batch[ex.batch.length - 1].event;
6041
6281
  return {
6042
6282
  processedThrough: { at: last.created_at, id: last.id },
6043
- factsWritten: written.length + updatedIds.length
6283
+ factsWritten: written.length + updatedIds.length,
6284
+ ...typingCounters ? { typing: typingCounters } : {},
6285
+ rewrittenIds: updatedIds,
6286
+ supersededIds
6044
6287
  };
6045
6288
  };
6046
6289
 
@@ -6062,7 +6305,6 @@ async function runLibrarianStrategy(deps, ctx) {
6062
6305
  var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
6063
6306
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
6064
6307
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
6065
- var CLASSIFIER_MAX_CHOICES = 255;
6066
6308
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
6067
6309
  var HEAL_BATCH_SIZE = 25;
6068
6310
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -7274,7 +7516,6 @@ DROP TRIGGER IF EXISTS ${ad};`);
7274
7516
  const batchSize = options?.batchSize ?? HEAL_BATCH_SIZE;
7275
7517
  const trigger = options?.trigger ?? "call";
7276
7518
  const diagBase = { entityId, operation: "heal", trigger };
7277
- const healFloor = resolveHealScreenMinConfidence(this.options.config);
7278
7519
  if (!Number.isInteger(batchSize) || batchSize < 1) {
7279
7520
  throw new Error("Invalid batchSize: must be an integer >= 1");
7280
7521
  }
@@ -7282,6 +7523,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7282
7523
  if (!Number.isInteger(bodyTruncationChars) || bodyTruncationChars < 1) {
7283
7524
  throw new Error("Invalid bodyTruncationChars: must be an integer >= 1");
7284
7525
  }
7526
+ const healFloor = resolveHealScreenMinConfidence(this.options.config);
7285
7527
  const now = Date.now();
7286
7528
  const recheckCutoff = now - HEAL_RECHECK_MS;
7287
7529
  const orphanAfterDays = this.options.config?.orphanAfterDays !== void 0 ? this.options.config?.orphanAfterDays : 30;
@@ -7566,7 +7808,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7566
7808
  diagBuffer.push({
7567
7809
  ...diagBase,
7568
7810
  code,
7569
- detail: { factId, reason: "below_floor", ...confidence !== void 0 ? { confidence } : {} }
7811
+ detail: { factId, reason: "below_floor", confidence }
7570
7812
  });
7571
7813
  }
7572
7814
  };
@@ -7650,8 +7892,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7650
7892
  const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
7651
7893
  const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
7652
7894
  if (classifierMode === "auto" && typeof classify === "function") {
7653
- const slugs = effectiveManifest.node_types.map((n) => n.type);
7654
- if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
7895
+ if (isManifestRepresentable(effectiveManifest)) {
7655
7896
  const classifierRun = await this._runClassifierBackfill(
7656
7897
  entityId,
7657
7898
  candidates,
@@ -7900,12 +8141,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7900
8141
  const minConfidence = resolveTypingMinConfidence(this.options.config);
7901
8142
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
7902
8143
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
7903
- const question = {
7904
- kind: "choice",
7905
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
7906
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
7907
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7908
- };
8144
+ const question = buildTypingQuestion(manifest);
7909
8145
  const edgeScreen = /* @__PURE__ */ new Map();
7910
8146
  if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
7911
8147
  const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);