@remnic/core 9.63.5 → 9.63.7

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 (262) hide show
  1. package/dist/access-admin-ops-surface.d.ts +1 -1
  2. package/dist/access-admin-ops-surface.js +27 -25
  3. package/dist/access-authorization-probe.d.ts +1 -1
  4. package/dist/access-authorization-probe.js +28 -26
  5. package/dist/access-boundary.d.ts +1 -1
  6. package/dist/access-boundary.js +27 -25
  7. package/dist/access-cli.js +83 -81
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-extraction-force-flush.d.ts +1 -1
  10. package/dist/access-extraction-force-flush.js +27 -25
  11. package/dist/access-http-lcm-compaction.d.ts +1 -1
  12. package/dist/access-http-lifecycle-flush.d.ts +1 -1
  13. package/dist/access-http-offline-stream.d.ts +1 -1
  14. package/dist/access-http-query.js +29 -27
  15. package/dist/access-http.d.ts +2 -2
  16. package/dist/access-http.js +43 -41
  17. package/dist/access-identity-continuity-surface.js +27 -25
  18. package/dist/access-lcm-surface.d.ts +1 -1
  19. package/dist/access-lcm-surface.js +27 -25
  20. package/dist/access-mcp.d.ts +1 -1
  21. package/dist/access-mcp.js +34 -32
  22. package/dist/access-namespace-preflight.js +27 -25
  23. package/dist/access-observe-write-surface.d.ts +1 -1
  24. package/dist/access-observe-write-surface.js +27 -25
  25. package/dist/access-offline-manifest.js +6 -5
  26. package/dist/access-operations-batch.js +29 -27
  27. package/dist/access-operations.d.ts +4 -4
  28. package/dist/access-operations.js +33 -31
  29. package/dist/access-recall-concurrency.d.ts +1 -1
  30. package/dist/access-recall-concurrency.js +27 -25
  31. package/dist/access-recall-response.d.ts +1 -1
  32. package/dist/access-recall-response.js +27 -25
  33. package/dist/access-recall-surface.d.ts +1 -1
  34. package/dist/access-recall-surface.js +27 -25
  35. package/dist/access-schema.d.ts +88 -88
  36. package/dist/access-schema.js +6 -5
  37. package/dist/access-service-helpers.d.ts +1 -1
  38. package/dist/access-service.d.ts +1 -1
  39. package/dist/access-service.js +27 -25
  40. package/dist/access-surface-catalog.d.ts +1 -1
  41. package/dist/access-surface-catalog.js +29 -27
  42. package/dist/access-surface-catalog.js.map +1 -1
  43. package/dist/active-recall.js +5 -3
  44. package/dist/active-recall.js.map +1 -1
  45. package/dist/adapters/index.js +4 -4
  46. package/dist/adapters/registry.js +2 -2
  47. package/dist/{auto-sync-BKRJDMKX.js → auto-sync-3SHMZVQS.js} +5 -3
  48. package/dist/{auto-sync-BKRJDMKX.js.map → auto-sync-3SHMZVQS.js.map} +1 -1
  49. package/dist/briefing.js +10 -10
  50. package/dist/calibration.d.ts +2 -1
  51. package/dist/calibration.js +7 -0
  52. package/dist/calibration.js.map +1 -1
  53. package/dist/causal-consolidation.js +11 -11
  54. package/dist/census-validation.d.ts +19 -0
  55. package/dist/census-validation.js +14 -0
  56. package/dist/census-validation.js.map +1 -0
  57. package/dist/{chunk-LEPOP46W.js → chunk-227UFSEQ.js} +4 -4
  58. package/dist/{chunk-Z4N7SVVF.js → chunk-2L7DKNVE.js} +12 -7
  59. package/dist/chunk-2L7DKNVE.js.map +1 -0
  60. package/dist/{chunk-3Z5TGRFA.js → chunk-3NZAVWU5.js} +9 -9
  61. package/dist/{chunk-I5FLIB2J.js → chunk-3S3PNR5H.js} +2 -2
  62. package/dist/{chunk-R6UMNP5C.js → chunk-3T6HIIKA.js} +2 -2
  63. package/dist/{chunk-77QZW2D6.js → chunk-3TDAA7VA.js} +2 -2
  64. package/dist/{chunk-TWTUGCTY.js → chunk-3YTTAGPB.js} +6 -1
  65. package/dist/chunk-3YTTAGPB.js.map +1 -0
  66. package/dist/{chunk-DXDAQZ2K.js → chunk-42TIIO2M.js} +2 -2
  67. package/dist/{chunk-Y7COCXY2.js → chunk-4F67JJPG.js} +2 -2
  68. package/dist/{chunk-PB4WVYGC.js → chunk-5S5DUJFJ.js} +2 -2
  69. package/dist/{chunk-KYTRF64R.js → chunk-5SCFDQEJ.js} +2 -2
  70. package/dist/{chunk-GG4DN63W.js → chunk-62Y5AGCM.js} +2 -2
  71. package/dist/{chunk-KHCUVYCY.js → chunk-6UKSOXAO.js} +3 -3
  72. package/dist/{chunk-F6JYBVL6.js → chunk-7ZAC2C2U.js} +24 -24
  73. package/dist/{chunk-GF7RQWXC.js → chunk-AJRJDXYR.js} +2 -2
  74. package/dist/{chunk-YEQCMA5L.js → chunk-BOSIHHOH.js} +2 -2
  75. package/dist/{chunk-7LF2OHIJ.js → chunk-BRHKW7GY.js} +2 -2
  76. package/dist/{chunk-LX4TNSAE.js → chunk-CBY54QYW.js} +4 -4
  77. package/dist/chunk-FEHIOYML.js +168 -0
  78. package/dist/chunk-FEHIOYML.js.map +1 -0
  79. package/dist/{chunk-6YMEU6OQ.js → chunk-G72IPMR7.js} +2 -2
  80. package/dist/{chunk-7AF243WZ.js → chunk-GBVRVYF4.js} +1 -1
  81. package/dist/{chunk-GTD4Q62X.js → chunk-H4GQ2Y24.js} +3 -3
  82. package/dist/{chunk-QI5RDDEL.js → chunk-HXZNTZ3Y.js} +6 -6
  83. package/dist/{chunk-CIAI24TQ.js → chunk-IBZQQOM5.js} +3 -3
  84. package/dist/{chunk-RYST72N5.js → chunk-IINVXO3U.js} +4 -154
  85. package/dist/chunk-IINVXO3U.js.map +1 -0
  86. package/dist/{chunk-R7TZ2HCS.js → chunk-JG22O53B.js} +58 -3
  87. package/dist/chunk-JG22O53B.js.map +1 -0
  88. package/dist/{chunk-VPHSMJ2E.js → chunk-JPWSYHLB.js} +2 -2
  89. package/dist/{chunk-X7LEDA74.js → chunk-KFB4YNXM.js} +2 -2
  90. package/dist/{chunk-IPLYGWQF.js → chunk-KQAFEZQX.js} +5 -5
  91. package/dist/chunk-LQWOFU6L.js +17 -0
  92. package/dist/chunk-LQWOFU6L.js.map +1 -0
  93. package/dist/{chunk-ZUPKNWRZ.js → chunk-MIUL6AUZ.js} +3 -3
  94. package/dist/{chunk-EJY3HJMT.js → chunk-MYI3RKI6.js} +2 -2
  95. package/dist/{chunk-NA56NSKL.js → chunk-OOJCXJBN.js} +2 -2
  96. package/dist/{chunk-7KQB4EBS.js → chunk-OPPBTPUU.js} +4 -4
  97. package/dist/{chunk-ERPBRXVZ.js → chunk-PZKWPXRF.js} +2 -2
  98. package/dist/{chunk-FHKXVTM5.js → chunk-Q5XKKDFQ.js} +16 -16
  99. package/dist/{chunk-QRWMS6SI.js → chunk-Q6OL23WM.js} +2 -2
  100. package/dist/{chunk-OW7NVMGQ.js → chunk-QIZOU3FN.js} +2 -2
  101. package/dist/{chunk-V3KIRICY.js → chunk-QQYHYW2N.js} +3 -3
  102. package/dist/{chunk-YFCEBB5P.js → chunk-QTXNS3HB.js} +2 -2
  103. package/dist/{chunk-2QSZNTDO.js → chunk-RKNJBZ55.js} +4 -4
  104. package/dist/{chunk-E4KMY4KR.js → chunk-SNEUAZ6B.js} +2 -2
  105. package/dist/{chunk-TSTI6A3A.js → chunk-SYJW273H.js} +11 -11
  106. package/dist/{chunk-EFKZT6AY.js → chunk-T42L3S6A.js} +6 -11
  107. package/dist/chunk-T42L3S6A.js.map +1 -0
  108. package/dist/{chunk-YXMHUBN2.js → chunk-TOP3FSDW.js} +25 -102
  109. package/dist/chunk-TOP3FSDW.js.map +1 -0
  110. package/dist/{chunk-PBRCYYO7.js → chunk-ULZFZL7K.js} +2 -2
  111. package/dist/{chunk-UGHCZS6K.js → chunk-VFZQXYN5.js} +2 -2
  112. package/dist/{chunk-IVXVLDNT.js → chunk-WKJTMXME.js} +37 -54
  113. package/dist/chunk-WKJTMXME.js.map +1 -0
  114. package/dist/{chunk-NKB43PGI.js → chunk-WZDTSBGQ.js} +2 -2
  115. package/dist/{chunk-2UM6WHME.js → chunk-XE2QCCT2.js} +2 -2
  116. package/dist/{chunk-FPEZ74F7.js → chunk-XNJQZLAP.js} +3 -3
  117. package/dist/{chunk-SYVGVK4S.js → chunk-XTMYB2HY.js} +2 -2
  118. package/dist/{chunk-OETHJBAL.js → chunk-XV6PUXJ5.js} +71 -71
  119. package/dist/{chunk-UCLMKNHA.js → chunk-YIMV2KYM.js} +2 -2
  120. package/dist/{chunk-DYZR3Z6D.js → chunk-YMQKPSB2.js} +4 -4
  121. package/dist/{chunk-AYVCKGA6.js → chunk-YTXNDEUS.js} +2 -2
  122. package/dist/{chunk-L3CHRBHE.js → chunk-ZRUEP4IK.js} +17 -11
  123. package/dist/chunk-ZRUEP4IK.js.map +1 -0
  124. package/dist/{cli-BFBDYV0D.d.ts → cli-BTNj5DzK.d.ts} +1 -1
  125. package/dist/cli.d.ts +2 -2
  126. package/dist/cli.js +59 -57
  127. package/dist/compounding/engine.js +10 -10
  128. package/dist/config.js +5 -3
  129. package/dist/connectors/codex-materialize-runner.js +10 -10
  130. package/dist/connectors/index.js +10 -10
  131. package/dist/consolidation-provenance-check.js +2 -2
  132. package/dist/convergence-refresh.js +12 -12
  133. package/dist/conversation-index/backend.js +2 -2
  134. package/dist/corpus-watermark.js +12 -12
  135. package/dist/entity-retrieval.js +10 -10
  136. package/dist/external-wiki-access.d.ts +1 -1
  137. package/dist/external-wiki-access.js +28 -26
  138. package/dist/external-wiki-mcp-tools.d.ts +1 -1
  139. package/dist/extraction-judge.d.ts +2 -1
  140. package/dist/extraction-judge.js +6 -1
  141. package/dist/extraction-normalization.js +2 -2
  142. package/dist/extraction-prompt.d.ts +20 -1
  143. package/dist/extraction-prompt.js +11 -1
  144. package/dist/extraction.js +13 -13
  145. package/dist/{first-start-migration-4NETATFF.js → first-start-migration-Q2VB2E2D.js} +4 -4
  146. package/dist/harmonic-retrieval.js +1 -1
  147. package/dist/index.d.ts +680 -680
  148. package/dist/index.js +92 -90
  149. package/dist/maintenance/memory-governance.js +10 -10
  150. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  151. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  152. package/dist/mcp-memory-inspector-app.d.ts +1 -1
  153. package/dist/namespaces/migrate.js +11 -11
  154. package/dist/namespaces/search.js +4 -4
  155. package/dist/namespaces/storage.js +10 -10
  156. package/dist/offline-sync.js +3 -2
  157. package/dist/operator-doctor-corpus.js +13 -13
  158. package/dist/operator-toolkit.js +24 -22
  159. package/dist/orchestration/maintenance.js +16 -16
  160. package/dist/orchestrator.js +85 -83
  161. package/dist/{public-http-8PcrDIYi.d.ts → public-http-BmPktTe3.d.ts} +1 -1
  162. package/dist/reconcile/cursor.js +7 -3
  163. package/dist/reconcile/cursor.js.map +1 -1
  164. package/dist/reconcile/manifest.js +3 -7
  165. package/dist/reconcile/plan.d.ts +15 -1
  166. package/dist/reconcile/plan.js +6 -10
  167. package/dist/resume-bundles.js +6 -4
  168. package/dist/schemas.d.ts +108 -108
  169. package/dist/search/factory.js +3 -3
  170. package/dist/search/index.js +3 -3
  171. package/dist/semantic-consolidation.js +16 -16
  172. package/dist/semantic-rule-promotion.js +10 -10
  173. package/dist/semantic-rule-verifier.js +10 -10
  174. package/dist/shared-context/manager.d.ts +8 -8
  175. package/dist/source-agent-qualifier.js +10 -10
  176. package/dist/storage.js +9 -9
  177. package/dist/support-passport/index.d.ts +4 -4
  178. package/dist/support-passport/index.js +30 -28
  179. package/dist/transfer/autodetect.js +1 -1
  180. package/dist/transfer/backup.js +1 -1
  181. package/dist/transfer/capsule-export.js +2 -2
  182. package/dist/transfer/types.d.ts +66 -66
  183. package/dist/verified-recall.js +10 -10
  184. package/package.json +2 -2
  185. package/src/calibration.ts +3 -1
  186. package/src/census-validation.ts +25 -0
  187. package/src/coding/architecture-surfaces.test.ts +9 -10
  188. package/src/coding/architecture-surfaces.ts +2 -35
  189. package/src/coding/codegraph-runtime-loader.test.ts +228 -0
  190. package/src/coding/codegraph-runtime.ts +30 -50
  191. package/src/coding/codegraph-surfaces.ts +2 -2
  192. package/src/coding/coding-knowledge-config.ts +35 -1
  193. package/src/coding/decision-surfaces.test.ts +9 -10
  194. package/src/coding/decision-surfaces.ts +2 -40
  195. package/src/coding/session-delta-surfaces.test.ts +9 -10
  196. package/src/coding/session-delta-surfaces.ts +2 -33
  197. package/src/extraction-judge.ts +3 -1
  198. package/src/extraction-output-language.test.ts +116 -0
  199. package/src/extraction-prompt.ts +70 -1
  200. package/src/extraction.ts +23 -95
  201. package/src/offline-sync.ts +4 -4
  202. package/src/reconcile/census-parity.test.ts +152 -0
  203. package/src/reconcile/cursor.ts +5 -5
  204. package/src/reconcile/manifest.ts +4 -11
  205. package/src/reconcile/plan.ts +18 -15
  206. package/dist/chunk-EFKZT6AY.js.map +0 -1
  207. package/dist/chunk-IVXVLDNT.js.map +0 -1
  208. package/dist/chunk-L3CHRBHE.js.map +0 -1
  209. package/dist/chunk-R7TZ2HCS.js.map +0 -1
  210. package/dist/chunk-RYST72N5.js.map +0 -1
  211. package/dist/chunk-TWTUGCTY.js.map +0 -1
  212. package/dist/chunk-YXMHUBN2.js.map +0 -1
  213. package/dist/chunk-Z4N7SVVF.js.map +0 -1
  214. package/dist/{access-service-cKQrte9Z.d.ts → access-service-CocW74uA.d.ts} +64 -64
  215. /package/dist/{chunk-LEPOP46W.js.map → chunk-227UFSEQ.js.map} +0 -0
  216. /package/dist/{chunk-3Z5TGRFA.js.map → chunk-3NZAVWU5.js.map} +0 -0
  217. /package/dist/{chunk-I5FLIB2J.js.map → chunk-3S3PNR5H.js.map} +0 -0
  218. /package/dist/{chunk-R6UMNP5C.js.map → chunk-3T6HIIKA.js.map} +0 -0
  219. /package/dist/{chunk-77QZW2D6.js.map → chunk-3TDAA7VA.js.map} +0 -0
  220. /package/dist/{chunk-DXDAQZ2K.js.map → chunk-42TIIO2M.js.map} +0 -0
  221. /package/dist/{chunk-Y7COCXY2.js.map → chunk-4F67JJPG.js.map} +0 -0
  222. /package/dist/{chunk-PB4WVYGC.js.map → chunk-5S5DUJFJ.js.map} +0 -0
  223. /package/dist/{chunk-KYTRF64R.js.map → chunk-5SCFDQEJ.js.map} +0 -0
  224. /package/dist/{chunk-GG4DN63W.js.map → chunk-62Y5AGCM.js.map} +0 -0
  225. /package/dist/{chunk-KHCUVYCY.js.map → chunk-6UKSOXAO.js.map} +0 -0
  226. /package/dist/{chunk-F6JYBVL6.js.map → chunk-7ZAC2C2U.js.map} +0 -0
  227. /package/dist/{chunk-GF7RQWXC.js.map → chunk-AJRJDXYR.js.map} +0 -0
  228. /package/dist/{chunk-YEQCMA5L.js.map → chunk-BOSIHHOH.js.map} +0 -0
  229. /package/dist/{chunk-7LF2OHIJ.js.map → chunk-BRHKW7GY.js.map} +0 -0
  230. /package/dist/{chunk-LX4TNSAE.js.map → chunk-CBY54QYW.js.map} +0 -0
  231. /package/dist/{chunk-6YMEU6OQ.js.map → chunk-G72IPMR7.js.map} +0 -0
  232. /package/dist/{chunk-7AF243WZ.js.map → chunk-GBVRVYF4.js.map} +0 -0
  233. /package/dist/{chunk-GTD4Q62X.js.map → chunk-H4GQ2Y24.js.map} +0 -0
  234. /package/dist/{chunk-QI5RDDEL.js.map → chunk-HXZNTZ3Y.js.map} +0 -0
  235. /package/dist/{chunk-CIAI24TQ.js.map → chunk-IBZQQOM5.js.map} +0 -0
  236. /package/dist/{chunk-VPHSMJ2E.js.map → chunk-JPWSYHLB.js.map} +0 -0
  237. /package/dist/{chunk-X7LEDA74.js.map → chunk-KFB4YNXM.js.map} +0 -0
  238. /package/dist/{chunk-IPLYGWQF.js.map → chunk-KQAFEZQX.js.map} +0 -0
  239. /package/dist/{chunk-ZUPKNWRZ.js.map → chunk-MIUL6AUZ.js.map} +0 -0
  240. /package/dist/{chunk-EJY3HJMT.js.map → chunk-MYI3RKI6.js.map} +0 -0
  241. /package/dist/{chunk-NA56NSKL.js.map → chunk-OOJCXJBN.js.map} +0 -0
  242. /package/dist/{chunk-7KQB4EBS.js.map → chunk-OPPBTPUU.js.map} +0 -0
  243. /package/dist/{chunk-ERPBRXVZ.js.map → chunk-PZKWPXRF.js.map} +0 -0
  244. /package/dist/{chunk-FHKXVTM5.js.map → chunk-Q5XKKDFQ.js.map} +0 -0
  245. /package/dist/{chunk-QRWMS6SI.js.map → chunk-Q6OL23WM.js.map} +0 -0
  246. /package/dist/{chunk-OW7NVMGQ.js.map → chunk-QIZOU3FN.js.map} +0 -0
  247. /package/dist/{chunk-V3KIRICY.js.map → chunk-QQYHYW2N.js.map} +0 -0
  248. /package/dist/{chunk-YFCEBB5P.js.map → chunk-QTXNS3HB.js.map} +0 -0
  249. /package/dist/{chunk-2QSZNTDO.js.map → chunk-RKNJBZ55.js.map} +0 -0
  250. /package/dist/{chunk-E4KMY4KR.js.map → chunk-SNEUAZ6B.js.map} +0 -0
  251. /package/dist/{chunk-TSTI6A3A.js.map → chunk-SYJW273H.js.map} +0 -0
  252. /package/dist/{chunk-PBRCYYO7.js.map → chunk-ULZFZL7K.js.map} +0 -0
  253. /package/dist/{chunk-UGHCZS6K.js.map → chunk-VFZQXYN5.js.map} +0 -0
  254. /package/dist/{chunk-NKB43PGI.js.map → chunk-WZDTSBGQ.js.map} +0 -0
  255. /package/dist/{chunk-2UM6WHME.js.map → chunk-XE2QCCT2.js.map} +0 -0
  256. /package/dist/{chunk-FPEZ74F7.js.map → chunk-XNJQZLAP.js.map} +0 -0
  257. /package/dist/{chunk-SYVGVK4S.js.map → chunk-XTMYB2HY.js.map} +0 -0
  258. /package/dist/{chunk-OETHJBAL.js.map → chunk-XV6PUXJ5.js.map} +0 -0
  259. /package/dist/{chunk-UCLMKNHA.js.map → chunk-YIMV2KYM.js.map} +0 -0
  260. /package/dist/{chunk-DYZR3Z6D.js.map → chunk-YMQKPSB2.js.map} +0 -0
  261. /package/dist/{chunk-AYVCKGA6.js.map → chunk-YTXNDEUS.js.map} +0 -0
  262. /package/dist/{first-start-migration-4NETATFF.js.map → first-start-migration-Q2VB2E2D.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/active-recall.ts"],"sourcesContent":["import { appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { DEFAULT_REASONING_MODEL } from \"./config.js\";\nimport { collapseWhitespace, truncateCodePointSafe } from \"./whitespace.js\";\nimport type {\n ActiveRecallChatType,\n ActiveRecallModelFallbackPolicy,\n ActiveRecallPromptStyle,\n ActiveRecallQueryMode,\n ActiveRecallThinking,\n} from \"./types.js\";\n\nexport interface ActiveRecallTurn {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface ActiveRecallInput {\n sessionKey: string;\n agentId: string;\n chatType: ActiveRecallChatType;\n recentTurns: ActiveRecallTurn[];\n currentMessage: string;\n}\n\nexport interface ActiveRecallConfig {\n enabled: boolean;\n agents: string[] | null;\n allowedChatTypes: ActiveRecallChatType[];\n queryMode: ActiveRecallQueryMode;\n promptStyle: ActiveRecallPromptStyle;\n customInstruction: string | null;\n promptReplacement: string | null;\n promptAppend: string | null;\n maxSummaryChars: number;\n recentUserTurns: number;\n recentAssistantTurns: number;\n recentUserChars: number;\n recentAssistantChars: number;\n thinking: ActiveRecallThinking;\n timeoutMs: number;\n cacheTtlMs: number;\n persistTranscripts: boolean;\n transcriptDir: string;\n entityGraphDepth: number;\n includeCausalTrajectories: boolean;\n includeDaySummary: boolean;\n attachRecallExplain: boolean;\n modelOverride: string | null;\n modelFallbackPolicy: ActiveRecallModelFallbackPolicy;\n}\n\nexport interface ActiveRecallResult {\n summary: string | null;\n citations: Array<{ memoryId: string; relevance: number }>;\n latencyMs: number;\n cacheHit: boolean;\n modelUsed: string;\n transcriptPath: string | null;\n}\n\nexport interface ActiveRecallDependencies {\n recall(query: string, sessionKey: string): Promise<string | null>;\n getLastRecallSnapshot?(sessionKey: string): { memoryIds?: string[] } | null;\n walkEntityGraph?(params: {\n sessionKey: string;\n query: string;\n depth: number;\n }): Promise<string[]>;\n loadCausalTrajectories?(params: {\n sessionKey: string;\n query: string;\n }): Promise<string[]>;\n loadDaySummary?(sessionKey: string): Promise<string | null>;\n explainLastRecall?(sessionKey: string): Promise<string | null>;\n generateSummary?(params: {\n prompt: string;\n sessionKey: string;\n agentId: string;\n model: string;\n timeoutMs: number;\n thinking: ActiveRecallThinking;\n fallbackPolicy: ActiveRecallModelFallbackPolicy;\n }): Promise<{ text: string | null; modelUsed?: string; cacheHit?: boolean }>;\n now?: () => number;\n}\n\ninterface CachedRecallResult {\n expiresAt: number;\n value: ActiveRecallResult;\n}\n\ninterface ActiveRecallTurnWithIndex {\n index: number;\n role: ActiveRecallTurn[\"role\"];\n content: string;\n}\n\nconst ACTIVE_RECALL_CACHE_MAX_ENTRIES = 256;\n\nconst NONE_SET = new Set([\n \"\",\n \"none\",\n \"no_reply\",\n \"nothing useful\",\n \"no relevant memory\",\n \"timeout\",\n \"[]\",\n \"{}\",\n \"null\",\n \"n/a\",\n]);\n\nconst STYLE_INSTRUCTIONS: Record<ActiveRecallPromptStyle, string> = {\n balanced: \"Summarize the most relevant memory context in a compact, neutral way.\",\n strict: \"Only include memory that is directly supported by the retrieved context.\",\n contextual: \"Prefer concise context that helps the next reply stay grounded in recent work.\",\n \"recall-heavy\": \"Bias toward richer recall coverage when multiple retrieved items reinforce each other.\",\n \"precision-heavy\": \"Bias toward precision. Omit anything uncertain or weakly supported.\",\n \"preference-only\": \"Only surface user preference or operating-style memory when present.\",\n};\n\nfunction cloneRecallResult(value: ActiveRecallResult): ActiveRecallResult {\n return {\n ...value,\n citations: [...value.citations],\n };\n}\n\nfunction buildCacheKey(input: ActiveRecallInput, config: ActiveRecallConfig, queryBundle: string): string {\n return JSON.stringify({\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n customInstruction: config.customInstruction,\n promptReplacement: config.promptReplacement,\n promptAppend: config.promptAppend,\n maxSummaryChars: config.maxSummaryChars,\n entityGraphDepth: config.entityGraphDepth,\n includeCausalTrajectories: config.includeCausalTrajectories,\n includeDaySummary: config.includeDaySummary,\n attachRecallExplain: config.attachRecallExplain,\n modelOverride: config.modelOverride,\n modelFallbackPolicy: config.modelFallbackPolicy,\n thinking: config.thinking,\n queryBundle,\n });\n}\n\nfunction pruneExpiredCache(\n cache: Map<string, CachedRecallResult>,\n currentTime: number,\n): void {\n for (const [key, entry] of cache.entries()) {\n if (entry.expiresAt <= currentTime) {\n cache.delete(key);\n }\n }\n}\n\nfunction enforceCacheLimit(cache: Map<string, CachedRecallResult>): void {\n while (cache.size > ACTIVE_RECALL_CACHE_MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (typeof oldestKey !== \"string\") {\n break;\n }\n cache.delete(oldestKey);\n }\n}\n\nfunction cropTurns(\n turns: ActiveRecallTurn[],\n role: \"user\" | \"assistant\",\n maxTurns: number,\n maxChars: number,\n): ActiveRecallTurnWithIndex[] {\n if (maxTurns <= 0) {\n return [];\n }\n\n const selected: ActiveRecallTurnWithIndex[] = [];\n for (let index = turns.length - 1; index >= 0 && selected.length < maxTurns; index -= 1) {\n const turn = turns[index];\n if (turn?.role === role) {\n selected.push({\n index,\n role: turn.role,\n content: collapseWhitespace(truncateCodePointSafe(turn.content, maxChars)),\n });\n }\n }\n\n return selected.reverse();\n}\n\nfunction mergeChronologicalTurns(\n userTurns: ActiveRecallTurnWithIndex[],\n assistantTurns: ActiveRecallTurnWithIndex[],\n): ActiveRecallTurnWithIndex[] {\n return [...userTurns, ...assistantTurns]\n .sort((left, right) => left.index - right.index)\n .filter((value) => value.content.length > 0);\n}\n\nexport function buildActiveRecallQueryBundle(\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n): string {\n if (config.queryMode === \"message\") {\n return collapseWhitespace(input.currentMessage);\n }\n\n const userTurns = cropTurns(\n input.recentTurns,\n \"user\",\n config.recentUserTurns,\n config.recentUserChars,\n );\n const assistantTurns = cropTurns(\n input.recentTurns,\n \"assistant\",\n config.recentAssistantTurns,\n config.recentAssistantChars,\n );\n const mergedTurns = mergeChronologicalTurns(userTurns, assistantTurns);\n\n const parts = [\n ...mergedTurns.map((turn) => `${turn.role}: ${turn.content}`),\n ];\n\n if (config.queryMode === \"full\") {\n return [...parts, `current: ${collapseWhitespace(input.currentMessage)}`]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n }\n\n return [`current: ${collapseWhitespace(input.currentMessage)}`, ...parts]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n}\n\nexport function normalizeActiveRecallSummary(value: string | null, maxChars: number): string | null {\n if (value == null) return null;\n const compact = collapseWhitespace(value);\n if (NONE_SET.has(compact.toLowerCase())) return null;\n return truncateCodePointSafe(compact, maxChars);\n}\n\nfunction sanitizeTranscriptPathSegment(value: string): string {\n const normalized = collapseWhitespace(value);\n return encodeURIComponent(normalized.length > 0 ? normalized : \"unknown\").replaceAll(\n \".\",\n \"%2E\",\n );\n}\n\nexport function buildActiveRecallPrompt(params: {\n config: ActiveRecallConfig;\n queryBundle: string;\n recallContext: string | null;\n graphContext: string[];\n causalContext: string[];\n daySummary: string | null;\n recallExplain: string | null;\n}): string {\n const promptReplacement = params.config.promptReplacement?.trim();\n if (promptReplacement) {\n return promptReplacement;\n }\n\n const sections = [\n params.config.customInstruction?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],\n `Query bundle:\\n${params.queryBundle}`,\n params.recallContext ? `Retrieved memory:\\n${params.recallContext}` : null,\n params.graphContext.length > 0 ? `Entity graph:\\n${params.graphContext.join(\"\\n\")}` : null,\n params.causalContext.length > 0 ? `Causal trajectories:\\n${params.causalContext.join(\"\\n\")}` : null,\n params.daySummary ? `Day summary:\\n${params.daySummary}` : null,\n params.recallExplain ? `Recall explain:\\n${params.recallExplain}` : null,\n params.config.promptAppend?.trim() || null,\n \"Return either NONE or a compact summary grounded only in the supplied context.\",\n ];\n return sections.filter((value): value is string => !!value && value.trim().length > 0).join(\"\\n\\n\");\n}\n\nasync function appendActiveRecallTranscript(\n transcriptRoot: string,\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n result: ActiveRecallResult,\n queryBundle: string,\n): Promise<string> {\n const date = new Date().toISOString().slice(0, 10);\n const filePath = path.join(\n transcriptRoot,\n \"agents\",\n sanitizeTranscriptPathSegment(input.agentId),\n date,\n `${sanitizeTranscriptPathSegment(input.sessionKey)}.jsonl`,\n );\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(\n filePath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n queryBundle,\n summary: result.summary,\n citations: result.citations,\n latencyMs: result.latencyMs,\n cacheHit: result.cacheHit,\n modelUsed: result.modelUsed,\n })}\\n`,\n \"utf8\",\n );\n return filePath;\n}\n\nexport function createActiveRecallEngine(\n deps: ActiveRecallDependencies,\n config: ActiveRecallConfig,\n) {\n const cache = new Map<string, CachedRecallResult>();\n const now = deps.now ?? (() => Date.now());\n\n return {\n async run(input: ActiveRecallInput): Promise<ActiveRecallResult> {\n if (!config.enabled) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"disabled\",\n transcriptPath: null,\n };\n }\n if (config.agents && !config.agents.includes(input.agentId)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n if (!config.allowedChatTypes.includes(input.chatType)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n\n const queryBundle = buildActiveRecallQueryBundle(input, config);\n const cacheKey = buildCacheKey(input, config, queryBundle);\n const currentTime = now();\n const cacheEnabled = config.cacheTtlMs > 0;\n if (cacheEnabled) {\n pruneExpiredCache(cache, currentTime);\n }\n const cached = cache.get(cacheKey);\n if (cacheEnabled && cached) {\n const result: ActiveRecallResult = {\n ...cloneRecallResult(cached.value),\n latencyMs: Math.max(0, now() - currentTime),\n cacheHit: true,\n };\n result.transcriptPath = null;\n if (config.persistTranscripts) {\n try {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n } catch {\n result.transcriptPath = null;\n }\n }\n return result;\n }\n\n const start = currentTime;\n const recallContext = await deps.recall(queryBundle, input.sessionKey);\n const graphContext =\n config.entityGraphDepth > 0 && deps.walkEntityGraph\n ? await deps.walkEntityGraph({\n sessionKey: input.sessionKey,\n query: queryBundle,\n depth: config.entityGraphDepth,\n })\n : [];\n const causalContext =\n config.includeCausalTrajectories && deps.loadCausalTrajectories\n ? await deps.loadCausalTrajectories({\n sessionKey: input.sessionKey,\n query: queryBundle,\n })\n : [];\n const daySummary =\n config.includeDaySummary && deps.loadDaySummary\n ? await deps.loadDaySummary(input.sessionKey)\n : null;\n const recallExplain =\n config.attachRecallExplain && deps.explainLastRecall\n ? await deps.explainLastRecall(input.sessionKey)\n : null;\n const prompt = buildActiveRecallPrompt({\n config,\n queryBundle,\n recallContext,\n graphContext,\n causalContext,\n daySummary,\n recallExplain,\n });\n\n const generated = deps.generateSummary\n ? await deps.generateSummary({\n prompt,\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n model: config.modelOverride ?? DEFAULT_REASONING_MODEL,\n timeoutMs: config.timeoutMs,\n thinking: config.thinking,\n fallbackPolicy: config.modelFallbackPolicy,\n })\n : {\n text: recallContext,\n modelUsed: config.modelOverride ?? DEFAULT_REASONING_MODEL,\n cacheHit: false,\n };\n const summary = normalizeActiveRecallSummary(\n generated.text,\n config.maxSummaryChars,\n );\n const snapshot = deps.getLastRecallSnapshot?.(input.sessionKey);\n const citations = (snapshot?.memoryIds ?? []).map((memoryId, index) => ({\n memoryId,\n relevance: Number((1 / (index + 1)).toFixed(3)),\n }));\n const result: ActiveRecallResult = {\n summary,\n citations,\n latencyMs: Math.max(0, now() - start),\n cacheHit: generated.cacheHit === true,\n modelUsed: generated.modelUsed ?? config.modelOverride ?? DEFAULT_REASONING_MODEL,\n transcriptPath: null,\n };\n if (config.persistTranscripts) {\n try {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n } catch {\n result.transcriptPath = null;\n }\n }\n\n if (cacheEnabled) {\n const completedAt = now();\n const cachedValue = cloneRecallResult(result);\n cachedValue.transcriptPath = null;\n cache.set(cacheKey, {\n expiresAt: completedAt + config.cacheTtlMs,\n value: cachedValue,\n });\n enforceCacheLimit(cache);\n }\n return result;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,aAAa;AAClC,OAAO,UAAU;AAiGjB,IAAM,kCAAkC;AAExC,IAAM,WAAW,oBAAI,IAAI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,qBAA8D;AAAA,EAClE,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,mBAAmB;AACrB;AAEA,SAAS,kBAAkB,OAA+C;AACxE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,CAAC,GAAG,MAAM,SAAS;AAAA,EAChC;AACF;AAEA,SAAS,cAAc,OAA0B,QAA4B,aAA6B;AACxG,SAAO,KAAK,UAAU;AAAA,IACpB,YAAY,MAAM;AAAA,IAClB,SAAS,MAAM;AAAA,IACf,WAAW,OAAO;AAAA,IAClB,aAAa,OAAO;AAAA,IACpB,mBAAmB,OAAO;AAAA,IAC1B,mBAAmB,OAAO;AAAA,IAC1B,cAAc,OAAO;AAAA,IACrB,iBAAiB,OAAO;AAAA,IACxB,kBAAkB,OAAO;AAAA,IACzB,2BAA2B,OAAO;AAAA,IAClC,mBAAmB,OAAO;AAAA,IAC1B,qBAAqB,OAAO;AAAA,IAC5B,eAAe,OAAO;AAAA,IACtB,qBAAqB,OAAO;AAAA,IAC5B,UAAU,OAAO;AAAA,IACjB;AAAA,EACF,CAAC;AACH;AAEA,SAAS,kBACP,OACA,aACM;AACN,aAAW,C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AW;AAAA,QACtE;AAAA,QACA,WAAW,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,CAAC;AAAA,MAChD,EAAE;AACF,YAAM,SAA6B;AAAA,QACjC;AAAA,QACA;AAAA,QACA,WAAW,KAAK,IAAI,GAAG,IAAI,IAAI,KAAK;AAAA,QACpC,UAAU,UAAU,aAAa;AAAA,QACjC,WAAW,UAAU,aAAa,OAAO,iBAAiB;AAAA,QAC1D,gBAAgB;AAAA,MAClB;AACA,UAAI,OAAO,oBAAoB;AAC7B,YAAI;AACF,iBAAO,iBAAiB,MAAM;AAAA,YAC5B,OAAO;AAAA,YACP;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF,QAAQ;AACN,iBAAO,iBAAiB;AAAA,QAC1B;AAAA,MACF;AAEA,UAAI,cAAc;AAChB,cAAM,cAAc,IAAI;AACxB,cAAM,cAAc,kBAAkB,MAAM;AAC5C,oBAAY,iBAAiB;AAC7B,cAAM,IAAI,UAAU;AAAA,UAClB,WAAW,cAAc,OAAO;AAAA,UAChC,OAAO;AAAA,QACT,CAAC;AACD,0BAAkB,KAAK;AAAA,MACzB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["result"]}
1
+ {"version":3,"sources":["../src/active-recall.ts"],"sourcesContent":["import { appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { DEFAULT_REASONING_MODEL } from \"./config.js\";\nimport { collapseWhitespace, truncateCodePointSafe } from \"./whitespace.js\";\nimport type {\n ActiveRecallChatType,\n ActiveRecallModelFallbackPolicy,\n ActiveRecallPromptStyle,\n ActiveRecallQueryMode,\n ActiveRecallThinking,\n} from \"./types.js\";\n\nexport interface ActiveRecallTurn {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface ActiveRecallInput {\n sessionKey: string;\n agentId: string;\n chatType: ActiveRecallChatType;\n recentTurns: ActiveRecallTurn[];\n currentMessage: string;\n}\n\nexport interface ActiveRecallConfig {\n enabled: boolean;\n agents: string[] | null;\n allowedChatTypes: ActiveRecallChatType[];\n queryMode: ActiveRecallQueryMode;\n promptStyle: ActiveRecallPromptStyle;\n customInstruction: string | null;\n promptReplacement: string | null;\n promptAppend: string | null;\n maxSummaryChars: number;\n recentUserTurns: number;\n recentAssistantTurns: number;\n recentUserChars: number;\n recentAssistantChars: number;\n thinking: ActiveRecallThinking;\n timeoutMs: number;\n cacheTtlMs: number;\n persistTranscripts: boolean;\n transcriptDir: string;\n entityGraphDepth: number;\n includeCausalTrajectories: boolean;\n includeDaySummary: boolean;\n attachRecallExplain: boolean;\n modelOverride: string | null;\n modelFallbackPolicy: ActiveRecallModelFallbackPolicy;\n}\n\nexport interface ActiveRecallResult {\n summary: string | null;\n citations: Array<{ memoryId: string; relevance: number }>;\n latencyMs: number;\n cacheHit: boolean;\n modelUsed: string;\n transcriptPath: string | null;\n}\n\nexport interface ActiveRecallDependencies {\n recall(query: string, sessionKey: string): Promise<string | null>;\n getLastRecallSnapshot?(sessionKey: string): { memoryIds?: string[] } | null;\n walkEntityGraph?(params: {\n sessionKey: string;\n query: string;\n depth: number;\n }): Promise<string[]>;\n loadCausalTrajectories?(params: {\n sessionKey: string;\n query: string;\n }): Promise<string[]>;\n loadDaySummary?(sessionKey: string): Promise<string | null>;\n explainLastRecall?(sessionKey: string): Promise<string | null>;\n generateSummary?(params: {\n prompt: string;\n sessionKey: string;\n agentId: string;\n model: string;\n timeoutMs: number;\n thinking: ActiveRecallThinking;\n fallbackPolicy: ActiveRecallModelFallbackPolicy;\n }): Promise<{ text: string | null; modelUsed?: string; cacheHit?: boolean }>;\n now?: () => number;\n}\n\ninterface CachedRecallResult {\n expiresAt: number;\n value: ActiveRecallResult;\n}\n\ninterface ActiveRecallTurnWithIndex {\n index: number;\n role: ActiveRecallTurn[\"role\"];\n content: string;\n}\n\nconst ACTIVE_RECALL_CACHE_MAX_ENTRIES = 256;\n\nconst NONE_SET = new Set([\n \"\",\n \"none\",\n \"no_reply\",\n \"nothing useful\",\n \"no relevant memory\",\n \"timeout\",\n \"[]\",\n \"{}\",\n \"null\",\n \"n/a\",\n]);\n\nconst STYLE_INSTRUCTIONS: Record<ActiveRecallPromptStyle, string> = {\n balanced: \"Summarize the most relevant memory context in a compact, neutral way.\",\n strict: \"Only include memory that is directly supported by the retrieved context.\",\n contextual: \"Prefer concise context that helps the next reply stay grounded in recent work.\",\n \"recall-heavy\": \"Bias toward richer recall coverage when multiple retrieved items reinforce each other.\",\n \"precision-heavy\": \"Bias toward precision. Omit anything uncertain or weakly supported.\",\n \"preference-only\": \"Only surface user preference or operating-style memory when present.\",\n};\n\nfunction cloneRecallResult(value: ActiveRecallResult): ActiveRecallResult {\n return {\n ...value,\n citations: [...value.citations],\n };\n}\n\nfunction buildCacheKey(input: ActiveRecallInput, config: ActiveRecallConfig, queryBundle: string): string {\n return JSON.stringify({\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n customInstruction: config.customInstruction,\n promptReplacement: config.promptReplacement,\n promptAppend: config.promptAppend,\n maxSummaryChars: config.maxSummaryChars,\n entityGraphDepth: config.entityGraphDepth,\n includeCausalTrajectories: config.includeCausalTrajectories,\n includeDaySummary: config.includeDaySummary,\n attachRecallExplain: config.attachRecallExplain,\n modelOverride: config.modelOverride,\n modelFallbackPolicy: config.modelFallbackPolicy,\n thinking: config.thinking,\n queryBundle,\n });\n}\n\nfunction pruneExpiredCache(\n cache: Map<string, CachedRecallResult>,\n currentTime: number,\n): void {\n for (const [key, entry] of cache.entries()) {\n if (entry.expiresAt <= currentTime) {\n cache.delete(key);\n }\n }\n}\n\nfunction enforceCacheLimit(cache: Map<string, CachedRecallResult>): void {\n while (cache.size > ACTIVE_RECALL_CACHE_MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (typeof oldestKey !== \"string\") {\n break;\n }\n cache.delete(oldestKey);\n }\n}\n\nfunction cropTurns(\n turns: ActiveRecallTurn[],\n role: \"user\" | \"assistant\",\n maxTurns: number,\n maxChars: number,\n): ActiveRecallTurnWithIndex[] {\n if (maxTurns <= 0) {\n return [];\n }\n\n const selected: ActiveRecallTurnWithIndex[] = [];\n for (let index = turns.length - 1; index >= 0 && selected.length < maxTurns; index -= 1) {\n const turn = turns[index];\n if (turn?.role === role) {\n selected.push({\n index,\n role: turn.role,\n content: collapseWhitespace(truncateCodePointSafe(turn.content, maxChars)),\n });\n }\n }\n\n return selected.reverse();\n}\n\nfunction mergeChronologicalTurns(\n userTurns: ActiveRecallTurnWithIndex[],\n assistantTurns: ActiveRecallTurnWithIndex[],\n): ActiveRecallTurnWithIndex[] {\n return [...userTurns, ...assistantTurns]\n .sort((left, right) => left.index - right.index)\n .filter((value) => value.content.length > 0);\n}\n\nexport function buildActiveRecallQueryBundle(\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n): string {\n if (config.queryMode === \"message\") {\n return collapseWhitespace(input.currentMessage);\n }\n\n const userTurns = cropTurns(\n input.recentTurns,\n \"user\",\n config.recentUserTurns,\n config.recentUserChars,\n );\n const assistantTurns = cropTurns(\n input.recentTurns,\n \"assistant\",\n config.recentAssistantTurns,\n config.recentAssistantChars,\n );\n const mergedTurns = mergeChronologicalTurns(userTurns, assistantTurns);\n\n const parts = [\n ...mergedTurns.map((turn) => `${turn.role}: ${turn.content}`),\n ];\n\n if (config.queryMode === \"full\") {\n return [...parts, `current: ${collapseWhitespace(input.currentMessage)}`]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n }\n\n return [`current: ${collapseWhitespace(input.currentMessage)}`, ...parts]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n}\n\nexport function normalizeActiveRecallSummary(value: string | null, maxChars: number): string | null {\n if (value == null) return null;\n const compact = collapseWhitespace(value);\n if (NONE_SET.has(compact.toLowerCase())) return null;\n return truncateCodePointSafe(compact, maxChars);\n}\n\nfunction sanitizeTranscriptPathSegment(value: string): string {\n const normalized = collapseWhitespace(value);\n return encodeURIComponent(normalized.length > 0 ? normalized : \"unknown\").replaceAll(\n \".\",\n \"%2E\",\n );\n}\n\nexport function buildActiveRecallPrompt(params: {\n config: ActiveRecallConfig;\n queryBundle: string;\n recallContext: string | null;\n graphContext: string[];\n causalContext: string[];\n daySummary: string | null;\n recallExplain: string | null;\n}): string {\n const promptReplacement = params.config.promptReplacement?.trim();\n if (promptReplacement) {\n return promptReplacement;\n }\n\n const sections = [\n params.config.customInstruction?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],\n `Query bundle:\\n${params.queryBundle}`,\n params.recallContext ? `Retrieved memory:\\n${params.recallContext}` : null,\n params.graphContext.length > 0 ? `Entity graph:\\n${params.graphContext.join(\"\\n\")}` : null,\n params.causalContext.length > 0 ? `Causal trajectories:\\n${params.causalContext.join(\"\\n\")}` : null,\n params.daySummary ? `Day summary:\\n${params.daySummary}` : null,\n params.recallExplain ? `Recall explain:\\n${params.recallExplain}` : null,\n params.config.promptAppend?.trim() || null,\n \"Return either NONE or a compact summary grounded only in the supplied context.\",\n ];\n return sections.filter((value): value is string => !!value && value.trim().length > 0).join(\"\\n\\n\");\n}\n\nasync function appendActiveRecallTranscript(\n transcriptRoot: string,\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n result: ActiveRecallResult,\n queryBundle: string,\n): Promise<string> {\n const date = new Date().toISOString().slice(0, 10);\n const filePath = path.join(\n transcriptRoot,\n \"agents\",\n sanitizeTranscriptPathSegment(input.agentId),\n date,\n `${sanitizeTranscriptPathSegment(input.sessionKey)}.jsonl`,\n );\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(\n filePath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n queryBundle,\n summary: result.summary,\n citations: result.citations,\n latencyMs: result.latencyMs,\n cacheHit: result.cacheHit,\n modelUsed: result.modelUsed,\n })}\\n`,\n \"utf8\",\n );\n return filePath;\n}\n\nexport function createActiveRecallEngine(\n deps: ActiveRecallDependencies,\n config: ActiveRecallConfig,\n) {\n const cache = new Map<string, CachedRecallResult>();\n const now = deps.now ?? (() => Date.now());\n\n return {\n async run(input: ActiveRecallInput): Promise<ActiveRecallResult> {\n if (!config.enabled) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"disabled\",\n transcriptPath: null,\n };\n }\n if (config.agents && !config.agents.includes(input.agentId)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n if (!config.allowedChatTypes.includes(input.chatType)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n\n const queryBundle = buildActiveRecallQueryBundle(input, config);\n const cacheKey = buildCacheKey(input, config, queryBundle);\n const currentTime = now();\n const cacheEnabled = config.cacheTtlMs > 0;\n if (cacheEnabled) {\n pruneExpiredCache(cache, currentTime);\n }\n const cached = cache.get(cacheKey);\n if (cacheEnabled && cached) {\n const result: ActiveRecallResult = {\n ...cloneRecallResult(cached.value),\n latencyMs: Math.max(0, now() - currentTime),\n cacheHit: true,\n };\n result.transcriptPath = null;\n if (config.persistTranscripts) {\n try {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n } catch {\n result.transcriptPath = null;\n }\n }\n return result;\n }\n\n const start = currentTime;\n const recallContext = await deps.recall(queryBundle, input.sessionKey);\n const graphContext =\n config.entityGraphDepth > 0 && deps.walkEntityGraph\n ? await deps.walkEntityGraph({\n sessionKey: input.sessionKey,\n query: queryBundle,\n depth: config.entityGraphDepth,\n })\n : [];\n const causalContext =\n config.includeCausalTrajectories && deps.loadCausalTrajectories\n ? await deps.loadCausalTrajectories({\n sessionKey: input.sessionKey,\n query: queryBundle,\n })\n : [];\n const daySummary =\n config.includeDaySummary && deps.loadDaySummary\n ? await deps.loadDaySummary(input.sessionKey)\n : null;\n const recallExplain =\n config.attachRecallExplain && deps.explainLastRecall\n ? await deps.explainLastRecall(input.sessionKey)\n : null;\n const prompt = buildActiveRecallPrompt({\n config,\n queryBundle,\n recallContext,\n graphContext,\n causalContext,\n daySummary,\n recallExplain,\n });\n\n const generated = deps.generateSummary\n ? await deps.generateSummary({\n prompt,\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n model: config.modelOverride ?? DEFAULT_REASONING_MODEL,\n timeoutMs: config.timeoutMs,\n thinking: config.thinking,\n fallbackPolicy: config.modelFallbackPolicy,\n })\n : {\n text: recallContext,\n modelUsed: config.modelOverride ?? DEFAULT_REASONING_MODEL,\n cacheHit: false,\n };\n const summary = normalizeActiveRecallSummary(\n generated.text,\n config.maxSummaryChars,\n );\n const snapshot = deps.getLastRecallSnapshot?.(input.sessionKey);\n const citations = (snapshot?.memoryIds ?? []).map((memoryId, index) => ({\n memoryId,\n relevance: Number((1 / (index + 1)).toFixed(3)),\n }));\n const result: ActiveRecallResult = {\n summary,\n citations,\n latencyMs: Math.max(0, now() - start),\n cacheHit: generated.cacheHit === true,\n modelUsed: generated.modelUsed ?? config.modelOverride ?? DEFAULT_REASONING_MODEL,\n transcriptPath: null,\n };\n if (config.persistTranscripts) {\n try {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n } catch {\n result.transcriptPath = null;\n }\n }\n\n if (cacheEnabled) {\n const completedAt = now();\n const cachedValue = cloneRecallResult(result);\n cachedValue.transcriptPath = null;\n cache.set(cacheKey, {\n expiresAt: completedAt + config.cacheTtlMs,\n value: cachedValue,\n });\n enforceCacheLimit(cache);\n }\n return result;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,aAAa;AAClC,OAAO,UA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gBAAgB;AAAA,MAClB;AACA,UAAI,OAAO,oBAAoB;AAC7B,YAAI;AACF,iBAAO,iBAAiB,MAAM;AAAA,YAC5B,OAAO;AAAA,YACP;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF,QAAQ;AACN,iBAAO,iBAAiB;AAAA,QAC1B;AAAA,MACF;AAEA,UAAI,cAAc;AAChB,cAAM,cAAc,IAAI;AACxB,cAAM,cAAc,kBAAkB,MAAM;AAC5C,oBAAY,iBAAiB;AAC7B,cAAM,IAAI,UAAU;AAAA,UAClB,WAAW,cAAc,OAAO;AAAA,UAChC,OAAO;AAAA,QACT,CAAC;AACD,0BAAkB,KAAK;AAAA,MACzB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["result"]}
@@ -1,7 +1,10 @@
1
1
  import "../chunk-SEDEKFYQ.js";
2
2
  import {
3
3
  AdapterRegistry
4
- } from "../chunk-2QSZNTDO.js";
4
+ } from "../chunk-RKNJBZ55.js";
5
+ import {
6
+ ClaudeCodeAdapter
7
+ } from "../chunk-J64TK33U.js";
5
8
  import {
6
9
  CodexAdapter
7
10
  } from "../chunk-RSUYKGGZ.js";
@@ -11,9 +14,6 @@ import {
11
14
  import {
12
15
  ReplitAdapter
13
16
  } from "../chunk-TMSXWOBZ.js";
14
- import {
15
- ClaudeCodeAdapter
16
- } from "../chunk-J64TK33U.js";
17
17
  import "../chunk-7RXCMVFQ.js";
18
18
  import "../chunk-PZ5AY32C.js";
19
19
  export {
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  AdapterRegistry
3
- } from "../chunk-2QSZNTDO.js";
3
+ } from "../chunk-RKNJBZ55.js";
4
+ import "../chunk-J64TK33U.js";
4
5
  import "../chunk-RSUYKGGZ.js";
5
6
  import "../chunk-42NQ7AVG.js";
6
7
  import "../chunk-TMSXWOBZ.js";
7
- import "../chunk-J64TK33U.js";
8
8
  import "../chunk-7RXCMVFQ.js";
9
9
  import "../chunk-PZ5AY32C.js";
10
10
  export {
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  dateInTimezone,
3
3
  defaultTimezone
4
- } from "./chunk-Y7COCXY2.js";
5
- import "./chunk-TWTUGCTY.js";
4
+ } from "./chunk-4F67JJPG.js";
5
+ import "./chunk-3YTTAGPB.js";
6
6
  import "./chunk-JXS5PDQ7.js";
7
+ import "./chunk-JG22O53B.js";
7
8
  import "./chunk-ZKOPY4WW.js";
8
9
  import "./chunk-QW27DOHG.js";
9
10
  import {
@@ -25,6 +26,7 @@ import "./chunk-JDSVLVCG.js";
25
26
  import "./chunk-5GKPFL3S.js";
26
27
  import "./chunk-JAKIDQB2.js";
27
28
  import "./chunk-P7FMDTKL.js";
29
+ import "./chunk-JUOZ62Y7.js";
28
30
  import "./chunk-EYIEWJNI.js";
29
31
  import "./chunk-JUC24CTX.js";
30
32
  import "./chunk-3WCASNQZ.js";
@@ -79,4 +81,4 @@ function startWearablesAutoSync(settings, deps) {
79
81
  export {
80
82
  startWearablesAutoSync
81
83
  };
82
- //# sourceMappingURL=auto-sync-BKRJDMKX.js.map
84
+ //# sourceMappingURL=auto-sync-3SHMZVQS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wearables/auto-sync.ts"],"sourcesContent":["/**\n * Wearables auto-sync — in-process periodic transcript refresh.\n *\n * Every tick re-syncs a short rolling window ending today for ALL\n * enabled sources, so the current day's transcript keeps growing while\n * the wearable records and provider-side revisions of recent days flow\n * in without operator action. Once per local day the window deepens to\n * `autoSyncDeepDays` to pick up late uploads and provider reprocessing\n * further back (phones syncing hours later, re-diarized transcripts).\n *\n * Day fetches are unconditional within the window — existing day files\n * are always re-fetched and re-composed; the content-hash skip in the\n * pipeline keeps unchanged days write-free, so a tick on a quiet day\n * is read-only. The timer is unref'd: it never keeps a one-shot CLI\n * process alive, and long-lived hosts stop it via the returned handle.\n */\n\nimport { describeErrorForOperator } from \"./errors.js\";\nimport { dateInTimezone, defaultTimezone } from \"./pipeline.js\";\n\nexport interface WearablesAutoSyncSettings {\n /** Minutes between ticks. */\n intervalMinutes: number;\n /** Rolling window (days ending today) refreshed on a normal tick. */\n days: number;\n /**\n * Window for the once-per-local-day deep pass. 0 disables the deep\n * pass; otherwise must be >= `days` (validated at config parse).\n */\n deepDays: number;\n /** IANA timezone used to detect the local-day rollover. */\n timezone?: string;\n}\n\nexport interface WearablesAutoSyncDeps {\n /** Run a sync across all enabled sources (WearablesService.sync). */\n sync(options: { days: number; signal?: AbortSignal }): Promise<unknown>;\n log: { info(message: string): void; warn(message: string): void };\n /** Clock injection for tests. */\n now?: () => Date;\n}\n\nexport interface WearablesAutoSyncHandle {\n /** Run one scheduler tick now (first-run hook and test seam). */\n tick(): Promise<void>;\n /**\n * Stop the scheduler: clears the timer, aborts the in-flight sync's\n * provider fetches via AbortSignal, and resolves once the in-flight\n * tick has fully settled — after `await stop()` nothing is writing\n * or reindexing anymore. The handle is single-use; a restarted host\n * starts a fresh one.\n */\n stop(): Promise<void>;\n}\n\n/**\n * Start the periodic refresh. The first tick fires after one full\n * interval rather than at start — gateways on low-power hardware can\n * restart-loop during setup (issue #462), and an immediate fetch on\n * every restart would hammer provider APIs. Operators who want an\n * instant refresh run `wearables sync` (or call `tick()`).\n */\nexport function startWearablesAutoSync(\n settings: WearablesAutoSyncSettings,\n deps: WearablesAutoSyncDeps,\n): WearablesAutoSyncHandle {\n let inFlight: Promise<void> | null = null;\n let stopped = false;\n let lastDeepDate: string | null = null;\n // Aborting cancels the in-flight sync's provider fetches promptly on\n // shutdown — without it, a slow tick would keep writing/reindexing\n // after orchestrator.destroy() while a restarted host starts a\n // second scheduler (Kilo review on PR #1464).\n const abortController = new AbortController();\n\n const tick = async (): Promise<void> => {\n // Overlap guard: a slow provider or large deep window must never\n // stack a second sync on top of a running one. The skipped call\n // resolves immediately — it must NOT await the running tick, or a\n // caller holding both promises could deadlock itself.\n if (inFlight || stopped) return;\n const run = (async () => {\n try {\n const now = deps.now ? deps.now() : new Date();\n const today = dateInTimezone(now, settings.timezone ?? defaultTimezone());\n const deep = settings.deepDays > 0 && lastDeepDate !== today;\n const days = deep ? settings.deepDays : settings.days;\n await deps.sync({ days, signal: abortController.signal });\n // Mark the deep pass done only AFTER it succeeded — a failed\n // deep pass retries on the next tick instead of silently\n // waiting for tomorrow (CLAUDE.md rule 25's \"confirm before\n // consuming the one-shot\" shape).\n if (deep) lastDeepDate = today;\n deps.log.info(\n `wearables auto-sync: refreshed ${days}-day window${deep ? \" (daily deep pass)\" : \"\"}`,\n );\n } catch (err) {\n // An abort raised by stop() is intentional shutdown, not a\n // failure — warning about it would be noise in every clean\n // shutdown log.\n if (!stopped) {\n deps.log.warn(\n `wearables auto-sync failed: ${describeErrorForOperator(err)} — retrying on the next tick`,\n );\n }\n } finally {\n inFlight = null;\n }\n })();\n inFlight = run;\n await run;\n };\n\n const timer = setInterval(() => {\n void tick();\n }, settings.intervalMinutes * 60_000);\n timer.unref?.();\n\n return {\n tick,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n abortController.abort();\n // tick() never rejects (all paths caught), so this only waits.\n if (inFlight) await inFlight;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DO,SAAS,uBACd,UACA,MACyB;AACzB,MAAI,WAAiC;AACrC,MAAI,UAAU;AACd,MAAI,eAA8B;AAKlC,QAAM,kBAAkB,IAAI,gBAAgB;AAE5C,QAAM,OAAO,YAA2B;AAKtC,QAAI,YAAY,QAAS;AACzB,UAAM,OAAO,YAAY;AACvB,UAAI;AACF,cAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,oBAAI,KAAK;AAC7C,cAAM,QAAQ,eAAe,KAAK,SAAS,YAAY,gBAAgB,CAAC;AACxE,cAAM,OAAO,SAAS,WAAW,KAAK,iBAAiB;AACvD,cAAM,OAAO,OAAO,SAAS,WAAW,SAAS;AACjD,cAAM,KAAK,KAAK,EAAE,MAAM,QAAQ,gBAAgB,OAAO,CAAC;AAKxD,YAAI,KAAM,gBAAe;AACzB,aAAK,IAAI;AAAA,UACP,kCAAkC,IAAI,cAAc,OAAO,uBAAuB,EAAE;AAAA,QACtF;AAAA,MACF,SAAS,KAAK;AAIZ,YAAI,CAAC,SAAS;AACZ,eAAK,IAAI;AAAA,YACP,+BAA+B,yBAAyB,GAAG,CAAC;AAAA,UAC9D;AAAA,QACF;AAAA,MACF,UAAE;AACA,mBAAW;AAAA,MACb;AAAA,IACF,GAAG;AACH,eAAW;AACX,UAAM;AAAA,EACR;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,KAAK;AAAA,EACZ,GAAG,SAAS,kBAAkB,GAAM;AACpC,QAAM,QAAQ;AAEd,SAAO;AAAA,IACL;AAAA,IACA,MAAM,YAAY;AAChB,gBAAU;AACV,oBAAc,KAAK;AACnB,sBAAgB,MAAM;AAEtB,UAAI,SAAU,OAAM;AAAA,IACtB;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/wearables/auto-sync.ts"],"sourcesContent":["/**\n * Wearables auto-sync — in-process periodic transcript refresh.\n *\n * Every tick re-syncs a short rolling window ending today for ALL\n * enabled sources, so the current day's transcript keeps growing while\n * the wearable records and provider-side revisions of recent days flow\n * in without operator action. Once per local day the window deepens to\n * `autoSyncDeepDays` to pick up late uploads and provider reprocessing\n * further back (phones syncing hours later, re-diarized transcripts).\n *\n * Day fetches are unconditional within the window — existing day files\n * are always re-fetched and re-composed; the content-hash skip in the\n * pipeline keeps unchanged days write-free, so a tick on a quiet day\n * is read-only. The timer is unref'd: it never keeps a one-shot CLI\n * process alive, and long-lived hosts stop it via the returned handle.\n */\n\nimport { describeErrorForOperator } from \"./errors.js\";\nimport { dateInTimezone, defaultTimezone } from \"./pipeline.js\";\n\nexport interface WearablesAutoSyncSettings {\n /** Minutes between ticks. */\n intervalMinutes: number;\n /** Rolling window (days ending today) refreshed on a normal tick. */\n days: number;\n /**\n * Window for the once-per-local-day deep pass. 0 disables the deep\n * pass; otherwise must be >= `days` (validated at config parse).\n */\n deepDays: number;\n /** IANA timezone used to detect the local-day rollover. */\n timezone?: string;\n}\n\nexport interface WearablesAutoSyncDeps {\n /** Run a sync across all enabled sources (WearablesService.sync). */\n sync(options: { days: number; signal?: AbortSignal }): Promise<unknown>;\n log: { info(message: string): void; warn(message: string): void };\n /** Clock injection for tests. */\n now?: () => Date;\n}\n\nexport interface WearablesAutoSyncHandle {\n /** Run one scheduler tick now (first-run hook and test seam). */\n tick(): Promise<void>;\n /**\n * Stop the scheduler: clears the timer, aborts the in-flight sync's\n * provider fetches via AbortSignal, and resolves once the in-flight\n * tick has fully settled — after `await stop()` nothing is writing\n * or reindexing anymore. The handle is single-use; a restarted host\n * starts a fresh one.\n */\n stop(): Promise<void>;\n}\n\n/**\n * Start the periodic refresh. The first tick fires after one full\n * interval rather than at start — gateways on low-power hardware can\n * restart-loop during setup (issue #462), and an immediate fetch on\n * every restart would hammer provider APIs. Operators who want an\n * instant refresh run `wearables sync` (or call `tick()`).\n */\nexport function startWearablesAutoSync(\n settings: WearablesAutoSyncSettings,\n deps: WearablesAutoSyncDeps,\n): WearablesAutoSyncHandle {\n let inFlight: Promise<void> | null = null;\n let stopped = false;\n let lastDeepDate: string | null = null;\n // Aborting cancels the in-flight sync's provider fetches promptly on\n // shutdown — without it, a slow tick would keep writing/reindexing\n // after orchestrator.destroy() while a restarted host starts a\n // second scheduler (Kilo review on PR #1464).\n const abortController = new AbortController();\n\n const tick = async (): Promise<void> => {\n // Overlap guard: a slow provider or large deep window must never\n // stack a second sync on top of a running one. The skipped call\n // resolves immediately — it must NOT await the running tick, or a\n // caller holding both promises could deadlock itself.\n if (inFlight || stopped) return;\n const run = (async () => {\n try {\n const now = deps.now ? deps.now() : new Date();\n const today = dateInTimezone(now, settings.timezone ?? defaultTimezone());\n const deep = settings.deepDays > 0 && lastDeepDate !== today;\n const days = deep ? settings.deepDays : settings.days;\n await deps.sync({ days, signal: abortController.signal });\n // Mark the deep pass done only AFTER it succeeded — a failed\n // deep pass retries on the next tick instead of silently\n // waiting for tomorrow (CLAUDE.md rule 25's \"confirm before\n // consuming the one-shot\" shape).\n if (deep) lastDeepDate = today;\n deps.log.info(\n `wearables auto-sync: refreshed ${days}-day window${deep ? \" (daily deep pass)\" : \"\"}`,\n );\n } catch (err) {\n // An abort raised by stop() is intentional shutdown, not a\n // failure — warning about it would be noise in every clean\n // shutdown log.\n if (!stopped) {\n deps.log.warn(\n `wearables auto-sync failed: ${describeErrorForOperator(err)} — retrying on the next tick`,\n );\n }\n } finally {\n inFlight = null;\n }\n })();\n inFlight = run;\n await run;\n };\n\n const timer = setInterval(() => {\n void tick();\n }, settings.intervalMinutes * 60_000);\n timer.unref?.();\n\n return {\n tick,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n abortController.abort();\n // tick() never rejects (all paths caught), so this only waits.\n if (inFlight) await inFlight;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DO,SAAS,uBACd,UACA,MACyB;AACzB,MAAI,WAAiC;AACrC,MAAI,UAAU;AACd,MAAI,eAA8B;AAKlC,QAAM,kBAAkB,IAAI,gBAAgB;AAE5C,QAAM,OAAO,YAA2B;AAKtC,QAAI,YAAY,QAAS;AACzB,UAAM,OAAO,YAAY;AACvB,UAAI;AACF,cAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,oBAAI,KAAK;AAC7C,cAAM,QAAQ,eAAe,KAAK,SAAS,YAAY,gBAAgB,CAAC;AACxE,cAAM,OAAO,SAAS,WAAW,KAAK,iBAAiB;AACvD,cAAM,OAAO,OAAO,SAAS,WAAW,SAAS;AACjD,cAAM,KAAK,KAAK,EAAE,MAAM,QAAQ,gBAAgB,OAAO,CAAC;AAKxD,YAAI,KAAM,gBAAe;AACzB,aAAK,IAAI;AAAA,UACP,kCAAkC,IAAI,cAAc,OAAO,uBAAuB,EAAE;AAAA,QACtF;AAAA,MACF,SAAS,KAAK;AAIZ,YAAI,CAAC,SAAS;AACZ,eAAK,IAAI;AAAA,YACP,+BAA+B,yBAAyB,GAAG,CAAC;AAAA,UAC9D;AAAA,QACF;AAAA,MACF,UAAE;AACA,mBAAW;AAAA,MACb;AAAA,IACF,GAAG;AACH,eAAW;AACX,UAAM;AAAA,EACR;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,KAAK;AAAA,EACZ,GAAG,SAAS,kBAAkB,GAAM;AACpC,QAAM,QAAQ;AAEd,SAAO;AAAA,IACL;AAAA,IACA,MAAM,YAAY;AAChB,gBAAU;AACV,oBAAc,KAAK;AACnB,sBAAgB,MAAM;AAEtB,UAAI,SAAU,OAAM;AAAA,IACtB;AAAA,EACF;AACF;","names":[]}
package/dist/briefing.js CHANGED
@@ -17,13 +17,13 @@ import {
17
17
  renderBriefingMarkdown,
18
18
  resolveBriefingSaveDir,
19
19
  validateBriefingFormat
20
- } from "./chunk-AYVCKGA6.js";
21
- import "./chunk-FHKXVTM5.js";
22
- import "./chunk-46WM6JX2.js";
20
+ } from "./chunk-YTXNDEUS.js";
21
+ import "./chunk-Q5XKKDFQ.js";
23
22
  import "./chunk-UHVXE24Y.js";
23
+ import "./chunk-46WM6JX2.js";
24
24
  import "./chunk-SXIMQLGV.js";
25
- import "./chunk-GF7RQWXC.js";
26
- import "./chunk-GG4DN63W.js";
25
+ import "./chunk-AJRJDXYR.js";
26
+ import "./chunk-62Y5AGCM.js";
27
27
  import "./chunk-OQIRBGUU.js";
28
28
  import "./chunk-VANZKHTN.js";
29
29
  import "./chunk-CYEPCZN5.js";
@@ -32,15 +32,15 @@ import "./chunk-VYISFWVX.js";
32
32
  import "./chunk-W7IGLX4G.js";
33
33
  import "./chunk-6KTXE6A3.js";
34
34
  import "./chunk-GUMZC2BO.js";
35
- import "./chunk-LEPOP46W.js";
35
+ import "./chunk-227UFSEQ.js";
36
+ import "./chunk-ET356KSB.js";
36
37
  import "./chunk-72A4L5JJ.js";
37
38
  import "./chunk-A7Q43EUZ.js";
38
- import "./chunk-ET356KSB.js";
39
39
  import "./chunk-S2V7RUCL.js";
40
40
  import "./chunk-AR253JBM.js";
41
+ import "./chunk-SCU65EZI.js";
41
42
  import "./chunk-PO7NXBG2.js";
42
43
  import "./chunk-S2HLHAZ4.js";
43
- import "./chunk-SCU65EZI.js";
44
44
  import "./chunk-DM2T26WE.js";
45
45
  import "./chunk-LDXUBPMO.js";
46
46
  import "./chunk-UG6VXIOK.js";
@@ -48,16 +48,16 @@ import "./chunk-AAD2ZS6P.js";
48
48
  import "./chunk-MUJ4QFUQ.js";
49
49
  import "./chunk-LCU5R6TQ.js";
50
50
  import "./chunk-BT7NVCML.js";
51
- import "./chunk-YXZG5TVN.js";
52
51
  import "./chunk-3ONXXHQO.js";
52
+ import "./chunk-YXZG5TVN.js";
53
53
  import "./chunk-5GINB5LC.js";
54
- import "./chunk-G7D6GZ5J.js";
55
54
  import "./chunk-UFKPQBXH.js";
56
55
  import "./chunk-XCB6QDL6.js";
57
56
  import "./chunk-RBOJCG4T.js";
58
57
  import "./chunk-ZVPVTPGI.js";
59
58
  import "./chunk-5WITETWU.js";
60
59
  import "./chunk-6CIAGZ6X.js";
60
+ import "./chunk-G7D6GZ5J.js";
61
61
  import "./chunk-VYEPACWY.js";
62
62
  import "./chunk-URS5GSM7.js";
63
63
  import "./chunk-ZLQ37WJX.js";
@@ -57,6 +57,7 @@ interface CorrectionMemory {
57
57
  * regressions surface via the contamination suite.
58
58
  */
59
59
  declare function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]>;
60
+ declare const CLUSTER_PROMPT = "You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\nOutput language: write facts, profile updates, entity names and aliases, tags, questions, and any rewritten or merged memory content in the source language of the conversation or input memories. Never translate into English or another language unless the user explicitly asked for a translation.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}";
60
61
  declare function synthesizeCalibrationRules(corrections: CorrectionMemory[], llm: FallbackLlmClient, existingRules: CalibrationRule[], agentId?: string, modelChain?: AgentPersonaModelConfig): Promise<CalibrationRule[]>;
61
62
  /**
62
63
  * Build a recall section from calibration rules relevant to the current query.
@@ -98,4 +99,4 @@ declare function runCalibrationIfEnabled(options: {
98
99
  */
99
100
  declare function getCalibrationRulesForRecall(memoryDir: string): Promise<CalibrationRule[]>;
100
101
 
101
- export { type CalibrationIndex, type CalibrationRule, type CorrectionMemory, buildCalibrationRecallSection, getCalibrationRulesForRecall, readCalibrationCorrections, readCalibrationIndex, runCalibrationConsolidation, runCalibrationIfEnabled, synthesizeCalibrationRules };
102
+ export { CLUSTER_PROMPT, type CalibrationIndex, type CalibrationRule, type CorrectionMemory, buildCalibrationRecallSection, getCalibrationRulesForRecall, readCalibrationCorrections, readCalibrationIndex, runCalibrationConsolidation, runCalibrationIfEnabled, synthesizeCalibrationRules };
@@ -1,3 +1,7 @@
1
+ import {
2
+ OUTPUT_LANGUAGE_POLICY
3
+ } from "./chunk-JG22O53B.js";
4
+ import "./chunk-QW27DOHG.js";
1
5
  import {
2
6
  FallbackLlmClient
3
7
  } from "./chunk-UW5NPZJ2.js";
@@ -6,6 +10,7 @@ import "./chunk-L2EXJQJP.js";
6
10
  import "./chunk-45GF7Y3V.js";
7
11
  import "./chunk-RGMVMVMF.js";
8
12
  import "./chunk-N7RWREIQ.js";
13
+ import "./chunk-JUOZ62Y7.js";
9
14
  import "./chunk-EYIEWJNI.js";
10
15
  import "./chunk-JUC24CTX.js";
11
16
  import {
@@ -126,6 +131,7 @@ A CalibrationRule describes:
126
131
  - ruleType: One of "model_tendency", "user_expectation", "scope_boundary", "verification_required"
127
132
 
128
133
  Focus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.
134
+ ${OUTPUT_LANGUAGE_POLICY}
129
135
 
130
136
  Output valid JSON only:
131
137
  {
@@ -277,6 +283,7 @@ async function getCalibrationRulesForRecall(memoryDir) {
277
283
  return index.rules;
278
284
  }
279
285
  export {
286
+ CLUSTER_PROMPT,
280
287
  buildCalibrationRecallSection,
281
288
  getCalibrationRulesForRecall,
282
289
  readCalibrationCorrections,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile } from \"./types.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { log } from \"./logger.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n index.updatedAt = new Date().toISOString();\n await writeFile(calibrationIndexPath(memoryDir), JSON.stringify(index, null, 2), \"utf8\");\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\nconst CALIBRATION_RULE_TYPES = new Set([\n \"model_tendency\",\n \"user_expectation\",\n \"scope_boundary\",\n \"verification_required\",\n]);\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidenceIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nconst CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: FallbackLlmClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n modelChain?: AgentPersonaModelConfig,\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText = existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n { role: \"user\", content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}` },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId, modelChain },\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n return rawRules\n .map((r: unknown): CalibrationRule | undefined => {\n if (!r || typeof r !== \"object\" || Array.isArray(r)) return undefined;\n const raw = r as Record<string, unknown>;\n const ruleType = nonEmptyString(raw.ruleType);\n const condition = nonEmptyString(raw.condition);\n const modelTendency = nonEmptyString(raw.modelTendency);\n const calibration = nonEmptyString(raw.calibration);\n const confidence = parseConfidence(raw.confidence);\n if (\n !ruleType ||\n !CALIBRATION_RULE_TYPES.has(ruleType) ||\n !condition ||\n !modelTendency ||\n !calibration ||\n confidence === undefined\n ) {\n return undefined;\n }\n const evidenceCorrectionIds = parseEvidenceIds(raw.evidenceIds);\n return {\n id: `cal-${createHash(\"sha256\").update(condition + calibration).digest(\"hex\").slice(0, 12)}`,\n ruleType: ruleType as CalibrationRule[\"ruleType\"],\n condition,\n modelTendency,\n userExpectation: nonEmptyString(raw.userExpectation) ?? \"\",\n calibration,\n confidence,\n evidenceCount: evidenceCorrectionIds.length,\n evidenceCorrectionIds,\n createdAt: now,\n lastReinforcedAt: now,\n };\n })\n .filter((rule): rule is CalibrationRule => !!rule);\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Uses the LLM to select which rules apply to the current context.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n): string | null {\n if (rules.length === 0) return null;\n\n // Simple relevance: include all rules (they're already filtered to this user)\n // In production, could use embedding similarity to filter\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of rules) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n if (!llm.isAvailable({ agentId: options.gatewayAgentId, modelChain: options.modelChain })) {\n log.debug(\"[calibration] no LLM available — skipping consolidation\");\n return [];\n }\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.debug(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n\n const newRules = await synthesizeCalibrationRules(corrections, llm, existingIndex.rules, options.gatewayAgentId, options.modelChain);\n if (newRules.length === 0) {\n log.debug(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, {\n rules: allRules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: corrections.length,\n });\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(`[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n gatewayAgentId: options.gatewayAgentId,\n modelChain: options.modelChain,\n workspaceDir: options.workspaceDir,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,OAAO,UAAU,iBAAiB;AA+B3C,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtF,0BAA0B,OAAO,IAAI,6BAA6B,WAAW,IAAI,2BAA2B;AAAA,IAC9G;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO,CAAC,GAAG,YAAW,oBAAI,KAAK,GAAE,YAAY,GAAG,0BAA0B,EAAE;AAAA,EACvF;AACF;AAEA,eAAe,sBAAsB,WAAmB,OAAwC;AAC9F,QAAM,MAAM,eAAe,SAAS;AACpC,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACpC,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,QAAM,UAAU,qBAAqB,SAA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,gBAAQ,IAAI,KAAK,IAAI,IAAI;AAAA,MAC3B;AAAA,IACF;AAEA,UAAM,WAAW,CAAC,GAAG,QAAQ,OAAO,CAAC;AACrC,UAAM,sBAAsB,QAAQ,WAAW;AAAA,MAC7C,OAAO;AAAA,MACP,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,0BAA0B,YAAY;AAAA,IACxC,CAAC;AAED,QAAI,MAAM,6BAA6B,SAAS,MAAM,iBAAiB,SAAS,MAAM,QAAQ;AAC9F,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,KAAK,mDAAmD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACpH,WAAO,CAAC;AAAA,EACV;AACF;AASA,eAAsB,wBAAwB,SAOf;AAC7B,MAAI,CAAC,QAAQ,oBAAoB;AAC/B,WAAO,CAAC;AAAA,EACV;AACA,SAAO,4BAA4B;AAAA,IACjC,WAAW,QAAQ;AAAA,IACnB,eAAe,QAAQ;AAAA,IACvB,gBAAgB,QAAQ;AAAA,IACxB,YAAY,QAAQ;AAAA,IACpB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;AAMA,eAAsB,6BACpB,WAC4B;AAC5B,QAAM,QAAQ,MAAM,qBAAqB,SAAS;AAClD,SAAO,MAAM;AACf;","names":[]}
1
+ {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile } from \"./types.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { log } from \"./logger.js\";\nimport { OUTPUT_LANGUAGE_POLICY } from \"./extraction-prompt.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n index.updatedAt = new Date().toISOString();\n await writeFile(calibrationIndexPath(memoryDir), JSON.stringify(index, null, 2), \"utf8\");\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\nconst CALIBRATION_RULE_TYPES = new Set([\n \"model_tendency\",\n \"user_expectation\",\n \"scope_boundary\",\n \"verification_required\",\n]);\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidenceIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nexport const CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n${OUTPUT_LANGUAGE_POLICY}\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: FallbackLlmClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n modelChain?: AgentPersonaModelConfig,\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText = existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n { role: \"user\", content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}` },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId, modelChain },\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n return rawRules\n .map((r: unknown): CalibrationRule | undefined => {\n if (!r || typeof r !== \"object\" || Array.isArray(r)) return undefined;\n const raw = r as Record<string, unknown>;\n const ruleType = nonEmptyString(raw.ruleType);\n const condition = nonEmptyString(raw.condition);\n const modelTendency = nonEmptyString(raw.modelTendency);\n const calibration = nonEmptyString(raw.calibration);\n const confidence = parseConfidence(raw.confidence);\n if (\n !ruleType ||\n !CALIBRATION_RULE_TYPES.has(ruleType) ||\n !condition ||\n !modelTendency ||\n !calibration ||\n confidence === undefined\n ) {\n return undefined;\n }\n const evidenceCorrectionIds = parseEvidenceIds(raw.evidenceIds);\n return {\n id: `cal-${createHash(\"sha256\").update(condition + calibration).digest(\"hex\").slice(0, 12)}`,\n ruleType: ruleType as CalibrationRule[\"ruleType\"],\n condition,\n modelTendency,\n userExpectation: nonEmptyString(raw.userExpectation) ?? \"\",\n calibration,\n confidence,\n evidenceCount: evidenceCorrectionIds.length,\n evidenceCorrectionIds,\n createdAt: now,\n lastReinforcedAt: now,\n };\n })\n .filter((rule): rule is CalibrationRule => !!rule);\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Uses the LLM to select which rules apply to the current context.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n): string | null {\n if (rules.length === 0) return null;\n\n // Simple relevance: include all rules (they're already filtered to this user)\n // In production, could use embedding similarity to filter\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of rules) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n if (!llm.isAvailable({ agentId: options.gatewayAgentId, modelChain: options.modelChain })) {\n log.debug(\"[calibration] no LLM available — skipping consolidation\");\n return [];\n }\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.debug(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n\n const newRules = await synthesizeCalibrationRules(corrections, llm, existingIndex.rules, options.gatewayAgentId, options.modelChain);\n if (newRules.length === 0) {\n log.debug(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, {\n rules: allRules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: corrections.length,\n });\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(`[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n gatewayAgentId: options.gatewayAgentId,\n modelChain: options.modelChain,\n workspaceDir: options.workspaceDir,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,OAAO,UAAU,iBAAiB;AAgC3C,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtF,0BAA0B,OAAO,IAAI,6BAA6B,WAAW,IAAI,2BAA2B;AAAA,IAC9G;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO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+ } from "./chunk-42TIIO2M.js";
8
8
  import "./chunk-5JMAGU26.js";
9
9
  import "./chunk-B7RWBZXW.js";
10
10
  import {
11
11
  runPostConsolidationMaterialize
12
- } from "./chunk-YEQCMA5L.js";
12
+ } from "./chunk-BOSIHHOH.js";
13
13
  import "./chunk-RDFF2NAU.js";
14
14
  import {
15
15
  resolveCausalTrajectoryStoreDir
16
16
  } from "./chunk-GPFZFCRN.js";
17
- import "./chunk-FHKXVTM5.js";
18
- import "./chunk-46WM6JX2.js";
17
+ import "./chunk-Q5XKKDFQ.js";
19
18
  import "./chunk-UHVXE24Y.js";
19
+ import "./chunk-46WM6JX2.js";
20
20
  import "./chunk-SXIMQLGV.js";
21
- import "./chunk-GF7RQWXC.js";
22
- import "./chunk-GG4DN63W.js";
21
+ import "./chunk-AJRJDXYR.js";
22
+ import "./chunk-62Y5AGCM.js";
23
23
  import "./chunk-OQIRBGUU.js";
24
24
  import "./chunk-VANZKHTN.js";
25
25
  import "./chunk-CYEPCZN5.js";
@@ -28,15 +28,15 @@ import "./chunk-VYISFWVX.js";
28
28
  import "./chunk-W7IGLX4G.js";
29
29
  import "./chunk-6KTXE6A3.js";
30
30
  import "./chunk-GUMZC2BO.js";
31
- import "./chunk-LEPOP46W.js";
31
+ import "./chunk-227UFSEQ.js";
32
+ import "./chunk-ET356KSB.js";
32
33
  import "./chunk-72A4L5JJ.js";
33
34
  import "./chunk-A7Q43EUZ.js";
34
- import "./chunk-ET356KSB.js";
35
35
  import "./chunk-S2V7RUCL.js";
36
36
  import "./chunk-AR253JBM.js";
37
+ import "./chunk-SCU65EZI.js";
37
38
  import "./chunk-PO7NXBG2.js";
38
39
  import "./chunk-S2HLHAZ4.js";
39
- import "./chunk-SCU65EZI.js";
40
40
  import "./chunk-DM2T26WE.js";
41
41
  import "./chunk-LDXUBPMO.js";
42
42
  import "./chunk-UG6VXIOK.js";
@@ -44,16 +44,16 @@ import "./chunk-AAD2ZS6P.js";
44
44
  import "./chunk-MUJ4QFUQ.js";
45
45
  import "./chunk-LCU5R6TQ.js";
46
46
  import "./chunk-BT7NVCML.js";
47
- import "./chunk-YXZG5TVN.js";
48
47
  import "./chunk-3ONXXHQO.js";
48
+ import "./chunk-YXZG5TVN.js";
49
49
  import "./chunk-5GINB5LC.js";
50
- import "./chunk-G7D6GZ5J.js";
51
50
  import "./chunk-UFKPQBXH.js";
52
51
  import "./chunk-XCB6QDL6.js";
53
52
  import "./chunk-RBOJCG4T.js";
54
53
  import "./chunk-ZVPVTPGI.js";
55
54
  import "./chunk-5WITETWU.js";
56
55
  import "./chunk-6CIAGZ6X.js";
56
+ import "./chunk-G7D6GZ5J.js";
57
57
  import "./chunk-VYEPACWY.js";
58
58
  import "./chunk-URS5GSM7.js";
59
59
  import "./chunk-ZLQ37WJX.js";
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Census field acceptance shared by offline-sync and the reconcile planner
3
+ * (issue #2477). Both surfaces parse untrusted peer censuses and must accept
4
+ * and reject exactly the same values; when these checks lived as two copies
5
+ * they could drift silently and break convergence. Each surface keeps only a
6
+ * thin wrapper that picks its own error type and message.
7
+ */
8
+ /** 64-character sha256 hex, either case; the canonical stored form is lowercase. */
9
+ declare const SHA256_HEX_PATTERN: RegExp;
10
+ /** Largest `mtimeMs` a census may carry: `new Date(ms)` must stay a valid Date. */
11
+ declare const CENSUS_MAX_MTIME_MS = 8640000000000000;
12
+ declare function isSha256Hex(value: unknown): value is string;
13
+ /**
14
+ * Fractional values are valid: `fs.stat()` reports sub-millisecond mtimes on
15
+ * common filesystems, so this deliberately does not require an integer.
16
+ */
17
+ declare function isCensusMtimeMs(value: unknown): value is number;
18
+
19
+ export { CENSUS_MAX_MTIME_MS, SHA256_HEX_PATTERN, isCensusMtimeMs, isSha256Hex };
@@ -0,0 +1,14 @@
1
+ import {
2
+ CENSUS_MAX_MTIME_MS,
3
+ SHA256_HEX_PATTERN,
4
+ isCensusMtimeMs,
5
+ isSha256Hex
6
+ } from "./chunk-LQWOFU6L.js";
7
+ import "./chunk-PZ5AY32C.js";
8
+ export {
9
+ CENSUS_MAX_MTIME_MS,
10
+ SHA256_HEX_PATTERN,
11
+ isCensusMtimeMs,
12
+ isSha256Hex
13
+ };
14
+ //# sourceMappingURL=census-validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,3 +1,6 @@
1
+ import {
2
+ failOpenFaissHealth
3
+ } from "./chunk-ET356KSB.js";
1
4
  import {
2
5
  rebuildConversationChunksFailOpen,
3
6
  upsertConversationChunksFailOpen
@@ -6,9 +9,6 @@ import {
6
9
  searchConversationIndex,
7
10
  searchConversationIndexFaissFailOpen
8
11
  } from "./chunk-A7Q43EUZ.js";
9
- import {
10
- failOpenFaissHealth
11
- } from "./chunk-ET356KSB.js";
12
12
 
13
13
  // src/conversation-index/backend.ts
14
14
  function createConversationIndexBackend(options) {
@@ -235,4 +235,4 @@ function createFaissBackend(getFaiss) {
235
235
  export {
236
236
  createConversationIndexBackend
237
237
  };
238
- //# sourceMappingURL=chunk-LEPOP46W.js.map
238
+ //# sourceMappingURL=chunk-227UFSEQ.js.map
@@ -7,15 +7,20 @@ import {
7
7
  sha256Bytes,
8
8
  validateArchiveRelativePath
9
9
  } from "./chunk-GCGJW34D.js";
10
- import {
11
- DEFAULT_OFFLINE_SYNC_EXCLUDE_GLOBS
12
- } from "./chunk-AREGMX2J.js";
13
10
  import {
14
11
  isEncryptedOfflineSyncFile,
15
12
  readPlainOfflineSyncFileChunk,
16
13
  sha256OfflineSyncFile,
17
14
  shouldExcludeOfflineSyncFile
18
15
  } from "./chunk-LC2BDILZ.js";
16
+ import {
17
+ DEFAULT_OFFLINE_SYNC_EXCLUDE_GLOBS
18
+ } from "./chunk-AREGMX2J.js";
19
+ import {
20
+ CENSUS_MAX_MTIME_MS,
21
+ isCensusMtimeMs,
22
+ isSha256Hex
23
+ } from "./chunk-LQWOFU6L.js";
19
24
  import {
20
25
  parseFlexibleIsoTimestamp
21
26
  } from "./chunk-P7FMDTKL.js";
@@ -43,7 +48,7 @@ var OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES = 64 * 1024 * 1024;
43
48
  var OFFLINE_SYNC_FILE_CONTENT_TRANSFER_CHUNK_BYTES = 8 * 1024 * 1024;
44
49
  var OFFLINE_SYNC_APPLY_MAX_BODY_BYTES = 16 * 1024 * 1024;
45
50
  var OFFLINE_SYNC_SNAPSHOT_BASE_MAX_BODY_BYTES = 64 * 1024 * 1024;
46
- var OFFLINE_SYNC_MAX_MTIME_MS = 864e13;
51
+ var OFFLINE_SYNC_MAX_MTIME_MS = CENSUS_MAX_MTIME_MS;
47
52
  var SYNC_INTERNAL_DIR = ".offline-sync";
48
53
  var OFFLINE_SYNC_UPLOAD_STAGING_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
49
54
  var OFFLINE_SYNC_FAST_BASE_MTIME_TOLERANCE_MS = 1e3;
@@ -105,7 +110,7 @@ function compareByPath(left, right) {
105
110
  return left.path.localeCompare(right.path);
106
111
  }
107
112
  function assertSha256(value, field) {
108
- if (typeof value !== "string" || !/^[a-f0-9]{64}$/i.test(value)) {
113
+ if (!isSha256Hex(value)) {
109
114
  throw new Error(`${field} must be a 64-character sha256 hex string`);
110
115
  }
111
116
  return value.toLowerCase();
@@ -124,7 +129,7 @@ function assertNonNegativeFinite(value, field) {
124
129
  }
125
130
  function assertOfflineSyncMtimeMs(value, field) {
126
131
  const mtimeMs = assertNonNegativeFinite(value, field);
127
- if (mtimeMs > OFFLINE_SYNC_MAX_MTIME_MS) {
132
+ if (!isCensusMtimeMs(mtimeMs)) {
128
133
  throw new Error(`${field} must be within JavaScript Date range`);
129
134
  }
130
135
  return mtimeMs;
@@ -1889,4 +1894,4 @@ export {
1889
1894
  normalizeOfflineSyncState,
1890
1895
  fileStatesFromSnapshot
1891
1896
  };
1892
- //# sourceMappingURL=chunk-Z4N7SVVF.js.map
1897
+ //# sourceMappingURL=chunk-2L7DKNVE.js.map