@equationalapplications/core-llm-wiki 9.14.1 → 9.16.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",
@@ -751,11 +753,14 @@ var SEVERITY = {
751
753
  event_created_at_clamped: "warn",
752
754
  event_created_at_restamped: "info",
753
755
  external_deletion_pending: "warn",
756
+ supersede_scheduled_end_replaced: "info",
754
757
  external_deletion_discarded: "warn",
755
758
  guidance_too_long: "warn",
756
759
  guidance_resolver_failed: "warn",
757
760
  source_pointer_unresolved: "warn",
758
761
  source_pointer_invalid: "warn",
762
+ source_event_gone: "warn",
763
+ derived_events_invalid: "warn",
759
764
  source_store_source_too_large: "warn",
760
765
  source_store_budget_exceeded: "warn",
761
766
  source_store_hash_mismatch: "warn",
@@ -788,6 +793,8 @@ var MESSAGE = {
788
793
  llm_usage: "An LLM call completed; token usage attached.",
789
794
  librarian_gate: "Librarian gate outcome counts for one pass.",
790
795
  librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
796
+ librarian_rewritten: "The librarian rewrote an engine-inferred fact in place; the previous text was not kept.",
797
+ librarian_superseded: "The librarian ended a fact\u2019s validity with a replacement fact.",
791
798
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
792
799
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
793
800
  read_budget: "A read was packed to a token budget.",
@@ -805,12 +812,15 @@ var MESSAGE = {
805
812
  import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
806
813
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
807
814
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
815
+ supersede_scheduled_end_replaced: "A supersede replaced a scheduled end date on the old fact; the prior end is kept in prior_valid_to and reopen() can restore it.",
808
816
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
809
817
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
810
818
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
811
819
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
812
- source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
820
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one, or the librarian merged such an unattributed candidate into this fact in place (its derived_events list was not extended).",
813
821
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
822
+ source_event_gone: "A librarian candidate was dropped at apply time because the event it came from no longer exists (deleted outside the engine while the pass ran).",
823
+ derived_events_invalid: "Import met a malformed derived_events value and stored null.",
814
824
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
815
825
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
816
826
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
@@ -1321,6 +1331,17 @@ function normalizeTitleKey(title) {
1321
1331
  function normalizeSlug(raw) {
1322
1332
  return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
1323
1333
  }
1334
+ function resolveNodeTypeMatch(raw, manifest) {
1335
+ const slug = typeof raw === "string" ? raw.trim() : "";
1336
+ if (!slug) return null;
1337
+ const lowered = slug.toLowerCase();
1338
+ const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
1339
+ if (exact) return { slug: exact.type, via: "exact" };
1340
+ const normalized = normalizeSlug(slug);
1341
+ if (!normalized) return null;
1342
+ const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
1343
+ return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
1344
+ }
1324
1345
  var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
1325
1346
  function isReservedAbstainSlug(raw) {
1326
1347
  return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
@@ -1669,6 +1690,27 @@ function validateSourcePointerValue(v) {
1669
1690
  return normalized;
1670
1691
  }
1671
1692
 
1693
+ // src/utils/derivedEvents.ts
1694
+ function validateDerivedEventsValue(v) {
1695
+ if (v === null) return null;
1696
+ if (!Array.isArray(v)) return void 0;
1697
+ for (const x of v) {
1698
+ if (typeof x !== "string" || x.length === 0) return void 0;
1699
+ }
1700
+ const out = dedupeEventIds(v);
1701
+ return out.length === 0 ? null : out;
1702
+ }
1703
+ function dedupeEventIds(ids) {
1704
+ const seen = /* @__PURE__ */ new Set();
1705
+ const out = [];
1706
+ for (const id of ids) {
1707
+ if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
1708
+ seen.add(id);
1709
+ out.push(id);
1710
+ }
1711
+ return out;
1712
+ }
1713
+
1672
1714
  // src/services/legacyWatermark.ts
1673
1715
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1674
1716
  if (checkpoint <= 0 || total <= 0) return null;
@@ -2075,6 +2117,19 @@ var ImportExportService = class {
2075
2117
  });
2076
2118
  }
2077
2119
  const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
2120
+ const rawDerived = fact["derived_events"];
2121
+ const hasDerivedEventsKey = rawDerived !== void 0;
2122
+ const derivedValidated = hasDerivedEventsKey ? validateDerivedEventsValue(rawDerived) : null;
2123
+ if (derivedValidated === void 0) {
2124
+ refusalDiagnostics.push({
2125
+ code: "derived_events_invalid",
2126
+ operation: "importDump",
2127
+ trigger: "call",
2128
+ entityId,
2129
+ detail: { factId: fact.id }
2130
+ });
2131
+ }
2132
+ const derivedEvents = derivedValidated ?? null;
2078
2133
  const factObj = {
2079
2134
  id: fact.id,
2080
2135
  entity_id: entityId,
@@ -2093,6 +2148,7 @@ var ImportExportService = class {
2093
2148
  embedding_blob: blobData ?? void 0,
2094
2149
  okf_type: fact.okf_type ?? null,
2095
2150
  source_pointer: sourcePointer,
2151
+ ...derivedEvents ? { derived_events: derivedEvents } : {},
2096
2152
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
2097
2153
  // populating these per spec, importDump does not derive or validate them.
2098
2154
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -2110,12 +2166,15 @@ var ImportExportService = class {
2110
2166
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
2111
2167
  })()
2112
2168
  };
2113
- await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
2169
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey, hasDerivedEventsKey);
2114
2170
  await this.entryRepo.setTemporal(fact.id, entityId, {
2115
2171
  valid_from: fact.valid_from ?? null,
2116
2172
  valid_to: fact.valid_to ?? null,
2117
2173
  superseded_by: fact.superseded_by ?? null,
2118
- superseded_at: fact.superseded_at ?? null
2174
+ superseded_at: fact.superseded_at ?? null,
2175
+ // prior_valid_to (spec D5): replace semantics like the four siblings;
2176
+ // null whenever the row is not superseded (the column's invariant).
2177
+ prior_valid_to: fact.superseded_by == null ? null : fact.prior_valid_to ?? null
2119
2178
  }, tx, { outbox: false });
2120
2179
  if (blobData != null) {
2121
2180
  factsWithPreservedBlob.set(fact.id, blobData);
@@ -2710,16 +2769,36 @@ ${guidanceSection(guidance)}`;
2710
2769
  } while (out !== prev);
2711
2770
  return out;
2712
2771
  }
2713
- buildSystemPrompt(template, variables, ontologyContext) {
2772
+ /** Write-site variant (ingest, librarian, ops extract). Body identical to the backfill variant by design (specs/type-on-write §5). */
2773
+ buildWriteSystemPrompt(template, variables, ontologyContext) {
2774
+ const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
2775
+ const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
2776
+ const shouldHydrate = Object.keys(variables).some(
2777
+ (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
2778
+ ) || ontologyContext != null && hasOntologyPlaceholders;
2779
+ const hydrated = shouldHydrate ? this.hydrate(effective, {
2780
+ ...variables,
2781
+ ...ontologyContext ? { ontologyManifest: ontologyContext.ontologyManifest, ontologyModeInstructions: ontologyContext.ontologyModeInstructions } : {}
2782
+ }) : effective;
2783
+ return hasOntologyPlaceholders ? hydrated : this.appendWriteOntology(hydrated, ontologyContext);
2784
+ }
2785
+ appendWriteOntology(systemPrompt, ctx) {
2786
+ if (!ctx) return systemPrompt;
2787
+ return `${systemPrompt}
2788
+
2789
+ ${ctx.ontologyModeInstructions}`;
2790
+ }
2791
+ /** Backfill-site variant. Body identical to the write variant by design (specs/type-on-write §5). */
2792
+ buildBackfillSystemPrompt(template, variables, ontologyContext) {
2714
2793
  const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
2715
2794
  const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
2716
2795
  const shouldHydrate = Object.keys(variables).some(
2717
2796
  (key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
2718
2797
  ) || ontologyContext != null && hasOntologyPlaceholders;
2719
2798
  const hydrated = shouldHydrate ? this.hydrate(effective, { ...variables, ...ontologyContext ?? {} }) : effective;
2720
- return hasOntologyPlaceholders ? hydrated : this.appendOntology(hydrated, ontologyContext);
2799
+ return hasOntologyPlaceholders ? hydrated : this.appendBackfillOntology(hydrated, ontologyContext);
2721
2800
  }
2722
- appendOntology(systemPrompt, ctx) {
2801
+ appendBackfillOntology(systemPrompt, ctx) {
2723
2802
  if (!ctx) return systemPrompt;
2724
2803
  return `${systemPrompt}
2725
2804
 
@@ -2730,13 +2809,13 @@ ${ctx.ontologyModeInstructions}`;
2730
2809
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
2731
2810
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
2732
2811
  return {
2733
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2812
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2734
2813
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
2735
2814
  ${documentChunk}`
2736
2815
  };
2737
2816
  }
2738
2817
  return {
2739
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
2818
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "ingest"),
2740
2819
  userPrompt: `Document Chunk:
2741
2820
  ${documentChunk}`
2742
2821
  };
@@ -2749,7 +2828,7 @@ ${documentChunk}`
2749
2828
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
2750
2829
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
2751
2830
  return {
2752
- systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2831
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2753
2832
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
2754
2833
  ${JSON.stringify(events, null, 2)}
2755
2834
 
@@ -2759,7 +2838,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
2759
2838
  };
2760
2839
  }
2761
2840
  return {
2762
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
2841
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "librarian"),
2763
2842
  userPrompt: `Events:
2764
2843
  ${JSON.stringify(events, null, 2)}
2765
2844
 
@@ -2850,7 +2929,7 @@ The following document anchors are provided for contradiction detection only. Do
2850
2929
  const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
2851
2930
  if (hasFacts || this.hasOntologyPlaceholders(template)) {
2852
2931
  return {
2853
- systemPrompt: this.buildSystemPrompt(template, { facts }, ontologyContext),
2932
+ systemPrompt: this.buildBackfillSystemPrompt(template, { facts }, ontologyContext),
2854
2933
  userPrompt: hasFacts ? "Please classify the facts." : `Facts:
2855
2934
  ${JSON.stringify(facts, null, 2)}`
2856
2935
  };
@@ -2858,7 +2937,7 @@ ${JSON.stringify(facts, null, 2)}`
2858
2937
  const factsBlock = `Facts:
2859
2938
  ${JSON.stringify(facts, null, 2)}`;
2860
2939
  return {
2861
- systemPrompt: this.appendOntology(template, ontologyContext),
2940
+ systemPrompt: this.appendBackfillOntology(template, ontologyContext),
2862
2941
  userPrompt: candidateSections !== void 0 ? `${factsBlock}
2863
2942
 
2864
2943
  ${candidateSections}` : factsBlock
@@ -2869,7 +2948,7 @@ ${candidateSections}` : factsBlock
2869
2948
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2870
2949
  const grounding = this.groundingFor("librarian");
2871
2950
  return {
2872
- systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2951
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2873
2952
  userPrompt: `Events:
2874
2953
  ${lines.join("\n")}`,
2875
2954
  // Corpus entries are one-per-batch-event in batch order (summaries are
@@ -2890,13 +2969,14 @@ ${JSON.stringify({ items })}` };
2890
2969
  * placeholders and leaves data placeholders verbatim; heal never receives
2891
2970
  * ontology context, matching `buildHealPrompt`.
2892
2971
  */
2893
- buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2972
+ buildInstructionTemplates(writeContext, librarianStrategy, guidance, backfillContext, ingestContext) {
2894
2973
  const o = this.globalOverrides;
2974
+ const backfill = backfillContext !== void 0 ? backfillContext : writeContext ? { ontologyManifest: writeContext.ontologyManifest, ontologyModeInstructions: writeContext.ontologyModeInstructions } : null;
2895
2975
  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"),
2976
+ ingest: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ingestContext !== void 0 ? ingestContext : writeContext), guidance), "ingest"),
2977
+ 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
2978
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2899
- ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2979
+ ontologyBackfill: this.buildBackfillSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, backfill)
2900
2980
  };
2901
2981
  }
2902
2982
  };
@@ -3182,7 +3262,7 @@ var IngestionService = class {
3182
3262
  }
3183
3263
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3184
3264
  if (chunks2.length === 0) return zeroChunkResult();
3185
- const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
3265
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
3186
3266
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3187
3267
  if (diagnostic) {
3188
3268
  emitDiagnostic(this.options, {
@@ -3993,10 +4073,17 @@ var TemporalService = class {
3993
4073
  if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3994
4074
  const start = old.valid_from ?? old.created_at;
3995
4075
  if (t <= start) throw new WikiSupersedeError("invalid_interval");
3996
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
4076
+ const replacedScheduledEnd = old.valid_to;
4077
+ await this.entryRepo.setTemporal(oldId, entityId, {
4078
+ valid_to: t,
4079
+ superseded_by: newId,
4080
+ superseded_at: now,
4081
+ prior_valid_to: replacedScheduledEnd
4082
+ }, tx);
3997
4083
  if (repl.valid_from == null) {
3998
4084
  await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
3999
4085
  }
4086
+ return { replacedScheduledEnd };
4000
4087
  }
4001
4088
  async supersede(entityId, oldId, replacement, options) {
4002
4089
  const now = Date.now();
@@ -4025,6 +4112,7 @@ var TemporalService = class {
4025
4112
  }
4026
4113
  const newId = typeof replacement === "string" ? replacement : created.id;
4027
4114
  const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
4115
+ let replacedScheduledEnd = null;
4028
4116
  await this.db.withTransactionAsync(async (tx) => {
4029
4117
  if (created) {
4030
4118
  await this.entryRepo.upsert(created, tx);
@@ -4032,8 +4120,17 @@ var TemporalService = class {
4032
4120
  await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
4033
4121
  }
4034
4122
  }
4035
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
4123
+ ({ replacedScheduledEnd } = await this.supersedeInTx(tx, entityId, oldId, newId, t, now));
4036
4124
  });
4125
+ if (replacedScheduledEnd != null) {
4126
+ emitDiagnostic(this.options, {
4127
+ code: "supersede_scheduled_end_replaced",
4128
+ operation: "supersede",
4129
+ trigger: "call",
4130
+ entityId,
4131
+ detail: { factId: oldId, priorValidTo: replacedScheduledEnd }
4132
+ });
4133
+ }
4037
4134
  await this.searchService.syncEntries(entityId, [oldId, newId]);
4038
4135
  if (created) {
4039
4136
  await this.embeddingService.embedFact(
@@ -4065,6 +4162,35 @@ var TemporalService = class {
4065
4162
  await this.searchService.syncEntries(entityId, [factId]);
4066
4163
  this.searchService.evictCache(entityId);
4067
4164
  }
4165
+ /**
4166
+ * Return a superseded fact to live once its replacement is forgotten or gone
4167
+ * (INTENT rule 12, specs/supersede-future-valid-to D4). Restores `valid_to`
4168
+ * to `prior_valid_to` (null when none was recorded).
4169
+ */
4170
+ async reopen(entityId, factId) {
4171
+ let restored = null;
4172
+ await this.db.withTransactionAsync(async (tx) => {
4173
+ const row = await this.entryRepo.findTemporalRow(factId, tx);
4174
+ if (!row || row.deleted_at != null) throw new WikiSupersedeError("not_found", "reopen()");
4175
+ if (row.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "reopen()");
4176
+ if (row.superseded_by == null) throw new WikiSupersedeError("not_superseded", "reopen()");
4177
+ if (row.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "reopen()");
4178
+ const successor = await this.entryRepo.findTemporalRow(row.superseded_by, tx);
4179
+ if (successor && successor.deleted_at == null) throw new WikiSupersedeError("successor_live", "reopen()");
4180
+ const p = row.prior_valid_to;
4181
+ restored = p != null && Number.isInteger(p) && p > (row.valid_from ?? row.created_at) ? p : null;
4182
+ const changes = await this.entryRepo.setTemporal(factId, entityId, {
4183
+ valid_to: restored,
4184
+ superseded_by: null,
4185
+ superseded_at: null,
4186
+ prior_valid_to: null
4187
+ }, tx);
4188
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "reopen()");
4189
+ });
4190
+ await this.searchService.syncEntries(entityId, [factId]);
4191
+ this.searchService.evictCache(entityId);
4192
+ return { valid_to: restored };
4193
+ }
4068
4194
  async history(entityId, factId) {
4069
4195
  const start = await this.entryRepo.findTemporalRow(factId);
4070
4196
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
@@ -4199,6 +4325,16 @@ function resolveSystemOneHealScreen(config) {
4199
4325
  }
4200
4326
  return healScreen ?? "llm";
4201
4327
  }
4328
+ function resolveSystemOneTypeOnWrite(config) {
4329
+ const typeOnWrite = config?.systemOne?.typeOnWrite;
4330
+ if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
4331
+ warnOnce(
4332
+ `[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.`
4333
+ );
4334
+ return "llm";
4335
+ }
4336
+ return typeOnWrite ?? "llm";
4337
+ }
4202
4338
  function resolveHealScreenMinConfidence(config) {
4203
4339
  if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4204
4340
  const floor = config?.systemOne?.minConfidence?.healScreen;
@@ -5013,8 +5149,34 @@ var MIGRATIONS = [
5013
5149
  );`
5014
5150
  );
5015
5151
  }
5152
+ },
5153
+ {
5154
+ version: 18,
5155
+ description: "Partial index on entries(entity_id, deleted_at) for prune and tombstone probes; nullable prior_valid_to column recording the scheduled end a supersede overwrote; nullable derived_events column listing the events an in-place librarian merge drew on",
5156
+ run: async (db, prefix) => {
5157
+ await createEntriesDeletedIndex(db, prefix);
5158
+ await addPriorValidToColumn(db, prefix);
5159
+ await addDerivedEventsColumn(db, prefix);
5160
+ }
5016
5161
  }
5017
5162
  ];
5163
+ async function addPriorValidToColumn(db, prefix) {
5164
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5165
+ if (!cols.some((c) => c.name === "prior_valid_to")) {
5166
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN prior_valid_to INTEGER`);
5167
+ }
5168
+ }
5169
+ async function createEntriesDeletedIndex(db, prefix) {
5170
+ await db.execAsync(
5171
+ `CREATE INDEX IF NOT EXISTS ${prefix}entries_deleted_idx ON ${prefix}entries(entity_id, deleted_at) WHERE deleted_at IS NOT NULL`
5172
+ );
5173
+ }
5174
+ async function addDerivedEventsColumn(db, prefix) {
5175
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5176
+ if (!cols.some((c) => c.name === "derived_events")) {
5177
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN derived_events TEXT`);
5178
+ }
5179
+ }
5018
5180
  async function createLegacySourceTypeIndex(db, prefix) {
5019
5181
  await db.execAsync(
5020
5182
  `CREATE INDEX IF NOT EXISTS ${prefix}entries_legacy_source_type_idx ON ${prefix}entries(source_type) WHERE source_type IN ('user_document', 'agent_inferred')`
@@ -5052,6 +5214,152 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
5052
5214
  });
5053
5215
  }
5054
5216
 
5217
+ // src/services/typing/typeOnWrite.ts
5218
+ var CLASSIFIER_MAX_CHOICES = 255;
5219
+ function isManifestRepresentable(manifest) {
5220
+ const slugs = manifest.node_types.map((n) => n.type);
5221
+ return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
5222
+ }
5223
+ function canEngageWriteTyping(config, provider, mode, manifest) {
5224
+ return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
5225
+ }
5226
+ function buildTypingQuestion(manifest) {
5227
+ return {
5228
+ kind: "choice",
5229
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
5230
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
5231
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
5232
+ };
5233
+ }
5234
+ function volunteeredTypeResolves(rawOkfType, manifest) {
5235
+ return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
5236
+ }
5237
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
5238
+ const question = buildTypingQuestion(manifest);
5239
+ const rawConcurrency = options.config?.chunkConcurrency ?? 1;
5240
+ const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
5241
+ let stopped = false;
5242
+ return withConcurrency(
5243
+ facts.map((fact) => async () => {
5244
+ if (stopped) return { kind: "unattempted" };
5245
+ let response;
5246
+ try {
5247
+ response = await callClassify(
5248
+ options,
5249
+ { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
5250
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
5251
+ );
5252
+ } catch (err) {
5253
+ if (err instanceof WikiBudgetExhausted) {
5254
+ stopped = true;
5255
+ return { kind: "unattempted" };
5256
+ }
5257
+ if (isContextOverflowError(err)) return { kind: "overflow_skip" };
5258
+ return { kind: "threw" };
5259
+ }
5260
+ const checked = validateClassifierAnswer(response, "okf_type", question);
5261
+ if (!checked.ok) return { kind: "invalid", reason: checked.reason };
5262
+ if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
5263
+ if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
5264
+ if (checked.answer.confidence < floor) return { kind: "low_confidence" };
5265
+ return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
5266
+ }),
5267
+ concurrency
5268
+ );
5269
+ }
5270
+ function emptyTypingCounters() {
5271
+ return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
5272
+ }
5273
+ function tallyTypingOutcome(c, o) {
5274
+ switch (o.kind) {
5275
+ case "unattempted":
5276
+ c.unattempted++;
5277
+ return;
5278
+ case "accepted":
5279
+ c.asked++;
5280
+ return;
5281
+ case "abstain":
5282
+ c.asked++;
5283
+ c.abstained++;
5284
+ return;
5285
+ case "low_confidence":
5286
+ c.asked++;
5287
+ c.lowConfidence++;
5288
+ return;
5289
+ case "invalid":
5290
+ case "threw":
5291
+ c.asked++;
5292
+ c.invalid++;
5293
+ return;
5294
+ case "overflow_skip":
5295
+ c.asked++;
5296
+ c.skipped++;
5297
+ return;
5298
+ }
5299
+ }
5300
+ function typingOutcomeReceipt(base, factId, outcome) {
5301
+ switch (outcome.kind) {
5302
+ case "abstain":
5303
+ return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
5304
+ case "low_confidence":
5305
+ return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
5306
+ case "invalid":
5307
+ return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
5308
+ case "threw":
5309
+ return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
5310
+ case "overflow_skip":
5311
+ return { ...base, code: "context_overflow_skipped", detail: { factId } };
5312
+ default:
5313
+ return null;
5314
+ }
5315
+ }
5316
+ function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
5317
+ const drops = [];
5318
+ const receipts = [];
5319
+ const emit = shouldEmitOntologyReceipt(mode);
5320
+ let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5321
+ if (emit) {
5322
+ receipts.push(...nodeTypeReceipts(
5323
+ base,
5324
+ factId,
5325
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
5326
+ normalized.okf_type,
5327
+ normalized.match
5328
+ ));
5329
+ }
5330
+ let typedByClassifier = false;
5331
+ if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
5332
+ const second = ontology?.validateAndNormalizeFact(
5333
+ { ...fact, okf_type: outcome.okfType, edges: [] },
5334
+ manifest,
5335
+ { strict: false }
5336
+ ) ?? { okf_type: null};
5337
+ if (emit) {
5338
+ receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
5339
+ }
5340
+ normalized = { okf_type: second.okf_type, edges: [] };
5341
+ if (second.okf_type) {
5342
+ typedByClassifier = true;
5343
+ if (emit) {
5344
+ receipts.push({
5345
+ ...base,
5346
+ code: "node_type_assigned",
5347
+ detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
5348
+ });
5349
+ }
5350
+ }
5351
+ } else if (normalized.okf_type) {
5352
+ if (emit) {
5353
+ receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
5354
+ }
5355
+ }
5356
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
5357
+ const r = typingOutcomeReceipt(base, factId, outcome);
5358
+ if (r) receipts.push(r);
5359
+ }
5360
+ return { normalized, drops, receipts, typedByClassifier };
5361
+ }
5362
+
5055
5363
  // src/services/librarian/constants.ts
5056
5364
  var FUZZY_THRESHOLD = 0.5;
5057
5365
  var MIN_TOKENS_TO_QUALIFY = 3;
@@ -5069,7 +5377,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5069
5377
  tags: typeof rest.tags === "string" ? JSON.parse(rest.tags) : rest.tags
5070
5378
  };
5071
5379
  });
5072
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5380
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
5381
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
5382
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
5073
5383
  const promptEvents = events.reverse();
5074
5384
  const librarianGrounding = deps.promptService.groundingFor("librarian");
5075
5385
  const { systemPrompt, userPrompt, groundingCorpus: librarianCorpus = [] } = deps.promptService.buildLibrarianPrompt(
@@ -5115,6 +5425,22 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5115
5425
  if (valid) validTasks.push(valid);
5116
5426
  else diagBuffer.push({ ...diagBase, code: "task_rejected", detail: { itemIndex, reason: taskRejectionReason(raw) } });
5117
5427
  });
5428
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
5429
+ const typingOutcomes = /* @__PURE__ */ new Map();
5430
+ if (engaged && typingState && typingCounters) {
5431
+ const asked = validFacts.filter((f) => !volunteeredTypeResolves(f.okf_type, typingState.manifest));
5432
+ const outcomes = await classifyFactsForWrite(
5433
+ deps.options,
5434
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
5435
+ asked,
5436
+ typingState.manifest,
5437
+ resolveTypingMinConfidence(deps.options.config)
5438
+ );
5439
+ asked.forEach((f, i) => {
5440
+ typingOutcomes.set(f, outcomes[i]);
5441
+ tallyTypingOutcome(typingCounters, outcomes[i]);
5442
+ });
5443
+ }
5118
5444
  const now = Date.now();
5119
5445
  const insertedFacts = [];
5120
5446
  await deps.db.withTransactionAsync(async (tx) => {
@@ -5161,20 +5487,18 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5161
5487
  }
5162
5488
  const ontologyFact = fact;
5163
5489
  const id = generateId("fact_");
5164
- const validationDrops = [];
5165
- const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
5490
+ const { normalized, drops: validationDrops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
5491
+ deps.ontologyService,
5492
+ ontologyFact,
5493
+ manifest,
5494
+ mode,
5495
+ typingOutcomes.get(fact),
5496
+ diagBase,
5497
+ id
5498
+ );
5166
5499
  for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
5167
- if (shouldEmitOntologyReceipt(mode)) {
5168
- for (const receipt of nodeTypeReceipts(
5169
- { entityId, operation: "librarian", trigger },
5170
- id,
5171
- ontologyFact.okf_type ?? "",
5172
- normalized.okf_type,
5173
- normalized.match
5174
- )) {
5175
- diagBuffer.push(receipt);
5176
- }
5177
- }
5500
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
5501
+ if (typedByClassifier && typingCounters) typingCounters.typed++;
5178
5502
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
5179
5503
  if (grounding?.diagnostic) {
5180
5504
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -5254,7 +5578,7 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5254
5578
  }
5255
5579
  deps.searchService.evictCache(entityId);
5256
5580
  const processedThrough = events.length > 0 ? { at: events[events.length - 1].created_at, id: events[events.length - 1].id } : null;
5257
- const out = { processedThrough, factsWritten: insertedFacts.length };
5581
+ const out = { processedThrough, factsWritten: insertedFacts.length, ...typingCounters ? { typing: typingCounters } : {} };
5258
5582
  return out;
5259
5583
  };
5260
5584
 
@@ -5281,7 +5605,7 @@ var RESOLVE_RESERVE_FACTOR = 2;
5281
5605
  var MIN_SEGMENT_CHARS = 500;
5282
5606
  var MAX_SEGMENT_CALLS = 8;
5283
5607
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5284
- async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
5608
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget, engaged = false) {
5285
5609
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
5286
5610
  if (events.length === 0) return { batch: [] };
5287
5611
  const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
@@ -5294,7 +5618,7 @@ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
5294
5618
  }
5295
5619
  let batch = labelEvents(events.slice(0, n));
5296
5620
  if (meter && meter.budget !== void 0) {
5297
- const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5621
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
5298
5622
  for (; ; ) {
5299
5623
  const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
5300
5624
  if (meter.fits(need)) break;
@@ -5450,8 +5774,8 @@ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe
5450
5774
  return { ...merged, batch: [lone] };
5451
5775
  }
5452
5776
  }
5453
- async function runExtract(deps, ctx, batch) {
5454
- const ontologyContext = await deps.ontologyService?.buildPromptContext(ctx.entityId) ?? null;
5777
+ async function runExtract(deps, ctx, batch, engaged = false) {
5778
+ const ontologyContext = await deps.ontologyService?.buildWritePromptContext(ctx.entityId, { engaged }) ?? null;
5455
5779
  return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
5456
5780
  }
5457
5781
  async function extractOnce(deps, ctx, ontologyContext, batch) {
@@ -5768,6 +6092,17 @@ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
5768
6092
  }
5769
6093
  return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
5770
6094
  }
6095
+ function mergeDerivedEvents(existing, contributing) {
6096
+ if (contributing === null || contributing === existing.source_pointer?.event_id) return void 0;
6097
+ const prior = existing.derived_events ?? [];
6098
+ if (prior.includes(contributing)) return void 0;
6099
+ return dedupeEventIds([...prior, contributing]);
6100
+ }
6101
+ function inheritedDerivedEvents(target, ownEventId) {
6102
+ if (!target) return {};
6103
+ const list = dedupeEventIds([target.source_pointer?.event_id, ...target.derived_events ?? []]).filter((id) => id !== ownEventId);
6104
+ return list.length > 0 ? { derived_events: list } : {};
6105
+ }
5771
6106
  async function applyOps(deps, ctx, input) {
5772
6107
  const { entityId, trigger } = ctx;
5773
6108
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -5777,6 +6112,7 @@ async function applyOps(deps, ctx, input) {
5777
6112
  const failed = new Set(input.failed);
5778
6113
  const written = [];
5779
6114
  const updatedIds = [];
6115
+ const supersededIds = [];
5780
6116
  const now = Date.now();
5781
6117
  await deps.db.withTransactionAsync(async (tx) => {
5782
6118
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
@@ -5797,24 +6133,22 @@ async function applyOps(deps, ctx, input) {
5797
6133
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
5798
6134
  }
5799
6135
  const pendingEdges = [];
5800
- const insert = async (g, draft, validFrom, overrides) => {
6136
+ const insert = async (g, draft, validFrom, overrides, inheritFrom) => {
5801
6137
  const fact = g.candidate.fact;
5802
6138
  const title = overrides?.title ?? fact.title;
5803
6139
  const body = overrides?.body ?? fact.body;
5804
6140
  const id = generateId("fact_");
5805
- const drops = [];
5806
- const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5807
- if (shouldEmitOntologyReceipt(mode)) {
5808
- for (const receipt of nodeTypeReceipts(
5809
- { entityId, operation: "librarian", trigger },
5810
- id,
5811
- typeof fact.okf_type === "string" ? fact.okf_type : "",
5812
- normalized.okf_type,
5813
- normalized.match
5814
- )) {
5815
- input.diagnostics.push(receipt);
5816
- }
5817
- }
6141
+ const { normalized, drops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
6142
+ deps.ontologyService,
6143
+ fact,
6144
+ manifest,
6145
+ mode,
6146
+ input.typing?.outcomes.get(g),
6147
+ diagBase,
6148
+ id
6149
+ );
6150
+ for (const receipt of doorReceipts) input.diagnostics.push(receipt);
6151
+ if (typedByClassifier && input.typing) input.typing.counters.typed++;
5818
6152
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
5819
6153
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
5820
6154
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -5843,6 +6177,9 @@ async function applyOps(deps, ctx, input) {
5843
6177
  deleted_at: null,
5844
6178
  okf_type: normalized.okf_type,
5845
6179
  source_pointer: pointer,
6180
+ // §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
6181
+ // rests on the target); ADD and plain SUPERSEDE carry no list.
6182
+ ...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
5846
6183
  ...g2?.trust,
5847
6184
  ...draft ? { lifecycle_status: "draft" } : {}
5848
6185
  };
@@ -5861,7 +6198,18 @@ async function applyOps(deps, ctx, input) {
5861
6198
  written.push({ id, vector: textChanged ? null : g.vector, fact: { id, entity_id: entityId, title, body, tags: fact.tags } });
5862
6199
  return id;
5863
6200
  };
6201
+ const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
6202
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
6203
+ const gatedLive = [];
5864
6204
  for (const g of input.gated) {
6205
+ const ev = g.candidate.sourceEventId;
6206
+ if (ev !== null && !presentIds.has(ev)) {
6207
+ input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
6208
+ continue;
6209
+ }
6210
+ gatedLive.push(g);
6211
+ }
6212
+ for (const g of gatedLive) {
5865
6213
  const idx = g.candidate.index;
5866
6214
  const vf = g.candidate.validFrom;
5867
6215
  if (g.decision.kind === "noop") continue;
@@ -5890,28 +6238,50 @@ async function applyOps(deps, ctx, input) {
5890
6238
  const [existing] = await deps.entryRepo.findByIds([op.targetId], [entityId], tx);
5891
6239
  if (existing) {
5892
6240
  const newTitle = op.title ?? g.candidate.fact.title;
6241
+ const contributing = g.candidate.sourceEventId;
6242
+ if (contributing === null && g.candidate.pointerUnresolved !== null) {
6243
+ input.diagnostics.push({
6244
+ ...diagBase,
6245
+ code: "source_pointer_unresolved",
6246
+ detail: { factId: existing.id, itemIndex: idx, reason: g.candidate.pointerUnresolved }
6247
+ });
6248
+ }
6249
+ const derived = mergeDerivedEvents(existing, contributing);
5893
6250
  await deps.entryRepo.upsert({
5894
6251
  ...existing,
5895
6252
  title: newTitle,
5896
6253
  body: op.body ?? g.candidate.fact.body,
5897
- updated_at: now
6254
+ updated_at: now,
6255
+ ...derived ? { derived_events: derived } : {}
5898
6256
  }, tx);
5899
6257
  titleIndex.delete(normalizeTitleKey(existing.title));
5900
6258
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
5901
6259
  updatedIds.push(existing.id);
6260
+ input.diagnostics.push({ ...diagBase, code: "librarian_rewritten", detail: { factId: existing.id } });
5902
6261
  continue;
5903
6262
  }
5904
6263
  }
5905
6264
  const supersedeFrom = op.op === "SUPERSEDE" && op.validFrom !== void 0 ? op.validFrom : vf;
5906
6265
  const overrides = op.op === "UPDATE" ? { title: op.title, body: op.body } : void 0;
5907
6266
  if (target.source_type === "immutable_document") {
5908
- const id = await insert(g, true, supersedeFrom, overrides);
6267
+ const docTarget = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
6268
+ const id = await insert(g, true, supersedeFrom, overrides, docTarget);
5909
6269
  input.diagnostics.push({ ...diagBase, code: "contradicts_document", detail: { factId: id, itemIndex: idx } });
5910
6270
  continue;
5911
6271
  }
5912
- const newId = await insert(g, false, supersedeFrom, overrides);
6272
+ const inheritFrom = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
6273
+ const newId = await insert(g, false, supersedeFrom, overrides, inheritFrom);
5913
6274
  try {
5914
- await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
6275
+ const { replacedScheduledEnd } = await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
6276
+ supersededIds.push(op.targetId);
6277
+ input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
6278
+ if (replacedScheduledEnd != null) {
6279
+ input.diagnostics.push({
6280
+ ...diagBase,
6281
+ code: "supersede_scheduled_end_replaced",
6282
+ detail: { factId: op.targetId, priorValidTo: replacedScheduledEnd }
6283
+ });
6284
+ }
5915
6285
  } catch (err) {
5916
6286
  if (!(err instanceof WikiSupersedeError)) throw err;
5917
6287
  input.diagnostics.push({
@@ -5951,7 +6321,7 @@ async function applyOps(deps, ctx, input) {
5951
6321
  await deps.taskRepo.upsert(taskObj, tx);
5952
6322
  }
5953
6323
  });
5954
- return { written, updatedIds };
6324
+ return { written, updatedIds, supersededIds };
5955
6325
  }
5956
6326
 
5957
6327
  // src/services/librarian/ops/index.ts
@@ -5960,7 +6330,9 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5960
6330
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5961
6331
  await deps.seedWatermark(entityId);
5962
6332
  const wm = await deps.getWatermark(entityId);
5963
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
6333
+ const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
6334
+ const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
6335
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config), engaged);
5964
6336
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5965
6337
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5966
6338
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5968,7 +6340,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5968
6340
  }
5969
6341
  let ex;
5970
6342
  try {
5971
- ex = await runExtract(deps, ctx, sel.batch);
6343
+ ex = await runExtract(deps, ctx, sel.batch, engaged);
5972
6344
  } catch (err) {
5973
6345
  if (err instanceof WikiBudgetExhausted) {
5974
6346
  return { processedThrough: null, factsWritten: 0, budgetStop: { requiredEstimate: err.requiredEstimate } };
@@ -6013,7 +6385,33 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6013
6385
  diagnostics.discard();
6014
6386
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
6015
6387
  }
6016
- const { written, updatedIds } = await applyOps(deps, ctx, {
6388
+ const typingCounters = engaged ? emptyTypingCounters() : void 0;
6389
+ const typingOutcomes = /* @__PURE__ */ new Map();
6390
+ if (engaged && typingState && typingCounters) {
6391
+ const failed = new Set(res.failed);
6392
+ const rejected = new Set(res.rejected);
6393
+ const asked = gated.filter((g) => {
6394
+ if (g.decision.kind === "noop") return false;
6395
+ if (volunteeredTypeResolves(g.candidate.fact.okf_type, typingState.manifest)) return false;
6396
+ if (g.decision.kind === "add" || failed.has(g)) return true;
6397
+ const op = res.ops.get(g);
6398
+ if (rejected.has(g) || !op) return true;
6399
+ return op.op !== "NOOP";
6400
+ });
6401
+ const outcomes = await classifyFactsForWrite(
6402
+ deps.options,
6403
+ { entityId, trigger, meter: ctx.meter, operation: "librarian" },
6404
+ asked.map((g) => g.candidate.fact),
6405
+ typingState.manifest,
6406
+ resolveTypingMinConfidence(deps.options.config)
6407
+ );
6408
+ asked.forEach((g, n) => {
6409
+ typingOutcomes.set(g, outcomes[n]);
6410
+ tallyTypingOutcome(typingCounters, outcomes[n]);
6411
+ });
6412
+ }
6413
+ const { written, updatedIds, supersededIds } = await applyOps(deps, ctx, {
6414
+ typing: typingCounters ? { outcomes: typingOutcomes, counters: typingCounters } : void 0,
6017
6415
  gated,
6018
6416
  ops: res.ops,
6019
6417
  rejected: res.rejected,
@@ -6042,7 +6440,10 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6042
6440
  const last = ex.batch[ex.batch.length - 1].event;
6043
6441
  return {
6044
6442
  processedThrough: { at: last.created_at, id: last.id },
6045
- factsWritten: written.length + updatedIds.length
6443
+ factsWritten: written.length + updatedIds.length,
6444
+ ...typingCounters ? { typing: typingCounters } : {},
6445
+ rewrittenIds: updatedIds,
6446
+ supersededIds
6046
6447
  };
6047
6448
  };
6048
6449
 
@@ -6064,7 +6465,6 @@ async function runLibrarianStrategy(deps, ctx) {
6064
6465
  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.`;
6065
6466
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
6066
6467
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
6067
- var CLASSIFIER_MAX_CHOICES = 255;
6068
6468
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
6069
6469
  var HEAL_BATCH_SIZE = 25;
6070
6470
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -7652,8 +8052,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7652
8052
  const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
7653
8053
  const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
7654
8054
  if (classifierMode === "auto" && typeof classify === "function") {
7655
- const slugs = effectiveManifest.node_types.map((n) => n.type);
7656
- if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
8055
+ if (isManifestRepresentable(effectiveManifest)) {
7657
8056
  const classifierRun = await this._runClassifierBackfill(
7658
8057
  entityId,
7659
8058
  candidates,
@@ -7902,12 +8301,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7902
8301
  const minConfidence = resolveTypingMinConfidence(this.options.config);
7903
8302
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
7904
8303
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
7905
- const question = {
7906
- kind: "choice",
7907
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
7908
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
7909
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7910
- };
8304
+ const question = buildTypingQuestion(manifest);
7911
8305
  const edgeScreen = /* @__PURE__ */ new Map();
7912
8306
  if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
7913
8307
  const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);