@remnic/core 9.69.38 → 9.69.40

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 (656) hide show
  1. package/dist/access-admin-ops-surface.d.ts +16 -14
  2. package/dist/access-admin-ops-surface.js +39 -39
  3. package/dist/access-authorization-probe.d.ts +16 -14
  4. package/dist/access-authorization-probe.js +40 -40
  5. package/dist/access-boundary.d.ts +16 -14
  6. package/dist/access-boundary.js +39 -39
  7. package/dist/access-cli.js +107 -105
  8. package/dist/access-cli.js.map +1 -1
  9. package/dist/access-coding-context-resolution.d.ts +1 -1
  10. package/dist/access-extraction-force-flush.d.ts +16 -14
  11. package/dist/access-extraction-force-flush.js +39 -39
  12. package/dist/access-health-types.d.ts +1 -1
  13. package/dist/access-http-briefing.d.ts +16 -14
  14. package/dist/access-http-briefing.js +40 -40
  15. package/dist/access-http-lcm-compaction.d.ts +16 -14
  16. package/dist/access-http-lifecycle-flush.d.ts +16 -14
  17. package/dist/access-http-offline-stream.d.ts +16 -14
  18. package/dist/access-http-query.d.ts +2 -2
  19. package/dist/access-http-query.js +41 -41
  20. package/dist/access-http.d.ts +17 -15
  21. package/dist/access-http.js +58 -58
  22. package/dist/access-identity-continuity-surface.d.ts +13 -12
  23. package/dist/access-identity-continuity-surface.js +39 -39
  24. package/dist/access-lcm-surface.d.ts +16 -14
  25. package/dist/access-lcm-surface.js +39 -39
  26. package/dist/access-mcp.d.ts +16 -14
  27. package/dist/access-mcp.js +47 -47
  28. package/dist/access-memory-search-fanout.d.ts +2 -2
  29. package/dist/{access-namespace-preflight-DY4z6L5X.d.ts → access-namespace-preflight-CKBumJ8W.d.ts} +1 -1
  30. package/dist/access-namespace-preflight.d.ts +3 -3
  31. package/dist/access-namespace-preflight.js +39 -39
  32. package/dist/access-observe-transcript.d.ts +13 -12
  33. package/dist/access-observe-write-category.d.ts +1 -1
  34. package/dist/access-observe-write-category.js +2 -2
  35. package/dist/access-observe-write-surface.d.ts +16 -14
  36. package/dist/access-observe-write-surface.js +39 -39
  37. package/dist/access-offline-manifest.d.ts +37 -13
  38. package/dist/access-offline-manifest.js +7 -3
  39. package/dist/access-operations-batch.js +41 -41
  40. package/dist/access-operations.d.ts +16 -14
  41. package/dist/access-operations.js +46 -46
  42. package/dist/access-recall-concurrency.d.ts +16 -14
  43. package/dist/access-recall-concurrency.js +39 -39
  44. package/dist/access-recall-response.d.ts +16 -14
  45. package/dist/access-recall-response.js +39 -39
  46. package/dist/access-recall-surface.d.ts +16 -14
  47. package/dist/access-recall-surface.js +39 -39
  48. package/dist/access-schema.d.ts +5 -3
  49. package/dist/access-schema.js +1 -1
  50. package/dist/{access-service-gBcdRUHY.d.ts → access-service-DJ3qogNt.d.ts} +8 -8
  51. package/dist/access-service-helpers.d.ts +16 -14
  52. package/dist/access-service.d.ts +16 -14
  53. package/dist/access-service.js +39 -39
  54. package/dist/access-surface-catalog.d.ts +16 -14
  55. package/dist/access-surface-catalog.js +41 -41
  56. package/dist/access-wearables-meetings-surface.d.ts +6 -5
  57. package/dist/action-confidence.d.ts +1 -1
  58. package/dist/active-memory-bridge.d.ts +1 -1
  59. package/dist/active-recall.d.ts +1 -1
  60. package/dist/active-recall.js +6 -5
  61. package/dist/active-recall.js.map +1 -1
  62. package/dist/activity/digest.d.ts +1 -1
  63. package/dist/adapters/index.js +4 -4
  64. package/dist/adapters/registry.js +2 -2
  65. package/dist/ambient-provenance.d.ts +1 -1
  66. package/dist/artifact-search.d.ts +1 -1
  67. package/dist/{auto-sync-RP4C6ZPF.js → auto-sync-D6BAPIJV.js} +5 -5
  68. package/dist/background-generation-config.d.ts +1 -1
  69. package/dist/background-generation-config.js +3 -1
  70. package/dist/background-generation.d.ts +1 -1
  71. package/dist/behavior-learner.d.ts +1 -1
  72. package/dist/behavior-signals.d.ts +1 -1
  73. package/dist/bootstrap.d.ts +13 -12
  74. package/dist/briefing-window.d.ts +2 -2
  75. package/dist/briefing.d.ts +2 -2
  76. package/dist/briefing.js +16 -16
  77. package/dist/buffer-surprise-report.d.ts +1 -1
  78. package/dist/buffer-turn-helpers.d.ts +1 -1
  79. package/dist/buffer.d.ts +2 -2
  80. package/dist/buffer.js +5 -5
  81. package/dist/bulk-import/index.d.ts +3 -3
  82. package/dist/calibration.d.ts +3 -2
  83. package/dist/calibration.js +2 -2
  84. package/dist/capabilities.d.ts +1 -1
  85. package/dist/{catalog-CW87xGx8.d.ts → catalog-BHXkBVhg.d.ts} +1 -1
  86. package/dist/causal-behavior.d.ts +1 -1
  87. package/dist/causal-consolidation.d.ts +1 -1
  88. package/dist/causal-consolidation.js +20 -19
  89. package/dist/causal-consolidation.js.map +1 -1
  90. package/dist/causal-trajectory-graph.d.ts +1 -1
  91. package/dist/{chunk-B36GUU6T.js → chunk-23HFXQ5J.js} +36 -3
  92. package/dist/chunk-23HFXQ5J.js.map +1 -0
  93. package/dist/{chunk-YFTNZMGR.js → chunk-27NO2KVB.js} +31 -8
  94. package/dist/chunk-27NO2KVB.js.map +1 -0
  95. package/dist/{chunk-T32B72QX.js → chunk-2SKMZUOW.js} +2 -2
  96. package/dist/{chunk-VHOSM5G4.js → chunk-2SNCQHJZ.js} +2 -2
  97. package/dist/{chunk-VV4ZVUE6.js → chunk-3QEVOQF5.js} +2 -2
  98. package/dist/{chunk-3N3PBBEH.js → chunk-3XPN7AVY.js} +2 -2
  99. package/dist/{chunk-XN6XT6GR.js → chunk-46Z3VGWF.js} +2 -2
  100. package/dist/{chunk-2PTNJTBE.js → chunk-4CMXI55L.js} +2 -2
  101. package/dist/{chunk-2MT4ADLQ.js → chunk-5LYSEZOF.js} +18 -9
  102. package/dist/chunk-5LYSEZOF.js.map +1 -0
  103. package/dist/{chunk-XWLLFKHM.js → chunk-62HFZNCJ.js} +19 -12
  104. package/dist/chunk-62HFZNCJ.js.map +1 -0
  105. package/dist/{chunk-VELCIWJZ.js → chunk-6L2II3KS.js} +22 -11
  106. package/dist/chunk-6L2II3KS.js.map +1 -0
  107. package/dist/{chunk-A6CKMIPK.js → chunk-7D6SER6A.js} +8 -8
  108. package/dist/{chunk-4B3HBIFX.js → chunk-7Z54NXVS.js} +2 -2
  109. package/dist/{chunk-X2NFFBTO.js → chunk-A7GQBJP5.js} +4 -4
  110. package/dist/{chunk-ACY4ZPF7.js → chunk-AEOOGXMQ.js} +10 -5
  111. package/dist/chunk-AEOOGXMQ.js.map +1 -0
  112. package/dist/{chunk-NWMUSKED.js → chunk-BGRTZOJB.js} +3 -3
  113. package/dist/{chunk-ZEGL7YCC.js → chunk-BXIJSPCL.js} +2 -2
  114. package/dist/{chunk-MLWMR2GE.js → chunk-BYQX4IOG.js} +2 -2
  115. package/dist/{chunk-ULDBGA5W.js → chunk-C5R73BON.js} +2 -2
  116. package/dist/{chunk-BD7JTBYP.js → chunk-D7MAYFQP.js} +2 -2
  117. package/dist/{chunk-V6G2PSXA.js → chunk-DAZANIYU.js} +251 -297
  118. package/dist/chunk-DAZANIYU.js.map +1 -0
  119. package/dist/{chunk-BRZWWUCJ.js → chunk-DFVSJFHK.js} +2 -2
  120. package/dist/{chunk-DPMTLJCT.js → chunk-ES5BUPYB.js} +2 -2
  121. package/dist/{chunk-MVAQ2WM3.js → chunk-G2XZFGYN.js} +6 -2
  122. package/dist/chunk-G2XZFGYN.js.map +1 -0
  123. package/dist/{chunk-TNSCIPBQ.js → chunk-G6NQ3L4T.js} +2 -2
  124. package/dist/{chunk-5N4MZLEH.js → chunk-GO5LOHCD.js} +2 -2
  125. package/dist/{chunk-AECJY3GJ.js → chunk-GSSDHAYH.js} +2 -2
  126. package/dist/{chunk-JA2QJOAX.js → chunk-HJUP3K6L.js} +2 -2
  127. package/dist/{chunk-ZKZFFWLV.js → chunk-ICNJ6J46.js} +2 -2
  128. package/dist/{chunk-6EHM2AV7.js → chunk-IMBQFHRV.js} +2 -2
  129. package/dist/{chunk-6PRY6CLC.js → chunk-IOPIGX7Y.js} +1 -1
  130. package/dist/{chunk-TRHBQVVO.js → chunk-IS2IDFJP.js} +14 -14
  131. package/dist/{chunk-R4VAUNNC.js → chunk-J4WGTN2N.js} +2 -2
  132. package/dist/{chunk-JPOX2AJB.js → chunk-J7FVMLBR.js} +2 -2
  133. package/dist/{chunk-BYZKLEWG.js → chunk-JAJIMTFB.js} +6 -6
  134. package/dist/{chunk-OKO57IXB.js → chunk-JOP7W24J.js} +11 -11
  135. package/dist/{chunk-YUW66UAH.js → chunk-JUDT33RX.js} +2 -2
  136. package/dist/{chunk-QHT7MOUF.js → chunk-K4A6UVPB.js} +22 -11
  137. package/dist/chunk-K4A6UVPB.js.map +1 -0
  138. package/dist/{chunk-UQNYPK7G.js → chunk-K4JKAXMO.js} +2 -2
  139. package/dist/{chunk-BV4ZKIZH.js → chunk-K75A5XWU.js} +3 -2
  140. package/dist/{chunk-3CBI2ZSA.js → chunk-KG2OOAFF.js} +20 -12
  141. package/dist/chunk-KG2OOAFF.js.map +1 -0
  142. package/dist/{chunk-M6HBPLBA.js → chunk-KOTG3RXE.js} +2 -2
  143. package/dist/{chunk-CWTCMZGE.js → chunk-KTOXQMW3.js} +119 -3
  144. package/dist/chunk-KTOXQMW3.js.map +1 -0
  145. package/dist/{chunk-OB3XMWX5.js → chunk-KVO2BTA4.js} +2 -2
  146. package/dist/{chunk-CBFYCDYO.js → chunk-KY236SP5.js} +3 -3
  147. package/dist/{chunk-4BCHFSC7.js → chunk-LFVZD5EC.js} +3 -3
  148. package/dist/{chunk-GGAXFTNH.js → chunk-LKFVVN7R.js} +2 -2
  149. package/dist/{chunk-IYKZJVL5.js → chunk-MDIEES23.js} +1 -1
  150. package/dist/chunk-MDIEES23.js.map +1 -0
  151. package/dist/{chunk-4RX5O34R.js → chunk-MJC7UKH7.js} +2 -2
  152. package/dist/{chunk-7S53BPTU.js → chunk-MVG3KXON.js} +69 -22
  153. package/dist/chunk-MVG3KXON.js.map +1 -0
  154. package/dist/chunk-NETQXOPY.js +221 -0
  155. package/dist/chunk-NETQXOPY.js.map +1 -0
  156. package/dist/{chunk-UZZ7SQT3.js → chunk-NVVZPBKI.js} +2 -2
  157. package/dist/{chunk-BLDBT6HZ.js → chunk-PJRKLB4Z.js} +18 -2
  158. package/dist/chunk-PJRKLB4Z.js.map +1 -0
  159. package/dist/{chunk-TTSJ7WUC.js → chunk-PKUJNICO.js} +2 -2
  160. package/dist/{chunk-QMWKENNK.js → chunk-Q4AUIFUA.js} +4 -4
  161. package/dist/{chunk-G43PMSME.js → chunk-QE6YVNP5.js} +7 -7
  162. package/dist/{chunk-WKDFJXW5.js → chunk-QM2SPLKQ.js} +1 -1
  163. package/dist/chunk-QM2SPLKQ.js.map +1 -0
  164. package/dist/{chunk-GT4ZHOKT.js → chunk-QPVNK2VE.js} +2 -2
  165. package/dist/{chunk-K5DA5TRG.js → chunk-QS5Q5RBV.js} +2 -2
  166. package/dist/{chunk-BX4EOMKT.js → chunk-RDLPFM7I.js} +2 -2
  167. package/dist/{chunk-EY5JAWZC.js → chunk-RJQAP333.js} +2 -2
  168. package/dist/{chunk-5AERZWJD.js → chunk-RLU2Y5GV.js} +4 -4
  169. package/dist/chunk-RLU2Y5GV.js.map +1 -0
  170. package/dist/{chunk-2OGTN37H.js → chunk-ROEFLU37.js} +4 -4
  171. package/dist/{chunk-62QIQEUC.js → chunk-SFHLQPBF.js} +25 -25
  172. package/dist/chunk-SK7D34OL.js +68 -0
  173. package/dist/chunk-SK7D34OL.js.map +1 -0
  174. package/dist/{chunk-HVS7TH2Y.js → chunk-SUEOG2S4.js} +2 -2
  175. package/dist/{chunk-74AHCL56.js → chunk-TEMKBSV6.js} +2 -2
  176. package/dist/{chunk-LQNRVPTV.js → chunk-THTF2W7M.js} +151 -118
  177. package/dist/chunk-THTF2W7M.js.map +1 -0
  178. package/dist/{chunk-KDFDXEXZ.js → chunk-TO36VPZI.js} +2 -2
  179. package/dist/{chunk-BJEJUOGM.js → chunk-TZ44E732.js} +44 -6
  180. package/dist/chunk-TZ44E732.js.map +1 -0
  181. package/dist/{chunk-JXN77SGO.js → chunk-U2VDCFXW.js} +1 -1
  182. package/dist/chunk-U2VDCFXW.js.map +1 -0
  183. package/dist/{chunk-3OYSIVOO.js → chunk-UZ6JYPJ6.js} +611 -289
  184. package/dist/chunk-UZ6JYPJ6.js.map +1 -0
  185. package/dist/{chunk-M3MYMWXG.js → chunk-V2ZA4YWE.js} +2 -2
  186. package/dist/{chunk-UIOIDW3L.js → chunk-VHKXRYQN.js} +2 -2
  187. package/dist/{chunk-GAS7KYC7.js → chunk-VKWFNPBH.js} +2 -2
  188. package/dist/{chunk-6H2G7RFT.js → chunk-VNQRRUNS.js} +11 -10
  189. package/dist/chunk-VNQRRUNS.js.map +1 -0
  190. package/dist/{chunk-XGRXQR6T.js → chunk-VQWBUPSJ.js} +2 -2
  191. package/dist/{chunk-TUKGXQ5T.js → chunk-VQYWKCDR.js} +2 -2
  192. package/dist/{chunk-PPQEP4OH.js → chunk-W23JARAQ.js} +2 -2
  193. package/dist/{chunk-YQNNHLCG.js → chunk-WPGR3RW4.js} +2 -2
  194. package/dist/{chunk-474DL7UB.js → chunk-WZYHPAG5.js} +3 -3
  195. package/dist/{chunk-5HYUUFMQ.js → chunk-XCPNH2MG.js} +259 -10
  196. package/dist/chunk-XCPNH2MG.js.map +1 -0
  197. package/dist/{chunk-GQQVEH6V.js → chunk-XM46Y66S.js} +2 -2
  198. package/dist/{chunk-JNSENHV5.js → chunk-YRIFXXMI.js} +3 -3
  199. package/dist/{chunk-TRLOFIQC.js → chunk-YTK5MVNF.js} +2 -2
  200. package/dist/{chunk-VMNCZ627.js → chunk-YTZN2UZO.js} +2 -2
  201. package/dist/chunk-Z4GUX2M6.js +94 -0
  202. package/dist/chunk-Z4GUX2M6.js.map +1 -0
  203. package/dist/{chunk-6ZMNTRU3.js → chunk-ZAEPD4C2.js} +2 -2
  204. package/dist/{chunk-KQW3YGEN.js → chunk-ZRMMXWYI.js} +2 -2
  205. package/dist/{chunk-P4ZAEYKG.js → chunk-ZX3AYNNV.js} +6 -3
  206. package/dist/chunk-ZX3AYNNV.js.map +1 -0
  207. package/dist/{chunk-MCRVQ5YQ.js → chunk-ZZCR2QYL.js} +2 -2
  208. package/dist/{cli-BNg-TAlz.d.ts → cli-BWri5-am.d.ts} +5 -5
  209. package/dist/cli.d.ts +18 -16
  210. package/dist/cli.js +80 -79
  211. package/dist/coding/export-okf-codegraph.d.ts +1 -1
  212. package/dist/coding/export-okf-codegraph.js +15 -15
  213. package/dist/coding/pre-action-gate.d.ts +1 -1
  214. package/dist/compounding/engine.d.ts +2 -2
  215. package/dist/compounding/engine.js +16 -16
  216. package/dist/compounding/preference-consolidator.d.ts +1 -1
  217. package/dist/compression-optimizer.d.ts +1 -1
  218. package/dist/config.d.ts +1 -1
  219. package/dist/config.js +6 -5
  220. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  221. package/dist/connectors/codex-materialize-runner.js +16 -16
  222. package/dist/connectors/codex-materialize.d.ts +1 -1
  223. package/dist/connectors/index.d.ts +1 -1
  224. package/dist/connectors/index.js +16 -16
  225. package/dist/consolidation-provenance-check.d.ts +2 -2
  226. package/dist/consolidation-undo.d.ts +2 -2
  227. package/dist/contradiction/index.d.ts +6 -5
  228. package/dist/converge-config.d.ts +1 -1
  229. package/dist/convergence-refresh.d.ts +2 -2
  230. package/dist/convergence-refresh.js +18 -18
  231. package/dist/conversation-index/backend.d.ts +1 -1
  232. package/dist/conversation-index/chunker.d.ts +1 -1
  233. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  234. package/dist/conversation-index/indexer.d.ts +1 -1
  235. package/dist/conversation-index/search.d.ts +1 -1
  236. package/dist/corpus-watermark.d.ts +1 -1
  237. package/dist/corpus-watermark.js +18 -18
  238. package/dist/cross-lingual-recall.d.ts +1 -1
  239. package/dist/day-summary.d.ts +1 -1
  240. package/dist/deep-recall-http-glue.d.ts +16 -14
  241. package/dist/deep-recall-http-glue.js +2 -2
  242. package/dist/deep-recall-mcp-tools.d.ts +16 -14
  243. package/dist/deep-recall-policy-llm.d.ts +4 -3
  244. package/dist/deep-recall-policy-llm.js +3 -3
  245. package/dist/deep-recall-seeds.d.ts +1 -1
  246. package/dist/delinearize.d.ts +1 -1
  247. package/dist/dependency-propagation-config.d.ts +1 -1
  248. package/dist/{dependency-propagation-delivery-Cq1ekOwV.d.ts → dependency-propagation-delivery-ueZlKTQB.d.ts} +1 -1
  249. package/dist/direct-answer-wiring.d.ts +1 -1
  250. package/dist/direct-answer.d.ts +1 -1
  251. package/dist/embedding-fallback.d.ts +1 -1
  252. package/dist/enrichment/index.d.ts +1 -1
  253. package/dist/entity-origin-fields.d.ts +1 -1
  254. package/dist/entity-retrieval.d.ts +2 -2
  255. package/dist/entity-retrieval.js +16 -16
  256. package/dist/entity-schema.d.ts +1 -1
  257. package/dist/episodic-context.d.ts +1 -1
  258. package/dist/eval-trajectory-contracts.d.ts +1 -1
  259. package/dist/eval-trajectory-store.d.ts +1 -1
  260. package/dist/eval-trajectory.d.ts +1 -1
  261. package/dist/explicit-capture.d.ts +13 -12
  262. package/dist/external-wiki-access.d.ts +16 -14
  263. package/dist/external-wiki-access.js +40 -40
  264. package/dist/external-wiki-collection-registration.d.ts +1 -1
  265. package/dist/external-wiki-collection.d.ts +1 -1
  266. package/dist/external-wiki-mcp-tools.d.ts +16 -14
  267. package/dist/extraction-error-classification.d.ts +14 -3
  268. package/dist/extraction-error-classification.js +5 -3
  269. package/dist/extraction-faithfulness.d.ts +4 -3
  270. package/dist/extraction-faithfulness.js +3 -3
  271. package/dist/extraction-judge-telemetry.d.ts +4 -3
  272. package/dist/extraction-judge-training.d.ts +4 -3
  273. package/dist/extraction-judge.d.ts +4 -3
  274. package/dist/extraction-judge.js +3 -3
  275. package/dist/extraction-liveness.d.ts +1 -1
  276. package/dist/extraction-normalization.d.ts +1 -1
  277. package/dist/extraction-prompt.d.ts +1 -1
  278. package/dist/extraction-source-grounding-rules.d.ts +1 -1
  279. package/dist/extraction-source-grounding.d.ts +1 -1
  280. package/dist/extraction-span-config.d.ts +1 -1
  281. package/dist/extraction-span-materialize.d.ts +1 -1
  282. package/dist/extraction.d.ts +4 -4
  283. package/dist/extraction.js +26 -24
  284. package/dist/fallback-llm-codex-subscription.d.ts +52 -7
  285. package/dist/fallback-llm-codex-subscription.js +17 -1
  286. package/dist/fallback-llm.d.ts +25 -28
  287. package/dist/fallback-llm.js +4 -3
  288. package/dist/{generic-recall-paths-BcySh_f9.d.ts → generic-recall-paths-CpyVmA88.d.ts} +1 -1
  289. package/dist/graph-append-error.d.ts +1 -1
  290. package/dist/graph-dashboard-diff.d.ts +1 -1
  291. package/dist/graph-dashboard-key.d.ts +1 -1
  292. package/dist/graph-dashboard-parser.d.ts +1 -1
  293. package/dist/graph-edge-reinforcement.d.ts +1 -1
  294. package/dist/graph-jsonl.d.ts +1 -1
  295. package/dist/graph-path-reconstruction.d.ts +1 -1
  296. package/dist/graph-path-scoring.d.ts +1 -1
  297. package/dist/graph-snapshot.d.ts +1 -1
  298. package/dist/graph.d.ts +1 -1
  299. package/dist/harmonic-retrieval.js +1 -1
  300. package/dist/importance.d.ts +1 -1
  301. package/dist/importers/index.d.ts +1 -1
  302. package/dist/importers/test-utils.d.ts +1 -1
  303. package/dist/in-flight-reads.d.ts +1 -1
  304. package/dist/{index-DWOb4wz9.d.ts → index-BvUA4S7M.d.ts} +3 -3
  305. package/dist/index.d.ts +80 -40
  306. package/dist/index.js +140 -115
  307. package/dist/intent.d.ts +1 -1
  308. package/dist/lcm/engine.d.ts +1 -1
  309. package/dist/lcm/engine.js +2 -2
  310. package/dist/lcm/index.d.ts +1 -1
  311. package/dist/lcm/index.js +7 -7
  312. package/dist/lcm/tools.d.ts +1 -1
  313. package/dist/lifecycle.d.ts +1 -1
  314. package/dist/live-connectors-runner.d.ts +1 -1
  315. package/dist/local-llm-BsJGulur.d.ts +247 -0
  316. package/dist/local-llm-config.d.ts +4 -1
  317. package/dist/local-llm-config.js +4 -2
  318. package/dist/local-llm-helpers.d.ts +18 -69
  319. package/dist/local-llm-helpers.js +1 -1
  320. package/dist/local-llm.d.ts +3 -170
  321. package/dist/local-llm.js +2 -2
  322. package/dist/local-model-endpoint.d.ts +1 -1
  323. package/dist/location/index.d.ts +3 -3
  324. package/dist/location/index.js +18 -18
  325. package/dist/maintenance/memory-governance.d.ts +1 -1
  326. package/dist/maintenance/memory-governance.js +16 -16
  327. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -2
  328. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +16 -16
  329. package/dist/maintenance/rebuild-memory-projection.d.ts +2 -2
  330. package/dist/maintenance/rebuild-memory-projection.js +17 -17
  331. package/dist/{maintenance-CW9wCzMP.d.ts → maintenance-CYubtIRr.d.ts} +9 -3
  332. package/dist/mcp-memory-inspector-app.d.ts +16 -14
  333. package/dist/memory-action-policy.d.ts +1 -1
  334. package/dist/memory-cache.d.ts +1 -1
  335. package/dist/memory-controller.d.ts +1 -1
  336. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  337. package/dist/memory-projection-store.d.ts +1 -1
  338. package/dist/memory-provenance.d.ts +1 -1
  339. package/dist/memory-snapshot.d.ts +1 -1
  340. package/dist/memory-subject-cli.d.ts +16 -14
  341. package/dist/memory-subject.d.ts +16 -14
  342. package/dist/memory-worth-outcomes.d.ts +2 -2
  343. package/dist/models-json.d.ts +1 -1
  344. package/dist/namespaces/migrate.d.ts +3 -3
  345. package/dist/namespaces/migrate.js +17 -17
  346. package/dist/namespaces/principal.d.ts +1 -1
  347. package/dist/namespaces/search.d.ts +12 -1
  348. package/dist/namespaces/search.js +9 -9
  349. package/dist/namespaces/storage.d.ts +3 -3
  350. package/dist/namespaces/storage.js +16 -16
  351. package/dist/native-knowledge.d.ts +1 -1
  352. package/dist/offline-sync-impression-drain.d.ts +1 -1
  353. package/dist/operator-doctor-corpus.d.ts +1 -1
  354. package/dist/operator-doctor-corpus.js +19 -19
  355. package/dist/operator-doctor-replica.d.ts +1 -1
  356. package/dist/operator-toolkit.d.ts +3 -3
  357. package/dist/operator-toolkit.js +30 -29
  358. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  359. package/dist/orchestration/maintenance.d.ts +4 -4
  360. package/dist/orchestration/maintenance.js +27 -27
  361. package/dist/{orchestrator-DocO0_hw.d.ts → orchestrator-BWDRJ_0d.d.ts} +37 -13
  362. package/dist/orchestrator.d.ts +13 -12
  363. package/dist/orchestrator.js +110 -106
  364. package/dist/patterns-cli.d.ts +1 -1
  365. package/dist/{pipeline-CiYcqqhl.d.ts → pipeline-7JMn2yMH.d.ts} +1 -1
  366. package/dist/policy-runtime.d.ts +1 -1
  367. package/dist/proactive-contention.d.ts +2 -2
  368. package/dist/provenance.d.ts +1 -1
  369. package/dist/{public-http-C0FoTiL_.d.ts → public-http-CJWs3mo9.d.ts} +1 -1
  370. package/dist/{qmd-qXD4vatU.d.ts → qmd-CxCH9G9m.d.ts} +2 -2
  371. package/dist/qmd-preflight.d.ts +2 -2
  372. package/dist/qmd-recall-cache.d.ts +1 -1
  373. package/dist/qmd.d.ts +2 -2
  374. package/dist/qmd.js +2 -2
  375. package/dist/recall-concurrency-config.d.ts +1 -1
  376. package/dist/recall-disclosure-escalation.d.ts +1 -1
  377. package/dist/recall-explain-renderer.d.ts +1 -1
  378. package/dist/recall-explain-renderer.js +3 -3
  379. package/dist/recall-memory-map.d.ts +1 -1
  380. package/dist/recall-navigate-access.d.ts +1 -1
  381. package/dist/recall-navigate-access.js +2 -2
  382. package/dist/recall-navigate-disclosure.d.ts +1 -1
  383. package/dist/recall-navigate-disclosure.js +1 -1
  384. package/dist/recall-navigate.d.ts +1 -1
  385. package/dist/recall-navigate.js +2 -2
  386. package/dist/recall-planner-llm.d.ts +3 -2
  387. package/dist/recall-planner-llm.js +4 -3
  388. package/dist/recall-planner-llm.js.map +1 -1
  389. package/dist/recall-state-view-admission.d.ts +13 -3
  390. package/dist/recall-state-view-admission.js +8 -8
  391. package/dist/recall-state-view-anchors.d.ts +85 -0
  392. package/dist/recall-state-view-anchors.js +21 -0
  393. package/dist/recall-state-view-anchors.js.map +1 -0
  394. package/dist/recall-state-view-inject.js +2 -2
  395. package/dist/recall-state-view-render.js +2 -2
  396. package/dist/recall-state-view-widen.js +2 -2
  397. package/dist/recall-state-view-wire.js +3 -3
  398. package/dist/recall-state-view.d.ts +38 -1
  399. package/dist/recall-state-view.js +11 -3
  400. package/dist/recall-state.d.ts +1 -1
  401. package/dist/recall-tag-filter.d.ts +1 -1
  402. package/dist/recall-timings.d.ts +1 -1
  403. package/dist/recall-xray-cli.d.ts +1 -1
  404. package/dist/recall-xray-cli.js +4 -4
  405. package/dist/recall-xray-renderer.d.ts +1 -1
  406. package/dist/recall-xray-renderer.js +3 -3
  407. package/dist/recall-xray.d.ts +1 -1
  408. package/dist/recall-xray.js +2 -2
  409. package/dist/reconcile/cursor.d.ts +1 -1
  410. package/dist/reconcile/manifest.d.ts +1 -1
  411. package/dist/reconcile/plan.d.ts +1 -1
  412. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  413. package/dist/replay/normalizers/claude.d.ts +1 -1
  414. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  415. package/dist/replay/normalizers/shared.d.ts +1 -1
  416. package/dist/replay/runner.d.ts +1 -1
  417. package/dist/replay/types.d.ts +1 -1
  418. package/dist/replica-divergence.d.ts +1 -1
  419. package/dist/replica-peers-config.d.ts +1 -1
  420. package/dist/resolve-auth-token.d.ts +1 -1
  421. package/dist/resume-bundles.js +7 -6
  422. package/dist/retrieval-agents.d.ts +2 -2
  423. package/dist/retrieval-tiers.d.ts +1 -1
  424. package/dist/routing/engine.d.ts +1 -1
  425. package/dist/routing/store.d.ts +1 -1
  426. package/dist/salvage-envelope.d.ts +1 -1
  427. package/dist/{scope-profiles-BT9rqC3w.d.ts → scope-profiles-BGAUqhBR.d.ts} +1 -1
  428. package/dist/search/embed-helper.d.ts +1 -1
  429. package/dist/search/factory.d.ts +1 -1
  430. package/dist/search/factory.js +8 -8
  431. package/dist/search/index.d.ts +1 -1
  432. package/dist/search/index.js +12 -12
  433. package/dist/search/lancedb-backend.d.ts +1 -1
  434. package/dist/search/lancedb-backend.js +2 -2
  435. package/dist/search/meilisearch-backend.d.ts +1 -1
  436. package/dist/search/meilisearch-backend.js +2 -2
  437. package/dist/search/noop-backend.d.ts +1 -1
  438. package/dist/search/orama-backend.d.ts +1 -1
  439. package/dist/search/orama-backend.js +2 -2
  440. package/dist/search/port.d.ts +2 -2
  441. package/dist/search/port.js +1 -1
  442. package/dist/search/remote-backend.d.ts +1 -1
  443. package/dist/search/remote-backend.js +2 -2
  444. package/dist/{semantic-consolidation-CmZi7thY.d.ts → semantic-consolidation-CCeRD9pV.d.ts} +1 -1
  445. package/dist/semantic-consolidation.d.ts +2 -2
  446. package/dist/semantic-consolidation.js +17 -17
  447. package/dist/semantic-rule-promotion.js +16 -16
  448. package/dist/semantic-rule-verifier.d.ts +1 -1
  449. package/dist/semantic-rule-verifier.js +16 -16
  450. package/dist/{service-CLkA7AQB.d.ts → service-BwpzRduk.d.ts} +2 -2
  451. package/dist/session-observer-bands.d.ts +1 -1
  452. package/dist/session-observer-state.d.ts +1 -1
  453. package/dist/shared-context/manager.d.ts +1 -1
  454. package/dist/signal.d.ts +1 -1
  455. package/dist/source-agent-qualifier.d.ts +1 -1
  456. package/dist/source-agent-qualifier.js +19 -19
  457. package/dist/standup/build.js +16 -16
  458. package/dist/{storage-wvX01lht.d.ts → storage-BprAGBG0.d.ts} +2 -1
  459. package/dist/storage.d.ts +2 -2
  460. package/dist/storage.js +15 -15
  461. package/dist/subject-config.d.ts +1 -1
  462. package/dist/summarizer.d.ts +1 -1
  463. package/dist/summarizer.js +5 -5
  464. package/dist/summary-snapshot.d.ts +1 -1
  465. package/dist/support-passport/index.d.ts +18 -17
  466. package/dist/support-passport/index.js +42 -42
  467. package/dist/task-llm-config.d.ts +16 -0
  468. package/dist/task-llm-config.js +12 -0
  469. package/dist/task-llm-config.js.map +1 -0
  470. package/dist/temporal-supersession.d.ts +2 -2
  471. package/dist/temporal-timeline-recall.d.ts +1 -1
  472. package/dist/temporal-validity.d.ts +1 -1
  473. package/dist/threading.d.ts +1 -1
  474. package/dist/tier-migration.d.ts +2 -2
  475. package/dist/tier-routing.d.ts +1 -1
  476. package/dist/topics.d.ts +1 -1
  477. package/dist/transcript.d.ts +1 -1
  478. package/dist/transfer/export-okf.d.ts +1 -1
  479. package/dist/transfer/export-okf.js +16 -16
  480. package/dist/trust-score-stage.d.ts +1 -1
  481. package/dist/trust-score.d.ts +1 -1
  482. package/dist/{types-Cyr32ABj.d.ts → types-nJV23pa3.d.ts} +1 -1
  483. package/dist/types.d.ts +1 -1
  484. package/dist/types.js +1 -1
  485. package/dist/utility-runtime.d.ts +1 -1
  486. package/dist/verified-recall.js +16 -16
  487. package/dist/who-knows-cli.d.ts +16 -14
  488. package/dist/who-knows-cli.js +17 -17
  489. package/dist/who-knows.d.ts +16 -14
  490. package/dist/who-knows.js +16 -16
  491. package/dist/write-envelope.d.ts +1 -1
  492. package/package.json +2 -2
  493. package/src/access-category-alias.test.ts +93 -0
  494. package/src/access-offline-manifest.ts +52 -2
  495. package/src/access-schema.ts +9 -4
  496. package/src/activity/config.test.ts +61 -0
  497. package/src/activity/config.ts +40 -1
  498. package/src/activity/timeline/analysis-provider.ts +8 -2
  499. package/src/activity/timeline/analysis-run.test.ts +82 -0
  500. package/src/activity/timeline/publish-cli.test.ts +30 -0
  501. package/src/activity/timeline/publish-cli.ts +7 -0
  502. package/src/activity/timeline/query.ts +8 -1
  503. package/src/activity/timeline/regenerate.test.ts +82 -2
  504. package/src/activity/timeline/regenerate.ts +7 -1
  505. package/src/activity/vault-frontmatter.test.ts +99 -1
  506. package/src/activity/vault-frontmatter.ts +131 -0
  507. package/src/activity/vault-publish.ts +6 -0
  508. package/src/activity/vault-publisher.test.ts +172 -0
  509. package/src/activity/vault-publisher.ts +69 -15
  510. package/src/activity/vault-region.test.ts +7 -2
  511. package/src/activity/vault-region.ts +7 -3
  512. package/src/background-generation-config.ts +32 -6
  513. package/src/background-generation.test.ts +10 -1
  514. package/src/cli/timeline-publish-commands.ts +9 -0
  515. package/src/config.test.ts +170 -43
  516. package/src/config.ts +17 -5
  517. package/src/extraction-error-classification.ts +36 -1
  518. package/src/extraction-timeout.test.ts +110 -1
  519. package/src/extraction.test.ts +19 -1
  520. package/src/extraction.ts +23 -21
  521. package/src/fallback-llm-codex-subscription.ts +193 -7
  522. package/src/fallback-llm-parse-failure.test.ts +156 -0
  523. package/src/fallback-llm.test.ts +58 -0
  524. package/src/fallback-llm.ts +187 -186
  525. package/src/index.ts +1 -0
  526. package/src/local-llm-config.ts +11 -10
  527. package/src/local-llm-headers-timeout.test.ts +30 -0
  528. package/src/local-llm-helpers.ts +28 -0
  529. package/src/local-llm.ts +8 -19
  530. package/src/namespaces/search.test.ts +51 -1
  531. package/src/namespaces/search.ts +48 -3
  532. package/src/orchestration/extraction-persist-promotion.test.ts +228 -2
  533. package/src/orchestration/extraction-persist-promotion.ts +17 -14
  534. package/src/orchestration/orchestrator-helpers.test.ts +104 -0
  535. package/src/orchestration/orchestrator-init.ts +366 -106
  536. package/src/orchestration/recall-internal.ts +85 -74
  537. package/src/orchestration/recall-rerank-coordinator.ts +41 -4
  538. package/src/orchestration/recall-search-pipeline.ts +25 -18
  539. package/src/orchestration/recall-state-view-pipeline.test.ts +89 -0
  540. package/src/orchestration/semantic-merge-promotion-payload.ts +62 -6
  541. package/src/orchestration/startup-collection-checks.ts +85 -0
  542. package/src/orchestrator-flush.test.ts +7 -0
  543. package/src/orchestrator-init.test.ts +1539 -0
  544. package/src/orchestrator.ts +7 -0
  545. package/src/qmd.ts +21 -10
  546. package/src/recall-rerank-coordinator.test.ts +153 -0
  547. package/src/recall-state-view-admission.ts +11 -1
  548. package/src/recall-state-view-anchors.ts +163 -0
  549. package/src/recall-state-view-cron-intent.test.ts +268 -0
  550. package/src/recall-state-view-widen.test.ts +14 -5
  551. package/src/recall-state-view-widen.ts +29 -8
  552. package/src/recall-state-view-zero-diff.test.ts +30 -0
  553. package/src/recall-state-view.test.ts +161 -0
  554. package/src/recall-state-view.ts +211 -37
  555. package/src/reconcile-identity-cache.test.ts +82 -1
  556. package/src/search/port.ts +1 -1
  557. package/src/storage/cas-revision-store.test.ts +4 -0
  558. package/src/storage/cas-revision-store.ts +104 -12
  559. package/src/storage-frontmatter-cas.test.ts +19 -17
  560. package/src/summarizer.ts +5 -1
  561. package/src/task-llm-config.test.ts +124 -0
  562. package/src/task-llm-config.ts +88 -0
  563. package/src/testing/subjects/startup-discovery-lifecycle.test.ts +273 -0
  564. package/src/trust-score-recall-paths.test.ts +1 -1
  565. package/src/types.ts +1 -0
  566. package/dist/chunk-255PC37A.js +0 -120
  567. package/dist/chunk-255PC37A.js.map +0 -1
  568. package/dist/chunk-2MT4ADLQ.js.map +0 -1
  569. package/dist/chunk-3CBI2ZSA.js.map +0 -1
  570. package/dist/chunk-3OYSIVOO.js.map +0 -1
  571. package/dist/chunk-5AERZWJD.js.map +0 -1
  572. package/dist/chunk-5HYUUFMQ.js.map +0 -1
  573. package/dist/chunk-6H2G7RFT.js.map +0 -1
  574. package/dist/chunk-7S53BPTU.js.map +0 -1
  575. package/dist/chunk-ACY4ZPF7.js.map +0 -1
  576. package/dist/chunk-B36GUU6T.js.map +0 -1
  577. package/dist/chunk-BJEJUOGM.js.map +0 -1
  578. package/dist/chunk-BLDBT6HZ.js.map +0 -1
  579. package/dist/chunk-CWTCMZGE.js.map +0 -1
  580. package/dist/chunk-IYKZJVL5.js.map +0 -1
  581. package/dist/chunk-JXN77SGO.js.map +0 -1
  582. package/dist/chunk-LQNRVPTV.js.map +0 -1
  583. package/dist/chunk-MVAQ2WM3.js.map +0 -1
  584. package/dist/chunk-P4ZAEYKG.js.map +0 -1
  585. package/dist/chunk-QHT7MOUF.js.map +0 -1
  586. package/dist/chunk-V6G2PSXA.js.map +0 -1
  587. package/dist/chunk-VELCIWJZ.js.map +0 -1
  588. package/dist/chunk-WKDFJXW5.js.map +0 -1
  589. package/dist/chunk-XWLLFKHM.js.map +0 -1
  590. package/dist/chunk-YFTNZMGR.js.map +0 -1
  591. /package/dist/{auto-sync-RP4C6ZPF.js.map → auto-sync-D6BAPIJV.js.map} +0 -0
  592. /package/dist/{chunk-T32B72QX.js.map → chunk-2SKMZUOW.js.map} +0 -0
  593. /package/dist/{chunk-VHOSM5G4.js.map → chunk-2SNCQHJZ.js.map} +0 -0
  594. /package/dist/{chunk-VV4ZVUE6.js.map → chunk-3QEVOQF5.js.map} +0 -0
  595. /package/dist/{chunk-3N3PBBEH.js.map → chunk-3XPN7AVY.js.map} +0 -0
  596. /package/dist/{chunk-XN6XT6GR.js.map → chunk-46Z3VGWF.js.map} +0 -0
  597. /package/dist/{chunk-2PTNJTBE.js.map → chunk-4CMXI55L.js.map} +0 -0
  598. /package/dist/{chunk-A6CKMIPK.js.map → chunk-7D6SER6A.js.map} +0 -0
  599. /package/dist/{chunk-4B3HBIFX.js.map → chunk-7Z54NXVS.js.map} +0 -0
  600. /package/dist/{chunk-X2NFFBTO.js.map → chunk-A7GQBJP5.js.map} +0 -0
  601. /package/dist/{chunk-NWMUSKED.js.map → chunk-BGRTZOJB.js.map} +0 -0
  602. /package/dist/{chunk-ZEGL7YCC.js.map → chunk-BXIJSPCL.js.map} +0 -0
  603. /package/dist/{chunk-MLWMR2GE.js.map → chunk-BYQX4IOG.js.map} +0 -0
  604. /package/dist/{chunk-ULDBGA5W.js.map → chunk-C5R73BON.js.map} +0 -0
  605. /package/dist/{chunk-BD7JTBYP.js.map → chunk-D7MAYFQP.js.map} +0 -0
  606. /package/dist/{chunk-BRZWWUCJ.js.map → chunk-DFVSJFHK.js.map} +0 -0
  607. /package/dist/{chunk-DPMTLJCT.js.map → chunk-ES5BUPYB.js.map} +0 -0
  608. /package/dist/{chunk-TNSCIPBQ.js.map → chunk-G6NQ3L4T.js.map} +0 -0
  609. /package/dist/{chunk-5N4MZLEH.js.map → chunk-GO5LOHCD.js.map} +0 -0
  610. /package/dist/{chunk-AECJY3GJ.js.map → chunk-GSSDHAYH.js.map} +0 -0
  611. /package/dist/{chunk-JA2QJOAX.js.map → chunk-HJUP3K6L.js.map} +0 -0
  612. /package/dist/{chunk-ZKZFFWLV.js.map → chunk-ICNJ6J46.js.map} +0 -0
  613. /package/dist/{chunk-6EHM2AV7.js.map → chunk-IMBQFHRV.js.map} +0 -0
  614. /package/dist/{chunk-6PRY6CLC.js.map → chunk-IOPIGX7Y.js.map} +0 -0
  615. /package/dist/{chunk-TRHBQVVO.js.map → chunk-IS2IDFJP.js.map} +0 -0
  616. /package/dist/{chunk-R4VAUNNC.js.map → chunk-J4WGTN2N.js.map} +0 -0
  617. /package/dist/{chunk-JPOX2AJB.js.map → chunk-J7FVMLBR.js.map} +0 -0
  618. /package/dist/{chunk-BYZKLEWG.js.map → chunk-JAJIMTFB.js.map} +0 -0
  619. /package/dist/{chunk-OKO57IXB.js.map → chunk-JOP7W24J.js.map} +0 -0
  620. /package/dist/{chunk-YUW66UAH.js.map → chunk-JUDT33RX.js.map} +0 -0
  621. /package/dist/{chunk-UQNYPK7G.js.map → chunk-K4JKAXMO.js.map} +0 -0
  622. /package/dist/{chunk-BV4ZKIZH.js.map → chunk-K75A5XWU.js.map} +0 -0
  623. /package/dist/{chunk-M6HBPLBA.js.map → chunk-KOTG3RXE.js.map} +0 -0
  624. /package/dist/{chunk-OB3XMWX5.js.map → chunk-KVO2BTA4.js.map} +0 -0
  625. /package/dist/{chunk-CBFYCDYO.js.map → chunk-KY236SP5.js.map} +0 -0
  626. /package/dist/{chunk-4BCHFSC7.js.map → chunk-LFVZD5EC.js.map} +0 -0
  627. /package/dist/{chunk-GGAXFTNH.js.map → chunk-LKFVVN7R.js.map} +0 -0
  628. /package/dist/{chunk-4RX5O34R.js.map → chunk-MJC7UKH7.js.map} +0 -0
  629. /package/dist/{chunk-UZZ7SQT3.js.map → chunk-NVVZPBKI.js.map} +0 -0
  630. /package/dist/{chunk-TTSJ7WUC.js.map → chunk-PKUJNICO.js.map} +0 -0
  631. /package/dist/{chunk-QMWKENNK.js.map → chunk-Q4AUIFUA.js.map} +0 -0
  632. /package/dist/{chunk-G43PMSME.js.map → chunk-QE6YVNP5.js.map} +0 -0
  633. /package/dist/{chunk-GT4ZHOKT.js.map → chunk-QPVNK2VE.js.map} +0 -0
  634. /package/dist/{chunk-K5DA5TRG.js.map → chunk-QS5Q5RBV.js.map} +0 -0
  635. /package/dist/{chunk-BX4EOMKT.js.map → chunk-RDLPFM7I.js.map} +0 -0
  636. /package/dist/{chunk-EY5JAWZC.js.map → chunk-RJQAP333.js.map} +0 -0
  637. /package/dist/{chunk-2OGTN37H.js.map → chunk-ROEFLU37.js.map} +0 -0
  638. /package/dist/{chunk-62QIQEUC.js.map → chunk-SFHLQPBF.js.map} +0 -0
  639. /package/dist/{chunk-HVS7TH2Y.js.map → chunk-SUEOG2S4.js.map} +0 -0
  640. /package/dist/{chunk-74AHCL56.js.map → chunk-TEMKBSV6.js.map} +0 -0
  641. /package/dist/{chunk-KDFDXEXZ.js.map → chunk-TO36VPZI.js.map} +0 -0
  642. /package/dist/{chunk-M3MYMWXG.js.map → chunk-V2ZA4YWE.js.map} +0 -0
  643. /package/dist/{chunk-UIOIDW3L.js.map → chunk-VHKXRYQN.js.map} +0 -0
  644. /package/dist/{chunk-GAS7KYC7.js.map → chunk-VKWFNPBH.js.map} +0 -0
  645. /package/dist/{chunk-XGRXQR6T.js.map → chunk-VQWBUPSJ.js.map} +0 -0
  646. /package/dist/{chunk-TUKGXQ5T.js.map → chunk-VQYWKCDR.js.map} +0 -0
  647. /package/dist/{chunk-PPQEP4OH.js.map → chunk-W23JARAQ.js.map} +0 -0
  648. /package/dist/{chunk-YQNNHLCG.js.map → chunk-WPGR3RW4.js.map} +0 -0
  649. /package/dist/{chunk-474DL7UB.js.map → chunk-WZYHPAG5.js.map} +0 -0
  650. /package/dist/{chunk-GQQVEH6V.js.map → chunk-XM46Y66S.js.map} +0 -0
  651. /package/dist/{chunk-JNSENHV5.js.map → chunk-YRIFXXMI.js.map} +0 -0
  652. /package/dist/{chunk-TRLOFIQC.js.map → chunk-YTK5MVNF.js.map} +0 -0
  653. /package/dist/{chunk-VMNCZ627.js.map → chunk-YTZN2UZO.js.map} +0 -0
  654. /package/dist/{chunk-6ZMNTRU3.js.map → chunk-ZAEPD4C2.js.map} +0 -0
  655. /package/dist/{chunk-KQW3YGEN.js.map → chunk-ZRMMXWYI.js.map} +0 -0
  656. /package/dist/{chunk-MCRVQ5YQ.js.map → chunk-ZZCR2QYL.js.map} +0 -0
@@ -4,26 +4,26 @@ import {
4
4
  } from "./chunk-27MKMTBY.js";
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation
7
- } from "./chunk-VMNCZ627.js";
7
+ } from "./chunk-YTZN2UZO.js";
8
8
  import "./chunk-5JMAGU26.js";
9
9
  import "./chunk-B7RWBZXW.js";
10
10
  import {
11
11
  runPostConsolidationMaterialize
12
- } from "./chunk-R4VAUNNC.js";
12
+ } from "./chunk-J4WGTN2N.js";
13
13
  import "./chunk-3UXOZBHV.js";
14
14
  import "./chunk-V6EGNVUT.js";
15
- import "./chunk-7S53BPTU.js";
16
- import "./chunk-UHVXE24Y.js";
15
+ import "./chunk-MVG3KXON.js";
17
16
  import "./chunk-46WM6JX2.js";
17
+ import "./chunk-UHVXE24Y.js";
18
18
  import "./chunk-D5F7TKMH.js";
19
- import "./chunk-BJEJUOGM.js";
20
- import "./chunk-OKO57IXB.js";
21
- import "./chunk-YQNNHLCG.js";
22
- import "./chunk-6KTXE6A3.js";
23
- import "./chunk-BD7JTBYP.js";
24
- import "./chunk-OB3XMWX5.js";
19
+ import "./chunk-TZ44E732.js";
20
+ import "./chunk-JOP7W24J.js";
25
21
  import "./chunk-CYEPCZN5.js";
26
- import "./chunk-TNSCIPBQ.js";
22
+ import "./chunk-G6NQ3L4T.js";
23
+ import "./chunk-WPGR3RW4.js";
24
+ import "./chunk-6KTXE6A3.js";
25
+ import "./chunk-D7MAYFQP.js";
26
+ import "./chunk-KVO2BTA4.js";
27
27
  import "./chunk-4O6WRBGE.js";
28
28
  import "./chunk-GUMZC2BO.js";
29
29
  import "./chunk-TFA6HPOA.js";
@@ -32,13 +32,13 @@ import "./chunk-72A4L5JJ.js";
32
32
  import "./chunk-A7Q43EUZ.js";
33
33
  import "./chunk-S2V7RUCL.js";
34
34
  import "./chunk-PCEYGOSL.js";
35
- import "./chunk-IYKZJVL5.js";
35
+ import "./chunk-MDIEES23.js";
36
36
  import "./chunk-SCU65EZI.js";
37
37
  import "./chunk-MRPOZBJC.js";
38
38
  import "./chunk-S2HLHAZ4.js";
39
39
  import "./chunk-DM2T26WE.js";
40
40
  import "./chunk-LDXUBPMO.js";
41
- import "./chunk-3N3PBBEH.js";
41
+ import "./chunk-3XPN7AVY.js";
42
42
  import "./chunk-AAD2ZS6P.js";
43
43
  import "./chunk-SHEHQBCG.js";
44
44
  import "./chunk-3ONXXHQO.js";
@@ -52,8 +52,8 @@ import "./chunk-RBOJCG4T.js";
52
52
  import "./chunk-R7QY5ZVB.js";
53
53
  import "./chunk-5WITETWU.js";
54
54
  import "./chunk-6CIAGZ6X.js";
55
- import "./chunk-3CBI2ZSA.js";
56
- import "./chunk-JXN77SGO.js";
55
+ import "./chunk-KG2OOAFF.js";
56
+ import "./chunk-U2VDCFXW.js";
57
57
  import "./chunk-ZLQ37WJX.js";
58
58
  import "./chunk-IUM3VSHI.js";
59
59
  import "./chunk-GDYU6VF4.js";
@@ -61,13 +61,14 @@ import "./chunk-BT7NVCML.js";
61
61
  import "./chunk-C64XATK7.js";
62
62
  import "./chunk-42JKGUFJ.js";
63
63
  import {
64
- FallbackLlmClient,
65
- fallbackLlmRuntimeContextFromConfig
66
- } from "./chunk-LQNRVPTV.js";
64
+ FallbackLlmClient
65
+ } from "./chunk-THTF2W7M.js";
67
66
  import "./chunk-I55KAVET.js";
68
67
  import "./chunk-L2EXJQJP.js";
69
68
  import "./chunk-45GF7Y3V.js";
70
- import "./chunk-CWTCMZGE.js";
69
+ import {
70
+ fallbackLlmRuntimeContextFromConfig
71
+ } from "./chunk-KTOXQMW3.js";
71
72
  import "./chunk-E2AWJ7KQ.js";
72
73
  import "./chunk-236PXYG7.js";
73
74
  import "./chunk-ZCUTSMR2.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/causal-consolidation.ts"],"sourcesContent":["/**\n * causal-consolidation.ts — CMC Phase 2: LLM-Assisted Causal Consolidation\n *\n * Uses an LLM to analyze causal trajectory patterns across sessions.\n * The LLM receives the causal chain graph as context — connected trajectories\n * from different sessions — and identifies recurring behavioral patterns,\n * preference signals, and actionable rules.\n *\n * This is the core CMC innovation: the LLM gets cross-session causal context\n * that no other memory system provides. It can see that a user investigated\n * a bug in session 1, attempted a fix in session 2, and succeeded in session 3 —\n * and synthesize a rule or preference from that chain.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { resolveCausalTrajectoryStoreDir, type CausalTrajectoryRecord } from \"./causal-trajectory.js\";\nimport { readChainIndex, resolveChainsDir, type CausalChainIndex, type CausalEdge } from \"./causal-chain.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile, PluginConfig } from \"./types.js\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { runPostConsolidationMaterialize } from \"./connectors/codex-materialize-runner.js\";\nimport type { MaterializeResult, RolloutSummaryInput } from \"./connectors/codex-materialize.js\";\nimport { buildExtensionsBlockForConsolidation } from \"./semantic-consolidation.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CausalPatternCandidate {\n id: string;\n sourceType: \"causal-pattern\";\n subject: string;\n category: \"principle\" | \"rule\" | \"preference\";\n content: string;\n score: number;\n rationale: string;\n outcome: null;\n provenance: string[];\n agent: string | null;\n workflow: string | null;\n}\n\nexport interface ConsolidationConfig {\n minRecurrence: number;\n minSessions: number;\n successThreshold: number;\n}\n\nexport interface LlmConsolidationResult {\n rules: Array<{\n content: string;\n category: \"rule\" | \"principle\" | \"preference\";\n confidence: number;\n evidence: string[];\n }>;\n preferences: Array<{\n statement: string;\n confidence: number;\n evidence: string[];\n }>;\n}\n\nconst CAUSAL_RULE_CATEGORIES = new Set([\"rule\", \"principle\", \"preference\"]);\n\ninterface ConsolidationLlmClient {\n isAvailable(options?: { agentId?: string; modelChain?: AgentPersonaModelConfig }): boolean;\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: { temperature?: number; maxTokens?: number; agentId?: string; modelChain?: AgentPersonaModelConfig },\n ): Promise<{ content: string } | null>;\n}\n\n// ─── Trajectory Reading ──────────────────────────────────────────────────────\n\nasync function readAllTrajectories(\n memoryDir: string,\n causalTrajectoryStoreDir?: string,\n): Promise<CausalTrajectoryRecord[]> {\n const root = resolveCausalTrajectoryStoreDir(memoryDir, causalTrajectoryStoreDir);\n const trajectoriesDir = path.join(root, \"trajectories\");\n\n const files = await listJsonFiles(trajectoriesDir).catch(() => [] as string[]);\n const results: CausalTrajectoryRecord[] = [];\n\n for (const filePath of files) {\n try {\n const raw = await readJsonFile(filePath);\n if (isRecord(raw) && typeof raw.trajectoryId === \"string\") {\n results.push(raw as unknown as CausalTrajectoryRecord);\n }\n } catch {\n // skip invalid\n }\n }\n\n return results;\n}\n\n// ─── Context Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format trajectories and their causal connections as a readable context\n * for the LLM. Groups by session and shows chain connections.\n */\nfunction formatCausalContext(\n trajectories: CausalTrajectoryRecord[],\n chainIndex: CausalChainIndex,\n maxChars: number = 8000,\n): string {\n // Group trajectories by session\n const bySession = new Map<string, CausalTrajectoryRecord[]>();\n for (const t of trajectories) {\n const list = bySession.get(t.sessionKey) ?? [];\n list.push(t);\n bySession.set(t.sessionKey, list);\n }\n\n const lines: string[] = [];\n lines.push(`## Causal Trajectories (${trajectories.length} across ${bySession.size} sessions)`);\n lines.push(\"\");\n\n // Format each session's trajectories\n for (const [sessionKey, sessionTrajs] of bySession) {\n lines.push(`### Session: ${sessionKey}`);\n for (const t of sessionTrajs.slice(0, 5)) {\n const outcome = t.outcomeKind === \"success\" ? \"+\" : t.outcomeKind === \"failure\" ? \"-\" : \"~\";\n lines.push(`[${outcome}] Goal: ${t.goal}`);\n lines.push(` Action: ${t.actionSummary}`);\n lines.push(` Outcome: ${t.outcomeSummary}`);\n if (t.followUpSummary) lines.push(` Follow-up: ${t.followUpSummary}`);\n if (t.entityRefs?.length) lines.push(` Entities: ${t.entityRefs.join(\", \")}`);\n }\n lines.push(\"\");\n }\n\n // Format causal chain connections\n const edgeCount = Object.keys(chainIndex.edges).length;\n if (edgeCount > 0) {\n lines.push(`## Cross-Session Causal Chains (${edgeCount} connections)`);\n lines.push(\"\");\n\n const trajectoryMap = new Map(trajectories.map((t) => [t.trajectoryId, t]));\n const shown = new Set<string>();\n\n for (const [edgeId, edge] of Object.entries(chainIndex.edges)) {\n if (shown.size >= 10) break; // limit output size\n const from = trajectoryMap.get(edge.fromTrajectoryId);\n const to = trajectoryMap.get(edge.toTrajectoryId);\n if (!from || !to) continue;\n\n lines.push(`${edge.edgeType}: \"${from.goal}\" (${from.sessionKey}) → \"${to.goal}\" (${to.sessionKey})`);\n shown.add(edgeId);\n }\n lines.push(\"\");\n }\n\n const result = lines.join(\"\\n\");\n return result.length > maxChars ? result.slice(0, maxChars) + \"\\n[truncated]\" : result;\n}\n\n// ─── LLM Consolidation ──────────────────────────────────────────────────────\n\nconst CONSOLIDATION_PROMPT = `You are analyzing a user's causal trajectory history across multiple sessions. Trajectories record what the user tried to do (goal), what they did (action), and what happened (outcome).\n\nYour job is to identify:\n1. BEHAVIORAL RULES: Recurring patterns where the same approach consistently succeeds or fails. These should be actionable guidance for future sessions.\n2. PREFERENCES: What the user cares about, prefers, or consistently chooses — even if never explicitly stated. Infer preferences from what they repeatedly do, retry until successful, or always include in their workflow.\n\nIMPORTANT:\n- Look for CROSS-SESSION patterns — things that repeat across different sessions are more significant than within-session patterns.\n- A user who retries the same goal across sessions has a strong implicit preference for that outcome.\n- Consistent action choices reveal preferences even when the user never says \"I prefer X.\"\n- Frame preferences as \"The user would prefer responses that...\" when applicable.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\"content\": \"actionable rule text\", \"category\": \"rule|principle\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ],\n \"preferences\": [\n {\"statement\": \"The user would prefer...\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ]\n}\n\nIf no clear patterns exist, return {\"rules\": [], \"preferences\": []}.`;\n\nasync function consolidateWithLlm(\n context: string,\n llm: ConsolidationLlmClient,\n options: { agentId?: string; modelChain?: AgentPersonaModelConfig } = {},\n): Promise<LlmConsolidationResult> {\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CONSOLIDATION_PROMPT },\n { role: \"user\", content: context },\n ],\n { temperature: 0.2, maxTokens: 2000, agentId: options.agentId, modelChain: options.modelChain },\n );\n\n if (!response?.content) {\n return { rules: [], preferences: [] };\n }\n\n try {\n // Extract JSON from response (may have markdown code fences)\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 const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n const rawPreferences: unknown[] = Array.isArray(parsed.preferences) ? parsed.preferences : [];\n return {\n rules: rawRules\n .map(parseLlmRule)\n .filter((rule): rule is LlmConsolidationResult[\"rules\"][number] => !!rule),\n preferences: rawPreferences\n .map(parseLlmPreference)\n .filter((pref): pref is LlmConsolidationResult[\"preferences\"][number] => !!pref),\n };\n } catch {\n log.warn(\"[cmc] failed to parse LLM consolidation response\");\n return { rules: [], preferences: [] };\n }\n}\n\n// ─── Candidate Generation ────────────────────────────────────────────────────\n\nfunction stablePatternId(content: string): string {\n const digest = createHash(\"sha256\")\n .update(`causal-pattern\\0${content}`)\n .digest(\"hex\")\n .slice(0, 16);\n return `causal-pattern:${digest}`;\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 parseEvidence(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 parseLlmRule(raw: unknown): LlmConsolidationResult[\"rules\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const content = typeof r.content === \"string\" ? r.content.trim() : \"\";\n const category = typeof r.category === \"string\" ? r.category : \"\";\n const confidence = parseConfidence(r.confidence);\n if (content.length <= 5 || !CAUSAL_RULE_CATEGORIES.has(category) || confidence === undefined) {\n return undefined;\n }\n return {\n content,\n category: category as \"rule\" | \"principle\" | \"preference\",\n confidence,\n evidence: parseEvidence(r.evidence),\n };\n}\n\nfunction parseLlmPreference(raw: unknown): LlmConsolidationResult[\"preferences\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const p = raw as Record<string, unknown>;\n const statement = typeof p.statement === \"string\" ? p.statement.trim() : \"\";\n const confidence = parseConfidence(p.confidence);\n if (statement.length <= 5 || confidence === undefined) return undefined;\n return {\n statement,\n confidence,\n evidence: parseEvidence(p.evidence),\n };\n}\n\nfunction llmResultToCandidates(result: LlmConsolidationResult): CausalPatternCandidate[] {\n const candidates: CausalPatternCandidate[] = [];\n\n for (const rule of result.rules) {\n const category =\n rule.category === \"principle\" || rule.category === \"preference\"\n ? rule.category\n : \"rule\";\n candidates.push({\n id: stablePatternId(rule.content),\n sourceType: \"causal-pattern\",\n subject: rule.content.slice(0, 80),\n category,\n content: rule.content,\n score: Math.min(1, rule.confidence ?? 0.7),\n rationale: \"LLM-identified causal pattern from cross-session trajectory analysis\",\n outcome: null,\n provenance: (rule.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n for (const preference of result.preferences) {\n candidates.push({\n id: stablePatternId(preference.statement),\n sourceType: \"causal-pattern\",\n subject: preference.statement.slice(0, 80),\n category: \"preference\",\n content: preference.statement,\n score: Math.min(1, preference.confidence ?? 0.7),\n rationale: \"LLM-identified preference from cross-session trajectory analysis\",\n outcome: null,\n provenance: (preference.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n return candidates;\n}\n\nfunction normalizePositiveInteger(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\nfunction normalizeSuccessThreshold(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(1, value);\n}\n\nfunction trajectorySuccessScore(trajectory: CausalTrajectoryRecord): number {\n if (trajectory.outcomeKind === \"success\") return 1;\n if (trajectory.outcomeKind === \"partial\") return 0.5;\n return 0;\n}\n\nfunction averageSuccessScore(trajectories: CausalTrajectoryRecord[]): number {\n if (trajectories.length === 0) return 0;\n const total = trajectories.reduce((sum, trajectory) => sum + trajectorySuccessScore(trajectory), 0);\n return total / trajectories.length;\n}\n\nfunction passesConsolidationGates(\n trajectories: CausalTrajectoryRecord[],\n config: ConsolidationConfig,\n): boolean {\n const minRecurrence = normalizePositiveInteger(config.minRecurrence, 1);\n if (trajectories.length < minRecurrence) return false;\n\n const minSessions = normalizePositiveInteger(config.minSessions, 1);\n const sessionCount = new Set(trajectories.map((trajectory) => trajectory.sessionKey)).size;\n if (sessionCount < minSessions) return false;\n\n const successThreshold = normalizeSuccessThreshold(config.successThreshold);\n if (successThreshold > 0 && averageSuccessScore(trajectories) < successThreshold) {\n return false;\n }\n\n return true;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run LLM-assisted consolidation: read trajectories, format causal context,\n * ask LLM to identify patterns and preferences.\n */\nexport async function deriveCausalPromotionCandidates(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n config: ConsolidationConfig;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n llmClient?: ConsolidationLlmClient;\n}): Promise<CausalPatternCandidate[]> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (!passesConsolidationGates(trajectories, options.config)) return [];\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n\n // Format the causal context for the LLM\n let context = formatCausalContext(trajectories, chainIndex);\n\n // Append memory extensions block if available (#382)\n if (options.pluginConfig) {\n const extBlock = await buildExtensionsBlockForConsolidation(options.pluginConfig);\n if (extBlock.length > 0) {\n context += \"\\n\\n\" + extBlock;\n }\n }\n\n // If no LLM available, fall back to empty (no deterministic fallback)\n const llm = options.llmClient ?? new FallbackLlmClient(\n options.gatewayConfig,\n options.pluginConfig\n ? fallbackLlmRuntimeContextFromConfig(options.pluginConfig, {\n workspaceDir: options.workspaceDir ?? options.pluginConfig.workspaceDir,\n })\n : { workspaceDir: options.workspaceDir },\n );\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) {\n log.debug(\"[cmc] no LLM available for consolidation — skipping\");\n return [];\n }\n\n // Call LLM for pattern analysis\n const result = await consolidateWithLlm(context, llm, llmOptions);\n const candidates = llmResultToCandidates(result);\n\n log.debug(`[cmc] LLM consolidation produced ${candidates.length} rule(s) and ${result.preferences.length} preference(s)`);\n return candidates;\n } catch (error) {\n log.warn(`[cmc] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Get LLM-synthesized preferences from causal trajectory analysis.\n * Returns formatted preference statements for recall injection.\n */\nexport async function synthesizeCausalPreferencesViaLlm(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n minTrajectories?: number;\n}): Promise<string | null> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (trajectories.length < (options.minTrajectories ?? 2)) return null;\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n const context = formatCausalContext(trajectories, chainIndex);\n\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) return null;\n\n const result = await consolidateWithLlm(context, llm, llmOptions);\n if (result.preferences.length === 0 && result.rules.length === 0) return null;\n\n const lines: string[] = [\"## Behavioral Insights (from Causal Chain Analysis)\", \"\"];\n\n for (const pref of result.preferences) {\n lines.push(`- ${pref.statement}`);\n }\n\n for (const rule of result.rules) {\n lines.push(`- ${rule.content}`);\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n } catch (error) {\n log.warn(`[cmc] preference synthesis failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n}\n\n/**\n * Optional post-consolidation hook — materializes Codex-native memory artifacts\n * after a causal consolidation run. Guarded by `codexMaterializeMemories` and\n * `codexMaterializeOnConsolidation`. Returns `null` when disabled or when the\n * sentinel is missing (honors user hand-edits).\n *\n * Split from the orchestrator-owned flow so #378 avoids touching\n * orchestrator.ts while Wave 1 edits are in flight.\n */\nexport async function materializeAfterCausalConsolidation(options: {\n config: PluginConfig;\n namespace?: string;\n memories?: MemoryFile[];\n memoryDir?: string;\n codexHome?: string;\n rolloutSummaries?: RolloutSummaryInput[];\n now?: Date;\n}): Promise<MaterializeResult | null> {\n // Delegates to the shared post-consolidation helper — see\n // runPostConsolidationMaterialize in codex-materialize-runner.ts.\n return runPostConsolidationMaterialize(\"[cmc]\", options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAO3B,OAAO,UAAU;AA0CjB,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,aAAa,YAAY,CAAC;AAY1E,eAAe,oBACb,WACA,0BACmC;AACnC,QAAM,OAAO,gCAAgC,WAAW,wBAAwB;AAChF,QAAM,kBAAkB,KAAK,KAAK,MAAM,cAAc;AAEtD,QAAM,QAAQ,MAAM,cAAc,eAAe,EAAE,MAAM,MAAM,CAAC,CAAa;AAC7E,QAAM,UAAoC,CAAC;AAE3C,aAAW,YAAY,OAAO;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,aAAa,QAAQ;AACvC,UAAI,SAAS,GAAG,KAAK,OAAO,IAAI,iBAAiB,UAAU;AACzD,gBAAQ,KAAK,GAAwC;AAAA,MACvD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO;AACT;AAQA,SAAS,oBACP,cACA,YACA,WAAmB,KACX;AAER,QAAM,YAAY,oBAAI,IAAsC;AAC5D,aAAW,KAAK,cAAc;AAC5B,UAAM,OAAO,UAAU,IAAI,EAAE,UAAU,KAAK,CAAC;AAC7C,SAAK,KAAK,CAAC;AACX,cAAU,IAAI,EAAE,YAAY,IAAI;AAAA,EAClC;AAEA,QAAM,QAAkB,CAAC;AACzB,QAAM,KAAK,2BAA2B,aAAa,MAAM,WAAW,UAAU,IAAI,YAAY;AAC9F,QAAM,KAAK,EAAE;AAGb,aAAW,CAAC,YAAY,YAAY,KAAK,WAAW;AAClD,UAAM,KAAK,gBAAgB,UAAU,EAAE;AACvC,eAAW,KAAK,aAAa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rC,YAAM,KAAK,KAAK,KAAK,SAAS,EAAE;AAAA,IAClC;AAEA,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,KAAK,KAAK,KAAK,OAAO,EAAE;AAAA,IAChC;AAEA,UAAM,KAAK,EAAE;AACb,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,SAAS,OAAO;AACd,QAAI,KAAK,kDAAkD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACnH,WAAO;AAAA,EACT;AACF;AAWA,eAAsB,oCAAoC,SAQpB;AAGpC,SAAO,gCAAgC,SAAS,OAAO;AACzD;","names":[]}
1
+ {"version":3,"sources":["../src/causal-consolidation.ts"],"sourcesContent":["/**\n * causal-consolidation.ts — CMC Phase 2: LLM-Assisted Causal Consolidation\n *\n * Uses an LLM to analyze causal trajectory patterns across sessions.\n * The LLM receives the causal chain graph as context — connected trajectories\n * from different sessions — and identifies recurring behavioral patterns,\n * preference signals, and actionable rules.\n *\n * This is the core CMC innovation: the LLM gets cross-session causal context\n * that no other memory system provides. It can see that a user investigated\n * a bug in session 1, attempted a fix in session 2, and succeeded in session 3 —\n * and synthesize a rule or preference from that chain.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { resolveCausalTrajectoryStoreDir, type CausalTrajectoryRecord } from \"./causal-trajectory.js\";\nimport { readChainIndex, resolveChainsDir, type CausalChainIndex, type CausalEdge } from \"./causal-chain.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile, PluginConfig } from \"./types.js\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { runPostConsolidationMaterialize } from \"./connectors/codex-materialize-runner.js\";\nimport type { MaterializeResult, RolloutSummaryInput } from \"./connectors/codex-materialize.js\";\nimport { buildExtensionsBlockForConsolidation } from \"./semantic-consolidation.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CausalPatternCandidate {\n id: string;\n sourceType: \"causal-pattern\";\n subject: string;\n category: \"principle\" | \"rule\" | \"preference\";\n content: string;\n score: number;\n rationale: string;\n outcome: null;\n provenance: string[];\n agent: string | null;\n workflow: string | null;\n}\n\nexport interface ConsolidationConfig {\n minRecurrence: number;\n minSessions: number;\n successThreshold: number;\n}\n\nexport interface LlmConsolidationResult {\n rules: Array<{\n content: string;\n category: \"rule\" | \"principle\" | \"preference\";\n confidence: number;\n evidence: string[];\n }>;\n preferences: Array<{\n statement: string;\n confidence: number;\n evidence: string[];\n }>;\n}\n\nconst CAUSAL_RULE_CATEGORIES = new Set([\"rule\", \"principle\", \"preference\"]);\n\ninterface ConsolidationLlmClient {\n isAvailable(options?: { agentId?: string; modelChain?: AgentPersonaModelConfig }): boolean;\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: { temperature?: number; maxTokens?: number; agentId?: string; modelChain?: AgentPersonaModelConfig },\n ): Promise<{ content: string } | null>;\n}\n\n// ─── Trajectory Reading ──────────────────────────────────────────────────────\n\nasync function readAllTrajectories(\n memoryDir: string,\n causalTrajectoryStoreDir?: string,\n): Promise<CausalTrajectoryRecord[]> {\n const root = resolveCausalTrajectoryStoreDir(memoryDir, causalTrajectoryStoreDir);\n const trajectoriesDir = path.join(root, \"trajectories\");\n\n const files = await listJsonFiles(trajectoriesDir).catch(() => [] as string[]);\n const results: CausalTrajectoryRecord[] = [];\n\n for (const filePath of files) {\n try {\n const raw = await readJsonFile(filePath);\n if (isRecord(raw) && typeof raw.trajectoryId === \"string\") {\n results.push(raw as unknown as CausalTrajectoryRecord);\n }\n } catch {\n // skip invalid\n }\n }\n\n return results;\n}\n\n// ─── Context Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format trajectories and their causal connections as a readable context\n * for the LLM. Groups by session and shows chain connections.\n */\nfunction formatCausalContext(\n trajectories: CausalTrajectoryRecord[],\n chainIndex: CausalChainIndex,\n maxChars: number = 8000,\n): string {\n // Group trajectories by session\n const bySession = new Map<string, CausalTrajectoryRecord[]>();\n for (const t of trajectories) {\n const list = bySession.get(t.sessionKey) ?? [];\n list.push(t);\n bySession.set(t.sessionKey, list);\n }\n\n const lines: string[] = [];\n lines.push(`## Causal Trajectories (${trajectories.length} across ${bySession.size} sessions)`);\n lines.push(\"\");\n\n // Format each session's trajectories\n for (const [sessionKey, sessionTrajs] of bySession) {\n lines.push(`### Session: ${sessionKey}`);\n for (const t of sessionTrajs.slice(0, 5)) {\n const outcome = t.outcomeKind === \"success\" ? \"+\" : t.outcomeKind === \"failure\" ? \"-\" : \"~\";\n lines.push(`[${outcome}] Goal: ${t.goal}`);\n lines.push(` Action: ${t.actionSummary}`);\n lines.push(` Outcome: ${t.outcomeSummary}`);\n if (t.followUpSummary) lines.push(` Follow-up: ${t.followUpSummary}`);\n if (t.entityRefs?.length) lines.push(` Entities: ${t.entityRefs.join(\", \")}`);\n }\n lines.push(\"\");\n }\n\n // Format causal chain connections\n const edgeCount = Object.keys(chainIndex.edges).length;\n if (edgeCount > 0) {\n lines.push(`## Cross-Session Causal Chains (${edgeCount} connections)`);\n lines.push(\"\");\n\n const trajectoryMap = new Map(trajectories.map((t) => [t.trajectoryId, t]));\n const shown = new Set<string>();\n\n for (const [edgeId, edge] of Object.entries(chainIndex.edges)) {\n if (shown.size >= 10) break; // limit output size\n const from = trajectoryMap.get(edge.fromTrajectoryId);\n const to = trajectoryMap.get(edge.toTrajectoryId);\n if (!from || !to) continue;\n\n lines.push(`${edge.edgeType}: \"${from.goal}\" (${from.sessionKey}) → \"${to.goal}\" (${to.sessionKey})`);\n shown.add(edgeId);\n }\n lines.push(\"\");\n }\n\n const result = lines.join(\"\\n\");\n return result.length > maxChars ? result.slice(0, maxChars) + \"\\n[truncated]\" : result;\n}\n\n// ─── LLM Consolidation ──────────────────────────────────────────────────────\n\nconst CONSOLIDATION_PROMPT = `You are analyzing a user's causal trajectory history across multiple sessions. Trajectories record what the user tried to do (goal), what they did (action), and what happened (outcome).\n\nYour job is to identify:\n1. BEHAVIORAL RULES: Recurring patterns where the same approach consistently succeeds or fails. These should be actionable guidance for future sessions.\n2. PREFERENCES: What the user cares about, prefers, or consistently chooses — even if never explicitly stated. Infer preferences from what they repeatedly do, retry until successful, or always include in their workflow.\n\nIMPORTANT:\n- Look for CROSS-SESSION patterns — things that repeat across different sessions are more significant than within-session patterns.\n- A user who retries the same goal across sessions has a strong implicit preference for that outcome.\n- Consistent action choices reveal preferences even when the user never says \"I prefer X.\"\n- Frame preferences as \"The user would prefer responses that...\" when applicable.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\"content\": \"actionable rule text\", \"category\": \"rule|principle\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ],\n \"preferences\": [\n {\"statement\": \"The user would prefer...\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ]\n}\n\nIf no clear patterns exist, return {\"rules\": [], \"preferences\": []}.`;\n\nasync function consolidateWithLlm(\n context: string,\n llm: ConsolidationLlmClient,\n options: { agentId?: string; modelChain?: AgentPersonaModelConfig } = {},\n): Promise<LlmConsolidationResult> {\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CONSOLIDATION_PROMPT },\n { role: \"user\", content: context },\n ],\n { temperature: 0.2, maxTokens: 2000, agentId: options.agentId, modelChain: options.modelChain },\n );\n\n if (!response?.content) {\n return { rules: [], preferences: [] };\n }\n\n try {\n // Extract JSON from response (may have markdown code fences)\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 const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n const rawPreferences: unknown[] = Array.isArray(parsed.preferences) ? parsed.preferences : [];\n return {\n rules: rawRules\n .map(parseLlmRule)\n .filter((rule): rule is LlmConsolidationResult[\"rules\"][number] => !!rule),\n preferences: rawPreferences\n .map(parseLlmPreference)\n .filter((pref): pref is LlmConsolidationResult[\"preferences\"][number] => !!pref),\n };\n } catch {\n log.warn(\"[cmc] failed to parse LLM consolidation response\");\n return { rules: [], preferences: [] };\n }\n}\n\n// ─── Candidate Generation ────────────────────────────────────────────────────\n\nfunction stablePatternId(content: string): string {\n const digest = createHash(\"sha256\")\n .update(`causal-pattern\\0${content}`)\n .digest(\"hex\")\n .slice(0, 16);\n return `causal-pattern:${digest}`;\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 parseEvidence(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 parseLlmRule(raw: unknown): LlmConsolidationResult[\"rules\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const content = typeof r.content === \"string\" ? r.content.trim() : \"\";\n const category = typeof r.category === \"string\" ? r.category : \"\";\n const confidence = parseConfidence(r.confidence);\n if (content.length <= 5 || !CAUSAL_RULE_CATEGORIES.has(category) || confidence === undefined) {\n return undefined;\n }\n return {\n content,\n category: category as \"rule\" | \"principle\" | \"preference\",\n confidence,\n evidence: parseEvidence(r.evidence),\n };\n}\n\nfunction parseLlmPreference(raw: unknown): LlmConsolidationResult[\"preferences\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const p = raw as Record<string, unknown>;\n const statement = typeof p.statement === \"string\" ? p.statement.trim() : \"\";\n const confidence = parseConfidence(p.confidence);\n if (statement.length <= 5 || confidence === undefined) return undefined;\n return {\n statement,\n confidence,\n evidence: parseEvidence(p.evidence),\n };\n}\n\nfunction llmResultToCandidates(result: LlmConsolidationResult): CausalPatternCandidate[] {\n const candidates: CausalPatternCandidate[] = [];\n\n for (const rule of result.rules) {\n const category =\n rule.category === \"principle\" || rule.category === \"preference\"\n ? rule.category\n : \"rule\";\n candidates.push({\n id: stablePatternId(rule.content),\n sourceType: \"causal-pattern\",\n subject: rule.content.slice(0, 80),\n category,\n content: rule.content,\n score: Math.min(1, rule.confidence ?? 0.7),\n rationale: \"LLM-identified causal pattern from cross-session trajectory analysis\",\n outcome: null,\n provenance: (rule.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n for (const preference of result.preferences) {\n candidates.push({\n id: stablePatternId(preference.statement),\n sourceType: \"causal-pattern\",\n subject: preference.statement.slice(0, 80),\n category: \"preference\",\n content: preference.statement,\n score: Math.min(1, preference.confidence ?? 0.7),\n rationale: \"LLM-identified preference from cross-session trajectory analysis\",\n outcome: null,\n provenance: (preference.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n return candidates;\n}\n\nfunction normalizePositiveInteger(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\nfunction normalizeSuccessThreshold(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(1, value);\n}\n\nfunction trajectorySuccessScore(trajectory: CausalTrajectoryRecord): number {\n if (trajectory.outcomeKind === \"success\") return 1;\n if (trajectory.outcomeKind === \"partial\") return 0.5;\n return 0;\n}\n\nfunction averageSuccessScore(trajectories: CausalTrajectoryRecord[]): number {\n if (trajectories.length === 0) return 0;\n const total = trajectories.reduce((sum, trajectory) => sum + trajectorySuccessScore(trajectory), 0);\n return total / trajectories.length;\n}\n\nfunction passesConsolidationGates(\n trajectories: CausalTrajectoryRecord[],\n config: ConsolidationConfig,\n): boolean {\n const minRecurrence = normalizePositiveInteger(config.minRecurrence, 1);\n if (trajectories.length < minRecurrence) return false;\n\n const minSessions = normalizePositiveInteger(config.minSessions, 1);\n const sessionCount = new Set(trajectories.map((trajectory) => trajectory.sessionKey)).size;\n if (sessionCount < minSessions) return false;\n\n const successThreshold = normalizeSuccessThreshold(config.successThreshold);\n if (successThreshold > 0 && averageSuccessScore(trajectories) < successThreshold) {\n return false;\n }\n\n return true;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run LLM-assisted consolidation: read trajectories, format causal context,\n * ask LLM to identify patterns and preferences.\n */\nexport async function deriveCausalPromotionCandidates(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n config: ConsolidationConfig;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n llmClient?: ConsolidationLlmClient;\n}): Promise<CausalPatternCandidate[]> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (!passesConsolidationGates(trajectories, options.config)) return [];\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n\n // Format the causal context for the LLM\n let context = formatCausalContext(trajectories, chainIndex);\n\n // Append memory extensions block if available (#382)\n if (options.pluginConfig) {\n const extBlock = await buildExtensionsBlockForConsolidation(options.pluginConfig);\n if (extBlock.length > 0) {\n context += \"\\n\\n\" + extBlock;\n }\n }\n\n // If no LLM available, fall back to empty (no deterministic fallback)\n const llm = options.llmClient ?? new FallbackLlmClient(\n options.gatewayConfig,\n options.pluginConfig\n ? fallbackLlmRuntimeContextFromConfig(options.pluginConfig, {\n workspaceDir: options.workspaceDir ?? options.pluginConfig.workspaceDir,\n })\n : { workspaceDir: options.workspaceDir },\n );\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) {\n log.debug(\"[cmc] no LLM available for consolidation — skipping\");\n return [];\n }\n\n // Call LLM for pattern analysis\n const result = await consolidateWithLlm(context, llm, llmOptions);\n const candidates = llmResultToCandidates(result);\n\n log.debug(`[cmc] LLM consolidation produced ${candidates.length} rule(s) and ${result.preferences.length} preference(s)`);\n return candidates;\n } catch (error) {\n log.warn(`[cmc] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Get LLM-synthesized preferences from causal trajectory analysis.\n * Returns formatted preference statements for recall injection.\n */\nexport async function synthesizeCausalPreferencesViaLlm(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n minTrajectories?: number;\n}): Promise<string | null> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (trajectories.length < (options.minTrajectories ?? 2)) return null;\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n const context = formatCausalContext(trajectories, chainIndex);\n\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) return null;\n\n const result = await consolidateWithLlm(context, llm, llmOptions);\n if (result.preferences.length === 0 && result.rules.length === 0) return null;\n\n const lines: string[] = [\"## Behavioral Insights (from Causal Chain Analysis)\", \"\"];\n\n for (const pref of result.preferences) {\n lines.push(`- ${pref.statement}`);\n }\n\n for (const rule of result.rules) {\n lines.push(`- ${rule.content}`);\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n } catch (error) {\n log.warn(`[cmc] preference synthesis failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n}\n\n/**\n * Optional post-consolidation hook — materializes Codex-native memory artifacts\n * after a causal consolidation run. Guarded by `codexMaterializeMemories` and\n * `codexMaterializeOnConsolidation`. Returns `null` when disabled or when the\n * sentinel is missing (honors user hand-edits).\n *\n * Split from the orchestrator-owned flow so #378 avoids touching\n * orchestrator.ts while Wave 1 edits are in flight.\n */\nexport async function materializeAfterCausalConsolidation(options: {\n config: PluginConfig;\n namespace?: string;\n memories?: MemoryFile[];\n memoryDir?: string;\n codexHome?: string;\n rolloutSummaries?: RolloutSummaryInput[];\n now?: Date;\n}): Promise<MaterializeResult | null> {\n // Delegates to the shared post-consolidation helper — see\n // runPostConsolidationMaterialize in codex-materialize-runner.ts.\n return runPostConsolidationMaterialize(\"[cmc]\", options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAO3B,OAAO,UAAU;AA0CjB,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,aAAa,YAAY,CAAC;AAY1E,eAAe,oBACb,WACA,0BACmC;AACnC,QAAM,OAAO,gCAAgC,WAAW,wBAAwB;AAChF,QAAM,kBAAkB,KAAK,KAAK,MAAM,cAAc;AAEtD,QAAM,QAAQ,MAAM,cAAc,eAAe,EAAE,MAAM,MAAM,CAAC,CAAa;AAC7E,QAAM,UAAoC,CAAC;AAE3C,aAAW,YAAY,OAAO;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,aAAa,QAAQ;AACvC,UAAI,SAAS,GAAG,KAAK,OAAO,IAAI,iBAAiB,UAAU;AACzD,gBAAQ,KAAK,GAAwC;AAAA,MACvD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO;AACT;AAQA,SAAS,oBACP,cACA,YACA,WAAmB,KACX;AAER,QAAM,YAAY,oBAAI,IAAsC;AAC5D,aAAW,KAAK,cAAc;AAC5B,UAAM,OAAO,UAAU,IAAI,EAAE,UAAU,KAAK,CAAC;AAC7C,SAAK,KAAK,CAAC;AACX,cAAU,IAAI,EAAE,YAAY,IAAI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,CAAC,IAAI,YAAY,UAAU,EAAG,QAAO;AAEzC,UAAM,SAAS,MAAM,mBAAmB,SAAS,KAAK,UAAU;AAChE,QAAI,OAAO,YAAY,WAAW,KAAK,OAAO,MAAM,WAAW,EAAG,QAAO;AAEzE,UAAM,QAAkB,CAAC,uDAAuD,EAAE;AAElF,eAAW,QAAQ,OAAO,aAAa;AACrC,YAAM,KAAK,KAAK,KAAK,SAAS,EAAE;AAAA,IAClC;AAEA,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,KAAK,KAAK,KAAK,OAAO,EAAE;AAAA,IAChC;AAEA,UAAM,KAAK,EAAE;AACb,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,SAAS,OAAO;AACd,QAAI,KAAK,kDAAkD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACnH,WAAO;AAAA,EACT;AACF;AAWA,eAAsB,oCAAoC,SAQpB;AAGpC,SAAO,gCAAgC,SAAS,OAAO;AACzD;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { a as GraphEdge } from './graph-DRkl22KE.js';
2
2
  import { CausalTrajectoryRecord } from './causal-trajectory.js';
3
3
  import './capabilities.js';
4
- import './types-Cyr32ABj.js';
4
+ import './types-nJV23pa3.js';
5
5
  import './message-parts/index.js';
6
6
  import './bounded-jsonl-state.js';
7
7
  import './operator-doctor-types.js';
@@ -19,7 +19,9 @@ import {
19
19
  // src/access-offline-manifest.ts
20
20
  import * as nodePath from "path";
21
21
  function planServerIdentityCacheWrite(input) {
22
- const entries = input.streamCompleted ? [...input.persisted.values()].filter((entry) => input.yieldedPaths.has(entry.path)) : [...input.persisted.values()];
22
+ const entries = input.streamCompleted ? [...input.persisted.values()].filter(
23
+ (entry) => input.yieldedPaths.has(entry.path) || input.retainedPaths?.has(entry.path)
24
+ ) : [...input.persisted.values()];
23
25
  return { shouldWrite: input.cacheDirty || entries.length !== input.persisted.size, entries };
24
26
  }
25
27
  function serverIdentityCachePath(storageDir) {
@@ -87,7 +89,8 @@ async function mergeServerIdentityCacheEntries(fs, cachePath, entries, citationT
87
89
  ...entry.memory ? {} : {
88
90
  ...typeof entry.normalizerVersion === "number" ? { normalizerVersion: entry.normalizerVersion } : {},
89
91
  ...typeof entry.identityResolutionVersion === "number" ? { identityResolutionVersion: entry.identityResolutionVersion } : {}
90
- }
92
+ },
93
+ ...entry.statIdentity !== void 0 && entry.excluded !== void 0 ? { statIdentity: entry.statIdentity, excluded: entry.excluded } : {}
91
94
  });
92
95
  }
93
96
  }
@@ -95,6 +98,25 @@ async function mergeServerIdentityCacheEntries(fs, cachePath, entries, citationT
95
98
  }
96
99
  return [...merged.values()];
97
100
  }
101
+ function retainExcludedClassifications(input) {
102
+ const retained = /* @__PURE__ */ new Set();
103
+ let changed = false;
104
+ for (const [pathName, classification] of input.classifications) {
105
+ if (input.yieldedPaths.has(pathName)) continue;
106
+ retained.add(pathName);
107
+ const entry = input.persisted.get(pathName) ?? { path: pathName, sha256: "" };
108
+ if (entry.statIdentity === classification.statIdentity && entry.excluded === classification.excluded) {
109
+ continue;
110
+ }
111
+ input.persisted.set(pathName, {
112
+ ...entry,
113
+ statIdentity: classification.statIdentity,
114
+ excluded: classification.excluded
115
+ });
116
+ changed = true;
117
+ }
118
+ return { retained, changed };
119
+ }
98
120
  async function createOfflineSyncManifestStream(orchestrator, namespace, userExcludeRegexps, options, parseMemory) {
99
121
  const storage = await offlineSyncStorageForSnapshot(orchestrator, namespace);
100
122
  const citationTemplate = orchestrator.config.inlineSourceAttributionFormat;
@@ -118,10 +140,12 @@ async function createOfflineSyncManifestStream(orchestrator, namespace, userExcl
118
140
  let streamCompleted = false;
119
141
  const persistedEntries = new Map(identityCache);
120
142
  const yieldedPaths = /* @__PURE__ */ new Set();
143
+ const retainedPaths = /* @__PURE__ */ new Set();
121
144
  const flush = async () => {
122
145
  const { shouldWrite, entries } = planServerIdentityCacheWrite({
123
146
  persisted: persistedEntries,
124
147
  yieldedPaths,
148
+ retainedPaths,
125
149
  streamCompleted,
126
150
  cacheDirty
127
151
  });
@@ -207,6 +231,13 @@ async function createOfflineSyncManifestStream(orchestrator, namespace, userExcl
207
231
  }
208
232
  streamCompleted = true;
209
233
  } finally {
234
+ const retained = retainExcludedClassifications({
235
+ persisted: persistedEntries,
236
+ classifications: classificationUpdates,
237
+ yieldedPaths
238
+ });
239
+ for (const pathName of retained.retained) retainedPaths.add(pathName);
240
+ if (retained.changed) cacheDirty = true;
210
241
  await flush();
211
242
  }
212
243
  })()
@@ -215,6 +246,8 @@ async function createOfflineSyncManifestStream(orchestrator, namespace, userExcl
215
246
 
216
247
  export {
217
248
  planServerIdentityCacheWrite,
249
+ mergeServerIdentityCacheEntries,
250
+ retainExcludedClassifications,
218
251
  createOfflineSyncManifestStream
219
252
  };
220
- //# sourceMappingURL=chunk-B36GUU6T.js.map
253
+ //# sourceMappingURL=chunk-23HFXQ5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-offline-manifest.ts"],"sourcesContent":["import * as nodePath from \"node:path\";\nimport { offlineSyncStorageForSnapshot } from \"./offline-sync-impression-drain.js\";\nimport { iterateOfflineSyncSnapshotFileRecords } from \"./offline-sync.js\";\nimport type { Orchestrator } from \"./orchestrator.js\";\nimport {\n CONTENT_HASH_NORMALIZER_VERSION,\n IDENTITY_RESOLUTION_VERSION,\n RECONCILE_MANIFEST_FORMAT,\n RECONCILE_MANIFEST_SCHEMA_VERSION,\n type ReconcileManifest,\n type ReconcileManifestFile,\n type ReconcileMemoryIdentity,\n type ReconcileMemoryParser,\n buildReconcileManifestFile,\n citationTemplateFingerprint,\n isCachedIdentityReusable,\n isReconcileMemoryIdentity,\n} from \"./reconcile/manifest.js\";\nimport { createPersistedSupportPassportPrivateFileExclusion } from \"./support-passport/card-projection.js\";\n\nexport interface OfflineSyncManifestRequest {\n includeTranscripts?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface OfflineSyncManifestStreamResponse extends Omit<ReconcileManifest, \"files\"> {\n namespace: string;\n files: AsyncIterable<ReconcileManifestFile>;\n}\n\nexport interface ServerIdentityCacheEntry {\n path: string;\n sha256: string;\n memory?: ReconcileMemoryIdentity;\n /** Stamped on sha-only entries so an upgrade re-parses them. */\n normalizerVersion?: number;\n identityResolutionVersion?: number;\n /** Stat identity the exclusion classification was computed against. */\n statIdentity?: string;\n /** Persisted support-passport private-memory classification for statIdentity. */\n excluded?: boolean;\n}\n\n/**\n * Decide what the manifest stream should persist, and whether a write is\n * needed at all.\n *\n * A write is required whenever the persisted set changed — an identity was\n * rebuilt, or an entry was dropped because its file lost its identity — and\n * also when a completed walk leaves entries for paths it never saw, which are\n * files that have since been deleted. Skipping the write in that last case\n * would strand those entries on disk forever.\n *\n * Pruning is gated on the walk completing: an aborted or partially consumed\n * stream has simply not observed the remaining paths, so it may only add.\n */\nexport function planServerIdentityCacheWrite(input: {\n persisted: ReadonlyMap<string, ServerIdentityCacheEntry>;\n yieldedPaths: ReadonlySet<string>;\n /** Paths the walk saw but never yielded (removed by the exclusion\n * callback). Not deleted — pruning them would drop their persisted\n * classification and force a re-classify on every later cycle. */\n retainedPaths?: ReadonlySet<string>;\n streamCompleted: boolean;\n cacheDirty: boolean;\n}): { shouldWrite: boolean; entries: ServerIdentityCacheEntry[] } {\n const entries = input.streamCompleted\n ? [...input.persisted.values()].filter(\n (entry) => input.yieldedPaths.has(entry.path) || input.retainedPaths?.has(entry.path)\n )\n : [...input.persisted.values()];\n return { shouldWrite: input.cacheDirty || entries.length !== input.persisted.size, entries };\n}\n\n/**\n * The cache lives under `.remnic/` rather than `state/`: snapshot enumeration\n * excludes internal `.remnic/` paths structurally (`isInternalRemnicStatePath`),\n * whereas `state/` is only filtered by an allowlist of known node-local\n * artifacts. Under `state/` this node-local cache would be advertised as a peer\n * file, so convergence would transfer the cache itself — and the stream rewrites\n * it during finalization, so the advertised digest could go stale mid-transfer.\n */\nfunction serverIdentityCachePath(storageDir: string): string {\n return nodePath.join(storageDir, \".remnic\", \"state\", \"converge-identity-cache.json\");\n}\n\nasync function loadServerIdentityCache(\n storageDir: string,\n citationTemplate?: string\n): Promise<Map<string, ServerIdentityCacheEntry>> {\n const cache = new Map<string, ServerIdentityCacheEntry>();\n try {\n const raw = JSON.parse(\n await import(\"node:fs/promises\").then((fs) => fs.readFile(serverIdentityCachePath(storageDir), \"utf8\"))\n ) as {\n citationTemplate?: string;\n files?: unknown[];\n };\n // Identities are derived after stripping inline attribution for a specific\n // citation template; entries written under a different one would produce\n // wrong contentHash values for unchanged files.\n if (raw.citationTemplate !== citationTemplateFingerprint(citationTemplate)) return cache;\n for (const candidate of raw.files ?? []) {\n const entry = candidate as Partial<ServerIdentityCacheEntry> | null;\n if (typeof entry?.path !== \"string\" || typeof entry.sha256 !== \"string\") continue;\n if (entry.memory !== undefined && !isReconcileMemoryIdentity(entry.memory)) continue;\n if (entry.statIdentity !== undefined && typeof entry.statIdentity !== \"string\") continue;\n if (entry.excluded !== undefined && typeof entry.excluded !== \"boolean\") continue;\n if (entry.normalizerVersion !== undefined && typeof entry.normalizerVersion !== \"number\") continue;\n if (entry.identityResolutionVersion !== undefined && typeof entry.identityResolutionVersion !== \"number\") {\n continue;\n }\n cache.set(entry.path, {\n path: entry.path,\n sha256: entry.sha256,\n ...(entry.memory ? { memory: entry.memory } : {}),\n ...(entry.memory\n ? {}\n : {\n ...(typeof entry.normalizerVersion === \"number\" ? { normalizerVersion: entry.normalizerVersion } : {}),\n ...(typeof entry.identityResolutionVersion === \"number\"\n ? { identityResolutionVersion: entry.identityResolutionVersion }\n : {}),\n }),\n ...(entry.statIdentity !== undefined && entry.excluded !== undefined\n ? { statIdentity: entry.statIdentity, excluded: entry.excluded }\n : {}),\n });\n }\n } catch {\n // missing or corrupt cache: cold build\n }\n return cache;\n}\n\nconst serverIdentityCacheWriteLocks = new Map<string, Promise<void>>();\n\n/** Serialize cache replacements per path: overlapping manifest streams for one\n * namespace would otherwise each publish a whole-file snapshot, and the slower\n * stream built from older filesystem state would overwrite the newer one. */\nasync function withServerIdentityCacheWriteLock(cachePath: string, write: () => Promise<void>): Promise<void> {\n const previous = serverIdentityCacheWriteLocks.get(cachePath) ?? Promise.resolve();\n const next = previous.then(write, write);\n serverIdentityCacheWriteLocks.set(cachePath, next);\n try {\n await next;\n } finally {\n if (serverIdentityCacheWriteLocks.get(cachePath) === next) {\n serverIdentityCacheWriteLocks.delete(cachePath);\n }\n }\n}\n\n/** Union of the entries being written and the current on-disk set; on conflict\n * the write wins (it reflects the newer run). Callers hold the write lock. */\nexport async function mergeServerIdentityCacheEntries(\n fs: typeof import(\"node:fs/promises\"),\n cachePath: string,\n entries: readonly ServerIdentityCacheEntry[],\n citationTemplate: string | undefined,\n dropped: ReadonlySet<string> = new Set()\n): Promise<ServerIdentityCacheEntry[]> {\n const merged = new Map(entries.map((entry) => [entry.path, entry]));\n try {\n const raw = JSON.parse(await fs.readFile(cachePath, \"utf8\")) as {\n citationTemplate?: string;\n files?: unknown[];\n };\n if (raw.citationTemplate === citationTemplateFingerprint(citationTemplate)) {\n for (const candidate of raw.files ?? []) {\n const entry = candidate as Partial<ServerIdentityCacheEntry> | null;\n if (typeof entry?.path !== \"string\" || typeof entry.sha256 !== \"string\") continue;\n if (entry.memory !== undefined && !isReconcileMemoryIdentity(entry.memory)) continue;\n if (dropped.has(entry.path) || merged.has(entry.path)) continue;\n merged.set(entry.path, {\n path: entry.path,\n sha256: entry.sha256,\n ...(entry.memory ? { memory: entry.memory } : {}),\n ...(entry.memory\n ? {}\n : {\n ...(typeof entry.normalizerVersion === \"number\" ? { normalizerVersion: entry.normalizerVersion } : {}),\n ...(typeof entry.identityResolutionVersion === \"number\"\n ? { identityResolutionVersion: entry.identityResolutionVersion }\n : {}),\n }),\n ...(entry.statIdentity !== undefined && entry.excluded !== undefined\n ? { statIdentity: entry.statIdentity, excluded: entry.excluded }\n : {}),\n });\n }\n }\n } catch {\n // missing or unreadable current cache: the write set stands alone\n }\n return [...merged.values()];\n}\n\n/** Record classifications for files the walk excluded (the exclusion callback\n * returned true, so they were never yielded): they were seen this walk, so\n * their entries must persist and must not be pruned as deleted. Mirrors the\n * per-yield classification application for never-yielded paths. */\nexport function retainExcludedClassifications(input: {\n persisted: Map<string, ServerIdentityCacheEntry>;\n classifications: ReadonlyMap<string, { statIdentity: string; excluded: boolean }>;\n yieldedPaths: ReadonlySet<string>;\n}): { retained: Set<string>; changed: boolean } {\n const retained = new Set<string>();\n let changed = false;\n for (const [pathName, classification] of input.classifications) {\n if (input.yieldedPaths.has(pathName)) continue;\n retained.add(pathName);\n const entry = input.persisted.get(pathName) ?? { path: pathName, sha256: \"\" };\n if (entry.statIdentity === classification.statIdentity && entry.excluded === classification.excluded) {\n continue;\n }\n input.persisted.set(pathName, {\n ...entry,\n statIdentity: classification.statIdentity,\n excluded: classification.excluded,\n });\n changed = true;\n }\n return { retained, changed };\n}\n\nexport async function createOfflineSyncManifestStream(\n orchestrator: Orchestrator,\n namespace: string,\n userExcludeRegexps: RegExp[],\n options: OfflineSyncManifestRequest,\n parseMemory: ReconcileMemoryParser\n): Promise<OfflineSyncManifestStreamResponse> {\n const storage = await offlineSyncStorageForSnapshot(orchestrator, namespace);\n const citationTemplate = orchestrator.config.inlineSourceAttributionFormat;\n const identityCache = await loadServerIdentityCache(storage.dir, citationTemplate);\n // The exclusion callback runs before every yield; without the persisted\n // classification it would read and parse every candidate file, defeating the\n // warm-cache skip entirely.\n const classificationUpdates = new Map<string, { statIdentity: string; excluded: boolean }>();\n const snapshotFiles = iterateOfflineSyncSnapshotFileRecords({\n root: storage.dir,\n includeContent: false,\n includeTranscripts: options.includeTranscripts !== false,\n readFileDigest: async ({ filePath }) => storage.digestOfflineSyncFile(filePath),\n signal: options.signal,\n userExcludeRegexps,\n excludeFile: createPersistedSupportPassportPrivateFileExclusion(storage, identityCache, classificationUpdates),\n });\n return {\n namespace,\n format: RECONCILE_MANIFEST_FORMAT,\n schemaVersion: RECONCILE_MANIFEST_SCHEMA_VERSION,\n files: (async function* () {\n // Any change to the persisted set, not just a rebuilt identity: a file\n // that lost its identity, or a completed walk that must prune vanished\n // paths, also has to reach disk or the removal is lost forever.\n let cacheDirty = false;\n let streamCompleted = false;\n // Seeded with every previously cached entry so a partially consumed\n // stream (client disconnect, abort) can only add to the cache. Writing\n // just this run's rebuilds would drop every cache hit, so one edit to a\n // large corpus would shrink the cache to that single entry and force a\n // near-cold rebuild on the next request.\n const persistedEntries = new Map(identityCache);\n const yieldedPaths = new Set<string>();\n const retainedPaths = new Set<string>();\n const flush = async (): Promise<void> => {\n const { shouldWrite, entries } = planServerIdentityCacheWrite({\n persisted: persistedEntries,\n yieldedPaths,\n retainedPaths,\n streamCompleted,\n cacheDirty,\n });\n if (!shouldWrite) return;\n try {\n const fs = await import(\"node:fs/promises\");\n const cachePath = serverIdentityCachePath(storage.dir);\n await withServerIdentityCacheWriteLock(cachePath, async () => {\n // Merge with whatever is on disk NOW: a concurrent stream for the\n // same namespace may have published newer entries after this\n // request loaded its snapshot, and a blind whole-file replace\n // would discard them.\n const written = new Set(entries.map((entry) => entry.path));\n const dropped = streamCompleted\n ? new Set([...identityCache.keys()].filter((pathName) => !written.has(pathName)))\n : new Set<string>();\n const merged = await mergeServerIdentityCacheEntries(\n fs,\n cachePath,\n entries,\n citationTemplate,\n dropped\n );\n await fs.mkdir(nodePath.dirname(cachePath), { recursive: true });\n const tmp = `${cachePath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;\n await fs.writeFile(\n tmp,\n JSON.stringify({ citationTemplate: citationTemplateFingerprint(citationTemplate), files: merged })\n );\n await fs.rename(tmp, cachePath);\n });\n } catch {\n // cache persistence is best-effort\n }\n };\n try {\n const applyClassification = (path: string, sha256: string): void => {\n const classification = classificationUpdates.get(path);\n if (classification === undefined) return;\n const entry = persistedEntries.get(path) ?? { path, sha256 };\n if (entry.statIdentity === classification.statIdentity && entry.excluded === classification.excluded) {\n return;\n }\n persistedEntries.set(path, {\n ...entry,\n ...(entry.memory ? { memory: entry.memory } : {}),\n statIdentity: classification.statIdentity,\n excluded: classification.excluded,\n });\n cacheDirty = true;\n };\n for await (const file of snapshotFiles) {\n yieldedPaths.add(file.path);\n const cached = identityCache.get(file.path);\n if (\n cached !== undefined &&\n cached.sha256.toLowerCase() === file.sha256.toLowerCase() &&\n isCachedIdentityReusable(cached)\n ) {\n applyClassification(file.path, file.sha256);\n yield {\n ...file,\n ...(cached.memory\n ? { memory: cached.memory }\n : {\n normalizerVersion: cached.normalizerVersion,\n identityResolutionVersion: cached.identityResolutionVersion,\n }),\n };\n continue;\n }\n const built = await buildReconcileManifestFile(\n file,\n async ({ path }) => storage.readOfflineSyncFile(nodePath.join(storage.dir, path)),\n parseMemory,\n citationTemplate\n );\n // Negative results persist too: a memory-shaped file that parses\n // without an identity would otherwise be re-read on every warm run.\n const previous = persistedEntries.get(built.path);\n if (previous?.sha256 !== built.sha256 || (built.memory !== undefined && previous?.memory !== built.memory)) {\n cacheDirty = true;\n }\n if (built.memory === undefined && built.normalizerVersion === undefined) {\n // Read failed: do not persist a negative identity for this SHA.\n yield built;\n continue;\n }\n persistedEntries.set(built.path, {\n path: built.path,\n sha256: built.sha256,\n ...(built.memory !== undefined\n ? { memory: built.memory }\n : {\n normalizerVersion: built.normalizerVersion,\n identityResolutionVersion: built.identityResolutionVersion,\n }),\n });\n applyClassification(built.path, built.sha256);\n yield built;\n }\n streamCompleted = true;\n } finally {\n // Files the exclusion callback removed from the snapshot were seen\n // this walk but never yielded: persist their classifications so the\n // next cycle skips the read+parse, and keep them out of the\n // deleted-path prune.\n const retained = retainExcludedClassifications({\n persisted: persistedEntries,\n classifications: classificationUpdates,\n yieldedPaths,\n });\n for (const pathName of retained.retained) retainedPaths.add(pathName);\n if (retained.changed) cacheDirty = true;\n await flush();\n }\n })(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,YAAY,cAAc;AAwDnB,SAAS,6BAA6B,OASqB;AAChE,QAAM,UAAU,MAAM,kBAClB,CAAC,GAAG,MAAM,U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B,OAAO;AAAA,gBAC1B,2BAA2B,OAAO;AAAA,cACpC;AAAA,YACN;AACA;AAAA,UACF;AACA,gBAAM,QAAQ,MAAM;AAAA,YAClB;AAAA,YACA,OAAO,EAAE,KAAK,MAAM,QAAQ,oBAA6B,cAAK,QAAQ,KAAK,IAAI,CAAC;AAAA,YAChF;AAAA,YACA;AAAA,UACF;AAGA,gBAAM,WAAW,iBAAiB,IAAI,MAAM,IAAI;AAChD,cAAI,UAAU,WAAW,MAAM,UAAW,MAAM,WAAW,UAAa,UAAU,WAAW,MAAM,QAAS;AAC1G,yBAAa;AAAA,UACf;AACA,cAAI,MAAM,WAAW,UAAa,MAAM,sBAAsB,QAAW;AAEvE,kBAAM;AACN;AAAA,UACF;AACA,2BAAiB,IAAI,MAAM,MAAM;AAAA,YAC/B,MAAM,MAAM;AAAA,YACZ,QAAQ,MAAM;AAAA,YACd,GAAI,MAAM,WAAW,SACjB,EAAE,QAAQ,MAAM,OAAO,IACvB;AAAA,cACE,mBAAmB,MAAM;AAAA,cACzB,2BAA2B,MAAM;AAAA,YACnC;AAAA,UACN,CAAC;AACD,8BAAoB,MAAM,MAAM,MAAM,MAAM;AAC5C,gBAAM;AAAA,QACR;AACA,0BAAkB;AAAA,MACpB,UAAE;AAKA,cAAM,WAAW,8BAA8B;AAAA,UAC7C,WAAW;AAAA,UACX,iBAAiB;AAAA,UACjB;AAAA,QACF,CAAC;AACD,mBAAW,YAAY,SAAS,SAAU,eAAc,IAAI,QAAQ;AACpE,YAAI,SAAS,QAAS,cAAa;AACnC,cAAM,MAAM;AAAA,MACd;AAAA,IACF,GAAG;AAAA,EACL;AACF;","names":[]}
@@ -1,8 +1,12 @@
1
1
  import {
2
2
  isLoopbackHost
3
3
  } from "./chunk-C5C7IJ4Q.js";
4
+ import {
5
+ expandTildePath
6
+ } from "./chunk-6KH5NLQS.js";
4
7
 
5
8
  // src/background-generation-config.ts
9
+ import { readFileSync } from "fs";
6
10
  function stripTrailingSlashes(value) {
7
11
  let end = value.length;
8
12
  while (end > 0 && value.charCodeAt(end - 1) === 47) {
@@ -44,14 +48,13 @@ function parseBackgroundGenerationObject(raw, keyName) {
44
48
  if (typeof tokenRaw !== "string" || tokenRaw.length === 0) {
45
49
  throw new Error(`${keyName} must include a token`);
46
50
  }
47
- const timeoutRaw = record.timeoutSeconds;
51
+ const timeoutRaw = record.timeoutSeconds ?? record.timeout_seconds;
48
52
  let timeoutSeconds = 120;
49
53
  if (timeoutRaw !== void 0) {
50
- const parsed = typeof timeoutRaw === "number" ? timeoutRaw : Number(timeoutRaw);
51
- if (!Number.isFinite(parsed) || parsed <= 0) {
54
+ if (typeof timeoutRaw !== "number" || !Number.isFinite(timeoutRaw) || timeoutRaw <= 0) {
52
55
  throw new Error(`${keyName} timeoutSeconds must be a finite number > 0`);
53
56
  }
54
- timeoutSeconds = parsed;
57
+ timeoutSeconds = timeoutRaw;
55
58
  }
56
59
  return {
57
60
  endpoint: parseBackgroundEndpoint(endpointRaw, `${keyName}.endpoint`),
@@ -59,13 +62,33 @@ function parseBackgroundGenerationObject(raw, keyName) {
59
62
  timeoutSeconds
60
63
  };
61
64
  }
62
- function parseBackgroundGeneration(cfg) {
65
+ function parseBackgroundGeneration(cfg, expandEnv) {
66
+ const pathRaw = cfg.llmBridgeClientConfigPath;
67
+ let fromFile;
68
+ if (pathRaw !== void 0 && pathRaw !== null && pathRaw !== "") {
69
+ if (typeof pathRaw !== "string") {
70
+ throw new Error("llmBridgeClientConfigPath must be a string");
71
+ }
72
+ const expanded = expandTildePath(expandEnv(pathRaw.trim()));
73
+ let parsed;
74
+ try {
75
+ parsed = JSON.parse(readFileSync(expanded, "utf8"));
76
+ } catch {
77
+ throw new Error(`llmBridgeClientConfigPath could not be read: ${expanded}`);
78
+ }
79
+ fromFile = parseBackgroundGenerationObject(parsed, "llmBridgeClientConfigPath");
80
+ }
63
81
  const explicitRaw = cfg.backgroundGeneration;
64
- if (explicitRaw === void 0 || explicitRaw === null) return void 0;
65
- return parseBackgroundGenerationObject(explicitRaw, "backgroundGeneration");
82
+ const fromExplicit = explicitRaw === void 0 || explicitRaw === null ? void 0 : parseBackgroundGenerationObject(explicitRaw, "backgroundGeneration");
83
+ if (!fromFile && !fromExplicit) return void 0;
84
+ return {
85
+ endpoint: fromExplicit?.endpoint ?? fromFile.endpoint,
86
+ token: fromExplicit?.token ?? fromFile.token,
87
+ timeoutSeconds: fromExplicit?.timeoutSeconds ?? fromFile.timeoutSeconds
88
+ };
66
89
  }
67
90
 
68
91
  export {
69
92
  parseBackgroundGeneration
70
93
  };
71
- //# sourceMappingURL=chunk-YFTNZMGR.js.map
94
+ //# sourceMappingURL=chunk-27NO2KVB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/background-generation-config.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\n\nimport { isLoopbackHost } from \"./runtime/http-transport.js\";\nimport { expandTildePath } from \"./utils/path.js\";\n\nexport interface BackgroundGenerationConfig {\n /** Full chat-completions URL. Never used as the global OpenAI base URL. */\n endpoint: string;\n /** Loopback bearer from the generated client file. */\n token: string;\n timeoutSeconds: number;\n}\n\nfunction stripTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) {\n end -= 1;\n }\n return end === value.length ? value : value.slice(0, end);\n}\n\nfunction parseBackgroundEndpoint(value: string, keyName: string): string {\n const trimmed = stripTrailingSlashes(value.trim());\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw new Error(`${keyName} must be an absolute HTTP or HTTPS URL`);\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(`${keyName} must use HTTP or HTTPS`);\n }\n if (parsed.protocol === \"http:\" && !isLoopbackHost(parsed.hostname)) {\n throw new Error(`${keyName} must use HTTPS unless the host is loopback`);\n }\n if (parsed.username || parsed.password || parsed.search || parsed.hash) {\n throw new Error(\n `${keyName} must not include credentials, query parameters, or fragments`,\n );\n }\n return trimmed;\n}\n\nfunction parseBackgroundGenerationObject(\n raw: unknown,\n keyName: string,\n): BackgroundGenerationConfig {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(`${keyName} must be an object`);\n }\n const record = raw as Record<string, unknown>;\n const endpointRaw = record.endpoint;\n if (typeof endpointRaw !== \"string\" || endpointRaw.trim().length === 0) {\n throw new Error(`${keyName} must include an endpoint URL`);\n }\n const tokenRaw = record.token;\n if (typeof tokenRaw !== \"string\" || tokenRaw.length === 0) {\n throw new Error(`${keyName} must include a token`);\n }\n const timeoutRaw = record.timeoutSeconds ?? record.timeout_seconds;\n let timeoutSeconds = 120;\n if (timeoutRaw !== undefined) {\n if (typeof timeoutRaw !== \"number\" || !Number.isFinite(timeoutRaw) || timeoutRaw <= 0) {\n throw new Error(`${keyName} timeoutSeconds must be a finite number > 0`);\n }\n timeoutSeconds = timeoutRaw;\n }\n return {\n endpoint: parseBackgroundEndpoint(endpointRaw, `${keyName}.endpoint`),\n token: tokenRaw,\n timeoutSeconds,\n };\n}\n\nexport function parseBackgroundGeneration(\n cfg: Record<string, unknown>,\n expandEnv: (value: string) => string,\n): BackgroundGenerationConfig | undefined {\n const pathRaw = cfg.llmBridgeClientConfigPath;\n let fromFile: BackgroundGenerationConfig | undefined;\n if (pathRaw !== undefined && pathRaw !== null && pathRaw !== \"\") {\n if (typeof pathRaw !== \"string\") {\n throw new Error(\"llmBridgeClientConfigPath must be a string\");\n }\n const expanded = expandTildePath(expandEnv(pathRaw.trim()));\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(expanded, \"utf8\"));\n } catch {\n throw new Error(`llmBridgeClientConfigPath could not be read: ${expanded}`);\n }\n fromFile = parseBackgroundGenerationObject(parsed, \"llmBridgeClientConfigPath\");\n }\n const explicitRaw = cfg.backgroundGeneration;\n const fromExplicit =\n explicitRaw === undefined || explicitRaw === null\n ? undefined\n : parseBackgroundGenerationObject(explicitRaw, \"backgroundGeneration\");\n if (!fromFile && !fromExplicit) return undefined;\n return {\n endpoint: fromExplicit?.endpoint ?? fromFile!.endpoint,\n token: fromExplicit?.token ?? fromFile!.token,\n timeoutSeconds: fromExplicit?.timeoutSeconds ?? fromFile!.timeoutSeconds,\n };\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,oBAAoB;AAa7B,SAAS,qBAAqB,OAAuB;AACnD,MAAI,MAAM,MAAM;AAChB,SAAO,MAAM,KAAK,MAAM,WAAW,MAAM,CAAC,MAAM,IAAI;AAClD,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,MAAM,SAAS,QAAQ,MAAM,MAAM,GAAG,GAAG;AAC1D;AAEA,SAAS,wBAAwB,OAAe,SAAyB;AACvE,QAAM,UAAU,qBAAqB,MAAM,KAAK,CAAC;AACjD,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,OAAO;AAAA,EAC1B,QAAQ;AACN,UAAM,IAAI,MAAM,GAAG,OAAO,wCAAwC;AAAA,EACpE;AACA,MAAI,OAAO,aAAa,YAAY,OAAO,aAAa,SAAS;AAC/D,UAAM,IAAI,MAAM,GAAG,OAAO,yBAAyB;AAAA,EACrD;AACA,MAAI,OAAO,aAAa,WAAW,CAAC,eAAe,OAAO,QAAQ,GAAG;AACnE,UAAM,IAAI,MAAM,GAAG,OAAO,6CAA6C;AAAA,EACzE;AACA,MAAI,OAAO,YAAY,OAAO,YAAY,OAAO,UAAU,OAAO,MAAM;AACtE,UAAM,IAAI;AAAA,MACR,GAAG,OAAO;AAAA,IACZ;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,gCACP,KACA,SAC4B;AAC5B,MAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GAAG;AACzD,UAAM,IAAI,MAAM,GAAG,OAAO,oBAAoB;AAAA,EAChD;AACA,QAAM,SAAS;AACf,QAAM,cAAc,OAAO;AAC3B,MAAI,OAAO,gBAAgB,YAAY,YAAY,KAAK,EAAE,WAAW,GAAG;AACtE,UAAM,IAAI,MA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F;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-7S53BPTU.js";
3
+ } from "./chunk-MVG3KXON.js";
4
4
  import {
5
5
  bumpMemoryCorpusVersionForDir
6
6
  } from "./chunk-XCB6QDL6.js";
@@ -765,4 +765,4 @@ export {
765
765
  listMemoryGovernanceRuns,
766
766
  readMemoryGovernanceRunArtifact
767
767
  };
768
- //# sourceMappingURL=chunk-T32B72QX.js.map
768
+ //# sourceMappingURL=chunk-2SKMZUOW.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-7S53BPTU.js";
3
+ } from "./chunk-MVG3KXON.js";
4
4
  import {
5
5
  MutationSerializer
6
6
  } from "./chunk-FFAZ2XFU.js";
@@ -412,4 +412,4 @@ export {
412
412
  resolveNamespaceStorageRoot,
413
413
  NamespaceStorageRouter
414
414
  };
415
- //# sourceMappingURL=chunk-VHOSM5G4.js.map
415
+ //# sourceMappingURL=chunk-2SNCQHJZ.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isNamespaceKind
3
- } from "./chunk-PPQEP4OH.js";
3
+ } from "./chunk-W23JARAQ.js";
4
4
  import {
5
5
  EngramAccessInputError
6
6
  } from "./chunk-2Z24E5W2.js";
@@ -40,4 +40,4 @@ export {
40
40
  positiveIntQueryParam,
41
41
  optionalNamespaceKindQueryParam
42
42
  };
43
- //# sourceMappingURL=chunk-VV4ZVUE6.js.map
43
+ //# sourceMappingURL=chunk-3QEVOQF5.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-AAD2ZS6P.js";
5
5
  import {
6
6
  gatewayTaskChainOptions
7
- } from "./chunk-LQNRVPTV.js";
7
+ } from "./chunk-THTF2W7M.js";
8
8
  import {
9
9
  extractJsonCandidates
10
10
  } from "./chunk-RGMVMVMF.js";
@@ -685,4 +685,4 @@ export {
685
685
  serializeFaithfulnessFields,
686
686
  parseFaithfulnessField
687
687
  };
688
- //# sourceMappingURL=chunk-3N3PBBEH.js.map
688
+ //# sourceMappingURL=chunk-3XPN7AVY.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-6ET2VII7.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-7S53BPTU.js";
10
+ } from "./chunk-MVG3KXON.js";
11
11
  import {
12
12
  parseContinuityImprovementLoops
13
13
  } from "./chunk-LDXUBPMO.js";
@@ -1283,4 +1283,4 @@ export {
1283
1283
  defaultTierMigrationCycleBudget,
1284
1284
  CompoundingEngine
1285
1285
  };
1286
- //# sourceMappingURL=chunk-XN6XT6GR.js.map
1286
+ //# sourceMappingURL=chunk-46Z3VGWF.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  rebuildMemoryProjection
3
- } from "./chunk-NWMUSKED.js";
3
+ } from "./chunk-BGRTZOJB.js";
4
4
 
5
5
  // src/convergence-refresh.ts
6
6
  async function refreshConvergedNamespaces(namespaces, namespaceSearchRouter, getStorage, searchEnabled) {
@@ -32,4 +32,4 @@ async function refreshConvergedNamespaces(namespaces, namespaceSearchRouter, get
32
32
  export {
33
33
  refreshConvergedNamespaces
34
34
  };
35
- //# sourceMappingURL=chunk-2PTNJTBE.js.map
35
+ //# sourceMappingURL=chunk-4CMXI55L.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-62OKGIJA.js";
8
8
  import {
9
9
  parseActivityConfig
10
- } from "./chunk-5HYUUFMQ.js";
10
+ } from "./chunk-XCPNH2MG.js";
11
11
  import {
12
12
  parseLocationConfig
13
13
  } from "./chunk-I3H5LFOI.js";
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-6ZMAMSHS.js";
28
28
  import {
29
29
  parseLocalLlmConfig
30
- } from "./chunk-6H2G7RFT.js";
30
+ } from "./chunk-VNQRRUNS.js";
31
31
  import {
32
32
  parseGraphPathScoringConfig
33
33
  } from "./chunk-6ZN34ISG.js";
@@ -69,6 +69,9 @@ import {
69
69
  import {
70
70
  parseBoundedJsonlStateConfig
71
71
  } from "./chunk-KFZY2OFH.js";
72
+ import {
73
+ parseBackgroundGeneration
74
+ } from "./chunk-27NO2KVB.js";
72
75
  import {
73
76
  parseActiveContextFields
74
77
  } from "./chunk-B32WYRXX.js";
@@ -80,7 +83,7 @@ import {
80
83
  } from "./chunk-FEHIOYML.js";
81
84
  import {
82
85
  parseRecallStateViews
83
- } from "./chunk-255PC37A.js";
86
+ } from "./chunk-NETQXOPY.js";
84
87
  import {
85
88
  parseReplicaPeersConfig
86
89
  } from "./chunk-WNIUPHWV.js";
@@ -2702,9 +2705,14 @@ function parseConfig(raw, rawOperatorConfig, runtimeSet) {
2702
2705
  } else if (apiKey !== void 0) {
2703
2706
  baseUrl = normalizeOpenaiBaseUrl(readEnvVar("OPENAI_BASE_URL"), "env");
2704
2707
  }
2708
+ const backgroundGeneration = parseBackgroundGeneration(cfg, resolveEnvVars);
2705
2709
  const sharedCrossSignalSemanticEnabled = cfg.sharedCrossSignalSemanticEnabled === true || cfg.crossSignalsSemanticEnabled === true;
2706
2710
  const sharedCrossSignalSemanticTimeoutMs = typeof cfg.sharedCrossSignalSemanticTimeoutMs === "number" ? Math.max(1, Math.floor(cfg.sharedCrossSignalSemanticTimeoutMs)) : typeof cfg.crossSignalsSemanticTimeoutMs === "number" ? Math.max(1, Math.floor(cfg.crossSignalsSemanticTimeoutMs)) : 4e3;
2707
- const recallPipelineConfig = buildRecallPipelineConfig(cfg);
2711
+ const sharedContextEnabled = coerceBool(cfg.sharedContextEnabled, "sharedContextEnabled") ?? false;
2712
+ const recallPipelineConfig = buildRecallPipelineConfig({
2713
+ ...cfg,
2714
+ sharedContextEnabled
2715
+ });
2708
2716
  const maintenanceNamespaceFanoutEnabled = resolveBooleanConfig(
2709
2717
  readFlatOrNestedConfig(
2710
2718
  cfg,
@@ -2770,6 +2778,7 @@ function parseConfig(raw, rawOperatorConfig, runtimeSet) {
2770
2778
  return {
2771
2779
  openaiApiKey: apiKey,
2772
2780
  openaiBaseUrl: baseUrl,
2781
+ backgroundGeneration,
2773
2782
  model,
2774
2783
  reasoningEffort,
2775
2784
  triggerMode,
@@ -3796,10 +3805,9 @@ function parseConfig(raw, rawOperatorConfig, runtimeSet) {
3796
3805
  autoPromoteMinConfidenceTier: cfg.autoPromoteMinConfidenceTier === "explicit" ? "explicit" : cfg.autoPromoteMinConfidenceTier === "implied" ? "implied" : "explicit",
3797
3806
  routingRulesEnabled: cfg.routingRulesEnabled === true,
3798
3807
  routingRulesStateFile: typeof cfg.routingRulesStateFile === "string" && cfg.routingRulesStateFile.trim().length > 0 ? cfg.routingRulesStateFile.trim() : "state/routing-rules.json",
3799
- // v4.0 shared-context (default off)
3800
- sharedContextEnabled: cfg.sharedContextEnabled === true,
3801
- // CLI values arrive as strings (`--config sharedContextAllowBindingAuthority=true`),
3802
- // so a strict `=== true` silently keeps the feature off. Default stays false.
3808
+ // Reuse the hoisted coerce above (default pipeline already saw it).
3809
+ sharedContextEnabled,
3810
+ // Same coercion contract for the binding-authority sibling (#2918 parity).
3803
3811
  sharedContextAllowBindingAuthority: coerceBool(cfg.sharedContextAllowBindingAuthority, "sharedContextAllowBindingAuthority") ?? false,
3804
3812
  sharedContextDir: typeof cfg.sharedContextDir === "string" && cfg.sharedContextDir.length > 0 ? cfg.sharedContextDir : void 0,
3805
3813
  sharedContextMaxInjectChars: typeof cfg.sharedContextMaxInjectChars === "number" ? cfg.sharedContextMaxInjectChars : 4e3,
@@ -4533,6 +4541,7 @@ function buildDefaultRecallPipeline(cfg) {
4533
4541
  return [
4534
4542
  {
4535
4543
  id: "shared-context",
4544
+ // Already coerced in parseConfig; do not coerce again.
4536
4545
  enabled: cfg.sharedContextEnabled === true,
4537
4546
  maxChars: typeof cfg.sharedContextMaxInjectChars === "number" ? Math.max(0, Math.floor(cfg.sharedContextMaxInjectChars)) : 4e3
4538
4547
  },
@@ -4783,4 +4792,4 @@ export {
4783
4792
  VALID_MEMORY_CATEGORIES,
4784
4793
  parseConfig
4785
4794
  };
4786
- //# sourceMappingURL=chunk-2MT4ADLQ.js.map
4795
+ //# sourceMappingURL=chunk-5LYSEZOF.js.map