@equationalapplications/core-llm-wiki 9.7.0 → 9.9.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.
@@ -775,20 +775,40 @@ function emptyManifest() {
775
775
  function normalizeTitleKey(title) {
776
776
  return title.trim().toLowerCase().replace(/\s+/g, " ");
777
777
  }
778
- function resolveNodeType(raw, manifest) {
779
- const slug = raw.trim();
778
+ function normalizeSlug(raw) {
779
+ return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
780
+ }
781
+ function resolveNodeTypeMatch(raw, manifest) {
782
+ const slug = typeof raw === "string" ? raw.trim() : "";
780
783
  if (!slug) return null;
781
- const hit = manifest.node_types.find((n) => n.type.toLowerCase() === slug.toLowerCase());
782
- return hit?.type ?? null;
784
+ const lowered = slug.toLowerCase();
785
+ const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
786
+ if (exact) return { slug: exact.type, via: "exact" };
787
+ const normalized = normalizeSlug(slug);
788
+ if (!normalized) return null;
789
+ const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
790
+ return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
791
+ }
792
+ function resolveNodeType(raw, manifest) {
793
+ return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
783
794
  }
784
795
  var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
785
796
  function isReservedAbstainSlug(raw) {
786
797
  return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
787
798
  }
788
799
  function resolveEdgeDefinitions(rawEdgeType, manifest) {
789
- const slug = rawEdgeType.trim();
800
+ const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
790
801
  if (!slug) return [];
791
- return manifest.edge_types.filter((e) => e.type.toLowerCase() === slug.toLowerCase());
802
+ const lowered = slug.toLowerCase();
803
+ const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
804
+ if (exact.length > 0) return exact;
805
+ const normalized = normalizeSlug(slug);
806
+ if (!normalized) return [];
807
+ const names = new Set(
808
+ manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
809
+ );
810
+ if (names.size !== 1) return [];
811
+ return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
792
812
  }
793
813
  function edgeTripleKey(type, sourceType, targetType) {
794
814
  return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
@@ -874,6 +894,7 @@ function buildDeclaresParentIndex(nodes) {
874
894
  function mergeOntologyUpdates(current, updates) {
875
895
  const node_types = [...current.node_types];
876
896
  const edge_types = [...current.edge_types];
897
+ const rejected = [];
877
898
  const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
878
899
  const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
879
900
  const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
@@ -883,9 +904,15 @@ function mergeOntologyUpdates(current, updates) {
883
904
  ]);
884
905
  for (const node of updates.node_types ?? []) {
885
906
  const type = node?.type?.trim();
886
- if (!type) continue;
907
+ if (!type) {
908
+ rejected.push("invalid_shape");
909
+ continue;
910
+ }
887
911
  const key = type.toLowerCase();
888
- if (nodeSlugs.has(key)) continue;
912
+ if (nodeSlugs.has(key)) {
913
+ rejected.push("duplicate_node_type");
914
+ continue;
915
+ }
889
916
  const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
890
917
  const parentSlug = rawParent.toLowerCase();
891
918
  const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
@@ -900,11 +927,20 @@ function mergeOntologyUpdates(current, updates) {
900
927
  const rawEdgeType = edge?.type?.trim();
901
928
  const sourceType = edge?.source_type?.trim();
902
929
  const targetType = edge?.target_type?.trim();
903
- if (!rawEdgeType || !sourceType || !targetType) continue;
930
+ if (!rawEdgeType || !sourceType || !targetType) {
931
+ rejected.push("invalid_shape");
932
+ continue;
933
+ }
904
934
  const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
905
935
  const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
906
- if (edgeKeys.has(edgeKey)) continue;
907
- if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) continue;
936
+ if (edgeKeys.has(edgeKey)) {
937
+ rejected.push("duplicate_edge");
938
+ continue;
939
+ }
940
+ if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
941
+ rejected.push("unknown_endpoint");
942
+ continue;
943
+ }
908
944
  edgeNames.set(edgeType.toLowerCase(), edgeType);
909
945
  edge_types.push({
910
946
  type: edgeType,
@@ -914,7 +950,7 @@ function mergeOntologyUpdates(current, updates) {
914
950
  });
915
951
  edgeKeys.add(edgeKey);
916
952
  }
917
- return { node_types, edge_types };
953
+ return { manifest: { node_types, edge_types }, rejected };
918
954
  }
919
955
  function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
920
956
  const strict = opts?.strict === true;
@@ -1208,9 +1244,9 @@ var MetadataRepository = class extends BaseRepository {
1208
1244
  mode: "emergent",
1209
1245
  manifest: emptyManifest()
1210
1246
  };
1211
- const merged = mergeOntologyUpdates(current.manifest, updates);
1247
+ const { manifest: merged, rejected } = mergeOntologyUpdates(current.manifest, updates);
1212
1248
  await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
1213
- return merged;
1249
+ return { manifest: merged, rejected };
1214
1250
  }
1215
1251
  };
1216
1252
 
@@ -2245,7 +2281,8 @@ Return ONLY a valid JSON object matching this schema:
2245
2281
  {
2246
2282
  "facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
2247
2283
  }
2248
- Extract verbatim factual content. JSON escaping rules: every literal " character in the source must be escaped as \\" inside any JSON string body, and every literal newline as \\n. Source prose containing quotes (e.g. a worked example with "...") must still be reproduced exactly \u2014 re-escape, do not omit. Do not return markdown, just raw JSON.`;
2284
+ Extract verbatim factual content. JSON escaping rules: every literal " character in the source must be escaped as \\" inside any JSON string body, and every literal newline as \\n. Source prose containing quotes (e.g. a worked example with "...") must still be reproduced exactly \u2014 re-escape, do not omit. Do not return markdown, just raw JSON.
2285
+ When the ontology manifest is present in your instructions, supply okf_type for each fact: use a manifest slug exactly as spelled (spelling variants like underscores, hyphens, or spaces are folded to the manifest form), or omit okf_type when no manifest type fits.`;
2249
2286
  var ONTOLOGY_BACKFILL_SYSTEM_PROMPT = `You are a knowledge classification agent. You will receive existing memory facts that currently have no ontology type. For each input fact { "id", "title", "body", "tags" }, assign the best matching okf_type from the ontology manifest and optionally propose edges to related facts by title.
2250
2287
  Return ONLY a valid JSON object matching this schema:
2251
2288
  {
@@ -2253,7 +2290,7 @@ Return ONLY a valid JSON object matching this schema:
2253
2290
  { "id": "string (input fact id, copied verbatim)", "okf_type": "string (manifest node type slug)", "edges": [{ "edge_type": "string", "target_title": "string" }] }
2254
2291
  ]
2255
2292
  }
2256
- If no manifest type fits a fact, omit that fact from "classifications" entirely \u2014 do not guess.
2293
+ If no manifest type fits a fact, assign the closest type the fact is an example of; omit that fact from "classifications" only when no type applies even broadly. Use the manifest slug EXACTLY as spelled (spelling variants are folded to the manifest form).
2257
2294
  When echoing an existing fact's title verbatim into "target_title", preserve every JSON escape sequence (\\", \\n, \\\\, \\/) exactly as it appeared in the input body \u2014 do not strip backslashes, do not add unescaped quotes. Do not return markdown, just raw JSON.`;
2258
2295
  var TITLE_CATALOG_MAX_ENTRIES = 200;
2259
2296
  function buildTitleCatalogBlock(rows) {
@@ -2845,7 +2882,11 @@ var SEVERITY = {
2845
2882
  source_store_budget_exceeded: "warn",
2846
2883
  source_store_hash_mismatch: "warn",
2847
2884
  source_store_duplicate_hash: "warn",
2848
- source_store_text_not_storable: "warn"
2885
+ source_store_text_not_storable: "warn",
2886
+ node_type_dropped: "warn",
2887
+ node_type_folded: "info",
2888
+ ontology_update_rejected: "warn",
2889
+ ingest_zero_facts: "warn"
2849
2890
  };
2850
2891
  var MESSAGE = {
2851
2892
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2894,8 +2935,48 @@ var MESSAGE = {
2894
2935
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
2895
2936
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
2896
2937
  source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
2897
- source_store_text_not_storable: "A source document text could not be stored as given."
2938
+ source_store_text_not_storable: "A source document text could not be stored as given.",
2939
+ node_type_dropped: "A supplied node type missed the ontology manifest and the fact was stored untyped.",
2940
+ node_type_folded: "A supplied node type was normalized into the manifest canonical slug.",
2941
+ ontology_update_rejected: "An emergent ontology proposal was rejected during the merge.",
2942
+ ingest_zero_facts: "A re-ingest tombstoned prior facts and edges and then wrote zero facts."
2898
2943
  };
2944
+ function shouldEmitOntologyReceipt(mode) {
2945
+ return mode !== "off";
2946
+ }
2947
+ function capReceiptSlug(slug) {
2948
+ return typeof slug === "string" ? slug.slice(0, 64) : "";
2949
+ }
2950
+ function nodeTypeReceipts(base, factId, rawType, okfType, match) {
2951
+ const out = [];
2952
+ const supplied = typeof rawType === "string" ? rawType.trim() : "";
2953
+ if (match && match.via === "normalize") {
2954
+ const to = capReceiptSlug(match.canonical);
2955
+ out.push({
2956
+ ...base,
2957
+ code: "node_type_folded",
2958
+ detail: {
2959
+ factId,
2960
+ nodeType: to,
2961
+ from: capReceiptSlug(match.raw),
2962
+ to,
2963
+ via: "normalize"
2964
+ }
2965
+ });
2966
+ }
2967
+ if (!okfType && supplied) {
2968
+ out.push({
2969
+ ...base,
2970
+ code: "node_type_dropped",
2971
+ detail: {
2972
+ factId,
2973
+ nodeType: capReceiptSlug(supplied),
2974
+ reason: "not_in_manifest"
2975
+ }
2976
+ });
2977
+ }
2978
+ return out;
2979
+ }
2899
2980
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2900
2981
  function copyDetail(detail) {
2901
2982
  const copy = { ...detail };
@@ -3310,6 +3391,15 @@ var IngestionService = class {
3310
3391
  });
3311
3392
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
3312
3393
  insertedFacts.push(...fullResult.insertedFacts);
3394
+ if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
3395
+ diagBuffer.push({
3396
+ entityId,
3397
+ operation: "ingest",
3398
+ trigger: "call",
3399
+ code: "ingest_zero_facts",
3400
+ detail: { sourceRef, chunks: chunks2.length }
3401
+ });
3402
+ }
3313
3403
  } else {
3314
3404
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
3315
3405
  const flat = [];
@@ -3447,6 +3537,20 @@ var IngestionService = class {
3447
3537
  strict: strictEffective,
3448
3538
  entityId
3449
3539
  }) ?? { okf_type: null};
3540
+ if (shouldEmitOntologyReceipt(mode)) {
3541
+ for (const receipt of nodeTypeReceipts(
3542
+ { entityId, operation: opts?.diag?.operation ?? "upsertGraph", trigger: "call" },
3543
+ node.id,
3544
+ node.type ?? "",
3545
+ normalized.okf_type,
3546
+ normalized.match
3547
+ )) {
3548
+ opts?.diag?.buffer.push({
3549
+ ...receipt,
3550
+ detail: { ...receipt.detail, sourceRef: params.sourceRef }
3551
+ });
3552
+ }
3553
+ }
3450
3554
  const wikiFact = {
3451
3555
  id: node.id,
3452
3556
  entity_id: entityId,
@@ -3501,8 +3605,8 @@ var IngestionService = class {
3501
3605
  continue;
3502
3606
  }
3503
3607
  const sourceType = sourceIdToType.get(edge.sourceId);
3504
- const candidates = (manifest.edge_types ?? []).filter(
3505
- (d) => d.type.toLowerCase() === edge.type.toLowerCase() && typeSatisfies(d.source_type, sourceType ?? "", manifest)
3608
+ const candidates = resolveEdgeDefinitions(edge.type, manifest).filter(
3609
+ (d) => typeSatisfies(d.source_type, sourceType ?? "", manifest)
3506
3610
  );
3507
3611
  const match = candidates[0];
3508
3612
  if (!match) {
@@ -3581,9 +3685,18 @@ var IngestionService = class {
3581
3685
  const now = Date.now();
3582
3686
  for (const { facts, ontology_updates } of orderedChunkFacts) {
3583
3687
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
3584
- manifest = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
3688
+ const { manifest: merged, rejected } = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
3689
+ manifest = merged;
3690
+ for (const reason of rejected) {
3691
+ diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason } });
3692
+ }
3585
3693
  ontologyState = await this.ontologyService.getEffectiveState(entityId, tx);
3586
3694
  mode = ontologyState.mode;
3695
+ } else if (mode === "strict" && ontology_updates) {
3696
+ const proposalCount = (Array.isArray(ontology_updates.node_types) ? ontology_updates.node_types.length : 0) + (Array.isArray(ontology_updates.edge_types) ? ontology_updates.edge_types.length : 0);
3697
+ for (let i = 0; i < proposalCount; i++) {
3698
+ diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
3699
+ }
3587
3700
  }
3588
3701
  for (const fact of facts) {
3589
3702
  const ontologyFact = fact;
@@ -3681,6 +3794,14 @@ var IngestionService = class {
3681
3794
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
3682
3795
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
3683
3796
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
3797
+ const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
3798
+ const { mode, manifest } = ontologyState;
3799
+ const titleIndex = /* @__PURE__ */ new Map();
3800
+ const indexedFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx);
3801
+ for (const f of indexedFacts) {
3802
+ titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
3803
+ }
3804
+ const pendingEdges = [];
3684
3805
  let inserted = 0;
3685
3806
  let skippedDuplicate = 0;
3686
3807
  const now = Date.now();
@@ -3705,6 +3826,26 @@ var IngestionService = class {
3705
3826
  detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
3706
3827
  });
3707
3828
  }
3829
+ const ontologyFact = fact;
3830
+ const validationDrops = [];
3831
+ const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
3832
+ for (const drop of validationDrops) {
3833
+ diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3834
+ }
3835
+ if (shouldEmitOntologyReceipt(mode)) {
3836
+ for (const receipt of nodeTypeReceipts(
3837
+ { entityId, operation: "ingest", trigger: "call" },
3838
+ id,
3839
+ ontologyFact.okf_type ?? "",
3840
+ normalized.okf_type,
3841
+ normalized.match
3842
+ )) {
3843
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3844
+ }
3845
+ }
3846
+ if (normalized.edges.length > 0) {
3847
+ pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
3848
+ }
3708
3849
  const wikiFact = {
3709
3850
  id,
3710
3851
  entity_id: entityId,
@@ -3723,10 +3864,11 @@ var IngestionService = class {
3723
3864
  last_accessed_at: null,
3724
3865
  access_count: 0,
3725
3866
  deleted_at: null,
3726
- okf_type: null,
3867
+ okf_type: normalized.okf_type,
3727
3868
  ...outcome?.trust
3728
3869
  };
3729
3870
  await this.entryRepo.upsert(wikiFact, tx);
3871
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
3730
3872
  insertedDescriptors.push({
3731
3873
  id,
3732
3874
  entity_id: entityId,
@@ -3736,6 +3878,27 @@ var IngestionService = class {
3736
3878
  });
3737
3879
  inserted++;
3738
3880
  }
3881
+ if (pendingEdges.length > 0) {
3882
+ for (const req of pendingEdges) {
3883
+ const resolveDrops = [];
3884
+ const resolved = this.ontologyService?.resolveEdges(
3885
+ entityId,
3886
+ req.sourceId,
3887
+ req.sourceType,
3888
+ req.edges,
3889
+ manifest,
3890
+ titleIndex,
3891
+ now,
3892
+ resolveDrops
3893
+ ) ?? [];
3894
+ for (const drop of resolveDrops) {
3895
+ diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef }));
3896
+ }
3897
+ for (const edge of resolved) {
3898
+ await this.edgeRepo.addIgnoreDuplicate(edge, tx);
3899
+ }
3900
+ }
3901
+ }
3739
3902
  return { inserted, skippedDuplicate, insertedDescriptors };
3740
3903
  }
3741
3904
  };
@@ -5964,7 +6127,16 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5964
6127
  await deps.db.withTransactionAsync(async (tx) => {
5965
6128
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
5966
6129
  if (mode === "emergent" && ontologyUpdates && deps.ontologyService) {
5967
- manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
6130
+ const { manifest: merged, rejected } = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
6131
+ manifest = merged;
6132
+ for (const reason of rejected) {
6133
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
6134
+ }
6135
+ } else if (mode === "strict" && ontologyUpdates) {
6136
+ const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
6137
+ for (let i = 0; i < proposalCount; i++) {
6138
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
6139
+ }
5968
6140
  }
5969
6141
  const titleIndex = /* @__PURE__ */ new Map();
5970
6142
  for (const existing of currentFactsRows) {
@@ -5999,6 +6171,17 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5999
6171
  const validationDrops = [];
6000
6172
  const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
6001
6173
  for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
6174
+ if (shouldEmitOntologyReceipt(mode)) {
6175
+ for (const receipt of nodeTypeReceipts(
6176
+ { entityId, operation: "librarian", trigger },
6177
+ id,
6178
+ ontologyFact.okf_type ?? "",
6179
+ normalized.okf_type,
6180
+ normalized.match
6181
+ )) {
6182
+ diagBuffer.push(receipt);
6183
+ }
6184
+ }
6002
6185
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
6003
6186
  if (grounding?.diagnostic) {
6004
6187
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -6532,7 +6715,16 @@ async function applyOps(deps, ctx, input) {
6532
6715
  await deps.db.withTransactionAsync(async (tx) => {
6533
6716
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
6534
6717
  if (mode === "emergent" && input.ontologyUpdates && deps.ontologyService) {
6535
- manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
6718
+ const { manifest: merged, rejected: rejected2 } = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
6719
+ manifest = merged;
6720
+ for (const reason of rejected2) {
6721
+ input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
6722
+ }
6723
+ } else if (mode === "strict" && input.ontologyUpdates) {
6724
+ const proposalCount = (Array.isArray(input.ontologyUpdates.node_types) ? input.ontologyUpdates.node_types.length : 0) + (Array.isArray(input.ontologyUpdates.edge_types) ? input.ontologyUpdates.edge_types.length : 0);
6725
+ for (let i = 0; i < proposalCount; i++) {
6726
+ input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
6727
+ }
6536
6728
  }
6537
6729
  const titleIndex = /* @__PURE__ */ new Map();
6538
6730
  for (const f of await deps.entryRepo.findRecentByEntityId(entityId, 100, tx)) {
@@ -6546,6 +6738,17 @@ async function applyOps(deps, ctx, input) {
6546
6738
  const id = generateId("fact_");
6547
6739
  const drops = [];
6548
6740
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
6741
+ if (shouldEmitOntologyReceipt(mode)) {
6742
+ for (const receipt of nodeTypeReceipts(
6743
+ { entityId, operation: "librarian", trigger },
6744
+ id,
6745
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
6746
+ normalized.okf_type,
6747
+ normalized.match
6748
+ )) {
6749
+ input.diagnostics.push(receipt);
6750
+ }
6751
+ }
6549
6752
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
6550
6753
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
6551
6754
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -8254,12 +8457,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
8254
8457
  if (!Number.isInteger(batchSize) || batchSize < 1) {
8255
8458
  throw new Error("Invalid batchSize: must be an integer >= 1");
8256
8459
  }
8460
+ if (options?.recheckCheckedBefore !== void 0 && (!Number.isInteger(options.recheckCheckedBefore) || options.recheckCheckedBefore < 0)) {
8461
+ throw new Error("Invalid recheckCheckedBefore: must be an integer >= 0");
8462
+ }
8257
8463
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
8258
8464
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
8259
8465
  }
8260
8466
  const trigger = options?.trigger ?? "call";
8261
8467
  const now = Date.now();
8262
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
8468
+ const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
8263
8469
  const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
8264
8470
  const ontologyService = this.ontologyService;
8265
8471
  if (!ontologyService) {
@@ -8303,7 +8509,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8303
8509
  promptOverride: options?.promptOverride,
8304
8510
  meter: options?.meter,
8305
8511
  trigger,
8306
- batchSize: escalated.length
8512
+ batchSize: escalated.length,
8513
+ recheckCutoff
8307
8514
  });
8308
8515
  return {
8309
8516
  scanned: classifierRun.result.scanned,
@@ -8323,7 +8530,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8323
8530
  return this._runGenerativeBackfill(entityId, candidates, {
8324
8531
  promptOverride: options?.promptOverride,
8325
8532
  meter: options?.meter,
8326
- trigger
8533
+ trigger,
8534
+ recheckCutoff
8327
8535
  });
8328
8536
  }
8329
8537
  /**
@@ -8353,7 +8561,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8353
8561
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
8354
8562
  const ontologyService = this.ontologyService;
8355
8563
  const now = Date.now();
8356
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
8564
+ const recheckCutoff = runOpts.recheckCutoff;
8357
8565
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
8358
8566
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
8359
8567
  const titleCatalog = buildTitleCatalogBlock(titleRows);
@@ -8605,7 +8813,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
8605
8813
  return;
8606
8814
  }
8607
8815
  if (txMode === "emergent" && ontologyUpdates) {
8608
- manifest = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
8816
+ const { manifest: merged, rejected } = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
8817
+ manifest = merged;
8818
+ for (const reason of rejected) {
8819
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
8820
+ }
8821
+ } else if (txMode === "strict" && ontologyUpdates) {
8822
+ const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
8823
+ for (let i = 0; i < proposalCount; i++) {
8824
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
8825
+ }
8609
8826
  }
8610
8827
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId, tx);
8611
8828
  const titleIndex = /* @__PURE__ */ new Map();
@@ -8639,6 +8856,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
8639
8856
  for (const drop of validationDrops) {
8640
8857
  diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: fact.id }));
8641
8858
  }
8859
+ for (const receipt of nodeTypeReceipts(
8860
+ { entityId, operation: "ontologyBackfill", trigger: "call" },
8861
+ fact.id,
8862
+ typeof classification.okf_type === "string" ? classification.okf_type : "",
8863
+ normalized.okf_type,
8864
+ normalized.match
8865
+ )) {
8866
+ diagBuffer.push(receipt);
8867
+ }
8642
8868
  if (!normalized.okf_type) {
8643
8869
  failedValidation++;
8644
8870
  continue;
@@ -11323,6 +11549,6 @@ var WriteService = class {
11323
11549
  }
11324
11550
  };
11325
11551
 
11326
- export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11327
- //# sourceMappingURL=chunk-6UTHJFXH.mjs.map
11328
- //# sourceMappingURL=chunk-6UTHJFXH.mjs.map
11552
+ export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11553
+ //# sourceMappingURL=chunk-EN37KODZ.mjs.map
11554
+ //# sourceMappingURL=chunk-EN37KODZ.mjs.map