@remnic/core 9.63.7 → 9.63.8

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 (157) hide show
  1. package/dist/access-admin-ops-surface.d.ts +3 -2
  2. package/dist/access-admin-ops-surface.js +11 -9
  3. package/dist/access-authorization-probe.d.ts +3 -2
  4. package/dist/access-authorization-probe.js +12 -10
  5. package/dist/access-boundary.d.ts +3 -2
  6. package/dist/access-boundary.js +11 -9
  7. package/dist/access-cli.js +46 -45
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-extraction-force-flush.d.ts +3 -2
  10. package/dist/access-extraction-force-flush.js +11 -9
  11. package/dist/access-http-lcm-compaction.d.ts +3 -2
  12. package/dist/access-http-lifecycle-flush.d.ts +3 -2
  13. package/dist/access-http-offline-stream.d.ts +3 -2
  14. package/dist/access-http-query.js +11 -9
  15. package/dist/access-http.d.ts +4 -3
  16. package/dist/access-http.js +24 -22
  17. package/dist/access-identity-continuity-surface.d.ts +2 -1
  18. package/dist/access-identity-continuity-surface.js +11 -9
  19. package/dist/access-lcm-surface.d.ts +3 -2
  20. package/dist/access-lcm-surface.js +11 -9
  21. package/dist/access-mcp-output-schemas.js +1 -1
  22. package/dist/access-mcp.d.ts +3 -2
  23. package/dist/access-mcp.js +19 -17
  24. package/dist/access-namespace-preflight.js +11 -9
  25. package/dist/access-observe-write-surface.d.ts +3 -2
  26. package/dist/access-observe-write-surface.js +11 -9
  27. package/dist/access-offline-manifest.d.ts +2 -1
  28. package/dist/access-offline-manifest.js +3 -3
  29. package/dist/access-operations-batch.js +13 -11
  30. package/dist/access-operations.d.ts +6 -5
  31. package/dist/access-operations.js +17 -15
  32. package/dist/access-recall-concurrency.d.ts +3 -2
  33. package/dist/access-recall-concurrency.js +11 -9
  34. package/dist/access-recall-response.d.ts +3 -2
  35. package/dist/access-recall-response.js +11 -9
  36. package/dist/access-recall-surface.d.ts +3 -2
  37. package/dist/access-recall-surface.js +11 -9
  38. package/dist/access-schema.d.ts +88 -88
  39. package/dist/access-schema.js +5 -5
  40. package/dist/{access-service-CocW74uA.d.ts → access-service-BaPa_km6.d.ts} +65 -65
  41. package/dist/access-service-helpers.d.ts +3 -2
  42. package/dist/access-service.d.ts +3 -2
  43. package/dist/access-service.js +11 -9
  44. package/dist/access-surface-catalog.d.ts +3 -2
  45. package/dist/access-surface-catalog.js +13 -11
  46. package/dist/access-surface-catalog.js.map +1 -1
  47. package/dist/active-recall.js +3 -3
  48. package/dist/bootstrap.d.ts +2 -1
  49. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
  50. package/dist/chunk-2YA5N2BY.js +65 -0
  51. package/dist/chunk-2YA5N2BY.js.map +1 -0
  52. package/dist/{chunk-5S5DUJFJ.js → chunk-3IMYRX3W.js} +2 -2
  53. package/dist/{chunk-QIZOU3FN.js → chunk-5OOTHWGJ.js} +2 -2
  54. package/dist/{chunk-YMQKPSB2.js → chunk-5TF5STAV.js} +4 -4
  55. package/dist/{chunk-PMVPCZJZ.js → chunk-6433HV72.js} +2 -2
  56. package/dist/{chunk-WKJTMXME.js → chunk-BPQ7L27U.js} +44 -42
  57. package/dist/{chunk-WKJTMXME.js.map → chunk-BPQ7L27U.js.map} +1 -1
  58. package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
  59. package/dist/{chunk-IBZQQOM5.js → chunk-DGUVXXAU.js} +3 -3
  60. package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
  61. package/dist/{chunk-HXZNTZ3Y.js → chunk-EDZNW3HE.js} +5 -5
  62. package/dist/{chunk-2L7DKNVE.js → chunk-FZEEWOI2.js} +4 -4
  63. package/dist/{chunk-XNJQZLAP.js → chunk-I2HTKOOP.js} +2 -2
  64. package/dist/{chunk-3S3PNR5H.js → chunk-KXWE62IH.js} +2 -2
  65. package/dist/{chunk-SYJW273H.js → chunk-LTYH2L6E.js} +12 -12
  66. package/dist/{chunk-YIMV2KYM.js → chunk-N7V3P4V5.js} +2 -2
  67. package/dist/{chunk-OOJCXJBN.js → chunk-O52TB5SL.js} +2 -2
  68. package/dist/{chunk-PZKWPXRF.js → chunk-PHKU6BZ2.js} +2 -2
  69. package/dist/{chunk-H4GQ2Y24.js → chunk-PQHNZ63P.js} +4 -4
  70. package/dist/{chunk-7ZAC2C2U.js → chunk-SY5JUJ2X.js} +35 -35
  71. package/dist/{chunk-YYQAKIDJ.js → chunk-VD2OT77P.js} +2 -2
  72. package/dist/chunk-VD2OT77P.js.map +1 -0
  73. package/dist/{chunk-KQAFEZQX.js → chunk-VDX2J7OX.js} +2 -2
  74. package/dist/{chunk-WZDTSBGQ.js → chunk-VYMICVRA.js} +2 -2
  75. package/dist/{chunk-XV6PUXJ5.js → chunk-WBPD6SBZ.js} +52 -59
  76. package/dist/chunk-WBPD6SBZ.js.map +1 -0
  77. package/dist/{chunk-3NZAVWU5.js → chunk-ZOAAY2OE.js} +2 -2
  78. package/dist/{chunk-PRDJMOST.js → chunk-ZVZHG7AI.js} +65 -15
  79. package/dist/chunk-ZVZHG7AI.js.map +1 -0
  80. package/dist/{chunk-IINVXO3U.js → chunk-ZWYXSF2T.js} +2 -2
  81. package/dist/{cli-BTNj5DzK.d.ts → cli-D0tV7eeU.d.ts} +2 -2
  82. package/dist/cli.d.ts +4 -3
  83. package/dist/cli.js +36 -34
  84. package/dist/config.js +3 -3
  85. package/dist/explicit-capture.d.ts +2 -1
  86. package/dist/external-wiki-access.d.ts +3 -2
  87. package/dist/external-wiki-access.js +12 -10
  88. package/dist/external-wiki-mcp-tools.d.ts +3 -2
  89. package/dist/{first-start-migration-Q2VB2E2D.js → first-start-migration-4NETATFF.js} +4 -4
  90. package/dist/included-memories.d.ts +11 -0
  91. package/dist/included-memories.js +14 -0
  92. package/dist/included-memories.js.map +1 -0
  93. package/dist/index.d.ts +682 -681
  94. package/dist/index.js +57 -56
  95. package/dist/lcm/index.js +3 -3
  96. package/dist/mcp-memory-inspector-app.d.ts +3 -2
  97. package/dist/offline-sync.js +2 -2
  98. package/dist/operator-toolkit.js +4 -4
  99. package/dist/{orchestrator-CSc9GfQv.d.ts → orchestrator-Bay_AofR.d.ts} +2 -3
  100. package/dist/orchestrator.d.ts +2 -1
  101. package/dist/orchestrator.js +46 -45
  102. package/dist/{public-http-BmPktTe3.d.ts → public-http-BtjiyKah.d.ts} +1 -1
  103. package/dist/recall-explain-renderer.d.ts +1 -0
  104. package/dist/recall-state.d.ts +6 -2
  105. package/dist/recall-state.js +6 -2
  106. package/dist/resume-bundles.js +4 -4
  107. package/dist/schemas.d.ts +108 -108
  108. package/dist/shared-context/manager.d.ts +8 -8
  109. package/dist/support-passport/index.d.ts +6 -5
  110. package/dist/support-passport/index.js +14 -12
  111. package/dist/transfer/backup.js +2 -2
  112. package/dist/transfer/capsule-export.js +2 -2
  113. package/dist/transfer/capsule-import.js +2 -2
  114. package/dist/transfer/types.d.ts +66 -66
  115. package/package.json +2 -2
  116. package/src/access-mcp-output-schemas.ts +1 -1
  117. package/src/access-recall-response.ts +4 -2
  118. package/src/access-recall-surface.ts +9 -9
  119. package/src/access-service-namespace.test.ts +9 -9
  120. package/src/access-service-raw-excerpt-read-gate.test.ts +1 -1
  121. package/src/included-memories.ts +88 -0
  122. package/src/orchestration/recall-internal-deps.ts +2 -4
  123. package/src/orchestration/recall-internal.ts +9 -13
  124. package/src/orchestration/recall-result-formatter-display-safe.test.ts +13 -16
  125. package/src/orchestration/recall-result-formatter.ts +32 -45
  126. package/src/orchestration/recall-section-coordinator.ts +20 -26
  127. package/src/orchestrator.ts +2 -4
  128. package/src/recall-explain-renderer.test.ts +4 -0
  129. package/src/recall-state.test.ts +108 -5
  130. package/src/recall-state.ts +85 -23
  131. package/src/recall-token-budget.test.ts +1 -1
  132. package/dist/chunk-PRDJMOST.js.map +0 -1
  133. package/dist/chunk-XV6PUXJ5.js.map +0 -1
  134. package/dist/chunk-YYQAKIDJ.js.map +0 -1
  135. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
  136. /package/dist/{chunk-5S5DUJFJ.js.map → chunk-3IMYRX3W.js.map} +0 -0
  137. /package/dist/{chunk-QIZOU3FN.js.map → chunk-5OOTHWGJ.js.map} +0 -0
  138. /package/dist/{chunk-YMQKPSB2.js.map → chunk-5TF5STAV.js.map} +0 -0
  139. /package/dist/{chunk-PMVPCZJZ.js.map → chunk-6433HV72.js.map} +0 -0
  140. /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  141. /package/dist/{chunk-IBZQQOM5.js.map → chunk-DGUVXXAU.js.map} +0 -0
  142. /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
  143. /package/dist/{chunk-HXZNTZ3Y.js.map → chunk-EDZNW3HE.js.map} +0 -0
  144. /package/dist/{chunk-2L7DKNVE.js.map → chunk-FZEEWOI2.js.map} +0 -0
  145. /package/dist/{chunk-XNJQZLAP.js.map → chunk-I2HTKOOP.js.map} +0 -0
  146. /package/dist/{chunk-3S3PNR5H.js.map → chunk-KXWE62IH.js.map} +0 -0
  147. /package/dist/{chunk-SYJW273H.js.map → chunk-LTYH2L6E.js.map} +0 -0
  148. /package/dist/{chunk-YIMV2KYM.js.map → chunk-N7V3P4V5.js.map} +0 -0
  149. /package/dist/{chunk-OOJCXJBN.js.map → chunk-O52TB5SL.js.map} +0 -0
  150. /package/dist/{chunk-PZKWPXRF.js.map → chunk-PHKU6BZ2.js.map} +0 -0
  151. /package/dist/{chunk-H4GQ2Y24.js.map → chunk-PQHNZ63P.js.map} +0 -0
  152. /package/dist/{chunk-7ZAC2C2U.js.map → chunk-SY5JUJ2X.js.map} +0 -0
  153. /package/dist/{chunk-KQAFEZQX.js.map → chunk-VDX2J7OX.js.map} +0 -0
  154. /package/dist/{chunk-WZDTSBGQ.js.map → chunk-VYMICVRA.js.map} +0 -0
  155. /package/dist/{chunk-3NZAVWU5.js.map → chunk-ZOAAY2OE.js.map} +0 -0
  156. /package/dist/{chunk-IINVXO3U.js.map → chunk-ZWYXSF2T.js.map} +0 -0
  157. /package/dist/{first-start-migration-Q2VB2E2D.js.map → first-start-migration-4NETATFF.js.map} +0 -0
@@ -4,7 +4,7 @@ import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, wri
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
 
7
- import { clampGraphRecallExpandedEntries, LastRecallStore } from "./recall-state.js";
7
+ import { clampGraphRecallExpandedEntries, LastRecallStore, RecallHandleHistoryStore } from "./recall-state.js";
8
8
  import type { RecallTierExplain } from "./types.js";
9
9
  import { listContainedSpillFiles } from "./utils/path-containment.js";
10
10
 
@@ -83,19 +83,69 @@ test("LastRecallStore.record persists tierExplain and round-trips to JSON on dis
83
83
  assert.deepEqual(parsed["s1"]?.tierExplain, tierExplain);
84
84
  });
85
85
 
86
- test("LastRecallStore.record persists per-result namespaces", async () => {
86
+ test("LastRecallStore.record shims legacy resultPaths/resultNamespaces into includedMemories", async () => {
87
87
  const { store } = await freshStore();
88
- const resultNamespaces = ["main", "shared"] as Array<string | undefined>;
89
88
  await store.record({
90
89
  sessionKey: "s1",
91
90
  query: "namespaced recall",
92
91
  memoryIds: ["same-id", "same-id"],
93
92
  resultPaths: ["facts/same-id.md", "facts/same-id.md"],
94
- resultNamespaces,
93
+ resultNamespaces: ["main", "shared"],
95
94
  });
96
95
  const snap = store.get("s1");
97
96
  assert.ok(snap);
98
- assert.deepEqual(snap.resultNamespaces, resultNamespaces);
97
+ assert.deepEqual(snap.includedMemories, [
98
+ { id: "same-id", path: "facts/same-id.md", namespace: "main" },
99
+ { id: "same-id", path: "facts/same-id.md", namespace: "shared" },
100
+ ]);
101
+ assert.deepEqual(snap.memoryIds, ["same-id", "same-id"]);
102
+ });
103
+
104
+ // ── Legacy on-disk shapes hydrate to includedMemories (#2476) ─────────────
105
+
106
+ test("LastRecallStore.load shims legacy last_recall.json shapes to includedMemories", async () => {
107
+ const { dir } = await freshStore();
108
+ const fixturePath = path.resolve(
109
+ import.meta.dirname,
110
+ "../../../tests/fixtures/last-recall-legacy-shape.json",
111
+ );
112
+ const fixture = JSON.parse(await readFile(fixturePath, "utf-8")) as Record<string, unknown>;
113
+
114
+ await mkdir(path.join(dir, "state"), { recursive: true });
115
+ await writeFile(
116
+ path.join(dir, "state", "last_recall.json"),
117
+ JSON.stringify(fixture),
118
+ "utf-8",
119
+ );
120
+ const store = new LastRecallStore(dir);
121
+ await store.load();
122
+
123
+ const full = store.get("legacy-full");
124
+ assert.ok(full);
125
+ assert.deepEqual(full.includedMemories, [
126
+ {
127
+ id: "fact-alpha",
128
+ path: "/memory-under-test/namespaces/team-alpha/facts/2026-08-01/fact-alpha.md",
129
+ namespace: "team-alpha",
130
+ },
131
+ { id: "fact-beta", path: "/memory-under-test/facts/2026-08-01/fact-beta.md" },
132
+ {
133
+ id: "fact-gamma",
134
+ path: "/memory-under-test/namespaces/team-alpha/facts/2026-08-01/fact-gamma.md",
135
+ namespace: "team-alpha",
136
+ },
137
+ ]);
138
+ assert.deepEqual(full.memoryIds, ["fact-alpha", "fact-beta", "fact-gamma"]);
139
+ assert.deepEqual(
140
+ full.resultPaths,
141
+ full.includedMemories?.map((memory) => memory.path),
142
+ );
143
+ assert.deepEqual(full.budgetsApplied?.omittedMemoryIds, ["fact-dropped"]);
144
+
145
+ const idsOnly = store.get("legacy-ids-only");
146
+ assert.ok(idsOnly);
147
+ assert.deepEqual(idsOnly.includedMemories, [{ id: "fact-delta", path: "" }]);
148
+ assert.deepEqual(idsOnly.memoryIds, ["fact-delta"]);
99
149
  });
100
150
 
101
151
  // ── Defensive copies isolate the stored snapshot from caller mutation ──────
@@ -1083,3 +1133,56 @@ test("LastRecallStore.drainPendingImpressions reports pendingDeferred when a spi
1083
1133
  await rm(dir, { recursive: true, force: true });
1084
1134
  }
1085
1135
  });
1136
+ +
1137
+ test("LastRecallStore rejects unsafe session keys on every read/write path", async () => {
1138
+ const { store, dir } = await freshStore();
1139
+ for (const key of ["__proto__", "constructor", "prototype"]) {
1140
+ await store.record({ sessionKey: key, query: "q", memoryIds: ["m-1"] });
1141
+ assert.equal(store.get(key), null, `get(${key}) must not surface prototype junk`);
1142
+ }
1143
+ assert.equal(store.getMostRecent(), null);
1144
+
1145
+ await store.annotateTierExplain("__proto__", {
1146
+ tier: "direct-answer",
1147
+ tierReason: "",
1148
+ filteredBy: [],
1149
+ candidatesConsidered: 0,
1150
+ latencyMs: 0,
1151
+ });
1152
+ assert.equal(store.get("__proto__"), null);
1153
+ const persistedKeys = await readFile(path.join(dir, "state", "last_recall.json"), "utf-8")
1154
+ .then((raw) => Object.keys(JSON.parse(raw) as object))
1155
+ .catch(() => [] as string[]);
1156
+ assert.deepEqual(persistedKeys, [], "no unsafe key persisted");
1157
+ });
1158
+
1159
+ test("RecallHandleHistoryStore rejects unsafe session keys", async () => {
1160
+ const dir = await mkdtemp(path.join(os.tmpdir(), "engram-handle-history-"));
1161
+ const store = new RecallHandleHistoryStore(dir);
1162
+ await store.load();
1163
+
1164
+ await store.record("__proto__", ["m-1"]);
1165
+ await store.record("constructor", ["m-2"]);
1166
+ assert.deepEqual(store.recent("__proto__"), []);
1167
+ assert.deepEqual(store.recent("constructor"), []);
1168
+
1169
+ await store.record("ok", ["m-3"]);
1170
+ assert.deepEqual(store.recent("ok"), [["m-3"]]);
1171
+ await rm(dir, { recursive: true, force: true });
1172
+ });
1173
+
1174
+ test("RecallHandleHistoryStore.load drops unsafe and malformed entries from persisted state", async () => {
1175
+ const dir = await mkdtemp(path.join(os.tmpdir(), "engram-handle-history-"));
1176
+ await mkdir(path.join(dir, "state"), { recursive: true });
1177
+ // JSON.parse materializes "__proto__" as an OWN key; load must not adopt it.
1178
+ const poisoned =
1179
+ '{"__proto__": [{"at": "t", "ids": ["evil"]}], "bad": "not-an-array", "ok": [{"at": "t", "ids": ["m-1"]}]}';
1180
+ await writeFile(path.join(dir, "state", "handle_history.json"), poisoned, "utf-8");
1181
+
1182
+ const store = new RecallHandleHistoryStore(dir);
1183
+ await store.load();
1184
+ assert.deepEqual(store.recent("__proto__"), []);
1185
+ assert.deepEqual(store.recent("bad"), []);
1186
+ assert.deepEqual(store.recent("ok"), [["m-1"]]);
1187
+ await rm(dir, { recursive: true, force: true });
1188
+ });
@@ -12,6 +12,22 @@ import type {
12
12
  RecallPlanMode,
13
13
  RecallTierExplain,
14
14
  } from "./types.js";
15
+ import {
16
+ coerceIncludedMemories,
17
+ type IncludedMemory,
18
+ } from "./included-memories.js";
19
+
20
+ export type { IncludedMemory } from "./included-memories.js";
21
+ export { coerceIncludedMemories } from "./included-memories.js";
22
+
23
+ // Session keys are caller-supplied (host session IDs) and land in indexed
24
+ // assignments on plain-object state. A key matching one of these would
25
+ // pollute Object.prototype (or read junk off it), so every read/write
26
+ // through this module rejects them — same contract load() already enforced.
27
+ function isUnsafeStateKey(key: string): boolean {
28
+ return key === "__proto__" || key === "constructor" || key === "prototype";
29
+ }
30
+
15
31
 
16
32
  export interface LastRecallBudgetSummary {
17
33
  requestedTopK?: number;
@@ -36,6 +52,7 @@ export interface LastRecallSnapshot {
36
52
  queryHash: string;
37
53
  queryLen: number;
38
54
  memoryIds: string[];
55
+ includedMemories?: IncludedMemory[];
39
56
  namespace?: string;
40
57
  recallNamespaces?: string[];
41
58
  traceId?: string;
@@ -172,6 +189,13 @@ type StateFileWriter = (filePath: string, content: string) => Promise<void>;
172
189
  * recordedAt are compared. Extracted so every annotation surface applies
173
190
  * identical guards (CLAUDE.md rule 22).
174
191
  */
192
+ function cloneTierExplain(
193
+ tierExplain: RecallTierExplain | undefined,
194
+ ): RecallTierExplain | undefined {
195
+ if (!tierExplain) return undefined;
196
+ return structuredClone(tierExplain);
197
+ }
198
+
175
199
  function snapshotMatchesExpectedIdentity(
176
200
  current: LastRecallSnapshot,
177
201
  expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },
@@ -182,34 +206,42 @@ function snapshotMatchesExpectedIdentity(
182
206
  }
183
207
  const hasExpectedTraceId =
184
208
  typeof expected.traceId === "string" && expected.traceId.length > 0;
185
- if (hasExpectedTraceId) {
186
- return current.traceId === expected.traceId;
187
- }
188
- if (expected.recordedAt !== undefined) {
209
+ if (hasExpectedTraceId && current.traceId !== expected.traceId) return false;
210
+ if (typeof expected.recordedAt === "string" && expected.recordedAt.length > 0) {
189
211
  return current.recordedAt === expected.recordedAt;
190
212
  }
191
213
  return true;
192
214
  }
193
215
 
194
- function cloneTierExplain(
195
- tierExplain: RecallTierExplain | undefined,
196
- ): RecallTierExplain | undefined {
197
- if (!tierExplain) return undefined;
198
- return structuredClone(tierExplain);
216
+ function hydrateLastRecallSnapshot(snapshot: LastRecallSnapshot): LastRecallSnapshot {
217
+ const includedMemories = coerceIncludedMemories(snapshot);
218
+ const budgets = snapshot.budgetsApplied
219
+ ? {
220
+ ...snapshot.budgetsApplied,
221
+ includedMemoryIds: includedMemories.map((memory) => memory.id),
222
+ includedMemoryPaths: includedMemories.map((memory) => memory.path),
223
+ includedMemoryNamespaces: includedMemories.map((memory) => memory.namespace),
224
+ }
225
+ : undefined;
226
+ return {
227
+ ...snapshot,
228
+ includedMemories,
229
+ memoryIds: includedMemories.map((memory) => memory.id),
230
+ resultPaths: includedMemories.map((memory) => memory.path),
231
+ resultNamespaces: includedMemories.map((memory) => memory.namespace),
232
+ ...(budgets ? { budgetsApplied: budgets } : {}),
233
+ };
199
234
  }
200
235
 
201
- /**
202
- * Deep-copy a LastRecallSnapshot so callers that receive it cannot
203
- * mutate the store's internal state through mutable array/object
204
- * fields. Same structuredClone rationale as cloneTierExplain above.
205
- */
206
236
  function cloneLastRecallSnapshot(
207
237
  snapshot: LastRecallSnapshot | null,
208
238
  ): LastRecallSnapshot | null {
209
239
  if (!snapshot) return null;
210
- return structuredClone(snapshot);
240
+ return structuredClone(hydrateLastRecallSnapshot(snapshot));
211
241
  }
212
242
 
243
+
244
+
213
245
  export interface TierMigrationCycleSummary {
214
246
  trigger: "extraction" | "maintenance" | "manual";
215
247
  scanned: number;
@@ -319,8 +351,22 @@ export class LastRecallStore {
319
351
  async load(): Promise<void> {
320
352
  try {
321
353
  const raw = await readFile(this.statePath, "utf-8");
322
- const parsed = JSON.parse(raw) as LastRecallState;
323
- if (parsed && typeof parsed === "object") this.state = parsed;
354
+ const parsed: unknown = JSON.parse(raw);
355
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
356
+ this.state = {};
357
+ return;
358
+ }
359
+ const next: LastRecallState = {};
360
+ for (const [sessionKey, snapshot] of Object.entries(parsed)) {
361
+ if (sessionKey === "__proto__" || sessionKey === "constructor" || sessionKey === "prototype") {
362
+ continue;
363
+ }
364
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
365
+ continue;
366
+ }
367
+ next[sessionKey] = hydrateLastRecallSnapshot(snapshot as LastRecallSnapshot);
368
+ }
369
+ this.state = next;
324
370
  } catch {
325
371
  this.state = {};
326
372
  }
@@ -329,6 +375,7 @@ export class LastRecallStore {
329
375
  get(sessionKey: string): LastRecallSnapshot | null {
330
376
  // Defensive copy: callers must not be able to mutate internal state
331
377
  // by reaching into array/object fields on the returned snapshot.
378
+ if (isUnsafeStateKey(sessionKey)) return null;
332
379
  return cloneLastRecallSnapshot(this.state[sessionKey] ?? null);
333
380
  }
334
381
 
@@ -352,7 +399,8 @@ export class LastRecallStore {
352
399
  async record(opts: {
353
400
  sessionKey: string;
354
401
  query: string;
355
- memoryIds: string[];
402
+ memoryIds?: string[];
403
+ includedMemories?: IncludedMemory[];
356
404
  namespace?: string;
357
405
  recallNamespaces?: string[];
358
406
  traceId?: string;
@@ -386,6 +434,10 @@ export class LastRecallStore {
386
434
  */
387
435
  backendDegradations?: SearchDegradation[];
388
436
  }): Promise<void> {
437
+ if (isUnsafeStateKey(opts.sessionKey)) {
438
+ log.debug("last recall record skipped: unsafe session key");
439
+ return;
440
+ }
389
441
  const now = new Date().toISOString();
390
442
  const queryHash = createHash("sha256").update(opts.query).digest("hex");
391
443
 
@@ -393,13 +445,15 @@ export class LastRecallStore {
393
445
  // cloneLastRecallSnapshot so caller arrays/objects passed in
394
446
  // `opts` cannot retain a live reference to the persisted state and
395
447
  // tear it after `record()` returns.
448
+ const includedMemories = coerceIncludedMemories(opts);
396
449
  const liveSnapshot: LastRecallSnapshot = {
397
450
  sessionKey: opts.sessionKey,
398
451
  recordedAt: now,
399
452
  queryHash,
400
453
  writeNonce: randomUUID(),
401
454
  queryLen: opts.query.length,
402
- memoryIds: opts.memoryIds,
455
+ includedMemories,
456
+ memoryIds: includedMemories.map((memory) => memory.id),
403
457
  namespace: opts.namespace,
404
458
  recallNamespaces: opts.recallNamespaces,
405
459
  traceId: opts.traceId,
@@ -410,8 +464,6 @@ export class LastRecallStore {
410
464
  sourcesUsed: opts.sourcesUsed,
411
465
  budgetsApplied: opts.budgetsApplied,
412
466
  latencyMs: opts.latencyMs,
413
- resultPaths: opts.resultPaths,
414
- resultNamespaces: opts.resultNamespaces,
415
467
  policyVersion: opts.policyVersion,
416
468
  identityInjectionMode: opts.identityInjection?.mode,
417
469
  identityInjectedChars: opts.identityInjection?.injectedChars,
@@ -810,6 +862,7 @@ export class LastRecallStore {
810
862
  tierExplain: RecallTierExplain,
811
863
  expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },
812
864
  ): Promise<void> {
865
+ if (isUnsafeStateKey(sessionKey)) return;
813
866
  const current = this.state[sessionKey];
814
867
  if (!current) return;
815
868
  if (!snapshotMatchesExpectedIdentity(current, expected)) return;
@@ -952,7 +1005,15 @@ export class RecallHandleHistoryStore {
952
1005
  try {
953
1006
  const raw = await readFile(this.statePath, "utf-8");
954
1007
  const parsed = JSON.parse(raw);
955
- if (parsed && typeof parsed === "object") this.state = parsed as typeof this.state;
1008
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1009
+ const next: Record<string, Array<{ at: string; ids: string[] }>> = {};
1010
+ for (const [sessionKey, entries] of Object.entries(parsed)) {
1011
+ if (isUnsafeStateKey(sessionKey)) continue;
1012
+ if (!Array.isArray(entries)) continue;
1013
+ next[sessionKey] = entries;
1014
+ }
1015
+ this.state = next;
1016
+ }
956
1017
  } catch {
957
1018
  this.state = {};
958
1019
  }
@@ -963,7 +1024,7 @@ export class RecallHandleHistoryStore {
963
1024
  * The ring is capped at {@link maxDepth}; older entries drop off the tail.
964
1025
  */
965
1026
  async record(sessionKey: string, memoryIds: readonly string[]): Promise<void> {
966
- if (!sessionKey) return;
1027
+ if (!sessionKey || isUnsafeStateKey(sessionKey)) return;
967
1028
  const ids = memoryIds.filter((id): id is string => typeof id === "string" && id.length > 0);
968
1029
  const entry = { at: new Date().toISOString(), ids };
969
1030
  const prior = this.state[sessionKey] ?? [];
@@ -982,6 +1043,7 @@ export class RecallHandleHistoryStore {
982
1043
  * Empty array when the session has no recorded history.
983
1044
  */
984
1045
  recent(sessionKey: string, depth: number = this.maxDepth): Array<readonly string[]> {
1046
+ if (isUnsafeStateKey(sessionKey)) return [];
985
1047
  const entries = this.state[sessionKey];
986
1048
  if (!entries || entries.length === 0) return [];
987
1049
  const limit = Math.max(0, Math.min(depth, entries.length));
@@ -46,6 +46,6 @@ test("recall reserves one memory chunk that fits both character and token budget
46
46
 
47
47
  const assembled = coordinator.assembleRecallSections(buckets);
48
48
 
49
- assert.deepEqual(assembled.includedMemoryIds, ["latin"]);
49
+ assert.deepEqual(assembled.includedMemories, [{ id: "latin", path: "memories/latin.md" }]);
50
50
  assert.ok(estimateTokenCount(assembled.sections.join("\n\n---\n\n")) <= 50);
51
51
  });
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/recall-state.ts"],"sourcesContent":["import { appendFile, mkdir, readFile, rename, rm, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { log } from \"./logger.js\";\nimport { writeFileAtomically } from \"./maintenance/atomic-file.js\";\nimport { isErrnoCode } from \"./utils/errno.js\";\nimport { withHeldFileLock, type HeldFileLockOptions } from \"./utils/serialize-mutations.js\";\nimport { ensureContainedSpillDir, listContainedSpillFiles } from \"./utils/path-containment.js\";\nimport type { SearchDegradation } from \"./search/port.js\";\nimport type {\n IdentityInjectionMode,\n RecallPlanMode,\n RecallTierExplain,\n} from \"./types.js\";\n\nexport interface LastRecallBudgetSummary {\n requestedTopK?: number;\n appliedTopK: number;\n recallBudgetChars: number;\n maxMemoryTokens: number;\n qmdFetchLimit?: number;\n qmdHybridFetchLimit?: number;\n finalContextChars?: number;\n truncated?: boolean;\n includedSections?: string[];\n omittedSections?: string[];\n includedMemoryIds?: string[];\n includedMemoryPaths?: string[];\n includedMemoryNamespaces?: Array<string | undefined>;\n omittedMemoryIds?: string[];\n}\n\nexport interface LastRecallSnapshot {\n sessionKey: string;\n recordedAt: string;\n queryHash: string;\n queryLen: number;\n memoryIds: string[];\n namespace?: string;\n recallNamespaces?: string[];\n traceId?: string;\n plannerMode?: RecallPlanMode;\n requestedMode?: RecallPlanMode;\n source?: string;\n fallbackUsed?: boolean;\n sourcesUsed?: string[];\n budgetsApplied?: LastRecallBudgetSummary;\n latencyMs?: number;\n resultPaths?: string[];\n resultNamespaces?: Array<string | undefined>;\n policyVersion?: string;\n identityInjectionMode?: IdentityInjectionMode | \"none\";\n identityInjectedChars?: number;\n identityInjectionTruncated?: boolean;\n /**\n * Collision-safe write nonce. Random UUID set on every `record()`\n * call so the observation-mode direct-answer hook can detect stale\n * snapshots and avoid annotating a snapshot that a subsequent recall\n * already replaced (issue #518).\n */\n writeNonce?: string;\n /**\n * Optional tier-level explanation of how recall was served\n * (issue #518). Populated by orchestrator call sites that can\n * identify a concrete tier; surfaces expose the block via\n * `engram query --explain`, the `?explain=1` HTTP flag, and the\n * `remnic_recall_explain` MCP tool. Orthogonal to the existing\n * graph-path `recallExplain` operation.\n */\n tierExplain?: RecallTierExplain;\n /**\n * Backend degradations observed while serving this recall (issue #1536).\n * Present only when a search backend reported unavailable/loading/timeout\n * during the recall — distinguishing \"no matches\" from \"backend could not\n * answer\" (CLAUDE.md rule 34). Deliberately independent of `tierExplain`,\n * which is gated behind `recallDirectAnswerEnabled`.\n */\n backendDegradations?: SearchDegradation[];\n}\n\nexport interface GraphRecallExpandedEntry {\n path: string;\n score: number;\n namespace: string;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Issue #681 PR 3/3 — confidence of the edge that produced this entry's\n * recorded provenance (strongest edge along the chosen entry path).\n * Range `[0, 1]`. Optional so persisted snapshots from older builds\n * round-trip through `clampGraphRecallExpandedEntries` without dropping.\n */\n edgeConfidence?: number;\n /** Graph-relative activation path node ids when provenance is enabled. */\n pathNodeIds?: string[];\n /** True when a graph path penalty was applied. */\n pathPenaltyApplied?: boolean;\n}\n\nexport function clampGraphRecallExpandedEntries(\n entries: unknown,\n maxEntries: number = 64,\n): GraphRecallExpandedEntry[] {\n const limit = Math.max(1, Math.floor(maxEntries));\n if (!Array.isArray(entries)) return [];\n return entries\n .filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\")\n .map((item) => {\n const graphType: \"entity\" | \"time\" | \"causal\" =\n item.graphType === \"entity\" || item.graphType === \"time\" || item.graphType === \"causal\"\n ? item.graphType\n : \"entity\";\n const out: GraphRecallExpandedEntry = {\n path: typeof item.path === \"string\" ? item.path : \"\",\n score: typeof item.score === \"number\" && Number.isFinite(item.score) ? item.score : 0,\n namespace: typeof item.namespace === \"string\" ? item.namespace : \"\",\n seed: typeof item.seed === \"string\" ? item.seed : \"\",\n hopDepth:\n typeof item.hopDepth === \"number\" && Number.isFinite(item.hopDepth)\n ? Math.max(0, Math.floor(item.hopDepth))\n : 0,\n decayedWeight:\n typeof item.decayedWeight === \"number\" && Number.isFinite(item.decayedWeight)\n ? Math.max(0, item.decayedWeight)\n : 0,\n graphType,\n };\n // Issue #681 PR 3/3: clamp `edgeConfidence` into [0, 1] when present.\n // Older snapshots without the field round-trip cleanly via the\n // optional shape; legacy callers always rendered as 1.0.\n if (\n typeof item.edgeConfidence === \"number\" &&\n Number.isFinite(item.edgeConfidence)\n ) {\n out.edgeConfidence = Math.min(1, Math.max(0, item.edgeConfidence));\n }\n if (\n Array.isArray(item.pathNodeIds) &&\n item.pathNodeIds.every((value): value is string => typeof value === \"string\")\n ) {\n out.pathNodeIds = item.pathNodeIds.slice(0, 64);\n }\n if (typeof item.pathPenaltyApplied === \"boolean\") {\n out.pathPenaltyApplied = item.pathPenaltyApplied;\n }\n return out;\n })\n .filter((item) => item.path.length > 0 && item.namespace.length > 0)\n .slice(0, limit);\n}\n\ntype LastRecallState = Record<string, LastRecallSnapshot>;\ntype StateFileWriter = (filePath: string, content: string) => Promise<void>;\n\n/**\n * Deep-copy a RecallTierExplain block. Used by both the write path\n * (so caller mutation after `record()` cannot tear the persisted\n * snapshot) and the read path (so caller mutation after `get()` /\n * `getMostRecent()` cannot tear the in-memory store).\n *\n * Uses structuredClone so future additions to RecallTierExplain do\n * not silently share references through hand-enumerated fields —\n * matching the pattern used elsewhere in the codebase (e.g.,\n * qmd-recall-cache.ts). The payload is pure JSON-shaped data, so\n * structuredClone is both safe and complete here.\n */\n/**\n * Stale-snapshot identity guard shared by the annotate methods (issue #518):\n * a writeNonce match wins outright; otherwise traceId (when expected) and\n * recordedAt are compared. Extracted so every annotation surface applies\n * identical guards (CLAUDE.md rule 22).\n */\nfunction snapshotMatchesExpectedIdentity(\n current: LastRecallSnapshot,\n expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },\n): boolean {\n if (!expected) return true;\n if (typeof expected.writeNonce === \"string\" && expected.writeNonce.length > 0) {\n return current.writeNonce === expected.writeNonce;\n }\n const hasExpectedTraceId =\n typeof expected.traceId === \"string\" && expected.traceId.length > 0;\n if (hasExpectedTraceId) {\n return current.traceId === expected.traceId;\n }\n if (expected.recordedAt !== undefined) {\n return current.recordedAt === expected.recordedAt;\n }\n return true;\n}\n\nfunction cloneTierExplain(\n tierExplain: RecallTierExplain | undefined,\n): RecallTierExplain | undefined {\n if (!tierExplain) return undefined;\n return structuredClone(tierExplain);\n}\n\n/**\n * Deep-copy a LastRecallSnapshot so callers that receive it cannot\n * mutate the store's internal state through mutable array/object\n * fields. Same structuredClone rationale as cloneTierExplain above.\n */\nfunction cloneLastRecallSnapshot(\n snapshot: LastRecallSnapshot | null,\n): LastRecallSnapshot | null {\n if (!snapshot) return null;\n return structuredClone(snapshot);\n}\n\nexport interface TierMigrationCycleSummary {\n trigger: \"extraction\" | \"maintenance\" | \"manual\";\n scanned: number;\n migrated: number;\n promoted: number;\n demoted: number;\n limit: number;\n dryRun: boolean;\n skipped?: string;\n errorCount?: number;\n}\n\nexport interface TierMigrationStatusSnapshot {\n updatedAt: string;\n lastCycle: TierMigrationCycleSummary | null;\n totals: {\n cycles: number;\n scanned: number;\n migrated: number;\n promoted: number;\n demoted: number;\n errors: number;\n };\n}\n\nconst DEFAULT_TIER_MIGRATION_STATUS: TierMigrationStatusSnapshot = {\n updatedAt: new Date(0).toISOString(),\n lastCycle: null,\n totals: {\n cycles: 0,\n scanned: 0,\n migrated: 0,\n promoted: 0,\n demoted: 0,\n errors: 0,\n },\n};\n\n/**\n * Suffix marking an impression spill CLAIMED for commit but not yet deleted.\n * The crash-safe drain renames `<uuid>.jsonl` -> `<uuid>.jsonl.claimed` before\n * committing its rows, mirroring the lifecycle ledger's claim/commit protocol\n * (#2033).\n */\nconst CLAIMED_IMPRESSION_SPILL_SUFFIX = \".claimed\";\n\n/**\n * Outcome of {@link LastRecallStore.drainPendingImpressions}. Distinguishes a\n * completed drain (or nothing pending) from a DEFERRED drain that left durable\n * spills in the offline-sync-EXCLUDED queue, so the caller can tell the\n * data-safe cases apart from the one where an offline-sync snapshot would\n * silently omit recorded impressions (#2033).\n */\nexport interface DrainPendingImpressionsResult {\n /** Pending spill rows were folded into the synced active file this call. */\n folded: boolean;\n /**\n * Durable spill rows remain in the offline-sync-EXCLUDED pending queue after\n * this drain: the rotation lock could not be acquired, a spill could not be\n * claimed, or the drain-only fold left rows that would only fit by rotating\n * into a sync-excluded archive. A snapshot taken now would silently omit them\n * (#2033): the caller MUST treat the active file as INCOMPLETE and retry or\n * abort the snapshot rather than report success. `false` means the active file\n * is complete — every pending row was folded or nothing was pending.\n */\n pendingDeferred: boolean;\n}\n\nexport class LastRecallStore {\n private readonly statePath: string;\n private readonly impressionsPath: string;\n private readonly writeStateFile: StateFileWriter;\n private readonly impressionsRotateBytes: number;\n private readonly impressionsRotateKeep: number;\n // Lock-acquisition timing for the cross-process impression rotation lock.\n // Only tests set this (small maxWaitMs) to force the acquisition-timeout\n // (`acquired=false`) branch deterministically; production uses the defaults.\n private readonly impressionsLockOptions?: Pick<HeldFileLockOptions, \"maxWaitMs\" | \"pollMs\">;\n private state: LastRecallState = {};\n private stateWriteChain: Promise<void> = Promise.resolve();\n // Serializes the rotate-then-append critical section so concurrent record()\n // calls never interleave rotation renames with each other's appends (#1910).\n private impressionsWriteChain: Promise<void> = Promise.resolve();\n\n constructor(\n memoryDir: string,\n options: {\n writeStateFile?: StateFileWriter;\n impressionsRotateBytes?: number;\n impressionsRotateKeep?: number;\n impressionsLockOptions?: Pick<HeldFileLockOptions, \"maxWaitMs\" | \"pollMs\">;\n } = {},\n ) {\n this.statePath = path.join(memoryDir, \"state\", \"last_recall.json\");\n this.impressionsPath = path.join(memoryDir, \"state\", \"recall_impressions.jsonl\");\n // 0 disables rotation (never coerced to a default); keep floors at 1.\n this.impressionsRotateBytes = Math.max(0, Math.floor(options.impressionsRotateBytes ?? 0));\n this.impressionsRotateKeep = Math.max(1, Math.floor(options.impressionsRotateKeep ?? 5));\n this.impressionsLockOptions = options.impressionsLockOptions;\n this.writeStateFile =\n options.writeStateFile ??\n (async (filePath, content) => {\n await writeFileAtomically(filePath, content);\n });\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw) as LastRecallState;\n if (parsed && typeof parsed === \"object\") this.state = parsed;\n } catch {\n this.state = {};\n }\n }\n\n get(sessionKey: string): LastRecallSnapshot | null {\n // Defensive copy: callers must not be able to mutate internal state\n // by reaching into array/object fields on the returned snapshot.\n return cloneLastRecallSnapshot(this.state[sessionKey] ?? null);\n }\n\n getMostRecent(): LastRecallSnapshot | null {\n const snapshots = Object.values(this.state);\n if (snapshots.length === 0) return null;\n // Secondary key on sessionKey keeps the sort stable when two\n // snapshots share a recordedAt timestamp (CLAUDE.md rule 19).\n snapshots.sort((a, b) => {\n const byTime = b.recordedAt.localeCompare(a.recordedAt);\n if (byTime !== 0) return byTime;\n return a.sessionKey.localeCompare(b.sessionKey);\n });\n return cloneLastRecallSnapshot(snapshots[0] ?? null);\n }\n\n /**\n * Persist last-recall snapshot and append an impression log entry.\n * Does not store raw query text; uses a stable hash for correlation.\n */\n async record(opts: {\n sessionKey: string;\n query: string;\n memoryIds: string[];\n namespace?: string;\n recallNamespaces?: string[];\n traceId?: string;\n plannerMode?: RecallPlanMode;\n requestedMode?: RecallPlanMode;\n source?: string;\n fallbackUsed?: boolean;\n sourcesUsed?: string[];\n budgetsApplied?: LastRecallBudgetSummary;\n latencyMs?: number;\n resultPaths?: string[];\n resultNamespaces?: Array<string | undefined>;\n policyVersion?: string;\n appendImpression?: boolean;\n identityInjection?: {\n mode: IdentityInjectionMode | \"none\";\n injectedChars: number;\n truncated: boolean;\n };\n /**\n * Per-tier explain annotation (issue #518). When supplied, the\n * snapshot carries it so downstream surfaces (CLI / HTTP / MCP)\n * can render which retrieval tier served the query.\n */\n tierExplain?: RecallTierExplain;\n /**\n * Backend degradations observed while serving this recall (issue #1536).\n * Passed at record time so the published snapshot is born annotated —\n * a post-record annotation would leave a window where readers see the\n * snapshot without them (codex review on #1544).\n */\n backendDegradations?: SearchDegradation[];\n }): Promise<void> {\n const now = new Date().toISOString();\n const queryHash = createHash(\"sha256\").update(opts.query).digest(\"hex\");\n\n // Build the snapshot from opts, then deep-copy it via\n // cloneLastRecallSnapshot so caller arrays/objects passed in\n // `opts` cannot retain a live reference to the persisted state and\n // tear it after `record()` returns.\n const liveSnapshot: LastRecallSnapshot = {\n sessionKey: opts.sessionKey,\n recordedAt: now,\n queryHash,\n writeNonce: randomUUID(),\n queryLen: opts.query.length,\n memoryIds: opts.memoryIds,\n namespace: opts.namespace,\n recallNamespaces: opts.recallNamespaces,\n traceId: opts.traceId,\n plannerMode: opts.plannerMode,\n requestedMode: opts.requestedMode,\n source: opts.source,\n fallbackUsed: opts.fallbackUsed,\n sourcesUsed: opts.sourcesUsed,\n budgetsApplied: opts.budgetsApplied,\n latencyMs: opts.latencyMs,\n resultPaths: opts.resultPaths,\n resultNamespaces: opts.resultNamespaces,\n policyVersion: opts.policyVersion,\n identityInjectionMode: opts.identityInjection?.mode,\n identityInjectedChars: opts.identityInjection?.injectedChars,\n identityInjectionTruncated: opts.identityInjection?.truncated,\n tierExplain: opts.tierExplain,\n backendDegradations:\n opts.backendDegradations && opts.backendDegradations.length > 0\n ? opts.backendDegradations\n : undefined,\n };\n // `cloneLastRecallSnapshot` handles `null` but that never applies\n // at this call site — the non-null assertion keeps the type\n // checker honest.\n const snapshot = cloneLastRecallSnapshot(liveSnapshot)!;\n\n this.state[opts.sessionKey] = snapshot;\n\n // Keep the state bounded; the impression log is append-only.\n const keys = Object.keys(this.state);\n if (keys.length > 50) {\n const ordered = keys\n .map((k) => ({ k, at: this.state[k]?.recordedAt ?? \"\" }))\n .sort((a, b) => b.at.localeCompare(a.at));\n for (const doomed of ordered.slice(50)) {\n delete this.state[doomed.k];\n }\n }\n\n try {\n await this.flushState();\n } catch (err) {\n log.debug(`last recall store write failed: ${err}`);\n }\n\n if (opts.appendImpression !== false) {\n const line = JSON.stringify(snapshot) + \"\\n\";\n // Chain onto the previous impression write so rotation + append run as one\n // serialized critical section — concurrent record() calls can never\n // interleave a rename with another call's append (#1910). `.catch` before\n // the link keeps a prior failure from poisoning the chain.\n const chained = this.impressionsWriteChain\n .catch(() => {})\n .then(() => this.appendImpressionSerialized(line));\n this.impressionsWriteChain = chained;\n try {\n await chained;\n } catch (err) {\n log.debug(`recall impressions append failed: ${err}`);\n }\n }\n }\n\n /**\n * Drain pending spills, rotate (best-effort, sized to the projected payload),\n * then append one impression line under ONE shared cross-process lock (#1910,\n * #2033). Both the archive-shift renames AND the append run inside the same\n * held lock so a peer process holding the lock can never rename the active\n * inode to `.1` between our open and write — which would land the impression in\n * a rotated archive that offline-sync excludes, silently dropping it from\n * active-state/sync consumers.\n *\n * On lock-acquisition timeout the impression is NEVER written to the active\n * file unlocked (#2033): a peer holding the lock is likely mid-rotation, so an\n * unlocked append can land in the inode it is about to rename to `.1` — the\n * exact silent-drop this lock prevents. Instead the row is spilled to a\n * durable node-local per-event file under `<impressions>.pending.d/` and\n * folded back into the active file by the next append that DOES hold the lock,\n * preserving durability without racing rotation. Rotation failure under the\n * held lock is logged and the append still runs. Callers invoke this only\n * through `impressionsWriteChain` so the sequence is serialized in-process.\n */\n private get impressionsPendingDir(): string {\n return `${this.impressionsPath}.pending.d`;\n }\n\n private async spillImpression(line: string): Promise<void> {\n await ensureContainedSpillDir(this.impressionsPendingDir);\n // Write to a temp name the drain's `.jsonl` lister ignores, then atomically\n // rename to the final `<uuid>.jsonl` (#2033). writeFile creates the path\n // before its bytes are durable, so writing straight to the final name lets a\n // concurrent lock holder's drain read/rename/delete a partial spill and\n // append malformed JSON — permanently losing that impression. The temp lives\n // in the SAME contained dir, so the rename is atomic and stays symlink-safe.\n const id = randomUUID();\n const tempPath = path.join(this.impressionsPendingDir, `${id}.jsonl.tmp`);\n const finalPath = path.join(this.impressionsPendingDir, `${id}.jsonl`);\n await writeFile(tempPath, line, \"utf-8\");\n await rename(tempPath, finalPath);\n }\n\n /**\n * Recover a claim a crashed drain left mid-flight (#2033): the crash-safe\n * drain renames `<uuid>.jsonl` -> `<uuid>.jsonl.claimed` BEFORE committing, so\n * a `.claimed` file with no matching commit is the ONLY durable copy of those\n * rows. Rename each orphan back to `<uuid>.jsonl` so it re-enters the normal\n * collect+claim+commit flow. MUST run under the held rotation lock, before\n * collecting. listContainedSpillFiles skips symlinked/escaping entries.\n */\n private async recoverOrphanedImpressionClaims(): Promise<void> {\n const orphans = await listContainedSpillFiles(\n this.impressionsPendingDir,\n `.jsonl${CLAIMED_IMPRESSION_SPILL_SUFFIX}`,\n );\n for (const claimedPath of orphans) {\n const original = claimedPath.slice(0, -CLAIMED_IMPRESSION_SPILL_SUFFIX.length);\n await rename(claimedPath, original).catch(() => undefined);\n }\n }\n\n /**\n * Recover a crash-orphaned spill temp after its write completed but before\n * the atomic `.tmp` → `.jsonl` rename. Valid JSONL temps are promoted back\n * into the normal queue; incomplete temps remain pending and keep offline sync\n * deferred rather than being discarded.\n */\n private async recoverOrphanedImpressionTemps(): Promise<void> {\n const temps = await listContainedSpillFiles(this.impressionsPendingDir, \".jsonl.tmp\");\n for (const tempPath of temps) {\n let content: string;\n try {\n content = await readFile(tempPath, \"utf-8\");\n for (const line of content.split(\"\\n\")) {\n if (line.trim().length > 0) JSON.parse(line);\n }\n } catch {\n continue;\n }\n const finalPath = tempPath.slice(0, -\".tmp\".length);\n await rename(tempPath, finalPath).catch(() => undefined);\n }\n }\n\n private async appendImpressionSerialized(line: string): Promise<void> {\n await mkdir(path.dirname(this.impressionsPath), { recursive: true });\n // Every active-file write goes under the shared cross-process rotation lock,\n // even when THIS writer's local rotation is disabled (`impressionsRotateBytes\n // <= 0`). A peer process with rotation enabled shares this lock and may\n // rename the active inode to `.1` at any moment, so an unlocked append could\n // land in an offline-sync-excluded archive and be silently dropped (#2033).\n // Only the local rotate DECISION is disabled — the bounded fold skips\n // rotation when this writer's limit is 0 — the lock itself is not.\n const lockPath = `${this.impressionsPath}.lock`;\n await withHeldFileLock(\n lockPath,\n { staleMs: 30_000, ...this.impressionsLockOptions },\n async (acquired) => {\n // withHeldFileLock falls back to task(false) when it cannot acquire the\n // lock within the budget. Do NOT append to the active file unlocked: a\n // peer holding the lock may be mid-rotation, so an unlocked append could\n // land in the inode it renames to `.1` (an offline-sync-excluded\n // archive), silently dropping the impression. Spill it to the durable\n // pending queue instead — the next lock holder folds it back in (#2033).\n if (!acquired) {\n log.debug(\"recall impressions rotation lock not acquired; spilling impression to the durable pending queue\");\n await this.spillImpression(line);\n return;\n }\n await this.foldPendingImpressionsAndAppend(line);\n },\n );\n }\n\n /**\n * Fold any durable pending recall-impression spills into the synced active\n * `recall_impressions.jsonl` WITHOUT recording a new impression (#2033).\n *\n * The pending spill dir is offline-sync-excluded, so an impression that a\n * lock-timed-out `record()` spilled there is absent from an offline-sync\n * snapshot and lost if this node is discarded before the next `record()`\n * folds it back. Offline sync calls this before building a snapshot so a\n * recorded impression always reaches the remote. Fast no-op — no lock and no\n * dir/lock-file creation — when nothing is pending.\n *\n * Returns a {@link DrainPendingImpressionsResult}: `folded` is true when rows\n * were folded into the active file; `pendingDeferred` is true when durable\n * spills still remain in the offline-sync-EXCLUDED queue after this call —\n * because the rotation lock could not be acquired, a spill could not be\n * claimed, or the drain-only fold deferred rows that would only fit by\n * rotating into a sync-excluded archive (#2033). A snapshot taken while\n * `pendingDeferred` is true would silently drop those rows, so the caller MUST\n * NOT report a clean snapshot — it either retries or aborts.\n */\n async drainPendingImpressions(): Promise<DrainPendingImpressionsResult> {\n if (!(await this.pendingSpillsRemain())) {\n return { folded: false, pendingDeferred: false };\n }\n const lockPath = `${this.impressionsPath}.lock`;\n let folded = false;\n let acquiredLock = false;\n let spillsRemain = false;\n await withHeldFileLock(\n lockPath,\n { staleMs: 30_000, ...this.impressionsLockOptions },\n async (acquired) => {\n // A peer holds the lock (mid-rotation or mid-append). We MUST NOT touch\n // the active file unlocked (#2033), so the spills stay in the\n // offline-sync-EXCLUDED pending queue. Report the drain as DEFERRED\n // (pendingDeferred=true) so the caller does not build a snapshot that\n // silently omits them; the next lock holder — or a caller retry — folds\n // them in.\n if (!acquired) return;\n acquiredLock = true;\n folded = await this.foldPendingImpressionsAndAppend(null);\n // Even WITH the lock, a spill the fold could not claim or a `.claimed`\n // orphan a failed commit left behind keeps durable rows in the excluded\n // queue. Treat that as an incomplete drain so the caller retries/aborts\n // rather than snapshotting an active file that omits them (#2033).\n spillsRemain = await this.pendingSpillsRemain();\n },\n );\n return { folded, pendingDeferred: !acquiredLock || spillsRemain };\n }\n\n /**\n * Claim/commit fold of durable pending impression spills into the active file\n * under the held rotation lock (#2033). `line` is a new impression to append\n * after the drained rows, or null for a drain-only pre-sync fold.\n *\n * Each spill is folded as an INDEPENDENT claim -> append -> finalize unit\n * rather than materializing the whole queue as one joined payload and\n * splitting it in a single synchronous pass (#2033). A multi-hundred-MB drain\n * done as one join/split blocks the event loop long enough for\n * `withHeldFileLock`'s ownership-refresh timer to miss its window, so a peer\n * stale-breaks the 30s lock and rotates/appends concurrently — defeating the\n * rotation lock this drain relies on. The per-file `await`s keep the payload\n * bounded to one spill at a time and let the refresh timer fire between files.\n *\n * The DRAIN-ONLY path (`line === null`, run before an offline-sync snapshot)\n * NEVER rotates a drained row into an archive. `recall_impressions.jsonl.*`\n * is offline-sync-EXCLUDED, so rotating a just-drained row into `.1`/`.2` and\n * then deleting its spill would leave that row only in a path sync omits —\n * silently lost when the node is discarded after a \"successful\" sync (#2033).\n * It folds only the rows that fit the synced active file under the cap and\n * leaves the rest durable in the pending queue; {@link drainPendingImpressions}\n * then reports the drain DEFERRED so the caller retries or aborts. The\n * record() path (`line !== null`) keeps rotating normally — its archives stay\n * on a live node that is not being discarded.\n *\n * Recovers any crash-orphaned claim first. Each impression carries a unique\n * writeNonce, so a crash-recovered re-commit is a collapsible duplicate, never\n * a lost row. listContainedSpillFiles rejects symlinked/escaping entries; a\n * spill that cannot be claimed is skipped this pass. An append failure rolls\n * that spill's claim back so the row retries on the next lock holder's drain.\n * Returns true when the active file was written. MUST run under the held\n * rotation lock.\n */\n private async foldPendingImpressionsAndAppend(line: string | null): Promise<boolean> {\n await this.recoverOrphanedImpressionTemps();\n await this.recoverOrphanedImpressionClaims();\n const spillFiles = await listContainedSpillFiles(this.impressionsPendingDir);\n const drainOnly = line === null;\n const cap = this.impressionsRotateBytes;\n let activeSize = 0;\n if (cap > 0) {\n try {\n activeSize = (await stat(this.impressionsPath)).size;\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n let wrote = false;\n for (const filePath of spillFiles) {\n const content = await readFile(filePath, \"utf-8\");\n const unit = content.length === 0 || content.endsWith(\"\\n\") ? content : `${content}\\n`;\n const unitBytes = Buffer.byteLength(unit, \"utf-8\");\n // Drain-only fold must never push a drained row into a sync-excluded\n // archive (#2033). Once the active file cannot take this spill under the\n // cap without rotating, stop: the remaining spills stay durable in the\n // pending queue and the drain reports itself deferred. A lone spill larger\n // than the cap on an empty active file is still folded whole (it cannot be\n // split without corrupting JSONL) so it reaches sync rather than stranding.\n if (drainOnly && cap > 0 && activeSize > 0 && activeSize + unitBytes >= cap) break;\n const claimedPath = `${filePath}${CLAIMED_IMPRESSION_SPILL_SUFFIX}`;\n try {\n await rename(filePath, claimedPath);\n } catch {\n continue; // could not claim → do not commit; a later drain retries it.\n }\n try {\n activeSize = await this.appendImpressionUnit(unit, activeSize, drainOnly);\n } catch (err) {\n // Commit failed: roll this spill's claim back so it retries on the next\n // lock holder's drain instead of being lost.\n await rename(claimedPath, filePath).catch(() => undefined);\n throw err;\n }\n // Commit is durable: delete the claimed file. A delete that fails leaves a\n // `.claimed` orphan the next drain recovers and re-commits — a\n // writeNonce-collapsible duplicate, never a lost row (#2033).\n await unlink(claimedPath).catch(() => undefined);\n wrote = true;\n }\n if (line !== null) {\n activeSize = await this.appendImpressionUnit(line, activeSize, false);\n wrote = true;\n }\n return wrote;\n }\n\n /**\n * Append one whole JSONL unit (a claimed spill's rows or a fresh impression\n * line) to the active impressions file, returning the resulting active-file\n * byte size. On the rotating (record) path, when the unit would push the\n * current active generation to/over `impressionsRotateBytes`, the full active\n * file is rotated aside FIRST so no generation exceeds the cap (#2033); a lone\n * unit larger than the cap on an empty active file is written whole because\n * splitting a JSONL row would corrupt it. `drainOnly` and disabled rotation\n * (`impressionsRotateBytes <= 0`) both skip rotation — drain-only defers its\n * overflow in {@link foldPendingImpressionsAndAppend} rather than rotating into\n * a sync-excluded archive. A rotation error is logged and the append still\n * runs so a row is never lost; an append failure propagates so the caller\n * rolls its claim back. MUST run under the held rotation lock.\n */\n private async appendImpressionUnit(\n unit: string,\n activeSize: number,\n drainOnly: boolean,\n ): Promise<number> {\n const cap = this.impressionsRotateBytes;\n const unitBytes = Buffer.byteLength(unit, \"utf-8\");\n if (cap > 0 && !drainOnly && activeSize > 0 && activeSize + unitBytes >= cap) {\n try {\n await this.shiftImpressionArchives();\n activeSize = 0;\n } catch (err) {\n log.debug(`recall impressions rotation failed (append preserved): ${err}`);\n }\n }\n await appendFile(this.impressionsPath, unit, \"utf-8\");\n return activeSize + unitBytes;\n }\n\n /**\n * True when any live `<uuid>.jsonl` spill, crash-orphaned `.claimed` file,\n * or crash-orphaned `.jsonl.tmp` spill remains in the offline-sync-EXCLUDED\n * pending queue (#2033). After a drain acquires the rotation lock, a spill\n * the fold could not claim (rename race / read-only dir) or a `.claimed`\n * orphan a failed commit left behind means durable rows are STILL excluded\n * from a snapshot — the drain must report itself INCOMPLETE so the caller\n * retries or aborts rather than snapshotting an active file that omits them.\n */\n private async pendingSpillsRemain(): Promise<boolean> {\n if ((await listContainedSpillFiles(this.impressionsPendingDir, \".jsonl.tmp\")).length > 0) {\n return true;\n }\n const liveSpills = await listContainedSpillFiles(this.impressionsPendingDir);\n if (liveSpills.length > 0) return true;\n const claimed = await listContainedSpillFiles(\n this.impressionsPendingDir,\n `.jsonl${CLAIMED_IMPRESSION_SPILL_SUFFIX}`,\n );\n return claimed.length > 0;\n }\n\n /**\n * Shift `.1..N` archives down one slot and move the active file to `.1`,\n * dropping anything beyond `keep`. Callers invoke this only while holding the\n * cross-process rotation lock (issue #1910).\n */\n private async shiftImpressionArchives(): Promise<void> {\n const keep = this.impressionsRotateKeep;\n // Drop the archive that would fall off the end, then shift down: .(keep-1)\n // -> .keep, ..., .1 -> .2, active -> .1.\n try {\n await rm(`${this.impressionsPath}.${keep}`, { force: true });\n } catch {\n // best-effort cleanup of the oldest archive\n }\n for (let i = keep - 1; i >= 1; i -= 1) {\n try {\n await rename(`${this.impressionsPath}.${i}`, `${this.impressionsPath}.${i + 1}`);\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n try {\n await rename(this.impressionsPath, `${this.impressionsPath}.1`);\n } catch (err) {\n if (!isErrnoCode(err, \"ENOENT\")) throw err;\n }\n }\n\n /**\n * Attach a RecallTierExplain block to the existing snapshot for a\n * session without rewriting the entire snapshot. Used by the\n * post-recall direct-answer annotation path (issue #518 slice 3c):\n * recallInternal records the snapshot first, then the orchestrator\n * fires the direct-answer tier in observation mode and annotates\n * the stored snapshot with whichever tier served the query.\n *\n * No-op when no snapshot exists for the given session; callers do\n * not need to guard on existence.\n */\n async annotateTierExplain(\n sessionKey: string,\n tierExplain: RecallTierExplain,\n expected?: { writeNonce?: string; traceId?: string; recordedAt?: string },\n ): Promise<void> {\n const current = this.state[sessionKey];\n if (!current) return;\n if (!snapshotMatchesExpectedIdentity(current, expected)) return;\n this.state[sessionKey] = {\n ...current,\n tierExplain: cloneTierExplain(tierExplain),\n };\n try {\n await this.flushState();\n } catch (err) {\n log.debug(`last recall tier-explain annotate failed: ${err}`);\n }\n }\n\n\n private flushState(): Promise<void> {\n const run = this.stateWriteChain.catch(() => undefined).then(async () => {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await this.writeStateFile(this.statePath, JSON.stringify(this.state, null, 2));\n });\n this.stateWriteChain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n\nexport class TierMigrationStatusStore {\n private readonly statePath: string;\n private state: TierMigrationStatusSnapshot = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n\n constructor(memoryDir: string) {\n this.statePath = path.join(memoryDir, \"state\", \"tier-migration-status.json\");\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<TierMigrationStatusSnapshot> | null;\n if (!parsed || typeof parsed !== \"object\") {\n this.state = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n return;\n }\n const totals = parsed.totals && typeof parsed.totals === \"object\"\n ? parsed.totals\n : DEFAULT_TIER_MIGRATION_STATUS.totals;\n this.state = {\n updatedAt:\n typeof parsed.updatedAt === \"string\" && parsed.updatedAt.length > 0\n ? parsed.updatedAt\n : DEFAULT_TIER_MIGRATION_STATUS.updatedAt,\n lastCycle:\n parsed.lastCycle && typeof parsed.lastCycle === \"object\"\n ? (parsed.lastCycle as TierMigrationCycleSummary)\n : null,\n totals: {\n cycles: typeof totals.cycles === \"number\" && Number.isFinite(totals.cycles) ? totals.cycles : 0,\n scanned: typeof totals.scanned === \"number\" && Number.isFinite(totals.scanned) ? totals.scanned : 0,\n migrated: typeof totals.migrated === \"number\" && Number.isFinite(totals.migrated) ? totals.migrated : 0,\n promoted: typeof totals.promoted === \"number\" && Number.isFinite(totals.promoted) ? totals.promoted : 0,\n demoted: typeof totals.demoted === \"number\" && Number.isFinite(totals.demoted) ? totals.demoted : 0,\n errors: typeof totals.errors === \"number\" && Number.isFinite(totals.errors) ? totals.errors : 0,\n },\n };\n } catch {\n this.state = structuredClone(DEFAULT_TIER_MIGRATION_STATUS);\n }\n }\n\n get(): TierMigrationStatusSnapshot {\n return {\n updatedAt: this.state.updatedAt,\n lastCycle: this.state.lastCycle ? { ...this.state.lastCycle } : null,\n totals: { ...this.state.totals },\n };\n }\n\n async recordCycle(summary: TierMigrationCycleSummary): Promise<void> {\n const now = new Date().toISOString();\n const migratedDelta = summary.dryRun ? 0 : Math.max(0, summary.migrated);\n const promotedDelta = summary.dryRun ? 0 : Math.max(0, summary.promoted);\n const demotedDelta = summary.dryRun ? 0 : Math.max(0, summary.demoted);\n const next: TierMigrationStatusSnapshot = {\n updatedAt: now,\n lastCycle: { ...summary },\n totals: {\n cycles: this.state.totals.cycles + 1,\n scanned: this.state.totals.scanned + Math.max(0, summary.scanned),\n migrated: this.state.totals.migrated + migratedDelta,\n promoted: this.state.totals.promoted + promotedDelta,\n demoted: this.state.totals.demoted + demotedDelta,\n errors: this.state.totals.errors + Math.max(0, summary.errorCount ?? 0),\n },\n };\n this.state = next;\n try {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, JSON.stringify(next, null, 2), \"utf-8\");\n } catch (err) {\n log.debug(`tier migration status write failed: ${err}`);\n }\n }\n}\n\n\n/**\n * Per-session bounded history of recent recall memory-id sets, used ONLY by\n * handle resolution (issue #1582). Distinct from {@link LastRecallStore} —\n * that keeps ONE last snapshot per session; this keeps a small ring (depth N)\n * of the memory-id arrays a session has recalled, newest first, so a handle\n * cited in a later turn still resolves even after a newer recall displaced the\n * \"last\" snapshot.\n *\n * Deliberately lightweight: stores only `string[]` per entry (no full\n * snapshot), capped at `depth` per session and 50 sessions total (rule 27\n * slice/cap guards). Misses are acceptable and tagged at resolution time.\n */\nexport class RecallHandleHistoryStore {\n private readonly statePath: string;\n private readonly writeStateFile: StateFileWriter;\n private state: Record<string, Array<{ at: string; ids: string[] }>> = {};\n private writeChain: Promise<void> = Promise.resolve();\n private readonly maxDepth: number;\n\n constructor(memoryDir: string, options: { writeStateFile?: StateFileWriter; maxDepth?: number } = {}) {\n this.statePath = path.join(memoryDir, \"state\", \"handle_history.json\");\n this.writeStateFile =\n options.writeStateFile ??\n (async (filePath, content) => {\n await writeFileAtomically(filePath, content);\n });\n this.maxDepth =\n typeof options.maxDepth === \"number\" && Number.isFinite(options.maxDepth)\n ? Math.max(1, Math.min(50, Math.floor(options.maxDepth)))\n : 5;\n }\n\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") this.state = parsed as typeof this.state;\n } catch {\n this.state = {};\n }\n }\n\n /**\n * Record one recall's admitted memory ids for a session, newest first.\n * The ring is capped at {@link maxDepth}; older entries drop off the tail.\n */\n async record(sessionKey: string, memoryIds: readonly string[]): Promise<void> {\n if (!sessionKey) return;\n const ids = memoryIds.filter((id): id is string => typeof id === \"string\" && id.length > 0);\n const entry = { at: new Date().toISOString(), ids };\n const prior = this.state[sessionKey] ?? [];\n const next = [entry, ...prior].slice(0, this.maxDepth);\n this.state[sessionKey] = next;\n this.capSessions();\n try {\n await this.flush();\n } catch (err) {\n log.debug(`recall handle history write failed: ${err}`);\n }\n }\n\n /**\n * Return the memory-id arrays for a session, newest first, capped at `depth`.\n * Empty array when the session has no recorded history.\n */\n recent(sessionKey: string, depth: number = this.maxDepth): Array<readonly string[]> {\n const entries = this.state[sessionKey];\n if (!entries || entries.length === 0) return [];\n const limit = Math.max(0, Math.min(depth, entries.length));\n return entries.slice(0, limit).map((e) => e.ids);\n }\n\n /** Test seam: drop all history (used by the corpus-scan hygiene test). */\n clearForTest(): void {\n this.state = {};\n }\n\n private capSessions(): void {\n const keys = Object.keys(this.state);\n if (keys.length <= 50) return;\n const ordered = keys\n .map((k) => ({ k, at: this.state[k]?.[0]?.at ?? \"\" }))\n .sort((a, b) => b.at.localeCompare(a.at));\n for (const doomed of ordered.slice(50)) {\n delete this.state[doomed.k];\n }\n }\n\n private flush(): Promise<void> {\n const run = this.writeChain.catch(() => undefined).then(async () => {\n await mkdir(path.dirname(this.statePath), { recursive: true });\n await this.writeStateFile(this.statePath, JSON.stringify(this.state, null, 2));\n });\n this.writeChain = run.then(() => undefined, () => undefined);\n return run;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,OAAO,UAAU,QAAQ,IAAI,MAAM,QAAQ,iBAAiB;AACjF,OAAO,UAAU;AACjB,SAAS,YAAY,kBAAkB;AAmGhC,SAAS,gCACd,SACA,aAAqB,IACO;AAC5B,QAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,UAAU,CAAC;AAChD,MAAI,CAAC,MAAM,QAA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