omnius 1.0.954 → 1.0.956

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.
Files changed (45) hide show
  1. package/dist/_types/execution/native-file-write-observation.d.ts +19 -0
  2. package/dist/_types/execution/native-memory-view-provider.d.ts +84 -0
  3. package/dist/_types/execution/shell-runs.d.ts +4 -0
  4. package/dist/_types/execution/tool-output-spool.d.ts +61 -0
  5. package/dist/_types/execution/tools/file-write.d.ts +53 -0
  6. package/dist/_types/execution/types.d.ts +34 -0
  7. package/dist/_types/execution/work-mode-capability.d.ts +23 -0
  8. package/dist/_types/memory/candidateCoverage.d.ts +23 -0
  9. package/dist/_types/memory/embeddings.d.ts +1 -1
  10. package/dist/_types/memory/memoryCapability.d.ts +259 -0
  11. package/dist/_types/memory/memorySourceResolver.d.ts +133 -0
  12. package/dist/_types/memory/memoryTypes.d.ts +16 -0
  13. package/dist/_types/memory/structuredMemoryStore.d.ts +63 -6
  14. package/dist/_types/memory/unifiedMemoryStore.d.ts +12 -1
  15. package/dist/_types/orchestrator/agenticRunner.d.ts +241 -46
  16. package/dist/_types/orchestrator/authored-instruction-context.d.ts +59 -0
  17. package/dist/_types/orchestrator/authored-instruction-revisions.d.ts +56 -0
  18. package/dist/_types/orchestrator/authored-instruction-sources.d.ts +60 -0
  19. package/dist/_types/orchestrator/auxiliary-context-operation.d.ts +196 -0
  20. package/dist/_types/orchestrator/brokered-tool-composition.d.ts +141 -0
  21. package/dist/_types/orchestrator/completionReadiness.d.ts +2 -2
  22. package/dist/_types/orchestrator/confined-composition-worker.d.ts +45 -0
  23. package/dist/_types/orchestrator/contentAddressedArtifactStore.d.ts +173 -0
  24. package/dist/_types/orchestrator/contextWindowDump.d.ts +4 -0
  25. package/dist/_types/orchestrator/explicit-work-mode.d.ts +92 -0
  26. package/dist/_types/orchestrator/interruption-lifecycle.d.ts +3 -0
  27. package/dist/_types/orchestrator/memory-capability-context.d.ts +49 -0
  28. package/dist/_types/orchestrator/owned-inference-wait.d.ts +123 -0
  29. package/dist/_types/orchestrator/owned-model-wait.d.ts +26 -0
  30. package/dist/_types/orchestrator/provider-context-contract.d.ts +78 -0
  31. package/dist/_types/orchestrator/request-tool-capabilities.d.ts +52 -0
  32. package/dist/_types/orchestrator/structured-memory-extraction-worker.d.ts +20 -0
  33. package/dist/_types/orchestrator/structuredMemoryInference.d.ts +12 -0
  34. package/dist/_types/orchestrator/successful-procedure-memory.d.ts +35 -0
  35. package/dist/api/py-embed.js +70 -17
  36. package/dist/index.js +2 -2
  37. package/dist/library.js +115248 -107892
  38. package/dist/memory-maintenance-worker.js +486 -81
  39. package/dist/omni-setup-worker.js +83 -30
  40. package/dist/tui/native/worker.js +3 -1
  41. package/dist/update-worker-runtime.js +280 -126
  42. package/docs/DISCOVERY.json +63 -0
  43. package/docs/DISCOVERY.md +1 -0
  44. package/npm-shrinkwrap.json +2 -2
  45. package/package.json +1 -1
@@ -1,6 +1,83 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __omnius_createRequire } from "node:module"; import { fileURLToPath as __omnius_fileURLToPath } from "node:url"; import { dirname as __omnius_dirname } from "node:path"; const require = __omnius_createRequire(import.meta.url); const __filename = __omnius_fileURLToPath(import.meta.url); const __dirname = __omnius_dirname(__filename);
3
3
 
4
+ // packages/memory/dist/memoryCapability.js
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ var MEMORY_NAMESPACES = Object.freeze({
7
+ projectUnified: "project_unified_memory",
8
+ projectLegacy: "project_legacy_memory",
9
+ telegramChat: "telegram_chat",
10
+ task: "task_evidence",
11
+ structured: "structured_records",
12
+ folds: "context_folds",
13
+ procedures: "successful_procedures"
14
+ });
15
+ var MEMORY_CONTRACT_LIMITS = Object.freeze({
16
+ scopes: 64,
17
+ scopeIds: 256,
18
+ matches: 100,
19
+ branches: 16,
20
+ stages: 64,
21
+ sourceRefs: 512,
22
+ spans: 128,
23
+ parents: 128,
24
+ textChars: 65536,
25
+ fieldChars: 512,
26
+ routes: 32,
27
+ traceBytes: 262144
28
+ });
29
+ var MemoryContractError = class extends Error {
30
+ code;
31
+ constructor(code) {
32
+ super(`Memory contract: ${code}`);
33
+ this.code = code;
34
+ this.name = "MemoryContractError";
35
+ }
36
+ };
37
+ var record = (x) => !!x && typeof x === "object" && !Array.isArray(x);
38
+ function canonical(value, depth = 0) {
39
+ if (depth > 32)
40
+ throw new MemoryContractError("value_depth_exceeded");
41
+ if (value === null || typeof value === "string" || typeof value === "boolean")
42
+ return JSON.stringify(value);
43
+ if (typeof value === "number" && Number.isFinite(value))
44
+ return JSON.stringify(value);
45
+ if (Array.isArray(value))
46
+ return `[${value.map((v) => canonical(v, depth + 1)).join(",")}]`;
47
+ if (record(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null))
48
+ return `{${Object.keys(value).filter((k) => value[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k], depth + 1)}`).join(",")}}`;
49
+ throw new MemoryContractError("non_json_value");
50
+ }
51
+ var memoryContentHash = (value) => createHash("sha256").update(value).digest("hex");
52
+ var stableMemoryHash = (value) => memoryContentHash(canonical(value));
53
+ var UNBOUND = stableMemoryHash({ memoryBinding: "unavailable" });
54
+
55
+ // packages/memory/dist/candidateCoverage.js
56
+ function observeCandidates(observer, coverage) {
57
+ try {
58
+ observer?.(Object.freeze({ ...coverage }));
59
+ } catch {
60
+ }
61
+ }
62
+ function candidateLimit(value, fallback, maximum = 5e3) {
63
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.min(maximum, Math.floor(value))) : fallback;
64
+ }
65
+ function memoryCueTerms(query) {
66
+ return [...new Set(query.toLowerCase().match(/[\p{L}\p{N}_.$:/%\\-]+/gu) ?? [])].slice(0, 32);
67
+ }
68
+ function literalLike(text3) {
69
+ return `%${text3.replace(/[\\%_]/g, "\\$&")}%`;
70
+ }
71
+ function lexicalPredicate(fields, terms) {
72
+ const haystack = fields.map((field) => `COALESCE(${field}, '')`).join(" || ' ' || ");
73
+ const clauses = terms.map(() => `LOWER(${haystack}) LIKE ? ESCAPE '\\'`);
74
+ return {
75
+ sql: clauses.length ? `(${clauses.join(" OR ")})` : "0",
76
+ params: terms.map(literalLike),
77
+ scoreSql: clauses.length ? clauses.map((clause) => `CASE WHEN ${clause} THEN 1 ELSE 0 END`).join(" + ") : "0"
78
+ };
79
+ }
80
+
4
81
  // packages/memory/dist/db.js
5
82
  import { createRequire } from "node:module";
6
83
  var _Database = null;
@@ -23,6 +100,12 @@ function initDb(dbPath) {
23
100
  runMigrations(db);
24
101
  return db;
25
102
  }
103
+ function openReadOnlyDb(dbPath) {
104
+ const Database = getDatabase();
105
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
106
+ db.pragma("query_only = ON");
107
+ return db;
108
+ }
26
109
  function runMigrations(db) {
27
110
  db.exec(`
28
111
  -- repo_profiles: one row per repository root.
@@ -3589,9 +3672,9 @@ var EMPTY_WORKING_SET = Object.freeze({
3589
3672
 
3590
3673
  // packages/memory/dist/episodeStore.js
3591
3674
  import { join } from "node:path";
3592
- import { mkdirSync, existsSync } from "node:fs";
3593
- import { randomUUID } from "node:crypto";
3594
- import { createHash } from "node:crypto";
3675
+ import { mkdirSync, existsSync, realpathSync } from "node:fs";
3676
+ import { randomUUID as randomUUID2 } from "node:crypto";
3677
+ import { createHash as createHash2 } from "node:crypto";
3595
3678
 
3596
3679
  // packages/memory/dist/zettelkasten.js
3597
3680
  var DEFAULT_CONFIG = {
@@ -3979,9 +4062,14 @@ function extractQueryEntities(query) {
3979
4062
  }
3980
4063
  function personalizedPageRankSnapshot(graph, seedNodeIds, config) {
3981
4064
  const cfg = { ...DEFAULT_CONFIG2, ...config };
4065
+ const viewNow = Date.now();
4066
+ cfg.validAt ??= viewNow;
4067
+ cfg.recordedAsOf ??= viewNow;
4068
+ cfg.topK = candidateLimit(cfg.topK, 10, 500);
4069
+ cfg.maxIterations = candidateLimit(cfg.maxIterations, 50, 1e3);
3982
4070
  const scores = /* @__PURE__ */ new Map();
3983
4071
  const adjacency = /* @__PURE__ */ new Map();
3984
- const empty = { scores, adjacency, assertTime: () => {
4072
+ const empty = { scores, adjacency, seedNodes: [], iterations: 0, assertTime: () => {
3985
4073
  } };
3986
4074
  if (seedNodeIds.length === 0)
3987
4075
  return empty;
@@ -4006,14 +4094,27 @@ function personalizedPageRankSnapshot(graph, seedNodeIds, config) {
4006
4094
  if (adjacency.size >= maxNodes)
4007
4095
  throw new PPRTraversalBudgetError("nodes", maxNodes);
4008
4096
  const remaining = maxEdges - edgeRows;
4009
- const edges = graph.currentEdges(nodeId, remaining + 1);
4097
+ const rows = graph.currentEdges(nodeId, remaining + 1, { validAt: cfg.validAt, recordedAsOf: cfg.recordedAsOf });
4098
+ const edges = cfg.edgeFilter ? rows.filter(cfg.edgeFilter) : rows;
4010
4099
  assertTime();
4011
- if (edges.length > remaining)
4100
+ if (rows.length > remaining)
4012
4101
  throw new PPRTraversalBudgetError("edges", maxEdges);
4013
- edgeRows += edges.length;
4102
+ edgeRows += rows.length;
4014
4103
  adjacency.set(nodeId, edges);
4015
4104
  return edges;
4016
4105
  };
4106
+ const proposedSeeds = [...new Set(seedNodeIds)];
4107
+ seedNodeIds = cfg.edgeFilter ? proposedSeeds.filter((id2) => edgesFor(id2).length > 0) : seedNodeIds;
4108
+ observeCandidates(cfg.onCandidateCoverage, {
4109
+ route: "ppr_seeds",
4110
+ population: proposedSeeds.length,
4111
+ examined: proposedSeeds.length,
4112
+ selected: seedNodeIds.length,
4113
+ limit: maxNodes,
4114
+ complete: true
4115
+ });
4116
+ if (!seedNodeIds.length)
4117
+ return { scores, adjacency, seedNodes: [], iterations: 0, assertTime };
4017
4118
  const teleportProb = 1 / seedNodeIds.length;
4018
4119
  const seedSet = new Set(seedNodeIds);
4019
4120
  const allNodes = /* @__PURE__ */ new Set();
@@ -4023,15 +4124,20 @@ function personalizedPageRankSnapshot(graph, seedNodeIds, config) {
4023
4124
  throw new PPRTraversalBudgetError("nodes", maxNodes);
4024
4125
  allNodes.add(nodeId);
4025
4126
  };
4026
- for (const seedId of seedNodeIds) {
4127
+ const maxHops = candidateLimit(cfg.maxHops, 2, 4);
4128
+ const queue = seedNodeIds.map((id2) => ({ id: id2, hop: 0 }));
4129
+ for (const seedId of seedNodeIds)
4027
4130
  addNode(seedId);
4028
- for (const edge of edgesFor(seedId)) {
4029
- const neighborId = edge.srcId === seedId ? edge.dstId : edge.srcId;
4030
- addNode(neighborId);
4031
- if (!expandedNeighbors.has(neighborId)) {
4032
- expandedNeighbors.add(neighborId);
4033
- for (const hop2 of edgesFor(neighborId))
4034
- addNode(hop2.srcId === neighborId ? hop2.dstId : hop2.srcId);
4131
+ for (let cursor = 0; cursor < queue.length; cursor++) {
4132
+ const { id: id2, hop } = queue[cursor];
4133
+ if (hop >= maxHops || expandedNeighbors.has(id2))
4134
+ continue;
4135
+ expandedNeighbors.add(id2);
4136
+ for (const edge of edgesFor(id2)) {
4137
+ const neighbor = edge.srcId === id2 ? edge.dstId : edge.srcId;
4138
+ if (!allNodes.has(neighbor)) {
4139
+ addNode(neighbor);
4140
+ queue.push({ id: neighbor, hop: hop + 1 });
4035
4141
  }
4036
4142
  }
4037
4143
  }
@@ -4066,45 +4172,66 @@ function personalizedPageRankSnapshot(graph, seedNodeIds, config) {
4066
4172
  for (const [id2, score] of newScores)
4067
4173
  scores.set(id2, score);
4068
4174
  if (maxDelta < cfg.convergenceThreshold) {
4069
- return { scores, adjacency, assertTime };
4175
+ return { scores, adjacency, seedNodes: seedNodeIds, iterations: iter + 1, assertTime };
4070
4176
  }
4071
4177
  }
4072
- return { scores, adjacency, assertTime };
4178
+ return { scores, adjacency, seedNodes: seedNodeIds, iterations: cfg.maxIterations, assertTime };
4073
4179
  }
4074
4180
  function retrieveByPPR(query, graph, episodeStore, config) {
4075
4181
  const cfg = { ...DEFAULT_CONFIG2, ...config };
4182
+ const viewNow = Date.now();
4183
+ cfg.validAt ??= viewNow;
4184
+ cfg.recordedAsOf ??= viewNow;
4185
+ cfg.topK = candidateLimit(cfg.topK, 10, 500);
4186
+ cfg.maxIterations = candidateLimit(cfg.maxIterations, 50, 1e3);
4187
+ const sources = /* @__PURE__ */ new Map();
4188
+ const sourceFor = (id2) => {
4189
+ if (!sources.has(id2)) {
4190
+ const episode = episodeStore.get(id2);
4191
+ sources.set(id2, episode && episode.timestamp <= cfg.recordedAsOf && (!cfg.episodeFilter || cfg.episodeFilter(episode)) ? episode : null);
4192
+ }
4193
+ return sources.get(id2) ?? null;
4194
+ };
4195
+ const sourceTokens = /* @__PURE__ */ new Set();
4196
+ let tokens = 0;
4197
+ const sourceLimit = typeof cfg.maxSourceTokens === "number" && Number.isFinite(cfg.maxSourceTokens) && cfg.maxSourceTokens > 0 ? cfg.maxSourceTokens : 64e3;
4198
+ const edgeFilter = (edge) => {
4199
+ if (!edge.sourceEpisodeId || !sourceFor(edge.sourceEpisodeId) || cfg.edgeFilter && !cfg.edgeFilter(edge))
4200
+ return false;
4201
+ if (!sourceTokens.has(edge.sourceEpisodeId)) {
4202
+ tokens += Buffer.byteLength(sourceFor(edge.sourceEpisodeId).content, "utf8") + 64;
4203
+ sourceTokens.add(edge.sourceEpisodeId);
4204
+ if (tokens > sourceLimit)
4205
+ throw new PPRTraversalBudgetError("tokens", sourceLimit);
4206
+ }
4207
+ return true;
4208
+ };
4076
4209
  const queryEntities = extractQueryEntities(query);
4077
4210
  if (queryEntities.length === 0) {
4078
4211
  return { episodes: [], queryEntities: [], seedNodes: [], iterations: 0 };
4079
4212
  }
4080
4213
  const seedNodes = [];
4214
+ const seedLimit = candidateLimit(cfg.maxNodes, 1024, 4096);
4215
+ const seedDeadline = performance.now() + (cfg.maxDurationMs ?? DEFAULT_CONFIG2.maxDurationMs);
4081
4216
  for (const entity of queryEntities) {
4082
- const seedsBefore = seedNodes.length;
4083
- const node = graph.findNode(entity);
4084
- if (node) {
4085
- seedNodes.push(node.id);
4086
- }
4087
- const symbolNodes = graph.findSymbolNodesByName(entity, 10);
4088
- for (const s of symbolNodes)
4089
- seedNodes.push(s.id);
4090
- if (seedNodes.length > seedsBefore)
4091
- continue;
4092
- for (const nodeType of ["file", "error", "tool", "entity", "event", "concept", "person"]) {
4093
- const candidates = graph.nodesByType(nodeType, 50);
4094
- for (const candidate of candidates) {
4095
- if (candidate.text.toLowerCase().includes(entity.toLowerCase()) || entity.toLowerCase().includes(candidate.text.toLowerCase())) {
4096
- seedNodes.push(candidate.id);
4097
- break;
4098
- }
4099
- }
4100
- if (seedNodes.length > seedsBefore)
4101
- break;
4102
- }
4217
+ if (performance.now() >= seedDeadline)
4218
+ throw new PPRTraversalBudgetError("time", cfg.maxDurationMs ?? DEFAULT_CONFIG2.maxDurationMs);
4219
+ const candidates = graph.findNodesByCue(entity, seedLimit + 1);
4220
+ if (candidates.length > seedLimit)
4221
+ throw new PPRTraversalBudgetError("nodes", seedLimit);
4222
+ for (const node of candidates)
4223
+ if (!seedNodes.includes(node.id))
4224
+ seedNodes.push(node.id);
4225
+ if (seedNodes.length > seedLimit)
4226
+ throw new PPRTraversalBudgetError("nodes", seedLimit);
4103
4227
  }
4104
4228
  if (seedNodes.length === 0) {
4105
4229
  return { episodes: [], queryEntities, seedNodes: [], iterations: 0 };
4106
4230
  }
4107
- const snapshot = personalizedPageRankSnapshot(graph, seedNodes, cfg);
4231
+ const remainingMs = seedDeadline - performance.now();
4232
+ if (remainingMs <= 0)
4233
+ throw new PPRTraversalBudgetError("time", cfg.maxDurationMs ?? DEFAULT_CONFIG2.maxDurationMs);
4234
+ const snapshot = personalizedPageRankSnapshot(graph, [...new Set(seedNodes)], { ...cfg, maxDurationMs: remainingMs, edgeFilter });
4108
4235
  const pprScores = snapshot.scores;
4109
4236
  const episodeScores = /* @__PURE__ */ new Map();
4110
4237
  for (const [nodeId, score] of pprScores) {
@@ -4116,18 +4243,21 @@ function retrieveByPPR(query, graph, episodeStore, config) {
4116
4243
  continue;
4117
4244
  const edges = snapshot.adjacency.get(nodeId);
4118
4245
  for (const edge of edges) {
4246
+ if (!pprScores.has(edge.srcId) || !pprScores.has(edge.dstId))
4247
+ continue;
4119
4248
  if (edge.sourceEpisodeId) {
4120
4249
  const existing = episodeScores.get(edge.sourceEpisodeId);
4121
4250
  if (existing) {
4251
+ existing.supports.set(edge.id, edge);
4122
4252
  existing.score += score;
4123
4253
  existing.matchedNodes.push(node.text);
4124
4254
  } else {
4125
- episodeScores.set(edge.sourceEpisodeId, { score, matchedNodes: [node.text] });
4255
+ episodeScores.set(edge.sourceEpisodeId, { score, matchedNodes: [node.text], supports: /* @__PURE__ */ new Map([[edge.id, edge]]) });
4126
4256
  }
4127
4257
  }
4128
4258
  }
4129
4259
  }
4130
- let entries = [...episodeScores.entries()];
4260
+ let entries = [...episodeScores.entries()].filter(([id2]) => sourceFor(id2));
4131
4261
  const engagementWeight = cfg.engagementWeight ?? 0;
4132
4262
  if (cfg.currentEmotionalState || cfg.influenceFor || engagementWeight !== 0) {
4133
4263
  const current = cfg.currentEmotionalState;
@@ -4157,18 +4287,32 @@ function retrieveByPPR(query, graph, episodeStore, config) {
4157
4287
  }
4158
4288
  const ranked = entries.sort((a, b) => b[1].score - a[1].score).slice(0, cfg.topK);
4159
4289
  const episodes = [];
4160
- for (const [epId, { score, matchedNodes }] of ranked) {
4290
+ for (const [epId, { score, matchedNodes, supports }] of ranked) {
4161
4291
  snapshot.assertTime();
4162
- const episode = episodeStore.get(epId);
4292
+ const episode = sourceFor(epId);
4163
4293
  if (episode) {
4164
- episodes.push({ episode, pprScore: score, matchedNodes: [...new Set(matchedNodes)] });
4294
+ episodes.push({
4295
+ episode,
4296
+ pprScore: score,
4297
+ matchedNodes: [...new Set(matchedNodes)],
4298
+ supports: [...supports.values()].map(({ id: id2, sourceEpisodeId, relation, srcId, dstId, validFrom, recordedAt }) => ({ id: id2, sourceEpisodeId, relation, srcId, dstId, validFrom, recordedAt }))
4299
+ });
4165
4300
  }
4166
4301
  }
4302
+ observeCandidates(cfg.onCandidateCoverage, {
4303
+ route: "ppr_source_materialization",
4304
+ population: entries.length,
4305
+ examined: entries.length,
4306
+ selected: episodes.length,
4307
+ limit: cfg.topK,
4308
+ complete: entries.length <= cfg.topK,
4309
+ reasonCode: entries.length > cfg.topK ? "rank_limit" : void 0
4310
+ });
4167
4311
  return {
4168
4312
  episodes,
4169
4313
  queryEntities,
4170
- seedNodes,
4171
- iterations: cfg.maxIterations
4314
+ seedNodes: snapshot.seedNodes,
4315
+ iterations: snapshot.iterations
4172
4316
  };
4173
4317
  }
4174
4318
 
@@ -4217,8 +4361,10 @@ function stableJson(value) {
4217
4361
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(",")}}`;
4218
4362
  }
4219
4363
  function episodeIdentityHash(ep) {
4220
- const identity = ep.metadata ? `${ep.content}\0metadata:${stableJson(ep.metadata)}` : ep.content;
4221
- return createHash("sha256").update(identity).digest("hex").slice(0, 16);
4364
+ let identity = ep.metadata ? `${ep.content}\0metadata:${stableJson(ep.metadata)}` : ep.content;
4365
+ if (ep.taskId || ep.sourceEpisodeId || ep.occurrenceId)
4366
+ identity += `\0occurrence:${stableJson([ep.taskId ?? null, ep.sourceEpisodeId ?? null, ep.occurrenceId ?? null])}`;
4367
+ return createHash2("sha256").update(identity).digest("hex").slice(0, 16);
4222
4368
  }
4223
4369
  var DECAY_TAU = {
4224
4370
  session: 36e5,
@@ -4299,6 +4445,78 @@ var EpisodeStore = class {
4299
4445
  }
4300
4446
  /** WO-AM-05: Optional TemporalGraph for Zettelkasten auto-linking */
4301
4447
  graph = null;
4448
+ graphSourceStoreRef = "";
4449
+ unregisterGraphSource;
4450
+ maxSourceBytes = 64 * 1024 * 1024;
4451
+ getGraphSourceStoreRef() {
4452
+ return this.graphSourceStoreRef;
4453
+ }
4454
+ readGraphSource(id2) {
4455
+ return this.db.transaction(() => {
4456
+ const source = this.captureGraphSource(id2, /* @__PURE__ */ new Set(), { remaining: this.maxSourceBytes });
4457
+ if (!source)
4458
+ return null;
4459
+ const episode = this.get(id2);
4460
+ return episode ? { episode, source } : null;
4461
+ })();
4462
+ }
4463
+ captureGraphSource(id2, seen = /* @__PURE__ */ new Set(), budget = { remaining: this.maxSourceBytes }) {
4464
+ if (seen.has(id2) || seen.size >= 32)
4465
+ return null;
4466
+ seen.add(id2);
4467
+ const length = this.db.prepare("SELECT length(CAST(content AS BLOB))+length(CAST(COALESCE(metadata,'') AS BLOB)) AS bytes FROM episodes WHERE id=?").get(id2);
4468
+ if (!length || length.bytes > budget.remaining)
4469
+ return null;
4470
+ budget.remaining -= length.bytes;
4471
+ const episode = this.get(id2);
4472
+ if (!episode)
4473
+ return null;
4474
+ const scope = {
4475
+ sessionId: episode.sessionId,
4476
+ sourceSurface: typeof episode.metadata?.sourceSurface === "string" ? episode.metadata.sourceSurface : null,
4477
+ declaredScopeId: typeof episode.metadata?.scopeId === "string" ? episode.metadata.scopeId : null
4478
+ };
4479
+ let roots = [], complete = true, ancestors;
4480
+ const derived = episode.modality === "reflection" || episode.modality === "gist";
4481
+ const observation = ["tool_call", "tool_result", "visual", "audio", "code", "social", "spatial", "text"].includes(episode.modality);
4482
+ if (episode.sourceEpisodeId) {
4483
+ const parent = this.captureGraphSource(episode.sourceEpisodeId, seen, budget);
4484
+ if (!parent || stableJson(parent.scope) !== stableJson(scope))
4485
+ return null;
4486
+ roots = parent.rootSourceIds;
4487
+ complete = parent.lineageComplete;
4488
+ ancestors = parent;
4489
+ } else if (!observation)
4490
+ complete = false;
4491
+ else
4492
+ roots = [createHash2("sha256").update(stableJson([this.graphSourceStoreRef, scope, episode.id])).digest("hex")];
4493
+ const ownVersion = createHash2("sha256").update(stableJson({
4494
+ id: episode.id,
4495
+ timestamp: episode.timestamp,
4496
+ sessionId: episode.sessionId,
4497
+ taskId: episode.taskId,
4498
+ turnNumber: episode.turnNumber,
4499
+ modality: episode.modality,
4500
+ toolName: episode.toolName,
4501
+ content: episode.content,
4502
+ metadata: episode.metadata,
4503
+ sourceEpisodeId: episode.sourceEpisodeId
4504
+ })).digest("hex");
4505
+ const sourceVersions = [{ sourceId: episode.id, version: ownVersion }, ...ancestors?.sourceVersions ?? []];
4506
+ const version = createHash2("sha256").update(stableJson(sourceVersions)).digest("hex");
4507
+ return {
4508
+ storeRef: this.graphSourceStoreRef,
4509
+ sourceId: episode.id,
4510
+ version,
4511
+ scope,
4512
+ sourceIds: sourceVersions.map((entry) => entry.sourceId),
4513
+ sourceVersions,
4514
+ sourceKind: derived ? "derived_claim" : observation ? "observation" : "unclassified_record",
4515
+ rootSourceIds: roots,
4516
+ lineageComplete: complete,
4517
+ observedAt: episode.timestamp
4518
+ };
4519
+ }
4302
4520
  /** WO-AM-05: Zettelkasten config for neighbor linking */
4303
4521
  zettelConfig = { topK: 5, minSimilarity: 0.7, evolutionThreshold: 0.6, maxLinksPerEpisode: 10 };
4304
4522
  /** AUDIT-3 (A2 completion): minimum importance an inserted episode must
@@ -4333,7 +4551,14 @@ var EpisodeStore = class {
4333
4551
  return null;
4334
4552
  }
4335
4553
  }
4336
- constructor(dbPath, graph, zettelConfig) {
4554
+ constructor(dbPath, graph, zettelConfig, options = {}) {
4555
+ this.maxSourceBytes = options.maxSourceBytes ?? 64 * 1024 * 1024;
4556
+ if (options.readOnly) {
4557
+ this.db = openReadOnlyDb(dbPath);
4558
+ this.graph = graph ?? null;
4559
+ this.attachGraphSource();
4560
+ return;
4561
+ }
4337
4562
  const dir = dbPath === ":memory:" ? null : join(dbPath, "..");
4338
4563
  if (dir && !existsSync(dir))
4339
4564
  mkdirSync(dir, { recursive: true });
@@ -4390,10 +4615,17 @@ var EpisodeStore = class {
4390
4615
  }
4391
4616
  this.db.pragma("journal_mode = WAL");
4392
4617
  this.db.pragma("synchronous = NORMAL");
4618
+ this.attachGraphSource();
4619
+ }
4620
+ attachGraphSource() {
4621
+ const filename = this.db.prepare("PRAGMA database_list").all().find((row) => row.name === "main")?.file;
4622
+ this.graphSourceStoreRef = createHash2("sha256").update(filename ? `episode-sqlite:${realpathSync(filename)}` : `episode-connection:${randomUUID2()}`).digest("hex");
4623
+ if (this.graph)
4624
+ this.unregisterGraphSource = this.graph.registerSourceStore(this.graphSourceStoreRef, (id2) => this.readGraphSource(id2)?.source ?? null);
4393
4625
  }
4394
4626
  /** Insert a new episode. Returns the episode ID. */
4395
4627
  insert(ep) {
4396
- const id2 = randomUUID();
4628
+ const id2 = randomUUID2();
4397
4629
  const now = Date.now();
4398
4630
  const contentHash = episodeIdentityHash(ep);
4399
4631
  const modality = ep.modality ?? "text";
@@ -4412,9 +4644,9 @@ var EpisodeStore = class {
4412
4644
  if (existing)
4413
4645
  return existing.id;
4414
4646
  this.db.prepare(`
4415
- INSERT INTO episodes (id, timestamp, session_id, task_id, turn_number, modality, tool_name, content, content_hash, metadata, importance, decay_class, strength)
4416
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1.0)
4417
- `).run(id2, now, ep.sessionId ?? null, ep.taskId ?? null, ep.turnNumber ?? null, modality, ep.toolName ?? null, ep.content, contentHash, ep.metadata ? JSON.stringify(ep.metadata) : null, importance, decayClass);
4647
+ INSERT INTO episodes (id, timestamp, session_id, task_id, turn_number, modality, tool_name, content, content_hash, metadata, importance, decay_class, strength, source_episode_id)
4648
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1.0, ?)
4649
+ `).run(id2, now, ep.sessionId ?? null, ep.taskId ?? null, ep.turnNumber ?? null, modality, ep.toolName ?? null, ep.content, contentHash, ep.metadata ? JSON.stringify(ep.metadata) : null, importance, decayClass, ep.sourceEpisodeId ?? null);
4418
4650
  if (this.graph) {
4419
4651
  try {
4420
4652
  const episode = this.get(id2);
@@ -4429,7 +4661,7 @@ var EpisodeStore = class {
4429
4661
  /** Retrieve episodes matching a query, scored by recency + importance + (lexical + embedding). */
4430
4662
  search(query, opts = {}) {
4431
4663
  const now = Date.now();
4432
- const limit = query.limit ?? 20;
4664
+ const limit = candidateLimit(query.limit, 20, 500);
4433
4665
  const qEmb = opts.queryEmbedding ?? null;
4434
4666
  const wLex = opts.lexicalWeight ?? 1;
4435
4667
  const wEmb = opts.embeddingWeight ?? 1;
@@ -4451,21 +4683,125 @@ var EpisodeStore = class {
4451
4683
  sql += " AND modality = ?";
4452
4684
  params.push(query.modality);
4453
4685
  }
4454
- if (query.since) {
4686
+ if (query.since !== void 0) {
4455
4687
  sql += " AND timestamp >= ?";
4456
4688
  params.push(query.since);
4457
4689
  }
4458
- if (query.until) {
4690
+ if (query.until !== void 0) {
4459
4691
  sql += " AND timestamp <= ?";
4460
4692
  params.push(query.until);
4461
4693
  }
4462
- if (query.minImportance) {
4694
+ if (query.minImportance !== void 0) {
4463
4695
  sql += " AND importance >= ?";
4464
4696
  params.push(query.minImportance);
4465
4697
  }
4466
- sql += " ORDER BY timestamp DESC LIMIT ?";
4467
- params.push(Math.min(limit * 5, 500));
4468
- let rows = this.db.prepare(sql).all(...params);
4698
+ const recordedAsOf = query.recordedAsOf ?? now;
4699
+ if (!Number.isFinite(recordedAsOf) || query.validAt !== void 0 && !Number.isFinite(query.validAt))
4700
+ throw new TypeError("Episode view timestamps must be finite");
4701
+ sql += " AND timestamp <= ?";
4702
+ params.push(recordedAsOf);
4703
+ const metadataClause = (key, value) => {
4704
+ sql += " AND json_valid(metadata) AND json_extract(metadata, ?) IS ?";
4705
+ params.push(`$.${JSON.stringify(key)}`, typeof value === "boolean" ? Number(value) : value ?? null);
4706
+ };
4707
+ for (const [key, value] of Object.entries(query.metadataFilter ?? {})) {
4708
+ if (value !== null && typeof value === "object")
4709
+ sql += " AND 0";
4710
+ else
4711
+ metadataClause(key, value);
4712
+ }
4713
+ if (query.soundClass)
4714
+ metadataClause("sound_class", query.soundClass);
4715
+ if (query.rmsRange) {
4716
+ sql += " AND json_valid(metadata) AND typeof(COALESCE(json_extract(metadata, '$.rms_db'), json_extract(metadata, '$.rmsDb'))) IN ('real','integer')";
4717
+ if (query.rmsRange.min !== void 0) {
4718
+ sql += " AND COALESCE(json_extract(metadata, '$.rms_db'), json_extract(metadata, '$.rmsDb')) >= ?";
4719
+ params.push(query.rmsRange.min);
4720
+ }
4721
+ if (query.rmsRange.max !== void 0) {
4722
+ sql += " AND COALESCE(json_extract(metadata, '$.rms_db'), json_extract(metadata, '$.rmsDb')) <= ?";
4723
+ params.push(query.rmsRange.max);
4724
+ }
4725
+ }
4726
+ const bound = candidateLimit(opts.candidateLimit, Math.max(limit * 5, 100));
4727
+ const population = (suffix = "", extra = []) => Number(this.db.prepare(sql.replace("SELECT *", "SELECT COUNT(*) AS n") + suffix).get(...params, ...extra).n);
4728
+ const byId = /* @__PURE__ */ new Map();
4729
+ const collect = (route, suffix, extra, order) => {
4730
+ const total = population(suffix, extra);
4731
+ const selected = this.db.prepare(sql + suffix + ` ORDER BY ${order} LIMIT ?`).all(...params, ...extra, bound);
4732
+ for (const row of selected)
4733
+ byId.set(row.id, row);
4734
+ observeCandidates(opts.onCandidateCoverage, {
4735
+ route,
4736
+ population: total,
4737
+ examined: total,
4738
+ selected: selected.length,
4739
+ limit: bound,
4740
+ complete: total <= bound,
4741
+ reasonCode: total > bound ? "candidate_limit" : void 0
4742
+ });
4743
+ };
4744
+ const terms = memoryCueTerms(query.query ?? "");
4745
+ if (terms.length) {
4746
+ const fields = ["content", "id", "task_id", "tool_name", "source_episode_id", "metadata"];
4747
+ const cue = lexicalPredicate(fields, terms);
4748
+ const total = population(` AND ${cue.sql}`, cue.params);
4749
+ const selected = this.db.prepare(sql + ` AND ${cue.sql} ORDER BY (${cue.scoreSql}) DESC, timestamp DESC, id ASC LIMIT ?`).all(...params, ...cue.params, ...cue.params, bound);
4750
+ for (const row of selected)
4751
+ byId.set(row.id, row);
4752
+ observeCandidates(opts.onCandidateCoverage, {
4753
+ route: "episode_lexical_like",
4754
+ population: total,
4755
+ examined: total,
4756
+ selected: selected.length,
4757
+ limit: bound,
4758
+ complete: total <= bound,
4759
+ reasonCode: total > bound ? "candidate_limit" : void 0
4760
+ });
4761
+ collect("episode_exact", " AND (id = ? OR task_id = ? OR tool_name = ? OR source_episode_id = ? OR instr(lower(content), lower(?)) > 0)", Array(5).fill(query.query.trim()), "timestamp DESC, id ASC");
4762
+ }
4763
+ collect("episode_recency", "", [], "timestamp DESC, id ASC");
4764
+ if (qEmb) {
4765
+ const denseLimit = candidateLimit(opts.scanLimit, 2e3, 5e4);
4766
+ if (!opts.queryEmbeddingModel)
4767
+ observeCandidates(opts.onCandidateCoverage, {
4768
+ route: "episode_dense",
4769
+ population: null,
4770
+ examined: 0,
4771
+ selected: 0,
4772
+ limit: denseLimit,
4773
+ complete: false,
4774
+ reasonCode: "embedding_profile_unknown"
4775
+ });
4776
+ else {
4777
+ let suffix = " AND embedding IS NOT NULL AND json_valid(metadata) AND json_extract(metadata, '$._embeddingProfile.model') = ? AND json_extract(metadata, '$._embeddingProfile.dimensions') = ?";
4778
+ const extra = [opts.queryEmbeddingModel, qEmb.length];
4779
+ if (opts.queryEmbeddingProfileRef) {
4780
+ suffix += " AND json_extract(metadata, '$._embeddingProfile.profileRef') = ?";
4781
+ extra.push(opts.queryEmbeddingProfileRef);
4782
+ }
4783
+ const total = population(suffix, extra);
4784
+ const selected = this.db.prepare(sql + suffix + " ORDER BY id ASC LIMIT ?").all(...params, ...extra, denseLimit);
4785
+ const valid = selected.filter((row) => {
4786
+ const profile = JSON.parse(row.metadata)?._embeddingProfile;
4787
+ return profile?.inputHash === createHash2("sha256").update(row.content).digest("hex");
4788
+ });
4789
+ for (const row of valid)
4790
+ byId.set(row.id, row);
4791
+ const eligible = population();
4792
+ observeCandidates(opts.onCandidateCoverage, {
4793
+ route: "episode_dense",
4794
+ population: total,
4795
+ eligiblePopulation: eligible,
4796
+ examined: selected.length,
4797
+ selected: valid.length,
4798
+ limit: denseLimit,
4799
+ complete: total <= denseLimit && total === eligible && valid.length === selected.length,
4800
+ reasonCode: total > denseLimit ? "scan_limit" : valid.length < selected.length ? "stale_embedding_input" : total < eligible ? "embedding_coverage_partial" : void 0
4801
+ });
4802
+ }
4803
+ }
4804
+ let rows = [...byId.values()];
4469
4805
  if (query.metadataFilter || query.soundClass || query.rmsRange) {
4470
4806
  rows = rows.filter((row) => {
4471
4807
  let meta = null;
@@ -4505,12 +4841,12 @@ var EpisodeStore = class {
4505
4841
  if (query.query) {
4506
4842
  const queryLower = query.query.toLowerCase();
4507
4843
  const contentLower = ep.content.toLowerCase();
4508
- const queryTerms = queryLower.split(/\s+/).filter((t) => t.length > 2);
4844
+ const queryTerms = memoryCueTerms(queryLower);
4509
4845
  const matched = queryTerms.filter((t) => contentLower.includes(t)).length;
4510
4846
  lex = queryTerms.length > 0 ? matched / queryTerms.length : 0;
4511
4847
  }
4512
4848
  let emb = 0;
4513
- if (qEmb && ep.embedding && ep.embedding.length === qEmb.length) {
4849
+ if (qEmb && opts.queryEmbeddingModel && ep.metadata?.["_embeddingProfile"] && ep.metadata["_embeddingProfile"]["model"] === opts.queryEmbeddingModel && (!opts.queryEmbeddingProfileRef || ep.metadata["_embeddingProfile"]["profileRef"] === opts.queryEmbeddingProfileRef) && ep.metadata["_embeddingProfile"]["inputHash"] === createHash2("sha256").update(ep.content).digest("hex") && ep.embedding && ep.embedding.length === qEmb.length) {
4514
4850
  const a = ep.embedding;
4515
4851
  const b = qEmb;
4516
4852
  let dot = 0, na = 0, nb = 0;
@@ -4549,10 +4885,9 @@ var EpisodeStore = class {
4549
4885
  });
4550
4886
  scored.sort((a, b) => b.score - a.score);
4551
4887
  const topK = scored.slice(0, limit);
4552
- if (opts.recordRetrieval !== false) {
4553
- this.recordRetrieved(topK.map((item) => item.episode), now);
4554
- }
4555
- return topK.map((s) => s.episode);
4888
+ const episodes = topK.map((item) => item.episode);
4889
+ this.recordRetrievalTelemetry(episodes, now, opts);
4890
+ return episodes;
4556
4891
  }
4557
4892
  /** WO-AM-05: PPR-enhanced search for multi-hop retrieval (HippoRAG).
4558
4893
  * Falls back to standard search if graph is unavailable or no entities found.
@@ -4561,10 +4896,14 @@ var EpisodeStore = class {
4561
4896
  if (!this.graph || !query.query) {
4562
4897
  return this.search(query, opts);
4563
4898
  }
4564
- const standardResults = this.search(query, { ...opts, recordRetrieval: false });
4899
+ const standardResults = this.search(query, { ...opts, recordRetrieval: false, onRetrievalTelemetry: void 0 });
4565
4900
  try {
4566
4901
  const pprResult = retrieveByPPR(query.query, this.graph, this, {
4567
4902
  ...opts.pprBudget,
4903
+ episodeFilter: (episode) => this.matchesQueryFilters(episode, query),
4904
+ validAt: query.validAt ?? Date.now(),
4905
+ recordedAsOf: query.recordedAsOf ?? Date.now(),
4906
+ onCandidateCoverage: opts.onCandidateCoverage,
4568
4907
  damping: 0.5,
4569
4908
  maxIterations: 50,
4570
4909
  convergenceThreshold: 1e-6,
@@ -4601,8 +4940,7 @@ var EpisodeStore = class {
4601
4940
  });
4602
4941
  const limit = query.limit ?? 20;
4603
4942
  const merged = [...candidates.values()].sort((a, b) => b.score - a.score || b.sourceCount - a.sourceCount || b.bestPprScore - a.bestPprScore || b.episode.timestamp - a.episode.timestamp || a.episode.id.localeCompare(b.episode.id)).slice(0, limit).map((candidate) => candidate.episode);
4604
- if (opts.recordRetrieval !== false)
4605
- this.recordRetrieved(merged, Date.now());
4943
+ this.recordRetrievalTelemetry(merged, Date.now(), opts);
4606
4944
  return merged;
4607
4945
  } catch (error) {
4608
4946
  if (error instanceof PPRTraversalBudgetError) {
@@ -4611,13 +4949,23 @@ var EpisodeStore = class {
4611
4949
  } catch {
4612
4950
  }
4613
4951
  }
4614
- if (opts.recordRetrieval !== false)
4615
- this.recordRetrieved(standardResults, Date.now());
4952
+ observeCandidates(opts.onCandidateCoverage, {
4953
+ route: "ppr",
4954
+ population: null,
4955
+ examined: 0,
4956
+ selected: 0,
4957
+ limit: query.limit ?? 20,
4958
+ complete: false,
4959
+ reasonCode: error instanceof PPRTraversalBudgetError ? `budget_${error.reason}` : "graph_unavailable"
4960
+ });
4961
+ this.recordRetrievalTelemetry(standardResults, Date.now(), opts);
4616
4962
  return standardResults;
4617
4963
  }
4618
4964
  }
4619
4965
  /** Apply every non-text relevance constraint to a graph candidate. */
4620
4966
  matchesQueryFilters(episode, query) {
4967
+ if (episode.timestamp > (query.recordedAsOf ?? Date.now()))
4968
+ return false;
4621
4969
  if (query.sessionId && episode.sessionId !== query.sessionId)
4622
4970
  return false;
4623
4971
  if (query.taskId && episode.taskId !== query.taskId)
@@ -4654,7 +5002,27 @@ var EpisodeStore = class {
4654
5002
  }
4655
5003
  return true;
4656
5004
  }
4657
- recordRetrieved(episodes, timestamp2) {
5005
+ /** Keep optional write/observer failures outside every retrieval error boundary. */
5006
+ recordRetrievalTelemetry(episodes, timestamp2, opts) {
5007
+ let observation;
5008
+ if (opts.recordRetrieval === false) {
5009
+ observation = { status: "disabled", reasonCode: "retrieval_recording_disabled" };
5010
+ } else if (episodes.length === 0) {
5011
+ observation = { status: "disabled", reasonCode: "empty_result" };
5012
+ } else {
5013
+ try {
5014
+ this.recordRetrieved(episodes, timestamp2, opts.bestEffortRetrievalTelemetry === true);
5015
+ observation = { status: "recorded" };
5016
+ } catch {
5017
+ observation = { status: "unavailable", reasonCode: "retrieval_event_write_failed" };
5018
+ }
5019
+ }
5020
+ try {
5021
+ void Promise.resolve(opts.onRetrievalTelemetry?.(observation)).catch(() => void 0);
5022
+ } catch {
5023
+ }
5024
+ }
5025
+ recordRetrieved(episodes, timestamp2, bestEffort = false) {
4658
5026
  if (episodes.length === 0)
4659
5027
  return;
4660
5028
  const updateStmt = this.db.prepare("UPDATE episodes SET strength = strength + 1, last_retrieved = ? WHERE id = ?");
@@ -4662,7 +5030,15 @@ var EpisodeStore = class {
4662
5030
  for (const episode of episodes)
4663
5031
  updateStmt.run(timestamp2, episode.id);
4664
5032
  });
4665
- updateAll();
5033
+ const previousTimeout = bestEffort ? this.db.pragma("busy_timeout", { simple: true }) : void 0;
5034
+ try {
5035
+ if (previousTimeout !== void 0)
5036
+ this.db.pragma("busy_timeout = 0");
5037
+ updateAll();
5038
+ } finally {
5039
+ if (previousTimeout !== void 0)
5040
+ this.db.pragma(`busy_timeout = ${previousTimeout}`);
5041
+ }
4666
5042
  }
4667
5043
  /** Get a single episode by ID. */
4668
5044
  get(id2) {
@@ -4695,9 +5071,16 @@ var EpisodeStore = class {
4695
5071
  return result.changes;
4696
5072
  }
4697
5073
  /** Update embedding for an episode (async fill from WO-AM-10). */
4698
- setEmbedding(id2, embedding) {
4699
- const buf = Buffer.from(embedding.buffer);
4700
- this.db.prepare("UPDATE episodes SET embedding = ? WHERE id = ?").run(buf, id2);
5074
+ setEmbedding(id2, embedding, profile) {
5075
+ const buf = Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength);
5076
+ const episode = this.get(id2);
5077
+ if (!episode)
5078
+ return;
5079
+ const metadata = { ...episode.metadata };
5080
+ delete metadata["_embeddingProfile"];
5081
+ if (profile?.model)
5082
+ metadata["_embeddingProfile"] = { model: profile.model, profileRef: profile.profileRef, dimensions: embedding.length, inputHash: createHash2("sha256").update(episode.content).digest("hex") };
5083
+ this.db.prepare("UPDATE episodes SET embedding = ?, metadata = ? WHERE id = ?").run(buf, JSON.stringify(metadata), id2);
4701
5084
  }
4702
5085
  /** WO-AM-GAP-03: Set CLIP embedding for cross-modal retrieval (512d). */
4703
5086
  setClipEmbedding(id2, clipEmbedding) {
@@ -4710,6 +5093,8 @@ var EpisodeStore = class {
4710
5093
  }
4711
5094
  /** Close the database connection. */
4712
5095
  close() {
5096
+ this.unregisterGraphSource?.();
5097
+ this.unregisterGraphSource = void 0;
4713
5098
  try {
4714
5099
  this.db.close();
4715
5100
  } catch {
@@ -6373,7 +6758,7 @@ function deleteEpisodes(db, ids, dryRun) {
6373
6758
  deleted += Number(result.changes ?? 0);
6374
6759
  }
6375
6760
  });
6376
- tx(unique2);
6761
+ tx.immediate(unique2);
6377
6762
  return deleted;
6378
6763
  }
6379
6764
  function maintainGraph(dbPath, options, shouldStop) {
@@ -6475,9 +6860,19 @@ function vectorDuplicateNodePairs(rows, threshold) {
6475
6860
  }
6476
6861
  return pairs;
6477
6862
  }
6863
+ function graphLineageProtection(db) {
6864
+ const columns = db.prepare("PRAGMA table_info(kg_edges)").all();
6865
+ if (!columns.some((column) => column.name === "lineage_protected"))
6866
+ return { legacy: "1=1", node: () => false };
6867
+ const query = db.prepare("SELECT 1 FROM kg_edges WHERE lineage_protected=1 AND (src_id=? OR dst_id=?) LIMIT 1");
6868
+ return { legacy: "COALESCE(lineage_protected,0)=0", node: (id2) => !!query.get(id2, id2) };
6869
+ }
6478
6870
  function mergeGraphNodes(db, pairs, dryRun) {
6871
+ const protectedLineage = graphLineageProtection(db);
6479
6872
  const seen = /* @__PURE__ */ new Set();
6480
6873
  const unique2 = pairs.filter((pair) => {
6874
+ if (protectedLineage.node(pair.keepId) || protectedLineage.node(pair.dropId))
6875
+ return false;
6481
6876
  if (!pair.keepId || !pair.dropId || pair.keepId === pair.dropId)
6482
6877
  return false;
6483
6878
  if (seen.has(pair.dropId))
@@ -6497,6 +6892,8 @@ function mergeGraphNodes(db, pairs, dryRun) {
6497
6892
  last_seen = MAX(last_seen, COALESCE((SELECT last_seen FROM kg_nodes WHERE id = ?), last_seen))
6498
6893
  WHERE id = ?`);
6499
6894
  for (const pair of rows) {
6895
+ if (protectedLineage.node(pair.keepId) || protectedLineage.node(pair.dropId))
6896
+ continue;
6500
6897
  bump.run(pair.dropId, pair.dropId, pair.keepId);
6501
6898
  src.run(pair.keepId, pair.dropId);
6502
6899
  dst.run(pair.keepId, pair.dropId);
@@ -6508,6 +6905,7 @@ function mergeGraphNodes(db, pairs, dryRun) {
6508
6905
  return merged;
6509
6906
  }
6510
6907
  function dedupeGraphEdges(db, limit, dryRun) {
6908
+ const protectedLineage = graphLineageProtection(db);
6511
6909
  let ids = [];
6512
6910
  try {
6513
6911
  ids = db.prepare(`SELECT id FROM (
@@ -6516,7 +6914,7 @@ function dedupeGraphEdges(db, limit, dryRun) {
6516
6914
  PARTITION BY src_id, dst_id, relation, COALESCE(fact, ''), COALESCE(modality, ''), COALESCE(valid_until, -1)
6517
6915
  ORDER BY confidence DESC, valid_from DESC, id DESC
6518
6916
  ) AS rn
6519
- FROM kg_edges
6917
+ FROM kg_edges WHERE ${protectedLineage.legacy}
6520
6918
  )
6521
6919
  WHERE rn > 1
6522
6920
  LIMIT ?`).all(Math.max(1, limit)).map((row) => row.id);
@@ -6530,12 +6928,13 @@ function dedupeGraphEdges(db, limit, dryRun) {
6530
6928
  function pruneInactiveEdges(db, limit, dryRun, supersededRetentionMs = 30 * DAY) {
6531
6929
  const now = Date.now();
6532
6930
  const lowConfidenceCutoff = now - 14 * DAY;
6931
+ const protectedLineage = graphLineageProtection(db);
6533
6932
  const supersededCutoff = supersededRetentionMs > 0 ? now - supersededRetentionMs : null;
6534
6933
  let ids = [];
6535
6934
  try {
6536
6935
  ids = db.prepare(`SELECT id
6537
6936
  FROM kg_edges
6538
- WHERE valid_until IS NOT NULL
6937
+ WHERE valid_until IS NOT NULL AND ${protectedLineage.legacy}
6539
6938
  AND ( (valid_until < ? AND COALESCE(confidence, 1) < 0.55)
6540
6939
  OR (? IS NOT NULL AND valid_until < ?) )
6541
6940
  ORDER BY valid_until ASC
@@ -6588,6 +6987,7 @@ function selectCapEvictionCandidates(db, options, withText) {
6588
6987
  const protectMs = Math.max(0, options.graphProtectRecentMs ?? DAY);
6589
6988
  const protectCut = now - protectMs;
6590
6989
  const protect = new Set(options.graphProtectNodeIds ?? []);
6990
+ const protectedLineage = graphLineageProtection(db);
6591
6991
  const hubDegreeGuard = 6;
6592
6992
  try {
6593
6993
  const shortlistLimit = Math.max(1, Math.min(batch * 4, batch + 2e4));
@@ -6602,7 +7002,7 @@ function selectCapEvictionCandidates(db, options, withText) {
6602
7002
  const degStmt = db.prepare("SELECT COUNT(*) AS d FROM kg_edges WHERE src_id = ? OR dst_id = ?");
6603
7003
  const scored = [];
6604
7004
  for (const row of shortlist) {
6605
- if (protect.has(row.id))
7005
+ if (protect.has(row.id) || protectedLineage.node(row.id))
6606
7006
  continue;
6607
7007
  let deg = 0;
6608
7008
  try {
@@ -6680,6 +7080,8 @@ function reinforceGraphNodes(dbPath, ids) {
6680
7080
  }
6681
7081
  }
6682
7082
  function archiveAndDeleteNodes(db, dbPath, ids, archive) {
7083
+ const protectedLineage = graphLineageProtection(db);
7084
+ ids = ids.filter((id2) => !protectedLineage.node(id2));
6683
7085
  if (ids.length === 0)
6684
7086
  return { nodes: 0, edges: 0, archived: 0 };
6685
7087
  const archivePath = dbPath.replace(/\.db$/i, ".archive.db");
@@ -6700,6 +7102,9 @@ function archiveAndDeleteNodes(db, dbPath, ids, archive) {
6700
7102
  }
6701
7103
  const chunkSize = 250;
6702
7104
  const run = db.transaction((chunk) => {
7105
+ chunk = chunk.filter((id2) => !protectedLineage.node(id2));
7106
+ if (!chunk.length)
7107
+ return;
6703
7108
  const ph = chunk.map(() => "?").join(",");
6704
7109
  if (attached) {
6705
7110
  try {
@@ -6715,7 +7120,7 @@ function archiveAndDeleteNodes(db, dbPath, ids, archive) {
6715
7120
  nodesDeleted += Number(nd.changes ?? 0);
6716
7121
  });
6717
7122
  for (let i = 0; i < ids.length; i += chunkSize) {
6718
- run(ids.slice(i, i + chunkSize));
7123
+ run.immediate(ids.slice(i, i + chunkSize));
6719
7124
  }
6720
7125
  } finally {
6721
7126
  if (attached) {