@remnic/core 1.1.0 → 1.1.2

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 (308) hide show
  1. package/dist/access-audit.d.ts +56 -0
  2. package/dist/access-audit.js +9 -0
  3. package/dist/access-cli.js +70 -53
  4. package/dist/access-cli.js.map +1 -1
  5. package/dist/access-http.d.ts +16 -9
  6. package/dist/access-http.js +26 -18
  7. package/dist/access-mcp.d.ts +16 -9
  8. package/dist/access-mcp.js +30 -8
  9. package/dist/access-schema.d.ts +124 -33
  10. package/dist/access-schema.js +5 -1
  11. package/dist/{access-service-HmO1Trrx.d.ts → access-service-Br8ZydTK.d.ts} +158 -63
  12. package/dist/access-service.d.ts +13 -6
  13. package/dist/access-service.js +23 -14
  14. package/dist/bootstrap.d.ts +6 -3
  15. package/dist/briefing.d.ts +1 -0
  16. package/dist/briefing.js +8 -6
  17. package/dist/buffer-surprise-report.d.ts +70 -0
  18. package/dist/buffer-surprise-report.js +7 -0
  19. package/dist/buffer-surprise-report.js.map +1 -0
  20. package/dist/buffer-surprise.d.ts +98 -0
  21. package/dist/buffer-surprise.js +11 -0
  22. package/dist/buffer-surprise.js.map +1 -0
  23. package/dist/buffer.d.ts +100 -2
  24. package/dist/buffer.js +1 -1
  25. package/dist/calibration.js +6 -6
  26. package/dist/causal-behavior.js +4 -4
  27. package/dist/causal-chain.js +2 -2
  28. package/dist/causal-consolidation.js +19 -18
  29. package/dist/causal-consolidation.js.map +1 -1
  30. package/dist/causal-retrieval.js +4 -4
  31. package/dist/causal-trajectory.js +1 -1
  32. package/dist/{chunk-QNJMBKFK.js → chunk-2LGMW3DJ.js} +3 -2
  33. package/dist/chunk-2LGMW3DJ.js.map +1 -0
  34. package/dist/{chunk-QDYXG4CS.js → chunk-3FPTCC3Z.js} +4 -3
  35. package/dist/chunk-3FPTCC3Z.js.map +1 -0
  36. package/dist/chunk-3GPTTA4J.js +57 -0
  37. package/dist/chunk-3GPTTA4J.js.map +1 -0
  38. package/dist/{chunk-ITRLGI2T.js → chunk-3OGMS3PE.js} +2 -2
  39. package/dist/{chunk-DEPL3635.js → chunk-3YGHKTBF.js} +1446 -196
  40. package/dist/chunk-3YGHKTBF.js.map +1 -0
  41. package/dist/{chunk-BLKTA7MM.js → chunk-4HQS2HPX.js} +54 -21
  42. package/dist/chunk-4HQS2HPX.js.map +1 -0
  43. package/dist/chunk-54V4BZWP.js +139 -0
  44. package/dist/chunk-54V4BZWP.js.map +1 -0
  45. package/dist/chunk-5JRF2PZA.js +67 -0
  46. package/dist/chunk-5JRF2PZA.js.map +1 -0
  47. package/dist/chunk-64NJRYU2.js +332 -0
  48. package/dist/chunk-64NJRYU2.js.map +1 -0
  49. package/dist/{chunk-OIT5QGG4.js → chunk-6AUUAZEX.js} +72 -2
  50. package/dist/chunk-6AUUAZEX.js.map +1 -0
  51. package/dist/{chunk-3QHL5ABG.js → chunk-6YJHX2DL.js} +191 -10
  52. package/dist/chunk-6YJHX2DL.js.map +1 -0
  53. package/dist/chunk-AJU4PJGY.js +126 -0
  54. package/dist/chunk-AJU4PJGY.js.map +1 -0
  55. package/dist/chunk-ASAITVLA.js +64 -0
  56. package/dist/chunk-ASAITVLA.js.map +1 -0
  57. package/dist/{chunk-44ICJRF3.js → chunk-AYXIPSZO.js} +5 -5
  58. package/dist/{chunk-MBJHSA7F.js → chunk-BECYBZLX.js} +265 -20
  59. package/dist/chunk-BECYBZLX.js.map +1 -0
  60. package/dist/chunk-C4SQJZAF.js +486 -0
  61. package/dist/chunk-C4SQJZAF.js.map +1 -0
  62. package/dist/{chunk-6UJ47TVX.js → chunk-CUPFXL3J.js} +2 -2
  63. package/dist/chunk-DF3RVK3X.js +119 -0
  64. package/dist/chunk-DF3RVK3X.js.map +1 -0
  65. package/dist/{chunk-N42IWANG.js → chunk-DG6YMRDC.js} +3 -3
  66. package/dist/chunk-DGVM5SFL.js +69 -0
  67. package/dist/chunk-DGVM5SFL.js.map +1 -0
  68. package/dist/{chunk-3SV6CQHO.js → chunk-DIXB44VE.js} +102 -66
  69. package/dist/chunk-DIXB44VE.js.map +1 -0
  70. package/dist/chunk-EIR5VLIH.js +90 -0
  71. package/dist/chunk-EIR5VLIH.js.map +1 -0
  72. package/dist/{chunk-GV6NLQ4X.js → chunk-F5VP6YCB.js} +374 -16
  73. package/dist/chunk-F5VP6YCB.js.map +1 -0
  74. package/dist/{chunk-6ZH4TU6I.js → chunk-FAAFWE4G.js} +2 -1
  75. package/dist/chunk-FAAFWE4G.js.map +1 -0
  76. package/dist/{chunk-7WQ6SLIE.js → chunk-FVA6TGI3.js} +2 -2
  77. package/dist/{chunk-PAORGQRI.js → chunk-GA5P7RST.js} +37 -23
  78. package/dist/chunk-GA5P7RST.js.map +1 -0
  79. package/dist/chunk-GDFS42HT.js +206 -0
  80. package/dist/chunk-GDFS42HT.js.map +1 -0
  81. package/dist/chunk-IISBCCWR.js +52 -0
  82. package/dist/chunk-IISBCCWR.js.map +1 -0
  83. package/dist/chunk-JBMSGZEQ.js +441 -0
  84. package/dist/chunk-JBMSGZEQ.js.map +1 -0
  85. package/dist/{chunk-J4IYOZZ5.js → chunk-JXS5PDQ7.js} +3 -1
  86. package/dist/chunk-JXS5PDQ7.js.map +1 -0
  87. package/dist/chunk-KVBLZUKV.js +173 -0
  88. package/dist/chunk-KVBLZUKV.js.map +1 -0
  89. package/dist/{chunk-4LACOVZX.js → chunk-L7IXWRYE.js} +10 -5
  90. package/dist/chunk-L7IXWRYE.js.map +1 -0
  91. package/dist/chunk-LBLXEFWK.js +51 -0
  92. package/dist/chunk-LBLXEFWK.js.map +1 -0
  93. package/dist/{chunk-WBSAYXVI.js → chunk-LOIMBRDE.js} +201 -45
  94. package/dist/chunk-LOIMBRDE.js.map +1 -0
  95. package/dist/{chunk-3WHVNEN7.js → chunk-LTCGGW2D.js} +1 -1
  96. package/dist/chunk-LTCGGW2D.js.map +1 -0
  97. package/dist/{chunk-ZVBB3T7V.js → chunk-NBVAS5MT.js} +25 -23
  98. package/dist/chunk-NBVAS5MT.js.map +1 -0
  99. package/dist/{chunk-UEYA6UC7.js → chunk-NZLQTHS5.js} +25 -2
  100. package/dist/chunk-NZLQTHS5.js.map +1 -0
  101. package/dist/{chunk-NQEVYWX6.js → chunk-OC5OXUQ4.js} +211 -7
  102. package/dist/chunk-OC5OXUQ4.js.map +1 -0
  103. package/dist/{chunk-LK6SGL53.js → chunk-OR64ZGRZ.js} +3 -2
  104. package/dist/chunk-OR64ZGRZ.js.map +1 -0
  105. package/dist/{chunk-SYUK3VLY.js → chunk-PVICZTKG.js} +117 -5
  106. package/dist/chunk-PVICZTKG.js.map +1 -0
  107. package/dist/chunk-PVPWZSSI.js +37 -0
  108. package/dist/chunk-PVPWZSSI.js.map +1 -0
  109. package/dist/{chunk-JL2PU6AI.js → chunk-R2XRID2N.js} +2 -2
  110. package/dist/{chunk-4NRAJUDS.js → chunk-RBBWYEFJ.js} +1 -1
  111. package/dist/chunk-RFYAYKTD.js +146 -0
  112. package/dist/chunk-RFYAYKTD.js.map +1 -0
  113. package/dist/chunk-SOBJ6NEY.js +18 -0
  114. package/dist/chunk-SOBJ6NEY.js.map +1 -0
  115. package/dist/{chunk-JIU55F3X.js → chunk-SPI27QT6.js} +2 -2
  116. package/dist/{chunk-MVTHXUBX.js → chunk-STGWEHYR.js} +479 -20
  117. package/dist/chunk-STGWEHYR.js.map +1 -0
  118. package/dist/{chunk-6LX5ORAS.js → chunk-TMYO7B5P.js} +4 -4
  119. package/dist/chunk-TVVEYCNW.js +65 -0
  120. package/dist/chunk-TVVEYCNW.js.map +1 -0
  121. package/dist/chunk-ULYOGL6R.js +322 -0
  122. package/dist/chunk-ULYOGL6R.js.map +1 -0
  123. package/dist/{chunk-37UIFYWO.js → chunk-UWB5LMWY.js} +108 -9
  124. package/dist/chunk-UWB5LMWY.js.map +1 -0
  125. package/dist/{chunk-47UU5PU2.js → chunk-VBVG2M5G.js} +18 -3
  126. package/dist/chunk-VBVG2M5G.js.map +1 -0
  127. package/dist/{chunk-7ECD5ATE.js → chunk-VDX363PS.js} +2 -2
  128. package/dist/{chunk-O5ETUNBT.js → chunk-VTU2B4VF.js} +7 -3
  129. package/dist/chunk-VTU2B4VF.js.map +1 -0
  130. package/dist/{chunk-MTLYEMJB.js → chunk-WCLICCGB.js} +18 -3
  131. package/dist/chunk-WCLICCGB.js.map +1 -0
  132. package/dist/chunk-X6GF3FX2.js +26 -0
  133. package/dist/chunk-X6GF3FX2.js.map +1 -0
  134. package/dist/{chunk-3QFQGRHO.js → chunk-XMHBH5H6.js} +4 -4
  135. package/dist/{chunk-DHHP2Z4X.js → chunk-XXVWLXSG.js} +2 -2
  136. package/dist/{chunk-XZ2TIKGC.js → chunk-Y7R2XJ5Q.js} +25 -9
  137. package/dist/chunk-Y7R2XJ5Q.js.map +1 -0
  138. package/dist/{chunk-ALXMCZEU.js → chunk-Z2E7VW55.js} +6 -3
  139. package/dist/chunk-Z2E7VW55.js.map +1 -0
  140. package/dist/chunk-ZAIM4TUE.js +488 -0
  141. package/dist/chunk-ZAIM4TUE.js.map +1 -0
  142. package/dist/chunk-ZZTOURJI.js +91 -0
  143. package/dist/chunk-ZZTOURJI.js.map +1 -0
  144. package/dist/{cli-BneVIEvh.d.ts → cli-BkeRaYfk.d.ts} +2 -2
  145. package/dist/cli.d.ts +13 -6
  146. package/dist/cli.js +42 -31
  147. package/dist/config.js +2 -2
  148. package/dist/consolidation-operator.d.ts +41 -0
  149. package/dist/consolidation-operator.js +11 -0
  150. package/dist/consolidation-operator.js.map +1 -0
  151. package/dist/consolidation-provenance-check.d.ts +68 -0
  152. package/dist/consolidation-provenance-check.js +9 -0
  153. package/dist/consolidation-provenance-check.js.map +1 -0
  154. package/dist/consolidation-undo.d.ts +123 -0
  155. package/dist/consolidation-undo.js +426 -0
  156. package/dist/consolidation-undo.js.map +1 -0
  157. package/dist/{contradiction-scan-GR33PONM.js → contradiction-scan-E3GJTI4F.js} +43 -7
  158. package/dist/contradiction-scan-E3GJTI4F.js.map +1 -0
  159. package/dist/cross-namespace-budget.d.ts +133 -0
  160. package/dist/cross-namespace-budget.js +9 -0
  161. package/dist/cross-namespace-budget.js.map +1 -0
  162. package/dist/direct-answer-wiring.js +5 -70
  163. package/dist/direct-answer-wiring.js.map +1 -1
  164. package/dist/embedding-fallback.js +2 -1
  165. package/dist/{engine-5TIQBYZR.js → engine-72LSIWQP.js} +8 -7
  166. package/dist/engine-72LSIWQP.js.map +1 -0
  167. package/dist/entity-retrieval.d.ts +1 -0
  168. package/dist/entity-retrieval.js +7 -6
  169. package/dist/explicit-capture.d.ts +6 -3
  170. package/dist/explicit-capture.js +2 -2
  171. package/dist/extraction-judge-telemetry.d.ts +113 -0
  172. package/dist/extraction-judge-telemetry.js +14 -0
  173. package/dist/extraction-judge-telemetry.js.map +1 -0
  174. package/dist/extraction-judge-training.d.ts +85 -0
  175. package/dist/extraction-judge-training.js +16 -0
  176. package/dist/extraction-judge-training.js.map +1 -0
  177. package/dist/extraction-judge.d.ts +124 -2
  178. package/dist/extraction-judge.js +11 -1
  179. package/dist/extraction.js +10 -9
  180. package/dist/fallback-llm.js +3 -3
  181. package/dist/graph-recall.d.ts +100 -0
  182. package/dist/graph-recall.js +8 -0
  183. package/dist/graph-recall.js.map +1 -0
  184. package/dist/graph-retrieval.d.ts +271 -0
  185. package/dist/graph-retrieval.js +21 -0
  186. package/dist/graph-retrieval.js.map +1 -0
  187. package/dist/importance.js +1 -1
  188. package/dist/index.d.ts +585 -20
  189. package/dist/index.js +542 -344
  190. package/dist/index.js.map +1 -1
  191. package/dist/local-llm.js +2 -2
  192. package/dist/memory-worth-bench.d.ts +51 -0
  193. package/dist/memory-worth-bench.js +131 -0
  194. package/dist/memory-worth-bench.js.map +1 -0
  195. package/dist/memory-worth-filter.d.ts +128 -0
  196. package/dist/memory-worth-filter.js +10 -0
  197. package/dist/memory-worth-filter.js.map +1 -0
  198. package/dist/memory-worth-outcomes.d.ts +118 -0
  199. package/dist/memory-worth-outcomes.js +9 -0
  200. package/dist/memory-worth-outcomes.js.map +1 -0
  201. package/dist/memory-worth.d.ts +102 -0
  202. package/dist/memory-worth.js +7 -0
  203. package/dist/memory-worth.js.map +1 -0
  204. package/dist/operator-toolkit.d.ts +40 -1
  205. package/dist/operator-toolkit.js +25 -16
  206. package/dist/{orchestrator-DRYA6_lW.d.ts → orchestrator-CmJ-NTdJ.d.ts} +233 -8
  207. package/dist/orchestrator.d.ts +6 -3
  208. package/dist/orchestrator.js +54 -44
  209. package/dist/page-versioning.d.ts +12 -1
  210. package/dist/page-versioning.js +5 -3
  211. package/dist/{port-C1GZFv8h.d.ts → port-BADbLZU5.d.ts} +2 -2
  212. package/dist/qmd-recall-cache.d.ts +1 -1
  213. package/dist/qmd.d.ts +5 -3
  214. package/dist/qmd.js +3 -3
  215. package/dist/reasoning-trace-recall.d.ts +90 -0
  216. package/dist/reasoning-trace-recall.js +13 -0
  217. package/dist/reasoning-trace-recall.js.map +1 -0
  218. package/dist/reasoning-trace-types.d.ts +54 -0
  219. package/dist/reasoning-trace-types.js +17 -0
  220. package/dist/reasoning-trace-types.js.map +1 -0
  221. package/dist/recall-audit-anomaly.d.ts +112 -0
  222. package/dist/recall-audit-anomaly.js +11 -0
  223. package/dist/recall-audit-anomaly.js.map +1 -0
  224. package/dist/recall-audit.js +5 -44
  225. package/dist/recall-audit.js.map +1 -1
  226. package/dist/recall-explain-renderer.d.ts +49 -0
  227. package/dist/recall-explain-renderer.js +18 -0
  228. package/dist/recall-explain-renderer.js.map +1 -0
  229. package/dist/recall-state.d.ts +12 -1
  230. package/dist/recall-state.js +1 -1
  231. package/dist/recall-xray-cli.d.ts +40 -0
  232. package/dist/recall-xray-cli.js +11 -0
  233. package/dist/recall-xray-cli.js.map +1 -0
  234. package/dist/recall-xray-renderer.d.ts +44 -0
  235. package/dist/recall-xray-renderer.js +18 -0
  236. package/dist/recall-xray-renderer.js.map +1 -0
  237. package/dist/recall-xray.d.ts +179 -0
  238. package/dist/recall-xray.js +13 -0
  239. package/dist/recall-xray.js.map +1 -0
  240. package/dist/resolve-provider-secret.d.ts +5 -1
  241. package/dist/resolve-provider-secret.js +3 -1
  242. package/dist/resume-bundles.js +6 -6
  243. package/dist/retrieval-agents.d.ts +1 -1
  244. package/dist/retrieval-tiers.d.ts +17 -0
  245. package/dist/retrieval-tiers.js +9 -0
  246. package/dist/retrieval-tiers.js.map +1 -0
  247. package/dist/schemas.d.ts +309 -53
  248. package/dist/schemas.js +1 -1
  249. package/dist/{semantic-consolidation-DrvSYRdB.d.ts → semantic-consolidation-CxJU6MJk.d.ts} +62 -1
  250. package/dist/semantic-consolidation.d.ts +2 -1
  251. package/dist/semantic-consolidation.js +22 -7
  252. package/dist/semantic-rule-promotion.js +7 -6
  253. package/dist/semantic-rule-verifier.js +7 -6
  254. package/dist/storage.d.ts +82 -1
  255. package/dist/storage.js +6 -5
  256. package/dist/summarizer.js +6 -6
  257. package/dist/temporal-supersession.d.ts +1 -0
  258. package/dist/tier-migration.d.ts +2 -1
  259. package/dist/tokens.js +2 -1
  260. package/dist/types.d.ts +276 -2
  261. package/dist/types.js +1 -1
  262. package/dist/verified-recall.js +7 -6
  263. package/package.json +1 -1
  264. package/dist/chunk-37UIFYWO.js.map +0 -1
  265. package/dist/chunk-3QHL5ABG.js.map +0 -1
  266. package/dist/chunk-3SV6CQHO.js.map +0 -1
  267. package/dist/chunk-3WHVNEN7.js.map +0 -1
  268. package/dist/chunk-47UU5PU2.js.map +0 -1
  269. package/dist/chunk-4LACOVZX.js.map +0 -1
  270. package/dist/chunk-6ZH4TU6I.js.map +0 -1
  271. package/dist/chunk-ALXMCZEU.js.map +0 -1
  272. package/dist/chunk-BLKTA7MM.js.map +0 -1
  273. package/dist/chunk-DEPL3635.js.map +0 -1
  274. package/dist/chunk-GV6NLQ4X.js.map +0 -1
  275. package/dist/chunk-J4IYOZZ5.js.map +0 -1
  276. package/dist/chunk-LAYN4LDC.js +0 -267
  277. package/dist/chunk-LAYN4LDC.js.map +0 -1
  278. package/dist/chunk-LK6SGL53.js.map +0 -1
  279. package/dist/chunk-MBJHSA7F.js.map +0 -1
  280. package/dist/chunk-MTLYEMJB.js.map +0 -1
  281. package/dist/chunk-MVTHXUBX.js.map +0 -1
  282. package/dist/chunk-NQEVYWX6.js.map +0 -1
  283. package/dist/chunk-O5ETUNBT.js.map +0 -1
  284. package/dist/chunk-OIT5QGG4.js.map +0 -1
  285. package/dist/chunk-PAORGQRI.js.map +0 -1
  286. package/dist/chunk-QDYXG4CS.js.map +0 -1
  287. package/dist/chunk-QNJMBKFK.js.map +0 -1
  288. package/dist/chunk-SYUK3VLY.js.map +0 -1
  289. package/dist/chunk-UEYA6UC7.js.map +0 -1
  290. package/dist/chunk-UVJFDP7P.js +0 -202
  291. package/dist/chunk-UVJFDP7P.js.map +0 -1
  292. package/dist/chunk-WBSAYXVI.js.map +0 -1
  293. package/dist/chunk-XZ2TIKGC.js.map +0 -1
  294. package/dist/chunk-ZVBB3T7V.js.map +0 -1
  295. package/dist/contradiction-scan-GR33PONM.js.map +0 -1
  296. /package/dist/{engine-5TIQBYZR.js.map → access-audit.js.map} +0 -0
  297. /package/dist/{chunk-ITRLGI2T.js.map → chunk-3OGMS3PE.js.map} +0 -0
  298. /package/dist/{chunk-44ICJRF3.js.map → chunk-AYXIPSZO.js.map} +0 -0
  299. /package/dist/{chunk-6UJ47TVX.js.map → chunk-CUPFXL3J.js.map} +0 -0
  300. /package/dist/{chunk-N42IWANG.js.map → chunk-DG6YMRDC.js.map} +0 -0
  301. /package/dist/{chunk-7WQ6SLIE.js.map → chunk-FVA6TGI3.js.map} +0 -0
  302. /package/dist/{chunk-JL2PU6AI.js.map → chunk-R2XRID2N.js.map} +0 -0
  303. /package/dist/{chunk-4NRAJUDS.js.map → chunk-RBBWYEFJ.js.map} +0 -0
  304. /package/dist/{chunk-JIU55F3X.js.map → chunk-SPI27QT6.js.map} +0 -0
  305. /package/dist/{chunk-6LX5ORAS.js.map → chunk-TMYO7B5P.js.map} +0 -0
  306. /package/dist/{chunk-7ECD5ATE.js.map → chunk-VDX363PS.js.map} +0 -0
  307. /package/dist/{chunk-3QFQGRHO.js.map → chunk-XMHBH5H6.js.map} +0 -0
  308. /package/dist/{chunk-DHHP2Z4X.js.map → chunk-XXVWLXSG.js.map} +0 -0
@@ -0,0 +1,173 @@
1
+ // src/recall-xray.ts
2
+ import { randomUUID } from "crypto";
3
+ var RECALL_XRAY_SERVED_BY_VALUES = [
4
+ "direct-answer",
5
+ "hybrid",
6
+ "graph",
7
+ "recent-scan",
8
+ "procedural",
9
+ "review-context"
10
+ ];
11
+ function isRecallXrayServedBy(value) {
12
+ return typeof value === "string" && RECALL_XRAY_SERVED_BY_VALUES.includes(value);
13
+ }
14
+ function buildXraySnapshot(input) {
15
+ const now = input.now ?? Date.now;
16
+ const snapshotIdGenerator = input.snapshotIdGenerator ?? randomUUID;
17
+ const results = Array.isArray(input.results) ? input.results.map(cloneResult) : [];
18
+ const filters = Array.isArray(input.filters) ? input.filters.map(cloneFilter) : [];
19
+ const budgetChars = nonNegativeInt(input.budget?.chars);
20
+ const budgetUsed = nonNegativeInt(input.budget?.used);
21
+ const tierExplain = input.tierExplain && typeof input.tierExplain === "object" ? cloneTierExplain(input.tierExplain) : null;
22
+ return {
23
+ schemaVersion: "1",
24
+ query: typeof input.query === "string" ? input.query : "",
25
+ snapshotId: snapshotIdGenerator(),
26
+ capturedAt: now(),
27
+ tierExplain,
28
+ results,
29
+ filters,
30
+ budget: { chars: budgetChars, used: budgetUsed },
31
+ sessionKey: nonEmptyString(input.sessionKey),
32
+ namespace: nonEmptyString(input.namespace),
33
+ traceId: nonEmptyString(input.traceId)
34
+ };
35
+ }
36
+ var RecallXrayBuilder = class {
37
+ query;
38
+ sessionKey;
39
+ namespace;
40
+ traceId;
41
+ tierExplain = null;
42
+ results = [];
43
+ filters = [];
44
+ budgetChars = 0;
45
+ budgetUsed = 0;
46
+ constructor(opts) {
47
+ this.query = typeof opts.query === "string" ? opts.query : "";
48
+ this.sessionKey = nonEmptyString(opts.sessionKey);
49
+ this.namespace = nonEmptyString(opts.namespace);
50
+ this.traceId = nonEmptyString(opts.traceId);
51
+ }
52
+ setNamespace(namespace) {
53
+ this.namespace = nonEmptyString(namespace);
54
+ }
55
+ setTraceId(traceId) {
56
+ this.traceId = nonEmptyString(traceId);
57
+ }
58
+ setTierExplain(tierExplain) {
59
+ this.tierExplain = tierExplain && typeof tierExplain === "object" ? cloneTierExplain(tierExplain) : null;
60
+ }
61
+ setBudget(budget) {
62
+ this.budgetChars = nonNegativeInt(budget.chars);
63
+ this.budgetUsed = nonNegativeInt(budget.used);
64
+ }
65
+ recordResult(result) {
66
+ this.results.push(cloneResult(result));
67
+ }
68
+ recordFilter(filter) {
69
+ this.filters.push(cloneFilter(filter));
70
+ }
71
+ build(opts = {}) {
72
+ return buildXraySnapshot({
73
+ query: this.query,
74
+ tierExplain: this.tierExplain,
75
+ results: this.results,
76
+ filters: this.filters,
77
+ budget: { chars: this.budgetChars, used: this.budgetUsed },
78
+ sessionKey: this.sessionKey,
79
+ namespace: this.namespace,
80
+ traceId: this.traceId,
81
+ now: opts.now,
82
+ snapshotIdGenerator: opts.snapshotIdGenerator
83
+ });
84
+ }
85
+ };
86
+ function cloneResult(result) {
87
+ if (!result || typeof result !== "object") {
88
+ throw new TypeError("RecallXrayResult must be an object");
89
+ }
90
+ if (!isRecallXrayServedBy(result.servedBy)) {
91
+ throw new TypeError(
92
+ `RecallXrayResult.servedBy must be one of ${RECALL_XRAY_SERVED_BY_VALUES.join(
93
+ ", "
94
+ )}; got ${JSON.stringify(result.servedBy)}`
95
+ );
96
+ }
97
+ const memoryId = typeof result.memoryId === "string" ? result.memoryId : "";
98
+ const path = typeof result.path === "string" ? result.path : "";
99
+ const admittedBy = Array.isArray(result.admittedBy) ? result.admittedBy.filter((x) => typeof x === "string") : [];
100
+ const graphPath = Array.isArray(result.graphPath) ? result.graphPath.filter((x) => typeof x === "string") : void 0;
101
+ const auditEntryId = nonEmptyString(result.auditEntryId);
102
+ const rejectedBy = nonEmptyString(result.rejectedBy);
103
+ const scoreDecomposition = cloneScoreDecomposition(result.scoreDecomposition);
104
+ const out = {
105
+ memoryId,
106
+ path,
107
+ servedBy: result.servedBy,
108
+ scoreDecomposition,
109
+ admittedBy
110
+ };
111
+ if (graphPath !== void 0) out.graphPath = graphPath;
112
+ if (auditEntryId !== void 0) out.auditEntryId = auditEntryId;
113
+ if (rejectedBy !== void 0) out.rejectedBy = rejectedBy;
114
+ return out;
115
+ }
116
+ function cloneFilter(filter) {
117
+ if (!filter || typeof filter !== "object") {
118
+ throw new TypeError("RecallFilterTrace must be an object");
119
+ }
120
+ const out = {
121
+ name: typeof filter.name === "string" ? filter.name : "",
122
+ considered: nonNegativeInt(filter.considered),
123
+ admitted: nonNegativeInt(filter.admitted)
124
+ };
125
+ const reason = nonEmptyString(filter.reason);
126
+ if (reason !== void 0) out.reason = reason;
127
+ return out;
128
+ }
129
+ function cloneScoreDecomposition(value) {
130
+ if (!value || typeof value !== "object") {
131
+ return { final: 0 };
132
+ }
133
+ const out = {
134
+ final: finiteNumber(value.final) ?? 0
135
+ };
136
+ const vector = finiteNumber(value.vector);
137
+ if (vector !== void 0) out.vector = vector;
138
+ const bm25 = finiteNumber(value.bm25);
139
+ if (bm25 !== void 0) out.bm25 = bm25;
140
+ const importance = finiteNumber(value.importance);
141
+ if (importance !== void 0) out.importance = importance;
142
+ const mmrPenalty = finiteNumber(value.mmrPenalty);
143
+ if (mmrPenalty !== void 0) out.mmrPenalty = mmrPenalty;
144
+ const tierPrior = finiteNumber(value.tierPrior);
145
+ if (tierPrior !== void 0) out.tierPrior = tierPrior;
146
+ return out;
147
+ }
148
+ function cloneTierExplain(tierExplain) {
149
+ return structuredClone(tierExplain);
150
+ }
151
+ function nonNegativeInt(value) {
152
+ if (typeof value !== "number" || !Number.isFinite(value)) return 0;
153
+ if (value <= 0) return 0;
154
+ return Math.floor(value);
155
+ }
156
+ function finiteNumber(value) {
157
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
158
+ return value;
159
+ }
160
+ function nonEmptyString(value) {
161
+ if (typeof value !== "string") return void 0;
162
+ const trimmed = value.trim();
163
+ if (trimmed.length === 0) return void 0;
164
+ return trimmed;
165
+ }
166
+
167
+ export {
168
+ RECALL_XRAY_SERVED_BY_VALUES,
169
+ isRecallXrayServedBy,
170
+ buildXraySnapshot,
171
+ RecallXrayBuilder
172
+ };
173
+ //# sourceMappingURL=chunk-KVBLZUKV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/recall-xray.ts"],"sourcesContent":["/**\n * Recall X-ray snapshot schema (issue #570, PR 1).\n *\n * The X-ray surface is the unified, per-result attribution document that\n * merges the tier that served each memory, its score decomposition, any\n * graph path, an audit entry id, and the exact filter/eligibility ladder\n * that either admitted or rejected each candidate. This file defines the\n * schema and an in-memory builder + builder-state helper.\n *\n * Scope for PR 1 (this slice):\n * - Types only + pure builder functions (no IO, no rendering).\n * - Orchestrator plumbing captures a snapshot when the caller passes\n * `xrayCapture: true`. No behavior change when the flag is absent.\n * - NO new public surfaces here — CLI/HTTP/MCP land in later slices.\n *\n * The shared renderer lands in PR 2 at `recall-xray-renderer.ts`. Do not\n * fork formatting logic into other surfaces; extend the renderer.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport type { RecallTierExplain } from \"./types.js\";\n\n/**\n * Which retrieval source produced a given result. This is the X-ray\n * tier ladder called out in issue #570 and is *distinct* from the\n * `RetrievalTier` enum (which describes issue #518's tier-explain\n * block). Keeping the sets separate lets the two observability\n * surfaces evolve without conflating their vocabularies:\n *\n * - `RetrievalTier` — direct-answer eligibility ladder.\n * - `RecallXrayServedBy` — which source materialized each result.\n */\nexport type RecallXrayServedBy =\n | \"direct-answer\"\n | \"hybrid\"\n | \"graph\"\n | \"recent-scan\"\n | \"procedural\"\n | \"review-context\";\n\nexport const RECALL_XRAY_SERVED_BY_VALUES: readonly RecallXrayServedBy[] = [\n \"direct-answer\",\n \"hybrid\",\n \"graph\",\n \"recent-scan\",\n \"procedural\",\n \"review-context\",\n] as const;\n\nexport function isRecallXrayServedBy(\n value: unknown,\n): value is RecallXrayServedBy {\n return (\n typeof value === \"string\" &&\n (RECALL_XRAY_SERVED_BY_VALUES as readonly string[]).includes(value)\n );\n}\n\n/**\n * Score decomposition for a single X-ray result.\n *\n * All fields are optional because different tiers populate different\n * terms: `hybrid` reports vector + bm25 + mmr penalty, `direct-answer`\n * reports importance + tier prior, etc. The only guaranteed field is\n * `final`, which is the post-combination score used for ordering.\n */\nexport interface RecallXrayScoreDecomposition {\n vector?: number;\n bm25?: number;\n importance?: number;\n mmrPenalty?: number;\n tierPrior?: number;\n final: number;\n}\n\n/**\n * Per-result breakdown inside an X-ray snapshot.\n */\nexport interface RecallXrayResult {\n memoryId: string;\n path: string;\n servedBy: RecallXrayServedBy;\n scoreDecomposition: RecallXrayScoreDecomposition;\n graphPath?: string[];\n auditEntryId?: string;\n /** Human-readable list of filters the candidate *passed*. */\n admittedBy: string[];\n /**\n * First filter that *would have* rejected the candidate, or undefined\n * when the candidate was admitted without a rejection trace. When\n * present, `admittedBy` may still contain filters the candidate passed\n * before the rejecting gate; consumers should render both.\n */\n rejectedBy?: string;\n}\n\n/**\n * Trace entry for a filter the orchestrator evaluated during recall.\n * Captures the name of the filter, how many candidates it saw, and how\n * many it let through. Used by X-ray consumers to render the filter\n * ladder above the per-result breakdown.\n */\nexport interface RecallFilterTrace {\n name: string;\n considered: number;\n admitted: number;\n /** Optional human-readable reason for any rejections. */\n reason?: string;\n}\n\n/**\n * The unified X-ray snapshot. CLI, HTTP, and MCP surfaces all render\n * this same shape through the shared renderer (CLAUDE.md rule 22).\n */\nexport interface RecallXraySnapshot {\n /** Stable v1 tag so downstream consumers can version-gate their parsers. */\n schemaVersion: \"1\";\n query: string;\n /** UUID minted per capture; unique across snapshots within a process. */\n snapshotId: string;\n /** Epoch milliseconds the snapshot was captured. */\n capturedAt: number;\n /**\n * Tier-explain block from issue #518, carried verbatim when present.\n * `null` means direct-answer tier did not run (disabled, or another\n * tier served the query).\n */\n tierExplain: RecallTierExplain | null;\n results: RecallXrayResult[];\n filters: RecallFilterTrace[];\n /**\n * Character budget accounting for the final assembled recall payload.\n * `used` is the rendered-context length; `chars` is the cap. Both are\n * non-negative integers in `[0, 2**31)`.\n */\n budget: { chars: number; used: number };\n /** Optional session-scope fields carried for downstream filtering. */\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n}\n\n// ─── Builder ──────────────────────────────────────────────────────────────\n\nexport interface BuildXraySnapshotInput {\n query: string;\n tierExplain?: RecallTierExplain | null;\n results?: RecallXrayResult[];\n filters?: RecallFilterTrace[];\n budget?: { chars?: number; used?: number };\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n /** Optional injected timestamp for deterministic tests. */\n now?: () => number;\n /** Optional injected id generator for deterministic tests. */\n snapshotIdGenerator?: () => string;\n}\n\n/**\n * Build a `RecallXraySnapshot` from explicit input fields. Pure\n * function; safe to call from anywhere. All array/object inputs are\n * shallow-copied so caller mutation after build cannot tear the\n * returned snapshot.\n */\nexport function buildXraySnapshot(\n input: BuildXraySnapshotInput,\n): RecallXraySnapshot {\n const now = input.now ?? Date.now;\n const snapshotIdGenerator = input.snapshotIdGenerator ?? randomUUID;\n\n const results = Array.isArray(input.results)\n ? input.results.map(cloneResult)\n : [];\n const filters = Array.isArray(input.filters)\n ? input.filters.map(cloneFilter)\n : [];\n\n const budgetChars = nonNegativeInt(input.budget?.chars);\n const budgetUsed = nonNegativeInt(input.budget?.used);\n\n const tierExplain =\n input.tierExplain && typeof input.tierExplain === \"object\"\n ? cloneTierExplain(input.tierExplain)\n : null;\n\n return {\n schemaVersion: \"1\",\n query: typeof input.query === \"string\" ? input.query : \"\",\n snapshotId: snapshotIdGenerator(),\n capturedAt: now(),\n tierExplain,\n results,\n filters,\n budget: { chars: budgetChars, used: budgetUsed },\n sessionKey: nonEmptyString(input.sessionKey),\n namespace: nonEmptyString(input.namespace),\n traceId: nonEmptyString(input.traceId),\n };\n}\n\n/**\n * Mutable builder used by the orchestrator to accumulate X-ray fields\n * as recall progresses. Call `build()` to get the finalized\n * immutable-ish snapshot. All inputs are validated at insert time so\n * a malformed entry cannot poison the snapshot later.\n */\nexport class RecallXrayBuilder {\n private readonly query: string;\n private readonly sessionKey: string | undefined;\n private namespace: string | undefined;\n private traceId: string | undefined;\n private tierExplain: RecallTierExplain | null = null;\n private readonly results: RecallXrayResult[] = [];\n private readonly filters: RecallFilterTrace[] = [];\n private budgetChars = 0;\n private budgetUsed = 0;\n\n constructor(opts: {\n query: string;\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n }) {\n this.query = typeof opts.query === \"string\" ? opts.query : \"\";\n this.sessionKey = nonEmptyString(opts.sessionKey);\n this.namespace = nonEmptyString(opts.namespace);\n this.traceId = nonEmptyString(opts.traceId);\n }\n\n setNamespace(namespace: string | undefined): void {\n this.namespace = nonEmptyString(namespace);\n }\n\n setTraceId(traceId: string | undefined): void {\n this.traceId = nonEmptyString(traceId);\n }\n\n setTierExplain(tierExplain: RecallTierExplain | null | undefined): void {\n this.tierExplain =\n tierExplain && typeof tierExplain === \"object\"\n ? cloneTierExplain(tierExplain)\n : null;\n }\n\n setBudget(budget: { chars?: number; used?: number }): void {\n this.budgetChars = nonNegativeInt(budget.chars);\n this.budgetUsed = nonNegativeInt(budget.used);\n }\n\n recordResult(result: RecallXrayResult): void {\n this.results.push(cloneResult(result));\n }\n\n recordFilter(filter: RecallFilterTrace): void {\n this.filters.push(cloneFilter(filter));\n }\n\n build(opts: {\n now?: () => number;\n snapshotIdGenerator?: () => string;\n } = {}): RecallXraySnapshot {\n return buildXraySnapshot({\n query: this.query,\n tierExplain: this.tierExplain,\n results: this.results,\n filters: this.filters,\n budget: { chars: this.budgetChars, used: this.budgetUsed },\n sessionKey: this.sessionKey,\n namespace: this.namespace,\n traceId: this.traceId,\n now: opts.now,\n snapshotIdGenerator: opts.snapshotIdGenerator,\n });\n }\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────\n\nfunction cloneResult(result: RecallXrayResult): RecallXrayResult {\n if (!result || typeof result !== \"object\") {\n throw new TypeError(\"RecallXrayResult must be an object\");\n }\n if (!isRecallXrayServedBy(result.servedBy)) {\n throw new TypeError(\n `RecallXrayResult.servedBy must be one of ${RECALL_XRAY_SERVED_BY_VALUES.join(\n \", \",\n )}; got ${JSON.stringify(result.servedBy)}`,\n );\n }\n const memoryId = typeof result.memoryId === \"string\" ? result.memoryId : \"\";\n const path = typeof result.path === \"string\" ? result.path : \"\";\n const admittedBy = Array.isArray(result.admittedBy)\n ? result.admittedBy.filter((x): x is string => typeof x === \"string\")\n : [];\n const graphPath = Array.isArray(result.graphPath)\n ? result.graphPath.filter((x): x is string => typeof x === \"string\")\n : undefined;\n const auditEntryId = nonEmptyString(result.auditEntryId);\n const rejectedBy = nonEmptyString(result.rejectedBy);\n const scoreDecomposition = cloneScoreDecomposition(result.scoreDecomposition);\n const out: RecallXrayResult = {\n memoryId,\n path,\n servedBy: result.servedBy,\n scoreDecomposition,\n admittedBy,\n };\n if (graphPath !== undefined) out.graphPath = graphPath;\n if (auditEntryId !== undefined) out.auditEntryId = auditEntryId;\n if (rejectedBy !== undefined) out.rejectedBy = rejectedBy;\n return out;\n}\n\nfunction cloneFilter(filter: RecallFilterTrace): RecallFilterTrace {\n if (!filter || typeof filter !== \"object\") {\n throw new TypeError(\"RecallFilterTrace must be an object\");\n }\n const out: RecallFilterTrace = {\n name: typeof filter.name === \"string\" ? filter.name : \"\",\n considered: nonNegativeInt(filter.considered),\n admitted: nonNegativeInt(filter.admitted),\n };\n const reason = nonEmptyString(filter.reason);\n if (reason !== undefined) out.reason = reason;\n return out;\n}\n\nfunction cloneScoreDecomposition(\n value: RecallXrayScoreDecomposition | undefined,\n): RecallXrayScoreDecomposition {\n if (!value || typeof value !== \"object\") {\n return { final: 0 };\n }\n const out: RecallXrayScoreDecomposition = {\n final: finiteNumber(value.final) ?? 0,\n };\n const vector = finiteNumber(value.vector);\n if (vector !== undefined) out.vector = vector;\n const bm25 = finiteNumber(value.bm25);\n if (bm25 !== undefined) out.bm25 = bm25;\n const importance = finiteNumber(value.importance);\n if (importance !== undefined) out.importance = importance;\n const mmrPenalty = finiteNumber(value.mmrPenalty);\n if (mmrPenalty !== undefined) out.mmrPenalty = mmrPenalty;\n const tierPrior = finiteNumber(value.tierPrior);\n if (tierPrior !== undefined) out.tierPrior = tierPrior;\n return out;\n}\n\nfunction cloneTierExplain(tierExplain: RecallTierExplain): RecallTierExplain {\n // Use structuredClone so future RecallTierExplain additions do not\n // silently share references through hand-enumerated fields. The\n // payload is JSON-shaped.\n return structuredClone(tierExplain);\n}\n\nfunction nonNegativeInt(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 0;\n if (value <= 0) return 0;\n return Math.floor(value);\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return value;\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n return trimmed;\n}\n"],"mappings":";AAmBA,SAAS,kBAAkB;AAsBpB,IAAM,+BAA8D;AAAA,EACzE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,qBACd,OAC6B;AAC7B,SACE,OAAO,UAAU,YAChB,6BAAmD,SAAS,KAAK;AAEtE;AA6GO,SAAS,kBACd,OACoB;AACpB,QAAM,MAAM,MAAM,OAAO,KAAK;AAC9B,QAAM,sBAAsB,MAAM,uBAAuB;AAEzD,QAAM,UAAU,MAAM,QAAQ,MAAM,OAAO,IACvC,MAAM,QAAQ,IAAI,WAAW,IAC7B,CAAC;AACL,QAAM,UAAU,MAAM,QAAQ,MAAM,OAAO,IACvC,MAAM,QAAQ,IAAI,WAAW,IAC7B,CAAC;AAEL,QAAM,cAAc,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,gBAAgB,WAAW;AACpC;AAEA,SAAS,eAAe,OAAwB;AAC9C,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,MAAI,SAAS,EAAG,QAAO;AACvB,SAAO,KAAK,MAAM,KAAK;AACzB;AAEA,SAAS,aAAa,OAAoC;AACxD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,SAAO;AACT;AAEA,SAAS,eAAe,OAAoC;AAC1D,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,SAAO;AACT;","names":[]}
@@ -1,12 +1,17 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-GV6NLQ4X.js";
3
+ } from "./chunk-F5VP6YCB.js";
4
+ import {
5
+ readEnvVar,
6
+ resolveHomeDir
7
+ } from "./chunk-MARWOCVP.js";
4
8
  import {
5
9
  log
6
10
  } from "./chunk-2ODBA7MQ.js";
7
11
 
8
12
  // src/briefing.ts
9
13
  import { readFile } from "fs/promises";
14
+ import os from "os";
10
15
  import path from "path";
11
16
  var BRIEFING_FORMAT_ALLOWED = ["markdown", "json"];
12
17
  var BRIEFING_FOLLOWUP_DEFAULT_MODEL = "gpt-5.2";
@@ -775,15 +780,15 @@ function renderBriefingMarkdown(ctx) {
775
780
  }
776
781
  return lines.join("\n").trimEnd() + "\n";
777
782
  }
778
- function resolveBriefingSaveDir(configOverride, env = process.env) {
783
+ function resolveBriefingSaveDir(configOverride, env) {
779
784
  if (typeof configOverride === "string" && configOverride.trim().length > 0) {
780
785
  return path.resolve(configOverride.trim());
781
786
  }
782
- const remnicHome = env.REMNIC_HOME?.trim();
787
+ const remnicHome = (env === void 0 ? readEnvVar("REMNIC_HOME") : env.REMNIC_HOME)?.trim();
783
788
  if (remnicHome && remnicHome.length > 0) {
784
789
  return path.join(remnicHome, "briefings");
785
790
  }
786
- const home = env.HOME ?? env.USERPROFILE ?? ".";
791
+ const home = env === void 0 ? resolveHomeDir() : env.HOME ?? env.USERPROFILE ?? os.homedir();
787
792
  return path.join(home, ".remnic", "briefings");
788
793
  }
789
794
  function briefingFilename(date, format = "markdown") {
@@ -810,4 +815,4 @@ export {
810
815
  resolveBriefingSaveDir,
811
816
  briefingFilename
812
817
  };
813
- //# sourceMappingURL=chunk-4LACOVZX.js.map
818
+ //# sourceMappingURL=chunk-L7IXWRYE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/briefing.ts"],"sourcesContent":["/**\n * Daily Context Briefing (Issue #370)\n *\n * Produces a focused \"here is what matters right now\" briefing by\n * cross-referencing active entities, recent facts, open commitments,\n * LLM-generated follow-ups, and an optional calendar source.\n *\n * The module exposes:\n * - `parseBriefingWindow(token)` — CLI-friendly window parser.\n * - `buildBriefing(options)` — core builder that returns markdown + JSON.\n * - `FileCalendarSource` — stub CalendarSource implementation that reads\n * a local ICS or JSON file.\n *\n * ALL OpenAI usage in this module goes through the Responses API. Chat\n * Completions is never used.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { StorageManager } from \"./storage.js\";\nimport { readEnvVar, resolveHomeDir } from \"./runtime/env.js\";\nimport type {\n BriefingActiveThread,\n BriefingCalendarSourceError,\n BriefingFocus,\n BriefingFollowup,\n BriefingOpenCommitment,\n BriefingRecentEntity,\n BriefingResult,\n BriefingSections,\n CalendarEvent,\n CalendarSource,\n EntityFile,\n MemoryFile,\n} from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────────\n// Window parsing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Allowed values for the briefing format flag/field. */\nexport const BRIEFING_FORMAT_ALLOWED = [\"markdown\", \"json\"] as const;\n\n/**\n * Default model used for the Responses API follow-up generation call.\n * Mirrors the extraction engine default in config.ts — keep in sync.\n */\nexport const BRIEFING_FOLLOWUP_DEFAULT_MODEL = \"gpt-5.2\";\nexport type BriefingFormatValue = typeof BRIEFING_FORMAT_ALLOWED[number];\n\n/**\n * Validate a user-supplied `--format` flag value.\n * Returns `null` when the value is valid (or `undefined`, meaning the flag\n * was not supplied and the caller should fall back to the configured default).\n * Returns an error message string when the value is explicitly invalid.\n */\nexport function validateBriefingFormat(value: string | undefined): string | null {\n if (value === undefined) return null;\n if ((BRIEFING_FORMAT_ALLOWED as readonly string[]).includes(value)) return null;\n return `Invalid --format value: \"${value}\". Accepted: ${BRIEFING_FORMAT_ALLOWED.join(\", \")}.`;\n}\n\n/** Parsed briefing lookback window. */\nexport interface ParsedBriefingWindow {\n /** Start of the window (inclusive). */\n from: Date;\n /** End of the window (exclusive). */\n to: Date;\n /** Human-readable label. */\n label: string;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Maximum allowed lookback offset in milliseconds (100 years).\n * Anything beyond this is almost certainly a typo or abuse — and would\n * overflow to `Invalid Date` for sufficiently large values anyway.\n */\nconst MAX_WINDOW_MS = 100 * 365 * DAY_MS;\n\n/**\n * Parse a CLI-friendly window token into a concrete date range.\n *\n * Accepted forms (case-insensitive):\n * - `yesterday` — the previous UTC calendar day.\n * - `today` — the current UTC calendar day so far.\n * - `NNh` — last N hours (e.g. `24h`, `48h`).\n * - `NNd` — last N calendar days (e.g. `3d`, `7d`).\n * - `NNw` — last N weeks (e.g. `1w`, `2w`).\n *\n * Returns `null` for invalid tokens so callers can surface a clean error.\n */\nexport function parseBriefingWindow(\n token: string,\n now: Date = new Date(),\n): ParsedBriefingWindow | null {\n const raw = typeof token === \"string\" ? token.trim().toLowerCase() : \"\";\n if (raw.length === 0) return null;\n\n if (raw === \"yesterday\") {\n const startOfToday = startOfUtcDay(now);\n const from = new Date(startOfToday.getTime() - DAY_MS);\n return { from, to: startOfToday, label: \"yesterday\" };\n }\n\n if (raw === \"today\") {\n return { from: startOfUtcDay(now), to: now, label: \"today\" };\n }\n\n const match = raw.match(/^(\\d+)\\s*(h|d|w)$/);\n if (!match) return null;\n const value = parseInt(match[1], 10);\n if (!Number.isFinite(value) || value <= 0) return null;\n const unit = match[2];\n let ms = 0;\n if (unit === \"h\") ms = value * 60 * 60 * 1000;\n else if (unit === \"d\") ms = value * DAY_MS;\n else if (unit === \"w\") ms = value * 7 * DAY_MS;\n if (ms === 0) return null;\n // Reject values that exceed the 100-year cap or would overflow to Invalid Date.\n if (ms > MAX_WINDOW_MS || !Number.isFinite(ms)) return null;\n const from = new Date(now.getTime() - ms);\n if (!Number.isFinite(from.getTime())) return null;\n return {\n from,\n to: now,\n label: `last ${value}${unit}`,\n };\n}\n\nfunction startOfUtcDay(date: Date): Date {\n const d = new Date(date.getTime());\n d.setUTCHours(0, 0, 0, 0);\n return d;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Focus filter\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse a CLI `--focus` string into a structured focus filter.\n *\n * Accepted forms:\n * - `person:Jane Doe`\n * - `project:remnic-core`\n * - `topic:retrieval`\n *\n * If no prefix is supplied, falls back to `topic:<value>`.\n */\nexport function parseBriefingFocus(token: string | undefined): BriefingFocus | null {\n if (typeof token !== \"string\") return null;\n const trimmed = token.trim();\n if (trimmed.length === 0) return null;\n const [maybeType, ...rest] = trimmed.split(\":\");\n if (rest.length === 0) {\n return { type: \"topic\", value: maybeType };\n }\n const rawType = maybeType.toLowerCase();\n if (rawType === \"person\" || rawType === \"project\" || rawType === \"topic\") {\n const value = rest.join(\":\").trim();\n if (value.length === 0) return null;\n return { type: rawType, value };\n }\n return { type: \"topic\", value: trimmed };\n}\n\n/**\n * Derive the slugged form of a typed focus value that mirrors how entityRefs\n * are constructed (lowercased, non-alphanumeric runs → hyphens, prefixed with\n * the focus type). Example: `person:Jane Doe` → `\"person-jane-doe\"`.\n *\n * This lets `focusMatchesMemory` match against `entityRef` even when the\n * focus value was supplied with spaces/capitals that the slug normalised away.\n */\nfunction focusToEntityRefSlug(focus: BriefingFocus): string {\n const sluggedValue = focus.value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n return `${focus.type}-${sluggedValue}`;\n}\n\n/**\n * Decide whether a memory/entity matches the given focus filter.\n * Purely deterministic — no LLM, case-insensitive substring match across\n * the most useful surfaces.\n *\n * For `entityRef` matching we also check the slugged form of the typed focus\n * (e.g. `person:Jane Doe` → `\"person-jane-doe\"`) because entityRefs are stored\n * in normalised slug form and a raw substring match on `\"Jane Doe\"` would never\n * hit `\"person-jane-doe\"`.\n */\nexport function focusMatchesMemory(memory: MemoryFile, focus: BriefingFocus): boolean {\n const needle = focus.value.toLowerCase();\n const entityRef = (memory.frontmatter.entityRef ?? \"\").toLowerCase();\n\n // Raw substring match across content and tags (preserves existing behaviour).\n const rawHaystack = [\n memory.content,\n entityRef,\n ...(memory.frontmatter.tags ?? []),\n ]\n .join(\" \")\n .toLowerCase();\n if (rawHaystack.includes(needle)) return true;\n\n // Slug match: check whether the entityRef contains the slugged focus value.\n // This catches typed focus tokens like `person:Jane Doe` whose slug form\n // `\"person-jane-doe\"` matches an entityRef but the raw value never would.\n const slug = focusToEntityRefSlug(focus);\n return entityRef.includes(slug);\n}\n\nexport function focusMatchesEntity(entity: EntityFile, focus: BriefingFocus): boolean {\n const needle = focus.value.toLowerCase();\n if (focus.type === \"person\" && entity.type.toLowerCase() !== \"person\") return false;\n if (focus.type === \"project\" && entity.type.toLowerCase() !== \"project\") return false;\n const haystack = [\n entity.name,\n entity.synthesis || entity.summary || \"\",\n ...entity.facts,\n ...(entity.aliases ?? []),\n ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts]),\n ]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(needle);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Calendar source\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Stub `CalendarSource` backed by a single local file. Supports:\n * - JSON files containing an array of `CalendarEvent` records, OR a wrapper\n * `{ events: CalendarEvent[] }` object.\n * - Minimal ICS (`.ics`) files — extracts `VEVENT` blocks with `SUMMARY`,\n * `DTSTART`, `DTEND`, `LOCATION`, `DESCRIPTION`, `UID`.\n *\n * Real calendar integrations (Google, iCloud, Microsoft) can plug into the\n * same `CalendarSource` interface later.\n */\nexport class FileCalendarSource implements CalendarSource {\n constructor(private readonly filePath: string) {}\n\n async eventsForDate(dateIso: string): Promise<CalendarEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf-8\");\n } catch (err) {\n log.warn(`briefing: calendar source unreadable at ${this.filePath}: ${err}`);\n return [];\n }\n\n const events = this.filePath.toLowerCase().endsWith(\".ics\")\n ? parseIcsEvents(raw)\n : parseJsonEvents(raw);\n\n return events.filter((event) => eventFallsOnDate(event, dateIso));\n }\n}\n\nfunction parseJsonEvents(raw: string): CalendarEvent[] {\n try {\n const parsed = JSON.parse(raw) as unknown;\n const arr = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { events?: unknown }).events)\n ? ((parsed as { events: unknown[] }).events)\n : [];\n const events: CalendarEvent[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, unknown>;\n const id = typeof e.id === \"string\" ? e.id : typeof e.uid === \"string\" ? e.uid : cryptoRandomId();\n const title = typeof e.title === \"string\" ? e.title : typeof e.summary === \"string\" ? e.summary : \"\";\n const start = typeof e.start === \"string\" ? e.start : typeof e.dtstart === \"string\" ? e.dtstart : \"\";\n if (!title || !start) continue;\n events.push({\n id,\n title,\n start,\n end: typeof e.end === \"string\" ? e.end : typeof e.dtend === \"string\" ? e.dtend : undefined,\n location: typeof e.location === \"string\" ? e.location : undefined,\n notes: typeof e.notes === \"string\" ? e.notes : typeof e.description === \"string\" ? e.description : undefined,\n });\n }\n return events;\n } catch (err) {\n log.warn(`briefing: calendar JSON parse failed: ${err}`);\n return [];\n }\n}\n\ninterface IcsParsedLine {\n property: string;\n params: Record<string, string>;\n value: string;\n}\n\n/**\n * Parse a single ICS content line into its property, parameters, and value.\n * Returns null if the line is not a well-formed property line.\n *\n * Example:\n * `DTSTART;TZID=America/New_York:20260411T233000`\n * → { property: \"DTSTART\", params: { TZID: \"America/New_York\" }, value: \"20260411T233000\" }\n */\nfunction parseIcsLine(line: string): IcsParsedLine | null {\n // Find the first `:` outside of any parameter value. Per RFC 5545 parameter\n // values may be quoted, but the minimal-parser use case here only needs to\n // handle unquoted TZID values.\n const colonIdx = line.indexOf(\":\");\n if (colonIdx <= 0) return null;\n const head = line.slice(0, colonIdx);\n const value = line.slice(colonIdx + 1).trim();\n // Head is of the form `PROPERTY[;PARAM=val[;PARAM=val]]`.\n const headParts = head.split(\";\");\n const property = headParts[0]!.toUpperCase();\n if (!/^[A-Z0-9-]+$/.test(property)) return null;\n const params: Record<string, string> = {};\n for (let i = 1; i < headParts.length; i++) {\n const segment = headParts[i]!;\n const eqIdx = segment.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const name = segment.slice(0, eqIdx).toUpperCase();\n let val = segment.slice(eqIdx + 1);\n // Strip surrounding quotes if present (RFC 5545 §3.1).\n if (val.startsWith('\"') && val.endsWith('\"') && val.length >= 2) {\n val = val.slice(1, -1);\n }\n params[name] = val;\n }\n return { property, params, value };\n}\n\ninterface IcsDateField {\n raw: string;\n params: Record<string, string>;\n}\n\n/** @internal — exported for testing only. */\nexport function parseIcsEvents(raw: string): CalendarEvent[] {\n const events: CalendarEvent[] = [];\n // RFC 5545 §3.1 line unfolding: a CRLF (now \\n) followed by a single\n // whitespace character (space or tab) is a fold — remove both characters\n // to join the continuation onto the preceding logical line. This MUST\n // happen after normalising CRLF → \\n and BEFORE splitting on \\n.\n const normalized = raw.replace(/\\r\\n/g, \"\\n\").replace(/\\n[ \\t]/g, \"\");\n const blocks = normalized.split(/BEGIN:VEVENT/i).slice(1);\n for (const block of blocks) {\n const endIdx = block.search(/END:VEVENT/i);\n const body = endIdx === -1 ? block : block.slice(0, endIdx);\n const simpleFields: Record<string, string> = {};\n const dateFields: Record<string, IcsDateField> = {};\n for (const line of body.split(\"\\n\")) {\n const parsed = parseIcsLine(line);\n if (!parsed) continue;\n const { property, params, value } = parsed;\n if (property === \"DTSTART\" || property === \"DTEND\") {\n if (dateFields[property] === undefined) {\n dateFields[property] = { raw: value, params };\n }\n } else if (simpleFields[property] === undefined) {\n simpleFields[property] = value;\n }\n }\n const title = simpleFields.SUMMARY;\n const dtstart = dateFields.DTSTART;\n if (!title || !dtstart) continue;\n const dtend = dateFields.DTEND;\n events.push({\n id: simpleFields.UID ?? cryptoRandomId(),\n title,\n start: normalizeIcsDate(dtstart.raw, dtstart.params),\n end: dtend ? normalizeIcsDate(dtend.raw, dtend.params) : undefined,\n location: simpleFields.LOCATION,\n notes: simpleFields.DESCRIPTION,\n });\n }\n return events;\n}\n\n/**\n * Normalise an ICS date/datetime value (optionally with a `TZID` parameter)\n * into an ISO 8601 string that downstream code can compare unambiguously.\n *\n * Behaviour:\n * - `20260411T150000Z` → `2026-04-11T15:00:00Z`\n * - `20260411` → `2026-04-11T00:00:00Z` (date-only events are day-boundaries)\n * - `20260411T150000` (floating, no Z, no TZID) → `2026-04-11T15:00:00` (floating)\n * - `20260411T233000` with `TZID=America/New_York` → `2026-04-12T03:30:00Z`\n * (applies the zone offset at that wallclock time; DST-aware via Intl)\n * - Unknown TZID falls back to UTC with a logged warning (conservative:\n * the event still appears, but on the UTC date).\n */\nfunction normalizeIcsDate(value: string, params: Record<string, string> = {}): string {\n // Date-time with explicit Z suffix (UTC).\n if (/^\\d{8}T\\d{6}Z$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n return `${y}-${m}-${d}T${hh}:${mm}:${ss}Z`;\n }\n // Date-time without Z: may be floating or zoned via TZID.\n if (/^\\d{8}T\\d{6}$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n const local = `${y}-${m}-${d}T${hh}:${mm}:${ss}`;\n const tzid = params.TZID;\n if (tzid) {\n const utcIso = icsWallclockToUtc(local, tzid);\n if (utcIso) return utcIso;\n log.warn(\n `briefing: unsupported TZID \"${tzid}\" — treating as UTC for ${local}`,\n );\n return `${local}Z`;\n }\n // No TZID → floating. Downstream compares the date slice directly.\n return local;\n }\n // Date-only (all-day event). Date-only values carry no TZID per RFC 5545.\n if (/^\\d{8}$/.test(value)) {\n return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T00:00:00Z`;\n }\n return value;\n}\n\n/**\n * Convert a wallclock local datetime in a named IANA timezone to a UTC ISO\n * string. Returns null if the timezone is unsupported by the runtime.\n *\n * Implementation note: this is the standard \"invert the formatter\" technique.\n * We treat the local wallclock as though it were UTC, ask the runtime what\n * time that instant shows in the target zone, and the delta is the zone's\n * offset at that wallclock moment (DST-aware).\n */\nfunction icsWallclockToUtc(local: string, tzid: string): string | null {\n const match = local.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!match) return null;\n const [, y, mo, d, hh, mm, ss] = match;\n // Treat the wallclock as UTC for the first probe.\n const naiveUtcMs = Date.UTC(\n Number(y),\n Number(mo) - 1,\n Number(d),\n Number(hh),\n Number(mm),\n Number(ss),\n );\n if (!Number.isFinite(naiveUtcMs)) return null;\n\n let formatter: Intl.DateTimeFormat;\n try {\n formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tzid,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n } catch {\n return null;\n }\n\n const zonedMs = zonedFormatToMs(formatter, new Date(naiveUtcMs));\n if (zonedMs === null) return null;\n // Offset = naiveUtc − zonedAtNaiveUtc (positive for zones east of UTC).\n const offsetMs = naiveUtcMs - zonedMs;\n // Apply the offset once to land on the real UTC instant.\n const realUtcMs = naiveUtcMs + offsetMs;\n // Second pass: offsets can differ when the wallclock crosses a DST boundary.\n const zonedMs2 = zonedFormatToMs(formatter, new Date(realUtcMs));\n if (zonedMs2 !== null) {\n const offsetMs2 = realUtcMs - zonedMs2;\n if (offsetMs2 !== offsetMs) {\n return new Date(naiveUtcMs + offsetMs2).toISOString();\n }\n }\n return new Date(realUtcMs).toISOString();\n}\n\n/**\n * Format a Date in the given timezone and return the absolute ms timestamp\n * of that wallclock time interpreted as if it were UTC. Used only by\n * `icsWallclockToUtc` to compute zone offsets.\n */\nfunction zonedFormatToMs(formatter: Intl.DateTimeFormat, date: Date): number | null {\n const parts = formatter.formatToParts(date);\n const get = (type: string): string | undefined =>\n parts.find((p) => p.type === type)?.value;\n const y = get(\"year\");\n const mo = get(\"month\");\n const d = get(\"day\");\n const hh = get(\"hour\");\n const mm = get(\"minute\");\n const ss = get(\"second\");\n if (!y || !mo || !d || !hh || !mm || !ss) return null;\n // RFC 5545 / Intl edge-case: some runtimes return `hour: \"24\"` for midnight\n // while keeping the same calendar day (instead of returning hour=0 with the\n // next day). Passing 24 straight to Date.UTC would roll the date forward by\n // one day, producing a 24-hour-skewed offset in icsWallclockToUtc and\n // shifting TZID midnight events to the wrong briefing day. Normalise to 0\n // and leave the date component unchanged.\n const normalizedHour = Number(hh) === 24 ? 0 : Number(hh);\n const ms = Date.UTC(Number(y), Number(mo) - 1, Number(d), normalizedHour, Number(mm), Number(ss));\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Returns true when `isoStr` has an explicit UTC or numeric offset suffix\n * (Z, ±HH:MM, or ±HHMM). Floating datetimes produced by `normalizeIcsDate`\n * have no such suffix.\n */\nfunction isoHasTimezone(isoStr: string): boolean {\n return /(Z|[+-]\\d{2}:?\\d{2})$/.test(isoStr);\n}\n\n/**\n * Parse an ISO datetime string (UTC-aware or floating) to milliseconds since\n * epoch, or `null` if the string is not a valid datetime.\n *\n * - UTC / offset-aware strings are passed directly to `new Date()`.\n * - Floating strings (no timezone suffix) are interpreted as UTC so that\n * interval arithmetic uses the same epoch base as UTC-aware strings.\n * The caller is responsible for using the correct date-boundary constants.\n */\nfunction isoToMs(isoStr: string): number | null {\n if (!isoStr) return null;\n let src = isoStr;\n if (!isoHasTimezone(src)) {\n // Treat floating time as UTC for interval math (append Z).\n src = src + \"Z\";\n }\n const ms = new Date(src).getTime();\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** @internal — exported for testing only. */\nexport function eventFallsOnDate(event: CalendarEvent, dateIso: string): boolean {\n const target = dateIso.slice(0, 10);\n const start = event.start;\n\n // Floating ICS datetime (no Z, no offset): `normalizeIcsDate` produces\n // \"YYYY-MM-DDTHH:MM:SS\" with no timezone. Passing this to `new Date()`\n // causes ECMAScript to parse it as local time, which then round-trips\n // through UTC via `toISOString()` and can shift the calendar date.\n // For floating times we compare date portions directly (no epoch arithmetic).\n const startIsFloating = !isoHasTimezone(start);\n\n if (startIsFloating) {\n // Validate the start timestamp with the same rigour applied to end:\n // 1. Shape check — must match the ISO-8601 date or datetime pattern.\n // 2. Real-date check — round-trip through UTC to reject impossible dates\n // like \"2026-02-30\" that JavaScript silently auto-corrects.\n // 3. Time-component check — reject out-of-range hours/minutes/seconds\n // (e.g. \"2026-04-11T25:99:00\") that JavaScript rolls over to a\n // different day, which would cause the event to be matched against\n // unrelated calendar dates.\n // If start fails any check we skip the event entirely — there is no usable\n // start date to fall back on.\n const startShapeOk =\n typeof start === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(start);\n if (!startShapeOk) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n const startDateStr = start.slice(0, 10);\n const startDateProbe = new Date(startDateStr + \"T00:00:00Z\");\n if (\n Number.isNaN(startDateProbe.getTime()) ||\n startDateProbe.toISOString().slice(0, 10) !== startDateStr\n ) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with impossible start date ${JSON.stringify(startDateStr)}`,\n );\n return false;\n }\n const startRawTime = start.indexOf(\"T\") !== -1 ? start.slice(start.indexOf(\"T\") + 1) : \"\";\n if (startRawTime !== \"\") {\n const startTimeParts = startRawTime.split(\":\").map(Number);\n const shh = startTimeParts[0] ?? 0;\n const smm = startTimeParts[1] ?? 0;\n const sss = Math.floor(startTimeParts[2] ?? 0);\n if (shh > 23 || smm > 59 || sss > 59) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with out-of-range start time ${JSON.stringify(startRawTime)}`,\n );\n return false;\n }\n }\n\n const startDate = startDateStr;\n const end = event.end;\n\n // Point event (no end) — simple date prefix comparison.\n if (!end) return startDate === target;\n\n // Validate that end is a recognisable ISO-8601 date/datetime string before\n // slicing it for lexicographic comparison. A malformed end (e.g. a JSON\n // feed emitting \"end\": \"invalid\") would otherwise produce a non-date prefix\n // from `end.slice(0, 10)` and cause the event to appear on unrelated days.\n // Fallback: treat the event as a single-day event starting on startDate.\n const endIsValid =\n typeof end === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(end);\n if (!endIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has malformed end timestamp ${JSON.stringify(end)}; treating as single-day event at ${startDate}`,\n );\n // Render the event but only on its start date.\n return startDate === target;\n }\n\n // UhLh: Reject impossible calendar dates that pass the regex (e.g. \"2026-99-99\").\n // The regex only validates the *shape* of the string — it accepts month 99 and\n // day 99. We must additionally verify the date is real by constructing a UTC\n // Date and checking that the ISO round-trip matches the input prefix. If the\n // date is impossible, Date will auto-correct it (e.g. \"2026-01-99\" becomes some\n // later date), so the round-trip will differ. Fall back to single-day semantics.\n const endDate = end.slice(0, 10);\n const endDateProbe = new Date(endDate + \"T00:00:00Z\");\n if (\n Number.isNaN(endDateProbe.getTime()) ||\n endDateProbe.toISOString().slice(0, 10) !== endDate\n ) {\n log.warn(\n `briefing: event \"${event.title}\" has impossible end date ${JSON.stringify(endDate)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n\n // Validate the time components of the end timestamp when present.\n // The regex above only checks the shape (e.g. two digits for hour) but does\n // not enforce numeric ranges. A value like \"2026-04-11T25:99:99\" passes the\n // regex and the date-round-trip check above yet carries an impossible time.\n // JavaScript's Date constructor silently rolls such values over to a later\n // date, which would make the event bleed into unrelated days. Extract the\n // individual time fields and reject anything outside the valid range.\n const rawTime = end.indexOf(\"T\") !== -1 ? end.slice(end.indexOf(\"T\") + 1) : \"\";\n if (rawTime !== \"\") {\n const timeParts = rawTime.split(\":\").map(Number);\n const hh = timeParts[0] ?? 0;\n const mm = timeParts[1] ?? 0;\n // Seconds may carry a fractional component; floor to get the integer part.\n const ss = Math.floor(timeParts[2] ?? 0);\n const timeIsValid = hh <= 23 && mm <= 59 && ss <= 59;\n if (!timeIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has out-of-range end time ${JSON.stringify(rawTime)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n }\n\n // Span event: include if [start, end) overlaps the target calendar day.\n //\n // We can't use pure YYYY-MM-DD lexicographic comparison because a\n // same-day event (`start=2026-04-11T14:30`, `end=2026-04-11T15:00`)\n // has `startDate === endDate === \"2026-04-11\"`, and a `target < endDate`\n // check would wrongly exclude it. A cross-day event ending at\n // `2026-04-12T00:00:00` (exact midnight) also needs the end day to be\n // treated as exclusive per half-open `[start, end)` semantics.\n //\n // Decide whether the end day is still active on the end date by looking\n // at the time portion: if the end time is strictly after midnight, the\n // event is still running at the start of the end day and should include\n // it; if the end time is exactly midnight, the event ends precisely at\n // the boundary and the end day is excluded. Within-day spans always\n // have a non-zero end time and so correctly include their own date.\n //\n // UhLg: A date-only end value (no \"T\" separator) produces an empty\n // endTime string. The regex above does not match empty string, so\n // endAtExactMidnight would be false and the event would incorrectly\n // appear on the end date. Date-only end values carry [start, end)\n // semantics (the end date is exclusive), so we treat them as midnight.\n const endTime = end.slice(11); // \"HH:MM\", \"HH:MM:SS\", \"HH:MM:SS.mmm\", or \"\" (date-only)\n // Treat any end time that is exactly midnight — or absent (date-only) — as\n // day-exclusive per [start, end) semantics.\n // Cases covered:\n // \"\" — date-only end (UhLg fix: exclusive like midnight)\n // \"00:00\" — HH:MM form (valid floating-time ISO value, no seconds)\n // \"00:00:00\" — HH:MM:SS form\n // \"00:00:00.000...\" — with fractional seconds (any number of trailing zeros)\n // A bare `>` string comparison incorrectly treats \"00:00:00.000\" as > \"00:00:00\"\n // because the fractional suffix makes the string lexicographically longer.\n const endIsDateOnly = endTime === \"\";\n const endAtExactMidnight = endIsDateOnly || /^00(:00){1,2}(\\.0+)?$/.test(endTime);\n const endActiveOnEndDay = !endAtExactMidnight;\n if (endActiveOnEndDay) {\n return startDate <= target && target <= endDate;\n }\n return startDate <= target && target < endDate;\n }\n\n // UTC or offset-aware ISO string: parse and normalise to UTC milliseconds,\n // then check whether the event's [start, end) interval overlaps the target\n // UTC day [dayStart, dayEnd).\n const startMs = isoToMs(start);\n if (startMs === null) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n\n // Boundaries of the target UTC day (half-open: [dayStart, dayEnd)).\n const dayStart = Date.UTC(\n Number(target.slice(0, 4)),\n Number(target.slice(5, 7)) - 1,\n Number(target.slice(8, 10)),\n );\n const dayEnd = dayStart + 86_400_000; // +24 h\n\n const end = event.end;\n if (!end) {\n // Point event: included iff start falls within [dayStart, dayEnd).\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n const endMs = isoToMs(end);\n if (endMs === null) {\n // Unparseable end — fall back to point-event semantics.\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n // Interval event: overlaps day iff start < dayEnd AND end > dayStart.\n // Using strict > for end so that an event ending exactly at midnight\n // (dayEnd of previous day) is NOT counted on the next day.\n return startMs < dayEnd && endMs > dayStart;\n}\n\nfunction cryptoRandomId(): string {\n // Keep dependency-free: Math.random is fine for synthetic fixture IDs.\n return `evt-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// buildBriefing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Dependency-injection hook for LLM follow-up generation (used in tests). */\nexport type BriefingFollowupGenerator = (\n prompt: {\n sections: BriefingSections;\n windowLabel: string;\n maxFollowups: number;\n },\n) => Promise<BriefingFollowup[]>;\n\n/** Options accepted by `buildBriefing`. */\nexport interface BuildBriefingOptions {\n /** Workspace-scoped storage. Tests pass a temp dir. */\n storage: StorageManager;\n /** Parsed window. If omitted, a default 1-day window is used. */\n window?: ParsedBriefingWindow;\n /** Optional focus filter. */\n focus?: BriefingFocus | null;\n /** Optional namespace hint for logging. */\n namespace?: string;\n /** Calendar source. Section omitted entirely when undefined. */\n calendarSource?: CalendarSource;\n /** Maximum LLM follow-ups (0 to disable the section). */\n maxFollowups?: number;\n /** Whether the module is allowed to invoke the Responses API. */\n allowLlm?: boolean;\n /** OpenAI API key. If absent the follow-up section is gracefully omitted. */\n openaiApiKey?: string;\n /** OpenAI-compatible base URL (for Azure or proxied endpoints). */\n openaiBaseUrl?: string;\n /** Model id for the Responses call. */\n model?: string;\n /** Injected follow-up generator. Overrides real LLM call (tests). */\n followupGenerator?: BriefingFollowupGenerator;\n /** Injected \"now\" — makes tests deterministic. */\n now?: Date;\n}\n\nconst MAX_ACTIVE_THREADS = 8;\nconst MAX_RECENT_ENTITIES = 8;\nconst MAX_OPEN_COMMITMENTS = 8;\n\n/**\n * Build the daily context briefing.\n *\n * Never throws on LLM failures — the suggested follow-ups section is simply\n * omitted and `followupsUnavailableReason` is set.\n */\nexport async function buildBriefing(options: BuildBriefingOptions): Promise<BriefingResult> {\n const now = options.now ?? new Date();\n const window = options.window ?? defaultWindow(now);\n const maxFollowups = clampFollowups(options.maxFollowups);\n const focus = options.focus ?? null;\n\n const [allMemories, allEntities] = await Promise.all([\n safeReadMemories(options.storage),\n safeReadEntities(options.storage),\n ]);\n\n const memoriesInWindow = filterMemoriesByWindow(allMemories, window);\n const focusedMemories = focus\n ? memoriesInWindow.filter((m) => focusMatchesMemory(m, focus))\n : memoriesInWindow;\n\n const activeThreads = buildActiveThreads(focusedMemories);\n const recentEntities = buildRecentEntities(allEntities, window, focus);\n // TODO(#370): openCommitments only covers memories inside the lookback window.\n // Still-open commitments (pending tag, commitment category) that pre-date the\n // window are silently omitted. A separate query over allMemories filtered to\n // open-status entries would surface these. Deferred to avoid scope creep here.\n const openCommitments = buildOpenCommitments(focusedMemories);\n\n const calendarLoadResult = options.calendarSource\n ? await loadTodayCalendar(options.calendarSource, now)\n : undefined;\n\n const calendarSourceErrors: BriefingCalendarSourceError[] =\n calendarLoadResult?.error ? [calendarLoadResult.error] : [];\n\n const sectionsBase: BriefingSections = {\n activeThreads,\n recentEntities,\n openCommitments,\n suggestedFollowups: [],\n todayCalendar: calendarLoadResult?.events,\n };\n\n let followups: BriefingFollowup[] = [];\n let followupsUnavailableReason: string | undefined;\n\n if (maxFollowups === 0 || options.allowLlm === false) {\n followupsUnavailableReason = \"LLM follow-ups disabled by configuration\";\n } else if (!options.openaiApiKey && !options.followupGenerator) {\n followupsUnavailableReason = \"OPENAI_API_KEY not configured\";\n } else {\n try {\n const generator = options.followupGenerator ?? buildOpenAiFollowupGenerator({\n apiKey: options.openaiApiKey!,\n model: options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL,\n baseURL: options.openaiBaseUrl,\n });\n const generated = await generator({\n sections: sectionsBase,\n windowLabel: window.label,\n maxFollowups,\n });\n followups = generated.slice(0, maxFollowups);\n } catch (err) {\n const errMsg = stringifyError(err);\n const modelName = options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL;\n // Detect \"model not found / invalid\" errors from the Responses API and\n // produce a user-friendly message that surfaces the problematic identifier.\n if (\n /model/i.test(errMsg) &&\n (/not found/i.test(errMsg) || /does not exist/i.test(errMsg) || /invalid/i.test(errMsg))\n ) {\n followupsUnavailableReason =\n `configured follow-up model '${modelName}' is not available in the Responses API`;\n } else {\n followupsUnavailableReason = `LLM follow-ups failed: ${errMsg}`;\n }\n log.warn(`briefing: ${followupsUnavailableReason}`);\n }\n }\n\n const sections: BriefingSections = {\n ...sectionsBase,\n suggestedFollowups: followups,\n };\n\n const windowIso = { from: window.from.toISOString(), to: window.to.toISOString() };\n const markdown = renderBriefingMarkdown({\n sections,\n windowLabel: window.label,\n focus,\n followupsUnavailableReason,\n generatedAt: now,\n namespace: options.namespace,\n });\n\n const json: Record<string, unknown> = {\n generatedAt: now.toISOString(),\n window: windowIso,\n focus,\n namespace: options.namespace ?? null,\n sections,\n followupsUnavailableReason: followupsUnavailableReason ?? null,\n calendarSourceErrors: calendarSourceErrors.length > 0 ? calendarSourceErrors : null,\n };\n\n const result: BriefingResult = {\n markdown,\n json,\n sections,\n followupsUnavailableReason,\n window: windowIso,\n };\n\n if (calendarSourceErrors.length > 0) {\n result.calendarSourceErrors = calendarSourceErrors;\n }\n\n return result;\n}\n\nfunction clampFollowups(value: number | undefined): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 5;\n return Math.max(0, Math.min(10, Math.floor(value)));\n}\n\nfunction defaultWindow(now: Date): ParsedBriefingWindow {\n const parsed = parseBriefingWindow(\"yesterday\", now);\n if (parsed) return parsed;\n return { from: new Date(now.getTime() - DAY_MS), to: now, label: \"yesterday\" };\n}\n\nasync function safeReadMemories(storage: StorageManager): Promise<MemoryFile[]> {\n try {\n return await storage.readAllMemories();\n } catch (err) {\n log.warn(`briefing: readAllMemories failed: ${err}`);\n return [];\n }\n}\n\nasync function safeReadEntities(storage: StorageManager): Promise<EntityFile[]> {\n try {\n return await storage.readAllEntityFiles();\n } catch (err) {\n log.warn(`briefing: readAllEntityFiles failed: ${err}`);\n return [];\n }\n}\n\nfunction memoryTimestamp(memory: MemoryFile): number {\n const raw = memory.frontmatter.updated || memory.frontmatter.created;\n if (!raw) return 0;\n const t = Date.parse(raw);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** @internal — exported for testing only. */\nexport function filterMemoriesByWindow(memories: MemoryFile[], window: ParsedBriefingWindow): MemoryFile[] {\n const fromMs = window.from.getTime();\n const toMs = window.to.getTime();\n return memories.filter((m) => {\n // Exclude explicitly retired statuses so commitments overridden within the\n // window don't appear as open. In addition to `superseded` / `archived`\n // (temporal retirement), also exclude `rejected` and `quarantined`, which\n // come from governance/disposition workflows: those memories have been\n // explicitly marked unsafe or invalid and must NOT flow into active\n // threads, open commitments, or follow-up generation, even if they\n // fall within the briefing window. Surfacing them would reintroduce\n // quarantined content into downstream automation as actionable context.\n //\n // `pending_review` memories are awaiting human review — not invalidated —\n // and must be included so reviewers see them in the briefing.\n const status = m.frontmatter.status;\n if (\n status === \"superseded\" ||\n status === \"archived\" ||\n status === \"rejected\" ||\n status === \"quarantined\"\n ) {\n return false;\n }\n const ts = memoryTimestamp(m);\n return ts >= fromMs && ts < toMs;\n });\n}\n\n/** @internal — exported for testing only. */\nexport function buildActiveThreads(memories: MemoryFile[]): BriefingActiveThread[] {\n const buckets = new Map<string, BriefingActiveThread>();\n for (const memory of memories) {\n const threadKey = extractThreadKey(memory);\n const updatedAt = memory.frontmatter.updated || memory.frontmatter.created || \"\";\n const existing = buckets.get(threadKey);\n if (!existing || updatedAt > existing.updatedAt) {\n buckets.set(threadKey, {\n id: threadKey,\n title: summarizeContentTitle(memory),\n updatedAt,\n // Always derive reason from the newest memory so the description\n // reflects the most-recent activity type, not the first memory seen.\n reason: describeReason(memory),\n });\n }\n }\n return Array.from(buckets.values())\n .sort((a, b) => {\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n // Tiebreaker: lexicographic order by id ensures a deterministic, stable\n // result when multiple threads share the same updatedAt timestamp (e.g.\n // after a batch extraction run).\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n })\n .slice(0, MAX_ACTIVE_THREADS);\n}\n\nfunction extractThreadKey(memory: MemoryFile): string {\n const entityRef = memory.frontmatter.entityRef?.trim();\n if (entityRef) return `entity:${entityRef}`;\n const tags = memory.frontmatter.tags ?? [];\n const topicTag = tags.find((t) => t.startsWith(\"topic:\"));\n if (topicTag) return topicTag;\n if (tags.length > 0) return `tag:${tags[0]}`;\n return `memory:${memory.frontmatter.id}`;\n}\n\nfunction summarizeContentTitle(memory: MemoryFile): string {\n const firstLine = (memory.content || \"\").split(\"\\n\").find((line) => line.trim().length > 0) ?? \"\";\n const trimmed = firstLine.trim();\n if (trimmed.length === 0) return memory.frontmatter.id;\n return trimmed.length > 120 ? `${trimmed.slice(0, 117)}...` : trimmed;\n}\n\nfunction describeReason(memory: MemoryFile): string {\n const cat = memory.frontmatter.category;\n if (cat === \"commitment\") return \"open commitment\";\n if (cat === \"decision\") return \"recent decision\";\n if (cat === \"correction\") return \"recent correction\";\n return \"recent activity\";\n}\n\n/** @internal — exported for testing only. */\nexport function buildRecentEntities(\n entities: EntityFile[],\n window: ParsedBriefingWindow,\n focus: BriefingFocus | null,\n): BriefingRecentEntity[] {\n const fromMs = window.from.getTime();\n const scored: BriefingRecentEntity[] = [];\n const now = window.to;\n for (const entity of entities) {\n if (focus && !focusMatchesEntity(entity, focus)) continue;\n const toMs = window.to.getTime();\n const updatedMs = entity.updated ? Date.parse(entity.updated) : 0;\n if (!Number.isFinite(updatedMs) || updatedMs < fromMs || updatedMs >= toMs) continue;\n const score = StorageManager.scoreEntity(entity, now);\n scored.push({\n name: entity.name,\n type: entity.type,\n updatedAt: entity.updated,\n score: Number(score.toFixed(4)),\n summary: entity.synthesis || entity.summary,\n });\n }\n return scored\n .sort((a, b) => {\n const scoreDiff = b.score - a.score;\n if (scoreDiff !== 0) return scoreDiff;\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n return 0;\n })\n .slice(0, MAX_RECENT_ENTITIES);\n}\n\nfunction buildOpenCommitments(memories: MemoryFile[]): BriefingOpenCommitment[] {\n const commitments: BriefingOpenCommitment[] = [];\n\n for (const memory of memories) {\n const tags = memory.frontmatter.tags ?? [];\n const isPending = tags.some((t) => t.toLowerCase() === \"pending\");\n const isCommitment = memory.frontmatter.category === \"commitment\";\n const isUnresolvedQuestion = /(?:\\?$|\\bfollow[- ]up\\b|\\btodo\\b)/i.test(memory.content);\n\n if (isPending || isCommitment || isUnresolvedQuestion) {\n const kind: BriefingOpenCommitment[\"kind\"] = isCommitment\n ? \"commitment\"\n : isUnresolvedQuestion\n ? \"question\"\n : \"pending_memory\";\n commitments.push({\n id: memory.frontmatter.id,\n kind,\n text: summarizeContentTitle(memory),\n source: memory.frontmatter.source,\n createdAt: memory.frontmatter.created,\n });\n }\n }\n\n return commitments\n .sort((a, b) => {\n // Missing timestamps sort last (highest comparator value).\n if (!a.createdAt && !b.createdAt) return 0;\n if (!a.createdAt) return 1;\n if (!b.createdAt) return -1;\n if (a.createdAt > b.createdAt) return -1;\n if (a.createdAt < b.createdAt) return 1;\n return 0;\n })\n .slice(0, MAX_OPEN_COMMITMENTS);\n}\n\ninterface CalendarLoadResult {\n events: CalendarEvent[] | undefined;\n error: BriefingCalendarSourceError | undefined;\n}\n\nasync function loadTodayCalendar(\n source: CalendarSource,\n now: Date,\n): Promise<CalendarLoadResult> {\n const sourceLabel = (source as { filePath?: string }).filePath ?? \"calendar\";\n try {\n const dateIso = now.toISOString().slice(0, 10);\n const events = await source.eventsForDate(dateIso);\n // Return the events array (possibly empty for a legitimately empty calendar).\n // An empty array is distinct from `undefined`: empty means \"source responded\n // with no events today\"; undefined means \"source failed\".\n return { events, error: undefined };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(`briefing: calendar source error (${sourceLabel}): ${message}`);\n // Return undefined events (not []) to signal an error so callers can\n // distinguish \"no events today\" from \"the calendar source threw\".\n return {\n events: undefined,\n error: { source: sourceLabel, error: message },\n };\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Follow-ups (Responses API)\n// ──────────────────────────────────────────────────────────────────────────\n\nfunction buildOpenAiFollowupGenerator(cfg: {\n apiKey: string;\n model: string;\n baseURL?: string;\n}): BriefingFollowupGenerator {\n return async ({ sections, windowLabel, maxFollowups }) => {\n // Lazy import keeps the module dependency-free when LLM path is unused.\n const { OpenAI } = (await import(\"openai\")) as {\n OpenAI: new (opts: { apiKey: string; baseURL?: string }) => unknown;\n };\n const clientOpts: { apiKey: string; baseURL?: string } = { apiKey: cfg.apiKey };\n if (cfg.baseURL) clientOpts.baseURL = cfg.baseURL;\n const client = new OpenAI(clientOpts) as {\n responses: {\n create: (args: {\n model: string;\n instructions: string;\n input: string;\n max_output_tokens?: number;\n }) => Promise<{ output_text?: string }>;\n };\n };\n\n const prompt = buildFollowupPrompt(sections, windowLabel, maxFollowups);\n const response = await client.responses.create({\n model: cfg.model,\n instructions: FOLLOWUP_INSTRUCTIONS,\n input: prompt,\n max_output_tokens: 512,\n });\n\n const text = typeof response.output_text === \"string\" ? response.output_text : \"\";\n return parseFollowupResponse(text, maxFollowups);\n };\n}\n\nconst FOLLOWUP_INSTRUCTIONS = `You suggest short follow-up prompts for a daily context briefing.\nReturn strict JSON of the form { \"followups\": [{ \"text\": \"...\", \"rationale\": \"...\" }] }.\nRules:\n- Never invent facts absent from the input.\n- Keep each \"text\" under 140 characters.\n- Prefer concrete, action-oriented phrasing.\n- Omit duplicates. Avoid filler.`;\n\nfunction buildFollowupPrompt(\n sections: BriefingSections,\n windowLabel: string,\n maxFollowups: number,\n): string {\n const lines: string[] = [];\n lines.push(`Window: ${windowLabel}`);\n lines.push(`Desired follow-ups: ${maxFollowups}`);\n lines.push(\"\");\n lines.push(\"Active threads:\");\n for (const t of sections.activeThreads) lines.push(`- ${t.title} (${t.reason})`);\n lines.push(\"\");\n lines.push(\"Recent entities:\");\n for (const e of sections.recentEntities) lines.push(`- ${e.name} [${e.type}]`);\n lines.push(\"\");\n lines.push(\"Open commitments:\");\n for (const c of sections.openCommitments) lines.push(`- [${c.kind}] ${c.text}`);\n return lines.join(\"\\n\");\n}\n\nfunction parseFollowupResponse(raw: string, max: number): BriefingFollowup[] {\n // JSON.parse throws on invalid JSON — let the caller catch it so the outer\n // try/catch in buildBriefing can set followupsUnavailableReason rather than\n // silently returning an empty array that masks the parse failure.\n const parsed = JSON.parse(raw) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`LLM returned non-object JSON: ${typeof parsed}`);\n }\n const arr = (parsed as { followups?: unknown }).followups;\n if (!Array.isArray(arr)) {\n throw new Error(`LLM response missing \"followups\" array`);\n }\n const out: BriefingFollowup[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const text = (entry as Record<string, unknown>).text;\n if (typeof text !== \"string\" || text.trim().length === 0) continue;\n const rationale = (entry as Record<string, unknown>).rationale;\n out.push({\n text: text.trim(),\n rationale: typeof rationale === \"string\" ? rationale.trim() : undefined,\n });\n if (out.length >= max) break;\n }\n return out;\n}\n\nfunction stringifyError(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Markdown rendering\n// ──────────────────────────────────────────────────────────────────────────\n\ninterface RenderContext {\n sections: BriefingSections;\n windowLabel: string;\n focus: BriefingFocus | null;\n followupsUnavailableReason?: string;\n generatedAt: Date;\n namespace?: string;\n}\n\nexport function renderBriefingMarkdown(ctx: RenderContext): string {\n const lines: string[] = [];\n lines.push(`# Daily Context Briefing`);\n lines.push(\"\");\n lines.push(`_Generated ${ctx.generatedAt.toISOString()} (window: ${ctx.windowLabel})_`);\n if (ctx.focus) {\n lines.push(`_Focus: ${ctx.focus.type}:${ctx.focus.value}_`);\n }\n if (ctx.namespace) {\n lines.push(`_Namespace: ${ctx.namespace}_`);\n }\n lines.push(\"\");\n\n lines.push(`## Active threads`);\n if (ctx.sections.activeThreads.length === 0) {\n lines.push(`_No active threads in window._`);\n } else {\n for (const t of ctx.sections.activeThreads) {\n lines.push(`- **${t.title}** — ${t.reason} (updated ${t.updatedAt})`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Recent entities`);\n if (ctx.sections.recentEntities.length === 0) {\n lines.push(`_No entities updated in window._`);\n } else {\n for (const e of ctx.sections.recentEntities) {\n const summary = e.summary ? ` — ${e.summary}` : \"\";\n lines.push(`- **${e.name}** (${e.type}, score ${e.score})${summary}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Open commitments`);\n if (ctx.sections.openCommitments.length === 0) {\n lines.push(`_No open commitments detected._`);\n } else {\n for (const c of ctx.sections.openCommitments) {\n lines.push(`- [${c.kind}] ${c.text}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Suggested follow-ups`);\n if (ctx.followupsUnavailableReason) {\n lines.push(`_Unavailable: ${ctx.followupsUnavailableReason}_`);\n } else if (ctx.sections.suggestedFollowups.length === 0) {\n lines.push(`_No follow-ups suggested._`);\n } else {\n for (const f of ctx.sections.suggestedFollowups) {\n const rationale = f.rationale ? ` _(${f.rationale})_` : \"\";\n lines.push(`- ${f.text}${rationale}`);\n }\n }\n lines.push(\"\");\n\n if (ctx.sections.todayCalendar !== undefined) {\n lines.push(`## Today's calendar`);\n if (ctx.sections.todayCalendar.length === 0) {\n lines.push(`_No events on the calendar today._`);\n } else {\n for (const ev of ctx.sections.todayCalendar) {\n const end = ev.end ? ` → ${ev.end}` : \"\";\n const loc = ev.location ? ` @ ${ev.location}` : \"\";\n lines.push(`- **${ev.title}** (${ev.start}${end})${loc}`);\n }\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Save helpers\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Resolve the directory where `--save` writes dated briefings.\n * Respects the following precedence:\n * 1. explicit `configOverride` argument\n * 2. `$REMNIC_HOME/briefings/`\n * 3. `$HOME/.remnic/briefings/`\n */\nexport function resolveBriefingSaveDir(\n configOverride: string | null | undefined,\n env?: NodeJS.ProcessEnv,\n): string {\n if (typeof configOverride === \"string\" && configOverride.trim().length > 0) {\n return path.resolve(configOverride.trim());\n }\n const remnicHome = (env === undefined ? readEnvVar(\"REMNIC_HOME\") : env.REMNIC_HOME)?.trim();\n if (remnicHome && remnicHome.length > 0) {\n return path.join(remnicHome, \"briefings\");\n }\n const home = env === undefined\n ? resolveHomeDir()\n : env.HOME ?? env.USERPROFILE ?? os.homedir();\n return path.join(home, \".remnic\", \"briefings\");\n}\n\n/** Format the dated filename for a given briefing. */\nexport function briefingFilename(date: Date, format: \"markdown\" | \"json\" = \"markdown\"): string {\n const day = date.toISOString().slice(0, 10);\n return format === \"json\" ? `${day}.json` : `${day}.md`;\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AACf,OAAO,UAAU;AAwBV,IAAM,0BAA0B,CAAC,YAAY,MAAM;AAMnD,IAAM,kCAAkC;AASxC,SAAS,uBAAuB,OAA0C;AAC/E,MAAI,UAAU,OAAW,QAAO;AAChC,MAAK,wBAA8C,SAAS,KAAK,EAAG,QAAO;AAC3E,SAAO,4BAA4B,KAAK,gBAAgB,wBAAwB,KAAK,IAAI,CAAC;AAC5F;AAYA,IAAM,SAAS,KAAK,KAAK,KAAK;AAO9B,IAAM,gBAAgB,MAAM,MAAM;AAc3B,SAAS,oBACd,OACA,MAAY,oBAAI,KAAK,GACQ;AAC7B,QAAM,MAAM,OAAO,UAAU,WAAW,MAAM,KAAK,EAAE,YAAY,IAAI;AACrE,MAAI,IAAI,WAAW,EAAG,QAAO;AAE7B,MAAI,QAAQ,aAAa;AACvB,UAAM,eAAe,cAAc,GAAG;AACtC,UAAMA,QAAO,IAAI,KAAK,aAAa,QAAQ,IAAI,MAAM;AACrD,WAAO,EAAE,MAAAA,OAAM,IAAI,cAAc,OAAO,YAAY;AAAA,EACtD;AAEA,MAAI,QAAQ,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GAAG;AAC3C,YAAM,KAAK,oCAAoC;AAAA,IACjD,OAAO;AACL,iBAAW,MAAM,IAAI,SAAS,eAAe;AAC3C,cAAM,MAAM,GAAG,MAAM,WAAM,GAAG,GAAG,KAAK;AACtC,cAAM,MAAM,GAAG,WAAW,MAAM,GAAG,QAAQ,KAAK;AAChD,cAAM,KAAK,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK,GAAG,GAAG,IAAI,GAAG,EAAE;AAAA,MAC1D;AAAA,IACF;AACA,UAAM,KAAK,EAAE;AAAA,EACf;AAEA,SAAO,MAAM,KAAK,IAAI,EAAE,QAAQ,IAAI;AACtC;AAaO,SAAS,uBACd,gBACA,KACQ;AACR,MAAI,OAAO,mBAAmB,YAAY,eAAe,KAAK,EAAE,SAAS,GAAG;AAC1E,WAAO,KAAK,QAAQ,eAAe,KAAK,CAAC;AAAA,EAC3C;AACA,QAAM,cAAc,QAAQ,SAAY,WAAW,aAAa,IAAI,IAAI,cAAc,KAAK;AAC3F,MAAI,cAAc,WAAW,SAAS,GAAG;AACvC,WAAO,KAAK,KAAK,YAAY,WAAW;AAAA,EAC1C;AACA,QAAM,OAAO,QAAQ,SACjB,eAAe,IACf,IAAI,QAAQ,IAAI,eAAe,GAAG,QAAQ;AAC9C,SAAO,KAAK,KAAK,MAAM,WAAW,WAAW;AAC/C;AAGO,SAAS,iBAAiB,MAAY,SAA8B,YAAoB;AAC7F,QAAM,MAAM,KAAK,YAAY,EAAE,MAAM,GAAG,EAAE;AAC1C,SAAO,WAAW,SAAS,GAAG,GAAG,UAAU,GAAG,GAAG;AACnD;","names":["from","end"]}
@@ -0,0 +1,51 @@
1
+ // src/recall-audit.ts
2
+ import { appendFile, mkdir, readdir, rm } from "fs/promises";
3
+ import path from "path";
4
+ function formatIsoDate(ts) {
5
+ const normalized = new Date(ts);
6
+ if (Number.isNaN(normalized.getTime())) {
7
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8
+ }
9
+ return normalized.toISOString().slice(0, 10);
10
+ }
11
+ function buildRecallAuditPath(rootDir, ts, sessionKey) {
12
+ const safeSessionKey = encodeURIComponent(sessionKey);
13
+ return path.join(rootDir, "transcripts", formatIsoDate(ts), `${safeSessionKey}.jsonl`);
14
+ }
15
+ async function appendRecallAuditEntry(rootDir, entry) {
16
+ const filePath = buildRecallAuditPath(rootDir, entry.ts, entry.sessionKey);
17
+ await mkdir(path.dirname(filePath), { recursive: true });
18
+ await appendFile(filePath, `${JSON.stringify(entry)}
19
+ `, "utf8");
20
+ return filePath;
21
+ }
22
+ async function pruneRecallAuditEntries(rootDir, retentionDays, now = /* @__PURE__ */ new Date()) {
23
+ const transcriptsDir = path.join(rootDir, "transcripts");
24
+ const removed = [];
25
+ const cutoff = new Date(now);
26
+ cutoff.setUTCHours(0, 0, 0, 0);
27
+ cutoff.setUTCDate(cutoff.getUTCDate() - Math.max(1, Math.floor(retentionDays)));
28
+ let entries;
29
+ try {
30
+ entries = await readdir(transcriptsDir, { withFileTypes: true });
31
+ } catch {
32
+ return removed;
33
+ }
34
+ for (const entry of entries) {
35
+ if (!entry.isDirectory()) continue;
36
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.name)) continue;
37
+ const day = /* @__PURE__ */ new Date(`${entry.name}T00:00:00.000Z`);
38
+ if (Number.isNaN(day.getTime()) || day >= cutoff) continue;
39
+ const dirPath = path.join(transcriptsDir, entry.name);
40
+ await rm(dirPath, { recursive: true, force: true });
41
+ removed.push(dirPath);
42
+ }
43
+ return removed;
44
+ }
45
+
46
+ export {
47
+ buildRecallAuditPath,
48
+ appendRecallAuditEntry,
49
+ pruneRecallAuditEntries
50
+ };
51
+ //# sourceMappingURL=chunk-LBLXEFWK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/recall-audit.ts"],"sourcesContent":["import type { Dirent } from \"node:fs\";\nimport { appendFile, mkdir, readdir, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport interface RecallAuditEntry {\n ts: string;\n sessionKey: string;\n agentId: string;\n trigger: string;\n queryText: string;\n candidateMemoryIds: string[];\n summary: string | null;\n injectedChars: number;\n toggleState: \"enabled\" | \"disabled-primary\" | \"disabled-secondary\";\n latencyMs?: number;\n plannerMode?: string;\n requestedMode?: string;\n fallbackUsed?: boolean;\n}\n\nfunction formatIsoDate(ts: string): string {\n const normalized = new Date(ts);\n if (Number.isNaN(normalized.getTime())) {\n return new Date().toISOString().slice(0, 10);\n }\n return normalized.toISOString().slice(0, 10);\n}\n\nexport function buildRecallAuditPath(rootDir: string, ts: string, sessionKey: string): string {\n const safeSessionKey = encodeURIComponent(sessionKey);\n return path.join(rootDir, \"transcripts\", formatIsoDate(ts), `${safeSessionKey}.jsonl`);\n}\n\nexport async function appendRecallAuditEntry(\n rootDir: string,\n entry: RecallAuditEntry,\n): Promise<string> {\n const filePath = buildRecallAuditPath(rootDir, entry.ts, entry.sessionKey);\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(filePath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n return filePath;\n}\n\nexport async function pruneRecallAuditEntries(\n rootDir: string,\n retentionDays: number,\n now: Date = new Date(),\n): Promise<string[]> {\n const transcriptsDir = path.join(rootDir, \"transcripts\");\n const removed: string[] = [];\n const cutoff = new Date(now);\n cutoff.setUTCHours(0, 0, 0, 0);\n cutoff.setUTCDate(cutoff.getUTCDate() - Math.max(1, Math.floor(retentionDays)));\n let entries: Dirent[];\n try {\n entries = await readdir(transcriptsDir, { withFileTypes: true });\n } catch {\n return removed;\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(entry.name)) continue;\n const day = new Date(`${entry.name}T00:00:00.000Z`);\n if (Number.isNaN(day.getTime()) || day >= cutoff) continue;\n const dirPath = path.join(transcriptsDir, entry.name);\n await rm(dirPath, { recursive: true, force: true });\n removed.push(dirPath);\n }\n\n return removed;\n}\n"],"mappings":";AACA,SAAS,YAAY,OAAO,SAAS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