@remnic/core 9.3.699 → 9.3.701

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 (285) hide show
  1. package/dist/access-boundary.d.ts +5 -5
  2. package/dist/access-boundary.js +14 -10
  3. package/dist/access-cli.js +30 -28
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +5 -5
  6. package/dist/access-http.js +18 -14
  7. package/dist/access-mcp.d.ts +5 -5
  8. package/dist/access-mcp.js +17 -13
  9. package/dist/access-operations.d.ts +5 -5
  10. package/dist/access-operations.js +16 -12
  11. package/dist/access-schema.js +3 -3
  12. package/dist/{access-service-DftqtNUy.d.ts → access-service-CGVWK6lZ.d.ts} +2 -2
  13. package/dist/access-service.d.ts +5 -5
  14. package/dist/access-service.js +13 -9
  15. package/dist/access-surface-catalog.d.ts +5 -5
  16. package/dist/action-confidence.d.ts +1 -1
  17. package/dist/action-confidence.js +2 -2
  18. package/dist/active-memory-bridge.d.ts +1 -1
  19. package/dist/active-recall.d.ts +1 -1
  20. package/dist/active-recall.js +1 -1
  21. package/dist/behavior-learner.d.ts +1 -1
  22. package/dist/behavior-signals.d.ts +1 -1
  23. package/dist/bootstrap.d.ts +4 -4
  24. package/dist/briefing.d.ts +1 -1
  25. package/dist/briefing.js +7 -3
  26. package/dist/buffer-surprise-report.d.ts +1 -1
  27. package/dist/buffer.d.ts +1 -1
  28. package/dist/calibration.d.ts +1 -1
  29. package/dist/capabilities.d.ts +1 -1
  30. package/dist/{catalog-D7YDNNF7.d.ts → catalog-DBIghceA.d.ts} +27 -53
  31. package/dist/causal-behavior.d.ts +1 -1
  32. package/dist/causal-consolidation.d.ts +1 -1
  33. package/dist/causal-consolidation.js +8 -4
  34. package/dist/causal-consolidation.js.map +1 -1
  35. package/dist/{chunk-E6GOVHHJ.js → chunk-27LQPUMZ.js} +3 -3
  36. package/dist/{chunk-XJNBEDFE.js → chunk-3FAMU5TX.js} +31 -74
  37. package/dist/chunk-3FAMU5TX.js.map +1 -0
  38. package/dist/chunk-3JJWNZTT.js +446 -0
  39. package/dist/chunk-3JJWNZTT.js.map +1 -0
  40. package/dist/{chunk-JYVD2XZ4.js → chunk-4HIAWLA2.js} +58 -25
  41. package/dist/chunk-4HIAWLA2.js.map +1 -0
  42. package/dist/{chunk-A62RAIBN.js → chunk-6W2D6FGG.js} +2 -2
  43. package/dist/{chunk-COEZR6F5.js → chunk-7TAQEPLE.js} +2 -2
  44. package/dist/{chunk-TIVZ4MCG.js → chunk-D75JXBV4.js} +3 -3
  45. package/dist/{chunk-YY2HGKWR.js → chunk-DEDQXIDL.js} +2 -2
  46. package/dist/{chunk-XFG3PVZE.js → chunk-FUCJAZ25.js} +8 -8
  47. package/dist/{chunk-EZWQZYLK.js → chunk-HF4N43Q7.js} +2 -2
  48. package/dist/{chunk-HZ5DRA4Q.js → chunk-HXHKLVAS.js} +20 -20
  49. package/dist/{chunk-AC5LO7IU.js → chunk-I4WBNM3M.js} +7 -1
  50. package/dist/chunk-I4WBNM3M.js.map +1 -0
  51. package/dist/{chunk-QVTSLRKT.js → chunk-IJEZMWKA.js} +3 -3
  52. package/dist/{chunk-ZXUOAFUG.js → chunk-IKNQAGBV.js} +1 -1
  53. package/dist/chunk-IKNQAGBV.js.map +1 -0
  54. package/dist/{chunk-RC3CNIPK.js → chunk-IO5NQEGZ.js} +2 -2
  55. package/dist/{chunk-2ULWWAQH.js → chunk-ISLJ5WIM.js} +2 -2
  56. package/dist/{chunk-2KJG6ZZK.js → chunk-IYOPIG3E.js} +2 -2
  57. package/dist/{chunk-M4DQWUKX.js → chunk-JKOKX3PS.js} +62 -163
  58. package/dist/chunk-JKOKX3PS.js.map +1 -0
  59. package/dist/{chunk-SJQ4HY3E.js → chunk-JO3E5VGS.js} +2 -2
  60. package/dist/{chunk-3LSSFCB4.js → chunk-K4DWSPMW.js} +11 -1
  61. package/dist/chunk-K4DWSPMW.js.map +1 -0
  62. package/dist/{chunk-IZ5E6ZTK.js → chunk-KF4TXW7Z.js} +6 -6
  63. package/dist/{chunk-CQ4PGFMC.js → chunk-KS7WQ4BZ.js} +4 -4
  64. package/dist/chunk-LTJAMRGI.js +286 -0
  65. package/dist/chunk-LTJAMRGI.js.map +1 -0
  66. package/dist/{chunk-PJIHCOGV.js → chunk-MNU5G4TK.js} +2 -2
  67. package/dist/{chunk-2K64VH66.js → chunk-ODTWHSY2.js} +69 -45
  68. package/dist/chunk-ODTWHSY2.js.map +1 -0
  69. package/dist/{chunk-LIWU4QI6.js → chunk-OLOYQZFB.js} +5 -5
  70. package/dist/{chunk-MRFVMSTR.js → chunk-OMNTQPZO.js} +20 -1
  71. package/dist/{chunk-MRFVMSTR.js.map → chunk-OMNTQPZO.js.map} +1 -1
  72. package/dist/{chunk-JI6HWBYL.js → chunk-Q4O3ET6F.js} +2 -2
  73. package/dist/{chunk-N55RJT4N.js → chunk-QP37KL5H.js} +2 -2
  74. package/dist/{chunk-LPIWEKZ3.js → chunk-SDPDU2PM.js} +3 -3
  75. package/dist/{chunk-RIC5U67B.js → chunk-SFMRLXIV.js} +232 -4
  76. package/dist/chunk-SFMRLXIV.js.map +1 -0
  77. package/dist/{chunk-RTN2BLZM.js → chunk-T5QAZIBO.js} +2 -2
  78. package/dist/{chunk-ANZLT74L.js → chunk-TFVVONWD.js} +2 -2
  79. package/dist/{chunk-SIDSEXUG.js → chunk-WFEZUGU5.js} +2 -2
  80. package/dist/{chunk-FSEQXHEZ.js → chunk-XTIRCSIH.js} +2 -2
  81. package/dist/{chunk-XL5RSHZP.js → chunk-YO4MBK3I.js} +2 -2
  82. package/dist/{chunk-AH2JUU6X.js → chunk-Z2YFLXHU.js} +2 -2
  83. package/dist/{chunk-MRX6S22R.js → chunk-ZT7B64BE.js} +2 -2
  84. package/dist/{chunk-UDDSC6PO.js → chunk-ZYNMX6IU.js} +54 -6
  85. package/dist/chunk-ZYNMX6IU.js.map +1 -0
  86. package/dist/{cli-DUMkkdLl.d.ts → cli-D3XeenwN.d.ts} +3 -3
  87. package/dist/cli.d.ts +6 -6
  88. package/dist/cli.js +32 -28
  89. package/dist/compounding/engine.d.ts +1 -1
  90. package/dist/compounding/engine.js +7 -3
  91. package/dist/compounding/preference-consolidator.d.ts +1 -1
  92. package/dist/compression-optimizer.d.ts +1 -1
  93. package/dist/config.d.ts +1 -1
  94. package/dist/config.js +1 -1
  95. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  96. package/dist/connectors/codex-materialize-runner.js +7 -3
  97. package/dist/connectors/codex-materialize.d.ts +1 -1
  98. package/dist/connectors/index.d.ts +1 -1
  99. package/dist/connectors/index.js +7 -3
  100. package/dist/consolidation-provenance-check.d.ts +1 -1
  101. package/dist/consolidation-undo.d.ts +1 -1
  102. package/dist/contradiction/index.d.ts +1 -1
  103. package/dist/conversation-index/backend.d.ts +1 -1
  104. package/dist/conversation-index/chunker.d.ts +1 -1
  105. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  106. package/dist/conversation-index/indexer.d.ts +1 -1
  107. package/dist/conversation-index/search.d.ts +1 -1
  108. package/dist/day-summary.d.ts +1 -1
  109. package/dist/delinearize.d.ts +1 -1
  110. package/dist/direct-answer-wiring.d.ts +1 -1
  111. package/dist/direct-answer.d.ts +1 -1
  112. package/dist/embedding-fallback.d.ts +1 -1
  113. package/dist/enrichment/index.d.ts +1 -1
  114. package/dist/entity-retrieval.d.ts +1 -1
  115. package/dist/entity-retrieval.js +7 -3
  116. package/dist/entity-schema.d.ts +1 -1
  117. package/dist/explicit-capture.d.ts +6 -6
  118. package/dist/extraction-faithfulness.d.ts +1 -1
  119. package/dist/extraction-judge-telemetry.d.ts +1 -1
  120. package/dist/extraction-judge-training.d.ts +1 -1
  121. package/dist/extraction-judge.d.ts +1 -1
  122. package/dist/extraction.d.ts +1 -1
  123. package/dist/fallback-llm.d.ts +1 -1
  124. package/dist/{forget-PLR6J5DN.js → forget-6SOIPUMQ.js} +32 -1
  125. package/dist/forget-6SOIPUMQ.js.map +1 -0
  126. package/dist/identity-continuity.d.ts +1 -1
  127. package/dist/importance.d.ts +1 -1
  128. package/dist/index.d.ts +21 -10
  129. package/dist/index.js +65 -43
  130. package/dist/index.js.map +1 -1
  131. package/dist/intent.d.ts +1 -1
  132. package/dist/lcm/engine.d.ts +1 -1
  133. package/dist/lcm/index.d.ts +1 -1
  134. package/dist/lcm/tools.d.ts +1 -1
  135. package/dist/lifecycle.d.ts +1 -1
  136. package/dist/live-connectors-runner.d.ts +1 -1
  137. package/dist/local-llm.d.ts +1 -1
  138. package/dist/maintenance/memory-governance.d.ts +1 -1
  139. package/dist/maintenance/memory-governance.js +7 -3
  140. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -3
  141. package/dist/maintenance/rebuild-memory-projection.js +8 -4
  142. package/dist/mcp-memory-inspector-app.d.ts +5 -5
  143. package/dist/memory-action-policy.d.ts +1 -1
  144. package/dist/memory-cache.d.ts +1 -1
  145. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  146. package/dist/memory-projection-store.d.ts +1 -1
  147. package/dist/memory-provenance.d.ts +1 -1
  148. package/dist/memory-provenance.js +1 -1
  149. package/dist/memory-worth-outcomes.d.ts +1 -1
  150. package/dist/models-json.d.ts +1 -1
  151. package/dist/namespaces/migrate.d.ts +2 -2
  152. package/dist/namespaces/migrate.js +8 -4
  153. package/dist/namespaces/principal.d.ts +1 -1
  154. package/dist/namespaces/search.d.ts +1 -1
  155. package/dist/namespaces/storage.d.ts +32 -3
  156. package/dist/namespaces/storage.js +7 -3
  157. package/dist/native-knowledge.d.ts +1 -1
  158. package/dist/operator-toolkit.d.ts +19 -2
  159. package/dist/operator-toolkit.js +17 -11
  160. package/dist/orchestration/maintenance.d.ts +2 -2
  161. package/dist/orchestration/maintenance.js +9 -5
  162. package/dist/{orchestrator-Dv8JQu3-.d.ts → orchestrator-BzMCZlKn.d.ts} +3 -3
  163. package/dist/orchestrator.d.ts +4 -4
  164. package/dist/orchestrator.js +22 -20
  165. package/dist/patterns-cli.d.ts +1 -1
  166. package/dist/policy-runtime.d.ts +1 -1
  167. package/dist/provenance.d.ts +1 -1
  168. package/dist/qmd-recall-cache.d.ts +1 -1
  169. package/dist/qmd.d.ts +1 -1
  170. package/dist/recall-disclosure-escalation.d.ts +1 -1
  171. package/dist/recall-explain-renderer.d.ts +1 -1
  172. package/dist/recall-explain-renderer.js +4 -4
  173. package/dist/recall-planner-llm.d.ts +1 -1
  174. package/dist/recall-state.d.ts +1 -1
  175. package/dist/recall-tag-filter.d.ts +1 -1
  176. package/dist/recall-xray-cli.d.ts +1 -1
  177. package/dist/recall-xray-cli.js +5 -5
  178. package/dist/recall-xray-renderer.d.ts +1 -1
  179. package/dist/recall-xray-renderer.js +4 -4
  180. package/dist/recall-xray.d.ts +1 -1
  181. package/dist/recall-xray.js +3 -3
  182. package/dist/resolve-auth-token.d.ts +1 -1
  183. package/dist/resume-bundles.js +2 -2
  184. package/dist/retrieval-agents.d.ts +1 -1
  185. package/dist/retrieval-tiers.d.ts +1 -1
  186. package/dist/routing/engine.d.ts +1 -1
  187. package/dist/routing/store.d.ts +1 -1
  188. package/dist/schemas.d.ts +28 -28
  189. package/dist/search/embed-helper.d.ts +1 -1
  190. package/dist/search/factory.d.ts +1 -1
  191. package/dist/search/index.d.ts +1 -1
  192. package/dist/search/lancedb-backend.d.ts +1 -1
  193. package/dist/search/meilisearch-backend.d.ts +1 -1
  194. package/dist/search/noop-backend.d.ts +1 -1
  195. package/dist/search/orama-backend.d.ts +1 -1
  196. package/dist/search/port.d.ts +1 -1
  197. package/dist/search/remote-backend.d.ts +1 -1
  198. package/dist/{semantic-consolidation-CgREi9E0.d.ts → semantic-consolidation-BtUfv-AL.d.ts} +1 -1
  199. package/dist/semantic-consolidation.d.ts +2 -2
  200. package/dist/semantic-consolidation.js +8 -4
  201. package/dist/semantic-rule-promotion.js +7 -3
  202. package/dist/semantic-rule-verifier.d.ts +1 -1
  203. package/dist/semantic-rule-verifier.js +7 -3
  204. package/dist/session-observer-bands.d.ts +1 -1
  205. package/dist/session-observer-state.d.ts +1 -1
  206. package/dist/shared-context/manager.d.ts +1 -1
  207. package/dist/signal.d.ts +1 -1
  208. package/dist/storage.d.ts +306 -2
  209. package/dist/storage.js +6 -2
  210. package/dist/summarizer.d.ts +1 -1
  211. package/dist/summarizer.js +3 -2
  212. package/dist/summary-snapshot.d.ts +1 -1
  213. package/dist/summary-snapshot.js +2 -1
  214. package/dist/temporal-supersession.d.ts +1 -1
  215. package/dist/temporal-supersession.js +1 -1
  216. package/dist/temporal-validity.d.ts +1 -1
  217. package/dist/threading.d.ts +1 -1
  218. package/dist/tier-migration.d.ts +1 -1
  219. package/dist/tier-routing.d.ts +1 -1
  220. package/dist/topics.d.ts +1 -1
  221. package/dist/transcript.d.ts +1 -1
  222. package/dist/transfer/types.d.ts +12 -12
  223. package/dist/{types-CeZYSC-E.d.ts → types-PuiPZ9iE.d.ts} +34 -1
  224. package/dist/types.d.ts +1 -1
  225. package/dist/types.js +1 -1
  226. package/dist/utility-runtime.d.ts +1 -1
  227. package/dist/utils/serialize-mutations.js +5 -280
  228. package/dist/utils/serialize-mutations.js.map +1 -1
  229. package/dist/verified-recall.js +7 -3
  230. package/package.json +2 -2
  231. package/src/config.ts +10 -0
  232. package/src/lifecycle/tombstones.test.ts +355 -0
  233. package/src/lifecycle/tombstones.ts +807 -0
  234. package/src/maintenance/forget.ts +41 -0
  235. package/src/maintenance/pattern-reinforcement.ts +47 -0
  236. package/src/memory-provenance.ts +12 -0
  237. package/src/namespaces/catalog.test.ts +222 -14
  238. package/src/namespaces/catalog.ts +54 -187
  239. package/src/namespaces/storage.ts +120 -80
  240. package/src/operator-toolkit.ts +77 -0
  241. package/src/orchestrator.ts +16 -0
  242. package/src/review/index.ts +48 -3
  243. package/src/storage.ts +329 -2
  244. package/src/summary-snapshot.test.ts +63 -1
  245. package/src/summary-snapshot.ts +61 -80
  246. package/src/temporal-supersession.ts +38 -0
  247. package/src/types.ts +34 -0
  248. package/src/utils/serialize-mutations.ts +10 -6
  249. package/dist/chunk-2K64VH66.js.map +0 -1
  250. package/dist/chunk-3LSSFCB4.js.map +0 -1
  251. package/dist/chunk-AC5LO7IU.js.map +0 -1
  252. package/dist/chunk-JYVD2XZ4.js.map +0 -1
  253. package/dist/chunk-M4DQWUKX.js.map +0 -1
  254. package/dist/chunk-RIC5U67B.js.map +0 -1
  255. package/dist/chunk-UDDSC6PO.js.map +0 -1
  256. package/dist/chunk-XJNBEDFE.js.map +0 -1
  257. package/dist/chunk-ZXUOAFUG.js.map +0 -1
  258. package/dist/forget-PLR6J5DN.js.map +0 -1
  259. /package/dist/{chunk-E6GOVHHJ.js.map → chunk-27LQPUMZ.js.map} +0 -0
  260. /package/dist/{chunk-A62RAIBN.js.map → chunk-6W2D6FGG.js.map} +0 -0
  261. /package/dist/{chunk-COEZR6F5.js.map → chunk-7TAQEPLE.js.map} +0 -0
  262. /package/dist/{chunk-TIVZ4MCG.js.map → chunk-D75JXBV4.js.map} +0 -0
  263. /package/dist/{chunk-YY2HGKWR.js.map → chunk-DEDQXIDL.js.map} +0 -0
  264. /package/dist/{chunk-XFG3PVZE.js.map → chunk-FUCJAZ25.js.map} +0 -0
  265. /package/dist/{chunk-EZWQZYLK.js.map → chunk-HF4N43Q7.js.map} +0 -0
  266. /package/dist/{chunk-HZ5DRA4Q.js.map → chunk-HXHKLVAS.js.map} +0 -0
  267. /package/dist/{chunk-QVTSLRKT.js.map → chunk-IJEZMWKA.js.map} +0 -0
  268. /package/dist/{chunk-RC3CNIPK.js.map → chunk-IO5NQEGZ.js.map} +0 -0
  269. /package/dist/{chunk-2ULWWAQH.js.map → chunk-ISLJ5WIM.js.map} +0 -0
  270. /package/dist/{chunk-2KJG6ZZK.js.map → chunk-IYOPIG3E.js.map} +0 -0
  271. /package/dist/{chunk-SJQ4HY3E.js.map → chunk-JO3E5VGS.js.map} +0 -0
  272. /package/dist/{chunk-IZ5E6ZTK.js.map → chunk-KF4TXW7Z.js.map} +0 -0
  273. /package/dist/{chunk-CQ4PGFMC.js.map → chunk-KS7WQ4BZ.js.map} +0 -0
  274. /package/dist/{chunk-PJIHCOGV.js.map → chunk-MNU5G4TK.js.map} +0 -0
  275. /package/dist/{chunk-LIWU4QI6.js.map → chunk-OLOYQZFB.js.map} +0 -0
  276. /package/dist/{chunk-JI6HWBYL.js.map → chunk-Q4O3ET6F.js.map} +0 -0
  277. /package/dist/{chunk-N55RJT4N.js.map → chunk-QP37KL5H.js.map} +0 -0
  278. /package/dist/{chunk-LPIWEKZ3.js.map → chunk-SDPDU2PM.js.map} +0 -0
  279. /package/dist/{chunk-RTN2BLZM.js.map → chunk-T5QAZIBO.js.map} +0 -0
  280. /package/dist/{chunk-ANZLT74L.js.map → chunk-TFVVONWD.js.map} +0 -0
  281. /package/dist/{chunk-SIDSEXUG.js.map → chunk-WFEZUGU5.js.map} +0 -0
  282. /package/dist/{chunk-FSEQXHEZ.js.map → chunk-XTIRCSIH.js.map} +0 -0
  283. /package/dist/{chunk-XL5RSHZP.js.map → chunk-YO4MBK3I.js.map} +0 -0
  284. /package/dist/{chunk-AH2JUU6X.js.map → chunk-Z2YFLXHU.js.map} +0 -0
  285. /package/dist/{chunk-MRX6S22R.js.map → chunk-ZT7B64BE.js.map} +0 -0
@@ -0,0 +1,446 @@
1
+ import {
2
+ serializeMutations
3
+ } from "./chunk-LTJAMRGI.js";
4
+
5
+ // src/lifecycle/tombstones.ts
6
+ var TOMBSTONE_PREFIX = "tomb";
7
+ function newTombstoneId() {
8
+ return `${TOMBSTONE_PREFIX}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
9
+ }
10
+ function keyedTierKey(namespace, entityRef, supersessionKey) {
11
+ return `${namespace}\0${entityRef}\0${supersessionKey}`;
12
+ }
13
+ function parseTombstoneLine(line) {
14
+ const trimmed = line.trim();
15
+ if (trimmed.length === 0) return null;
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(trimmed);
19
+ } catch {
20
+ return null;
21
+ }
22
+ if (!parsed || typeof parsed !== "object") return null;
23
+ const e = parsed;
24
+ if (typeof e.id !== "string" || e.id.length === 0) return null;
25
+ if (e.kind !== "tombstone" && e.kind !== "revocation") return null;
26
+ if (e.reason !== "correction" && e.reason !== "supersession" && e.reason !== "retraction" && e.reason !== "contradiction_resolution") {
27
+ return null;
28
+ }
29
+ if (typeof e.sourceMemoryId !== "string") return null;
30
+ if (typeof e.contentHash !== "string") return null;
31
+ if (typeof e.normalizedText !== "string") return null;
32
+ if (typeof e.namespace !== "string") return null;
33
+ if (typeof e.createdAt !== "string") return null;
34
+ if (e.createdBy !== "user_correction" && e.createdBy !== "contradiction_resolution" && e.createdBy !== "supersession" && e.createdBy !== "chat") {
35
+ return null;
36
+ }
37
+ const out = {
38
+ id: e.id,
39
+ kind: e.kind,
40
+ reason: e.reason,
41
+ sourceMemoryId: e.sourceMemoryId,
42
+ contentHash: e.contentHash,
43
+ normalizedText: e.normalizedText,
44
+ namespace: e.namespace,
45
+ createdAt: e.createdAt,
46
+ createdBy: e.createdBy
47
+ };
48
+ if (typeof e.entityRef === "string") out.entityRef = e.entityRef;
49
+ if (typeof e.supersessionKey === "string") out.supersessionKey = e.supersessionKey;
50
+ if (typeof e.revokes === "string") out.revokes = e.revokes;
51
+ return out;
52
+ }
53
+ var TombstoneStore = class {
54
+ constructor(filePath, namespace, options, io) {
55
+ this.filePath = filePath;
56
+ this.namespace = namespace;
57
+ this.options = options;
58
+ this.io = io;
59
+ }
60
+ filePath;
61
+ namespace;
62
+ options;
63
+ io;
64
+ entries = [];
65
+ /** contentHash → tombstone id (newest) — exact tier. */
66
+ byHash = /* @__PURE__ */ new Map();
67
+ /** normalizedText → tombstone id (newest) — normalized tier. */
68
+ byNormalized = /* @__PURE__ */ new Map();
69
+ /** entityRef\0supersessionKey → tombstone id (newest) — keyed tier. */
70
+ byKey = /* @__PURE__ */ new Map();
71
+ /** Tombstone ids that have a later revocation entry. */
72
+ revokedIds = /* @__PURE__ */ new Set();
73
+ /** id → entry index (newest only, for revocation lookups). */
74
+ byId = /* @__PURE__ */ new Map();
75
+ loaded = false;
76
+ loadPromise = null;
77
+ corruptedLines = 0;
78
+ lastAppendAt = null;
79
+ /**
80
+ * Last-seen mtime of the JSONL file (cross-process staleness probe, #1579).
81
+ * Tracked inside the store so the StorageManager wiring stays thin. When the
82
+ * file's mtime advances past this value between accesses, the in-memory index
83
+ * is stale (a peer process appended) and is reloaded before the next lookup.
84
+ */
85
+ fileMtimeMs = 0;
86
+ /** Lazy load + build the in-memory index. Idempotent. */
87
+ async load() {
88
+ if (this.loaded) return;
89
+ if (this.loadPromise) return this.loadPromise;
90
+ this.loadPromise = this.loadInternal();
91
+ try {
92
+ await this.loadPromise;
93
+ } finally {
94
+ this.loadPromise = null;
95
+ }
96
+ }
97
+ async loadInternal() {
98
+ this.recordFileMtime();
99
+ let raw;
100
+ try {
101
+ raw = await this.io.read(this.filePath);
102
+ } catch (err) {
103
+ const code = err?.code;
104
+ if (code !== "ENOENT") {
105
+ }
106
+ this.loaded = true;
107
+ return;
108
+ }
109
+ this.resetIndex();
110
+ let corrupted = 0;
111
+ for (const line of raw.split("\n")) {
112
+ const entry = parseTombstoneLine(line);
113
+ if (!entry) {
114
+ if (line.trim().length > 0) corrupted += 1;
115
+ continue;
116
+ }
117
+ this.indexEntry(entry);
118
+ }
119
+ this.corruptedLines = corrupted;
120
+ this.loaded = true;
121
+ }
122
+ resetIndex() {
123
+ this.entries = [];
124
+ this.byHash.clear();
125
+ this.byNormalized.clear();
126
+ this.byKey.clear();
127
+ this.revokedIds.clear();
128
+ this.byId.clear();
129
+ }
130
+ /**
131
+ * Index an entry. Later entries (higher array index = newer createdAt)
132
+ * OVERRIDE earlier ones at each tier key — the newest matching entry wins
133
+ * (rule 25). Revocation entries mark their target as revoked.
134
+ */
135
+ indexEntry(entry) {
136
+ this.entries.push(entry);
137
+ this.byId.set(entry.id, entry);
138
+ if (entry.createdAt > (this.lastAppendAt ?? "")) {
139
+ this.lastAppendAt = entry.createdAt;
140
+ }
141
+ if (entry.kind === "revocation") {
142
+ if (entry.revokes) this.revokedIds.add(entry.revokes);
143
+ return;
144
+ }
145
+ const ns = entry.namespace;
146
+ if (entry.contentHash) this.byHash.set(`${ns}\0${entry.contentHash}`, entry.id);
147
+ if (entry.normalizedText) this.byNormalized.set(`${ns}\0${entry.normalizedText}`, entry.id);
148
+ if (entry.entityRef && entry.supersessionKey) {
149
+ this.byKey.set(keyedTierKey(ns, entry.entityRef, entry.supersessionKey), entry.id);
150
+ }
151
+ }
152
+ /** Invalidate the in-memory cache (rule 25). The next access reloads. */
153
+ invalidate() {
154
+ this.loaded = false;
155
+ this.loadPromise = null;
156
+ this.resetIndex();
157
+ }
158
+ /**
159
+ * Cross-process staleness probe (#1579). If the file's mtime advanced since
160
+ * the last load/own-write, a peer process appended and our in-memory index is
161
+ * stale — invalidate AND reload in place so the next lookup sees the new
162
+ * entries. Best-effort: a stat error is swallowed (the loaded index is
163
+ * retained rather than crashing the write path). No-op when no `stat` was
164
+ * injected or when the mtime is unchanged. After our own append/revoke/rebuild
165
+ * `markWritten` records the new mtime, so this probe does not fire for our
166
+ * own writes (only for peer-process appends).
167
+ */
168
+ async ensureFreshAgainstDisk() {
169
+ if (!this.io.stat) return;
170
+ let mtimeMs;
171
+ try {
172
+ mtimeMs = Math.floor(this.io.stat(this.filePath).mtimeMs);
173
+ } catch {
174
+ return;
175
+ }
176
+ if (mtimeMs === this.fileMtimeMs && this.loaded) return;
177
+ this.fileMtimeMs = mtimeMs;
178
+ this.invalidate();
179
+ await this.load();
180
+ }
181
+ /**
182
+ * Record the file mtime after THIS process writes (append / revoke / rebuild)
183
+ * so `ensureFreshAgainstDisk` does not treat our own write as a peer append
184
+ * and throw away the just-updated in-memory index (#1579 — avoids a needless
185
+ * invalidate+reload in the hot write path).
186
+ */
187
+ markWritten() {
188
+ this.recordFileMtime();
189
+ }
190
+ recordFileMtime() {
191
+ if (!this.io.stat) return;
192
+ try {
193
+ this.fileMtimeMs = Math.floor(this.io.stat(this.filePath).mtimeMs);
194
+ } catch {
195
+ }
196
+ }
197
+ /**
198
+ * Append a tombstone entry. Serialized via `serializeMutations` keyed by
199
+ * file path so concurrent appends do not interleave, with rejection recovery
200
+ * (rule 40 — a single failed append never poisons the chain). The in-memory
201
+ * index is updated AFTER the durable append succeeds.
202
+ *
203
+ * Returns the new tombstone id.
204
+ */
205
+ async appendTombstone(input) {
206
+ await this.load();
207
+ const createdAt = input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
208
+ const id = newTombstoneId();
209
+ const entry = {
210
+ id,
211
+ kind: "tombstone",
212
+ reason: input.reason,
213
+ sourceMemoryId: input.sourceMemoryId,
214
+ contentHash: input.contentHash ?? this.options.hashContent(input.rawContent),
215
+ normalizedText: this.options.normalizeText(input.rawContent),
216
+ ...input.entityRef ? { entityRef: input.entityRef } : {},
217
+ ...input.supersessionKey ? { supersessionKey: input.supersessionKey } : {},
218
+ namespace: this.namespace,
219
+ createdAt,
220
+ createdBy: input.createdBy
221
+ };
222
+ await this.serializeAppend(entry);
223
+ this.indexEntry(entry);
224
+ this.markWritten();
225
+ return id;
226
+ }
227
+ /**
228
+ * Append a revocation entry referencing `tombstoneId`. The log is
229
+ * append-only; lookup treats a revoked tombstone as re-allowed (rule 25).
230
+ */
231
+ async revoke(tombstoneId, createdBy) {
232
+ await this.load();
233
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
234
+ const id = newTombstoneId();
235
+ const entry = {
236
+ id,
237
+ kind: "revocation",
238
+ reason: "correction",
239
+ sourceMemoryId: "",
240
+ contentHash: "",
241
+ normalizedText: "",
242
+ namespace: this.namespace,
243
+ createdAt,
244
+ createdBy,
245
+ revokes: tombstoneId
246
+ };
247
+ await this.serializeAppend(entry);
248
+ this.indexEntry(entry);
249
+ this.markWritten();
250
+ return id;
251
+ }
252
+ serializeAppend(entry) {
253
+ const line = JSON.stringify(entry) + "\n";
254
+ return serializeMutations(
255
+ `tombstone:${this.filePath}`,
256
+ () => this.io.append(this.filePath, line)
257
+ );
258
+ }
259
+ /**
260
+ * Look up whether `query` is blocked by an active (non-revoked) tombstone.
261
+ * Tiers are checked in order: exact (contentHash) → normalized → keyed →
262
+ * semantic (off by default). Returns the first active match, or `null`.
263
+ *
264
+ * Namespace isolation (rule 42): only entries with `namespace === query.namespace`
265
+ * match. The store is per-namespace, so this is belt-and-suspenders.
266
+ */
267
+ lookup(query) {
268
+ if (!this.options.enabled) return null;
269
+ if (!this.loaded) return null;
270
+ const ns = query.namespace;
271
+ if (query.contentHash) {
272
+ const id = this.byHash.get(`${ns}\0${query.contentHash}`);
273
+ if (id && !this.revokedIds.has(id)) {
274
+ const entry = this.byId.get(id);
275
+ if (entry && entry.namespace === ns) {
276
+ return { tombstoneId: id, matchedTier: "exact", reason: entry.reason };
277
+ }
278
+ }
279
+ }
280
+ if (query.normalizedText) {
281
+ const id = this.byNormalized.get(`${ns}\0${query.normalizedText}`);
282
+ if (id && !this.revokedIds.has(id)) {
283
+ const entry = this.byId.get(id);
284
+ if (entry && entry.namespace === ns) {
285
+ return { tombstoneId: id, matchedTier: "normalized", reason: entry.reason };
286
+ }
287
+ }
288
+ }
289
+ if (query.entityRef) {
290
+ const keysToCheck = [];
291
+ if (query.supersessionKey) keysToCheck.push(query.supersessionKey);
292
+ if (query.supersessionKeys) {
293
+ for (const k of query.supersessionKeys) {
294
+ if (!keysToCheck.includes(k)) keysToCheck.push(k);
295
+ }
296
+ }
297
+ for (const key of keysToCheck) {
298
+ const id = this.byKey.get(keyedTierKey(ns, query.entityRef, key));
299
+ if (id && !this.revokedIds.has(id)) {
300
+ const entry = this.byId.get(id);
301
+ if (entry && entry.namespace === ns) {
302
+ return { tombstoneId: id, matchedTier: "keyed", reason: entry.reason };
303
+ }
304
+ }
305
+ }
306
+ }
307
+ if (this.options.semanticMatch && this.options.semanticSimilarity && query.normalizedText) {
308
+ const threshold = this.options.semanticThreshold;
309
+ let best = null;
310
+ for (const entry of this.entries) {
311
+ if (entry.kind !== "tombstone") continue;
312
+ if (entry.namespace !== query.namespace) continue;
313
+ if (this.revokedIds.has(entry.id)) continue;
314
+ if (!entry.normalizedText) continue;
315
+ const score = this.options.semanticSimilarity(query.normalizedText, entry.normalizedText);
316
+ if (score >= threshold && (!best || score > best.score)) {
317
+ best = { id: entry.id, reason: entry.reason, score };
318
+ }
319
+ }
320
+ if (best) {
321
+ return { tombstoneId: best.id, matchedTier: "semantic", reason: best.reason };
322
+ }
323
+ }
324
+ return null;
325
+ }
326
+ /** Aggregate stats for the doctor / x-ray surfaces. */
327
+ stats() {
328
+ let active = 0;
329
+ for (const entry of this.entries) {
330
+ if (entry.kind === "tombstone" && !this.revokedIds.has(entry.id)) active += 1;
331
+ }
332
+ return {
333
+ count: active,
334
+ revoked: this.revokedIds.size,
335
+ lastAppendAt: this.lastAppendAt,
336
+ corruptedLines: this.corruptedLines,
337
+ loaded: this.loaded
338
+ };
339
+ }
340
+ /** Read-only snapshot of all entries (for rebuild + tests). */
341
+ snapshot() {
342
+ return this.entries;
343
+ }
344
+ /**
345
+ * Rebuild the in-memory index + JSONL from the supplied retired-memory
346
+ * records + existing entries (preserving revocations). Byte-stable: entries
347
+ * are sorted by (createdAt, id) before write (rule 38).
348
+ *
349
+ * Returns the count of tombstone entries written.
350
+ */
351
+ async rebuild(retiredMemories) {
352
+ const existingRevocations = this.entries.filter((e) => e.kind === "revocation");
353
+ const foreignTombstones = this.entries.filter(
354
+ (e) => e.kind === "tombstone" && e.namespace !== this.namespace
355
+ );
356
+ const existingBySource = /* @__PURE__ */ new Map();
357
+ for (const e of this.entries) {
358
+ if (e.kind === "tombstone") {
359
+ existingBySource.set(`${e.sourceMemoryId}\0${e.supersessionKey ?? ""}`, e.id);
360
+ }
361
+ }
362
+ const rebuilt = retiredMemories.map((m) => ({
363
+ id: existingBySource.get(`${m.memoryId}\0${m.supersessionKey ?? ""}`) ?? newTombstoneId(),
364
+ kind: "tombstone",
365
+ reason: m.reason,
366
+ sourceMemoryId: m.memoryId,
367
+ contentHash: m.contentHash ?? this.options.hashContent(m.rawContent),
368
+ normalizedText: this.options.normalizeText(m.rawContent),
369
+ ...m.entityRef ? { entityRef: m.entityRef } : {},
370
+ ...m.supersessionKey ? { supersessionKey: m.supersessionKey } : {},
371
+ namespace: this.namespace,
372
+ createdAt: m.createdAt,
373
+ createdBy: m.createdBy
374
+ }));
375
+ rebuilt.sort(
376
+ (a, b) => a.createdAt === b.createdAt ? a.id < b.id ? -1 : a.id > b.id ? 1 : 0 : a.createdAt < b.createdAt ? -1 : 1
377
+ );
378
+ const all = [...rebuilt, ...existingRevocations, ...foreignTombstones].sort(
379
+ (a, b) => a.createdAt === b.createdAt ? a.id < b.id ? -1 : a.id > b.id ? 1 : 0 : a.createdAt < b.createdAt ? -1 : 1
380
+ );
381
+ const serialized = all.map((e) => JSON.stringify(e)).join("\n") + (all.length > 0 ? "\n" : "");
382
+ await serializeMutations(
383
+ `tombstone-rebuild:${this.filePath}`,
384
+ () => this.io.write(this.filePath, serialized)
385
+ );
386
+ this.resetIndex();
387
+ for (const entry of all) this.indexEntry(entry);
388
+ this.corruptedLines = 0;
389
+ this.loaded = true;
390
+ this.markWritten();
391
+ return rebuilt.length;
392
+ }
393
+ };
394
+ function collectRetiredMemoriesForRebuild(memories, deps) {
395
+ const retired = [];
396
+ for (const m of memories) {
397
+ const status = m.frontmatter.status;
398
+ if (status !== "superseded" && status !== "rejected" && status !== "forgotten") continue;
399
+ if (m.frontmatter.category !== "fact") continue;
400
+ const reason = status === "superseded" ? "supersession" : status === "forgotten" ? "retraction" : "correction";
401
+ const createdBy = reason === "supersession" ? "supersession" : "user_correction";
402
+ const entityRef = m.frontmatter.entityRef;
403
+ const keys = entityRef && m.frontmatter.structuredAttributes ? deps.supersessionKeysForFact({
404
+ entityRef,
405
+ structuredAttributes: m.frontmatter.structuredAttributes
406
+ }) : [];
407
+ const keysToEmit = keys.length > 0 ? keys : [void 0];
408
+ for (const key of keysToEmit) {
409
+ retired.push({
410
+ memoryId: m.frontmatter.id,
411
+ rawContent: deps.stripCitation(m.content),
412
+ contentHash: m.frontmatter.contentHash,
413
+ ...entityRef ? { entityRef } : {},
414
+ ...key ? { supersessionKey: key } : {},
415
+ reason,
416
+ createdBy,
417
+ createdAt: m.frontmatter.updated || m.frontmatter.created || (/* @__PURE__ */ new Date()).toISOString()
418
+ });
419
+ }
420
+ }
421
+ return retired;
422
+ }
423
+ function buildRetiredFactTombstoneInputs(memory, opts) {
424
+ const keys = memory.entityRef && memory.structuredAttributes ? opts.supersessionKeysForFact({
425
+ entityRef: memory.entityRef,
426
+ structuredAttributes: memory.structuredAttributes
427
+ }) : [];
428
+ const keysToEmit = keys.length > 0 ? keys : [void 0];
429
+ return keysToEmit.map((key) => ({
430
+ reason: opts.reason,
431
+ createdBy: opts.createdBy,
432
+ sourceMemoryId: memory.id,
433
+ rawContent: memory.content,
434
+ ...memory.contentHash ? { contentHash: memory.contentHash } : {},
435
+ ...memory.entityRef ? { entityRef: memory.entityRef } : {},
436
+ ...key ? { supersessionKey: key } : {},
437
+ createdAt: opts.createdAt
438
+ }));
439
+ }
440
+
441
+ export {
442
+ TombstoneStore,
443
+ collectRetiredMemoriesForRebuild,
444
+ buildRetiredFactTombstoneInputs
445
+ };
446
+ //# sourceMappingURL=chunk-3JJWNZTT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lifecycle/tombstones.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// lifecycle/tombstones.ts — Tombstone store + non-resurrection invariant\n// (issue #1579)\n//\n// A \"tombstone\" records that a fact has been retired (corrected, superseded,\n// or retracted) so that the SAME fact cannot silently come back to life through\n// any of the five resurrection paths:\n//\n// 1. Re-extraction (session replay, re-observation)\n// 2. Importers (capsule / import-* payloads)\n// 3. Consolidation merges\n// 4. Dreams (REM re-derivation)\n// 5. Pattern reinforcement (duplicate promotion)\n//\n// The invariant is enforced at the SINGLE storage persist path\n// (`StorageManager.writeMemory` — the same chokepoint that records catalog\n// writes, issue #1522). Every write path funnels through it, so paths (a)–(e)\n// are blocked WITHOUT per-path code.\n//\n// File-first / rebuildable (the repo's storage philosophy): the JSONL at\n// `<stateDir>/tombstones.jsonl` is a cache of truth. The authoritative sources\n// are the memory files themselves (status: superseded/retracted) and the\n// `corrections/` records. `rebuildTombstonesFromStorage` reconstructs the\n// JSONL from those sources.\n//\n// Design rules honored (issue #1579 design section):\n// - Hash `rawContent` exactly as the dedup index does — one helper\n// (`ContentHashIndex.computeHash` / `normalizeContent`), never a second\n// (checklist §13; rule 23).\n// - Append-only log — never rewrite history; a later `kind: \"revocation\"`\n// entry re-allows (rule 25).\n// - Instance-scoped, never module-level (rule 11).\n// - Namespace-scoped — a tombstone in namespace A never blocks namespace B\n// (rule 42).\n// - Serialized appends with rejection recovery (rule 40).\n// - Never silent drop — a blocked write lands as pending_review + blockedBy\n// (rule 34).\n// - Do NOT register a blocked fact as an active dedup/index entry (rule 44).\n// - Off = pre-feature behavior for rollback safety (rule 30).\n// - Semantic tier (4) ships dark, off by default (rule 48).\n// ---------------------------------------------------------------------------\n\nimport { serializeMutations } from \"../utils/serialize-mutations.js\";\n\n/** Why a tombstone was emitted. */\nexport type TombstoneReason =\n | \"correction\"\n | \"supersession\"\n | \"retraction\"\n | \"contradiction_resolution\";\n\n/** Who emitted the tombstone. */\nexport type TombstoneCreatedBy =\n | \"user_correction\"\n | \"contradiction_resolution\"\n | \"supersession\"\n | \"chat\";\n\n/** Tier that matched on lookup. */\nexport type TombstoneMatchTier = \"exact\" | \"normalized\" | \"keyed\" | \"semantic\";\n\n/**\n * A single append-only tombstone log entry.\n *\n * `kind: \"tombstone\"` blocks; `kind: \"revocation\"` re-allows. The log is\n * never rewritten — the NEWEST matching entry wins at lookup (rule 25).\n */\nexport interface TombstoneEntry {\n /** Stable tombstone id (`tomb-<ts>-<rand>`). */\n id: string;\n kind: \"tombstone\" | \"revocation\";\n reason: TombstoneReason;\n /** The memory that was retired. */\n sourceMemoryId: string;\n /** sha256 of the retired memory's rawContent (rule 23). */\n contentHash: string;\n /** `ContentHashIndex.normalizeContent(rawContent)` — the pre-hash form. */\n normalizedText: string;\n entityRef?: string;\n /** Structured-attribute supersession key when one existed. */\n supersessionKey?: string;\n /** Namespace scope (rule 42). */\n namespace: string;\n createdAt: string;\n createdBy: TombstoneCreatedBy;\n /** For `kind: \"revocation\"`: the tombstone id being revoked. */\n revokes?: string;\n}\n\n/** A positive block decision returned by `TombstoneStore.lookup`. */\nexport interface TombstoneMatch {\n tombstoneId: string;\n matchedTier: TombstoneMatchTier;\n reason: TombstoneReason;\n}\n\n/** Inputs to a lookup. At least one discriminator must be present.\n *\n * Issue #1579 thread Ociag/Oci-W: `supersessionKeys` (plural) lets the write\n * chokepoint check EVERY derived key, not just the first. Emitters register\n * one tombstone per matched key (temporal-supersession, rebuild), so a block\n * can live on any later key; querying only `supersessionKeys[0]` missed it\n * and the retired fact resurrected as active. `supersessionKey` (singular)\n * remains for direct/unit callers; `lookup` checks the union of both. */\nexport interface TombstoneLookupQuery {\n contentHash?: string;\n normalizedText?: string;\n entityRef?: string;\n /** Single supersession key (direct/unit callers). */\n supersessionKey?: string;\n /** All derived supersession keys (write chokepoint). The keyed tier is\n * checked for each; the first active match wins. */\n supersessionKeys?: string[];\n namespace: string;\n}\n\n/** Configuration for a tombstone store instance. */\nexport interface TombstoneStoreOptions {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n /** sha256 of raw content — wired to `ContentHashIndex.computeHash`. */\n hashContent: (raw: string) => string;\n /** Normalize raw content — wired to `ContentHashIndex.normalizeContent`. */\n normalizeText: (raw: string) => string;\n /**\n * Optional cosine similarity in [0, 1] for the semantic tier. When\n * undefined or when `semanticMatch` is false, the semantic tier is\n * skipped entirely.\n */\n semanticSimilarity?: (a: string, b: string) => number;\n}\n\n/** Injected file I/O — the StorageManager wires its secure-store-aware\n * implementations so tombstones are encrypted at rest alongside other state.\n * `stat` is optional; when provided the store tracks the file mtime itself and\n * runs a cross-process staleness probe on each access (#1579). */\nexport interface TombstoneFileIo {\n read: (filePath: string) => Promise<string>;\n append: (filePath: string, content: string) => Promise<void>;\n write: (filePath: string, content: string) => Promise<void>;\n stat?: (filePath: string) => { mtimeMs: number };\n}\n\n/** Aggregate stats for `remnic doctor`. */\nexport interface TombstoneStats {\n count: number;\n revoked: number;\n lastAppendAt: string | null;\n corruptedLines: number;\n /** Whether the in-memory index matches the on-disk file (rebuild check). */\n loaded: boolean;\n}\n\nconst TOMBSTONE_PREFIX = \"tomb\";\n\nfunction newTombstoneId(): string {\n return `${TOMBSTONE_PREFIX}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/** Deterministic key for the keyed tier (namespace + entityRef + supersessionKey).\n *\n * The namespace is part of the discriminator so two namespace-scoped stores\n * that share the same backing `tombstones.jsonl` (namespaces disabled, or the\n * same directory used with different namespace configs) cannot overwrite each\n * other's index entries — a later tombstone for namespace B with the same\n * entity/key no longer evicts namespace A's entry (issue #1579 thread Ocs-O). */\nfunction keyedTierKey(namespace: string, entityRef: string, supersessionKey: string): string {\n return `${namespace}\\0${entityRef}\\0${supersessionKey}`;\n}\n\n/**\n * Parse one JSONL line into a TombstoneEntry, validating the discriminated\n * union. Returns `null` for malformed lines (rule 34 — skip with a counter,\n * never crash).\n */\nexport function parseTombstoneLine(line: string): TombstoneEntry | null {\n const trimmed = line.trim();\n if (trimmed.length === 0) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const e = parsed as Record<string, unknown>;\n if (typeof e.id !== \"string\" || e.id.length === 0) return null;\n if (e.kind !== \"tombstone\" && e.kind !== \"revocation\") return null;\n if (\n e.reason !== \"correction\" &&\n e.reason !== \"supersession\" &&\n e.reason !== \"retraction\" &&\n e.reason !== \"contradiction_resolution\"\n ) {\n return null;\n }\n if (typeof e.sourceMemoryId !== \"string\") return null;\n if (typeof e.contentHash !== \"string\") return null;\n if (typeof e.normalizedText !== \"string\") return null;\n if (typeof e.namespace !== \"string\") return null;\n if (typeof e.createdAt !== \"string\") return null;\n if (\n e.createdBy !== \"user_correction\" &&\n e.createdBy !== \"contradiction_resolution\" &&\n e.createdBy !== \"supersession\" &&\n e.createdBy !== \"chat\"\n ) {\n return null;\n }\n const out: TombstoneEntry = {\n id: e.id,\n kind: e.kind,\n reason: e.reason,\n sourceMemoryId: e.sourceMemoryId,\n contentHash: e.contentHash,\n normalizedText: e.normalizedText,\n namespace: e.namespace,\n createdAt: e.createdAt,\n createdBy: e.createdBy,\n };\n if (typeof e.entityRef === \"string\") out.entityRef = e.entityRef;\n if (typeof e.supersessionKey === \"string\") out.supersessionKey = e.supersessionKey;\n if (typeof e.revokes === \"string\") out.revokes = e.revokes;\n return out;\n}\n\n/**\n * The instance-scoped tombstone store. One per StorageManager (rule 11),\n * namespace-scoped via `namespace` + the on-disk path (rule 42).\n *\n * The in-memory index is built lazily on first access and invalidated on\n * append + by the StorageManager's cache-invalidation chokepoint (rule 25).\n */\nexport class TombstoneStore {\n private entries: TombstoneEntry[] = [];\n /** contentHash → tombstone id (newest) — exact tier. */\n private readonly byHash = new Map<string, string>();\n /** normalizedText → tombstone id (newest) — normalized tier. */\n private readonly byNormalized = new Map<string, string>();\n /** entityRef\\0supersessionKey → tombstone id (newest) — keyed tier. */\n private readonly byKey = new Map<string, string>();\n /** Tombstone ids that have a later revocation entry. */\n private readonly revokedIds = new Set<string>();\n /** id → entry index (newest only, for revocation lookups). */\n private readonly byId = new Map<string, TombstoneEntry>();\n private loaded = false;\n private loadPromise: Promise<void> | null = null;\n private corruptedLines = 0;\n private lastAppendAt: string | null = null;\n /**\n * Last-seen mtime of the JSONL file (cross-process staleness probe, #1579).\n * Tracked inside the store so the StorageManager wiring stays thin. When the\n * file's mtime advances past this value between accesses, the in-memory index\n * is stale (a peer process appended) and is reloaded before the next lookup.\n */\n private fileMtimeMs = 0;\n\n constructor(\n private readonly filePath: string,\n private readonly namespace: string,\n private readonly options: TombstoneStoreOptions,\n private readonly io: TombstoneFileIo,\n ) {}\n\n /** Lazy load + build the in-memory index. Idempotent. */\n async load(): Promise<void> {\n if (this.loaded) return;\n if (this.loadPromise) return this.loadPromise;\n this.loadPromise = this.loadInternal();\n try {\n await this.loadPromise;\n } finally {\n this.loadPromise = null;\n }\n }\n\n private async loadInternal(): Promise<void> {\n // Record the file's mtime so the staleness probe does not immediately\n // invalidate on the next access (fileMtimeMs starts at 0; without this,\n // any non-zero mtime would trigger a spurious reload). Done before the\n // read so an ENOENT still records 0.\n this.recordFileMtime();\n let raw: string;\n try {\n raw = await this.io.read(this.filePath);\n } catch (err) {\n // ENOENT is fine — fresh store. Other errors leave the store empty\n // rather than crashing the write path (rule 34 spirit: degrade to\n // \"no tombstones known\" rather than blocking all writes).\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code !== \"ENOENT\") {\n // Swallow — the write path must not crash on a corrupt tombstone file.\n // Rebuild will repair on the next doctor/maintenance run.\n }\n this.loaded = true;\n return;\n }\n this.resetIndex();\n let corrupted = 0;\n for (const line of raw.split(\"\\n\")) {\n const entry = parseTombstoneLine(line);\n if (!entry) {\n if (line.trim().length > 0) corrupted += 1;\n continue;\n }\n this.indexEntry(entry);\n }\n this.corruptedLines = corrupted;\n this.loaded = true;\n }\n\n private resetIndex(): void {\n this.entries = [];\n this.byHash.clear();\n this.byNormalized.clear();\n this.byKey.clear();\n this.revokedIds.clear();\n this.byId.clear();\n }\n\n /**\n * Index an entry. Later entries (higher array index = newer createdAt)\n * OVERRIDE earlier ones at each tier key — the newest matching entry wins\n * (rule 25). Revocation entries mark their target as revoked.\n */\n private indexEntry(entry: TombstoneEntry): void {\n this.entries.push(entry);\n this.byId.set(entry.id, entry);\n if (entry.createdAt > (this.lastAppendAt ?? \"\")) {\n this.lastAppendAt = entry.createdAt;\n }\n if (entry.kind === \"revocation\") {\n if (entry.revokes) this.revokedIds.add(entry.revokes);\n return;\n }\n // Tombstone entries populate the lookup maps. The namespace is part of\n // every discriminator key (issue #1579 thread Ocs-O): when two\n // namespace-scoped stores share the same backing file, a later tombstone\n // for namespace B with identical content must NOT evict namespace A's map\n // entry — otherwise A's lookup finds B's id, rejects it on namespace\n // mismatch, and misses its own still-active tombstone (resurrection).\n const ns = entry.namespace;\n if (entry.contentHash) this.byHash.set(`${ns}\\0${entry.contentHash}`, entry.id);\n if (entry.normalizedText) this.byNormalized.set(`${ns}\\0${entry.normalizedText}`, entry.id);\n if (entry.entityRef && entry.supersessionKey) {\n this.byKey.set(keyedTierKey(ns, entry.entityRef, entry.supersessionKey), entry.id);\n }\n }\n\n /** Invalidate the in-memory cache (rule 25). The next access reloads. */\n invalidate(): void {\n this.loaded = false;\n this.loadPromise = null;\n this.resetIndex();\n }\n\n /**\n * Cross-process staleness probe (#1579). If the file's mtime advanced since\n * the last load/own-write, a peer process appended and our in-memory index is\n * stale — invalidate AND reload in place so the next lookup sees the new\n * entries. Best-effort: a stat error is swallowed (the loaded index is\n * retained rather than crashing the write path). No-op when no `stat` was\n * injected or when the mtime is unchanged. After our own append/revoke/rebuild\n * `markWritten` records the new mtime, so this probe does not fire for our\n * own writes (only for peer-process appends).\n */\n async ensureFreshAgainstDisk(): Promise<void> {\n if (!this.io.stat) return;\n let mtimeMs: number;\n try {\n mtimeMs = Math.floor(this.io.stat(this.filePath).mtimeMs);\n } catch {\n return; // ENOENT / permission — keep the loaded index (fail-open).\n }\n if (mtimeMs === this.fileMtimeMs && this.loaded) return;\n this.fileMtimeMs = mtimeMs;\n this.invalidate();\n await this.load();\n }\n\n /**\n * Record the file mtime after THIS process writes (append / revoke / rebuild)\n * so `ensureFreshAgainstDisk` does not treat our own write as a peer append\n * and throw away the just-updated in-memory index (#1579 — avoids a needless\n * invalidate+reload in the hot write path).\n */\n private markWritten(): void {\n this.recordFileMtime();\n }\n\n private recordFileMtime(): void {\n if (!this.io.stat) return;\n try {\n this.fileMtimeMs = Math.floor(this.io.stat(this.filePath).mtimeMs);\n } catch {\n // ENOENT — fresh store with no file yet; mtime stays at its current value.\n }\n }\n\n /**\n * Append a tombstone entry. Serialized via `serializeMutations` keyed by\n * file path so concurrent appends do not interleave, with rejection recovery\n * (rule 40 — a single failed append never poisons the chain). The in-memory\n * index is updated AFTER the durable append succeeds.\n *\n * Returns the new tombstone id.\n */\n async appendTombstone(input: {\n reason: TombstoneReason;\n createdBy: TombstoneCreatedBy;\n sourceMemoryId: string;\n rawContent: string;\n entityRef?: string;\n supersessionKey?: string;\n createdAt?: string;\n /**\n * Pre-computed canonical contentHash from the retired memory's frontmatter.\n * When provided, used directly so the tombstone's exact tier matches the\n * hash writeMemory computes on re-extraction (issue #1579 review: cited\n * facts must not slip past the chokepoint because the emitter hashed the\n * citation-annotated body instead of the canonical source).\n */\n contentHash?: string;\n }): Promise<string> {\n await this.load();\n const createdAt = input.createdAt ?? new Date().toISOString();\n const id = newTombstoneId();\n const entry: TombstoneEntry = {\n id,\n kind: \"tombstone\",\n reason: input.reason,\n sourceMemoryId: input.sourceMemoryId,\n contentHash: input.contentHash ?? this.options.hashContent(input.rawContent),\n normalizedText: this.options.normalizeText(input.rawContent),\n ...(input.entityRef ? { entityRef: input.entityRef } : {}),\n ...(input.supersessionKey ? { supersessionKey: input.supersessionKey } : {}),\n namespace: this.namespace,\n createdAt,\n createdBy: input.createdBy,\n };\n await this.serializeAppend(entry);\n this.indexEntry(entry);\n this.markWritten();\n return id;\n }\n\n /**\n * Append a revocation entry referencing `tombstoneId`. The log is\n * append-only; lookup treats a revoked tombstone as re-allowed (rule 25).\n */\n async revoke(tombstoneId: string, createdBy: TombstoneCreatedBy): Promise<string> {\n await this.load();\n const createdAt = new Date().toISOString();\n const id = newTombstoneId();\n const entry: TombstoneEntry = {\n id,\n kind: \"revocation\",\n reason: \"correction\",\n sourceMemoryId: \"\",\n contentHash: \"\",\n normalizedText: \"\",\n namespace: this.namespace,\n createdAt,\n createdBy,\n revokes: tombstoneId,\n };\n await this.serializeAppend(entry);\n this.indexEntry(entry);\n this.markWritten();\n return id;\n }\n\n private serializeAppend(entry: TombstoneEntry): Promise<void> {\n const line = JSON.stringify(entry) + \"\\n\";\n // serializeMutations recovers after rejection (rule 40): a failed append\n // surfaces to THIS caller but the next append is not poisoned.\n return serializeMutations(`tombstone:${this.filePath}`, () =>\n this.io.append(this.filePath, line),\n );\n }\n\n /**\n * Look up whether `query` is blocked by an active (non-revoked) tombstone.\n * Tiers are checked in order: exact (contentHash) → normalized → keyed →\n * semantic (off by default). Returns the first active match, or `null`.\n *\n * Namespace isolation (rule 42): only entries with `namespace === query.namespace`\n * match. The store is per-namespace, so this is belt-and-suspenders.\n */\n lookup(query: TombstoneLookupQuery): TombstoneMatch | null {\n // We intentionally do NOT await load() here — lookup is called from the\n // hot write path. Callers MUST ensure the store is loaded before lookup\n // (StorageManager does this in ensureTombstoneStoreLoaded). If not loaded,\n // lookup returns null (fail-open: a missing tombstone check is preferable\n // to crashing every write — see rule 34 / the \"degrade gracefully\" note).\n if (!this.options.enabled) return null;\n if (!this.loaded) return null;\n\n // Tier 1: exact contentHash. Namespace is part of the map key (thread\n // Ocs-O), so the lookup finds only this namespace's tombstone even when\n // the backing file is shared. The namespace equality check below is kept\n // as defense-in-depth.\n const ns = query.namespace;\n if (query.contentHash) {\n const id = this.byHash.get(`${ns}\\0${query.contentHash}`);\n if (id && !this.revokedIds.has(id)) {\n const entry = this.byId.get(id);\n if (entry && entry.namespace === ns) {\n return { tombstoneId: id, matchedTier: \"exact\", reason: entry.reason };\n }\n }\n }\n // Tier 2: normalized text.\n if (query.normalizedText) {\n const id = this.byNormalized.get(`${ns}\\0${query.normalizedText}`);\n if (id && !this.revokedIds.has(id)) {\n const entry = this.byId.get(id);\n if (entry && entry.namespace === ns) {\n return { tombstoneId: id, matchedTier: \"normalized\", reason: entry.reason };\n }\n }\n }\n // Tier 3: keyed (entityRef + supersessionKey). Issue #1579 thread\n // Ociag/Oci-W: check EVERY supplied key, not just the first — emitters\n // append one tombstone per matched supersession key, so the active block\n // can live on any later key. The union of `supersessionKey` (singular,\n // direct callers) and `supersessionKeys` (array, write chokepoint) is\n // checked; the first active match wins (tiers are equality-based, so\n // ordering across keys does not affect correctness).\n if (query.entityRef) {\n const keysToCheck: string[] = [];\n if (query.supersessionKey) keysToCheck.push(query.supersessionKey);\n if (query.supersessionKeys) {\n for (const k of query.supersessionKeys) {\n if (!keysToCheck.includes(k)) keysToCheck.push(k);\n }\n }\n for (const key of keysToCheck) {\n const id = this.byKey.get(keyedTierKey(ns, query.entityRef, key));\n if (id && !this.revokedIds.has(id)) {\n const entry = this.byId.get(id);\n if (entry && entry.namespace === ns) {\n return { tombstoneId: id, matchedTier: \"keyed\", reason: entry.reason };\n }\n }\n }\n }\n // Tier 4: semantic (off by default, rule 48).\n if (this.options.semanticMatch && this.options.semanticSimilarity && query.normalizedText) {\n const threshold = this.options.semanticThreshold;\n let best: { id: string; reason: TombstoneReason; score: number } | null = null;\n for (const entry of this.entries) {\n if (entry.kind !== \"tombstone\") continue;\n if (entry.namespace !== query.namespace) continue;\n if (this.revokedIds.has(entry.id)) continue;\n if (!entry.normalizedText) continue;\n const score = this.options.semanticSimilarity(query.normalizedText, entry.normalizedText);\n if (score >= threshold && (!best || score > best.score)) {\n best = { id: entry.id, reason: entry.reason, score };\n }\n }\n if (best) {\n return { tombstoneId: best.id, matchedTier: \"semantic\", reason: best.reason };\n }\n }\n return null;\n }\n\n /** Aggregate stats for the doctor / x-ray surfaces. */\n stats(): TombstoneStats {\n let active = 0;\n for (const entry of this.entries) {\n if (entry.kind === \"tombstone\" && !this.revokedIds.has(entry.id)) active += 1;\n }\n return {\n count: active,\n revoked: this.revokedIds.size,\n lastAppendAt: this.lastAppendAt,\n corruptedLines: this.corruptedLines,\n loaded: this.loaded,\n };\n }\n\n /** Read-only snapshot of all entries (for rebuild + tests). */\n snapshot(): readonly TombstoneEntry[] {\n return this.entries;\n }\n\n /**\n * Rebuild the in-memory index + JSONL from the supplied retired-memory\n * records + existing entries (preserving revocations). Byte-stable: entries\n * are sorted by (createdAt, id) before write (rule 38).\n *\n * Returns the count of tombstone entries written.\n */\n async rebuild(retiredMemories: ReadonlyArray<RetiredMemoryRecord>): Promise<number> {\n // Preserve existing revocations (all namespaces — ids are globally\n // unique) so a rebuild does not silently un-revoke.\n const existingRevocations = this.entries.filter((e) => e.kind === \"revocation\");\n // Preserve tombstone entries from OTHER namespaces when the backing file\n // is shared (issue #1579 thread Oc2MJ). rebuild rewrites the entire file;\n // without preserving foreign entries, rebuilding namespace A would\n // silently delete namespace B's tombstones, allowing resurrection in B.\n const foreignTombstones = this.entries.filter(\n (e) => e.kind === \"tombstone\" && e.namespace !== this.namespace,\n );\n // Reuse existing tombstone ids for source-equivalent entries so a prior\n // revocation (which references the tombstone id) survives rebuild — minting\n // fresh ids would orphan the revocation and silently un-revoke the content.\n // Issue #1579 thread Oci-T: key the reuse map by (sourceMemoryId,\n // supersessionKey), not just sourceMemoryId. A retired fact with multiple\n // structured-attribute keys emits one record per key (see\n // collectRetiredMemoriesForRebuild); keying only by sourceMemoryId made\n // every rebuilt record share one id, so a revocation of key A silently\n // revoked key B (over-revoke) — or, if a prior single-key tombstone was\n // revoked, the new multi-key records all inherited a revoked id and\n // silently un-blocked (orphan). Including the supersession-key\n // discriminator keeps each keyed tombstone's id (and thus its revocation)\n // independent. Records without a supersession key fall back to a stable\n // empty-string discriminator so they still reuse by sourceMemoryId alone.\n const existingBySource = new Map<string, string>();\n for (const e of this.entries) {\n if (e.kind === \"tombstone\") {\n existingBySource.set(`${e.sourceMemoryId}\\u{0000}${e.supersessionKey ?? \"\"}`, e.id);\n }\n }\n const rebuilt: TombstoneEntry[] = retiredMemories.map((m) => ({\n id:\n existingBySource.get(`${m.memoryId}\\u{0000}${m.supersessionKey ?? \"\"}`) ??\n newTombstoneId(),\n kind: \"tombstone\" as const,\n reason: m.reason,\n sourceMemoryId: m.memoryId,\n contentHash: m.contentHash ?? this.options.hashContent(m.rawContent),\n normalizedText: this.options.normalizeText(m.rawContent),\n ...(m.entityRef ? { entityRef: m.entityRef } : {}),\n ...(m.supersessionKey ? { supersessionKey: m.supersessionKey } : {}),\n namespace: this.namespace,\n createdAt: m.createdAt,\n createdBy: m.createdBy,\n }));\n // Sort deterministically (rule 38): createdAt, then id for stability.\n rebuilt.sort((a, b) =>\n a.createdAt === b.createdAt\n ? a.id < b.id ? -1 : a.id > b.id ? 1 : 0\n : a.createdAt < b.createdAt ? -1 : 1,\n );\n const all = [...rebuilt, ...existingRevocations, ...foreignTombstones].sort((a, b) =>\n a.createdAt === b.createdAt\n ? a.id < b.id ? -1 : a.id > b.id ? 1 : 0\n : a.createdAt < b.createdAt ? -1 : 1,\n );\n const serialized = all.map((e) => JSON.stringify(e)).join(\"\\n\") + (all.length > 0 ? \"\\n\" : \"\");\n await serializeMutations(`tombstone-rebuild:${this.filePath}`, () =>\n this.io.write(this.filePath, serialized),\n );\n this.resetIndex();\n for (const entry of all) this.indexEntry(entry);\n this.corruptedLines = 0;\n this.loaded = true;\n this.markWritten();\n return rebuilt.length;\n }\n}\n\n/** A retired memory projected into the shape `TombstoneStore.rebuild` consumes. */\nexport interface RetiredMemoryRecord {\n memoryId: string;\n rawContent: string;\n entityRef?: string;\n supersessionKey?: string;\n reason: TombstoneReason;\n createdBy: TombstoneCreatedBy;\n createdAt: string;\n /** Canonical contentHash from the retired memory's frontmatter (#1579). */\n contentHash?: string;\n}\n\n/**\n * Project a corpus of memories into the retired-memory records `rebuild`\n * consumes. Pure (no I/O) so the StorageManager wiring stays thin (#1579,\n * #1520 god-file ratchet). Only superseded / forgotten / rejected FACTS\n * participate — entities, questions, and artifacts have their own lifecycle\n * (issue pitfall). The supersession key is derived from structured attributes\n * via the injected helper so there is one keyed-tier definition (rule 23).\n */\nexport function collectRetiredMemoriesForRebuild(\n memories: ReadonlyArray<{\n frontmatter: {\n id: string;\n status?: string;\n category?: string;\n contentHash?: string;\n entityRef?: string;\n structuredAttributes?: Record<string, string>;\n updated?: string;\n created?: string;\n };\n content: string;\n }>,\n deps: {\n /** Strip citation annotations from the body before hashing/normalizing. */\n stripCitation: (text: string) => string;\n /** Derive the keyed-tier supersession key (one helper, rule 23). */\n supersessionKeysForFact: (spec: {\n entityRef?: string;\n structuredAttributes?: Record<string, string>;\n }) => string[];\n },\n): RetiredMemoryRecord[] {\n const retired: RetiredMemoryRecord[] = [];\n for (const m of memories) {\n const status = m.frontmatter.status;\n if (status !== \"superseded\" && status !== \"rejected\" && status !== \"forgotten\") continue;\n if (m.frontmatter.category !== \"fact\") continue;\n const reason: TombstoneReason =\n status === \"superseded\" ? \"supersession\" : status === \"forgotten\" ? \"retraction\" : \"correction\";\n const createdBy: TombstoneCreatedBy =\n reason === \"supersession\" ? \"supersession\" : \"user_correction\";\n const entityRef = m.frontmatter.entityRef;\n const keys =\n entityRef && m.frontmatter.structuredAttributes\n ? deps.supersessionKeysForFact({\n entityRef,\n structuredAttributes: m.frontmatter.structuredAttributes,\n })\n : [];\n // Issue #1579 thread Ocgjz: emit one record per matched supersession key\n // (not just keys[0]) so rebuild reproduces the same keyed tombstones as\n // live temporal-supersession (which now appends one per key — thread ObteS).\n // Without this, a rebuild would under-rebuild the JSONL and keyed-tier\n // blocks would disappear until rediscovered.\n const keysToEmit = keys.length > 0 ? keys : [undefined];\n for (const key of keysToEmit) {\n retired.push({\n memoryId: m.frontmatter.id,\n rawContent: deps.stripCitation(m.content),\n contentHash: m.frontmatter.contentHash,\n ...(entityRef ? { entityRef } : {}),\n ...(key ? { supersessionKey: key } : {}),\n reason,\n createdBy,\n createdAt: m.frontmatter.updated || m.frontmatter.created || new Date().toISOString(),\n });\n }\n }\n return retired;\n}\n\n/**\n * Build the live-emission tombstone inputs for a single retired FACT — one\n * input per derived supersession key (or a single keyless record when no\n * structured attributes are present). Pure (no I/O) so the emitters in\n * `StorageManager.supersedeMemory` (contradiction) and `forgetMemory`\n * (retraction) stay thin (#1579, #1520 god-file ratchet). Mirrors the\n * temporal-supersession emitter and `collectRetiredMemoriesForRebuild` so\n * every retire path emits the same keyed-tombstone shape (issue #1579\n * threads Oci-Y / OchiF: without per-key tombstones, a paraphrased\n * re-observation missed the keyed tier and the fact resurrected active).\n */\nexport function buildRetiredFactTombstoneInputs(\n memory: {\n id: string;\n content: string;\n contentHash?: string;\n entityRef?: string;\n structuredAttributes?: Record<string, string>;\n },\n opts: {\n reason: TombstoneReason;\n createdBy: TombstoneCreatedBy;\n createdAt: string;\n supersessionKeysForFact: (spec: {\n entityRef?: string;\n structuredAttributes?: Record<string, string>;\n }) => string[];\n },\n): Array<{\n reason: TombstoneReason;\n createdBy: TombstoneCreatedBy;\n sourceMemoryId: string;\n rawContent: string;\n contentHash?: string;\n entityRef?: string;\n supersessionKey?: string;\n createdAt: string;\n}> {\n const keys =\n memory.entityRef && memory.structuredAttributes\n ? opts.supersessionKeysForFact({\n entityRef: memory.entityRef,\n structuredAttributes: memory.structuredAttributes,\n })\n : [];\n const keysToEmit = keys.length > 0 ? keys : [undefined];\n return keysToEmit.map((key) => ({\n reason: opts.reason,\n createdBy: opts.createdBy,\n sourceMemoryId: memory.id,\n rawContent: memory.content,\n ...(memory.contentHash ? { contentHash: memory.contentHash } : {}),\n ...(memory.entityRef ? { entityRef: memory.entityRef } : {}),\n ...(key ? { supersessionKey: key } : {}),\n createdAt: opts.createdAt,\n }));\n}\n"],"mappings":";;;;;AA0JA,IAAM,mBAAmB;AAEzB,SAAS,iBAAyB;AAChC,SAAO,GAAG,gBAAgB,IAAI,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AACjG;AASA,SAAS,aAAa,WAAmB,WAAmB,iBAAiC;AAC3F,SAAO,GAAG,SAAS,KAAK,SAAS,KAAK,eAAe;AACvD;AAOO,SAAS,mBAAmB,MAAqC;AACtE,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACj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