@remnic/core 10.0.49 → 10.0.50

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 (338) hide show
  1. package/dist/access-admin-ops-surface.js +41 -40
  2. package/dist/access-authorization-probe.js +42 -41
  3. package/dist/access-boundary.js +41 -40
  4. package/dist/access-cli.js +107 -106
  5. package/dist/access-cli.js.map +1 -1
  6. package/dist/access-extraction-force-flush.js +41 -40
  7. package/dist/access-http-briefing.d.ts +2 -0
  8. package/dist/access-http-briefing.d.ts.map +1 -1
  9. package/dist/access-http-briefing.js +42 -41
  10. package/dist/access-http-query.js +43 -42
  11. package/dist/access-http.d.ts.map +1 -1
  12. package/dist/access-http.js +59 -58
  13. package/dist/access-identity-continuity-surface.js +41 -40
  14. package/dist/access-lcm-surface.js +41 -40
  15. package/dist/access-mcp.js +51 -50
  16. package/dist/access-namespace-preflight.js +41 -40
  17. package/dist/access-observe-write-category.d.ts +1 -1
  18. package/dist/access-observe-write-category.d.ts.map +1 -1
  19. package/dist/access-observe-write-category.js +10 -10
  20. package/dist/access-observe-write-surface.d.ts.map +1 -1
  21. package/dist/access-observe-write-surface.js +41 -40
  22. package/dist/access-offline-manifest.js +4 -4
  23. package/dist/access-operations-batch.js +42 -41
  24. package/dist/access-operations.js +49 -48
  25. package/dist/access-recall-concurrency.js +41 -40
  26. package/dist/access-recall-response.js +41 -40
  27. package/dist/access-recall-surface.js +41 -40
  28. package/dist/access-schema.js +6 -6
  29. package/dist/access-service.d.ts +5 -0
  30. package/dist/access-service.d.ts.map +1 -1
  31. package/dist/access-service.js +41 -40
  32. package/dist/access-surface-catalog.js +43 -42
  33. package/dist/access-surface-catalog.js.map +1 -1
  34. package/dist/active-recall.js +14 -14
  35. package/dist/{auto-sync-BNCBMU6H.js → auto-sync-UQQ6YJSB.js} +3 -3
  36. package/dist/briefing-deadline.d.ts +7 -0
  37. package/dist/briefing-deadline.d.ts.map +1 -0
  38. package/dist/briefing-deadline.js +13 -0
  39. package/dist/briefing-window.d.ts +12 -4
  40. package/dist/briefing-window.d.ts.map +1 -1
  41. package/dist/briefing-window.js +3 -1
  42. package/dist/briefing.d.ts +2 -0
  43. package/dist/briefing.d.ts.map +1 -1
  44. package/dist/briefing.js +12 -11
  45. package/dist/buffer.js +3 -3
  46. package/dist/calibration.js +2 -2
  47. package/dist/{capsule-merge-RNQUP2VL.js → capsule-merge-D4BTIJGK.js} +3 -3
  48. package/dist/causal-consolidation.js +11 -11
  49. package/dist/{chunk-ESDOQEJM.js → chunk-2AKIVSHP.js} +2 -2
  50. package/dist/{chunk-MCS4LIXP.js → chunk-43TUWQNR.js} +2 -2
  51. package/dist/{chunk-2NLCDNGA.js → chunk-564YP3DW.js} +2 -2
  52. package/dist/{chunk-PBWJVRKE.js → chunk-5FUDSK6Z.js} +2 -2
  53. package/dist/{chunk-V4GPFCJ7.js → chunk-5G53JSRO.js} +2 -2
  54. package/dist/{chunk-WJCAAVZX.js → chunk-5X2H3X4J.js} +2 -2
  55. package/dist/{chunk-CPBYKOTC.js → chunk-6ZQX3R66.js} +2 -2
  56. package/dist/{chunk-AF4UIHON.js → chunk-74AY3S7U.js} +9 -9
  57. package/dist/{chunk-XSJL62LE.js → chunk-7J6A5MV2.js} +2 -2
  58. package/dist/{chunk-A3WXV7YU.js → chunk-7SAE6T36.js} +2 -2
  59. package/dist/{chunk-BWF3KNSQ.js → chunk-7YVER7ZO.js} +2 -2
  60. package/dist/{chunk-5IDQVE4U.js → chunk-A3UFV4K3.js} +6 -6
  61. package/dist/{chunk-LWRIGKFM.js → chunk-A5L5KGDI.js} +19 -1
  62. package/dist/chunk-A5L5KGDI.js.map +1 -0
  63. package/dist/{chunk-6TIVVOVU.js → chunk-BNJAVRNJ.js} +9 -9
  64. package/dist/{chunk-CMOYD5CA.js → chunk-CCL2OXFO.js} +2 -2
  65. package/dist/{chunk-7XFQSQYS.js → chunk-CRN3EPE2.js} +4 -3
  66. package/dist/chunk-CRN3EPE2.js.map +1 -0
  67. package/dist/{chunk-3NYIXVCT.js → chunk-DMKTOCC7.js} +2 -2
  68. package/dist/chunk-DMKTOCC7.js.map +1 -0
  69. package/dist/{chunk-FRXS6SC7.js → chunk-EKUI7I2X.js} +20 -4
  70. package/dist/chunk-EKUI7I2X.js.map +1 -0
  71. package/dist/{chunk-N6EM7ESC.js → chunk-EKYWZYZJ.js} +22 -14
  72. package/dist/chunk-EKYWZYZJ.js.map +1 -0
  73. package/dist/{chunk-FOKTW6GY.js → chunk-EWBXMGXR.js} +2 -2
  74. package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
  75. package/dist/{chunk-6W3QH3QW.js → chunk-GQIYL7OD.js} +388 -292
  76. package/dist/chunk-GQIYL7OD.js.map +1 -0
  77. package/dist/{chunk-E47UQBYW.js → chunk-GXVXBYRA.js} +3 -3
  78. package/dist/{chunk-RZDDNH63.js → chunk-HKOMHP6D.js} +27 -15
  79. package/dist/chunk-HKOMHP6D.js.map +1 -0
  80. package/dist/{chunk-AGCEJDG2.js → chunk-HPNXS6W6.js} +2 -2
  81. package/dist/{chunk-O4CA53UY.js → chunk-IMKOJVD4.js} +69 -63
  82. package/dist/chunk-IMKOJVD4.js.map +1 -0
  83. package/dist/{chunk-N5PISU26.js → chunk-IN6U2BS5.js} +2 -2
  84. package/dist/{chunk-HI53EK3Y.js → chunk-IUYXCTA7.js} +2 -2
  85. package/dist/{chunk-VGRBKEBH.js → chunk-JBWD3J5U.js} +3 -3
  86. package/dist/{chunk-YB3WN6XA.js → chunk-K5QQXVG6.js} +12 -12
  87. package/dist/{chunk-7LCGFUMB.js → chunk-KQAFEZQX.js} +4 -4
  88. package/dist/{chunk-HDT3DMUF.js → chunk-KW5YZELC.js} +2 -2
  89. package/dist/{chunk-DM6SOROF.js → chunk-LIBVANOF.js} +2 -2
  90. package/dist/{chunk-VKUMKVEU.js → chunk-LMMBV7QC.js} +4 -4
  91. package/dist/{chunk-NMOEOQV4.js → chunk-M2DOJBH7.js} +2 -2
  92. package/dist/{chunk-3INLTKTW.js → chunk-M4HRYLOA.js} +2 -2
  93. package/dist/{chunk-YY6PWFUC.js → chunk-M6TP6UYD.js} +3 -3
  94. package/dist/{chunk-BJTFLP3J.js → chunk-MLNXATFG.js} +2 -2
  95. package/dist/{chunk-C7WDWD35.js → chunk-MWURUSRE.js} +5 -5
  96. package/dist/{chunk-WIBWONL4.js → chunk-N74WJ7B2.js} +2 -2
  97. package/dist/{chunk-LCHFINL4.js → chunk-N7FNCE7F.js} +2 -2
  98. package/dist/{chunk-QZK6HG4J.js → chunk-NPLM7AFU.js} +2 -2
  99. package/dist/{chunk-CRJX4OMN.js → chunk-NSP5PIQH.js} +2 -2
  100. package/dist/{chunk-X52SXKVC.js → chunk-P7OVFGMU.js} +2 -2
  101. package/dist/{chunk-2J6BIOVN.js → chunk-PJCVI44H.js} +2 -2
  102. package/dist/{chunk-Q6PYCPHO.js → chunk-Q3PNQYAC.js} +2 -2
  103. package/dist/{chunk-D76AHITY.js → chunk-QS765SBL.js} +2 -2
  104. package/dist/{chunk-KNCR7APE.js → chunk-QTDZ2NYC.js} +7 -7
  105. package/dist/{chunk-YFXRLRKP.js → chunk-S4OZKPBS.js} +7 -11
  106. package/dist/{chunk-YFXRLRKP.js.map → chunk-S4OZKPBS.js.map} +1 -1
  107. package/dist/{chunk-HCPVL6SF.js → chunk-SJTSWG2Z.js} +3 -3
  108. package/dist/{chunk-SA6P2KS3.js → chunk-TEH5MDX5.js} +33 -17
  109. package/dist/chunk-TEH5MDX5.js.map +1 -0
  110. package/dist/{chunk-XFND63OB.js → chunk-TFWJXWL6.js} +2 -2
  111. package/dist/{chunk-SVJ5JVZO.js → chunk-TXKQBQYW.js} +3 -3
  112. package/dist/{chunk-WQFHHJWK.js → chunk-UALXWWGN.js} +2 -2
  113. package/dist/{chunk-3PVKV3XL.js → chunk-UNOAVHV4.js} +2 -2
  114. package/dist/{chunk-FYZXZUGU.js → chunk-UQBOPCDK.js} +2 -2
  115. package/dist/{chunk-SUKPM6DV.js → chunk-UWMZT2TY.js} +47 -4
  116. package/dist/chunk-UWMZT2TY.js.map +1 -0
  117. package/dist/{chunk-OD7ZXCUF.js → chunk-UXGXJUZ5.js} +7 -7
  118. package/dist/{chunk-NH37SP6V.js → chunk-UZVQFGAY.js} +81 -78
  119. package/dist/chunk-UZVQFGAY.js.map +1 -0
  120. package/dist/{chunk-2BY56HE6.js → chunk-VCOMACR6.js} +35 -35
  121. package/dist/{chunk-5FNZ3G6X.js → chunk-VKQI47DJ.js} +4 -4
  122. package/dist/{chunk-MPJDQC4G.js → chunk-WJCXUE2J.js} +2 -2
  123. package/dist/{chunk-C3HRYVGD.js → chunk-WV4UYDP6.js} +2 -2
  124. package/dist/{chunk-E3DL3CAL.js → chunk-WXJC2L66.js} +2 -2
  125. package/dist/chunk-X2KO4FK5.js +40 -0
  126. package/dist/chunk-X2KO4FK5.js.map +1 -0
  127. package/dist/{chunk-O7GNSHFF.js → chunk-XC3H7KON.js} +2 -2
  128. package/dist/{chunk-OOOX5C4X.js → chunk-XL2EE5W3.js} +4 -4
  129. package/dist/{chunk-NUK5XU3P.js → chunk-XTXWR6KQ.js} +25 -10
  130. package/dist/chunk-XTXWR6KQ.js.map +1 -0
  131. package/dist/{chunk-CZVNOTLR.js → chunk-XXR4A33N.js} +2 -2
  132. package/dist/{chunk-2AV2U2SZ.js → chunk-YDIOMDBW.js} +2 -2
  133. package/dist/{chunk-QFTNWDJ6.js → chunk-YECEEJUU.js} +2 -2
  134. package/dist/{chunk-BMG3SAXA.js → chunk-Z5277JWF.js} +3 -3
  135. package/dist/{chunk-SW3WHVKN.js → chunk-ZFNXJEUG.js} +2 -2
  136. package/dist/{chunk-VY6BD5KB.js → chunk-ZMO2S5RT.js} +12 -10
  137. package/dist/chunk-ZMO2S5RT.js.map +1 -0
  138. package/dist/{chunk-KMTMMBEB.js → chunk-ZNRTHYYW.js} +6 -6
  139. package/dist/{chunk-VCBS5GRQ.js → chunk-ZSMA67FV.js} +2 -2
  140. package/dist/cli.js +80 -79
  141. package/dist/coding/export-okf-codegraph.js +9 -9
  142. package/dist/compounding/engine.js +11 -11
  143. package/dist/config.js +14 -14
  144. package/dist/connectors/codex-materialize-runner.js +10 -10
  145. package/dist/connectors/index.js +10 -10
  146. package/dist/consolidation-provenance-check.js +4 -4
  147. package/dist/consolidation-undo.js +2 -2
  148. package/dist/convergence-refresh.js +12 -12
  149. package/dist/corpus-watermark.js +12 -12
  150. package/dist/correction/passive-correction-notifications.d.ts +1 -1
  151. package/dist/correction/passive-correction-notifications.d.ts.map +1 -1
  152. package/dist/dashboard-runtime.js +2 -2
  153. package/dist/deep-recall-http-glue.js +7 -7
  154. package/dist/{entity-canonical-id-migration-2YOLMOFC.js → entity-canonical-id-migration-ZBNRGUNV.js} +3 -3
  155. package/dist/entity-canonical-id-migration-ZBNRGUNV.js.map +1 -0
  156. package/dist/entity-retrieval.js +11 -11
  157. package/dist/explicit-capture.js +2 -2
  158. package/dist/external-wiki-access.js +42 -41
  159. package/dist/extraction.js +16 -16
  160. package/dist/{first-start-migration-QVD22WWS.js → first-start-migration-A6PHIBUQ.js} +4 -4
  161. package/dist/harmonic-retrieval.js +10 -10
  162. package/dist/index.d.ts +1 -0
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +130 -122
  165. package/dist/lcm/engine.js +2 -2
  166. package/dist/lcm/index.js +5 -5
  167. package/dist/local-llm.js +2 -2
  168. package/dist/location/index.js +15 -15
  169. package/dist/location/tagging.d.ts +7 -5
  170. package/dist/location/tagging.d.ts.map +1 -1
  171. package/dist/maintenance/memory-governance.js +10 -10
  172. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  173. package/dist/maintenance/rebuild-memory-projection-runner.js +12 -12
  174. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  175. package/dist/memory-browse-operations.js +42 -41
  176. package/dist/namespaces/migrate.js +11 -11
  177. package/dist/namespaces/storage.js +10 -10
  178. package/dist/offline-sync-file-io.d.ts +15 -0
  179. package/dist/offline-sync-file-io.d.ts.map +1 -1
  180. package/dist/offline-sync-file-io.js +9 -1
  181. package/dist/offline-sync-snapshot-stream.js +4 -4
  182. package/dist/offline-sync-upload-staging.js +2 -2
  183. package/dist/offline-sync.d.ts.map +1 -1
  184. package/dist/offline-sync.js +3 -3
  185. package/dist/operator-doctor-corpus.js +13 -13
  186. package/dist/operator-toolkit.js +24 -24
  187. package/dist/orchestration/maintenance.js +23 -23
  188. package/dist/orchestrator.d.ts +1 -0
  189. package/dist/orchestrator.d.ts.map +1 -1
  190. package/dist/orchestrator.js +109 -108
  191. package/dist/page-versioning.js +2 -2
  192. package/dist/recall-navigation-operations.js +42 -41
  193. package/dist/recall-navigation.js +41 -40
  194. package/dist/resume-bundles.js +15 -15
  195. package/dist/semantic-consolidation.js +15 -15
  196. package/dist/semantic-rule-promotion.js +10 -10
  197. package/dist/semantic-rule-verifier.js +10 -10
  198. package/dist/source-agent-qualifier.js +13 -13
  199. package/dist/standup/build.js +10 -10
  200. package/dist/storage/entity-canonical-id-migration-adapter.d.ts +1 -0
  201. package/dist/storage/entity-canonical-id-migration-adapter.d.ts.map +1 -1
  202. package/dist/storage/entity-canonical-id-migration.d.ts +7 -0
  203. package/dist/storage/entity-canonical-id-migration.d.ts.map +1 -1
  204. package/dist/storage/entity-canonical-id-references.d.ts +2 -0
  205. package/dist/storage/entity-canonical-id-references.d.ts.map +1 -1
  206. package/dist/storage/entity-migration-completion-cache.d.ts +46 -0
  207. package/dist/storage/entity-migration-completion-cache.d.ts.map +1 -0
  208. package/dist/storage/entity-store.d.ts +1 -8
  209. package/dist/storage/entity-store.d.ts.map +1 -1
  210. package/dist/storage/memory-read-store.d.ts +3 -2
  211. package/dist/storage/memory-read-store.d.ts.map +1 -1
  212. package/dist/storage/windowed-memory-read.d.ts +6 -0
  213. package/dist/storage/windowed-memory-read.d.ts.map +1 -1
  214. package/dist/storage.d.ts +2 -0
  215. package/dist/storage.d.ts.map +1 -1
  216. package/dist/storage.js +9 -9
  217. package/dist/summarizer.js +3 -3
  218. package/dist/support-passport/index.js +44 -43
  219. package/dist/transfer/capsule-export.js +2 -2
  220. package/dist/transfer/capsule-import.js +4 -4
  221. package/dist/transfer/export-okf.js +10 -10
  222. package/dist/verified-recall.js +10 -10
  223. package/dist/who-knows-cli.js +11 -11
  224. package/dist/who-knows.js +10 -10
  225. package/package.json +2 -2
  226. package/src/access-http-briefing.ts +4 -0
  227. package/src/access-http.test.ts +40 -11
  228. package/src/access-http.ts +6 -0
  229. package/src/access-observe-write-category.ts +1 -1
  230. package/src/access-observe-write-surface.ts +24 -19
  231. package/src/access-operations-batch.ts +18 -2
  232. package/src/access-service.ts +5 -0
  233. package/src/briefing-abort.test.ts +173 -0
  234. package/src/briefing-deadline.test.ts +84 -0
  235. package/src/briefing-deadline.ts +33 -0
  236. package/src/briefing-window-abort.test.ts +47 -0
  237. package/src/briefing-window.ts +33 -4
  238. package/src/briefing.ts +23 -16
  239. package/src/correction/passive-correction-notifications-abort.test.ts +42 -0
  240. package/src/correction/passive-correction-notifications.ts +4 -0
  241. package/src/entity-lazy-compatibility.test.ts +229 -0
  242. package/src/entity-migration-completion-notification.test.ts +148 -0
  243. package/src/index.ts +1 -1
  244. package/src/location/tagging.ts +14 -12
  245. package/src/offline-sync-file-io.ts +61 -2
  246. package/src/offline-sync.test.ts +313 -20
  247. package/src/offline-sync.ts +43 -21
  248. package/src/orchestrator-init.test.ts +49 -1
  249. package/src/orchestrator.ts +9 -8
  250. package/src/storage/entity-canonical-id-migration-adapter.ts +16 -1
  251. package/src/storage/entity-canonical-id-migration.ts +17 -8
  252. package/src/storage/entity-canonical-id-references.ts +24 -0
  253. package/src/storage/entity-migration-completion-cache.nofollow.test.ts +223 -0
  254. package/src/storage/entity-migration-completion-cache.ts +153 -0
  255. package/src/storage/entity-store.ts +58 -86
  256. package/src/storage/memory-read-store.ts +9 -3
  257. package/src/storage/windowed-memory-read.ts +8 -0
  258. package/src/storage-startup-nonblocking-migration.test.ts +183 -0
  259. package/src/storage.ts +7 -2
  260. package/src/testing/subjects/entity-migration-completion-cache.test.ts +90 -0
  261. package/dist/chunk-3NYIXVCT.js.map +0 -1
  262. package/dist/chunk-6W3QH3QW.js.map +0 -1
  263. package/dist/chunk-7XFQSQYS.js.map +0 -1
  264. package/dist/chunk-FRXS6SC7.js.map +0 -1
  265. package/dist/chunk-LWRIGKFM.js.map +0 -1
  266. package/dist/chunk-N6EM7ESC.js.map +0 -1
  267. package/dist/chunk-NH37SP6V.js.map +0 -1
  268. package/dist/chunk-NUK5XU3P.js.map +0 -1
  269. package/dist/chunk-O4CA53UY.js.map +0 -1
  270. package/dist/chunk-RZDDNH63.js.map +0 -1
  271. package/dist/chunk-SA6P2KS3.js.map +0 -1
  272. package/dist/chunk-SUKPM6DV.js.map +0 -1
  273. package/dist/chunk-VY6BD5KB.js.map +0 -1
  274. /package/dist/{auto-sync-BNCBMU6H.js.map → auto-sync-UQQ6YJSB.js.map} +0 -0
  275. /package/dist/{entity-canonical-id-migration-2YOLMOFC.js.map → briefing-deadline.js.map} +0 -0
  276. /package/dist/{capsule-merge-RNQUP2VL.js.map → capsule-merge-D4BTIJGK.js.map} +0 -0
  277. /package/dist/{chunk-ESDOQEJM.js.map → chunk-2AKIVSHP.js.map} +0 -0
  278. /package/dist/{chunk-MCS4LIXP.js.map → chunk-43TUWQNR.js.map} +0 -0
  279. /package/dist/{chunk-2NLCDNGA.js.map → chunk-564YP3DW.js.map} +0 -0
  280. /package/dist/{chunk-PBWJVRKE.js.map → chunk-5FUDSK6Z.js.map} +0 -0
  281. /package/dist/{chunk-V4GPFCJ7.js.map → chunk-5G53JSRO.js.map} +0 -0
  282. /package/dist/{chunk-WJCAAVZX.js.map → chunk-5X2H3X4J.js.map} +0 -0
  283. /package/dist/{chunk-CPBYKOTC.js.map → chunk-6ZQX3R66.js.map} +0 -0
  284. /package/dist/{chunk-AF4UIHON.js.map → chunk-74AY3S7U.js.map} +0 -0
  285. /package/dist/{chunk-XSJL62LE.js.map → chunk-7J6A5MV2.js.map} +0 -0
  286. /package/dist/{chunk-A3WXV7YU.js.map → chunk-7SAE6T36.js.map} +0 -0
  287. /package/dist/{chunk-BWF3KNSQ.js.map → chunk-7YVER7ZO.js.map} +0 -0
  288. /package/dist/{chunk-5IDQVE4U.js.map → chunk-A3UFV4K3.js.map} +0 -0
  289. /package/dist/{chunk-6TIVVOVU.js.map → chunk-BNJAVRNJ.js.map} +0 -0
  290. /package/dist/{chunk-CMOYD5CA.js.map → chunk-CCL2OXFO.js.map} +0 -0
  291. /package/dist/{chunk-FOKTW6GY.js.map → chunk-EWBXMGXR.js.map} +0 -0
  292. /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
  293. /package/dist/{chunk-E47UQBYW.js.map → chunk-GXVXBYRA.js.map} +0 -0
  294. /package/dist/{chunk-AGCEJDG2.js.map → chunk-HPNXS6W6.js.map} +0 -0
  295. /package/dist/{chunk-N5PISU26.js.map → chunk-IN6U2BS5.js.map} +0 -0
  296. /package/dist/{chunk-HI53EK3Y.js.map → chunk-IUYXCTA7.js.map} +0 -0
  297. /package/dist/{chunk-VGRBKEBH.js.map → chunk-JBWD3J5U.js.map} +0 -0
  298. /package/dist/{chunk-YB3WN6XA.js.map → chunk-K5QQXVG6.js.map} +0 -0
  299. /package/dist/{chunk-7LCGFUMB.js.map → chunk-KQAFEZQX.js.map} +0 -0
  300. /package/dist/{chunk-HDT3DMUF.js.map → chunk-KW5YZELC.js.map} +0 -0
  301. /package/dist/{chunk-DM6SOROF.js.map → chunk-LIBVANOF.js.map} +0 -0
  302. /package/dist/{chunk-VKUMKVEU.js.map → chunk-LMMBV7QC.js.map} +0 -0
  303. /package/dist/{chunk-NMOEOQV4.js.map → chunk-M2DOJBH7.js.map} +0 -0
  304. /package/dist/{chunk-3INLTKTW.js.map → chunk-M4HRYLOA.js.map} +0 -0
  305. /package/dist/{chunk-YY6PWFUC.js.map → chunk-M6TP6UYD.js.map} +0 -0
  306. /package/dist/{chunk-BJTFLP3J.js.map → chunk-MLNXATFG.js.map} +0 -0
  307. /package/dist/{chunk-C7WDWD35.js.map → chunk-MWURUSRE.js.map} +0 -0
  308. /package/dist/{chunk-WIBWONL4.js.map → chunk-N74WJ7B2.js.map} +0 -0
  309. /package/dist/{chunk-LCHFINL4.js.map → chunk-N7FNCE7F.js.map} +0 -0
  310. /package/dist/{chunk-QZK6HG4J.js.map → chunk-NPLM7AFU.js.map} +0 -0
  311. /package/dist/{chunk-CRJX4OMN.js.map → chunk-NSP5PIQH.js.map} +0 -0
  312. /package/dist/{chunk-X52SXKVC.js.map → chunk-P7OVFGMU.js.map} +0 -0
  313. /package/dist/{chunk-2J6BIOVN.js.map → chunk-PJCVI44H.js.map} +0 -0
  314. /package/dist/{chunk-Q6PYCPHO.js.map → chunk-Q3PNQYAC.js.map} +0 -0
  315. /package/dist/{chunk-D76AHITY.js.map → chunk-QS765SBL.js.map} +0 -0
  316. /package/dist/{chunk-KNCR7APE.js.map → chunk-QTDZ2NYC.js.map} +0 -0
  317. /package/dist/{chunk-HCPVL6SF.js.map → chunk-SJTSWG2Z.js.map} +0 -0
  318. /package/dist/{chunk-XFND63OB.js.map → chunk-TFWJXWL6.js.map} +0 -0
  319. /package/dist/{chunk-SVJ5JVZO.js.map → chunk-TXKQBQYW.js.map} +0 -0
  320. /package/dist/{chunk-WQFHHJWK.js.map → chunk-UALXWWGN.js.map} +0 -0
  321. /package/dist/{chunk-3PVKV3XL.js.map → chunk-UNOAVHV4.js.map} +0 -0
  322. /package/dist/{chunk-FYZXZUGU.js.map → chunk-UQBOPCDK.js.map} +0 -0
  323. /package/dist/{chunk-OD7ZXCUF.js.map → chunk-UXGXJUZ5.js.map} +0 -0
  324. /package/dist/{chunk-2BY56HE6.js.map → chunk-VCOMACR6.js.map} +0 -0
  325. /package/dist/{chunk-5FNZ3G6X.js.map → chunk-VKQI47DJ.js.map} +0 -0
  326. /package/dist/{chunk-MPJDQC4G.js.map → chunk-WJCXUE2J.js.map} +0 -0
  327. /package/dist/{chunk-C3HRYVGD.js.map → chunk-WV4UYDP6.js.map} +0 -0
  328. /package/dist/{chunk-E3DL3CAL.js.map → chunk-WXJC2L66.js.map} +0 -0
  329. /package/dist/{chunk-O7GNSHFF.js.map → chunk-XC3H7KON.js.map} +0 -0
  330. /package/dist/{chunk-OOOX5C4X.js.map → chunk-XL2EE5W3.js.map} +0 -0
  331. /package/dist/{chunk-CZVNOTLR.js.map → chunk-XXR4A33N.js.map} +0 -0
  332. /package/dist/{chunk-2AV2U2SZ.js.map → chunk-YDIOMDBW.js.map} +0 -0
  333. /package/dist/{chunk-QFTNWDJ6.js.map → chunk-YECEEJUU.js.map} +0 -0
  334. /package/dist/{chunk-BMG3SAXA.js.map → chunk-Z5277JWF.js.map} +0 -0
  335. /package/dist/{chunk-SW3WHVKN.js.map → chunk-ZFNXJEUG.js.map} +0 -0
  336. /package/dist/{chunk-KMTMMBEB.js.map → chunk-ZNRTHYYW.js.map} +0 -0
  337. /package/dist/{chunk-VCBS5GRQ.js.map → chunk-ZSMA67FV.js.map} +0 -0
  338. /package/dist/{first-start-migration-QVD22WWS.js.map → first-start-migration-A6PHIBUQ.js.map} +0 -0
@@ -81,6 +81,7 @@ function assertSafeEntityId(entityId) {
81
81
  // src/storage/entity-canonical-id-references.ts
82
82
  import { statSync } from "fs";
83
83
  import path2 from "path";
84
+ import { z } from "zod";
84
85
  import {
85
86
  closeSync,
86
87
  constants,
@@ -141,6 +142,22 @@ function readJournalFileNoFollow(statePath) {
141
142
  closeSync(fd);
142
143
  }
143
144
  }
145
+ var CompletedJournalAttestationSchema = z.object({
146
+ version: z.literal(1),
147
+ complete: z.literal(true),
148
+ completionFingerprint: z.string()
149
+ });
150
+ async function entityCanonicalIdMigrationCompleted(stateDir, readFingerprint) {
151
+ const result = readJournalFileNoFollow(path2.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));
152
+ if (result.kind !== "ok") return false;
153
+ try {
154
+ const parsed = CompletedJournalAttestationSchema.safeParse(JSON.parse(result.raw));
155
+ if (!parsed.success) return false;
156
+ return parsed.data.completionFingerprint === await readFingerprint();
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
144
161
  async function appendCanonicalizedTombstone(stateDir, input, currentIds, append, revoke, label) {
145
162
  let refIds = currentIds();
146
163
  let identity = canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, refIds);
@@ -398,6 +415,7 @@ export {
398
415
  withRawEntityPageMutation,
399
416
  assertSafeEntityId,
400
417
  ENTITY_CANONICAL_ID_MIGRATION_FILE,
418
+ entityCanonicalIdMigrationCompleted,
401
419
  appendCanonicalizedTombstone,
402
420
  memoizedJournalCompletion,
403
421
  HistoricalEntityCanonicalIdCache,
@@ -416,4 +434,4 @@ export {
416
434
  repairContentAfterJournalMove,
417
435
  repairContentAfterJournalMoveSync
418
436
  };
419
- //# sourceMappingURL=chunk-LWRIGKFM.js.map
437
+ //# sourceMappingURL=chunk-A5L5KGDI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/entity-canonical-id-lock.ts","../src/storage/entity-id-safety.ts","../src/storage/entity-canonical-id-references.ts"],"sourcesContent":["import { appendFileSync, mkdirSync, realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { invalidateForScope } from \"../memory-cache.js\";\nimport { serializeMutations, withHeldFileLock } from \"../utils/serialize-mutations.js\";\n\nconst ENTITY_CANONICAL_ID_MUTATION_LOCK_STALE_MS = 60_000;\nconst ENTITY_CANONICAL_ID_MUTATION_LOCK_MAX_WAIT_MS = 300_000;\n\nexport function isEntityPagePath(baseDir: string, filePath: string): boolean {\n if (path.extname(filePath) !== \".md\") return false;\n const parentDir = path.dirname(path.resolve(filePath));\n const entitiesDir = path.resolve(baseDir, \"entities\");\n if (parentDir === entitiesDir) return true;\n try {\n return realpathSync(parentDir) === path.join(realpathSync(baseDir), \"entities\");\n } catch {\n return false;\n }\n}\n\nfunction recordRawEntityMutation(baseDir: string, stateDir: string): void {\n invalidateForScope(baseDir, \"entity-write\");\n mkdirSync(stateDir, { recursive: true });\n appendFileSync(path.join(stateDir, \".entity-mutation-version.log\"), \"x\");\n}\n\nexport function withEntityCanonicalMutationLock<T>(\n stateDir: string,\n task: (refreshLock: () => Promise<boolean>) => Promise<T>,\n): Promise<T> {\n const lockPath = path.join(stateDir, \"entity-canonical-id-mutation.lock\");\n return serializeMutations(lockPath, () =>\n withHeldFileLock(\n lockPath,\n {\n staleMs: ENTITY_CANONICAL_ID_MUTATION_LOCK_STALE_MS,\n maxWaitMs: ENTITY_CANONICAL_ID_MUTATION_LOCK_MAX_WAIT_MS,\n },\n async (acquired, lock) => {\n if (!acquired) throw new Error(\"Timed out waiting for entity mutation lock.\");\n return task(() => lock.refresh());\n },\n ),\n );\n}\n\nexport async function withRawEntityPageMutation<T>(\n baseDir: string,\n filePath: string,\n task: (refreshLock: () => Promise<boolean>) => Promise<T>,\n): Promise<T> {\n if (!isEntityPagePath(baseDir, filePath)) {\n return task(async () => true);\n }\n const stateDir = path.join(baseDir, \"state\");\n return withEntityCanonicalMutationLock(stateDir, async (refreshLock) => {\n try {\n return await task(refreshLock);\n } finally {\n recordRawEntityMutation(baseDir, stateDir);\n }\n });\n}\n","const UNSAFE_ENTITY_ID_PATTERN = /[\\/\\\\\\p{Cc}\\p{Zl}\\p{Zp}]/u;\n\nexport function assertSafeEntityId(entityId: string): void {\n if (UNSAFE_ENTITY_ID_PATTERN.test(entityId)) {\n throw new Error(\"Refusing unsafe entity id containing a path separator or control character.\");\n }\n}\n","import { statSync } from \"node:fs\";\n/**\n * Write-boundary surface of the entity canonical-id migration (issue #2213).\n *\n * The migration itself (entity-canonical-id-migration.ts) renames legacy\n * entity files and rewrites references ONCE, to convergence, then retires.\n * Everything here exists so nothing can re-introduce a legacy reference\n * afterwards without the migration having to rescan the corpus:\n *\n * - store-mediated writes canonicalize the caller-supplied `entityRef`\n * ({@link canonicalizeEntityRefOption});\n * - bulk writers that persist raw record bytes (capsule import/merge)\n * canonicalize the frontmatter line ({@link canonicalizeEntityRefFrontmatter});\n * - raw-byte writers that CANNOT parse what they write (offline sync,\n * consolidation-undo, governance restores) request one bounded\n * reconciliation pass instead ({@link requestEntityCanonicalIdReconcile}).\n */\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport {\n closeSync,\n constants,\n fstatSync,\n lstatSync,\n realpathSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { log } from \"../logger.js\";\nimport { isErrnoCode } from \"../utils/errno.js\";\nimport { RECALL_FALLBACK_DIRS } from \"../utils/category-dir.js\";\nimport { withEntityCanonicalMutationLock } from \"./entity-canonical-id-lock.js\";\nimport { assertSafeEntityId } from \"./entity-id-safety.js\";\nimport { normalizeSupersessionKey } from \"../temporal-supersession.js\";\n\nexport const ENTITY_CANONICAL_ID_MIGRATION_FILE = \"entity-canonical-id-migration-v1.json\";\n\n/**\n * Parse a journal document into a mapping table. A document without a valid\n * `mappings` object is a LEGITIMATELY empty table; an unreadable/unparsable\n * document THROWS so callers can distinguish \"empty\" from \"failed\".\n */\nfunction parseJournalMappings(raw: string): Readonly<Record<string, string>> {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed) || !(\"mappings\" in parsed)) return {};\n const mappings = parsed.mappings;\n if (!mappings || typeof mappings !== \"object\" || Array.isArray(mappings)) return {};\n // Null prototype: journal-supplied ids like `constructor` must be own\n // entries, never collide with Object.prototype (Codex P2, round 20).\n const cleaned: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [legacyId, canonicalId] of Object.entries(mappings)) {\n if (legacyId.length > 0 && typeof canonicalId === \"string\" && canonicalId.length > 0) {\n assertSafeEntityId(legacyId);\n assertSafeEntityId(canonicalId);\n cleaned[legacyId] = canonicalId;\n }\n }\n return cleaned;\n}\n\n/** Whether the journal says its migration completed. Throws like the mapping parser. */\nfunction parseJournalComplete(raw: string): boolean {\n // SAFETY: JSON.parse output is unknown; the shape is validated on access.\n const parsed = JSON.parse(raw) as { complete?: unknown };\n return parsed !== null && parsed.complete === true;\n}\n\ntype JournalRead =\n | { kind: \"ok\"; raw: string; key: string }\n | { kind: \"missing\" }\n | { kind: \"refused\" }\n | { kind: \"error\" };\n\n/**\n * Open the journal WITHOUT following symlinks and read content + identity\n * from the same opened inode (repo rule: reject symlink traversal from\n * memory directories). O_NOFOLLOW makes the open refuse a symlinked FINAL\n * component (ELOOP); the parent `state/` directory is verified AFTER the\n * open, together with a path↔fd identity pairing, so a parent swapped\n * around the open cannot hold: a swap still in place fails the parent\n * lstat, and a swap reverted fails the dev/ino pairing against the real\n * journal. Platforms without O_NOFOLLOW get the same post-open checks.\n */\nfunction readJournalFileNoFollow(statePath: string): JournalRead {\n let fd: number;\n try {\n fd = openSync(statePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n } catch (error) {\n if (isErrnoCode(error, \"ENOENT\")) return { kind: \"missing\" };\n if (isErrnoCode(error, \"ELOOP\")) return { kind: \"refused\" };\n return { kind: \"error\" };\n }\n try {\n const s = fstatSync(fd);\n if (!s.isFile()) return { kind: \"refused\" };\n const parent = lstatSync(path.dirname(statePath));\n if (parent.isSymbolicLink() || !parent.isDirectory()) return { kind: \"refused\" };\n const l = lstatSync(statePath);\n if (l.isSymbolicLink() || l.dev !== s.dev || l.ino !== s.ino) return { kind: \"refused\" };\n return {\n kind: \"ok\",\n raw: readFileSync(fd, \"utf-8\"),\n key: `${s.dev}:${s.ino}:${s.mtimeMs}:${s.ctimeMs}:${s.size}`,\n };\n } catch {\n return { kind: \"error\" };\n } finally {\n closeSync(fd);\n }\n}\n\n/** The journal fields completion attestation needs; extra journal fields are ignored. */\nconst CompletedJournalAttestationSchema = z.object({\n version: z.literal(1),\n complete: z.literal(true),\n completionFingerprint: z.string(),\n});\n\n/** Skip compatibility scans only when journal completion attests to the live inputs. */\nexport async function entityCanonicalIdMigrationCompleted(\n stateDir: string,\n readFingerprint: () => Promise<string>,\n): Promise<boolean> {\n const result = readJournalFileNoFollow(path.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));\n if (result.kind !== \"ok\") return false;\n try {\n const parsed = CompletedJournalAttestationSchema.safeParse(JSON.parse(result.raw));\n if (!parsed.success) return false;\n return parsed.data.completionFingerprint === await readFingerprint();\n } catch {\n return false;\n }\n}\n\nexport function loadHistoricalEntityCanonicalIds(stateDir: string): Readonly<Record<string, string>> {\n const result = readJournalFileNoFollow(path.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));\n if (result.kind !== \"ok\") return {};\n try {\n return parseJournalMappings(result.raw);\n } catch {\n return {};\n }\n}\n\n/**\n * Append a tombstone with its identity canonicalized against the CURRENT\n * journal, then recheck: a peer publishing a mapping inside the\n * resolve-to-append window would leave the guard under the legacy id while\n * lookups canonicalize. Each identity change appends the replacement FIRST\n * (AGENTS.md §14 — the retired fact must never be without an active guard),\n * then revokes the superseded one — a park makes the prior canonical\n * claimant a distinct entity, and a stale keyed guard under it would\n * suppress that entity's facts. When the journal will not settle, one final\n * replacement runs under the entity MUTATION lock (parks publish under it).\n */\nexport async function appendCanonicalizedTombstone(\n stateDir: string,\n input: { entityRef?: string; supersessionKey?: string },\n currentIds: () => Readonly<Record<string, string>>,\n append: (identity: TombstoneIdentity) => Promise<string | null>,\n revoke: (tombstoneId: string) => Promise<unknown>,\n label: string,\n): Promise<string | null> {\n let refIds = currentIds();\n let identity = canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, refIds);\n let result = await append(identity);\n const replaceIfChanged = async (next: TombstoneIdentity): Promise<boolean> => {\n if (next.entityRef === identity.entityRef && next.supersessionKey === identity.supersessionKey) {\n return false;\n }\n identity = next;\n const superseded = result;\n result = await append(next);\n if (superseded !== null) {\n try {\n await revoke(superseded);\n } catch (err) {\n log.warn(`failed to revoke superseded tombstone ${superseded} for ${label}: ${err}`);\n }\n }\n return true;\n };\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = currentIds();\n if (fresh === refIds) return result;\n refIds = fresh;\n if (!(await replaceIfChanged(canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, fresh)))) {\n return result;\n }\n }\n await withEntityCanonicalMutationLock(stateDir, async () => {\n await replaceIfChanged(canonicalizeTombstoneIdentity(input.entityRef, input.supersessionKey, currentIds()));\n });\n return result;\n}\n\n/**\n * Journal mapping table keyed by the journal FILE's identity, so a long-lived\n * StorageManager never canonicalizes against a stale snapshot after ANY other\n * writer changes the journal — a peer process completing a migration, or\n * `pruneBlocked()` parking a contested mapping (which rewrites the journal\n * without bumping any shared version). `writeState` publishes via\n * temp-file-plus-rename, so every journal write swaps the inode and the key\n * always moves — the identity is taken from the fstat of the SAME opened\n * inode the content is read from (no stat→read window). Reload cost is one\n * open per lookup and one journal parse per actual change.\n *\n * Failure semantics: last-known data is served ONLY for the SAME state dir\n * (module-level instances can face several stores — another store's table\n * must never leak in), and a failed read/parse never commits the journal's\n * identity, so the next lookup retries instead of caching an empty table\n * under a valid key.\n */\n\n/** Journal lookup result: mapping table plus its completion flag. */\nexport type HistoricalEntityIdsEntry = {\n mappings: Readonly<Record<string, string>>;\n complete: boolean;\n};\n\n\n\n/**\n * Memoized journal-completion view keyed on the journal file's stat identity.\n * entityList consults completion once per listed entity; without this each\n * consult re-opens and re-reads the journal (quadratic I/O on large corpora).\n */\nexport function memoizedJournalCompletion(\n cache: HistoricalEntityCanonicalIdCache,\n stateDir: () => string,\n): () => boolean {\n let memo: { key: string; complete: boolean } | undefined;\n return (): boolean => {\n let key = \"missing\";\n try {\n const journalPath = path.join(stateDir(), ENTITY_CANONICAL_ID_MIGRATION_FILE);\n const j = statSync(journalPath);\n key = `${j.dev}:${j.ino}:${j.mtimeMs}:${j.ctimeMs}:${j.size}`;\n } catch {\n key = \"missing\";\n }\n if (memo && memo.key === key) return memo.complete;\n const entry = cache.getEntry(stateDir());\n memo = { key, complete: entry.complete };\n return memo.complete;\n };\n}\n\nexport class HistoricalEntityCanonicalIdCache {\n private mappings: Readonly<Record<string, string>> = {};\n private complete = false;\n private key: string | null = null;\n private stateDir: string | null = null;\n\n get(stateDir: string): Readonly<Record<string, string>> {\n return this.getEntry(stateDir).mappings;\n }\n\n\n /** Table plus the journal's completion flag, cached under one identity. */\n getEntry(stateDir: string): HistoricalEntityIdsEntry {\n const lastKnownMappings = this.stateDir === stateDir ? this.mappings : {};\n const lastKnownComplete = this.stateDir === stateDir ? this.complete : false;\n const lastKnown: HistoricalEntityIdsEntry = { mappings: lastKnownMappings, complete: lastKnownComplete };\n const result = readJournalFileNoFollow(path.join(stateDir, ENTITY_CANONICAL_ID_MIGRATION_FILE));\n if (result.kind === \"refused\") {\n // Symlinked/non-regular journal: never follow it, never adopt its\n // identity — serve this store's last-known table. If it later becomes\n // a regular file its identity differs from the stored key and reloads.\n log.warn(\"ignoring non-regular entity canonical-id journal (symlink refused)\");\n return lastKnown;\n }\n if (result.kind === \"error\") {\n // A TRANSIENT open/read failure (EACCES/EIO) must not dump a valid\n // table for {}: a write during the outage would skip canonicalization\n // AND its post-write identity check would compare equal. Serve this\n // store's last-known table; only a genuine ENOENT means \"no journal\".\n return lastKnown;\n }\n const key = result.kind === \"missing\" ? \"missing\" : result.key;\n if (key !== this.key || stateDir !== this.stateDir) {\n let table: Readonly<Record<string, string>> = {};\n let complete = false;\n if (result.kind === \"ok\") {\n try {\n table = parseJournalMappings(result.raw);\n complete = parseJournalComplete(result.raw);\n } catch {\n // Parse failed under a VALID identity: do not commit the key —\n // the next lookup retries instead of pinning an empty table.\n return lastKnown;\n }\n }\n this.mappings = table;\n this.complete = complete;\n this.key = key;\n this.stateDir = stateDir;\n }\n return { mappings: this.mappings, complete: this.complete };\n }\n}\n\nexport function resolveHistoricalEntityCanonicalId(\n normalized: string,\n mappings: Readonly<Record<string, string>>,\n): string {\n let current = normalized;\n const seen = new Set<string>();\n while (!seen.has(current)) {\n seen.add(current);\n // Own properties only: an unmapped id like `constructor` must not read\n // Object.prototype and return a function (Codex P2, round 20).\n const next = Object.hasOwn(mappings, current) ? mappings[current] : undefined;\n if (!next || next === current) break;\n current = next;\n }\n return current;\n}\n\n/**\n * Canonicalize the `entityRef` a memory-write caller supplied (issue #2213).\n *\n * Extraction and capture callers pass whatever id the LLM or user produced,\n * which can name a legacy id this migration already renamed. Resolving at the\n * WRITE boundary means store-mediated writes can never re-introduce legacy\n * references — which is what let the completed migration retire its recurring\n * full-corpus reference rewrite. It also keeps write-time tombstone lookups on\n * the same id space as migrated tombstones. Unknown ids pass through verbatim.\n */\nexport function canonicalizeEntityRefOption<T extends { entityRef?: string }>(\n options: T,\n mappings: Readonly<Record<string, string>>,\n): T {\n // Non-strings (absent, or a JS caller's null/junk) pass through untouched:\n // this boundary canonicalizes ids, it does not take over input validation\n // the write path never performed — serialization already drops falsy refs.\n if (typeof options.entityRef !== \"string\") return options;\n return { ...options, entityRef: resolveHistoricalEntityCanonicalId(options.entityRef, mappings) };\n}\n\n/**\n * Canonicalize the effective `entityRef:` line inside a raw memory record's\n * leading frontmatter block (issue #2213). Bulk writers that persist record\n * bytes verbatim — capsule import/merge — are a write boundary too: a capsule\n * can carry pre-migration memories whose refs the target's completed journal\n * already renamed, and no later reconciliation pass exists to absorb them.\n *\n * Line selection mirrors the frontmatter parser and the migration's own\n * serializer: the LAST `entityRef` key wins (indentation tolerated), its\n * indent is preserved, and CRLF records keep their line endings. The closing\n * delimiter must be a standalone `---` line. Non-frontmatter content, records\n * without an `entityRef` line, and ids the journal does not map all pass\n * through byte-identical.\n */\nexport function canonicalizeEntityRefFrontmatter(\n content: string,\n mappings: Readonly<Record<string, string>>,\n): string {\n if (Object.keys(mappings).length === 0) return content;\n const loc = locateEntityRefLine(content);\n if (loc === null) return content;\n const canonical = resolveHistoricalEntityCanonicalId(loc.value, mappings);\n if (canonical === loc.value) return content;\n const line = loc.lines[loc.index]!;\n const indent = /^\\s*/.exec(line)?.[0] ?? \"\";\n loc.lines[loc.index] = `${indent}entityRef: ${canonical}${line.endsWith(\"\\r\") ? \"\\r\" : \"\"}`;\n return loc.lines.join(\"\\n\") + content.slice(loc.closeIndex);\n}\n\n/** The raw `entityRef` value in a record's leading frontmatter, or null. */\nexport function readEntityRefFromFrontmatter(content: string): string | null {\n return locateEntityRefLine(content)?.value ?? null;\n}\n\nfunction locateEntityRefLine(\n content: string,\n): { lines: string[]; index: number; value: string; closeIndex: number } | null {\n if (!/^---\\r?\\n/.test(content)) return null;\n const close = /\\r?\\n---(?:\\r?\\n|$)/g;\n close.lastIndex = content.indexOf(\"\\n\") + 1;\n const closeMatch = close.exec(content);\n if (!closeMatch) return null;\n const lines = content.slice(0, closeMatch.index).split(\"\\n\");\n let index = -1;\n for (let i = 1; i < lines.length; i += 1) {\n if (/^\\s*entityRef\\s*:/.test(lines[i] ?? \"\")) index = i;\n }\n if (index === -1) return null;\n const line = lines[index]!;\n const value = line.slice(line.indexOf(\":\") + 1).replace(/\\r$/, \"\").trim();\n if (value.length === 0) return null;\n return { lines, index, value, closeIndex: closeMatch.index };\n}\n\n/**\n * Reconcile-pending marker (issue #2213). Raw-byte memory writers that CANNOT\n * canonicalize inline — offline-sync file replication (opaque, possibly\n * encrypted buffers), consolidation-undo restores, governance-run restores —\n * touch this marker instead. The next migration invocation honors it by\n * running ONE bounded reference-reconciliation pass over the completed\n * journal's retained mappings, then clears it. This replaces the retired\n * every-run corpus rewrite with a signal that fires only when a raw writer\n * actually landed unvetted bytes.\n */\nexport const ENTITY_CANONICAL_ID_RECONCILE_MARKER = \"entity-canonical-id-reconcile.pending\";\n/** The generation a migration run renamed aside for consumption; a crash can strand it. */\nexport const ENTITY_CANONICAL_ID_RECONCILE_CONSUMING_MARKER = `${ENTITY_CANONICAL_ID_RECONCILE_MARKER}.consuming`;\n\nexport function requestEntityCanonicalIdReconcileSync(stateDir: string): void {\n const markerPath = path.join(stateDir, ENTITY_CANONICAL_ID_RECONCILE_MARKER);\n const temporary = `${markerPath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n // Never write THROUGH a symlinked marker OR a symlinked state dir (repo\n // rule: reject symlink traversal from memory directories). The parent is\n // lstat-verified as a real directory — direct restore/import callers can\n // reach this helper without validateRoots() — and temp-file-plus-rename\n // handles the final component: rename() replaces a planted link ITSELF\n // rather than following it, with no O_NOFOLLOW dependency.\n const parent = lstatSync(stateDir);\n if (parent.isSymbolicLink() || !parent.isDirectory()) {\n log.warn(`refusing to write entity canonical-id reconcile marker: ${stateDir} is not a real directory`);\n return;\n }\n const parentRealPath = realpathSync(stateDir);\n writeFileSync(temporary, `${new Date().toISOString()}\\n`, { mode: 0o600 });\n // Revalidate the parent between the temp write and publication (Codex\n // P2, round 20): a state-dir swapped for a symlink after the check above\n // would have landed the temp file through the link. Node has no openat,\n // so the residual window is the realpath→rename gap — this recheck\n // reduces check-then-use to the platform primitive's own atomicity.\n const recheck = lstatSync(stateDir);\n if (recheck.isSymbolicLink() || !recheck.isDirectory() || realpathSync(stateDir) !== parentRealPath) {\n rmSync(temporary, { force: true });\n log.warn(`refusing to publish entity canonical-id reconcile marker: ${stateDir} changed during write`);\n return;\n }\n renameSync(temporary, markerPath);\n } catch (error) {\n rmSync(temporary, { force: true });\n // Best effort by design: a marker failure must not fail the restore/sync\n // that requested it (AGENTS.md §4). The reference stays legacy-but-readable\n // until the next mapping change.\n log.warn(`could not request entity canonical-id reconcile: ${error}`);\n }\n}\n\nexport async function requestEntityCanonicalIdReconcile(stateDir: string): Promise<void> {\n requestEntityCanonicalIdReconcileSync(stateDir);\n}\n\n/**\n * Post-persist TOCTOU guard (issue #2213). A writer resolves `entityRef`\n * against one journal generation, then awaits (snapshots, locks, fsyncs)\n * before its bytes land — a peer migration can publish AND finish its final\n * reference scan inside that window, leaving the just-written file behind.\n * Callers pass the mapping table captured at resolve time plus a fresh cache\n * read taken AFTER the write: the cache returns the identical object while\n * the journal file is unchanged, so an identity mismatch means the journal\n * moved mid-write and one bounded reconcile pass is requested.\n */\nexport function reconcileIfJournalMovedSync(\n stateDir: string,\n idsAtResolve: Readonly<Record<string, string>>,\n idsAfterWrite: Readonly<Record<string, string>>,\n): void {\n if (idsAtResolve === idsAfterWrite) return;\n requestEntityCanonicalIdReconcileSync(stateDir);\n}\n\nexport async function reconcileIfJournalMoved(\n stateDir: string,\n idsAtResolve: Readonly<Record<string, string>>,\n idsAfterWrite: Readonly<Record<string, string>>,\n): Promise<void> {\n reconcileIfJournalMovedSync(stateDir, idsAtResolve, idsAfterWrite);\n}\n\n/**\n * Classify a raw write target for entity-reference handling (issue #2213):\n * - `\"memory\"` — hot recall / cold / archive record whose FRONTMATTER\n * `entityRef` the writer must canonicalize at the write (and repair after).\n * - `\"entity\"` — an `entities/` page. Its migrated surface is relationship\n * TARGETS in the body, which only `rewriteRelationshipTargets` understands;\n * raw writers persist bytes faithfully and request the bounded reconcile\n * pass instead of attempting a frontmatter rewrite.\n * - `\"outside\"` — transcripts, profiles, runtime state, and every other file\n * outside the migration's scan scope: write byte-identical, no marker.\n */\nexport type EntityRefWritePathKind = \"memory\" | \"entity\" | \"outside\";\n\nexport function classifyEntityRefWritePath(baseDir: string, filePath: string): EntityRefWritePathKind {\n if (!filePath.endsWith(\".md\")) return \"outside\";\n const rel = path.relative(baseDir, filePath);\n if (rel.startsWith(\"..\") || path.isAbsolute(rel)) return \"outside\";\n const top = rel.split(path.sep)[0] ?? \"\";\n if (top === \"entities\") return \"entity\";\n return RECALL_FALLBACK_DIRS.includes(top) || top === \"cold\" || top === \"archive\" ? \"memory\" : \"outside\";\n}\n\n/** True when `filePath` is in the migration's scan scope at all. */\nexport function pathMayCarryEntityRefs(baseDir: string, filePath: string): boolean {\n return classifyEntityRefWritePath(baseDir, filePath) !== \"outside\";\n}\n\n/**\n * Canonicalize a tombstone's identity fields at the append chokepoint\n * (issue #2213): emitters (forget, temporal supersession, pattern\n * reinforcement, supersede) build inputs from records that may have been\n * read before a peer migration completed. The supersession key embeds the\n * NORMALIZED entity segment (`entity::attr`), so it is re-prefixed when the\n * ref moved — otherwise the keyed guard lands in the legacy id space while\n * write-time lookups canonicalize, and a paraphrase resurrects.\n */\nexport interface TombstoneIdentity {\n entityRef: string | undefined;\n supersessionKey: string | undefined;\n}\n\nexport function canonicalizeTombstoneIdentity(\n entityRef: string | undefined,\n supersessionKey: string | undefined,\n refIds: Readonly<Record<string, string>>,\n): TombstoneIdentity {\n if (typeof entityRef !== \"string\") return { entityRef, supersessionKey };\n const canonical = resolveHistoricalEntityCanonicalId(entityRef, refIds);\n if (canonical === entityRef) return { entityRef, supersessionKey };\n if (supersessionKey) {\n const stalePrefix = `${normalizeSupersessionKey(entityRef)}::`;\n if (supersessionKey.startsWith(stalePrefix)) {\n supersessionKey = `${normalizeSupersessionKey(canonical)}::${supersessionKey.slice(stalePrefix.length)}`;\n }\n }\n return { entityRef: canonical, supersessionKey };\n}\n\n/**\n * Post-persist repair (issue #2213): when the journal moved across a persist,\n * re-resolve the caller's ORIGINAL ref against the fresh table and rewrite\n * the file in place (bounded). When the journal will not settle, take the\n * entity MUTATION lock — parks/removals (the direction the reconcile pass\n * cannot repair, because the removed mapping is gone from the table) publish\n * under it — settle once, then request the marker for additive moves only.\n */\nexport async function repairEntityRefAfterJournalMove(options: {\n stateDir: string;\n currentIds: () => Readonly<Record<string, string>>;\n idsAtResolve: Readonly<Record<string, string>>;\n rawRef: string;\n frontmatter: { entityRef?: string };\n rewrite: () => Promise<void>;\n}): Promise<void> {\n let refIds = options.idsAtResolve;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.currentIds();\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = resolveHistoricalEntityCanonicalId(options.rawRef, fresh);\n if (desired === options.frontmatter.entityRef) return;\n options.frontmatter.entityRef = desired;\n await options.rewrite();\n }\n await withEntityCanonicalMutationLock(options.stateDir, async () => {\n const desired = resolveHistoricalEntityCanonicalId(options.rawRef, options.currentIds());\n if (desired !== options.frontmatter.entityRef) {\n options.frontmatter.entityRef = desired;\n await options.rewrite();\n }\n });\n await requestEntityCanonicalIdReconcile(options.stateDir);\n}\n\n/**\n * Content-form counterpart of {@link repairEntityRefAfterJournalMove} for\n * async writers that persist raw record bytes (capsule import/merge,\n * binary-lifecycle redirects): same bounded loop, same locked settle.\n */\nexport async function repairContentAfterJournalMove(options: {\n stateDir: string;\n cache: HistoricalEntityCanonicalIdCache;\n idsAtWrite: Readonly<Record<string, string>>;\n rawContent: string;\n lastWritten: string;\n rewrite: (content: string) => Promise<void>;\n}): Promise<void> {\n let refIds = options.idsAtWrite;\n let written = options.lastWritten;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.cache.get(options.stateDir);\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, fresh);\n if (desired === written) return;\n written = desired;\n await options.rewrite(desired);\n }\n await withEntityCanonicalMutationLock(options.stateDir, async () => {\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, options.cache.get(options.stateDir));\n if (desired !== written) {\n written = desired;\n await options.rewrite(desired);\n }\n });\n await requestEntityCanonicalIdReconcile(options.stateDir);\n}\n\n/**\n * Sync variant (space promotion, curation, review actions). Sync callers\n * cannot take the async mutation lock, so exhaustion surfaces a retryable\n * error after requesting the marker — a silent return could leave the bytes\n * on a parked canonical claimant the reconcile pass cannot restore.\n */\nexport function repairContentAfterJournalMoveSync(options: {\n stateDir: string;\n cache: HistoricalEntityCanonicalIdCache;\n idsAtWrite: Readonly<Record<string, string>>;\n rawContent: string;\n lastWritten: string;\n rewrite: (content: string) => void;\n}): void {\n let refIds = options.idsAtWrite;\n let written = options.lastWritten;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n const fresh = options.cache.get(options.stateDir);\n if (fresh === refIds) return;\n refIds = fresh;\n const desired = canonicalizeEntityRefFrontmatter(options.rawContent, fresh);\n if (desired === written) return;\n written = desired;\n options.rewrite(desired);\n }\n requestEntityCanonicalIdReconcileSync(options.stateDir);\n throw new Error(\n \"entity canonical-id journal kept changing during post-write repair; retry the write\",\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB,WAAW,oBAAoB;AACxD,OAAO,UAAU;AAIjB,IAAM,6CAA6C;AACnD,IAAM,gDAAgD;AAE/C,SAAS,iBAAiB,SAAiB,UAA2B;AAC3E,MAAI,KAAK,QAAQ,QAAQ,MAAM,MAAO,QAAO;AAC7C,QAAM,YAAY,KAAK,QAAQ,KAAK,QAAQ,QAAQ,CAAC;AACrD,QAAM,cAAc,KAAK,QAAQ,SAAS,UAAU;AACpD,MAAI,cAAc,YAAa,QAAO;AACtC,MAAI;AACF,WAAO,aAAa,SAAS,MAAM,KAAK,KAAK,aAAa,OAAO,GAAG,UAAU;AAAA,EAChF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,wBAAwB,SAAiB,UAAwB;AACxE,qBAAmB,SAAS,cAAc;AAC1C,YAAU,UAAU,EAAE,WAAW,KAAK,CAAC;AACvC,iBAAe,KAAK,KAAK,UAAU,8BAA8B,GAAG,GAAG;AACzE;AAEO,SAAS,gCACd,UACA,MACY;AACZ,QAAM,WAAW,KAAK,KAAK,UAAU,mCAAmC;AACxE,SAAO;AAAA,IAAmB;AAAA,IAAU,MAClC;AAAA,MACE;AAAA,MACA;AAAA,QACE,SAAS;AAAA,QACT,WAAW;AAAA,MACb;AAAA,MACA,OAAO,UAAU,SAAS;AACxB,YAAI,CAAC,SAAU,OAAM,IAAI,MAAM,6CAA6C;AAC5E,eAAO,KAAK,MAAM,KAAK,QAAQ,CAAC;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,0BACpB,SACA,UACA,MACY;AACZ,MAAI,CAAC,iBAAiB,SAAS,QAAQ,GAAG;AACxC,WAAO,KAAK,YAAY,IAAI;AAAA,EAC9B;AACA,QAAM,WAAW,KAAK,KAAK,SAAS,OAAO;AAC3C,SAAO,gCAAgC,UAAU,OAAO,gBA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AI,UAAU,QAAQ;AACtB,WAAS,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;AAC/C,UAAM,QAAQ,QAAQ,MAAM,IAAI,QAAQ,QAAQ;AAChD,QAAI,UAAU,OAAQ;AACtB,aAAS;AACT,UAAM,UAAU,iCAAiC,QAAQ,YAAY,KAAK;AAC1E,QAAI,YAAY,QAAS;AACzB,cAAU;AACV,YAAQ,QAAQ,OAAO;AAAA,EACzB;AACA,wCAAsC,QAAQ,QAAQ;AACtD,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":["path","realpathSync","path","path","realpathSync","path"]}
@@ -3,7 +3,7 @@ import {
3
3
  readNamespaceMaintenanceLastRanStatuses,
4
4
  readNamespaceMaintenanceStatuses,
5
5
  runNamespaceMaintenancePlan
6
- } from "./chunk-HCPVL6SF.js";
6
+ } from "./chunk-SJTSWG2Z.js";
7
7
  import {
8
8
  analyzeSessionIntegrity,
9
9
  applySessionRepair,
@@ -14,7 +14,7 @@ import {
14
14
  } from "./chunk-CMTINOFS.js";
15
15
  import {
16
16
  summarizeCorpusAndReplica
17
- } from "./chunk-3PVKV3XL.js";
17
+ } from "./chunk-UNOAVHV4.js";
18
18
  import {
19
19
  readJudgeVerdictStats
20
20
  } from "./chunk-OZKOPQCM.js";
@@ -32,23 +32,23 @@ import {
32
32
  } from "./chunk-2DQ2XREU.js";
33
33
  import {
34
34
  runConsolidationProvenanceCheck
35
- } from "./chunk-OOOX5C4X.js";
35
+ } from "./chunk-XL2EE5W3.js";
36
36
  import {
37
37
  reportBufferSurpriseDistribution
38
38
  } from "./chunk-YBPYIAA5.js";
39
39
  import {
40
40
  parseConfig
41
- } from "./chunk-KNCR7APE.js";
41
+ } from "./chunk-QTDZ2NYC.js";
42
42
  import {
43
43
  readAggregateExtractionWatermark
44
- } from "./chunk-PBWJVRKE.js";
44
+ } from "./chunk-5FUDSK6Z.js";
45
45
  import {
46
46
  listMemoryGovernanceRuns,
47
47
  readMemoryGovernanceRunArtifact
48
- } from "./chunk-YY6PWFUC.js";
48
+ } from "./chunk-M6TP6UYD.js";
49
49
  import {
50
50
  listNamespaces
51
- } from "./chunk-QFTNWDJ6.js";
51
+ } from "./chunk-YECEEJUU.js";
52
52
  import {
53
53
  analyzeGraphHealth
54
54
  } from "./chunk-KRAMCBIW.js";
@@ -57,7 +57,7 @@ import {
57
57
  } from "./chunk-AWD36R4D.js";
58
58
  import {
59
59
  StorageManager
60
- } from "./chunk-6W3QH3QW.js";
60
+ } from "./chunk-GQIYL7OD.js";
61
61
  import {
62
62
  lintWorkspaceFiles
63
63
  } from "./chunk-DM2T26WE.js";
@@ -1683,4 +1683,4 @@ export {
1683
1683
  runBenchmarkRecall,
1684
1684
  runOperatorRepair
1685
1685
  };
1686
- //# sourceMappingURL=chunk-6TIVVOVU.js.map
1686
+ //# sourceMappingURL=chunk-BNJAVRNJ.js.map
@@ -2,7 +2,7 @@ import {
2
2
  OFFLINE_SYNC_SNAPSHOT_FORMAT,
3
3
  filterOfflineSyncDeletionRevisions,
4
4
  iterateOfflineSyncSnapshotFileRecords
5
- } from "./chunk-SA6P2KS3.js";
5
+ } from "./chunk-TEH5MDX5.js";
6
6
  import {
7
7
  computeOmittedEmbeddingGenerationPaths,
8
8
  embeddingGenerationMembership
@@ -61,4 +61,4 @@ async function buildEmbeddingAwareSnapshotStream(options) {
61
61
  export {
62
62
  buildEmbeddingAwareSnapshotStream
63
63
  };
64
- //# sourceMappingURL=chunk-CMOYD5CA.js.map
64
+ //# sourceMappingURL=chunk-CCL2OXFO.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getOperation
3
- } from "./chunk-O4CA53UY.js";
3
+ } from "./chunk-IMKOJVD4.js";
4
4
  import {
5
5
  EngramAccessInputError
6
6
  } from "./chunk-3MUKQQ7A.js";
@@ -13,7 +13,8 @@ async function respondBriefingHttp(options) {
13
13
  }
14
14
  const output = await op.run(options.gatedBody, {
15
15
  service: options.service,
16
- authenticatedPrincipal: options.principal
16
+ authenticatedPrincipal: options.principal,
17
+ abortSignal: options.abortSignal
17
18
  });
18
19
  options.respondJson(200, output.result);
19
20
  }
@@ -21,4 +22,4 @@ async function respondBriefingHttp(options) {
21
22
  export {
22
23
  respondBriefingHttp
23
24
  };
24
- //# sourceMappingURL=chunk-7XFQSQYS.js.map
25
+ //# sourceMappingURL=chunk-CRN3EPE2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-http-briefing.ts"],"sourcesContent":["import { getOperation } from \"./access-boundary.js\";\nimport { EngramAccessInputError, type EngramAccessService } from \"./access-service.js\";\n\ntype JsonResponder = (status: number, payload: unknown) => void;\n\nexport interface BriefingHttpOptions {\n /** Request body already run through the namespace gate (gatedBodyNamespace). */\n gatedBody: Record<string, unknown>;\n service: EngramAccessService;\n principal: string | undefined;\n respondJson: JsonResponder;\n /** HTTP request lifetime; aborting it stops the briefing (issue #3139). */\n abortSignal?: AbortSignal;\n}\n\n/**\n * POST /engram/v1/briefing — daily briefing over the access HTTP boundary.\n *\n * Dispatches the registered `briefing` boundary operation (the one the MCP\n * tool uses) so schema validation, namespace gating, and principal\n * propagation reach every HTTP briefing call — the same shape as the\n * coding/delta read dispatch. Pure read: nothing persists, so no\n * write-quota accounting. The operation result already carries both\n * renderings (markdown + json sections) in one response, letting thin\n * clients render without a CLI subprocess.\n */\nexport async function respondBriefingHttp(options: BriefingHttpOptions): Promise<void> {\n const op = getOperation(\"briefing\");\n if (!op) {\n throw new EngramAccessInputError(\"access-boundary: operation not registered: briefing\");\n }\n // SAFETY: the built-in briefing operation returns { result }; this adapter passes it through unchanged.\n const output = (await op.run(options.gatedBody, {\n service: options.service,\n authenticatedPrincipal: options.principal,\n abortSignal: options.abortSignal,\n })) as { result: unknown };\n options.respondJson(200, output.result);\n}\n"],"mappings":";;;;;;;;AA0BA,eAAsB,oBAAoB,SAA6C;AACrF,QAAM,KAAK,aAAa,UAAU;AAClC,MAAI,CAAC,IAAI;AACP,UAAM,IAAI,uBAAuB,qDAAqD;AAAA,EACxF;AAEA,QAAM,SAAU,MAAM,GAAG,IAAI,QAAQ,WAAW;AAAA,IAC9C,SAAS,QAAQ;AAAA,IACjB,wBAAwB,QAAQ;AAAA,IAChC,aAAa,QAAQ;AAAA,EACvB,CAAC;AACD,UAAQ,YAAY,KAAK,OAAO,MAAM;AACxC;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  canonicalCategoryForAlias,
3
3
  categoryAliasCoercion
4
- } from "./chunk-BMG3SAXA.js";
4
+ } from "./chunk-Z5277JWF.js";
5
5
 
6
6
  // src/access-observe-write-category.ts
7
7
  function splitCanonicalWriteRequest(request) {
@@ -22,4 +22,4 @@ function splitCanonicalWriteRequest(request) {
22
22
  export {
23
23
  splitCanonicalWriteRequest
24
24
  };
25
- //# sourceMappingURL=chunk-3NYIXVCT.js.map
25
+ //# sourceMappingURL=chunk-DMKTOCC7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-observe-write-category.ts"],"sourcesContent":["/**\n * Category-alias split + replay restamp for observe/write (#2829).\n * Extracted from access-observe-write-surface.ts to stay under the 1200-line cap.\n *\n * The wire schema already maps an alias to \"fact\". `rawCategory` is the\n * caller's spelling: it must not reach the write candidate or fingerprint,\n * and a replay must rebuild the note from THIS request's spelling.\n */\nimport {\n canonicalCategoryForAlias,\n categoryAliasCoercion,\n reapplyCategoryCoercion,\n type CategoryAliasCoercion,\n type MemoryCategoryAlias,\n} from \"./access-schema.js\";\n\nexport { reapplyCategoryCoercion };\nexport { buildWithBriefingLocation } from \"./location/tagging.js\";\n\nexport function splitCanonicalWriteRequest<T extends { rawCategory?: string; category?: string }>(\n request: T,\n): {\n canonical: Omit<T, \"rawCategory\">;\n categoryCoercion: CategoryAliasCoercion | undefined;\n} {\n const { rawCategory, ...canonical } = request;\n // #2962: a direct service caller bypasses the wire schema, so an accepted\n // alias can still sit on `category`. Canonicalize it at the same boundary\n // the schema's transform covers for HTTP/MCP/CLI, minting the retained\n // spelling from the request itself. A schema-minted `rawCategory` always\n // wins (it names the spelling the transform actually canonicalized);\n // near-misses pass through untouched and reject at the write candidate\n // with the attempted category echoed.\n if (rawCategory === undefined && typeof canonical.category === \"string\") {\n const mapped = canonicalCategoryForAlias(canonical.category);\n if (mapped !== undefined) {\n const from = canonical.category as MemoryCategoryAlias;\n return {\n canonical: { ...canonical, category: mapped } as Omit<T, \"rawCategory\">,\n categoryCoercion: { from, to: mapped },\n };\n }\n }\n return { canonical, categoryCoercion: categoryAliasCoercion(rawCategory) };\n}\n"],"mappings":";;;;;;AAmBO,SAAS,2BACd,SAIA;AACA,QAAM,EAAE,aAAa,GAAG,UAAU,IAAI;AAQtC,MAAI,gBAAgB,UAAa,OAAO,UAAU,aAAa,UAAU;AACvE,UAAM,SAAS,0BAA0B,UAAU,QAAQ;AAC3D,QAAI,WAAW,QAAW;AACxB,YAAM,OAAO,UAAU;AACvB,aAAO;AAAA,QACL,WAAW,EAAE,GAAG,WAAW,UAAU,OAAO;AAAA,QAC5C,kBAAkB,EAAE,MAAM,IAAI,OAAO;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,WAAW,kBAAkB,sBAAsB,WAAW,EAAE;AAC3E;","names":[]}
@@ -76,6 +76,9 @@ async function safeReadMemories(storage, window, options = {}) {
76
76
  resultCount = memories.length;
77
77
  return memories;
78
78
  } catch (err) {
79
+ if (isAbortError(err) && options.signal?.aborted) {
80
+ throw err;
81
+ }
79
82
  if (err instanceof BriefingReadTimedOut) {
80
83
  outcome = "timeout";
81
84
  bestEffortLog(
@@ -99,7 +102,9 @@ async function safeReadMemories(storage, window, options = {}) {
99
102
  }
100
103
  async function readBriefingMemories(storage, window, mode, options) {
101
104
  if (mode === "windowed") {
102
- const result = await storage.readMemoriesWindow({ updatedAfter: window.from });
105
+ const readOptions = { updatedAfter: window.from };
106
+ if (options.signal) readOptions.abortSignal = options.signal;
107
+ const result = await storage.readMemoriesWindow(readOptions);
103
108
  return result.memories;
104
109
  }
105
110
  const isCancellable = storage.supportsAbortSignal === true || storage.supportsCancellation === true || storage.cancellable === true || storage.readAllMemories?.supportsAbortSignal === true;
@@ -113,8 +118,9 @@ async function readBriefingMemories(storage, window, mode, options) {
113
118
  deadlineFired = true;
114
119
  controller.abort();
115
120
  }, deadlineMs);
121
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
116
122
  try {
117
- const memories = await storage.readAllMemories({ abortSignal: controller.signal });
123
+ const memories = await storage.readAllMemories({ abortSignal: signal });
118
124
  if (deadlineFired) {
119
125
  throw new BriefingReadTimedOut(deadlineMs);
120
126
  }
@@ -126,9 +132,19 @@ async function readBriefingMemories(storage, window, mode, options) {
126
132
  clearTimeout(timer);
127
133
  }
128
134
  }
135
+ async function safeReadEntities(storage, signal) {
136
+ try {
137
+ return await storage.readAllEntityFiles({ abortSignal: signal });
138
+ } catch (err) {
139
+ if (isAbortError(err) && signal.aborted) throw err;
140
+ log.warn(`briefing: readAllEntityFiles failed: ${err}`);
141
+ return [];
142
+ }
143
+ }
129
144
 
130
145
  export {
131
146
  BRIEFING_FULL_READ_FALLBACK_MS,
132
- safeReadMemories
147
+ safeReadMemories,
148
+ safeReadEntities
133
149
  };
134
- //# sourceMappingURL=chunk-FRXS6SC7.js.map
150
+ //# sourceMappingURL=chunk-EKUI7I2X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/briefing-window.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { EntityFile, MemoryFile } from \"./types.js\";\nimport { isAbortError } from \"./abort-error.js\";\nimport type { CorpusReadOptions } from \"./corpus-read-cancellation.js\";\nimport type { ParsedBriefingWindow } from \"./briefing.js\";\nimport type { WindowedMemoryReadOptions } from \"./storage/windowed-memory-read.js\";\n\ntype BriefingMemoryReader = {\n readMemoriesWindow?: (options: WindowedMemoryReadOptions) => Promise<{ memories: MemoryFile[] }>;\n readAllMemories: ((options?: CorpusReadOptions) => Promise<MemoryFile[]>) & {\n supportsAbortSignal?: boolean;\n };\n supportsAbortSignal?: boolean;\n supportsCancellation?: boolean;\n cancellable?: boolean;\n};\n\n/**\n * Deadline for the legacy full-read fallback (issue #2779). Storage doubles\n * that predate `readMemoriesWindow()` can only answer with a full-corpus\n * `readAllMemories()`, which is unbounded work; on a large corpus that read\n * alone can outlast the 60s MCP client timeout. Arm an AbortController with\n * this budget (well under 60s, leaving room for entity reads and follow-ups)\n * and fail open with an empty read. The deadline reaches the read as an\n * abort signal (the #2307 corpus-read contract), so the scan stops at its\n * next boundary instead of being abandoned to run on in the background.\n */\nexport const BRIEFING_FULL_READ_FALLBACK_MS = 30_000;\n\n/** Options for {@link safeReadMemories}. */\nexport interface SafeReadMemoriesOptions {\n /** Test seam overriding {@link BRIEFING_FULL_READ_FALLBACK_MS}. */\n fallbackDeadlineMs?: number;\n /**\n * Caller cancellation. The signal reaches the storage read so it stops at\n * its next boundary, and a cancelled read is rethrown rather than degraded\n * into an empty corpus (issue #3139).\n */\n signal?: AbortSignal;\n}\n\ntype BriefingReadMode = \"windowed\" | \"full-read-fallback\";\ntype BriefingReadOutcome = \"success\" | \"timeout\" | \"error\";\n\n/** Internal marker: the fallback deadline fired and the read was aborted. */\nclass BriefingReadTimedOut extends Error {\n constructor(readonly deadlineMs: number) {\n super(\"briefing full-read fallback timed out\");\n this.name = \"BriefingReadTimedOut\";\n }\n}\n\n/** Internal marker: the adapter's readAllMemories predates the signal contract. */\nclass LegacyReadUnsupported extends Error {\n constructor() {\n super(\"readAllMemories does not accept an abort signal\");\n this.name = \"LegacyReadUnsupported\";\n }\n}\n\nconst SAFE_ERROR_CLASSES: Record<string, true> = {\n Error: true,\n TypeError: true,\n RangeError: true,\n ReferenceError: true,\n SyntaxError: true,\n URIError: true,\n EvalError: true,\n AggregateError: true,\n AbortError: true,\n TimeoutError: true,\n SystemError: true,\n BriefingReadTimedOut: true,\n LegacyReadUnsupported: true,\n StorageError: true,\n EngramAccessInputError: true,\n};\n\n/**\n * Sanitize adapter-controlled Error.name before structured discriminator logs\n * (issue #2827). Allow-lists known system/remnic error names and maps any\n * unrecognized or backend-controlled names to a safe bounded class (\"CustomError\").\n */\nfunction errorClass(err: unknown): string {\n if (err instanceof Error) {\n const name = err.name;\n if (typeof name === \"string\" && SAFE_ERROR_CLASSES[name] === true) {\n return name;\n }\n return \"CustomError\";\n }\n return typeof err === \"string\"\n ? \"string\"\n : typeof err === \"object\" && err !== null\n ? \"object\"\n : typeof err;\n}\n\nfunction bestEffortLog(level: \"info\" | \"warn\", message: string): void {\n try {\n log[level](message);\n } catch {\n // Diagnostics must never turn a successful or fail-open briefing read into\n // a request failure when a host logger transport is unavailable.\n }\n}\n\n/**\n * One structured, content-free discriminator per briefing memory read\n * (issue #2779): `mode`, `durationMs`, `count` when known, `outcome`, and on\n * failure a safe error class — never error messages or memory content.\n */\nfunction logBriefingMemoryRead(\n mode: BriefingReadMode,\n outcome: BriefingReadOutcome,\n durationMs: number,\n resultCount: number | undefined,\n errClass: string | undefined,\n): void {\n const fields = [\n `mode=${mode}`,\n `durationMs=${durationMs}`,\n ...(resultCount === undefined ? [] : [`count=${resultCount}`]),\n `outcome=${outcome}`,\n ...(errClass === undefined ? [] : [`err=${errClass}`]),\n ];\n bestEffortLog(\"info\", `briefing: memory read ${fields.join(\" \")}`);\n}\n\n/** Read only the memories needed by a briefing, with compatibility fallback. */\nexport async function safeReadMemories(\n storage: BriefingMemoryReader,\n window: ParsedBriefingWindow,\n options: SafeReadMemoriesOptions = {},\n): Promise<MemoryFile[]> {\n const startedAt = Date.now();\n const mode: BriefingReadMode =\n typeof storage.readMemoriesWindow === \"function\" ? \"windowed\" : \"full-read-fallback\";\n let outcome: BriefingReadOutcome = \"error\";\n let resultCount: number | undefined;\n let errClass: string | undefined;\n try {\n const memories = await readBriefingMemories(storage, window, mode, options);\n outcome = \"success\";\n resultCount = memories.length;\n return memories;\n } catch (err) {\n if (isAbortError(err) && options.signal?.aborted) {\n // Caller cancellation is not a read failure: rethrow it so the briefing\n // rejects instead of degrading into an empty corpus (issue #3139). The\n // own fallback deadline is reported as BriefingReadTimedOut below.\n throw err;\n }\n if (err instanceof BriefingReadTimedOut) {\n outcome = \"timeout\";\n bestEffortLog(\n \"warn\",\n `briefing: memory read mode=full-read-fallback timed out after ${err.deadlineMs}ms — ` +\n `returning no memories (storage adapter lacks readMemoriesWindow; upgrade it to ` +\n `windowed or signal-aware reads)`,\n );\n } else if (err instanceof LegacyReadUnsupported) {\n errClass = errorClass(err);\n bestEffortLog(\n \"warn\",\n `briefing: memory read mode=full-read-fallback refused: readAllMemories() takes no abort ` +\n `signal, so its scan could not be stopped at the deadline — returning no memories ` +\n `(upgrade the storage adapter to readMemoriesWindow or a signal-aware readAllMemories)`,\n );\n } else {\n errClass = errorClass(err);\n bestEffortLog(\"warn\", `briefing: read memories failed (${errClass}) — returning no memories`);\n }\n return [];\n } finally {\n logBriefingMemoryRead(mode, outcome, Date.now() - startedAt, resultCount, errClass);\n }\n}\n\nasync function readBriefingMemories(\n storage: BriefingMemoryReader,\n window: ParsedBriefingWindow,\n mode: BriefingReadMode,\n options: SafeReadMemoriesOptions,\n): Promise<MemoryFile[]> {\n // A briefing only needs memories inside its lookback window. Avoid parsing\n // the full corpus on cache misses; keep the full-read fallback for custom\n // StorageManager-compatible callers that predate readMemoriesWindow().\n if (mode === \"windowed\") {\n const readOptions: WindowedMemoryReadOptions = { updatedAfter: window.from };\n if (options.signal) readOptions.abortSignal = options.signal;\n const result = await storage.readMemoriesWindow!(readOptions);\n return result.memories;\n }\n // Refuse legacy adapters that do not explicitly declare cancellation support (#2827).\n // Require affirmative cancellation support (`true` on one explicit marker) before fallback.\n // Do not rely on Function.length, which is zero for default/rest/bound functions.\n const isCancellable =\n storage.supportsAbortSignal === true ||\n storage.supportsCancellation === true ||\n storage.cancellable === true ||\n storage.readAllMemories?.supportsAbortSignal === true;\n if (!isCancellable) {\n throw new LegacyReadUnsupported();\n }\n const deadlineMs = options.fallbackDeadlineMs ?? BRIEFING_FULL_READ_FALLBACK_MS;\n const controller = new AbortController();\n let deadlineFired = false;\n const timer = setTimeout(() => {\n deadlineFired = true;\n controller.abort();\n }, deadlineMs);\n const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;\n try {\n // Direct await, no Promise.race: the signal IS the deadline. A\n // signal-aware read settles on abort (AbortError at its next scan\n // boundary, #2307), so nothing is left scanning in the background once\n // this function returns.\n const memories = await storage.readAllMemories({ abortSignal: signal });\n if (deadlineFired) {\n // A double that resolves partial rows instead of rejecting on abort\n // must not have them served as a complete corpus.\n throw new BriefingReadTimedOut(deadlineMs);\n }\n return memories;\n } catch (err) {\n if (isAbortError(err) && deadlineFired) throw new BriefingReadTimedOut(deadlineMs);\n throw err;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport async function safeReadEntities(\n storage: { readAllEntityFiles(options?: CorpusReadOptions): Promise<EntityFile[]> },\n signal: AbortSignal,\n): Promise<EntityFile[]> {\n try {\n return await storage.readAllEntityFiles({ abortSignal: signal });\n } catch (err) {\n if (isAbortError(err) && signal.aborted) throw err;\n log.warn(`briefing: readAllEntityFiles failed: ${err}`);\n return [];\n }\n}\n"],"mappings":";;;;;;;;AA2BO,IAAM,iCAAiC;AAkB9C,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACvC,YAAqB,YAAoB;AACvC,UAAM,uCAAuC;AAD1B;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGA,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACxC,cAAc;AACZ,UAAM,iDAAiD;AACvD,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,qBAA2C;AAAA,EAC/C,OAAO;AAAA,EACP,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,UAAU;AAAA,EACV,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa;AAAA,EACb,sBAAs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AAqB,UAAU;AACjF,UAAM;AAAA,EACR,UAAE;AACA,iBAAa,KAAK;AAAA,EACpB;AACF;AAEA,eAAsB,iBACpB,SACA,QACuB;AACvB,MAAI;AACF,WAAO,MAAM,QAAQ,mBAAmB,EAAE,aAAa,OAAO,CAAC;AAAA,EACjE,SAAS,KAAK;AACZ,QAAI,aAAa,GAAG,KAAK,OAAO,QAAS,OAAM;AAC/C,QAAI,KAAK,wCAAwC,GAAG,EAAE;AACtD,WAAO,CAAC;AAAA,EACV;AACF;","names":[]}
@@ -18,13 +18,13 @@ import {
18
18
  } from "./chunk-3HSRWJTC.js";
19
19
  import {
20
20
  respondDeepRecall
21
- } from "./chunk-CPBYKOTC.js";
21
+ } from "./chunk-6ZQX3R66.js";
22
22
  import {
23
23
  handleSupportPassportOwnerHttp
24
- } from "./chunk-LCHFINL4.js";
24
+ } from "./chunk-N7FNCE7F.js";
25
25
  import {
26
26
  buildSupportPassportPublicRequestHandler
27
- } from "./chunk-FOKTW6GY.js";
27
+ } from "./chunk-EWBXMGXR.js";
28
28
  import {
29
29
  handleMcpGetSse
30
30
  } from "./chunk-SRT6SHVZ.js";
@@ -37,14 +37,14 @@ import {
37
37
  processChatMessage,
38
38
  sessionBelongsToPrincipal,
39
39
  subscribeChatTranscript
40
- } from "./chunk-OD7ZXCUF.js";
40
+ } from "./chunk-UXGXJUZ5.js";
41
41
  import {
42
42
  handleRecallWhyHttpQuery,
43
43
  handleRecallXrayHttpQuery
44
44
  } from "./chunk-FC3ZFEXF.js";
45
45
  import {
46
46
  RelayMissionStoreError
47
- } from "./chunk-KMTMMBEB.js";
47
+ } from "./chunk-ZNRTHYYW.js";
48
48
  import {
49
49
  executeResolution,
50
50
  isValidResolutionVerb
@@ -61,10 +61,10 @@ import {
61
61
  optionalNamespaceKindQueryParam,
62
62
  optionalQueryString,
63
63
  positiveIntQueryParam
64
- } from "./chunk-V4GPFCJ7.js";
64
+ } from "./chunk-5G53JSRO.js";
65
65
  import {
66
66
  respondBriefingHttp
67
- } from "./chunk-7XFQSQYS.js";
67
+ } from "./chunk-CRN3EPE2.js";
68
68
  import {
69
69
  maybeHandleLifecycleFlush
70
70
  } from "./chunk-2BPPGNAQ.js";
@@ -75,20 +75,23 @@ import {
75
75
  authorizationProbeNamespaces,
76
76
  authorizationProbeRequiresPrincipalNamespace,
77
77
  probeOperationAuthorization
78
- } from "./chunk-WQFHHJWK.js";
78
+ } from "./chunk-UALXWWGN.js";
79
79
  import {
80
80
  getOperation,
81
81
  resolveQueryNamespaceWritablePreflight
82
- } from "./chunk-O4CA53UY.js";
82
+ } from "./chunk-IMKOJVD4.js";
83
83
  import {
84
84
  handleWhoKnowsHttpQuery
85
- } from "./chunk-AGCEJDG2.js";
85
+ } from "./chunk-HPNXS6W6.js";
86
86
  import {
87
87
  isTrustZoneName
88
88
  } from "./chunk-JWX2Q6HS.js";
89
89
  import {
90
90
  subscribeGraphEvents
91
91
  } from "./chunk-DEUNUKTD.js";
92
+ import {
93
+ BriefingTimeoutError
94
+ } from "./chunk-X2KO4FK5.js";
92
95
  import {
93
96
  CorrectionContractError
94
97
  } from "./chunk-ETSJD5IV.js";
@@ -102,7 +105,7 @@ import {
102
105
  } from "./chunk-PARM6OYL.js";
103
106
  import {
104
107
  validateRequest
105
- } from "./chunk-BMG3SAXA.js";
108
+ } from "./chunk-Z5277JWF.js";
106
109
  import {
107
110
  peerManifestRevision
108
111
  } from "./chunk-QYAXMXOB.js";
@@ -117,7 +120,7 @@ import {
117
120
  OFFLINE_SYNC_APPLY_MAX_BODY_BYTES,
118
121
  OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,
119
122
  OFFLINE_SYNC_SNAPSHOT_BASE_MAX_BODY_BYTES
120
- } from "./chunk-SA6P2KS3.js";
123
+ } from "./chunk-TEH5MDX5.js";
121
124
  import {
122
125
  resolveNamespaceCapabilities
123
126
  } from "./chunk-C5LWPYS3.js";
@@ -893,6 +896,10 @@ var EngramAccessHttpServer = class extends ReviewDeckAccessHttpBase {
893
896
  res.once("close", abortDisconnectedRequest);
894
897
  correlationIdStore.run(correlationId, () => {
895
898
  void this.handle(req, res, correlationId, abortController.signal).catch((err) => {
899
+ if (err instanceof BriefingTimeoutError) {
900
+ this.respondJson(res, 504, { error: err.message, code: "briefing_timeout" });
901
+ return;
902
+ }
896
903
  if (isAbortError(err)) {
897
904
  if (!res.destroyed && !res.writableEnded) {
898
905
  res.end();
@@ -2040,7 +2047,8 @@ var EngramAccessHttpServer = class extends ReviewDeckAccessHttpBase {
2040
2047
  gatedBody: this.gatedBodyNamespace(req, await this.readJsonBody(req)),
2041
2048
  service: this.service,
2042
2049
  principal: this.resolveRequestPrincipal(req),
2043
- respondJson: (status, payload) => this.respondJson(res, status, payload)
2050
+ respondJson: (status, payload) => this.respondJson(res, status, payload),
2051
+ abortSignal
2044
2052
  });
2045
2053
  return;
2046
2054
  }
@@ -3565,4 +3573,4 @@ export {
3565
3573
  resolveDefaultAdminConsolePublicDir,
3566
3574
  EngramAccessHttpServer
3567
3575
  };
3568
- //# sourceMappingURL=chunk-N6EM7ESC.js.map
3576
+ //# sourceMappingURL=chunk-EKYWZYZJ.js.map