@remnic/core 10.0.169 → 10.0.170

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 (349) hide show
  1. package/dist/access-admin-ops-surface.js +124 -123
  2. package/dist/access-cli.js +124 -123
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-coding-context-resolution.js +8 -8
  5. package/dist/access-extraction-force-flush-preempt.js +124 -123
  6. package/dist/access-extraction-force-flush.js +124 -123
  7. package/dist/access-http-briefing.js +124 -123
  8. package/dist/access-http-query.js +124 -123
  9. package/dist/access-http.js +124 -123
  10. package/dist/access-identity-continuity-surface.js +124 -123
  11. package/dist/access-lcm-surface.js +124 -123
  12. package/dist/access-mcp.js +124 -123
  13. package/dist/access-observe-write-category.js +8 -8
  14. package/dist/access-observe-write-surface.js +124 -123
  15. package/dist/access-offline-manifest.js +5 -5
  16. package/dist/access-operations-batch.js +124 -123
  17. package/dist/access-operations.js +124 -123
  18. package/dist/access-recall-concurrency.js +124 -123
  19. package/dist/access-recall-diagnostics.js +2 -2
  20. package/dist/access-recall-response.js +124 -123
  21. package/dist/access-recall-surface.d.ts.map +1 -1
  22. package/dist/access-recall-surface.js +124 -123
  23. package/dist/access-schema.js +7 -7
  24. package/dist/access-service.js +124 -123
  25. package/dist/active-recall.js +21 -20
  26. package/dist/active-recall.js.map +1 -1
  27. package/dist/adapters/index.js +4 -4
  28. package/dist/adapters/registry.js +2 -2
  29. package/dist/behavior-learner.js +1 -1
  30. package/dist/briefing.js +13 -13
  31. package/dist/buffer.js +6 -6
  32. package/dist/causal-behavior.js +2 -2
  33. package/dist/causal-chain.js +2 -2
  34. package/dist/causal-consolidation.js +16 -16
  35. package/dist/causal-retrieval.js +2 -2
  36. package/dist/causal-trajectory-graph.js +2 -2
  37. package/dist/causal-trajectory.js +1 -1
  38. package/dist/{chunk-FHWX2REL.js → chunk-2OAFPBQB.js} +2 -2
  39. package/dist/{chunk-5IZL4DCV.js → chunk-4DF5LMBJ.js} +2 -2
  40. package/dist/{chunk-FWTGO4NE.js → chunk-4DLGKTM6.js} +2 -2
  41. package/dist/{chunk-D6YCETHG.js → chunk-4E2Z44CV.js} +2 -2
  42. package/dist/{chunk-W4EJMMPP.js → chunk-4LVQSHHN.js} +11 -11
  43. package/dist/{chunk-W4Q65VJL.js → chunk-4X7HQKAG.js} +2 -2
  44. package/dist/{chunk-I74SUMNI.js → chunk-5ACIRCBO.js} +65 -3
  45. package/dist/chunk-5ACIRCBO.js.map +1 -0
  46. package/dist/{chunk-LPUEBFX2.js → chunk-5JCYPBY5.js} +2 -2
  47. package/dist/{chunk-ID65XTF3.js → chunk-5SOSQTVE.js} +2 -2
  48. package/dist/{chunk-32OTLNAU.js → chunk-5YIOUS5T.js} +203 -198
  49. package/dist/chunk-5YIOUS5T.js.map +1 -0
  50. package/dist/{chunk-SEIGLG62.js → chunk-6VFMEBXY.js} +4 -4
  51. package/dist/{chunk-333SBFXB.js → chunk-7AAMJQFW.js} +2 -2
  52. package/dist/{chunk-AHOYKJ5X.js → chunk-7SNEJNA3.js} +96 -23
  53. package/dist/chunk-7SNEJNA3.js.map +1 -0
  54. package/dist/{chunk-T3MCVSUC.js → chunk-A2XFG462.js} +2 -2
  55. package/dist/{chunk-HXFIILGF.js → chunk-BFPF5N3H.js} +4 -4
  56. package/dist/{chunk-GWY5ZFHP.js → chunk-BJOQQCYC.js} +5 -5
  57. package/dist/{chunk-7OYDFIL4.js → chunk-CY2C5LM4.js} +3 -3
  58. package/dist/{chunk-BFBS7OFQ.js → chunk-DC55RIEZ.js} +4 -4
  59. package/dist/{chunk-TGQW3AMK.js → chunk-DNXQVCIC.js} +3 -3
  60. package/dist/{chunk-TQ4CELUR.js → chunk-E53NLIAP.js} +3 -3
  61. package/dist/{chunk-2LA3H54D.js → chunk-E5IZTY4W.js} +2 -2
  62. package/dist/{chunk-PFR6ZKQI.js → chunk-EBI6FI5U.js} +6 -6
  63. package/dist/{chunk-JN7OSQJR.js → chunk-ETTV5F53.js} +2 -2
  64. package/dist/{chunk-FRYCXXTB.js → chunk-FSORYJRP.js} +3 -3
  65. package/dist/{chunk-K36RMINQ.js → chunk-GOZXQNIM.js} +3 -3
  66. package/dist/{chunk-H4IU24V5.js → chunk-GUF2JKG5.js} +2 -2
  67. package/dist/{chunk-XTRC6SSS.js → chunk-H6TCS5XX.js} +11 -8
  68. package/dist/chunk-H6TCS5XX.js.map +1 -0
  69. package/dist/{chunk-MTJFK42O.js → chunk-HHVK2JRE.js} +2 -2
  70. package/dist/{chunk-D5ZLTLHF.js → chunk-HR3DKJCU.js} +2 -2
  71. package/dist/{chunk-AUFPPBC3.js → chunk-IJKO5RVJ.js} +3 -3
  72. package/dist/{chunk-O3OEVYUR.js → chunk-IK7NPYYU.js} +2 -2
  73. package/dist/{chunk-ILNPU5W5.js → chunk-IMA4DJ7K.js} +5 -45
  74. package/dist/chunk-IMA4DJ7K.js.map +1 -0
  75. package/dist/{chunk-ACPFBVUD.js → chunk-JDH2BA2P.js} +2 -2
  76. package/dist/{chunk-VF6SC4OD.js → chunk-JNBSTHVT.js} +2 -2
  77. package/dist/chunk-JVVWCZ2P.js +18 -0
  78. package/dist/chunk-JVVWCZ2P.js.map +1 -0
  79. package/dist/{chunk-OBPOIZNR.js → chunk-KBHUGMUW.js} +2 -2
  80. package/dist/{chunk-M7CFCRWJ.js → chunk-KW4XA7GM.js} +3 -3
  81. package/dist/{chunk-B5KTTWC7.js → chunk-L5EE2CXU.js} +2 -2
  82. package/dist/{chunk-QNUNAXBE.js → chunk-L7LZDISF.js} +1 -9
  83. package/dist/{chunk-QNUNAXBE.js.map → chunk-L7LZDISF.js.map} +1 -1
  84. package/dist/{chunk-N3FRR6II.js → chunk-LAOJHOTG.js} +2 -2
  85. package/dist/{chunk-QPLI7LUU.js → chunk-LH57QATU.js} +2 -2
  86. package/dist/{chunk-JGGNUEVD.js → chunk-NDPS6OU2.js} +2 -2
  87. package/dist/{chunk-N7AIFTSH.js → chunk-NJG63FY2.js} +1 -1
  88. package/dist/{chunk-N7AIFTSH.js.map → chunk-NJG63FY2.js.map} +1 -1
  89. package/dist/{chunk-UPD5XDJX.js → chunk-NKAGGDSL.js} +4 -4
  90. package/dist/{chunk-G3RLCVJC.js → chunk-OGQL7QC7.js} +2 -2
  91. package/dist/{chunk-K3FH3LAQ.js → chunk-OJXK5C6Z.js} +4 -4
  92. package/dist/{chunk-HDLNSDLK.js → chunk-P3XO7HE3.js} +2 -2
  93. package/dist/{chunk-VMRPLHEU.js → chunk-PQIFYBUX.js} +2 -2
  94. package/dist/{chunk-WLT6LTQP.js → chunk-PRRWKTK6.js} +2 -2
  95. package/dist/{chunk-CX24SVLK.js → chunk-Q7OKGBZY.js} +2 -2
  96. package/dist/{chunk-BHRPZBAH.js → chunk-QJBULLKG.js} +3 -3
  97. package/dist/{chunk-WCJQ3OUP.js → chunk-QKAFFVSO.js} +2 -2
  98. package/dist/{chunk-VKXJQF5C.js → chunk-QKBFVLDH.js} +2 -2
  99. package/dist/{chunk-7FPI5MFB.js → chunk-QMFHKWHN.js} +5 -5
  100. package/dist/{chunk-I7WPLMUX.js → chunk-QRCE77YX.js} +2 -2
  101. package/dist/{chunk-K2DTHNDY.js → chunk-R2AJAAHJ.js} +4 -4
  102. package/dist/{chunk-5KDDAQ6K.js → chunk-R3UQIS3F.js} +6 -6
  103. package/dist/{chunk-B3M56D2A.js → chunk-RDHEBINJ.js} +2 -2
  104. package/dist/{chunk-3I3NXB6X.js → chunk-RHQL2RIM.js} +2 -2
  105. package/dist/{chunk-FMIM36I4.js → chunk-SA2YALFU.js} +2 -2
  106. package/dist/{chunk-DPL5VO5V.js → chunk-SAPC7N43.js} +3 -3
  107. package/dist/{chunk-ZA6CYFAK.js → chunk-SOQOUZ2Y.js} +2 -2
  108. package/dist/{chunk-VHXRLD6S.js → chunk-T2JZF45K.js} +2 -2
  109. package/dist/{chunk-63A2BU2B.js → chunk-T4MKFTJF.js} +2 -2
  110. package/dist/{chunk-E7ATID4Z.js → chunk-UFX24WNJ.js} +14 -14
  111. package/dist/{chunk-HQPFACXO.js → chunk-UH3FPX3L.js} +2 -2
  112. package/dist/{chunk-3LADDLAF.js → chunk-V5W67PQV.js} +4 -4
  113. package/dist/{chunk-PRC7SZYM.js → chunk-VAQIBC2L.js} +2 -2
  114. package/dist/{chunk-3Q3XD3NO.js → chunk-W2E2WFXL.js} +3 -3
  115. package/dist/{chunk-GF5NN3LE.js → chunk-W2UV6VE3.js} +2 -2
  116. package/dist/{chunk-SH3GOZWK.js → chunk-W35ICLYZ.js} +2 -2
  117. package/dist/{chunk-ALTLOHO7.js → chunk-WF2LYKOB.js} +2 -2
  118. package/dist/{chunk-FSXYBIEZ.js → chunk-X5MFCZDL.js} +72 -35
  119. package/dist/chunk-X5MFCZDL.js.map +1 -0
  120. package/dist/{chunk-FZVROZKC.js → chunk-XVZA6VXC.js} +4 -4
  121. package/dist/{chunk-IJVU4ILJ.js → chunk-XYNUEXLC.js} +4 -4
  122. package/dist/{chunk-RVAPK2S7.js → chunk-Y65XX5PC.js} +2 -2
  123. package/dist/{chunk-YWMCV5HL.js → chunk-YE77U5HZ.js} +3 -3
  124. package/dist/{chunk-VPEIWMUT.js → chunk-YLTU2DC4.js} +2 -2
  125. package/dist/{chunk-62YZOQFR.js → chunk-YRD525ZO.js} +2 -2
  126. package/dist/{chunk-TBBDFYXW.js → chunk-YVUNHNB6.js} +2 -3
  127. package/dist/chunk-YVUNHNB6.js.map +1 -0
  128. package/dist/{chunk-ITGAGNX5.js → chunk-YY5UXARJ.js} +24 -12
  129. package/dist/chunk-YY5UXARJ.js.map +1 -0
  130. package/dist/{chunk-U7KP6QFU.js → chunk-ZJ3CEAJD.js} +2 -2
  131. package/dist/{chunk-QC2MHZDD.js → chunk-ZOJUWVAU.js} +1 -1
  132. package/dist/{chunk-HH6PXQ2B.js → chunk-ZYP4YEEI.js} +2 -2
  133. package/dist/cli.js +124 -123
  134. package/dist/coding/export-okf-codegraph.js +21 -21
  135. package/dist/coding/pre-action-gate.js +2 -2
  136. package/dist/compounding/engine.js +14 -14
  137. package/dist/config-deprecations.d.ts +3 -0
  138. package/dist/config-deprecations.d.ts.map +1 -0
  139. package/dist/config-deprecations.js +9 -0
  140. package/dist/config.d.ts.map +1 -1
  141. package/dist/config.js +21 -20
  142. package/dist/connectors/codex-materialize-runner.js +13 -13
  143. package/dist/connectors/index.js +13 -13
  144. package/dist/convergence-refresh.js +16 -16
  145. package/dist/corpus-watermark.js +15 -15
  146. package/dist/deep-recall-http-glue.js +8 -8
  147. package/dist/deep-recall.js +2 -2
  148. package/dist/embedding-fallback.js +1 -1
  149. package/dist/entity-retrieval.js +14 -14
  150. package/dist/explicit-capture.js +124 -123
  151. package/dist/extraction-span-materialize.js +2 -2
  152. package/dist/extraction.js +22 -22
  153. package/dist/{first-start-migration-BPVJ4HJQ.js → first-start-migration-PPPP54X6.js} +5 -5
  154. package/dist/{graph-edge-decay-CXTNJ7IQ.js → graph-edge-decay-EKWXRBWF.js} +5 -5
  155. package/dist/graph-jsonl.js +3 -3
  156. package/dist/graph-snapshot.js +3 -3
  157. package/dist/graph.js +2 -2
  158. package/dist/harmonic-retrieval.js +13 -13
  159. package/dist/index.js +173 -171
  160. package/dist/lcm/engine.js +2 -2
  161. package/dist/lcm/index.js +4 -4
  162. package/dist/lifecycle.d.ts +0 -6
  163. package/dist/lifecycle.d.ts.map +1 -1
  164. package/dist/lifecycle.js +1 -1
  165. package/dist/location/index.js +25 -15
  166. package/dist/location/provider-setup.d.ts +26 -1
  167. package/dist/location/provider-setup.d.ts.map +1 -1
  168. package/dist/maintenance/memory-governance.js +14 -14
  169. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +13 -13
  170. package/dist/maintenance/rebuild-memory-projection-runner.js +16 -16
  171. package/dist/maintenance/rebuild-memory-projection.js +15 -15
  172. package/dist/memory-browse.js +6 -6
  173. package/dist/{migrate-from-identity-anchor-MJYB6NNN.js → migrate-from-identity-anchor-TZSZXJ6L.js} +2 -2
  174. package/dist/migrate-from-identity-anchor-TZSZXJ6L.js.map +1 -0
  175. package/dist/model-registry.d.ts +0 -5
  176. package/dist/model-registry.d.ts.map +1 -1
  177. package/dist/model-registry.js +1 -1
  178. package/dist/namespaces/migrate.js +14 -14
  179. package/dist/namespaces/search.js +6 -6
  180. package/dist/namespaces/storage.js +13 -13
  181. package/dist/offline-sync-changeset-generations.js +3 -3
  182. package/dist/offline-sync-embedding-generation.js +2 -2
  183. package/dist/offline-sync-snapshot-stream.js +5 -5
  184. package/dist/offline-sync.js +4 -4
  185. package/dist/operator-doctor-corpus.js +16 -16
  186. package/dist/operator-toolkit.js +32 -31
  187. package/dist/orchestration/backlog-scheduler.js +125 -124
  188. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  189. package/dist/orchestration/buffer-drain-runner.js +125 -124
  190. package/dist/orchestration/maintenance.js +22 -22
  191. package/dist/orchestration/semantic-consolidation-coordinator.d.ts.map +1 -1
  192. package/dist/orchestration/workspace-ops.d.ts.map +1 -1
  193. package/dist/orchestrator.js +124 -123
  194. package/dist/peers/index.d.ts +2 -1
  195. package/dist/peers/index.d.ts.map +1 -1
  196. package/dist/peers/index.js +3 -3
  197. package/dist/peers/interaction-log-append.d.ts +8 -0
  198. package/dist/peers/interaction-log-append.d.ts.map +1 -0
  199. package/dist/peers/storage.d.ts +22 -8
  200. package/dist/peers/storage.d.ts.map +1 -1
  201. package/dist/policy-runtime.js +2 -2
  202. package/dist/qmd.js +2 -2
  203. package/dist/recall-explain-renderer.js +3 -3
  204. package/dist/recall-navigate-access.js +2 -2
  205. package/dist/recall-navigate-disclosure.js +2 -2
  206. package/dist/recall-navigate.js +2 -2
  207. package/dist/recall-navigation.js +124 -123
  208. package/dist/recall-state-view-admission.js +6 -6
  209. package/dist/recall-why-service.js +6 -6
  210. package/dist/recall-xray-cli.js +4 -4
  211. package/dist/recall-xray-renderer.js +3 -3
  212. package/dist/recall-xray.js +2 -2
  213. package/dist/resume-bundles.js +22 -21
  214. package/dist/retrieval.js +2 -2
  215. package/dist/search/factory.js +5 -5
  216. package/dist/search/index.js +9 -9
  217. package/dist/semantic-consolidation.d.ts +10 -16
  218. package/dist/semantic-consolidation.d.ts.map +1 -1
  219. package/dist/semantic-consolidation.js +14 -14
  220. package/dist/semantic-rule-promotion.js +13 -13
  221. package/dist/semantic-rule-verifier.js +13 -13
  222. package/dist/source-agent-qualifier.js +17 -17
  223. package/dist/standup/build.js +13 -13
  224. package/dist/storage/links-frontmatter.d.ts +3 -0
  225. package/dist/storage/links-frontmatter.d.ts.map +1 -0
  226. package/dist/storage.d.ts.map +1 -1
  227. package/dist/storage.js +12 -12
  228. package/dist/summarizer.js +2 -2
  229. package/dist/tier-routing.js +2 -2
  230. package/dist/{tier-stats-FLFKN7Y6.js → tier-stats-XWJSVEHC.js} +5 -5
  231. package/dist/transfer/capsule-export.js +2 -2
  232. package/dist/transfer/capsule-import.js +2 -2
  233. package/dist/transfer/export-okf.js +13 -13
  234. package/dist/types.d.ts +1 -0
  235. package/dist/types.d.ts.map +1 -1
  236. package/dist/types.js +1 -1
  237. package/dist/utility-learner.js +2 -2
  238. package/dist/utility-runtime.js +3 -3
  239. package/dist/verified-recall.js +13 -13
  240. package/dist/who-knows-cli.js +14 -14
  241. package/dist/who-knows.js +13 -13
  242. package/package.json +2 -2
  243. package/src/access-recall-surface.ts +0 -2
  244. package/src/config-deprecations.ts +14 -0
  245. package/src/config.ts +2 -1
  246. package/src/lifecycle.ts +0 -8
  247. package/src/location/provider-setup.test.ts +273 -2
  248. package/src/location/provider-setup.ts +138 -32
  249. package/src/model-registry.ts +0 -11
  250. package/src/orchestration/semantic-consolidation-coordinator.ts +40 -33
  251. package/src/orchestration/semantic-consolidation-split.test.ts +72 -0
  252. package/src/orchestration/workspace-ops.test.ts +23 -0
  253. package/src/orchestration/workspace-ops.ts +6 -5
  254. package/src/peers/index.ts +1 -1
  255. package/src/peers/interaction-log-append.ts +132 -0
  256. package/src/peers/peers.test.ts +30 -0
  257. package/src/peers/profile-reasoner.ts +1 -1
  258. package/src/peers/storage.ts +4 -105
  259. package/src/semantic-consolidation.ts +35 -27
  260. package/src/storage/links-frontmatter.ts +69 -0
  261. package/src/storage-links-parse.test.ts +153 -0
  262. package/src/storage.ts +4 -18
  263. package/src/testing/subjects/dependency-propagation.test.ts +5 -4
  264. package/src/types.ts +1 -0
  265. package/dist/chunk-32OTLNAU.js.map +0 -1
  266. package/dist/chunk-AHOYKJ5X.js.map +0 -1
  267. package/dist/chunk-FSXYBIEZ.js.map +0 -1
  268. package/dist/chunk-I74SUMNI.js.map +0 -1
  269. package/dist/chunk-ILNPU5W5.js.map +0 -1
  270. package/dist/chunk-ITGAGNX5.js.map +0 -1
  271. package/dist/chunk-TBBDFYXW.js.map +0 -1
  272. package/dist/chunk-XTRC6SSS.js.map +0 -1
  273. /package/dist/{chunk-FHWX2REL.js.map → chunk-2OAFPBQB.js.map} +0 -0
  274. /package/dist/{chunk-5IZL4DCV.js.map → chunk-4DF5LMBJ.js.map} +0 -0
  275. /package/dist/{chunk-FWTGO4NE.js.map → chunk-4DLGKTM6.js.map} +0 -0
  276. /package/dist/{chunk-D6YCETHG.js.map → chunk-4E2Z44CV.js.map} +0 -0
  277. /package/dist/{chunk-W4EJMMPP.js.map → chunk-4LVQSHHN.js.map} +0 -0
  278. /package/dist/{chunk-W4Q65VJL.js.map → chunk-4X7HQKAG.js.map} +0 -0
  279. /package/dist/{chunk-LPUEBFX2.js.map → chunk-5JCYPBY5.js.map} +0 -0
  280. /package/dist/{chunk-ID65XTF3.js.map → chunk-5SOSQTVE.js.map} +0 -0
  281. /package/dist/{chunk-SEIGLG62.js.map → chunk-6VFMEBXY.js.map} +0 -0
  282. /package/dist/{chunk-333SBFXB.js.map → chunk-7AAMJQFW.js.map} +0 -0
  283. /package/dist/{chunk-T3MCVSUC.js.map → chunk-A2XFG462.js.map} +0 -0
  284. /package/dist/{chunk-HXFIILGF.js.map → chunk-BFPF5N3H.js.map} +0 -0
  285. /package/dist/{chunk-GWY5ZFHP.js.map → chunk-BJOQQCYC.js.map} +0 -0
  286. /package/dist/{chunk-7OYDFIL4.js.map → chunk-CY2C5LM4.js.map} +0 -0
  287. /package/dist/{chunk-BFBS7OFQ.js.map → chunk-DC55RIEZ.js.map} +0 -0
  288. /package/dist/{chunk-TGQW3AMK.js.map → chunk-DNXQVCIC.js.map} +0 -0
  289. /package/dist/{chunk-TQ4CELUR.js.map → chunk-E53NLIAP.js.map} +0 -0
  290. /package/dist/{chunk-2LA3H54D.js.map → chunk-E5IZTY4W.js.map} +0 -0
  291. /package/dist/{chunk-PFR6ZKQI.js.map → chunk-EBI6FI5U.js.map} +0 -0
  292. /package/dist/{chunk-JN7OSQJR.js.map → chunk-ETTV5F53.js.map} +0 -0
  293. /package/dist/{chunk-FRYCXXTB.js.map → chunk-FSORYJRP.js.map} +0 -0
  294. /package/dist/{chunk-K36RMINQ.js.map → chunk-GOZXQNIM.js.map} +0 -0
  295. /package/dist/{chunk-H4IU24V5.js.map → chunk-GUF2JKG5.js.map} +0 -0
  296. /package/dist/{chunk-MTJFK42O.js.map → chunk-HHVK2JRE.js.map} +0 -0
  297. /package/dist/{chunk-D5ZLTLHF.js.map → chunk-HR3DKJCU.js.map} +0 -0
  298. /package/dist/{chunk-AUFPPBC3.js.map → chunk-IJKO5RVJ.js.map} +0 -0
  299. /package/dist/{chunk-O3OEVYUR.js.map → chunk-IK7NPYYU.js.map} +0 -0
  300. /package/dist/{chunk-ACPFBVUD.js.map → chunk-JDH2BA2P.js.map} +0 -0
  301. /package/dist/{chunk-VF6SC4OD.js.map → chunk-JNBSTHVT.js.map} +0 -0
  302. /package/dist/{chunk-OBPOIZNR.js.map → chunk-KBHUGMUW.js.map} +0 -0
  303. /package/dist/{chunk-M7CFCRWJ.js.map → chunk-KW4XA7GM.js.map} +0 -0
  304. /package/dist/{chunk-B5KTTWC7.js.map → chunk-L5EE2CXU.js.map} +0 -0
  305. /package/dist/{chunk-N3FRR6II.js.map → chunk-LAOJHOTG.js.map} +0 -0
  306. /package/dist/{chunk-QPLI7LUU.js.map → chunk-LH57QATU.js.map} +0 -0
  307. /package/dist/{chunk-JGGNUEVD.js.map → chunk-NDPS6OU2.js.map} +0 -0
  308. /package/dist/{chunk-UPD5XDJX.js.map → chunk-NKAGGDSL.js.map} +0 -0
  309. /package/dist/{chunk-G3RLCVJC.js.map → chunk-OGQL7QC7.js.map} +0 -0
  310. /package/dist/{chunk-K3FH3LAQ.js.map → chunk-OJXK5C6Z.js.map} +0 -0
  311. /package/dist/{chunk-HDLNSDLK.js.map → chunk-P3XO7HE3.js.map} +0 -0
  312. /package/dist/{chunk-VMRPLHEU.js.map → chunk-PQIFYBUX.js.map} +0 -0
  313. /package/dist/{chunk-WLT6LTQP.js.map → chunk-PRRWKTK6.js.map} +0 -0
  314. /package/dist/{chunk-CX24SVLK.js.map → chunk-Q7OKGBZY.js.map} +0 -0
  315. /package/dist/{chunk-BHRPZBAH.js.map → chunk-QJBULLKG.js.map} +0 -0
  316. /package/dist/{chunk-WCJQ3OUP.js.map → chunk-QKAFFVSO.js.map} +0 -0
  317. /package/dist/{chunk-VKXJQF5C.js.map → chunk-QKBFVLDH.js.map} +0 -0
  318. /package/dist/{chunk-7FPI5MFB.js.map → chunk-QMFHKWHN.js.map} +0 -0
  319. /package/dist/{chunk-I7WPLMUX.js.map → chunk-QRCE77YX.js.map} +0 -0
  320. /package/dist/{chunk-K2DTHNDY.js.map → chunk-R2AJAAHJ.js.map} +0 -0
  321. /package/dist/{chunk-5KDDAQ6K.js.map → chunk-R3UQIS3F.js.map} +0 -0
  322. /package/dist/{chunk-B3M56D2A.js.map → chunk-RDHEBINJ.js.map} +0 -0
  323. /package/dist/{chunk-3I3NXB6X.js.map → chunk-RHQL2RIM.js.map} +0 -0
  324. /package/dist/{chunk-FMIM36I4.js.map → chunk-SA2YALFU.js.map} +0 -0
  325. /package/dist/{chunk-DPL5VO5V.js.map → chunk-SAPC7N43.js.map} +0 -0
  326. /package/dist/{chunk-ZA6CYFAK.js.map → chunk-SOQOUZ2Y.js.map} +0 -0
  327. /package/dist/{chunk-VHXRLD6S.js.map → chunk-T2JZF45K.js.map} +0 -0
  328. /package/dist/{chunk-63A2BU2B.js.map → chunk-T4MKFTJF.js.map} +0 -0
  329. /package/dist/{chunk-E7ATID4Z.js.map → chunk-UFX24WNJ.js.map} +0 -0
  330. /package/dist/{chunk-HQPFACXO.js.map → chunk-UH3FPX3L.js.map} +0 -0
  331. /package/dist/{chunk-3LADDLAF.js.map → chunk-V5W67PQV.js.map} +0 -0
  332. /package/dist/{chunk-PRC7SZYM.js.map → chunk-VAQIBC2L.js.map} +0 -0
  333. /package/dist/{chunk-3Q3XD3NO.js.map → chunk-W2E2WFXL.js.map} +0 -0
  334. /package/dist/{chunk-GF5NN3LE.js.map → chunk-W2UV6VE3.js.map} +0 -0
  335. /package/dist/{chunk-SH3GOZWK.js.map → chunk-W35ICLYZ.js.map} +0 -0
  336. /package/dist/{chunk-ALTLOHO7.js.map → chunk-WF2LYKOB.js.map} +0 -0
  337. /package/dist/{chunk-FZVROZKC.js.map → chunk-XVZA6VXC.js.map} +0 -0
  338. /package/dist/{chunk-IJVU4ILJ.js.map → chunk-XYNUEXLC.js.map} +0 -0
  339. /package/dist/{chunk-RVAPK2S7.js.map → chunk-Y65XX5PC.js.map} +0 -0
  340. /package/dist/{chunk-YWMCV5HL.js.map → chunk-YE77U5HZ.js.map} +0 -0
  341. /package/dist/{chunk-VPEIWMUT.js.map → chunk-YLTU2DC4.js.map} +0 -0
  342. /package/dist/{chunk-62YZOQFR.js.map → chunk-YRD525ZO.js.map} +0 -0
  343. /package/dist/{chunk-U7KP6QFU.js.map → chunk-ZJ3CEAJD.js.map} +0 -0
  344. /package/dist/{chunk-QC2MHZDD.js.map → chunk-ZOJUWVAU.js.map} +0 -0
  345. /package/dist/{chunk-HH6PXQ2B.js.map → chunk-ZYP4YEEI.js.map} +0 -0
  346. /package/dist/{graph-edge-decay-CXTNJ7IQ.js.map → config-deprecations.js.map} +0 -0
  347. /package/dist/{first-start-migration-BPVJ4HJQ.js.map → first-start-migration-PPPP54X6.js.map} +0 -0
  348. /package/dist/{migrate-from-identity-anchor-MJYB6NNN.js.map → graph-edge-decay-EKWXRBWF.js.map} +0 -0
  349. /package/dist/{tier-stats-FLFKN7Y6.js.map → tier-stats-XWJSVEHC.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/peers/profile-reasoner.ts"],"sourcesContent":["/**\n * Peer profile reasoner — issue #679 PR 2/5.\n *\n * Pure async function that, for each peer:\n *\n * 1. Reads recent interaction-log entries via `readPeerInteractionLog`.\n * 2. Calls an injected LLM client (same chat shape as\n * `FallbackLlmClient.chatCompletion`) to derive 0..N profile-field\n * proposals with provenance `{observedAt, signal, sourceSessionId,\n * note}`.\n * 3. Merges the proposals into the peer's existing `PeerProfile`,\n * appending provenance entries (never replacing existing\n * provenance — the reasoner is additive by design so the operator\n * retains the full audit trail).\n * 4. Writes via `writePeerProfile`.\n *\n * Gating is handled in two layers:\n *\n * - The orchestrator wires the call behind the\n * `peerProfileReasonerEnabled` config flag (default `false` —\n * opt-in per Gotcha #30/#48). The reasoner ALSO short-circuits\n * when `options.enabled !== true`, so direct callers can't\n * accidentally bypass the flag.\n * - Per-peer, the `peerProfileReasonerMinInteractions` threshold\n * skips peers whose log has fewer entries since the last reasoner\n * run than required.\n *\n * The reasoner is intentionally storage-agnostic — it accepts an LLM\n * client by interface (`PeerProfileReasonerLlm`) so tests can mock the\n * call and the orchestrator can inject either the gateway client or\n * a fast local model. No direct OpenAI imports here.\n */\n\nimport {\n appendInteractionLog,\n listPeers,\n readPeerInteractionLog,\n readPeerProfile,\n writePeerProfile,\n} from \"./storage.js\";\nimport type {\n Peer,\n PeerInteractionLogEntry,\n PeerProfile,\n PeerProfileFieldProvenance,\n} from \"./types.js\";\nimport { PEER_ID_PATTERN } from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────\n// Types\n// ──────────────────────────────────────────────────────────────────────\n\n/**\n * Minimal chat-completion contract the reasoner depends on. Matches\n * `FallbackLlmClient.chatCompletion` so the orchestrator can pass it\n * through directly. Tests inject a mock that returns canned strings.\n *\n * Returning `null` means the LLM is unavailable / failed — the\n * reasoner treats that as \"no proposals for this peer\" rather than an\n * error so a flaky LLM never aborts the whole pass.\n */\nexport interface PeerProfileReasonerLlm {\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: { temperature?: number; maxTokens?: number; timeoutMs?: number },\n ): Promise<{ content: string } | null>;\n}\n\n/**\n * One LLM-proposed profile-field update.\n *\n * `value` is the new markdown string to set under `field`. The\n * provenance entry the LLM emits travels alongside it; the reasoner\n * does NOT trust the LLM's `observedAt` — it always overwrites with\n * the run's `now` timestamp so provenance can never claim future or\n * past observation timestamps the operator didn't witness.\n */\nexport interface PeerProfileReasonerProposal {\n /** Stable section key, e.g. \"communication_style\". */\n readonly field: string;\n /** Markdown value to set under that key. */\n readonly value: string;\n /**\n * Short label for the signal that justified the inference,\n * e.g. \"explicit_preference\", \"tool_pattern\", \"topic_recurrence\".\n */\n readonly signal: string;\n /** Optional free-form note explaining the inference. */\n readonly note?: string;\n /**\n * Originating session id, when the LLM can attribute the inference\n * to a specific log line. Reasoner clamps this to a value that\n * actually appeared in the log window so the LLM can't hallucinate.\n */\n readonly sourceSessionId?: string;\n}\n\nexport interface PeerProfileReasonerOptions {\n /** Memory directory containing the peers/ subtree. */\n readonly memoryDir: string;\n /**\n * Master gate. When `false` (the default the orchestrator passes\n * when the config flag is off), the reasoner is a no-op and\n * returns an empty result. Direct callers must explicitly pass\n * `true` so the gate can never be defaulted ON by accident\n * (Gotcha #48 — least-privileged default).\n */\n readonly enabled: boolean;\n /** Injected LLM client. Required when `enabled === true`. */\n readonly llm?: PeerProfileReasonerLlm;\n /** Model name to log for telemetry; not used to dispatch. */\n readonly model?: string;\n /**\n * Minimum new interaction-log entries since last reasoner run\n * before this peer is processed. Peers below the threshold are\n * skipped with `reason: \"below_min_interactions\"`.\n */\n readonly minInteractions: number;\n /**\n * Hard cap on profile fields the reasoner will accept across all\n * peers in a single run. Tracked in insertion order: once the cap\n * is reached, subsequent proposals are dropped with\n * `dropped_due_to_cap` in the per-peer result. Use to bound LLM\n * cost and reviewer load per pass.\n */\n readonly maxFieldsPerRun: number;\n /**\n * Optional restriction to specific peer ids. When omitted, the\n * reasoner enumerates the entire peer registry via `listPeers`.\n */\n readonly peerIds?: ReadonlyArray<string>;\n /**\n * Maximum number of recent log entries to feed the LLM per peer.\n * Defaults to 50. Bounded so a runaway log can't blow the prompt.\n */\n readonly maxLogEntriesPerPeer?: number;\n /**\n * Reasoner run timestamp. Defaults to `new Date()` at call time.\n * Tests inject a deterministic clock; the orchestrator passes\n * `new Date()` so provenance entries reflect actual wall time.\n */\n readonly now?: Date;\n /**\n * Optional logger; defaults to a no-op so the reasoner stays\n * silent in unit tests. The orchestrator wires its `log` here so\n * runs surface in the gateway log under the\n * `[peer-profile-reasoner]` prefix.\n */\n readonly log?: {\n debug?: (msg: string) => void;\n info?: (msg: string) => void;\n warn?: (msg: string) => void;\n };\n /**\n * Whether to append a `peer_profile_reasoner_run` entry to the\n * peer's interaction log when the reasoner emits at least one\n * field for that peer. Defaults to `true`. Disable in tests that\n * want to assert the log was untouched.\n */\n readonly appendRunMarkerToLog?: boolean;\n /**\n * Optional abort signal. The reasoner checks between peers and\n * returns the partial result if cancelled mid-run.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface PeerProfileReasonerPeerResult {\n readonly peerId: string;\n readonly status:\n | \"processed\"\n | \"skipped_below_min_interactions\"\n | \"skipped_no_log\"\n | \"skipped_disabled\"\n | \"skipped_no_llm\"\n | \"skipped_llm_unavailable\"\n | \"skipped_invalid_proposal\"\n | \"skipped_cap_reached\"\n | \"skipped_aborted\"\n | \"error\";\n /** Number of fields actually applied to the peer's profile. */\n readonly fieldsApplied: number;\n /** Number of proposals dropped because the per-run cap was hit. */\n readonly droppedDueToCap: number;\n /** Set of field keys applied; useful for tests and telemetry. */\n readonly fields: ReadonlyArray<string>;\n /** Error message, when `status === \"error\"`. */\n readonly error?: string;\n}\n\nexport interface PeerProfileReasonerResult {\n readonly peersConsidered: number;\n readonly peersProcessed: number;\n readonly fieldsApplied: number;\n readonly perPeer: ReadonlyArray<PeerProfileReasonerPeerResult>;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Prompt + parser (pure, exported for tests)\n// ──────────────────────────────────────────────────────────────────────\n\n/**\n * Build the user-facing reasoner prompt. The system message carries\n * the strict-JSON instruction; this function emits the user message\n * with the peer context and the recent log slice.\n *\n * The prompt is intentionally schema-prescriptive — sibling modules\n * (`semantic-consolidation.ts`, `extraction-judge.ts`) demonstrated\n * that letting the LLM improvise field names produces unstable\n * profiles across runs.\n */\nexport function buildPeerProfileReasonerPrompt(input: {\n peer: Peer;\n existingProfile: PeerProfile | null;\n log: ReadonlyArray<PeerInteractionLogEntry>;\n maxFields: number;\n}): string {\n const existingFields = input.existingProfile\n ? Object.keys(input.existingProfile.fields)\n : [];\n const logBlock = input.log\n .map((e) => {\n const session = e.sessionId ? ` session=${e.sessionId}` : \"\";\n return `- [${e.timestamp}] (${e.kind})${session} ${e.summary}`;\n })\n .join(\"\\n\");\n return [\n `You are an async peer-profile reasoner. Your job is to read recent interaction-log entries for one peer and propose 0..${input.maxFields} profile-field updates.`,\n \"\",\n `Peer:`,\n ` id: ${input.peer.id}`,\n ` kind: ${input.peer.kind}`,\n ` displayName: ${input.peer.displayName}`,\n \"\",\n `Existing profile field keys (preserve names when proposing updates that refine an existing field): ${existingFields.length > 0 ? existingFields.join(\", \") : \"(none yet)\"}`,\n \"\",\n `Recent interaction log (oldest first):`,\n logBlock.length > 0 ? logBlock : \"(no entries)\",\n \"\",\n `Output a single JSON object: {\"proposals\": [{\"field\": \"<stable_key>\", \"value\": \"<markdown>\", \"signal\": \"<short_label>\", \"note\": \"<optional>\", \"sourceSessionId\": \"<optional>\"}]}.`,\n \"\",\n `Rules:`,\n `1. Only propose fields supported by evidence in the log. Do not invent.`,\n `2. Keys are short snake_case (e.g. \"communication_style\", \"tool_patterns\").`,\n `3. value is markdown. signal is a short label like \"explicit_preference\" or \"topic_recurrence\".`,\n `4. Omit fields you can't justify. Empty proposals array is valid.`,\n `5. Output JSON ONLY — no prose before or after.`,\n ].join(\"\\n\");\n}\n\n/**\n * Parse the LLM response. Tolerates a fenced code block wrapper.\n * Returns an empty array on any malformed payload — the contract is\n * that flaky LLM output silently produces zero proposals rather than\n * surfacing an error to the caller.\n *\n * Exported so unit tests can verify parser behavior without spinning\n * up the full reasoner.\n */\nexport function parsePeerProfileReasonerResponse(\n raw: string,\n): PeerProfileReasonerProposal[] {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return [];\n const trimmed = raw.trim();\n // Dropped the \\s* groups around the lazy body (they overlapped it and\n // backtracked polynomially — CodeQL js/polynomial-redos). Input is already\n // trimmed and fenced[1] is trimmed below, so matches are identical.\n const fenced = /^```(?:json)?([\\s\\S]*?)```$/u.exec(trimmed);\n const payload = fenced ? fenced[1].trim() : trimmed;\n let parsed: unknown;\n try {\n parsed = JSON.parse(payload);\n } catch {\n return [];\n }\n // Gotcha #18: JSON.parse('null') succeeds. Reject non-objects.\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return [];\n }\n const obj = parsed as { proposals?: unknown };\n if (!Array.isArray(obj.proposals)) return [];\n const out: PeerProfileReasonerProposal[] = [];\n // Gotcha — drop prototype-pollution keys at the field-name layer.\n const RESERVED_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n for (const item of obj.proposals) {\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) continue;\n const r = item as Record<string, unknown>;\n if (typeof r.field !== \"string\" || r.field.trim() === \"\") continue;\n if (RESERVED_KEYS.has(r.field)) continue;\n if (typeof r.value !== \"string\" || r.value.trim() === \"\") continue;\n if (typeof r.signal !== \"string\" || r.signal.trim() === \"\") continue;\n const proposal: PeerProfileReasonerProposal = {\n field: r.field,\n value: r.value,\n signal: r.signal,\n ...(typeof r.note === \"string\" && r.note.length > 0 ? { note: r.note } : {}),\n ...(typeof r.sourceSessionId === \"string\" && r.sourceSessionId.length > 0\n ? { sourceSessionId: r.sourceSessionId }\n : {}),\n };\n out.push(proposal);\n }\n return out;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Reasoner core\n// ──────────────────────────────────────────────────────────────────────\n\nconst SYSTEM_MESSAGE =\n 'You are a peer-profile reasoner. Output ONLY a JSON object of the form {\"proposals\":[{\"field\":\"...\",\"value\":\"...\",\"signal\":\"...\",\"note\":\"...\",\"sourceSessionId\":\"...\"}]}. No prose, no fenced code block, no commentary.';\n\nconst RUN_MARKER_KIND = \"peer_profile_reasoner_run\";\n\n/**\n * Find the most recent reasoner-run marker timestamp in the log.\n * Used to count \"interactions since last run\" so the threshold\n * gate doesn't keep firing on the same dormant log forever.\n */\nfunction lastRunTimestamp(\n log: ReadonlyArray<PeerInteractionLogEntry>,\n): string | undefined {\n let latest: string | undefined;\n for (const entry of log) {\n if (entry.kind !== RUN_MARKER_KIND) continue;\n if (latest === undefined || entry.timestamp > latest) {\n latest = entry.timestamp;\n }\n }\n return latest;\n}\n\nfunction noopLogger(): NonNullable<PeerProfileReasonerOptions[\"log\"]> {\n return { debug: () => {}, info: () => {}, warn: () => {} };\n}\n\n/**\n * Run the reasoner across all (or the requested subset of) peers.\n *\n * Always returns a `PeerProfileReasonerResult` — never throws to the\n * caller — so the orchestrator can wire it as a best-effort\n * post-consolidation hook (Gotcha #13).\n */\nexport async function runPeerProfileReasoner(\n options: PeerProfileReasonerOptions,\n): Promise<PeerProfileReasonerResult> {\n const log = {\n debug: options.log?.debug ?? noopLogger().debug!,\n info: options.log?.info ?? noopLogger().info!,\n warn: options.log?.warn ?? noopLogger().warn!,\n };\n const result: {\n peersConsidered: number;\n peersProcessed: number;\n fieldsApplied: number;\n perPeer: PeerProfileReasonerPeerResult[];\n } = {\n peersConsidered: 0,\n peersProcessed: 0,\n fieldsApplied: 0,\n perPeer: [],\n };\n // Disabled flag is the master gate. Defaults to false in callers'\n // config; we additionally require strict `=== true` here so a\n // stray \"true\" string doesn't silently flip the flag (Gotcha #36).\n if (options.enabled !== true) {\n log.debug(\"[peer-profile-reasoner] disabled — no-op\");\n return result;\n }\n if (!options.llm) {\n log.warn(\"[peer-profile-reasoner] no LLM client supplied — skipping run\");\n return result;\n }\n const minInteractions = Number.isFinite(options.minInteractions)\n ? Math.max(0, Math.floor(options.minInteractions))\n : 0;\n const maxFields = Number.isFinite(options.maxFieldsPerRun)\n ? Math.max(0, Math.floor(options.maxFieldsPerRun))\n : 0;\n if (maxFields === 0) {\n log.debug(\"[peer-profile-reasoner] maxFieldsPerRun=0 — no-op\");\n return result;\n }\n const maxLogPerPeer = Number.isFinite(options.maxLogEntriesPerPeer ?? NaN)\n ? Math.max(1, Math.floor(options.maxLogEntriesPerPeer as number))\n : 50;\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n\n let peers: Peer[];\n try {\n if (options.peerIds && options.peerIds.length > 0) {\n // Filter the explicit list against on-disk peers so we never\n // act on an id the operator typed but didn't register.\n const all = await listPeers(options.memoryDir);\n const wanted = new Set(\n options.peerIds.filter(\n (id) => typeof id === \"string\" && PEER_ID_PATTERN.test(id),\n ),\n );\n peers = all.filter((p) => wanted.has(p.id));\n } else {\n peers = await listPeers(options.memoryDir);\n }\n } catch (err) {\n log.warn(\n `[peer-profile-reasoner] listPeers failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return result;\n }\n result.peersConsidered = peers.length;\n let fieldsAppliedTotal = 0;\n\n for (const peer of peers) {\n if (options.signal?.aborted) {\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_aborted\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n try {\n // Codex P2 review on PR #736: the min-interactions threshold\n // must reflect the FULL log of new activity, not the\n // `maxLogPerPeer`-truncated slice. Otherwise a peer with a\n // genuinely active conversation history can be permanently\n // marked `skipped_below_min_interactions` whenever\n // `peerProfileReasonerMinInteractions > maxLogEntriesPerPeer`,\n // because the slice will never include enough new entries.\n // Read the full log first to compute the gate, then truncate\n // for prompt construction below.\n const fullLog = await readPeerInteractionLog(\n options.memoryDir,\n peer.id,\n );\n if (fullLog.length === 0) {\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_no_log\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n // Count interactions since the last reasoner-run marker, so\n // dormant peers don't trigger another LLM call until enough\n // new signal accumulates. Run markers themselves don't count.\n const lastRun = lastRunTimestamp(fullLog);\n const sinceLastRunFull = lastRun\n ? fullLog.filter(\n (e) => e.timestamp > lastRun && e.kind !== RUN_MARKER_KIND,\n )\n : fullLog.filter((e) => e.kind !== RUN_MARKER_KIND);\n if (sinceLastRunFull.length < minInteractions) {\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_below_min_interactions\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n // Truncate ONLY for prompt construction so the LLM context\n // stays bounded. Use the most recent `maxLogPerPeer` entries\n // from the full since-last-run set so the prompt prefers fresh\n // signal over older entries.\n const sinceLastRun =\n sinceLastRunFull.length > maxLogPerPeer\n ? sinceLastRunFull.slice(sinceLastRunFull.length - maxLogPerPeer)\n : sinceLastRunFull;\n\n const existingProfile = await readPeerProfile(options.memoryDir, peer.id);\n\n const remainingBudget = maxFields - fieldsAppliedTotal;\n if (remainingBudget <= 0) {\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_cap_reached\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n\n const prompt = buildPeerProfileReasonerPrompt({\n peer,\n existingProfile,\n log: sinceLastRun,\n maxFields: remainingBudget,\n });\n const messages = [\n { role: \"system\" as const, content: SYSTEM_MESSAGE },\n { role: \"user\" as const, content: prompt },\n ];\n let response: { content: string } | null;\n try {\n response = await options.llm.chatCompletion(messages, {\n temperature: 0.2,\n maxTokens: 1500,\n });\n } catch (err) {\n log.warn(\n `[peer-profile-reasoner] LLM call failed for \"${peer.id}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_llm_unavailable\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n if (!response || typeof response.content !== \"string\") {\n result.perPeer.push({\n peerId: peer.id,\n status: \"skipped_llm_unavailable\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n\n const proposals = parsePeerProfileReasonerResponse(response.content);\n if (proposals.length === 0) {\n result.perPeer.push({\n peerId: peer.id,\n status: \"processed\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n });\n continue;\n }\n\n // Build the merged profile. We never replace existing\n // provenance entries — provenance is append-only so the\n // operator retains a full audit trail.\n const sessionIdsInWindow = new Set(\n sinceLastRun\n .map((e) => e.sessionId)\n .filter((s): s is string => typeof s === \"string\" && s.length > 0),\n );\n const baseFields: Record<string, string> = existingProfile\n ? { ...existingProfile.fields }\n : {};\n const baseProvenance: Record<string, PeerProfileFieldProvenance[]> = {};\n if (existingProfile) {\n for (const [k, list] of Object.entries(existingProfile.provenance)) {\n baseProvenance[k] = [...list];\n }\n }\n\n // Codex P1 review on PR #736: the global `fieldsAppliedTotal`\n // counter must NOT be incremented until the profile write\n // actually succeeds. Otherwise a transient I/O error here\n // poisons the per-run cap for every subsequent peer — they get\n // marked `skipped_cap_reached` for fields that were never\n // persisted. Track the candidate count locally and only\n // commit it to the run-wide budget after `writePeerProfile`\n // returns successfully (Gotcha #25 — don't destroy old state\n // before confirming new state succeeds).\n const appliedFieldsForPeer: string[] = [];\n let droppedDueToCap = 0;\n let invalidProposalSeen = false;\n for (const proposal of proposals) {\n // Use a candidate-budget projection so we never propose more\n // than the run-wide cap allows even before we know the write\n // will succeed.\n const candidateBudget =\n maxFields - fieldsAppliedTotal - appliedFieldsForPeer.length;\n if (candidateBudget <= 0) {\n droppedDueToCap += 1;\n continue;\n }\n // Final defensive guard against prototype keys (parser\n // already drops them, but be redundant for safety).\n if (\n proposal.field === \"__proto__\" ||\n proposal.field === \"constructor\" ||\n proposal.field === \"prototype\"\n ) {\n invalidProposalSeen = true;\n continue;\n }\n // Sanity-check field key matches a conservative pattern so a\n // hostile LLM can't sneak path-traversal-shaped keys through\n // for downstream consumers.\n if (!/^[a-zA-Z][a-zA-Z0-9_]{0,63}$/.test(proposal.field)) {\n invalidProposalSeen = true;\n continue;\n }\n baseFields[proposal.field] = proposal.value;\n const sourceSessionId =\n proposal.sourceSessionId &&\n sessionIdsInWindow.has(proposal.sourceSessionId)\n ? proposal.sourceSessionId\n : undefined;\n const provEntry: PeerProfileFieldProvenance = {\n observedAt: nowIso,\n signal: proposal.signal,\n ...(sourceSessionId ? { sourceSessionId } : {}),\n ...(proposal.note && proposal.note.length > 0\n ? { note: proposal.note }\n : {}),\n };\n const list = baseProvenance[proposal.field] ?? [];\n list.push(provEntry);\n baseProvenance[proposal.field] = list;\n appliedFieldsForPeer.push(proposal.field);\n // NOTE: fieldsAppliedTotal is NOT incremented here — see the\n // P1 comment above. We commit the budget after the write\n // succeeds.\n }\n\n if (appliedFieldsForPeer.length === 0) {\n result.perPeer.push({\n peerId: peer.id,\n status: invalidProposalSeen\n ? \"skipped_invalid_proposal\"\n : droppedDueToCap > 0\n ? \"skipped_cap_reached\"\n : \"processed\",\n fieldsApplied: 0,\n droppedDueToCap,\n fields: [],\n });\n continue;\n }\n\n const merged: PeerProfile = {\n peerId: peer.id,\n updatedAt: nowIso,\n fields: baseFields,\n provenance: baseProvenance,\n };\n await writePeerProfile(options.memoryDir, merged);\n // Write succeeded — NOW commit the budget. A throw above\n // bubbles to the outer catch, where the peer is recorded as\n // `error` and the global cap remains intact for subsequent\n // peers (Codex P1 fix on PR #736).\n fieldsAppliedTotal += appliedFieldsForPeer.length;\n\n // Append a run marker so the next reasoner pass can compute\n // \"interactions since last run\" without a dedicated state\n // file. The marker is best-effort — a write failure here\n // logs but does not roll back the profile (the operator\n // would prefer a slightly noisy threshold over a lost\n // profile update).\n const wantsMarker = options.appendRunMarkerToLog ?? true;\n if (wantsMarker) {\n try {\n await appendInteractionLog(options.memoryDir, peer.id, {\n timestamp: nowIso,\n kind: RUN_MARKER_KIND,\n summary: `applied ${appliedFieldsForPeer.length} field(s) via ${options.model ?? \"unknown-model\"}`,\n });\n } catch (err) {\n log.warn(\n `[peer-profile-reasoner] run-marker append failed for \"${peer.id}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n result.perPeer.push({\n peerId: peer.id,\n status: \"processed\",\n fieldsApplied: appliedFieldsForPeer.length,\n droppedDueToCap,\n fields: appliedFieldsForPeer,\n });\n result.peersProcessed += 1;\n result.fieldsApplied = fieldsAppliedTotal;\n } catch (err) {\n log.warn(\n `[peer-profile-reasoner] error processing peer \"${peer.id}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n result.perPeer.push({\n peerId: peer.id,\n status: \"error\",\n fieldsApplied: 0,\n droppedDueToCap: 0,\n fields: [],\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;AAmNO,SAAS,+BAA+B,OAKpC;AACT,QAAM,iBAAiB,MAAM,kBACzB,OAAO,KAAK,MAAM,gBAAgB,MAAM,IACxC,CAAC;AACL,QAAM,WAAW,MAAM,IACpB,IAAI,CAAC,MAAM;AACV,UAAM,UAAU,EAAE,YAAY,YAAY,EAAE,SAAS,KAAK;AAC1D,WAAO,MAAM,EAAE,SAAS,MAAM,EAAE,IAAI,IAAI,OAAO,IAAI,EAAE,OAAO;AAAA,EAC9D,CAAC,EACA,KAAK,IAAI;AACZ,SAAO;AAAA,IACL,0HAA0H,MAAM,SAAS;AAAA,IACzI;AAAA,IACA;AAAA,IACA,SAAS,MAAM,KAAK,EA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b,WAAW;AAAA,QACX,QAAQ;AAAA,QACR,YAAY;AAAA,MACd;AACA,YAAM,iBAAiB,QAAQ,WAAW,MAAM;AAKhD,4BAAsB,qBAAqB;AAQ3C,YAAM,cAAc,QAAQ,wBAAwB;AACpD,UAAI,aAAa;AACf,YAAI;AACF,gBAAM,qBAAqB,QAAQ,WAAW,KAAK,IAAI;AAAA,YACrD,WAAW;AAAA,YACX,MAAM;AAAA,YACN,SAAS,WAAW,qBAAqB,MAAM,iBAAiB,QAAQ,SAAS,eAAe;AAAA,UAClG,CAAC;AAAA,QACH,SAAS,KAAK;AACZ,cAAI;AAAA,YACF,yDAAyD,KAAK,EAAE,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,UACxH;AAAA,QACF;AAAA,MACF;AAEA,aAAO,QAAQ,KAAK;AAAA,QAClB,QAAQ,KAAK;AAAA,QACb,QAAQ;AAAA,QACR,eAAe,qBAAqB;AAAA,QACpC;AAAA,QACA,QAAQ;AAAA,MACV,CAAC;AACD,aAAO,kBAAkB;AACzB,aAAO,gBAAgB;AAAA,IACzB,SAAS,KAAK;AACZ,UAAI;AAAA,QACF,kDAAkD,KAAK,EAAE,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,MACjH;AACA,aAAO,QAAQ,KAAK;AAAA,QAClB,QAAQ,KAAK;AAAA,QACb,QAAQ;AAAA,QACR,eAAe;AAAA,QACf,iBAAiB;AAAA,QACjB,QAAQ,CAAC;AAAA,QACT,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/peers/migrate-from-identity-anchor.ts","../src/peers/storage.ts","../src/peers/types.ts"],"sourcesContent":["/**\n * Identity-anchor → peer-registry migration — issue #679 PR 5/5.\n *\n * Reads the legacy `identity/identity-anchor.md` file (written by\n * `StorageManager.writeIdentityAnchor`) and the `IDENTITY.md`\n * reflections file, then seeds the peer registry with a `self` peer\n * whose `peers/self/identity.md` kernel captures the relevant\n * source material.\n *\n * Design principles:\n *\n * 1. **Idempotent** — if `peers/self/identity.md` already exists this\n * function returns `{ skipped: true }` without overwriting it. The\n * second-run guarantee prevents accidental double-migration and\n * makes `remnic peer migrate` safe to run in CI / post-install hooks.\n *\n * 2. **Non-destructive** — the legacy files are never deleted. The\n * operator is responsible for archive / clean-up after verifying the\n * migration result. Legacy `engram.identity_anchor_*` MCP tools\n * continue to work against the on-disk anchor file.\n *\n * 3. **Dry-run** — when `options.dryRun` is `true` the function\n * computes the proposed `Peer` record and returns it alongside a\n * `{ dryRun: true }` marker, without writing anything to disk.\n *\n * 4. **Transparent** — the return value always includes the full\n * proposed `Peer` so callers can print what was (or would be) written.\n *\n * ## Source data\n *\n * The migrator reads two optional legacy sources:\n *\n * - `{memoryDir}/identity/identity-anchor.md` — structured sections\n * (`## Identity Traits`, `## Communication Preferences`, etc.) written\n * by `identityAnchorUpdate`. When present, the full content is\n * embedded in `peer.notes` under a clearly labelled subsection.\n *\n * - `{memoryDir}/IDENTITY.md` — free-form reflection entries appended\n * by the extraction engine. When present it is summarised as\n * a second subsection of `peer.notes`.\n *\n * If neither file exists the `self` peer is still created with sensible\n * defaults so that the peer registry is bootstrapped for fresh installs.\n *\n * ## Path safety\n *\n * All file reads use `path.join` relative to the caller-supplied\n * `memoryDir`. The migration never follows symlinks for the source files\n * (uses `lstat` to detect + skip them). Writes go through the standard\n * peer storage helpers which enforce path-traversal and symlink guards.\n */\n\nimport { promises as fs, constants as fsConstants } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { readPeer, writePeerIfAbsent } from \"./storage.js\";\nimport type { Peer } from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Public types\n// ──────────────────────────────────────────────────────────────────────────────\n\n/** Options for `migrateFromIdentityAnchor`. */\nexport interface MigrateFromIdentityAnchorOptions {\n /**\n * Memory directory (same value as `config.memoryDir`). All source and\n * destination paths are resolved relative to this root.\n */\n memoryDir: string;\n\n /**\n * When `true`, compute and return the proposed peer record without\n * writing anything to disk. The `written` and `skipped` flags in the\n * result will both be `false`; the `peer` field carries the proposed\n * record.\n */\n dryRun?: boolean;\n\n /**\n * Optional override for the `self` peer's display name. Defaults to\n * `\"Self\"`.\n */\n displayName?: string;\n\n /**\n * Optional ISO-8601 timestamp to use as `createdAt`. When omitted the\n * current time is used.\n */\n createdAt?: string;\n}\n\n/** Result returned by `migrateFromIdentityAnchor`. */\nexport interface MigrateFromIdentityAnchorResult {\n /**\n * The peer record that was (or would be) written for `peers/self/`.\n * Always present regardless of `skipped` or `dryRun`.\n */\n peer: Peer;\n\n /**\n * `true` when the migration wrote `peers/self/identity.md` to disk.\n * `false` when `dryRun` is set or the file already existed (`skipped`).\n */\n written: boolean;\n\n /**\n * `true` when an existing `peers/self/identity.md` was detected and\n * the migration was a no-op. When `skipped` is `true`, `written` is\n * always `false`.\n */\n skipped: boolean;\n\n /**\n * `true` when `options.dryRun` was set. No files were written; the\n * `peer` field holds the proposed record.\n */\n dryRun: boolean;\n\n /**\n * The identity-anchor source file path that was read (if found).\n * `null` when the file did not exist or was a symlink (skipped).\n */\n identityAnchorSource: string | null;\n\n /**\n * The `IDENTITY.md` source file path that was read (if found).\n * `null` when the file did not exist or was a symlink (skipped).\n */\n identityMdSource: string | null;\n}\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read a legacy source file with the same security posture as the peer storage\n * module:\n *\n * 1. **Parent-directory symlink rejection** — lstat the parent directory and\n * return null if it is a symlink. This closes the case where e.g.\n * `memoryDir/identity/` is itself a symlink pointing outside `memoryDir`.\n *\n * 2. **Kernel-level O_NOFOLLOW** — open the file with `O_NOFOLLOW` so the\n * kernel atomically rejects a symlink at the final path component. This\n * eliminates the TOCTOU race between a separate lstat check and the\n * subsequent read that `safeReadLegacyFile` previously had.\n *\n * Returns `{ content, filePath }` on success, or `{ content: null, filePath: null }`\n * when the file is missing, is a symlink, the parent is a symlink, or the\n * path is not a regular file. Re-throws unexpected I/O errors (EACCES, EIO,\n * etc.) so the caller can surface real filesystem problems.\n */\nasync function safeReadLegacyFile(\n filePath: string,\n): Promise<{ content: string; filePath: string } | { content: null; filePath: null }> {\n // 1. Reject a symlinked parent directory.\n const parent = path.dirname(filePath);\n try {\n const parentStat = await fs.lstat(parent);\n if (parentStat.isSymbolicLink()) {\n return { content: null, filePath: null };\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { content: null, filePath: null };\n }\n throw err;\n }\n\n // 2. Open with O_NOFOLLOW so the kernel refuses a symlink at the target\n // path, atomically closing the lstat-then-read TOCTOU window.\n let fh: import(\"node:fs/promises\").FileHandle;\n try {\n fh = await fs.open(filePath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT — file does not exist; ELOOP — O_NOFOLLOW detected a symlink.\n if (code === \"ENOENT\" || code === \"ELOOP\" || code === \"ENOTDIR\") {\n return { content: null, filePath: null };\n }\n throw err;\n }\n\n try {\n // Verify it is a regular file (not a directory, FIFO, device, etc.).\n const stat = await fh.stat();\n if (!stat.isFile()) {\n return { content: null, filePath: null };\n }\n const content = await fh.readFile(\"utf8\");\n return { content, filePath };\n } finally {\n await fh.close();\n }\n}\n\n/**\n * Build the `notes` markdown body for the `self` peer from the two\n * optional legacy sources.\n *\n * The resulting notes are kept intentionally terse — the peer kernel is\n * meant to hold stable identity facts, not a full dump of every reflection\n * entry. We label the sections clearly so operators know exactly what came\n * from where.\n */\nfunction buildSelfNotes(\n anchorContent: string | null,\n identityMdContent: string | null,\n): string | undefined {\n const parts: string[] = [];\n\n if (anchorContent !== null && anchorContent.trim().length > 0) {\n parts.push(\n \"## Migrated from identity-anchor.md\\n\\n\" + anchorContent.trim(),\n );\n }\n\n if (identityMdContent !== null && identityMdContent.trim().length > 0) {\n // IDENTITY.md can be quite long. Embed it as a labelled section so the\n // operator can prune it manually after migration rather than losing data.\n parts.push(\n \"## Migrated from IDENTITY.md\\n\\n\" + identityMdContent.trim(),\n );\n }\n\n if (parts.length === 0) return undefined;\n return parts.join(\"\\n\\n\");\n}\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Public API\n// ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * Migrate legacy identity-anchor data into `peers/self/identity.md`.\n *\n * @see {@link MigrateFromIdentityAnchorOptions} for full option documentation.\n * @see {@link MigrateFromIdentityAnchorResult} for return value semantics.\n */\nexport async function migrateFromIdentityAnchor(\n options: MigrateFromIdentityAnchorOptions,\n): Promise<MigrateFromIdentityAnchorResult> {\n const { memoryDir, dryRun = false } = options;\n const now = new Date().toISOString();\n const createdAt = options.createdAt ?? now;\n const displayName = options.displayName ?? \"Self\";\n\n // 1. Guard: if peers/self/identity.md already exists, skip.\n // We read through the standard `readPeer` helper (which enforces all\n // path-traversal guards) rather than stat-ing the file directly.\n const existing = await readPeer(memoryDir, \"self\");\n if (existing !== null) {\n return {\n peer: existing,\n written: false,\n skipped: true,\n // P2 (codex): preserve the caller-requested dryRun flag even on the\n // skip path. Previously hard-coded `false`, which contradicted the\n // MigrateFromIdentityAnchorResult contract for dry-run callers.\n dryRun,\n identityAnchorSource: null,\n identityMdSource: null,\n };\n }\n\n // 2. Read legacy sources (both optional; symlinks are silently skipped).\n const anchorPath = path.join(memoryDir, \"identity\", \"identity-anchor.md\");\n const identityMdPath = path.join(memoryDir, \"IDENTITY.md\");\n\n const [anchorResult, identityMdResult] = await Promise.all([\n safeReadLegacyFile(anchorPath),\n safeReadLegacyFile(identityMdPath),\n ]);\n\n // 3. Compose the self peer record.\n const notes = buildSelfNotes(\n anchorResult.content,\n identityMdResult.content,\n );\n\n const peer: Peer = {\n id: \"self\",\n kind: \"self\",\n displayName,\n createdAt,\n updatedAt: now,\n ...(notes !== undefined ? { notes } : {}),\n };\n\n // 4. Write (unless dry-run). Use the peer storage create-if-absent helper so\n // migration gets the same root, peer-directory, parent-inode, and O_NOFOLLOW\n // guards as writePeer while preserving the non-overwrite migration contract.\n if (!dryRun) {\n const created = await writePeerIfAbsent(memoryDir, peer);\n if (!created) {\n const raceWinner = await readPeer(memoryDir, \"self\");\n return {\n peer: raceWinner ?? peer,\n written: false,\n skipped: true,\n dryRun,\n identityAnchorSource: null,\n identityMdSource: null,\n };\n }\n }\n\n return {\n peer,\n written: !dryRun,\n skipped: false,\n dryRun,\n identityAnchorSource: anchorResult.filePath,\n identityMdSource: identityMdResult.filePath,\n };\n}\n","/**\n * Peer registry storage primitives — issue #679 PR 1/5.\n *\n * Pure file-I/O helpers for the per-peer kernel files:\n *\n * peers/{peer-id}/identity.md — slow, human-edited identity facts\n * peers/{peer-id}/profile.md — evolving profile (reasoner-owned)\n * peers/{peer-id}/interactions.log.md — append-only signal log\n *\n * No reasoner logic, no recall integration, no migration of existing\n * identity-anchor data — those land in PR 2/5 — 5/5.\n *\n * Path safety: `peerId` is validated against PEER_ID_PATTERN before any\n * filesystem operation. Reading a non-existent peer returns null (does not\n * throw). Reading malformed files throws — callers can catch and recover.\n */\n\nimport { promises as fs, constants as fsConstants } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Atomic, symlink-rejecting open: returns a file handle whose\n * underlying open(2) call carried `O_NOFOLLOW`, so the kernel itself\n * refuses to follow a symlink at the target path. Closes the\n * check-then-use TOCTOU race that a separate `assertPathNotSymlink`\n * + `fs.writeFile` pattern leaves open (codex P1 round 5 on PR #723).\n */\nasync function openNoFollow(file: string, flags: number): Promise<import(\"node:fs/promises\").FileHandle> {\n return fs.open(file, flags | fsConstants.O_NOFOLLOW);\n}\n\n/** Read a file, refusing to follow symlinks at the kernel level\n * AND verifying parent-dir inode stability (codex P1 round 9). */\nasync function readFileNoFollow(file: string): Promise<string> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(file, fsConstants.O_RDONLY);\n try {\n return await fh.readFile(\"utf8\");\n } finally {\n await fh.close();\n }\n}\n\n/**\n * Codex P1 round 9: O_NOFOLLOW only protects the FINAL path\n * component, so a parent-directory swap mid-flight (peers/<id>\n * unlinked + replaced with a symlink between assertPeerDirNotEscaped\n * and the open) could still write outside memoryDir. Without\n * `openat` (Node has no stable JS binding for it), the best\n * pure-Node mitigation is to:\n * 1. Open the parent directory with O_DIRECTORY | O_NOFOLLOW so\n * WE hold the original-inode handle.\n * 2. fstat the parent handle and compare its (dev, inode) against\n * lstat of the parent path. If they diverge, a swap happened\n * between mkdir and now — abort.\n * 3. Then do the symlink-rejecting open of the file.\n * This narrows the race window to the few microseconds between the\n * fstat/lstat compare and the open. Fully closing the race needs\n * `openat`, which is tracked as a follow-up.\n */\nasync function assertParentDirInodeStable(filePath: string): Promise<void> {\n const parent = path.dirname(filePath);\n const dh = await fs.open(\n parent,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n try {\n const fstatInfo = await dh.stat();\n const lstatInfo = await fs.lstat(parent);\n if (fstatInfo.ino !== lstatInfo.ino || fstatInfo.dev !== lstatInfo.dev) {\n throw new Error(\n `parent directory \"${parent}\" was swapped between checks (inode mismatch)`,\n );\n }\n if (lstatInfo.isSymbolicLink()) {\n throw new Error(`parent directory \"${parent}\" is a symlink and is rejected`);\n }\n } finally {\n await dh.close();\n }\n}\n\n/** Overwrite a file, refusing to follow symlinks at the kernel level\n * AND verifying the parent directory inode is stable across the open\n * (codex P1 round 9). */\nasync function writeFileNoFollow(file: string, data: string): Promise<void> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(\n file,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC,\n );\n try {\n await fh.writeFile(data, \"utf8\");\n } finally {\n await fh.close();\n }\n}\n\n/**\n * Create a file only when absent, refusing symlinks and non-regular existing\n * targets. Returns false only for an existing regular file.\n */\nasync function writeFileNoFollowIfAbsent(file: string, data: string): Promise<boolean> {\n await assertParentDirInodeStable(file);\n let fh: import(\"node:fs/promises\").FileHandle;\n try {\n fh = await openNoFollow(\n file,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL,\n );\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw err;\n }\n const existing = await fs.lstat(file);\n if (existing.isSymbolicLink()) {\n throw new Error(`refusing to create \"${file}\": target is a symlink`);\n }\n if (!existing.isFile()) {\n throw new Error(`refusing to create \"${file}\": target is not a regular file`);\n }\n return false;\n }\n try {\n await fh.writeFile(data, \"utf8\");\n } finally {\n await fh.close();\n }\n return true;\n}\n\n/** Append to a file, refusing to follow symlinks AND verifying parent\n * inode stability (codex P1 round 9). */\nasync function appendFileNoFollow(file: string, data: string): Promise<void> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(\n file,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND,\n );\n try {\n await fh.writeFile(data, \"utf8\");\n } finally {\n await fh.close();\n }\n}\n\nimport {\n PEER_ID_MAX_LENGTH,\n PEER_ID_PATTERN,\n type Peer,\n type PeerInteractionLogEntry,\n type PeerKind,\n type PeerProfile,\n type PeerProfileFieldProvenance,\n} from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────\n// Validation\n// ──────────────────────────────────────────────────────────────────────\n\nconst ALLOWED_KINDS: ReadonlySet<PeerKind> = new Set<PeerKind>([\n \"self\",\n \"human\",\n \"agent\",\n \"integration\",\n]);\n\n/**\n * Validate a peer id. Throws `Error` with a descriptive message on failure.\n * Exported so callers can pre-check user input before constructing a Peer.\n */\nexport function assertValidPeerId(peerId: unknown): asserts peerId is string {\n if (typeof peerId !== \"string\") {\n throw new Error(\"peerId must be a string\");\n }\n if (peerId.length === 0) {\n throw new Error(\"peerId must not be empty\");\n }\n if (peerId.length > PEER_ID_MAX_LENGTH) {\n throw new Error(`peerId must be ≤ ${PEER_ID_MAX_LENGTH} characters`);\n }\n if (!PEER_ID_PATTERN.test(peerId)) {\n throw new Error(\n `peerId \"${peerId}\" is invalid — must match ${PEER_ID_PATTERN}`,\n );\n }\n // Defence-in-depth: reject consecutive dots/dashes/underscores. The\n // regex already prevents leading/trailing separators, but explicit\n // adjacency checks document intent and survive future regex refactors.\n if (/[.\\-_]{2,}/.test(peerId)) {\n throw new Error(\n `peerId \"${peerId}\" is invalid — must not contain consecutive separators`,\n );\n }\n}\n\n/**\n * Strict plain-object check. Rejects arrays, null, Maps, Sets, class\n * instances, and anything else with a non-Object/null prototype.\n * Codex P2 round 13: writePeerProfile previously treated any\n * non-null non-array object as plain; inputs like `new Map()` would\n * pass and serialize to `{}` losing all data.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction assertValidKind(kind: unknown): asserts kind is PeerKind {\n if (typeof kind !== \"string\" || !ALLOWED_KINDS.has(kind as PeerKind)) {\n throw new Error(\n `peer kind must be one of ${Array.from(ALLOWED_KINDS).join(\", \")}`,\n );\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Path helpers\n// ──────────────────────────────────────────────────────────────────────\n\n/** Root directory holding the peer registry, relative to memoryDir. */\nexport const PEERS_DIR_NAME = \"peers\";\n\nfunction peersRoot(memoryDir: string): string {\n return path.join(memoryDir, PEERS_DIR_NAME);\n}\n\nfunction peerDir(memoryDir: string, peerId: string): string {\n // Guard against path traversal on top of regex validation. After\n // assertValidPeerId, peerId cannot contain `/`, `..`, or NUL — but we\n // re-check defensively here.\n assertValidPeerId(peerId);\n const candidate = path.join(peersRoot(memoryDir), peerId);\n const root = peersRoot(memoryDir);\n // Ensure resolved path stays within peersRoot. Note: this is a\n // lexical check only — a symlinked peer directory can still escape.\n // I/O sites must additionally call `assertPeerDirNotEscaped` (below)\n // before reading or writing, which uses lstat to reject symlinks\n // and realpath to confirm physical containment (codex P1 #723).\n const relative = path.relative(root, candidate);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`peerId \"${peerId}\" resolves outside peers root`);\n }\n return candidate;\n}\n\n/**\n * Reject the peers root if it is itself a symlink. Called BEFORE any\n * `fs.mkdir`, so a `peers → /tmp/outside` symlink can't get its\n * target mutated by a recursive mkdir before subsequent checks fire\n * (codex P2 + cursor M on PR #723).\n */\nasync function assertPeersRootNotSymlink(memoryDir: string): Promise<void> {\n const root = peersRoot(memoryDir);\n let rootStat: import(\"node:fs\").Stats | null = null;\n try {\n rootStat = await fs.lstat(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n if (rootStat && rootStat.isSymbolicLink()) {\n throw new Error(`peers root \"${root}\" is a symlink and is rejected`);\n }\n}\n\n/**\n * Codex P1 round 13: atomic mkdir of the peer directory under a\n * verified peers root. Opens the peers root with O_DIRECTORY|\n * O_NOFOLLOW first (creating it if missing under the same flags) so\n * a root-symlink swap can't redirect the subsequent mkdir to its\n * target. The dir handle is held across the mkdir, then we lstat\n * the candidate and reject if it's a symlink.\n */\nasync function mkdirPeerDirAtomic(memoryDir: string, peerId: string): Promise<void> {\n const root = peersRoot(memoryDir);\n // Ensure the root exists as a real directory, not a symlink. Use\n // mkdir + lstat: if mkdir succeeds (or EEXIST), lstat must report\n // a directory and not a symlink.\n await fs.mkdir(memoryDir, { recursive: true });\n try {\n await fs.mkdir(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n const rootLstat = await fs.lstat(root);\n if (rootLstat.isSymbolicLink()) {\n throw new Error(`peers root \"${root}\" is a symlink and is rejected`);\n }\n if (!rootLstat.isDirectory()) {\n throw new Error(`peers root \"${root}\" exists but is not a directory`);\n }\n // Open the root with O_DIRECTORY|O_NOFOLLOW to anchor the inode.\n // Hold the handle across the peer-dir mkdir so a root swap\n // mid-operation is detected via fstat-vs-lstat compare afterward.\n const rootHandle = await fs.open(\n root,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n try {\n const candidate = peerDir(memoryDir, peerId);\n await fs.mkdir(candidate, { recursive: true });\n // Verify root inode unchanged across the mkdir.\n const fstatRoot = await rootHandle.stat();\n const lstatRoot = await fs.lstat(root);\n if (fstatRoot.ino !== lstatRoot.ino || fstatRoot.dev !== lstatRoot.dev) {\n throw new Error(`peers root \"${root}\" was swapped during mkdir`);\n }\n // Reject symlinked peer dir.\n const peerLstat = await fs.lstat(candidate);\n if (peerLstat.isSymbolicLink()) {\n throw new Error(`peer directory \"${peerId}\" is a symlink and is rejected`);\n }\n } finally {\n await rootHandle.close();\n }\n}\n\n/**\n * Codex P1 on PR #723: `peerDir` only enforces a lexical\n * `path.relative` check, so a symlinked peer directory like\n * `peers/self → /tmp/outside` would slip through. Run this guard\n * AFTER the peer directory has been (or is known to) exist, so we\n * can lstat it and realpath-check containment. For first-time writes,\n * call `mkdirPeerDirAtomic` BEFORE this; for reads, this alone.\n */\nasync function assertPeerDirNotEscaped(memoryDir: string, peerId: string): Promise<void> {\n const candidate = peerDir(memoryDir, peerId);\n const root = peersRoot(memoryDir);\n // 1. The peers root must not be a symlink (defensive — writers\n // already checked this before mkdir, but reads must still verify).\n await assertPeersRootNotSymlink(memoryDir);\n // 2. lstat on the candidate itself. If it's a symlink, refuse.\n let candidateStat: import(\"node:fs\").Stats | null = null;\n try {\n candidateStat = await fs.lstat(candidate);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n if (candidateStat && candidateStat.isSymbolicLink()) {\n throw new Error(`peer directory \"${peerId}\" is a symlink and is rejected`);\n }\n // 3. Real-path containment. Only meaningful if the candidate exists.\n if (candidateStat) {\n const realRoot = await fs.realpath(root);\n const realCandidate = await fs.realpath(candidate);\n const rel = path.relative(realRoot, realCandidate);\n if (rel === \"\" || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n throw new Error(`peer directory \"${peerId}\" escapes the peers root`);\n }\n }\n}\n\nfunction identityPath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"identity.md\");\n}\n\nfunction profilePath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"profile.md\");\n}\n\nfunction interactionsPath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"interactions.log.md\");\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Minimal YAML helpers (peer files only)\n// ──────────────────────────────────────────────────────────────────────\n//\n// We deliberately do not depend on the codebase's primary YAML parser\n// (`storage.ts`) because the peer schema is small and structured. We emit\n// a strict, predictable subset:\n//\n// ---\n// id: my-peer\n// kind: agent\n// displayName: \"Codex\"\n// createdAt: 2026-04-25T00:00:00.000Z\n// updatedAt: 2026-04-25T00:00:00.000Z\n// ---\n// {free-form markdown notes}\n//\n// String values are always double-quoted with `\\\\` and `\\\"` escapes. ISO\n// timestamps and the kind enum are emitted bare. This keeps round-trip\n// behaviour deterministic and easy to validate.\n\nfunction escapeYamlString(value: string): string {\n // Cursor Medium: must escape newlines / carriage returns / tabs so a\n // value like `displayName: \"first\\nsecond\"` doesn't blow up the\n // line-oriented parsePeerFrontmatter. Backslash → `\\\\`, double-quote\n // → `\\\"`, newline → `\\n`, carriage return → `\\r`, tab → `\\t`.\n return `\"${value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\")}\"`;\n}\n\nfunction unescapeYamlString(quoted: string): string {\n // Caller has already verified `quoted` starts and ends with a double quote.\n const body = quoted.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === \"\\\\\" && i + 1 < body.length) {\n const next = body[i + 1];\n if (next === \"\\\\\" || next === '\"') {\n out += next;\n i++;\n continue;\n }\n if (next === \"n\") {\n out += \"\\n\";\n i++;\n continue;\n }\n if (next === \"r\") {\n out += \"\\r\";\n i++;\n continue;\n }\n if (next === \"t\") {\n out += \"\\t\";\n i++;\n continue;\n }\n }\n out += ch;\n }\n return out;\n}\n\ninterface ParsedFrontmatter {\n fields: Record<string, string>;\n body: string;\n}\n\nfunction parsePeerFrontmatter(raw: string): ParsedFrontmatter {\n // Frontmatter must begin with a `---` line. We tolerate a leading BOM\n // and trailing newlines but otherwise require a strict, line-oriented\n // YAML subset of `key: value` pairs.\n const text = raw.replace(/^\\uFEFF/, \"\");\n if (!text.startsWith(\"---\")) {\n throw new Error(\"peer file is missing YAML frontmatter delimiter\");\n }\n // Split on the first occurrence of `\\n---` after the leading `---`.\n const after = text.slice(3);\n const close = after.indexOf(\"\\n---\");\n if (close === -1) {\n throw new Error(\"peer file frontmatter is not terminated\");\n }\n const fmBlock = after.slice(0, close).replace(/^\\n/, \"\");\n const body = after.slice(close + 4).replace(/^\\n/, \"\");\n const fields: Record<string, string> = {};\n for (const lineRaw of fmBlock.split(\"\\n\")) {\n const line = lineRaw.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n throw new Error(`peer frontmatter line is malformed: ${line}`);\n }\n const key = line.slice(0, colon).trim();\n const valueRaw = line.slice(colon + 1).trim();\n if (key === \"\") {\n throw new Error(`peer frontmatter has empty key: ${line}`);\n }\n let value: string;\n if (valueRaw.startsWith('\"') && valueRaw.endsWith('\"') && valueRaw.length >= 2) {\n value = unescapeYamlString(valueRaw);\n } else {\n value = valueRaw;\n }\n fields[key] = value;\n }\n return { fields, body };\n}\n\nfunction emitPeerIdentity(peer: Peer): string {\n const lines: string[] = [\"---\"];\n lines.push(`id: ${escapeYamlString(peer.id)}`);\n lines.push(`kind: ${peer.kind}`);\n lines.push(`displayName: ${escapeYamlString(peer.displayName)}`);\n // Cursor M: emit timestamps as quoted YAML strings — bare emission\n // would let a `createdAt` value containing a newline inject extra\n // frontmatter fields when round-tripped through `parsePeerFrontmatter`.\n // (`writePeer` validates these are non-empty strings, but the type\n // doesn't constrain content.)\n lines.push(`createdAt: ${escapeYamlString(peer.createdAt)}`);\n lines.push(`updatedAt: ${escapeYamlString(peer.updatedAt)}`);\n lines.push(\"---\");\n lines.push(\"\");\n lines.push(peer.notes ?? \"\");\n // Trailing newline for POSIX friendliness.\n // CodeQL: the previous `replace(/\\n+$/, \"\\n\")` flagged as\n // polynomial-regex risk because `\\n+` can backtrack on long\n // trailing-newline runs. Strip trailing newlines with a bounded\n // loop instead — O(N) over the trailing-newline count, no regex.\n let out = lines.join(\"\\n\");\n while (out.endsWith(\"\\n\")) out = out.slice(0, -1);\n return out + \"\\n\";\n}\n\nfunction assertWritablePeer(peer: Peer): void {\n assertValidPeerId(peer.id);\n assertValidKind(peer.kind);\n if (typeof peer.displayName !== \"string\") {\n throw new Error(\"peer.displayName must be a string\");\n }\n if (typeof peer.createdAt !== \"string\" || peer.createdAt === \"\") {\n throw new Error(\"peer.createdAt must be a non-empty ISO-8601 string\");\n }\n if (typeof peer.updatedAt !== \"string\" || peer.updatedAt === \"\") {\n throw new Error(\"peer.updatedAt must be a non-empty ISO-8601 string\");\n }\n // Codex P2 round 8: reject non-string `peer.notes`. Without this,\n // an untyped JS caller passing an object/number would silently\n // coerce to \"[object Object]\"/\"42\" via lines.push(notes ?? \"\")\n // and corrupt user-authored identity content. Notes are optional;\n // omit by passing undefined (NOT null).\n if (peer.notes !== undefined && typeof peer.notes !== \"string\") {\n throw new Error(\"peer.notes must be a string when provided\");\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Public storage API\n// ──────────────────────────────────────────────────────────────────────\n\n/**\n * Read a peer's identity kernel.\n *\n * Returns `null` (does not throw) when the peer directory or identity\n * file does not exist. Throws on filesystem errors other than ENOENT and\n * on malformed files.\n */\nexport async function readPeer(\n memoryDir: string,\n peerId: string,\n): Promise<Peer | null> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = identityPath(memoryDir, peerId);\n // Codex P1 #2: even with the directory validated, a symlinked\n // identity.md inside a real peer dir would let us read arbitrary\n // out-of-scope files. Reject symlinks at the file level too.\n let raw: string;\n try {\n raw = await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n const { fields, body } = parsePeerFrontmatter(raw);\n const id = fields.id ?? peerId;\n if (id !== peerId) {\n throw new Error(\n `peer identity file mismatch — expected id \"${peerId}\", file claims \"${id}\"`,\n );\n }\n const kind = fields.kind;\n assertValidKind(kind);\n const displayName = fields.displayName ?? \"\";\n const createdAt = fields.createdAt ?? \"\";\n if (createdAt === \"\") {\n throw new Error(`peer \"${peerId}\" is missing createdAt`);\n }\n // Codex P2: nullish-coalescing alone treated `updatedAt: \"\"` as a\n // valid empty timestamp, contradicting writePeer's non-empty\n // validation and the module's \"malformed files throw\" contract.\n // Treat empty string as missing and fall back to createdAt; throw\n // only when the field is malformed in some other way (caught by\n // the typeof check).\n const rawUpdatedAt = fields.updatedAt;\n const updatedAt =\n typeof rawUpdatedAt === \"string\" && rawUpdatedAt.length > 0\n ? rawUpdatedAt\n : createdAt;\n // Codex P2 + CodeQL: previously used `body.replace(/^\\s+/, \"\")`\n // which stripped ALL leading whitespace — including indentation in\n // notes. The `\\s+` patterns also flagged as polynomial-regex risk\n // (CodeQL alert #74) because they can backtrack on adversarial\n // inputs. Strip exactly one leading separator newline and one\n // trailing newline — internal AND user-authored leading\n // indentation are preserved verbatim, and the regex is bounded.\n let trimmedBody = body;\n if (trimmedBody.startsWith(\"\\r\\n\")) trimmedBody = trimmedBody.slice(2);\n else if (trimmedBody.startsWith(\"\\n\")) trimmedBody = trimmedBody.slice(1);\n if (trimmedBody.endsWith(\"\\r\\n\")) trimmedBody = trimmedBody.slice(0, -2);\n else if (trimmedBody.endsWith(\"\\n\")) trimmedBody = trimmedBody.slice(0, -1);\n return {\n id: peerId,\n kind,\n displayName,\n createdAt,\n updatedAt,\n notes: trimmedBody === \"\" ? undefined : trimmedBody,\n };\n}\n\n/**\n * Write (create or overwrite) a peer's identity kernel.\n *\n * Creates `peers/{id}/` if it does not exist. Does not touch the peer's\n * profile or interaction log. Atomic-write semantics are deferred to\n * later PRs — for the schema slice we simply write the file.\n */\nexport async function writePeer(memoryDir: string, peer: Peer): Promise<void> {\n assertWritablePeer(peer);\n // Codex P1 round 13: atomic root validation. Open the peers root\n // (or its parent if peers doesn't exist yet) with O_DIRECTORY|\n // O_NOFOLLOW BEFORE the mkdir. This holds a kernel handle on the\n // original-inode root, so a swap between the symlink check and\n // the mkdir can't redirect mkdir to a symlink-target. We then\n // mkdir, lstat the result against the held handle, and only\n // proceed if they match.\n await mkdirPeerDirAtomic(memoryDir, peer.id);\n await assertPeerDirNotEscaped(memoryDir, peer.id);\n const file = identityPath(memoryDir, peer.id);\n // Codex P1 #2: reject if identity.md exists as a symlink so we\n // don't follow it on overwrite.\n await writeFileNoFollow(file, emitPeerIdentity(peer));\n}\n\n/**\n * Create a peer identity only if it is absent, applying the same root,\n * peer-directory, parent-inode, and O_NOFOLLOW guards as writePeer.\n *\n * Returns true when this call created the identity file and false when a\n * regular identity file already existed. Symlinked roots, peer directories,\n * identity paths, and non-regular identity paths are rejected.\n */\nexport async function writePeerIfAbsent(\n memoryDir: string,\n peer: Peer,\n): Promise<boolean> {\n assertWritablePeer(peer);\n await mkdirPeerDirAtomic(memoryDir, peer.id);\n await assertPeerDirNotEscaped(memoryDir, peer.id);\n const file = identityPath(memoryDir, peer.id);\n return await writeFileNoFollowIfAbsent(file, emitPeerIdentity(peer));\n}\n\n/**\n * Delete a peer's `identity.md` if present, applying the same symlink\n * and path-escape protections as the read/write paths.\n *\n * Returns `true` if a regular file was unlinked, `false` if no\n * `identity.md` existed at the time of the call. The peer directory\n * itself is left in place so any companion files (`profile.md`,\n * `interactions/`, etc.) are untouched. Idempotent: missing target\n * returns `false` rather than throwing.\n *\n * Cursor M (PR #756 review): a manual `path.join` + raw `fs.unlink`\n * bypasses `assertPeerDirNotEscaped`, the peers-root symlink check,\n * and the parent-inode-stable / lstat guards used by every other\n * peer I/O entrypoint. A symlinked `peers/<id>/` could redirect the\n * unlink to an arbitrary `identity.md` outside `memoryDir`. This\n * function consolidates the safe-delete contract so callers cannot\n * skip the guards.\n */\nexport async function deletePeer(memoryDir: string, peerId: string): Promise<boolean> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = identityPath(memoryDir, peerId);\n // Refuse to follow a symlink at `identity.md` itself: lstat first\n // and reject if the target is a symlink. Then verify the parent\n // directory inode is stable across the unlink (mirrors the\n // assertParentDirInodeStable + O_NOFOLLOW pattern used by\n // writeFileNoFollow). This narrows the TOCTOU window between the\n // lstat and the unlink to the same few microseconds the write path\n // accepts.\n let lstatBefore: import(\"node:fs\").Stats;\n try {\n lstatBefore = await fs.lstat(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n if (lstatBefore.isSymbolicLink()) {\n throw new Error(`refusing to unlink \"${file}\": target is a symlink`);\n }\n if (!lstatBefore.isFile()) {\n throw new Error(`refusing to unlink \"${file}\": target is not a regular file`);\n }\n await assertParentDirInodeStable(file);\n try {\n await fs.unlink(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n return true;\n}\n\n/**\n * Destructively purge the entire peer directory for a given peerId —\n * `identity.md`, `profile.md`, `interactions.log.md`, and any other\n * files written by future extensions.\n *\n * This is the DESTRUCTIVE counterpart to `deletePeer` (which only\n * removes `identity.md`). Callers must pass `confirm: \"yes\"` to prevent\n * accidental data loss — the function throws `Error(\"forgetPeer requires\n * confirm: 'yes'\")` when the flag is absent or wrong.\n *\n * Idempotent: if the peer directory does not exist the function returns\n * `{ purged: false }` rather than throwing. Safe to run twice.\n *\n * Security contract (mirrors `deletePeer`):\n * - `peerId` is validated against `PEER_ID_PATTERN`.\n * - The peers root is checked for symlink swap (assertPeersRootNotSymlink).\n * - `assertPeerDirNotEscaped` performs realpath containment: symlinked\n * peer directories are rejected and the resolved path is confirmed to\n * stay inside peersRoot (same guard used by every other I/O entry-point).\n * - A secondary `lstat` + `isSymbolicLink()` check is kept as defence-in-\n * depth before the `fs.rm` call itself.\n * - `fs.rm` with `{ recursive: true, force: true }` is used for the\n * actual removal so partially-populated directories are handled\n * atomically by the OS rather than file-by-file in userland.\n *\n * Returns:\n * `{ purged: true }` — directory existed and was removed.\n * `{ purged: false }` — directory did not exist (no-op).\n */\nexport async function forgetPeer(\n memoryDir: string,\n peerId: string,\n opts: { confirm: string },\n): Promise<{ purged: boolean }> {\n if (opts.confirm !== \"yes\") {\n throw new Error(\"forgetPeer requires confirm: 'yes'\");\n }\n assertValidPeerId(peerId);\n await assertPeersRootNotSymlink(memoryDir);\n // assertPeerDirNotEscaped performs the realpath-containment check that\n // the lexical `peerDir()` guard alone cannot provide: it lstat-checks\n // the candidate, rejects symlinks, and confirms the resolved path stays\n // inside peersRoot. Mirrors the contract of every other I/O entry-point\n // in this module (`readPeer`, `writePeer`, `deletePeer`,\n // `appendInteractionLog`, `readPeerProfile`, `writePeerProfile`).\n // The function handles ENOENT gracefully (returns without throwing), so\n // calling it here is safe for the idempotent no-op path as well.\n await assertPeerDirNotEscaped(memoryDir, peerId);\n\n const dir = peerDir(memoryDir, peerId);\n\n // lstat the candidate directory. Return early (idempotent) if it\n // doesn't exist. Reject if it resolves to a symlink.\n let dirStat: import(\"node:fs\").Stats;\n try {\n dirStat = await fs.lstat(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { purged: false };\n }\n throw err;\n }\n if (dirStat.isSymbolicLink()) {\n throw new Error(\n `refusing to purge peer directory \"${peerId}\": target is a symlink`,\n );\n }\n if (!dirStat.isDirectory()) {\n throw new Error(\n `refusing to purge peer directory \"${peerId}\": target is not a directory`,\n );\n }\n\n // Perform the recursive removal. `fs.rm` with `{ recursive: true }`\n // is the correct API (replaces the deprecated `fs.rmdir`). The\n // `force: true` flag makes it a no-op if the directory was already\n // removed between our lstat and this call (race-safe idempotency).\n await fs.rm(dir, { recursive: true, force: true });\n return { purged: true };\n}\n\n/**\n * Enumerate all peers under `memoryDir/peers/`.\n *\n * Returns an empty array if the peers root does not exist. Subdirectories\n * whose name fails `PEER_ID_PATTERN` are skipped (defensive: the user\n * may have hand-edited the directory). Directories that exist but lack\n * `identity.md` are also skipped.\n */\nexport async function listPeers(memoryDir: string): Promise<Peer[]> {\n // Codex P2 round 13: atomic readdir against the root. Open the\n // peers directory with O_DIRECTORY|O_NOFOLLOW first so we hold the\n // original-inode handle, then readdir from that handle. A\n // root-symlink swap between assertPeersRootNotSymlink and a path-\n // based readdir is no longer possible — the kernel rejects the\n // open if the path resolves to a symlink, and the dirHandle.read()\n // operates on the original inode regardless of subsequent path-\n // based mutations.\n const root = peersRoot(memoryDir);\n // Cursor M round 14: Node's FileHandle has no `readdir` method\n // (only `fs.readdir(path)` is exposed), so we can't read directly\n // from the handle. Instead anchor the original-inode by opening\n // the dir with O_NOFOLLOW, fstat it, then do path-based readdir\n // and confirm the path's lstat AFTER matches the held inode. If\n // it diverges, a swap happened — abort. This is a fence around\n // the readdir, not the kernel-level guarantee a true `fdreaddir`\n // would give, but it closes the path-traversal race without\n // requiring native bindings.\n let entries: string[];\n let dh: import(\"node:fs/promises\").FileHandle | null = null;\n try {\n dh = await fs.open(\n root,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n const fstatBefore = await dh.stat();\n entries = await fs.readdir(root);\n const lstatAfter = await fs.lstat(root);\n if (\n fstatBefore.ino !== lstatAfter.ino ||\n fstatBefore.dev !== lstatAfter.dev ||\n lstatAfter.isSymbolicLink()\n ) {\n throw new Error(`peers root \"${root}\" was swapped during readdir`);\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n } finally {\n if (dh) await dh.close();\n }\n const peers: Peer[] = [];\n // Sort for deterministic ordering — callers that need a different\n // sort order can re-sort the result.\n entries.sort();\n for (const name of entries) {\n if (!PEER_ID_PATTERN.test(name) || name.length > PEER_ID_MAX_LENGTH) {\n continue;\n }\n let stat;\n try {\n // Codex P1: use `lstat` so we don't follow symlinks. A\n // `peers/<valid-id>` symlink pointing at an arbitrary directory\n // would otherwise let listPeers (and the readPeer that\n // follows) traverse outside the peers root.\n stat = await fs.lstat(path.join(root, name));\n } catch (err) {\n // Codex P2 round 13: don't swallow non-ENOENT errors.\n // Permission-denied / EACCES / EIO need to surface so the\n // operator sees a real I/O problem rather than a silently\n // truncated peer list.\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n // Skip symlinks entirely — only real directories are peers.\n if (!stat.isDirectory() || stat.isSymbolicLink()) continue;\n let peer: Peer | null = null;\n try {\n peer = await readPeer(memoryDir, name);\n } catch (err) {\n // Cursor M round 14: classifying by `.code` alone treated\n // security-check failures (assertPeerDirNotEscaped /\n // assertParentDirInodeStable / \"is a symlink and is rejected\"\n // / \"inode mismatch\") as parse failures and silently skipped\n // them. Those messages are critical signals — an attacker\n // attempted to redirect a read outside the peers root. Match\n // by message prefix to detect them and propagate.\n const code = (err as NodeJS.ErrnoException).code;\n const message = err instanceof Error ? err.message : String(err);\n const isSecurityFailure =\n message.startsWith(\"peers root\") ||\n message.startsWith(\"peer directory\") ||\n message.startsWith(\"parent directory\") ||\n message.startsWith(\"path \") /* \"path \\\"...\\\" is a symlink\" */ ||\n message.includes(\"escapes the peers root\") ||\n message.includes(\"inode mismatch\") ||\n message.includes(\"is a symlink and is rejected\") ||\n message.includes(\"was swapped\");\n if (isSecurityFailure) throw err;\n // Real I/O errors (EACCES, EIO, EBUSY, etc.) propagate too.\n if (code && code !== \"ENOENT\") throw err;\n // Schema/parse failures fall through and skip the entry.\n continue;\n }\n if (peer !== null) {\n peers.push(peer);\n }\n }\n return peers;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Interaction log (append-only)\n// ──────────────────────────────────────────────────────────────────────\n\nfunction sanitizeLogField(value: string): string {\n // Cursor Medium: every interaction-log field — not just summary —\n // must collapse newlines so a malicious or buggy `timestamp` /\n // `kind` / `sessionId` value can't break the one-line-per-entry\n // invariant the append-only log relies on. Replace CR/LF/Tab with\n // a single space; trim leading/trailing whitespace.\n return value.replace(/[\\r\\n\\t]+/g, \" \").trim();\n}\n\nfunction isCanonicalIsoTimestamp(value: string): boolean {\n const ms = Date.parse(value);\n return Number.isFinite(ms) && new Date(ms).toISOString() === value;\n}\n\nfunction parseIsoTimestampMs(value: string): number | null {\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(value)) {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction assertCanonicalIsoTimestamp(value: string, field: string): void {\n if (!isCanonicalIsoTimestamp(value)) {\n throw new Error(`${field} must be a canonical ISO-8601 timestamp`);\n }\n}\n\nfunction formatLogEntry(entry: PeerInteractionLogEntry): string {\n // One line per entry. We use a leading bullet so the file remains\n // readable as ordinary markdown. Order: timestamp, kind, optional\n // session id, summary. ALL fields are passed through `sanitizeLogField`\n // so a stray newline anywhere can't shatter the append-only invariant\n // (cursor Medium on PR #723).\n //\n // Cursor Low on PR #736: the previous bare `session=<id>` token was\n // ambiguous with summaries that literally start with `session=`\n // (e.g. summary `\"session=foo bar\"` round-tripped to\n // `{sessionId: \"foo\", summary: \"bar\"}`). New entries wrap the\n // session marker in square brackets — `[session=<id>]` — which a\n // sanitized summary can never start with (sanitizeLogField never\n // emits `[` as the first character of a summary that originally\n // started with `session=`, and bracketed metadata is unambiguously\n // distinct from `session=` text). Old entries written by previous\n // code remain parseable through the legacy fallback in\n // `parseLogLine`.\n const ts = sanitizeLogField(entry.timestamp);\n const kind = sanitizeLogField(entry.kind);\n const summary = sanitizeLogField(entry.summary);\n const session = entry.sessionId\n ? ` [session=${sanitizeLogField(entry.sessionId)}]`\n : \"\";\n return `- [${ts}] (${kind})${session} ${summary}`;\n}\n\n/**\n * Append one entry to a peer's interaction log.\n *\n * Creates `peers/{id}/` and `interactions.log.md` if needed. The file is\n * append-only by contract — this helper never rewrites prior entries.\n * Returns the absolute path of the log file (useful for tests).\n */\nexport async function appendInteractionLog(\n memoryDir: string,\n peerId: string,\n entry: PeerInteractionLogEntry,\n): Promise<string> {\n assertValidPeerId(peerId);\n // Codex P2 round 10: trim() before the empty check matches what\n // sanitizeLogField does at format time. A whitespace-only\n // `timestamp` or `kind` would previously pass validation and then\n // be normalized to \"\" later, producing an entry like `- [] ()`\n // that breaks downstream parsers.\n if (typeof entry.timestamp !== \"string\" || entry.timestamp.trim() === \"\") {\n throw new Error(\"interaction entry must have a non-whitespace timestamp\");\n }\n assertCanonicalIsoTimestamp(entry.timestamp.trim(), \"interaction entry timestamp\");\n if (typeof entry.kind !== \"string\" || entry.kind.trim() === \"\") {\n throw new Error(\"interaction entry must have a non-whitespace kind\");\n }\n if (typeof entry.summary !== \"string\") {\n throw new Error(\"interaction entry must have a string summary\");\n }\n // Codex P2 round 6/8/9: optional sessionId must be a non-empty\n // string OR strictly `undefined` (omitted). null and empty string\n // are both rejected explicitly: the previous behavior silently\n // dropped them during formatting, which reinterprets invalid input\n // instead of failing fast like other validators in this module.\n // Codex P2 round 12: trim() before the empty check matches what\n // sanitizeLogField does at format time. Whitespace-only sessionId\n // would otherwise pass validation and produce a `session=` token\n // with an empty value that breaks downstream log parsers.\n if (entry.sessionId !== undefined) {\n if (typeof entry.sessionId !== \"string\" || entry.sessionId.trim() === \"\") {\n throw new Error(\"interaction entry sessionId must be a non-whitespace string when provided\");\n }\n }\n await mkdirPeerDirAtomic(memoryDir, peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = interactionsPath(memoryDir, peerId);\n const line = formatLogEntry(entry) + \"\\n\";\n // `appendFile` creates the file if it does not exist. POSIX guarantees\n // writes < PIPE_BUF are atomic; entries on this path are well under\n // that bound. Ordering across concurrent writers is the caller's\n // responsibility for now — the reasoner runs serially in PR 2/5.\n await appendFileNoFollow(file, line);\n return file;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Profile read/write (schema scaffold; reasoner ships in PR 2/5)\n// ──────────────────────────────────────────────────────────────────────\n\ninterface ProfileFile {\n updatedAt: string;\n fields: Record<string, string>;\n provenance: Record<string, PeerProfileFieldProvenance[]>;\n}\n\nfunction emitPeerProfile(profile: PeerProfile): string {\n // Profiles use a JSON-in-fenced-code-block payload inside a markdown\n // file so they remain human-readable. The frontmatter holds the\n // updatedAt stamp; the body holds the full structured payload.\n const payload: ProfileFile = {\n updatedAt: profile.updatedAt,\n fields: { ...profile.fields },\n provenance: Object.fromEntries(\n Object.entries(profile.provenance).map(([k, v]) => [k, [...v]]),\n ),\n };\n const json = JSON.stringify(payload, null, 2);\n return [\n \"---\",\n `peerId: ${escapeYamlString(profile.peerId)}`,\n `updatedAt: ${escapeYamlString(profile.updatedAt)}`,\n \"---\",\n \"\",\n \"<!-- peer profile — managed by the async reasoner. Manual edits will be overwritten. -->\",\n \"\",\n \"```json\",\n json,\n \"```\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parsePeerProfile(raw: string, peerId: string): PeerProfile {\n const { fields: fm, body } = parsePeerFrontmatter(raw);\n if (fm.peerId !== undefined && fm.peerId !== peerId) {\n throw new Error(\n `peer profile mismatch — expected \"${peerId}\", file claims \"${fm.peerId}\"`,\n );\n }\n const fenceMatch = body.match(/```json\\s*\\n([\\s\\S]*?)\\n```/);\n if (!fenceMatch) {\n throw new Error(`peer profile for \"${peerId}\" is missing JSON payload`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fenceMatch[1]);\n } catch (err) {\n throw new Error(\n `peer profile for \"${peerId}\" has invalid JSON: ${(err as Error).message}`,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(`peer profile for \"${peerId}\" is not an object`);\n }\n const payload = parsed as Partial<ProfileFile>;\n // Codex P2: only accept string updatedAt values. A malformed payload\n // like `{ \"updatedAt\": 123 }` would previously short-circuit through\n // `payload.updatedAt ?? fm.updatedAt ?? \"\"` and produce a `PeerProfile`\n // whose updatedAt is a number — corrupting any downstream code that\n // assumes the contract.\n const payloadUpdatedAt = typeof payload.updatedAt === \"string\" ? payload.updatedAt : undefined;\n const updatedAt = payloadUpdatedAt ?? fm.updatedAt ?? \"\";\n if (typeof updatedAt !== \"string\" || updatedAt === \"\") {\n throw new Error(`peer profile for \"${peerId}\" is missing updatedAt`);\n }\n // Codex P2 round 10: a malformed `fields: \"wat\"` or\n // `provenance: 42` previously coerced to {} and silently dropped\n // the section. That contradicts the \"malformed files throw\"\n // contract — the file IS malformed, not just empty. Reject loudly.\n // `undefined` is still tolerated (an older profile file might omit\n // the section entirely).\n let fieldsObj: object;\n if (payload.fields === undefined) {\n fieldsObj = {};\n } else if (\n typeof payload.fields === \"object\" &&\n payload.fields !== null &&\n !Array.isArray(payload.fields)\n ) {\n fieldsObj = payload.fields;\n } else {\n throw new Error(`peer profile for \"${peerId}\" has malformed fields section`);\n }\n let provenanceObj: object;\n if (payload.provenance === undefined) {\n provenanceObj = {};\n } else if (\n typeof payload.provenance === \"object\" &&\n payload.provenance !== null &&\n !Array.isArray(payload.provenance)\n ) {\n provenanceObj = payload.provenance;\n } else {\n throw new Error(`peer profile for \"${peerId}\" has malformed provenance section`);\n }\n // Coerce values defensively. We never trust the on-disk shape.\n // Codex P1: skip prototype-pollution keys explicitly. We don't use\n // null-prototype objects in the returned shape because callers\n // (tests, downstream consumers) expect plain objects with normal\n // semantics — the assertion `assert.deepEqual` differentiates by\n // prototype. The skip-list is the load-bearing defense; iteration\n // via Object.entries() of attacker-controlled JSON objects is safe\n // as long as we never assign through dangerous keys.\n const DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const fields: Record<string, string> = {};\n for (const [k, v] of Object.entries(fieldsObj)) {\n if (DANGEROUS_KEYS.has(k)) continue;\n if (typeof v === \"string\") fields[k] = v;\n }\n const provenance: Record<string, PeerProfileFieldProvenance[]> = {};\n for (const [k, v] of Object.entries(provenanceObj)) {\n if (DANGEROUS_KEYS.has(k)) continue;\n if (!Array.isArray(v)) continue;\n const list: PeerProfileFieldProvenance[] = [];\n for (const item of v) {\n if (\n typeof item !== \"object\" ||\n item === null ||\n Array.isArray(item)\n ) {\n continue;\n }\n const r = item as unknown as Record<string, unknown>;\n // Codex P2 round 9: empty observedAt/signal strings should be\n // treated as malformed, not valid. Drop the entry.\n if (typeof r.observedAt !== \"string\" || r.observedAt === \"\") continue;\n if (typeof r.signal !== \"string\" || r.signal === \"\") continue;\n // Codex P2 round 6: previously the optional fields were never\n // type-checked, so a hand-edited `{sourceSessionId: 123}`\n // survived and corrupted the PeerProfileFieldProvenance contract.\n // Build a clean record with only string-typed optional fields.\n const clean: PeerProfileFieldProvenance = {\n observedAt: r.observedAt,\n signal: r.signal,\n ...(typeof r.sourceSessionId === \"string\" && r.sourceSessionId.length > 0\n ? { sourceSessionId: r.sourceSessionId }\n : {}),\n ...(typeof r.note === \"string\" && r.note.length > 0\n ? { note: r.note }\n : {}),\n };\n list.push(clean);\n }\n provenance[k] = list;\n }\n return { peerId, updatedAt, fields, provenance };\n}\n\n/**\n * Read a peer's profile. Returns null if the profile file does not exist.\n *\n * The PR-1 surface only ships the structured read/write so the reasoner\n * (PR 2/5) and recall integration (PR 3/5) have a stable target. We do\n * not yet expose any field-update helpers.\n */\nexport async function readPeerProfile(\n memoryDir: string,\n peerId: string,\n): Promise<PeerProfile | null> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = profilePath(memoryDir, peerId);\n let raw: string;\n try {\n raw = await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n return parsePeerProfile(raw, peerId);\n}\n\n/**\n * Write (create or overwrite) a peer's profile.\n */\nexport async function writePeerProfile(\n memoryDir: string,\n profile: PeerProfile,\n): Promise<void> {\n assertValidPeerId(profile.peerId);\n if (typeof profile.updatedAt !== \"string\" || profile.updatedAt === \"\") {\n throw new Error(\"profile.updatedAt must be a non-empty ISO-8601 string\");\n }\n // Codex P2 round 6: validate the nested payload shape on write so\n // round-trip semantics are preserved. Without this, untyped JS\n // callers can persist non-string field values or malformed\n // provenance entries — readPeerProfile silently scrubs them on\n // the way back, so data is lost without an error. Fail fast at\n // the boundary instead.\n if (!isPlainObject(profile.fields)) {\n throw new Error(\"profile.fields must be a plain object\");\n }\n // Codex P2 round 11: parsePeerProfile drops \"__proto__\" /\n // \"constructor\" / \"prototype\" keys on read. Without symmetric\n // rejection on write, those keys silently disappear during\n // round-trip — failing the contract that what writes succeeds\n // also reads back. Reject at the boundary so JS callers learn\n // immediately that those keys aren't allowed.\n const RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n for (const [key, value] of Object.entries(profile.fields)) {\n if (RESERVED_KEYS.has(key)) {\n throw new Error(`profile.fields key \"${key}\" is reserved and cannot be persisted`);\n }\n if (typeof value !== \"string\") {\n throw new Error(`profile.fields[\"${key}\"] must be a string`);\n }\n }\n if (!isPlainObject(profile.provenance)) {\n throw new Error(\"profile.provenance must be a plain object\");\n }\n for (const [key, list] of Object.entries(profile.provenance)) {\n if (RESERVED_KEYS.has(key)) {\n throw new Error(`profile.provenance key \"${key}\" is reserved and cannot be persisted`);\n }\n if (!Array.isArray(list)) {\n throw new Error(`profile.provenance[\"${key}\"] must be an array`);\n }\n for (let i = 0; i < list.length; i++) {\n const item = list[i] as unknown;\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) {\n throw new Error(`profile.provenance[\"${key}\"][${i}] must be an object`);\n }\n const r = item as Record<string, unknown>;\n if (typeof r.observedAt !== \"string\" || r.observedAt === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].observedAt must be a non-empty string`);\n }\n if (typeof r.signal !== \"string\" || r.signal === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].signal must be a non-empty string`);\n }\n // Cursor M round 9: empty optional strings would round-trip lose\n // (parsePeerProfile drops them on read). Reject at the boundary\n // for consistency with other validators in this module.\n if (r.sourceSessionId !== undefined) {\n if (typeof r.sourceSessionId !== \"string\" || r.sourceSessionId === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].sourceSessionId must be a non-empty string when provided`);\n }\n }\n if (r.note !== undefined) {\n if (typeof r.note !== \"string\" || r.note === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].note must be a non-empty string when provided`);\n }\n }\n }\n }\n await mkdirPeerDirAtomic(memoryDir, profile.peerId);\n await assertPeerDirNotEscaped(memoryDir, profile.peerId);\n const file = profilePath(memoryDir, profile.peerId);\n await writeFileNoFollow(file, emitPeerProfile(profile));\n}\n\n/**\n * Read the raw interaction log for a peer.\n *\n * Returns the empty string if the log does not yet exist. Callers parse\n * the log themselves — this PR does not ship structured log parsing.\n * Exposed primarily so tests can verify monotonic append semantics.\n */\nexport async function readInteractionLogRaw(\n memoryDir: string,\n peerId: string,\n): Promise<string> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = interactionsPath(memoryDir, peerId);\n try {\n return await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return \"\";\n }\n throw err;\n }\n}\n\n/**\n * Inverse of `formatLogEntry`. Used by `readPeerInteractionLog` to\n * convert the on-disk one-line bullet form back into a structured\n * `PeerInteractionLogEntry`. Returns `null` for malformed lines so\n * callers can keep the rest of the log even when a single entry was\n * hand-edited or partially written.\n *\n * Formats accepted (must match `formatLogEntry`):\n *\n * - [TS] (KIND) [session=SID] SUMMARY // canonical (PR #736)\n * - [TS] (KIND) SUMMARY // session optional\n *\n * The unbracketed `session=SID` form (which would have been written\n * by an earlier draft of #679 PR 2/5) is intentionally NOT parsed —\n * the cursor #736 finding showed it was indistinguishable from a\n * summary that legitimately starts with `session=`. Since #679 PR\n * 2/5 is the first shipped writer for `sessionId` AND ships the\n * bracketed canonical form simultaneously, there is no real legacy\n * data on disk to support. A summary like `session=foo bar` thus\n * round-trips verbatim into `summary` rather than being mis-claimed\n * as a session id.\n *\n * Whitespace inside SUMMARY is preserved verbatim. The parser is\n * deliberately strict — anything that doesn't start with `- [` is\n * rejected and dropped (the file is also markdown-friendly, so blank\n * lines and stray prose are simply ignored).\n */\nfunction parseLogLine(line: string): PeerInteractionLogEntry | null {\n if (!line.startsWith(\"- [\")) return null;\n const tsClose = line.indexOf(\"]\", 3);\n if (tsClose === -1) return null;\n const timestamp = line.slice(3, tsClose).trim();\n if (timestamp === \"\") return null;\n if (parseIsoTimestampMs(timestamp) === null) return null;\n // Skip optional whitespace between `]` and `(`.\n let cursor = tsClose + 1;\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n if (line[cursor] !== \"(\") return null;\n const kindOpen = cursor;\n const kindClose = line.indexOf(\")\", kindOpen + 1);\n if (kindClose === -1) return null;\n const kind = line.slice(kindOpen + 1, kindClose).trim();\n if (kind === \"\") return null;\n cursor = kindClose + 1;\n let sessionId: string | undefined;\n // Optional session id token. We tolerate any leading whitespace\n // count; `formatLogEntry` always emits exactly one space, but\n // operator-edited logs may diverge.\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n // Canonical form (PR #736): `[session=<id>]`. Unambiguous because\n // a sanitized summary cannot start with `[session=` followed by a\n // closing bracket and a space — sanitization preserves user content\n // verbatim except for newlines/CR/tab, so a summary that literally\n // begins `[session=foo]` would imply the OPERATOR wrote a real\n // session marker, which is acceptable as session attribution.\n if (line.startsWith(\"[session=\", cursor)) {\n const close = line.indexOf(\"]\", cursor + \"[session=\".length);\n // A `[session=...]` with no closing bracket on the same line is\n // malformed metadata; treat the whole tail as summary instead of\n // misclaiming a session id.\n if (close > -1) {\n const sid = line.slice(cursor + \"[session=\".length, close).trim();\n if (sid.length > 0) sessionId = sid;\n cursor = close + 1;\n }\n }\n // NOTE: the legacy unbracketed `session=<id>` form is intentionally\n // NOT parsed. The cursor #736 finding is fundamentally a format\n // ambiguity: `- [TS] (KIND) session=foo bar` is indistinguishable\n // from a real session token vs. a summary that begins with the\n // literal text `session=foo bar`. Since #679 PR 2/5 is the first\n // PR that writes `sessionId` to the log AND ships the bracketed\n // canonical form simultaneously, there is no production legacy\n // data to support. Old `session=`-style summaries — both real\n // operator notes and hypothetical legacy entries — round-trip\n // verbatim into `summary` rather than being silently mis-claimed\n // as a session id.\n // Remaining tail is the summary (possibly empty if the log was\n // hand-edited; we still accept \"\" because `formatLogEntry` itself\n // accepts an empty summary string).\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n const summary = line.slice(cursor);\n return sessionId === undefined\n ? { timestamp, kind, summary }\n : { timestamp, kind, sessionId, summary };\n}\n\n/**\n * Read the structured interaction log for a peer.\n *\n * Returns an empty array when the log file does not exist. Each line\n * is parsed via `parseLogLine`; malformed lines are silently skipped\n * so the reasoner can still derive profile fields from a partially\n * corrupt log rather than aborting the whole pass.\n *\n * `options.limit` (when > 0) restricts the result to the most recent\n * N entries. `options.afterTimestamp` (ISO-8601) filters out entries\n * with `timestamp <= afterTimestamp`, comparing parsed instants so\n * legacy valid ISO-8601 forms like `Z` without milliseconds or\n * offset timestamps keep working. Both filters are applied in order:\n * timestamp first, then limit.\n *\n * Order: oldest → newest, matching the append-only on-disk order so\n * downstream consumers can reason about temporal evolution without\n * re-sorting.\n */\nexport async function readPeerInteractionLog(\n memoryDir: string,\n peerId: string,\n options: { limit?: number; afterTimestamp?: string } = {},\n): Promise<PeerInteractionLogEntry[]> {\n const raw = await readInteractionLogRaw(memoryDir, peerId);\n if (raw === \"\") return [];\n const entries: PeerInteractionLogEntry[] = [];\n // Split on bare newlines; logs are written with a trailing `\\n` per\n // entry by `appendInteractionLog`, so the final element after split\n // is typically the empty string. Both `\\r\\n` and `\\n` are tolerated.\n for (const lineRaw of raw.split(/\\r?\\n/)) {\n const line = lineRaw.trimEnd();\n if (line === \"\") continue;\n const parsed = parseLogLine(line);\n if (parsed === null) continue;\n entries.push(parsed);\n }\n let filtered = entries;\n if (typeof options.afterTimestamp === \"string\" && options.afterTimestamp.length > 0) {\n const cutoff = options.afterTimestamp;\n const cutoffMs = parseIsoTimestampMs(cutoff);\n if (cutoffMs === null) {\n throw new Error(\"afterTimestamp must be an ISO-8601 timestamp\");\n }\n filtered = filtered.filter((e) => {\n const entryMs = parseIsoTimestampMs(e.timestamp);\n return entryMs !== null && entryMs > cutoffMs;\n });\n }\n // Gotcha #27: guard slice(-n) against n === 0 — `slice(-0)` returns\n // the entire array. Treat 0 and negatives as \"no limit applied\".\n if (typeof options.limit === \"number\" && options.limit > 0) {\n if (filtered.length > options.limit) {\n filtered = filtered.slice(filtered.length - options.limit);\n }\n }\n return filtered;\n}\n","/**\n * Peer registry types — issue #679 PR 1/5.\n *\n * Generalizes the singular identity-anchor model to a multi-peer registry.\n * Every party Remnic interacts with — humans, agents, integrations, and\n * \"self\" — is represented as a `Peer` with an evolving cognitive profile.\n *\n * This module defines pure types only. Storage primitives live in\n * `./storage.ts`. Reasoner integration, recall injection, CLI/HTTP/MCP\n * surfaces, and migration of existing identity-anchor data ship in later\n * PRs (2/5 — 5/5).\n */\n\n/**\n * Kind of peer.\n *\n * - `self` — the current Remnic operator (replaces singular identity-anchor).\n * - `human` — another human collaborator distinct from self.\n * - `agent` — another AI agent (Claude Code, Codex, Hermes, etc.).\n * - `integration` — non-conversational integration (cron, webhook, importer).\n */\nexport type PeerKind = \"self\" | \"human\" | \"agent\" | \"integration\";\n\n/**\n * Stable, slow-changing facts about a peer.\n *\n * `id` matches `^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$`, 1-64 chars,\n * with no leading/trailing/consecutive dots or dashes. Stored on disk under\n * `peers/{id}/identity.md` as YAML frontmatter + markdown body.\n */\nexport interface Peer {\n /** Stable, opaque identifier. See PEER_ID_PATTERN. */\n readonly id: string;\n /** Kind of peer. Drives default profile schema and recall posture. */\n readonly kind: PeerKind;\n /** Human-readable display name. Distinct from `id`; mutable. */\n readonly displayName: string;\n /** ISO-8601 timestamp of first registration. */\n readonly createdAt: string;\n /** ISO-8601 timestamp of most recent update to identity. */\n readonly updatedAt: string;\n /** Optional free-form markdown body for the identity kernel. */\n readonly notes?: string;\n}\n\n/**\n * Evolving cognitive profile for a peer.\n *\n * Updated by the async profile reasoner (PR 2/5) from observable session\n * signals. Every field carries provenance back to its originating session\n * and signal. This PR only defines the shape — population is deferred.\n */\nexport interface PeerProfile {\n /** Peer this profile belongs to. */\n readonly peerId: string;\n /** ISO-8601 timestamp of most recent profile mutation. */\n readonly updatedAt: string;\n /**\n * Arbitrary key/value profile fields. Values are markdown strings.\n * Keys are stable section identifiers (e.g. `communication_style`,\n * `recurring_concerns`). The reasoner is responsible for choosing\n * keys; this PR does not constrain them beyond requiring strings.\n */\n readonly fields: Record<string, string>;\n /**\n * Per-field provenance. Maps field key → list of provenance entries.\n * A field may have multiple sources (the reasoner accumulates evidence\n * across sessions before promoting a field).\n */\n readonly provenance: Record<string, ReadonlyArray<PeerProfileFieldProvenance>>;\n}\n\n/**\n * Provenance for a single profile-field mutation.\n *\n * Reasoner output (PR 2/5) attaches one of these every time it touches a\n * field, so the user can audit exactly why a profile claim exists.\n */\nexport interface PeerProfileFieldProvenance {\n /** ISO-8601 timestamp the field was set/updated by this signal. */\n readonly observedAt: string;\n /** Originating session id (or other source identifier). */\n readonly sourceSessionId?: string;\n /** Short label for the signal type (e.g. \"explicit_preference\"). */\n readonly signal: string;\n /** Optional free-form note explaining the inference. */\n readonly note?: string;\n}\n\n/**\n * One row of the append-only interaction log for a peer.\n *\n * Stored on disk under `peers/{id}/interactions.log.md` as a sequence of\n * markdown bullet entries with a leading ISO-8601 timestamp. Append-only\n * by contract — the reasoner reads this log to derive profile updates.\n */\nexport interface PeerInteractionLogEntry {\n /** ISO-8601 timestamp the interaction occurred. */\n readonly timestamp: string;\n /** Originating session id, if any. */\n readonly sessionId?: string;\n /** Short kind label (e.g. \"message\", \"tool_call\", \"preference_set\"). */\n readonly kind: string;\n /** Free-form markdown summary of the interaction. */\n readonly summary: string;\n}\n\n/**\n * Regex enforced on `Peer.id`. Exported so callers can mirror validation\n * before constructing a `Peer`.\n *\n * Rules:\n * - 1-64 characters total\n * - First and last character must be `[A-Za-z0-9]`\n * - Interior may contain `.`, `_`, `-` in addition to alphanumerics\n * - No leading or trailing dot/dash/underscore\n * - No consecutive separators (`..`, `--`, `__`, `.-`, etc.)\n *\n * Cursor Medium: previously the regex allowed `a..b` even though the\n * docs claimed otherwise — a separate JS-side check enforced the rule\n * but the standalone PATTERN was wrong for any external consumer\n * relying on it. Tighten the regex itself so PEER_ID_PATTERN is the\n * single source of truth: an alphanumeric, optionally followed by\n * groups of (one separator + one-or-more alphanumerics), with the\n * final group ending on an alphanumeric. Negative lookahead-free so\n * it works in any JS engine.\n */\n// CodeQL alert #75: the previous form `^[A-Za-z0-9](?:[._-]?[A-Za-z0-9]+)*$`\n// was ambiguous on alphanumeric runs because `[._-]?` could match\n// empty, letting each iteration consume 1+ alphanumerics in many\n// overlapping ways — exponential backtracking on adversarial inputs.\n// Tighten so the optional group REQUIRES a separator before each\n// subsequent alphanumeric run; no overlapping match paths, linear\n// time on any input.\nexport const PEER_ID_PATTERN = /^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/;\n\n/** Maximum length for `Peer.id`. */\nexport const PEER_ID_MAX_LENGTH = 64;\n"],"mappings":";AAoDA,SAAS,YAAYA,KAAI,aAAaC,oBAAmB;AACzD,OAAOC,WAAU;;;ACpCjB,SAAS,YAAY,IAAI,aAAa,mBAAmB;AACzD,OAAO,UAAU;;;ACoHV,IAAM,kBAAkB;AAGxB,IAAM,q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A,SAAS,CAAC;AAAA,IACV,SAAS;AAAA,IACT;AAAA,IACA,sBAAsB,aAAa;AAAA,IACnC,kBAAkB,iBAAiB;AAAA,EACrC;AACF;","names":["fs","fsConstants","path","path","fs","fsConstants"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/semantic-consolidation.ts"],"sourcesContent":["/**\n * semantic-consolidation.ts — Semantic Consolidation Engine\n *\n * Finds clusters of semantically similar memories using token overlap,\n * synthesizes canonical versions via LLM, and archives the originals.\n * Reduces memory store bloat while preserving all unique information.\n */\n\nimport type { MemoryFile, PluginConfig } from \"./types.js\";\nimport { normalizeRecallTokens, countRecallTokenOverlap } from \"./recall-tokenization.js\";\nimport { runPostConsolidationMaterialize } from \"./connectors/codex-materialize-runner.js\";\nimport type { MaterializeResult, RolloutSummaryInput } from \"./connectors/codex-materialize.js\";\nimport { discoverMemoryExtensions, renderExtensionsBlock, resolveExtensionsRoot } from \"./memory-extension-host/index.js\";\nimport { log } from \"./logger.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\n\n// Re-export resolveExtensionsRoot for backward compatibility — existing\n// consumers that import from semantic-consolidation.ts continue to work.\nexport { resolveExtensionsRoot } from \"./memory-extension-host/index.js\";\n\n// Operator vocabulary (issue #561). The types and validators live in a\n// standalone `consolidation-operator.ts` module so `storage.ts` can import\n// them without creating a `storage → semantic-consolidation →\n// codex-materialize-runner → storage` cycle. Re-exported here so existing\n// consumers that reach for `./semantic-consolidation.js` keep working.\nexport {\n CONSOLIDATION_OPERATORS,\n isConsolidationOperator,\n isSemanticConsolidationLlmOperator,\n isValidDerivedFromEntry,\n type ConsolidationOperator,\n type SemanticConsolidationLlmOperator,\n} from \"./consolidation-operator.js\";\n\nimport {\n CONSOLIDATION_OPERATORS as _CONSOLIDATION_OPERATORS,\n isConsolidationOperator as _isConsolidationOperator,\n isSemanticConsolidationLlmOperator as _isSemanticConsolidationLlmOperator,\n type ConsolidationOperator as _ConsolidationOperator,\n type SemanticConsolidationLlmOperator as _SemanticConsolidationLlmOperator,\n} from \"./consolidation-operator.js\";\n\nexport interface ConsolidationCluster {\n category: string;\n memories: MemoryFile[];\n overlapScore: number;\n canonicalContent?: string;\n}\n\nexport interface SemanticConsolidationResult {\n clustersFound: number;\n memoriesConsolidated: number;\n memoriesArchived: number;\n errors: number;\n clusters: ConsolidationCluster[];\n}\n\n/**\n * Find clusters of semantically similar memories using token overlap.\n */\nexport function findSimilarClusters(\n memories: MemoryFile[],\n config: {\n threshold: number;\n minClusterSize: number;\n excludeCategories: string[];\n maxPerRun: number;\n },\n): ConsolidationCluster[] {\n const excluded = new Set(config.excludeCategories);\n\n // Group by category first\n const byCategory = new Map<string, MemoryFile[]>();\n for (const m of memories) {\n const cat = m.frontmatter.category;\n if (excluded.has(cat)) continue;\n if (m.frontmatter.status && m.frontmatter.status !== \"active\") continue;\n const list = byCategory.get(cat) ?? [];\n list.push(m);\n byCategory.set(cat, list);\n }\n\n const clusters: ConsolidationCluster[] = [];\n let totalCandidates = 0;\n\n for (const [category, mems] of byCategory) {\n if (totalCandidates >= config.maxPerRun) break;\n\n // Token-normalize all memories in this category\n const tokenized = mems.map((m) => ({\n memory: m,\n tokens: new Set(normalizeRecallTokens(m.content, [])),\n }));\n\n // Track which memories are already clustered\n const clustered = new Set<string>();\n\n for (let i = 0; i < tokenized.length && totalCandidates < config.maxPerRun; i++) {\n const remainingBudget = config.maxPerRun - totalCandidates;\n if (remainingBudget < config.minClusterSize) break;\n if (clustered.has(tokenized[i].memory.frontmatter.id)) continue;\n\n const cluster: MemoryFile[] = [tokenized[i].memory];\n let totalOverlap = 0;\n let comparisons = 0;\n\n for (let j = i + 1; j < tokenized.length && cluster.length < remainingBudget; j++) {\n if (clustered.has(tokenized[j].memory.frontmatter.id)) continue;\n\n const aTokens = tokenized[i].tokens;\n const bTokens = tokenized[j].tokens;\n if (aTokens.size === 0 || bTokens.size === 0) continue;\n\n // Bidirectional overlap: what fraction of tokens are shared\n const overlap = countRecallTokenOverlap(aTokens, [...bTokens].join(\" \"));\n const maxTokens = Math.max(aTokens.size, bTokens.size);\n const score = maxTokens > 0 ? overlap / maxTokens : 0;\n\n if (score >= config.threshold) {\n cluster.push(tokenized[j].memory);\n totalOverlap += score;\n comparisons++;\n }\n }\n\n if (cluster.length >= config.minClusterSize) {\n for (const m of cluster) clustered.add(m.frontmatter.id);\n clusters.push({\n category,\n memories: cluster,\n overlapScore: comparisons > 0 ? totalOverlap / comparisons : 0,\n });\n totalCandidates += cluster.length;\n }\n }\n }\n\n return clusters;\n}\n\n/**\n * Build the LLM prompt for synthesizing a canonical memory from a cluster.\n */\nexport function buildConsolidationPrompt(cluster: ConsolidationCluster): string {\n const memoryTexts = cluster.memories\n .map(\n (m, i) =>\n `Memory ${i + 1} (${m.frontmatter.id}, created ${m.frontmatter.created}):\\n${m.content}`,\n )\n .join(\"\\n\\n\");\n\n return `You are a memory consolidation system. The following ${cluster.memories.length} memories in the \"${cluster.category}\" category contain overlapping information.\n\nSynthesize them into ONE canonical memory that:\n1. Preserves ALL unique information from every source memory\n2. Removes redundancy and repetition\n3. Uses clear, concise language\n4. Maintains the same category and tone\n5. Does NOT add information that isn't in the sources\n\n${memoryTexts}\n\nWrite ONLY the consolidated memory content (no metadata, no explanation, no preamble):`;\n}\n\n/**\n * Parse the LLM response to extract the canonical content.\n */\nexport function parseConsolidationResponse(response: string): string {\n return response.trim();\n}\n\n// ─── Operator-aware prompt / parse (issue #561 PR 3) ─────────────────────────\n\n/**\n * Structured result from an operator-aware consolidation LLM call.\n *\n * - `operator` — the consolidation operator the LLM chose for this cluster.\n * Falls back to the heuristic default when the LLM omits or returns an\n * unknown value (the parser never surfaces an invalid operator; see\n * `parseOperatorAwareConsolidationResponse`).\n * - `output` — the canonical content (same format the legacy prompt\n * returns). Callers persist this as the body of the new memory.\n */\nexport interface OperatorAwareConsolidationResult {\n // Restricted to the LLM-allowed subset (Cursor Bugbot, PR #730):\n // `pattern-reinforcement` is reserved for the maintenance job and\n // must never reach this struct from a consolidation LLM response.\n operator: _SemanticConsolidationLlmOperator;\n output: string;\n}\n\n/**\n * Heuristic default operator for a cluster. Used as the fallback when the\n * LLM does not return a parseable operator, and as the \"floor\" decision in\n * `parseOperatorAwareConsolidationResponse`.\n *\n * Current heuristic (kept deliberately conservative — PR 3 only):\n *\n * - Two or more memories being collapsed into one canonical blob is a\n * MERGE by definition. This is the path the current clustering\n * pipeline exercises.\n * - A cluster of size 1 that still reaches consolidation (future path,\n * e.g. supersession of a single older memory by a newer value) is an\n * UPDATE.\n * - SPLIT is never selected by the heuristic because the current write\n * path emits exactly one canonical memory per cluster. The prompt\n * reserves SPLIT for future cluster shapes where the LLM decides one\n * logical source actually encodes several distinct facts — at which\n * point the orchestrator would need to write multiple outputs.\n */\nexport function chooseConsolidationOperator(\n cluster: ConsolidationCluster,\n): _SemanticConsolidationLlmOperator {\n if (cluster.memories.length <= 1) return \"update\";\n return \"merge\";\n}\n\n/**\n * Build the operator-aware LLM prompt. The LLM is asked to return a\n * JSON object `{ \"operator\": <split|merge|update>, \"output\": <content> }`.\n *\n * The prompt is additive: it still asks for a single canonical blob under\n * `output`, so the upstream write path does not change. Future expansions\n * (SPLIT emitting multiple outputs) are explicitly documented as\n * out-of-scope for the parser — `parseOperatorAwareConsolidationResponse`\n * collapses any SPLIT response into a single canonical output for now.\n */\nexport function buildOperatorAwareConsolidationPrompt(\n cluster: ConsolidationCluster,\n): string {\n const memoryTexts = cluster.memories\n .map(\n (m, i) =>\n `Memory ${i + 1} (${m.frontmatter.id}, created ${m.frontmatter.created}):\\n${m.content}`,\n )\n .join(\"\\n\\n\");\n\n return `You are a memory consolidation system. The following ${cluster.memories.length} memories in the \"${cluster.category}\" category contain overlapping information.\n\nPick exactly ONE consolidation operator for this cluster and return a JSON object.\n\nOperator vocabulary:\n - \"merge\" — multiple distinct source memories overlap and should be collapsed into one canonical memory (most common).\n - \"update\" — one source memory carries a stale value that a newer source supersedes within the same logical fact.\n - \"split\" — a single logical source really encodes multiple distinct facts that should be separated (rare; if you pick split, still emit ONE canonical body — the write path will chunk it later).\n\nOutput JSON ONLY, no prose before or after. The \"operator\" key MUST be set to exactly one of the three strings \"merge\", \"update\", or \"split\" — never a pipe-separated placeholder like \"merge|update|split\". Example shape:\n {\n \"operator\": \"merge\",\n \"output\": \"<the canonical memory text>\"\n }\n\nThe \"output\" value must:\n1. Preserve ALL unique information from every source memory\n2. Remove redundancy and repetition\n3. Use clear, concise language\n4. Match the \"${cluster.category}\" category and tone\n5. NOT add information that isn't in the sources\n\n${memoryTexts}\n\nReturn ONLY the JSON object:`;\n}\n\n/**\n * Parse an operator-aware consolidation response.\n *\n * Contract:\n * - Accepts strict JSON `{ \"operator\": \"...\", \"output\": \"...\" }`.\n * - Tolerates a JSON payload wrapped in a fenced code block (```json ...```).\n * - Falls back to the heuristic operator when the JSON is malformed,\n * the `operator` field is missing / unknown, or the raw response is\n * a plain blob with no JSON at all. This keeps PR 3 backwards\n * compatible with older models that ignore the JSON instruction.\n * - Never throws. A missing / empty `output` field falls back to the\n * trimmed raw response so the caller still writes something rather\n * than dropping the cluster.\n */\nexport function parseOperatorAwareConsolidationResponse(\n response: string,\n cluster: ConsolidationCluster,\n): OperatorAwareConsolidationResult {\n const fallback: OperatorAwareConsolidationResult = {\n operator: chooseConsolidationOperator(cluster),\n output: response.trim(),\n };\n\n const trimmed = response.trim();\n if (trimmed.length === 0) return fallback;\n\n // Strip a fenced code block if present.\n // Dropped the \\s* groups around the lazy body (they overlapped it and\n // backtracked polynomially — CodeQL js/polynomial-redos). Input is already\n // trimmed and fenced[1] is trimmed below, so matches are identical.\n const fenced = /^```(?:json)?([\\s\\S]*?)```$/u.exec(trimmed);\n const payload = fenced ? fenced[1].trim() : trimmed;\n\n // Find a balanced brace-delimited JSON object that has an `operator`\n // key (PR #632 round-4 review, codex P1). A first/last-brace slice\n // breaks when the model prepends an earlier brace block (e.g.\n // `Example: {\"note\":\"...\"} ... {\"operator\":\"merge\",...}`). Walk the\n // payload tracking nesting + string/escape state and skip past\n // objects that don't look like our target shape.\n const parsed = findLastJsonObjectWithOperator(payload);\n if (parsed === undefined) return fallback;\n if (typeof parsed !== \"object\" || parsed === null) return fallback;\n\n const obj = parsed as Record<string, unknown>;\n const rawOperator = typeof obj.operator === \"string\" ? obj.operator.trim().toLowerCase() : \"\";\n const rawOutput = typeof obj.output === \"string\" ? obj.output : \"\";\n\n // Narrow gate (Cursor Bugbot review on PR #730 head `aa1c2a8`):\n // accept ONLY the legacy split/merge/update LLM vocabulary here.\n // `pattern-reinforcement` joined the broader `ConsolidationOperator`\n // type in #687 PR 2/4 but is reserved for the maintenance job — if\n // an LLM hallucinates that operator we must NOT promote it onto\n // `derived_via`.\n const operator = _isSemanticConsolidationLlmOperator(rawOperator)\n ? rawOperator\n : chooseConsolidationOperator(cluster);\n const output = rawOutput.trim().length > 0 ? rawOutput.trim() : response.trim();\n\n return { operator, output };\n}\n\n/**\n * Walk `text`, find all balanced top-level `{ ... }` blocks whose\n * JSON.parse result is an object with an `operator` key, and return\n * the LAST one (function name reflects this — PR #632 review,\n * cursor Low). Returns `undefined` when nothing matches. Tracks\n * string state + escape sequences so braces inside string values\n * don't throw off the depth counter.\n *\n * Used by `parseOperatorAwareConsolidationResponse` to tolerate models\n * that prepend an explanatory JSON example block before the real\n * payload (PR #632 round-4 + round-5 review, codex P1). We take the\n * LAST candidate so that an instructional example with an `operator`\n * key ahead of the real answer doesn't steal precedence — models\n * typically write the example first and the real answer last.\n */\nfunction findLastJsonObjectWithOperator(text: string): unknown {\n let searchFrom = 0;\n let last: unknown = undefined;\n while (searchFrom < text.length) {\n const start = text.indexOf(\"{\", searchFrom);\n if (start < 0) return last;\n let depth = 0;\n let inString = false;\n let escape = false;\n let closed = false;\n let endIdx = -1;\n for (let i = start; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escape) {\n escape = false;\n } else if (ch === \"\\\\\") {\n escape = true;\n } else if (ch === '\"') {\n inString = false;\n }\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === \"{\") {\n depth += 1;\n } else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) {\n closed = true;\n endIdx = i;\n break;\n }\n }\n }\n if (!closed) return last;\n const slice = text.slice(start, endIdx + 1);\n try {\n const parsed = JSON.parse(slice);\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"operator\" in (parsed as Record<string, unknown>)\n ) {\n last = parsed;\n }\n } catch {\n // Fall through to the next candidate.\n }\n searchFrom = endIdx + 1;\n }\n return last;\n}\n\n// Silence unused-import warnings when tsup tree-shakes: these are used\n// above in chooseConsolidationOperator + parse helpers.\nvoid _CONSOLIDATION_OPERATORS;\n\n/**\n * Discover extensions and build the block to append to a consolidation prompt.\n * Returns \"\" when extensions are disabled or none are found.\n */\nexport async function buildExtensionsBlockForConsolidation(\n config: PluginConfig,\n): Promise<string> {\n if (!resolvePipelineProcessingCapabilities(config).memoryExtensions) return \"\";\n const root = resolveExtensionsRoot(config);\n const extensions = await discoverMemoryExtensions(root, log);\n if (extensions.length === 0) return \"\";\n return renderExtensionsBlock(extensions);\n}\n\n/**\n * Optional post-consolidation hook — materializes the namespace into Codex's\n * native memory layout when the consolidation run finishes. Kept here (rather\n * than in orchestrator.ts) so #378 doesn't conflict with Wave 1 edits.\n *\n * Safe to call regardless of config state: honors `codexMaterializeMemories`\n * and `codexMaterializeOnConsolidation` and silently becomes a no-op when\n * either is disabled.\n */\nexport async function materializeAfterSemanticConsolidation(options: {\n config: PluginConfig;\n namespace?: string;\n memories?: MemoryFile[];\n memoryDir?: string;\n codexHome?: string;\n rolloutSummaries?: RolloutSummaryInput[];\n now?: Date;\n}): Promise<MaterializeResult | null> {\n // Delegates to the shared post-consolidation helper so semantic and causal\n // flows stay in lock-step — any guard/logging change happens in one place.\n return runPostConsolidationMaterialize(\"[semantic-consolidation]\", options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4DO,SAAS,oBACd,UACA,QAMwB;AACxB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AAS;AACb,QAAI,SAAS;AACb,aAAS,IAAI,OAAO,IAAI,KAAK,QAAQ,KAAK;AACxC,YAAM,KAAK,KAAK,CAAC;AACjB,UAAI,UAAU;AACZ,YAAI,QAAQ;AACV,mBAAS;AAAA,QACX,WAAW,OAAO,MAAM;AACtB,mBAAS;AAAA,QACX,WAAW,OAAO,KAAK;AACrB,qBAAW;AAAA,QACb;AACA;AAAA,MACF;AACA,UAAI,OAAO,KAAK;AACd,mBAAW;AAAA,MACb,WAAW,OAAO,KAAK;AACrB,iBAAS;AAAA,MACX,WAAW,OAAO,KAAK;AACrB,iBAAS;AACT,YAAI,UAAU,GAAG;AACf,mBAAS;AACT,mBAAS;AACT;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,QAAI,CAAC,OAAQ,QAAO;AACpB,UAAM,QAAQ,KAAK,MAAM,OAAO,SAAS,CAAC;AAC1C,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,UACE,OAAO,WAAW,YAClB,WAAW,QACX,cAAe,QACf;AACA,eAAO;AAAA,MACT;AAAA,IACF,QAAQ;AAAA,IAER;AACA,iBAAa,SAAS;AAAA,EACxB;AACA,SAAO;AACT;AAUA,eAAsB,qCACpB,QACiB;AACjB,MAAI,CAAC,sCAAsC,MAAM,EAAE,iBAAkB,QAAO;AAC5E,QAAM,OAAO,sBAAsB,MAAM;AACzC,QAAM,aAAa,MAAM,yBAAyB,MAAM,GAAG;AAC3D,MAAI,WAAW,WAAW,EAAG,QAAO;AACpC,SAAO,sBAAsB,UAAU;AACzC;AAWA,eAAsB,sCAAsC,SAQtB;AAGpC,SAAO,gCAAgC,4BAA4B,OAAO;AAC5E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lifecycle.ts"],"sourcesContent":["import type {\n LifecycleState,\n MemoryCategory,\n MemoryFile,\n MemoryFrontmatter,\n VerificationState,\n} from \"./types.js\";\n\nexport interface LifecyclePolicy {\n promoteHeatThreshold: number;\n staleDecayThreshold: number;\n archiveDecayThreshold: number;\n protectedCategories: MemoryCategory[];\n}\n\nexport interface LifecycleSignals {\n /**\n * Optional relevance feedback in [-1, 1]. Negative values increase decay.\n * Positive values raise heat.\n */\n feedbackScore?: number;\n /**\n * Optional bounded prior derived from memory-action outcomes in [-1, 1].\n * This is intentionally low-impact to avoid circular amplification.\n */\n actionPriorScore?: number;\n /**\n * Optional causal impact score from CMC chain analysis in [0, 0.3].\n * Computed as 0.1 * incomingEdges + 0.15 * outgoingEdges, clamped.\n * Weight in heat/decay is intentionally low (0.05) to avoid circular amplification.\n */\n causalImpactScore?: number;\n}\n\nexport interface LifecycleDecision {\n currentState: LifecycleState;\n nextState: LifecycleState;\n heatScore: number;\n decayScore: number;\n changed: boolean;\n reason: string;\n}\n\nexport interface LifecycleValueInputs {\n confidence: number;\n access: number;\n recency: number;\n importance: number;\n feedback: number;\n disputedPenalty: number;\n}\n\nconst DEFAULT_POLICY: LifecyclePolicy = {\n promoteHeatThreshold: 0.55,\n staleDecayThreshold: 0.65,\n archiveDecayThreshold: 0.85,\n protectedCategories: [\"decision\", \"principle\", \"commitment\", \"preference\", \"procedure\"],\n};\n\nexport function clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0;\n if (value < 0) return 0;\n if (value > 1) return 1;\n return value;\n}\n\nexport function clampLifecycleThreshold(value: number): number {\n return clamp01(value);\n}\n\nfunction parseIsoMs(value?: string): number | null {\n if (!value) return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nexport function daysSince(value: string | undefined, nowMs: number): number {\n const ts = parseIsoMs(value);\n if (ts === null) return 365;\n return Math.max(0, (nowMs - ts) / 86_400_000);\n}\n\nfunction confidenceTierWeight(frontmatter: MemoryFrontmatter): number {\n switch (frontmatter.confidenceTier) {\n case \"explicit\":\n return 1;\n case \"implied\":\n return 0.8;\n case \"inferred\":\n return 0.6;\n case \"speculative\":\n return 0.35;\n default:\n return clamp01(frontmatter.confidence ?? 0.5);\n }\n}\n\nfunction accessWeight(accessCount: number | undefined): number {\n const raw = accessCount ?? 0;\n if (raw <= 0) return 0;\n return clamp01(Math.log1p(raw) / Math.log1p(20));\n}\n\nfunction recencyWeight(frontmatter: MemoryFrontmatter, nowMs: number): number {\n const lastTouch = frontmatter.lastAccessed ?? frontmatter.updated ?? frontmatter.created;\n const ageDays = daysSince(lastTouch, nowMs);\n return clamp01(1 - ageDays / 90);\n}\n\nfunction feedbackWeight(signals?: LifecycleSignals): number {\n const raw = (signals?.feedbackScore ?? 0) + (signals?.actionPriorScore ?? 0);\n return clamp01((raw + 1) / 2);\n}\n\nfunction boundedFeedbackScore(signals?: LifecycleSignals): number {\n const raw = (signals?.feedbackScore ?? 0) + (signals?.actionPriorScore ?? 0);\n if (!Number.isFinite(raw)) return 0;\n if (raw < -1) return -1;\n if (raw > 1) return 1;\n return raw;\n}\n\nfunction isProtectedMemory(\n frontmatter: MemoryFrontmatter,\n policy: LifecyclePolicy,\n): boolean {\n return frontmatter.policyClass === \"protected\" || policy.protectedCategories.includes(frontmatter.category);\n}\n\nexport function resolveLifecycleState(frontmatter: MemoryFrontmatter): LifecycleState {\n if (frontmatter.status === \"archived\") return \"archived\";\n return frontmatter.lifecycleState ?? \"candidate\";\n}\n\nexport function computeHeat(\n memory: Pick<MemoryFile, \"frontmatter\">,\n now: Date,\n signals?: LifecycleSignals,\n): number {\n const frontmatter = memory.frontmatter;\n if (frontmatter.status === \"archived\") return 0;\n\n const inputs = computeLifecycleValueInputs(memory, now, signals);\n const causalBoost = clamp01(signals?.causalImpactScore ?? 0) * 0.05;\n const score = (inputs.confidence * 0.25)\n + (inputs.access * 0.3)\n + (inputs.recency * 0.2)\n + (inputs.importance * 0.15)\n + (inputs.feedback * 0.1)\n + causalBoost\n - inputs.disputedPenalty;\n return clamp01(score);\n}\n\nexport function computeLifecycleValueInputs(\n memory: Pick<MemoryFile, \"frontmatter\">,\n now: Date,\n signals?: LifecycleSignals,\n): LifecycleValueInputs {\n const frontmatter = memory.frontmatter;\n const nowMs = now.getTime();\n return {\n confidence: confidenceTierWeight(frontmatter),\n access: accessWeight(frontmatter.accessCount),\n recency: recencyWeight(frontmatter, nowMs),\n importance: clamp01(frontmatter.importance?.score ?? 0.5),\n feedback: feedbackWeight(signals),\n disputedPenalty: frontmatter.verificationState === \"disputed\" ? 0.2 : 0,\n };\n}\n\nexport function computeDecay(\n memory: Pick<MemoryFile, \"frontmatter\">,\n now: Date,\n signals?: LifecycleSignals,\n): number {\n const frontmatter = memory.frontmatter;\n if (frontmatter.status === \"archived\") return 1;\n\n const nowMs = now.getTime();\n const ageDays = daysSince(frontmatter.updated ?? frontmatter.created, nowMs);\n const staleAccessDays = daysSince(frontmatter.lastAccessed, nowMs);\n const ageRisk = clamp01(ageDays / 180);\n const staleAccessRisk = clamp01(staleAccessDays / 120);\n const confidenceRisk = 1 - confidenceTierWeight(frontmatter);\n const feedbackRisk = clamp01((boundedFeedbackScore(signals) * -1 + 1) / 2);\n const heat = computeHeat(memory, now, signals);\n\n const score = (ageRisk * 0.3)\n + (staleAccessRisk * 0.25)\n + (confidenceRisk * 0.2)\n + (feedbackRisk * 0.1)\n + ((1 - heat) * 0.15);\n\n return clamp01(score);\n}\n\nfunction toTerminalDisputedState(\n currentState: LifecycleState,\n): LifecycleState {\n if (currentState === \"archived\") return \"archived\";\n return \"stale\";\n}\n\nfunction isActiveEligible(verificationState?: VerificationState): boolean {\n return verificationState === \"user_confirmed\" || verificationState === \"system_inferred\";\n}\n\nexport function decideLifecycleTransition(\n memory: Pick<MemoryFile, \"frontmatter\">,\n policy: Partial<LifecyclePolicy>,\n now: Date,\n signals?: LifecycleSignals,\n): LifecycleDecision {\n const mergedPolicy: LifecyclePolicy = { ...DEFAULT_POLICY, ...policy };\n const frontmatter = memory.frontmatter;\n const currentState = resolveLifecycleState(frontmatter);\n const heatScore = computeHeat(memory, now, signals);\n const decayScore = computeDecay(memory, now, signals);\n const protectedMemory = isProtectedMemory(frontmatter, mergedPolicy);\n\n if (currentState === \"archived\") {\n return {\n currentState,\n nextState: \"archived\",\n heatScore,\n decayScore,\n changed: false,\n reason: \"archived_is_terminal\",\n };\n }\n\n if (frontmatter.verificationState === \"disputed\") {\n const nextState = toTerminalDisputedState(currentState);\n return {\n currentState,\n nextState,\n heatScore,\n decayScore,\n changed: nextState !== currentState,\n reason: \"disputed_memories_do_not_promote_to_active\",\n };\n }\n\n if (decayScore >= mergedPolicy.archiveDecayThreshold && !protectedMemory) {\n return {\n currentState,\n nextState: \"archived\",\n heatScore,\n decayScore,\n changed: true,\n reason: \"decay_exceeded_archive_threshold\",\n };\n }\n\n if (decayScore >= mergedPolicy.staleDecayThreshold) {\n return {\n currentState,\n nextState: \"stale\",\n heatScore,\n decayScore,\n changed: currentState !== \"stale\",\n reason: \"decay_exceeded_stale_threshold\",\n };\n }\n\n if (heatScore >= mergedPolicy.promoteHeatThreshold) {\n const nextState = isActiveEligible(frontmatter.verificationState)\n ? \"active\"\n : \"validated\";\n return {\n currentState,\n nextState,\n heatScore,\n decayScore,\n changed: currentState !== nextState,\n reason: \"heat_exceeded_promote_threshold\",\n };\n }\n\n return {\n currentState,\n nextState: currentState,\n heatScore,\n decayScore,\n changed: false,\n reason: \"no_transition\",\n };\n}\n"],"mappings":";AAoDA,IAAM,iBAAkC;AAAA,EACtC,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,uBAAuB;AAAA,EACvB,qBAAqB,CAAC,YAAY,aAAa,cAAc,cAAc,WAAW;AACxF;AAEO,SAAS,QAAQ,OAAuB;AAC7C,MAAI,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACpC,MAAI,QAAQ,EAAG,QAAO;AACtB,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO;AACT;AAEO,SAAS,wBAAwB,OAAuB;AAC7D,SAAO,QAAQ,KAAK;AACtB;AAEA,SAAS,WAAW,OAA+B;AACjD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,KAAK,KAAK,MAAM,KAAK;AA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