@remnic/core 10.0.91 → 10.0.93

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 (522) hide show
  1. package/dist/access-admin-ops-surface.js +334 -61
  2. package/dist/access-authorization-probe.js +2 -283
  3. package/dist/access-boundary.d.ts +1 -1
  4. package/dist/access-boundary.d.ts.map +1 -1
  5. package/dist/access-boundary.js +1 -282
  6. package/dist/access-cli.js +288 -304
  7. package/dist/access-cli.js.map +1 -1
  8. package/dist/access-coding-context-resolution.js +3 -3
  9. package/dist/access-extraction-force-flush.js +334 -61
  10. package/dist/access-http-briefing.js +334 -62
  11. package/dist/access-http-query.js +334 -63
  12. package/dist/access-http.js +332 -114
  13. package/dist/access-identity-continuity-surface.js +334 -61
  14. package/dist/access-lcm-surface.js +334 -61
  15. package/dist/access-mcp-frames.d.ts +20 -6
  16. package/dist/access-mcp-frames.d.ts.map +1 -1
  17. package/dist/access-mcp-frames.js +1 -1
  18. package/dist/access-mcp.d.ts +5 -0
  19. package/dist/access-mcp.d.ts.map +1 -1
  20. package/dist/access-mcp.js +332 -89
  21. package/dist/access-namespace-preflight.js +2 -282
  22. package/dist/access-observe-transcript.js +3 -3
  23. package/dist/access-observe-write-category.js +6 -6
  24. package/dist/access-observe-write-surface.js +334 -61
  25. package/dist/access-offline-manifest.js +12 -11
  26. package/dist/access-operations-batch.js +332 -66
  27. package/dist/access-operations.js +332 -75
  28. package/dist/access-recall-concurrency.js +334 -61
  29. package/dist/access-recall-diagnostics.js +6 -5
  30. package/dist/access-recall-response.js +334 -61
  31. package/dist/access-recall-surface.js +334 -61
  32. package/dist/access-schema.js +2 -2
  33. package/dist/access-service.d.ts +1 -0
  34. package/dist/access-service.d.ts.map +1 -1
  35. package/dist/access-service.js +337 -64
  36. package/dist/access-surface-catalog.js +6 -283
  37. package/dist/access-surface-catalog.js.map +1 -1
  38. package/dist/active-context-transform.js +1 -1
  39. package/dist/active-memory-bridge.js +3 -2
  40. package/dist/active-recall.js +36 -37
  41. package/dist/active-recall.js.map +1 -1
  42. package/dist/activity/journal-extract.d.ts +13 -1
  43. package/dist/activity/journal-extract.d.ts.map +1 -1
  44. package/dist/{auto-sync-3AZW7MXI.js → auto-sync-BO5YZKM6.js} +13 -15
  45. package/dist/{auto-sync-3AZW7MXI.js.map → auto-sync-BO5YZKM6.js.map} +1 -1
  46. package/dist/briefing.js +20 -20
  47. package/dist/buffer.js +16 -16
  48. package/dist/calibration.js +10 -10
  49. package/dist/{capsule-merge-2IIXFXN5.js → capsule-merge-6IDAYTKG.js} +6 -6
  50. package/dist/causal-consolidation.js +23 -23
  51. package/dist/{chunk-QL7RHYK6.js → chunk-2LMA22UU.js} +5 -5
  52. package/dist/{chunk-RGUUBAT5.js → chunk-2WCLTWV2.js} +3 -3
  53. package/dist/{chunk-RSK2WIEM.js → chunk-2YODOG2O.js} +2 -2
  54. package/dist/{chunk-WYG5UNDY.js → chunk-3AUDELZL.js} +2 -2
  55. package/dist/{chunk-OFVCFKDH.js → chunk-3CYOCE6U.js} +3 -3
  56. package/dist/{chunk-6HM6HARE.js → chunk-3FBAEPCU.js} +2 -2
  57. package/dist/{chunk-PIITB2YZ.js → chunk-3ZS3NUEI.js} +4 -4
  58. package/dist/{chunk-V4XE263I.js → chunk-43AA5FVD.js} +1 -1
  59. package/dist/chunk-43AA5FVD.js.map +1 -0
  60. package/dist/{chunk-ANZZLRUX.js → chunk-4IVRQMZW.js} +2 -2
  61. package/dist/{chunk-63E37JCN.js → chunk-4RAJT5L2.js} +4 -4
  62. package/dist/{chunk-45VUHDV2.js → chunk-5CO5G4MN.js} +2 -2
  63. package/dist/{chunk-PUEO37QG.js → chunk-5YT2IIFX.js} +729 -17
  64. package/dist/chunk-5YT2IIFX.js.map +1 -0
  65. package/dist/{chunk-P5VZSSYL.js → chunk-622V2AZA.js} +233 -40
  66. package/dist/chunk-622V2AZA.js.map +1 -0
  67. package/dist/{chunk-3UMDRGFS.js → chunk-65HWAQ4F.js} +3 -3
  68. package/dist/{chunk-T67LUYCR.js → chunk-77NTFICT.js} +5 -5
  69. package/dist/chunk-A2WFUMUN.js +86 -0
  70. package/dist/chunk-A2WFUMUN.js.map +1 -0
  71. package/dist/{chunk-UE6RRXMF.js → chunk-A4F7OIC5.js} +2 -2
  72. package/dist/chunk-AHA5VQGP.js +117 -0
  73. package/dist/chunk-AHA5VQGP.js.map +1 -0
  74. package/dist/{chunk-AOFEMUHG.js → chunk-ATG2PQ4V.js} +56 -5
  75. package/dist/chunk-ATG2PQ4V.js.map +1 -0
  76. package/dist/{chunk-63O7LVMN.js → chunk-B33YWUJV.js} +3 -3
  77. package/dist/{chunk-QVMOCJRV.js → chunk-B377OKUP.js} +2 -2
  78. package/dist/{chunk-IUKYFTGW.js → chunk-B3DR2JBZ.js} +140 -125
  79. package/dist/chunk-B3DR2JBZ.js.map +1 -0
  80. package/dist/{chunk-ZT6WPSII.js → chunk-BGHCSLE5.js} +2 -2
  81. package/dist/{chunk-YYOMGOHB.js → chunk-BOK6BN5M.js} +2 -2
  82. package/dist/{chunk-OH7QLI6W.js → chunk-BPPUH5JM.js} +5 -5
  83. package/dist/{chunk-EV76IZ37.js → chunk-BTI4C4MA.js} +2 -2
  84. package/dist/{chunk-O6ZSWHVR.js → chunk-C2KE5DMD.js} +4 -4
  85. package/dist/{chunk-47F6WWLQ.js → chunk-C73N66PR.js} +2 -2
  86. package/dist/{chunk-3XIWW4TB.js → chunk-CGJYL633.js} +2 -2
  87. package/dist/{chunk-WRT7GJ2D.js → chunk-CIWMTNHW.js} +4 -4
  88. package/dist/{chunk-O55EKIEC.js → chunk-D3ZKHLN2.js} +2 -2
  89. package/dist/{chunk-CD4BCCNP.js → chunk-DJ7WVEWX.js} +2 -2
  90. package/dist/{chunk-RO7RUBLD.js → chunk-EFL24KOI.js} +2 -2
  91. package/dist/{chunk-4CJTQHEG.js → chunk-ESLOLCD4.js} +3 -3
  92. package/dist/{chunk-Z4Q6USKJ.js → chunk-ETBVCRVL.js} +4 -4
  93. package/dist/{chunk-VILPVT4S.js → chunk-EZ47HOJ6.js} +4 -4
  94. package/dist/{chunk-EFYN5I7Z.js → chunk-F4QFU5IZ.js} +2 -2
  95. package/dist/{chunk-T6OZW2WR.js → chunk-FA7SLQ5X.js} +7 -1
  96. package/dist/chunk-FA7SLQ5X.js.map +1 -0
  97. package/dist/{chunk-SHUBTAY2.js → chunk-FMKILENU.js} +14 -14
  98. package/dist/{chunk-YLXETSAH.js → chunk-GCZJ7XRI.js} +2 -2
  99. package/dist/{chunk-J4MMPQ7Q.js → chunk-GQXOBKPL.js} +7 -9
  100. package/dist/{chunk-J4MMPQ7Q.js.map → chunk-GQXOBKPL.js.map} +1 -1
  101. package/dist/{chunk-UDKWFDV2.js → chunk-HLUHEMN4.js} +27 -3
  102. package/dist/chunk-HLUHEMN4.js.map +1 -0
  103. package/dist/{chunk-QFEDITXM.js → chunk-JNDMIAJ4.js} +2 -2
  104. package/dist/chunk-JTSSSR4L.js +359 -0
  105. package/dist/chunk-JTSSSR4L.js.map +1 -0
  106. package/dist/{chunk-5KBIOI4G.js → chunk-JVBAPAWZ.js} +217 -13
  107. package/dist/chunk-JVBAPAWZ.js.map +1 -0
  108. package/dist/{chunk-E5PPE4VA.js → chunk-K2VRKCPA.js} +2 -2
  109. package/dist/{chunk-MKRYQROF.js → chunk-LGEHAQHK.js} +4 -4
  110. package/dist/{chunk-7HTUYFR3.js → chunk-LLPMMMWG.js} +27 -10
  111. package/dist/chunk-LLPMMMWG.js.map +1 -0
  112. package/dist/{chunk-XYTQJD7F.js → chunk-LMJVP5CM.js} +2 -2
  113. package/dist/{chunk-JC36FPQ5.js → chunk-LPV72KRQ.js} +2 -2
  114. package/dist/{chunk-2LCRG2YV.js → chunk-M2XR6B6V.js} +2 -2
  115. package/dist/{chunk-GGRRF4PZ.js → chunk-MDPT6QFK.js} +1 -1
  116. package/dist/{chunk-GGRRF4PZ.js.map → chunk-MDPT6QFK.js.map} +1 -1
  117. package/dist/{chunk-VPQFK63H.js → chunk-MH632KPO.js} +2 -2
  118. package/dist/{chunk-EQ4U73UH.js → chunk-MLAMXQAW.js} +14 -2
  119. package/dist/chunk-MLAMXQAW.js.map +1 -0
  120. package/dist/{chunk-ZU5JDLOH.js → chunk-MMRTPH3J.js} +2 -2
  121. package/dist/{chunk-ZZ67UTQX.js → chunk-MUX7IL77.js} +2 -2
  122. package/dist/{chunk-RYWROSL5.js → chunk-NAQ4A5IX.js} +7 -7
  123. package/dist/{chunk-TVIVY7KU.js → chunk-NED7IR7B.js} +4 -4
  124. package/dist/{chunk-ADYP7HXE.js → chunk-NHVAX7MH.js} +3 -3
  125. package/dist/{chunk-TG3R2SID.js → chunk-NMGHGTVR.js} +5 -5
  126. package/dist/{chunk-YCNIGRRF.js → chunk-NS7U4ZYU.js} +13 -117
  127. package/dist/chunk-NS7U4ZYU.js.map +1 -0
  128. package/dist/{chunk-NGHDW6UU.js → chunk-NUQEREIP.js} +2 -2
  129. package/dist/{chunk-5IIQU4JZ.js → chunk-OB72KNMF.js} +4 -4
  130. package/dist/{chunk-7L3TODI7.js → chunk-OJXJWNFY.js} +2 -2
  131. package/dist/{chunk-66L5ZRJC.js → chunk-P3WRNWWM.js} +157 -4
  132. package/dist/chunk-P3WRNWWM.js.map +1 -0
  133. package/dist/{chunk-E6M225BJ.js → chunk-PC5DRBGD.js} +18 -8
  134. package/dist/chunk-PC5DRBGD.js.map +1 -0
  135. package/dist/{chunk-EURPSF4Y.js → chunk-PH5ZQM35.js} +2 -2
  136. package/dist/{chunk-BMWMTAQF.js → chunk-PRAUN6PN.js} +3 -3
  137. package/dist/{chunk-RWGRSKN5.js → chunk-PT4DZDJA.js} +2 -2
  138. package/dist/{chunk-7EPY3IQL.js → chunk-PZJQ46DH.js} +2 -2
  139. package/dist/{chunk-AH637HZ5.js → chunk-QDESY76F.js} +3 -3
  140. package/dist/{chunk-I6QGI65T.js → chunk-QRMG4HK4.js} +3 -3
  141. package/dist/{chunk-ZU3NJNO7.js → chunk-QSF5SJAM.js} +4 -4
  142. package/dist/{chunk-5IYOKDM4.js → chunk-R23JWJD3.js} +5 -5
  143. package/dist/{chunk-EWJZZDRG.js → chunk-R4BBGPI2.js} +219 -219
  144. package/dist/chunk-R4BBGPI2.js.map +1 -0
  145. package/dist/{chunk-LJQFJF4J.js → chunk-RM2YUFH6.js} +6 -6
  146. package/dist/{chunk-IPT2OY4B.js → chunk-RQFXZYTF.js} +35 -33
  147. package/dist/chunk-RQFXZYTF.js.map +1 -0
  148. package/dist/{chunk-AP6NCP3V.js → chunk-S3S72HRM.js} +8 -6
  149. package/dist/chunk-S3S72HRM.js.map +1 -0
  150. package/dist/{chunk-6QMWECO5.js → chunk-SGQPR5SX.js} +7 -7
  151. package/dist/{chunk-ZGFLIK5H.js → chunk-SPAKBUJY.js} +2 -2
  152. package/dist/{chunk-ER7XANP3.js → chunk-SQ3GEIEL.js} +4 -4
  153. package/dist/{chunk-5UCMYPVF.js → chunk-SVT5IA2H.js} +2 -2
  154. package/dist/{chunk-HVKUCT3W.js → chunk-T4KY6UYF.js} +5 -3
  155. package/dist/{chunk-HVKUCT3W.js.map → chunk-T4KY6UYF.js.map} +1 -1
  156. package/dist/{chunk-FRSHF6FU.js → chunk-TJ4F6H4H.js} +3 -3
  157. package/dist/{chunk-R6HMAIKM.js → chunk-TOSPNM4T.js} +2 -2
  158. package/dist/{chunk-NJJMVS5Y.js → chunk-TRQE3RYR.js} +5 -5
  159. package/dist/{chunk-RMXS4I66.js → chunk-TVDJEUV5.js} +2 -2
  160. package/dist/{chunk-PLCYKAWH.js → chunk-TYRWSE4B.js} +2 -2
  161. package/dist/{chunk-YS2GHSWN.js → chunk-UBEKET2V.js} +389 -39
  162. package/dist/chunk-UBEKET2V.js.map +1 -0
  163. package/dist/{chunk-IQWUACVG.js → chunk-UHMHJX5G.js} +3 -3
  164. package/dist/{chunk-YODUDA6R.js → chunk-UN4RVUG2.js} +22 -22
  165. package/dist/{chunk-KZSGBWOJ.js → chunk-V2KGDESV.js} +2 -2
  166. package/dist/{chunk-E6Z4FBX6.js → chunk-V2QSNFCT.js} +2 -2
  167. package/dist/{chunk-BCCG7VWM.js → chunk-V65H7MI6.js} +396 -13
  168. package/dist/chunk-V65H7MI6.js.map +1 -0
  169. package/dist/chunk-W54Z2MOP.js +4500 -0
  170. package/dist/chunk-W54Z2MOP.js.map +1 -0
  171. package/dist/{chunk-N74SGESS.js → chunk-WKSQTMU7.js} +2 -2
  172. package/dist/{chunk-RIZ5NUNN.js → chunk-WQ4XKIOX.js} +4 -4
  173. package/dist/{chunk-WWK6J6SE.js → chunk-WQURALGV.js} +4996 -2748
  174. package/dist/chunk-WQURALGV.js.map +1 -0
  175. package/dist/{chunk-QEYTRFR3.js → chunk-X26YOFGS.js} +2 -2
  176. package/dist/{chunk-ITHZFHST.js → chunk-X2BVB74H.js} +2 -2
  177. package/dist/{chunk-GNXGJBCA.js → chunk-XIYLWEXC.js} +2 -2
  178. package/dist/{chunk-IBJ6U753.js → chunk-XKZBZOKV.js} +4 -4
  179. package/dist/{chunk-7O2MC42R.js → chunk-XNRLRNQF.js} +2 -2
  180. package/dist/{chunk-65AUYLU3.js → chunk-XPXHQI6N.js} +2 -2
  181. package/dist/{chunk-JBCCWVU2.js → chunk-XRDYRWZI.js} +2 -2
  182. package/dist/chunk-XRWWCW4H.js +102 -0
  183. package/dist/chunk-XRWWCW4H.js.map +1 -0
  184. package/dist/chunk-YKJBSMMP.js +67137 -0
  185. package/dist/chunk-YKJBSMMP.js.map +1 -0
  186. package/dist/{chunk-2JSDPUKD.js → chunk-YMFPFXEX.js} +2 -2
  187. package/dist/{chunk-645WOU5I.js → chunk-ZDZJNXL6.js} +4 -4
  188. package/dist/{chunk-6TCXIRP5.js → chunk-ZKE4CO6B.js} +4 -4
  189. package/dist/{chunk-KEPXC4KN.js → chunk-ZSE774RV.js} +2 -2
  190. package/dist/cli.d.ts.map +1 -1
  191. package/dist/cli.js +305 -187
  192. package/dist/coding/export-okf-codegraph.js +29 -29
  193. package/dist/compounding/engine.js +23 -24
  194. package/dist/config.d.ts.map +1 -1
  195. package/dist/config.js +36 -37
  196. package/dist/connectors/codex-materialize-runner.js +20 -20
  197. package/dist/connectors/index.js +21 -21
  198. package/dist/connectors/live/framework.d.ts +7 -0
  199. package/dist/connectors/live/framework.d.ts.map +1 -1
  200. package/dist/connectors/live/google-drive.d.ts +17 -3
  201. package/dist/connectors/live/google-drive.d.ts.map +1 -1
  202. package/dist/consolidation-provenance-check.js +4 -4
  203. package/dist/consolidation-undo.js +5 -5
  204. package/dist/contradiction/index.js +7 -6
  205. package/dist/{contradiction-scan-P2MHYFVG.js → contradiction-scan-IBPYGQZF.js} +4 -3
  206. package/dist/convergence-refresh.js +22 -22
  207. package/dist/corpus-watermark.js +23 -23
  208. package/dist/deep-recall-http-glue.js +2 -2
  209. package/dist/deep-recall-policy-llm.js +4 -4
  210. package/dist/direct-answer-wiring.js +2 -2
  211. package/dist/embedding-fallback.js +1 -1
  212. package/dist/entity-retrieval.js +21 -21
  213. package/dist/eval-trajectory-store.js +2 -2
  214. package/dist/eval-trajectory.js +2 -2
  215. package/dist/event-order-recall.js +2 -2
  216. package/dist/explicit-capture.d.ts +3 -2
  217. package/dist/explicit-capture.d.ts.map +1 -1
  218. package/dist/explicit-capture.js +530 -6
  219. package/dist/explicit-cue-recall.js +2 -2
  220. package/dist/external-wiki-access.js +2 -283
  221. package/dist/extraction-faithfulness.js +4 -4
  222. package/dist/extraction-judge.js +5 -5
  223. package/dist/extraction-normalization.js +1 -1
  224. package/dist/extraction-quote-grounding.d.ts.map +1 -1
  225. package/dist/extraction-quote-grounding.js +1 -1
  226. package/dist/extraction-source-grounding-rules.js +2 -2
  227. package/dist/extraction-source-grounding.js +3 -3
  228. package/dist/extraction.js +43 -44
  229. package/dist/fallback-llm-codex-subscription.js +2 -2
  230. package/dist/fallback-llm.js +3 -3
  231. package/dist/{first-start-migration-QFI7B5SH.js → first-start-migration-FILJH3RO.js} +6 -5
  232. package/dist/{first-start-migration-QFI7B5SH.js.map → first-start-migration-FILJH3RO.js.map} +1 -1
  233. package/dist/focused-list-recall.js +2 -2
  234. package/dist/harmonic-retrieval.js +20 -20
  235. package/dist/index.js +776 -797
  236. package/dist/lcm/index.js +2 -2
  237. package/dist/live-connectors-runner.d.ts +2 -0
  238. package/dist/live-connectors-runner.d.ts.map +1 -1
  239. package/dist/live-connectors-runner.js +3 -4
  240. package/dist/local-llm-config.js +2 -2
  241. package/dist/local-llm-helpers.d.ts +4 -0
  242. package/dist/local-llm-helpers.d.ts.map +1 -1
  243. package/dist/local-llm-helpers.js +3 -1
  244. package/dist/local-llm.d.ts +4 -1
  245. package/dist/local-llm.d.ts.map +1 -1
  246. package/dist/local-llm.js +4 -4
  247. package/dist/location/index.js +27 -29
  248. package/dist/maintenance/memory-governance.js +20 -20
  249. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +20 -20
  250. package/dist/maintenance/rebuild-memory-projection-runner.js +22 -22
  251. package/dist/maintenance/rebuild-memory-projection.js +21 -21
  252. package/dist/memory-browse-operations.js +2 -283
  253. package/dist/memory-browse.js +8 -7
  254. package/dist/memory-controller.js +2 -2
  255. package/dist/memory-subject.js +2 -2
  256. package/dist/namespaces/migrate.js +21 -21
  257. package/dist/namespaces/search.js +5 -5
  258. package/dist/namespaces/storage.js +20 -20
  259. package/dist/offline-sync-changeset-generations.js +1 -1
  260. package/dist/offline-sync-embedding-generation.js +1 -1
  261. package/dist/offline-sync-impression-drain.js +6 -6
  262. package/dist/offline-sync-snapshot-stream.js +1 -1
  263. package/dist/offline-sync.js +1 -1
  264. package/dist/operator-doctor-corpus.js +24 -24
  265. package/dist/operator-toolkit.js +58 -61
  266. package/dist/orchestration/backlog-scheduler.js +279 -295
  267. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  268. package/dist/orchestration/buffer-drain-runner.js +279 -295
  269. package/dist/orchestration/extraction-run.d.ts +4 -0
  270. package/dist/orchestration/extraction-run.d.ts.map +1 -1
  271. package/dist/orchestration/fact-dedup-window.d.ts +1 -1
  272. package/dist/orchestration/fact-dedup-window.d.ts.map +1 -1
  273. package/dist/orchestration/maintenance.js +39 -42
  274. package/dist/orchestrator.d.ts +11 -11
  275. package/dist/orchestrator.d.ts.map +1 -1
  276. package/dist/orchestrator.js +291 -308
  277. package/dist/page-versioning.js +3 -3
  278. package/dist/qmd-daemon-session.js +2 -2
  279. package/dist/qmd.js +3 -3
  280. package/dist/recall-explain-renderer.js +3 -3
  281. package/dist/recall-navigate-access.js +2 -2
  282. package/dist/recall-navigate-disclosure.js +2 -2
  283. package/dist/recall-navigate.js +2 -2
  284. package/dist/recall-navigation-operations.js +2 -283
  285. package/dist/recall-navigation.js +334 -61
  286. package/dist/recall-planner-llm.js +3 -3
  287. package/dist/recall-state-view-admission.js +6 -6
  288. package/dist/recall-why-service.js +10 -9
  289. package/dist/recall-why.js +4 -3
  290. package/dist/recall-xray-cli.js +4 -4
  291. package/dist/recall-xray-renderer.js +3 -3
  292. package/dist/recall-xray.js +2 -2
  293. package/dist/reconcile/manifest.js +3 -3
  294. package/dist/{resolution-N7H3F2E4.js → resolution-OVVIF7ZY.js} +8 -7
  295. package/dist/response-guidance-recall.js +2 -2
  296. package/dist/resume-bundles.js +40 -41
  297. package/dist/salvage-envelope.js +4 -4
  298. package/dist/search/factory.js +4 -4
  299. package/dist/search/index.js +4 -4
  300. package/dist/semantic-consolidation.js +23 -23
  301. package/dist/semantic-rule-promotion.js +20 -20
  302. package/dist/semantic-rule-verifier.js +20 -20
  303. package/dist/shared-context/manager.js +2 -3
  304. package/dist/source-agent-qualifier.js +32 -33
  305. package/dist/standup/build.js +20 -20
  306. package/dist/{state-store-I5HLZTZT.js → state-store-EEAX2MBS.js} +2 -2
  307. package/dist/storage/content-hash-index.d.ts +10 -0
  308. package/dist/storage/content-hash-index.d.ts.map +1 -1
  309. package/dist/storage.js +19 -19
  310. package/dist/subject-config.js +3 -3
  311. package/dist/summarizer.d.ts +4 -1
  312. package/dist/summarizer.d.ts.map +1 -1
  313. package/dist/summarizer.js +6 -6
  314. package/dist/support-passport/index.js +53 -297
  315. package/dist/targeted-fact-recall.js +2 -2
  316. package/dist/tier-routing.js +3 -2
  317. package/dist/{tier-stats-FQGQSFET.js → tier-stats-FXEUJN73.js} +6 -5
  318. package/dist/{tier-stats-FQGQSFET.js.map → tier-stats-FXEUJN73.js.map} +1 -1
  319. package/dist/transcript.js +2 -2
  320. package/dist/transfer/capsule-import.js +4 -4
  321. package/dist/transfer/export-okf.js +20 -20
  322. package/dist/types.d.ts +10 -10
  323. package/dist/types.d.ts.map +1 -1
  324. package/dist/types.js +1 -1
  325. package/dist/verified-recall.js +20 -20
  326. package/dist/wearables/memory-gen.d.ts +5 -1
  327. package/dist/wearables/memory-gen.d.ts.map +1 -1
  328. package/dist/wearables/service.d.ts.map +1 -1
  329. package/dist/who-knows-cli.js +21 -21
  330. package/dist/who-knows.js +20 -20
  331. package/dist/write-envelope.js +3 -3
  332. package/package.json +2 -2
  333. package/src/access-boundary.ts +5 -1
  334. package/src/access-category-alias.test.ts +5 -0
  335. package/src/access-mcp-frames.test.ts +60 -5
  336. package/src/access-mcp-frames.ts +72 -18
  337. package/src/access-mcp.test.ts +66 -2
  338. package/src/access-mcp.ts +19 -13
  339. package/src/access-service-coding-write.test.ts +7 -0
  340. package/src/access-service.ts +3 -0
  341. package/src/activity/journal-extract-storage.test.ts +31 -0
  342. package/src/activity/journal-extract.test.ts +1 -0
  343. package/src/activity/journal-extract.ts +24 -3
  344. package/src/cli.ts +1 -2
  345. package/src/config.test.ts +17 -0
  346. package/src/config.ts +25 -7
  347. package/src/connectors/live/framework.ts +8 -0
  348. package/src/connectors/live/google-drive.test.ts +74 -0
  349. package/src/connectors/live/google-drive.ts +138 -11
  350. package/src/explicit-capture.test.ts +109 -17
  351. package/src/explicit-capture.ts +90 -37
  352. package/src/extraction-quote-grounding.test.ts +20 -0
  353. package/src/extraction-quote-grounding.ts +21 -11
  354. package/src/fact-dedup-window.test.ts +37 -0
  355. package/src/live-connectors-runner.ts +3 -0
  356. package/src/live-connectors-secretref.test.ts +126 -0
  357. package/src/local-llm-helpers.ts +12 -0
  358. package/src/local-llm-shutdown.test.ts +194 -0
  359. package/src/local-llm.ts +32 -30
  360. package/src/orchestration/extraction-run.ts +12 -3
  361. package/src/orchestration/fact-dedup-window.ts +5 -1
  362. package/src/orchestrator-connector-dedup.test.ts +9 -5
  363. package/src/orchestrator.ts +52 -55
  364. package/src/storage/content-hash-index.ts +27 -2
  365. package/src/storage-fact-hash-publish-failure.test.ts +87 -0
  366. package/src/summarizer-shutdown.test.ts +195 -0
  367. package/src/summarizer.ts +15 -2
  368. package/src/types.ts +10 -10
  369. package/src/wearables/memory-gen.test.ts +20 -0
  370. package/src/wearables/memory-gen.ts +14 -7
  371. package/src/wearables/service.ts +14 -1
  372. package/src/wearables/storage-io.test.ts +25 -0
  373. package/dist/chunk-27XYV2XL.js +0 -43
  374. package/dist/chunk-27XYV2XL.js.map +0 -1
  375. package/dist/chunk-5KBIOI4G.js.map +0 -1
  376. package/dist/chunk-66L5ZRJC.js.map +0 -1
  377. package/dist/chunk-7HTUYFR3.js.map +0 -1
  378. package/dist/chunk-AOFEMUHG.js.map +0 -1
  379. package/dist/chunk-AP6NCP3V.js.map +0 -1
  380. package/dist/chunk-APYY5CX3.js +0 -335
  381. package/dist/chunk-APYY5CX3.js.map +0 -1
  382. package/dist/chunk-ATPWMT2E.js +0 -223
  383. package/dist/chunk-ATPWMT2E.js.map +0 -1
  384. package/dist/chunk-BCCG7VWM.js.map +0 -1
  385. package/dist/chunk-E6M225BJ.js.map +0 -1
  386. package/dist/chunk-EQ4U73UH.js.map +0 -1
  387. package/dist/chunk-ETSJD5IV.js +0 -361
  388. package/dist/chunk-ETSJD5IV.js.map +0 -1
  389. package/dist/chunk-EWJZZDRG.js.map +0 -1
  390. package/dist/chunk-FHGWKODN.js +0 -2300
  391. package/dist/chunk-FHGWKODN.js.map +0 -1
  392. package/dist/chunk-GRTKLWYX.js +0 -621
  393. package/dist/chunk-GRTKLWYX.js.map +0 -1
  394. package/dist/chunk-IGLJNHOX.js +0 -62
  395. package/dist/chunk-IGLJNHOX.js.map +0 -1
  396. package/dist/chunk-IPT2OY4B.js.map +0 -1
  397. package/dist/chunk-IUKYFTGW.js.map +0 -1
  398. package/dist/chunk-KUIRDD74.js +0 -3991
  399. package/dist/chunk-KUIRDD74.js.map +0 -1
  400. package/dist/chunk-MVMRUGBH.js +0 -1919
  401. package/dist/chunk-MVMRUGBH.js.map +0 -1
  402. package/dist/chunk-ODL4ZTNI.js +0 -3644
  403. package/dist/chunk-ODL4ZTNI.js.map +0 -1
  404. package/dist/chunk-OGXXGHW6.js +0 -223
  405. package/dist/chunk-OGXXGHW6.js.map +0 -1
  406. package/dist/chunk-P5VZSSYL.js.map +0 -1
  407. package/dist/chunk-PPCLZ4JU.js +0 -28
  408. package/dist/chunk-PPCLZ4JU.js.map +0 -1
  409. package/dist/chunk-PUEO37QG.js.map +0 -1
  410. package/dist/chunk-RRTVGD3J.js +0 -792
  411. package/dist/chunk-RRTVGD3J.js.map +0 -1
  412. package/dist/chunk-STSLB4HT.js +0 -18793
  413. package/dist/chunk-STSLB4HT.js.map +0 -1
  414. package/dist/chunk-T6OZW2WR.js.map +0 -1
  415. package/dist/chunk-TRBGGJKZ.js +0 -32218
  416. package/dist/chunk-TRBGGJKZ.js.map +0 -1
  417. package/dist/chunk-UDKWFDV2.js.map +0 -1
  418. package/dist/chunk-V4XE263I.js.map +0 -1
  419. package/dist/chunk-V7IZKJI3.js +0 -22
  420. package/dist/chunk-V7IZKJI3.js.map +0 -1
  421. package/dist/chunk-VMVVSZTD.js +0 -61
  422. package/dist/chunk-VMVVSZTD.js.map +0 -1
  423. package/dist/chunk-VNUOAXWP.js +0 -203
  424. package/dist/chunk-VNUOAXWP.js.map +0 -1
  425. package/dist/chunk-WLBEZZK5.js +0 -729
  426. package/dist/chunk-WLBEZZK5.js.map +0 -1
  427. package/dist/chunk-WUUES6CU.js +0 -25
  428. package/dist/chunk-WUUES6CU.js.map +0 -1
  429. package/dist/chunk-WWK6J6SE.js.map +0 -1
  430. package/dist/chunk-XICOH5HT.js +0 -346
  431. package/dist/chunk-XICOH5HT.js.map +0 -1
  432. package/dist/chunk-YCNIGRRF.js.map +0 -1
  433. package/dist/chunk-YS2GHSWN.js.map +0 -1
  434. package/dist/chunk-ZCLEYJPB.js +0 -10143
  435. package/dist/chunk-ZCLEYJPB.js.map +0 -1
  436. /package/dist/{capsule-merge-2IIXFXN5.js.map → capsule-merge-6IDAYTKG.js.map} +0 -0
  437. /package/dist/{chunk-QL7RHYK6.js.map → chunk-2LMA22UU.js.map} +0 -0
  438. /package/dist/{chunk-RGUUBAT5.js.map → chunk-2WCLTWV2.js.map} +0 -0
  439. /package/dist/{chunk-RSK2WIEM.js.map → chunk-2YODOG2O.js.map} +0 -0
  440. /package/dist/{chunk-WYG5UNDY.js.map → chunk-3AUDELZL.js.map} +0 -0
  441. /package/dist/{chunk-OFVCFKDH.js.map → chunk-3CYOCE6U.js.map} +0 -0
  442. /package/dist/{chunk-6HM6HARE.js.map → chunk-3FBAEPCU.js.map} +0 -0
  443. /package/dist/{chunk-PIITB2YZ.js.map → chunk-3ZS3NUEI.js.map} +0 -0
  444. /package/dist/{chunk-ANZZLRUX.js.map → chunk-4IVRQMZW.js.map} +0 -0
  445. /package/dist/{chunk-63E37JCN.js.map → chunk-4RAJT5L2.js.map} +0 -0
  446. /package/dist/{chunk-45VUHDV2.js.map → chunk-5CO5G4MN.js.map} +0 -0
  447. /package/dist/{chunk-3UMDRGFS.js.map → chunk-65HWAQ4F.js.map} +0 -0
  448. /package/dist/{chunk-T67LUYCR.js.map → chunk-77NTFICT.js.map} +0 -0
  449. /package/dist/{chunk-UE6RRXMF.js.map → chunk-A4F7OIC5.js.map} +0 -0
  450. /package/dist/{chunk-63O7LVMN.js.map → chunk-B33YWUJV.js.map} +0 -0
  451. /package/dist/{chunk-QVMOCJRV.js.map → chunk-B377OKUP.js.map} +0 -0
  452. /package/dist/{chunk-ZT6WPSII.js.map → chunk-BGHCSLE5.js.map} +0 -0
  453. /package/dist/{chunk-YYOMGOHB.js.map → chunk-BOK6BN5M.js.map} +0 -0
  454. /package/dist/{chunk-OH7QLI6W.js.map → chunk-BPPUH5JM.js.map} +0 -0
  455. /package/dist/{chunk-EV76IZ37.js.map → chunk-BTI4C4MA.js.map} +0 -0
  456. /package/dist/{chunk-O6ZSWHVR.js.map → chunk-C2KE5DMD.js.map} +0 -0
  457. /package/dist/{chunk-47F6WWLQ.js.map → chunk-C73N66PR.js.map} +0 -0
  458. /package/dist/{chunk-3XIWW4TB.js.map → chunk-CGJYL633.js.map} +0 -0
  459. /package/dist/{chunk-WRT7GJ2D.js.map → chunk-CIWMTNHW.js.map} +0 -0
  460. /package/dist/{chunk-O55EKIEC.js.map → chunk-D3ZKHLN2.js.map} +0 -0
  461. /package/dist/{chunk-CD4BCCNP.js.map → chunk-DJ7WVEWX.js.map} +0 -0
  462. /package/dist/{chunk-RO7RUBLD.js.map → chunk-EFL24KOI.js.map} +0 -0
  463. /package/dist/{chunk-4CJTQHEG.js.map → chunk-ESLOLCD4.js.map} +0 -0
  464. /package/dist/{chunk-Z4Q6USKJ.js.map → chunk-ETBVCRVL.js.map} +0 -0
  465. /package/dist/{chunk-VILPVT4S.js.map → chunk-EZ47HOJ6.js.map} +0 -0
  466. /package/dist/{chunk-EFYN5I7Z.js.map → chunk-F4QFU5IZ.js.map} +0 -0
  467. /package/dist/{chunk-SHUBTAY2.js.map → chunk-FMKILENU.js.map} +0 -0
  468. /package/dist/{chunk-YLXETSAH.js.map → chunk-GCZJ7XRI.js.map} +0 -0
  469. /package/dist/{chunk-QFEDITXM.js.map → chunk-JNDMIAJ4.js.map} +0 -0
  470. /package/dist/{chunk-E5PPE4VA.js.map → chunk-K2VRKCPA.js.map} +0 -0
  471. /package/dist/{chunk-MKRYQROF.js.map → chunk-LGEHAQHK.js.map} +0 -0
  472. /package/dist/{chunk-XYTQJD7F.js.map → chunk-LMJVP5CM.js.map} +0 -0
  473. /package/dist/{chunk-JC36FPQ5.js.map → chunk-LPV72KRQ.js.map} +0 -0
  474. /package/dist/{chunk-2LCRG2YV.js.map → chunk-M2XR6B6V.js.map} +0 -0
  475. /package/dist/{chunk-VPQFK63H.js.map → chunk-MH632KPO.js.map} +0 -0
  476. /package/dist/{chunk-ZU5JDLOH.js.map → chunk-MMRTPH3J.js.map} +0 -0
  477. /package/dist/{chunk-ZZ67UTQX.js.map → chunk-MUX7IL77.js.map} +0 -0
  478. /package/dist/{chunk-RYWROSL5.js.map → chunk-NAQ4A5IX.js.map} +0 -0
  479. /package/dist/{chunk-TVIVY7KU.js.map → chunk-NED7IR7B.js.map} +0 -0
  480. /package/dist/{chunk-ADYP7HXE.js.map → chunk-NHVAX7MH.js.map} +0 -0
  481. /package/dist/{chunk-TG3R2SID.js.map → chunk-NMGHGTVR.js.map} +0 -0
  482. /package/dist/{chunk-NGHDW6UU.js.map → chunk-NUQEREIP.js.map} +0 -0
  483. /package/dist/{chunk-5IIQU4JZ.js.map → chunk-OB72KNMF.js.map} +0 -0
  484. /package/dist/{chunk-7L3TODI7.js.map → chunk-OJXJWNFY.js.map} +0 -0
  485. /package/dist/{chunk-EURPSF4Y.js.map → chunk-PH5ZQM35.js.map} +0 -0
  486. /package/dist/{chunk-BMWMTAQF.js.map → chunk-PRAUN6PN.js.map} +0 -0
  487. /package/dist/{chunk-RWGRSKN5.js.map → chunk-PT4DZDJA.js.map} +0 -0
  488. /package/dist/{chunk-7EPY3IQL.js.map → chunk-PZJQ46DH.js.map} +0 -0
  489. /package/dist/{chunk-AH637HZ5.js.map → chunk-QDESY76F.js.map} +0 -0
  490. /package/dist/{chunk-I6QGI65T.js.map → chunk-QRMG4HK4.js.map} +0 -0
  491. /package/dist/{chunk-ZU3NJNO7.js.map → chunk-QSF5SJAM.js.map} +0 -0
  492. /package/dist/{chunk-5IYOKDM4.js.map → chunk-R23JWJD3.js.map} +0 -0
  493. /package/dist/{chunk-LJQFJF4J.js.map → chunk-RM2YUFH6.js.map} +0 -0
  494. /package/dist/{chunk-6QMWECO5.js.map → chunk-SGQPR5SX.js.map} +0 -0
  495. /package/dist/{chunk-ZGFLIK5H.js.map → chunk-SPAKBUJY.js.map} +0 -0
  496. /package/dist/{chunk-ER7XANP3.js.map → chunk-SQ3GEIEL.js.map} +0 -0
  497. /package/dist/{chunk-5UCMYPVF.js.map → chunk-SVT5IA2H.js.map} +0 -0
  498. /package/dist/{chunk-FRSHF6FU.js.map → chunk-TJ4F6H4H.js.map} +0 -0
  499. /package/dist/{chunk-R6HMAIKM.js.map → chunk-TOSPNM4T.js.map} +0 -0
  500. /package/dist/{chunk-NJJMVS5Y.js.map → chunk-TRQE3RYR.js.map} +0 -0
  501. /package/dist/{chunk-RMXS4I66.js.map → chunk-TVDJEUV5.js.map} +0 -0
  502. /package/dist/{chunk-PLCYKAWH.js.map → chunk-TYRWSE4B.js.map} +0 -0
  503. /package/dist/{chunk-IQWUACVG.js.map → chunk-UHMHJX5G.js.map} +0 -0
  504. /package/dist/{chunk-YODUDA6R.js.map → chunk-UN4RVUG2.js.map} +0 -0
  505. /package/dist/{chunk-KZSGBWOJ.js.map → chunk-V2KGDESV.js.map} +0 -0
  506. /package/dist/{chunk-E6Z4FBX6.js.map → chunk-V2QSNFCT.js.map} +0 -0
  507. /package/dist/{chunk-N74SGESS.js.map → chunk-WKSQTMU7.js.map} +0 -0
  508. /package/dist/{chunk-RIZ5NUNN.js.map → chunk-WQ4XKIOX.js.map} +0 -0
  509. /package/dist/{chunk-QEYTRFR3.js.map → chunk-X26YOFGS.js.map} +0 -0
  510. /package/dist/{chunk-ITHZFHST.js.map → chunk-X2BVB74H.js.map} +0 -0
  511. /package/dist/{chunk-GNXGJBCA.js.map → chunk-XIYLWEXC.js.map} +0 -0
  512. /package/dist/{chunk-IBJ6U753.js.map → chunk-XKZBZOKV.js.map} +0 -0
  513. /package/dist/{chunk-7O2MC42R.js.map → chunk-XNRLRNQF.js.map} +0 -0
  514. /package/dist/{chunk-65AUYLU3.js.map → chunk-XPXHQI6N.js.map} +0 -0
  515. /package/dist/{chunk-JBCCWVU2.js.map → chunk-XRDYRWZI.js.map} +0 -0
  516. /package/dist/{chunk-2JSDPUKD.js.map → chunk-YMFPFXEX.js.map} +0 -0
  517. /package/dist/{chunk-645WOU5I.js.map → chunk-ZDZJNXL6.js.map} +0 -0
  518. /package/dist/{chunk-6TCXIRP5.js.map → chunk-ZKE4CO6B.js.map} +0 -0
  519. /package/dist/{chunk-KEPXC4KN.js.map → chunk-ZSE774RV.js.map} +0 -0
  520. /package/dist/{contradiction-scan-P2MHYFVG.js.map → contradiction-scan-IBPYGQZF.js.map} +0 -0
  521. /package/dist/{resolution-N7H3F2E4.js.map → resolution-OVVIF7ZY.js.map} +0 -0
  522. /package/dist/{state-store-I5HLZTZT.js.map → state-store-EEAX2MBS.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/summarizer.ts"],"sourcesContent":["import { mkdir, readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { log } from \"./logger.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport {\n completeBackgroundGeneration,\n parseBackgroundGenerationJson,\n} from \"./background-generation.js\";\nimport type { HourlySummary, TranscriptEntry, PluginConfig, GatewayConfig } from \"./types.js\";\nimport type { TranscriptManager } from \"./transcript.js\";\nimport { readSummarySnapshot, upsertSummarySnapshot, writeSummarySnapshot } from \"./summary-snapshot.js\";\nimport { encodeStoragePathSegment, resolveSafeStoragePath } from \"./storage-paths.js\";\nimport { sessionStoragePaths } from \"./session-identity.js\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\n\n// Schema for LLM summary output\nconst HourlySummarySchema = z.object({\n bullets: z.array(z.string().trim().min(1)).min(1).describe(\"3-5 bullet points summarizing the hour's activity\"),\n});\n\ntype HourlySummaryResult = z.infer<typeof HourlySummarySchema>;\n\nconst HourlySummaryExtendedSchema = z.object({\n topics: z.array(z.string()).default([]),\n decisions: z.array(z.string()).default([]),\n actionItems: z.array(z.string()).default([]),\n rejected: z.array(z.string()).default([]),\n});\n\ntype HourlySummaryExtendedResult = z.infer<typeof HourlySummaryExtendedSchema>;\n\ntype HourlySummaryExtendedMeta = {\n userTurns: number;\n assistantTurns: number;\n toolCalls: number;\n toolCounts: Record<string, number>;\n};\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Outcome stats of one `runHourly` pass (issue #2783). The summarizer must\n * not report success on empty work: an empty or stale transcript store is\n * the delegate-mode starvation signature, and callers surface these counts\n * and the staleness flag as a distinct warning instead of a bare ok.\n */\nexport interface HourlySummarizerRunStats {\n sessionsConsidered: number;\n sessionsWithEntries: number;\n summariesWritten: number;\n /** True when the newest transcript entry across the store is older than STALE_STORE_MS. */\n staleStore: boolean;\n /** ISO timestamp of the newest transcript entry seen by the scan, when any exist. */\n newestEntryTimestamp: string | null;\n /** True when the transcript scan itself FAILED (unreadable store) — distinct from an empty store. */\n scanFailed: boolean;\n}\n\n/** A store whose newest entry is older than this is considered stale (starvation signal, issue #2783). */\nconst STALE_STORE_MS = 2 * 60 * 60 * 1000;\n\n/**\n * Interpret one {@link HourlySummarizerRunStats} into the operator-facing\n * message/warning (issue #2783). Every degraded shape — failed scan, empty\n * store, backend-down, stale store — is DISTINCT from success; monitoring\n * alerts on `warning`, never on `ok` (ok only means \"the run completed\").\n */\nexport function summarizeHourlyStatus(stats: HourlySummarizerRunStats): {\n message: string;\n warning?: string;\n} {\n if (stats.scanFailed) {\n return {\n message:\n \"Hourly summarization completed, but the transcript store scan FAILED (unreadable directory or I/O error). Investigate the daemon's memoryDir.\",\n warning: \"transcript store scan failed\",\n };\n }\n if (stats.sessionsConsidered === 0) {\n return {\n message:\n \"Hourly summarization completed, but the transcript store is empty — no sessions found. If turns are ingested via observe, transcript persistence may be disabled or failing.\",\n warning: \"transcript store is empty\",\n };\n }\n if (stats.sessionsWithEntries > 0 && stats.summariesWritten === 0) {\n return {\n message: `Hourly summarization found ${stats.sessionsWithEntries} session(s) with transcript entries but wrote no summaries — the summarizer backend may be down.`,\n warning: \"sessions with entries produced no summaries\",\n };\n }\n if (stats.sessionsWithEntries === 0 && stats.staleStore) {\n return {\n message: `Hourly summarization completed with no transcript entries for the target hour, and the store looks stale (newest entry ${stats.newestEntryTimestamp ?? \"unknown\"}).`,\n warning: \"no transcript entries for the target hour and no new entries recently\",\n };\n }\n return {\n message: `Hourly summarization completed: ${stats.summariesWritten} summar${stats.summariesWritten === 1 ? \"y\" : \"ies\"} written across ${stats.sessionsWithEntries} session${stats.sessionsWithEntries === 1 ? \"\" : \"s\"} with transcript entries.`,\n };\n}\n\nexport class HourlySummarizer {\n private summariesDir: string;\n private config: PluginConfig;\n private localLlm: LocalLlmClient;\n private fallbackLlm: FallbackLlmClient;\n private modelRegistry: ModelRegistry;\n private transcript?: TranscriptManager;\n\n constructor(\n config: PluginConfig,\n gatewayConfig?: GatewayConfig,\n modelRegistry?: ModelRegistry,\n transcript?: TranscriptManager\n ) {\n this.config = config;\n this.summariesDir = path.join(config.memoryDir, \"summaries\", \"hourly\");\n this.modelRegistry = modelRegistry ?? new ModelRegistry(config.memoryDir);\n this.transcript = transcript;\n\n // Initialize local LLM client with shared model registry\n this.localLlm = new LocalLlmClient(config, this.modelRegistry);\n\n // Initialize fallback client with gateway config\n this.fallbackLlm = new FallbackLlmClient(gatewayConfig, fallbackLlmRuntimeContextFromConfig(config));\n\n if (\n !gatewayConfig?.agents?.defaults?.model?.primary &&\n !resolveLocalLlmCapabilities(config).localLlm &&\n config.modelSource !== \"gateway\"\n ) {\n log.warn(\"no gateway default AI and local LLM disabled — hourly summarization disabled\");\n }\n }\n\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n private get shouldUseLocalLlm(): boolean {\n return resolveLocalLlmCapabilities(this.config).localLlm && !this.useGatewayModelSource;\n }\n\n private withGatewayAgent(\n options: import(\"./fallback-llm.js\").FallbackLlmOptions\n ): import(\"./fallback-llm.js\").FallbackLlmOptions {\n if (!this.useGatewayModelSource) return options;\n // Shared resolution (taskModelChain > gatewayAgentId) — gotcha #22. Issue #1365.\n return { ...options, ...gatewayTaskChainOptions(this.config) };\n }\n\n async initialize(): Promise<void> {\n await mkdir(this.summariesDir, { recursive: true });\n log.info(\"hourly summarizer initialized\");\n }\n\n private async summarySessionDir(sessionKey: string): Promise<string> {\n return resolveSafeStoragePath(this.summariesDir, encodeStoragePathSegment(sessionKey, \"session\"));\n }\n\n private async legacySummarySessionDir(sessionKey: string): Promise<string | null> {\n if (sessionKey.includes(\"\\0\")) return null;\n try {\n return await resolveSafeStoragePath(this.summariesDir, sessionKey);\n } catch {\n return null;\n }\n }\n\n private summaryDateString(hour: string): string {\n const dateStr = hour.slice(0, 10);\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateStr)) {\n throw new Error(`invalid hourly summary timestamp: ${hour}`);\n }\n return dateStr;\n }\n\n // Generate summary for a specific hour and session\n async generateSummary(\n sessionKey: string,\n hourStart: Date,\n entries: TranscriptEntry[]\n ): Promise<HourlySummary | null> {\n if (entries.length === 0) return null;\n\n // Format entries for the LLM\n const conversation = entries.map((e) => `[${e.role}] ${e.content}`).join(\"\\n\\n\");\n\n if (resolvePipelineProcessingCapabilities(this.config).hourlySummariesExtended) {\n const extended = await this.generateExtended(sessionKey, hourStart, conversation, entries);\n if (!extended) return null;\n const meta: HourlySummaryExtendedMeta = {\n userTurns: entries.filter((e) => e.role === \"user\").length,\n assistantTurns: entries.filter((e) => e.role === \"assistant\").length,\n toolCalls: extended._meta.toolCalls,\n toolCounts: extended._meta.toolCounts,\n };\n // Keep HourlySummary surface stable; encode \"topics\" as bullets for recall injection.\n const base: HourlySummary = {\n hour: hourStart.toISOString(),\n sessionKey,\n bullets: extended.topics.length > 0 ? extended.topics.slice(0, 5) : [\"(summary generated)\"],\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n const withExtras = base as any;\n withExtras._extended = extended;\n withExtras._extendedMeta = meta;\n return base;\n }\n\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n if (this.config.backgroundGeneration) {\n try {\n const text = await completeBackgroundGeneration(this.config, [\n {\n role: \"system\",\n content:\n \"You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\\n\\nGuidelines:\\n- Focus on what was accomplished, decided, or discussed\\n- Include specific topics, projects, or entities mentioned\\n- Note any significant user requests or agent actions\\n- Keep bullets brief but informative (1-2 sentences each)\\n- Skip trivial greetings or meta-conversation\\n- Use present tense for ongoing work, past for completed items\\n\\nRespond with valid JSON only, matching this schema:\\n{\\\"bullets\\\": [\\\"bullet 1\\\", \\\"bullet 2\\\", \\\"bullet 3\\\"]}\",\n },\n { role: \"user\", content: `Summarize this conversation:\\n\\n${conversation}` },\n ]);\n const parsed = parseBackgroundGenerationJson(text, (value) => HourlySummarySchema.parse(value));\n if (parsed) {\n return {\n hour: hourIso,\n sessionKey,\n bullets: parsed.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n } catch {\n log.info(\"summary generation: background generation unavailable, continuing\");\n }\n }\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.generateWithLocalLlm(conversation);\n if (localResult) {\n const durationMs = Date.now() - startTime;\n log.debug(`generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms using local LLM`);\n return {\n hour: hourIso,\n sessionKey,\n bullets: localResult.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n // Local failed, fall back if allowed\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"summary generation: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"summary generation: local LLM error, falling back to gateway default AI:\", err);\n }\n }\n\n // Fall back to gateway's default AI\n log.info(\"summary generation: falling back to gateway default AI\");\n\n try {\n const messages = [\n {\n role: \"system\" as const,\n content: `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`,\n },\n { role: \"user\" as const, content: `Summarize this conversation:\\n\\n${conversation}` },\n ];\n\n const result = await this.fallbackLlm.parseWithSchema(\n messages,\n HourlySummarySchema,\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 8192 })\n );\n\n const durationMs = Date.now() - startTime;\n\n if (result) {\n log.debug(`generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms via fallback`);\n return {\n hour: hourIso,\n sessionKey,\n bullets: result.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n\n log.warn(\"summary generation fallback returned no parsed output\");\n return null;\n } catch (err) {\n log.error(\"summary generation fallback failed\", err);\n return null;\n }\n }\n\n private async generateExtended(\n sessionKey: string,\n hourStart: Date,\n conversation: string,\n entries: TranscriptEntry[]\n ): Promise<(HourlySummaryExtendedResult & { _meta: HourlySummaryExtendedMeta }) | null> {\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n let toolCounts: Record<string, number> = {};\n if (this.config.hourlySummariesIncludeToolStats && this.transcript) {\n const uses = await this.transcript.readToolUse(sessionKey, hourStart, hourEnd);\n for (const u of uses) toolCounts[u.tool] = (toolCounts[u.tool] ?? 0) + 1;\n }\n\n const sys = `You are a conversation summarization system.\\n\\nSummarize the hour into structured sections.\\n\\nReturn valid JSON matching:\\n{\\n \\\"topics\\\": [\\\"...\\\"],\\n \\\"decisions\\\": [\\\"...\\\"],\\n \\\"actionItems\\\": [\\\"...\\\"],\\n \\\"rejected\\\": [\\\"...\\\"]\\n}\\n\\nGuidelines:\\n- Prefer concrete topics and decisions.\\n- Action items should be imperative.\\n- Rejected ideas are things that were explicitly discarded or reversed.\\n- If there are none for a section, return an empty array.\\n`;\n\n const toolStatsLine =\n Object.keys(toolCounts).length > 0\n ? `Tools used (counts): ${Object.entries(toolCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([k, v]) => `${k}=${v}`)\n .join(\", \")}\\n\\n`\n : \"\";\n const userTurns = entries.filter((e) => e.role === \"user\").length;\n const assistantTurns = entries.filter((e) => e.role === \"assistant\").length;\n const toolCalls = Object.values(toolCounts).reduce((a, b) => a + b, 0);\n const statsLine = `Stats: userTurns=${userTurns}, assistantTurns=${assistantTurns}, toolCalls=${toolCalls}\\n\\n`;\n\n const user = `Hour: ${hourIso}\\nSession: ${sessionKey}\\n\\n${statsLine}${toolStatsLine}Conversation:\\n${conversation}\\n`;\n\n if (this.config.backgroundGeneration) {\n try {\n const text = await completeBackgroundGeneration(this.config, [\n { role: \"system\", content: sys },\n { role: \"user\", content: user },\n ]);\n const parsed = parseBackgroundGenerationJson(text, (value) => HourlySummaryExtendedSchema.parse(value));\n if (parsed) {\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (background)`\n );\n return { ...parsed, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n }\n } catch {\n log.info(\"extended summary: background generation unavailable, continuing\");\n }\n }\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n const truncated =\n user.length > contextSizes.maxInputChars\n ? user.slice(0, contextSizes.maxInputChars) + \"\\n\\n[truncated]\"\n : user;\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"Output valid JSON only.\" },\n { role: \"user\", content: sys + \"\\n\\n\" + truncated },\n ],\n {\n temperature: 0.2,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary_extended\",\n priority: \"background\",\n }\n );\n if (response?.content) {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n const result = HourlySummaryExtendedSchema.parse(parsed);\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (local)`\n );\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n } catch {\n // keep trying candidates\n }\n }\n }\n } catch (err) {\n if (!this.config.localLlmFallback) return null;\n log.info(\"extended summary: local failed, falling back:\", err);\n }\n }\n\n try {\n const result = await this.fallbackLlm.parseWithSchema(\n [\n { role: \"system\" as const, content: sys },\n { role: \"user\" as const, content: user },\n ],\n HourlySummaryExtendedSchema,\n this.withGatewayAgent({ temperature: 0.2, maxTokens: 2048 })\n );\n if (result) {\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (fallback)`\n );\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n }\n return null;\n } catch (err) {\n log.error(\"extended summary generation failed\", err);\n return null;\n }\n }\n\n /**\n * Generate summary using local LLM with JSON mode.\n * Uses dynamic context sizing based on model capabilities.\n */\n private async generateWithLocalLlm(conversation: string): Promise<HourlySummaryResult | null> {\n // Get dynamic context sizes based on model capabilities\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Summarizer model context: ${contextSizes.description}`);\n\n const maxConversationChars = contextSizes.maxInputChars;\n const truncatedConversation =\n conversation.length > maxConversationChars\n ? conversation.slice(0, maxConversationChars) + \"\\n\\n[truncated]\"\n : conversation;\n\n const instructions = `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`;\n\n const fullPrompt = `${instructions}\\n\\nConversation to summarize:\\n${truncatedConversation}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a conversation summarization system. Output valid JSON only.\" },\n { role: \"user\", content: fullPrompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary\",\n priority: \"background\",\n }\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n // Parse JSON response\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return HourlySummarySchema.parse(parsed);\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM summary: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n // Save summary to file\n async saveSummary(summary: HourlySummary): Promise<void> {\n const sessionDir = await this.summarySessionDir(summary.sessionKey);\n await mkdir(sessionDir, { recursive: true });\n\n // Format date as YYYY-MM-DD for the filename\n const dateStr = this.summaryDateString(summary.hour);\n const filePath = await resolveSafeStoragePath(sessionDir, `${dateStr}.md`);\n\n // Format hour as HH:00 for display\n const hourStr = summary.hour.slice(11, 13);\n\n // Build markdown content\n const lines: string[] = [];\n\n // Check if file exists to append or create\n let existingContent = \"\";\n try {\n existingContent = await readFile(filePath, \"utf-8\");\n } catch {\n // File doesn't exist yet, will create new\n }\n\n // Check if this hour already exists (idempotent)\n const hourHeader = `## ${hourStr}:00`;\n if (existingContent.includes(hourHeader)) {\n // Replace existing hour section\n const headerMatch = new RegExp(`(^|\\\\n)${escapeRegExp(hourHeader)}\\\\n`).exec(existingContent);\n const sectionStart = headerMatch\n ? headerMatch.index + headerMatch[1].length\n : existingContent.indexOf(hourHeader);\n const nextHeaderPattern = /\\n## \\d{2}:00\\n/g;\n nextHeaderPattern.lastIndex = sectionStart + hourHeader.length;\n const nextHeader = nextHeaderPattern.exec(existingContent);\n const beforeHour = existingContent.slice(0, sectionStart);\n const afterHour = nextHeader ? existingContent.slice(nextHeader.index + 1) : \"\";\n const newSection = this.formatHourSection(summary, hourHeader);\n existingContent = beforeHour + newSection.trimEnd() + (afterHour ? \"\\n\\n\" + afterHour : \"\\n\");\n\n await writeFile(filePath, existingContent, \"utf-8\");\n log.debug(`updated hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n } else {\n // Append new hour section\n const newSection = this.formatHourSection(summary, hourHeader);\n\n if (existingContent) {\n // Add to existing file\n await writeFile(filePath, existingContent.trimEnd() + \"\\n\\n\" + newSection, \"utf-8\");\n } else {\n // Create new file with header\n const header = `# Hourly Summaries — ${dateStr}\\n\\n*Session: ${summary.sessionKey}*\\n`;\n await writeFile(filePath, header + \"\\n\" + newSection, \"utf-8\");\n }\n log.debug(`saved hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n }\n try {\n await upsertSummarySnapshot(this.config.memoryDir, summary);\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to update summary snapshot for ${summary.sessionKey} (fail-open): ${String(error)}`\n );\n }\n }\n\n private formatHourSection(summary: HourlySummary, hourHeader: string): string {\n const ext = (summary as any)._extended as\n | (HourlySummaryExtendedResult & { _meta?: HourlySummaryExtendedMeta })\n | undefined;\n const meta = (summary as any)._extendedMeta as HourlySummaryExtendedMeta | undefined;\n const lines: string[] = [hourHeader, \"\"];\n\n if (resolvePipelineProcessingCapabilities(this.config).hourlySummariesExtended && ext) {\n lines.push(\"### Topics Discussed\");\n for (const t of ext.topics) lines.push(`- ${t}`);\n lines.push(\"\");\n lines.push(\"### Decisions Made\");\n for (const d of ext.decisions) lines.push(`- ${d}`);\n lines.push(\"\");\n lines.push(\"### Action Items\");\n for (const a of ext.actionItems) lines.push(`- ${a}`);\n lines.push(\"\");\n lines.push(\"### Rejected Ideas / Reversals\");\n for (const r of ext.rejected) lines.push(`- ${r}`);\n lines.push(\"\");\n if (meta && Object.keys(meta.toolCounts).length > 0) {\n lines.push(\"### Tools Used\");\n const top = Object.entries(meta.toolCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 12);\n for (const [name, count] of top) lines.push(`- ${name}: ${count}`);\n lines.push(\"\");\n }\n lines.push(\"### Stats\");\n lines.push(`- Turns: ${summary.turnCount}`);\n if (meta) {\n lines.push(`- User turns: ${meta.userTurns}`);\n lines.push(`- Assistant turns: ${meta.assistantTurns}`);\n lines.push(`- Tool calls: ${meta.toolCalls}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n for (const bullet of summary.bullets) lines.push(`- ${bullet}`);\n lines.push(` *(${summary.turnCount} turns)*`);\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n // Read recent summaries for recall injection\n async readRecent(sessionKey: string, hours: number): Promise<HourlySummary[]> {\n try {\n const cutoffTime = Date.now() - hours * 60 * 60 * 1000;\n\n const snapshot = await readSummarySnapshot(this.config.memoryDir, sessionKey);\n if (snapshot) {\n return snapshot\n .filter((s) => new Date(s.hour).getTime() >= cutoffTime)\n .sort((a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime());\n }\n\n const summaries: HourlySummary[] = [];\n const encodedDir = await this.summarySessionDir(sessionKey);\n const legacyDir = await this.legacySummarySessionDir(sessionKey);\n const seenDirs = new Set<string>();\n\n for (const sessionDir of [encodedDir, legacyDir]) {\n if (!sessionDir || seenDirs.has(sessionDir)) continue;\n seenDirs.add(sessionDir);\n const parsed = await this.readSummaryDir(sessionDir, sessionKey);\n summaries.push(...parsed);\n }\n\n const byHour = new Map<string, HourlySummary>();\n for (const summary of summaries) {\n if (!byHour.has(summary.hour)) byHour.set(summary.hour, summary);\n }\n\n const sortedSummaries = Array.from(byHour.values()).sort(\n (a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime()\n );\n\n // Filter to recent hours while materializing the full parsed history.\n const recent = sortedSummaries.filter((s) => new Date(s.hour).getTime() >= cutoffTime);\n\n if (sortedSummaries.length > 0) {\n try {\n await writeSummarySnapshot(this.config.memoryDir, sessionKey, sortedSummaries);\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to materialize summary snapshot for ${sessionKey} (fail-open): ${String(error)}`\n );\n }\n }\n\n return recent;\n } catch {\n // Directory doesn't exist or error reading\n return [];\n }\n }\n\n private async readSummaryDir(sessionDir: string, sessionKey: string): Promise<HourlySummary[]> {\n let files: string[];\n try {\n files = await readdir(sessionDir);\n } catch {\n return [];\n }\n\n const summaries: HourlySummary[] = [];\n const mdFiles = files.filter((f) => f.endsWith(\".md\"));\n for (const file of mdFiles) {\n const filePath = await resolveSafeStoragePath(sessionDir, file).catch(() => null);\n if (filePath === null) continue;\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n summaries.push(...this.parseSummaryFile(content, sessionKey, file));\n } catch {\n // Skip unreadable summary files.\n }\n }\n\n return summaries;\n }\n\n private parseSummaryFile(content: string, sessionKey: string, filename: string): HourlySummary[] {\n const summaries: HourlySummary[] = [];\n\n // Extract date from filename (YYYY-MM-DD.md)\n const dateMatch = filename.match(/^(\\d{4}-\\d{2}-\\d{2})\\.md$/);\n if (!dateMatch) return summaries;\n const dateStr = dateMatch[1];\n\n // Split by hour sections\n const hourSections = content.split(/\\n## (\\d{2}):00\\n/);\n\n // First element is the header, skip it\n for (let i = 1; i < hourSections.length; i += 2) {\n const hourStr = hourSections[i];\n const sectionContent = hourSections[i + 1] || \"\";\n\n // Parse bullets\n const bullets: string[] = [];\n const lines = sectionContent.split(\"\\n\");\n let turnCount = 0;\n\n let inTopics = false;\n let sawExtendedTopicsHeader = false;\n for (const line of lines) {\n if (line.startsWith(\"### Topics\")) {\n inTopics = true;\n sawExtendedTopicsHeader = true;\n continue;\n }\n if (line.startsWith(\"### \") && !line.startsWith(\"### Topics\")) {\n inTopics = false;\n }\n const bulletMatch = line.match(/^- (.+)$/);\n if (bulletMatch) {\n // For extended format, only treat topic bullets as recall bullets.\n if (!sawExtendedTopicsHeader || inTopics) bullets.push(bulletMatch[1]);\n }\n const turnMatch = line.match(/\\((\\d+) turns?\\)/);\n if (turnMatch) turnCount = parseInt(turnMatch[1], 10);\n }\n\n if (bullets.length > 0) {\n summaries.push({\n hour: `${dateStr}T${hourStr}:00:00.000Z`,\n sessionKey,\n bullets,\n turnCount,\n generatedAt: \"\", // Not stored in file, not needed for recall\n });\n }\n }\n\n return summaries;\n }\n\n // Format summaries for recall injection\n formatForRecall(summaries: HourlySummary[], maxCount: number): string {\n if (summaries.length === 0) return \"\";\n\n const limited = summaries.slice(0, maxCount);\n const lines: string[] = [`## Recent Activity (last ${limited.length} hours)`];\n\n for (const summary of limited) {\n const hourStr = summary.hour.slice(11, 16); // HH:MM\n for (const bullet of summary.bullets) {\n lines.push(`- ${hourStr}: ${bullet}`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n // Main entry point for cron job\n async runHourly(): Promise<HourlySummarizerRunStats> {\n log.debug(\"running hourly summary generation\");\n\n // Get active sessions from transcript. The scan outcome is kept LOCAL to\n // this invocation (review round 2): shared instance state would let two\n // concurrent runHourly calls cross-report each other's timestamps.\n const scan = await this.getActiveSessions();\n const sessions = scan.sessionKeys;\n let sessionsWithEntries = 0;\n let summariesWritten = 0;\n\n for (const sessionKey of sessions) {\n // Calculate the hour we want to summarize (previous hour)\n const now = new Date();\n const hourStart = new Date(now.getTime() - 60 * 60 * 1000);\n hourStart.setMinutes(0, 0, 0);\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n\n // Get entries for this session in the target hour\n const entries = await this.getTranscriptEntries(sessionKey, hourStart, hourEnd);\n\n if (entries.length === 0) {\n log.debug(`no transcript entries for ${sessionKey} at ${hourStart.toISOString()}`);\n continue;\n }\n sessionsWithEntries += 1;\n\n // Generate and save summary\n const summary = await this.generateSummary(sessionKey, hourStart, entries);\n if (summary) {\n await this.saveSummary(summary);\n summariesWritten += 1;\n log.info(`generated hourly summary for ${sessionKey} (${entries.length} turns)`);\n }\n }\n\n return {\n sessionsConsidered: sessions.length,\n sessionsWithEntries,\n summariesWritten,\n // Staleness signal (issue #2783): newest entry across the whole\n // store, from the same scan getActiveSessions already performs.\n staleStore:\n scan.newestEntryTimestamp !== null &&\n Date.now() - new Date(scan.newestEntryTimestamp).getTime() > STALE_STORE_MS,\n newestEntryTimestamp: scan.newestEntryTimestamp,\n scanFailed: scan.scanFailed,\n };\n }\n\n // Get list of active sessions from the transcript directory, plus the\n // scan bookkeeping runHourly reports: newest entry timestamp (staleness\n // signal) and whether the scan itself FAILED. A failed scan must not be\n // reported as an empty store — those are different incidents (review\n // round 2).\n private async getActiveSessions(): Promise<{\n sessionKeys: string[];\n newestEntryTimestamp: string | null;\n scanFailed: boolean;\n }> {\n const transcriptDir = await resolveSafeStoragePath(this.config.memoryDir, \"transcripts\").catch(() => null);\n if (transcriptDir === null) {\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: false };\n }\n\n const sessionKeys = new Set<string>();\n let newestEntryTimestamp: string | null = null;\n let newestEntryTimeMs = Number.NaN;\n let fileReadFailed = false;\n const collect = async (transcriptPath: string): Promise<void> => {\n try {\n const raw = await readFile(transcriptPath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n if (typeof entry.sessionKey === \"string\" && entry.sessionKey.length > 0) {\n sessionKeys.add(entry.sessionKey);\n }\n // Compare parsed epoch values, never strings: a malformed\n // timestamp in a hand-edited file must not poison the staleness\n // signal with a lexically-maximal garbage value (review).\n if (typeof entry.timestamp === \"string\") {\n const timeMs = new Date(entry.timestamp).getTime();\n if (Number.isFinite(timeMs) && (Number.isNaN(newestEntryTimeMs) || timeMs > newestEntryTimeMs)) {\n newestEntryTimeMs = timeMs;\n newestEntryTimestamp = entry.timestamp;\n }\n }\n } catch {\n // ignore malformed transcript lines\n }\n }\n } catch (err) {\n // ENOENT is a concurrently-deleted file — ignore. Any other read\n // failure (permissions, I/O) means the store is partially UNREADABLE:\n // mark the scan failed so the caller warns instead of reporting an\n // empty store (review round 3).\n if ((err as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n fileReadFailed = true;\n }\n }\n };\n\n try {\n const typeEntries = await readdir(transcriptDir, { withFileTypes: true });\n for (const typeEnt of typeEntries) {\n if (!typeEnt.isDirectory()) continue;\n const typeDir = await resolveSafeStoragePath(transcriptDir, typeEnt.name).catch(() => null);\n if (typeDir === null) continue;\n const idEntries = await readdir(typeDir, { withFileTypes: true });\n for (const idEnt of idEntries) {\n if (!idEnt.isDirectory()) continue;\n const chanDir = await resolveSafeStoragePath(typeDir, idEnt.name).catch(() => null);\n if (chanDir === null) continue;\n const files = (await readdir(chanDir)).filter((f) => f.endsWith(\".jsonl\")).sort();\n for (const file of files) {\n const transcriptPath = await resolveSafeStoragePath(chanDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n await collect(transcriptPath);\n }\n }\n }\n return {\n sessionKeys: Array.from(sessionKeys),\n newestEntryTimestamp,\n scanFailed: fileReadFailed,\n };\n } catch (err) {\n // ENOENT on the root is a never-written store — an EMPTY store, not a\n // scan failure (those are different incidents).\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: false };\n }\n log.warn(`transcript scan failed: ${err}`);\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: true };\n }\n }\n\n // Get transcript entries for a session within a time range\n private async getTranscriptEntries(sessionKey: string, startTime: Date, endTime: Date): Promise<TranscriptEntry[]> {\n // Shared session-identity layer (issue #1496, rule #22). Arbitrary keys\n // route to `session/<hash>`; legacy `agent:<id>:...` keep their paths. The\n // shared helper also supplies the read-back-only candidate dirs (mirrors\n // TranscriptManager) so legacy `other/default` AND old `parts.length >= 3`\n // data stays discoverable here too.\n const paths = sessionStoragePaths(sessionKey);\n\n try {\n const transcriptRoot = path.join(this.config.memoryDir, \"transcripts\");\n const candidateDirs = new Set(\n [paths.dir, paths.alternateDir, paths.legacyDir, ...paths.readbackDirs].filter(\n (dir): dir is string => typeof dir === \"string\" && dir.length > 0\n )\n );\n const entries: TranscriptEntry[] = [];\n // Dedup identical raw rows that a partially-applied migration may have\n // left in both the primary dir and a read-back dir (issue #1496, cursor\n // review). Exact raw JSONL line is the stable identity.\n const seenRawLines = new Set<string>();\n\n // Read all daily transcript files in the directory\n for (const candidateDir of candidateDirs) {\n const transcriptDir = await resolveSafeStoragePath(transcriptRoot, candidateDir).catch(() => null);\n if (transcriptDir === null) continue;\n\n const files = await readdir(transcriptDir).catch(() => []);\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n\n const transcriptPath = await resolveSafeStoragePath(transcriptDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n\n try {\n const content = await readFile(transcriptPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\");\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const entryTime = new Date(entry.timestamp).getTime();\n\n if (\n entry.sessionKey === sessionKey &&\n entryTime >= startTime.getTime() &&\n entryTime < endTime.getTime() &&\n !seenRawLines.has(line)\n ) {\n seenRawLines.add(line);\n entries.push(entry);\n }\n } catch {\n // Skip malformed lines\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return entries;\n } catch {\n return [];\n }\n }\n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Y,IAAI,KAAK,MAAM,SAAS,EAAE,QAAQ;AAEpD,oBACE,MAAM,eAAe,cACrB,aAAa,UAAU,QAAQ,KAC/B,YAAY,QAAQ,QAAQ,KAC5B,CAAC,aAAa,IAAI,IAAI,GACtB;AACA,+BAAa,IAAI,IAAI;AACrB,0BAAQ,KAAK,KAAK;AAAA,gBACpB;AAAA,cACF,QAAQ;AAAA,cAER;AAAA,YACF;AAAA,UACF,QAAQ;AAAA,UAER;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extraction-quote-grounding.ts"],"sourcesContent":["/**\n * Quote-anchored source grounding.\n *\n * An extracted fact carries the exact words that support it in `quote`. A quote\n * that is a verbatim substring of the source (whitespace-normalized) is real\n * evidence: the claim only has to be supported by the text around that span,\n * not by word overlap against the whole conversation. Items without such a\n * quote never get an anchor here and stay on the whole-source rules.\n */\n\nimport type { ExtractionResult } from \"./types.js\";\nimport {\n GROUNDING_MIN_SHARED_TOKENS,\n areGroundingTokensCompatible,\n entityNameStart,\n hasDenialReporting,\n hasNonAssertiveReporting,\n isGroundedEntityName,\n normalizedEntityIdentifierTokens,\n sourceSentences,\n tokenize,\n} from \"./extraction-source-grounding-helpers.js\";\n\n/** Shortest normalized quote that counts as evidence; \"the\" or \"I\" prove nothing. */\nexport const QUOTE_ANCHOR_MIN_CHARS = 12;\n/** Characters of context kept on each side of the quote inside its turn. */\nexport const QUOTE_ANCHOR_CONTEXT_CHARS = 400;\n/** Share of a claim's content words that must occur in the quote's window. */\nexport const QUOTE_ANCHOR_MIN_WINDOW_COVERAGE = 0.35;\n/** Share of a claim's content words that must occur anywhere in the source; the rest is invented. */\nexport const QUOTE_ANCHOR_MIN_SOURCE_COVERAGE = 0.75;\nconst QUOTE_ANCHOR_MAX_OCCURRENCES = 8;\nconst TURN_SEPARATOR = \"\\n\\n\";\nconst NEGATOR_PATTERN = /\\b(?:not|no|never|cannot|without|neither|nor)\\b|n't\\b/iu;\nconst EXCLUSION_PATTERN =\n /\\b(?:exclu\\w*|avoid\\w*|omit\\w*|skip\\w*|ignor\\w*|forbid\\w*|prohibit\\w*|disallow\\w*|prevent\\w*|reject\\w*|refus\\w*|insufficient|instead|rather|unless|except)\\b/iu;\n\n/** A verbatim quote and the text around it inside its turn. */\nexport interface QuoteAnchor {\n /** Whitespace-normalized quote, exactly as it appears in the source. */\n quote: string;\n /** `quote` with its turn-local context; `;` inside the quote is rewritten to `,`. */\n window: string;\n}\n\nexport type TokenPool = (token: string) => boolean;\n\ntype Entity = ExtractionResult[\"entities\"][number];\ntype Relationship = NonNullable<ExtractionResult[\"relationships\"]>[number];\n\nfunction normalizeWhitespaceWithMap(source: string): { text: string; originalIndex: number[] } {\n const chars: string[] = [];\n const originalIndex: number[] = [];\n let inSpace = false;\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index]!;\n if (/\\s/u.test(char)) {\n if (inSpace) continue;\n inSpace = true;\n chars.push(\" \");\n } else {\n inSpace = false;\n chars.push(char);\n }\n originalIndex.push(index);\n }\n return { text: chars.join(\"\"), originalIndex };\n}\n\nfunction turnStartOffsets(source: string, turns: readonly string[]): readonly number[] | undefined {\n const offsets: number[] = [];\n let at = 0;\n for (const turn of turns) {\n if (!source.startsWith(turn, at)) return undefined;\n offsets.push(at);\n at += turn.length + TURN_SEPARATOR.length;\n }\n return at - TURN_SEPARATOR.length === source.length ? offsets : undefined;\n}\n\nfunction findQuoteAnchors(quote: string, source: string, bounds?: readonly number[]): QuoteAnchor[] {\n const needle = quote.replace(/\\s+/gu, \" \").trim();\n if (needle.length < QUOTE_ANCHOR_MIN_CHARS) return [];\n const normalized = normalizeWhitespaceWithMap(source);\n const anchors: QuoteAnchor[] = [];\n let from = 0;\n while (anchors.length < QUOTE_ANCHOR_MAX_OCCURRENCES) {\n const at = normalized.text.indexOf(needle, from);\n if (at < 0) break;\n from = at + 1;\n const start = normalized.originalIndex[at]!;\n const end = normalized.originalIndex[at + needle.length - 1]! + 1;\n\n let before: string;\n let after: string;\n if (bounds === undefined) {\n if (source.slice(start, end).includes(TURN_SEPARATOR)) continue;\n before = source.slice(Math.max(0, start - QUOTE_ANCHOR_CONTEXT_CHARS), start);\n const sepBefore = before.lastIndexOf(TURN_SEPARATOR);\n if (sepBefore >= 0) before = before.slice(sepBefore + TURN_SEPARATOR.length);\n else if (start > QUOTE_ANCHOR_CONTEXT_CHARS) before = before.replace(/^\\S+/u, \"\");\n after = source.slice(end, end + QUOTE_ANCHOR_CONTEXT_CHARS);\n const sepAfter = after.indexOf(TURN_SEPARATOR);\n if (sepAfter >= 0) after = after.slice(0, sepAfter);\n else if (source.length - end > QUOTE_ANCHOR_CONTEXT_CHARS) after = after.replace(/\\S+$/u, \"\");\n } else {\n let turnStart = 0;\n let turnEnd = source.length;\n for (const bound of bounds) {\n if (bound <= start) turnStart = bound;\n else {\n turnEnd = bound - TURN_SEPARATOR.length;\n break;\n }\n }\n if (turnEnd < end) continue;\n before = source.slice(Math.max(turnStart, start - QUOTE_ANCHOR_CONTEXT_CHARS), start);\n if (start - QUOTE_ANCHOR_CONTEXT_CHARS > turnStart) before = before.replace(/^\\S+/u, \"\");\n const contextEnd = Math.min(turnEnd, end + QUOTE_ANCHOR_CONTEXT_CHARS);\n after = source.slice(end, contextEnd);\n if (end + QUOTE_ANCHOR_CONTEXT_CHARS < turnEnd) after = after.replace(/\\S+$/u, \"\");\n }\n\n anchors.push({ quote: needle, window: `${before}${needle.replace(/;/gu, \",\")}${after}` });\n }\n return anchors;\n}\n\n/**\n * Returns one anchor per place `quote` occurs verbatim in `source`, or [] when\n * the quote is absent, too short, or not an exact substring. A quote that\n * spans a turn separator is not one turn's words and yields no anchor; windows\n * never extend past their turn.\n *\n * The quote is one evidence unit: a `;` inside it is rewritten to `,` in the\n * window so sentence splitting cannot cut it, or a claim that merges two of\n * its clauses could never be grounded in a single sentence.\n *\n * `source` may have been rewritten before grounding (temporal anchoring,\n * pronoun resolution) while the model quoted the original words. When the raw\n * quote is not found, `transformQuote` applies the same rewrite to the quote.\n *\n * `turns` are the texts `source` was joined from; when they tile `source`\n * exactly, quotes and windows cut at real turn boundaries instead of any\n * blank line. Without them, every `TURN_SEPARATOR` run is a boundary.\n */\nexport function quoteAnchors(\n quote: string | undefined,\n source: string,\n transformQuote?: (quote: string) => string,\n turns?: readonly string[],\n): QuoteAnchor[] {\n if (typeof quote !== \"string\") return [];\n const bounds = turns === undefined ? undefined : turnStartOffsets(source, turns);\n const exact = findQuoteAnchors(quote, source, bounds);\n if (exact.length > 0 || transformQuote === undefined) return exact;\n return findQuoteAnchors(transformQuote(quote), source, bounds);\n}\n\nexport function tokenPool(tokens: ReadonlySet<string>): TokenPool {\n const list = [...tokens];\n return (token) => tokens.has(token) || list.some((poolToken) => areGroundingTokensCompatible(token, poolToken));\n}\n\nfunction hasNegation(text: string): boolean {\n return NEGATOR_PATTERN.test(text.replace(/[\\u2018\\u2019]/gu, \"'\")) || hasDenialReporting(text);\n}\n\nconst CLAUSE_PATTERN = /[^;.!?\\n]+[;.!?]*/gu;\n/** Split \"X, and Y\" claim coordination without touching list commas. */\nconst CLAIM_COORD_SPLIT = /,\\s{1,8}(?:and|but|or|nor)\\s{1,8}/iu;\n\nfunction splitClaimClauses(content: string): string[] {\n return (content.match(CLAUSE_PATTERN) ?? [content]).flatMap((clause) => {\n const parts = clause\n .split(CLAIM_COORD_SPLIT)\n .map((part) => part.trim())\n .filter((part) => part.length > 0);\n return parts.length > 0 ? parts : [clause];\n });\n}\n\nfunction clauseOverlap(clauseTokens: readonly string[], target: string) {\n const has = tokenPool(tokenize(target));\n const shared = clauseTokens.filter(has).length;\n return { shared, ratio: clauseTokens.length === 0 ? 0 : shared / clauseTokens.length };\n}\n\n/** What a quote clause's first negator governs: the words after it. */\nfunction negatedScope(clause: string): string {\n const match = NEGATOR_PATTERN.exec(clause.replace(/[\\u2018\\u2019]/gu, \"'\"));\n return match ? clause.slice(match.index + match[0].length) : clause;\n}\n\n/**\n * True when the claim asserts what a quote clause denies or does not assert:\n * \"did not approve the budget\" or \"denied approving it\" restated as \"approved\n * the budget\", \"suspects Bob stole funds\" or \"Is Alice the CEO?\" restated as a\n * plain statement. The claim must restate the quote clause, and none of its\n * clauses that share a word with what the negator governs may keep the\n * negator, exclusion word, or reporting marker (\"do not X\" reworded as \"X is\n * excluded\", or \"Alice reviewed it, but she did not approve it\"). A negator in\n * a clause about something else does not count, so a claim that keeps one\n * quote negation can still misstate another quote clause, and a claim clause\n * that shares only the subject does not satisfy the check.\n */\nfunction misstatesQuote(content: string, quote: string): boolean {\n const claimClauses = splitClaimClauses(content);\n return (quote.match(CLAUSE_PATTERN) ?? []).some((quoteClause) => {\n const needsNegation = hasNegation(quoteClause);\n const needsReporting = quoteClause.trim().endsWith(\"?\") || hasNonAssertiveReporting(quoteClause);\n if (!needsNegation && !needsReporting) return false;\n const clauseTokens = [...tokenize(quoteClause)];\n const whole = clauseOverlap(clauseTokens, content);\n if (whole.shared < GROUNDING_MIN_SHARED_TOKENS || whole.ratio < 0.5) return false;\n const clausesSharing = (tokens: readonly string[]) =>\n claimClauses.filter((claimClause) => clauseOverlap(tokens, claimClause).shared > 0);\n if (needsNegation) {\n const scopeTokens = [...tokenize(negatedScope(quoteClause))];\n const related = clausesSharing(scopeTokens.length > 0 ? scopeTokens : clauseTokens);\n if (!related.some((text) => hasNegation(text) || EXCLUSION_PATTERN.test(text))) return true;\n }\n return needsReporting\n && !clausesSharing(clauseTokens).some((text) => hasNonAssertiveReporting(text) || text.trim().endsWith(\"?\"));\n });\n}\n\n/**\n * A claim is supported by a verbatim quote when it shares at least\n * GROUNDING_MIN_SHARED_TOKENS content words with the quote, a good part of its\n * words sit in the text around the quote, nearly all of them occur in the\n * source at all, and it does not invert a negated clause of the quote. Reworded\n * and lightly elaborated claims pass; claims that bring words the conversation\n * never used, or that have nothing to do with the quote, do not.\n */\nexport function isQuoteAnchoredClaim(content: string, anchor: QuoteAnchor, sourceHas: TokenPool): boolean {\n const contentTokens = [...tokenize(content)];\n if (contentTokens.length === 0) return false;\n const quoteHas = tokenPool(tokenize(anchor.quote));\n if (contentTokens.filter(quoteHas).length < GROUNDING_MIN_SHARED_TOKENS) return false;\n const windowHas = tokenPool(tokenize(anchor.window));\n if (contentTokens.filter(windowHas).length / contentTokens.length < QUOTE_ANCHOR_MIN_WINDOW_COVERAGE) {\n return false;\n }\n return contentTokens.filter(sourceHas).length / contentTokens.length >= QUOTE_ANCHOR_MIN_SOURCE_COVERAGE\n && !misstatesQuote(content, anchor.quote);\n}\n\n/** Keeps the entity facts (flat and sectioned) `isSupported` accepts; undefined when none remain. */\nexport function filterEntityFacts(entity: Entity, isSupported: (fact: string) => boolean): Entity | undefined {\n const facts = entity.facts.filter(isSupported);\n const structuredSections = entity.structuredSections?.flatMap((section) => {\n const groundedFacts = section.facts.filter(isSupported);\n return groundedFacts.length > 0 ? [{ ...section, facts: groundedFacts }] : [];\n });\n if (facts.length === 0 && (structuredSections === undefined || structuredSections.length === 0)) {\n return undefined;\n }\n const { structuredSections: _structuredSections, ...entityWithoutSections } = entity;\n return {\n ...entityWithoutSections,\n facts,\n ...(structuredSections && structuredSections.length > 0 ? { structuredSections } : {}),\n };\n}\n\n/**\n * Entities carry no quote of their own; the anchors of facts that kept support\n * them. Returns a fact predicate, or undefined when no anchor window names the entity.\n */\nexport function quoteAnchoredEntitySupport(\n entity: Entity,\n anchors: readonly QuoteAnchor[],\n sourceHas: TokenPool,\n): ((fact: string) => boolean) | undefined {\n const nameAnchors = anchors.filter((anchor) => isGroundedEntityName(entity.name, anchor.window));\n if (nameAnchors.length === 0) return undefined;\n return (fact) => nameAnchors.some((anchor) => isQuoteAnchoredClaim(fact, anchor, sourceHas));\n}\n\n/**\n * The label words and both names must sit in one anchor-window sentence, source\n * before target, so an invented label or a reversed edge never passes.\n */\nexport function isQuoteAnchoredRelationship(\n relationship: Relationship,\n anchors: readonly QuoteAnchor[],\n sourceHas: TokenPool,\n): boolean {\n const labelTokens = [...tokenize(relationship.label)];\n if (labelTokens.length === 0) return false;\n const relationText = [\n normalizedEntityIdentifierTokens(relationship.source).join(\" \"),\n relationship.label,\n normalizedEntityIdentifierTokens(relationship.target).join(\" \"),\n ].join(\" \");\n return anchors.some((anchor) => {\n const windowHas = tokenPool(tokenize(anchor.window));\n return labelTokens.every(windowHas)\n && sourceSentences(anchor.window).some((sentence) => {\n const sourceStart = entityNameStart(relationship.source, sentence);\n return sourceStart >= 0 && entityNameStart(relationship.target, sentence) > sourceStart;\n })\n && isQuoteAnchoredClaim(relationText, anchor, sourceHas);\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAwBO,IAAM,yBAAyB;AAE/B,IAAM,6BAA6B;AAEnC,IAAM,mCAAmC;AAEzC,IAAM,mCAAmC;AAChD,IAAM,+BAA+B;AACrC,IAAM,iBAAiB;AACvB,IAAM,kBAAkB;AACxB,IAAM,oBACJ;AAeF,SAAS,2BAA2B,QAA2D;AAC7F,QAAM,QAAkB,CAAC;AACzB,QAAM,gBAA0B,CAAC;AACjC,MAAI,UAAU;AACd,WAAS,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;AACrD,UAAM,OAAO,OAAO,KAAK;AACzB,QAAI,MAAM,KAAK,IAAI,GAAG;AACpB,UAAI,QAAS;AACb,gBAAU;AACV,YAAM,KAAK,GAAG;AAAA,IAChB,OAAO;AACL,gBAAU;AACV,YAAM,KAAK,IAAI;AAAA,IACjB;AACA,kBAAc,KAAK,KAAK;AAAA,EAC1B;AACA,SAAO,EAAE,MAAM,MAAM,KAAK,EAAE,GAAG,cAAc;AAC/C;AAEA,SAAS,iBAAiB,QAAgB,OAAyD;AACjG,QAAM,UAAoB,CAAC;AAC3B,MAAI,KAAK;AACT,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,OAAO,WAAW,MAAM,EAAE,EAAG,QAAO;AACzC,YAAQ,KAAK,EAA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,EAAE,mBAAmB,IAAI,CAAC;AAAA,EACtF;AACF;AAMO,SAAS,2BACd,QACA,SACA,WACyC;AACzC,QAAM,cAAc,QAAQ,OAAO,CAAC,WAAW,qBAAqB,OAAO,MAAM,OAAO,MAAM,CAAC;AAC/F,MAAI,YAAY,WAAW,EAAG,QAAO;AACrC,SAAO,CAAC,SAAS,YAAY,KAAK,CAAC,WAAW,qBAAqB,MAAM,QAAQ,SAAS,CAAC;AAC7F;AAMO,SAAS,4BACd,cACA,SACA,WACS;AACT,QAAM,cAAc,CAAC,GAAG,SAAS,aAAa,KAAK,CAAC;AACpD,MAAI,YAAY,WAAW,EAAG,QAAO;AACrC,QAAM,eAAe;AAAA,IACnB,iCAAiC,aAAa,MAAM,EAAE,KAAK,GAAG;AAAA,IAC9D,aAAa;AAAA,IACb,iCAAiC,aAAa,MAAM,EAAE,KAAK,GAAG;AAAA,EAChE,EAAE,KAAK,GAAG;AACV,SAAO,QAAQ,KAAK,CAAC,WAAW;AAC9B,UAAM,YAAY,UAAU,SAAS,OAAO,MAAM,CAAC;AACnD,WAAO,YAAY,MAAM,SAAS,KAC7B,gBAAgB,OAAO,MAAM,EAAE,KAAK,CAAC,aAAa;AACnD,YAAM,cAAc,gBAAgB,aAAa,QAAQ,QAAQ;AACjE,aAAO,eAAe,KAAK,gBAAgB,aAAa,QAAQ,QAAQ,IAAI;AAAA,IAC9E,CAAC,KACE,qBAAqB,cAAc,QAAQ,SAAS;AAAA,EAC3D,CAAC;AACH;","names":[]}
@@ -1,361 +0,0 @@
1
- import {
2
- coerceBool,
3
- coerceNumber
4
- } from "./chunk-PQVCH2AE.js";
5
-
6
- // src/correction/correction-contract.ts
7
- var MEMORY_CATEGORIES = [
8
- "fact",
9
- "preference",
10
- "correction",
11
- "entity",
12
- "decision",
13
- "relationship",
14
- "principle",
15
- "commitment",
16
- "moment",
17
- "skill",
18
- "rule",
19
- "procedure",
20
- "reasoning_trace"
21
- ];
22
- var CORRECTION_ACTION_KINDS = [
23
- "supersede",
24
- "edit",
25
- "retract",
26
- "rescope",
27
- "redaction_rule"
28
- ];
29
- var CORRECTION_TEXT_MAX = 1e4;
30
- var REDACTION_PATTERN_MAX = 256;
31
- var CORRECTION_MEMORY_ID_MAX = 512;
32
- function validateCorrectionRequest(request) {
33
- if (!request || typeof request !== "object") {
34
- throw new CorrectionContractError("CorrectionRequest must be an object.");
35
- }
36
- const text = typeof request.text === "string" ? request.text.trim() : "";
37
- if (text.length === 0) {
38
- throw new CorrectionContractError("CorrectionRequest.text is required and must be non-empty.");
39
- }
40
- if (text.length > CORRECTION_TEXT_MAX) {
41
- throw new CorrectionContractError(
42
- `CorrectionRequest.text exceeds the ${CORRECTION_TEXT_MAX}-character limit (${text.length}).`
43
- );
44
- }
45
- const targetIds = Array.isArray(request.targetIds) ? request.targetIds.filter((id) => typeof id === "string" && id.length > 0) : void 0;
46
- const normalizedTargets = targetIds !== void 0 && targetIds.length === 0 ? void 0 : targetIds;
47
- const duplicateOf = readDuplicateOf(request.duplicateOf);
48
- if (duplicateOf) {
49
- if (!normalizedTargets || normalizedTargets.length !== 1) {
50
- throw new CorrectionContractError(
51
- "CorrectionRequest.duplicateOf requires exactly one targetIds entry (the duplicate memory)."
52
- );
53
- }
54
- if (normalizedTargets[0] === duplicateOf) {
55
- throw new CorrectionContractError(
56
- "CorrectionRequest.duplicateOf must be a different memory from targetIds."
57
- );
58
- }
59
- }
60
- return {
61
- text,
62
- ...normalizedTargets ? { targetIds: normalizedTargets } : {},
63
- ...duplicateOf ? { duplicateOf } : {},
64
- ...request.sessionKey ? { sessionKey: request.sessionKey } : {},
65
- ...request.principal ? { principal: request.principal } : {},
66
- ...request.namespace ? { namespace: request.namespace } : {}
67
- };
68
- }
69
- function readDuplicateOf(value) {
70
- if (value === void 0 || value === null) return void 0;
71
- if (typeof value !== "string") {
72
- throw new CorrectionContractError("CorrectionRequest.duplicateOf must be a memory id string.");
73
- }
74
- const id = value.trim();
75
- if (id.length === 0 || id !== value) {
76
- throw new CorrectionContractError("CorrectionRequest.duplicateOf must be a non-empty memory id.");
77
- }
78
- if (id.length > CORRECTION_MEMORY_ID_MAX) {
79
- throw new CorrectionContractError(
80
- `CorrectionRequest.duplicateOf exceeds the ${CORRECTION_MEMORY_ID_MAX}-character limit (${id.length}).`
81
- );
82
- }
83
- return id;
84
- }
85
- function validateRedactionPattern(pattern) {
86
- if (typeof pattern !== "string") {
87
- throw new CorrectionContractError("redaction_rule.pattern must be a string.");
88
- }
89
- const trimmed = pattern.trim();
90
- if (trimmed.length === 0) {
91
- throw new CorrectionContractError("redaction_rule.pattern is required.");
92
- }
93
- if (trimmed.length > REDACTION_PATTERN_MAX) {
94
- throw new CorrectionContractError(
95
- `redaction_rule.pattern exceeds the ${REDACTION_PATTERN_MAX}-character bound.`
96
- );
97
- }
98
- if (isRegexLike(trimmed) && isUnsafeRedactionRegex(trimmed)) {
99
- throw new CorrectionContractError(
100
- "redaction_rule.pattern is unsafe \u2014 use a bounded literal or a regex without nested quantifiers / overlapping alternation."
101
- );
102
- }
103
- if (isRegexLike(trimmed)) {
104
- const regexBody = trimmed.slice(1, -1);
105
- if (regexBody.length === 0) {
106
- throw new CorrectionContractError("redaction_rule.pattern body is empty \u2014 use a non-empty regex.");
107
- }
108
- try {
109
- if (new RegExp(regexBody).test("")) {
110
- throw new CorrectionContractError(
111
- "redaction_rule.pattern matches the empty string \u2014 it would withhold every fact."
112
- );
113
- }
114
- } catch (e) {
115
- if (e instanceof CorrectionContractError) throw e;
116
- }
117
- }
118
- return trimmed;
119
- }
120
- function isRegexLike(pattern) {
121
- return pattern.startsWith("/") && pattern.endsWith("/") && pattern.length >= 2;
122
- }
123
- function isUnsafeRedactionRegex(pattern) {
124
- const body = pattern.startsWith("/") && pattern.endsWith("/") ? pattern.slice(1, -1) : pattern;
125
- if (/(?:^|[^\\])\(\.\*\)|(?:^|[^\\])\.\*|(?:^|[^\\])\.\+|^\.([^*+]?)$/.test(body)) {
126
- return true;
127
- }
128
- if (body.length > 512) return true;
129
- for (let i = 0; i < body.length; i++) {
130
- if (body[i] !== "(") continue;
131
- let depth = 1;
132
- let j = i + 1;
133
- while (j < body.length && depth > 0) {
134
- if (body[j] === "\\") {
135
- j += 2;
136
- continue;
137
- }
138
- if (body[j] === "(") depth++;
139
- else if (body[j] === ")") depth--;
140
- j++;
141
- }
142
- if (depth !== 0) continue;
143
- const afterGroup = body[j];
144
- if (afterGroup !== "+" && afterGroup !== "*" && afterGroup !== "{") continue;
145
- const groupBody = body.slice(i + 1, j - 1);
146
- if (/[+*?]$/.test(groupBody) || /\{\d+,?\d*\}[+*?]?$/.test(groupBody)) {
147
- return true;
148
- }
149
- if (groupBody.includes("|")) {
150
- const branches = groupBody.split("|");
151
- if (branches.length >= 2) {
152
- const firstChars = new Set(branches.map((b) => b[0]).filter(Boolean));
153
- if (firstChars.size < branches.filter((b) => b.length > 0).length) {
154
- return true;
155
- }
156
- }
157
- }
158
- i = j;
159
- }
160
- return false;
161
- }
162
- function validateCorrectionAction(action) {
163
- if (!action || typeof action !== "object") {
164
- throw new CorrectionContractError("CorrectionAction must be an object.");
165
- }
166
- const a = action;
167
- if (typeof a.kind !== "string" || !CORRECTION_ACTION_KINDS.includes(a.kind)) {
168
- throw new CorrectionContractError(
169
- `CorrectionAction.kind must be one of: ${CORRECTION_ACTION_KINDS.join(", ")}.`
170
- );
171
- }
172
- switch (a.kind) {
173
- case "supersede":
174
- if (typeof a.loserId !== "string" || a.loserId.length === 0) {
175
- throw new CorrectionContractError("supersede.loserId is required.");
176
- }
177
- {
178
- const hasReplacement = a.replacement !== void 0 && a.replacement !== null;
179
- const hasWinner = a.winnerId !== void 0 && a.winnerId !== null;
180
- if (hasWinner) {
181
- if (typeof a.winnerId !== "string" || a.winnerId.trim().length === 0 || a.winnerId !== a.winnerId.trim()) {
182
- throw new CorrectionContractError("supersede.winnerId must be a non-empty memory id.");
183
- }
184
- if (a.winnerId === a.loserId) {
185
- throw new CorrectionContractError("supersede.winnerId must differ from loserId.");
186
- }
187
- if (hasReplacement) {
188
- throw new CorrectionContractError("supersede.winnerId cannot be combined with a replacement draft.");
189
- }
190
- }
191
- if (hasReplacement) validateMemoryDraft(a.replacement);
192
- }
193
- break;
194
- case "edit":
195
- if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
196
- throw new CorrectionContractError("edit.memoryId is required.");
197
- }
198
- if (typeof a.patch !== "string" || a.patch.length === 0) {
199
- throw new CorrectionContractError("edit.patch is required and must be non-empty.");
200
- }
201
- break;
202
- case "retract":
203
- if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
204
- throw new CorrectionContractError("retract.memoryId is required.");
205
- }
206
- break;
207
- case "rescope":
208
- if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
209
- throw new CorrectionContractError("rescope.memoryId is required.");
210
- }
211
- if (typeof a.toNamespace !== "string" || a.toNamespace.trim().length === 0) {
212
- throw new CorrectionContractError("rescope.toNamespace is required.");
213
- }
214
- break;
215
- case "redaction_rule":
216
- if (typeof a.pattern !== "string") {
217
- throw new CorrectionContractError("redaction_rule.pattern is required.");
218
- }
219
- validateRedactionPattern(a.pattern);
220
- break;
221
- }
222
- }
223
- function validateMemoryDraft(draft) {
224
- if (!draft || typeof draft !== "object") {
225
- throw new CorrectionContractError("MemoryDraft must be an object.");
226
- }
227
- const d = draft;
228
- if (typeof d.content !== "string" || d.content.trim().length === 0) {
229
- throw new CorrectionContractError("MemoryDraft.content is required and must be non-empty.");
230
- }
231
- if (d.category !== void 0) {
232
- if (typeof d.category !== "string" || !MEMORY_CATEGORIES.includes(d.category)) {
233
- throw new CorrectionContractError(
234
- `MemoryDraft.category must be one of: ${MEMORY_CATEGORIES.join(", ")}.`
235
- );
236
- }
237
- }
238
- if (d.confidence !== void 0 && (typeof d.confidence !== "number" || d.confidence < 0 || d.confidence > 1)) {
239
- throw new CorrectionContractError("MemoryDraft.confidence must be a number in [0, 1].");
240
- }
241
- if (d.tags !== void 0 && !Array.isArray(d.tags)) {
242
- throw new CorrectionContractError("MemoryDraft.tags must be an array.");
243
- }
244
- if (d.structuredAttributes !== void 0 && (typeof d.structuredAttributes !== "object" || d.structuredAttributes === null)) {
245
- throw new CorrectionContractError("MemoryDraft.structuredAttributes must be an object.");
246
- }
247
- }
248
- function deterministicFallbackPlan(args) {
249
- return {
250
- planId: newPlanId(),
251
- request: args.request,
252
- namespace: args.namespace,
253
- affected: args.affected,
254
- classification: "outdated",
255
- actions: [],
256
- diff: "",
257
- confidence: 0,
258
- warnings: [...args.warnings, "planner LLM unavailable \u2014 manual action selection required"],
259
- createdAt: args.createdAt,
260
- expiresAt: args.expiresAt,
261
- status: "pending"
262
- };
263
- }
264
- function newPlanId() {
265
- return `corr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
266
- }
267
- var CorrectionContractError = class extends Error {
268
- constructor(message) {
269
- super(message);
270
- this.name = "CorrectionContractError";
271
- }
272
- };
273
-
274
- // src/correction/correction-config.ts
275
- var DEFAULT_CORRECTION_CLASSIFY_TIMEOUT_MS = 45e3;
276
- var MAX_CORRECTION_CLASSIFY_TIMEOUT_MS = 3e5;
277
- function parseCorrectionConfig(cfg) {
278
- return {
279
- correctionEnabled: (() => {
280
- const nested = cfg.correction?.enabled;
281
- const raw = nested !== void 0 ? nested : cfg.correctionEnabled;
282
- if (raw === void 0 || raw === null) return true;
283
- const value = coerceBool(raw);
284
- if (value === void 0) {
285
- throw new Error(`Invalid correction.enabled: expected a boolean, got ${JSON.stringify(raw)}`);
286
- }
287
- return value;
288
- })(),
289
- correctionApplyRequiresConfirm: (() => {
290
- const nested = cfg.correction?.applyRequiresConfirm;
291
- const raw = nested !== void 0 ? nested : cfg.correctionApplyRequiresConfirm;
292
- if (raw === void 0 || raw === null) return true;
293
- const value = coerceBool(raw);
294
- if (value === void 0) {
295
- throw new Error(`Invalid correction.applyRequiresConfirm: expected a boolean, got ${JSON.stringify(raw)}`);
296
- }
297
- return value;
298
- })(),
299
- correctionMaxAffected: (() => {
300
- const rawNested = cfg.correction?.maxAffected;
301
- const raw = rawNested !== void 0 ? rawNested : cfg.correctionMaxAffected;
302
- if (raw === void 0 || raw === null) return 10;
303
- const n = coerceNumber(raw);
304
- if (n === void 0 || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {
305
- throw new Error(`Invalid correction.maxAffected: expected an integer >= 1, got ${JSON.stringify(raw)}`);
306
- }
307
- return n;
308
- })(),
309
- correctionPlanTtlHours: (() => {
310
- const nested = cfg.correction?.planTtlHours;
311
- const fromNested = nested !== void 0 ? coerceNumber(nested) : void 0;
312
- if (fromNested !== void 0 && fromNested >= 1) return fromNested;
313
- if (nested !== void 0 && fromNested === void 0) {
314
- throw new Error(`Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(nested)}`);
315
- }
316
- if (fromNested !== void 0 && fromNested < 1) {
317
- throw new Error(`Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(nested)}`);
318
- }
319
- const fromFlat = coerceNumber(cfg.correctionPlanTtlHours);
320
- if (fromFlat !== void 0 && fromFlat >= 1) return fromFlat;
321
- if (cfg.correctionPlanTtlHours !== void 0 && fromFlat === void 0) {
322
- throw new Error(
323
- `Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(cfg.correctionPlanTtlHours)}`
324
- );
325
- }
326
- if (fromFlat !== void 0 && fromFlat < 1) {
327
- throw new Error(
328
- `Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(cfg.correctionPlanTtlHours)}`
329
- );
330
- }
331
- return 24;
332
- })(),
333
- correctionClassifyTimeoutMs: (() => {
334
- const nested = cfg.correction?.classifyTimeoutMs;
335
- const raw = nested !== void 0 ? nested : cfg.correctionClassifyTimeoutMs;
336
- if (raw === void 0 || raw === null) return DEFAULT_CORRECTION_CLASSIFY_TIMEOUT_MS;
337
- const n = coerceNumber(raw);
338
- if (n === void 0 || !Number.isInteger(n) || n < 1 || n > MAX_CORRECTION_CLASSIFY_TIMEOUT_MS) {
339
- throw new Error(
340
- `Invalid correction.classifyTimeoutMs: expected an integer from 1 to ${MAX_CORRECTION_CLASSIFY_TIMEOUT_MS}, got ${JSON.stringify(raw)}`
341
- );
342
- }
343
- return n;
344
- })()
345
- };
346
- }
347
-
348
- export {
349
- MEMORY_CATEGORIES,
350
- CORRECTION_TEXT_MAX,
351
- validateCorrectionRequest,
352
- validateRedactionPattern,
353
- validateCorrectionAction,
354
- deterministicFallbackPlan,
355
- newPlanId,
356
- CorrectionContractError,
357
- DEFAULT_CORRECTION_CLASSIFY_TIMEOUT_MS,
358
- MAX_CORRECTION_CLASSIFY_TIMEOUT_MS,
359
- parseCorrectionConfig
360
- };
361
- //# sourceMappingURL=chunk-ETSJD5IV.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/correction/correction-contract.ts","../src/correction/correction-config.ts"],"sourcesContent":["/**\n * correction/correction-contract.ts — Types for the Correction Contract\n * (issue #1580).\n *\n * The Correction Contract is the SINGLE plan/apply pipeline every memory\n * correction flows through: supersession, invalidation, tombstone, edit,\n * rescope, redaction. A correction arrives as a plain-language statement\n * (\"we migrated to MySQL in March\"); the planner turns it into a structured\n * {@link CorrectionPlan}; the executor applies the plan in non-destructive\n * order through the existing storage/orchestrator chokepoints.\n *\n * This module is PURE types + validation helpers — no I/O, no side effects.\n * The planner and executor live in sibling modules and inject their own\n * collaborators so the contract is testable in isolation (rule 33).\n *\n * Design rules honored (issue #1580 design section):\n * - Plans are per-request state on disk, never module-level (rules 11/47).\n * - Caller-supplied namespaces are NEVER trusted raw — the service\n * resolves them through the normal namespace policy (rule 42).\n * - Bulk operations refuse past maxAffected (no silent truncation, §39).\n * - `never_store` redaction patterns must be bounded and safe (§34).\n */\n\nimport type { MemoryCategory, MemoryFrontmatter } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Request\n// ---------------------------------------------------------------------------\n\n/**\n * The user-facing input: a plain-language correction plus optional explicit\n * targets. This is what every surface (MCP / HTTP / CLI) collects before\n * handing off to the planner.\n */\nexport interface CorrectionRequest {\n /** Natural-language correction statement. Required, non-empty. */\n text: string;\n /**\n * Explicit target memory ids (or handles via #1582). When present the\n * planner resolves these directly; an unknown id is an explicit error\n * (rule 34), never a silent empty plan. When absent the planner searches.\n */\n targetIds?: string[];\n /** Session key for namespace/principal resolution. */\n sessionKey?: string;\n /** Authenticated principal (resolved by the service, never trusted raw). */\n principal?: string;\n /**\n * Caller-suggested namespace. ALWAYS re-resolved through the namespace\n * policy by the service before reaching the planner (rule 42). The\n * planner only sees the ALREADY-AUTHORIZED namespace.\n */\n namespace?: string;\n /**\n * Winner memory id. When set, `targetIds` must be exactly the duplicate\n * (the loser). The planner skips classification and drafts one recoverable\n * supersede — no hard delete, no replacement write.\n */\n duplicateOf?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Classification + actions\n// ---------------------------------------------------------------------------\n\nexport type CorrectionClassification =\n | \"wrong\"\n | \"outdated\"\n | \"incomplete\"\n | \"wrong_scope\"\n | \"never_store\";\n\nexport const CORRECTION_CLASSIFICATIONS: readonly CorrectionClassification[] = [\n \"wrong\",\n \"outdated\",\n \"incomplete\",\n \"wrong_scope\",\n \"never_store\",\n];\n\n/**\n * A draft for a replacement memory (supersede action). Mirrors the subset of\n * {@link MemoryFrontmatter} a correction caller may legitimately set; the\n * executor fills in id/created/updated/source.\n */\nexport interface MemoryDraft {\n content: string;\n category?: MemoryCategory;\n confidence?: number;\n tags?: string[];\n entityRef?: string;\n /** Optional event-time anchor for bi-temporal supersession (#1578). */\n validAt?: string;\n /** Optional observed-at anchor for bi-temporal supersession (#1578). */\n observedAt?: string;\n structuredAttributes?: Record<string, string>;\n}\n\n/**\n * The known {@link MemoryCategory} values. A replacement/rescope category must\n * be one of these — rejecting path-like or unexpected strings before they reach\n * `StorageManager.writeMemory`, which incorporates the category into the\n * generated memory id/path (review thread Of-XJ).\n */\nexport const MEMORY_CATEGORIES: readonly MemoryCategory[] = [\n \"fact\", \"preference\", \"correction\", \"entity\", \"decision\",\n \"relationship\", \"principle\", \"commitment\", \"moment\",\n \"skill\", \"rule\", \"procedure\", \"reasoning_trace\",\n];\n\nexport type CorrectionAction =\n /**\n * Outdated: a new fact replaces the loser, or `winnerId` records an\n * existing memory as the replacement without writing a new one.\n */\n | { kind: \"supersede\"; loserId: string; replacement?: MemoryDraft; winnerId?: string }\n /** Incomplete / minor-wrong: a versioned edit to an existing memory. */\n | { kind: \"edit\"; memoryId: string; patch: string }\n /** Wrong: retire + tombstone. */\n | { kind: \"retract\"; memoryId: string }\n /** Wrong scope: move to a different namespace. */\n | { kind: \"rescope\"; memoryId: string; toNamespace: string }\n /** Never-store: a future-extraction redaction rule. */\n | { kind: \"redaction_rule\"; pattern: string };\n\nexport const CORRECTION_ACTION_KINDS: readonly CorrectionAction[\"kind\"][] = [\n \"supersede\",\n \"edit\",\n \"retract\",\n \"rescope\",\n \"redaction_rule\",\n];\n\n// ---------------------------------------------------------------------------\n// Plan + outcome\n// ---------------------------------------------------------------------------\n\n/**\n * One affected memory in a plan: where it lives, an excerpt, why it is\n * affected, and (when available) the source quote that supports the\n * correction (#1575 provenance).\n */\nexport interface CorrectionAffectedEntry {\n memoryId: string;\n /** File path relative to the storage dir, for diff rendering. */\n path: string;\n excerpt: string;\n why: string;\n sourceQuote?: string;\n}\n\n/**\n * A persisted, expiring correction plan. Read-only artifact produced by the\n * planner; consumed (once) by the executor.\n */\nexport interface CorrectionPlan {\n planId: string;\n request: CorrectionRequest;\n /** Authorized namespace the plan is scoped to (resolved by the service). */\n namespace: string;\n affected: CorrectionAffectedEntry[];\n classification: CorrectionClassification;\n actions: CorrectionAction[];\n /** Human-readable diff preview rendered via page-versioning. */\n diff: string;\n /** Planner confidence in [0, 1]. `0` means manual selection required. */\n confidence: number;\n warnings: string[];\n createdAt: string;\n /** ISO timestamp after which apply rejects the plan as expired. */\n expiresAt: string;\n /**\n * Lifecycle: `pending` → `applying` → `applied`|`partial` (or `discarded`).\n * The executor flips a plan to `applying` BEFORE running any mutation\n * (review thread OgIqt): if the process dies mid-apply, the plan stays\n * `applying` and is NOT silently retryable — a partially-applied plan must\n * never be re-applied wholesale (it would duplicate succeeded actions).\n */\n status?: \"pending\" | \"applying\" | \"applied\" | \"discarded\" | \"partial\";\n /**\n * ISO timestamp recorded when the plan transitioned to `applying` (#1713\n * Item 2). Startup recovery uses this to detect plans stuck in `applying`\n * past the stale-applying TTL (process died mid-apply) and discard+scrub\n * them. Absent on plans that never entered `applying`.\n */\n applyingAt?: string;\n}\n\n/**\n * Per-action outcome recorded by the executor. An action whose new-state\n * write failed is `failed`; the executor never destroys old state for a\n * failed action (rule 25 / checklist §14).\n */\nexport interface CorrectionActionResult {\n action: CorrectionAction;\n status: \"applied\" | \"failed\" | \"skipped\";\n /** For supersede: the new memory id. For edit: the memory id. */\n memoryId?: string;\n /** For supersede/retract: the emitted tombstone id (if any). */\n tombstoneId?: string;\n error?: string;\n}\n\nexport interface CorrectionOutcome {\n planId: string;\n status: \"applied\" | \"partial\";\n results: CorrectionActionResult[];\n /** Audit-record memory id (corrections are themselves memories). */\n auditMemoryId: string;\n /** ISO timestamp of the apply. */\n appliedAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// Validation helpers (pure) — shared by planner, executor, and surface tests\n// ---------------------------------------------------------------------------\n\n/** Maximum supported `text` length. Surfaces bound this earlier; the planner\n * re-validates so a direct-service caller cannot bypass. */\nexport const CORRECTION_TEXT_MAX = 10_000;\n\n/** Maximum supported redaction pattern length (§34 — bounded patterns). */\nexport const REDACTION_PATTERN_MAX = 256;\n\n/** Maximum memory-id length for `duplicateOf` / explicit targets. */\nexport const CORRECTION_MEMORY_ID_MAX = 512;\n\n/**\n * Validate a {@link CorrectionRequest}'s invariants. Returns the cleaned\n * request or throws with a field-specific message (rule 51 — list valid\n * options, never silently default).\n */\nexport function validateCorrectionRequest(request: CorrectionRequest): CorrectionRequest {\n if (!request || typeof request !== \"object\") {\n throw new CorrectionContractError(\"CorrectionRequest must be an object.\");\n }\n const text = typeof request.text === \"string\" ? request.text.trim() : \"\";\n if (text.length === 0) {\n throw new CorrectionContractError(\"CorrectionRequest.text is required and must be non-empty.\");\n }\n if (text.length > CORRECTION_TEXT_MAX) {\n throw new CorrectionContractError(\n `CorrectionRequest.text exceeds the ${CORRECTION_TEXT_MAX}-character limit (${text.length}).`,\n );\n }\n const targetIds = Array.isArray(request.targetIds)\n ? request.targetIds.filter((id): id is string => typeof id === \"string\" && id.length > 0)\n : undefined;\n const normalizedTargets = targetIds !== undefined && targetIds.length === 0 ? undefined : targetIds;\n const duplicateOf = readDuplicateOf(request.duplicateOf);\n if (duplicateOf) {\n if (!normalizedTargets || normalizedTargets.length !== 1) {\n throw new CorrectionContractError(\n \"CorrectionRequest.duplicateOf requires exactly one targetIds entry (the duplicate memory).\",\n );\n }\n if (normalizedTargets[0] === duplicateOf) {\n throw new CorrectionContractError(\n \"CorrectionRequest.duplicateOf must be a different memory from targetIds.\",\n );\n }\n }\n return {\n text,\n ...(normalizedTargets ? { targetIds: normalizedTargets } : {}),\n ...(duplicateOf ? { duplicateOf } : {}),\n ...(request.sessionKey ? { sessionKey: request.sessionKey } : {}),\n ...(request.principal ? { principal: request.principal } : {}),\n ...(request.namespace ? { namespace: request.namespace } : {}),\n };\n}\n\nfunction readDuplicateOf(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") {\n throw new CorrectionContractError(\"CorrectionRequest.duplicateOf must be a memory id string.\");\n }\n const id = value.trim();\n if (id.length === 0 || id !== value) {\n throw new CorrectionContractError(\"CorrectionRequest.duplicateOf must be a non-empty memory id.\");\n }\n if (id.length > CORRECTION_MEMORY_ID_MAX) {\n throw new CorrectionContractError(\n `CorrectionRequest.duplicateOf exceeds the ${CORRECTION_MEMORY_ID_MAX}-character limit (${id.length}).`,\n );\n }\n return id;\n}\n\n/**\n * Validate a redaction pattern (§34 — bounded, literal-or-safe-regex; reject\n * catastrophic patterns). Returns the cleaned pattern or throws.\n */\nexport function validateRedactionPattern(pattern: string): string {\n if (typeof pattern !== \"string\") {\n throw new CorrectionContractError(\"redaction_rule.pattern must be a string.\");\n }\n const trimmed = pattern.trim();\n if (trimmed.length === 0) {\n throw new CorrectionContractError(\"redaction_rule.pattern is required.\");\n }\n if (trimmed.length > REDACTION_PATTERN_MAX) {\n throw new CorrectionContractError(\n `redaction_rule.pattern exceeds the ${REDACTION_PATTERN_MAX}-character bound.`,\n );\n }\n // Reject patterns that could match an unbounded string (overly-broad) OR\n // exhibit catastrophic backtracking (nested quantifiers like `(a+)+`). We do\n // NOT execute the regex (that would be ReDoS itself); we only inspect shape.\n if (isRegexLike(trimmed) && isUnsafeRedactionRegex(trimmed)) {\n throw new CorrectionContractError(\n \"redaction_rule.pattern is unsafe — use a bounded literal or a regex without nested quantifiers / overlapping alternation.\",\n );\n }\n // #1669 P2: reject zero-width regex (empty body or matches empty string)\n // that would withhold every fact.\n if (isRegexLike(trimmed)) {\n const regexBody = trimmed.slice(1, -1);\n if (regexBody.length === 0) {\n throw new CorrectionContractError(\"redaction_rule.pattern body is empty — use a non-empty regex.\");\n }\n try {\n if (new RegExp(regexBody).test(\"\")) {\n throw new CorrectionContractError(\n \"redaction_rule.pattern matches the empty string — it would withhold every fact.\",\n );\n }\n } catch (e) {\n if (e instanceof CorrectionContractError) throw e;\n // Compilation failed — the extraction-time defense handles it.\n }\n }\n return trimmed;\n}\n\n/** Only `/.../`-wrapped patterns are treated as regex; everything else is a\n * literal (review thread P1 — consistent with extraction-redaction-rules.ts). */\nfunction isRegexLike(pattern: string): boolean {\n return pattern.startsWith(\"/\") && pattern.endsWith(\"/\") && pattern.length >= 2;\n}\n\n/**\n * Reject a regex that would either match an arbitrary-length run of any\n * character (overly-broad) OR exhibit catastrophic backtracking (ReDoS).\n * Mirrors the safe-regex heuristic in extraction-redaction-rules.ts so the\n * apply-time chokepoint and the extraction-time defense agree on what is\n * pathological — intentionally not imported to keep the two modules decoupled\n * (contract owns validation; extraction owns consultation).\n */\nfunction isUnsafeRedactionRegex(pattern: string): boolean {\n const body = pattern.startsWith(\"/\") && pattern.endsWith(\"/\")\n ? pattern.slice(1, -1)\n : pattern;\n // `.*`, `.+`, `.`, or `(.*)` etc. anywhere → overly broad.\n if (/(?:^|[^\\\\])\\(\\.\\*\\)|(?:^|[^\\\\])\\.\\*|(?:^|[^\\\\])\\.\\+|^\\.([^*+]?)$/.test(body)) {\n return true;\n }\n // Nested quantifier: a group (...) whose body ends with a quantifier and\n // which is itself quantified → exponential blowup on near-miss inputs\n // (classic ReDoS shapes: (a+)+, (a*)*, (a?)+). Also catches overlapping\n // alternation under repetition: (a|a)+ where branches share a prefix.\n if (body.length > 512) return true;\n for (let i = 0; i < body.length; i++) {\n if (body[i] !== \"(\") continue;\n let depth = 1;\n let j = i + 1;\n while (j < body.length && depth > 0) {\n if (body[j] === \"\\\\\") { j += 2; continue; }\n if (body[j] === \"(\") depth++;\n else if (body[j] === \")\") depth--;\n j++;\n }\n if (depth !== 0) continue;\n const afterGroup = body[j];\n if (afterGroup !== \"+\" && afterGroup !== \"*\" && afterGroup !== \"{\") continue;\n const groupBody = body.slice(i + 1, j - 1);\n if (/[+*?]$/.test(groupBody) || /\\{\\d+,?\\d*\\}[+*?]?$/.test(groupBody)) {\n return true;\n }\n if (groupBody.includes(\"|\")) {\n const branches = groupBody.split(\"|\");\n if (branches.length >= 2) {\n const firstChars = new Set(branches.map((b) => b[0]).filter(Boolean));\n if (firstChars.size < branches.filter((b) => b.length > 0).length) {\n return true;\n }\n }\n }\n i = j;\n }\n return false;\n}\n\n/**\n * Validate the shape of a {@link CorrectionAction}. Used by the executor\n * before applying and by the surface layer to reject malformed client input\n * (rule 51 — list valid kinds).\n */\nexport function validateCorrectionAction(action: unknown): asserts action is CorrectionAction {\n if (!action || typeof action !== \"object\") {\n throw new CorrectionContractError(\"CorrectionAction must be an object.\");\n }\n const a = action as Record<string, unknown>;\n if (typeof a.kind !== \"string\" || !CORRECTION_ACTION_KINDS.includes(a.kind as CorrectionAction[\"kind\"])) {\n throw new CorrectionContractError(\n `CorrectionAction.kind must be one of: ${CORRECTION_ACTION_KINDS.join(\", \")}.`,\n );\n }\n switch (a.kind) {\n case \"supersede\":\n if (typeof a.loserId !== \"string\" || a.loserId.length === 0) {\n throw new CorrectionContractError(\"supersede.loserId is required.\");\n }\n {\n const hasReplacement = a.replacement !== undefined && a.replacement !== null;\n const hasWinner = a.winnerId !== undefined && a.winnerId !== null;\n if (hasWinner) {\n if (typeof a.winnerId !== \"string\" || a.winnerId.trim().length === 0 || a.winnerId !== a.winnerId.trim()) {\n throw new CorrectionContractError(\"supersede.winnerId must be a non-empty memory id.\");\n }\n if (a.winnerId === a.loserId) {\n throw new CorrectionContractError(\"supersede.winnerId must differ from loserId.\");\n }\n if (hasReplacement) {\n throw new CorrectionContractError(\"supersede.winnerId cannot be combined with a replacement draft.\");\n }\n }\n if (hasReplacement) validateMemoryDraft(a.replacement);\n }\n break;\n case \"edit\":\n if (typeof a.memoryId !== \"string\" || a.memoryId.length === 0) {\n throw new CorrectionContractError(\"edit.memoryId is required.\");\n }\n if (typeof a.patch !== \"string\" || a.patch.length === 0) {\n throw new CorrectionContractError(\"edit.patch is required and must be non-empty.\");\n }\n break;\n case \"retract\":\n if (typeof a.memoryId !== \"string\" || a.memoryId.length === 0) {\n throw new CorrectionContractError(\"retract.memoryId is required.\");\n }\n break;\n case \"rescope\":\n if (typeof a.memoryId !== \"string\" || a.memoryId.length === 0) {\n throw new CorrectionContractError(\"rescope.memoryId is required.\");\n }\n if (typeof a.toNamespace !== \"string\" || a.toNamespace.trim().length === 0) {\n throw new CorrectionContractError(\"rescope.toNamespace is required.\");\n }\n break;\n case \"redaction_rule\":\n if (typeof a.pattern !== \"string\") {\n throw new CorrectionContractError(\"redaction_rule.pattern is required.\");\n }\n validateRedactionPattern(a.pattern);\n break;\n }\n}\n\n/** Validate a {@link MemoryDraft}. Throws on invalid shape. */\nexport function validateMemoryDraft(draft: unknown): asserts draft is MemoryDraft {\n if (!draft || typeof draft !== \"object\") {\n throw new CorrectionContractError(\"MemoryDraft must be an object.\");\n }\n const d = draft as Record<string, unknown>;\n if (typeof d.content !== \"string\" || d.content.trim().length === 0) {\n throw new CorrectionContractError(\"MemoryDraft.content is required and must be non-empty.\");\n }\n if (d.category !== undefined) {\n if (typeof d.category !== \"string\" || !(MEMORY_CATEGORIES as readonly string[]).includes(d.category)) {\n throw new CorrectionContractError(\n `MemoryDraft.category must be one of: ${MEMORY_CATEGORIES.join(\", \")}.`,\n );\n }\n }\n if (d.confidence !== undefined && (typeof d.confidence !== \"number\" || d.confidence < 0 || d.confidence > 1)) {\n throw new CorrectionContractError(\"MemoryDraft.confidence must be a number in [0, 1].\");\n }\n if (d.tags !== undefined && !Array.isArray(d.tags)) {\n throw new CorrectionContractError(\"MemoryDraft.tags must be an array.\");\n }\n if (d.structuredAttributes !== undefined && (typeof d.structuredAttributes !== \"object\" || d.structuredAttributes === null)) {\n throw new CorrectionContractError(\"MemoryDraft.structuredAttributes must be an object.\");\n }\n}\n\n/**\n * Deterministic fallback plan (rule 13): when the planner's LLM is\n * unavailable, the plan degrades to a search result, never an error page.\n * Classification `outdated`, confidence `0`, actions empty.\n */\nexport function deterministicFallbackPlan(args: {\n request: CorrectionRequest;\n namespace: string;\n affected: CorrectionAffectedEntry[];\n warnings: string[];\n createdAt: string;\n expiresAt: string;\n}): CorrectionPlan {\n return {\n planId: newPlanId(),\n request: args.request,\n namespace: args.namespace,\n affected: args.affected,\n classification: \"outdated\",\n actions: [],\n diff: \"\",\n confidence: 0,\n warnings: [...args.warnings, \"planner LLM unavailable — manual action selection required\"],\n createdAt: args.createdAt,\n expiresAt: args.expiresAt,\n status: \"pending\",\n };\n}\n\n/** Generate a stable plan id. Exposed for tests + deterministic fallback. */\nexport function newPlanId(): string {\n return `corr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Error class for contract violations. Surfaces map it to a 400 / input error. */\nexport class CorrectionContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CorrectionContractError\";\n }\n}\n","/**\n * Correction-contract config (issue #1580 plus classify timeout).\n *\n * Extracted from config.ts so the grandfathered parser file does not grow.\n * Nested `correction.<key>` wins over the flat `correction<Key>` legacy key.\n * Invalid values throw — they are never clamped or silently defaulted.\n *\n * Reads stay inline on `cfg` so the parsed-key extractor records the same\n * paths the plugin schema declares.\n */\nimport { coerceBool, coerceNumber } from \"../connectors/coerce.js\";\n\nexport const DEFAULT_CORRECTION_CLASSIFY_TIMEOUT_MS = 45_000;\nexport const MAX_CORRECTION_CLASSIFY_TIMEOUT_MS = 300_000;\n\nexport interface ParsedCorrectionConfig {\n correctionEnabled: boolean;\n correctionApplyRequiresConfirm: boolean;\n correctionMaxAffected: number;\n correctionPlanTtlHours: number;\n correctionClassifyTimeoutMs: number;\n}\n\nexport function parseCorrectionConfig(cfg: Record<string, unknown>): ParsedCorrectionConfig {\n return {\n correctionEnabled: (() => {\n const nested = (cfg.correction as Record<string, unknown> | undefined)?.enabled;\n const raw = nested !== undefined ? nested : cfg.correctionEnabled;\n if (raw === undefined || raw === null) return true;\n const value = coerceBool(raw);\n if (value === undefined) {\n throw new Error(`Invalid correction.enabled: expected a boolean, got ${JSON.stringify(raw)}`);\n }\n return value;\n })(),\n correctionApplyRequiresConfirm: (() => {\n const nested = (cfg.correction as Record<string, unknown> | undefined)?.applyRequiresConfirm;\n const raw = nested !== undefined ? nested : cfg.correctionApplyRequiresConfirm;\n if (raw === undefined || raw === null) return true;\n const value = coerceBool(raw);\n if (value === undefined) {\n throw new Error(`Invalid correction.applyRequiresConfirm: expected a boolean, got ${JSON.stringify(raw)}`);\n }\n return value;\n })(),\n correctionMaxAffected: (() => {\n const rawNested = (cfg.correction as Record<string, unknown> | undefined)?.maxAffected;\n const raw = rawNested !== undefined ? rawNested : cfg.correctionMaxAffected;\n if (raw === undefined || raw === null) return 10;\n const n = coerceNumber(raw);\n if (n === undefined || !Number.isFinite(n) || n < 1 || !Number.isInteger(n)) {\n throw new Error(`Invalid correction.maxAffected: expected an integer >= 1, got ${JSON.stringify(raw)}`);\n }\n return n;\n })(),\n correctionPlanTtlHours: (() => {\n const nested = (cfg.correction as Record<string, unknown> | undefined)?.planTtlHours;\n const fromNested = nested !== undefined ? coerceNumber(nested) : undefined;\n if (fromNested !== undefined && fromNested >= 1) return fromNested;\n if (nested !== undefined && fromNested === undefined) {\n throw new Error(`Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(nested)}`);\n }\n if (fromNested !== undefined && fromNested < 1) {\n throw new Error(`Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(nested)}`);\n }\n const fromFlat = coerceNumber(cfg.correctionPlanTtlHours);\n if (fromFlat !== undefined && fromFlat >= 1) return fromFlat;\n if (cfg.correctionPlanTtlHours !== undefined && fromFlat === undefined) {\n throw new Error(\n `Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(cfg.correctionPlanTtlHours)}`\n );\n }\n if (fromFlat !== undefined && fromFlat < 1) {\n throw new Error(\n `Invalid correction.planTtlHours: expected a number >= 1, got ${JSON.stringify(cfg.correctionPlanTtlHours)}`\n );\n }\n return 24;\n })(),\n correctionClassifyTimeoutMs: (() => {\n const nested = (cfg.correction as Record<string, unknown> | undefined)?.classifyTimeoutMs;\n const raw = nested !== undefined ? nested : cfg.correctionClassifyTimeoutMs;\n if (raw === undefined || raw === null) return DEFAULT_CORRECTION_CLASSIFY_TIMEOUT_MS;\n const n = coerceNumber(raw);\n if (n === undefined || !Number.isInteger(n) || n < 1 || n > MAX_CORRECTION_CLASSIFY_TIMEOUT_MS) {\n throw new Error(\n `Invalid correction.classifyTimeoutMs: expected an integer from 1 to ${MAX_CORRECTION_CLASSIFY_TIMEOUT_MS}, got ${JSON.stringify(raw)}`\n );\n }\n return n;\n })(),\n };\n}\n"],"mappings":";;;;;;AAwGO,IAAM,oBAA+C;AAAA,EAC1D;AAAA,EAAQ;AAAA,EAAc;AAAA,EAAc;AAAA,EAAU;AAAA,EAC9C;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