@remnic/core 1.1.2 → 1.1.4

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 (489) hide show
  1. package/dist/abort-error.js +1 -0
  2. package/dist/abstraction-nodes.js +1 -0
  3. package/dist/access-audit.js +1 -0
  4. package/dist/access-cli.js +72 -47
  5. package/dist/access-cli.js.map +1 -1
  6. package/dist/access-http.d.ts +50 -5
  7. package/dist/access-http.js +39 -16
  8. package/dist/access-idempotency.js +1 -0
  9. package/dist/access-mcp.d.ts +10 -5
  10. package/dist/access-mcp.js +38 -14
  11. package/dist/access-schema.d.ts +133 -13
  12. package/dist/access-schema.js +20 -1
  13. package/dist/access-service-CtXFnprR.d.ts +2033 -0
  14. package/dist/access-service.d.ts +11 -6
  15. package/dist/access-service.js +40 -15
  16. package/dist/active-memory-bridge.js +1 -0
  17. package/dist/active-recall.js +1 -0
  18. package/dist/active-recall.js.map +1 -1
  19. package/dist/behavior-learner.js +1 -0
  20. package/dist/behavior-learner.js.map +1 -1
  21. package/dist/behavior-signals.js +1 -0
  22. package/dist/bootstrap.d.ts +6 -4
  23. package/dist/bootstrap.js +1 -0
  24. package/dist/boxes.js +1 -0
  25. package/dist/briefing.d.ts +9 -5
  26. package/dist/briefing.js +10 -7
  27. package/dist/buffer-surprise-report.js +1 -0
  28. package/dist/buffer-surprise.js +1 -0
  29. package/dist/buffer.d.ts +1 -1
  30. package/dist/buffer.js +1 -0
  31. package/dist/calibration.d.ts +8 -1
  32. package/dist/calibration.js +10 -2
  33. package/dist/calibration.js.map +1 -1
  34. package/dist/capsule-cli.d.ts +137 -0
  35. package/dist/capsule-cli.js +34 -0
  36. package/dist/capsule-crypto-5CYAGVC5.js +18 -0
  37. package/dist/capsule-export-NZQPOTQ4.js +17 -0
  38. package/dist/capsule-export-NZQPOTQ4.js.map +1 -0
  39. package/dist/capsule-import-SDCUXLEV.js +16 -0
  40. package/dist/capsule-import-SDCUXLEV.js.map +1 -0
  41. package/dist/capsule-merge-DI7PNQ2H.js +189 -0
  42. package/dist/capsule-merge-DI7PNQ2H.js.map +1 -0
  43. package/dist/causal-behavior.js +1 -0
  44. package/dist/causal-behavior.js.map +1 -1
  45. package/dist/causal-chain.js +1 -0
  46. package/dist/causal-consolidation.js +12 -9
  47. package/dist/causal-consolidation.js.map +1 -1
  48. package/dist/causal-retrieval.js +2 -1
  49. package/dist/causal-retrieval.js.map +1 -1
  50. package/dist/causal-trajectory-graph.js +4 -1
  51. package/dist/causal-trajectory-graph.js.map +1 -1
  52. package/dist/causal-trajectory.js +2 -1
  53. package/dist/chunk-2LSZVONP.js +67 -0
  54. package/dist/chunk-2LSZVONP.js.map +1 -0
  55. package/dist/chunk-32KD5IHZ.js +245 -0
  56. package/dist/chunk-32KD5IHZ.js.map +1 -0
  57. package/dist/chunk-3KIS4VGT.js +228 -0
  58. package/dist/chunk-3KIS4VGT.js.map +1 -0
  59. package/dist/chunk-3LCWFNVS.js +350 -0
  60. package/dist/chunk-3LCWFNVS.js.map +1 -0
  61. package/dist/chunk-43EKP2UK.js +26 -0
  62. package/dist/chunk-43EKP2UK.js.map +1 -0
  63. package/dist/chunk-457A4P3L.js +119 -0
  64. package/dist/chunk-457A4P3L.js.map +1 -0
  65. package/dist/{chunk-TMYO7B5P.js → chunk-47WOM4YW.js} +2 -2
  66. package/dist/{chunk-FVA6TGI3.js → chunk-52PDY6GD.js} +42 -2
  67. package/dist/chunk-52PDY6GD.js.map +1 -0
  68. package/dist/{chunk-ULYOGL6R.js → chunk-5HRY2WRF.js} +7 -3
  69. package/dist/chunk-5HRY2WRF.js.map +1 -0
  70. package/dist/{chunk-BOUYNNYD.js → chunk-67YLUWLG.js} +32 -13
  71. package/dist/{chunk-BOUYNNYD.js.map → chunk-67YLUWLG.js.map} +1 -1
  72. package/dist/chunk-6TBWYBJ3.js +236 -0
  73. package/dist/chunk-6TBWYBJ3.js.map +1 -0
  74. package/dist/chunk-74EMIVE4.js +329 -0
  75. package/dist/chunk-74EMIVE4.js.map +1 -0
  76. package/dist/chunk-74WWN7ZW.js +82 -0
  77. package/dist/chunk-74WWN7ZW.js.map +1 -0
  78. package/dist/chunk-A6XUJE5D.js +126 -0
  79. package/dist/chunk-A6XUJE5D.js.map +1 -0
  80. package/dist/{chunk-STGWEHYR.js → chunk-AEMBDV7M.js} +1187 -62
  81. package/dist/chunk-AEMBDV7M.js.map +1 -0
  82. package/dist/{chunk-PVICZTKG.js → chunk-AGZHRWPT.js} +5 -5
  83. package/dist/{chunk-PVICZTKG.js.map → chunk-AGZHRWPT.js.map} +1 -1
  84. package/dist/chunk-AJA46VX5.js +393 -0
  85. package/dist/chunk-AJA46VX5.js.map +1 -0
  86. package/dist/chunk-ASIQZXYO.js +277 -0
  87. package/dist/chunk-ASIQZXYO.js.map +1 -0
  88. package/dist/{chunk-DG6YMRDC.js → chunk-B2TL6GA2.js} +2 -2
  89. package/dist/chunk-BJMBJZ2Y.js +290 -0
  90. package/dist/chunk-BJMBJZ2Y.js.map +1 -0
  91. package/dist/chunk-BT7NVCML.js +79 -0
  92. package/dist/chunk-BT7NVCML.js.map +1 -0
  93. package/dist/chunk-CK5NTM2S.js +454 -0
  94. package/dist/chunk-CK5NTM2S.js.map +1 -0
  95. package/dist/{chunk-AYXIPSZO.js → chunk-CRU27Q4J.js} +2 -2
  96. package/dist/{chunk-UWB5LMWY.js → chunk-CUI2STX6.js} +526 -24
  97. package/dist/chunk-CUI2STX6.js.map +1 -0
  98. package/dist/{chunk-CUPFXL3J.js → chunk-EGEPUGN4.js} +4 -4
  99. package/dist/chunk-EGEPUGN4.js.map +1 -0
  100. package/dist/{chunk-3OGMS3PE.js → chunk-F5VQOQ2E.js} +3 -2
  101. package/dist/chunk-F5VQOQ2E.js.map +1 -0
  102. package/dist/chunk-FP2373TW.js +149 -0
  103. package/dist/chunk-FP2373TW.js.map +1 -0
  104. package/dist/{chunk-RBBWYEFJ.js → chunk-G2WADRQ3.js} +1 -1
  105. package/dist/chunk-G7D6GZ5J.js +48 -0
  106. package/dist/chunk-G7D6GZ5J.js.map +1 -0
  107. package/dist/chunk-H7XKCNR6.js +60 -0
  108. package/dist/chunk-H7XKCNR6.js.map +1 -0
  109. package/dist/{chunk-LOIMBRDE.js → chunk-HIRKCQGF.js} +1994 -412
  110. package/dist/chunk-HIRKCQGF.js.map +1 -0
  111. package/dist/chunk-IXEJRKCZ.js +18 -0
  112. package/dist/chunk-IXEJRKCZ.js.map +1 -0
  113. package/dist/chunk-IYY4MCPG.js +275 -0
  114. package/dist/chunk-IYY4MCPG.js.map +1 -0
  115. package/dist/{chunk-BECYBZLX.js → chunk-JWSENLQI.js} +502 -22
  116. package/dist/chunk-JWSENLQI.js.map +1 -0
  117. package/dist/chunk-KNKUID7G.js +183 -0
  118. package/dist/chunk-KNKUID7G.js.map +1 -0
  119. package/dist/chunk-L2IO2QPY.js +2036 -0
  120. package/dist/chunk-L2IO2QPY.js.map +1 -0
  121. package/dist/{chunk-ZAIM4TUE.js → chunk-LW2NMHDW.js} +46 -1
  122. package/dist/chunk-LW2NMHDW.js.map +1 -0
  123. package/dist/chunk-MDYG7VI7.js +48 -0
  124. package/dist/chunk-MDYG7VI7.js.map +1 -0
  125. package/dist/{chunk-VDX363PS.js → chunk-MUELDH4F.js} +10 -3
  126. package/dist/chunk-MUELDH4F.js.map +1 -0
  127. package/dist/chunk-MXC3AP5I.js +74 -0
  128. package/dist/chunk-MXC3AP5I.js.map +1 -0
  129. package/dist/chunk-NN3TS5BM.js +147 -0
  130. package/dist/chunk-NN3TS5BM.js.map +1 -0
  131. package/dist/{chunk-3YGHKTBF.js → chunk-NZS2BLTP.js} +963 -326
  132. package/dist/chunk-NZS2BLTP.js.map +1 -0
  133. package/dist/chunk-OA3L7BFR.js +183 -0
  134. package/dist/chunk-OA3L7BFR.js.map +1 -0
  135. package/dist/chunk-OZHRDTDX.js +240 -0
  136. package/dist/chunk-OZHRDTDX.js.map +1 -0
  137. package/dist/chunk-PCUKNJAZ.js +165 -0
  138. package/dist/chunk-PCUKNJAZ.js.map +1 -0
  139. package/dist/{chunk-6PFRXT4K.js → chunk-PFV5C235.js} +11 -6
  140. package/dist/chunk-PFV5C235.js.map +1 -0
  141. package/dist/chunk-PZ5AY32C.js +10 -0
  142. package/dist/chunk-PZ5AY32C.js.map +1 -0
  143. package/dist/{chunk-Y7R2XJ5Q.js → chunk-Q7FJ5ZHM.js} +6 -2
  144. package/dist/chunk-Q7FJ5ZHM.js.map +1 -0
  145. package/dist/{chunk-WCLICCGB.js → chunk-RILIVK4O.js} +91 -4
  146. package/dist/chunk-RILIVK4O.js.map +1 -0
  147. package/dist/{chunk-C2EFFULQ.js → chunk-RK2Y4XOM.js} +163 -20
  148. package/dist/chunk-RK2Y4XOM.js.map +1 -0
  149. package/dist/{chunk-TP4FZJIZ.js → chunk-RULE4VG5.js} +5 -1
  150. package/dist/chunk-RULE4VG5.js.map +1 -0
  151. package/dist/{chunk-PVPWZSSI.js → chunk-SMA4IMHV.js} +19 -3
  152. package/dist/chunk-SMA4IMHV.js.map +1 -0
  153. package/dist/{chunk-6YJHX2DL.js → chunk-TIFRGAKO.js} +242 -22
  154. package/dist/chunk-TIFRGAKO.js.map +1 -0
  155. package/dist/chunk-TUFG6VXY.js +875 -0
  156. package/dist/chunk-TUFG6VXY.js.map +1 -0
  157. package/dist/chunk-TYEOAFH3.js +251 -0
  158. package/dist/chunk-TYEOAFH3.js.map +1 -0
  159. package/dist/chunk-UKJAGEXH.js +260 -0
  160. package/dist/chunk-UKJAGEXH.js.map +1 -0
  161. package/dist/{chunk-KVBLZUKV.js → chunk-USFPPRAF.js} +93 -3
  162. package/dist/chunk-USFPPRAF.js.map +1 -0
  163. package/dist/{chunk-NBVAS5MT.js → chunk-V7TEH5I2.js} +6 -6
  164. package/dist/{chunk-GA5P7RST.js → chunk-VTJVUHRK.js} +22 -36
  165. package/dist/chunk-VTJVUHRK.js.map +1 -0
  166. package/dist/{chunk-SPI27QT6.js → chunk-W7WWT4FJ.js} +9 -4
  167. package/dist/chunk-W7WWT4FJ.js.map +1 -0
  168. package/dist/chunk-WIICJPET.js +45 -0
  169. package/dist/chunk-WIICJPET.js.map +1 -0
  170. package/dist/{chunk-VBVG2M5G.js → chunk-WPGJYVUH.js} +6 -2
  171. package/dist/chunk-WPGJYVUH.js.map +1 -0
  172. package/dist/{chunk-4HQS2HPX.js → chunk-WSZIHQBK.js} +29 -9
  173. package/dist/{chunk-4HQS2HPX.js.map → chunk-WSZIHQBK.js.map} +1 -1
  174. package/dist/{chunk-NZLQTHS5.js → chunk-WW3QQF4H.js} +4 -1
  175. package/dist/chunk-WW3QQF4H.js.map +1 -0
  176. package/dist/{chunk-DIXB44VE.js → chunk-X6VBWOVZ.js} +28 -13
  177. package/dist/chunk-X6VBWOVZ.js.map +1 -0
  178. package/dist/{chunk-XXVWLXSG.js → chunk-XQ4EJLUD.js} +64 -92
  179. package/dist/chunk-XQ4EJLUD.js.map +1 -0
  180. package/dist/{chunk-OC5OXUQ4.js → chunk-XRCYKJ3V.js} +780 -17
  181. package/dist/chunk-XRCYKJ3V.js.map +1 -0
  182. package/dist/{chunk-F5VP6YCB.js → chunk-Y4A6M3B6.js} +573 -156
  183. package/dist/chunk-Y4A6M3B6.js.map +1 -0
  184. package/dist/chunk-YNJHCGDT.js +309 -0
  185. package/dist/chunk-YNJHCGDT.js.map +1 -0
  186. package/dist/{chunk-L7IXWRYE.js → chunk-ZIBOQULP.js} +22 -13
  187. package/dist/chunk-ZIBOQULP.js.map +1 -0
  188. package/dist/{chunk-W6SL7OFG.js → chunk-ZTSE2ZJ6.js} +12 -2
  189. package/dist/{chunk-W6SL7OFG.js.map → chunk-ZTSE2ZJ6.js.map} +1 -1
  190. package/dist/chunking.js +1 -0
  191. package/dist/cipher-GVE2GQ5H.js +28 -0
  192. package/dist/cipher-GVE2GQ5H.js.map +1 -0
  193. package/dist/citations.js +1 -0
  194. package/dist/{cli-BkeRaYfk.d.ts → cli-lMql2FCr.d.ts} +26 -7
  195. package/dist/cli.d.ts +11 -6
  196. package/dist/cli.js +69 -34
  197. package/dist/codex-thread-key.js +1 -0
  198. package/dist/commitment-ledger.js +1 -0
  199. package/dist/compression-optimizer.js +1 -0
  200. package/dist/config.d.ts +2 -1
  201. package/dist/config.js +4 -1
  202. package/dist/connectors-cli-DFGtY2DB.d.ts +257 -0
  203. package/dist/connectors-cli.d.ts +2 -0
  204. package/dist/connectors-cli.js +22 -0
  205. package/dist/connectors-cli.js.map +1 -0
  206. package/dist/consolidation-operator.d.ts +65 -5
  207. package/dist/consolidation-operator.js +6 -1
  208. package/dist/consolidation-provenance-check.d.ts +1 -1
  209. package/dist/consolidation-provenance-check.js +3 -2
  210. package/dist/consolidation-undo.d.ts +1 -1
  211. package/dist/consolidation-undo.js +1 -0
  212. package/dist/consolidation-undo.js.map +1 -1
  213. package/dist/{contradiction-review-WIUBAR52.js → contradiction-review-5LTTVDQV.js} +2 -1
  214. package/dist/contradiction-review-5LTTVDQV.js.map +1 -0
  215. package/dist/{contradiction-scan-E3GJTI4F.js → contradiction-scan-3Z6YW7YA.js} +2 -1
  216. package/dist/{contradiction-scan-E3GJTI4F.js.map → contradiction-scan-3Z6YW7YA.js.map} +1 -1
  217. package/dist/cross-namespace-budget.js +1 -0
  218. package/dist/cue-anchors.js +1 -0
  219. package/dist/dashboard-runtime.js +1 -0
  220. package/dist/day-summary.js +1 -0
  221. package/dist/delinearize.js +1 -0
  222. package/dist/direct-answer-wiring.js +1 -0
  223. package/dist/direct-answer.js +1 -0
  224. package/dist/dreams-ledger-LR2NBAZE.js +286 -0
  225. package/dist/dreams-ledger-LR2NBAZE.js.map +1 -0
  226. package/dist/embedding-fallback.js +1 -0
  227. package/dist/engine-O6YWKQM3.js +28 -0
  228. package/dist/engine-O6YWKQM3.js.map +1 -0
  229. package/dist/entity-retrieval.d.ts +1 -1
  230. package/dist/entity-retrieval.js +10 -7
  231. package/dist/entity-schema.js +1 -0
  232. package/dist/evals.js +1 -0
  233. package/dist/evidence-pack.d.ts +16 -0
  234. package/dist/evidence-pack.js +8 -0
  235. package/dist/evidence-pack.js.map +1 -0
  236. package/dist/explicit-capture.d.ts +6 -4
  237. package/dist/explicit-capture.js +1 -0
  238. package/dist/extraction-judge-telemetry.js +1 -0
  239. package/dist/extraction-judge-training.js +1 -0
  240. package/dist/extraction-judge.js +1 -0
  241. package/dist/extraction.js +8 -7
  242. package/dist/fallback-llm.js +3 -2
  243. package/dist/first-start-migration-4MHQEOSD.js +263 -0
  244. package/dist/first-start-migration-4MHQEOSD.js.map +1 -0
  245. package/dist/forget-PLR6J5DN.js +69 -0
  246. package/dist/forget-PLR6J5DN.js.map +1 -0
  247. package/dist/framework-CyHYDcri.d.ts +153 -0
  248. package/dist/fs-utils-IRVUFB6G.js +30 -0
  249. package/dist/fs-utils-IRVUFB6G.js.map +1 -0
  250. package/dist/graph-dashboard-diff.js +1 -0
  251. package/dist/graph-dashboard-key.js +1 -0
  252. package/dist/graph-dashboard-parser.js +1 -0
  253. package/dist/graph-edge-decay-PWB63GRE.js +207 -0
  254. package/dist/graph-edge-decay-PWB63GRE.js.map +1 -0
  255. package/dist/graph-edge-reinforcement.d.ts +81 -0
  256. package/dist/graph-edge-reinforcement.js +24 -0
  257. package/dist/graph-edge-reinforcement.js.map +1 -0
  258. package/dist/graph-events.d.ts +87 -0
  259. package/dist/graph-events.js +14 -0
  260. package/dist/graph-events.js.map +1 -0
  261. package/dist/graph-recall.js +1 -0
  262. package/dist/graph-retrieval.js +1 -0
  263. package/dist/graph-snapshot.d.ts +112 -0
  264. package/dist/graph-snapshot.js +19 -0
  265. package/dist/graph-snapshot.js.map +1 -0
  266. package/dist/graph.d.ts +105 -7
  267. package/dist/graph.js +20 -3
  268. package/dist/harmonic-retrieval.js +1 -0
  269. package/dist/himem.js +1 -0
  270. package/dist/hygiene.js +1 -0
  271. package/dist/identity-continuity.js +1 -0
  272. package/dist/importance.js +1 -0
  273. package/dist/index.d.ts +574 -13
  274. package/dist/index.js +337 -69
  275. package/dist/index.js.map +1 -1
  276. package/dist/intent.js +1 -0
  277. package/dist/json-extract.js +1 -0
  278. package/dist/json-store.js +1 -0
  279. package/dist/kdf-7S6RWKLZ.js +26 -0
  280. package/dist/kdf-7S6RWKLZ.js.map +1 -0
  281. package/dist/legacy-hook-compat.js +1 -0
  282. package/dist/legacy-hook-compat.js.map +1 -1
  283. package/dist/lifecycle.js +1 -0
  284. package/dist/live-connectors-runner.d.ts +48 -0
  285. package/dist/live-connectors-runner.js +17 -0
  286. package/dist/live-connectors-runner.js.map +1 -0
  287. package/dist/local-llm.js +1 -0
  288. package/dist/logger.js +1 -0
  289. package/dist/memory-action-policy.js +1 -0
  290. package/dist/memory-cache.d.ts +2 -1
  291. package/dist/memory-cache.js +4 -1
  292. package/dist/memory-governance-JZHZDOLN.js +37 -0
  293. package/dist/memory-governance-JZHZDOLN.js.map +1 -0
  294. package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
  295. package/dist/memory-lifecycle-ledger-utils.js +4 -1
  296. package/dist/memory-projection-format.js +1 -0
  297. package/dist/{memory-projection-store-DeSXPh1j.d.ts → memory-projection-store-CY8TU40w.d.ts} +2 -1
  298. package/dist/memory-projection-store.d.ts +1 -1
  299. package/dist/memory-projection-store.js +2 -1
  300. package/dist/memory-worth-bench.js +1 -0
  301. package/dist/memory-worth-bench.js.map +1 -1
  302. package/dist/memory-worth-filter.js +1 -0
  303. package/dist/memory-worth-outcomes.d.ts +1 -1
  304. package/dist/memory-worth-outcomes.js +1 -0
  305. package/dist/memory-worth.js +1 -0
  306. package/dist/metadata-FC3XPDRQ.js +21 -0
  307. package/dist/metadata-FC3XPDRQ.js.map +1 -0
  308. package/dist/migrate-from-identity-anchor-TTEDEJGX.js +8 -0
  309. package/dist/migrate-from-identity-anchor-TTEDEJGX.js.map +1 -0
  310. package/dist/model-registry.js +1 -0
  311. package/dist/models-json.js +1 -0
  312. package/dist/native-knowledge.js +1 -0
  313. package/dist/negative.js +1 -0
  314. package/dist/objective-state-writers.js +1 -0
  315. package/dist/objective-state-writers.js.map +1 -1
  316. package/dist/objective-state.js +1 -0
  317. package/dist/openai-chat-compat.js +1 -0
  318. package/dist/operator-toolkit.d.ts +46 -2
  319. package/dist/operator-toolkit.js +29 -17
  320. package/dist/opik-exporter.js +1 -0
  321. package/dist/opik-exporter.js.map +1 -1
  322. package/dist/{orchestrator-CmJ-NTdJ.d.ts → orchestrator-ChkesB8U.d.ts} +177 -13
  323. package/dist/orchestrator.d.ts +6 -4
  324. package/dist/orchestrator.js +57 -41
  325. package/dist/page-versioning.js +1 -0
  326. package/dist/path-RMTY5Y5A.js +9 -0
  327. package/dist/path-RMTY5Y5A.js.map +1 -0
  328. package/dist/patterns-cli.d.ts +160 -0
  329. package/dist/patterns-cli.js +29 -0
  330. package/dist/patterns-cli.js.map +1 -0
  331. package/dist/peers-6OSQ3NK6.js +44 -0
  332. package/dist/peers-6OSQ3NK6.js.map +1 -0
  333. package/dist/plugin-id.js +1 -0
  334. package/dist/policy-runtime.js +1 -0
  335. package/dist/{port-BADbLZU5.d.ts → port-hqGnoStS.d.ts} +6 -0
  336. package/dist/profiling.js +1 -0
  337. package/dist/purge-6ATBGT77.js +205 -0
  338. package/dist/purge-6ATBGT77.js.map +1 -0
  339. package/dist/qmd-recall-cache.d.ts +1 -1
  340. package/dist/qmd-recall-cache.js +1 -0
  341. package/dist/qmd.d.ts +2 -1
  342. package/dist/qmd.js +4 -3
  343. package/dist/reasoning-trace-recall.js +1 -0
  344. package/dist/reasoning-trace-types.js +1 -0
  345. package/dist/recall-audit-anomaly.js +1 -0
  346. package/dist/recall-audit.js +1 -0
  347. package/dist/recall-disclosure-escalation.d.ts +84 -0
  348. package/dist/recall-disclosure-escalation.js +14 -0
  349. package/dist/recall-disclosure-escalation.js.map +1 -0
  350. package/dist/recall-explain-renderer.js +4 -1
  351. package/dist/recall-mmr.js +1 -0
  352. package/dist/recall-qos.js +1 -0
  353. package/dist/recall-query-policy.js +1 -0
  354. package/dist/recall-state.d.ts +7 -0
  355. package/dist/recall-state.js +2 -1
  356. package/dist/recall-tag-filter.d.ts +56 -0
  357. package/dist/recall-tag-filter.js +14 -0
  358. package/dist/recall-tag-filter.js.map +1 -0
  359. package/dist/recall-tokenization.js +1 -0
  360. package/dist/recall-xray-cli.d.ts +9 -2
  361. package/dist/recall-xray-cli.js +9 -4
  362. package/dist/recall-xray-renderer.js +4 -1
  363. package/dist/recall-xray.d.ts +116 -2
  364. package/dist/recall-xray.js +9 -3
  365. package/dist/reconstruct.js +1 -0
  366. package/dist/release-changelog.js +2 -0
  367. package/dist/release-changelog.js.map +1 -1
  368. package/dist/relevance.js +1 -0
  369. package/dist/rerank.js +1 -0
  370. package/dist/{resolution-QBTDHTG7.js → resolution-YGIBORXI.js} +2 -1
  371. package/dist/{resolution-QBTDHTG7.js.map → resolution-YGIBORXI.js.map} +1 -1
  372. package/dist/resolve-auth-token.d.ts +51 -0
  373. package/dist/resolve-auth-token.js +12 -0
  374. package/dist/resolve-auth-token.js.map +1 -0
  375. package/dist/resolve-provider-secret.d.ts +9 -1
  376. package/dist/resolve-provider-secret.js +4 -1
  377. package/dist/resume-bundles.js +4 -3
  378. package/dist/retrieval-agents.d.ts +1 -1
  379. package/dist/retrieval-agents.js +1 -0
  380. package/dist/retrieval-tiers.js +1 -0
  381. package/dist/retrieval.js +1 -0
  382. package/dist/sanitize.js +1 -0
  383. package/dist/schemas.d.ts +15 -2
  384. package/dist/schemas.js +2 -1
  385. package/dist/sdk-compat.js +1 -0
  386. package/dist/sdk-compat.js.map +1 -1
  387. package/dist/secure-store-4R2GSO7S.js +156 -0
  388. package/dist/secure-store-4R2GSO7S.js.map +1 -0
  389. package/dist/semantic-chunking.js +1 -0
  390. package/dist/{semantic-consolidation-CxJU6MJk.d.ts → semantic-consolidation-ByBXb-sf.d.ts} +3 -3
  391. package/dist/semantic-consolidation.d.ts +2 -2
  392. package/dist/semantic-consolidation.js +12 -7
  393. package/dist/semantic-rule-promotion.d.ts +1 -1
  394. package/dist/semantic-rule-promotion.js +10 -7
  395. package/dist/semantic-rule-verifier.d.ts +1 -1
  396. package/dist/semantic-rule-verifier.js +10 -7
  397. package/dist/session-integrity.js +1 -0
  398. package/dist/session-observer-bands.js +1 -0
  399. package/dist/session-observer-state.js +1 -0
  400. package/dist/session-toggles.js +2 -0
  401. package/dist/session-toggles.js.map +1 -1
  402. package/dist/signal.js +1 -0
  403. package/dist/skills-registry.js +2 -0
  404. package/dist/skills-registry.js.map +1 -1
  405. package/dist/source-attribution.js +1 -0
  406. package/dist/state-NCHQ4TRG.js +8 -0
  407. package/dist/state-NCHQ4TRG.js.map +1 -0
  408. package/dist/state-store-3EH7HYIN.js +16 -0
  409. package/dist/state-store-3EH7HYIN.js.map +1 -0
  410. package/dist/storage.d.ts +76 -2
  411. package/dist/storage.js +9 -6
  412. package/dist/store-contract.js +1 -0
  413. package/dist/summarizer.js +5 -4
  414. package/dist/summary-snapshot.js +1 -0
  415. package/dist/temporal-index.js +1 -0
  416. package/dist/temporal-supersession.d.ts +1 -1
  417. package/dist/temporal-supersession.js +2 -1
  418. package/dist/temporal-validity.d.ts +52 -0
  419. package/dist/temporal-validity.js +14 -0
  420. package/dist/temporal-validity.js.map +1 -0
  421. package/dist/threading.js +1 -0
  422. package/dist/tier-migration.d.ts +2 -2
  423. package/dist/tier-migration.js +1 -0
  424. package/dist/tier-routing.js +1 -0
  425. package/dist/tier-stats-62ZVDFKS.js +152 -0
  426. package/dist/tier-stats-62ZVDFKS.js.map +1 -0
  427. package/dist/tmt.js +1 -0
  428. package/dist/tokens.js +1 -0
  429. package/dist/topics.js +1 -0
  430. package/dist/trace-C5ETWBEF.js +290 -0
  431. package/dist/trace-C5ETWBEF.js.map +1 -0
  432. package/dist/transcript.js +1 -0
  433. package/dist/trust-zones.js +1 -0
  434. package/dist/tui-RI7P6PBS.js +13 -0
  435. package/dist/tui-RI7P6PBS.js.map +1 -0
  436. package/dist/types-V3FJ26TF.js +30 -0
  437. package/dist/types-V3FJ26TF.js.map +1 -0
  438. package/dist/types.d.ts +634 -9
  439. package/dist/types.js +10 -3
  440. package/dist/utility-learner.js +1 -0
  441. package/dist/utility-runtime.js +1 -0
  442. package/dist/utility-telemetry.js +1 -0
  443. package/dist/verified-recall.js +10 -7
  444. package/dist/version-utils.js +1 -0
  445. package/dist/whitespace.js +1 -0
  446. package/dist/work-product-ledger.js +1 -0
  447. package/package.json +7 -3
  448. package/scripts/ensure-better-sqlite3.mjs +124 -0
  449. package/dist/access-service-Br8ZydTK.d.ts +0 -827
  450. package/dist/chunk-3OGMS3PE.js.map +0 -1
  451. package/dist/chunk-3YGHKTBF.js.map +0 -1
  452. package/dist/chunk-6PFRXT4K.js.map +0 -1
  453. package/dist/chunk-6YJHX2DL.js.map +0 -1
  454. package/dist/chunk-BECYBZLX.js.map +0 -1
  455. package/dist/chunk-C2EFFULQ.js.map +0 -1
  456. package/dist/chunk-CUPFXL3J.js.map +0 -1
  457. package/dist/chunk-DIXB44VE.js.map +0 -1
  458. package/dist/chunk-F5VP6YCB.js.map +0 -1
  459. package/dist/chunk-FVA6TGI3.js.map +0 -1
  460. package/dist/chunk-GA5P7RST.js.map +0 -1
  461. package/dist/chunk-KVBLZUKV.js.map +0 -1
  462. package/dist/chunk-L7IXWRYE.js.map +0 -1
  463. package/dist/chunk-LOIMBRDE.js.map +0 -1
  464. package/dist/chunk-LTCGGW2D.js +0 -14
  465. package/dist/chunk-LTCGGW2D.js.map +0 -1
  466. package/dist/chunk-NZLQTHS5.js.map +0 -1
  467. package/dist/chunk-OC5OXUQ4.js.map +0 -1
  468. package/dist/chunk-PVPWZSSI.js.map +0 -1
  469. package/dist/chunk-SPI27QT6.js.map +0 -1
  470. package/dist/chunk-STGWEHYR.js.map +0 -1
  471. package/dist/chunk-TP4FZJIZ.js.map +0 -1
  472. package/dist/chunk-ULYOGL6R.js.map +0 -1
  473. package/dist/chunk-UWB5LMWY.js.map +0 -1
  474. package/dist/chunk-VBVG2M5G.js.map +0 -1
  475. package/dist/chunk-VDX363PS.js.map +0 -1
  476. package/dist/chunk-WCLICCGB.js.map +0 -1
  477. package/dist/chunk-X6GF3FX2.js +0 -26
  478. package/dist/chunk-X6GF3FX2.js.map +0 -1
  479. package/dist/chunk-XXVWLXSG.js.map +0 -1
  480. package/dist/chunk-Y7R2XJ5Q.js.map +0 -1
  481. package/dist/chunk-ZAIM4TUE.js.map +0 -1
  482. package/dist/engine-72LSIWQP.js +0 -23
  483. /package/dist/{contradiction-review-WIUBAR52.js.map → capsule-cli.js.map} +0 -0
  484. /package/dist/{engine-72LSIWQP.js.map → capsule-crypto-5CYAGVC5.js.map} +0 -0
  485. /package/dist/{chunk-TMYO7B5P.js.map → chunk-47WOM4YW.js.map} +0 -0
  486. /package/dist/{chunk-DG6YMRDC.js.map → chunk-B2TL6GA2.js.map} +0 -0
  487. /package/dist/{chunk-AYXIPSZO.js.map → chunk-CRU27Q4J.js.map} +0 -0
  488. /package/dist/{chunk-RBBWYEFJ.js.map → chunk-G2WADRQ3.js.map} +0 -0
  489. /package/dist/{chunk-NBVAS5MT.js.map → chunk-V7TEH5I2.js.map} +0 -0
@@ -2,20 +2,12 @@ import {
2
2
  CompoundingEngine,
3
3
  SharedContextManager,
4
4
  defaultTierMigrationCycleBudget
5
- } from "./chunk-XXVWLXSG.js";
6
- import {
7
- extractTopics
8
- } from "./chunk-UHGBNIOS.js";
5
+ } from "./chunk-XQ4EJLUD.js";
9
6
  import {
10
7
  applyUtilityPromotionRuntimePolicy,
11
8
  applyUtilityRankingRuntimeDelta,
12
9
  loadUtilityRuntimeValues
13
10
  } from "./chunk-FSFEQI74.js";
14
- import {
15
- applyTemporalSupersession,
16
- normalizeSupersessionKey,
17
- shouldFilterSupersededFromRecall
18
- } from "./chunk-W6SL7OFG.js";
19
11
  import {
20
12
  TierMigrationExecutor
21
13
  } from "./chunk-Z5AAYHUC.js";
@@ -25,12 +17,29 @@ import {
25
17
  import {
26
18
  TmtBuilder
27
19
  } from "./chunk-TPB3I2AC.js";
20
+ import {
21
+ extractTopics
22
+ } from "./chunk-UHGBNIOS.js";
23
+ import {
24
+ HourlySummarizer
25
+ } from "./chunk-B2TL6GA2.js";
26
+ import {
27
+ applyTemporalSupersession,
28
+ normalizeSupersessionKey,
29
+ shouldFilterSupersededFromRecall
30
+ } from "./chunk-ZTSE2ZJ6.js";
31
+ import {
32
+ isValidAsOf
33
+ } from "./chunk-MDYG7VI7.js";
28
34
  import {
29
35
  SessionObserverState
30
36
  } from "./chunk-JR4ZC3G4.js";
31
37
  import {
32
- HourlySummarizer
33
- } from "./chunk-DG6YMRDC.js";
38
+ applyRuntimeRetrievalPolicy
39
+ } from "./chunk-5IZL4DCV.js";
40
+ import {
41
+ findUnresolvedEntityRefs
42
+ } from "./chunk-X7XN6YU4.js";
34
43
  import {
35
44
  RelevanceStore
36
45
  } from "./chunk-5NPGSAVB.js";
@@ -57,28 +66,19 @@ import {
57
66
  resolvePromptTagPrefilterAsync
58
67
  } from "./chunk-V3RXWQIE.js";
59
68
  import {
60
- applyRuntimeRetrievalPolicy
61
- } from "./chunk-5IZL4DCV.js";
69
+ createRecallSectionMetricRecorder
70
+ } from "./chunk-7DHTMOND.js";
62
71
  import {
63
72
  LastRecallStore,
64
73
  TierMigrationStatusStore,
65
74
  clampGraphRecallExpandedEntries
66
- } from "./chunk-VBVG2M5G.js";
67
- import {
68
- buildXraySnapshot
69
- } from "./chunk-KVBLZUKV.js";
70
- import {
71
- findUnresolvedEntityRefs
72
- } from "./chunk-X7XN6YU4.js";
75
+ } from "./chunk-WPGJYVUH.js";
73
76
  import {
74
77
  applyReasoningTraceBoost
75
78
  } from "./chunk-ZZTOURJI.js";
76
79
  import {
77
80
  reorderRecallResultsWithMmr
78
81
  } from "./chunk-YDBIWGNI.js";
79
- import {
80
- createRecallSectionMetricRecorder
81
- } from "./chunk-7DHTMOND.js";
82
82
  import {
83
83
  buildQmdRecallCacheKey,
84
84
  getCachedQmdRecall,
@@ -87,13 +87,19 @@ import {
87
87
  import {
88
88
  NegativeExampleStore
89
89
  } from "./chunk-D654IBA6.js";
90
- import {
91
- evaluateMemoryActionPolicy
92
- } from "./chunk-H63EDPFJ.js";
93
90
  import {
94
91
  applyMemoryWorthFilter,
95
92
  buildMemoryWorthCounterMap
96
93
  } from "./chunk-3GPTTA4J.js";
94
+ import {
95
+ runLiveConnectorsOnce
96
+ } from "./chunk-ASIQZXYO.js";
97
+ import {
98
+ evaluateMemoryActionPolicy
99
+ } from "./chunk-H63EDPFJ.js";
100
+ import {
101
+ classifyMemoryKind
102
+ } from "./chunk-YAZNBMNF.js";
97
103
  import {
98
104
  hasBroadGraphIntent,
99
105
  inferIntentFromText,
@@ -101,13 +107,6 @@ import {
101
107
  isTaskInitiationIntent,
102
108
  planRecallMode
103
109
  } from "./chunk-GGD5W7TB.js";
104
- import {
105
- classifyMemoryKind
106
- } from "./chunk-YAZNBMNF.js";
107
- import {
108
- EXTRACTION_JUDGE_VERDICT_CATEGORY,
109
- recordJudgeVerdict
110
- } from "./chunk-AJU4PJGY.js";
111
110
  import {
112
111
  recordJudgeTrainingPair
113
112
  } from "./chunk-DF3RVK3X.js";
@@ -120,19 +119,19 @@ import {
120
119
  } from "./chunk-C4SQJZAF.js";
121
120
  import {
122
121
  ExtractionEngine
123
- } from "./chunk-DIXB44VE.js";
122
+ } from "./chunk-X6VBWOVZ.js";
124
123
  import {
125
124
  parseMemoryActionEligibilityContext
126
- } from "./chunk-NZLQTHS5.js";
127
- import {
128
- ProfilingCollector
129
- } from "./chunk-NBNN5GOB.js";
125
+ } from "./chunk-WW3QQF4H.js";
130
126
  import {
131
127
  ModelRegistry
132
128
  } from "./chunk-FEMOX5AD.js";
133
129
  import {
134
130
  LocalLlmClient
135
131
  } from "./chunk-R2XRID2N.js";
132
+ import {
133
+ formatDaySummaryMemories
134
+ } from "./chunk-GZCUW5IC.js";
136
135
  import {
137
136
  tryDirectAnswer
138
137
  } from "./chunk-6AUUAZEX.js";
@@ -143,30 +142,38 @@ import {
143
142
  buildEntityRecallSection,
144
143
  entityRecentTranscriptLookbackHours,
145
144
  readRecentEntityTranscriptEntries
146
- } from "./chunk-FVA6TGI3.js";
145
+ } from "./chunk-52PDY6GD.js";
147
146
  import {
148
- formatDaySummaryMemories
149
- } from "./chunk-GZCUW5IC.js";
147
+ buildCompressionGuidelinesMarkdown,
148
+ computeCompressionGuidelineCandidate,
149
+ refineCompressionGuidelineCandidateSemantically,
150
+ renderCompressionGuidelinesMarkdown
151
+ } from "./chunk-2NMMFZ5T.js";
150
152
  import {
151
153
  RoutingRulesStore,
152
- expandTildePath,
153
154
  normalizeReplaySessionKey
154
- } from "./chunk-GA5P7RST.js";
155
+ } from "./chunk-VTJVUHRK.js";
155
156
  import {
156
157
  searchVerifiedEpisodes
157
- } from "./chunk-CUPFXL3J.js";
158
+ } from "./chunk-EGEPUGN4.js";
158
159
  import {
159
160
  ThreadingManager
160
161
  } from "./chunk-JRNQ3RNA.js";
161
162
  import {
162
163
  searchVerifiedSemanticRules
163
- } from "./chunk-SPI27QT6.js";
164
+ } from "./chunk-W7WWT4FJ.js";
164
165
  import {
165
166
  searchWorkProductLedgerEntries
166
167
  } from "./chunk-CULXMQJH.js";
167
168
  import {
168
169
  TranscriptManager
169
170
  } from "./chunk-E6K4NIEU.js";
171
+ import {
172
+ PolicyRuntimeManager
173
+ } from "./chunk-EABGC2TL.js";
174
+ import {
175
+ searchObjectiveStateSnapshots
176
+ } from "./chunk-LOBRX7VD.js";
170
177
  import {
171
178
  NamespaceSearchRouter,
172
179
  NamespaceStorageRouter,
@@ -174,16 +181,10 @@ import {
174
181
  createConversationIndexRuntime,
175
182
  createSearchBackend,
176
183
  writeConversationChunks
177
- } from "./chunk-NBVAS5MT.js";
184
+ } from "./chunk-V7TEH5I2.js";
178
185
  import {
179
186
  parseQmdExplain
180
- } from "./chunk-4HQS2HPX.js";
181
- import {
182
- PolicyRuntimeManager
183
- } from "./chunk-EABGC2TL.js";
184
- import {
185
- searchObjectiveStateSnapshots
186
- } from "./chunk-LOBRX7VD.js";
187
+ } from "./chunk-WSZIHQBK.js";
187
188
  import {
188
189
  searchHarmonicRetrieval
189
190
  } from "./chunk-HMDCOMYU.js";
@@ -192,31 +193,23 @@ import {
192
193
  scoreImportance
193
194
  } from "./chunk-JXS5PDQ7.js";
194
195
  import {
195
- launchProcessSync
196
- } from "./chunk-OR64ZGRZ.js";
196
+ recordEvalShadowRecall
197
+ } from "./chunk-K6WK37A6.js";
198
+ import {
199
+ EXTRACTION_JUDGE_VERDICT_CATEGORY,
200
+ recordJudgeVerdict
201
+ } from "./chunk-AJU4PJGY.js";
197
202
  import {
198
203
  collectNativeKnowledgeChunks,
199
204
  formatNativeKnowledgeSection,
200
205
  searchNativeKnowledge
201
206
  } from "./chunk-7SEAZFFB.js";
202
- import {
203
- recordEvalShadowRecall
204
- } from "./chunk-K6WK37A6.js";
205
- import {
206
- GraphIndex
207
- } from "./chunk-C2EFFULQ.js";
208
207
  import {
209
208
  CODEX_THREAD_KEY_PREFIX
210
209
  } from "./chunk-3PG3H5TD.js";
211
210
  import {
212
211
  applyCommitmentLedgerLifecycle
213
212
  } from "./chunk-FYIYMQ5N.js";
214
- import {
215
- buildCompressionGuidelinesMarkdown,
216
- computeCompressionGuidelineCandidate,
217
- refineCompressionGuidelineCandidateSemantically,
218
- renderCompressionGuidelinesMarkdown
219
- } from "./chunk-2NMMFZ5T.js";
220
213
  import {
221
214
  semanticChunkContent
222
215
  } from "./chunk-KVE7R4CG.js";
@@ -235,10 +228,10 @@ import {
235
228
  materializeAfterSemanticConsolidation,
236
229
  parseConsolidationResponse,
237
230
  parseOperatorAwareConsolidationResponse
238
- } from "./chunk-PVICZTKG.js";
231
+ } from "./chunk-AGZHRWPT.js";
239
232
  import {
240
233
  FallbackLlmClient
241
- } from "./chunk-AYXIPSZO.js";
234
+ } from "./chunk-CRU27Q4J.js";
242
235
  import {
243
236
  buildRecallQueryPolicy
244
237
  } from "./chunk-6HZ6AO2P.js";
@@ -260,22 +253,38 @@ import {
260
253
  isAbortError,
261
254
  throwIfAborted
262
255
  } from "./chunk-PVGDJXVK.js";
256
+ import {
257
+ clusterByKey,
258
+ stableHash
259
+ } from "./chunk-NN3TS5BM.js";
263
260
  import {
264
261
  listTrustZoneRecords,
265
262
  searchTrustZoneRecords
266
263
  } from "./chunk-EQINRHYR.js";
267
264
  import {
268
- buildProcedurePersistBody
269
- } from "./chunk-QDW3E4RD.js";
265
+ buildXraySnapshot
266
+ } from "./chunk-USFPPRAF.js";
270
267
  import {
271
268
  shouldSkipImplicitExtraction
272
269
  } from "./chunk-3FPTCC3Z.js";
273
270
  import {
274
271
  selectRouteRule
275
272
  } from "./chunk-2LGMW3DJ.js";
273
+ import {
274
+ ProfilingCollector
275
+ } from "./chunk-NBNN5GOB.js";
276
+ import {
277
+ launchProcessSync
278
+ } from "./chunk-OR64ZGRZ.js";
279
+ import {
280
+ buildProcedurePersistBody
281
+ } from "./chunk-QDW3E4RD.js";
282
+ import {
283
+ GraphIndex
284
+ } from "./chunk-RK2Y4XOM.js";
276
285
  import {
277
286
  searchCausalTrajectories
278
- } from "./chunk-RBBWYEFJ.js";
287
+ } from "./chunk-G2WADRQ3.js";
279
288
  import {
280
289
  canReadNamespace,
281
290
  defaultNamespaceForPrincipal,
@@ -294,18 +303,21 @@ import {
294
303
  normalizeAttributePairs,
295
304
  normalizeEntityName,
296
305
  parseEntityFile
297
- } from "./chunk-F5VP6YCB.js";
298
- import {
299
- confidenceTier
300
- } from "./chunk-LTCGGW2D.js";
306
+ } from "./chunk-Y4A6M3B6.js";
301
307
  import {
302
308
  attachCitation,
303
309
  hasCitationForTemplate,
304
310
  stripCitationForTemplate
305
311
  } from "./chunk-4KAN3GZ3.js";
312
+ import {
313
+ confidenceTier
314
+ } from "./chunk-43EKP2UK.js";
315
+ import {
316
+ isActiveMemoryStatus
317
+ } from "./chunk-RULE4VG5.js";
306
318
  import {
307
319
  openBetterSqlite3
308
- } from "./chunk-BOUYNNYD.js";
320
+ } from "./chunk-67YLUWLG.js";
309
321
  import {
310
322
  lintWorkspaceFiles,
311
323
  rotateMarkdownFileToArchive
@@ -319,9 +331,13 @@ import {
319
331
  import {
320
332
  log
321
333
  } from "./chunk-2ODBA7MQ.js";
334
+ import {
335
+ keyring_exports,
336
+ secureStoreDir
337
+ } from "./chunk-BJMBJZ2Y.js";
322
338
 
323
339
  // src/orchestrator.ts
324
- import path7 from "path";
340
+ import path6 from "path";
325
341
  import os from "os";
326
342
  import { createHash as createHash2, randomBytes } from "crypto";
327
343
  import { existsSync as existsSync2 } from "fs";
@@ -919,7 +935,7 @@ async function buildProcedureRecallSection(storage, prompt, config) {
919
935
  );
920
936
  const all = await storage.readAllMemories();
921
937
  const scored = all.filter(
922
- (m) => m.frontmatter.category === "procedure" && m.frontmatter.status !== "pending_review" && m.frontmatter.status !== "rejected" && m.frontmatter.status !== "quarantined" && m.frontmatter.status !== "superseded" && m.frontmatter.status !== "archived"
938
+ (m) => m.frontmatter.category === "procedure" && isActiveMemoryStatus(m.frontmatter.status)
923
939
  ).map((m) => ({ m, score: scoreProcedureForPrompt(m, trimmed, queryIntent) })).filter((x) => x.score > 0.04).sort((a, b) => b.score - a.score).slice(0, maxN);
924
940
  if (scored.length === 0) return null;
925
941
  const blocks = scored.map(({ m, score }) => {
@@ -943,6 +959,8 @@ var DAY_SUMMARY_CRON_ID = "engram-day-summary";
943
959
  var GOVERNANCE_CRON_ID = "engram-nightly-governance";
944
960
  var PROCEDURAL_MINING_CRON_ID = "engram-procedural-mining";
945
961
  var CONTRADICTION_SCAN_CRON_ID = "engram-contradiction-scan";
962
+ var PATTERN_REINFORCEMENT_CRON_ID = "engram-pattern-reinforcement";
963
+ var GRAPH_EDGE_DECAY_CRON_ID = "engram-graph-edge-decay";
946
964
  async function acquireCronJobsLock(jobsPath) {
947
965
  const lockPath2 = `${jobsPath}.lock`;
948
966
  const start = Date.now();
@@ -1103,6 +1121,202 @@ async function ensureContradictionScanCron(jobsPath, options) {
1103
1121
  delivery: { mode: "none" }
1104
1122
  }));
1105
1123
  }
1124
+ async function ensurePatternReinforcementCron(jobsPath, options) {
1125
+ const scheduleExpr = typeof options.scheduleExpr === "string" && options.scheduleExpr.trim().length > 0 ? options.scheduleExpr.trim() : "53 4 * * 0";
1126
+ const agentId = typeof options.agentId === "string" && options.agentId.trim().length > 0 ? options.agentId.trim() : "main";
1127
+ return ensureCronJob(jobsPath, PATTERN_REINFORCEMENT_CRON_ID, () => ({
1128
+ id: PATTERN_REINFORCEMENT_CRON_ID,
1129
+ agentId,
1130
+ name: "Remnic Pattern Reinforcement (weekly)",
1131
+ enabled: true,
1132
+ schedule: {
1133
+ kind: "cron",
1134
+ expr: scheduleExpr,
1135
+ tz: options.timezone
1136
+ },
1137
+ sessionTarget: "isolated",
1138
+ wakeMode: "now",
1139
+ payload: {
1140
+ kind: "agentTurn",
1141
+ timeoutSeconds: 900,
1142
+ thinking: "off",
1143
+ message: "You are OpenClaw automation. Call tool `engram.pattern_reinforcement_run` with empty params. If successful output exactly NO_REPLY. On error output one concise line. Do NOT use message tool."
1144
+ },
1145
+ delivery: { mode: "none" }
1146
+ }));
1147
+ }
1148
+ async function ensureGraphEdgeDecayCron(jobsPath, options) {
1149
+ const scheduleExpr = typeof options.scheduleExpr === "string" && options.scheduleExpr.trim().length > 0 ? options.scheduleExpr.trim() : "13 4 * * 0";
1150
+ const agentId = typeof options.agentId === "string" && options.agentId.trim().length > 0 ? options.agentId.trim() : "main";
1151
+ const scheduleLabel = graphEdgeDecayScheduleLabel(scheduleExpr);
1152
+ return ensureCronJob(jobsPath, GRAPH_EDGE_DECAY_CRON_ID, () => ({
1153
+ id: GRAPH_EDGE_DECAY_CRON_ID,
1154
+ agentId,
1155
+ // Schedule label reflects the actual cron expression (`daily` /
1156
+ // `weekly` / `custom`) so cron dashboards do not show "weekly"
1157
+ // when the schedule is in fact daily — Cursor review on PR #729.
1158
+ name: `Remnic Graph Edge Decay (${scheduleLabel})`,
1159
+ enabled: true,
1160
+ schedule: {
1161
+ kind: "cron",
1162
+ expr: scheduleExpr,
1163
+ tz: options.timezone
1164
+ },
1165
+ sessionTarget: "isolated",
1166
+ wakeMode: "now",
1167
+ payload: {
1168
+ kind: "agentTurn",
1169
+ timeoutSeconds: 900,
1170
+ thinking: "off",
1171
+ message: "You are OpenClaw automation. Call tool `engram.graph_edge_decay_run` with empty params. If successful output exactly NO_REPLY. On error output one concise line. Do NOT use message tool."
1172
+ },
1173
+ delivery: { mode: "none" }
1174
+ }));
1175
+ }
1176
+ function graphEdgeDecayCadenceToCronExpr(cadenceMs) {
1177
+ if (!Number.isFinite(cadenceMs) || cadenceMs <= 0) {
1178
+ return "13 4 * * 0";
1179
+ }
1180
+ const day = 24 * 60 * 60 * 1e3;
1181
+ if (cadenceMs < 7 * day) return "13 4 * * *";
1182
+ return "13 4 * * 0";
1183
+ }
1184
+ function graphEdgeDecayScheduleLabel(scheduleExpr) {
1185
+ if (scheduleExpr === "13 4 * * *") return "daily";
1186
+ if (scheduleExpr === "13 4 * * 0") return "weekly";
1187
+ return "custom";
1188
+ }
1189
+
1190
+ // src/maintenance/pattern-reinforcement.ts
1191
+ function patternReinforcementKey(content) {
1192
+ return content.trim().toLowerCase().replace(/\s+/g, " ").slice(0, 200);
1193
+ }
1194
+ function patternReinforcementClusterKey(category, content) {
1195
+ return `${category}::${patternReinforcementKey(content)}`;
1196
+ }
1197
+ function pickCanonical(memories) {
1198
+ let best = memories[0];
1199
+ let bestInstant = memoryInstant(best);
1200
+ let bestStamp = memoryStamp(best);
1201
+ for (let i = 1; i < memories.length; i += 1) {
1202
+ const candidate = memories[i];
1203
+ const instant = memoryInstant(candidate);
1204
+ const stamp = memoryStamp(candidate);
1205
+ let cmp;
1206
+ if (instant !== null && bestInstant !== null) {
1207
+ cmp = instant - bestInstant;
1208
+ } else {
1209
+ cmp = stamp.localeCompare(bestStamp);
1210
+ }
1211
+ if (cmp > 0 || cmp === 0 && candidate.frontmatter.id > best.frontmatter.id) {
1212
+ best = candidate;
1213
+ bestInstant = instant;
1214
+ bestStamp = stamp;
1215
+ }
1216
+ }
1217
+ return best;
1218
+ }
1219
+ function memoryStamp(memory) {
1220
+ return memory.frontmatter.updated || memory.frontmatter.created || "";
1221
+ }
1222
+ function memoryInstant(memory) {
1223
+ const stamp = memoryStamp(memory);
1224
+ if (stamp.length === 0) return null;
1225
+ const parsed = Date.parse(stamp);
1226
+ return Number.isFinite(parsed) ? parsed : null;
1227
+ }
1228
+ var ACTIVE_STATUS = "active";
1229
+ async function runPatternReinforcement(storage, options) {
1230
+ const minCount = Math.max(2, Math.floor(options.minCount));
1231
+ const targetCategories = new Set(options.categories);
1232
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1233
+ const nowIso = now().toISOString();
1234
+ if (targetCategories.size === 0) {
1235
+ return emptyResult();
1236
+ }
1237
+ const memories = await storage.readAllMemories();
1238
+ const eligible = memories.filter((m) => {
1239
+ if (!targetCategories.has(m.frontmatter.category)) return false;
1240
+ const status = m.frontmatter.status ?? ACTIVE_STATUS;
1241
+ return status === ACTIVE_STATUS || status === "superseded";
1242
+ });
1243
+ if (eligible.length === 0) return emptyResult();
1244
+ const clusters = clusterByKey(
1245
+ eligible,
1246
+ (m) => patternReinforcementClusterKey(m.frontmatter.category, m.content)
1247
+ );
1248
+ const result = {
1249
+ clustersFound: 0,
1250
+ canonicalsUpdated: 0,
1251
+ duplicatesSuperseded: 0,
1252
+ clusters: []
1253
+ };
1254
+ for (const cluster of clusters.values()) {
1255
+ if (cluster.length < minCount) continue;
1256
+ const activeMembers = cluster.filter((m) => {
1257
+ const status = m.frontmatter.status ?? ACTIVE_STATUS;
1258
+ return status === ACTIVE_STATUS;
1259
+ });
1260
+ if (activeMembers.length === 0) continue;
1261
+ result.clustersFound += 1;
1262
+ const canonical = pickCanonical(activeMembers);
1263
+ const activeDuplicates = activeMembers.filter((m) => m !== canonical);
1264
+ const sourceIds = [...cluster].map((m) => m.frontmatter.id).filter((id) => typeof id === "string" && id.length > 0).sort();
1265
+ const previousCount = canonical.frontmatter.reinforcement_count ?? 0;
1266
+ const newCount = sourceIds.length;
1267
+ const reinforcementBumped = newCount > previousCount;
1268
+ const previousDerivedFrom = Array.isArray(canonical.frontmatter.derived_from) ? [...canonical.frontmatter.derived_from].sort() : [];
1269
+ const sortedSourceIds = [...sourceIds].sort();
1270
+ const membershipChanged = previousDerivedFrom.length !== sortedSourceIds.length || previousDerivedFrom.some((id, i) => id !== sortedSourceIds[i]);
1271
+ const previousVia = canonical.frontmatter.derived_via;
1272
+ const viaChanged = previousVia !== "pattern-reinforcement";
1273
+ const canonicalNeedsRefresh = reinforcementBumped || membershipChanged || viaChanged;
1274
+ if (canonicalNeedsRefresh) {
1275
+ const patch = {
1276
+ derived_from: sourceIds,
1277
+ derived_via: "pattern-reinforcement",
1278
+ updated: nowIso
1279
+ };
1280
+ if (reinforcementBumped) {
1281
+ patch.reinforcement_count = newCount;
1282
+ patch.last_reinforced_at = nowIso;
1283
+ } else {
1284
+ patch.reinforcement_count = canonical.frontmatter.reinforcement_count ?? newCount;
1285
+ patch.last_reinforced_at = canonical.frontmatter.last_reinforced_at ?? nowIso;
1286
+ }
1287
+ await storage.writeMemoryFrontmatter(canonical, patch);
1288
+ result.canonicalsUpdated += 1;
1289
+ }
1290
+ const supersededIds = [];
1291
+ for (const dup of activeDuplicates) {
1292
+ const patch = {
1293
+ status: "superseded",
1294
+ supersededBy: canonical.frontmatter.id,
1295
+ supersededAt: nowIso,
1296
+ updated: nowIso
1297
+ };
1298
+ await storage.writeMemoryFrontmatter(dup, patch);
1299
+ supersededIds.push(dup.frontmatter.id);
1300
+ result.duplicatesSuperseded += 1;
1301
+ }
1302
+ result.clusters.push({
1303
+ canonicalId: canonical.frontmatter.id,
1304
+ count: newCount,
1305
+ sourceIds,
1306
+ supersededIds,
1307
+ reinforcementBumped
1308
+ });
1309
+ }
1310
+ return result;
1311
+ }
1312
+ function emptyResult() {
1313
+ return {
1314
+ clustersFound: 0,
1315
+ canonicalsUpdated: 0,
1316
+ duplicatesSuperseded: 0,
1317
+ clusters: []
1318
+ };
1319
+ }
1106
1320
 
1107
1321
  // src/dedup/semantic.ts
1108
1322
  async function decideSemanticDedup(content, lookup, options) {
@@ -1412,6 +1626,9 @@ function openLcmDatabase(memoryDir) {
1412
1626
  async function ensureLcmStateDir(memoryDir) {
1413
1627
  await mkdir4(path4.join(memoryDir, "state"), { recursive: true });
1414
1628
  }
1629
+ function applyLcmSchema(db) {
1630
+ applySchema(db);
1631
+ }
1415
1632
  function applySchema(db) {
1416
1633
  const versionRow = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='lcm_meta'").get();
1417
1634
  if (!versionRow) {
@@ -2706,119 +2923,6 @@ async function cleanupConversationChunks(rootDir, retentionDays) {
2706
2923
  }
2707
2924
  }
2708
2925
 
2709
- // src/coding/git-context.ts
2710
- import path6 from "path";
2711
- var DEFAULT_GIT_TIMEOUT_MS = 2e3;
2712
- function defaultGitInvoker() {
2713
- return (cwd, args) => {
2714
- const result = launchProcessSync("git", args, {
2715
- cwd,
2716
- encoding: "utf-8",
2717
- timeout: DEFAULT_GIT_TIMEOUT_MS,
2718
- shell: false
2719
- });
2720
- if (result.error) {
2721
- return { stdout: "", exitCode: 127 };
2722
- }
2723
- return {
2724
- stdout: typeof result.stdout === "string" ? result.stdout : "",
2725
- exitCode: typeof result.status === "number" ? result.status : 1
2726
- };
2727
- };
2728
- }
2729
- function stableHash(input) {
2730
- let hash = 2166136261;
2731
- for (let i = 0; i < input.length; i++) {
2732
- hash ^= input.charCodeAt(i);
2733
- hash = Math.imul(hash, 16777619) >>> 0;
2734
- }
2735
- return hash.toString(16).padStart(8, "0");
2736
- }
2737
- function normalizeOriginUrl(rawUrl) {
2738
- let url = rawUrl.trim();
2739
- if (!url) return "";
2740
- if (/\.git$/i.test(url)) url = url.slice(0, -4);
2741
- if (/^[A-Za-z]:[\\/]/.test(url)) {
2742
- return url.toLowerCase();
2743
- }
2744
- const protoMatch = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?(\[[^\]]+\]|[^/:]*)(?::(\d+))?(\/.*)?$/i.exec(url);
2745
- if (protoMatch) {
2746
- let host = protoMatch[1] ?? "";
2747
- const wasBracketed = host.startsWith("[") && host.endsWith("]");
2748
- if (wasBracketed) host = host.slice(1, -1);
2749
- const port = protoMatch[2];
2750
- const repoPath = (protoMatch[3] ?? "").replace(/^\/+/, "");
2751
- const hostPort = port ? wasBracketed ? `[${host}]:${port}` : `${host}:${port}` : host;
2752
- const prefix = hostPort.length > 0 ? hostPort : "localhost";
2753
- return `${prefix}/${repoPath}`.toLowerCase();
2754
- }
2755
- const scpMatch = /^(?:([^@\s/]+)@)?(\[[^\]]+\]|[^:@\s/]+):(.+)$/.exec(url);
2756
- if (scpMatch) {
2757
- let host = scpMatch[2] ?? "";
2758
- if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
2759
- const repoPath = scpMatch[3] ?? "";
2760
- if (repoPath.startsWith("//")) {
2761
- return url.toLowerCase();
2762
- }
2763
- return `${host}/${repoPath.replace(/^\/+/, "")}`.toLowerCase();
2764
- }
2765
- return url.toLowerCase();
2766
- }
2767
- async function resolveGitContext(cwd, options = {}) {
2768
- try {
2769
- if (typeof cwd !== "string" || cwd.length === 0) return null;
2770
- const expanded = expandTildePath(cwd);
2771
- if (!path6.isAbsolute(expanded)) return null;
2772
- const invoker = options.invoker ?? defaultGitInvoker();
2773
- const topLevel = invoker(expanded, ["rev-parse", "--show-toplevel"]);
2774
- if (topLevel.exitCode !== 0) return null;
2775
- const rootPath = topLevel.stdout.trim();
2776
- if (!rootPath) return null;
2777
- const branchResult = invoker(rootPath, ["rev-parse", "--abbrev-ref", "HEAD"]);
2778
- let branch = null;
2779
- if (branchResult.exitCode === 0) {
2780
- const raw = branchResult.stdout.trim();
2781
- branch = raw && raw !== "HEAD" ? raw : null;
2782
- } else {
2783
- const unbornRef = invoker(rootPath, ["symbolic-ref", "--quiet", "HEAD"]);
2784
- if (unbornRef.exitCode === 0) {
2785
- const raw = unbornRef.stdout.trim();
2786
- const prefix = "refs/heads/";
2787
- if (raw.startsWith(prefix)) {
2788
- const candidate = raw.slice(prefix.length);
2789
- if (candidate) branch = candidate;
2790
- }
2791
- }
2792
- }
2793
- const originResult = invoker(rootPath, ["remote", "get-url", "origin"]);
2794
- let projectId;
2795
- if (originResult.exitCode === 0) {
2796
- const normalized = normalizeOriginUrl(originResult.stdout);
2797
- projectId = normalized ? `origin:${stableHash(normalized)}` : `root:${stableHash(rootPath)}`;
2798
- } else {
2799
- projectId = `root:${stableHash(rootPath)}`;
2800
- }
2801
- const headRef = invoker(rootPath, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
2802
- let defaultBranch = null;
2803
- if (headRef.exitCode === 0) {
2804
- const raw = headRef.stdout.trim();
2805
- const prefix = "refs/remotes/origin/";
2806
- if (raw.startsWith(prefix)) {
2807
- const candidate = raw.slice(prefix.length);
2808
- if (candidate) defaultBranch = candidate;
2809
- }
2810
- }
2811
- return {
2812
- projectId,
2813
- branch,
2814
- rootPath,
2815
- defaultBranch
2816
- };
2817
- } catch {
2818
- return null;
2819
- }
2820
- }
2821
-
2822
2926
  // src/coding/coding-namespace.ts
2823
2927
  function sanitizeFragment(input) {
2824
2928
  if (typeof input !== "string") return "";
@@ -2889,27 +2993,30 @@ function branchNamespaceName(projectId, branch) {
2889
2993
  const suffixed = disambig ? `${base}-${stableHash(trimmedBranch)}` : base;
2890
2994
  return capLength(suffixed);
2891
2995
  }
2892
- function resolveCodingNamespaceOverlay(codingContext, config) {
2996
+ function resolveCodingNamespaceOverlay(codingContext, config, defaultNamespace) {
2893
2997
  if (!codingContext) return null;
2894
2998
  if (!config.projectScope) return null;
2895
2999
  const projectId = typeof codingContext.projectId === "string" ? codingContext.projectId.trim() : "";
2896
3000
  if (!projectId) return null;
2897
3001
  const projectNs = projectNamespaceName(projectId);
3002
+ const includeRoot = config.globalFallback === true;
2898
3003
  if (config.branchScope && typeof codingContext.branch === "string" && codingContext.branch.length > 0) {
2899
3004
  const branchNs = branchNamespaceName(projectId, codingContext.branch);
3005
+ const fallbacks = [projectNs];
3006
+ if (includeRoot) fallbacks.push("");
2900
3007
  return {
2901
3008
  namespace: branchNs,
2902
- readFallbacks: [projectNs],
3009
+ readFallbacks: fallbacks,
2903
3010
  scope: "branch"
2904
3011
  };
2905
3012
  }
2906
3013
  return {
2907
3014
  namespace: projectNs,
2908
- readFallbacks: [],
3015
+ readFallbacks: includeRoot ? [""] : [],
2909
3016
  scope: "project"
2910
3017
  };
2911
3018
  }
2912
- function describeCodingScope(codingContext, config) {
3019
+ function describeCodingScope(codingContext, config, defaultNamespace) {
2913
3020
  const projectId = codingContext?.projectId ?? null;
2914
3021
  const branch = codingContext?.branch ?? null;
2915
3022
  if (!codingContext) {
@@ -2943,7 +3050,7 @@ function describeCodingScope(codingContext, config) {
2943
3050
  disabledReason: "empty-project"
2944
3051
  };
2945
3052
  }
2946
- const overlay = resolveCodingNamespaceOverlay(codingContext, config);
3053
+ const overlay = resolveCodingNamespaceOverlay(codingContext, config, defaultNamespace);
2947
3054
  if (!overlay) {
2948
3055
  return {
2949
3056
  scope: "none",
@@ -3064,7 +3171,7 @@ async function raceRecallAbort(promise, signal, message = "recall aborted") {
3064
3171
  }
3065
3172
  var COMPACTION_SIGNAL_MAX_AGE_MS = 60 * 60 * 1e3;
3066
3173
  function defaultWorkspaceDir() {
3067
- return path7.join(os.homedir(), ".openclaw", "workspace");
3174
+ return path6.join(os.homedir(), ".openclaw", "workspace");
3068
3175
  }
3069
3176
  function sanitizeSessionKeyForFilename(sessionKey) {
3070
3177
  const readable = sessionKey.replace(/[^a-zA-Z0-9._-]/g, "_");
@@ -3232,11 +3339,11 @@ function mergeGraphExpandedResults(primary, expanded) {
3232
3339
  return Array.from(mergedByPath.values());
3233
3340
  }
3234
3341
  function graphPathRelativeToStorage(storageDir, candidatePath) {
3235
- const absolutePath = path7.isAbsolute(candidatePath) ? candidatePath : path7.resolve(storageDir, candidatePath);
3236
- const rel = path7.relative(storageDir, absolutePath);
3342
+ const absolutePath = path6.isAbsolute(candidatePath) ? candidatePath : path6.resolve(storageDir, candidatePath);
3343
+ const rel = path6.relative(storageDir, absolutePath);
3237
3344
  if (!rel || rel === ".") return null;
3238
3345
  if (rel.startsWith("..")) return null;
3239
- return rel.split(path7.sep).join("/");
3346
+ return rel.split(path6.sep).join("/");
3240
3347
  }
3241
3348
  function normalizeGraphActivationScore(score) {
3242
3349
  const bounded = Number.isFinite(score) && score > 0 ? score : 0;
@@ -3378,7 +3485,7 @@ function buildMemoryPathById(allMemsForGraph, storageDir) {
3378
3485
  for (const mem of allMemsForGraph ?? []) {
3379
3486
  const id = mem.frontmatter.id;
3380
3487
  if (!id) continue;
3381
- pathById.set(id, path7.relative(storageDir, mem.path));
3488
+ pathById.set(id, path6.relative(storageDir, mem.path));
3382
3489
  }
3383
3490
  return pathById;
3384
3491
  }
@@ -3386,7 +3493,7 @@ function appendMemoryToGraphContext(options) {
3386
3493
  if (!Array.isArray(options.allMemsForGraph)) return;
3387
3494
  const nowIso = (/* @__PURE__ */ new Date()).toISOString();
3388
3495
  options.allMemsForGraph.push({
3389
- path: path7.join(options.storageDir, options.memoryRelPath),
3496
+ path: path6.join(options.storageDir, options.memoryRelPath),
3390
3497
  content: options.content,
3391
3498
  frontmatter: {
3392
3499
  id: options.memoryId,
@@ -3406,16 +3513,16 @@ function resolvePersistedMemoryRelativePath(options) {
3406
3513
  const persisted = options.pathById.get(options.memoryId);
3407
3514
  if (persisted) return persisted;
3408
3515
  if (options.category === "correction") {
3409
- return path7.join("corrections", `${options.memoryId}.md`);
3516
+ return path6.join("corrections", `${options.memoryId}.md`);
3410
3517
  }
3411
3518
  const subtree = options.category === "procedure" ? "procedures" : options.category === "reasoning_trace" ? "reasoning-traces" : "facts";
3412
3519
  const idParts = options.memoryId.split("-");
3413
3520
  const maybeTimestamp = Number(idParts[1]);
3414
3521
  if (Number.isFinite(maybeTimestamp) && maybeTimestamp > 0) {
3415
3522
  const day = new Date(maybeTimestamp).toISOString().slice(0, 10);
3416
- return path7.join(subtree, day, `${options.memoryId}.md`);
3523
+ return path6.join(subtree, day, `${options.memoryId}.md`);
3417
3524
  }
3418
- return path7.join(subtree, `${options.memoryId}.md`);
3525
+ return path6.join(subtree, `${options.memoryId}.md`);
3419
3526
  }
3420
3527
  var Orchestrator = class _Orchestrator {
3421
3528
  storage;
@@ -3507,6 +3614,15 @@ var Orchestrator = class _Orchestrator {
3507
3614
  * through the same namespace layer).
3508
3615
  */
3509
3616
  _codingContextBySession = /* @__PURE__ */ new Map();
3617
+ /**
3618
+ * Per-session peer ID registry (issue #679 PR 3/5).
3619
+ * Set by connectors / hooks via `setPeerIdForSession` so `recallInternal`
3620
+ * can inject the peer's profile into recall context when
3621
+ * `peerProfileRecallEnabled` is true. Cleared when the session ends.
3622
+ * Keyed by sessionKey so concurrent sessions don't clobber each other
3623
+ * (rule 11 — scope globals per plugin ID / session).
3624
+ */
3625
+ _peerIdBySession = /* @__PURE__ */ new Map();
3510
3626
  routingRulesStore = null;
3511
3627
  contentHashIndex = null;
3512
3628
  artifactSourceStatusCache = /* @__PURE__ */ new WeakMap();
@@ -3533,6 +3649,13 @@ var Orchestrator = class _Orchestrator {
3533
3649
  lastTierMigrationRunAtMs = 0;
3534
3650
  conversationIndexLastUpdateAtMs = /* @__PURE__ */ new Map();
3535
3651
  lastFileHygieneRunAtMs = 0;
3652
+ // Pattern-reinforcement cadence gate (issue #687 PR 2/4). Tracks the
3653
+ // last successful run so `runPatternReinforcement` can short-circuit
3654
+ // when the configured cadence has not elapsed. Keyed by namespace
3655
+ // so MCP-triggered runs in tenant A don't suppress runs in tenant B
3656
+ // (PR #730 review feedback, Codex P2). The default-tenant path
3657
+ // uses the empty-string key.
3658
+ lastPatternReinforcementAtByNs = /* @__PURE__ */ new Map();
3536
3659
  lastRecallFailureLogAtMs = 0;
3537
3660
  lastRecallFailureAtMs = 0;
3538
3661
  suppressedRecallFailures = 0;
@@ -3660,14 +3783,58 @@ var Orchestrator = class _Orchestrator {
3660
3783
  applyCodingNamespaceOverlay(sessionKey, baseNamespace) {
3661
3784
  if (!this.config.namespacesEnabled) return baseNamespace;
3662
3785
  const codingContext = this.getCodingContextForSession(sessionKey);
3663
- const overlay = resolveCodingNamespaceOverlay(codingContext, this.config.codingMode);
3786
+ const overlay = resolveCodingNamespaceOverlay(codingContext, this.config.codingMode, this.config.defaultNamespace);
3664
3787
  if (!overlay) return baseNamespace;
3665
3788
  return combineNamespaces(baseNamespace, overlay.namespace);
3666
3789
  }
3790
+ /**
3791
+ * Register a peer ID for a session so recall can inject the peer's
3792
+ * profile into context (issue #679 PR 3/5). Pass `null` to clear.
3793
+ *
3794
+ * Connectors and the `before_agent_start` hook call this when the
3795
+ * session's counter-party is known. The ID is validated against
3796
+ * `PEER_ID_PATTERN` before storing.
3797
+ *
3798
+ * Fail-closed (Codex P1 review): an invalid peerId clears any
3799
+ * previously registered mapping for the session rather than silently
3800
+ * keeping stale data. This prevents a malformed metadata update from
3801
+ * mixing one peer's profile context into another session.
3802
+ *
3803
+ * Defensive init (Cursor review + rule 16): `Object.create(
3804
+ * Orchestrator.prototype)` stubs in legacy tests skip class-field
3805
+ * initializers, so `_peerIdBySession` may be undefined. Mirror the
3806
+ * same guard used by `setCodingContextForSession`.
3807
+ */
3808
+ setPeerIdForSession(sessionKey, peerId) {
3809
+ if (typeof sessionKey !== "string" || sessionKey.length === 0) return;
3810
+ if (!this._peerIdBySession) {
3811
+ this._peerIdBySession = /* @__PURE__ */ new Map();
3812
+ }
3813
+ if (peerId === null) {
3814
+ this._peerIdBySession.delete(sessionKey);
3815
+ return;
3816
+ }
3817
+ if (typeof peerId !== "string" || peerId.length === 0 || peerId.length > 64 || !/^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/.test(peerId)) {
3818
+ log.warn(`setPeerIdForSession: invalid peerId \u2014 clearing session mapping`);
3819
+ this._peerIdBySession.delete(sessionKey);
3820
+ return;
3821
+ }
3822
+ this._peerIdBySession.set(sessionKey, peerId);
3823
+ }
3824
+ /**
3825
+ * Return the peer ID registered for a session, or `null` when none
3826
+ * is set. Used by `recallInternal` to inject the peer profile section.
3827
+ * Defensive `_peerIdBySession` lookup — legacy orchestrator-flush tests
3828
+ * use `Object.create(Orchestrator.prototype)` which skips class-field
3829
+ * initializers, so the Map may be undefined on stubs.
3830
+ */
3831
+ getPeerIdForSession(sessionKey) {
3832
+ if (typeof sessionKey !== "string" || sessionKey.length === 0) return null;
3833
+ return this._peerIdBySession?.get(sessionKey) ?? null;
3834
+ }
3667
3835
  /**
3668
3836
  * Read-side overlay: returns the list of namespaces a session should read
3669
- * from, including any read fallbacks (branch → project asymmetry lands in
3670
- * PR 3; PR 2 returns an empty fallbacks list).
3837
+ * from, including any read fallbacks (branch → project, global root).
3671
3838
  *
3672
3839
  * Returns `null` when:
3673
3840
  * - `namespacesEnabled` is false (overlay would create false isolation)
@@ -3684,7 +3851,7 @@ var Orchestrator = class _Orchestrator {
3684
3851
  applyCodingRecallOverlay(sessionKey) {
3685
3852
  if (!this.config.namespacesEnabled) return null;
3686
3853
  const codingContext = this.getCodingContextForSession(sessionKey);
3687
- const overlay = resolveCodingNamespaceOverlay(codingContext, this.config.codingMode);
3854
+ const overlay = resolveCodingNamespaceOverlay(codingContext, this.config.codingMode, this.config.defaultNamespace);
3688
3855
  if (!overlay) return null;
3689
3856
  return { namespace: overlay.namespace, readFallbacks: overlay.readFallbacks };
3690
3857
  }
@@ -3767,11 +3934,14 @@ var Orchestrator = class _Orchestrator {
3767
3934
  if (this.config.namespacesEnabled) return true;
3768
3935
  return this.qmd.isAvailable();
3769
3936
  }
3937
+ invalidateLiveContentHashIndex() {
3938
+ this.contentHashIndex = null;
3939
+ }
3770
3940
  constructor(config) {
3771
3941
  this.config = config;
3772
3942
  this.profiler = new ProfilingCollector({
3773
3943
  enabled: config.profilingEnabled,
3774
- storageDir: config.profilingStorageDir || path7.join(config.memoryDir, "profiling"),
3944
+ storageDir: config.profilingStorageDir || path6.join(config.memoryDir, "profiling"),
3775
3945
  maxTraces: config.profilingMaxTraces
3776
3946
  });
3777
3947
  this.storageRouter = new NamespaceStorageRouter(config);
@@ -3786,6 +3956,14 @@ var Orchestrator = class _Orchestrator {
3786
3956
  maxVersionsPerPage: config.versioningMaxPerPage,
3787
3957
  sidecarDir: config.versioningSidecarDir
3788
3958
  });
3959
+ if (config.secureStoreEnabled) {
3960
+ this.storage.setSecureStoreRequired(true);
3961
+ const storeId = secureStoreDir(config.memoryDir);
3962
+ const existingKey = keyring_exports.getKey(storeId);
3963
+ if (existingKey) {
3964
+ this.storage.setSecureStoreKey(existingKey, config.secureStoreEncryptOnWrite);
3965
+ }
3966
+ }
3789
3967
  this.qmd = createSearchBackend(config);
3790
3968
  const conversationIndexRuntime = createConversationIndexRuntime(config, {
3791
3969
  getQmd: () => this.conversationQmd,
@@ -3795,10 +3973,10 @@ var Orchestrator = class _Orchestrator {
3795
3973
  this.conversationFaiss = conversationIndexRuntime.faiss;
3796
3974
  this.conversationIndexBackend = conversationIndexRuntime.backend;
3797
3975
  this.sharedContext = config.sharedContextEnabled ? new SharedContextManager(config) : void 0;
3798
- this.compounding = config.compoundingEnabled ? new CompoundingEngine(config) : void 0;
3976
+ this.compounding = config.compoundingEnabled ? new CompoundingEngine(config, this.storage) : void 0;
3799
3977
  this.buffer = new SmartBuffer(config, this.storage);
3800
3978
  this.transcript = new TranscriptManager(config);
3801
- this.conversationIndexDir = path7.join(
3979
+ this.conversationIndexDir = path6.join(
3802
3980
  config.memoryDir,
3803
3981
  "conversation-index",
3804
3982
  "chunks"
@@ -3852,7 +4030,7 @@ var Orchestrator = class _Orchestrator {
3852
4030
  this.modelRegistry
3853
4031
  );
3854
4032
  this.threading = new ThreadingManager(
3855
- path7.join(config.memoryDir, "threads"),
4033
+ path6.join(config.memoryDir, "threads"),
3856
4034
  config.threadingGapMinutes
3857
4035
  );
3858
4036
  this.tmtBuilder = new TmtBuilder(config.memoryDir, {
@@ -4097,8 +4275,7 @@ var Orchestrator = class _Orchestrator {
4097
4275
  promotionByOutcomeEnabled: this.config.promotionByOutcomeEnabled
4098
4276
  });
4099
4277
  if (this.config.factDeduplicationEnabled) {
4100
- const stateDir = path7.join(this.config.memoryDir, "state");
4101
- this.contentHashIndex = new ContentHashIndex(stateDir);
4278
+ this.contentHashIndex = this.storage.createContentHashIndex();
4102
4279
  await this.contentHashIndex.load();
4103
4280
  log.info(
4104
4281
  `content-hash dedup: loaded ${this.contentHashIndex.size} hashes`
@@ -4126,7 +4303,7 @@ var Orchestrator = class _Orchestrator {
4126
4303
  const files = await readdir3(wsDir).catch(() => []);
4127
4304
  for (const f of files) {
4128
4305
  if (!f.startsWith(".compaction-reset-signal-")) continue;
4129
- const fp = path7.join(wsDir, f);
4306
+ const fp = path6.join(wsDir, f);
4130
4307
  const s = await stat3(fp).catch(() => null);
4131
4308
  if (s && Date.now() - s.mtimeMs >= COMPACTION_SIGNAL_MAX_AGE_MS) {
4132
4309
  await unlink2(fp).catch(() => {
@@ -4334,6 +4511,43 @@ var Orchestrator = class _Orchestrator {
4334
4511
  log.debug(`contradiction scan cron auto-register failed (non-fatal): ${err}`);
4335
4512
  }
4336
4513
  }
4514
+ if (this.config.patternReinforcementEnabled) {
4515
+ try {
4516
+ await this.autoRegisterPatternReinforcementCron();
4517
+ } catch (err) {
4518
+ log.debug(`pattern reinforcement cron auto-register failed (non-fatal): ${err}`);
4519
+ }
4520
+ }
4521
+ if (this.config.graphEdgeDecayEnabled) {
4522
+ try {
4523
+ await this.autoRegisterGraphEdgeDecayCron();
4524
+ } catch (err) {
4525
+ log.debug(`graph edge decay cron auto-register failed (non-fatal): ${err}`);
4526
+ }
4527
+ }
4528
+ if (signal.aborted) return;
4529
+ if (this.config.lifecyclePolicyEnabled && this.config.qmdTierMigrationEnabled) {
4530
+ try {
4531
+ const { runFirstStartMigration } = await import("./first-start-migration-4MHQEOSD.js");
4532
+ const result = await runFirstStartMigration({
4533
+ storage: this.storage,
4534
+ config: this.config,
4535
+ qmd: this.qmd,
4536
+ hotCollection: this.config.qmdCollection,
4537
+ coldCollection: this.config.qmdColdCollection,
4538
+ signal
4539
+ });
4540
+ if (!result.skipped) {
4541
+ log.info(
4542
+ `first-start lifecycle migration: demoted ${result.demotedCount} of ${result.candidateCount} candidates (cap=${result.cappedAt})`
4543
+ );
4544
+ } else {
4545
+ log.debug(`first-start lifecycle migration skipped: ${result.skipReason}`);
4546
+ }
4547
+ } catch (err) {
4548
+ log.warn(`first-start lifecycle migration failed (non-fatal): ${err}`);
4549
+ }
4550
+ }
4337
4551
  log.info("orchestrator initialized (full \u2014 deferred steps complete)");
4338
4552
  }
4339
4553
  /**
@@ -4441,7 +4655,7 @@ var Orchestrator = class _Orchestrator {
4441
4655
  */
4442
4656
  async autoRegisterDaySummaryCron() {
4443
4657
  const home = resolveHomeDir();
4444
- const jobsPath = path7.join(home, ".openclaw", "cron", "jobs.json");
4658
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4445
4659
  try {
4446
4660
  if (!existsSync2(jobsPath)) {
4447
4661
  log.debug(
@@ -4465,7 +4679,7 @@ var Orchestrator = class _Orchestrator {
4465
4679
  }
4466
4680
  async autoRegisterNightlyGovernanceCron() {
4467
4681
  const home = resolveHomeDir();
4468
- const jobsPath = path7.join(home, ".openclaw", "cron", "jobs.json");
4682
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4469
4683
  try {
4470
4684
  if (!existsSync2(jobsPath)) {
4471
4685
  log.debug("nightly governance cron: jobs.json not found, skipping auto-register");
@@ -4487,7 +4701,7 @@ var Orchestrator = class _Orchestrator {
4487
4701
  }
4488
4702
  async autoRegisterProceduralMiningCron() {
4489
4703
  const home = resolveHomeDir();
4490
- const jobsPath = path7.join(home, ".openclaw", "cron", "jobs.json");
4704
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4491
4705
  try {
4492
4706
  if (!existsSync2(jobsPath)) {
4493
4707
  log.debug("procedural mining cron: jobs.json not found, skipping auto-register");
@@ -4507,7 +4721,7 @@ var Orchestrator = class _Orchestrator {
4507
4721
  }
4508
4722
  async autoRegisterContradictionScanCron() {
4509
4723
  const home = resolveHomeDir();
4510
- const jobsPath = path7.join(home, ".openclaw", "cron", "jobs.json");
4724
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4511
4725
  try {
4512
4726
  if (!existsSync2(jobsPath)) {
4513
4727
  log.debug("contradiction scan cron: jobs.json not found, skipping auto-register");
@@ -4525,6 +4739,109 @@ var Orchestrator = class _Orchestrator {
4525
4739
  log.debug(`contradiction scan cron auto-register error: ${err}`);
4526
4740
  }
4527
4741
  }
4742
+ async autoRegisterPatternReinforcementCron() {
4743
+ const home = resolveHomeDir();
4744
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4745
+ try {
4746
+ if (!existsSync2(jobsPath)) {
4747
+ log.debug("pattern reinforcement cron: jobs.json not found, skipping auto-register");
4748
+ return;
4749
+ }
4750
+ const created = await ensurePatternReinforcementCron(jobsPath, {
4751
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
4752
+ });
4753
+ if (created.created) {
4754
+ log.info(`pattern reinforcement cron auto-registered (${created.jobId})`);
4755
+ } else {
4756
+ log.debug("pattern reinforcement cron already exists, skipping auto-register");
4757
+ }
4758
+ } catch (err) {
4759
+ log.debug(`pattern reinforcement cron auto-register error: ${err}`);
4760
+ }
4761
+ }
4762
+ /**
4763
+ * Run the pattern-reinforcement maintenance job (issue #687 PR 2/4).
4764
+ *
4765
+ * Cadence-gated on `patternReinforcementCadenceMs` so every caller
4766
+ * (orchestrator cron path, MCP tool, CLI) shares a single floor —
4767
+ * none can call this on a hot loop and burn the corpus. When the
4768
+ * feature is disabled or the cadence has not elapsed, returns a
4769
+ * synthetic "skipped" result rather than throwing.
4770
+ *
4771
+ * Cadence tracking is per-namespace so a tenant-scoped MCP run in
4772
+ * one namespace does not silence a cron run in another (PR #730
4773
+ * review feedback, Codex P2). Pass `force: true` for ad-hoc
4774
+ * operator runs that must bypass the cadence floor — mirrors the
4775
+ * pattern used by other maintenance MCP tools.
4776
+ *
4777
+ * `force` deliberately does NOT bypass the master
4778
+ * `patternReinforcementEnabled` flag (PR #730 review feedback,
4779
+ * Cursor Medium). Operators who have explicitly disabled the
4780
+ * feature must not have their corpus mutated by an MCP tool call —
4781
+ * the only way to run the job is to enable the feature in config.
4782
+ */
4783
+ async runPatternReinforcement(options = {}) {
4784
+ const cadenceKey = options.namespace ?? "";
4785
+ if (!this.config.patternReinforcementEnabled) {
4786
+ return { ran: false, skippedReason: "disabled", namespace: cadenceKey };
4787
+ }
4788
+ const cadence = this.config.patternReinforcementCadenceMs;
4789
+ const lastAt = this.lastPatternReinforcementAtByNs.get(cadenceKey);
4790
+ if (!options.force && cadence > 0 && lastAt !== void 0 && Date.now() - lastAt < cadence) {
4791
+ return { ran: false, skippedReason: "cadence", namespace: cadenceKey };
4792
+ }
4793
+ const storage = options.namespace ? await this.getStorage(options.namespace) : this.storage;
4794
+ const result = await runPatternReinforcement(storage, {
4795
+ categories: this.config.patternReinforcementCategories,
4796
+ minCount: this.config.patternReinforcementMinCount
4797
+ });
4798
+ this.lastPatternReinforcementAtByNs.set(cadenceKey, Date.now());
4799
+ log.debug(
4800
+ `pattern reinforcement [ns=${cadenceKey || "(default)"}]: clusters=${result.clustersFound} canonicalsUpdated=${result.canonicalsUpdated} duplicatesSuperseded=${result.duplicatesSuperseded}`
4801
+ );
4802
+ return { ran: true, result, namespace: cadenceKey };
4803
+ }
4804
+ async autoRegisterGraphEdgeDecayCron() {
4805
+ const home = resolveHomeDir();
4806
+ const jobsPath = path6.join(home, ".openclaw", "cron", "jobs.json");
4807
+ try {
4808
+ if (!existsSync2(jobsPath)) {
4809
+ log.debug("graph edge decay cron: jobs.json not found, skipping auto-register");
4810
+ return;
4811
+ }
4812
+ const scheduleExpr = graphEdgeDecayCadenceToCronExpr(this.config.graphEdgeDecayCadenceMs);
4813
+ const created = await ensureGraphEdgeDecayCron(jobsPath, {
4814
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
4815
+ scheduleExpr
4816
+ });
4817
+ if (created.created) {
4818
+ log.info(`graph edge decay cron auto-registered (${created.jobId}, ${scheduleExpr})`);
4819
+ } else {
4820
+ log.debug("graph edge decay cron already exists, skipping auto-register");
4821
+ }
4822
+ } catch (err) {
4823
+ log.debug(`graph edge decay cron auto-register error: ${err}`);
4824
+ }
4825
+ }
4826
+ async runLiveConnectors(options = {}) {
4827
+ return runLiveConnectorsOnce({
4828
+ memoryDir: this.config.memoryDir,
4829
+ connectors: this.config.connectors,
4830
+ force: options.force === true,
4831
+ abortSignal: options.abortSignal,
4832
+ ingestDocuments: async (docs) => {
4833
+ const fetchedAt = (/* @__PURE__ */ new Date()).toISOString();
4834
+ const turns = docs.map((doc) => ({
4835
+ role: "assistant",
4836
+ content: doc.title ? `# ${doc.title}
4837
+
4838
+ ${doc.content}` : doc.content,
4839
+ timestamp: fetchedAt
4840
+ }));
4841
+ await this.ingestBulkImportBatch(turns);
4842
+ }
4843
+ });
4844
+ }
4528
4845
  async applyBehaviorRuntimePolicy(state) {
4529
4846
  const result = await this.policyRuntime.applyFromBehaviorState(state);
4530
4847
  this.runtimePolicyValues = await this.policyRuntime.loadRuntimeValues();
@@ -4543,15 +4860,15 @@ var Orchestrator = class _Orchestrator {
4543
4860
  this.lastFileHygieneRunAtMs = now;
4544
4861
  if (hygiene.rotateEnabled) {
4545
4862
  for (const rel of hygiene.rotatePaths) {
4546
- const abs = path7.isAbsolute(rel) ? rel : path7.join(this.config.workspaceDir, rel);
4863
+ const abs = path6.isAbsolute(rel) ? rel : path6.join(this.config.workspaceDir, rel);
4547
4864
  try {
4548
4865
  const raw = await readFile4(abs, "utf-8");
4549
4866
  if (raw.length > hygiene.rotateMaxBytes) {
4550
- const archiveDir = path7.join(
4867
+ const archiveDir = path6.join(
4551
4868
  this.config.workspaceDir,
4552
4869
  hygiene.archiveDir
4553
4870
  );
4554
- const base = path7.basename(abs);
4871
+ const base = path6.basename(abs);
4555
4872
  const prefix = base.toUpperCase().replace(/\.MD$/i, "").replace(/[^A-Z0-9]+/g, "-") || "FILE";
4556
4873
  const { newContent } = await rotateMarkdownFileToArchive({
4557
4874
  filePath: abs,
@@ -4576,8 +4893,8 @@ var Orchestrator = class _Orchestrator {
4576
4893
  log.warn(w.message);
4577
4894
  }
4578
4895
  if (hygiene.warningsLogEnabled && warnings.length > 0) {
4579
- const fp = path7.join(this.config.memoryDir, hygiene.warningsLogPath);
4580
- await mkdir5(path7.dirname(fp), { recursive: true });
4896
+ const fp = path6.join(this.config.memoryDir, hygiene.warningsLogPath);
4897
+ await mkdir5(path6.dirname(fp), { recursive: true });
4581
4898
  const stamp = (/* @__PURE__ */ new Date()).toISOString();
4582
4899
  const block = `
4583
4900
 
@@ -4614,7 +4931,28 @@ var Orchestrator = class _Orchestrator {
4614
4931
  async runSemanticConsolidationNow(options) {
4615
4932
  return this.runSemanticConsolidation({ ...options, force: true });
4616
4933
  }
4934
+ async runDeepSleepGovernanceNow(options) {
4935
+ const targetStorage = options?.storage ?? this.storage;
4936
+ const { runMemoryGovernance } = await import("./memory-governance-JZHZDOLN.js");
4937
+ const { summarizeGovernanceResultForDreams } = await import("./dreams-ledger-LR2NBAZE.js");
4938
+ const govResult = await runMemoryGovernance({
4939
+ memoryDir: targetStorage.dir,
4940
+ mode: options?.dryRun === true ? "shadow" : "apply"
4941
+ });
4942
+ if (options?.dryRun !== true) {
4943
+ try {
4944
+ await this.processEntitySynthesisQueue(
4945
+ this.namespaceFromStorageDir(targetStorage.dir),
4946
+ 5
4947
+ );
4948
+ } catch (error) {
4949
+ log.debug(`deep-sleep governance: entity synthesis refresh failed after apply: ${error}`);
4950
+ }
4951
+ }
4952
+ return summarizeGovernanceResultForDreams(govResult, options?.dryRun === true);
4953
+ }
4617
4954
  async runSemanticConsolidation(options) {
4955
+ const targetStorage = options?.storage ?? this.storage;
4618
4956
  const result = {
4619
4957
  clustersFound: 0,
4620
4958
  memoriesConsolidated: 0,
@@ -4627,7 +4965,7 @@ var Orchestrator = class _Orchestrator {
4627
4965
  return result;
4628
4966
  }
4629
4967
  log.info("[semantic-consolidation] starting run");
4630
- const allMemories = await this.storage.readAllMemories();
4968
+ const allMemories = await targetStorage.readAllMemories();
4631
4969
  if (allMemories.length < 10) {
4632
4970
  log.debug("[semantic-consolidation] too few memories, skipping");
4633
4971
  return result;
@@ -4730,10 +5068,10 @@ var Orchestrator = class _Orchestrator {
4730
5068
  const derivedFromEntries = [];
4731
5069
  for (const m of cluster.memories) {
4732
5070
  if (!m.path) continue;
4733
- const entry = await this.storage.snapshotForProvenance(m.path);
5071
+ const entry = await targetStorage.snapshotForProvenance(m.path);
4734
5072
  if (entry) derivedFromEntries.push(entry);
4735
5073
  }
4736
- const canonicalId = await this.storage.writeMemory(
5074
+ const canonicalId = await targetStorage.writeMemory(
4737
5075
  newest.frontmatter.category,
4738
5076
  canonicalContent,
4739
5077
  {
@@ -4752,7 +5090,7 @@ var Orchestrator = class _Orchestrator {
4752
5090
  );
4753
5091
  result.memoriesConsolidated++;
4754
5092
  for (const m of cluster.memories) {
4755
- const archiveResult = await this.storage.archiveMemory(m, {
5093
+ const archiveResult = await targetStorage.archiveMemory(m, {
4756
5094
  actor: "semantic-consolidation",
4757
5095
  reasonCode: "semantic-consolidation",
4758
5096
  relatedMemoryIds: [canonicalId]
@@ -4771,7 +5109,7 @@ var Orchestrator = class _Orchestrator {
4771
5109
  await this.embeddingFallback.removeFromIndex(m.frontmatter.id);
4772
5110
  if (this.config.queryAwareIndexingEnabled && m.path && m.frontmatter?.created) {
4773
5111
  deindexMemory(
4774
- this.config.memoryDir,
5112
+ targetStorage.dir,
4775
5113
  m.path,
4776
5114
  m.frontmatter.created,
4777
5115
  m.frontmatter.tags ?? []
@@ -4803,13 +5141,39 @@ var Orchestrator = class _Orchestrator {
4803
5141
  try {
4804
5142
  await materializeAfterSemanticConsolidation({
4805
5143
  config: this.config,
4806
- memoryDir: this.config.memoryDir
5144
+ memoryDir: targetStorage.dir
4807
5145
  });
4808
5146
  } catch (err) {
4809
5147
  log.warn(
4810
5148
  `[semantic-consolidation] Codex materialize post-hook failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`
4811
5149
  );
4812
5150
  }
5151
+ if (this.config.peerProfileReasonerEnabled) {
5152
+ try {
5153
+ const { runPeerProfileReasoner } = await import("./peers-6OSQ3NK6.js");
5154
+ const llm2 = new FallbackLlmClient2(this.config.gatewayConfig);
5155
+ const peerResult = await runPeerProfileReasoner({
5156
+ memoryDir: targetStorage.dir,
5157
+ enabled: true,
5158
+ llm: llm2,
5159
+ model: this.config.peerProfileReasonerModel,
5160
+ minInteractions: this.config.peerProfileReasonerMinInteractions,
5161
+ maxFieldsPerRun: this.config.peerProfileReasonerMaxFieldsPerRun,
5162
+ log: {
5163
+ debug: (msg) => log.debug(msg),
5164
+ info: (msg) => log.info(msg),
5165
+ warn: (msg) => log.warn(msg)
5166
+ }
5167
+ });
5168
+ log.info(
5169
+ `[peer-profile-reasoner] complete: peers=${peerResult.peersConsidered}, processed=${peerResult.peersProcessed}, fields=${peerResult.fieldsApplied}`
5170
+ );
5171
+ } catch (err) {
5172
+ log.warn(
5173
+ `[peer-profile-reasoner] post-consolidation hook failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`
5174
+ );
5175
+ }
5176
+ }
4813
5177
  return result;
4814
5178
  }
4815
5179
  async waitForExtractionIdle(timeoutMs = 6e4) {
@@ -4989,16 +5353,16 @@ ${evidenceText}`
4989
5353
  const datesToScan = [yesterday, utcToday].filter(
4990
5354
  (v, i, a) => a.indexOf(v) === i
4991
5355
  );
4992
- const factsBaseDir = path7.join(storage.dir, "facts");
5356
+ const factsBaseDir = path6.join(storage.dir, "facts");
4993
5357
  const MAX_CHARS = 1e5;
4994
5358
  const facts = [];
4995
5359
  for (const date of datesToScan) {
4996
- const factsDir = path7.join(factsBaseDir, date);
5360
+ const factsDir = path6.join(factsBaseDir, date);
4997
5361
  try {
4998
5362
  const entries = await readdir3(factsDir, { withFileTypes: true });
4999
5363
  for (const entry of entries) {
5000
5364
  if (!entry.name.endsWith(".md")) continue;
5001
- const fullPath = path7.join(factsDir, entry.name);
5365
+ const fullPath = path6.join(factsDir, entry.name);
5002
5366
  try {
5003
5367
  const raw = await readFile4(fullPath, "utf-8");
5004
5368
  const fmMatch = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
@@ -5014,7 +5378,7 @@ ${evidenceText}`
5014
5378
  facts.push({
5015
5379
  path: fullPath,
5016
5380
  frontmatter: {
5017
- id: fm.id || path7.basename(entry.name, ".md"),
5381
+ id: fm.id || path6.basename(entry.name, ".md"),
5018
5382
  category: fm.category || "fact",
5019
5383
  created: fm.created || "unknown",
5020
5384
  updated: fm.updated || fm.created || "unknown",
@@ -5035,13 +5399,13 @@ ${evidenceText}`
5035
5399
  (a, b) => a.frontmatter.created < b.frontmatter.created ? -1 : 1
5036
5400
  );
5037
5401
  const hourlySummaries = [];
5038
- const hourlyBaseDir = path7.join(storage.dir, "summaries", "hourly");
5402
+ const hourlyBaseDir = path6.join(storage.dir, "summaries", "hourly");
5039
5403
  try {
5040
5404
  const sessionKeys = await readdir3(hourlyBaseDir, { withFileTypes: true });
5041
5405
  for (const sk of sessionKeys) {
5042
5406
  if (!sk.isDirectory()) continue;
5043
5407
  for (const date of datesToScan) {
5044
- const summaryFile = path7.join(hourlyBaseDir, sk.name, `${date}.md`);
5408
+ const summaryFile = path6.join(hourlyBaseDir, sk.name, `${date}.md`);
5045
5409
  try {
5046
5410
  const raw = await readFile4(summaryFile, "utf-8");
5047
5411
  if (raw.trim().length > 0) {
@@ -5139,7 +5503,7 @@ ${evidenceText}`
5139
5503
  }
5140
5504
  async getLastGraphRecallSnapshot(namespace) {
5141
5505
  const storage = await this.getStorage(namespace);
5142
- const snapshotPath = path7.join(
5506
+ const snapshotPath = path6.join(
5143
5507
  storage.dir,
5144
5508
  "state",
5145
5509
  "last_graph_recall.json"
@@ -5178,7 +5542,7 @@ ${evidenceText}`
5178
5542
  }
5179
5543
  async getLastIntentSnapshot(namespace) {
5180
5544
  const storage = await this.getStorage(namespace);
5181
- const snapshotPath = path7.join(storage.dir, "state", "last_intent.json");
5545
+ const snapshotPath = path6.join(storage.dir, "state", "last_intent.json");
5182
5546
  try {
5183
5547
  const raw = await readFile4(snapshotPath, "utf-8");
5184
5548
  const parsed = JSON.parse(raw);
@@ -5211,7 +5575,7 @@ ${evidenceText}`
5211
5575
  }
5212
5576
  async getLastQmdRecallSnapshot(namespace) {
5213
5577
  const storage = await this.getStorage(namespace);
5214
- const snapshotPath = path7.join(
5578
+ const snapshotPath = path6.join(
5215
5579
  storage.dir,
5216
5580
  "state",
5217
5581
  "last_qmd_recall.json"
@@ -5272,9 +5636,10 @@ ${evidenceText}`
5272
5636
  `Seed paths (${snapshot.seedCount}):`,
5273
5637
  ...snapshot.seeds.map((p) => `- ${p}`),
5274
5638
  `Expanded paths (${snapshot.expandedCount}, showing ${expanded.length}):`,
5275
- ...expanded.map(
5276
- (e) => `- ${e.path} (score=${e.score.toFixed(3)}, ns=${e.namespace}, seed=${e.seed || "unknown"}, hop=${e.hopDepth}, w=${e.decayedWeight.toFixed(3)}, type=${e.graphType})`
5277
- ),
5639
+ ...expanded.map((e) => {
5640
+ const confLabel = typeof e.edgeConfidence === "number" && Number.isFinite(e.edgeConfidence) ? e.edgeConfidence.toFixed(2) : "n/a";
5641
+ return `- ${e.path} (score=${e.score.toFixed(3)}, ns=${e.namespace}, seed=${e.seed || "unknown"}, hop=${e.hopDepth}, w=${e.decayedWeight.toFixed(3)}, type=${e.graphType}, conf=${confLabel})`;
5642
+ }),
5278
5643
  `Final ranked results (${snapshot.finalResults?.length ?? 0}, showing ${finalResults.length}):`,
5279
5644
  ...finalResults.map(
5280
5645
  (entry) => `- ${entry.path} (score=${entry.score.toFixed(3)}, sources=${entry.sourceLabels.join(",") || "baseline"})`
@@ -5363,7 +5728,7 @@ ${r.snippet.trim()}
5363
5728
  const entries = await readdir3(dir, { withFileTypes: true });
5364
5729
  let total = 0;
5365
5730
  for (const entry of entries) {
5366
- const fullPath = path7.join(dir, entry.name);
5731
+ const fullPath = path6.join(dir, entry.name);
5367
5732
  if (entry.isDirectory()) {
5368
5733
  total += await this.countConversationChunkDocs(fullPath);
5369
5734
  continue;
@@ -5618,6 +5983,11 @@ ${r.snippet.trim()}
5618
5983
  log.warn("recall: init gate timed out \u2014 proceeding without full init");
5619
5984
  }
5620
5985
  }
5986
+ if (this.config.secureStoreEnabled && !this.storage.isSecureStoreUnlocked()) {
5987
+ const lockedMsg = "[secure-store locked] Memory store is encrypted and locked. Run `remnic secure-store unlock` then restart the daemon to decrypt.";
5988
+ log.warn("recall blocked: secure-store is locked");
5989
+ return lockedMsg;
5990
+ }
5621
5991
  try {
5622
5992
  const recallPromise = this.recallInternal(prompt, sessionKey, {
5623
5993
  ...options,
@@ -6240,17 +6610,18 @@ ${r.snippet.trim()}
6240
6610
  0
6241
6611
  );
6242
6612
  seedPaths.push(
6243
- ...seedRelativePaths.map((rel) => path7.join(storage.dir, rel))
6613
+ ...seedRelativePaths.map((rel) => path6.join(storage.dir, rel))
6244
6614
  );
6245
6615
  const seedSet = new Set(seedRelativePaths);
6246
6616
  const expanded = await this.graphIndexFor(storage).spreadingActivation(
6247
6617
  seedRelativePaths,
6248
- this.config.maxGraphTraversalSteps
6618
+ this.config.maxGraphTraversalSteps,
6619
+ options.includeLowConfidence === true ? { includeLowConfidence: true } : void 0
6249
6620
  );
6250
6621
  if (expanded.length === 0) continue;
6251
6622
  for (const candidate of expanded.slice(0, perNamespaceExpandedCap)) {
6252
6623
  if (seedSet.has(candidate.path)) continue;
6253
- const memoryPath = path7.resolve(storage.dir, candidate.path);
6624
+ const memoryPath = path6.resolve(storage.dir, candidate.path);
6254
6625
  const memory = await storage.readMemoryByPath(memoryPath);
6255
6626
  if (!memory) continue;
6256
6627
  if (isArtifactMemoryPath(memory.path)) continue;
@@ -6274,10 +6645,15 @@ ${r.snippet.trim()}
6274
6645
  path: memory.path,
6275
6646
  score,
6276
6647
  namespace,
6277
- seed: path7.resolve(storage.dir, candidate.seed),
6648
+ seed: path6.resolve(storage.dir, candidate.seed),
6278
6649
  hopDepth: candidate.hopDepth,
6279
6650
  decayedWeight: candidate.decayedWeight,
6280
- graphType: candidate.graphType
6651
+ graphType: candidate.graphType,
6652
+ // Issue #681 PR 3/3 — surface the per-edge confidence used for
6653
+ // PageRank weighting / floor pruning so downstream observability
6654
+ // (recall_xray, memory_graph_explain) can attribute ranking and
6655
+ // pruning decisions to specific edges.
6656
+ edgeConfidence: candidate.edgeConfidence
6281
6657
  });
6282
6658
  }
6283
6659
  }
@@ -6290,12 +6666,12 @@ ${r.snippet.trim()}
6290
6666
  }
6291
6667
  async recordLastGraphRecallSnapshot(options) {
6292
6668
  try {
6293
- const snapshotPath = path7.join(
6669
+ const snapshotPath = path6.join(
6294
6670
  options.storage.dir,
6295
6671
  "state",
6296
6672
  "last_graph_recall.json"
6297
6673
  );
6298
- await mkdir5(path7.dirname(snapshotPath), { recursive: true });
6674
+ await mkdir5(path6.dirname(snapshotPath), { recursive: true });
6299
6675
  const now = (/* @__PURE__ */ new Date()).toISOString();
6300
6676
  const totalSeedCount = options.seedPaths.length;
6301
6677
  const totalExpandedCount = options.expandedPaths.length;
@@ -6329,12 +6705,12 @@ ${r.snippet.trim()}
6329
6705
  }
6330
6706
  async recordLastIntentSnapshot(options) {
6331
6707
  try {
6332
- const snapshotPath = path7.join(
6708
+ const snapshotPath = path6.join(
6333
6709
  options.storage.dir,
6334
6710
  "state",
6335
6711
  "last_intent.json"
6336
6712
  );
6337
- await mkdir5(path7.dirname(snapshotPath), { recursive: true });
6713
+ await mkdir5(path6.dirname(snapshotPath), { recursive: true });
6338
6714
  await writeFile4(
6339
6715
  snapshotPath,
6340
6716
  JSON.stringify(options.snapshot, null, 2),
@@ -6346,12 +6722,12 @@ ${r.snippet.trim()}
6346
6722
  }
6347
6723
  async recordLastQmdRecallSnapshot(options) {
6348
6724
  try {
6349
- const snapshotPath = path7.join(
6725
+ const snapshotPath = path6.join(
6350
6726
  options.storage.dir,
6351
6727
  "state",
6352
6728
  "last_qmd_recall.json"
6353
6729
  );
6354
- await mkdir5(path7.dirname(snapshotPath), { recursive: true });
6730
+ await mkdir5(path6.dirname(snapshotPath), { recursive: true });
6355
6731
  await writeFile4(
6356
6732
  snapshotPath,
6357
6733
  JSON.stringify(options.snapshot, null, 2),
@@ -6366,8 +6742,8 @@ ${r.snippet.trim()}
6366
6742
  const stateDir = await this.resolveStateDirForNamespace(
6367
6743
  options.namespace
6368
6744
  );
6369
- const snapshotPath = path7.join(stateDir, "last_intent.json");
6370
- await mkdir5(path7.dirname(snapshotPath), { recursive: true });
6745
+ const snapshotPath = path6.join(stateDir, "last_intent.json");
6746
+ await mkdir5(path6.dirname(snapshotPath), { recursive: true });
6371
6747
  await writeFile4(
6372
6748
  snapshotPath,
6373
6749
  JSON.stringify(options.snapshot, null, 2),
@@ -6379,12 +6755,12 @@ ${r.snippet.trim()}
6379
6755
  }
6380
6756
  async resolveStateDirForNamespace(namespace) {
6381
6757
  if (!this.config.namespacesEnabled) {
6382
- return path7.join(this.config.memoryDir, "state");
6758
+ return path6.join(this.config.memoryDir, "state");
6383
6759
  }
6384
6760
  if (namespace !== this.config.defaultNamespace) {
6385
- return path7.join(this.config.memoryDir, "namespaces", namespace, "state");
6761
+ return path6.join(this.config.memoryDir, "namespaces", namespace, "state");
6386
6762
  }
6387
- const candidate = path7.join(
6763
+ const candidate = path6.join(
6388
6764
  this.config.memoryDir,
6389
6765
  "namespaces",
6390
6766
  this.config.defaultNamespace
@@ -6392,11 +6768,11 @@ ${r.snippet.trim()}
6392
6768
  try {
6393
6769
  const candidateStat = await stat3(candidate);
6394
6770
  if (candidateStat.isDirectory()) {
6395
- return path7.join(candidate, "state");
6771
+ return path6.join(candidate, "state");
6396
6772
  }
6397
6773
  } catch {
6398
6774
  }
6399
- return path7.join(this.config.memoryDir, "state");
6775
+ return path6.join(this.config.memoryDir, "state");
6400
6776
  }
6401
6777
  buildGraphRecallRankedResults(results, sourceLabelResolver, limit = 64) {
6402
6778
  return results.slice(0, limit).map((result) => ({
@@ -6430,12 +6806,12 @@ ${r.snippet.trim()}
6430
6806
  return Math.max(0, Math.floor(value));
6431
6807
  }
6432
6808
  appendRecallSection(sectionBuckets, sectionId, content) {
6433
- if (!this.isRecallSectionEnabled(sectionId)) return;
6809
+ if (!this.isRecallSectionEnabled(sectionId)) return false;
6434
6810
  const trimmed = content.trim();
6435
- if (trimmed.length === 0) return;
6811
+ if (trimmed.length === 0) return false;
6436
6812
  const maxChars = this.getRecallSectionMaxChars(sectionId);
6437
6813
  let finalContent = trimmed;
6438
- if (maxChars === 0) return;
6814
+ if (maxChars === 0) return false;
6439
6815
  if (typeof maxChars === "number" && finalContent.length > maxChars) {
6440
6816
  finalContent = `${finalContent.slice(0, maxChars)}
6441
6817
 
@@ -6445,6 +6821,7 @@ ${r.snippet.trim()}
6445
6821
  const existing = sectionBuckets.get(sectionId) ?? [];
6446
6822
  existing.push(finalContent);
6447
6823
  sectionBuckets.set(sectionId, existing);
6824
+ return true;
6448
6825
  }
6449
6826
  truncateRecallSectionToBudget(content, maxChars) {
6450
6827
  if (maxChars <= 0) return "";
@@ -6570,6 +6947,11 @@ ${r.snippet.trim()}
6570
6947
  }
6571
6948
  async recallInternal(prompt, sessionKey, options = {}) {
6572
6949
  const recallStart = Date.now();
6950
+ let asOfMs;
6951
+ if (typeof options.asOf === "string" && options.asOf.length > 0) {
6952
+ const parsed = Date.parse(options.asOf);
6953
+ if (Number.isFinite(parsed)) asOfMs = parsed;
6954
+ }
6573
6955
  const timings = {};
6574
6956
  const profileTraceId = this.profiler.startTrace("recall", sessionKey, {
6575
6957
  qmdEnabled: this.config.qmdEnabled,
@@ -6644,6 +7026,7 @@ ${r.snippet.trim()}
6644
7026
  let recalledMemoryCount = 0;
6645
7027
  let recalledMemoryIds = [];
6646
7028
  let recalledMemoryPaths = [];
7029
+ let xrayRecalledResults = [];
6647
7030
  const xrayBranchPoolSize = {
6648
7031
  hot_qmd: 0,
6649
7032
  hot_embedding: 0,
@@ -6756,7 +7139,7 @@ ${r.snippet.trim()}
6756
7139
  const graphExpandedResultPaths = /* @__PURE__ */ new Set();
6757
7140
  const graphSourceLabelsForPath = (resultPath) => {
6758
7141
  const labels = [];
6759
- const normalizedPath = resultPath.split(path7.sep).join("/");
7142
+ const normalizedPath = resultPath.split(path6.sep).join("/");
6760
7143
  const isEntityPath = normalizedPath.startsWith("entities/") || normalizedPath.includes("/entities/");
6761
7144
  if (graphBaselinePaths.has(resultPath)) labels.push("baseline");
6762
7145
  if (graphExpandedResultPaths.has(resultPath))
@@ -6980,6 +7363,71 @@ ${trimmedBody}`;
6980
7363
  });
6981
7364
  return profile2 || null;
6982
7365
  })();
7366
+ let peerProfileXrayAnnotation = void 0;
7367
+ const peerProfileRecallPromise = (async () => {
7368
+ if (!this.config.peerProfileRecallEnabled) return null;
7369
+ if (this.config.peerProfileRecallMaxFields <= 0) return null;
7370
+ const peerId = this.getPeerIdForSession(sessionKey);
7371
+ if (!peerId) return null;
7372
+ const t0 = Date.now();
7373
+ try {
7374
+ const { readPeerProfile: _readPeerProfile } = await import("./peers-6OSQ3NK6.js");
7375
+ const peerProfile = await _readPeerProfile(this.config.memoryDir, peerId);
7376
+ recordRecallSectionMetric({
7377
+ section: "peerProfile",
7378
+ priority: "core",
7379
+ durationMs: Date.now() - t0,
7380
+ deadlineMs: recallSectionDeadlineMs,
7381
+ source: "fresh",
7382
+ success: true
7383
+ });
7384
+ if (!peerProfile) {
7385
+ peerProfileXrayAnnotation = null;
7386
+ return null;
7387
+ }
7388
+ const allFields = Object.entries(peerProfile.fields);
7389
+ if (allFields.length === 0) {
7390
+ peerProfileXrayAnnotation = null;
7391
+ return null;
7392
+ }
7393
+ const fieldsByRecency = allFields.map(([key, value]) => {
7394
+ const prov = peerProfile.provenance[key];
7395
+ let latestMs = 0;
7396
+ if (Array.isArray(prov) && prov.length > 0) {
7397
+ for (const p of prov) {
7398
+ if (typeof p.observedAt === "string") {
7399
+ const parsed = Date.parse(p.observedAt);
7400
+ if (Number.isFinite(parsed) && parsed > latestMs) {
7401
+ latestMs = parsed;
7402
+ }
7403
+ }
7404
+ }
7405
+ }
7406
+ return { key, value, latestMs };
7407
+ }).sort((a, b) => {
7408
+ if (b.latestMs !== a.latestMs) return b.latestMs - a.latestMs;
7409
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
7410
+ });
7411
+ const capped = fieldsByRecency.slice(0, this.config.peerProfileRecallMaxFields);
7412
+ const lines = capped.map(({ key, value }) => `**${key}**: ${value}`);
7413
+ peerProfileXrayAnnotation = { peerId, fieldsInjected: capped.length };
7414
+ return `## Peer Profile
7415
+
7416
+ ${lines.join("\n\n")}`;
7417
+ } catch (err) {
7418
+ recordRecallSectionMetric({
7419
+ section: "peerProfile",
7420
+ priority: "core",
7421
+ durationMs: Date.now() - t0,
7422
+ deadlineMs: recallSectionDeadlineMs,
7423
+ source: "fresh",
7424
+ success: false,
7425
+ timing: `error(${err instanceof Error ? err.message : String(err)})`
7426
+ });
7427
+ log.debug(`peer profile recall injection failed (non-fatal): ${err}`);
7428
+ return null;
7429
+ }
7430
+ })();
6983
7431
  const identityContinuityPromise = (async () => {
6984
7432
  if (!this.isRecallSectionEnabled(
6985
7433
  "identity-continuity",
@@ -7969,11 +8417,11 @@ ${formatted}`;
7969
8417
  if (!this.config.compactionResetEnabled) return null;
7970
8418
  const workspaceDir = compactionWorkspaceDir || this.config.workspaceDir || defaultWorkspaceDir();
7971
8419
  const safeSessionKey = sanitizeSessionKeyForFilename(effectiveSessionKey);
7972
- const signalPath = path7.join(
8420
+ const signalPath = path6.join(
7973
8421
  workspaceDir,
7974
8422
  `.compaction-reset-signal-${safeSessionKey}`
7975
8423
  );
7976
- const bootPath = path7.join(workspaceDir, "BOOT.md");
8424
+ const bootPath = path6.join(workspaceDir, "BOOT.md");
7977
8425
  try {
7978
8426
  const signalStat = await stat3(signalPath).catch(() => null);
7979
8427
  if (!signalStat) return null;
@@ -8275,7 +8723,8 @@ ${formatted}`;
8275
8723
  transcriptSection,
8276
8724
  compactionSection,
8277
8725
  summariesSection,
8278
- conversationRecallSection
8726
+ conversationRecallSection,
8727
+ peerProfileSection
8279
8728
  ] = await raceRecallAbort(
8280
8729
  Promise.all(
8281
8730
  [
@@ -8297,7 +8746,8 @@ ${formatted}`;
8297
8746
  ["transcript", transcriptPromise],
8298
8747
  ["compaction", compactionPromise],
8299
8748
  ["summaries", summariesPromise],
8300
- ["convRecall", conversationRecallPromise]
8749
+ ["convRecall", conversationRecallPromise],
8750
+ ["peerProfile", peerProfileRecallPromise]
8301
8751
  ].map(
8302
8752
  ([name, p]) => p.then((v) => {
8303
8753
  log.debug(
@@ -8388,6 +8838,16 @@ ${formatted}`;
8388
8838
 
8389
8839
  ${profile}`
8390
8840
  );
8841
+ if (peerProfileSection) {
8842
+ const peerSectionAppended = this.appendRecallSection(
8843
+ sectionBuckets,
8844
+ "peer-profile",
8845
+ peerProfileSection
8846
+ );
8847
+ if (!peerSectionAppended) {
8848
+ peerProfileXrayAnnotation = null;
8849
+ }
8850
+ }
8391
8851
  if (calibrationSection) {
8392
8852
  this.appendRecallSection(
8393
8853
  sectionBuckets,
@@ -8615,7 +9075,8 @@ ${tmtNode.summary}`
8615
9075
  } = await this.expandResultsViaGraph({
8616
9076
  memoryResults,
8617
9077
  recallNamespaces,
8618
- recallResultLimit
9078
+ recallResultLimit,
9079
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
8619
9080
  });
8620
9081
  graphSnapshotStatus = "completed";
8621
9082
  graphDecisionStatus = "completed";
@@ -8669,7 +9130,9 @@ ${tmtNode.summary}`
8669
9130
  memoryResults = await this.boostSearchResults(
8670
9131
  memoryResults,
8671
9132
  recallNamespaces,
8672
- retrievalQuery
9133
+ retrievalQuery,
9134
+ void 0,
9135
+ { asOfMs }
8673
9136
  );
8674
9137
  if (this.config.rerankEnabled && this.config.rerankProvider === "local") {
8675
9138
  const ranked = await rerankLocalOrNoop({
@@ -8791,6 +9254,7 @@ ${tmtNode.summary}`
8791
9254
  });
8792
9255
  recalledMemoryIds = this.extractMemoryIdsFromResults(memoryResults);
8793
9256
  recalledMemoryPaths = memoryResults.map((result) => result.path).filter(Boolean);
9257
+ xrayRecalledResults = memoryResults;
8794
9258
  impressionRecorded = true;
8795
9259
  } else if (!confidenceGateRejected) {
8796
9260
  const queryAwarePrefilter = await queryAwarePrefilterPromise;
@@ -8814,7 +9278,9 @@ ${tmtNode.summary}`
8814
9278
  const boostedScoped = await this.boostSearchResults(
8815
9279
  scopedCandidates,
8816
9280
  recallNamespaces,
8817
- retrievalQuery
9281
+ retrievalQuery,
9282
+ void 0,
9283
+ { asOfMs }
8818
9284
  );
8819
9285
  xrayBranchPoolSize.hot_embedding = Math.max(
8820
9286
  xrayBranchPoolSize.hot_embedding,
@@ -8849,6 +9315,7 @@ ${tmtNode.summary}`
8849
9315
  });
8850
9316
  recalledMemoryIds = this.extractMemoryIdsFromResults(scoped);
8851
9317
  recalledMemoryPaths = scoped.map((result) => result.path).filter(Boolean);
9318
+ xrayRecalledResults = scoped;
8852
9319
  impressionRecorded = true;
8853
9320
  } else {
8854
9321
  const longTerm = await this.applyColdFallbackPipeline({
@@ -8858,7 +9325,9 @@ ${tmtNode.summary}`
8858
9325
  recallMode,
8859
9326
  queryAwarePrefilter,
8860
9327
  abortSignal: options.abortSignal,
8861
- xrayPoolSizeSink: xrayColdPoolSink
9328
+ xrayPoolSizeSink: xrayColdPoolSink,
9329
+ asOfMs,
9330
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
8862
9331
  });
8863
9332
  if (longTerm.length > 0) {
8864
9333
  if (shouldPersistGraphSnapshot) {
@@ -8883,6 +9352,7 @@ ${tmtNode.summary}`
8883
9352
  });
8884
9353
  recalledMemoryIds = this.extractMemoryIdsFromResults(longTerm);
8885
9354
  recalledMemoryPaths = longTerm.map((result) => result.path).filter(Boolean);
9355
+ xrayRecalledResults = longTerm;
8886
9356
  impressionRecorded = true;
8887
9357
  }
8888
9358
  }
@@ -8940,7 +9410,9 @@ ${tmtNode.summary}`
8940
9410
  const boostedScoped = await this.boostSearchResults(
8941
9411
  scopedCandidates,
8942
9412
  recallNamespaces,
8943
- retrievalQuery
9413
+ retrievalQuery,
9414
+ void 0,
9415
+ { asOfMs }
8944
9416
  );
8945
9417
  xrayBranchPoolSize.hot_embedding = Math.max(
8946
9418
  xrayBranchPoolSize.hot_embedding,
@@ -8975,6 +9447,7 @@ ${tmtNode.summary}`
8975
9447
  });
8976
9448
  recalledMemoryIds = this.extractMemoryIdsFromResults(scoped);
8977
9449
  recalledMemoryPaths = scoped.map((result) => result.path).filter(Boolean);
9450
+ xrayRecalledResults = scoped;
8978
9451
  impressionRecorded = true;
8979
9452
  } else {
8980
9453
  const memories = await this.readAllMemoriesForNamespaces(recallNamespaces);
@@ -8983,12 +9456,14 @@ ${tmtNode.summary}`
8983
9456
  enabled: this.config.temporalSupersessionEnabled,
8984
9457
  includeInRecall: this.config.temporalSupersessionIncludeInRecall
8985
9458
  };
9459
+ const asOfActive = typeof asOfMs === "number" && Number.isFinite(asOfMs);
8986
9460
  const activeMemories = memories.filter(
8987
9461
  (m) => {
8988
9462
  if (isArtifactMemoryPath(m.path)) return false;
8989
9463
  const status = m.frontmatter.status;
8990
9464
  if (!status || status === "active") return true;
8991
9465
  if (status === "superseded") {
9466
+ if (asOfActive) return true;
8992
9467
  return !shouldFilterSupersededFromRecall(m.frontmatter, supersessionOptions);
8993
9468
  }
8994
9469
  return false;
@@ -9005,7 +9480,9 @@ ${tmtNode.summary}`
9005
9480
  recallMode,
9006
9481
  queryAwarePrefilter,
9007
9482
  abortSignal: options.abortSignal,
9008
- xrayPoolSizeSink: xrayColdPoolSink
9483
+ xrayPoolSizeSink: xrayColdPoolSink,
9484
+ asOfMs,
9485
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
9009
9486
  });
9010
9487
  if (longTerm.length > 0) {
9011
9488
  recallSource = "cold_fallback";
@@ -9024,6 +9501,7 @@ ${tmtNode.summary}`
9024
9501
  });
9025
9502
  recalledMemoryIds = this.extractMemoryIdsFromResults(longTerm);
9026
9503
  recalledMemoryPaths = longTerm.map((result) => result.path).filter(Boolean);
9504
+ xrayRecalledResults = longTerm;
9027
9505
  impressionRecorded = true;
9028
9506
  }
9029
9507
  } else {
@@ -9045,7 +9523,8 @@ ${tmtNode.summary}`
9045
9523
  recentAsResults,
9046
9524
  recallNamespaces,
9047
9525
  retrievalQuery,
9048
- preloadedMap
9526
+ preloadedMap,
9527
+ { asOfMs }
9049
9528
  )).sort((a, b) => b.score - a.score);
9050
9529
  xrayBranchPoolSize.recent_scan = Math.max(
9051
9530
  xrayBranchPoolSize.recent_scan,
@@ -9080,6 +9559,7 @@ ${tmtNode.summary}`
9080
9559
  });
9081
9560
  recalledMemoryIds = this.extractMemoryIdsFromResults(recent);
9082
9561
  recalledMemoryPaths = recent.map((result) => result.path).filter(Boolean);
9562
+ xrayRecalledResults = recent;
9083
9563
  impressionRecorded = true;
9084
9564
  } else {
9085
9565
  const longTerm = await this.applyColdFallbackPipeline({
@@ -9089,7 +9569,9 @@ ${tmtNode.summary}`
9089
9569
  recallMode,
9090
9570
  queryAwarePrefilter,
9091
9571
  abortSignal: options.abortSignal,
9092
- xrayPoolSizeSink: xrayColdPoolSink
9572
+ xrayPoolSizeSink: xrayColdPoolSink,
9573
+ asOfMs,
9574
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
9093
9575
  });
9094
9576
  if (longTerm.length > 0) {
9095
9577
  if (shouldPersistGraphSnapshot) {
@@ -9114,6 +9596,7 @@ ${tmtNode.summary}`
9114
9596
  });
9115
9597
  recalledMemoryIds = this.extractMemoryIdsFromResults(longTerm);
9116
9598
  recalledMemoryPaths = longTerm.map((result) => result.path).filter(Boolean);
9599
+ xrayRecalledResults = longTerm;
9117
9600
  impressionRecorded = true;
9118
9601
  }
9119
9602
  }
@@ -9126,7 +9609,9 @@ ${tmtNode.summary}`
9126
9609
  recallMode,
9127
9610
  queryAwarePrefilter,
9128
9611
  abortSignal: options.abortSignal,
9129
- xrayPoolSizeSink: xrayColdPoolSink
9612
+ xrayPoolSizeSink: xrayColdPoolSink,
9613
+ asOfMs,
9614
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
9130
9615
  });
9131
9616
  if (longTerm.length > 0) {
9132
9617
  if (shouldPersistGraphSnapshot) {
@@ -9151,6 +9636,7 @@ ${tmtNode.summary}`
9151
9636
  });
9152
9637
  recalledMemoryIds = this.extractMemoryIdsFromResults(longTerm);
9153
9638
  recalledMemoryPaths = longTerm.map((result) => result.path).filter(Boolean);
9639
+ xrayRecalledResults = longTerm;
9154
9640
  impressionRecorded = true;
9155
9641
  }
9156
9642
  }
@@ -9311,15 +9797,25 @@ _Context: ${topQuestion.context}_`
9311
9797
  const match = p.match(/([^/]+)\.md$/);
9312
9798
  return match ? match[1] ?? null : null;
9313
9799
  };
9800
+ const xrayResultByPath = new Map(
9801
+ xrayRecalledResults.map((xr) => [xr.path, xr])
9802
+ );
9314
9803
  const results = [];
9315
9804
  for (const recalledPath of recalledMemoryPaths) {
9316
9805
  const derivedId = idFromPath(recalledPath);
9317
9806
  if (!derivedId) continue;
9807
+ const xrayResult = xrayResultByPath.get(recalledPath);
9808
+ const scoreDecomposition = {
9809
+ final: xrayResult?.score ?? 0
9810
+ };
9811
+ if (xrayResult?.explain?.reinforcementBoost !== void 0 && xrayResult.explain.reinforcementBoost > 0) {
9812
+ scoreDecomposition.reinforcementBoost = xrayResult.explain.reinforcementBoost;
9813
+ }
9318
9814
  results.push({
9319
9815
  memoryId: derivedId,
9320
9816
  path: recalledPath,
9321
9817
  servedBy,
9322
- scoreDecomposition: { final: 0 },
9818
+ scoreDecomposition,
9323
9819
  admittedBy: []
9324
9820
  });
9325
9821
  }
@@ -9365,7 +9861,14 @@ _Context: ${topQuestion.context}_`
9365
9861
  },
9366
9862
  sessionKey,
9367
9863
  namespace: selfNamespace,
9368
- traceId
9864
+ traceId,
9865
+ // Issue #679 completion: record peer-profile injection in the
9866
+ // xray snapshot. peerProfileXrayAnnotation is set inside
9867
+ // peerProfileRecallPromise when injection actually occurred,
9868
+ // and stays null otherwise. By the time xray capture runs,
9869
+ // phase-1 parallel work is complete so the annotation is
9870
+ // guaranteed to be populated.
9871
+ peerProfileInjection: peerProfileXrayAnnotation
9369
9872
  });
9370
9873
  } catch (err) {
9371
9874
  log.debug(`x-ray capture failed: ${err}`);
@@ -10093,7 +10596,7 @@ ${normalized}`).digest("hex");
10093
10596
  );
10094
10597
  this.tierMigrationInFlight = true;
10095
10598
  try {
10096
- const coldStorage = new StorageManager(path7.join(storage.dir, "cold"));
10599
+ const coldStorage = new StorageManager(path6.join(storage.dir, "cold"));
10097
10600
  const [hotMemories, coldMemories] = await Promise.all([
10098
10601
  storage.readAllMemories(),
10099
10602
  coldStorage.readAllMemories()
@@ -10659,6 +11162,7 @@ ${normalized}`).digest("hex");
10659
11162
  let writeCategory = fact.category;
10660
11163
  let targetStorage = storage;
10661
11164
  let routedRuleId;
11165
+ let routedNamespaceExplicit = false;
10662
11166
  if (routeRules.length > 0) {
10663
11167
  try {
10664
11168
  const routeText = `${fact.category} ${fact.tags.join(" ")} ${fact.content}`;
@@ -10669,6 +11173,7 @@ ${normalized}`).digest("hex");
10669
11173
  writeCategory = selected.target.category;
10670
11174
  }
10671
11175
  if (selected.target.namespace) {
11176
+ routedNamespaceExplicit = true;
10672
11177
  targetStorage = await this.storageRouter.storageFor(
10673
11178
  selected.target.namespace
10674
11179
  );
@@ -10680,6 +11185,23 @@ ${normalized}`).digest("hex");
10680
11185
  );
10681
11186
  }
10682
11187
  }
11188
+ if (this.config.extractionScopeClassificationEnabled && this.config.namespacesEnabled && fact.scope === "global" && !routedNamespaceExplicit) {
11189
+ const currentNs = this.namespaceFromStorageDir(targetStorage.dir);
11190
+ if (currentNs !== this.config.sharedNamespace) {
11191
+ try {
11192
+ targetStorage = await this.storageRouter.storageFor(
11193
+ this.config.sharedNamespace
11194
+ );
11195
+ log.debug(
11196
+ `scope-routing: fact "${fact.content.slice(0, 60)}\u2026" routed to shared namespace (scope=global)`
11197
+ );
11198
+ } catch (scopeRouteErr) {
11199
+ log.warn(
11200
+ `scope-routing: failed to resolve shared namespace storage; writing to session namespace (fail-open): ${scopeRouteErr}`
11201
+ );
11202
+ }
11203
+ }
11204
+ }
10683
11205
  const canonicalContentForHash = citationEnabled && hasCitationForTemplate(fact.content, citationTemplate) ? stripCitationForTemplate(fact.content, citationTemplate) : fact.content;
10684
11206
  const contentHashDedupKey = writeCategory === "procedure" ? buildProcedurePersistBody(fact.content, fact.procedureSteps) : canonicalContentForHash;
10685
11207
  if (this.contentHashIndex && this.contentHashIndex.has(contentHashDedupKey)) {
@@ -11266,7 +11788,7 @@ ${normalized}`).digest("hex");
11266
11788
  const allMems = allMemsForGraph ?? [];
11267
11789
  for (const m of allMems) {
11268
11790
  if (m.frontmatter.entityRef === entityRef) {
11269
- const rel = path7.relative(storage.dir, m.path);
11791
+ const rel = path6.relative(storage.dir, m.path);
11270
11792
  if (rel !== memoryRelPath) entitySiblings.push(rel);
11271
11793
  }
11272
11794
  }
@@ -11333,8 +11855,7 @@ ${normalized}`).digest("hex");
11333
11855
  ])
11334
11856
  )
11335
11857
  ) : await storage.readAllMemories();
11336
- const isActive = (m) => !m.frontmatter.status || m.frontmatter.status === "active";
11337
- const pool = needsFullRebuild ? allMemories.filter(isActive) : (() => {
11858
+ const pool = needsFullRebuild ? allMemories.filter((m) => isActiveMemoryStatus(m.frontmatter.status)) : (() => {
11338
11859
  const idSet = new Set(persistedIds);
11339
11860
  return allMemories.filter((m) => idSet.has(m.frontmatter.id));
11340
11861
  })();
@@ -11520,24 +12041,54 @@ ${normalized}`).digest("hex");
11520
12041
  }
11521
12042
  if (this.config.lifecyclePolicyEnabled) {
11522
12043
  try {
12044
+ const lightSleepStartedAt = (/* @__PURE__ */ new Date()).toISOString();
11523
12045
  const lifecycleCorpus = await this.storage.readAllMemories();
11524
12046
  await this.runLifecyclePolicyPass(lifecycleCorpus);
12047
+ await this.recordScheduledDreamsPhaseRun(
12048
+ "lightSleep",
12049
+ lifecycleCorpus.length,
12050
+ `scheduled lifecycle policy pass assessed ${lifecycleCorpus.length} memories`,
12051
+ {
12052
+ startedAt: lightSleepStartedAt,
12053
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
12054
+ }
12055
+ );
11525
12056
  } catch (err) {
11526
12057
  log.warn(`lifecycle policy pass failed (ignored): ${err}`);
11527
12058
  }
11528
12059
  }
11529
12060
  await this.runCompressionGuidelineLearningPass();
11530
- await this.runTierMigrationCycle(this.storage, "maintenance");
11531
- allMemories = await this.storage.readAllMemories();
11532
- if (this.config.factArchivalEnabled) {
11533
- const archived = await this.runFactArchival(allMemories);
11534
- if (archived > 0) {
11535
- log.info(`archived ${archived} old low-importance facts`);
12061
+ try {
12062
+ const deepSleepStartedAt = (/* @__PURE__ */ new Date()).toISOString();
12063
+ await this.runTierMigrationCycle(this.storage, "maintenance");
12064
+ allMemories = await this.storage.readAllMemories();
12065
+ if (this.config.factArchivalEnabled) {
12066
+ const archived = await this.runFactArchival(allMemories);
12067
+ if (archived > 0) {
12068
+ log.info(`archived ${archived} old low-importance facts`);
12069
+ }
12070
+ }
12071
+ await this.recordScheduledDreamsPhaseRun(
12072
+ "deepSleep",
12073
+ allMemories.length,
12074
+ `scheduled deep-sleep maintenance assessed ${allMemories.length} memories`,
12075
+ {
12076
+ startedAt: deepSleepStartedAt,
12077
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
12078
+ }
12079
+ );
12080
+ } catch (err) {
12081
+ log.warn(`deep-sleep maintenance pass failed (ignored): ${err}`);
12082
+ try {
12083
+ allMemories = await this.storage.readAllMemories();
12084
+ } catch (readErr) {
12085
+ log.warn(`deep-sleep maintenance recovery read failed: ${readErr}`);
12086
+ throw err;
11536
12087
  }
11537
12088
  }
11538
12089
  if (this.config.semanticConsolidationEnabled) {
11539
12090
  try {
11540
- const stateFilePath = path7.join(
12091
+ const stateFilePath = path6.join(
11541
12092
  this.config.memoryDir,
11542
12093
  "state",
11543
12094
  "semantic-consolidation-last-run.json"
@@ -11559,15 +12110,33 @@ ${normalized}`).digest("hex");
11559
12110
  } catch {
11560
12111
  }
11561
12112
  if (shouldRun) {
12113
+ const remStartedAt = (/* @__PURE__ */ new Date()).toISOString();
11562
12114
  const semResult = await this.runSemanticConsolidation();
12115
+ let remItemsProcessed = allMemories.length;
12116
+ try {
12117
+ allMemories = await this.storage.readAllMemories();
12118
+ remItemsProcessed = allMemories.length;
12119
+ } catch (err) {
12120
+ log.warn(
12121
+ `[semantic-consolidation] post-run telemetry refresh failed (non-fatal): ${err}`
12122
+ );
12123
+ }
12124
+ await this.recordScheduledDreamsPhaseRun(
12125
+ "rem",
12126
+ remItemsProcessed,
12127
+ `scheduled REM consolidation found ${semResult.clustersFound} clusters`,
12128
+ {
12129
+ startedAt: remStartedAt,
12130
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
12131
+ }
12132
+ );
11563
12133
  if (semResult.memoriesArchived > 0) {
11564
12134
  log.info(
11565
12135
  `[semantic-consolidation] archived ${semResult.memoriesArchived} memories during maintenance`
11566
12136
  );
11567
- allMemories = await this.storage.readAllMemories();
11568
12137
  }
11569
12138
  if (semResult.errors === 0 || semResult.memoriesArchived > 0) {
11570
- const stateDir = path7.join(this.config.memoryDir, "state");
12139
+ const stateDir = path6.join(this.config.memoryDir, "state");
11571
12140
  await mkdir5(stateDir, { recursive: true });
11572
12141
  await writeFile4(
11573
12142
  stateFilePath,
@@ -11618,7 +12187,7 @@ ${normalized}`).digest("hex");
11618
12187
  if (this.config.temporalMemoryTreeEnabled) {
11619
12188
  try {
11620
12189
  const tmtEntries = allMemories.filter(
11621
- (m) => m.frontmatter.status !== "superseded" && m.frontmatter.status !== "archived"
12190
+ (m) => m.frontmatter.status !== "superseded" && m.frontmatter.status !== "archived" && m.frontmatter.status !== "forgotten"
11622
12191
  ).map((m) => ({
11623
12192
  path: m.path,
11624
12193
  id: m.frontmatter.id,
@@ -11933,8 +12502,8 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
11933
12502
  return 0;
11934
12503
  }
11935
12504
  }
11936
- async buildLifecycleActionPriors() {
11937
- const events = await this.storage.readMemoryActionEvents(1200);
12505
+ async buildLifecycleActionPriors(storage = this.storage) {
12506
+ const events = await storage.readMemoryActionEvents(1200);
11938
12507
  if (events.length === 0) return /* @__PURE__ */ new Map();
11939
12508
  const nowMs = Date.now();
11940
12509
  const windowMs = 14 * 24 * 60 * 60 * 1e3;
@@ -11971,7 +12540,28 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
11971
12540
  }
11972
12541
  return out;
11973
12542
  }
11974
- async runLifecyclePolicyPass(allMemories) {
12543
+ async recordScheduledDreamsPhaseRun(phase, itemsProcessed, notes, timing = {}) {
12544
+ try {
12545
+ const { recordDreamsPhaseRun } = await import("./dreams-ledger-LR2NBAZE.js");
12546
+ await recordDreamsPhaseRun({
12547
+ memoryDir: this.storage.dir,
12548
+ phase,
12549
+ trigger: "scheduled",
12550
+ itemsProcessed,
12551
+ notes,
12552
+ startedAt: timing.startedAt,
12553
+ completedAt: timing.completedAt
12554
+ });
12555
+ } catch (error) {
12556
+ log.debug(`dreams ledger scheduled ${phase} write failed (non-fatal): ${error}`);
12557
+ }
12558
+ }
12559
+ async runLifecyclePolicyNow(storage = this.storage) {
12560
+ const lifecycleCorpus = await storage.readAllMemories();
12561
+ await this.runLifecyclePolicyPass(lifecycleCorpus, storage);
12562
+ return { memoriesAssessed: lifecycleCorpus.length };
12563
+ }
12564
+ async runLifecyclePolicyPass(allMemories, storage = this.storage) {
11975
12565
  const now = /* @__PURE__ */ new Date();
11976
12566
  const nowIso = now.toISOString();
11977
12567
  const countsByState = {
@@ -11992,9 +12582,9 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
11992
12582
  archiveDecayThreshold: thresholds.archiveDecayThreshold,
11993
12583
  protectedCategories: this.config.lifecycleProtectedCategories
11994
12584
  };
11995
- const actionPriors = await this.buildLifecycleActionPriors();
12585
+ const actionPriors = await this.buildLifecycleActionPriors(storage);
11996
12586
  for (const memory of allMemories) {
11997
- if (memory.frontmatter.status === "superseded") {
12587
+ if (memory.frontmatter.status === "superseded" || memory.frontmatter.status === "forgotten") {
11998
12588
  continue;
11999
12589
  }
12000
12590
  evaluatedCount += 1;
@@ -12016,7 +12606,7 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
12016
12606
  const scoreDelta = Math.abs((prevHeat ?? -1) - decision.heatScore) + Math.abs((prevDecay ?? -1) - decision.decayScore);
12017
12607
  const shouldPersist = memory.frontmatter.lifecycleState !== nextState || memory.frontmatter.heatScore === void 0 || memory.frontmatter.decayScore === void 0 || memory.frontmatter.lastValidatedAt === void 0 || scoreDelta >= 0.01;
12018
12608
  if (!shouldPersist) continue;
12019
- const wrote = await this.storage.writeMemoryFrontmatter(memory, {
12609
+ const wrote = await storage.writeMemoryFrontmatter(memory, {
12020
12610
  lifecycleState: nextState,
12021
12611
  heatScore: decision.heatScore,
12022
12612
  decayScore: decision.decayScore,
@@ -12041,12 +12631,12 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
12041
12631
  protectedCategories: this.config.lifecycleProtectedCategories
12042
12632
  }
12043
12633
  };
12044
- const metricsPath = path7.join(
12045
- this.storage.dir,
12634
+ const metricsPath = path6.join(
12635
+ storage.dir,
12046
12636
  "state",
12047
12637
  "lifecycle-metrics.json"
12048
12638
  );
12049
- await mkdir5(path7.dirname(metricsPath), { recursive: true });
12639
+ await mkdir5(path6.dirname(metricsPath), { recursive: true });
12050
12640
  await writeFile4(metricsPath, JSON.stringify(metrics, null, 2), "utf-8");
12051
12641
  }
12052
12642
  /**
@@ -12108,7 +12698,7 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
12108
12698
  */
12109
12699
  async runSummarization(allMemories) {
12110
12700
  const activeMemories = allMemories.filter(
12111
- (m) => !m.frontmatter.status || m.frontmatter.status === "active"
12701
+ (m) => isActiveMemoryStatus(m.frontmatter.status)
12112
12702
  );
12113
12703
  if (activeMemories.length < this.config.summarizationTriggerCount) {
12114
12704
  return;
@@ -12173,7 +12763,7 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
12173
12763
  */
12174
12764
  async runTopicExtraction(allMemories) {
12175
12765
  const activeMemories = allMemories.filter(
12176
- (m) => !m.frontmatter.status || m.frontmatter.status === "active"
12766
+ (m) => isActiveMemoryStatus(m.frontmatter.status)
12177
12767
  );
12178
12768
  if (activeMemories.length === 0) return;
12179
12769
  const topics = extractTopics(
@@ -12573,7 +13163,7 @@ ${lines.join("\n\n")}`;
12573
13163
  nsMap = buildMemoryWorthCounterMap(memories);
12574
13164
  this.memoryWorthCounterCache.set(ns, { at: nowMs, counters: nsMap });
12575
13165
  }
12576
- for (const [path8, c] of nsMap) counters.set(path8, c);
13166
+ for (const [path7, c] of nsMap) counters.set(path7, c);
12577
13167
  } catch (err) {
12578
13168
  log.debug("memory-worth: failed to read namespace, skipping", {
12579
13169
  namespace: ns,
@@ -12744,12 +13334,12 @@ ${lines.join("\n\n")}`;
12744
13334
  */
12745
13335
  semanticDedupScopeFor(targetStorage) {
12746
13336
  if (!this.config.namespacesEnabled) return {};
12747
- const memoryDir = path7.resolve(this.config.memoryDir);
12748
- const storageDir = path7.resolve(targetStorage.dir);
13337
+ const memoryDir = path6.resolve(this.config.memoryDir);
13338
+ const storageDir = path6.resolve(targetStorage.dir);
12749
13339
  if (storageDir === memoryDir) {
12750
13340
  return { pathExcludePrefixes: ["namespaces/"] };
12751
13341
  }
12752
- let rel = path7.relative(memoryDir, storageDir);
13342
+ let rel = path6.relative(memoryDir, storageDir);
12753
13343
  if (!rel || rel.startsWith("..")) {
12754
13344
  log.debug(
12755
13345
  `semantic dedup: target storage dir ${storageDir} is outside memoryDir ${memoryDir}; scoping lookup to absolute path prefix`
@@ -12768,7 +13358,7 @@ ${lines.join("\n\n")}`;
12768
13358
  if (hits.length === 0) return [];
12769
13359
  const results = [];
12770
13360
  for (const hit of hits) {
12771
- const fullPath = path7.isAbsolute(hit.path) ? hit.path : path7.join(this.config.memoryDir, hit.path);
13361
+ const fullPath = path6.isAbsolute(hit.path) ? hit.path : path6.join(this.config.memoryDir, hit.path);
12772
13362
  const memory = await this.storage.readMemoryByPath(fullPath);
12773
13363
  if (!memory) continue;
12774
13364
  results.push({
@@ -12900,7 +13490,8 @@ ${lines.join("\n\n")}`;
12900
13490
  const { merged } = await this.expandResultsViaGraph({
12901
13491
  memoryResults: results,
12902
13492
  recallNamespaces: options.recallNamespaces,
12903
- recallResultLimit: options.recallResultLimit
13493
+ recallResultLimit: options.recallResultLimit,
13494
+ ...options.includeLowConfidence === true ? { includeLowConfidence: true } : {}
12904
13495
  });
12905
13496
  results = merged;
12906
13497
  }
@@ -12909,7 +13500,7 @@ ${lines.join("\n\n")}`;
12909
13500
  options.recallNamespaces,
12910
13501
  options.prompt,
12911
13502
  void 0,
12912
- { allowLifecycleFiltered: true }
13503
+ { allowLifecycleFiltered: true, asOfMs: options.asOfMs }
12913
13504
  );
12914
13505
  if (this.config.rerankEnabled && this.config.rerankProvider === "local") {
12915
13506
  const ranked = await rerankLocalOrNoop({
@@ -13083,12 +13674,17 @@ ${lines.join("\n\n")}`;
13083
13674
  let lifecycleFilteredCount = 0;
13084
13675
  let temporalSupersededFilteredCount = 0;
13085
13676
  let dedicatedSurfaceFilteredCount = 0;
13677
+ let forgottenFilteredCount = 0;
13086
13678
  const boosted = [];
13087
13679
  const recencyWeight = this.effectiveRecencyWeight();
13088
13680
  for (const r of results) {
13089
13681
  const memory = memoryByPath.get(r.path);
13090
13682
  let score = r.score;
13091
13683
  if (memory) {
13684
+ if (memory.frontmatter.status === "forgotten") {
13685
+ forgottenFilteredCount += 1;
13686
+ continue;
13687
+ }
13092
13688
  if (options?.allowLifecycleFiltered !== true && shouldFilterLifecycleRecallCandidate(memory.frontmatter, {
13093
13689
  lifecyclePolicyEnabled: this.config.lifecyclePolicyEnabled,
13094
13690
  lifecycleFilterStaleEnabled: this.config.lifecycleFilterStaleEnabled
@@ -13096,10 +13692,28 @@ ${lines.join("\n\n")}`;
13096
13692
  lifecycleFilteredCount += 1;
13097
13693
  continue;
13098
13694
  }
13099
- if (shouldFilterSupersededFromRecall(memory.frontmatter, {
13100
- enabled: this.config.temporalSupersessionEnabled,
13101
- includeInRecall: this.config.temporalSupersessionIncludeInRecall
13102
- })) {
13695
+ const asOfActive = typeof options?.asOfMs === "number" && Number.isFinite(options.asOfMs);
13696
+ if (asOfActive) {
13697
+ if (!isValidAsOf(memory.frontmatter, options.asOfMs)) {
13698
+ temporalSupersededFilteredCount += 1;
13699
+ continue;
13700
+ }
13701
+ } else if (
13702
+ // Temporal supersession filter (issue #375): drop memories that
13703
+ // a newer fact has retired, unless the caller opted in to history.
13704
+ // NOTE: This check is intentionally independent of
13705
+ // allowLifecycleFiltered (Finding A fix) — cold fallback sets
13706
+ // allowLifecycleFiltered=true to include archived/retired
13707
+ // candidates, but superseded memories must still be filtered
13708
+ // unless temporalSupersessionIncludeInRecall is set.
13709
+ // Skipped entirely when `as_of` is active (above branch); the
13710
+ // half-open `[valid_at, invalid_at)` evaluation in isValidAsOf
13711
+ // is the authoritative gate for historical recall.
13712
+ shouldFilterSupersededFromRecall(memory.frontmatter, {
13713
+ enabled: this.config.temporalSupersessionEnabled,
13714
+ includeInRecall: this.config.temporalSupersessionIncludeInRecall
13715
+ })
13716
+ ) {
13103
13717
  temporalSupersededFilteredCount += 1;
13104
13718
  continue;
13105
13719
  }
@@ -13198,6 +13812,22 @@ ${lines.join("\n\n")}`;
13198
13812
  this.utilityRuntimeValues,
13199
13813
  lifecycleDelta >= 0 ? "boost" : "suppress"
13200
13814
  );
13815
+ let reinforcementBoost = 0;
13816
+ if (this.config.reinforcementRecallBoostEnabled && typeof memory.frontmatter.reinforcement_count === "number" && memory.frontmatter.reinforcement_count > 0) {
13817
+ reinforcementBoost = Math.min(
13818
+ memory.frontmatter.reinforcement_count * this.config.reinforcementRecallBoostWeight,
13819
+ this.config.reinforcementRecallBoostMax
13820
+ );
13821
+ score += reinforcementBoost;
13822
+ }
13823
+ if (reinforcementBoost > 0) {
13824
+ boosted.push({
13825
+ ...r,
13826
+ score,
13827
+ explain: { ...r.explain ?? {}, reinforcementBoost }
13828
+ });
13829
+ continue;
13830
+ }
13201
13831
  }
13202
13832
  boosted.push({ ...r, score });
13203
13833
  }
@@ -13216,6 +13846,11 @@ ${lines.join("\n\n")}`;
13216
13846
  `dedicated surface filter removed ${dedicatedSurfaceFilteredCount} dream/procedural candidates from generic recall`
13217
13847
  );
13218
13848
  }
13849
+ if (forgottenFilteredCount > 0) {
13850
+ log.debug(
13851
+ `forgotten status filter removed ${forgottenFilteredCount} candidates from recall`
13852
+ );
13853
+ }
13219
13854
  return boosted.sort((a, b) => b.score - a.score);
13220
13855
  }
13221
13856
  /**
@@ -13266,7 +13901,9 @@ ${lines.join("\n\n")}`;
13266
13901
  const resultStorage = await this.storageRouter.storageFor(resultNamespace);
13267
13902
  const existingMemory = await resultStorage.getMemoryById(memoryId);
13268
13903
  if (!existingMemory) continue;
13269
- if (existingMemory.frontmatter.status === "superseded") continue;
13904
+ if (existingMemory.frontmatter.status === "superseded" || existingMemory.frontmatter.status === "forgotten") {
13905
+ continue;
13906
+ }
13270
13907
  const verification = await this.extraction.verifyContradiction(
13271
13908
  { content, category },
13272
13909
  {
@@ -13330,7 +13967,7 @@ ${lines.join("\n\n")}`;
13330
13967
  if (resultNamespace !== namespaceScope) continue;
13331
13968
  const resultStorage = await this.storageRouter.storageFor(resultNamespace);
13332
13969
  const memory = await resultStorage.getMemoryById(memoryId);
13333
- if (memory && memory.frontmatter.status !== "superseded") {
13970
+ if (memory && memory.frontmatter.status !== "superseded" && memory.frontmatter.status !== "forgotten") {
13334
13971
  candidates.push({
13335
13972
  id: memory.frontmatter.id,
13336
13973
  content: memory.content,
@@ -13358,8 +13995,8 @@ ${lines.join("\n\n")}`;
13358
13995
  }
13359
13996
  namespaceFromStorageDir(storageDir) {
13360
13997
  if (!this.config.namespacesEnabled) return this.config.defaultNamespace;
13361
- const resolvedStorageDir = path7.resolve(storageDir);
13362
- const resolvedMemoryDir = path7.resolve(this.config.memoryDir);
13998
+ const resolvedStorageDir = path6.resolve(storageDir);
13999
+ const resolvedMemoryDir = path6.resolve(this.config.memoryDir);
13363
14000
  if (resolvedStorageDir === resolvedMemoryDir)
13364
14001
  return this.config.defaultNamespace;
13365
14002
  const m = resolvedStorageDir.match(/[\\/]namespaces[\\/]([^\\/]+)$/);
@@ -13400,9 +14037,9 @@ export {
13400
14037
  saveTaxonomy,
13401
14038
  getTaxonomyDir,
13402
14039
  getTaxonomyFilePath,
13403
- stableHash,
13404
- normalizeOriginUrl,
13405
- resolveGitContext,
14040
+ openLcmDatabase,
14041
+ ensureLcmStateDir,
14042
+ applyLcmSchema,
13406
14043
  projectNamespaceName,
13407
14044
  branchNamespaceName,
13408
14045
  resolveCodingNamespaceOverlay,
@@ -13435,4 +14072,4 @@ export {
13435
14072
  resolvePersistedMemoryRelativePath,
13436
14073
  Orchestrator
13437
14074
  };
13438
- //# sourceMappingURL=chunk-3YGHKTBF.js.map
14075
+ //# sourceMappingURL=chunk-NZS2BLTP.js.map