@remnic/core 9.48.0 → 9.49.0

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 (240) hide show
  1. package/dist/access-admin-ops-surface.d.ts +6 -5
  2. package/dist/access-admin-ops-surface.js +27 -26
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-authorization-probe.d.ts +6 -5
  5. package/dist/access-authorization-probe.js +28 -27
  6. package/dist/access-boundary.d.ts +6 -5
  7. package/dist/access-boundary.js +27 -26
  8. package/dist/access-cli.js +64 -63
  9. package/dist/access-cli.js.map +1 -1
  10. package/dist/access-extraction-force-flush.d.ts +6 -5
  11. package/dist/access-extraction-force-flush.js +27 -26
  12. package/dist/access-http-lcm-compaction.d.ts +6 -5
  13. package/dist/access-http-lifecycle-flush.d.ts +6 -5
  14. package/dist/access-http-offline-stream.d.ts +6 -5
  15. package/dist/access-http-query.js +27 -26
  16. package/dist/access-http.d.ts +6 -5
  17. package/dist/access-http.js +35 -34
  18. package/dist/access-identity-continuity-surface.d.ts +5 -4
  19. package/dist/access-identity-continuity-surface.js +27 -26
  20. package/dist/access-lcm-surface.d.ts +6 -5
  21. package/dist/access-lcm-surface.js +27 -26
  22. package/dist/access-mcp.d.ts +6 -5
  23. package/dist/access-mcp.js +33 -32
  24. package/dist/access-namespace-preflight.js +27 -26
  25. package/dist/access-observe-write-surface.d.ts +6 -5
  26. package/dist/access-observe-write-surface.js +27 -26
  27. package/dist/access-offline-manifest.d.ts +5 -4
  28. package/dist/access-operations-batch.js +29 -28
  29. package/dist/access-operations.d.ts +6 -5
  30. package/dist/access-operations.js +32 -31
  31. package/dist/access-recall-concurrency.d.ts +6 -5
  32. package/dist/access-recall-concurrency.js +27 -26
  33. package/dist/access-recall-response.d.ts +6 -5
  34. package/dist/access-recall-response.js +27 -26
  35. package/dist/access-recall-surface.d.ts +6 -5
  36. package/dist/access-recall-surface.js +27 -26
  37. package/dist/access-schema.js +3 -3
  38. package/dist/{access-service-andNjwfD.d.ts → access-service-DvXOzCrM.d.ts} +3 -3
  39. package/dist/access-service-helpers.d.ts +6 -5
  40. package/dist/access-service.d.ts +6 -5
  41. package/dist/access-service.js +27 -26
  42. package/dist/access-surface-catalog.d.ts +6 -5
  43. package/dist/access-wearables-meetings-surface.d.ts +3 -2
  44. package/dist/bootstrap.d.ts +5 -4
  45. package/dist/briefing.d.ts +2 -1
  46. package/dist/briefing.js +7 -6
  47. package/dist/buffer.d.ts +2 -1
  48. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
  49. package/dist/{capsule-merge-Q6AR3XL7.js → capsule-merge-6GFHWECG.js} +4 -4
  50. package/dist/causal-consolidation.js +8 -7
  51. package/dist/causal-consolidation.js.map +1 -1
  52. package/dist/{chunk-FMCHFSZF.js → chunk-2RIWJUSQ.js} +6 -6
  53. package/dist/{chunk-S55OAS5P.js → chunk-2VHLLPTX.js} +4 -4
  54. package/dist/{chunk-GWHPQOUC.js → chunk-3R6D33UF.js} +2 -2
  55. package/dist/{chunk-PELT6ADC.js → chunk-5AGR7SAI.js} +3 -3
  56. package/dist/chunk-5GINB5LC.js +13 -0
  57. package/dist/chunk-5GINB5LC.js.map +1 -0
  58. package/dist/{chunk-FJ2ND6CZ.js → chunk-5JRC6BYS.js} +10 -10
  59. package/dist/{chunk-A2TFK5PG.js → chunk-ABR2HEJO.js} +2 -2
  60. package/dist/{chunk-NXUJRXSF.js → chunk-B6KGGRUL.js} +2 -2
  61. package/dist/{chunk-PRVJH7CY.js → chunk-BMCHFWGX.js} +2 -2
  62. package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
  63. package/dist/{chunk-ANCC3JJH.js → chunk-C3KVFJH5.js} +2 -2
  64. package/dist/{chunk-JYPO7L3G.js → chunk-CNQQMB67.js} +2 -2
  65. package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
  66. package/dist/{chunk-2EJNXE53.js → chunk-ENEA47UC.js} +2 -2
  67. package/dist/{chunk-PLCZD3LG.js → chunk-EY64JLOM.js} +66 -31
  68. package/dist/chunk-EY64JLOM.js.map +1 -0
  69. package/dist/{chunk-4WBGZYZZ.js → chunk-EYAIZBLM.js} +4 -4
  70. package/dist/chunk-EYAIZBLM.js.map +1 -0
  71. package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
  72. package/dist/{chunk-HAYSYUAB.js → chunk-FMXJ555A.js} +2 -2
  73. package/dist/{chunk-VANZKHTN.js → chunk-G5OB4XZX.js} +4 -4
  74. package/dist/{chunk-DUEEQCTT.js → chunk-I3YHVVT4.js} +2 -2
  75. package/dist/{chunk-3JUYWPFJ.js → chunk-I4TQST3L.js} +2 -2
  76. package/dist/{chunk-HIDEBEAN.js → chunk-IPBNC77A.js} +8 -8
  77. package/dist/{chunk-45OTV7FZ.js → chunk-IXPKESVP.js} +11 -11
  78. package/dist/{chunk-KSGEGHYA.js → chunk-IZANPXMV.js} +34 -34
  79. package/dist/{chunk-IP3DHDU2.js → chunk-JFLOOTXU.js} +3 -3
  80. package/dist/{chunk-XL3TATMJ.js → chunk-JHMAYABJ.js} +4 -4
  81. package/dist/{chunk-HRMEYQRO.js → chunk-JXZ7NLYH.js} +2 -2
  82. package/dist/{chunk-53AJILXF.js → chunk-K7VKAHFE.js} +4 -4
  83. package/dist/{chunk-IJ7HK452.js → chunk-KMAP7SNQ.js} +2 -2
  84. package/dist/{chunk-D5NGH2EW.js → chunk-L6DCVUCA.js} +2 -2
  85. package/dist/{chunk-M4DMO67I.js → chunk-LQL7ARIC.js} +3 -3
  86. package/dist/{chunk-3NDN5P55.js → chunk-MXPB6PJQ.js} +2 -2
  87. package/dist/{chunk-RSPSHRZA.js → chunk-MZZR3J6M.js} +2 -2
  88. package/dist/{chunk-YLHM5BQQ.js → chunk-OLX2HJFW.js} +4 -4
  89. package/dist/{chunk-NIS256NW.js → chunk-QKD65RGL.js} +2 -2
  90. package/dist/{chunk-A4JMGKCD.js → chunk-R5IGA2NH.js} +4 -4
  91. package/dist/chunk-RBOJCG4T.js +77 -0
  92. package/dist/chunk-RBOJCG4T.js.map +1 -0
  93. package/dist/{chunk-7YKVM5H3.js → chunk-RHTO4HTL.js} +2 -2
  94. package/dist/{chunk-GD7UPIBG.js → chunk-RJV6Q2FT.js} +2 -2
  95. package/dist/{chunk-5L7PTX2Q.js → chunk-SHDZNSK4.js} +2 -2
  96. package/dist/{chunk-WOEVJKKQ.js → chunk-SMPVHGHG.js} +3 -3
  97. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  98. package/dist/{chunk-52I3YZZ6.js → chunk-ULWHRQEQ.js} +2 -2
  99. package/dist/{chunk-KQAFEZQX.js → chunk-VDX2J7OX.js} +2 -2
  100. package/dist/{chunk-2P3GQVM2.js → chunk-YQIVWS7Y.js} +50 -41
  101. package/dist/chunk-YQIVWS7Y.js.map +1 -0
  102. package/dist/{chunk-G2RBWVFQ.js → chunk-Z4U6U3M3.js} +2 -2
  103. package/dist/{chunk-EZNXW27Q.js → chunk-Z5UC3OKB.js} +6 -6
  104. package/dist/{cli-p_WmVo2h.d.ts → cli-PyAUaozE.d.ts} +3 -3
  105. package/dist/cli.d.ts +7 -6
  106. package/dist/cli.js +52 -51
  107. package/dist/compounding/engine.d.ts +2 -1
  108. package/dist/compounding/engine.js +7 -6
  109. package/dist/connectors/codex-materialize-runner.js +7 -6
  110. package/dist/connectors/index.js +7 -6
  111. package/dist/consolidation-provenance-check.d.ts +2 -1
  112. package/dist/consolidation-provenance-check.js +4 -4
  113. package/dist/consolidation-undo.d.ts +2 -1
  114. package/dist/consolidation-undo.js +3 -3
  115. package/dist/contradiction/index.d.ts +2 -1
  116. package/dist/convergence-refresh.d.ts +2 -1
  117. package/dist/convergence-refresh.js +9 -8
  118. package/dist/corpus-read-cancellation.d.ts +38 -0
  119. package/dist/corpus-read-cancellation.js +9 -0
  120. package/dist/corpus-read-cancellation.js.map +1 -0
  121. package/dist/corpus-watermark.js +16 -15
  122. package/dist/dashboard-runtime.js +2 -2
  123. package/dist/entity-retrieval.d.ts +2 -1
  124. package/dist/entity-retrieval.js +7 -6
  125. package/dist/explicit-capture.d.ts +5 -4
  126. package/dist/external-wiki-access.d.ts +6 -5
  127. package/dist/external-wiki-access.js +28 -27
  128. package/dist/external-wiki-mcp-tools.d.ts +6 -5
  129. package/dist/extraction.js +8 -7
  130. package/dist/in-flight-reads.d.ts +46 -2
  131. package/dist/in-flight-reads.js +5 -3
  132. package/dist/index.d.ts +11 -10
  133. package/dist/index.js +68 -67
  134. package/dist/lcm/index.js +3 -3
  135. package/dist/maintenance/memory-governance.js +7 -6
  136. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -1
  137. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -6
  138. package/dist/maintenance/rebuild-memory-projection.d.ts +2 -1
  139. package/dist/maintenance/rebuild-memory-projection.js +8 -7
  140. package/dist/{maintenance-BfcuwfJS.d.ts → maintenance-j7sfNQdK.d.ts} +1 -1
  141. package/dist/mcp-memory-inspector-app.d.ts +6 -5
  142. package/dist/memory-corpus-version.js +2 -2
  143. package/dist/memory-worth-outcomes.d.ts +2 -1
  144. package/dist/namespaces/migrate.d.ts +2 -1
  145. package/dist/namespaces/migrate.js +15 -14
  146. package/dist/namespaces/search.js +7 -7
  147. package/dist/namespaces/storage.d.ts +2 -1
  148. package/dist/namespaces/storage.js +7 -6
  149. package/dist/operator-doctor-corpus.js +17 -16
  150. package/dist/operator-toolkit.d.ts +2 -1
  151. package/dist/operator-toolkit.js +22 -21
  152. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -1
  153. package/dist/orchestration/maintenance.d.ts +3 -2
  154. package/dist/orchestration/maintenance.js +12 -11
  155. package/dist/{orchestrator-B7nLo4z1.d.ts → orchestrator-Haa9xVPV.d.ts} +3 -3
  156. package/dist/orchestrator.d.ts +5 -4
  157. package/dist/orchestrator.js +64 -63
  158. package/dist/page-versioning.js +3 -3
  159. package/dist/search/factory.js +6 -6
  160. package/dist/search/index.js +11 -11
  161. package/dist/search/lancedb-backend.js +2 -2
  162. package/dist/search/meilisearch-backend.js +2 -2
  163. package/dist/search/orama-backend.js +2 -2
  164. package/dist/semantic-consolidation.js +8 -7
  165. package/dist/semantic-rule-promotion.js +7 -6
  166. package/dist/semantic-rule-verifier.js +7 -6
  167. package/dist/{service-B5W5IYCx.d.ts → service-Da_BI4S8.d.ts} +1 -1
  168. package/dist/source-agent-qualifier.js +7 -6
  169. package/dist/{storage-COL907QF.d.ts → storage-D1apCiCS.d.ts} +4 -3
  170. package/dist/storage.d.ts +2 -1
  171. package/dist/storage.js +6 -5
  172. package/dist/temporal-supersession.d.ts +2 -1
  173. package/dist/tier-migration.d.ts +2 -1
  174. package/dist/transfer/backup.js +2 -2
  175. package/dist/transfer/capsule-export.js +2 -2
  176. package/dist/transfer/capsule-import.js +5 -5
  177. package/dist/verified-recall.js +7 -6
  178. package/package.json +3 -3
  179. package/src/corpus-read-cancellation.ts +42 -0
  180. package/src/entity-retrieval.ts +4 -4
  181. package/src/in-flight-reads.ts +119 -6
  182. package/src/orchestration/namespace-read-fanout.ts +13 -2
  183. package/src/orchestration/recall-internal-deps.ts +2 -0
  184. package/src/orchestration/recall-internal.ts +4 -1
  185. package/src/orchestration/recall-search-pipeline.ts +2 -0
  186. package/src/orchestration/recall-search-prefilter.ts +5 -1
  187. package/src/orchestrator.ts +5 -5
  188. package/src/storage/entity-store.ts +9 -2
  189. package/src/storage/memory-read-store.ts +33 -4
  190. package/src/storage-contract/corpus-read-cancellation.test.ts +408 -0
  191. package/src/storage.ts +61 -19
  192. package/dist/chunk-2P3GQVM2.js.map +0 -1
  193. package/dist/chunk-4WBGZYZZ.js.map +0 -1
  194. package/dist/chunk-PDJTHRAW.js +0 -36
  195. package/dist/chunk-PDJTHRAW.js.map +0 -1
  196. package/dist/chunk-PLCZD3LG.js.map +0 -1
  197. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
  198. /package/dist/{capsule-merge-Q6AR3XL7.js.map → capsule-merge-6GFHWECG.js.map} +0 -0
  199. /package/dist/{chunk-FMCHFSZF.js.map → chunk-2RIWJUSQ.js.map} +0 -0
  200. /package/dist/{chunk-S55OAS5P.js.map → chunk-2VHLLPTX.js.map} +0 -0
  201. /package/dist/{chunk-GWHPQOUC.js.map → chunk-3R6D33UF.js.map} +0 -0
  202. /package/dist/{chunk-PELT6ADC.js.map → chunk-5AGR7SAI.js.map} +0 -0
  203. /package/dist/{chunk-FJ2ND6CZ.js.map → chunk-5JRC6BYS.js.map} +0 -0
  204. /package/dist/{chunk-A2TFK5PG.js.map → chunk-ABR2HEJO.js.map} +0 -0
  205. /package/dist/{chunk-NXUJRXSF.js.map → chunk-B6KGGRUL.js.map} +0 -0
  206. /package/dist/{chunk-PRVJH7CY.js.map → chunk-BMCHFWGX.js.map} +0 -0
  207. /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  208. /package/dist/{chunk-ANCC3JJH.js.map → chunk-C3KVFJH5.js.map} +0 -0
  209. /package/dist/{chunk-JYPO7L3G.js.map → chunk-CNQQMB67.js.map} +0 -0
  210. /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
  211. /package/dist/{chunk-2EJNXE53.js.map → chunk-ENEA47UC.js.map} +0 -0
  212. /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
  213. /package/dist/{chunk-HAYSYUAB.js.map → chunk-FMXJ555A.js.map} +0 -0
  214. /package/dist/{chunk-VANZKHTN.js.map → chunk-G5OB4XZX.js.map} +0 -0
  215. /package/dist/{chunk-DUEEQCTT.js.map → chunk-I3YHVVT4.js.map} +0 -0
  216. /package/dist/{chunk-3JUYWPFJ.js.map → chunk-I4TQST3L.js.map} +0 -0
  217. /package/dist/{chunk-HIDEBEAN.js.map → chunk-IPBNC77A.js.map} +0 -0
  218. /package/dist/{chunk-45OTV7FZ.js.map → chunk-IXPKESVP.js.map} +0 -0
  219. /package/dist/{chunk-KSGEGHYA.js.map → chunk-IZANPXMV.js.map} +0 -0
  220. /package/dist/{chunk-IP3DHDU2.js.map → chunk-JFLOOTXU.js.map} +0 -0
  221. /package/dist/{chunk-XL3TATMJ.js.map → chunk-JHMAYABJ.js.map} +0 -0
  222. /package/dist/{chunk-HRMEYQRO.js.map → chunk-JXZ7NLYH.js.map} +0 -0
  223. /package/dist/{chunk-53AJILXF.js.map → chunk-K7VKAHFE.js.map} +0 -0
  224. /package/dist/{chunk-IJ7HK452.js.map → chunk-KMAP7SNQ.js.map} +0 -0
  225. /package/dist/{chunk-D5NGH2EW.js.map → chunk-L6DCVUCA.js.map} +0 -0
  226. /package/dist/{chunk-M4DMO67I.js.map → chunk-LQL7ARIC.js.map} +0 -0
  227. /package/dist/{chunk-3NDN5P55.js.map → chunk-MXPB6PJQ.js.map} +0 -0
  228. /package/dist/{chunk-RSPSHRZA.js.map → chunk-MZZR3J6M.js.map} +0 -0
  229. /package/dist/{chunk-YLHM5BQQ.js.map → chunk-OLX2HJFW.js.map} +0 -0
  230. /package/dist/{chunk-NIS256NW.js.map → chunk-QKD65RGL.js.map} +0 -0
  231. /package/dist/{chunk-A4JMGKCD.js.map → chunk-R5IGA2NH.js.map} +0 -0
  232. /package/dist/{chunk-7YKVM5H3.js.map → chunk-RHTO4HTL.js.map} +0 -0
  233. /package/dist/{chunk-GD7UPIBG.js.map → chunk-RJV6Q2FT.js.map} +0 -0
  234. /package/dist/{chunk-5L7PTX2Q.js.map → chunk-SHDZNSK4.js.map} +0 -0
  235. /package/dist/{chunk-WOEVJKKQ.js.map → chunk-SMPVHGHG.js.map} +0 -0
  236. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  237. /package/dist/{chunk-52I3YZZ6.js.map → chunk-ULWHRQEQ.js.map} +0 -0
  238. /package/dist/{chunk-KQAFEZQX.js.map → chunk-VDX2J7OX.js.map} +0 -0
  239. /package/dist/{chunk-G2RBWVFQ.js.map → chunk-Z4U6U3M3.js.map} +0 -0
  240. /package/dist/{chunk-EZNXW27Q.js.map → chunk-Z5UC3OKB.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { P as PluginConfig } from './types-D_Au9qJO.js';
2
- import { O as Orchestrator } from './orchestrator-B7nLo4z1.js';
2
+ import { O as Orchestrator } from './orchestrator-Haa9xVPV.js';
3
3
  import './message-parts/index.js';
4
4
  import './bounded-jsonl-state.js';
5
5
  import './operator-doctor-types.js';
@@ -9,7 +9,8 @@ import './recall-state.js';
9
9
  import './utils/serialize-mutations.js';
10
10
  import './search/port.js';
11
11
  import './briefing.js';
12
- import './storage-COL907QF.js';
12
+ import './storage-D1apCiCS.js';
13
+ import './corpus-read-cancellation.js';
13
14
  import './artifact-search.js';
14
15
  import './entity-id-normalization.js';
15
16
  import './page-versioning.js';
@@ -29,7 +30,7 @@ import './resolve-provider-secret.js';
29
30
  import './transcript.js';
30
31
  import './session-integrity.js';
31
32
  import './summarizer.js';
32
- import './maintenance-BfcuwfJS.js';
33
+ import './maintenance-j7sfNQdK.js';
33
34
  import './catalog-Iwbk9h5E.js';
34
35
  import './namespaces/search.js';
35
36
  import './compounding/engine.js';
@@ -79,7 +80,7 @@ import './negative.js';
79
80
  import './session-observer-state.js';
80
81
  import './semantic-TddhF0y7.js';
81
82
  import './replay/types.js';
82
- import './service-B5W5IYCx.js';
83
+ import './service-Da_BI4S8.js';
83
84
  import './extraction-judge.js';
84
85
  import './lcm/engine.js';
85
86
  import './lcm/archive.js';
@@ -1,5 +1,6 @@
1
- import { S as StorageManager } from './storage-COL907QF.js';
1
+ import { S as StorageManager } from './storage-D1apCiCS.js';
2
2
  import { B as BriefingSections, c as BriefingFollowup, d as BriefingFocus, e as CalendarSource, f as CalendarEvent, M as MemoryFile, g as BriefingActiveThread, h as BriefingResult, E as EntityFile, i as BriefingRecentEntity } from './types-D_Au9qJO.js';
3
+ import './corpus-read-cancellation.js';
3
4
  import './artifact-search.js';
4
5
  import './entity-id-normalization.js';
5
6
  import './page-versioning.js';
package/dist/briefing.js CHANGED
@@ -17,17 +17,17 @@ import {
17
17
  renderBriefingMarkdown,
18
18
  resolveBriefingSaveDir,
19
19
  validateBriefingFormat
20
- } from "./chunk-3NDN5P55.js";
21
- import "./chunk-PLCZD3LG.js";
20
+ } from "./chunk-MXPB6PJQ.js";
21
+ import "./chunk-EY64JLOM.js";
22
22
  import "./chunk-UHVXE24Y.js";
23
23
  import "./chunk-ENTCVTQR.js";
24
24
  import "./chunk-SXIMQLGV.js";
25
25
  import "./chunk-S2V7RUCL.js";
26
26
  import "./chunk-J6A3CX5N.js";
27
27
  import "./chunk-3S63QIFQ.js";
28
+ import "./chunk-SCU65EZI.js";
28
29
  import "./chunk-WRJVB3C2.js";
29
30
  import "./chunk-S2HLHAZ4.js";
30
- import "./chunk-SCU65EZI.js";
31
31
  import "./chunk-DM2T26WE.js";
32
32
  import "./chunk-LDXUBPMO.js";
33
33
  import "./chunk-JYIJNNN3.js";
@@ -37,10 +37,11 @@ import "./chunk-CGASUJVP.js";
37
37
  import "./chunk-R3DJVOSM.js";
38
38
  import "./chunk-BT7NVCML.js";
39
39
  import "./chunk-YXZG5TVN.js";
40
+ import "./chunk-5GINB5LC.js";
40
41
  import "./chunk-G7D6GZ5J.js";
41
- import "./chunk-7YKVM5H3.js";
42
- import "./chunk-IJ7HK452.js";
43
- import "./chunk-PDJTHRAW.js";
42
+ import "./chunk-RHTO4HTL.js";
43
+ import "./chunk-KMAP7SNQ.js";
44
+ import "./chunk-RBOJCG4T.js";
44
45
  import "./chunk-NZBZ7IS2.js";
45
46
  import "./chunk-DNHVPZOD.js";
46
47
  import "./chunk-6CIAGZ6X.js";
package/dist/buffer.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { S as StorageManager } from './storage-COL907QF.js';
1
+ import { S as StorageManager } from './storage-D1apCiCS.js';
2
2
  import { P as PluginConfig, j as BufferTurn, k as ExtractionBufferSnapshot } from './types-D_Au9qJO.js';
3
+ import './corpus-read-cancellation.js';
3
4
  import './artifact-search.js';
4
5
  import './entity-id-normalization.js';
5
6
  import './page-versioning.js';
@@ -3,7 +3,7 @@ import {
3
3
  decryptCapsuleFileInMemory,
4
4
  encryptCapsuleFile,
5
5
  isEncryptedCapsuleFile
6
- } from "./chunk-X7Y7WX73.js";
6
+ } from "./chunk-DQEMWVMT.js";
7
7
  import "./chunk-BJMBJZ2Y.js";
8
8
  import "./chunk-UKJAGEXH.js";
9
9
  import "./chunk-FP2373TW.js";
@@ -15,4 +15,4 @@ export {
15
15
  encryptCapsuleFile,
16
16
  isEncryptedCapsuleFile
17
17
  };
18
- //# sourceMappingURL=capsule-crypto-7FJQINUR.js.map
18
+ //# sourceMappingURL=capsule-crypto-YO5QJ6L3.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  createVersion
3
- } from "./chunk-7YKVM5H3.js";
3
+ } from "./chunk-RHTO4HTL.js";
4
4
  import {
5
5
  bumpMemoryCorpusVersionForDir
6
- } from "./chunk-IJ7HK452.js";
7
- import "./chunk-PDJTHRAW.js";
6
+ } from "./chunk-KMAP7SNQ.js";
7
+ import "./chunk-RBOJCG4T.js";
8
8
  import {
9
9
  HistoricalEntityCanonicalIdCache,
10
10
  canonicalizeEntityRefFrontmatter,
@@ -277,4 +277,4 @@ async function readLocalFile(absPath) {
277
277
  export {
278
278
  mergeCapsule
279
279
  };
280
- //# sourceMappingURL=capsule-merge-Q6AR3XL7.js.map
280
+ //# sourceMappingURL=capsule-merge-6GFHWECG.js.map
@@ -4,26 +4,26 @@ import {
4
4
  } from "./chunk-WZFAPHIK.js";
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation
7
- } from "./chunk-GWHPQOUC.js";
7
+ } from "./chunk-3R6D33UF.js";
8
8
  import "./chunk-JLNBQWZ2.js";
9
9
  import "./chunk-B7RWBZXW.js";
10
10
  import {
11
11
  runPostConsolidationMaterialize
12
- } from "./chunk-G2RBWVFQ.js";
12
+ } from "./chunk-Z4U6U3M3.js";
13
13
  import "./chunk-KSXJOC4F.js";
14
14
  import {
15
15
  resolveCausalTrajectoryStoreDir
16
16
  } from "./chunk-W4FBGYGK.js";
17
- import "./chunk-PLCZD3LG.js";
17
+ import "./chunk-EY64JLOM.js";
18
18
  import "./chunk-UHVXE24Y.js";
19
19
  import "./chunk-ENTCVTQR.js";
20
20
  import "./chunk-SXIMQLGV.js";
21
21
  import "./chunk-S2V7RUCL.js";
22
22
  import "./chunk-J6A3CX5N.js";
23
23
  import "./chunk-3S63QIFQ.js";
24
+ import "./chunk-SCU65EZI.js";
24
25
  import "./chunk-WRJVB3C2.js";
25
26
  import "./chunk-S2HLHAZ4.js";
26
- import "./chunk-SCU65EZI.js";
27
27
  import "./chunk-DM2T26WE.js";
28
28
  import "./chunk-LDXUBPMO.js";
29
29
  import "./chunk-JYIJNNN3.js";
@@ -33,10 +33,11 @@ import "./chunk-CGASUJVP.js";
33
33
  import "./chunk-R3DJVOSM.js";
34
34
  import "./chunk-BT7NVCML.js";
35
35
  import "./chunk-YXZG5TVN.js";
36
+ import "./chunk-5GINB5LC.js";
36
37
  import "./chunk-G7D6GZ5J.js";
37
- import "./chunk-7YKVM5H3.js";
38
- import "./chunk-IJ7HK452.js";
39
- import "./chunk-PDJTHRAW.js";
38
+ import "./chunk-RHTO4HTL.js";
39
+ import "./chunk-KMAP7SNQ.js";
40
+ import "./chunk-RBOJCG4T.js";
40
41
  import "./chunk-NZBZ7IS2.js";
41
42
  import "./chunk-DNHVPZOD.js";
42
43
  import "./chunk-6CIAGZ6X.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,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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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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xB,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":[]}
@@ -21,13 +21,13 @@ import {
21
21
  processChatMessage,
22
22
  sessionBelongsToPrincipal,
23
23
  subscribeChatTranscript
24
- } from "./chunk-IP3DHDU2.js";
24
+ } from "./chunk-JFLOOTXU.js";
25
25
  import {
26
26
  RelayMissionStoreError
27
- } from "./chunk-53AJILXF.js";
27
+ } from "./chunk-K7VKAHFE.js";
28
28
  import {
29
29
  validateRequest
30
- } from "./chunk-NIS256NW.js";
30
+ } from "./chunk-QKD65RGL.js";
31
31
  import {
32
32
  executeResolution,
33
33
  isValidResolutionVerb
@@ -50,12 +50,12 @@ import {
50
50
  import {
51
51
  authorizationProbeNamespaces,
52
52
  probeOperationAuthorization
53
- } from "./chunk-HRMEYQRO.js";
53
+ } from "./chunk-JXZ7NLYH.js";
54
54
  import {
55
55
  CorrectionContractError,
56
56
  getOperation,
57
57
  resolveQueryNamespaceWritablePreflight
58
- } from "./chunk-45OTV7FZ.js";
58
+ } from "./chunk-IXPKESVP.js";
59
59
  import {
60
60
  isTrustZoneName
61
61
  } from "./chunk-JGSKJHF7.js";
@@ -3263,4 +3263,4 @@ export {
3263
3263
  MeetingsInputError,
3264
3264
  EngramAccessHttpServer
3265
3265
  };
3266
- //# sourceMappingURL=chunk-FMCHFSZF.js.map
3266
+ //# sourceMappingURL=chunk-2RIWJUSQ.js.map
@@ -9,14 +9,14 @@ import {
9
9
  } from "./chunk-666A3MOW.js";
10
10
  import {
11
11
  rebuildMemoryLifecycleLedger
12
- } from "./chunk-52I3YZZ6.js";
12
+ } from "./chunk-ULWHRQEQ.js";
13
13
  import {
14
14
  planNamespaceMaintenance,
15
15
  runNamespaceMaintenanceBatchPlan
16
- } from "./chunk-D5NGH2EW.js";
16
+ } from "./chunk-L6DCVUCA.js";
17
17
  import {
18
18
  rebuildMemoryProjection
19
- } from "./chunk-M4DMO67I.js";
19
+ } from "./chunk-LQL7ARIC.js";
20
20
  import {
21
21
  activityDayWindow,
22
22
  activityDigestPath,
@@ -1714,4 +1714,4 @@ export {
1714
1714
  ActivitySyncScheduler,
1715
1715
  MaintenanceScheduler
1716
1716
  };
1717
- //# sourceMappingURL=chunk-S55OAS5P.js.map
1717
+ //# sourceMappingURL=chunk-2VHLLPTX.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-JLNBQWZ2.js";
6
6
  import {
7
7
  runPostConsolidationMaterialize
8
- } from "./chunk-G2RBWVFQ.js";
8
+ } from "./chunk-Z4U6U3M3.js";
9
9
  import {
10
10
  isSemanticConsolidationLlmOperator
11
11
  } from "./chunk-G7D6GZ5J.js";
@@ -220,4 +220,4 @@ export {
220
220
  buildExtensionsBlockForConsolidation,
221
221
  materializeAfterSemanticConsolidation
222
222
  };
223
- //# sourceMappingURL=chunk-GWHPQOUC.js.map
223
+ //# sourceMappingURL=chunk-3R6D33UF.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  namespaceCollectionName
3
- } from "./chunk-PRVJH7CY.js";
3
+ } from "./chunk-BMCHFWGX.js";
4
4
  import {
5
5
  NamespaceStorageRouter
6
- } from "./chunk-ANCC3JJH.js";
6
+ } from "./chunk-C3KVFJH5.js";
7
7
  import {
8
8
  namespaceIdentityFromToken,
9
9
  namespaceIdentityToken
@@ -213,4 +213,4 @@ export {
213
213
  verifyNamespaces,
214
214
  runNamespaceMigration
215
215
  };
216
- //# sourceMappingURL=chunk-PELT6ADC.js.map
216
+ //# sourceMappingURL=chunk-5AGR7SAI.js.map
@@ -0,0 +1,13 @@
1
+ import {
2
+ throwIfAborted
3
+ } from "./chunk-BTTPKDIL.js";
4
+
5
+ // src/corpus-read-cancellation.ts
6
+ function checkCorpusReadAbort(options) {
7
+ throwIfAborted(options?.abortSignal, "corpus read aborted");
8
+ }
9
+
10
+ export {
11
+ checkCorpusReadAbort
12
+ };
13
+ //# sourceMappingURL=chunk-5GINB5LC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/corpus-read-cancellation.ts"],"sourcesContent":["/**\n * Cancellation contract for the shared full-corpus read primitives (issue #2307).\n *\n * `readAllArtifactsCached`, `readAllEntityFiles`, `readAllMemories`, and the\n * artifact source-status snapshot each walk and parse an entire memory tree. Issue\n * #2291 bounded the recall providers that call them, so a timed-out recall returns\n * on time — but the scan underneath kept running, and for the primitives without\n * in-flight coalescing every abandoned request started another one. On a large or\n * network-mounted store those pile up into sustained I/O no live request needs.\n *\n * The mechanism is a plain optional parameter, not ambient async context: these\n * primitives have dozens of callers across extraction, maintenance, wearables, and\n * coding surfaces, and an ambient signal would silently attach a request's\n * cancellation to background work that merely shares its async context. An\n * explicit parameter is greppable, and a caller that does not opt in behaves\n * exactly as before.\n *\n * Two invariants bind every implementation:\n *\n * 1. **Checked before the cache lookup.** A caller that has already given up gets\n * an `AbortError`, warm cache or not — the same contract the recall providers\n * follow, so cancellation never depends on cache state.\n * 2. **A cancelled read never publishes.** Every checkpoint throws, so control\n * leaves before the cache write. A partial corpus must never be cached, or\n * served, as if it were complete.\n */\n\nimport { throwIfAborted } from \"./abort-error.js\";\n\nexport interface CorpusReadOptions {\n /**\n * Stops the read at its next directory, batch, or attempt boundary. A single\n * in-flight file read is not interrupted; the boundaries are what bound the\n * work, and on a tree large enough to matter there are thousands of them.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Stop a corpus read at a scan boundary when its caller has given up. */\nexport function checkCorpusReadAbort(options?: CorpusReadOptions): void {\n throwIfAborted(options?.abortSignal, \"corpus read aborted\");\n}\n"],"mappings":";;;;;AAuCO,SAAS,qBAAqB,SAAmC;AACtE,iBAAe,SAAS,aAAa,qBAAqB;AAC5D;","names":[]}
@@ -1,21 +1,21 @@
1
+ import {
2
+ RemoteSearchBackend
3
+ } from "./chunk-VYISFWVX.js";
4
+ import {
5
+ EmbedHelper
6
+ } from "./chunk-GWFSVJ4P.js";
1
7
  import {
2
8
  LanceDbBackend
3
- } from "./chunk-XL3TATMJ.js";
9
+ } from "./chunk-JHMAYABJ.js";
4
10
  import {
5
11
  MeilisearchBackend
6
- } from "./chunk-VANZKHTN.js";
12
+ } from "./chunk-G5OB4XZX.js";
7
13
  import {
8
14
  NoopSearchBackend
9
15
  } from "./chunk-CYEPCZN5.js";
10
16
  import {
11
17
  OramaBackend
12
- } from "./chunk-YLHM5BQQ.js";
13
- import {
14
- RemoteSearchBackend
15
- } from "./chunk-VYISFWVX.js";
16
- import {
17
- EmbedHelper
18
- } from "./chunk-GWFSVJ4P.js";
18
+ } from "./chunk-OLX2HJFW.js";
19
19
  import {
20
20
  createConversationIndexBackend
21
21
  } from "./chunk-227UFSEQ.js";
@@ -178,4 +178,4 @@ export {
178
178
  createConversationSearchBackend,
179
179
  createConversationIndexRuntime
180
180
  };
181
- //# sourceMappingURL=chunk-FJ2ND6CZ.js.map
181
+ //# sourceMappingURL=chunk-5JRC6BYS.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-PLCZD3LG.js";
3
+ } from "./chunk-EY64JLOM.js";
4
4
  import {
5
5
  composeMemoryEnvelope
6
6
  } from "./chunk-CGASUJVP.js";
@@ -546,4 +546,4 @@ export {
546
546
  setSemanticRulePromotionTestHooks,
547
547
  promoteSemanticRuleFromMemory
548
548
  };
549
- //# sourceMappingURL=chunk-A2TFK5PG.js.map
549
+ //# sourceMappingURL=chunk-ABR2HEJO.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7T4TOGMS.js";
4
4
  import {
5
5
  defineOperation
6
- } from "./chunk-45OTV7FZ.js";
6
+ } from "./chunk-IXPKESVP.js";
7
7
 
8
8
  // src/external-wiki-access.ts
9
9
  import { z } from "zod";
@@ -26,4 +26,4 @@ var externalWikiSearchOperation = defineOperation({
26
26
  export {
27
27
  externalWikiSearchOperation
28
28
  };
29
- //# sourceMappingURL=chunk-NXUJRXSF.js.map
29
+ //# sourceMappingURL=chunk-B6KGGRUL.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createSearchBackend
3
- } from "./chunk-FJ2ND6CZ.js";
3
+ } from "./chunk-5JRC6BYS.js";
4
4
  import {
5
5
  namespaceIdentityToken,
6
6
  normalizeNamespaceIdentity
@@ -470,4 +470,4 @@ export {
470
470
  NamespaceSearchRouter,
471
471
  normalizeQmdResultPath
472
472
  };
473
- //# sourceMappingURL=chunk-PRVJH7CY.js.map
473
+ //# sourceMappingURL=chunk-BMCHFWGX.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-765K3SAT.js";
4
4
  import {
5
5
  encryptCapsuleFile
6
- } from "./chunk-X7Y7WX73.js";
6
+ } from "./chunk-DQEMWVMT.js";
7
7
  import {
8
8
  computeTransferOutputRel,
9
9
  isTransferPathExcluded
@@ -109,4 +109,4 @@ async function enforceRetention(outDirAbs, retentionDays) {
109
109
  export {
110
110
  backupMemoryDir
111
111
  };
112
- //# sourceMappingURL=chunk-2NLLXCJG.js.map
112
+ //# sourceMappingURL=chunk-BXLOS5AJ.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-PLCZD3LG.js";
3
+ } from "./chunk-EY64JLOM.js";
4
4
  import {
5
5
  keyring_exports,
6
6
  secureStoreDir
@@ -388,4 +388,4 @@ export {
388
388
  resolveNamespaceStorageRoot,
389
389
  NamespaceStorageRouter
390
390
  };
391
- //# sourceMappingURL=chunk-ANCC3JJH.js.map
391
+ //# sourceMappingURL=chunk-C3KVFJH5.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  listNamespaces
3
- } from "./chunk-PELT6ADC.js";
3
+ } from "./chunk-5AGR7SAI.js";
4
4
  import {
5
5
  capabilityAllowsNamespace
6
6
  } from "./chunk-MZWSOLMT.js";
@@ -282,4 +282,4 @@ export {
282
282
  computeServiceCorpusWatermarks,
283
283
  computeServiceCorpusCensus
284
284
  };
285
- //# sourceMappingURL=chunk-JYPO7L3G.js.map
285
+ //# sourceMappingURL=chunk-CNQQMB67.js.map
@@ -246,4 +246,4 @@ export {
246
246
  decryptCapsuleFile,
247
247
  decryptCapsuleFileInMemory
248
248
  };
249
- //# sourceMappingURL=chunk-X7Y7WX73.js.map
249
+ //# sourceMappingURL=chunk-DQEMWVMT.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-FQC3DHH2.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-PLCZD3LG.js";
10
+ } from "./chunk-EY64JLOM.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-2EJNXE53.js.map
1286
+ //# sourceMappingURL=chunk-ENEA47UC.js.map