@graphrefly/graphrefly 0.47.2 → 0.48.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 (266) hide show
  1. package/dist/base/composition/index.cjs +4 -3
  2. package/dist/base/composition/index.cjs.map +1 -1
  3. package/dist/base/composition/index.d.cts +14 -5
  4. package/dist/base/composition/index.d.ts +14 -5
  5. package/dist/base/composition/index.js +8 -8
  6. package/dist/base/index.cjs +152 -78
  7. package/dist/base/index.cjs.map +1 -1
  8. package/dist/base/index.d.cts +2 -2
  9. package/dist/base/index.d.ts +2 -2
  10. package/dist/base/index.js +75 -70
  11. package/dist/base/io/index.cjs +31 -17
  12. package/dist/base/io/index.cjs.map +1 -1
  13. package/dist/base/io/index.d.cts +32 -5
  14. package/dist/base/io/index.d.ts +32 -5
  15. package/dist/base/io/index.js +1 -1
  16. package/dist/base/mutation/index.cjs +21 -0
  17. package/dist/base/mutation/index.cjs.map +1 -1
  18. package/dist/base/mutation/index.d.cts +23 -1
  19. package/dist/base/mutation/index.d.ts +23 -1
  20. package/dist/base/mutation/index.js +3 -1
  21. package/dist/base/sources/browser/index.cjs +5 -3
  22. package/dist/base/sources/browser/index.cjs.map +1 -1
  23. package/dist/base/sources/browser/index.d.cts +20 -2
  24. package/dist/base/sources/browser/index.d.ts +20 -2
  25. package/dist/base/sources/browser/index.js +5 -3
  26. package/dist/base/sources/browser/index.js.map +1 -1
  27. package/dist/base/sources/event/index.cjs +28 -0
  28. package/dist/base/sources/event/index.cjs.map +1 -1
  29. package/dist/base/sources/event/index.d.cts +67 -3
  30. package/dist/base/sources/event/index.d.ts +67 -3
  31. package/dist/base/sources/event/index.js +4 -1
  32. package/dist/base/sources/index.cjs +75 -37
  33. package/dist/base/sources/index.cjs.map +1 -1
  34. package/dist/base/sources/index.d.cts +1 -1
  35. package/dist/base/sources/index.d.ts +1 -1
  36. package/dist/base/sources/index.js +5 -2
  37. package/dist/{chunk-R6ZCSXKX.js → chunk-23MAWVOJ.js} +3 -3
  38. package/dist/{chunk-MS3WPRJR.js → chunk-3REMCHSS.js} +6 -6
  39. package/dist/chunk-3REMCHSS.js.map +1 -0
  40. package/dist/{chunk-CEVNQ74M.js → chunk-3YGXPUHW.js} +2 -2
  41. package/dist/{chunk-CEVNQ74M.js.map → chunk-3YGXPUHW.js.map} +1 -1
  42. package/dist/{chunk-6ZLCPUXS.js → chunk-46X2EFQH.js} +15 -4
  43. package/dist/chunk-46X2EFQH.js.map +1 -0
  44. package/dist/{chunk-NY2PYHNC.js → chunk-5UY3PNFY.js} +12 -5
  45. package/dist/chunk-5UY3PNFY.js.map +1 -0
  46. package/dist/{chunk-FQSQONOU.js → chunk-65OM4XLQ.js} +49 -3
  47. package/dist/chunk-65OM4XLQ.js.map +1 -0
  48. package/dist/{chunk-3PSLNJDU.js → chunk-6DQYBIHW.js} +314 -49
  49. package/dist/chunk-6DQYBIHW.js.map +1 -0
  50. package/dist/{chunk-LDCSZ72P.js → chunk-6YBER5UP.js} +3 -3
  51. package/dist/{chunk-LDCSZ72P.js.map → chunk-6YBER5UP.js.map} +1 -1
  52. package/dist/{chunk-3O3NKZJW.js → chunk-7T7WLEPM.js} +24 -3
  53. package/dist/chunk-7T7WLEPM.js.map +1 -0
  54. package/dist/{chunk-PKPO3JTZ.js → chunk-AQAKDE7F.js} +29 -11
  55. package/dist/chunk-AQAKDE7F.js.map +1 -0
  56. package/dist/{chunk-6MRSX3YK.js → chunk-B5Y5GPD5.js} +2 -2
  57. package/dist/{chunk-BXGZFGZ4.js → chunk-C5QD5DQX.js} +22 -1
  58. package/dist/chunk-C5QD5DQX.js.map +1 -0
  59. package/dist/{chunk-4XCHZRUJ.js → chunk-D5YGR4TP.js} +58 -7
  60. package/dist/chunk-D5YGR4TP.js.map +1 -0
  61. package/dist/{chunk-NPRP3MCV.js → chunk-DHDCOOJU.js} +2 -2
  62. package/dist/chunk-DHDCOOJU.js.map +1 -0
  63. package/dist/{chunk-VP3TIUDF.js → chunk-DVTDF5OI.js} +2 -2
  64. package/dist/{chunk-OXD5LFQP.js → chunk-G7H6PN7P.js} +2 -2
  65. package/dist/{chunk-EL5VHUGK.js → chunk-GGKHHG5Y.js} +32 -18
  66. package/dist/chunk-GGKHHG5Y.js.map +1 -0
  67. package/dist/{chunk-446I4EGD.js → chunk-J5TBZFBD.js} +2 -2
  68. package/dist/{chunk-7AVQIGF6.js → chunk-K4ZYJ4EM.js} +554 -460
  69. package/dist/chunk-K4ZYJ4EM.js.map +1 -0
  70. package/dist/{chunk-QFE5BQH7.js → chunk-LTSI7ULC.js} +2 -2
  71. package/dist/{chunk-5GVURVIG.js → chunk-MMHGYX44.js} +12 -2
  72. package/dist/{chunk-5GVURVIG.js.map → chunk-MMHGYX44.js.map} +1 -1
  73. package/dist/{chunk-KRFGO5QH.js → chunk-MQMTRKY3.js} +118 -43
  74. package/dist/chunk-MQMTRKY3.js.map +1 -0
  75. package/dist/{chunk-42FQ27MQ.js → chunk-MTODGQBR.js} +44 -179
  76. package/dist/chunk-MTODGQBR.js.map +1 -0
  77. package/dist/{chunk-FVINAAKA.js → chunk-NBK6QQMG.js} +14 -13
  78. package/dist/{chunk-FVINAAKA.js.map → chunk-NBK6QQMG.js.map} +1 -1
  79. package/dist/{chunk-KNU73RZW.js → chunk-NSA5K5G2.js} +2 -2
  80. package/dist/{chunk-MLTPJMH6.js → chunk-QQYULEZL.js} +2 -2
  81. package/dist/chunk-QSW4DFKE.js +31 -0
  82. package/dist/chunk-QSW4DFKE.js.map +1 -0
  83. package/dist/{chunk-VAZXUK6G.js → chunk-SUNCHMML.js} +2 -2
  84. package/dist/{chunk-EP4WVQLX.js → chunk-T2U6N3FV.js} +6 -6
  85. package/dist/{chunk-T7SP3EYR.js → chunk-T5URUIIY.js} +33 -24
  86. package/dist/chunk-T5URUIIY.js.map +1 -0
  87. package/dist/{chunk-VNXAF2KE.js → chunk-TPTZZV25.js} +6 -6
  88. package/dist/chunk-TPTZZV25.js.map +1 -0
  89. package/dist/{chunk-IOJDYUA7.js → chunk-V46JWFGV.js} +6 -5
  90. package/dist/chunk-V46JWFGV.js.map +1 -0
  91. package/dist/{chunk-WGDEBIP4.js → chunk-X6ESZDR6.js} +5 -6
  92. package/dist/chunk-X6ESZDR6.js.map +1 -0
  93. package/dist/{chunk-N65E26UL.js → chunk-XEWV254I.js} +2 -2
  94. package/dist/{chunk-N65E26UL.js.map → chunk-XEWV254I.js.map} +1 -1
  95. package/dist/{chunk-PTWADEH3.js → chunk-YBJVKMTM.js} +34 -14
  96. package/dist/chunk-YBJVKMTM.js.map +1 -0
  97. package/dist/{chunk-DDTS7F5O.js → chunk-ZW32BPXV.js} +12 -3
  98. package/dist/chunk-ZW32BPXV.js.map +1 -0
  99. package/dist/compat/index.cjs +51 -4
  100. package/dist/compat/index.cjs.map +1 -1
  101. package/dist/compat/index.d.cts +1 -1
  102. package/dist/compat/index.d.ts +1 -1
  103. package/dist/compat/index.js +6 -6
  104. package/dist/compat/nestjs/index.cjs +51 -4
  105. package/dist/compat/nestjs/index.cjs.map +1 -1
  106. package/dist/compat/nestjs/index.d.cts +1 -1
  107. package/dist/compat/nestjs/index.d.ts +1 -1
  108. package/dist/compat/nestjs/index.js +3 -3
  109. package/dist/{fallback-Bx46zqky.d.cts → fallback-BROR6ZhO.d.cts} +1 -1
  110. package/dist/{fallback-pIWW8A2d.d.ts → fallback-DO80aM_3.d.ts} +1 -1
  111. package/dist/{index-B_p8tnvf.d.cts → index-D1z3XcF9.d.cts} +1 -0
  112. package/dist/{index-_HDSmPyp.d.ts → index-DZ6yua0Q.d.ts} +1 -0
  113. package/dist/index.cjs +2215 -1676
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.d.cts +10 -10
  116. package/dist/index.d.ts +10 -10
  117. package/dist/index.js +169 -146
  118. package/dist/index.js.map +1 -1
  119. package/dist/presets/ai/index.cjs +46 -0
  120. package/dist/presets/ai/index.cjs.map +1 -1
  121. package/dist/presets/ai/index.js +12 -12
  122. package/dist/presets/harness/index.cjs +130 -18
  123. package/dist/presets/harness/index.cjs.map +1 -1
  124. package/dist/presets/harness/index.d.cts +15 -5
  125. package/dist/presets/harness/index.d.ts +15 -5
  126. package/dist/presets/harness/index.js +22 -22
  127. package/dist/presets/index.cjs +222 -53
  128. package/dist/presets/index.cjs.map +1 -1
  129. package/dist/presets/index.d.cts +2 -2
  130. package/dist/presets/index.d.ts +2 -2
  131. package/dist/presets/index.js +45 -45
  132. package/dist/presets/inspect/index.cjs +63 -14
  133. package/dist/presets/inspect/index.cjs.map +1 -1
  134. package/dist/presets/inspect/index.d.cts +1 -1
  135. package/dist/presets/inspect/index.d.ts +1 -1
  136. package/dist/presets/inspect/index.js +6 -6
  137. package/dist/presets/resilience/index.cjs +29 -21
  138. package/dist/presets/resilience/index.cjs.map +1 -1
  139. package/dist/presets/resilience/index.d.cts +12 -8
  140. package/dist/presets/resilience/index.d.ts +12 -8
  141. package/dist/presets/resilience/index.js +3 -3
  142. package/dist/{rate-limiter-DpVbSYdH.d.cts → rate-limiter-DC26FM8J.d.cts} +10 -1
  143. package/dist/{rate-limiter-CEALq4N1.d.ts → rate-limiter-DyWpwpQP.d.ts} +10 -1
  144. package/dist/{reactive-layout-fswlBUvX.d.ts → reactive-layout-BBBWH0V_.d.cts} +85 -4
  145. package/dist/{reactive-layout-fswlBUvX.d.cts → reactive-layout-BBBWH0V_.d.ts} +85 -4
  146. package/dist/solutions/index.cjs +168 -47
  147. package/dist/solutions/index.cjs.map +1 -1
  148. package/dist/solutions/index.d.cts +2 -2
  149. package/dist/solutions/index.d.ts +2 -2
  150. package/dist/solutions/index.js +28 -28
  151. package/dist/{spawnable-5mDY501F.d.cts → spawnable-B2IlW60f.d.cts} +23 -2
  152. package/dist/{spawnable-D3lR0oQu.d.ts → spawnable-tttFz2Nh.d.ts} +23 -2
  153. package/dist/testing/index.cjs +94 -0
  154. package/dist/testing/index.cjs.map +1 -0
  155. package/dist/testing/index.d.cts +59 -0
  156. package/dist/testing/index.d.ts +59 -0
  157. package/dist/testing/index.js +73 -0
  158. package/dist/testing/index.js.map +1 -0
  159. package/dist/utils/ai/browser.cjs.map +1 -1
  160. package/dist/utils/ai/browser.d.cts +2 -2
  161. package/dist/utils/ai/browser.d.ts +2 -2
  162. package/dist/utils/ai/browser.js +6 -6
  163. package/dist/utils/ai/browser.js.map +1 -1
  164. package/dist/utils/ai/index.cjs +250 -166
  165. package/dist/utils/ai/index.cjs.map +1 -1
  166. package/dist/utils/ai/index.d.cts +108 -12
  167. package/dist/utils/ai/index.d.ts +108 -12
  168. package/dist/utils/ai/index.js +21 -19
  169. package/dist/utils/ai/node.cjs.map +1 -1
  170. package/dist/utils/ai/node.d.cts +5 -5
  171. package/dist/utils/ai/node.d.ts +5 -5
  172. package/dist/utils/ai/node.js +2 -2
  173. package/dist/utils/ai/node.js.map +1 -1
  174. package/dist/utils/cqrs/index.cjs +29 -3
  175. package/dist/utils/cqrs/index.cjs.map +1 -1
  176. package/dist/utils/cqrs/index.d.cts +12 -7
  177. package/dist/utils/cqrs/index.d.ts +12 -7
  178. package/dist/utils/cqrs/index.js +2 -2
  179. package/dist/utils/demo-shell/index.cjs +45 -19
  180. package/dist/utils/demo-shell/index.cjs.map +1 -1
  181. package/dist/utils/demo-shell/index.d.cts +1 -1
  182. package/dist/utils/demo-shell/index.d.ts +1 -1
  183. package/dist/utils/demo-shell/index.js +2 -2
  184. package/dist/utils/domain-templates/index.cjs.map +1 -1
  185. package/dist/utils/domain-templates/index.js +3 -3
  186. package/dist/utils/graphspec/index.cjs.map +1 -1
  187. package/dist/utils/graphspec/index.js +3 -3
  188. package/dist/utils/index.cjs +1642 -1225
  189. package/dist/utils/index.cjs.map +1 -1
  190. package/dist/utils/index.d.cts +7 -7
  191. package/dist/utils/index.d.ts +7 -7
  192. package/dist/utils/index.js +72 -54
  193. package/dist/utils/inspect/index.cjs +52 -4
  194. package/dist/utils/inspect/index.cjs.map +1 -1
  195. package/dist/utils/inspect/index.d.cts +32 -3
  196. package/dist/utils/inspect/index.d.ts +32 -3
  197. package/dist/utils/inspect/index.js +4 -4
  198. package/dist/utils/job-queue/index.cjs +46 -9
  199. package/dist/utils/job-queue/index.cjs.map +1 -1
  200. package/dist/utils/job-queue/index.d.cts +33 -3
  201. package/dist/utils/job-queue/index.d.ts +33 -3
  202. package/dist/utils/job-queue/index.js +2 -2
  203. package/dist/utils/memory/index.cjs +556 -462
  204. package/dist/utils/memory/index.cjs.map +1 -1
  205. package/dist/utils/memory/index.d.cts +203 -24
  206. package/dist/utils/memory/index.d.ts +203 -24
  207. package/dist/utils/memory/index.js +10 -2
  208. package/dist/utils/messaging/index.cjs.map +1 -1
  209. package/dist/utils/messaging/index.d.cts +4 -3
  210. package/dist/utils/messaging/index.d.ts +4 -3
  211. package/dist/utils/messaging/index.js +2 -2
  212. package/dist/utils/orchestration/index.cjs +9 -0
  213. package/dist/utils/orchestration/index.cjs.map +1 -1
  214. package/dist/utils/orchestration/index.js +3 -3
  215. package/dist/utils/process/index.cjs +32 -2
  216. package/dist/utils/process/index.cjs.map +1 -1
  217. package/dist/utils/process/index.d.cts +4 -3
  218. package/dist/utils/process/index.d.ts +4 -3
  219. package/dist/utils/process/index.js +2 -2
  220. package/dist/utils/reactive-layout/index.cjs +184 -55
  221. package/dist/utils/reactive-layout/index.cjs.map +1 -1
  222. package/dist/utils/reactive-layout/index.d.cts +128 -3
  223. package/dist/utils/reactive-layout/index.d.ts +128 -3
  224. package/dist/utils/reactive-layout/index.js +16 -8
  225. package/dist/utils/reduction/index.cjs.map +1 -1
  226. package/dist/utils/reduction/index.js +2 -2
  227. package/dist/utils/resilience/index.cjs +29 -20
  228. package/dist/utils/resilience/index.cjs.map +1 -1
  229. package/dist/utils/resilience/index.d.cts +1 -1
  230. package/dist/utils/resilience/index.d.ts +1 -1
  231. package/dist/utils/resilience/index.js +2 -2
  232. package/dist/utils/surface/index.cjs.map +1 -1
  233. package/dist/utils/surface/index.js +4 -4
  234. package/package.json +15 -3
  235. package/dist/chunk-3O3NKZJW.js.map +0 -1
  236. package/dist/chunk-3PSLNJDU.js.map +0 -1
  237. package/dist/chunk-42FQ27MQ.js.map +0 -1
  238. package/dist/chunk-4XCHZRUJ.js.map +0 -1
  239. package/dist/chunk-6ZLCPUXS.js.map +0 -1
  240. package/dist/chunk-7AVQIGF6.js.map +0 -1
  241. package/dist/chunk-BXGZFGZ4.js.map +0 -1
  242. package/dist/chunk-DDTS7F5O.js.map +0 -1
  243. package/dist/chunk-EL5VHUGK.js.map +0 -1
  244. package/dist/chunk-FQSQONOU.js.map +0 -1
  245. package/dist/chunk-IOJDYUA7.js.map +0 -1
  246. package/dist/chunk-KRFGO5QH.js.map +0 -1
  247. package/dist/chunk-MS3WPRJR.js.map +0 -1
  248. package/dist/chunk-NPRP3MCV.js.map +0 -1
  249. package/dist/chunk-NY2PYHNC.js.map +0 -1
  250. package/dist/chunk-PKPO3JTZ.js.map +0 -1
  251. package/dist/chunk-PTWADEH3.js.map +0 -1
  252. package/dist/chunk-T7SP3EYR.js.map +0 -1
  253. package/dist/chunk-VNXAF2KE.js.map +0 -1
  254. package/dist/chunk-W2BOPXTI.js +0 -1
  255. package/dist/chunk-W2BOPXTI.js.map +0 -1
  256. package/dist/chunk-WGDEBIP4.js.map +0 -1
  257. /package/dist/{chunk-R6ZCSXKX.js.map → chunk-23MAWVOJ.js.map} +0 -0
  258. /package/dist/{chunk-6MRSX3YK.js.map → chunk-B5Y5GPD5.js.map} +0 -0
  259. /package/dist/{chunk-VP3TIUDF.js.map → chunk-DVTDF5OI.js.map} +0 -0
  260. /package/dist/{chunk-OXD5LFQP.js.map → chunk-G7H6PN7P.js.map} +0 -0
  261. /package/dist/{chunk-446I4EGD.js.map → chunk-J5TBZFBD.js.map} +0 -0
  262. /package/dist/{chunk-QFE5BQH7.js.map → chunk-LTSI7ULC.js.map} +0 -0
  263. /package/dist/{chunk-KNU73RZW.js.map → chunk-NSA5K5G2.js.map} +0 -0
  264. /package/dist/{chunk-MLTPJMH6.js.map → chunk-QQYULEZL.js.map} +0 -0
  265. /package/dist/{chunk-VAZXUK6G.js.map → chunk-SUNCHMML.js.map} +0 -0
  266. /package/dist/{chunk-EP4WVQLX.js.map → chunk-T2U6N3FV.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { M as MeasurementAdapter, P as PreparedSegment, d as LineBreaksResult, C as CharPosition, L as LayoutCursor, I as Interval } from '../../reactive-layout-fswlBUvX.cjs';
2
- export { a as LayoutLine, b as LayoutNextLineContext, c as LayoutNextLineResult, R as ReactiveLayoutBundle, e as ReactiveLayoutOptions, S as SegmentBreakKind, f as SegmentMeasureStats, g as analyzeAndMeasure, h as carveTextLineSlots, i as computeCharPositions, j as computeLineBreaks, l as layoutNextLine, r as reactiveLayout } from '../../reactive-layout-fswlBUvX.cjs';
1
+ import { M as MeasurementAdapter, S as SegmentAdapter, g as SegmentInfo, P as PreparedSegment, d as LineBreaksResult, C as CharPosition, L as LayoutCursor, I as Interval } from '../../reactive-layout-BBBWH0V_.cjs';
2
+ export { a as LayoutLine, b as LayoutNextLineContext, c as LayoutNextLineResult, R as ReactiveLayoutBundle, e as ReactiveLayoutOptions, f as SegmentBreakKind, h as SegmentMeasureStats, i as analyzeAndMeasure, j as carveTextLineSlots, k as computeCharPositions, l as computeLineBreaks, m as layoutNextLine, r as reactiveLayout } from '../../reactive-layout-BBBWH0V_.cjs';
3
3
  import { Node } from '@graphrefly/pure-ts/core';
4
4
  import { Graph } from '@graphrefly/pure-ts/graph';
5
5
 
@@ -10,6 +10,47 @@ import { Graph } from '@graphrefly/pure-ts/graph';
10
10
  * Sync constructors, sync `measureSegment()` — no async, no polling.
11
11
  */
12
12
 
13
+ /**
14
+ * Reference {@link SegmentAdapter} backed by the platform `Intl.Segmenter`
15
+ * — the substrate's default on engines that ship `Intl.Segmenter` (V8,
16
+ * SpiderMonkey, JSC, modern Node, browsers).
17
+ *
18
+ * **Hermes / RN consumers must not use this** — Hermes ships without
19
+ * `Intl.Segmenter`, and the constructor below throws a clear `TypeError`
20
+ * naming the polyfill path (`optimizations.md` 🟠 (d), 2026-05-20). Wire a
21
+ * custom {@link SegmentAdapter} via `reactiveLayout({ segmentAdapter })`
22
+ * instead — see the {@link SegmentAdapter} JSDoc for the recipe.
23
+ *
24
+ * Per-granularity `Intl.Segmenter` instances are lazy-cached internally
25
+ * (matches the pre-DS module-scoped lazy that this class replaces — see
26
+ * the pre-2026-05-20 `_graphemeSegmenter` helper in `reactive-layout.ts`).
27
+ * Construction is eager (`new IntlSegmentAdapter()` throws on Hermes) so
28
+ * the failure surfaces at factory boot, not at first text-measure call.
29
+ *
30
+ * @remarks
31
+ * Construction policy is **fail-fast**: an engine without `Intl.Segmenter`
32
+ * is fundamentally unable to use this adapter, and silently lazy-deferring
33
+ * the throw would just shift it from `reactiveLayout({})` into the first
34
+ * `analyzeAndMeasure` invocation deep in a reactive wave (the original
35
+ * memo:Re Story 3.6 failure shape — non-resubscribable terminal on
36
+ * `measured-blocks`, cryptic `Cannot read property 'prototype' of
37
+ * undefined`). Eager throw with the polyfill recipe is the better DX.
38
+ */
39
+ declare class IntlSegmentAdapter implements SegmentAdapter {
40
+ private wordSeg;
41
+ private graphemeSeg;
42
+ constructor();
43
+ segmentWords(text: string): Iterable<SegmentInfo>;
44
+ segmentGraphemes(text: string): Iterable<SegmentInfo>;
45
+ }
46
+ declare function getDefaultSegmentAdapter(): SegmentAdapter;
47
+ /**
48
+ * Test-only: reset the module-shared default. Use in `afterEach` after stubbing
49
+ * `Intl.Segmenter` so a subsequent unstubbed test rebuilds a fresh default.
50
+ *
51
+ * @internal
52
+ */
53
+ declare function _resetDefaultSegmentAdapterForTests(): void;
13
54
  type CliMeasureAdapterOptions = {
14
55
  /** Pixel width per terminal cell (default: 8). */
15
56
  cellPx?: number;
@@ -27,6 +68,72 @@ declare class CliMeasureAdapter implements MeasurementAdapter {
27
68
  width: number;
28
69
  };
29
70
  }
71
+ /**
72
+ * A synchronous text-measurement function.
73
+ *
74
+ * `(text, font) => widthPx`. Must be **synchronous** (the layout engine is a
75
+ * pure-arithmetic reactive graph — no async, no polling per spec §5.8/§5.10)
76
+ * and **pure** for a given `(text, font)` pair within a layout pass.
77
+ *
78
+ * `font` is the same CSS-`font`-shorthand string the rest of Reactive Layout
79
+ * uses (e.g. `"16px Kalam"`). A host backend that keys on a parsed
80
+ * size/family instead can ignore parts it does not need.
81
+ */
82
+ type MeasureFn = (text: string, font: string) => number;
83
+ /**
84
+ * Backend-agnostic measurement adapter — wraps an injected synchronous
85
+ * `(text, font) => widthPx` function.
86
+ *
87
+ * This is the **React Native / Hermes reference adapter** and the documented
88
+ * RN measure-adapter contract. RN has no DOM/`OffscreenCanvas`, so
89
+ * {@link CanvasMeasureAdapter} cannot run there; instead the host supplies a
90
+ * sync measure function bound to its native text engine and passes it here.
91
+ * The substrate ships only this generic seam + contract — the concrete
92
+ * native binding stays userland (same split as the `bytes`-`StorageBackend`
93
+ * Drizzle/Expo-SQLite adapter vs. the upstream `bigintJsonCodecFor`).
94
+ *
95
+ * ### React Native (Skia) reference wiring — userland
96
+ *
97
+ * ```ts
98
+ * import { Skia } from "@shopify/react-native-skia";
99
+ * import { InjectedMeasureAdapter } from "@graphrefly/graphrefly/utils/reactive-layout";
100
+ *
101
+ * // Build the font(s) you lay out with once, outside the measure fn.
102
+ * const typeface = Skia.Typeface.MakeFreeTypeFaceFromData(kalamTtf);
103
+ * const skFont = Skia.Font(typeface, 16);
104
+ *
105
+ * const adapter = new InjectedMeasureAdapter((text, _font) => {
106
+ * // Skia Font.measureText / getGlyphWidths is synchronous — perfect fit.
107
+ * return skFont.measureText(text).width;
108
+ * });
109
+ * ```
110
+ *
111
+ * RN core (no Skia) can instead inject a precomputed per-glyph metric table
112
+ * lookup, or `@shopify/react-native-skia`'s `Paragraph` builder measured
113
+ * synchronously. The only contract is **sync + pure**.
114
+ *
115
+ * @remarks
116
+ * - **Hermes-safe:** this adapter has zero `node:*` and zero DOM globals —
117
+ * the injected fn is the sole boundary to the host text engine. The
118
+ * root-package browser-safety bundle assertion enforces no `node:*` and
119
+ * that DOM globals in the `reactive-layout` graph stay `typeof`-guarded
120
+ * (the `CanvasMeasureAdapter` convention) — see the `reactive-layout`
121
+ * solution doc for the precise guarantee.
122
+ * - An optional `cache: true` memoizes by the `(font, text)` pair (an internal `\u0000` delimiter, collision-safe). Leave it
123
+ * off (default) when the host engine is already fast or when the working
124
+ * set is unbounded; turn it on for repeated re-layout of stable content.
125
+ */
126
+ declare class InjectedMeasureAdapter implements MeasurementAdapter {
127
+ private readonly fn;
128
+ private readonly cache;
129
+ constructor(fn: MeasureFn, opts?: {
130
+ cache?: boolean;
131
+ });
132
+ measureSegment(text: string, font: string): {
133
+ width: number;
134
+ };
135
+ clearCache(): void;
136
+ }
30
137
  type PrecomputedAdapterOptions = {
31
138
  /**
32
139
  * Pre-computed metrics: `{ font: { segment: widthPx } }`.
@@ -191,6 +298,12 @@ interface ImageMeasurer {
191
298
  type BlockAdapters = {
192
299
  /** Text measurement adapter (required — delegates to `reactiveLayout` internals). */
193
300
  text: MeasurementAdapter;
301
+ /**
302
+ * Text segmentation adapter (optional). Defaults to a lazy
303
+ * {@link IntlSegmentAdapter}; **must be supplied on Hermes / RN** to avoid
304
+ * the missing-`Intl.Segmenter` runtime throw — see {@link SegmentAdapter}.
305
+ */
306
+ segment?: SegmentAdapter;
194
307
  /** SVG measurement (optional — required only if SVG blocks are present). */
195
308
  svg?: SvgMeasurer;
196
309
  /** Image measurement (optional — required only if image blocks without explicit dimensions are present). */
@@ -397,6 +510,11 @@ type PositionedLine = {
397
510
  /** Options for `reactiveFlowLayout`. */
398
511
  type ReactiveFlowLayoutOptions = {
399
512
  adapter: MeasurementAdapter;
513
+ /**
514
+ * Segmentation backend (optional). Defaults to a lazy {@link IntlSegmentAdapter};
515
+ * **must be supplied on Hermes / RN** — see {@link SegmentAdapter}.
516
+ */
517
+ segmentAdapter?: SegmentAdapter;
400
518
  name?: string;
401
519
  text?: string;
402
520
  font?: string;
@@ -450,6 +568,13 @@ type ComputeFlowLinesOptions = {
450
568
  * set larger (e.g. `2 * lineHeight`) for looser manuscript settings.
451
569
  */
452
570
  paragraphSpacing?: number;
571
+ /**
572
+ * Segmentation adapter passed through to internal `layoutNextLine` calls
573
+ * (the grapheme-slicing path triggers on partial-segment breaks). Defaults
574
+ * to the lazy {@link IntlSegmentAdapter}; **wire a polyfilled
575
+ * {@link SegmentAdapter} on Hermes / RN.**
576
+ */
577
+ segmentAdapter?: SegmentAdapter;
453
578
  };
454
579
  /**
455
580
  * Lay out `segments` across N columns, wrapping each line around `obstacles`.
@@ -489,4 +614,4 @@ declare function computeFlowLines(segments: PreparedSegment[], container: FlowCo
489
614
  */
490
615
  declare function reactiveFlowLayout(opts: ReactiveFlowLayoutOptions): ReactiveFlowLayoutBundle;
491
616
 
492
- export { type BlockAdapters, CanvasMeasureAdapter, type CanvasMeasureAdapterOptions, type CanvasModule, CharPosition, type CircleObstacle, CliMeasureAdapter, type CliMeasureAdapterOptions, type ComputeFlowLinesOptions, type ContentBlock, type FlowColumns, type FlowContainer, type FlowLinesResult, type ImageMeasurer, ImageSizeAdapter, Interval, LayoutCursor, LineBreaksResult, type MeasuredBlock, MeasurementAdapter, NodeCanvasMeasureAdapter, type Obstacle, type PositionedBlock, type PositionedLine, PrecomputedAdapter, type PrecomputedAdapterOptions, PreparedSegment, type ReactiveBlockLayoutBundle, type ReactiveBlockLayoutOptions, type ReactiveFlowLayoutBundle, type ReactiveFlowLayoutOptions, type RectObstacle, SvgBoundsAdapter, type SvgMeasurer, circleIntervalForBand, computeBlockFlow, computeFlowLines, computeTotalHeight, measureBlock, measureBlocks, reactiveBlockLayout, reactiveFlowLayout, rectIntervalForBand };
617
+ export { type BlockAdapters, CanvasMeasureAdapter, type CanvasMeasureAdapterOptions, type CanvasModule, CharPosition, type CircleObstacle, CliMeasureAdapter, type CliMeasureAdapterOptions, type ComputeFlowLinesOptions, type ContentBlock, type FlowColumns, type FlowContainer, type FlowLinesResult, type ImageMeasurer, ImageSizeAdapter, InjectedMeasureAdapter, Interval, IntlSegmentAdapter, LayoutCursor, LineBreaksResult, type MeasureFn, type MeasuredBlock, MeasurementAdapter, NodeCanvasMeasureAdapter, type Obstacle, type PositionedBlock, type PositionedLine, PrecomputedAdapter, type PrecomputedAdapterOptions, PreparedSegment, type ReactiveBlockLayoutBundle, type ReactiveBlockLayoutOptions, type ReactiveFlowLayoutBundle, type ReactiveFlowLayoutOptions, type RectObstacle, SegmentAdapter, SegmentInfo, SvgBoundsAdapter, type SvgMeasurer, _resetDefaultSegmentAdapterForTests, circleIntervalForBand, computeBlockFlow, computeFlowLines, computeTotalHeight, getDefaultSegmentAdapter, measureBlock, measureBlocks, reactiveBlockLayout, reactiveFlowLayout, rectIntervalForBand };
@@ -1,5 +1,5 @@
1
- import { M as MeasurementAdapter, P as PreparedSegment, d as LineBreaksResult, C as CharPosition, L as LayoutCursor, I as Interval } from '../../reactive-layout-fswlBUvX.js';
2
- export { a as LayoutLine, b as LayoutNextLineContext, c as LayoutNextLineResult, R as ReactiveLayoutBundle, e as ReactiveLayoutOptions, S as SegmentBreakKind, f as SegmentMeasureStats, g as analyzeAndMeasure, h as carveTextLineSlots, i as computeCharPositions, j as computeLineBreaks, l as layoutNextLine, r as reactiveLayout } from '../../reactive-layout-fswlBUvX.js';
1
+ import { M as MeasurementAdapter, S as SegmentAdapter, g as SegmentInfo, P as PreparedSegment, d as LineBreaksResult, C as CharPosition, L as LayoutCursor, I as Interval } from '../../reactive-layout-BBBWH0V_.js';
2
+ export { a as LayoutLine, b as LayoutNextLineContext, c as LayoutNextLineResult, R as ReactiveLayoutBundle, e as ReactiveLayoutOptions, f as SegmentBreakKind, h as SegmentMeasureStats, i as analyzeAndMeasure, j as carveTextLineSlots, k as computeCharPositions, l as computeLineBreaks, m as layoutNextLine, r as reactiveLayout } from '../../reactive-layout-BBBWH0V_.js';
3
3
  import { Node } from '@graphrefly/pure-ts/core';
4
4
  import { Graph } from '@graphrefly/pure-ts/graph';
5
5
 
@@ -10,6 +10,47 @@ import { Graph } from '@graphrefly/pure-ts/graph';
10
10
  * Sync constructors, sync `measureSegment()` — no async, no polling.
11
11
  */
12
12
 
13
+ /**
14
+ * Reference {@link SegmentAdapter} backed by the platform `Intl.Segmenter`
15
+ * — the substrate's default on engines that ship `Intl.Segmenter` (V8,
16
+ * SpiderMonkey, JSC, modern Node, browsers).
17
+ *
18
+ * **Hermes / RN consumers must not use this** — Hermes ships without
19
+ * `Intl.Segmenter`, and the constructor below throws a clear `TypeError`
20
+ * naming the polyfill path (`optimizations.md` 🟠 (d), 2026-05-20). Wire a
21
+ * custom {@link SegmentAdapter} via `reactiveLayout({ segmentAdapter })`
22
+ * instead — see the {@link SegmentAdapter} JSDoc for the recipe.
23
+ *
24
+ * Per-granularity `Intl.Segmenter` instances are lazy-cached internally
25
+ * (matches the pre-DS module-scoped lazy that this class replaces — see
26
+ * the pre-2026-05-20 `_graphemeSegmenter` helper in `reactive-layout.ts`).
27
+ * Construction is eager (`new IntlSegmentAdapter()` throws on Hermes) so
28
+ * the failure surfaces at factory boot, not at first text-measure call.
29
+ *
30
+ * @remarks
31
+ * Construction policy is **fail-fast**: an engine without `Intl.Segmenter`
32
+ * is fundamentally unable to use this adapter, and silently lazy-deferring
33
+ * the throw would just shift it from `reactiveLayout({})` into the first
34
+ * `analyzeAndMeasure` invocation deep in a reactive wave (the original
35
+ * memo:Re Story 3.6 failure shape — non-resubscribable terminal on
36
+ * `measured-blocks`, cryptic `Cannot read property 'prototype' of
37
+ * undefined`). Eager throw with the polyfill recipe is the better DX.
38
+ */
39
+ declare class IntlSegmentAdapter implements SegmentAdapter {
40
+ private wordSeg;
41
+ private graphemeSeg;
42
+ constructor();
43
+ segmentWords(text: string): Iterable<SegmentInfo>;
44
+ segmentGraphemes(text: string): Iterable<SegmentInfo>;
45
+ }
46
+ declare function getDefaultSegmentAdapter(): SegmentAdapter;
47
+ /**
48
+ * Test-only: reset the module-shared default. Use in `afterEach` after stubbing
49
+ * `Intl.Segmenter` so a subsequent unstubbed test rebuilds a fresh default.
50
+ *
51
+ * @internal
52
+ */
53
+ declare function _resetDefaultSegmentAdapterForTests(): void;
13
54
  type CliMeasureAdapterOptions = {
14
55
  /** Pixel width per terminal cell (default: 8). */
15
56
  cellPx?: number;
@@ -27,6 +68,72 @@ declare class CliMeasureAdapter implements MeasurementAdapter {
27
68
  width: number;
28
69
  };
29
70
  }
71
+ /**
72
+ * A synchronous text-measurement function.
73
+ *
74
+ * `(text, font) => widthPx`. Must be **synchronous** (the layout engine is a
75
+ * pure-arithmetic reactive graph — no async, no polling per spec §5.8/§5.10)
76
+ * and **pure** for a given `(text, font)` pair within a layout pass.
77
+ *
78
+ * `font` is the same CSS-`font`-shorthand string the rest of Reactive Layout
79
+ * uses (e.g. `"16px Kalam"`). A host backend that keys on a parsed
80
+ * size/family instead can ignore parts it does not need.
81
+ */
82
+ type MeasureFn = (text: string, font: string) => number;
83
+ /**
84
+ * Backend-agnostic measurement adapter — wraps an injected synchronous
85
+ * `(text, font) => widthPx` function.
86
+ *
87
+ * This is the **React Native / Hermes reference adapter** and the documented
88
+ * RN measure-adapter contract. RN has no DOM/`OffscreenCanvas`, so
89
+ * {@link CanvasMeasureAdapter} cannot run there; instead the host supplies a
90
+ * sync measure function bound to its native text engine and passes it here.
91
+ * The substrate ships only this generic seam + contract — the concrete
92
+ * native binding stays userland (same split as the `bytes`-`StorageBackend`
93
+ * Drizzle/Expo-SQLite adapter vs. the upstream `bigintJsonCodecFor`).
94
+ *
95
+ * ### React Native (Skia) reference wiring — userland
96
+ *
97
+ * ```ts
98
+ * import { Skia } from "@shopify/react-native-skia";
99
+ * import { InjectedMeasureAdapter } from "@graphrefly/graphrefly/utils/reactive-layout";
100
+ *
101
+ * // Build the font(s) you lay out with once, outside the measure fn.
102
+ * const typeface = Skia.Typeface.MakeFreeTypeFaceFromData(kalamTtf);
103
+ * const skFont = Skia.Font(typeface, 16);
104
+ *
105
+ * const adapter = new InjectedMeasureAdapter((text, _font) => {
106
+ * // Skia Font.measureText / getGlyphWidths is synchronous — perfect fit.
107
+ * return skFont.measureText(text).width;
108
+ * });
109
+ * ```
110
+ *
111
+ * RN core (no Skia) can instead inject a precomputed per-glyph metric table
112
+ * lookup, or `@shopify/react-native-skia`'s `Paragraph` builder measured
113
+ * synchronously. The only contract is **sync + pure**.
114
+ *
115
+ * @remarks
116
+ * - **Hermes-safe:** this adapter has zero `node:*` and zero DOM globals —
117
+ * the injected fn is the sole boundary to the host text engine. The
118
+ * root-package browser-safety bundle assertion enforces no `node:*` and
119
+ * that DOM globals in the `reactive-layout` graph stay `typeof`-guarded
120
+ * (the `CanvasMeasureAdapter` convention) — see the `reactive-layout`
121
+ * solution doc for the precise guarantee.
122
+ * - An optional `cache: true` memoizes by the `(font, text)` pair (an internal `\u0000` delimiter, collision-safe). Leave it
123
+ * off (default) when the host engine is already fast or when the working
124
+ * set is unbounded; turn it on for repeated re-layout of stable content.
125
+ */
126
+ declare class InjectedMeasureAdapter implements MeasurementAdapter {
127
+ private readonly fn;
128
+ private readonly cache;
129
+ constructor(fn: MeasureFn, opts?: {
130
+ cache?: boolean;
131
+ });
132
+ measureSegment(text: string, font: string): {
133
+ width: number;
134
+ };
135
+ clearCache(): void;
136
+ }
30
137
  type PrecomputedAdapterOptions = {
31
138
  /**
32
139
  * Pre-computed metrics: `{ font: { segment: widthPx } }`.
@@ -191,6 +298,12 @@ interface ImageMeasurer {
191
298
  type BlockAdapters = {
192
299
  /** Text measurement adapter (required — delegates to `reactiveLayout` internals). */
193
300
  text: MeasurementAdapter;
301
+ /**
302
+ * Text segmentation adapter (optional). Defaults to a lazy
303
+ * {@link IntlSegmentAdapter}; **must be supplied on Hermes / RN** to avoid
304
+ * the missing-`Intl.Segmenter` runtime throw — see {@link SegmentAdapter}.
305
+ */
306
+ segment?: SegmentAdapter;
194
307
  /** SVG measurement (optional — required only if SVG blocks are present). */
195
308
  svg?: SvgMeasurer;
196
309
  /** Image measurement (optional — required only if image blocks without explicit dimensions are present). */
@@ -397,6 +510,11 @@ type PositionedLine = {
397
510
  /** Options for `reactiveFlowLayout`. */
398
511
  type ReactiveFlowLayoutOptions = {
399
512
  adapter: MeasurementAdapter;
513
+ /**
514
+ * Segmentation backend (optional). Defaults to a lazy {@link IntlSegmentAdapter};
515
+ * **must be supplied on Hermes / RN** — see {@link SegmentAdapter}.
516
+ */
517
+ segmentAdapter?: SegmentAdapter;
400
518
  name?: string;
401
519
  text?: string;
402
520
  font?: string;
@@ -450,6 +568,13 @@ type ComputeFlowLinesOptions = {
450
568
  * set larger (e.g. `2 * lineHeight`) for looser manuscript settings.
451
569
  */
452
570
  paragraphSpacing?: number;
571
+ /**
572
+ * Segmentation adapter passed through to internal `layoutNextLine` calls
573
+ * (the grapheme-slicing path triggers on partial-segment breaks). Defaults
574
+ * to the lazy {@link IntlSegmentAdapter}; **wire a polyfilled
575
+ * {@link SegmentAdapter} on Hermes / RN.**
576
+ */
577
+ segmentAdapter?: SegmentAdapter;
453
578
  };
454
579
  /**
455
580
  * Lay out `segments` across N columns, wrapping each line around `obstacles`.
@@ -489,4 +614,4 @@ declare function computeFlowLines(segments: PreparedSegment[], container: FlowCo
489
614
  */
490
615
  declare function reactiveFlowLayout(opts: ReactiveFlowLayoutOptions): ReactiveFlowLayoutBundle;
491
616
 
492
- export { type BlockAdapters, CanvasMeasureAdapter, type CanvasMeasureAdapterOptions, type CanvasModule, CharPosition, type CircleObstacle, CliMeasureAdapter, type CliMeasureAdapterOptions, type ComputeFlowLinesOptions, type ContentBlock, type FlowColumns, type FlowContainer, type FlowLinesResult, type ImageMeasurer, ImageSizeAdapter, Interval, LayoutCursor, LineBreaksResult, type MeasuredBlock, MeasurementAdapter, NodeCanvasMeasureAdapter, type Obstacle, type PositionedBlock, type PositionedLine, PrecomputedAdapter, type PrecomputedAdapterOptions, PreparedSegment, type ReactiveBlockLayoutBundle, type ReactiveBlockLayoutOptions, type ReactiveFlowLayoutBundle, type ReactiveFlowLayoutOptions, type RectObstacle, SvgBoundsAdapter, type SvgMeasurer, circleIntervalForBand, computeBlockFlow, computeFlowLines, computeTotalHeight, measureBlock, measureBlocks, reactiveBlockLayout, reactiveFlowLayout, rectIntervalForBand };
617
+ export { type BlockAdapters, CanvasMeasureAdapter, type CanvasMeasureAdapterOptions, type CanvasModule, CharPosition, type CircleObstacle, CliMeasureAdapter, type CliMeasureAdapterOptions, type ComputeFlowLinesOptions, type ContentBlock, type FlowColumns, type FlowContainer, type FlowLinesResult, type ImageMeasurer, ImageSizeAdapter, InjectedMeasureAdapter, Interval, IntlSegmentAdapter, LayoutCursor, LineBreaksResult, type MeasureFn, type MeasuredBlock, MeasurementAdapter, NodeCanvasMeasureAdapter, type Obstacle, type PositionedBlock, type PositionedLine, PrecomputedAdapter, type PrecomputedAdapterOptions, PreparedSegment, type ReactiveBlockLayoutBundle, type ReactiveBlockLayoutOptions, type ReactiveFlowLayoutBundle, type ReactiveFlowLayoutOptions, type RectObstacle, SegmentAdapter, SegmentInfo, SvgBoundsAdapter, type SvgMeasurer, _resetDefaultSegmentAdapterForTests, circleIntervalForBand, computeBlockFlow, computeFlowLines, computeTotalHeight, getDefaultSegmentAdapter, measureBlock, measureBlocks, reactiveBlockLayout, reactiveFlowLayout, rectIntervalForBand };
@@ -1,10 +1,4 @@
1
1
  import {
2
- CanvasMeasureAdapter,
3
- CliMeasureAdapter,
4
- ImageSizeAdapter,
5
- NodeCanvasMeasureAdapter,
6
- PrecomputedAdapter,
7
- SvgBoundsAdapter,
8
2
  circleIntervalForBand,
9
3
  computeBlockFlow,
10
4
  computeFlowLines,
@@ -14,15 +8,25 @@ import {
14
8
  reactiveBlockLayout,
15
9
  reactiveFlowLayout,
16
10
  rectIntervalForBand
17
- } from "../../chunk-42FQ27MQ.js";
11
+ } from "../../chunk-MTODGQBR.js";
18
12
  import {
13
+ CanvasMeasureAdapter,
14
+ CliMeasureAdapter,
15
+ ImageSizeAdapter,
16
+ InjectedMeasureAdapter,
17
+ IntlSegmentAdapter,
18
+ NodeCanvasMeasureAdapter,
19
+ PrecomputedAdapter,
20
+ SvgBoundsAdapter,
21
+ _resetDefaultSegmentAdapterForTests,
19
22
  analyzeAndMeasure,
20
23
  carveTextLineSlots,
21
24
  computeCharPositions,
22
25
  computeLineBreaks,
26
+ getDefaultSegmentAdapter,
23
27
  layoutNextLine,
24
28
  reactiveLayout
25
- } from "../../chunk-3PSLNJDU.js";
29
+ } from "../../chunk-6DQYBIHW.js";
26
30
  import "../../chunk-KN3H5CNT.js";
27
31
  import "../../chunk-36NMM65U.js";
28
32
  import "../../chunk-AZDQPQ3V.js";
@@ -30,9 +34,12 @@ export {
30
34
  CanvasMeasureAdapter,
31
35
  CliMeasureAdapter,
32
36
  ImageSizeAdapter,
37
+ InjectedMeasureAdapter,
38
+ IntlSegmentAdapter,
33
39
  NodeCanvasMeasureAdapter,
34
40
  PrecomputedAdapter,
35
41
  SvgBoundsAdapter,
42
+ _resetDefaultSegmentAdapterForTests,
36
43
  analyzeAndMeasure,
37
44
  carveTextLineSlots,
38
45
  circleIntervalForBand,
@@ -41,6 +48,7 @@ export {
41
48
  computeFlowLines,
42
49
  computeLineBreaks,
43
50
  computeTotalHeight,
51
+ getDefaultSegmentAdapter,
44
52
  layoutNextLine,
45
53
  measureBlock,
46
54
  measureBlocks,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/reduction/index.ts","../../../src/base/meta/domain-meta.ts","../../../src/base/mutation/index.ts"],"sourcesContent":["/**\n * Reduction primitives (roadmap §8.1).\n *\n * Composable building blocks for taking heterogeneous massive inputs and producing\n * prioritized, auditable, human-actionable output. Each primitive is either a Graph\n * factory or a Node factory, built on top of core + extra primitives.\n *\n * @module\n */\n\nimport {\n\tbatch,\n\tCOMPLETE,\n\tDATA,\n\tERROR,\n\ttype Message,\n\ttype Node,\n\ttype NodeOptions,\n\tnode,\n} from \"@graphrefly/pure-ts/core\";\n\nimport { merge } from \"@graphrefly/pure-ts/extra\";\nimport { Graph, type GraphOptions } from \"@graphrefly/pure-ts/graph\";\n\n// ---------------------------------------------------------------------------\n// Shared helpers (same pattern as orchestration.ts)\n// ---------------------------------------------------------------------------\n\nexport type { StepRef } from \"../orchestration/pipeline-graph.js\";\n\nimport { keepalive } from \"@graphrefly/pure-ts/extra\";\nimport { domainMeta } from \"../../base/meta/domain-meta.js\";\nimport { tryIncrementBounded } from \"../../base/mutation/index.js\";\nimport type { StepRef } from \"../orchestration/pipeline-graph.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"reduction\", kind, meta);\n}\n\n// stratify moved to `src/extra/stratify.ts` (protocol-level primitive).\n\n// ---------------------------------------------------------------------------\n// funnel\n// ---------------------------------------------------------------------------\n\n/** A named stage for {@link funnel}. */\nexport type FunnelStage = {\n\t/** Stage name (mounted as subgraph). */\n\tname: string;\n\t/** Builder: receives a sub-graph, should add an `\"input\"` and `\"output\"` node. */\n\tbuild: (sub: Graph) => void;\n};\n\n/** Options for {@link funnel}. */\nexport type FunnelOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Multi-source merge with sequential reduction stages.\n *\n * Sources are merged into a single stream. Each stage is a named subgraph\n * (mounted via `graph.mount()`). Stages connect linearly:\n * `merged → stage[0].input → stage[0].output → stage[1].input → ...`\n *\n * @param name - Graph name.\n * @param sources - Input nodes to merge.\n * @param stages - Sequential reduction stages.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"merged\"` and mounted stage subgraphs.\n *\n * @category patterns\n */\nexport function funnel<T>(\n\tname: string,\n\tsources: ReadonlyArray<Node<T>>,\n\tstages: ReadonlyArray<FunnelStage>,\n\topts?: FunnelOptions,\n): Graph {\n\tif (sources.length === 0) throw new RangeError(\"funnel requires at least one source\");\n\tif (stages.length === 0) throw new RangeError(\"funnel requires at least one stage\");\n\n\tconst g = new Graph(name, opts);\n\n\t// Merge all sources\n\tconst merged = sources.length === 1 ? sources[0] : merge(...(sources as unknown as Node<T>[]));\n\tg.add(merged as Node<unknown>, { name: \"merged\" });\n\n\t// Build and mount each stage linearly.\n\t// Stage inputs are standalone state nodes, so we bridge via subscribe\n\t// (connect() requires constructor deps). Bridge effects forward DATA\n\t// from the previous output to the next stage's input.\n\tlet prevOutputPath = \"merged\";\n\tfor (let i = 0; i < stages.length; i++) {\n\t\tconst stage = stages[i];\n\t\tconst sub = new Graph(stage.name);\n\t\tstage.build(sub);\n\n\t\t// Validate that the stage has input and output nodes\n\t\ttry {\n\t\t\tsub.resolve(\"input\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"input\" node`);\n\t\t}\n\t\ttry {\n\t\t\tsub.resolve(\"output\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"output\" node`);\n\t\t}\n\n\t\tg.mount(stage.name, sub);\n\n\t\t// Bridge replacement: effect that forwards DATA from previous output\n\t\t// to the next stage's input. TEARDOWN excluded because stage lifecycle\n\t\t// is managed by the parent graph. Shows up in describe().\n\t\tconst prevNode = g.resolve(prevOutputPath);\n\t\tconst stageInputPath = `${stage.name}::input`;\n\t\tconst stageInput = g.resolve(stageInputPath);\n\t\tconst bridgeName = `__bridge_${prevOutputPath}→${stage.name}_input`;\n\t\tconst br = node(\n\t\t\t[prevNode],\n\t\t\t(batchData, _actions, ctx) => {\n\t\t\t\tconst data = batchData.map((batch, i) =>\n\t\t\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t\t\t);\n\t\t\t\tstageInput.emit(data[0]);\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ describeKind: \"effect\", name: bridgeName },\n\t\t);\n\t\tg.add(br as Node<unknown>, { name: bridgeName });\n\t\tg.addDisposer(keepalive(br));\n\n\t\tprevOutputPath = `${stage.name}::output`;\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// feedback\n// ---------------------------------------------------------------------------\n\n/** Options for {@link feedback}. */\nexport type FeedbackOptions = {\n\t/** Maximum feedback iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n\t/** Optional budget gate node path for cost-bounded iteration. */\n\tbudgetNode?: StepRef;\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Introduce a bounded reactive cycle into an existing graph.\n *\n * When `condition` emits a non-null DATA value, the feedback effect routes it\n * back to the `reentry` state node — creating a cycle. Bounded by\n * `maxIterations` (default 10). The counter node (`__feedback_<condition>`)\n * is the source of truth — reset it to 0 to allow more iterations.\n *\n * To remove the feedback cycle, call `graph.remove(\"__feedback_<condition>\")`.\n *\n * @param graph - Existing graph to augment with a feedback cycle.\n * @param condition - Path to a node whose DATA triggers feedback.\n * @param reentry - Path to a state node that receives the feedback value.\n * @param opts - Iteration bounds and metadata.\n * @returns The same graph (mutated with feedback nodes added).\n *\n * @category patterns\n */\nexport function feedback(\n\tgraph: Graph,\n\tcondition: string,\n\treentry: string,\n\topts?: FeedbackOptions,\n): Graph {\n\tconst maxIter = opts?.maxIterations ?? 10;\n\n\t// Internal counter node — source of truth for iteration bound.\n\t// Reset to 0 to allow more iterations.\n\tconst counterName = `__feedback_${condition}`;\n\tconst counter = node<number>([], {\n\t\t...{\n\t\t\tmeta: baseMeta(\"feedback_counter\", {\n\t\t\t\tmaxIterations: maxIter,\n\t\t\t\tfeedbackFrom: condition,\n\t\t\t\tfeedbackTo: reentry,\n\t\t\t}),\n\t\t},\n\t\tinitial: 0,\n\t});\n\tgraph.add(counter as Node<unknown>, { name: counterName });\n\n\t// Resolve the condition and reentry nodes\n\tconst condNode = graph.resolve(condition);\n\tconst reentryNode = graph.resolve(reentry);\n\n\t// Graph-visible feedback effect: intercepts condition DATA, routes back to\n\t// reentry with iteration counting. Registered in the graph so it shows up\n\t// in describe() and cleans up on graph.destroy().\n\t// Feedback effect: subscribe to condition node for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst feedbackEffectName = `__feedback_effect_${condition}`;\n\tconst feedbackEffect = node(\n\t\t[],\n\t\t(_data, _feedbackActions) => {\n\t\t\tconst unsub = condNode.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tconst condValue = msg[1];\n\t\t\t\t\t\tif (condValue == null) return;\n\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\tif (tryIncrementBounded(counter, maxIter)) {\n\t\t\t\t\t\t\t\treentryNode.emit(condValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (t === COMPLETE || t === ERROR) {\n\t\t\t\t\t\tconst terminal: Message = t === ERROR && msg.length > 1 ? [ERROR, msg[1]] : [t];\n\t\t\t\t\t\tcounter.down([terminal]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn { onDeactivation: () => unsub() };\n\t\t},\n\t\t{\n\t\t\tname: feedbackEffectName,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tmeta: {\n\t\t\t\t...baseMeta(\"feedback_effect\", {\n\t\t\t\t\tfeedbackFrom: condition,\n\t\t\t\t\tfeedbackTo: reentry,\n\t\t\t\t}),\n\t\t\t\t_internal: true,\n\t\t\t},\n\t\t},\n\t);\n\tgraph.add(feedbackEffect as Node<unknown>, { name: feedbackEffectName });\n\tgraph.addDisposer(keepalive(feedbackEffect));\n\n\treturn graph;\n}\n\n// `budgetGate` was promoted to `extra/resilience/budget-gate.ts` per Tier 2.2.\n// Import from `@graphrefly/graphrefly/extra` (or `../../extra/resilience/budget-gate.js`\n// internally) instead. See the resilience family for sibling primitives:\n// `retry`, `circuitBreaker`, `rateLimiter`, `tokenBucket`, `fallback`, `withStatus`.\n\n// ---------------------------------------------------------------------------\n// scorer\n// ---------------------------------------------------------------------------\n\n/** A scored item with full breakdown. */\nexport type ScoredItem<T = unknown> = {\n\t/** Original value. */\n\tvalue: T;\n\t/** Final weighted score. */\n\tscore: number;\n\t/** Per-signal breakdown: signal index → weighted contribution. */\n\tbreakdown: number[];\n};\n\n/** Options for {@link scorer}. */\nexport type ScorerOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n\t/** Custom scoring function per signal. Default: identity (signal value IS the score). */\n\tscoreFns?: ReadonlyArray<(value: unknown) => number>;\n};\n\n/**\n * Reactive multi-signal scoring with live weights.\n *\n * Each source emits items to score. Weights are reactive state nodes that\n * LLM or human can adjust live. Output is sorted scored items with full\n * breakdown.\n *\n * @param sources - Signal nodes (each emits a numeric score dimension).\n * @param weights - Reactive weight nodes (one per source).\n * @param opts - Optional node/meta options.\n * @returns Node emitting scored output.\n *\n * @category patterns\n */\nexport function scorer(\n\tsources: ReadonlyArray<Node<number>>,\n\tweights: ReadonlyArray<Node<number>>,\n\topts?: ScorerOptions,\n): Node<ScoredItem<number[]>> {\n\tif (sources.length === 0) throw new RangeError(\"scorer requires at least one source\");\n\tif (sources.length !== weights.length) {\n\t\tthrow new RangeError(\"scorer requires the same number of sources and weights\");\n\t}\n\n\tconst allDeps = [...(sources as unknown as Node[]), ...(weights as unknown as Node[])];\n\tconst n = sources.length;\n\tconst scoreFns = opts?.scoreFns;\n\n\treturn node<ScoredItem<number[]>>(\n\t\tallDeps,\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst vals = batchData.map((batch, i) =>\n\t\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t\t);\n\t\t\tconst signals = vals.slice(0, n) as number[];\n\t\t\tconst weightValues = vals.slice(n) as number[];\n\n\t\t\tconst breakdown: number[] = [];\n\t\t\tlet totalScore = 0;\n\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst sig = signals[i] ?? 0;\n\t\t\t\tconst wt = weightValues[i] ?? 0;\n\t\t\t\tconst rawScore = scoreFns?.[i] ? scoreFns[i](sig) : sig;\n\t\t\t\tconst weighted = (rawScore as number) * wt;\n\t\t\t\tbreakdown.push(weighted);\n\t\t\t\ttotalScore += weighted;\n\t\t\t}\n\n\t\t\tactions.emit({\n\t\t\t\tvalue: signals,\n\t\t\t\tscore: totalScore,\n\t\t\t\tbreakdown,\n\t\t\t});\n\t\t},\n\t\t{\n\t\t\t...(opts\n\t\t\t\t? {\n\t\t\t\t\t\tequals: opts.equals,\n\t\t\t\t\t\tresubscribable: opts.resubscribable,\n\t\t\t\t\t\tresetOnTeardown: opts.resetOnTeardown,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"scorer\", opts?.meta),\n\t\t},\n\t);\n}\n\n// `effectivenessTracker` was deleted per Class B audit Alt E (2026-04-30).\n// The shared substrate now lives in `extra/composition/audited-success-tracker.ts`\n// — re-exported via `@graphrefly/graphrefly-ts/extra` for general use.\n","/**\n * Metadata helpers for pattern-layer nodes (Tier 2.2 promotion from\n * `patterns/_internal/`).\n *\n * Each domain (orchestration, messaging, reduction, ai, cqrs, domain_template,\n * memory, lens, audit, harness) shares the same metadata convention. Promoted\n * to `extra/` so non-patterns code (and downstream consumers building their\n * own domain primitives) can use the same shape.\n *\n * @module\n */\n\n/**\n * Build a domain metadata object for pattern-layer nodes.\n *\n * Each domain follows the same shape: `{ [domain]: true, [domain]_type: kind, ...extra }`.\n *\n * @param domain - The domain tag (e.g. `\"orchestration\"`, `\"ai\"`, `\"cqrs\"`).\n * @param kind - The specific type within the domain (e.g. `\"gate\"`, `\"prompt\"`).\n * @param extra - Additional metadata to merge.\n * @returns Metadata object.\n */\nexport function domainMeta(\n\tdomain: string,\n\tkind: string,\n\textra?: Record<string, unknown>,\n): Record<string, unknown> {\n\treturn {\n\t\t[domain]: true,\n\t\t[`${domain}_type`]: kind,\n\t\t...(extra ?? {}),\n\t};\n}\n","/**\n * Universal mutation framework (Phase 14 — DS-14 locked 2026-05-05).\n *\n * Single `mutate(act, opts)` factory replaces the prior `lightMutation` +\n * `wrapMutation` two-tier split (pre-1.0 break per Q-O2).\n *\n * Two frames:\n * - `\"inline\"` — no batch; up() runs raw. Seq bumps before action; persists\n * on throw. Hot-path-friendly for atomic single-write mutations.\n * - `\"transactional\"` — opens `batch(() => up(...))`. On throw: batch discards\n * deferred deliveries, then `down()` runs (if provided), then failure record.\n *\n * Phase-4 primitives share the same shape: imperative mutation methods +\n * closure state + reactive audit log + freeze-at-entry + rollback-on-throw.\n * This module factors out the common machinery so each primitive becomes\n * declarative wiring over typed audit records.\n */\n\nimport {\n\tbatch,\n\tDATA,\n\tDIRTY,\n\ttype Node,\n\ttype NodeGuard,\n\tnode,\n\tpolicy,\n\twallClockNs,\n} from \"@graphrefly/pure-ts/core\";\nimport {\n\ttype ReactiveLogBundle,\n\ttype ReactiveLogOptions,\n\treactiveLog,\n} from \"@graphrefly/pure-ts/extra\";\nimport { Graph } from \"@graphrefly/pure-ts/graph\";\n\n// ── tryIncrementBounded ──────────────────────────────────────────────────\n\n/**\n * Bounded increment for a self-owned counter state node.\n *\n * Reads `counter.cache`, bumps by `by` (default 1) if `cur + by <= cap`,\n * writes back. Returns `false` when the cap would be exceeded (no-op write).\n * Documented P3 exception: the counter is not a declared dep of the caller —\n * it's a private budget read+written from a single call site. This helper\n * keeps the `.cache` access in one named place so caller bodies (which may\n * be inside reactive fn execution paths) stay free of cross-node `.cache`\n * reads.\n *\n * **Safety today:**\n * 1. Single-threaded JS runner never invokes the caller concurrently.\n * 2. `counter.down` writes the cache synchronously before returning, so\n * synchronous re-entry through a downstream publish reads the\n * freshly-incremented value — no double-count.\n *\n * **Future risk:** under a free-threaded runner (PY no-GIL or hypothetical\n * concurrent TS runner), two concurrent firings could still race. Revisit\n * when that surfaces.\n *\n * @param counter - Self-owned counter Node. Caller is the sole writer.\n * @param cap - Upper bound (inclusive). Pass `Number.MAX_SAFE_INTEGER` for\n * \"effectively unbounded\" use cases (e.g. token meters).\n * @param by - Delta to add (default `1`). Must be a finite non-negative\n * number; callers should pre-validate. Overflow-safe via\n * `by > cap - cur` check rather than `cur + by >= cap`.\n */\nexport function tryIncrementBounded(counter: Node<number>, cap: number, by = 1): boolean {\n\tconst cur = (counter.cache as number | undefined) ?? 0;\n\tif (by > cap - cur) return false;\n\tcounter.down([[DIRTY], [DATA, cur + by]]);\n\treturn true;\n}\n\n// ── Audit record schema ──────────────────────────────────────────────────\n\n/** Shared base shape for every audit record. Per-primitive types extend this. */\nexport interface BaseAuditRecord {\n\treadonly t_ns: number;\n\treadonly seq?: number;\n\treadonly handlerVersion?: { id: string; version: string | number };\n}\n\n// ── Default audit guard ──────────────────────────────────────────────────\n\n/**\n * Allow `observe` and `signal`; deny external `write` on the audit log so\n * consumers can subscribe + signal-bridge but cannot inject fake records.\n */\nexport const DEFAULT_AUDIT_GUARD: NodeGuard = policy((allow, deny) => {\n\tallow(\"observe\");\n\tallow(\"signal\");\n\tdeny(\"write\");\n});\n\n// ── createAuditLog ───────────────────────────────────────────────────────\n\nexport type AuditLogOpts<R extends BaseAuditRecord> = {\n\tname: string;\n\t/** Bounded retention; default 1024 per Audit 2 / cross-cutting bounded-default policy. */\n\tretainedLimit?: number;\n\t/** Override the default audit guard. */\n\tguard?: NodeGuard;\n\t/** Mount the audit `entries` Node under this graph (and activate withLatest). */\n\tgraph?: Graph;\n\t/** Pass-through to {@link reactiveLog}. */\n\tversioning?: ReactiveLogOptions<R>[\"versioning\"];\n};\n\n/**\n * Build a reactive audit log with sane defaults: bounded retention, deny-write\n * guard, `withLatest()` companions activated. Returns the {@link ReactiveLogBundle}\n * directly — primitives expose this as `<primitive>.events` / `.decisions` /\n * `.dispatches` / `.invocations` and alias it as `.audit`.\n *\n * @category internal\n */\nexport function createAuditLog<R extends BaseAuditRecord>(\n\topts: AuditLogOpts<R>,\n): ReactiveLogBundle<R> {\n\tconst log = reactiveLog<R>([], {\n\t\tname: opts.name,\n\t\tmaxSize: opts.retainedLimit ?? 1024,\n\t\tguard: opts.guard ?? DEFAULT_AUDIT_GUARD,\n\t\t...(opts.versioning != null ? { versioning: opts.versioning } : {}),\n\t});\n\t// Lazy companion activation up-front so `bundle.lastValue` / `hasLatest`\n\t// are queryable without an explicit `withLatest()` call.\n\tlog.withLatest();\n\tif (opts.graph) {\n\t\topts.graph.add(log.entries, { name: opts.name });\n\t}\n\treturn log;\n}\n\n// ── Universal mutation factory (Phase 14 — DS-14 lock Q-O2/Q-O3) ────────\n//\n// Single `mutate(act, opts)` factory. Two frames:\n//\n// - `\"inline\"` — no batch frame; up() runs raw. Seq bumps before action;\n// persists on throw. Hot-path-friendly for atomic single-write mutations.\n//\n// - `\"transactional\"` — opens `batch(() => up(...))`. On throw: batch discards\n// deferred deliveries, then `down()` runs, then failure record persists.\n//\n// **Heuristic:** if your imperative method's body is one or two lines (mutate\n// state, emit), use `frame: \"inline\"`. If it runs a user-supplied handler or\n// has multiple steps that could leave inconsistent state mid-throw, use\n// `frame: \"transactional\"`.\n\nexport type FailureMeta = {\n\tt_ns: number;\n\tseq?: number;\n\terrorType: string;\n};\n\nexport type SuccessMeta = {\n\tt_ns: number;\n\tseq?: number;\n};\n\n/**\n * Mutation action shape. Plain function shorthand auto-wraps as `{ up: fn }`.\n *\n * - `up` — the mutation action (the \"up migration\").\n * - `down` — optional rollback for closure mutations that `batch()` can't\n * reach. Receives the SAME frozen args as `up`. Runs AFTER batch reactive\n * rollback, BEFORE the failure record. Throws inside `down` are\n * console.error'd without masking the original error. Only meaningful\n * with `frame: \"transactional\"`.\n */\nexport type MutationAct<TArgs extends readonly unknown[], TResult> = {\n\tup: (...args: TArgs) => TResult;\n\tdown?: (...args: TArgs) => void;\n};\n\nexport type MutationFrame = \"inline\" | \"transactional\";\n\nexport type MutateOpts<TArgs extends readonly unknown[], TResult, R extends BaseAuditRecord> = {\n\t/** Frame mode. `\"inline\"` = no batch; `\"transactional\"` = batch + rollback. */\n\tframe: MutationFrame;\n\t/**\n\t * Optional log to append records to. When omitted, the wrapper still\n\t * provides freeze / seq-advance / rollback-on-throw but skips record\n\t * emission — useful for primitives that want centralized mutation\n\t * semantics without a dedicated log surface (e.g. `Topic.publish`).\n\t */\n\tlog?: ReactiveLogBundle<R>;\n\t/** Build the success record from the action's args + result + meta. */\n\tonSuccessRecord?: (args: TArgs, result: TResult, meta: SuccessMeta) => R | undefined;\n\t/** Build the failure record from the args + error + meta. */\n\tonFailureRecord?: (args: TArgs, error: unknown, meta: FailureMeta) => R | undefined;\n\t/** Deep-freeze args at entry (default `true`). Opt out for hot paths. */\n\tfreeze?: boolean;\n\t/** Optional sequence cursor — auto-advanced and stamped onto records. */\n\tseq?: Node<number>;\n\t/** Optional handler version — stamped per Audit 5. */\n\thandlerVersion?: { id: string; version: string | number };\n};\n\nfunction deepFreeze<T>(value: T): T {\n\tif (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tfor (const k of Object.keys(value as Record<string, unknown>)) {\n\t\tdeepFreeze((value as Record<string, unknown>)[k]);\n\t}\n\treturn Object.freeze(value);\n}\n\n/**\n * Universal mutation factory (Phase 14 — DS-14 Q-O2).\n *\n * Replaces the prior `lightMutation` + `wrapMutation` two-tier split.\n * Single factory with `frame: \"inline\" | \"transactional\"` discriminant.\n *\n * @param act - The mutation action. Either a plain function (auto-wrapped as\n * `{ up: fn }`) or a `{ up, down? }` object for explicit rollback.\n * @param opts - Configuration: frame, log, record builders, freeze, seq.\n * @returns A typed wrapper function with the same signature as `act.up`.\n */\nexport function mutate<TArgs extends readonly unknown[], TResult, R extends BaseAuditRecord>(\n\tact: MutationAct<TArgs, TResult> | ((...args: TArgs) => TResult),\n\topts: MutateOpts<TArgs, TResult, R>,\n): (...args: TArgs) => TResult {\n\tconst { up, down } = typeof act === \"function\" ? { up: act, down: undefined } : act;\n\tconst freeze = opts.freeze ?? true;\n\n\tif (opts.frame === \"inline\") {\n\t\treturn function wrapped(...args: TArgs): TResult {\n\t\t\tconst sealed = freeze ? (args.map(deepFreeze) as unknown as TArgs) : args;\n\t\t\tconst t_ns = wallClockNs();\n\t\t\tconst seq = opts.seq ? bumpCursor(opts.seq) : undefined;\n\t\t\ttry {\n\t\t\t\tconst result = up(...sealed);\n\t\t\t\tif (opts.log && opts.onSuccessRecord) {\n\t\t\t\t\tappendAudit<TArgs, TResult, R, SuccessMeta>(\n\t\t\t\t\t\topts.log,\n\t\t\t\t\t\topts.onSuccessRecord,\n\t\t\t\t\t\tsealed,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\t{ t_ns, seq },\n\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t} catch (err) {\n\t\t\t\tif (opts.log && opts.onFailureRecord) {\n\t\t\t\t\tconst errorType = err instanceof Error ? err.name : typeof err;\n\t\t\t\t\tappendAudit<TArgs, unknown, R, FailureMeta>(\n\t\t\t\t\t\topts.log,\n\t\t\t\t\t\topts.onFailureRecord,\n\t\t\t\t\t\tsealed,\n\t\t\t\t\t\terr,\n\t\t\t\t\t\t{ t_ns, seq, errorType },\n\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t}\n\n\t// frame === \"transactional\"\n\treturn function wrapped(...args: TArgs): TResult {\n\t\tconst sealed = freeze ? (args.map(deepFreeze) as unknown as TArgs) : args;\n\t\tconst t_ns = wallClockNs();\n\t\tlet result: TResult;\n\t\tlet captured: unknown;\n\t\tlet captureSet = false;\n\t\tlet seq: number | undefined;\n\t\ttry {\n\t\t\tbatch(() => {\n\t\t\t\tif (opts.seq) seq = bumpCursor(opts.seq);\n\t\t\t\ttry {\n\t\t\t\t\tresult = up(...sealed);\n\t\t\t\t\tif (opts.log && opts.onSuccessRecord) {\n\t\t\t\t\t\tappendAudit<TArgs, TResult, R, SuccessMeta>(\n\t\t\t\t\t\t\topts.log,\n\t\t\t\t\t\t\topts.onSuccessRecord,\n\t\t\t\t\t\t\tsealed,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t{ t_ns, seq },\n\t\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcaptured = err;\n\t\t\t\t\tcaptureSet = true;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (outerErr) {\n\t\t\t// Fire `down` AFTER batch's reactive rollback, BEFORE failure record.\n\t\t\t// Gate on `captureSet` — if the throw came from outside the inner try\n\t\t\t// (framework-level batch error before action ran), don't fire down.\n\t\t\tif (captureSet && down) {\n\t\t\t\ttry {\n\t\t\t\t\tdown(...sealed);\n\t\t\t\t} catch (downErr) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`mutate: down hook threw — original action error preserved (${\n\t\t\t\t\t\t\tcaptured instanceof Error ? captured.name : typeof captured\n\t\t\t\t\t\t}). Down error:`,\n\t\t\t\t\t\tdownErr,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (captureSet && opts.log && opts.onFailureRecord) {\n\t\t\t\tconst errorType = captured instanceof Error ? captured.name : typeof captured;\n\t\t\t\tappendAudit<TArgs, unknown, R, FailureMeta>(\n\t\t\t\t\topts.log,\n\t\t\t\t\topts.onFailureRecord,\n\t\t\t\t\tsealed,\n\t\t\t\t\tcaptured,\n\t\t\t\t\t{ t_ns, seq, errorType },\n\t\t\t\t\topts.handlerVersion,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow captureSet ? captured : outerErr;\n\t\t}\n\t\treturn result!;\n\t};\n}\n\n/**\n * Advance a cursor node and return the new value. Emits `[DIRTY], [DATA, next]`\n * directly on the cursor — atomic outside a batch, rollback-discardable inside.\n *\n * Resets to `0` if the cursor cache is missing, non-numeric, `NaN`, or\n * non-finite (e.g. corrupted by `restore()` from a malformed snapshot, or\n * by a misbehaving codec). `??` alone would let `NaN` and `\"\"` pass through\n * and silently corrupt audit ordering downstream.\n *\n * **Silent reset diagnostic (EH-12).** When the cache holds a non-numeric\n * value at bump time, the cursor restarts at 0 and the next bump returns 1\n * — colliding with the seq stamped on the very first record after construct.\n * To make seq-monotonicity violations after a restore visible to operators,\n * the helper emits a one-shot `console.warn` per cursor instance describing\n * the offending value. The cursor is identified by a `WeakSet<Node<number>>`\n * so the warning fires exactly once per node — repeat malformed bumps stay\n * quiet to avoid log spam. Production callers wanting to suppress can swap\n * the global `console` (universal-safe code path; no Node-only API used).\n *\n * Works whether or not the cursor has any subscribers — `down` updates the\n * cache regardless, so primitives that bump before consumers attach (e.g.\n * `JobQueueGraph.enqueue`) still see a coherent sequence.\n *\n * @category internal\n */\nconst _bumpCursorWarned = new WeakSet<Node<number>>();\nexport function bumpCursor(seq: Node<number>): number {\n\tconst raw = seq.cache;\n\tconst valid = typeof raw === \"number\" && Number.isFinite(raw);\n\tif (!valid && raw !== undefined && !_bumpCursorWarned.has(seq)) {\n\t\t_bumpCursorWarned.add(seq);\n\t\tconsole.warn(\n\t\t\t`bumpCursor: cursor cache held a non-numeric value (${String(raw)}); resetting to 0. ` +\n\t\t\t\t\"Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, \" +\n\t\t\t\t\"OR a malformed initial seed (e.g. state<number>(NaN)). \" +\n\t\t\t\t\"Audit consumers may see colliding seq values after this point.\",\n\t\t);\n\t}\n\tconst cur = valid ? raw : 0;\n\tconst next = cur + 1;\n\tseq.down([[DIRTY], [DATA, next]]);\n\treturn next;\n}\n\n/**\n * Build a record via the supplied builder, stamp `handlerVersion` if present,\n * and append it to the audit log. `undefined` records are skipped (callers\n * pass an `onSuccess` / `onFailure` that returns `undefined` to opt out per\n * call).\n *\n * @category internal\n */\nexport function appendAudit<\n\tTArgs extends readonly unknown[],\n\tTValue,\n\tR extends BaseAuditRecord,\n\tM extends SuccessMeta | FailureMeta,\n>(\n\taudit: ReactiveLogBundle<R>,\n\tbuilder: (args: TArgs, value: TValue, meta: M) => R | undefined,\n\targs: TArgs,\n\tvalue: TValue,\n\tmeta: M,\n\thandlerVersion?: { id: string; version: string | number },\n): void {\n\tconst record = builder(args, value, meta);\n\tif (record === undefined) return;\n\tconst stamped = handlerVersion != null ? ({ ...record, handlerVersion } as R) : record;\n\taudit.append(stamped);\n}\n\n// ── registerCursor / registerCursorMap ───────────────────────────────────\n\n/**\n * Promote a closure counter to a state node mounted under `graph`.\n * Replaces ad-hoc `let _seq = 0` patterns with a node observable in\n * `describe()` and persistable via storage tiers.\n *\n * @category internal\n */\nexport function registerCursor(graph: Graph, name: string, initial = 0): Node<number> {\n\tconst cursor = node<number>([], { initial, name, describeKind: \"state\" });\n\tgraph.add(cursor, { name });\n\treturn cursor;\n}\n\n/**\n * Promote a closure `Map<K, number>` to N state nodes (one per key) mounted\n * under `<graph>::<name>::<key>`. Used by saga (per-event-type cursor).\n *\n * @category internal\n */\nexport function registerCursorMap<K extends string>(\n\tgraph: Graph,\n\tname: string,\n\tkeys: readonly K[],\n\tinitial = 0,\n): { readonly [P in K]: Node<number> } {\n\tconst out = {} as { [P in K]: Node<number> };\n\t// Mount cursors under a child plain-Graph so per-key node names stay flat\n\t// (path-separator `::` is reserved by Graph.add). Using `Graph` directly\n\t// rather than `graph.constructor` avoids spawning a typed subclass with\n\t// an incompatible constructor signature (e.g., CqrsGraph(name, opts)).\n\tconst sub = new Graph(name);\n\tfor (const k of keys) {\n\t\tconst cursor = node<number>([], {\n\t\t\tinitial,\n\t\t\tname: k,\n\t\t\tdescribeKind: \"state\",\n\t\t});\n\t\tsub.add(cursor, { name: k });\n\t\tout[k] = cursor;\n\t}\n\tgraph.mount(name, sub);\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,IAAAA,eASO;AAEP,IAAAC,gBAAsB;AACtB,IAAAC,gBAAyC;AAQzC,IAAAD,gBAA0B;;;ACRnB,SAAS,WACf,QACA,MACA,OAC0B;AAC1B,SAAO;AAAA,IACN,CAAC,MAAM,GAAG;AAAA,IAC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AAC5B,YAAM,OAAO,UAAU;AAAA,QAAI,CAACD,QAAO,MAClCA,UAAS,QAAQA,OAAM,SAAS,IAAIA,OAAM,GAAG,EAAE,IAAI,IAAI,SAAS,CAAC;AAAA,MAClE;AACA,YAAM,UAAU,KAAK,MAAM,GAAG,CAAC;AAC/B,YAAM,eAAe,KAAK,MAAM,CAAC;AAEjC,YAAM,YAAsB,CAAC;AAC7B,UAAI,aAAa;AAEjB,eAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC3B,cAAM,MAAM,QAAQ,CAAC,KAAK;AAC1B,cAAM,KAAK,aAAa,CAAC,KAAK;AAC9B,cAAM,WAAW,WAAW,CAAC,IAAI,SAAS,CAAC,EAAE,GAAG,IAAI;AACpD,cAAM,WAAY,WAAsB;AACxC,kBAAU,KAAK,QAAQ;AACvB,sBAAc;AAAA,MACf;AAEA,cAAQ,KAAK;AAAA,QACZ,OAAO;AAAA,QACP,OAAO;AAAA,QACP;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA;AAAA,MACC,GAAI,OACD;AAAA,QACA,QAAQ,KAAK;AAAA,QACb,gBAAgB,KAAK;AAAA,QACrB,iBAAiB,KAAK;AAAA,MACvB,IACC,CAAC;AAAA,MACJ,cAAc;AAAA,MACd,MAAM,SAAS,UAAU,MAAM,IAAI;AAAA,IACpC;AAAA,EACD;AACD;","names":["import_core","import_extra","import_graph","batch","i"]}
1
+ {"version":3,"sources":["../../../src/utils/reduction/index.ts","../../../src/base/meta/domain-meta.ts","../../../src/base/mutation/index.ts"],"sourcesContent":["/**\n * Reduction primitives (roadmap §8.1).\n *\n * Composable building blocks for taking heterogeneous massive inputs and producing\n * prioritized, auditable, human-actionable output. Each primitive is either a Graph\n * factory or a Node factory, built on top of core + extra primitives.\n *\n * @module\n */\n\nimport {\n\tbatch,\n\tCOMPLETE,\n\tDATA,\n\tERROR,\n\ttype Message,\n\ttype Node,\n\ttype NodeOptions,\n\tnode,\n} from \"@graphrefly/pure-ts/core\";\n\nimport { merge } from \"@graphrefly/pure-ts/extra\";\nimport { Graph, type GraphOptions } from \"@graphrefly/pure-ts/graph\";\n\n// ---------------------------------------------------------------------------\n// Shared helpers (same pattern as orchestration.ts)\n// ---------------------------------------------------------------------------\n\nexport type { StepRef } from \"../orchestration/pipeline-graph.js\";\n\nimport { keepalive } from \"@graphrefly/pure-ts/extra\";\nimport { domainMeta } from \"../../base/meta/domain-meta.js\";\nimport { tryIncrementBounded } from \"../../base/mutation/index.js\";\nimport type { StepRef } from \"../orchestration/pipeline-graph.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"reduction\", kind, meta);\n}\n\n// stratify moved to `src/extra/stratify.ts` (protocol-level primitive).\n\n// ---------------------------------------------------------------------------\n// funnel\n// ---------------------------------------------------------------------------\n\n/** A named stage for {@link funnel}. */\nexport type FunnelStage = {\n\t/** Stage name (mounted as subgraph). */\n\tname: string;\n\t/** Builder: receives a sub-graph, should add an `\"input\"` and `\"output\"` node. */\n\tbuild: (sub: Graph) => void;\n};\n\n/** Options for {@link funnel}. */\nexport type FunnelOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Multi-source merge with sequential reduction stages.\n *\n * Sources are merged into a single stream. Each stage is a named subgraph\n * (mounted via `graph.mount()`). Stages connect linearly:\n * `merged → stage[0].input → stage[0].output → stage[1].input → ...`\n *\n * @param name - Graph name.\n * @param sources - Input nodes to merge.\n * @param stages - Sequential reduction stages.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"merged\"` and mounted stage subgraphs.\n *\n * @category patterns\n */\nexport function funnel<T>(\n\tname: string,\n\tsources: ReadonlyArray<Node<T>>,\n\tstages: ReadonlyArray<FunnelStage>,\n\topts?: FunnelOptions,\n): Graph {\n\tif (sources.length === 0) throw new RangeError(\"funnel requires at least one source\");\n\tif (stages.length === 0) throw new RangeError(\"funnel requires at least one stage\");\n\n\tconst g = new Graph(name, opts);\n\n\t// Merge all sources\n\tconst merged = sources.length === 1 ? sources[0] : merge(...(sources as unknown as Node<T>[]));\n\tg.add(merged as Node<unknown>, { name: \"merged\" });\n\n\t// Build and mount each stage linearly.\n\t// Stage inputs are standalone state nodes, so we bridge via subscribe\n\t// (connect() requires constructor deps). Bridge effects forward DATA\n\t// from the previous output to the next stage's input.\n\tlet prevOutputPath = \"merged\";\n\tfor (let i = 0; i < stages.length; i++) {\n\t\tconst stage = stages[i];\n\t\tconst sub = new Graph(stage.name);\n\t\tstage.build(sub);\n\n\t\t// Validate that the stage has input and output nodes\n\t\ttry {\n\t\t\tsub.resolve(\"input\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"input\" node`);\n\t\t}\n\t\ttry {\n\t\t\tsub.resolve(\"output\");\n\t\t} catch {\n\t\t\tthrow new Error(`funnel stage \"${stage.name}\" must define an \"output\" node`);\n\t\t}\n\n\t\tg.mount(stage.name, sub);\n\n\t\t// Bridge replacement: effect that forwards DATA from previous output\n\t\t// to the next stage's input. TEARDOWN excluded because stage lifecycle\n\t\t// is managed by the parent graph. Shows up in describe().\n\t\tconst prevNode = g.resolve(prevOutputPath);\n\t\tconst stageInputPath = `${stage.name}::input`;\n\t\tconst stageInput = g.resolve(stageInputPath);\n\t\tconst bridgeName = `__bridge_${prevOutputPath}→${stage.name}_input`;\n\t\tconst br = node(\n\t\t\t[prevNode],\n\t\t\t(batchData, _actions, ctx) => {\n\t\t\t\tconst data = batchData.map((batch, i) =>\n\t\t\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t\t\t);\n\t\t\t\tstageInput.emit(data[0]);\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ describeKind: \"effect\", name: bridgeName },\n\t\t);\n\t\tg.add(br as Node<unknown>, { name: bridgeName });\n\t\tg.addDisposer(keepalive(br));\n\n\t\tprevOutputPath = `${stage.name}::output`;\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// feedback\n// ---------------------------------------------------------------------------\n\n/** Options for {@link feedback}. */\nexport type FeedbackOptions = {\n\t/** Maximum feedback iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n\t/** Optional budget gate node path for cost-bounded iteration. */\n\tbudgetNode?: StepRef;\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Introduce a bounded reactive cycle into an existing graph.\n *\n * When `condition` emits a non-null DATA value, the feedback effect routes it\n * back to the `reentry` state node — creating a cycle. Bounded by\n * `maxIterations` (default 10). The counter node (`__feedback_<condition>`)\n * is the source of truth — reset it to 0 to allow more iterations.\n *\n * To remove the feedback cycle, call `graph.remove(\"__feedback_<condition>\")`.\n *\n * @param graph - Existing graph to augment with a feedback cycle.\n * @param condition - Path to a node whose DATA triggers feedback.\n * @param reentry - Path to a state node that receives the feedback value.\n * @param opts - Iteration bounds and metadata.\n * @returns The same graph (mutated with feedback nodes added).\n *\n * @category patterns\n */\nexport function feedback(\n\tgraph: Graph,\n\tcondition: string,\n\treentry: string,\n\topts?: FeedbackOptions,\n): Graph {\n\tconst maxIter = opts?.maxIterations ?? 10;\n\n\t// Internal counter node — source of truth for iteration bound.\n\t// Reset to 0 to allow more iterations.\n\tconst counterName = `__feedback_${condition}`;\n\tconst counter = node<number>([], {\n\t\t...{\n\t\t\tmeta: baseMeta(\"feedback_counter\", {\n\t\t\t\tmaxIterations: maxIter,\n\t\t\t\tfeedbackFrom: condition,\n\t\t\t\tfeedbackTo: reentry,\n\t\t\t}),\n\t\t},\n\t\tinitial: 0,\n\t});\n\tgraph.add(counter as Node<unknown>, { name: counterName });\n\n\t// Resolve the condition and reentry nodes\n\tconst condNode = graph.resolve(condition);\n\tconst reentryNode = graph.resolve(reentry);\n\n\t// Graph-visible feedback effect: intercepts condition DATA, routes back to\n\t// reentry with iteration counting. Registered in the graph so it shows up\n\t// in describe() and cleans up on graph.destroy().\n\t// Feedback effect: subscribe to condition node for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\tconst feedbackEffectName = `__feedback_effect_${condition}`;\n\tconst feedbackEffect = node(\n\t\t[],\n\t\t(_data, _feedbackActions) => {\n\t\t\tconst unsub = condNode.subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\tconst t = msg[0];\n\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\tconst condValue = msg[1];\n\t\t\t\t\t\tif (condValue == null) return;\n\t\t\t\t\t\tbatch(() => {\n\t\t\t\t\t\t\tif (tryIncrementBounded(counter, maxIter)) {\n\t\t\t\t\t\t\t\treentryNode.emit(condValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (t === COMPLETE || t === ERROR) {\n\t\t\t\t\t\tconst terminal: Message = t === ERROR && msg.length > 1 ? [ERROR, msg[1]] : [t];\n\t\t\t\t\t\tcounter.down([terminal]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn { onDeactivation: () => unsub() };\n\t\t},\n\t\t{\n\t\t\tname: feedbackEffectName,\n\t\t\tdescribeKind: \"effect\",\n\t\t\tmeta: {\n\t\t\t\t...baseMeta(\"feedback_effect\", {\n\t\t\t\t\tfeedbackFrom: condition,\n\t\t\t\t\tfeedbackTo: reentry,\n\t\t\t\t}),\n\t\t\t\t_internal: true,\n\t\t\t},\n\t\t},\n\t);\n\tgraph.add(feedbackEffect as Node<unknown>, { name: feedbackEffectName });\n\tgraph.addDisposer(keepalive(feedbackEffect));\n\n\treturn graph;\n}\n\n// `budgetGate` was promoted to `extra/resilience/budget-gate.ts` per Tier 2.2.\n// Import from `@graphrefly/graphrefly/extra` (or `../../extra/resilience/budget-gate.js`\n// internally) instead. See the resilience family for sibling primitives:\n// `retry`, `circuitBreaker`, `rateLimiter`, `tokenBucket`, `fallback`, `withStatus`.\n\n// ---------------------------------------------------------------------------\n// scorer\n// ---------------------------------------------------------------------------\n\n/** A scored item with full breakdown. */\nexport type ScoredItem<T = unknown> = {\n\t/** Original value. */\n\tvalue: T;\n\t/** Final weighted score. */\n\tscore: number;\n\t/** Per-signal breakdown: signal index → weighted contribution. */\n\tbreakdown: number[];\n};\n\n/** Options for {@link scorer}. */\nexport type ScorerOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n\t/** Custom scoring function per signal. Default: identity (signal value IS the score). */\n\tscoreFns?: ReadonlyArray<(value: unknown) => number>;\n};\n\n/**\n * Reactive multi-signal scoring with live weights.\n *\n * Each source emits items to score. Weights are reactive state nodes that\n * LLM or human can adjust live. Output is sorted scored items with full\n * breakdown.\n *\n * @param sources - Signal nodes (each emits a numeric score dimension).\n * @param weights - Reactive weight nodes (one per source).\n * @param opts - Optional node/meta options.\n * @returns Node emitting scored output.\n *\n * @category patterns\n */\nexport function scorer(\n\tsources: ReadonlyArray<Node<number>>,\n\tweights: ReadonlyArray<Node<number>>,\n\topts?: ScorerOptions,\n): Node<ScoredItem<number[]>> {\n\tif (sources.length === 0) throw new RangeError(\"scorer requires at least one source\");\n\tif (sources.length !== weights.length) {\n\t\tthrow new RangeError(\"scorer requires the same number of sources and weights\");\n\t}\n\n\tconst allDeps = [...(sources as unknown as Node[]), ...(weights as unknown as Node[])];\n\tconst n = sources.length;\n\tconst scoreFns = opts?.scoreFns;\n\n\treturn node<ScoredItem<number[]>>(\n\t\tallDeps,\n\t\t(batchData, actions, ctx) => {\n\t\t\tconst vals = batchData.map((batch, i) =>\n\t\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t\t);\n\t\t\tconst signals = vals.slice(0, n) as number[];\n\t\t\tconst weightValues = vals.slice(n) as number[];\n\n\t\t\tconst breakdown: number[] = [];\n\t\t\tlet totalScore = 0;\n\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tconst sig = signals[i] ?? 0;\n\t\t\t\tconst wt = weightValues[i] ?? 0;\n\t\t\t\tconst rawScore = scoreFns?.[i] ? scoreFns[i](sig) : sig;\n\t\t\t\tconst weighted = (rawScore as number) * wt;\n\t\t\t\tbreakdown.push(weighted);\n\t\t\t\ttotalScore += weighted;\n\t\t\t}\n\n\t\t\tactions.emit({\n\t\t\t\tvalue: signals,\n\t\t\t\tscore: totalScore,\n\t\t\t\tbreakdown,\n\t\t\t});\n\t\t},\n\t\t{\n\t\t\t...(opts\n\t\t\t\t? {\n\t\t\t\t\t\tequals: opts.equals,\n\t\t\t\t\t\tresubscribable: opts.resubscribable,\n\t\t\t\t\t\tresetOnTeardown: opts.resetOnTeardown,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"scorer\", opts?.meta),\n\t\t},\n\t);\n}\n\n// `effectivenessTracker` was deleted per Class B audit Alt E (2026-04-30).\n// The shared substrate now lives in `extra/composition/audited-success-tracker.ts`\n// — re-exported via `@graphrefly/graphrefly-ts/extra` for general use.\n","/**\n * Metadata helpers for pattern-layer nodes (Tier 2.2 promotion from\n * `patterns/_internal/`).\n *\n * Each domain (orchestration, messaging, reduction, ai, cqrs, domain_template,\n * memory, lens, audit, harness) shares the same metadata convention. Promoted\n * to `extra/` so non-patterns code (and downstream consumers building their\n * own domain primitives) can use the same shape.\n *\n * @module\n */\n\n/**\n * Build a domain metadata object for pattern-layer nodes.\n *\n * Each domain follows the same shape: `{ [domain]: true, [domain]_type: kind, ...extra }`.\n *\n * @param domain - The domain tag (e.g. `\"orchestration\"`, `\"ai\"`, `\"cqrs\"`).\n * @param kind - The specific type within the domain (e.g. `\"gate\"`, `\"prompt\"`).\n * @param extra - Additional metadata to merge.\n * @returns Metadata object.\n */\nexport function domainMeta(\n\tdomain: string,\n\tkind: string,\n\textra?: Record<string, unknown>,\n): Record<string, unknown> {\n\treturn {\n\t\t[domain]: true,\n\t\t[`${domain}_type`]: kind,\n\t\t...(extra ?? {}),\n\t};\n}\n","/**\n * Universal mutation framework (Phase 14 — DS-14 locked 2026-05-05).\n *\n * Single `mutate(act, opts)` factory replaces the prior `lightMutation` +\n * `wrapMutation` two-tier split (pre-1.0 break per Q-O2).\n *\n * Two frames:\n * - `\"inline\"` — no batch; up() runs raw. Seq bumps before action; persists\n * on throw. Hot-path-friendly for atomic single-write mutations.\n * - `\"transactional\"` — opens `batch(() => up(...))`. On throw: batch discards\n * deferred deliveries, then `down()` runs (if provided), then failure record.\n *\n * Phase-4 primitives share the same shape: imperative mutation methods +\n * closure state + reactive audit log + freeze-at-entry + rollback-on-throw.\n * This module factors out the common machinery so each primitive becomes\n * declarative wiring over typed audit records.\n */\n\nimport {\n\tbatch,\n\tDATA,\n\tDIRTY,\n\ttype Node,\n\ttype NodeGuard,\n\tnode,\n\tpolicy,\n\twallClockNs,\n} from \"@graphrefly/pure-ts/core\";\nimport {\n\ttype ReactiveLogBundle,\n\ttype ReactiveLogOptions,\n\treactiveLog,\n} from \"@graphrefly/pure-ts/extra\";\nimport { Graph } from \"@graphrefly/pure-ts/graph\";\n\n// ── tryIncrementBounded ──────────────────────────────────────────────────\n\n/**\n * Bounded increment for a self-owned counter state node.\n *\n * Reads `counter.cache`, bumps by `by` (default 1) if `cur + by <= cap`,\n * writes back. Returns `false` when the cap would be exceeded (no-op write).\n * Documented P3 exception: the counter is not a declared dep of the caller —\n * it's a private budget read+written from a single call site. This helper\n * keeps the `.cache` access in one named place so caller bodies (which may\n * be inside reactive fn execution paths) stay free of cross-node `.cache`\n * reads.\n *\n * **Safety today:**\n * 1. Single-threaded JS runner never invokes the caller concurrently.\n * 2. `counter.down` writes the cache synchronously before returning, so\n * synchronous re-entry through a downstream publish reads the\n * freshly-incremented value — no double-count.\n *\n * **Future risk:** under a free-threaded runner (PY no-GIL or hypothetical\n * concurrent TS runner), two concurrent firings could still race. Revisit\n * when that surfaces.\n *\n * @param counter - Self-owned counter Node. Caller is the sole writer.\n * @param cap - Upper bound (inclusive). Pass `Number.MAX_SAFE_INTEGER` for\n * \"effectively unbounded\" use cases (e.g. token meters).\n * @param by - Delta to add (default `1`). Must be a finite non-negative\n * number; callers should pre-validate. Overflow-safe via\n * `by > cap - cur` check rather than `cur + by >= cap`.\n */\nexport function tryIncrementBounded(counter: Node<number>, cap: number, by = 1): boolean {\n\tconst cur = (counter.cache as number | undefined) ?? 0;\n\tif (by > cap - cur) return false;\n\tcounter.down([[DIRTY], [DATA, cur + by]]);\n\treturn true;\n}\n\n// ── Audit record schema ──────────────────────────────────────────────────\n\n/** Shared base shape for every audit record. Per-primitive types extend this. */\nexport interface BaseAuditRecord {\n\treadonly t_ns: number;\n\treadonly seq?: number;\n\treadonly handlerVersion?: { id: string; version: string | number };\n}\n\n// ── Default audit guard ──────────────────────────────────────────────────\n\n/**\n * Allow `observe` and `signal`; deny external `write` on the audit log so\n * consumers can subscribe + signal-bridge but cannot inject fake records.\n */\nexport const DEFAULT_AUDIT_GUARD: NodeGuard = policy((allow, deny) => {\n\tallow(\"observe\");\n\tallow(\"signal\");\n\tdeny(\"write\");\n});\n\n// ── createAuditLog ───────────────────────────────────────────────────────\n\nexport type AuditLogOpts<R extends BaseAuditRecord> = {\n\tname: string;\n\t/** Bounded retention; default 1024 per Audit 2 / cross-cutting bounded-default policy. */\n\tretainedLimit?: number;\n\t/** Override the default audit guard. */\n\tguard?: NodeGuard;\n\t/** Mount the audit `entries` Node under this graph (and activate withLatest). */\n\tgraph?: Graph;\n\t/** Pass-through to {@link reactiveLog}. */\n\tversioning?: ReactiveLogOptions<R>[\"versioning\"];\n};\n\n/**\n * Build a reactive audit log with sane defaults: bounded retention, deny-write\n * guard, `withLatest()` companions activated. Returns the {@link ReactiveLogBundle}\n * directly — primitives expose this as `<primitive>.events` / `.decisions` /\n * `.dispatches` / `.invocations` and alias it as `.audit`.\n *\n * @category internal\n */\nexport function createAuditLog<R extends BaseAuditRecord>(\n\topts: AuditLogOpts<R>,\n): ReactiveLogBundle<R> {\n\tconst log = reactiveLog<R>([], {\n\t\tname: opts.name,\n\t\tmaxSize: opts.retainedLimit ?? 1024,\n\t\tguard: opts.guard ?? DEFAULT_AUDIT_GUARD,\n\t\t...(opts.versioning != null ? { versioning: opts.versioning } : {}),\n\t});\n\t// Lazy companion activation up-front so `bundle.lastValue` / `hasLatest`\n\t// are queryable without an explicit `withLatest()` call.\n\tlog.withLatest();\n\tif (opts.graph) {\n\t\topts.graph.add(log.entries, { name: opts.name });\n\t}\n\treturn log;\n}\n\n/**\n * Read-only projection of a {@link ReactiveLogBundle}. Exposes only the\n * observation surface (`entries` / `size` / `at` / `withLatest` / `lastValue`\n * / `view` / `scan` / `mutationLog`) — the mutators (`append` / `appendMany`\n * / `clear` / `trimHead` / `attach` / `attachStorage`) and the lifecycle\n * disposers are intentionally absent.\n */\nexport type ReadonlyAuditLog<R> = Pick<\n\tReactiveLogBundle<R>,\n\t\"entries\" | \"size\" | \"at\" | \"withLatest\" | \"lastValue\" | \"view\" | \"scan\" | \"mutationLog\"\n>;\n\n/**\n * Wrap an audit log so the `.audit` alias a primitive exposes (the Audit-2\n * `.audit` duplication convention — `saga.audit` / `cqrs.audit` /\n * `jobQueue.audit` / `processManager.audit`) is a **stable read-only view**,\n * not the live mutable bundle. Closes M7: a consumer calling\n * `someGraph.audit.append(...)` would otherwise silently mutate the owning\n * primitive's canonical log. The returned object is frozen and shares the\n * underlying log's nodes (zero copy) — reads are byte-identical to the live\n * bundle; mutators are simply not present (compile-time) and the object is\n * frozen (run-time defense for JS callers).\n *\n * @category internal\n */\nexport function readonlyAuditLog<R>(log: ReactiveLogBundle<R>): ReadonlyAuditLog<R> {\n\treturn Object.freeze({\n\t\tget entries() {\n\t\t\treturn log.entries;\n\t\t},\n\t\tget size() {\n\t\t\treturn log.size;\n\t\t},\n\t\tget lastValue() {\n\t\t\treturn log.lastValue;\n\t\t},\n\t\tget mutationLog() {\n\t\t\treturn log.mutationLog;\n\t\t},\n\t\tat: log.at.bind(log),\n\t\twithLatest: log.withLatest.bind(log),\n\t\tview: log.view.bind(log),\n\t\tscan: log.scan.bind(log),\n\t}) satisfies ReadonlyAuditLog<R>;\n}\n\n// ── Universal mutation factory (Phase 14 — DS-14 lock Q-O2/Q-O3) ────────\n//\n// Single `mutate(act, opts)` factory. Two frames:\n//\n// - `\"inline\"` — no batch frame; up() runs raw. Seq bumps before action;\n// persists on throw. Hot-path-friendly for atomic single-write mutations.\n//\n// - `\"transactional\"` — opens `batch(() => up(...))`. On throw: batch discards\n// deferred deliveries, then `down()` runs, then failure record persists.\n//\n// **Heuristic:** if your imperative method's body is one or two lines (mutate\n// state, emit), use `frame: \"inline\"`. If it runs a user-supplied handler or\n// has multiple steps that could leave inconsistent state mid-throw, use\n// `frame: \"transactional\"`.\n\nexport type FailureMeta = {\n\tt_ns: number;\n\tseq?: number;\n\terrorType: string;\n};\n\nexport type SuccessMeta = {\n\tt_ns: number;\n\tseq?: number;\n};\n\n/**\n * Mutation action shape. Plain function shorthand auto-wraps as `{ up: fn }`.\n *\n * - `up` — the mutation action (the \"up migration\").\n * - `down` — optional rollback for closure mutations that `batch()` can't\n * reach. Receives the SAME frozen args as `up`. Runs AFTER batch reactive\n * rollback, BEFORE the failure record. Throws inside `down` are\n * console.error'd without masking the original error. Only meaningful\n * with `frame: \"transactional\"`.\n */\nexport type MutationAct<TArgs extends readonly unknown[], TResult> = {\n\tup: (...args: TArgs) => TResult;\n\tdown?: (...args: TArgs) => void;\n};\n\nexport type MutationFrame = \"inline\" | \"transactional\";\n\nexport type MutateOpts<TArgs extends readonly unknown[], TResult, R extends BaseAuditRecord> = {\n\t/** Frame mode. `\"inline\"` = no batch; `\"transactional\"` = batch + rollback. */\n\tframe: MutationFrame;\n\t/**\n\t * Optional log to append records to. When omitted, the wrapper still\n\t * provides freeze / seq-advance / rollback-on-throw but skips record\n\t * emission — useful for primitives that want centralized mutation\n\t * semantics without a dedicated log surface (e.g. `Topic.publish`).\n\t */\n\tlog?: ReactiveLogBundle<R>;\n\t/** Build the success record from the action's args + result + meta. */\n\tonSuccessRecord?: (args: TArgs, result: TResult, meta: SuccessMeta) => R | undefined;\n\t/** Build the failure record from the args + error + meta. */\n\tonFailureRecord?: (args: TArgs, error: unknown, meta: FailureMeta) => R | undefined;\n\t/** Deep-freeze args at entry (default `true`). Opt out for hot paths. */\n\tfreeze?: boolean;\n\t/** Optional sequence cursor — auto-advanced and stamped onto records. */\n\tseq?: Node<number>;\n\t/** Optional handler version — stamped per Audit 5. */\n\thandlerVersion?: { id: string; version: string | number };\n};\n\nfunction deepFreeze<T>(value: T): T {\n\tif (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tfor (const k of Object.keys(value as Record<string, unknown>)) {\n\t\tdeepFreeze((value as Record<string, unknown>)[k]);\n\t}\n\treturn Object.freeze(value);\n}\n\n/**\n * Universal mutation factory (Phase 14 — DS-14 Q-O2).\n *\n * Replaces the prior `lightMutation` + `wrapMutation` two-tier split.\n * Single factory with `frame: \"inline\" | \"transactional\"` discriminant.\n *\n * @param act - The mutation action. Either a plain function (auto-wrapped as\n * `{ up: fn }`) or a `{ up, down? }` object for explicit rollback.\n * @param opts - Configuration: frame, log, record builders, freeze, seq.\n * @returns A typed wrapper function with the same signature as `act.up`.\n */\nexport function mutate<TArgs extends readonly unknown[], TResult, R extends BaseAuditRecord>(\n\tact: MutationAct<TArgs, TResult> | ((...args: TArgs) => TResult),\n\topts: MutateOpts<TArgs, TResult, R>,\n): (...args: TArgs) => TResult {\n\tconst { up, down } = typeof act === \"function\" ? { up: act, down: undefined } : act;\n\tconst freeze = opts.freeze ?? true;\n\n\tif (opts.frame === \"inline\") {\n\t\treturn function wrapped(...args: TArgs): TResult {\n\t\t\tconst sealed = freeze ? (args.map(deepFreeze) as unknown as TArgs) : args;\n\t\t\tconst t_ns = wallClockNs();\n\t\t\tconst seq = opts.seq ? bumpCursor(opts.seq) : undefined;\n\t\t\ttry {\n\t\t\t\tconst result = up(...sealed);\n\t\t\t\tif (opts.log && opts.onSuccessRecord) {\n\t\t\t\t\tappendAudit<TArgs, TResult, R, SuccessMeta>(\n\t\t\t\t\t\topts.log,\n\t\t\t\t\t\topts.onSuccessRecord,\n\t\t\t\t\t\tsealed,\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\t{ t_ns, seq },\n\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t} catch (err) {\n\t\t\t\tif (opts.log && opts.onFailureRecord) {\n\t\t\t\t\tconst errorType = err instanceof Error ? err.name : typeof err;\n\t\t\t\t\tappendAudit<TArgs, unknown, R, FailureMeta>(\n\t\t\t\t\t\topts.log,\n\t\t\t\t\t\topts.onFailureRecord,\n\t\t\t\t\t\tsealed,\n\t\t\t\t\t\terr,\n\t\t\t\t\t\t{ t_ns, seq, errorType },\n\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t}\n\n\t// frame === \"transactional\"\n\treturn function wrapped(...args: TArgs): TResult {\n\t\tconst sealed = freeze ? (args.map(deepFreeze) as unknown as TArgs) : args;\n\t\tconst t_ns = wallClockNs();\n\t\tlet result: TResult;\n\t\tlet captured: unknown;\n\t\tlet captureSet = false;\n\t\tlet seq: number | undefined;\n\t\ttry {\n\t\t\tbatch(() => {\n\t\t\t\tif (opts.seq) seq = bumpCursor(opts.seq);\n\t\t\t\ttry {\n\t\t\t\t\tresult = up(...sealed);\n\t\t\t\t\tif (opts.log && opts.onSuccessRecord) {\n\t\t\t\t\t\tappendAudit<TArgs, TResult, R, SuccessMeta>(\n\t\t\t\t\t\t\topts.log,\n\t\t\t\t\t\t\topts.onSuccessRecord,\n\t\t\t\t\t\t\tsealed,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t{ t_ns, seq },\n\t\t\t\t\t\t\topts.handlerVersion,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tcaptured = err;\n\t\t\t\t\tcaptureSet = true;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (outerErr) {\n\t\t\t// Fire `down` AFTER batch's reactive rollback, BEFORE failure record.\n\t\t\t// Gate on `captureSet` — if the throw came from outside the inner try\n\t\t\t// (framework-level batch error before action ran), don't fire down.\n\t\t\tif (captureSet && down) {\n\t\t\t\ttry {\n\t\t\t\t\tdown(...sealed);\n\t\t\t\t} catch (downErr) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`mutate: down hook threw — original action error preserved (${\n\t\t\t\t\t\t\tcaptured instanceof Error ? captured.name : typeof captured\n\t\t\t\t\t\t}). Down error:`,\n\t\t\t\t\t\tdownErr,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (captureSet && opts.log && opts.onFailureRecord) {\n\t\t\t\tconst errorType = captured instanceof Error ? captured.name : typeof captured;\n\t\t\t\tappendAudit<TArgs, unknown, R, FailureMeta>(\n\t\t\t\t\topts.log,\n\t\t\t\t\topts.onFailureRecord,\n\t\t\t\t\tsealed,\n\t\t\t\t\tcaptured,\n\t\t\t\t\t{ t_ns, seq, errorType },\n\t\t\t\t\topts.handlerVersion,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow captureSet ? captured : outerErr;\n\t\t}\n\t\treturn result!;\n\t};\n}\n\n/**\n * Advance a cursor node and return the new value. Emits `[DIRTY], [DATA, next]`\n * directly on the cursor — atomic outside a batch, rollback-discardable inside.\n *\n * Resets to `0` if the cursor cache is missing, non-numeric, `NaN`, or\n * non-finite (e.g. corrupted by `restore()` from a malformed snapshot, or\n * by a misbehaving codec). `??` alone would let `NaN` and `\"\"` pass through\n * and silently corrupt audit ordering downstream.\n *\n * **Silent reset diagnostic (EH-12).** When the cache holds a non-numeric\n * value at bump time, the cursor restarts at 0 and the next bump returns 1\n * — colliding with the seq stamped on the very first record after construct.\n * To make seq-monotonicity violations after a restore visible to operators,\n * the helper emits a one-shot `console.warn` per cursor instance describing\n * the offending value. The cursor is identified by a `WeakSet<Node<number>>`\n * so the warning fires exactly once per node — repeat malformed bumps stay\n * quiet to avoid log spam. Production callers wanting to suppress can swap\n * the global `console` (universal-safe code path; no Node-only API used).\n *\n * Works whether or not the cursor has any subscribers — `down` updates the\n * cache regardless, so primitives that bump before consumers attach (e.g.\n * `JobQueueGraph.enqueue`) still see a coherent sequence.\n *\n * @category internal\n */\nconst _bumpCursorWarned = new WeakSet<Node<number>>();\nexport function bumpCursor(seq: Node<number>): number {\n\tconst raw = seq.cache;\n\tconst valid = typeof raw === \"number\" && Number.isFinite(raw);\n\tif (!valid && raw !== undefined && !_bumpCursorWarned.has(seq)) {\n\t\t_bumpCursorWarned.add(seq);\n\t\tconsole.warn(\n\t\t\t`bumpCursor: cursor cache held a non-numeric value (${String(raw)}); resetting to 0. ` +\n\t\t\t\t\"Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, \" +\n\t\t\t\t\"OR a malformed initial seed (e.g. state<number>(NaN)). \" +\n\t\t\t\t\"Audit consumers may see colliding seq values after this point.\",\n\t\t);\n\t}\n\tconst cur = valid ? raw : 0;\n\tconst next = cur + 1;\n\tseq.down([[DIRTY], [DATA, next]]);\n\treturn next;\n}\n\n/**\n * Build a record via the supplied builder, stamp `handlerVersion` if present,\n * and append it to the audit log. `undefined` records are skipped (callers\n * pass an `onSuccess` / `onFailure` that returns `undefined` to opt out per\n * call).\n *\n * @category internal\n */\nexport function appendAudit<\n\tTArgs extends readonly unknown[],\n\tTValue,\n\tR extends BaseAuditRecord,\n\tM extends SuccessMeta | FailureMeta,\n>(\n\taudit: ReactiveLogBundle<R>,\n\tbuilder: (args: TArgs, value: TValue, meta: M) => R | undefined,\n\targs: TArgs,\n\tvalue: TValue,\n\tmeta: M,\n\thandlerVersion?: { id: string; version: string | number },\n): void {\n\tconst record = builder(args, value, meta);\n\tif (record === undefined) return;\n\tconst stamped = handlerVersion != null ? ({ ...record, handlerVersion } as R) : record;\n\taudit.append(stamped);\n}\n\n// ── registerCursor / registerCursorMap ───────────────────────────────────\n\n/**\n * Promote a closure counter to a state node mounted under `graph`.\n * Replaces ad-hoc `let _seq = 0` patterns with a node observable in\n * `describe()` and persistable via storage tiers.\n *\n * @category internal\n */\nexport function registerCursor(graph: Graph, name: string, initial = 0): Node<number> {\n\tconst cursor = node<number>([], { initial, name, describeKind: \"state\" });\n\tgraph.add(cursor, { name });\n\treturn cursor;\n}\n\n/**\n * Promote a closure `Map<K, number>` to N state nodes (one per key) mounted\n * under `<graph>::<name>::<key>`. Used by saga (per-event-type cursor).\n *\n * @category internal\n */\nexport function registerCursorMap<K extends string>(\n\tgraph: Graph,\n\tname: string,\n\tkeys: readonly K[],\n\tinitial = 0,\n): { readonly [P in K]: Node<number> } {\n\tconst out = {} as { [P in K]: Node<number> };\n\t// Mount cursors under a child plain-Graph so per-key node names stay flat\n\t// (path-separator `::` is reserved by Graph.add). Using `Graph` directly\n\t// rather than `graph.constructor` avoids spawning a typed subclass with\n\t// an incompatible constructor signature (e.g., CqrsGraph(name, opts)).\n\tconst sub = new Graph(name);\n\tfor (const k of keys) {\n\t\tconst cursor = node<number>([], {\n\t\t\tinitial,\n\t\t\tname: k,\n\t\t\tdescribeKind: \"state\",\n\t\t});\n\t\tsub.add(cursor, { name: k });\n\t\tout[k] = cursor;\n\t}\n\tgraph.mount(name, sub);\n\treturn out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,IAAAA,eASO;AAEP,IAAAC,gBAAsB;AACtB,IAAAC,gBAAyC;AAQzC,IAAAD,gBAA0B;;;ACRnB,SAAS,WACf,QACA,MACA,OAC0B;AAC1B,SAAO;AAAA,IACN,CAAC,MAAM,GAAG;AAAA,IACV,CAAC,GAAG,MAAM,OAAO,GAAG;AAAA,IACpB,GAAI,SAAS,CAAC;AAAA,EACf;AACD;;;ACdA,kBASO;AACP,mBAIO;AACP,mBAAsB;AAgCf,SAAS,oBAAoB,SAAuB,KAAa,KAAK,GAAY;AACxF,Q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GAAG,CAAC;AAC/B,YAAM,eAAe,KAAK,MAAM,CAAC;AAEjC,YAAM,YAAsB,CAAC;AAC7B,UAAI,aAAa;AAEjB,eAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC3B,cAAM,MAAM,QAAQ,CAAC,KAAK;AAC1B,cAAM,KAAK,aAAa,CAAC,KAAK;AAC9B,cAAM,WAAW,WAAW,CAAC,IAAI,SAAS,CAAC,EAAE,GAAG,IAAI;AACpD,cAAM,WAAY,WAAsB;AACxC,kBAAU,KAAK,QAAQ;AACvB,sBAAc;AAAA,MACf;AAEA,cAAQ,KAAK;AAAA,QACZ,OAAO;AAAA,QACP,OAAO;AAAA,QACP;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IACA;AAAA,MACC,GAAI,OACD;AAAA,QACA,QAAQ,KAAK;AAAA,QACb,gBAAgB,KAAK;AAAA,QACrB,iBAAiB,KAAK;AAAA,MACvB,IACC,CAAC;AAAA,MACJ,cAAc;AAAA,MACd,MAAM,SAAS,UAAU,MAAM,IAAI;AAAA,IACpC;AAAA,EACD;AACD;","names":["import_core","import_extra","import_graph","batch","i"]}
@@ -2,9 +2,9 @@ import {
2
2
  feedback,
3
3
  funnel,
4
4
  scorer
5
- } from "../../chunk-QFE5BQH7.js";
5
+ } from "../../chunk-LTSI7ULC.js";
6
6
  import "../../chunk-FMPF42Q4.js";
7
- import "../../chunk-BXGZFGZ4.js";
7
+ import "../../chunk-C5QD5DQX.js";
8
8
  import "../../chunk-AZDQPQ3V.js";
9
9
  export {
10
10
  feedback,