@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.
package/dist/index.js CHANGED
@@ -63,7 +63,11 @@ var SEVERITY = {
63
63
  source_store_budget_exceeded: "warn",
64
64
  source_store_hash_mismatch: "warn",
65
65
  source_store_duplicate_hash: "warn",
66
- source_store_text_not_storable: "warn"
66
+ source_store_text_not_storable: "warn",
67
+ node_type_dropped: "warn",
68
+ node_type_folded: "info",
69
+ ontology_update_rejected: "warn",
70
+ ingest_zero_facts: "warn"
67
71
  };
68
72
  var MESSAGE = {
69
73
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -112,8 +116,48 @@ var MESSAGE = {
112
116
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
113
117
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
114
118
  source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
115
- source_store_text_not_storable: "A source document text could not be stored as given."
119
+ source_store_text_not_storable: "A source document text could not be stored as given.",
120
+ node_type_dropped: "A supplied node type missed the ontology manifest and the fact was stored untyped.",
121
+ node_type_folded: "A supplied node type was normalized into the manifest canonical slug.",
122
+ ontology_update_rejected: "An emergent ontology proposal was rejected during the merge.",
123
+ ingest_zero_facts: "A re-ingest tombstoned prior facts and edges and then wrote zero facts."
116
124
  };
125
+ function shouldEmitOntologyReceipt(mode) {
126
+ return mode !== "off";
127
+ }
128
+ function capReceiptSlug(slug) {
129
+ return typeof slug === "string" ? slug.slice(0, 64) : "";
130
+ }
131
+ function nodeTypeReceipts(base, factId, rawType, okfType, match) {
132
+ const out = [];
133
+ const supplied = typeof rawType === "string" ? rawType.trim() : "";
134
+ if (match && match.via === "normalize") {
135
+ const to = capReceiptSlug(match.canonical);
136
+ out.push({
137
+ ...base,
138
+ code: "node_type_folded",
139
+ detail: {
140
+ factId,
141
+ nodeType: to,
142
+ from: capReceiptSlug(match.raw),
143
+ to,
144
+ via: "normalize"
145
+ }
146
+ });
147
+ }
148
+ if (!okfType && supplied) {
149
+ out.push({
150
+ ...base,
151
+ code: "node_type_dropped",
152
+ detail: {
153
+ factId,
154
+ nodeType: capReceiptSlug(supplied),
155
+ reason: "not_in_manifest"
156
+ }
157
+ });
158
+ }
159
+ return out;
160
+ }
117
161
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
118
162
  function copyDetail(detail) {
119
163
  const copy = { ...detail };
@@ -3463,28 +3507,35 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3463
3507
  /**
3464
3508
  * Live untyped facts eligible for ontology backfill, oldest first.
3465
3509
  * Skips facts checked within the recheck cooldown (ontology_checked_at > recheckCutoff).
3510
+ * The queue sees CURRENT facts only (ontology-curation Task 10): rows whose
3511
+ * validity window excludes "now" are invisible to typing, matching the
3512
+ * read-time liveness definition (utils/temporal.ts).
3466
3513
  */
3467
3514
  async findUntypedByEntityId(entityId, limit, recheckCutoff, tx) {
3468
3515
  const executor = this.getExecutor(tx);
3516
+ const now = Date.now();
3469
3517
  const rows = await executor.getAllAsync(
3470
3518
  `SELECT * FROM ${this.prefix}entries
3471
3519
  WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL
3472
3520
  AND (ontology_checked_at IS NULL OR ontology_checked_at <= ?)
3521
+ AND ${liveAtSql("current")}
3473
3522
  ORDER BY updated_at ASC LIMIT ?`,
3474
- [entityId, recheckCutoff, limit]
3523
+ [entityId, recheckCutoff, now, now, limit]
3475
3524
  );
3476
3525
  return rows.map(mapRowToFact);
3477
3526
  }
3478
- /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). */
3527
+ /** Counts live untyped facts: eligible (past cooldown) vs deferred (in cooldown). Current facts only, as {@link findUntypedByEntityId}. */
3479
3528
  async countUntypedByEntityId(entityId, recheckCutoff, tx) {
3480
3529
  const executor = this.getExecutor(tx);
3530
+ const now = Date.now();
3481
3531
  const row = await executor.getFirstAsync(
3482
3532
  `SELECT
3483
3533
  SUM(CASE WHEN ontology_checked_at IS NULL OR ontology_checked_at <= ? THEN 1 ELSE 0 END) AS eligible,
3484
3534
  SUM(CASE WHEN ontology_checked_at IS NOT NULL AND ontology_checked_at > ? THEN 1 ELSE 0 END) AS deferred
3485
3535
  FROM ${this.prefix}entries
3486
- WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL`,
3487
- [recheckCutoff, recheckCutoff, entityId]
3536
+ WHERE entity_id = ? AND okf_type IS NULL AND deleted_at IS NULL
3537
+ AND ${liveAtSql("current")}`,
3538
+ [recheckCutoff, recheckCutoff, entityId, now, now]
3488
3539
  );
3489
3540
  return { eligible: Number(row?.eligible ?? 0), deferred: Number(row?.deferred ?? 0) };
3490
3541
  }
@@ -4517,20 +4568,40 @@ function emptyManifest() {
4517
4568
  function normalizeTitleKey(title) {
4518
4569
  return title.trim().toLowerCase().replace(/\s+/g, " ");
4519
4570
  }
4520
- function resolveNodeType(raw, manifest) {
4521
- const slug = raw.trim();
4571
+ function normalizeSlug(raw) {
4572
+ return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
4573
+ }
4574
+ function resolveNodeTypeMatch(raw, manifest) {
4575
+ const slug = typeof raw === "string" ? raw.trim() : "";
4522
4576
  if (!slug) return null;
4523
- const hit = manifest.node_types.find((n) => n.type.toLowerCase() === slug.toLowerCase());
4524
- return hit?.type ?? null;
4577
+ const lowered = slug.toLowerCase();
4578
+ const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
4579
+ if (exact) return { slug: exact.type, via: "exact" };
4580
+ const normalized = normalizeSlug(slug);
4581
+ if (!normalized) return null;
4582
+ const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
4583
+ return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
4584
+ }
4585
+ function resolveNodeType(raw, manifest) {
4586
+ return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
4525
4587
  }
4526
4588
  var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
4527
4589
  function isReservedAbstainSlug(raw) {
4528
4590
  return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
4529
4591
  }
4530
4592
  function resolveEdgeDefinitions(rawEdgeType, manifest) {
4531
- const slug = rawEdgeType.trim();
4593
+ const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
4532
4594
  if (!slug) return [];
4533
- return manifest.edge_types.filter((e) => e.type.toLowerCase() === slug.toLowerCase());
4595
+ const lowered = slug.toLowerCase();
4596
+ const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
4597
+ if (exact.length > 0) return exact;
4598
+ const normalized = normalizeSlug(slug);
4599
+ if (!normalized) return [];
4600
+ const names = new Set(
4601
+ manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
4602
+ );
4603
+ if (names.size !== 1) return [];
4604
+ return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
4534
4605
  }
4535
4606
  function edgeTripleKey(type, sourceType, targetType) {
4536
4607
  return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
@@ -4616,6 +4687,7 @@ function buildDeclaresParentIndex(nodes) {
4616
4687
  function mergeOntologyUpdates(current, updates) {
4617
4688
  const node_types = [...current.node_types];
4618
4689
  const edge_types = [...current.edge_types];
4690
+ const rejected = [];
4619
4691
  const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
4620
4692
  const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
4621
4693
  const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
@@ -4625,9 +4697,15 @@ function mergeOntologyUpdates(current, updates) {
4625
4697
  ]);
4626
4698
  for (const node of updates.node_types ?? []) {
4627
4699
  const type = node?.type?.trim();
4628
- if (!type) continue;
4700
+ if (!type) {
4701
+ rejected.push("invalid_shape");
4702
+ continue;
4703
+ }
4629
4704
  const key = type.toLowerCase();
4630
- if (nodeSlugs.has(key)) continue;
4705
+ if (nodeSlugs.has(key)) {
4706
+ rejected.push("duplicate_node_type");
4707
+ continue;
4708
+ }
4631
4709
  const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
4632
4710
  const parentSlug = rawParent.toLowerCase();
4633
4711
  const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
@@ -4642,11 +4720,20 @@ function mergeOntologyUpdates(current, updates) {
4642
4720
  const rawEdgeType = edge?.type?.trim();
4643
4721
  const sourceType = edge?.source_type?.trim();
4644
4722
  const targetType = edge?.target_type?.trim();
4645
- if (!rawEdgeType || !sourceType || !targetType) continue;
4723
+ if (!rawEdgeType || !sourceType || !targetType) {
4724
+ rejected.push("invalid_shape");
4725
+ continue;
4726
+ }
4646
4727
  const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
4647
4728
  const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
4648
- if (edgeKeys.has(edgeKey)) continue;
4649
- if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) continue;
4729
+ if (edgeKeys.has(edgeKey)) {
4730
+ rejected.push("duplicate_edge");
4731
+ continue;
4732
+ }
4733
+ if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
4734
+ rejected.push("unknown_endpoint");
4735
+ continue;
4736
+ }
4650
4737
  edgeNames.set(edgeType.toLowerCase(), edgeType);
4651
4738
  edge_types.push({
4652
4739
  type: edgeType,
@@ -4656,7 +4743,7 @@ function mergeOntologyUpdates(current, updates) {
4656
4743
  });
4657
4744
  edgeKeys.add(edgeKey);
4658
4745
  }
4659
- return { node_types, edge_types };
4746
+ return { manifest: { node_types, edge_types }, rejected };
4660
4747
  }
4661
4748
  function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
4662
4749
  const strict = opts?.strict === true;
@@ -4935,9 +5022,9 @@ var MetadataRepository = class extends BaseRepository {
4935
5022
  mode: "emergent",
4936
5023
  manifest: emptyManifest()
4937
5024
  };
4938
- const merged = mergeOntologyUpdates(current.manifest, updates);
5025
+ const { manifest: merged, rejected } = mergeOntologyUpdates(current.manifest, updates);
4939
5026
  await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
4940
- return merged;
5027
+ return { manifest: merged, rejected };
4941
5028
  }
4942
5029
  };
4943
5030
 
@@ -7459,7 +7546,8 @@ Return ONLY a valid JSON object matching this schema:
7459
7546
  {
7460
7547
  "facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
7461
7548
  }
7462
- 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.`;
7549
+ 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.
7550
+ 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.`;
7463
7551
  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.
7464
7552
  Return ONLY a valid JSON object matching this schema:
7465
7553
  {
@@ -7467,7 +7555,7 @@ Return ONLY a valid JSON object matching this schema:
7467
7555
  { "id": "string (input fact id, copied verbatim)", "okf_type": "string (manifest node type slug)", "edges": [{ "edge_type": "string", "target_title": "string" }] }
7468
7556
  ]
7469
7557
  }
7470
- If no manifest type fits a fact, omit that fact from "classifications" entirely \u2014 do not guess.
7558
+ 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).
7471
7559
  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.`;
7472
7560
  var TITLE_CATALOG_MAX_ENTRIES = 200;
7473
7561
  function buildTitleCatalogBlock(rows) {
@@ -8287,6 +8375,15 @@ var IngestionService = class {
8287
8375
  });
8288
8376
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
8289
8377
  insertedFacts.push(...fullResult.insertedFacts);
8378
+ if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
8379
+ diagBuffer.push({
8380
+ entityId,
8381
+ operation: "ingest",
8382
+ trigger: "call",
8383
+ code: "ingest_zero_facts",
8384
+ detail: { sourceRef, chunks: chunks2.length }
8385
+ });
8386
+ }
8290
8387
  } else {
8291
8388
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
8292
8389
  const flat = [];
@@ -8424,6 +8521,20 @@ var IngestionService = class {
8424
8521
  strict: strictEffective,
8425
8522
  entityId
8426
8523
  }) ?? { okf_type: null};
8524
+ if (shouldEmitOntologyReceipt(mode)) {
8525
+ for (const receipt of nodeTypeReceipts(
8526
+ { entityId, operation: opts?.diag?.operation ?? "upsertGraph", trigger: "call" },
8527
+ node.id,
8528
+ node.type ?? "",
8529
+ normalized.okf_type,
8530
+ normalized.match
8531
+ )) {
8532
+ opts?.diag?.buffer.push({
8533
+ ...receipt,
8534
+ detail: { ...receipt.detail, sourceRef: params.sourceRef }
8535
+ });
8536
+ }
8537
+ }
8427
8538
  const wikiFact = {
8428
8539
  id: node.id,
8429
8540
  entity_id: entityId,
@@ -8478,8 +8589,8 @@ var IngestionService = class {
8478
8589
  continue;
8479
8590
  }
8480
8591
  const sourceType = sourceIdToType.get(edge.sourceId);
8481
- const candidates = (manifest.edge_types ?? []).filter(
8482
- (d) => d.type.toLowerCase() === edge.type.toLowerCase() && typeSatisfies(d.source_type, sourceType ?? "", manifest)
8592
+ const candidates = resolveEdgeDefinitions(edge.type, manifest).filter(
8593
+ (d) => typeSatisfies(d.source_type, sourceType ?? "", manifest)
8483
8594
  );
8484
8595
  const match = candidates[0];
8485
8596
  if (!match) {
@@ -8558,9 +8669,18 @@ var IngestionService = class {
8558
8669
  const now = Date.now();
8559
8670
  for (const { facts, ontology_updates } of orderedChunkFacts) {
8560
8671
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
8561
- manifest = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
8672
+ const { manifest: merged, rejected } = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
8673
+ manifest = merged;
8674
+ for (const reason of rejected) {
8675
+ diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason } });
8676
+ }
8562
8677
  ontologyState = await this.ontologyService.getEffectiveState(entityId, tx);
8563
8678
  mode = ontologyState.mode;
8679
+ } else if (mode === "strict" && ontology_updates) {
8680
+ 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);
8681
+ for (let i = 0; i < proposalCount; i++) {
8682
+ diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
8683
+ }
8564
8684
  }
8565
8685
  for (const fact of facts) {
8566
8686
  const ontologyFact = fact;
@@ -8658,6 +8778,14 @@ var IngestionService = class {
8658
8778
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
8659
8779
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
8660
8780
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
8781
+ const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
8782
+ const { mode, manifest } = ontologyState;
8783
+ const titleIndex = /* @__PURE__ */ new Map();
8784
+ const indexedFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx);
8785
+ for (const f of indexedFacts) {
8786
+ titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
8787
+ }
8788
+ const pendingEdges = [];
8661
8789
  let inserted = 0;
8662
8790
  let skippedDuplicate = 0;
8663
8791
  const now = Date.now();
@@ -8682,6 +8810,26 @@ var IngestionService = class {
8682
8810
  detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
8683
8811
  });
8684
8812
  }
8813
+ const ontologyFact = fact;
8814
+ const validationDrops = [];
8815
+ const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
8816
+ for (const drop of validationDrops) {
8817
+ diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
8818
+ }
8819
+ if (shouldEmitOntologyReceipt(mode)) {
8820
+ for (const receipt of nodeTypeReceipts(
8821
+ { entityId, operation: "ingest", trigger: "call" },
8822
+ id,
8823
+ ontologyFact.okf_type ?? "",
8824
+ normalized.okf_type,
8825
+ normalized.match
8826
+ )) {
8827
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
8828
+ }
8829
+ }
8830
+ if (normalized.edges.length > 0) {
8831
+ pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
8832
+ }
8685
8833
  const wikiFact = {
8686
8834
  id,
8687
8835
  entity_id: entityId,
@@ -8700,10 +8848,11 @@ var IngestionService = class {
8700
8848
  last_accessed_at: null,
8701
8849
  access_count: 0,
8702
8850
  deleted_at: null,
8703
- okf_type: null,
8851
+ okf_type: normalized.okf_type,
8704
8852
  ...outcome?.trust
8705
8853
  };
8706
8854
  await this.entryRepo.upsert(wikiFact, tx);
8855
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
8707
8856
  insertedDescriptors.push({
8708
8857
  id,
8709
8858
  entity_id: entityId,
@@ -8713,6 +8862,27 @@ var IngestionService = class {
8713
8862
  });
8714
8863
  inserted++;
8715
8864
  }
8865
+ if (pendingEdges.length > 0) {
8866
+ for (const req of pendingEdges) {
8867
+ const resolveDrops = [];
8868
+ const resolved = this.ontologyService?.resolveEdges(
8869
+ entityId,
8870
+ req.sourceId,
8871
+ req.sourceType,
8872
+ req.edges,
8873
+ manifest,
8874
+ titleIndex,
8875
+ now,
8876
+ resolveDrops
8877
+ ) ?? [];
8878
+ for (const drop of resolveDrops) {
8879
+ diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef }));
8880
+ }
8881
+ for (const edge of resolved) {
8882
+ await this.edgeRepo.addIgnoreDuplicate(edge, tx);
8883
+ }
8884
+ }
8885
+ }
8716
8886
  return { inserted, skippedDuplicate, insertedDescriptors };
8717
8887
  }
8718
8888
  };
@@ -9755,7 +9925,16 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
9755
9925
  await deps.db.withTransactionAsync(async (tx) => {
9756
9926
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
9757
9927
  if (mode === "emergent" && ontologyUpdates && deps.ontologyService) {
9758
- manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
9928
+ const { manifest: merged, rejected } = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
9929
+ manifest = merged;
9930
+ for (const reason of rejected) {
9931
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
9932
+ }
9933
+ } else if (mode === "strict" && ontologyUpdates) {
9934
+ const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
9935
+ for (let i = 0; i < proposalCount; i++) {
9936
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
9937
+ }
9759
9938
  }
9760
9939
  const titleIndex = /* @__PURE__ */ new Map();
9761
9940
  for (const existing of currentFactsRows) {
@@ -9790,6 +9969,17 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
9790
9969
  const validationDrops = [];
9791
9970
  const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
9792
9971
  for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
9972
+ if (shouldEmitOntologyReceipt(mode)) {
9973
+ for (const receipt of nodeTypeReceipts(
9974
+ { entityId, operation: "librarian", trigger },
9975
+ id,
9976
+ ontologyFact.okf_type ?? "",
9977
+ normalized.okf_type,
9978
+ normalized.match
9979
+ )) {
9980
+ diagBuffer.push(receipt);
9981
+ }
9982
+ }
9793
9983
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
9794
9984
  if (grounding?.diagnostic) {
9795
9985
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -10323,7 +10513,16 @@ async function applyOps(deps, ctx, input) {
10323
10513
  await deps.db.withTransactionAsync(async (tx) => {
10324
10514
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
10325
10515
  if (mode === "emergent" && input.ontologyUpdates && deps.ontologyService) {
10326
- manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
10516
+ const { manifest: merged, rejected: rejected2 } = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
10517
+ manifest = merged;
10518
+ for (const reason of rejected2) {
10519
+ input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
10520
+ }
10521
+ } else if (mode === "strict" && input.ontologyUpdates) {
10522
+ 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);
10523
+ for (let i = 0; i < proposalCount; i++) {
10524
+ input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
10525
+ }
10327
10526
  }
10328
10527
  const titleIndex = /* @__PURE__ */ new Map();
10329
10528
  for (const f of await deps.entryRepo.findRecentByEntityId(entityId, 100, tx)) {
@@ -10337,6 +10536,17 @@ async function applyOps(deps, ctx, input) {
10337
10536
  const id = generateId("fact_");
10338
10537
  const drops = [];
10339
10538
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
10539
+ if (shouldEmitOntologyReceipt(mode)) {
10540
+ for (const receipt of nodeTypeReceipts(
10541
+ { entityId, operation: "librarian", trigger },
10542
+ id,
10543
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
10544
+ normalized.okf_type,
10545
+ normalized.match
10546
+ )) {
10547
+ input.diagnostics.push(receipt);
10548
+ }
10549
+ }
10340
10550
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
10341
10551
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
10342
10552
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -12045,12 +12255,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
12045
12255
  if (!Number.isInteger(batchSize) || batchSize < 1) {
12046
12256
  throw new Error("Invalid batchSize: must be an integer >= 1");
12047
12257
  }
12258
+ if (options?.recheckCheckedBefore !== void 0 && (!Number.isInteger(options.recheckCheckedBefore) || options.recheckCheckedBefore < 0)) {
12259
+ throw new Error("Invalid recheckCheckedBefore: must be an integer >= 0");
12260
+ }
12048
12261
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
12049
12262
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
12050
12263
  }
12051
12264
  const trigger = options?.trigger ?? "call";
12052
12265
  const now = Date.now();
12053
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
12266
+ const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
12054
12267
  const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
12055
12268
  const ontologyService = this.ontologyService;
12056
12269
  if (!ontologyService) {
@@ -12094,7 +12307,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12094
12307
  promptOverride: options?.promptOverride,
12095
12308
  meter: options?.meter,
12096
12309
  trigger,
12097
- batchSize: escalated.length
12310
+ batchSize: escalated.length,
12311
+ recheckCutoff
12098
12312
  });
12099
12313
  return {
12100
12314
  scanned: classifierRun.result.scanned,
@@ -12114,7 +12328,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12114
12328
  return this._runGenerativeBackfill(entityId, candidates, {
12115
12329
  promptOverride: options?.promptOverride,
12116
12330
  meter: options?.meter,
12117
- trigger
12331
+ trigger,
12332
+ recheckCutoff
12118
12333
  });
12119
12334
  }
12120
12335
  /**
@@ -12144,7 +12359,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12144
12359
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
12145
12360
  const ontologyService = this.ontologyService;
12146
12361
  const now = Date.now();
12147
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
12362
+ const recheckCutoff = runOpts.recheckCutoff;
12148
12363
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
12149
12364
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
12150
12365
  const titleCatalog = buildTitleCatalogBlock(titleRows);
@@ -12396,7 +12611,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
12396
12611
  return;
12397
12612
  }
12398
12613
  if (txMode === "emergent" && ontologyUpdates) {
12399
- manifest = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
12614
+ const { manifest: merged, rejected } = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
12615
+ manifest = merged;
12616
+ for (const reason of rejected) {
12617
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
12618
+ }
12619
+ } else if (txMode === "strict" && ontologyUpdates) {
12620
+ const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
12621
+ for (let i = 0; i < proposalCount; i++) {
12622
+ diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
12623
+ }
12400
12624
  }
12401
12625
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId, tx);
12402
12626
  const titleIndex = /* @__PURE__ */ new Map();
@@ -12430,6 +12654,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
12430
12654
  for (const drop of validationDrops) {
12431
12655
  diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: fact.id }));
12432
12656
  }
12657
+ for (const receipt of nodeTypeReceipts(
12658
+ { entityId, operation: "ontologyBackfill", trigger: "call" },
12659
+ fact.id,
12660
+ typeof classification.okf_type === "string" ? classification.okf_type : "",
12661
+ normalized.okf_type,
12662
+ normalized.match
12663
+ )) {
12664
+ diagBuffer.push(receipt);
12665
+ }
12433
12666
  if (!normalized.okf_type) {
12434
12667
  failedValidation++;
12435
12668
  continue;
@@ -15012,7 +15245,8 @@ var FACT_ONTOLOGY_FIELDS = `
15012
15245
  Each fact may optionally include:
15013
15246
  - "okf_type": string \u2014 must be one of the node_types in the manifest
15014
15247
  - "edges": [{ "edge_type": string, "target_title": string }] \u2014 target_title must match another fact's title in this response or existing memory
15015
- - An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.`;
15248
+ - An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.
15249
+ Each node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \`target_title\`.`;
15016
15250
  var EMERGENT_EXTRA = `
15017
15251
  You may also return "ontology_updates" to propose new types:
15018
15252
  "ontology_updates": {
@@ -15021,7 +15255,7 @@ You may also return "ontology_updates" to propose new types:
15021
15255
  }
15022
15256
  Only propose types not already in the manifest. Do not redefine existing types.`;
15023
15257
  function buildOntologyPromptAppendix(mode, manifestJson) {
15024
- const strictRules = mode === "strict" ? "STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit any node_type, omit okf_type and edges entirely." : "EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.";
15258
+ const strictRules = mode === "strict" ? "STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly." : "EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.";
15025
15259
  const fallback = "If okf_type or an edge is invalid, omit them rather than inventing unlisted types.";
15026
15260
  const ontologyModeInstructions = [
15027
15261
  "## Ontology constraints",
@@ -15084,15 +15318,15 @@ var OntologyService = class {
15084
15318
  }
15085
15319
  async mergeEmergentUpdates(entityId, updates, tx) {
15086
15320
  const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
15087
- const merged = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
15321
+ const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
15088
15322
  this.invalidateCache(entityId);
15089
- return merged;
15323
+ return { manifest: merged, rejected };
15090
15324
  }
15091
15325
  validateAndNormalizeFact(fact, manifest, opts) {
15092
15326
  const rawType = typeof fact.okf_type === "string" ? fact.okf_type : "";
15093
15327
  const strict = opts?.strict === true;
15094
- const canonical = resolveNodeType(rawType, manifest);
15095
- if (!canonical) {
15328
+ const match = resolveNodeTypeMatch(rawType, manifest);
15329
+ if (!match) {
15096
15330
  if (strict) throw new WikiStrictOntologyViolation(opts?.entityId ?? "", "node", rawType);
15097
15331
  if (opts?.drops && Array.isArray(fact.edges)) {
15098
15332
  for (const edge of fact.edges) {
@@ -15107,8 +15341,13 @@ var OntologyService = class {
15107
15341
  }
15108
15342
  return { okf_type: null, edges: [] };
15109
15343
  }
15344
+ const canonical = match.slug;
15110
15345
  const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);
15111
- return { okf_type: canonical, edges };
15346
+ return {
15347
+ okf_type: canonical,
15348
+ edges,
15349
+ match: { raw: rawType, canonical, via: match.via }
15350
+ };
15112
15351
  }
15113
15352
  /**
15114
15353
  * Pure resolver: given a source type, LLM-supplied edges, the manifest,
@@ -15288,6 +15527,16 @@ var LintRepository = class extends BaseRepository {
15288
15527
  [entityId, afterId, limit]
15289
15528
  );
15290
15529
  }
15530
+ /** Keyset page of TYPED facts in this entity (id + stored slug). Read-only. "Typed" here means the deletion-only scan the edge-violation query uses: soft-deleted and draft rows are out; validity windows are NOT consulted — the count mirrors `pageLiveEdgeViolations` exactly (spec §9, CodeRabbit #441). */
15531
+ async pageLiveTypedFacts(entityId, afterId, limit) {
15532
+ return this.db.getAllAsync(
15533
+ `SELECT id, okf_type FROM ${this.prefix}entries
15534
+ WHERE entity_id = ? AND id > ? AND deleted_at IS NULL
15535
+ AND lifecycle_status != 'draft' AND okf_type IS NOT NULL
15536
+ ORDER BY id ASC LIMIT ?`,
15537
+ [entityId, afterId, limit]
15538
+ );
15539
+ }
15291
15540
  };
15292
15541
 
15293
15542
  // src/services/LintService.ts
@@ -15327,11 +15576,29 @@ var LintService = class {
15327
15576
  after = page[page.length - 1].id;
15328
15577
  }
15329
15578
  }
15579
+ let nodeTypeViolations = 0;
15580
+ const nodeTypeViolationIds = [];
15581
+ const nodesConstrained = mode !== "off" && (manifest.node_types?.length ?? 0) > 0;
15582
+ if (nodesConstrained) {
15583
+ let after = "";
15584
+ for (; ; ) {
15585
+ const page = await this.lintRepo.pageLiveTypedFacts(entityId, after, LINT_PAGE_SIZE);
15586
+ for (const f of page) {
15587
+ if (resolveNodeType(f.okf_type, manifest) === null) {
15588
+ nodeTypeViolations++;
15589
+ if (nodeTypeViolationIds.length < LINT_SAMPLE_SIZE) nodeTypeViolationIds.push(f.id);
15590
+ }
15591
+ }
15592
+ if (page.length < LINT_PAGE_SIZE) break;
15593
+ after = page[page.length - 1].id;
15594
+ }
15595
+ }
15330
15596
  return {
15331
15597
  danglingEdges,
15332
15598
  manifestViolations,
15599
+ nodeTypeViolations,
15333
15600
  ...health,
15334
- sample: { danglingEdgeIds, manifestViolationEdgeIds }
15601
+ sample: { danglingEdgeIds, manifestViolationEdgeIds, nodeTypeViolationIds }
15335
15602
  };
15336
15603
  }
15337
15604
  };
@@ -15558,25 +15825,43 @@ function normalizeRememberInput(entityId, input, now) {
15558
15825
 
15559
15826
  // src/services/RememberService.ts
15560
15827
  var RememberService = class {
15561
- constructor(db, entryRepo, ontologyService, searchService, embeddingService) {
15828
+ constructor(db, entryRepo, ontologyService, searchService, embeddingService, options) {
15562
15829
  this.db = db;
15563
15830
  this.entryRepo = entryRepo;
15564
15831
  this.ontologyService = ontologyService;
15565
15832
  this.searchService = searchService;
15566
15833
  this.embeddingService = embeddingService;
15834
+ this.options = options;
15567
15835
  }
15568
15836
  async remember(entityId, input) {
15569
15837
  const now = Date.now();
15570
15838
  const { fact, validFrom, okfType } = normalizeRememberInput(entityId, input, now);
15571
15839
  let stored;
15840
+ const pendingReceipts = [];
15572
15841
  await this.db.withTransactionAsync(async (tx) => {
15573
15842
  if (okfType !== null) {
15574
15843
  const { mode, manifest } = await this.ontologyService.getEffectiveState(entityId, tx);
15575
- const factLike = { okf_type: okfType, edges: [] };
15576
- fact.okf_type = this.ontologyService.validateAndNormalizeFact(factLike, manifest, {
15577
- strict: mode === "strict",
15578
- entityId
15579
- }).okf_type;
15844
+ if (mode !== "off") {
15845
+ const factLike = { okf_type: okfType, edges: [] };
15846
+ const normalized = this.ontologyService.validateAndNormalizeFact(factLike, manifest, {
15847
+ strict: mode === "strict",
15848
+ entityId
15849
+ });
15850
+ fact.okf_type = normalized.okf_type;
15851
+ if (shouldEmitOntologyReceipt(mode)) {
15852
+ for (const receipt of nodeTypeReceipts(
15853
+ { entityId, operation: "remember", trigger: "call" },
15854
+ fact.id,
15855
+ okfType,
15856
+ normalized.okf_type,
15857
+ normalized.match
15858
+ )) {
15859
+ pendingReceipts.push(receipt);
15860
+ }
15861
+ }
15862
+ } else {
15863
+ fact.okf_type = okfType;
15864
+ }
15580
15865
  }
15581
15866
  await this.entryRepo.upsert(fact, tx);
15582
15867
  if (validFrom !== void 0) {
@@ -15588,6 +15873,9 @@ var RememberService = class {
15588
15873
  }
15589
15874
  stored = readBack;
15590
15875
  });
15876
+ for (const receipt of pendingReceipts) {
15877
+ emitDiagnostic(this.options ?? {}, receipt);
15878
+ }
15591
15879
  await this.searchService.syncEntries(entityId, [fact.id]);
15592
15880
  await this.embeddingService.embedFact(
15593
15881
  { id: fact.id, entity_id: entityId, title: fact.title, body: fact.body, tags: fact.tags },
@@ -15669,7 +15957,7 @@ var WikiMemory = class {
15669
15957
  new MiniSearchIndexStrategy()
15670
15958
  );
15671
15959
  this.temporalService = new TemporalService(this.db, this.options, this.entryRepo, this.searchService, this.embeddingService);
15672
- this.rememberService = new RememberService(this.db, this.entryRepo, this.ontologyService, this.searchService, this.embeddingService);
15960
+ this.rememberService = new RememberService(this.db, this.entryRepo, this.ontologyService, this.searchService, this.embeddingService, this.options);
15673
15961
  this.jobManager = new JobManager(this.prefix);
15674
15962
  this.promptService = new PromptService(options.config?.prompts, resolveGrounding(options.config?.grounding));
15675
15963
  this.ingestionService = new IngestionService(