@equationalapplications/core-llm-wiki 9.6.0 → 9.8.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) {
@@ -7889,6 +7977,74 @@ function toGroundingAnchor(anchor) {
7889
7977
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
7890
7978
  var DEFAULT_CHUNK_OVERLAP = 400;
7891
7979
 
7980
+ // src/utils/contextCaps.ts
7981
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7982
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
7983
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
7984
+
7985
+ // src/config/context.ts
7986
+ var DEFAULT_CHARS_PER_TOKEN = 4;
7987
+ var DEFAULT_SAFETY_FRACTION = 0.9;
7988
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7989
+ var OP_FLOOR = {
7990
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7991
+ heal: HEAL_MAX_PROMPT_CHARS,
7992
+ extract: OPS_MAX_EXTRACT_CHARS
7993
+ };
7994
+ function bad(key, value, why) {
7995
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
7996
+ }
7997
+ function resolveContextBudget(config) {
7998
+ const context = config?.context;
7999
+ if (!context || context.budget === void 0) {
8000
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
8001
+ }
8002
+ if (context.budget !== "legacy" && context.budget !== "declared") {
8003
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
8004
+ }
8005
+ if (context.budget === "legacy") {
8006
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
8007
+ }
8008
+ const window = context.contextWindowTokens;
8009
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
8010
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
8011
+ }
8012
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
8013
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
8014
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
8015
+ }
8016
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
8017
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
8018
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
8019
+ }
8020
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
8021
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
8022
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
8023
+ }
8024
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
8025
+ }
8026
+ function declaredPromptCap(budget, op) {
8027
+ const derived = Math.floor(
8028
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
8029
+ );
8030
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
8031
+ return Math.max(OP_FLOOR.heal, derived);
8032
+ }
8033
+ function resolveMaxPromptChars(budget, op) {
8034
+ if (budget.mode !== "declared") {
8035
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
8036
+ }
8037
+ if (op === "extract") {
8038
+ const resolveDerived = declaredPromptCap(budget, "resolve");
8039
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
8040
+ return Math.max(OP_FLOOR.extract, extractDerived);
8041
+ }
8042
+ return declaredPromptCap(budget, op);
8043
+ }
8044
+ function resolveDefaultChunkLength(budget) {
8045
+ return DEFAULT_MAX_CHUNK_LENGTH;
8046
+ }
8047
+
7892
8048
  // src/utils/usage.ts
7893
8049
  function estimateTokens(text) {
7894
8050
  return Math.ceil(text.length / 4);
@@ -8029,7 +8185,7 @@ var IngestionService = class {
8029
8185
  if (!sourceRef) throw new Error("Invalid sourceRef");
8030
8186
  const sourceHash = normalizeSourceHash(params.sourceHash);
8031
8187
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
8032
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
8188
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
8033
8189
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
8034
8190
  const chunkOverlap = Math.min(
8035
8191
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -8219,6 +8375,15 @@ var IngestionService = class {
8219
8375
  });
8220
8376
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
8221
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
+ }
8222
8387
  } else {
8223
8388
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
8224
8389
  const flat = [];
@@ -8356,6 +8521,20 @@ var IngestionService = class {
8356
8521
  strict: strictEffective,
8357
8522
  entityId
8358
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
+ }
8359
8538
  const wikiFact = {
8360
8539
  id: node.id,
8361
8540
  entity_id: entityId,
@@ -8410,8 +8589,8 @@ var IngestionService = class {
8410
8589
  continue;
8411
8590
  }
8412
8591
  const sourceType = sourceIdToType.get(edge.sourceId);
8413
- const candidates = (manifest.edge_types ?? []).filter(
8414
- (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)
8415
8594
  );
8416
8595
  const match = candidates[0];
8417
8596
  if (!match) {
@@ -8490,9 +8669,18 @@ var IngestionService = class {
8490
8669
  const now = Date.now();
8491
8670
  for (const { facts, ontology_updates } of orderedChunkFacts) {
8492
8671
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
8493
- 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
+ }
8494
8677
  ontologyState = await this.ontologyService.getEffectiveState(entityId, tx);
8495
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
+ }
8496
8684
  }
8497
8685
  for (const fact of facts) {
8498
8686
  const ontologyFact = fact;
@@ -8590,6 +8778,14 @@ var IngestionService = class {
8590
8778
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
8591
8779
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
8592
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 = [];
8593
8789
  let inserted = 0;
8594
8790
  let skippedDuplicate = 0;
8595
8791
  const now = Date.now();
@@ -8614,6 +8810,26 @@ var IngestionService = class {
8614
8810
  detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
8615
8811
  });
8616
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
+ }
8617
8833
  const wikiFact = {
8618
8834
  id,
8619
8835
  entity_id: entityId,
@@ -8632,10 +8848,11 @@ var IngestionService = class {
8632
8848
  last_accessed_at: null,
8633
8849
  access_count: 0,
8634
8850
  deleted_at: null,
8635
- okf_type: null,
8851
+ okf_type: normalized.okf_type,
8636
8852
  ...outcome?.trust
8637
8853
  };
8638
8854
  await this.entryRepo.upsert(wikiFact, tx);
8855
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
8639
8856
  insertedDescriptors.push({
8640
8857
  id,
8641
8858
  entity_id: entityId,
@@ -8645,6 +8862,27 @@ var IngestionService = class {
8645
8862
  });
8646
8863
  inserted++;
8647
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
+ }
8648
8886
  return { inserted, skippedDuplicate, insertedDescriptors };
8649
8887
  }
8650
8888
  };
@@ -8815,6 +9053,9 @@ function resolveLibrarianStrategy(config) {
8815
9053
  function resolveMaintenanceMode(config) {
8816
9054
  return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
8817
9055
  }
9056
+ function resolveContextBudgetOrThrow(config) {
9057
+ return resolveContextBudget(config);
9058
+ }
8818
9059
  function changedDefaultWarnings(config) {
8819
9060
  const warnings = [];
8820
9061
  const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
@@ -9684,7 +9925,16 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
9684
9925
  await deps.db.withTransactionAsync(async (tx) => {
9685
9926
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
9686
9927
  if (mode === "emergent" && ontologyUpdates && deps.ontologyService) {
9687
- 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
+ }
9688
9938
  }
9689
9939
  const titleIndex = /* @__PURE__ */ new Map();
9690
9940
  for (const existing of currentFactsRows) {
@@ -9719,6 +9969,17 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
9719
9969
  const validationDrops = [];
9720
9970
  const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
9721
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
+ }
9722
9983
  const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
9723
9984
  if (grounding?.diagnostic) {
9724
9985
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
@@ -9821,18 +10082,18 @@ function parseValidFrom(v) {
9821
10082
 
9822
10083
  // src/services/librarian/ops/extract.ts
9823
10084
  var OPS_MAX_EVENTS_PER_PASS = 50;
9824
- var OPS_MAX_EXTRACT_CHARS = 24e3;
9825
10085
  var RESOLVE_RESERVE_FACTOR = 2;
9826
10086
  var MIN_SEGMENT_CHARS = 500;
9827
10087
  var MAX_SEGMENT_CALLS = 8;
9828
10088
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
9829
- async function selectBatch(deps, entityId, wm, meter, guidance) {
10089
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
9830
10090
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
9831
10091
  if (events.length === 0) return { batch: [] };
10092
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
9832
10093
  let n = 0;
9833
10094
  let chars = 0;
9834
10095
  for (const e of events) {
9835
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
10096
+ if (n > 0 && chars + e.summary.length > extractCap) break;
9836
10097
  chars += e.summary.length;
9837
10098
  n++;
9838
10099
  }
@@ -10158,7 +10419,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
10158
10419
  }
10159
10420
 
10160
10421
  // src/services/librarian/ops/resolve.ts
10161
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
10162
10422
  function validateOp(raw, aliases) {
10163
10423
  if (!raw || typeof raw !== "object") return null;
10164
10424
  const r = raw;
@@ -10177,7 +10437,7 @@ function validateOp(raw, aliases) {
10177
10437
  return update;
10178
10438
  }
10179
10439
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
10180
- async function runResolve(deps, ctx, ambiguous) {
10440
+ async function runResolve(deps, ctx, ambiguous, budget) {
10181
10441
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
10182
10442
  if (ambiguous.length === 0) return out;
10183
10443
  const { entityId, trigger } = ctx;
@@ -10203,7 +10463,7 @@ async function runResolve(deps, ctx, ambiguous) {
10203
10463
  onSkip: (g, err) => {
10204
10464
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
10205
10465
  },
10206
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
10466
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
10207
10467
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
10208
10468
  });
10209
10469
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -10253,7 +10513,16 @@ async function applyOps(deps, ctx, input) {
10253
10513
  await deps.db.withTransactionAsync(async (tx) => {
10254
10514
  let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
10255
10515
  if (mode === "emergent" && input.ontologyUpdates && deps.ontologyService) {
10256
- 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
+ }
10257
10526
  }
10258
10527
  const titleIndex = /* @__PURE__ */ new Map();
10259
10528
  for (const f of await deps.entryRepo.findRecentByEntityId(entityId, 100, tx)) {
@@ -10267,6 +10536,17 @@ async function applyOps(deps, ctx, input) {
10267
10536
  const id = generateId("fact_");
10268
10537
  const drops = [];
10269
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
+ }
10270
10550
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
10271
10551
  const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
10272
10552
  const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
@@ -10412,7 +10692,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10412
10692
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
10413
10693
  await deps.seedWatermark(entityId);
10414
10694
  const wm = await deps.getWatermark(entityId);
10415
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
10695
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
10416
10696
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
10417
10697
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
10418
10698
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -10440,7 +10720,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10440
10720
  });
10441
10721
  }
10442
10722
  diagnostics.push(gateDiagnostic);
10443
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
10723
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
10444
10724
  for (const itemIndex of res.overflowSkipped) {
10445
10725
  diagnostics.push({
10446
10726
  entityId,
@@ -10509,7 +10789,6 @@ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
10509
10789
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10510
10790
  var CLASSIFIER_MAX_CHOICES = 255;
10511
10791
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
10512
- var HEAL_MAX_PROMPT_CHARS = 4e4;
10513
10792
  var HEAL_BATCH_SIZE = 25;
10514
10793
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10515
10794
  var MAX_EMBED_ATTEMPTS = 5;
@@ -11813,7 +12092,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11813
12092
  };
11814
12093
  },
11815
12094
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
11816
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
12095
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
11817
12096
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
11818
12097
  supportsEscalation: true,
11819
12098
  onSkip: (fact, err) => {
@@ -11976,12 +12255,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
11976
12255
  if (!Number.isInteger(batchSize) || batchSize < 1) {
11977
12256
  throw new Error("Invalid batchSize: must be an integer >= 1");
11978
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
+ }
11979
12261
  if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
11980
12262
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
11981
12263
  }
11982
12264
  const trigger = options?.trigger ?? "call";
11983
12265
  const now = Date.now();
11984
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
12266
+ const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
11985
12267
  const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
11986
12268
  const ontologyService = this.ontologyService;
11987
12269
  if (!ontologyService) {
@@ -12025,7 +12307,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12025
12307
  promptOverride: options?.promptOverride,
12026
12308
  meter: options?.meter,
12027
12309
  trigger,
12028
- batchSize: escalated.length
12310
+ batchSize: escalated.length,
12311
+ recheckCutoff
12029
12312
  });
12030
12313
  return {
12031
12314
  scanned: classifierRun.result.scanned,
@@ -12045,7 +12328,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12045
12328
  return this._runGenerativeBackfill(entityId, candidates, {
12046
12329
  promptOverride: options?.promptOverride,
12047
12330
  meter: options?.meter,
12048
- trigger
12331
+ trigger,
12332
+ recheckCutoff
12049
12333
  });
12050
12334
  }
12051
12335
  /**
@@ -12075,7 +12359,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12075
12359
  runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
12076
12360
  const ontologyService = this.ontologyService;
12077
12361
  const now = Date.now();
12078
- const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
12362
+ const recheckCutoff = runOpts.recheckCutoff;
12079
12363
  const ontologyContext = await ontologyService.buildPromptContext(entityId);
12080
12364
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
12081
12365
  const titleCatalog = buildTitleCatalogBlock(titleRows);
@@ -12327,7 +12611,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
12327
12611
  return;
12328
12612
  }
12329
12613
  if (txMode === "emergent" && ontologyUpdates) {
12330
- 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
+ }
12331
12624
  }
12332
12625
  const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId, tx);
12333
12626
  const titleIndex = /* @__PURE__ */ new Map();
@@ -12361,6 +12654,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
12361
12654
  for (const drop of validationDrops) {
12362
12655
  diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: fact.id }));
12363
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
+ }
12364
12666
  if (!normalized.okf_type) {
12365
12667
  failedValidation++;
12366
12668
  continue;
@@ -14943,7 +15245,8 @@ var FACT_ONTOLOGY_FIELDS = `
14943
15245
  Each fact may optionally include:
14944
15246
  - "okf_type": string \u2014 must be one of the node_types in the manifest
14945
15247
  - "edges": [{ "edge_type": string, "target_title": string }] \u2014 target_title must match another fact's title in this response or existing memory
14946
- - 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\`.`;
14947
15250
  var EMERGENT_EXTRA = `
14948
15251
  You may also return "ontology_updates" to propose new types:
14949
15252
  "ontology_updates": {
@@ -14952,7 +15255,7 @@ You may also return "ontology_updates" to propose new types:
14952
15255
  }
14953
15256
  Only propose types not already in the manifest. Do not redefine existing types.`;
14954
15257
  function buildOntologyPromptAppendix(mode, manifestJson) {
14955
- 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.";
14956
15259
  const fallback = "If okf_type or an edge is invalid, omit them rather than inventing unlisted types.";
14957
15260
  const ontologyModeInstructions = [
14958
15261
  "## Ontology constraints",
@@ -15015,15 +15318,15 @@ var OntologyService = class {
15015
15318
  }
15016
15319
  async mergeEmergentUpdates(entityId, updates, tx) {
15017
15320
  const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
15018
- const merged = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
15321
+ const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
15019
15322
  this.invalidateCache(entityId);
15020
- return merged;
15323
+ return { manifest: merged, rejected };
15021
15324
  }
15022
15325
  validateAndNormalizeFact(fact, manifest, opts) {
15023
15326
  const rawType = typeof fact.okf_type === "string" ? fact.okf_type : "";
15024
15327
  const strict = opts?.strict === true;
15025
- const canonical = resolveNodeType(rawType, manifest);
15026
- if (!canonical) {
15328
+ const match = resolveNodeTypeMatch(rawType, manifest);
15329
+ if (!match) {
15027
15330
  if (strict) throw new WikiStrictOntologyViolation(opts?.entityId ?? "", "node", rawType);
15028
15331
  if (opts?.drops && Array.isArray(fact.edges)) {
15029
15332
  for (const edge of fact.edges) {
@@ -15038,8 +15341,13 @@ var OntologyService = class {
15038
15341
  }
15039
15342
  return { okf_type: null, edges: [] };
15040
15343
  }
15344
+ const canonical = match.slug;
15041
15345
  const edges = validateInlineEdges(canonical, null, fact.edges ?? [], manifest, opts);
15042
- return { okf_type: canonical, edges };
15346
+ return {
15347
+ okf_type: canonical,
15348
+ edges,
15349
+ match: { raw: rawType, canonical, via: match.via }
15350
+ };
15043
15351
  }
15044
15352
  /**
15045
15353
  * Pure resolver: given a source type, LLM-supplied edges, the manifest,
@@ -15219,6 +15527,16 @@ var LintRepository = class extends BaseRepository {
15219
15527
  [entityId, afterId, limit]
15220
15528
  );
15221
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
+ }
15222
15540
  };
15223
15541
 
15224
15542
  // src/services/LintService.ts
@@ -15258,11 +15576,29 @@ var LintService = class {
15258
15576
  after = page[page.length - 1].id;
15259
15577
  }
15260
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
+ }
15261
15596
  return {
15262
15597
  danglingEdges,
15263
15598
  manifestViolations,
15599
+ nodeTypeViolations,
15264
15600
  ...health,
15265
- sample: { danglingEdgeIds, manifestViolationEdgeIds }
15601
+ sample: { danglingEdgeIds, manifestViolationEdgeIds, nodeTypeViolationIds }
15266
15602
  };
15267
15603
  }
15268
15604
  };
@@ -15489,25 +15825,43 @@ function normalizeRememberInput(entityId, input, now) {
15489
15825
 
15490
15826
  // src/services/RememberService.ts
15491
15827
  var RememberService = class {
15492
- constructor(db, entryRepo, ontologyService, searchService, embeddingService) {
15828
+ constructor(db, entryRepo, ontologyService, searchService, embeddingService, options) {
15493
15829
  this.db = db;
15494
15830
  this.entryRepo = entryRepo;
15495
15831
  this.ontologyService = ontologyService;
15496
15832
  this.searchService = searchService;
15497
15833
  this.embeddingService = embeddingService;
15834
+ this.options = options;
15498
15835
  }
15499
15836
  async remember(entityId, input) {
15500
15837
  const now = Date.now();
15501
15838
  const { fact, validFrom, okfType } = normalizeRememberInput(entityId, input, now);
15502
15839
  let stored;
15840
+ const pendingReceipts = [];
15503
15841
  await this.db.withTransactionAsync(async (tx) => {
15504
15842
  if (okfType !== null) {
15505
15843
  const { mode, manifest } = await this.ontologyService.getEffectiveState(entityId, tx);
15506
- const factLike = { okf_type: okfType, edges: [] };
15507
- fact.okf_type = this.ontologyService.validateAndNormalizeFact(factLike, manifest, {
15508
- strict: mode === "strict",
15509
- entityId
15510
- }).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
+ }
15511
15865
  }
15512
15866
  await this.entryRepo.upsert(fact, tx);
15513
15867
  if (validFrom !== void 0) {
@@ -15519,6 +15873,9 @@ var RememberService = class {
15519
15873
  }
15520
15874
  stored = readBack;
15521
15875
  });
15876
+ for (const receipt of pendingReceipts) {
15877
+ emitDiagnostic(this.options ?? {}, receipt);
15878
+ }
15522
15879
  await this.searchService.syncEntries(entityId, [fact.id]);
15523
15880
  await this.embeddingService.embedFact(
15524
15881
  { id: fact.id, entity_id: entityId, title: fact.title, body: fact.body, tags: fact.tags },
@@ -15570,6 +15927,7 @@ var WikiMemory = class {
15570
15927
  this.db = withSerializedTransactions(db);
15571
15928
  this.options = options;
15572
15929
  warnChangedDefaultsOnce(options.config);
15930
+ resolveContextBudgetOrThrow(options.config);
15573
15931
  this.prefix = options.config?.tablePrefix ?? "llm_wiki_";
15574
15932
  if (!TABLE_PREFIX_PATTERN.test(this.prefix)) {
15575
15933
  throw new Error(
@@ -15599,7 +15957,7 @@ var WikiMemory = class {
15599
15957
  new MiniSearchIndexStrategy()
15600
15958
  );
15601
15959
  this.temporalService = new TemporalService(this.db, this.options, this.entryRepo, this.searchService, this.embeddingService);
15602
- 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);
15603
15961
  this.jobManager = new JobManager(this.prefix);
15604
15962
  this.promptService = new PromptService(options.config?.prompts, resolveGrounding(options.config?.grounding));
15605
15963
  this.ingestionService = new IngestionService(
@@ -17686,6 +18044,11 @@ function parseOkfBundle(entityId, files, options) {
17686
18044
  };
17687
18045
  }
17688
18046
 
18047
+ // src/utils/contextBudget.ts
18048
+ function estimateTokensWith(budget, text) {
18049
+ return Math.ceil(text.length / budget.charsPerToken);
18050
+ }
18051
+
17689
18052
  // src/librarianPrompt.ts
17690
18053
  var DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = `You are a careful memory synthesis assistant.
17691
18054
  Use only the retrieved context when answering the request.
@@ -17773,6 +18136,7 @@ exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
17773
18136
  exports.chunkText = chunkText;
17774
18137
  exports.configureRandomSource = configureRandomSource;
17775
18138
  exports.createWiki = createWiki;
18139
+ exports.estimateTokensWith = estimateTokensWith;
17776
18140
  exports.formatContext = formatContext;
17777
18141
  exports.formatGraphContext = formatGraphContext;
17778
18142
  exports.formatMemoryDump = formatMemoryDump;
@@ -17783,6 +18147,9 @@ exports.isWikiSearchUnavailableError = isWikiSearchUnavailableError;
17783
18147
  exports.mapLibrarianOptionsToReadOptions = mapLibrarianOptionsToReadOptions;
17784
18148
  exports.parseEmbedding = parseEmbedding;
17785
18149
  exports.parseOkfBundle = parseOkfBundle;
18150
+ exports.resolveContextBudget = resolveContextBudget;
18151
+ exports.resolveDefaultChunkLength = resolveDefaultChunkLength;
18152
+ exports.resolveMaxPromptChars = resolveMaxPromptChars;
17786
18153
  exports.resolveOntologyJobDefaults = resolveOntologyJobDefaults;
17787
18154
  exports.resolveSystemOneTyping = resolveSystemOneTyping;
17788
18155
  exports.resolveTypingMinConfidence = resolveTypingMinConfidence;