@graphrefly/graphrefly 0.27.0 → 0.29.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.
- package/dist/backoff-HPZMEZNF.js +1 -0
- package/dist/cascading-Bp99ckMJ.d.ts +180 -0
- package/dist/cascading-CcAgRacD.d.cts +180 -0
- package/dist/chunk-22F4K3G7.js +1 -0
- package/dist/chunk-22SVXUPB.js +64 -0
- package/dist/chunk-2GQREQ6C.js +1 -0
- package/dist/chunk-3JXNEPCD.js +2 -0
- package/dist/chunk-4JJCCD5S.js +2 -0
- package/dist/chunk-4OFIQ66T.js +1 -0
- package/dist/chunk-4V4C7K56.js +1 -0
- package/dist/chunk-4VVTGLXJ.js +1 -0
- package/dist/chunk-567NWZ3T.js +1 -0
- package/dist/chunk-5JDE5JHE.js +1 -0
- package/dist/chunk-5QDBSZBV.js +1 -0
- package/dist/chunk-5Z4HDCO6.js +1 -0
- package/dist/chunk-63FFOHLA.js +1 -0
- package/dist/chunk-6QZNQS5B.js +1 -0
- package/dist/chunk-7JDLFI6N.js +1 -0
- package/dist/chunk-7TDOES3L.js +1 -0
- package/dist/chunk-A7IAQQ63.js +1 -0
- package/dist/chunk-AMG5VBHW.js +1 -0
- package/dist/chunk-AUY2YKCO.js +1 -0
- package/dist/chunk-AV3PIDFQ.js +1 -0
- package/dist/chunk-BA5URFYW.js +1 -0
- package/dist/chunk-BKPLTBL5.js +1 -0
- package/dist/chunk-BZP5T4X6.js +1 -0
- package/dist/chunk-CK2E7BTU.js +1 -0
- package/dist/chunk-CSJE2EKV.js +1 -0
- package/dist/chunk-E3AXATVZ.js +9 -0
- package/dist/chunk-ESMPEKEV.js +1 -0
- package/dist/chunk-GJR3P6JG.js +1 -0
- package/dist/chunk-GNCBXARM.js +1 -0
- package/dist/chunk-GPW2V3RE.js +1 -0
- package/dist/chunk-HSIEYSDY.js +1 -0
- package/dist/chunk-I6VIH3VA.js +1 -0
- package/dist/chunk-ISCENNXS.js +1 -0
- package/dist/chunk-JYOUF6UQ.js +1 -0
- package/dist/chunk-KASHOCF5.js +1 -0
- package/dist/chunk-LGSNR4LU.js +5 -0
- package/dist/chunk-LVGBLZM2.js +1 -0
- package/dist/chunk-MGKAO4EK.js +7 -0
- package/dist/chunk-NSG4C6BF.js +23 -0
- package/dist/chunk-OL33ZI6R.js +1 -0
- package/dist/chunk-PCZ35NXD.js +78 -0
- package/dist/chunk-PGMUCUHG.js +43 -0
- package/dist/chunk-QYADASLV.js +1 -0
- package/dist/chunk-RD52SNH2.js +1 -0
- package/dist/chunk-SLMYTGTU.js +1 -0
- package/dist/chunk-TWMEGG45.js +1 -0
- package/dist/chunk-UVJQ35G2.js +1 -0
- package/dist/chunk-VGTCGNRX.js +18 -0
- package/dist/chunk-VIMF6LGM.js +1 -0
- package/dist/chunk-VJLMUKOI.js +1 -0
- package/dist/chunk-VWPRPPKR.js +1 -0
- package/dist/chunk-W4TSQ6RJ.js +1 -0
- package/dist/chunk-WM7H7WTY.js +3 -0
- package/dist/chunk-Y32RJO24.js +1 -0
- package/dist/chunk-Y53B6NS4.js +1 -0
- package/dist/compat/index.cjs +15 -7656
- package/dist/compat/index.d.cts +15 -14
- package/dist/compat/index.d.ts +15 -14
- package/dist/compat/index.js +1 -50
- package/dist/compat/jotai/index.cjs +1 -2048
- package/dist/compat/jotai/index.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/jotai/index.js +1 -9
- package/dist/compat/nanostores/index.cjs +1 -2175
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nanostores/index.js +1 -23
- package/dist/compat/nestjs/index.cjs +15 -6782
- package/dist/compat/nestjs/index.d.cts +7 -6
- package/dist/compat/nestjs/index.d.ts +7 -6
- package/dist/compat/nestjs/index.js +1 -83
- package/dist/compat/react/index.cjs +1 -141
- package/dist/compat/react/index.d.cts +2 -2
- package/dist/compat/react/index.d.ts +2 -2
- package/dist/compat/react/index.js +1 -12
- package/dist/compat/solid/index.cjs +1 -128
- package/dist/compat/solid/index.d.cts +2 -2
- package/dist/compat/solid/index.d.ts +2 -2
- package/dist/compat/solid/index.js +1 -12
- package/dist/compat/svelte/index.cjs +1 -131
- package/dist/compat/svelte/index.d.cts +2 -2
- package/dist/compat/svelte/index.d.ts +2 -2
- package/dist/compat/svelte/index.js +1 -12
- package/dist/compat/vue/index.cjs +1 -146
- package/dist/compat/vue/index.d.cts +2 -2
- package/dist/compat/vue/index.d.ts +2 -2
- package/dist/compat/vue/index.js +1 -12
- package/dist/compat/zustand/index.cjs +7 -4931
- package/dist/compat/zustand/index.d.cts +5 -5
- package/dist/compat/zustand/index.d.ts +5 -5
- package/dist/compat/zustand/index.js +1 -12
- package/dist/composite-BL-llbnE.d.ts +69 -0
- package/dist/composite-Dze--DaA.d.cts +69 -0
- package/dist/core/index.cjs +1 -2271
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +1 -110
- package/dist/extra/browser.cjs +1 -0
- package/dist/extra/browser.d.cts +3 -0
- package/dist/extra/browser.d.ts +3 -0
- package/dist/extra/browser.js +1 -0
- package/dist/extra/index.cjs +24 -9971
- package/dist/extra/index.d.cts +13 -6
- package/dist/extra/index.d.ts +13 -6
- package/dist/extra/index.js +1 -381
- package/dist/extra/node.cjs +3 -0
- package/dist/extra/node.d.cts +81 -0
- package/dist/extra/node.d.ts +81 -0
- package/dist/extra/node.js +2 -0
- package/dist/extra/operators.cjs +1 -0
- package/dist/extra/operators.d.cts +910 -0
- package/dist/extra/operators.d.ts +910 -0
- package/dist/extra/operators.js +1 -0
- package/dist/extra/reactive.cjs +1 -0
- package/dist/extra/reactive.d.cts +352 -0
- package/dist/extra/reactive.d.ts +352 -0
- package/dist/extra/reactive.js +1 -0
- package/dist/extra/sources.cjs +1 -2486
- package/dist/extra/sources.d.cts +6 -2
- package/dist/extra/sources.d.ts +6 -2
- package/dist/extra/sources.js +1 -57
- package/dist/extra/storage-browser.cjs +1 -0
- package/dist/extra/storage-browser.d.cts +71 -0
- package/dist/extra/storage-browser.d.ts +71 -0
- package/dist/extra/storage-browser.js +1 -0
- package/dist/extra/storage-core.cjs +1 -0
- package/dist/extra/storage-core.d.cts +98 -0
- package/dist/extra/storage-core.d.ts +98 -0
- package/dist/extra/storage-core.js +1 -0
- package/dist/extra/storage-node.cjs +2 -0
- package/dist/extra/storage-node.d.cts +60 -0
- package/dist/extra/storage-node.d.ts +60 -0
- package/dist/extra/storage-node.js +1 -0
- package/dist/fallback-BaTS7vVY.d.cts +258 -0
- package/dist/fallback-eOm3LNxP.d.ts +258 -0
- package/dist/graph/index.cjs +7 -5030
- package/dist/graph/index.d.cts +6 -5
- package/dist/graph/index.d.ts +6 -5
- package/dist/graph/index.js +1 -50
- package/dist/{graph-DNCrvZSn.d.cts → graph-DgohqXK-.d.cts} +151 -32
- package/dist/{graph-CCwGKLCm.d.ts → graph-Qjg9gWHI.d.ts} +151 -32
- package/dist/{index-BwfLUNw4.d.ts → index-2BVuRCI4.d.ts} +173 -2040
- package/dist/{index-BPVt8kqc.d.ts → index-2NvguqQA.d.ts} +10 -195
- package/dist/index-A65LZhoM.d.ts +186 -0
- package/dist/{index-DlLp-2Xn.d.cts → index-B-8FCEua.d.cts} +10 -195
- package/dist/index-B-gqvYel.d.ts +135 -0
- package/dist/index-B2PRuolf.d.cts +86 -0
- package/dist/index-BJqt9EwW.d.ts +231 -0
- package/dist/{index-BHlKbUwO.d.cts → index-BKjT5DiZ.d.cts} +173 -2040
- package/dist/{index-C0svESO4.d.ts → index-BM8BU4q6.d.ts} +1 -1
- package/dist/{index-VdHQMPy1.d.ts → index-BQaEnxBf.d.ts} +1 -1
- package/dist/index-BSfwiy5B.d.ts +192 -0
- package/dist/index-BTSkeCZs.d.cts +291 -0
- package/dist/index-BUVtw1Ay.d.cts +186 -0
- package/dist/index-BUi57v_p.d.ts +163 -0
- package/dist/{messaging-Gt4LPbyA.d.cts → index-BanNUILp.d.cts} +31 -93
- package/dist/{audit-DRlSzBu9.d.ts → index-BayHDRx6.d.cts} +27 -21
- package/dist/{index-B6D3QNSA.d.ts → index-BiyjsZ0m.d.ts} +148 -20
- package/dist/index-BqZ6vB2A.d.ts +2057 -0
- package/dist/{memory-li6FL5RM.d.ts → index-BuVidq3D.d.cts} +26 -26
- package/dist/index-Byh-xTyp.d.ts +105 -0
- package/dist/index-C08QPDcV.d.cts +321 -0
- package/dist/{demo-shell-BDkOptd6.d.ts → index-C66RJiX8.d.ts} +14 -14
- package/dist/index-C8RfjffH.d.ts +291 -0
- package/dist/index-CA1Cu7Ud.d.ts +873 -0
- package/dist/{index-ByQxazQJ.d.cts → index-CABbltIu.d.cts} +1 -1
- package/dist/{index-VHqptjhu.d.cts → index-CHEBsnYv.d.cts} +1 -1
- package/dist/{index-BuEoe-Qu.d.ts → index-CI0yDnLp.d.ts} +9 -9
- package/dist/{index-B9B7_HEY.d.ts → index-CJ45TW-h.d.ts} +1 -1
- package/dist/{index-CO8uBlUh.d.cts → index-CJZKZoo4.d.cts} +148 -20
- package/dist/{index-wEn0eFe8.d.ts → index-CX2tFJL1.d.ts} +1 -1
- package/dist/{index-BaSM3aYt.d.ts → index-CcWOJ6F0.d.ts} +3 -3
- package/dist/{audit-ClmqGOCx.d.cts → index-CiaVoZGo.d.ts} +27 -21
- package/dist/{index-Dzk2hrlR.d.ts → index-Ct5CWc4E.d.ts} +1 -1
- package/dist/index-D38duMCv.d.cts +357 -0
- package/dist/{index-C8oil6M6.d.ts → index-D5XJ2tSx.d.ts} +30 -6
- package/dist/{index-DO_6JN9Z.d.cts → index-D80do5jX.d.cts} +1 -1
- package/dist/index-D9HKAH_-.d.cts +231 -0
- package/dist/index-DBe_8XW5.d.cts +143 -0
- package/dist/{memory-C6Z2tGpC.d.cts → index-DCeTyFlB.d.ts} +26 -26
- package/dist/index-DDy8eeXS.d.ts +321 -0
- package/dist/index-DJ5oNBc8.d.ts +143 -0
- package/dist/{index-CI3DprxP.d.cts → index-DP0_O3ls.d.cts} +30 -6
- package/dist/{demo-shell-Crid1WdR.d.cts → index-DX8xS-yB.d.cts} +14 -14
- package/dist/index-DiZejfCI.d.cts +2057 -0
- package/dist/index-DknyJ2Fu.d.cts +163 -0
- package/dist/index-DoWMs-Kk.d.cts +135 -0
- package/dist/{messaging-XDoYablx.d.ts → index-DuB5aO4-.d.ts} +31 -93
- package/dist/index-DwjJGKxV.d.ts +357 -0
- package/dist/{index-B6EhDnjH.d.cts → index-H_oxVec5.d.cts} +1 -1
- package/dist/{index-3lsddbbS.d.ts → index-IMAHq-ia.d.ts} +1 -1
- package/dist/{index-B1tloyhO.d.cts → index-U1nir7MX.d.cts} +1 -1
- package/dist/index-Vg7tORgk.d.ts +86 -0
- package/dist/index-dig-r2tQ.d.cts +873 -0
- package/dist/{index-CxFrXH4m.d.ts → index-gsT79Xu9.d.ts} +1 -1
- package/dist/{index-D8wS_PeY.d.cts → index-i99Ka8s7.d.cts} +9 -9
- package/dist/index-iKkyJosF.d.cts +105 -0
- package/dist/{index-Xi3u0HCQ.d.cts → index-jleeotBT.d.cts} +1 -1
- package/dist/{index-DVGiGFGT.d.cts → index-kykKWwV-.d.cts} +3 -3
- package/dist/index-vgcLF5TH.d.cts +192 -0
- package/dist/{index-DYme44FM.d.cts → index-y1RllPn4.d.cts} +1 -1
- package/dist/index.cjs +151 -24142
- package/dist/index.d.cts +69 -2099
- package/dist/index.d.ts +69 -2099
- package/dist/index.js +1 -3868
- package/dist/{meta-CbznRPYJ.d.ts → meta-CX7YsOzp.d.cts} +5 -5
- package/dist/{meta-BxCA7rcr.d.cts → meta-CckhhFRd.d.ts} +5 -5
- package/dist/{node-BmerH3kS.d.cts → node-Dd6wHSib.d.cts} +71 -11
- package/dist/{node-BmerH3kS.d.ts → node-Dd6wHSib.d.ts} +71 -11
- package/dist/{observable-BgGUwcqp.d.ts → observable-BZJgo616.d.ts} +1 -1
- package/dist/{observable-DJt_AxzQ.d.cts → observable-kwzpLvbi.d.cts} +1 -1
- package/dist/patterns/ai/browser.cjs +25 -0
- package/dist/patterns/ai/browser.d.cts +127 -0
- package/dist/patterns/ai/browser.d.ts +127 -0
- package/dist/patterns/ai/browser.js +3 -0
- package/dist/patterns/ai/index.cjs +92 -0
- package/dist/patterns/ai/index.d.cts +17 -0
- package/dist/patterns/ai/index.d.ts +17 -0
- package/dist/patterns/ai/index.js +1 -0
- package/dist/patterns/ai/node.cjs +2 -0
- package/dist/patterns/ai/node.d.cts +58 -0
- package/dist/patterns/ai/node.d.ts +58 -0
- package/dist/patterns/ai/node.js +1 -0
- package/dist/patterns/audit/index.cjs +7 -0
- package/dist/patterns/audit/index.d.cts +6 -0
- package/dist/patterns/audit/index.d.ts +6 -0
- package/dist/patterns/audit/index.js +1 -0
- package/dist/patterns/cqrs/index.cjs +7 -0
- package/dist/patterns/cqrs/index.d.cts +5 -0
- package/dist/patterns/cqrs/index.d.ts +5 -0
- package/dist/patterns/cqrs/index.js +1 -0
- package/dist/patterns/demo-shell/index.cjs +8 -0
- package/dist/patterns/demo-shell/index.d.cts +6 -0
- package/dist/patterns/demo-shell/index.d.ts +6 -0
- package/dist/patterns/demo-shell/index.js +1 -0
- package/dist/patterns/domain-templates/index.cjs +7 -0
- package/dist/patterns/domain-templates/index.d.cts +5 -0
- package/dist/patterns/domain-templates/index.d.ts +5 -0
- package/dist/patterns/domain-templates/index.js +1 -0
- package/dist/patterns/graphspec/index.cjs +84 -0
- package/dist/patterns/graphspec/index.d.cts +7 -0
- package/dist/patterns/graphspec/index.d.ts +7 -0
- package/dist/patterns/graphspec/index.js +1 -0
- package/dist/patterns/guarded-execution/index.cjs +7 -0
- package/dist/patterns/guarded-execution/index.d.cts +7 -0
- package/dist/patterns/guarded-execution/index.d.ts +7 -0
- package/dist/patterns/guarded-execution/index.js +1 -0
- package/dist/patterns/harness/index.cjs +49 -0
- package/dist/patterns/harness/index.d.cts +11 -0
- package/dist/patterns/harness/index.d.ts +11 -0
- package/dist/patterns/harness/index.js +1 -0
- package/dist/patterns/job-queue/index.cjs +7 -0
- package/dist/patterns/job-queue/index.d.cts +5 -0
- package/dist/patterns/job-queue/index.d.ts +5 -0
- package/dist/patterns/job-queue/index.js +1 -0
- package/dist/patterns/lens/index.cjs +7 -0
- package/dist/patterns/lens/index.d.cts +7 -0
- package/dist/patterns/lens/index.d.ts +7 -0
- package/dist/patterns/lens/index.js +1 -0
- package/dist/patterns/memory/index.cjs +7 -0
- package/dist/patterns/memory/index.d.cts +5 -0
- package/dist/patterns/memory/index.d.ts +5 -0
- package/dist/patterns/memory/index.js +1 -0
- package/dist/patterns/messaging/index.cjs +7 -0
- package/dist/patterns/messaging/index.d.cts +5 -0
- package/dist/patterns/messaging/index.d.ts +5 -0
- package/dist/patterns/messaging/index.js +1 -0
- package/dist/patterns/orchestration/index.cjs +7 -0
- package/dist/patterns/orchestration/index.d.cts +6 -0
- package/dist/patterns/orchestration/index.d.ts +6 -0
- package/dist/patterns/orchestration/index.js +1 -0
- package/dist/patterns/reactive-layout/index.cjs +8 -6444
- package/dist/patterns/reactive-layout/index.d.cts +6 -6
- package/dist/patterns/reactive-layout/index.d.ts +6 -6
- package/dist/patterns/reactive-layout/index.js +1 -56
- package/dist/patterns/reduction/index.cjs +7 -0
- package/dist/patterns/reduction/index.d.cts +5 -0
- package/dist/patterns/reduction/index.d.ts +5 -0
- package/dist/patterns/reduction/index.js +1 -0
- package/dist/patterns/refine-loop/index.cjs +9 -0
- package/dist/patterns/refine-loop/index.d.cts +7 -0
- package/dist/patterns/refine-loop/index.d.ts +7 -0
- package/dist/patterns/refine-loop/index.js +1 -0
- package/dist/patterns/resilient-pipeline/index.cjs +1 -0
- package/dist/patterns/resilient-pipeline/index.d.cts +7 -0
- package/dist/patterns/resilient-pipeline/index.d.ts +7 -0
- package/dist/patterns/resilient-pipeline/index.js +1 -0
- package/dist/patterns/surface/index.cjs +15 -0
- package/dist/patterns/surface/index.d.cts +8 -0
- package/dist/patterns/surface/index.d.ts +8 -0
- package/dist/patterns/surface/index.js +1 -0
- package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-BkBwVvwm.d.ts} +2 -2
- package/dist/{reactive-layout-MQP--J3F.d.cts → reactive-layout-PiFwVaWS.d.cts} +2 -2
- package/dist/reactive-log-1QTyx10a.d.ts +190 -0
- package/dist/reactive-log-BiVoSxke.d.cts +190 -0
- package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CwO_COHy.d.cts} +2 -67
- package/dist/{composite-C7PcQvcs.d.cts → reactive-map-FeuTVAJb.d.ts} +2 -67
- package/dist/resilience-CBfYJW5C.d.ts +493 -0
- package/dist/resilience-XRUF267O.js +1 -0
- package/dist/resilience-uBz4yvYB.d.cts +493 -0
- package/dist/{sugar-CCOxXK1e.d.ts → sugar-CY-MCfZ9.d.ts} +17 -15
- package/dist/{sugar-D02n5JjF.d.cts → sugar-DHttV0LX.d.cts} +17 -15
- package/dist/topology-tree-CVjt2gp7.d.cts +25 -0
- package/dist/topology-tree-one6oSKY.d.ts +25 -0
- package/dist/types-O3GzJY2U.d.cts +401 -0
- package/dist/types-u64Ose53.d.ts +401 -0
- package/package.json +252 -22
- package/dist/ai-CaR_912Q.d.cts +0 -1033
- package/dist/ai-WlRltJV7.d.ts +0 -1033
- package/dist/chunk-3ZWCKRHX.js +0 -117
- package/dist/chunk-3ZWCKRHX.js.map +0 -1
- package/dist/chunk-7TAQJHQV.js +0 -103
- package/dist/chunk-7TAQJHQV.js.map +0 -1
- package/dist/chunk-APFNLIRG.js +0 -62
- package/dist/chunk-APFNLIRG.js.map +0 -1
- package/dist/chunk-AT5LKYNL.js +0 -395
- package/dist/chunk-AT5LKYNL.js.map +0 -1
- package/dist/chunk-BQ6RQQFF.js +0 -5087
- package/dist/chunk-BQ6RQQFF.js.map +0 -1
- package/dist/chunk-BVZYTZ5H.js +0 -599
- package/dist/chunk-BVZYTZ5H.js.map +0 -1
- package/dist/chunk-DST5DKZS.js +0 -1371
- package/dist/chunk-DST5DKZS.js.map +0 -1
- package/dist/chunk-GTE6PWRZ.js +0 -866
- package/dist/chunk-GTE6PWRZ.js.map +0 -1
- package/dist/chunk-HXZEYDUR.js +0 -94
- package/dist/chunk-HXZEYDUR.js.map +0 -1
- package/dist/chunk-J22W6HV3.js +0 -107
- package/dist/chunk-J22W6HV3.js.map +0 -1
- package/dist/chunk-J2VBW3DZ.js +0 -302
- package/dist/chunk-J2VBW3DZ.js.map +0 -1
- package/dist/chunk-JSCT3CR4.js +0 -38
- package/dist/chunk-JSCT3CR4.js.map +0 -1
- package/dist/chunk-JWBCY4NC.js +0 -330
- package/dist/chunk-JWBCY4NC.js.map +0 -1
- package/dist/chunk-K2AUJHVP.js +0 -2251
- package/dist/chunk-K2AUJHVP.js.map +0 -1
- package/dist/chunk-MJ2NKQQL.js +0 -119
- package/dist/chunk-MJ2NKQQL.js.map +0 -1
- package/dist/chunk-N6UR7YVY.js +0 -198
- package/dist/chunk-N6UR7YVY.js.map +0 -1
- package/dist/chunk-NC6S43JJ.js +0 -456
- package/dist/chunk-NC6S43JJ.js.map +0 -1
- package/dist/chunk-OFVJBJXR.js +0 -98
- package/dist/chunk-OFVJBJXR.js.map +0 -1
- package/dist/chunk-OHISZPOJ.js +0 -97
- package/dist/chunk-OHISZPOJ.js.map +0 -1
- package/dist/chunk-OU5CQKNW.js +0 -102
- package/dist/chunk-OU5CQKNW.js.map +0 -1
- package/dist/chunk-PF7GRZMW.js +0 -2712
- package/dist/chunk-PF7GRZMW.js.map +0 -1
- package/dist/chunk-PHOUUNK7.js +0 -2291
- package/dist/chunk-PHOUUNK7.js.map +0 -1
- package/dist/chunk-RNHBMHKA.js +0 -1665
- package/dist/chunk-RNHBMHKA.js.map +0 -1
- package/dist/chunk-SX52TAR4.js +0 -110
- package/dist/chunk-SX52TAR4.js.map +0 -1
- package/dist/chunk-VYPWMZ6H.js +0 -98
- package/dist/chunk-VYPWMZ6H.js.map +0 -1
- package/dist/chunk-WBZOVTYK.js +0 -171
- package/dist/chunk-WBZOVTYK.js.map +0 -1
- package/dist/chunk-WKNUIZOY.js +0 -354
- package/dist/chunk-WKNUIZOY.js.map +0 -1
- package/dist/chunk-X3VMZYBT.js +0 -713
- package/dist/chunk-X3VMZYBT.js.map +0 -1
- package/dist/chunk-X5R3GL6H.js +0 -525
- package/dist/chunk-X5R3GL6H.js.map +0 -1
- package/dist/chunk-XGPU467M.js +0 -136
- package/dist/chunk-XGPU467M.js.map +0 -1
- package/dist/compat/index.cjs.map +0 -1
- package/dist/compat/index.js.map +0 -1
- package/dist/compat/jotai/index.cjs.map +0 -1
- package/dist/compat/jotai/index.js.map +0 -1
- package/dist/compat/nanostores/index.cjs.map +0 -1
- package/dist/compat/nanostores/index.js.map +0 -1
- package/dist/compat/nestjs/index.cjs.map +0 -1
- package/dist/compat/nestjs/index.js.map +0 -1
- package/dist/compat/react/index.cjs.map +0 -1
- package/dist/compat/react/index.js.map +0 -1
- package/dist/compat/solid/index.cjs.map +0 -1
- package/dist/compat/solid/index.js.map +0 -1
- package/dist/compat/svelte/index.cjs.map +0 -1
- package/dist/compat/svelte/index.js.map +0 -1
- package/dist/compat/vue/index.cjs.map +0 -1
- package/dist/compat/vue/index.js.map +0 -1
- package/dist/compat/zustand/index.cjs.map +0 -1
- package/dist/compat/zustand/index.js.map +0 -1
- package/dist/core/index.cjs.map +0 -1
- package/dist/core/index.js.map +0 -1
- package/dist/extra/index.cjs.map +0 -1
- package/dist/extra/index.js.map +0 -1
- package/dist/extra/sources.cjs.map +0 -1
- package/dist/extra/sources.js.map +0 -1
- package/dist/graph/index.cjs.map +0 -1
- package/dist/graph/index.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/patterns/ai.cjs +0 -7930
- package/dist/patterns/ai.cjs.map +0 -1
- package/dist/patterns/ai.d.cts +0 -10
- package/dist/patterns/ai.d.ts +0 -10
- package/dist/patterns/ai.js +0 -71
- package/dist/patterns/ai.js.map +0 -1
- package/dist/patterns/audit.cjs +0 -5805
- package/dist/patterns/audit.cjs.map +0 -1
- package/dist/patterns/audit.d.cts +0 -6
- package/dist/patterns/audit.d.ts +0 -6
- package/dist/patterns/audit.js +0 -29
- package/dist/patterns/audit.js.map +0 -1
- package/dist/patterns/demo-shell.cjs +0 -5604
- package/dist/patterns/demo-shell.cjs.map +0 -1
- package/dist/patterns/demo-shell.d.cts +0 -6
- package/dist/patterns/demo-shell.d.ts +0 -6
- package/dist/patterns/demo-shell.js +0 -15
- package/dist/patterns/demo-shell.js.map +0 -1
- package/dist/patterns/memory.cjs +0 -5283
- package/dist/patterns/memory.cjs.map +0 -1
- package/dist/patterns/memory.d.cts +0 -5
- package/dist/patterns/memory.d.ts +0 -5
- package/dist/patterns/memory.js +0 -20
- package/dist/patterns/memory.js.map +0 -1
- package/dist/patterns/reactive-layout/index.cjs.map +0 -1
- package/dist/patterns/reactive-layout/index.js.map +0 -1
- package/dist/storage-CMjUUuxn.d.ts +0 -190
- package/dist/storage-DdWlZo6U.d.cts +0 -190
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/patterns/index.ts","../src/patterns/domain-templates.ts","../src/patterns/reduction.ts","../src/patterns/graphspec.ts","../src/patterns/guarded-execution.ts","../src/patterns/harness/index.ts","../src/patterns/harness/bridge.ts","../src/patterns/harness/types.ts","../src/patterns/harness/strategy.ts","../src/patterns/harness/loop.ts","../src/patterns/harness/profile.ts","../src/patterns/harness/trace.ts","../src/patterns/lens.ts","../src/patterns/resilient-pipeline.ts","../src/patterns/surface/index.ts","../src/patterns/surface/errors.ts","../src/patterns/surface/create.ts","../src/patterns/surface/reduce.ts","../src/patterns/surface/snapshot.ts","../src/index.ts"],"sourcesContent":["/**\n * Patterns layer: domain/solution helpers (Phase 4+).\n */\n\nexport * as ai from \"./ai.js\";\nexport * as accountability from \"./audit.js\";\nexport * as cqrs from \"./cqrs.js\";\nexport * as demoShell from \"./demo-shell.js\";\nexport * as domainTemplates from \"./domain-templates.js\";\nexport * as graphspec from \"./graphspec.js\";\nexport * as guarded from \"./guarded-execution.js\";\nexport * as harness from \"./harness/index.js\";\nexport * as lens from \"./lens.js\";\nexport * as memory from \"./memory.js\";\nexport * as messaging from \"./messaging.js\";\nexport * as orchestration from \"./orchestration.js\";\nexport * as layout from \"./reactive-layout/index.js\";\nexport * as reduction from \"./reduction.js\";\nexport * as resilientPipeline from \"./resilient-pipeline.js\";\n// Surface layer (§9.3-core): top-level + namespaced. The surface is the\n// entry point for @graphrefly/mcp-server and @graphrefly/cli, so named\n// exports live at the root alongside `core`/`graph`/`extra` style.\nexport * from \"./surface/index.js\";\nexport * as surface from \"./surface/index.js\";\n","/**\n * Domain templates (roadmap §8.2).\n *\n * Opinionated Graph factories for common \"info → action\" domains.\n * Each template wires up §8.1 reduction primitives (stratify, funnel, feedback,\n * budgetGate, scorer) with domain-specific stages. Users fork/extend by\n * accessing named nodes and swapping stages.\n *\n * **Source injection (option B):** templates accept a `source` node, not a\n * hardcoded adapter. Pass `fromOTel(...)`, `fromGitHook(...)`, or a test\n * `state()` — the topology is the same.\n *\n * @module\n */\n\nimport { batch } from \"../core/batch.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\nimport { feedback, type StratifyRule, scorer, stratify } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"domain_template\", kind, extra);\n}\n\n// ---------------------------------------------------------------------------\n// 1. observabilityGraph\n// ---------------------------------------------------------------------------\n\n/** Stratification branch config for observability signals. */\nexport type ObservabilityBranch = {\n\tname: string;\n\tclassify: (value: unknown) => boolean;\n};\n\n/** Options for {@link observabilityGraph}. */\nexport type ObservabilityGraphOptions = GraphOptions & {\n\t/** Ingested signal source (e.g. fromOTel(...) or test state). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification rules for signal stratification.\n\t * Default: errors / traces / metrics branches.\n\t */\n\tbranches?: ObservabilityBranch[];\n\n\t/**\n\t * Correlation function: receives stratified branch values and produces\n\t * correlated insights. Default: identity pass-through.\n\t */\n\tcorrelate?: (values: unknown[]) => unknown;\n\n\t/**\n\t * SLO verification function: returns a verification result for a\n\t * correlated insight. Default: always passes.\n\t */\n\tsloCheck?: (value: unknown) => unknown;\n\n\t/**\n\t * Scorer weights for alert prioritization. One per branch.\n\t * Default: equal weights [1, 1, 1].\n\t */\n\tweights?: number[];\n\n\t/** Max feedback iterations for false-positive learning. Default: 5. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * OTel ingest → stratified reduction → correlation → SLO verification →\n * alert prioritization → output.\n *\n * Well-known node names:\n * - `\"source\"` — injected signal source\n * - `\"stratify::branch/<name>\"` — per-branch classification\n * - `\"correlate\"` — cross-branch correlation\n * - `\"slo_value\"`, `\"slo_verified\"` — SLO verification pair\n * - `\"alerts\"` — scored, prioritized output\n * - `\"output\"` — final output (alias for alerts)\n *\n * @category patterns\n */\nexport function observabilityGraph(name: string, opts: ObservabilityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Stratify ---\n\tconst defaultBranches: ObservabilityBranch[] = [\n\t\t{ name: \"errors\", classify: (v) => isTagged(v, \"error\") },\n\t\t{ name: \"traces\", classify: (v) => isTagged(v, \"trace\") },\n\t\t{ name: \"metrics\", classify: (v) => isTagged(v, \"metric\") },\n\t];\n\tconst branches = opts.branches ?? defaultBranches;\n\tconst rules: StratifyRule<unknown>[] = branches.map((b) => ({\n\t\tname: b.name,\n\t\tclassify: b.classify,\n\t}));\n\tconst strat = stratify(\"stratify\", opts.source, rules);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Correlate ---\n\t// Collect latest value from each branch, produce correlated output.\n\t// Wrap each branch in a derived with `initial: null` so every branch has\n\t// a seed value at subscribe time — this lets the correlate wave reach its\n\t// first-run gate even when the classifier only routes to one branch.\n\tconst branchNodes = branches.map((b) => {\n\t\ttry {\n\t\t\tconst raw = g.resolve(`stratify::branch/${b.name}`);\n\t\t\treturn derived([raw as Node], ([v]) => v, { initial: null });\n\t\t} catch {\n\t\t\treturn state<unknown>(null);\n\t\t}\n\t});\n\tconst correlateFn = opts.correlate ?? ((vals: unknown[]) => vals);\n\tconst correlateNode = derived<unknown>(\n\t\tbranchNodes as Node[],\n\t\t(vals) => correlateFn(vals as unknown[]),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"correlate\" }),\n\t\t},\n\t);\n\tg.add(\"correlate\", correlateNode);\n\n\t// --- SLO verification ---\n\tconst sloCheckFn = opts.sloCheck ?? (() => ({ pass: true }));\n\tconst sloValue = derived<unknown>([correlateNode], (vals) => vals[0], {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_value\" }),\n\t});\n\tconst sloVerified = derived<unknown>([sloValue], (vals) => sloCheckFn(vals[0]), {\n\t\tmeta: baseMeta(\"observability\", { stage: \"slo_verified\" }),\n\t});\n\tg.add(\"slo_value\", sloValue);\n\tg.add(\"slo_verified\", sloVerified);\n\n\t// --- Alert scorer ---\n\tconst weightValues = opts.weights ?? branches.map(() => 1);\n\tconst signalNodes = branchNodes.map((bn) =>\n\t\tderived<number>([bn], (vals) => (vals[0] != null ? 1 : 0)),\n\t);\n\tconst weightNodes = weightValues.map((w) => state<number>(w));\n\tfor (let i = 0; i < signalNodes.length; i++) {\n\t\tg.add(`__signal_${i}`, signalNodes[i] as Node<unknown>);\n\t\tg.add(`__weight_${i}`, weightNodes[i] as Node<unknown>);\n\t}\n\tconst alerts = scorer(\n\t\tsignalNodes as ReadonlyArray<Node<number>>,\n\t\tweightNodes as ReadonlyArray<Node<number>>,\n\t);\n\tg.add(\"alerts\", alerts as Node<unknown>);\n\n\t// --- Output alias ---\n\tconst output = derived<unknown>(\n\t\t[alerts as Node, sloVerified],\n\t\t(vals) => ({\n\t\t\tscored: vals[0],\n\t\t\tslo: vals[1],\n\t\t}),\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"output\" }),\n\t\t},\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false-positive learning) ---\n\t// SLO failures feed back to re-check with updated context.\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[sloVerified],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result && result.pass === false) return result;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"observability\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 2. issueTrackerGraph\n// ---------------------------------------------------------------------------\n\n/** A structured issue extracted from raw findings. */\nexport type ExtractedIssue = {\n\tid: string;\n\ttitle: string;\n\tseverity: number;\n\tsource: string;\n\traw: unknown;\n};\n\n/** Options for {@link issueTrackerGraph}. */\nexport type IssueTrackerGraphOptions = GraphOptions & {\n\t/** Findings source (e.g. fromGitHook(...), fromFSWatch(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Extract structured issues from raw findings.\n\t * Default: wraps raw value as a single issue.\n\t */\n\textract?: (raw: unknown) => ExtractedIssue;\n\n\t/**\n\t * Verify an extracted issue (assertion check).\n\t * Default: always valid.\n\t */\n\tverify?: (issue: ExtractedIssue) => unknown;\n\n\t/**\n\t * Detect regression by comparing against known patterns.\n\t * Receives (current issue, known patterns).\n\t * Default: no regression detected.\n\t */\n\tdetectRegression?: (issue: ExtractedIssue, known: unknown) => unknown;\n\n\t/** Max feedback iterations for re-scanning. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Findings ingest → extraction → verification → regression detection →\n * distillation → prioritized queue.\n *\n * Well-known node names:\n * - `\"source\"` — injected findings source\n * - `\"extract\"` — structured issue extraction\n * - `\"verify\"` — issue verification\n * - `\"known_patterns\"` — accumulated known issue patterns (state)\n * - `\"regression\"` — regression detection\n * - `\"priority\"` — severity-based prioritization\n * - `\"output\"` — final prioritized output\n *\n * @category patterns\n */\nexport function issueTrackerGraph(name: string, opts: IssueTrackerGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Extract ---\n\tlet _issueCounter = 0;\n\tconst defaultExtract = (raw: unknown): ExtractedIssue => ({\n\t\tid: `issue-${++_issueCounter}`,\n\t\ttitle: String(raw),\n\t\tseverity: 1,\n\t\tsource: \"unknown\",\n\t\traw,\n\t});\n\tconst extractFn = opts.extract ?? defaultExtract;\n\tconst extractNode = derived<ExtractedIssue>([opts.source], (vals) => extractFn(vals[0]), {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"extract\" }),\n\t});\n\tg.add(\"extract\", extractNode as Node<unknown>);\n\n\t// --- Verify ---\n\tconst verifyFn = opts.verify ?? (() => ({ valid: true }));\n\tconst verifyNode = derived<unknown>(\n\t\t[extractNode as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\treturn { issue, verification: verifyFn(issue) };\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"verify\" }),\n\t\t},\n\t);\n\tg.add(\"verify\", verifyNode);\n\n\t// --- Known patterns (memory / distillation state) ---\n\tconst knownPatterns = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"known_patterns\" }),\n\t});\n\tg.add(\"known_patterns\", knownPatterns as Node<unknown>);\n\n\t// --- Regression detection ---\n\tconst detectFn = opts.detectRegression ?? (() => ({ regression: false }));\n\tconst regressionNode = derived<unknown>(\n\t\t[extractNode as Node, knownPatterns as Node],\n\t\t(vals) => {\n\t\t\tconst issue = vals[0] as ExtractedIssue;\n\t\t\tconst known = vals[1];\n\t\t\treturn { issue, regression: detectFn(issue, known) };\n\t\t},\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"regression\" }) },\n\t);\n\tg.add(\"regression\", regressionNode);\n\n\t// --- Priority scoring ---\n\tconst severitySignal = derived<number>([extractNode as Node], (vals) => {\n\t\tconst issue = vals[0] as ExtractedIssue;\n\t\treturn issue?.severity ?? 0;\n\t});\n\tconst regressionSignal = derived<number>([regressionNode], (vals) => {\n\t\tconst r = vals[0] as Record<string, unknown> | null;\n\t\treturn r?.regression ? 2 : 0;\n\t});\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\tg.add(\"__regression_signal\", regressionSignal as Node<unknown>);\n\n\tconst severityWeight = state<number>(1);\n\tconst regressionWeight = state<number>(1.5);\n\tg.add(\"__severity_weight\", severityWeight as Node<unknown>);\n\tg.add(\"__regression_weight\", regressionWeight as Node<unknown>);\n\n\tconst priority = scorer([severitySignal, regressionSignal], [severityWeight, regressionWeight]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[verifyNode, regressionNode, priority as Node],\n\t\t(vals) => ({\n\t\t\tverified: vals[0],\n\t\t\tregression: vals[1],\n\t\t\tpriority: vals[2],\n\t\t}),\n\t\t{ meta: baseMeta(\"issue_tracker\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (re-scan on verification failure) ---\n\tconst fbReentry = state<unknown>(null, {\n\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_reentry\" }),\n\t});\n\tg.add(\"feedback_reentry\", fbReentry);\n\tconst fbCondition = derived<unknown>(\n\t\t[verifyNode],\n\t\t(vals) => {\n\t\t\tconst result = vals[0] as Record<string, unknown> | null;\n\t\t\tif (result) {\n\t\t\t\tconst v = result.verification as Record<string, unknown> | null;\n\t\t\t\tif (v && v.valid === false) return result;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"issue_tracker\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"feedback_reentry\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 3. contentModerationGraph\n// ---------------------------------------------------------------------------\n\n/** Classification result from LLM moderation. */\nexport type ModerationResult = {\n\tlabel: \"safe\" | \"review\" | \"block\";\n\tconfidence: number;\n\treason?: string;\n\toriginal: unknown;\n};\n\n/** Options for {@link contentModerationGraph}. */\nexport type ContentModerationGraphOptions = GraphOptions & {\n\t/** Content source (text/multimedia ingest). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Classification function: returns a ModerationResult.\n\t * Default: labels everything \"review\" with confidence 0.5.\n\t */\n\tclassify?: (content: unknown) => ModerationResult;\n\n\t/** System prompt for LLM classification. */\n\tsystemPrompt?: string;\n\n\t/** Scorer weights: [safe, review, block]. Default: [0.1, 1, 2]. */\n\tweights?: [number, number, number];\n\n\t/** Max feedback iterations for policy refinement. Default: 5. */\n\tmaxFeedbackIterations?: number;\n\n\t/** Max review queue size. When set, oldest entries are trimmed on overflow. */\n\tmaxQueueSize?: number;\n};\n\n/**\n * Content ingest → LLM/rule classification → stratified routing (safe/review/block) →\n * human review queue → scorer → feedback (false positives → policy refinement) → output.\n *\n * Well-known node names:\n * - `\"source\"` — content ingest\n * - `\"classify\"` — LLM or rule-based classification\n * - `\"stratify::branch/safe\"`, `\"stratify::branch/review\"`, `\"stratify::branch/block\"` — routed branches\n * - `\"review_queue\"` — state node for human review items\n * - `\"priority\"` — scored priority output\n * - `\"policy\"` — writable state for policy refinement\n * - `\"output\"` — final moderation output\n *\n * @category patterns\n */\nexport function contentModerationGraph(name: string, opts: ContentModerationGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Classify ---\n\tconst defaultClassify = (content: unknown): ModerationResult => ({\n\t\tlabel: \"review\",\n\t\tconfidence: 0.5,\n\t\toriginal: content,\n\t});\n\tconst classifyFn = opts.classify ?? defaultClassify;\n\tconst classifyNode = derived<ModerationResult>([opts.source], (vals) => classifyFn(vals[0]), {\n\t\tmeta: baseMeta(\"content_moderation\", { stage: \"classify\" }),\n\t});\n\tg.add(\"classify\", classifyNode as Node<unknown>);\n\n\t// --- Stratify (safe / review / block) ---\n\tconst strat = stratify<ModerationResult>(\"stratify\", classifyNode, [\n\t\t{ name: \"safe\", classify: (v) => v.label === \"safe\" },\n\t\t{ name: \"review\", classify: (v) => v.label === \"review\" },\n\t\t{ name: \"block\", classify: (v) => v.label === \"block\" },\n\t]);\n\tg.mount(\"stratify\", strat);\n\n\t// --- Review queue (reactiveLog — O(1) append, bounded) ---\n\tconst reviewLog = reactiveLog<ModerationResult>([], {\n\t\tname: \"review_queue\",\n\t\tmaxSize: opts.maxQueueSize,\n\t});\n\tg.add(\"review_queue\", reviewLog.entries as Node<unknown>);\n\n\t// Bridge review branch → review queue accumulator\n\tlet reviewBranch: Node<unknown>;\n\ttry {\n\t\treviewBranch = g.resolve(\"stratify::branch/review\");\n\t} catch {\n\t\treviewBranch = state<unknown>(null);\n\t\tg.add(\"__review_fallback\", reviewBranch);\n\t}\n\tconst reviewAccumulator = effect([reviewBranch], (vals) => {\n\t\tconst item = vals[0] as ModerationResult | null;\n\t\tif (item) {\n\t\t\treviewLog.append(item);\n\t\t}\n\t});\n\tg.add(\"__review_accumulator\", reviewAccumulator as Node<unknown>);\n\tg.addDisposer(keepalive(reviewAccumulator as Node<unknown>));\n\ttry {\n\t} catch {\n\t\t// fallback branch — no stratify edge to register\n\t}\n\n\t// --- Policy state (human/LLM writable) ---\n\tconst policy = state<Record<string, unknown>>(\n\t\t{},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", {\n\t\t\t\tstage: \"policy\",\n\t\t\t\taccess: \"both\",\n\t\t\t\tdescription: \"Moderation policy rules — updated via feedback\",\n\t\t\t}),\n\t\t},\n\t);\n\tg.add(\"policy\", policy as Node<unknown>);\n\n\t// --- Priority scorer ---\n\tconst weights = opts.weights ?? [0.1, 1, 2];\n\tconst confidenceSignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\treturn r?.confidence ?? 0;\n\t});\n\tconst severitySignal = derived<number>([classifyNode as Node], (vals) => {\n\t\tconst r = vals[0] as ModerationResult | null;\n\t\tif (!r) return 0;\n\t\treturn r.label === \"block\" ? weights[2] : r.label === \"review\" ? weights[1] : weights[0];\n\t});\n\tg.add(\"__confidence_signal\", confidenceSignal as Node<unknown>);\n\tg.add(\"__severity_signal\", severitySignal as Node<unknown>);\n\n\tconst wConfidence = state<number>(1);\n\tconst wSeverity = state<number>(1);\n\tg.add(\"__w_confidence\", wConfidence as Node<unknown>);\n\tg.add(\"__w_severity\", wSeverity as Node<unknown>);\n\n\tconst priority = scorer([confidenceSignal, severitySignal], [wConfidence, wSeverity]);\n\tg.add(\"priority\", priority as Node<unknown>);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[classifyNode as Node, priority as Node],\n\t\t(vals) => ({\n\t\t\tclassification: vals[0],\n\t\t\tpriority: vals[1],\n\t\t}),\n\t\t{ meta: baseMeta(\"content_moderation\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (false positive → policy refinement) ---\n\t// Feedback condition: human marks a review item as false positive.\n\t// When review_queue changes and policy exists, signal for update.\n\tconst fbCondition = derived<unknown>(\n\t\t[reviewLog.entries as Node, policy as Node],\n\t\t(vals) => {\n\t\t\tconst entries = vals[0] as readonly ModerationResult[] | null;\n\t\t\tif (entries && entries.length > 0) {\n\t\t\t\tconst latest = entries[entries.length - 1];\n\t\t\t\t// Items explicitly marked as false positive feed back\n\t\t\t\tif (latest && (latest as unknown as Record<string, unknown>).falsePositive) {\n\t\t\t\t\treturn latest;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"content_moderation\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"policy\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 5,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// 4. dataQualityGraph\n// ---------------------------------------------------------------------------\n\n/** Schema validation result. */\nexport type ValidationResult = {\n\tvalid: boolean;\n\terrors: string[];\n\trecord: unknown;\n};\n\n/** Anomaly detection result. */\nexport type AnomalyResult = {\n\tanomaly: boolean;\n\tscore: number;\n\tdetail?: string;\n\trecord: unknown;\n};\n\n/** Options for {@link dataQualityGraph}. */\nexport type DataQualityGraphOptions = GraphOptions & {\n\t/** Data source (e.g. fromPrisma(...), fromKysely(...)). */\n\tsource: Node<unknown>;\n\n\t/**\n\t * Schema validation function.\n\t * Default: always valid.\n\t */\n\tvalidate?: (record: unknown) => ValidationResult;\n\n\t/**\n\t * Anomaly detection function.\n\t * Default: no anomaly.\n\t */\n\tdetectAnomaly?: (record: unknown) => AnomalyResult;\n\n\t/**\n\t * Drift detection: compares current record against baseline.\n\t * Default: no drift.\n\t */\n\tdetectDrift?: (record: unknown, baseline: unknown) => unknown;\n\n\t/**\n\t * Remediation suggestion function.\n\t * Default: no suggestion.\n\t */\n\tsuggest?: (result: { validation: ValidationResult; anomaly: AnomalyResult }) => unknown;\n\n\t/** Max feedback iterations for rule refinement. Default: 3. */\n\tmaxFeedbackIterations?: number;\n};\n\n/**\n * Data ingest → schema validation → anomaly detection → drift alerting →\n * auto-remediation suggestions → output.\n *\n * Well-known node names:\n * - `\"source\"` — data ingest\n * - `\"validate\"` — schema validation\n * - `\"anomaly\"` — anomaly detection\n * - `\"baseline\"` — rolling baseline state\n * - `\"drift\"` — drift detection\n * - `\"remediate\"` — auto-remediation suggestions\n * - `\"output\"` — combined quality report\n *\n * @category patterns\n */\nexport function dataQualityGraph(name: string, opts: DataQualityGraphOptions): Graph {\n\tconst g = new Graph(name, opts);\n\n\t// --- Source ---\n\tg.add(\"source\", opts.source);\n\n\t// --- Schema validation ---\n\tconst validateFn =\n\t\topts.validate ??\n\t\t((record: unknown): ValidationResult => ({\n\t\t\tvalid: true,\n\t\t\terrors: [],\n\t\t\trecord,\n\t\t}));\n\tconst validateNode = derived<ValidationResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? validateFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"validate\" }) },\n\t);\n\tg.add(\"validate\", validateNode as Node<unknown>);\n\n\t// --- Anomaly detection ---\n\tconst detectAnomalyFn =\n\t\topts.detectAnomaly ??\n\t\t((record: unknown): AnomalyResult => ({\n\t\t\tanomaly: false,\n\t\t\tscore: 0,\n\t\t\trecord,\n\t\t}));\n\tconst anomalyNode = derived<AnomalyResult | undefined>(\n\t\t[opts.source],\n\t\t(vals) => (vals[0] != null ? detectAnomalyFn(vals[0]) : undefined),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"anomaly\" }) },\n\t);\n\tg.add(\"anomaly\", anomalyNode as Node<unknown>);\n\n\t// --- Baseline (rolling state) ---\n\tconst baseline = state<unknown>(null, {\n\t\tmeta: baseMeta(\"data_quality\", {\n\t\t\tstage: \"baseline\",\n\t\t\tdescription: \"Rolling baseline for drift detection\",\n\t\t}),\n\t});\n\tg.add(\"baseline\", baseline);\n\n\t// Update baseline on valid records\n\tconst baselineUpdater = effect([validateNode as Node], (vals) => {\n\t\tconst result = vals[0] as ValidationResult;\n\t\tif (result?.valid) {\n\t\t\tbatch(() => {\n\t\t\t\tbaseline.down([[DATA, result.record]]);\n\t\t\t});\n\t\t}\n\t});\n\tg.add(\"__baseline_updater\", baselineUpdater as Node<unknown>);\n\tkeepalive(baselineUpdater as Node<unknown>);\n\n\t// --- Drift detection ---\n\tconst detectDriftFn = opts.detectDrift ?? (() => ({ drift: false }));\n\tconst driftNode = derived<unknown>(\n\t\t[opts.source, baseline],\n\t\t(vals) => detectDriftFn(vals[0], vals[1]),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"drift\" }) },\n\t);\n\tg.add(\"drift\", driftNode);\n\n\t// --- Remediation suggestions ---\n\tconst suggestFn = opts.suggest ?? (() => null);\n\tconst remediateNode = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node],\n\t\t(vals) =>\n\t\t\tsuggestFn({\n\t\t\t\tvalidation: vals[0] as ValidationResult,\n\t\t\t\tanomaly: vals[1] as AnomalyResult,\n\t\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"remediate\" }) },\n\t);\n\tg.add(\"remediate\", remediateNode);\n\n\t// --- Output ---\n\tconst output = derived<unknown>(\n\t\t[validateNode as Node, anomalyNode as Node, driftNode, remediateNode],\n\t\t(vals) => ({\n\t\t\tvalidation: vals[0],\n\t\t\tanomaly: vals[1],\n\t\t\tdrift: vals[2],\n\t\t\tremediation: vals[3],\n\t\t}),\n\t\t{ meta: baseMeta(\"data_quality\", { stage: \"output\" }) },\n\t);\n\tg.add(\"output\", output);\n\n\t// --- Feedback (anomaly → validation rule refinement) ---\n\tconst validationRules = state<unknown[]>([], {\n\t\tmeta: baseMeta(\"data_quality\", { stage: \"validation_rules\" }),\n\t});\n\tg.add(\"validation_rules\", validationRules as Node<unknown>);\n\n\tconst fbCondition = derived<unknown>(\n\t\t[anomalyNode as Node],\n\t\t(vals) => {\n\t\t\tconst a = vals[0] as AnomalyResult | null;\n\t\t\tif (a?.anomaly) return a;\n\t\t\treturn null;\n\t\t},\n\t\t{\n\t\t\tmeta: baseMeta(\"data_quality\", { stage: \"feedback_condition\" }),\n\t\t},\n\t);\n\tg.add(\"feedback_condition\", fbCondition as Node<unknown>);\n\tfeedback(g, \"feedback_condition\", \"validation_rules\", {\n\t\tmaxIterations: opts.maxFeedbackIterations ?? 3,\n\t});\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Check if a value has a `type` or `kind` tag matching the given label. */\nfunction isTagged(value: unknown, tag: string): boolean {\n\tif (value == null || typeof value !== \"object\") return false;\n\tconst v = value as Record<string, unknown>;\n\treturn v.type === tag || v.kind === tag;\n}\n","/**\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 { batch } from \"../core/batch.js\";\nimport type { NodeActions } from \"../core/config.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\ttype Message,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport { type Node, type NodeOptions, node } from \"../core/node.js\";\nimport { derived, effect, state } from \"../core/sugar.js\";\nimport { merge } from \"../extra/operators.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/graph.js\";\n\n// ---------------------------------------------------------------------------\n// Shared helpers (same pattern as orchestration.ts)\n// ---------------------------------------------------------------------------\n\nexport type StepRef = string | Node<unknown>;\n\nimport { domainMeta, keepalive, tryIncrementBounded } from \"./_internal.js\";\n\nfunction baseMeta(kind: string, meta?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"reduction\", kind, meta);\n}\n\n// ---------------------------------------------------------------------------\n// stratify\n// ---------------------------------------------------------------------------\n\n/** A single routing rule for {@link stratify}. */\nexport type StratifyRule<T> = {\n\t/** Branch name (used as node name under `branch/<name>`). */\n\tname: string;\n\t/** Classifier: returns `true` if the value belongs to this branch. */\n\tclassify: (value: T) => boolean;\n\t/** Optional operator chain applied to the branch after classification. */\n\tops?: (n: Node<T>) => Node;\n};\n\n/** Options for {@link stratify}. */\nexport type StratifyOptions = GraphOptions & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Route input to different reduction branches based on classifier functions.\n *\n * Each branch gets an independent operator chain. Rules are reactive — update\n * the `\"rules\"` state node to rewrite classification at runtime. Rule updates\n * affect **future items only** (streaming classification, not retroactive).\n *\n * Branch nodes are structural — created at construction time and persist for\n * the graph's lifetime. If a rule name is removed from the rules array, the\n * corresponding branch silently drops items (classifier not found). To tear\n * down a dead branch, call `graph.remove(\"branch/<name>\")`.\n *\n * @param name - Graph name.\n * @param source - Input node (registered externally or will be added as `\"source\"`).\n * @param rules - Initial routing rules.\n * @param opts - Optional graph/meta options.\n * @returns Graph with `\"source\"`, `\"rules\"`, and `\"branch/<name>\"` nodes.\n *\n * @category patterns\n */\nexport function stratify<T>(\n\tname: string,\n\tsource: Node<T>,\n\trules: ReadonlyArray<StratifyRule<T>>,\n\topts?: StratifyOptions,\n): Graph {\n\tconst g = new Graph(name, opts);\n\n\tg.add(\"source\", source as Node<unknown>);\n\tconst rulesNode = state<ReadonlyArray<StratifyRule<T>>>(rules, {\n\t\tmeta: baseMeta(\"stratify_rules\"),\n\t});\n\tg.add(\"rules\", rulesNode as Node<unknown>);\n\n\tfor (const rule of rules) {\n\t\t_addBranch(g, source, rulesNode, rule);\n\t}\n\n\treturn g;\n}\n\nfunction _addBranch<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trulesNode: Node<ReadonlyArray<StratifyRule<T>>>,\n\trule: StratifyRule<T>,\n): void {\n\tconst branchName = `branch/${rule.name}`;\n\n\t// Two-dep gating: intercepts messages from BOTH source (dep 0) and rules\n\t// (dep 1). Classification is deferred until all dirty deps have settled,\n\t// eliminating the stale-rules race when both are updated in the same batch().\n\t//\n\t// Protocol: DIRTY is buffered until DATA arrives. If the classifier matches,\n\t// emit [DIRTY, DATA]. If not, emit [DIRTY, RESOLVED] so downstream exits\n\t// dirty status cleanly (spec §1.3.1). Source RESOLVED forwards as RESOLVED.\n\t// Rules-only changes produce no downstream emission (\"future items only\").\n\t//\n\t// Producer pattern with `[]` deps: the framework does NOT auto-propagate\n\t// DIRTY/RESOLVED/COMPLETE from source or rules. We forward source terminals\n\t// explicitly below, and we silently absorb rules signals — preserving the\n\t// \"future items only\" semantic (rules changes are invisible downstream).\n\tconst _noValue: unique symbol = Symbol(\"noValue\");\n\tlet sourceDirty = false;\n\tlet rulesDirty = false;\n\tlet sourcePhase2 = false; // source delivered DATA or RESOLVED this cycle\n\tlet sourceValue: T | typeof _noValue = _noValue; // DATA payload, or _noValue for RESOLVED\n\tlet pendingDirty = false; // owe downstream a DIRTY\n\t// Latest rules DATA, seeded at factory time (wiring-time external read —\n\t// allowed per foundation-redesign §3.6). Updated by the rules subscribe\n\t// handler so `resolve()` never reads `rulesNode.cache` from a reactive context.\n\tlet latestRules: ReadonlyArray<StratifyRule<T>> = rulesNode.cache ?? [];\n\n\tfunction resolve(actions: NodeActions): void {\n\t\tif (sourcePhase2) {\n\t\t\tsourcePhase2 = false;\n\t\t\tconst value = sourceValue;\n\t\t\tsourceValue = _noValue;\n\t\t\tif (value !== _noValue) {\n\t\t\t\t// Source emitted DATA — classify with settled rules\n\t\t\t\tconst currentRule = latestRules.find((r) => r.name === rule.name);\n\t\t\t\tlet matches = false;\n\t\t\t\ttry {\n\t\t\t\t\tmatches = currentRule?.classify(value) ?? false;\n\t\t\t\t} catch {\n\t\t\t\t\tmatches = false;\n\t\t\t\t}\n\t\t\t\tif (matches) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.emit(value);\n\t\t\t\t} else {\n\t\t\t\t\tif (pendingDirty) {\n\t\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Source RESOLVED (unchanged)\n\t\t\t\tif (pendingDirty) {\n\t\t\t\t\tpendingDirty = false;\n\t\t\t\t\tactions.down([[DIRTY], [RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// else: rules-only change — no reclassification (\"future items only\")\n\t}\n\n\t// Producer pattern: manually subscribe to source and rules for per-message\n\t// interception (onMessage removed in v5)\n\tconst filterNode = node<T>(\n\t\t[],\n\t\t(_data, filterActions) => {\n\t\t\tconst srcUnsub = (source as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 0, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst rulesUnsub = (rulesNode as Node).subscribe((msgs) => {\n\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t_handleStratifyMessage(msg, 1, filterActions);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tsrcUnsub();\n\t\t\t\trulesUnsub();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"stratify_branch\", { branch: rule.name }),\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t},\n\t);\n\n\tfunction _handleStratifyMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// --- DIRTY (phase 1) ---\n\t\tif (t === DIRTY) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = true;\n\t\t\t\tpendingDirty = true;\n\t\t\t} else {\n\t\t\t\trulesDirty = true;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Phase 2 (DATA / RESOLVED) ---\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (depIndex === 0) {\n\t\t\t\tsourceDirty = false;\n\t\t\t\tsourcePhase2 = true;\n\t\t\t\tsourceValue = t === DATA ? (msg[1] as T) : _noValue;\n\t\t\t} else {\n\t\t\t\t// Rules dep: capture DATA payload into closure before settling.\n\t\t\t\tif (t === DATA) {\n\t\t\t\t\tlatestRules = msg[1] as ReadonlyArray<StratifyRule<T>>;\n\t\t\t\t}\n\t\t\t\trulesDirty = false;\n\t\t\t}\n\n\t\t\t// Wait for all dirty deps to settle\n\t\t\tif (sourceDirty || rulesDirty) return true;\n\n\t\t\tresolve(actions);\n\t\t\treturn true;\n\t\t}\n\n\t\t// --- Terminal ---\n\t\tif (t === COMPLETE || t === ERROR || t === TEARDOWN) {\n\t\t\tsourceDirty = false;\n\t\t\trulesDirty = false;\n\t\t\tsourcePhase2 = false;\n\t\t\tsourceValue = _noValue;\n\t\t\tpendingDirty = false;\n\t\t\tif (depIndex === 0) {\n\t\t\t\tactions.down([msg]);\n\t\t\t}\n\t\t\t// Rules terminal: swallow (branch stays alive)\n\t\t\treturn true;\n\t\t}\n\n\t\t// Swallow PAUSE/RESUME/INVALIDATE from rules dep (internal impl detail)\n\t\tif (depIndex === 1) return true;\n\n\t\treturn false;\n\t}\n\n\tgraph.add(branchName, filterNode as Node<unknown>);\n\n\t// If the rule has an ops chain, apply it and connect the edge\n\tif (rule.ops) {\n\t\tconst transformed = rule.ops(filterNode);\n\t\tconst transformedName = `branch/${rule.name}/out`;\n\t\tgraph.add(transformedName, transformed as Node<unknown>);\n\t}\n}\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\", merged as Node<unknown>);\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 = effect(\n\t\t\t[prevNode],\n\t\t\t([data]) => {\n\t\t\t\tstageInput.down([[DATA, data]]);\n\t\t\t},\n\t\t\t{ name: bridgeName },\n\t\t);\n\t\tg.add(bridgeName, br as Node<unknown>);\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 = state<number>(0, {\n\t\tmeta: baseMeta(\"feedback_counter\", {\n\t\t\tmaxIterations: maxIter,\n\t\t\tfeedbackFrom: condition,\n\t\t\tfeedbackTo: reentry,\n\t\t}),\n\t});\n\tgraph.add(counterName, counter as Node<unknown>);\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.down([[DATA, 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 () => 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(feedbackEffectName, feedbackEffect as Node<unknown>);\n\tgraph.addDisposer(keepalive(feedbackEffect));\n\n\treturn graph;\n}\n\n// ---------------------------------------------------------------------------\n// budgetGate\n// ---------------------------------------------------------------------------\n\n/** A reactive constraint for {@link budgetGate}. */\nexport type BudgetConstraint<T = unknown> = {\n\t/** Constraint node whose value is checked. */\n\tnode: Node<T>;\n\t/** Returns `true` when the constraint is satisfied (budget available). */\n\tcheck: (value: T) => boolean;\n};\n\n/** Options for {@link budgetGate}. */\nexport type BudgetGateOptions = Omit<NodeOptions<unknown>, \"describeKind\" | \"name\" | \"meta\"> & {\n\tmeta?: Record<string, unknown>;\n};\n\n/**\n * Pass-through that respects reactive constraint nodes.\n *\n * DATA flows through when all constraints are satisfied. When any constraint\n * is exceeded, PAUSE is sent upstream and DATA is buffered. When constraints\n * relax, RESUME is sent and buffered DATA flushes.\n *\n * @param source - Input node.\n * @param constraints - Reactive constraint checks.\n * @param opts - Optional node options.\n * @returns Gated node.\n *\n * @category patterns\n */\nexport function budgetGate<T>(\n\tsource: Node<T>,\n\tconstraints: ReadonlyArray<BudgetConstraint>,\n\topts?: BudgetGateOptions,\n): Node<T> {\n\tif (constraints.length === 0) throw new RangeError(\"budgetGate requires at least one constraint\");\n\n\tconst constraintNodes = constraints.map((c) => c.node);\n\tconst allDeps = [source as Node, ...constraintNodes] as Node[];\n\n\tlet buffer: T[] = [];\n\tlet paused = false;\n\tlet pendingResolved = false;\n\tconst lockId = Symbol(\"budget-gate\");\n\n\t// Latest DATA from each constraint. Seeded at **activation time** (inside the\n\t// producer fn below) — a wiring-time boundary read, not a reactive-callback\n\t// read — so concurrent constraint updates between factory-time and\n\t// activation-time are reflected before `checkBudget()` first runs. The\n\t// subscribe handler updates this array on each constraint DATA message, so\n\t// `checkBudget` never reads `.cache` from inside a reactive callback.\n\tconst latestValues: unknown[] = new Array(constraints.length);\n\n\tfunction checkBudget(): boolean {\n\t\treturn constraints.every((c, i) => c.check(latestValues[i]));\n\t}\n\n\tfunction flushBuffer(actions: NodeActions): void {\n\t\twhile (buffer.length > 0 && checkBudget()) {\n\t\t\tconst item = buffer[0]!;\n\t\t\tbuffer = buffer.slice(1);\n\t\t\tactions.emit(item);\n\t\t}\n\t\t// Drain deferred RESOLVED once buffer is empty\n\t\tif (buffer.length === 0 && pendingResolved) {\n\t\t\tpendingResolved = false;\n\t\t\tactions.down([[RESOLVED]]);\n\t\t}\n\t}\n\n\t// Producer pattern: manually subscribe to all deps for per-message interception\n\t// (onMessage removed in v5 — use producer+subscribe instead)\n\treturn node<T>(\n\t\t[],\n\t\t(_data, gateActions) => {\n\t\t\t// Seed `latestValues` at activation (not factory time) so any constraint\n\t\t\t// updates between factory return and first subscribe are captured before\n\t\t\t// source's push-on-subscribe fires `checkBudget()`.\n\t\t\tfor (let i = 0; i < constraints.length; i++) {\n\t\t\t\tlatestValues[i] = constraints[i]!.node.cache;\n\t\t\t}\n\t\t\tconst unsubs: Array<() => void> = [];\n\t\t\tfor (let depIdx = 0; depIdx < allDeps.length; depIdx++) {\n\t\t\t\tconst dep = allDeps[depIdx];\n\t\t\t\tunsubs.push(\n\t\t\t\t\tdep.subscribe((msgs) => {\n\t\t\t\t\t\tfor (const msg of msgs) {\n\t\t\t\t\t\t\t_handleBudgetMessage(msg, depIdx, gateActions);\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t},\n\t\t{\n\t\t\t...opts,\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: baseMeta(\"budget_gate\", opts?.meta),\n\t\t} as NodeOptions<T>,\n\t);\n\n\tfunction _handleBudgetMessage(msg: Message, depIndex: number, actions: NodeActions): boolean {\n\t\tconst t = msg[0];\n\n\t\t// Source messages (dep 0)\n\t\tif (depIndex === 0) {\n\t\t\tif (t === DATA) {\n\t\t\t\tif (checkBudget() && buffer.length === 0) {\n\t\t\t\t\tactions.emit(msg[1] as T);\n\t\t\t\t} else {\n\t\t\t\t\tbuffer.push(msg[1] as T);\n\t\t\t\t\tif (!paused) {\n\t\t\t\t\t\tpaused = true;\n\t\t\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === DIRTY) {\n\t\t\t\tactions.down([[DIRTY]]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === RESOLVED) {\n\t\t\t\tif (buffer.length === 0) {\n\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t} else {\n\t\t\t\t\t// Buffer non-empty: defer RESOLVED until buffer drains\n\t\t\t\t\tpendingResolved = true;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\t// Force-flush all buffered items regardless of budget (terminal = done)\n\t\t\t\tfor (const item of buffer) {\n\t\t\t\t\tactions.emit(item);\n\t\t\t\t}\n\t\t\t\tbuffer = [];\n\t\t\t\tpendingResolved = false;\n\t\t\t\t// Release PAUSE lock before forwarding terminal\n\t\t\t\tif (paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t\tactions.down([msg]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Constraint node messages (dep 1+): capture DATA then re-check budget\n\t\tif (t === DATA) {\n\t\t\tlatestValues[depIndex - 1] = msg[1];\n\t\t}\n\t\tif (t === DATA || t === RESOLVED) {\n\t\t\tif (checkBudget() && buffer.length > 0) {\n\t\t\t\tflushBuffer(actions);\n\t\t\t\tif (buffer.length === 0 && paused) {\n\t\t\t\t\tpaused = false;\n\t\t\t\t\tactions.up([[RESUME, lockId]]);\n\t\t\t\t}\n\t\t\t} else if (!checkBudget() && !paused && buffer.length > 0) {\n\t\t\t\tpaused = true;\n\t\t\t\tactions.up([[PAUSE, lockId]]);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (t === DIRTY) {\n\t\t\t// Don't propagate constraint DIRTY downstream\n\t\t\treturn true;\n\t\t}\n\t\tif (t === ERROR) {\n\t\t\t// Constraint error → forward downstream\n\t\t\tactions.down([msg]);\n\t\t\treturn true;\n\t\t}\n\t\tif (t === COMPLETE) {\n\t\t\t// Constraint completed — locked at last value, no-op\n\t\t\treturn true;\n\t\t}\n\t\t// Unknown constraint types → default forwarding\n\t\treturn false;\n\t}\n}\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 derived<ScoredItem<number[]>>(\n\t\tallDeps,\n\t\t(vals) => {\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\treturn {\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// ---------------------------------------------------------------------------\n// effectivenessTracker\n// ---------------------------------------------------------------------------\n\n/** A single effectiveness record for an action×context pair. */\nexport type EffectivenessEntry = {\n\treadonly key: string;\n\treadonly attempts: number;\n\treadonly successes: number;\n\treadonly successRate: number;\n};\n\n/** Snapshot shape for the effectiveness tracker node. */\nexport type EffectivenessSnapshot = ReadonlyMap<string, EffectivenessEntry>;\n\n/** Bundle returned by {@link effectivenessTracker}. */\nexport interface EffectivenessTrackerBundle {\n\t/** Reactive node — current effectiveness map snapshot. */\n\treadonly node: Node<EffectivenessSnapshot>;\n\n\t/** Record a completed action (success or failure). */\n\trecord(key: string, success: boolean): void;\n\n\t/** Look up effectiveness for a specific key. */\n\tlookup(key: string): EffectivenessEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/** Options for {@link effectivenessTracker}. */\nexport type EffectivenessTrackerOptions = {\n\t/** Name for the reactive map (default \"effectiveness-entries\"). */\n\tname?: string;\n};\n\n/**\n * Generic action×context → success rate tracker.\n *\n * Generalized from the harness `strategyModel` pattern. Tracks attempts and\n * successes per string key, exposes a reactive snapshot node, and provides\n * `record()` / `lookup()` methods.\n *\n * Use cases: A/B testing, routing optimization, cache policy tuning, retry\n * strategy selection — any domain that tracks effectiveness per action.\n *\n * @param opts - Optional configuration.\n * @returns Bundle with reactive node, record(), lookup(), dispose().\n */\nexport function effectivenessTracker(\n\topts?: EffectivenessTrackerOptions,\n): EffectivenessTrackerBundle {\n\tconst _map = reactiveMap<string, EffectivenessEntry>({\n\t\tname: opts?.name ?? \"effectiveness-entries\",\n\t});\n\n\tconst snapshot = derived<EffectivenessSnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\treturn new Map(mapSnap as ReadonlyMap<string, EffectivenessEntry>);\n\t\t},\n\t\t{\n\t\t\tname: `${opts?.name ?? \"effectiveness\"}-snapshot`,\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as EffectivenessSnapshot;\n\t\t\t\tconst bm = b as EffectivenessSnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(key: string, success: boolean): void {\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\tkey,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(key: string): EffectivenessEntry | undefined {\n\t\treturn _map.get(key);\n\t}\n\n\tconst _unsub = keepalive(snapshot);\n\n\treturn {\n\t\tnode: snapshot,\n\t\trecord,\n\t\tlookup,\n\t\tdispose: () => _unsub(),\n\t};\n}\n","/**\n * LLM graph composition (roadmap §8.3).\n *\n * Declarative GraphSpec schema + compiler/decompiler for graph topology.\n * The LLM designs graphs as JSON; compileSpec instantiates them; decompileGraph\n * extracts them back. Templates support reusable subgraph patterns. Feedback\n * edges express bounded cycles via §8.1 feedback().\n *\n * @module\n */\n\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, effect, producer, state } from \"../core/sugar.js\";\nimport { GRAPH_META_SEGMENT, Graph } from \"../graph/graph.js\";\nimport type { ChatMessage, LLMAdapter, LLMResponse } from \"./ai.js\";\nimport { feedback as feedbackPrimitive } from \"./reduction.js\";\n\n// ---------------------------------------------------------------------------\n// GraphSpec types\n// ---------------------------------------------------------------------------\n\n/** A single node declaration in a GraphSpec. */\nexport type GraphSpecNode = {\n\t/** Node kind: state, producer, derived, effect, operator. */\n\ttype: \"state\" | \"producer\" | \"derived\" | \"effect\" | \"operator\";\n\t/** Dependency node names (for derived/effect/operator). */\n\tdeps?: string[];\n\t/** Named function from the catalog (for derived/effect/operator/producer). */\n\tfn?: string;\n\t/** Named source from the catalog (for producer). */\n\tsource?: string;\n\t/** Freeform config passed to the catalog fn/source factory. */\n\tconfig?: Record<string, unknown>;\n\t/** Initial value (for state nodes). */\n\tinitial?: unknown;\n\t/** Human/LLM-readable metadata. */\n\tmeta?: Record<string, unknown>;\n};\n\n/** Template instantiation node — expanded at compile time. */\nexport type GraphSpecTemplateRef = {\n\ttype: \"template\";\n\t/** Name of the template to instantiate. */\n\ttemplate: string;\n\t/** Parameter bindings: template param name → node name. */\n\tbind: Record<string, string>;\n};\n\n/** A reusable subgraph pattern with parameter substitution. */\nexport type GraphSpecTemplate = {\n\t/** Parameter names (prefixed with $ in node refs). */\n\tparams: string[];\n\t/** Node declarations within the template. */\n\tnodes: Record<string, GraphSpecNode>;\n\t/** Which node's output is the template's output. */\n\toutput: string;\n};\n\n/** A feedback edge: bounded cycle from condition to reentry. */\nexport type GraphSpecFeedbackEdge = {\n\t/** Node whose DATA triggers the feedback. */\n\tfrom: string;\n\t/** State node that receives the feedback value. */\n\tto: string;\n\t/** Max iterations before stopping (default: 10). */\n\tmaxIterations?: number;\n};\n\n/** Declarative graph topology for LLM composition (§8.3). */\nexport type GraphSpec = {\n\t/** Graph name. */\n\tname: string;\n\t/** Node declarations (keyed by node name). */\n\tnodes: Record<string, GraphSpecNode | GraphSpecTemplateRef>;\n\t/** Reusable subgraph templates. */\n\ttemplates?: Record<string, GraphSpecTemplate>;\n\t/** Feedback edges (bounded cycles). */\n\tfeedback?: GraphSpecFeedbackEdge[];\n};\n\n// ---------------------------------------------------------------------------\n// Catalog types\n// ---------------------------------------------------------------------------\n\n/**\n * Factory for creating a derived/effect/operator node from catalog.\n * Receives resolved dep nodes and the config from the spec.\n */\nexport type FnFactory = (deps: Node<unknown>[], config: Record<string, unknown>) => Node<unknown>;\n\n/**\n * Factory for creating a producer node from catalog.\n * Receives the config from the spec.\n */\nexport type SourceFactory = (config: Record<string, unknown>) => Node<unknown>;\n\n// ---------------------------------------------------------------------------\n// Rich catalog entries (§9.1b — auto-prompt, catalog-aware validation)\n// ---------------------------------------------------------------------------\n\n/** Simple config field descriptor for LLM prompt generation and validation. */\nexport type ConfigFieldSchema = {\n\t/** Human-readable type: \"string\", \"number\", \"boolean\", \"string[]\", etc. */\n\ttype: string;\n\t/** Whether this field is required (default: true). */\n\trequired?: boolean;\n\t/** Allowed values (enum constraint). */\n\tenum?: readonly (string | number | boolean)[];\n\t/** Human-readable description for LLM context. */\n\tdescription?: string;\n\t/** Default value if omitted. */\n\tdefault?: unknown;\n};\n\n/**\n * Rich catalog entry: bundles a runtime factory with LLM-facing metadata.\n *\n * The metadata is used to:\n * 1. Auto-generate prompt text for {@link llmCompose} (replaces manual `catalogDescription`)\n * 2. Validate LLM output in {@link validateSpec} (catch wrong fn names, invalid config)\n * 3. Provide actionable error messages for {@link llmRefine} feedback loops\n *\n * Developers register ONE object; the library handles prompt generation and validation.\n */\nexport type CatalogFnEntry = {\n\t/** Runtime factory. */\n\tfactory: FnFactory;\n\t/** One-line description for LLM prompt (what it does, not how). */\n\tdescription: string;\n\t/** Config field schemas. Keys are config field names. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects (shown in prompt for complex fns). */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags for grouping in prompt (e.g., \"resilience\", \"reduction\", \"ai\"). */\n\ttags?: string[];\n};\n\n/** Rich catalog entry for producer sources. */\nexport type CatalogSourceEntry = {\n\t/** Runtime factory. */\n\tfactory: SourceFactory;\n\t/** One-line description for LLM prompt. */\n\tdescription: string;\n\t/** Config field schemas. */\n\tconfigSchema?: Record<string, ConfigFieldSchema>;\n\t/** Example config objects. */\n\texamples?: Record<string, unknown>[];\n\t/** Category tags. */\n\ttags?: string[];\n};\n\n/**\n * Fn/source lookup table passed to compileSpec and llmCompose.\n *\n * Accepts both bare factories (backward-compatible) and rich {@link CatalogFnEntry}\n * / {@link CatalogSourceEntry} objects. When rich entries are provided, the library\n * auto-generates LLM prompts and validates LLM output against the catalog.\n */\nexport type GraphSpecCatalog = {\n\tfns?: Record<string, FnFactory | CatalogFnEntry>;\n\tsources?: Record<string, SourceFactory | CatalogSourceEntry>;\n};\n\n// ---------------------------------------------------------------------------\n// Catalog helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this a rich catalog fn entry (vs bare factory)? */\nexport function isRichFnEntry(entry: FnFactory | CatalogFnEntry): entry is CatalogFnEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Type guard: is this a rich catalog source entry (vs bare factory)? */\nexport function isRichSourceEntry(\n\tentry: SourceFactory | CatalogSourceEntry,\n): entry is CatalogSourceEntry {\n\treturn typeof entry === \"object\" && entry !== null && \"factory\" in entry;\n}\n\n/** Extract the runtime factory from a catalog entry (rich or bare). */\nexport function extractFnFactory(entry: FnFactory | CatalogFnEntry): FnFactory {\n\treturn isRichFnEntry(entry) ? entry.factory : entry;\n}\n\n/** Extract the runtime factory from a catalog source entry (rich or bare). */\nexport function extractSourceFactory(entry: SourceFactory | CatalogSourceEntry): SourceFactory {\n\treturn isRichSourceEntry(entry) ? entry.factory : entry;\n}\n\n/**\n * Auto-generate catalog prompt text from rich catalog entries.\n *\n * Groups fns by tag, formats each as `- name: description. Config: { ... }`.\n * Falls back to listing names only for bare factories.\n */\nexport function generateCatalogPrompt(catalog: GraphSpecCatalog): string {\n\tconst sections: string[] = [];\n\n\tif (catalog.fns) {\n\t\t// Group by first tag (or \"Other\")\n\t\tconst groups = new Map<string, string[]>();\n\t\tfor (const [name, entry] of Object.entries(catalog.fns)) {\n\t\t\tconst tag = isRichFnEntry(entry) ? (entry.tags?.[0] ?? \"Other\") : \"Other\";\n\t\t\tif (!groups.has(tag)) groups.set(tag, []);\n\t\t\tgroups.get(tag)!.push(formatFnEntry(name, entry));\n\t\t}\n\t\tfor (const [tag, lines] of groups) {\n\t\t\tsections.push(`${tag}:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\tif (catalog.sources) {\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, entry] of Object.entries(catalog.sources)) {\n\t\t\tlines.push(formatSourceEntry(name, entry));\n\t\t}\n\t\tif (lines.length > 0) {\n\t\t\tsections.push(`Sources:\\n${lines.join(\"\\n\")}`);\n\t\t}\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n\nfunction formatFnEntry(name: string, entry: FnFactory | CatalogFnEntry): string {\n\tif (!isRichFnEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.enum) desc += ` (${v.enum.join(\"|\")})`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\nfunction formatSourceEntry(name: string, entry: SourceFactory | CatalogSourceEntry): string {\n\tif (!isRichSourceEntry(entry)) return `- ${name}`;\n\tlet line = `- ${name}: ${entry.description}`;\n\tif (entry.configSchema) {\n\t\tconst fields = Object.entries(entry.configSchema).map(([k, v]) => {\n\t\t\tlet desc = `${k}: ${v.type}`;\n\t\t\tif (v.required === false) desc += \"?\";\n\t\t\treturn desc;\n\t\t});\n\t\tline += `. Config: { ${fields.join(\", \")} }`;\n\t}\n\treturn line;\n}\n\n/**\n * Validate a GraphSpec against a catalog.\n *\n * Checks that fn/source names reference actual catalog entries, and validates\n * config fields against configSchema when rich entries are available.\n * Returns additional errors beyond structural {@link validateSpec} checks.\n */\nexport function validateSpecAgainstCatalog(\n\tspec: GraphSpec,\n\tcatalog: GraphSpecCatalog,\n): GraphSpecValidation {\n\tconst errors: string[] = [];\n\tconst fnNames = new Set(Object.keys(catalog.fns ?? {}));\n\tconst sourceNames = new Set(Object.keys(catalog.sources ?? {}));\n\n\tfor (const [nodeName, nodeRaw] of Object.entries(spec.nodes)) {\n\t\tif (nodeRaw.type === \"template\") continue;\n\t\tconst node = nodeRaw as GraphSpecNode;\n\n\t\t// Check fn name exists in catalog\n\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t// Check if they used a source name as fn\n\t\t\tif (sourceNames.has(node.fn)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" is a source, not a function. ` +\n\t\t\t\t\t\t`Use it as a producer source instead, or use a function from: ${[...fnNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Check source name exists in catalog\n\t\tif (node.source && sourceNames.size > 0 && !sourceNames.has(node.source)) {\n\t\t\tif (fnNames.has(node.source)) {\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" is a function, not a source. ` +\n\t\t\t\t\t\t`Use it as fn instead, or use a source from: ${[...sourceNames].join(\", \")}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst suggestion = findClosest(node.source, sourceNames);\n\t\t\t\terrors.push(\n\t\t\t\t\t`Node \"${nodeName}\": source \"${node.source}\" not found in catalog` +\n\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Validate config against schema (if rich entry)\n\t\tif (node.fn && node.config && catalog.fns?.[node.fn]) {\n\t\t\tconst entry = catalog.fns[node.fn];\n\t\t\tif (isRichFnEntry(entry) && entry.configSchema) {\n\t\t\t\tfor (const [field, schema] of Object.entries(entry.configSchema)) {\n\t\t\t\t\tif (schema.required !== false && !(field in node.config)) {\n\t\t\t\t\t\terrors.push(`Node \"${nodeName}\": config missing required field \"${field}\"`);\n\t\t\t\t\t}\n\t\t\t\t\tif (field in node.config && schema.enum) {\n\t\t\t\t\t\tconst val = node.config[field];\n\t\t\t\t\t\tif (!schema.enum.includes(val as string | number | boolean)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${nodeName}\": config.${field} = ${JSON.stringify(val)}, ` +\n\t\t\t\t\t\t\t\t\t`expected one of: ${schema.enum.join(\", \")}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Also check template inner nodes\n\tif (spec.templates) {\n\t\tfor (const [tName, template] of Object.entries(spec.templates)) {\n\t\t\tfor (const [nodeName, node] of Object.entries(template.nodes)) {\n\t\t\t\tif (node.fn && fnNames.size > 0 && !fnNames.has(node.fn)) {\n\t\t\t\t\tconst suggestion = findClosest(node.fn, fnNames);\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Template \"${tName}\" node \"${nodeName}\": fn \"${node.fn}\" not found in catalog` +\n\t\t\t\t\t\t\t(suggestion ? `. Did you mean \"${suggestion}\"?` : \"\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n/** Simple Levenshtein-based closest match for \"did you mean?\" suggestions. */\nfunction findClosest(input: string, candidates: Set<string>): string | null {\n\tlet best: string | null = null;\n\tlet bestDist = Infinity;\n\tconst lower = input.toLowerCase();\n\tfor (const c of candidates) {\n\t\tconst dist = levenshtein(lower, c.toLowerCase());\n\t\tif (dist < bestDist && dist <= Math.max(3, Math.floor(input.length / 2))) {\n\t\t\tbestDist = dist;\n\t\t\tbest = c;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction levenshtein(a: string, b: string): number {\n\tconst m = a.length;\n\tconst n = b.length;\n\tconst dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>\n\t\tArray.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n\t);\n\tfor (let i = 1; i <= m; i++) {\n\t\tfor (let j = 1; j <= n; j++) {\n\t\t\tdp[i][j] =\n\t\t\t\ta[i - 1] === b[j - 1]\n\t\t\t\t\t? dp[i - 1][j - 1]\n\t\t\t\t\t: 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);\n\t\t}\n\t}\n\treturn dp[m][n];\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\n/** Validation result from {@link validateSpec}. */\nexport type GraphSpecValidation = {\n\tvalid: boolean;\n\terrors: string[];\n};\n\nconst VALID_NODE_TYPES = new Set([\n\t\"state\",\n\t\"producer\",\n\t\"derived\",\n\t\"effect\",\n\t\"operator\",\n\t\"template\",\n]);\n\nconst INNER_NODE_TYPES = new Set([\"state\", \"producer\", \"derived\", \"effect\", \"operator\"]);\n\n/**\n * Validate a GraphSpec JSON object.\n *\n * Checks structural validity: required fields, node types, dep references,\n * template references, feedback edge targets, self-cycles, and bind completeness.\n */\nexport function validateSpec(spec: unknown): GraphSpecValidation {\n\tconst errors: string[] = [];\n\n\tif (spec == null || typeof spec !== \"object\") {\n\t\treturn { valid: false, errors: [\"GraphSpec must be a non-null object\"] };\n\t}\n\n\tconst s = spec as Record<string, unknown>;\n\n\tif (typeof s.name !== \"string\" || s.name.length === 0) {\n\t\terrors.push(\"Missing or empty 'name' field\");\n\t}\n\n\tif (s.nodes == null || typeof s.nodes !== \"object\" || Array.isArray(s.nodes)) {\n\t\terrors.push(\"Missing or invalid 'nodes' field (must be an object)\");\n\t\treturn { valid: false, errors };\n\t}\n\n\tconst nodeNames = new Set(Object.keys(s.nodes as object));\n\tconst nodeTypes = new Map<string, string>();\n\tconst templateDefs = new Map<string, { params: string[] }>();\n\n\t// Pre-scan template definitions for param validation\n\tif (s.templates != null && typeof s.templates === \"object\" && !Array.isArray(s.templates)) {\n\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\tif (tRaw != null && typeof tRaw === \"object\") {\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\ttemplateDefs.set(tName, {\n\t\t\t\t\tparams: Array.isArray(t.params) ? (t.params as string[]) : [],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate templates\n\tif (s.templates != null) {\n\t\tif (typeof s.templates !== \"object\" || Array.isArray(s.templates)) {\n\t\t\terrors.push(\"'templates' must be an object\");\n\t\t} else {\n\t\t\tfor (const [tName, tRaw] of Object.entries(s.templates as Record<string, unknown>)) {\n\t\t\t\tif (tRaw == null || typeof tRaw !== \"object\") {\n\t\t\t\t\terrors.push(`Template \"${tName}\": must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst t = tRaw as Record<string, unknown>;\n\t\t\t\tif (!Array.isArray(t.params)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'params' array`);\n\t\t\t\t}\n\t\t\t\tif (t.nodes == null || typeof t.nodes !== \"object\" || Array.isArray(t.nodes)) {\n\t\t\t\t\terrors.push(`Template \"${tName}\": missing or invalid 'nodes' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst paramSet = new Set(Array.isArray(t.params) ? (t.params as string[]) : []);\n\t\t\t\t\tconst innerNames = new Set(Object.keys(t.nodes as object));\n\t\t\t\t\tfor (const [nName, nRaw] of Object.entries(t.nodes as Record<string, unknown>)) {\n\t\t\t\t\t\tif (nRaw == null || typeof nRaw !== \"object\") {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": must be an object`);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst n = nRaw as Record<string, unknown>;\n\t\t\t\t\t\tif (typeof n.type !== \"string\" || !INNER_NODE_TYPES.has(n.type)) {\n\t\t\t\t\t\t\terrors.push(`Template \"${tName}\" node \"${nName}\": invalid type`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t\t\t\tif (!innerNames.has(dep) && !paramSet.has(dep)) {\n\t\t\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t\t\t`Template \"${tName}\" node \"${nName}\": dep \"${dep}\" is not an inner node or param`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof t.output !== \"string\") {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": missing 'output' string`);\n\t\t\t\t\t} else if (!(t.nodes as Record<string, unknown>)[t.output as string]) {\n\t\t\t\t\t\terrors.push(`Template \"${tName}\": output \"${t.output}\" is not a declared node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate nodes\n\tfor (const [name, raw] of Object.entries(s.nodes as Record<string, unknown>)) {\n\t\tif (raw == null || typeof raw !== \"object\") {\n\t\t\terrors.push(`Node \"${name}\": must be an object`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst n = raw as Record<string, unknown>;\n\t\tif (typeof n.type !== \"string\" || !VALID_NODE_TYPES.has(n.type)) {\n\t\t\terrors.push(\n\t\t\t\t`Node \"${name}\": invalid type \"${String(n.type)}\" (expected: ${[...VALID_NODE_TYPES].join(\", \")})`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tnodeTypes.set(name, n.type);\n\n\t\tif (n.type === \"template\") {\n\t\t\tif (typeof n.template !== \"string\" || !templateDefs.has(n.template)) {\n\t\t\t\terrors.push(`Node \"${name}\": template \"${String(n.template)}\" not found in templates`);\n\t\t\t} else {\n\t\t\t\t// Check bind completeness: all template params must be bound\n\t\t\t\tif (n.bind == null || typeof n.bind !== \"object\" || Array.isArray(n.bind)) {\n\t\t\t\t\terrors.push(`Node \"${name}\": template ref requires 'bind' object`);\n\t\t\t\t} else {\n\t\t\t\t\tconst tmpl = templateDefs.get(n.template as string)!;\n\t\t\t\t\tconst bind = n.bind as Record<string, string>;\n\t\t\t\t\tfor (const param of tmpl.params) {\n\t\t\t\t\t\tif (!(param in bind)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": template param \"${param}\" is not bound (template \"${n.template}\")`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [, target] of Object.entries(bind)) {\n\t\t\t\t\t\tif (typeof target === \"string\" && !nodeNames.has(target)) {\n\t\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t\t`Node \"${name}\": bind target \"${target}\" does not reference an existing node`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (Array.isArray(n.deps)) {\n\t\t\t\tfor (const dep of n.deps as string[]) {\n\t\t\t\t\t// Self-referencing dep\n\t\t\t\t\tif (dep === name) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": self-referencing dep`);\n\t\t\t\t\t} else if (!nodeNames.has(dep)) {\n\t\t\t\t\t\terrors.push(`Node \"${name}\": dep \"${dep}\" does not reference an existing node`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Warn: derived/effect/operator without deps\n\t\t\tif (\n\t\t\t\t(n.type === \"derived\" || n.type === \"effect\" || n.type === \"operator\") &&\n\t\t\t\t!Array.isArray(n.deps)\n\t\t\t) {\n\t\t\t\terrors.push(`Node \"${name}\": ${n.type} node should have a 'deps' array`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Validate feedback edges\n\tif (s.feedback != null) {\n\t\tif (!Array.isArray(s.feedback)) {\n\t\t\terrors.push(\"'feedback' must be an array\");\n\t\t} else {\n\t\t\tfor (let i = 0; i < (s.feedback as unknown[]).length; i++) {\n\t\t\t\tconst edge = (s.feedback as unknown[])[i];\n\t\t\t\tif (edge == null || typeof edge !== \"object\") {\n\t\t\t\t\terrors.push(`Feedback [${i}]: must be an object`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst e = edge as Record<string, unknown>;\n\t\t\t\tif (typeof e.from !== \"string\" || !nodeNames.has(e.from)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'from' \"${String(e.from)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (typeof e.from === \"string\" && e.from === e.to) {\n\t\t\t\t\terrors.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`);\n\t\t\t\t}\n\t\t\t\tif (typeof e.to !== \"string\" || !nodeNames.has(e.to)) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' \"${String(e.to)}\" does not reference an existing node`,\n\t\t\t\t\t);\n\t\t\t\t} else if (typeof e.to === \"string\" && nodeTypes.get(e.to) !== \"state\") {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t`Feedback [${i}]: 'to' node \"${e.to}\" must be a state node (got \"${nodeTypes.get(e.to) ?? \"unknown\"}\")`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// compileSpec\n// ---------------------------------------------------------------------------\n\n/** Options for {@link compileSpec}. */\nexport type CompileSpecOptions = {\n\t/** Fn/source catalog for resolving named factories. */\n\tcatalog?: GraphSpecCatalog;\n};\n\n/**\n * Instantiate a Graph from a GraphSpec.\n *\n * Handles template expansion (mounted subgraphs), feedback wiring via §8.1\n * feedback(), node factory lookup from the catalog, and topology validation.\n *\n * @param spec - Declarative graph topology.\n * @param opts - Catalog and compile options.\n * @returns A running Graph.\n * @throws On validation failure, missing catalog entries, or unresolvable deps.\n *\n * @category patterns\n */\nexport function compileSpec(spec: GraphSpec, opts?: CompileSpecOptions): Graph {\n\tconst validation = validateSpec(spec);\n\tif (!validation.valid) {\n\t\tthrow new Error(`compileSpec: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tconst catalog = opts?.catalog ?? {};\n\tconst g = new Graph(spec.name);\n\tconst templates = spec.templates ?? {};\n\n\t// Catalog-aware validation (when rich entries are available)\n\tconst catalogValidation = validateSpecAgainstCatalog(spec, catalog);\n\tif (!catalogValidation.valid) {\n\t\tthrow new Error(\n\t\t\t`compileSpec: catalog validation errors:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t);\n\t}\n\n\t// Helper: resolve fn/source factories from catalog (handles rich + bare entries)\n\tconst resolveFn = (fnName: string): FnFactory | undefined => {\n\t\tconst entry = catalog.fns?.[fnName];\n\t\treturn entry ? extractFnFactory(entry) : undefined;\n\t};\n\tconst resolveSource = (sourceName: string): SourceFactory | undefined => {\n\t\tconst entry = catalog.sources?.[sourceName];\n\t\treturn entry ? extractSourceFactory(entry) : undefined;\n\t};\n\n\t// Phase 1: Create non-template nodes (state/producer first, then derived/effect/operator)\n\tconst created = new Map<string, Node<unknown>>();\n\tconst deferred: [string, GraphSpecNode][] = [];\n\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type === \"template\") continue; // handled in Phase 2\n\n\t\tconst n = raw as GraphSpecNode;\n\t\tif (n.type === \"state\") {\n\t\t\tconst nd = state(n.initial, {\n\t\t\t\tname,\n\t\t\t\tmeta: n.meta ? { ...n.meta } : undefined,\n\t\t\t});\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t} else if (n.type === \"producer\") {\n\t\t\tconst sourceFactory = n.source ? resolveSource(n.source) : undefined;\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\t\t\tif (sourceFactory) {\n\t\t\t\tconst nd = sourceFactory(n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else if (fnFactory) {\n\t\t\t\tconst nd = fnFactory([], n.config ?? {});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t} else {\n\t\t\t\t// No catalog entry — create a bare producer placeholder\n\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\tname,\n\t\t\t\t\tmeta: { ...n.meta, _specFn: n.fn, _specSource: n.source },\n\t\t\t\t});\n\t\t\t\tg.add(name, nd);\n\t\t\t\tcreated.set(name, nd);\n\t\t\t}\n\t\t} else {\n\t\t\tdeferred.push([name, n]);\n\t\t}\n\t}\n\n\t// Resolve deferred nodes (derived/effect/operator) in dependency order\n\tlet progressed = true;\n\tconst pending = new Map(deferred);\n\twhile (pending.size > 0 && progressed) {\n\t\tprogressed = false;\n\t\tfor (const [name, n] of [...pending.entries()]) {\n\t\t\tconst deps = n.deps ?? [];\n\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\n\t\t\tconst resolvedDeps = deps.map((dep) => created.get(dep)!);\n\t\t\tconst fnFactory = n.fn ? resolveFn(n.fn) : undefined;\n\n\t\t\tlet nd: Node<unknown>;\n\t\t\tif (fnFactory) {\n\t\t\t\tnd = fnFactory(resolvedDeps, n.config ?? {});\n\t\t\t} else if (n.type === \"effect\") {\n\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t} else {\n\t\t\t\t// derived/operator without catalog fn — identity passthrough\n\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t}\n\t\t\tg.add(name, nd);\n\t\t\tcreated.set(name, nd);\n\t\t\tpending.delete(name);\n\t\t\tprogressed = true;\n\t\t}\n\t}\n\tif (pending.size > 0) {\n\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\tthrow new Error(`compileSpec: unresolvable deps for nodes: ${unresolved}`);\n\t}\n\n\t// Phase 2: Expand template instantiations as mounted subgraphs\n\tfor (const [name, raw] of Object.entries(spec.nodes)) {\n\t\tif (raw.type !== \"template\") continue;\n\t\tconst ref = raw as GraphSpecTemplateRef;\n\t\tconst tmpl = templates[ref.template]!;\n\n\t\tconst sub = new Graph(name);\n\t\tconst subCreated = new Map<string, Node<unknown>>();\n\t\tconst subDeferred: [string, GraphSpecNode][] = [];\n\n\t\t// Create inner nodes, resolving $params to bound nodes\n\t\tfor (const [nName, nSpec] of Object.entries(tmpl.nodes)) {\n\t\t\tconst resolvedDeps = (nSpec.deps ?? []).map((dep) => {\n\t\t\t\tif (dep.startsWith(\"$\") && ref.bind[dep]) {\n\t\t\t\t\treturn ref.bind[dep];\n\t\t\t\t}\n\t\t\t\treturn dep;\n\t\t\t});\n\t\t\tconst specWithResolvedDeps = { ...nSpec, deps: resolvedDeps };\n\n\t\t\tif (nSpec.type === \"state\") {\n\t\t\t\tconst nd = state(nSpec.initial, {\n\t\t\t\t\tname: nName,\n\t\t\t\t\tmeta: nSpec.meta ? { ...nSpec.meta } : undefined,\n\t\t\t\t});\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t} else if (nSpec.type === \"producer\") {\n\t\t\t\t// Handle producer nodes inside templates\n\t\t\t\tconst sourceFactory = nSpec.source ? resolveSource(nSpec.source) : undefined;\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\t\t\t\tif (sourceFactory) {\n\t\t\t\t\tconst nd = sourceFactory(nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else if (fnFactory) {\n\t\t\t\t\tconst nd = fnFactory([], nSpec.config ?? {});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t} else {\n\t\t\t\t\tconst nd = producer(() => {}, {\n\t\t\t\t\t\tname: nName,\n\t\t\t\t\t\tmeta: { ...nSpec.meta, _specFn: nSpec.fn, _specSource: nSpec.source },\n\t\t\t\t\t});\n\t\t\t\t\tsub.add(nName, nd);\n\t\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsubDeferred.push([nName, specWithResolvedDeps]);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve deferred inner nodes\n\t\tlet subProgressed = true;\n\t\tconst subPending = new Map(subDeferred);\n\t\twhile (subPending.size > 0 && subProgressed) {\n\t\t\tsubProgressed = false;\n\t\t\tfor (const [nName, nSpec] of [...subPending.entries()]) {\n\t\t\t\tconst deps = nSpec.deps ?? [];\n\t\t\t\tconst allReady = deps.every((dep) => subCreated.has(dep) || created.has(dep));\n\t\t\t\tif (!allReady) continue;\n\n\t\t\t\tconst resolvedDeps = deps.map((dep) => subCreated.get(dep) ?? created.get(dep)!);\n\t\t\t\tconst fnFactory = nSpec.fn ? resolveFn(nSpec.fn) : undefined;\n\n\t\t\t\tlet nd: Node<unknown>;\n\t\t\t\tif (fnFactory) {\n\t\t\t\t\tnd = fnFactory(resolvedDeps, nSpec.config ?? {});\n\t\t\t\t} else if (nSpec.type === \"effect\") {\n\t\t\t\t\tnd = effect(resolvedDeps, () => {});\n\t\t\t\t} else {\n\t\t\t\t\tnd = derived(resolvedDeps, (vals: readonly unknown[]) => vals[0]);\n\t\t\t\t}\n\t\t\t\tsub.add(nName, nd);\n\t\t\t\tsubCreated.set(nName, nd);\n\t\t\t\tsubPending.delete(nName);\n\t\t\t\tsubProgressed = true;\n\t\t\t}\n\t\t}\n\t\tif (subPending.size > 0) {\n\t\t\tconst unresolved = [...subPending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`compileSpec: template \"${ref.template}\" has unresolvable deps: ${unresolved}`,\n\t\t\t);\n\t\t}\n\n\t\tg.mount(name, sub);\n\t\t// Register template output as a reachable node path\n\t\tconst outputPath = `${name}::${tmpl.output}`;\n\t\tcreated.set(name, g.resolve(outputPath));\n\n\t\t// Store template origin meta on the mounted subgraph's first node\n\t\t// so decompileGraph can recover it without structural fingerprinting.\n\t\ttry {\n\t\t\tconst outputNode = g.resolve(outputPath);\n\t\t\toutputNode.meta._templateName?.down([[DATA, ref.template]]);\n\t\t\toutputNode.meta._templateBind?.down([[DATA, ref.bind]]);\n\t\t} catch {\n\t\t\t/* meta nodes may not exist; template origin is best-effort */\n\t\t}\n\t}\n\n\t// Edges are derived from node `_deps` (Unit 7) — no explicit edge wiring step.\n\n\t// Phase 4: Wire feedback edges via §8.1 feedback()\n\tfor (const fb of spec.feedback ?? []) {\n\t\tfeedbackPrimitive(g, fb.from, fb.to, {\n\t\t\tmaxIterations: fb.maxIterations,\n\t\t});\n\t}\n\n\treturn g;\n}\n\n// ---------------------------------------------------------------------------\n// decompileGraph\n// ---------------------------------------------------------------------------\n\n/** Internal meta keys used by compileSpec/feedback — stripped from output. */\nconst INTERNAL_META_KEYS = new Set([\n\t\"reduction\",\n\t\"reduction_type\",\n\t\"_specFn\",\n\t\"_specSource\",\n\t\"_templateName\",\n\t\"_templateBind\",\n\t\"feedbackFrom\",\n\t\"feedbackTo\",\n\t\"_internal\",\n]);\n\n/**\n * Extract a GraphSpec from a running graph.\n *\n * Uses `describe({ detail: \"standard\" })` as a starting point, then enriches:\n * - Feedback edges recovered from counter node meta (`feedbackFrom`/`feedbackTo`)\n * - Template refs recovered from output node meta (`_templateName`/`_templateBind`)\n * - Structural fingerprinting as fallback for 2+ identical mounted subgraphs\n *\n * @param graph - Running graph to decompile.\n * @returns A GraphSpec representation.\n *\n * @category patterns\n */\nexport function decompileGraph(graph: Graph): GraphSpec {\n\tconst desc = graph.describe({ detail: \"standard\" });\n\tconst nodes: Record<string, GraphSpecNode> = {};\n\tconst feedbackEdges: GraphSpecFeedbackEdge[] = [];\n\tconst metaSegment = `::${GRAPH_META_SEGMENT}::`;\n\n\t// Detect feedback counter nodes and extract feedback edges from meta\n\tconst feedbackCounterPattern = /^__feedback_(?!effect_)(.+)$/;\n\tconst feedbackConditions = new Set<string>();\n\n\tfor (const path of Object.keys(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tconst match = feedbackCounterPattern.exec(path);\n\t\tif (match) {\n\t\t\tfeedbackConditions.add(match[1]!);\n\t\t\tconst meta = desc.nodes[path]?.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?.feedbackFrom && meta?.feedbackTo) {\n\t\t\t\tfeedbackEdges.push({\n\t\t\t\t\tfrom: meta.feedbackFrom as string,\n\t\t\t\t\tto: meta.feedbackTo as string,\n\t\t\t\t\t...(meta.maxIterations ? { maxIterations: meta.maxIterations as number } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build nodes map, skipping meta, feedback internals, and bridge nodes\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tif (path.includes(metaSegment)) continue;\n\t\tif (feedbackCounterPattern.test(path)) continue;\n\t\t// Skip internal infrastructure nodes (bridge, feedback effect) via meta tag\n\t\tif (nodeDesc.meta?._internal) continue;\n\t\t// Legacy fallback: skip by naming convention\n\t\tif (path.startsWith(\"__feedback_effect_\")) continue;\n\t\tif (path.startsWith(\"__bridge_\")) continue;\n\t\t// Skip subgraph-internal nodes (they belong to templates)\n\t\tif (path.includes(\"::\")) continue;\n\n\t\tconst specNode: GraphSpecNode = {\n\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t};\n\n\t\tif (nodeDesc.deps.length > 0) {\n\t\t\tspecNode.deps = nodeDesc.deps.filter((d) => !d.includes(\"::\"));\n\t\t}\n\n\t\tif (nodeDesc.type === \"state\" && nodeDesc.value !== undefined) {\n\t\t\tspecNode.initial = nodeDesc.value;\n\t\t}\n\n\t\tif (nodeDesc.meta && Object.keys(nodeDesc.meta).length > 0) {\n\t\t\tconst meta: Record<string, unknown> = {};\n\t\t\tfor (const [k, v] of Object.entries(nodeDesc.meta as Record<string, unknown>)) {\n\t\t\t\tif (!INTERNAL_META_KEYS.has(k)) meta[k] = v;\n\t\t\t}\n\t\t\tif (Object.keys(meta).length > 0) {\n\t\t\t\tspecNode.meta = meta;\n\t\t\t}\n\t\t}\n\n\t\tnodes[path] = specNode;\n\t}\n\n\t// Detect templates: first from compile-time meta (option B), then structural fallback\n\tconst templates: Record<string, GraphSpecTemplate> = {};\n\tconst templateRefs: Record<string, GraphSpecTemplateRef> = {};\n\tconst metaDetectedSubgraphs = new Set<string>();\n\n\t// Option B: recover template origin from meta stored by compileSpec\n\tfor (const subName of desc.subgraphs) {\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tconst meta = nodeDesc.meta as Record<string, unknown> | undefined;\n\t\t\tif (meta?._templateName && meta?._templateBind) {\n\t\t\t\tconst templateName = meta._templateName as string;\n\t\t\t\tconst bind = meta._templateBind as Record<string, string>;\n\n\t\t\t\t// Reconstruct template definition from the subgraph's nodes\n\t\t\t\tif (!templates[templateName]) {\n\t\t\t\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\t\t\t\tconst tmplInnerNames = new Set<string>();\n\t\t\t\t\tconst tmplPrefix = `${subName}::`;\n\t\t\t\t\tfor (const [p, nd] of Object.entries(desc.nodes)) {\n\t\t\t\t\t\tif (!p.startsWith(tmplPrefix) || p.includes(metaSegment)) continue;\n\t\t\t\t\t\tconst localName = p.slice(tmplPrefix.length);\n\t\t\t\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\t\t\t\ttmplInnerNames.add(localName);\n\t\t\t\t\t\ttmplNodes[localName] = {\n\t\t\t\t\t\t\ttype: nd.type as GraphSpecNode[\"type\"],\n\t\t\t\t\t\t\t...(nd.deps.length > 0\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tdeps: nd.deps.map((d) =>\n\t\t\t\t\t\t\t\t\t\t\td.startsWith(tmplPrefix) ? d.slice(tmplPrefix.length) : d,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\t// Detect params (external deps) and output\n\t\t\t\t\tconst tmplParams: string[] = [];\n\t\t\t\t\tconst tmplParamMap = new Map<string, string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (!tmplInnerNames.has(dep) && !tmplParamMap.has(dep)) {\n\t\t\t\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\t\t\t\ttmplParams.push(param);\n\t\t\t\t\t\t\t\ttmplParamMap.set(dep, param);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Substitute external deps with $params\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tif (n.deps) n.deps = n.deps.map((d) => tmplParamMap.get(d) ?? d);\n\t\t\t\t\t}\n\t\t\t\t\t// Find output\n\t\t\t\t\tconst depended = new Set<string>();\n\t\t\t\t\tfor (const n of Object.values(tmplNodes)) {\n\t\t\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\t\t\tif (tmplInnerNames.has(dep)) depended.add(dep);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst outputCandidates = [...tmplInnerNames].filter((n) => !depended.has(n));\n\t\t\t\t\tconst tmplOutput = outputCandidates[0] ?? [...tmplInnerNames].pop()!;\n\n\t\t\t\t\ttemplates[templateName] = { params: tmplParams, nodes: tmplNodes, output: tmplOutput };\n\t\t\t\t}\n\n\t\t\t\tdelete nodes[subName];\n\t\t\t\ttemplateRefs[subName] = { type: \"template\", template: templateName, bind };\n\t\t\t\tmetaDetectedSubgraphs.add(subName);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Structural fallback: group remaining mounted subgraphs by fingerprint\n\tconst structureMap = new Map<string, { name: string; nodes: Record<string, GraphSpecNode> }[]>();\n\tfor (const subName of desc.subgraphs) {\n\t\tif (metaDetectedSubgraphs.has(subName)) continue;\n\t\tconst subNodes: Record<string, GraphSpecNode> = {};\n\t\tconst prefix = `${subName}::`;\n\t\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\t\tif (path.includes(metaSegment)) continue;\n\t\t\tif (!path.startsWith(prefix)) continue;\n\t\t\tconst localName = path.slice(prefix.length);\n\t\t\tif (localName.includes(\"::\")) continue;\n\t\t\tsubNodes[localName] = {\n\t\t\t\ttype: nodeDesc.type as GraphSpecNode[\"type\"],\n\t\t\t\t...(nodeDesc.deps.length > 0\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tdeps: nodeDesc.deps.map((d) => (d.startsWith(prefix) ? d.slice(prefix.length) : d)),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t\tconst fingerprint = JSON.stringify(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(subNodes)\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([k, v]) => [k, { type: v.type, deps: v.deps ?? [] }]),\n\t\t\t),\n\t\t);\n\t\tif (!structureMap.has(fingerprint)) {\n\t\t\tstructureMap.set(fingerprint, []);\n\t\t}\n\t\tstructureMap.get(fingerprint)!.push({ name: subName, nodes: subNodes });\n\t}\n\n\t// Subgraphs with identical structure (2+ instances) → templates\n\tfor (const [, group] of structureMap) {\n\t\tif (group.length < 2) continue;\n\t\tconst templateName = `${group[0]!.name}_template`;\n\t\tconst refNodes = group[0]!.nodes;\n\t\tconst innerNames = new Set(Object.keys(refNodes));\n\n\t\t// Detect external deps as params (from first member)\n\t\tconst params: string[] = [];\n\t\tconst baseParamMap = new Map<string, string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (!innerNames.has(dep) && !baseParamMap.has(dep)) {\n\t\t\t\t\tconst param = `$${dep}`;\n\t\t\t\t\tparams.push(param);\n\t\t\t\t\tbaseParamMap.set(dep, param);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Find output node\n\t\tconst depended = new Set<string>();\n\t\tfor (const n of Object.values(refNodes)) {\n\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\tif (innerNames.has(dep)) depended.add(dep);\n\t\t\t}\n\t\t}\n\t\tconst outputCandidates = [...innerNames].filter((n) => !depended.has(n));\n\t\tconst output = outputCandidates[0] ?? [...innerNames].pop()!;\n\n\t\t// Build template nodes with param-substituted deps\n\t\tconst tmplNodes: Record<string, GraphSpecNode> = {};\n\t\tfor (const [nName, nSpec] of Object.entries(refNodes)) {\n\t\t\ttmplNodes[nName] = {\n\t\t\t\t...nSpec,\n\t\t\t\tdeps: nSpec.deps?.map((d) => baseParamMap.get(d) ?? d),\n\t\t\t};\n\t\t}\n\n\t\ttemplates[templateName] = { params, nodes: tmplNodes, output };\n\n\t\t// Build per-member bind maps (each member may bind to different external nodes)\n\t\tfor (const member of group) {\n\t\t\tdelete nodes[member.name];\n\t\t\t// Build this member's own bind map by scanning its external deps\n\t\t\tconst memberBind: Record<string, string> = {};\n\t\t\tconst memberInnerNames = new Set(Object.keys(member.nodes));\n\t\t\tfor (const n of Object.values(member.nodes)) {\n\t\t\t\tfor (const dep of n.deps ?? []) {\n\t\t\t\t\tif (!memberInnerNames.has(dep)) {\n\t\t\t\t\t\t// Find which param this external dep maps to\n\t\t\t\t\t\tconst param = baseParamMap.get(dep) ?? `$${dep}`;\n\t\t\t\t\t\tmemberBind[param] = dep;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplateRefs[member.name] = {\n\t\t\t\ttype: \"template\",\n\t\t\t\ttemplate: templateName,\n\t\t\t\tbind: memberBind,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst allNodes: Record<string, GraphSpecNode | GraphSpecTemplateRef> = {\n\t\t...nodes,\n\t\t...templateRefs,\n\t};\n\n\tconst result: GraphSpec = { name: desc.name, nodes: allNodes };\n\tif (Object.keys(templates).length > 0) result.templates = templates;\n\tif (feedbackEdges.length > 0) result.feedback = feedbackEdges;\n\n\treturn result;\n}\n\n// ---------------------------------------------------------------------------\n// specDiff\n// ---------------------------------------------------------------------------\n\n/** A single change in a spec diff. */\nexport type SpecDiffEntry = {\n\ttype: \"added\" | \"removed\" | \"changed\";\n\tpath: string;\n\tdetail?: string;\n};\n\n/** Structural diff between two GraphSpecs. */\nexport type SpecDiffResult = {\n\tentries: SpecDiffEntry[];\n\tsummary: string;\n};\n\n/**\n * Compute a structural diff between two GraphSpecs.\n *\n * Template-aware: reports \"changed template definition\" vs \"changed\n * instantiation bindings.\" No runtime needed — pure JSON comparison.\n *\n * @param specA - The \"before\" spec.\n * @param specB - The \"after\" spec.\n * @returns Diff entries and a human-readable summary.\n *\n * @category patterns\n */\nexport function specDiff(specA: GraphSpec, specB: GraphSpec): SpecDiffResult {\n\tconst entries: SpecDiffEntry[] = [];\n\n\t// Diff name\n\tif (specA.name !== specB.name) {\n\t\tentries.push({\n\t\t\ttype: \"changed\",\n\t\t\tpath: \"name\",\n\t\t\tdetail: `\"${specA.name}\" → \"${specB.name}\"`,\n\t\t});\n\t}\n\n\t// Diff nodes\n\tconst nodesA = new Set(Object.keys(specA.nodes));\n\tconst nodesB = new Set(Object.keys(specB.nodes));\n\n\tfor (const name of nodesB) {\n\t\tif (!nodesA.has(name)) {\n\t\t\tconst n = specB.nodes[name]!;\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: `type: ${n.type}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `nodes.${name}` });\n\t\t}\n\t}\n\tfor (const name of nodesA) {\n\t\tif (!nodesB.has(name)) continue;\n\t\tconst a = specA.nodes[name]!;\n\t\tconst b = specB.nodes[name]!;\n\t\tif (JSON.stringify(a) !== JSON.stringify(b)) {\n\t\t\tconst details: string[] = [];\n\t\t\tif (a.type !== b.type) details.push(`type: ${a.type} → ${b.type}`);\n\t\t\tif (JSON.stringify((a as GraphSpecNode).deps) !== JSON.stringify((b as GraphSpecNode).deps)) {\n\t\t\t\tdetails.push(\"deps changed\");\n\t\t\t}\n\t\t\tif ((a as GraphSpecNode).fn !== (b as GraphSpecNode).fn) {\n\t\t\t\tdetails.push(`fn: ${(a as GraphSpecNode).fn} → ${(b as GraphSpecNode).fn}`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tJSON.stringify((a as GraphSpecNode).config) !== JSON.stringify((b as GraphSpecNode).config)\n\t\t\t) {\n\t\t\t\tdetails.push(\"config changed\");\n\t\t\t}\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `nodes.${name}`,\n\t\t\t\tdetail: details.join(\"; \") || \"modified\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff templates\n\tconst tmplA = specA.templates ?? {};\n\tconst tmplB = specB.templates ?? {};\n\tconst tmplNamesA = new Set(Object.keys(tmplA));\n\tconst tmplNamesB = new Set(Object.keys(tmplB));\n\n\tfor (const name of tmplNamesB) {\n\t\tif (!tmplNamesA.has(name)) {\n\t\t\tentries.push({ type: \"added\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) {\n\t\t\tentries.push({ type: \"removed\", path: `templates.${name}` });\n\t\t}\n\t}\n\tfor (const name of tmplNamesA) {\n\t\tif (!tmplNamesB.has(name)) continue;\n\t\tif (JSON.stringify(tmplA[name]) !== JSON.stringify(tmplB[name])) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `templates.${name}`,\n\t\t\t\tdetail: \"template definition changed\",\n\t\t\t});\n\t\t}\n\t}\n\n\t// Diff feedback\n\tconst fbA = specA.feedback ?? [];\n\tconst fbB = specB.feedback ?? [];\n\tconst fbKeyA = new Set(fbA.map((e) => `${e.from}->${e.to}`));\n\tconst fbKeyB = new Set(fbB.map((e) => `${e.from}->${e.to}`));\n\n\tfor (const fb of fbB) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyA.has(key)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"added\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tif (!fbKeyB.has(key)) {\n\t\t\tentries.push({ type: \"removed\", path: `feedback.${key}` });\n\t\t}\n\t}\n\tfor (const fb of fbA) {\n\t\tconst key = `${fb.from}->${fb.to}`;\n\t\tconst counterpart = fbB.find((b) => b.from === fb.from && b.to === fb.to);\n\t\tif (counterpart && JSON.stringify(fb) !== JSON.stringify(counterpart)) {\n\t\t\tentries.push({\n\t\t\t\ttype: \"changed\",\n\t\t\t\tpath: `feedback.${key}`,\n\t\t\t\tdetail: `maxIterations: ${fb.maxIterations ?? 10} → ${counterpart.maxIterations ?? 10}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Build summary\n\tconst added = entries.filter((e) => e.type === \"added\").length;\n\tconst removed = entries.filter((e) => e.type === \"removed\").length;\n\tconst changed = entries.filter((e) => e.type === \"changed\").length;\n\tconst parts: string[] = [];\n\tif (added) parts.push(`${added} added`);\n\tif (removed) parts.push(`${removed} removed`);\n\tif (changed) parts.push(`${changed} changed`);\n\tconst summary = parts.length > 0 ? parts.join(\", \") : \"no changes\";\n\n\treturn { entries, summary };\n}\n\n// ---------------------------------------------------------------------------\n// llmCompose\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmCompose}. */\nexport type LLMComposeOptions = {\n\tmodel?: string;\n\ttemperature?: number;\n\tmaxTokens?: number;\n\t/** Extra instructions appended to the system prompt. */\n\tsystemPromptExtra?: string;\n\t/**\n\t * Available fn/source catalog names for the LLM to reference.\n\t * When omitted and `catalog` contains rich {@link CatalogFnEntry} entries,\n\t * the prompt is auto-generated via {@link generateCatalogPrompt}.\n\t */\n\tcatalogDescription?: string;\n\t/**\n\t * Catalog for auto-prompt generation and catalog-aware validation.\n\t * When rich entries are provided, the catalog prompt is auto-generated\n\t * and LLM output is validated against fn/source names and config schemas.\n\t */\n\tcatalog?: GraphSpecCatalog;\n\t/**\n\t * Max auto-refine attempts when the LLM output fails catalog validation.\n\t * Each attempt feeds the validation errors back to the LLM via llmRefine.\n\t * Default: 0 (no auto-refine). Set to 2-3 for production use.\n\t */\n\tmaxAutoRefine?: number;\n};\n\nconst LLM_COMPOSE_SYSTEM_PROMPT = `You are a graph architect for GraphReFly, a reactive graph protocol.\n\nGiven a natural-language description, produce a JSON GraphSpec with this structure:\n\n{\n \"name\": \"<graph_name>\",\n \"nodes\": {\n \"<node_name>\": {\n \"type\": \"state\" | \"derived\" | \"producer\" | \"effect\" | \"operator\",\n \"deps\": [\"<dep_node_name>\", ...],\n \"fn\": \"<catalog_function_name>\",\n \"source\": \"<catalog_source_name>\",\n \"config\": { ... },\n \"initial\": <value>,\n \"meta\": { \"description\": \"<purpose>\" }\n },\n \"<template_instance>\": {\n \"type\": \"template\",\n \"template\": \"<template_name>\",\n \"bind\": { \"$param\": \"node_name\" }\n }\n },\n \"templates\": {\n \"<template_name>\": {\n \"params\": [\"$param1\", \"$param2\"],\n \"nodes\": { ... },\n \"output\": \"<output_node>\"\n }\n },\n \"feedback\": [\n { \"from\": \"<condition_node>\", \"to\": \"<state_node>\", \"maxIterations\": 10 }\n ]\n}\n\nRules:\n- \"state\" nodes hold user/LLM-writable values (knobs). Use \"initial\" for default values.\n- \"derived\" nodes compute from deps using a named \"fn\".\n- \"effect\" nodes produce side effects from deps.\n- \"producer\" nodes generate values from a named \"source\".\n- Use \"templates\" when the same subgraph pattern repeats (e.g., per-source resilience).\n- Use \"feedback\" for bounded cycles where a derived value writes back to a state node.\n- meta.description is required for every node.\n- Return ONLY valid JSON, no markdown fences or commentary.`;\n\n/** Strip markdown code fences. */\nfunction stripFences(text: string): string {\n\tconst match = text.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```[\\s\\S]*$/);\n\treturn match ? match[1]! : text;\n}\n\n/**\n * Ask an LLM to compose a GraphSpec from a natural-language problem description.\n *\n * The LLM generates a GraphSpec (with templates + feedback), validated before\n * returning. The spec is for human review before compilation via compileSpec().\n *\n * @param problem - Natural language problem description.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options and catalog description.\n * @returns A validated GraphSpec.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmCompose(\n\tproblem: string,\n\tadapter: LLMAdapter,\n\topts?: LLMComposeOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\n\t// Auto-generate catalog prompt from rich entries, or use manual description\n\tconst catalogPrompt =\n\t\topts?.catalogDescription ?? (opts?.catalog ? generateCatalogPrompt(opts.catalog) : undefined);\n\tif (catalogPrompt) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog (use ONLY these names):\\n${catalogPrompt}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{ role: \"user\", content: problem },\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response (Promise, plain value).\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmCompose: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmCompose: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\tlet spec = parsed as GraphSpec;\n\n\t// Catalog-aware validation + auto-refine loop\n\tif (opts?.catalog) {\n\t\tconst maxRefine = opts.maxAutoRefine ?? 0;\n\t\tfor (let attempt = 0; attempt <= maxRefine; attempt++) {\n\t\t\tconst catalogValidation = validateSpecAgainstCatalog(spec, opts.catalog);\n\t\t\tif (catalogValidation.valid) break;\n\n\t\t\tif (attempt === maxRefine) {\n\t\t\t\t// Last attempt failed — return with errors attached as meta\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`llmCompose: catalog validation failed after ${maxRefine} refine attempts:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Auto-refine: feed catalog errors back to LLM\n\t\t\tspec = await llmRefine(\n\t\t\t\tspec,\n\t\t\t\t`Fix these catalog errors:\\n${catalogValidation.errors.join(\"\\n\")}\\n\\nUse ONLY functions and sources from the catalog.`,\n\t\t\t\tadapter,\n\t\t\t\t{ ...opts, catalogDescription: catalogPrompt },\n\t\t\t);\n\t\t}\n\t}\n\n\treturn spec;\n}\n\n// ---------------------------------------------------------------------------\n// llmRefine\n// ---------------------------------------------------------------------------\n\n/** Options for {@link llmRefine}. */\nexport type LLMRefineOptions = LLMComposeOptions;\n\n/**\n * Ask an LLM to modify an existing GraphSpec based on feedback or changed requirements.\n *\n * @param currentSpec - The current GraphSpec to modify.\n * @param feedback - Natural language feedback or changed requirements.\n * @param adapter - LLM adapter for the generation call.\n * @param opts - Model options.\n * @returns A new GraphSpec incorporating the feedback.\n * @throws On invalid LLM output or validation failure.\n *\n * @category patterns\n */\nexport async function llmRefine(\n\tcurrentSpec: GraphSpec,\n\tfeedback: string,\n\tadapter: LLMAdapter,\n\topts?: LLMRefineOptions,\n): Promise<GraphSpec> {\n\tlet systemPrompt = LLM_COMPOSE_SYSTEM_PROMPT;\n\tif (opts?.catalogDescription) {\n\t\tsystemPrompt += `\\n\\nAvailable catalog:\\n${opts.catalogDescription}`;\n\t}\n\tif (opts?.systemPromptExtra) {\n\t\tsystemPrompt += `\\n\\n${opts.systemPromptExtra}`;\n\t}\n\n\tconst messages: ChatMessage[] = [\n\t\t{ role: \"system\", content: systemPrompt },\n\t\t{\n\t\t\trole: \"user\",\n\t\t\tcontent: `Current GraphSpec:\\n${JSON.stringify(currentSpec, null, 2)}\\n\\nModification request: ${feedback}\\n\\nReturn the complete modified GraphSpec as JSON.`,\n\t\t},\n\t];\n\n\tconst rawResult = adapter.invoke(messages, {\n\t\tmodel: opts?.model,\n\t\ttemperature: opts?.temperature ?? 0,\n\t\tmaxTokens: opts?.maxTokens,\n\t});\n\n\t// System boundary: await the adapter's response.\n\tconst response = (await rawResult) as LLMResponse;\n\tlet content = response.content.trim();\n\n\tif (content.startsWith(\"```\")) {\n\t\tcontent = stripFences(content);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new Error(`llmRefine: LLM response is not valid JSON: ${content.slice(0, 200)}`);\n\t}\n\n\tconst validation = validateSpec(parsed);\n\tif (!validation.valid) {\n\t\tthrow new Error(`llmRefine: invalid GraphSpec:\\n${validation.errors.join(\"\\n\")}`);\n\t}\n\n\treturn parsed as GraphSpec;\n}\n","/**\n * Composable safety layer (roadmap §9.0b).\n *\n * {@link guardedExecution} wraps any {@link Graph} with:\n *\n * - {@link policyEnforcer} — reactive ABAC, policies stored as a `Node` so\n * LLMs / humans can update them at runtime. Now with full transitive\n * dynamic coverage via `watchTopologyTree`.\n * - Scoped {@link GuardedExecutionGraph.scopedDescribe} — delegates to\n * `target.describe({actor})` so callers see only what the actor is\n * allowed to see.\n * - The enforcer's `violations` topic is republished as `violations` on\n * the wrapper, composable with {@link graphLens}.`health` alerts.\n *\n * V1 scope: policies + actor + scoped describe. Budget-as-option is NOT\n * in V1 — it requires a cost-tracking design that hasn't landed yet.\n * Callers who need a budget limit today append a budget-aware\n * {@link PolicyRuleData} to the policies list (check current cost and\n * `deny` when exhausted).\n *\n * @module\n */\nimport type { Actor } from \"../core/actor.js\";\nimport type { PolicyRuleData } from \"../core/guard.js\";\nimport type { Node } from \"../core/node.js\";\nimport {\n\ttype DescribeFilter,\n\tGraph,\n\ttype GraphDescribeOptions,\n\ttype GraphDescribeOutput,\n\ttype GraphOptions,\n} from \"../graph/index.js\";\nimport { type PolicyEnforcerGraph, type PolicyViolation, policyEnforcer } from \"./audit.js\";\nimport type { TopicGraph } from \"./messaging.js\";\n\n/** Options for {@link guardedExecution}. */\nexport interface GuardedExecutionOptions {\n\t/**\n\t * Policies enforced against every guarded write. Static list or a live\n\t * `Node<readonly PolicyRuleData[]>` (LLM-updatable).\n\t *\n\t * **Deny-by-default gotcha:** the underlying `policyFromRules()` denies any\n\t * action that matches no rule. An empty policies list in `mode: \"enforce\"`\n\t * therefore blocks EVERY write AND every `observe` through the stacked\n\t * guard — including `scopedDescribe()`. If you want a permissive base, add\n\t * at least `{ effect: \"allow\", action: \"*\" }` and layer deny rules on top.\n\t * In `mode: \"audit\"` no guards are stacked, so empty policies are safe.\n\t */\n\tpolicies: readonly PolicyRuleData[] | Node<readonly PolicyRuleData[]>;\n\t/**\n\t * Actor whose perspective drives {@link GuardedExecutionGraph.scopedDescribe}\n\t * and {@link GuardedExecutionGraph.describe} — when omitted, callers must\n\t * pass `{actor}` explicitly or they get the target's raw describe.\n\t */\n\tactor?: Actor;\n\t/**\n\t * `\"enforce\"` (default) — push guards onto target nodes so disallowed\n\t * writes throw {@link GuardDenied}.\n\t * `\"audit\"` — record would-be denials to the `violations` topic without\n\t * blocking writes.\n\t */\n\tmode?: \"audit\" | \"enforce\";\n\t/** Ring-buffer cap for the `violations` topic. Default 1000 (inherited from policyEnforcer). */\n\tviolationsLimit?: number;\n\t/** Wrapper graph name. Default `${target.name}_guarded`. */\n\tname?: string;\n\t/** Wrapper graph options. */\n\tgraph?: GraphOptions;\n}\n\n/**\n * Wrapper over a target {@link Graph} providing reactive ABAC + scoped\n * describe. Mounts a {@link PolicyEnforcerGraph} under `enforcer`.\n *\n * @category patterns\n */\nexport class GuardedExecutionGraph extends Graph {\n\treadonly enforcer: PolicyEnforcerGraph;\n\treadonly violations: TopicGraph<PolicyViolation>;\n\tprivate readonly _target: Graph;\n\tprivate readonly _defaultActor: Actor | undefined;\n\n\tconstructor(target: Graph, opts: GuardedExecutionOptions) {\n\t\tsuper(opts.name ?? `${target.name}_guarded`, opts.graph);\n\t\tthis._target = target;\n\t\tthis._defaultActor = opts.actor;\n\n\t\tconst enforcerOpts: {\n\t\t\tmode: \"audit\" | \"enforce\";\n\t\t\tname: string;\n\t\t\tviolationsLimit?: number;\n\t\t} = {\n\t\t\tmode: opts.mode ?? \"enforce\",\n\t\t\tname: \"enforcer\",\n\t\t};\n\t\tif (opts.violationsLimit != null) enforcerOpts.violationsLimit = opts.violationsLimit;\n\n\t\tthis.enforcer = policyEnforcer(target, opts.policies, enforcerOpts);\n\t\tthis.violations = this.enforcer.violations;\n\n\t\t// Mount the enforcer as a child so `wrapper.describe()` surfaces its\n\t\t// `policies` / `violationCount` nodes for introspection.\n\t\tthis.mount(\"enforcer\", this.enforcer);\n\t}\n\n\t/**\n\t * Describe the **target** graph scoped to the configured actor. Returns\n\t * only nodes the actor is permitted to see (via the target's node guards\n\t * filtering `describe()` via `actor`).\n\t *\n\t * Pass `{actor}` in opts to override the configured actor for this call.\n\t * Pass any standard {@link GraphDescribeOptions} fields (`detail`,\n\t * `fields`, `filter`) — they apply to the target's describe.\n\t *\n\t * **Mode interaction:**\n\t * - In `mode: \"enforce\"` (default), the enforcer stacks a policy-derived\n\t * guard on every target node. `scopedDescribe({actor})` then filters by\n\t * the AND of per-node guards AND the stacked policy guard.\n\t * - In `mode: \"audit\"`, NO guards are stacked — `scopedDescribe` filters\n\t * purely by the target's pre-existing per-node guards. If a target has\n\t * no node-level guards, the policy rules you pass have no effect on\n\t * visibility (they only populate the `violations` topic on writes).\n\t */\n\tscopedDescribe(\n\t\topts?: Omit<GraphDescribeOptions, \"actor\"> & { actor?: Actor },\n\t): GraphDescribeOutput {\n\t\tconst actor = opts?.actor ?? this._defaultActor;\n\t\tconst describeOpts: GraphDescribeOptions = {\n\t\t\t...opts,\n\t\t\t...(actor != null ? { actor } : {}),\n\t\t};\n\t\treturn this._target.describe(describeOpts);\n\t}\n\n\t/** The wrapped graph (escape hatch for tooling). */\n\tget target(): Graph {\n\t\treturn this._target;\n\t}\n}\n\n/**\n * Wrap a {@link Graph} with {@link policyEnforcer} plus a scoped describe\n * lens. Returns a {@link GuardedExecutionGraph} that can be mounted, diffed,\n * or composed with {@link graphLens}.\n *\n * @param target - The graph to guard.\n * @param opts - See {@link GuardedExecutionOptions}.\n *\n * @example\n * ```ts\n * const guarded = guardedExecution(app, {\n * actor: { type: \"human\", id: \"alice\" },\n * policies: [\n * { effect: \"allow\", action: \"read\", actorType: \"human\" },\n * { effect: \"deny\", action: \"write\", pathPattern: \"system::*\" },\n * ],\n * mode: \"enforce\",\n * });\n *\n * const view = guarded.scopedDescribe({ detail: \"standard\" });\n * guarded.violations.events.subscribe(msgs => console.log(\"violations:\", msgs));\n * ```\n *\n * @category patterns\n */\nexport function guardedExecution(\n\ttarget: Graph,\n\topts: GuardedExecutionOptions,\n): GuardedExecutionGraph {\n\treturn new GuardedExecutionGraph(target, opts);\n}\n\n// Re-export types useful for call sites.\nexport type { DescribeFilter };\n","/**\n * Harness wiring (roadmap §9.0).\n *\n * Reactive collaboration loop: static-topology, flowing data.\n * Composes orchestration (gate), AI (promptNode), reduction (scorer/stratify),\n * and messaging (TopicGraph/bridge) into a 7-stage loop.\n *\n * @module\n */\n\nexport * from \"./bridge.js\";\nexport * from \"./loop.js\";\nexport * from \"./profile.js\";\nexport * from \"./strategy.js\";\nexport * from \"./trace.js\";\nexport * from \"./types.js\";\n","/**\n * Harness bridge factories (roadmap §9.0).\n *\n * Intake bridges, eval source wrapper, before/after comparison,\n * affected-task filter, code-change bridge, and notification effect.\n * All are compositions of existing primitives — no new abstractions.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { derived, effect, state } from \"../../core/sugar.js\";\nimport { switchMap } from \"../../extra/operators.js\";\nimport { fromAny } from \"../../extra/sources.js\";\nimport type { TopicGraph } from \"../messaging.js\";\n\nimport type { IntakeItem, Severity, TriagedItem } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Generic intake bridge\n// ---------------------------------------------------------------------------\n\n/** Options for {@link createIntakeBridge}. */\nexport interface IntakeBridgeOptions {\n\t/** Name for the effect node (default \"intake-bridge\"). */\n\tname?: string;\n}\n\n/**\n * Generic source→intake bridge factory.\n *\n * Watches a source node for new values, passes each through a user-supplied\n * `parser` that produces zero or more `IntakeItem`s, and publishes them to\n * the given intake topic.\n *\n * This is the generalized pattern behind {@link evalIntakeBridge}. Use it for\n * CI results, test failures, Slack messages, monitoring alerts, or any domain\n * where structured results should flow into a harness loop.\n *\n * @param source - Reactive node emitting domain-specific data.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Converts source data into IntakeItem[]. Return empty array to skip.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function createIntakeBridge<T>(\n\tsource: Node<T>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser: (value: T) => IntakeItem[],\n\topts?: IntakeBridgeOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([value]) => {\n\t\t\tif (value == null) return;\n\t\t\tconst items = parser(value as T);\n\t\t\tfor (const item of items) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Generic eval result shape\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal eval result shape accepted by the bridge.\n *\n * TS eval runner uses `EvalRun` from `evals/lib/types.ts` which is a superset\n * of this shape. The bridge only reads what it needs.\n */\nexport interface EvalResult {\n\trun_id: string;\n\tmodel: string;\n\ttasks: EvalTaskResult[];\n}\n\nexport interface EvalTaskResult {\n\ttask_id: string;\n\tvalid: boolean;\n\tjudge_scores?: EvalJudgeScore[];\n}\n\nexport interface EvalJudgeScore {\n\tclaim: string;\n\tpass: boolean;\n\treasoning: string;\n}\n\n// ---------------------------------------------------------------------------\n// Bridge factory\n// ---------------------------------------------------------------------------\n\nexport interface EvalIntakeBridgeOptions {\n\t/** Name for the effect node (default \"eval-intake-bridge\"). */\n\tname?: string;\n\t/** Minimum severity for eval-sourced items (default \"medium\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Create an effect node that watches an eval results source and publishes\n * per-criterion findings to an intake topic.\n *\n * Each failing judge criterion produces a separate IntakeItem — not one\n * item per task. This gives the triage stage granular findings to classify.\n *\n * @param evalSource - Node emitting EvalResult (or EvalResult[]).\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param opts - Optional configuration.\n * @returns The effect node (for lifecycle management).\n */\nexport function evalIntakeBridge(\n\tevalSource: Node<EvalResult | EvalResult[]>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\topts?: EvalIntakeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"medium\";\n\n\treturn effect(\n\t\t[evalSource],\n\t\t([results]) => {\n\t\t\tif (results == null) return;\n\t\t\tconst runs = Array.isArray(results) ? (results as EvalResult[]) : [results as EvalResult];\n\n\t\t\tfor (const run of runs) {\n\t\t\t\tfor (const task of run.tasks) {\n\t\t\t\t\t// Only process tasks with failures\n\t\t\t\t\tif (task.valid && task.judge_scores?.every((s) => s.pass)) continue;\n\n\t\t\t\t\t// Task-level validity failure (no judge scores or overall invalid)\n\t\t\t\t\tif (!task.valid && (!task.judge_scores || task.judge_scores.length === 0)) {\n\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\tsummary: `Task ${task.task_id} invalid (model: ${run.model})`,\n\t\t\t\t\t\t\tevidence: `Run ${run.run_id}: task produced invalid output`,\n\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Per-criterion findings\n\t\t\t\t\tif (task.judge_scores) {\n\t\t\t\t\t\tfor (const score of task.judge_scores) {\n\t\t\t\t\t\t\tif (score.pass) continue;\n\t\t\t\t\t\t\tintakeTopic.publish({\n\t\t\t\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\t\t\t\tsummary: `${task.task_id}: ${score.claim} (model: ${run.model})`,\n\t\t\t\t\t\t\t\tevidence: score.reasoning,\n\t\t\t\t\t\t\t\taffectsAreas: [\"graphspec\"],\n\t\t\t\t\t\t\t\taffectsEvalTasks: [task.task_id],\n\t\t\t\t\t\t\t\tseverity: defaultSeverity,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"eval-intake-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition A: Eval-driven improvement loop\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap any eval runner as a reactive producer node.\n *\n * When `trigger` emits, calls `runner()` and emits the result downstream.\n * Uses `switchMap` + `fromAny` — the async boundary stays in the source\n * layer (spec §5.10). A new trigger cancels any in-flight run.\n *\n * ```ts\n * const trigger = state(0); // bump to trigger a new run\n * const results = evalSource(trigger, () => runEvals(config));\n * results.subscribe(msgs => { ... });\n * trigger.down([[DATA, 1]]); // fires the runner\n * ```\n *\n * @param trigger - Any node; each new DATA emission fires the runner.\n * @param runner - Returns an EvalResult (or promise of one).\n */\nexport function evalSource<T extends EvalResult>(\n\ttrigger: Node<unknown>,\n\trunner: () => T | Promise<T>,\n): Node<T> {\n\treturn switchMap(trigger, () => fromAny(runner()) as Node<T>);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Per-task delta produced by {@link beforeAfterCompare}. */\nexport interface EvalTaskDelta {\n\ttaskId: string;\n\tbefore: boolean;\n\tafter: boolean;\n\t/** Score-level diff (after − before), undefined if no scores present. */\n\tscoreDiff?: number;\n}\n\n/** Output of {@link beforeAfterCompare}. */\nexport interface EvalDelta {\n\t/** Task IDs that newly fail in `after` (were passing in `before`). */\n\tnewFailures: string[];\n\t/** Task IDs that now pass in `after` (were failing in `before`). */\n\tresolved: string[];\n\t/** Full per-task breakdown. */\n\ttaskDeltas: EvalTaskDelta[];\n\t/** True when net resolutions > net failures. */\n\toverallImproved: boolean;\n}\n\n/**\n * Derived node that computes before/after eval deltas.\n *\n * Pure computation: no LLM, no async. Compares per-task validity and\n * pass counts between two `EvalResult` snapshots.\n *\n * @param before - Node holding the baseline eval result.\n * @param after - Node holding the new eval result.\n */\nexport function beforeAfterCompare(\n\tbefore: Node<EvalResult>,\n\tafter: Node<EvalResult>,\n): Node<EvalDelta> {\n\treturn derived<EvalDelta>(\n\t\t[before as Node<unknown>, after as Node<unknown>],\n\t\t([b, a]) => {\n\t\t\tconst bRes = b as EvalResult;\n\t\t\tconst aRes = a as EvalResult;\n\n\t\t\tconst beforeMap = new Map<string, EvalTaskResult>(bRes.tasks.map((t) => [t.task_id, t]));\n\t\t\tconst afterMap = new Map<string, EvalTaskResult>(aRes.tasks.map((t) => [t.task_id, t]));\n\n\t\t\tconst allIds = new Set([...beforeMap.keys(), ...afterMap.keys()]);\n\t\t\tconst taskDeltas: EvalTaskDelta[] = [];\n\t\t\tconst newFailures: string[] = [];\n\t\t\tconst resolved: string[] = [];\n\n\t\t\tfor (const id of allIds) {\n\t\t\t\tconst bt = beforeMap.get(id);\n\t\t\t\tconst at = afterMap.get(id);\n\t\t\t\tconst beforeValid = bt?.valid ?? false;\n\t\t\t\tconst afterValid = at?.valid ?? false;\n\n\t\t\t\tconst beforeScore = bt?.judge_scores\n\t\t\t\t\t? bt.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst afterScore = at?.judge_scores\n\t\t\t\t\t? at.judge_scores.filter((s) => s.pass).length\n\t\t\t\t\t: undefined;\n\t\t\t\tconst scoreDiff =\n\t\t\t\t\tbeforeScore !== undefined && afterScore !== undefined\n\t\t\t\t\t\t? afterScore - beforeScore\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\ttaskDeltas.push({ taskId: id, before: beforeValid, after: afterValid, scoreDiff });\n\t\t\t\tif (beforeValid && !afterValid) newFailures.push(id);\n\t\t\t\tif (!beforeValid && afterValid) resolved.push(id);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tnewFailures,\n\t\t\t\tresolved,\n\t\t\t\ttaskDeltas,\n\t\t\t\toverallImproved: resolved.length > newFailures.length,\n\t\t\t};\n\t\t},\n\t\t{ name: \"eval-delta\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/**\n * Derived node that selects which eval task IDs to re-run.\n *\n * Collects `affectsEvalTasks` from all triaged items, deduplicates, then\n * optionally intersects with `fullTaskSet`. Returns a sorted array of IDs.\n *\n * Use this to avoid re-running the full eval suite after each fix: only the\n * tasks that the triaged items claim to affect are returned.\n *\n * @param issues - Node holding the current list of triaged items.\n * @param fullTaskSet - Optional node (or plain array) of all known task IDs.\n * When provided, output is the intersection.\n */\nexport function affectedTaskFilter(\n\tissues: Node<readonly TriagedItem[]>,\n\tfullTaskSet?: Node<readonly string[]> | readonly string[],\n): Node<string[]> {\n\tconst taskSetNode: Node<unknown> | null =\n\t\tfullTaskSet == null\n\t\t\t? null\n\t\t\t: Array.isArray(fullTaskSet)\n\t\t\t\t? (state(fullTaskSet as readonly string[]) as Node<unknown>)\n\t\t\t\t: (fullTaskSet as Node<unknown>);\n\n\tconst deps: Node<unknown>[] = [issues as Node<unknown>];\n\tif (taskSetNode) deps.push(taskSetNode);\n\n\treturn derived<string[]>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst items = values[0] as readonly TriagedItem[];\n\t\t\tconst all = taskSetNode ? new Set(values[1] as readonly string[]) : null;\n\n\t\t\tconst affected = new Set<string>();\n\t\t\tfor (const item of items) {\n\t\t\t\tfor (const id of item.affectsEvalTasks ?? []) {\n\t\t\t\t\tif (all == null || all.has(id)) affected.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [...affected].sort();\n\t\t},\n\t\t{ name: \"affected-task-filter\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Composition D: Quality gate (CI/CD)\n// ---------------------------------------------------------------------------\n\n/** A single lint error emitted by a CI tool. */\nexport interface LintError {\n\tfile: string;\n\tline: number;\n\tcol: number;\n\trule: string;\n\tmessage: string;\n}\n\n/** A single test failure emitted by a test runner. */\nexport interface TestFailure {\n\ttestId: string;\n\tfile: string;\n\tmessage: string;\n}\n\n/** Structured code-change / CI event. */\nexport interface CodeChange {\n\t/** Files touched by the change. */\n\tfiles: string[];\n\tlintErrors?: LintError[];\n\ttestFailures?: TestFailure[];\n}\n\n/** Options for {@link codeChangeBridge}. */\nexport interface CodeChangeBridgeOptions {\n\t/** Name for the effect node (default \"code-change-bridge\"). */\n\tname?: string;\n\t/** Default severity for generated IntakeItems (default \"high\"). */\n\tdefaultSeverity?: Severity;\n}\n\n/**\n * Intake bridge for code-change / CI events.\n *\n * Watches a source node for `CodeChange` events and publishes one\n * `IntakeItem` per lint error and per test failure to the intake topic.\n * Pass a custom `parser` to override the default mapping.\n *\n * @param source - Node emitting CodeChange events.\n * @param intakeTopic - TopicGraph to publish IntakeItem entries to.\n * @param parser - Optional custom parser (overrides default).\n * @param opts - Optional configuration.\n */\nexport function codeChangeBridge(\n\tsource: Node<CodeChange>,\n\tintakeTopic: TopicGraph<IntakeItem>,\n\tparser?: (change: CodeChange) => IntakeItem[],\n\topts?: CodeChangeBridgeOptions,\n): Node<unknown> {\n\tconst defaultSeverity = opts?.defaultSeverity ?? \"high\";\n\n\tfunction defaultParser(change: CodeChange): IntakeItem[] {\n\t\tconst items: IntakeItem[] = [];\n\t\tfor (const err of change.lintErrors ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"code-change\",\n\t\t\t\tsummary: `Lint: ${err.rule} in ${err.file}:${err.line}`,\n\t\t\t\tevidence: err.message,\n\t\t\t\taffectsAreas: [err.file],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\tfor (const fail of change.testFailures ?? []) {\n\t\t\titems.push({\n\t\t\t\tsource: \"test\",\n\t\t\t\tsummary: `Test failure: ${fail.testId}`,\n\t\t\t\tevidence: fail.message,\n\t\t\t\taffectsAreas: [fail.file],\n\t\t\t\taffectsEvalTasks: [fail.testId],\n\t\t\t\tseverity: defaultSeverity,\n\t\t\t});\n\t\t}\n\t\treturn items;\n\t}\n\n\tconst resolve = parser ?? defaultParser;\n\n\treturn effect(\n\t\t[source as Node<unknown>],\n\t\t([change]) => {\n\t\t\tif (change == null) return;\n\t\t\tfor (const item of resolve(change as CodeChange)) {\n\t\t\t\tintakeTopic.publish(item);\n\t\t\t}\n\t\t},\n\t\t{ name: opts?.name ?? \"code-change-bridge\" },\n\t);\n}\n\n// ---------------------------------------------------------------------------\n\n/** Transport function for {@link notifyEffect}. Sync or async. */\nexport type NotifyTransport<T> = (item: T) => void | Promise<void>;\n\n/** Options for {@link notifyEffect}. */\nexport interface NotifyEffectOptions {\n\t/** Name for the effect node (default \"notify-effect\"). */\n\tname?: string;\n}\n\n/**\n * Effect node that sends each new topic entry to an external channel.\n *\n * The `transport` function is called for every item published to `topic`.\n * Async transports are bridged via `fromAny` (spec §5.10 compliant).\n *\n * Typical use: Slack webhook, GitHub PR comment, email notification, etc.\n * The factory provides reactive wiring; the transport supplies domain logic.\n *\n * ```ts\n * notifyEffect(alertQueue, async (item) => {\n * await fetch(SLACK_WEBHOOK, { method: 'POST', body: JSON.stringify({ text: item.summary }) });\n * });\n * ```\n *\n * @param topic - TopicGraph whose latest entry triggers the notification.\n * @param transport - Called with each new item. May return a Promise.\n * @param opts - Optional configuration.\n */\nexport function notifyEffect<T>(\n\ttopic: TopicGraph<T>,\n\ttransport: NotifyTransport<T>,\n\topts?: NotifyEffectOptions,\n): Node<unknown> {\n\treturn effect(\n\t\t[topic.latest as Node<unknown>],\n\t\t([item]) => {\n\t\t\tif (item == null) return;\n\t\t\t// transport is a side effect (webhook, Slack, email). Async transports\n\t\t\t// are fire-and-forget — the Promise result does not feed back into the\n\t\t\t// graph. Suppress unhandled-rejection noise by voiding the return.\n\t\t\tvoid transport(item as T);\n\t\t},\n\t\t{ name: opts?.name ?? \"notify-effect\" },\n\t);\n}\n","/**\n * Harness wiring types (roadmap §9.0).\n *\n * Shared types for the reactive collaboration loop: intake, triage, queue,\n * gate, execute, verify, reflect. These types are intentionally domain-agnostic\n * — the harness loop is not specific to eval workflows.\n *\n * @module\n */\n\n// ---------------------------------------------------------------------------\n// Intake\n// ---------------------------------------------------------------------------\n\n/** Sources that can produce intake items. */\nexport type IntakeSource = \"eval\" | \"test\" | \"human\" | \"code-change\" | \"hypothesis\" | \"parity\";\n\n/** Severity levels for intake items. */\nexport type Severity = \"critical\" | \"high\" | \"medium\" | \"low\";\n\n/** Root cause categories for triage classification. */\nexport type RootCause =\n\t| \"composition\"\n\t| \"missing-fn\"\n\t| \"bad-docs\"\n\t| \"schema-gap\"\n\t| \"regression\"\n\t| \"unknown\";\n\n/** Intervention types that address root causes. */\nexport type Intervention =\n\t| \"template\"\n\t| \"catalog-fn\"\n\t| \"docs\"\n\t| \"wrapper\"\n\t| \"schema-change\"\n\t| \"investigate\";\n\n/** Routing destinations after triage. */\nexport type QueueRoute = \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\";\n\n/** Ordered queue route names for iteration. */\nexport const QUEUE_NAMES: readonly QueueRoute[] = [\n\t\"auto-fix\",\n\t\"needs-decision\",\n\t\"investigation\",\n\t\"backlog\",\n];\n\n/**\n * An item entering the harness loop via the INTAKE stage.\n *\n * All intake sources produce this uniform shape — the intake topic\n * doesn't care where items came from.\n */\nexport interface IntakeItem {\n\tsource: IntakeSource;\n\tsummary: string;\n\tevidence: string;\n\taffectsAreas: string[];\n\taffectsEvalTasks?: string[];\n\tseverity?: Severity;\n\trelatedTo?: string[];\n\t/** Item-carried reingestion count. Incremented on each full-loop reingestion. */\n\t_reingestions?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Triage output\n// ---------------------------------------------------------------------------\n\n/** Output of the TRIAGE stage — enriched intake item with classification. */\nexport interface TriagedItem extends IntakeItem {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\troute: QueueRoute;\n\tpriority: number;\n\ttriageReasoning?: string;\n\t/** Item-carried retry count. Incremented on each fast-retry pass. */\n\t_retries?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Effectiveness record for a rootCause→intervention pair. */\nexport interface StrategyEntry {\n\trootCause: RootCause;\n\tintervention: Intervention;\n\tattempts: number;\n\tsuccesses: number;\n\tsuccessRate: number;\n}\n\n/** Key format: `${rootCause}→${intervention}`. */\nexport type StrategyKey = `${RootCause}→${Intervention}`;\n\nexport function strategyKey(rootCause: RootCause, intervention: Intervention): StrategyKey {\n\treturn `${rootCause}→${intervention}`;\n}\n\n// ---------------------------------------------------------------------------\n// Execution & verification\n// ---------------------------------------------------------------------------\n\n/** LLM output shape from the EXECUTE stage (partial — lacks `item`). */\nexport type ExecuteOutput = {\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n};\n\n/** Full execution result assembled downstream (LLM output + context). */\nexport interface ExecutionResult {\n\titem: TriagedItem;\n\toutcome: \"success\" | \"failure\" | \"partial\";\n\tdetail: string;\n}\n\n/** Whether an error is self-correctable (fast-retry) or structural (full loop). */\nexport type ErrorClass = \"self-correctable\" | \"structural\";\n\n/** Classifier for fast-retry path. */\nexport type ErrorClassifier = (result: ExecutionResult) => ErrorClass;\n\n/** Default error classifier: parse/config errors are self-correctable. */\nexport function defaultErrorClassifier(result: ExecutionResult): ErrorClass {\n\tconst d = result.detail.toLowerCase();\n\tif (\n\t\td.includes(\"parse\") ||\n\t\td.includes(\"json\") ||\n\t\td.includes(\"config\") ||\n\t\td.includes(\"validation\") ||\n\t\td.includes(\"syntax\")\n\t) {\n\t\treturn \"self-correctable\";\n\t}\n\treturn \"structural\";\n}\n\n// ---------------------------------------------------------------------------\n// Verification output\n// ---------------------------------------------------------------------------\n\n/** Result of the VERIFY stage. */\nexport interface VerifyResult {\n\titem: TriagedItem;\n\texecution: ExecutionResult;\n\tverified: boolean;\n\tfindings: string[];\n\terrorClass?: ErrorClass;\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/** Configurable signals for priority scoring. */\nexport interface PrioritySignals {\n\t/** Per-severity base weight (default: critical=100, high=70, medium=40, low=10). */\n\tseverityWeights?: Partial<Record<Severity, number>>;\n\t/** Decay rate per second for attention decay (default ~1.15e-6 ≈ 7-day half-life). */\n\tdecayRate?: number;\n\t/** Strategy model effectiveness boost threshold (default 0.7). */\n\teffectivenessThreshold?: number;\n\t/** Strategy model effectiveness boost amount (default 15). */\n\teffectivenessBoost?: number;\n}\n\n/** Default severity weights. */\nexport const DEFAULT_SEVERITY_WEIGHTS: Record<Severity, number> = {\n\tcritical: 100,\n\thigh: 70,\n\tmedium: 40,\n\tlow: 10,\n};\n\n/** Default decay rate: ~7-day half-life. */\nexport const DEFAULT_DECAY_RATE = Math.LN2 / (7 * 24 * 3600);\n\n// ---------------------------------------------------------------------------\n// Harness loop configuration\n// ---------------------------------------------------------------------------\n\n/** Per-queue configuration in the harness loop. */\nexport interface QueueConfig {\n\t/** Whether this queue is gated (requires human approval). */\n\tgated: boolean;\n\t/** Maximum pending items in the gate (default Infinity). */\n\tmaxPending?: number;\n\t/** Start the gate in open (auto-approve) mode? */\n\tstartOpen?: boolean;\n}\n\n/** Default queue configurations. */\nexport const DEFAULT_QUEUE_CONFIGS: Record<QueueRoute, QueueConfig> = {\n\t\"auto-fix\": { gated: false },\n\t\"needs-decision\": { gated: true },\n\tinvestigation: { gated: true },\n\tbacklog: { gated: false, startOpen: false },\n};\n\n/** Options for {@link harnessLoop}. */\nexport interface HarnessLoopOptions {\n\t/** LLM adapter for promptNode-based stages (triage, execute, verify, reflect). */\n\tadapter: unknown; // LLMAdapter — kept as unknown to avoid circular dep\n\n\t/** Custom triage prompt (receives IntakeItem + strategy model as context). */\n\ttriagePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom execute prompt. */\n\texecutePrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Custom verify prompt. */\n\tverifyPrompt?: string | ((...args: unknown[]) => string);\n\n\t/** Per-queue configuration overrides. */\n\tqueues?: Partial<Record<QueueRoute, QueueConfig>>;\n\n\t/** Priority scoring signals. */\n\tpriority?: PrioritySignals;\n\n\t/** Error classifier for fast-retry path. */\n\terrorClassifier?: ErrorClassifier;\n\n\t/** Max fast-retries per item before routing to full intake (default 2). */\n\tmaxRetries?: number;\n\n\t/** Global retry cap across all items — circuit breaker (default maxRetries × 10). */\n\tmaxTotalRetries?: number;\n\n\t/** Max re-ingestions from verify→intake before giving up (default 1). */\n\tmaxReingestions?: number;\n\n\t/** Global reingestion cap across all items — circuit breaker (default maxReingestions × 10). */\n\tmaxTotalReingestions?: number;\n\n\t/** Retained limit for topic logs (default 1000). */\n\tretainedLimit?: number;\n}\n","/**\n * Strategy model and priority scoring (roadmap §9.0).\n *\n * Pure-computation derived nodes — no LLM, no async.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { Node } from \"../../core/node.js\";\nimport { derived } from \"../../core/sugar.js\";\nimport { reactiveMap } from \"../../extra/reactive-map.js\";\nimport { decay } from \"../memory.js\";\n\nimport {\n\tDEFAULT_DECAY_RATE,\n\tDEFAULT_SEVERITY_WEIGHTS,\n\ttype Intervention,\n\ttype PrioritySignals,\n\ttype RootCause,\n\ttype StrategyEntry,\n\ttype StrategyKey,\n\tstrategyKey,\n\ttype TriagedItem,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Strategy model\n// ---------------------------------------------------------------------------\n\n/** Snapshot shape for the strategy model node. */\nexport type StrategySnapshot = ReadonlyMap<StrategyKey, StrategyEntry>;\n\n/** Bundle returned by {@link strategyModel}. */\nexport interface StrategyModelBundle {\n\t/** Reactive node — current strategy map. */\n\treadonly node: Node<StrategySnapshot>;\n\n\t/** Record a completed issue (success or failure). */\n\trecord(rootCause: RootCause, intervention: Intervention, success: boolean): void;\n\n\t/** Look up effectiveness for a specific pair. */\n\tlookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined;\n\n\t/** Tear down internal keepalive subscriptions. */\n\tdispose(): void;\n}\n\n/**\n * Create a strategy model that tracks `rootCause × intervention → successRate`\n * over completed issues. Pure derived computation — no LLM.\n *\n * The model feeds back into TRIAGE for routing hints.\n */\nexport function strategyModel(): StrategyModelBundle {\n\tconst _map = reactiveMap<StrategyKey, StrategyEntry>({ name: \"strategy-entries\" });\n\n\t// Derived node that projects the reactive map into a plain Map snapshot.\n\tconst snapshot = derived<StrategySnapshot>(\n\t\t[_map.entries],\n\t\t([mapSnap]) => {\n\t\t\tconst raw = mapSnap as ReadonlyMap<StrategyKey, StrategyEntry>;\n\t\t\t// Return a fresh frozen copy so consumers see a stable reference.\n\t\t\treturn new Map(raw);\n\t\t},\n\t\t{\n\t\t\tname: \"strategy-model\",\n\t\t\tequals: (a, b) => {\n\t\t\t\tconst am = a as StrategySnapshot;\n\t\t\t\tconst bm = b as StrategySnapshot;\n\t\t\t\tif (am.size !== bm.size) return false;\n\t\t\t\tfor (const [k, v] of am) {\n\t\t\t\t\tconst bv = bm.get(k);\n\t\t\t\t\tif (!bv || v.attempts !== bv.attempts || v.successes !== bv.successes) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t},\n\t\t},\n\t);\n\n\tfunction record(rootCause: RootCause, intervention: Intervention, success: boolean): void {\n\t\tconst key = strategyKey(rootCause, intervention);\n\t\tconst existing = _map.get(key);\n\t\tconst attempts = (existing?.attempts ?? 0) + 1;\n\t\tconst successes = (existing?.successes ?? 0) + (success ? 1 : 0);\n\t\t_map.set(key, {\n\t\t\trootCause,\n\t\t\tintervention,\n\t\t\tattempts,\n\t\t\tsuccesses,\n\t\t\tsuccessRate: successes / attempts,\n\t\t});\n\t}\n\n\tfunction lookup(rootCause: RootCause, intervention: Intervention): StrategyEntry | undefined {\n\t\treturn _map.get(strategyKey(rootCause, intervention));\n\t}\n\n\t// Keep the derived alive so get() works without an external subscriber.\n\tconst _unsub = snapshot.subscribe(() => {});\n\n\tfunction dispose(): void {\n\t\t_unsub();\n\t}\n\n\treturn { node: snapshot, record, lookup, dispose };\n}\n\n// ---------------------------------------------------------------------------\n// Priority scoring\n// ---------------------------------------------------------------------------\n\n/**\n * Create a priority scoring derived node for a single triaged item.\n *\n * Combines severity weight, attention decay, strategy model effectiveness,\n * and an optional external urgency signal.\n *\n * @param item - Node holding the triaged item.\n * @param strategy - Strategy model node.\n * @param lastInteractionNs - Node holding the monotonic timestamp (ns) of last human interaction.\n * @param urgency - Optional external urgency signal node (0–1 scale).\n * @param signals - Configurable scoring parameters.\n */\nexport function priorityScore(\n\titem: Node<TriagedItem>,\n\tstrategy: Node<StrategySnapshot>,\n\tlastInteractionNs: Node<number>,\n\turgency?: Node<number>,\n\tsignals?: PrioritySignals,\n): Node<number> {\n\tconst severityWeights = { ...DEFAULT_SEVERITY_WEIGHTS, ...signals?.severityWeights };\n\tconst decayRate = signals?.decayRate ?? DEFAULT_DECAY_RATE;\n\tconst effectivenessThreshold = signals?.effectivenessThreshold ?? 0.7;\n\tconst effectivenessBoost = signals?.effectivenessBoost ?? 15;\n\n\tconst deps: Node<unknown>[] = [item, strategy, lastInteractionNs];\n\tif (urgency) deps.push(urgency);\n\n\treturn derived<number>(\n\t\tdeps,\n\t\t(values) => {\n\t\t\tconst itm = values[0] as TriagedItem;\n\t\t\tconst strat = values[1] as StrategySnapshot;\n\t\t\tconst lastNs = values[2] as number;\n\t\t\tconst urg = urgency ? (values[3] as number) : 0;\n\n\t\t\t// Base score from severity\n\t\t\tconst baseWeight = severityWeights[itm.severity ?? \"medium\"];\n\t\t\tconst ageSeconds = (monotonicNs() - lastNs) / 1e9;\n\t\t\tlet score = decay(baseWeight, ageSeconds, decayRate, 0);\n\n\t\t\t// Strategy model boost\n\t\t\tconst key = strategyKey(itm.rootCause, itm.intervention);\n\t\t\tconst entry = strat.get(key);\n\t\t\tif (entry && entry.successRate >= effectivenessThreshold) {\n\t\t\t\tscore += effectivenessBoost;\n\t\t\t}\n\n\t\t\t// External urgency boost (0–1 scale → 0–20 points)\n\t\t\tscore += urg * 20;\n\n\t\t\treturn score;\n\t\t},\n\t\t{ name: \"priority-score\" },\n\t);\n}\n","/**\n * harnessLoop() factory (roadmap §9.0).\n *\n * Wires the static 7-stage topology: INTAKE → TRIAGE → QUEUE → GATE →\n * EXECUTE → VERIFY → REFLECT. Static topology, flowing data — the Kafka\n * insight applied to human+LLM collaboration.\n *\n * @module\n */\n\nimport type { Node } from \"../../core/node.js\";\nimport { node } from \"../../core/node.js\";\nimport { effect, state } from \"../../core/sugar.js\";\nimport { merge, withLatestFrom } from \"../../extra/operators.js\";\nimport { Graph } from \"../../graph/graph.js\";\nimport { trackingKey, tryIncrementBounded } from \"../_internal.js\";\nimport type { LLMAdapter } from \"../ai.js\";\nimport { promptNode } from \"../ai.js\";\nimport { TopicGraph } from \"../messaging.js\";\nimport { type GateController, gate } from \"../orchestration.js\";\nimport { type StrategyModelBundle, type StrategySnapshot, strategyModel } from \"./strategy.js\";\nimport {\n\tDEFAULT_QUEUE_CONFIGS,\n\tdefaultErrorClassifier,\n\ttype ErrorClass,\n\ttype ErrorClassifier,\n\ttype ExecuteOutput,\n\ttype ExecutionResult,\n\ttype HarnessLoopOptions,\n\ttype IntakeItem,\n\tQUEUE_NAMES,\n\ttype QueueConfig,\n\ttype QueueRoute,\n\ttype TriagedItem,\n\ttype VerifyResult,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Default prompts\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TRIAGE_PROMPT = `You are a triage classifier for a reactive collaboration harness.\n\nGiven an intake item, classify it and output JSON:\n{\n \"rootCause\": \"composition\" | \"missing-fn\" | \"bad-docs\" | \"schema-gap\" | \"regression\" | \"unknown\",\n \"intervention\": \"template\" | \"catalog-fn\" | \"docs\" | \"wrapper\" | \"schema-change\" | \"investigate\",\n \"route\": \"auto-fix\" | \"needs-decision\" | \"investigation\" | \"backlog\",\n \"priority\": <number 0-100>,\n \"triageReasoning\": \"<one sentence>\"\n}\n\nStrategy model (past effectiveness):\n{{strategy}}\n\nIntake item:\n{{item}}`;\n\nconst DEFAULT_EXECUTE_PROMPT = `You are an implementation agent.\n\nGiven a triaged issue with root cause and intervention type, produce a fix.\n\nIssue:\n{{item}}\n\nOutput JSON:\n{\n \"outcome\": \"success\" | \"failure\" | \"partial\",\n \"detail\": \"<description of what was done or what failed>\"\n}`;\n\nconst DEFAULT_VERIFY_PROMPT = `You are a QA reviewer.\n\nGiven an execution result, verify whether the fix is correct.\n\nExecution:\n{{execution}}\n\nOriginal issue:\n{{item}}\n\nOutput JSON:\n{\n \"verified\": true/false,\n \"findings\": [\"<finding1>\", ...],\n \"errorClass\": \"self-correctable\" | \"structural\" // only if verified=false\n}`;\n\n// ---------------------------------------------------------------------------\n// HarnessGraph\n// ---------------------------------------------------------------------------\n\n/** The graph returned by {@link harnessLoop}. */\nexport class HarnessGraph extends Graph {\n\t/** Intake topic — publish items here to enter the loop. */\n\treadonly intake: TopicGraph<IntakeItem>;\n\n\t/** Per-route queue topics. */\n\treadonly queues: ReadonlyMap<QueueRoute, TopicGraph<TriagedItem>>;\n\n\t/** Per-route gate controllers (only for gated queues). */\n\treadonly gates: ReadonlyMap<QueueRoute, GateController<TriagedItem>>;\n\n\t/** Strategy model bundle — record outcomes, lookup effectiveness. */\n\treadonly strategy: StrategyModelBundle;\n\n\t/** Verify results topic — subscribe to see verification outcomes. */\n\treadonly verifyResults: TopicGraph<VerifyResult>;\n\n\t/** Global retry count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalRetries: Node<number>;\n\n\t/** Global reingestion count across all items (circuit breaker). Reactive — subscribable. */\n\treadonly totalReingestions: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tintake: TopicGraph<IntakeItem>,\n\t\tqueues: Map<QueueRoute, TopicGraph<TriagedItem>>,\n\t\tgates: Map<QueueRoute, GateController<TriagedItem>>,\n\t\tstrategy: StrategyModelBundle,\n\t\tverifyResults: TopicGraph<VerifyResult>,\n\t\ttotalRetries: Node<number>,\n\t\ttotalReingestions: Node<number>,\n\t) {\n\t\tsuper(name);\n\t\tthis.intake = intake;\n\t\tthis.queues = queues;\n\t\tthis.gates = gates;\n\t\tthis.strategy = strategy;\n\t\tthis.verifyResults = verifyResults;\n\t\tthis.totalRetries = totalRetries;\n\t\tthis.totalReingestions = totalReingestions;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// harnessLoop factory\n// ---------------------------------------------------------------------------\n\n/**\n * Wire the reactive collaboration loop as a static-topology graph.\n *\n * The loop has 7 stages:\n * 1. **INTAKE** — items arrive from multiple sources via `intake.publish()`\n * 2. **TRIAGE** — promptNode classifies, routes, and prioritizes\n * 3. **QUEUE** — 4 priority-ordered TopicGraphs (auto-fix, needs-decision, investigation, backlog)\n * 4. **GATE** — human approval on configurable queues\n * 5. **EXECUTE** — promptNode or human implements the fix\n * 6. **VERIFY** — promptNode reviews + optional fast-retry\n * 7. **REFLECT** — strategy model records outcomes\n *\n * @param name - Graph name.\n * @param opts - Configuration.\n * @returns HarnessGraph with controller accessors.\n */\nexport function harnessLoop(name: string, opts: HarnessLoopOptions): HarnessGraph {\n\tconst adapter = opts.adapter as LLMAdapter;\n\tconst maxRetries = opts.maxRetries ?? 2;\n\tconst retainedLimit = opts.retainedLimit ?? 1000;\n\tconst errorClassifier: ErrorClassifier = opts.errorClassifier ?? defaultErrorClassifier;\n\n\t// Merge queue configs with defaults\n\tconst queueConfigs = new Map<QueueRoute, QueueConfig>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueConfigs.set(route, {\n\t\t\t...DEFAULT_QUEUE_CONFIGS[route],\n\t\t\t...opts.queues?.[route],\n\t\t});\n\t}\n\n\t// --- Stage 1: INTAKE ---\n\tconst intake = new TopicGraph<IntakeItem>(\"intake\", { retainedLimit });\n\n\t// --- Strategy model (used by triage + reflect) ---\n\tconst strategy = strategyModel();\n\n\t// --- Stage 2: TRIAGE ---\n\t// Strategy context uses withLatestFrom: intake.latest is the reactive trigger,\n\t// strategy.node is sampled without being a trigger. This breaks the feedback\n\t// cycle (verify → strategy.record() → strategy.node) reactively — strategy\n\t// changes don't re-fire triage, only new intake items do.\n\tconst triageInput = withLatestFrom(\n\t\tintake.latest as Node<unknown>,\n\t\tstrategy.node as Node<unknown>,\n\t);\n\n\tconst triageNode = promptNode<TriagedItem>(\n\t\tadapter,\n\t\t[triageInput as Node<unknown>],\n\t\topts.triagePrompt ??\n\t\t\t((pair: unknown) => {\n\t\t\t\tconst [item, strat] = pair as [unknown, StrategySnapshot];\n\t\t\t\t// Empty text → promptNode's SENTINEL gate skips the LLM call.\n\t\t\t\tif (!item) return \"\";\n\t\t\t\treturn DEFAULT_TRIAGE_PROMPT.replace(\n\t\t\t\t\t\"{{strategy}}\",\n\t\t\t\t\tJSON.stringify(Array.from(strat.entries())),\n\t\t\t\t).replace(\"{{item}}\", JSON.stringify(item));\n\t\t\t}),\n\t\t{\n\t\t\tname: \"triage\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Stage 3: QUEUE ---\n\tconst queueTopics = new Map<QueueRoute, TopicGraph<TriagedItem>>();\n\tfor (const route of QUEUE_NAMES) {\n\t\tqueueTopics.set(route, new TopicGraph<TriagedItem>(`queue/${route}`, { retainedLimit }));\n\t}\n\n\t// Router: merge intake fields into triage classification before routing to queue.\n\t// The LLM only returns {rootCause, intervention, route, priority} — the router\n\t// pairs it with the original intake item (summary, evidence, etc.).\n\t// Sample triageInput (not intake.latest) — triageInput holds the [item, strategy]\n\t// pair that *triggered* this specific triage, so we get the correct item even if\n\t// a newer intake item has arrived since. triageNode triggers; triageInput sampled.\n\tconst routerInput = withLatestFrom(triageNode as Node<unknown>, triageInput as Node<unknown>);\n\tconst router = effect([routerInput as Node<unknown>], ([pair]) => {\n\t\tif (pair == null) return;\n\t\tconst [classification, triagePair] = pair as [\n\t\t\tTriagedItem | null,\n\t\t\t[IntakeItem | null, StrategySnapshot] | null,\n\t\t];\n\t\tif (!classification || !classification.route) return;\n\t\tconst intakeItem = triagePair?.[0];\n\t\tconst merged: TriagedItem = { ...intakeItem, ...classification };\n\t\tconst topic = queueTopics.get(merged.route);\n\t\tif (topic) topic.publish(merged);\n\t});\n\tconst routerUnsub = router.subscribe(() => {});\n\n\t// --- Stage 4: GATE ---\n\t// Create a container graph for gates (gate() requires a Graph to register nodes in)\n\tconst gateGraph = new Graph(\"gates\");\n\tconst gateControllers = new Map<QueueRoute, GateController<TriagedItem>>();\n\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tconst topic = queueTopics.get(route)!;\n\n\t\tif (config.gated) {\n\t\t\t// Register the topic's latest node in the gate graph so gate() can resolve it\n\t\t\tgateGraph.add(`${route}/source`, topic.latest as Node<unknown>);\n\t\t\tconst ctrl = gate<TriagedItem>(gateGraph, `${route}/gate`, `${route}/source`, {\n\t\t\t\tmaxPending: config.maxPending,\n\t\t\t\tstartOpen: config.startOpen,\n\t\t\t});\n\t\t\tgateControllers.set(route, ctrl);\n\t\t}\n\t}\n\n\t// --- Stage 5: EXECUTE ---\n\t// Merge all gate outputs + ungated queue latests + retry feedback into a\n\t// single execute input using the merge() operator (no imperative .down()).\n\tconst retryTopic = new TopicGraph<TriagedItem>(\"retry-input\", { retainedLimit });\n\n\tconst queueOutputs: Node<TriagedItem | null>[] = [];\n\tfor (const route of QUEUE_NAMES) {\n\t\tconst config = queueConfigs.get(route)!;\n\t\tif (config.gated && gateControllers.has(route)) {\n\t\t\tqueueOutputs.push(gateControllers.get(route)!.node as Node<TriagedItem | null>);\n\t\t} else {\n\t\t\tqueueOutputs.push(queueTopics.get(route)!.latest as Node<TriagedItem | null>);\n\t\t}\n\t}\n\tqueueOutputs.push(retryTopic.latest as Node<TriagedItem | null>);\n\n\tconst executeInput = merge<TriagedItem | null>(...queueOutputs);\n\n\tconst executeNode = promptNode<ExecuteOutput>(\n\t\tadapter,\n\t\t[executeInput as Node<unknown>],\n\t\topts.executePrompt ??\n\t\t\t((item: unknown) => DEFAULT_EXECUTE_PROMPT.replace(\"{{item}}\", JSON.stringify(item))),\n\t\t{\n\t\t\tname: \"execute\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Execute context: [execOutput, item] captured once per execute-wave ---\n\t//\n\t// executeInput feeds into executeNode (dep) AND later into verifyNode (dep).\n\t// Without this node, verifyNode would fire twice per wave in the retry path:\n\t// once when executeNode settles (with stale item from prevData), and once when\n\t// executeInput delivers the retry item directly. The second fire would pair the\n\t// correct item with a verify output that was computed using the wrong item.\n\t//\n\t// withLatestFrom(executeNode, executeInput) fires exactly once per execute-wave:\n\t// executeInput notifies executeNode first (depth-first), executeNode runs fn and\n\t// settles in executeContextNode.dep[0], then executeInput settles in dep[1].\n\t// dirtyDepCount reaches 0 only after both settle → fn runs once with correct data.\n\tconst executeContextNode = withLatestFrom(\n\t\texecuteNode as Node<unknown>,\n\t\texecuteInput as Node<unknown>,\n\t);\n\n\t// --- Stage 6: VERIFY ---\n\tconst verifyResults = new TopicGraph<VerifyResult>(\"verify-results\", { retainedLimit });\n\n\t// The LLM returns only {verified, findings, errorClass?}. We type the promptNode\n\t// output as the partial shape and assemble the full VerifyResult downstream.\n\ttype VerifyOutput = { verified: boolean; findings: string[]; errorClass?: ErrorClass };\n\n\t// verifyNode depends on executeContextNode ([execOutput, item]) — single dep.\n\t// This ensures verifyNode fires once per execute-wave with the correct item.\n\tconst verifyNode = promptNode<VerifyOutput>(\n\t\tadapter,\n\t\t[executeContextNode as Node<unknown>],\n\t\topts.verifyPrompt ??\n\t\t\t((ctxPair: unknown) => {\n\t\t\t\tconst [execution, item] = ctxPair as [ExecuteOutput | null, unknown];\n\t\t\t\treturn DEFAULT_VERIFY_PROMPT.replace(\"{{execution}}\", JSON.stringify(execution)).replace(\n\t\t\t\t\t\"{{item}}\",\n\t\t\t\t\tJSON.stringify(item),\n\t\t\t\t);\n\t\t\t}),\n\t\t{\n\t\t\tname: \"verify\",\n\t\t\tformat: \"json\",\n\t\t\tretries: 1,\n\t\t},\n\t);\n\n\t// --- Fast-retry path ---\n\t// verifyContext = withLatestFrom(verifyNode, executeContextNode):\n\t// [verifyOutput, [execOutput, item]]\n\t// Fires once when verifyNode settles; executeContextNode is sampled as secondary.\n\tconst verifyContext = withLatestFrom(\n\t\tverifyNode as Node<unknown>,\n\t\texecuteContextNode as Node<unknown>,\n\t);\n\n\tconst maxReingestions = opts.maxReingestions ?? 1;\n\tconst maxTotalRetries = Math.min(opts.maxTotalRetries ?? maxRetries * 10, 100);\n\tconst maxTotalReingestions = Math.min(opts.maxTotalReingestions ?? maxReingestions * 10, 100);\n\tconst totalRetries = state(0);\n\tconst totalReingestions = state(0);\n\n\t// Uses shared `tryIncrementBounded` (patterns/_internal.ts) — documented\n\t// P3 exception for self-owned counters read+written from a single call\n\t// site (`fastRetry` effect below).\n\n\t// Use raw node() so we can check batchData[0] directly — effect() falls back\n\t// to ctx.prevData[0] when verifyContext emits RESOLVED (secondary-only wave),\n\t// which would re-fire with stale context and create phantom retries.\n\tconst fastRetry = node([verifyContext as Node<unknown>], (batchData, _actions) => {\n\t\tconst batch = batchData[0];\n\t\tif (batch == null || batch.length === 0) return; // RESOLVED or not involved — skip\n\t\tconst ctxVal = batch[batch.length - 1];\n\t\tif (ctxVal == null) return;\n\t\t// verifyContext shape: [verifyOutput, [execOutput, item]]\n\t\tconst [vo, execCtx] = ctxVal as [\n\t\t\tVerifyOutput | null,\n\t\t\t[ExecuteOutput | null, TriagedItem | null] | null,\n\t\t];\n\t\tconst [execRaw, item] = execCtx ?? [null, null];\n\t\tif (!vo || !item) return;\n\n\t\t// Assemble full ExecutionResult + VerifyResult from LLM outputs + context\n\t\tconst exec: ExecutionResult = {\n\t\t\titem,\n\t\t\toutcome: execRaw?.outcome ?? \"failure\",\n\t\t\tdetail: execRaw?.detail ?? \"unknown\",\n\t\t};\n\t\tconst vr: VerifyResult = {\n\t\t\titem,\n\t\t\texecution: exec,\n\t\t\tverified: vo.verified,\n\t\t\tfindings: vo.findings ?? [],\n\t\t\terrorClass: vo.errorClass,\n\t\t};\n\n\t\tif (vr.verified) {\n\t\t\tstrategy.record(item.rootCause, item.intervention, true);\n\t\t\tverifyResults.publish(vr);\n\t\t\treturn;\n\t\t}\n\n\t\t// Failed verification\n\t\tconst errClass =\n\t\t\tvr.errorClass ??\n\t\t\terrorClassifier({\n\t\t\t\titem,\n\t\t\t\toutcome: \"failure\",\n\t\t\t\tdetail: vr.findings.join(\"; \"),\n\t\t\t});\n\n\t\tconst itemRetries = item._retries ?? 0;\n\n\t\tif (\n\t\t\terrClass === \"self-correctable\" &&\n\t\t\titemRetries < maxRetries &&\n\t\t\ttryIncrementBounded(totalRetries, maxTotalRetries)\n\t\t) {\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst retryItem: TriagedItem = {\n\t\t\t\t...item,\n\t\t\t\t_retries: itemRetries + 1,\n\t\t\t\tsummary: `[RETRY ${itemRetries + 1}/${maxRetries}] ${key} — Previous attempt failed: ${vr.findings.join(\"; \")}`,\n\t\t\t\trelatedTo: [key],\n\t\t\t};\n\t\t\tretryTopic.publish(retryItem);\n\t\t} else {\n\t\t\t// Structural failure or max retries exceeded → full loop via INTAKE\n\t\t\tstrategy.record(item.rootCause, item.intervention, false);\n\t\t\tverifyResults.publish(vr);\n\n\t\t\tconst key = trackingKey(item);\n\t\t\tconst itemReingestions = item._reingestions ?? 0;\n\t\t\tif (\n\t\t\t\titemReingestions < maxReingestions &&\n\t\t\t\ttryIncrementBounded(totalReingestions, maxTotalReingestions)\n\t\t\t) {\n\t\t\t\tintake.publish({\n\t\t\t\t\tsource: \"eval\",\n\t\t\t\t\tsummary: `Verification failed for: ${key}`,\n\t\t\t\t\tevidence: vr.findings.join(\"\\n\"),\n\t\t\t\t\taffectsAreas: item.affectsAreas,\n\t\t\t\t\taffectsEvalTasks: item.affectsEvalTasks,\n\t\t\t\t\tseverity: \"high\",\n\t\t\t\t\trelatedTo: [key],\n\t\t\t\t\t_reingestions: itemReingestions + 1,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\tconst fastRetryUnsub = fastRetry.subscribe(() => {}); // keepalive (COMPOSITION-GUIDE §1)\n\n\t// --- Stage 7: REFLECT ---\n\t// Strategy model is already updated in the fast-retry/verify effect above.\n\t// Hypothesis generation and memory distillation are pluggable extensions\n\t// wired externally via verifyResults topic subscription — not hardcoded here.\n\n\t// --- Assemble HarnessGraph ---\n\tconst harness = new HarnessGraph(\n\t\tname,\n\t\tintake,\n\t\tqueueTopics,\n\t\tgateControllers,\n\t\tstrategy,\n\t\tverifyResults,\n\t\ttotalRetries,\n\t\ttotalReingestions,\n\t);\n\n\t// Register disposers for unregistered internal nodes (D1/D2 fix)\n\tharness.addDisposer(routerUnsub);\n\tharness.addDisposer(fastRetryUnsub);\n\tharness.addDisposer(strategy.dispose);\n\n\t// Register stage nodes for introspection (harnessTrace, describe, observe)\n\tharness.add(\"triage\", triageNode as Node<unknown>);\n\tharness.add(\"execute\", executeNode as Node<unknown>);\n\tharness.add(\"verify\", verifyNode as Node<unknown>);\n\tharness.add(\"strategy\", strategy.node as Node<unknown>);\n\n\t// Mount subgraphs\n\tharness.mount(\"intake\", intake);\n\tfor (const [route, topic] of queueTopics) {\n\t\tharness.mount(`queue/${route}`, topic);\n\t}\n\tharness.mount(\"gates\", gateGraph);\n\tharness.mount(\"retry-input\", retryTopic);\n\tharness.mount(\"verify-results\", verifyResults);\n\n\treturn harness;\n}\n","/**\n * Harness-specific graph profiling (roadmap §9.0).\n *\n * Extends {@link graphProfile} with harness domain counters:\n * queue depths, strategy entries, retry/reingestion tracker sizes.\n *\n * @module\n */\n\nimport {\n\ttype GraphProfileOptions,\n\ttype GraphProfileResult,\n\tgraphProfile,\n} from \"../../graph/profile.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport type { QueueRoute } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Harness-specific profile extending the base graph profile. */\nexport interface HarnessProfileResult extends GraphProfileResult {\n\t/** Per-queue retained item counts. */\n\tqueueDepths: Record<QueueRoute, number>;\n\t/** Number of rootCause→intervention entries in the strategy model. */\n\tstrategyEntries: number;\n\t/** Global retry count across all items. */\n\ttotalRetries: number;\n\t/** Global reingestion count across all items. */\n\ttotalReingestions: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a harness graph with domain-specific counters.\n *\n * @param harness - The HarnessGraph to profile.\n * @param opts - Optional base profile options.\n * @returns Harness profile with queue depths, strategy stats, and tracker sizes.\n */\nexport function harnessProfile(\n\tharness: HarnessGraph,\n\topts?: GraphProfileOptions,\n): HarnessProfileResult {\n\tconst base = graphProfile(harness, opts);\n\n\tconst queueDepths: Record<string, number> = {};\n\tfor (const [route, topic] of harness.queues) {\n\t\tqueueDepths[route] = topic.retained().length;\n\t}\n\n\treturn {\n\t\t...base,\n\t\tqueueDepths: queueDepths as Record<QueueRoute, number>,\n\t\tstrategyEntries: harness.strategy.node.cache?.size ?? 0,\n\t\ttotalRetries: harness.totalRetries.cache ?? 0,\n\t\ttotalReingestions: harness.totalReingestions.cache ?? 0,\n\t};\n}\n","/**\n * Harness pipeline trace (roadmap §9.0 — Inspection Tool Consolidation).\n *\n * Attaches reactive observers (via `observe()`) to all harness stages.\n * One call gives full pipeline visibility with stage labels and elapsed\n * timestamps relative to the `harnessTrace()` invocation time.\n *\n * Supports two output modes:\n * - **String logger** (default): rendered lines to `console.log` or a custom sink.\n * - **Structured events**: programmatic `TraceEvent[]` list for test assertions\n * and tooling. Access via `handle.events`.\n *\n * Supports configurable detail levels (`\"summary\"`, `\"standard\"`, `\"full\"`)\n * to control output verbosity without composing different tool calls.\n *\n * @module\n */\n\nimport { monotonicNs } from \"../../core/clock.js\";\nimport type { ObserveResult } from \"../../graph/graph.js\";\nimport type { HarnessGraph } from \"./loop.js\";\nimport { QUEUE_NAMES } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Event type captured by structured trace. */\nexport type TraceEventType = \"data\" | \"error\" | \"complete\";\n\n/** A single structured trace event. */\nexport interface TraceEvent {\n\t/** Elapsed seconds since trace was created. */\n\telapsed: number;\n\t/** Pipeline stage label (INTAKE, TRIAGE, QUEUE, GATE, EXECUTE, VERIFY, STRATEGY). */\n\tstage: string;\n\t/** Event type. */\n\ttype: TraceEventType;\n\t/** Data payload (present for \"data\" and \"error\" events). Omitted at \"summary\" detail. */\n\tdata?: unknown;\n\t/** Human-readable summary of the data. Present at \"standard\" and \"full\" detail. */\n\tsummary?: string;\n}\n\n/** Detail level for trace output. */\nexport type TraceDetail =\n\t/** Stage + elapsed only. No data preview. Lowest overhead. */\n\t| \"summary\"\n\t/** Stage + elapsed + truncated data preview. Default. */\n\t| \"standard\"\n\t/** Stage + elapsed + full raw data. Use for debugging, not production. */\n\t| \"full\";\n\n/** Handle returned by {@link harnessTrace}. Call `dispose()` to stop tracing. */\nexport interface HarnessTraceHandle {\n\t/** Stop tracing and detach all observers. Safe to call multiple times. */\n\tdispose(): void;\n\t/**\n\t * Structured trace events collected since creation. Plain array — no\n\t * subscription needed (COMPOSITION-GUIDE §1: avoid lazy-activation\n\t * friction for inspection tools). Populated reactively via observe().\n\t */\n\treadonly events: readonly TraceEvent[];\n}\n\n/** Options for {@link harnessTrace}. */\nexport interface HarnessTraceOptions {\n\t/** Sink for rendered trace lines. Default: `console.log`. */\n\tlogger?: (line: string) => void;\n\t/** Detail level for both string and structured output. Default: `\"summary\"`. */\n\tdetail?: TraceDetail;\n}\n\n// ---------------------------------------------------------------------------\n// Stage labels\n// ---------------------------------------------------------------------------\n\n/** Observe paths → stage labels for the 7 harness stages. */\nconst STAGE_LABELS: Record<string, string> = {\n\t\"intake::latest\": \"INTAKE\",\n\ttriage: \"TRIAGE\",\n\texecute: \"EXECUTE\",\n\t\"verify-results::latest\": \"VERIFY\",\n\tstrategy: \"STRATEGY\",\n};\n\nfor (const route of QUEUE_NAMES) {\n\tSTAGE_LABELS[`queue/${route}::latest`] = \"QUEUE\";\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Attach reactive trace observers to all harness pipeline stages.\n *\n * Wires `graph.observe(path, { format: \"json\" })` to each stage node,\n * intercepting the logger callback to emit stage-labeled lines with\n * elapsed timestamps. Surfaces DATA, ERROR, and COMPLETE events.\n *\n * **Structured events:** Every trace event is also pushed to\n * `handle.events` — a plain array (not a reactive node) that tests and\n * tooling can inspect programmatically. To use structured events alone\n * without string output, pass `{ logger: null }`.\n *\n * **Detail levels:**\n * - `\"summary\"` — stage + elapsed only. Minimal overhead.\n * - `\"standard\"` (default) — stage + elapsed + truncated data preview.\n * - `\"full\"` — stage + elapsed + full raw data object in events.\n *\n * Elapsed timestamps are relative to the `harnessTrace()` invocation time,\n * not the first event.\n *\n * @param harness - The HarnessGraph to trace.\n * @param opts - Optional configuration.\n * @returns Handle with `dispose()` to stop tracing and `events` for structured access.\n */\nexport function harnessTrace(\n\tharness: HarnessGraph,\n\topts?: HarnessTraceOptions,\n): HarnessTraceHandle {\n\tconst logger = opts?.logger ?? console.log;\n\tconst detail: TraceDetail = opts?.detail ?? \"summary\";\n\tconst startNs = monotonicNs();\n\tconst observations: ObserveResult[] = [];\n\tconst events: TraceEvent[] = [];\n\n\tfunction elapsedSecs(): number {\n\t\treturn (monotonicNs() - startNs) / 1e9;\n\t}\n\n\tfunction elapsedStr(): string {\n\t\treturn elapsedSecs().toFixed(3);\n\t}\n\n\tfunction recordEvent(stage: string, type: TraceEventType, rawData: unknown): void {\n\t\tconst e = elapsedSecs();\n\t\tconst ev: TraceEvent = { elapsed: e, stage, type };\n\n\t\tif (detail !== \"summary\") {\n\t\t\tev.summary = summarize(rawData);\n\t\t}\n\t\tif (detail === \"full\") {\n\t\t\tev.data = rawData;\n\t\t}\n\n\t\tevents.push(ev);\n\t}\n\n\tfunction wireStage(path: string, stage: string): void {\n\t\ttry {\n\t\t\tconst obs = harness.observe(path, {\n\t\t\t\tformat: \"json\",\n\t\t\t\tlogger: (_line, event) => {\n\t\t\t\t\tif (event.type === \"data\") {\n\t\t\t\t\t\trecordEvent(stage, \"data\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tif (detail === \"summary\") {\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst dataStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ←${dataStr}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"error\") {\n\t\t\t\t\t\trecordEvent(stage, \"error\", event.data);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tconst errStr = event.data !== undefined ? ` ${summarize(event.data)}` : \"\";\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ✗${errStr}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (event.type === \"complete\") {\n\t\t\t\t\t\trecordEvent(stage, \"complete\", undefined);\n\t\t\t\t\t\tif (logger) {\n\t\t\t\t\t\t\tlogger(`[${elapsedStr()}s] ${stage.padEnd(9)} ■ complete`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tincludeTypes: [\"data\", \"error\", \"complete\"],\n\t\t\t});\n\t\t\tobservations.push(obs);\n\t\t} catch {\n\t\t\t// Node may not exist (e.g., queue route not mounted) — skip silently\n\t\t}\n\t}\n\n\t// Wire stage nodes (COMPOSITION-GUIDE §5: sinks before sources)\n\tfor (const [path, stage] of Object.entries(STAGE_LABELS)) {\n\t\twireStage(path, stage);\n\t}\n\n\t// Wire gate outputs per gated queue\n\tfor (const [gatedRoute] of harness.gates) {\n\t\twireStage(`gates::${gatedRoute}/gate`, \"GATE\");\n\t}\n\n\treturn {\n\t\tget events(): readonly TraceEvent[] {\n\t\t\treturn events;\n\t\t},\n\t\tdispose() {\n\t\t\tfor (const obs of observations) obs.dispose();\n\t\t\tobservations.length = 0;\n\t\t},\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction summarize(value: unknown): string {\n\tif (value == null) return \"null\";\n\tif (typeof value === \"string\") return truncate(value, 80);\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (typeof value === \"bigint\") return String(value);\n\ttry {\n\t\tconst json = JSON.stringify(value);\n\t\treturn truncate(json, 120);\n\t} catch {\n\t\treturn String(value);\n\t}\n}\n\nfunction truncate(s: string, max: number): string {\n\treturn s.length > max ? `${s.slice(0, max - 1)}…` : s;\n}\n","/**\n * Reactive graph observability (roadmap §9.0b — mid-level harness blocks).\n *\n * {@link graphLens} rides on any {@link Graph}, exposing four reactive\n * observability surfaces:\n *\n * - {@link LensGraph.stats} — `Node<TopologyStats>` recomputed on\n * structural change (transitive across mounted subgraphs). Named `stats`\n * rather than `topology` to avoid collision with the inherited\n * {@link Graph.topology} event stream on `LensGraph`.\n * - {@link LensGraph.health} — `Node<HealthReport>` flipping `ok=false`\n * when any node enters `\"errored\"` status, with `upstreamCause` walked\n * backward through deps.\n * - {@link LensGraph.flow} — `ReactiveMapBundle<string, FlowEntry>` (not a\n * plain snapshot node) tracking per-path DATA counts + `lastUpdate_ns`.\n * O(1) `get`/`has`/`size` queries; `.entries` node emits lazily only when\n * subscribed. Built on the shipped `reactiveMap` primitive.\n * - {@link LensGraph.why} — returns a live `Node<CausalChain>` from `from`\n * to `to`, reusing {@link reactiveExplainPath}.\n *\n * Everything is pure-reactive — no polling, no opinionated thresholds.\n * Callers who want periodic staleness checks or bottleneck classification\n * compose them explicitly with `fromTimer` + a derived node.\n *\n * The transitive topology-subscription helper lives in {@link watchTopologyTree}\n * (re-exported here for convenience; canonical source is `graph/topology-tree.ts`).\n *\n * @module\n */\nimport { monotonicNs } from \"../core/clock.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { type ReactiveMapBundle, reactiveMap } from \"../extra/reactive-map.js\";\nimport {\n\ttype CausalChain,\n\tGraph,\n\ttype GraphDescribeOutput,\n\ttype GraphOptions,\n\treachable,\n\twatchTopologyTree,\n} from \"../graph/index.js\";\nimport { domainMeta, keepalive } from \"./_internal.js\";\nimport { reactiveExplainPath } from \"./audit.js\";\n\nexport { watchTopologyTree } from \"../graph/index.js\";\n\n// ---------------------------------------------------------------------------\n// Payload types\n// ---------------------------------------------------------------------------\n\n/** Aggregate topology stats emitted by {@link LensGraph.stats}. */\nexport interface TopologyStats {\n\t/** Total primary nodes across this graph and all transitively mounted subgraphs. */\n\tnodeCount: number;\n\t/** Total directed edges (derived from deps; no duplicates). */\n\tedgeCount: number;\n\t/** Count of mounted subgraphs (transitive). */\n\tsubgraphCount: number;\n\t/** Qualified paths with no upstream deps (source nodes). Sorted. */\n\tsources: readonly string[];\n\t/** Qualified paths with no downstream consumers in-graph (sink nodes). Sorted. */\n\tsinks: readonly string[];\n\t/** Longest path from any source to any sink (in edges). `0` for empty graphs. */\n\tdepth: number;\n\t/** `true` if the dep DAG contains a cycle (feedback edge). */\n\thasCycles: boolean;\n}\n\n/** A single health problem entry. */\nexport interface HealthProblem {\n\tpath: string;\n\t/** V1 only reports `\"errored\"`. Future versions may add `\"completed\"`, `\"disconnected\"`. */\n\tstatus: \"errored\";\n\t/** First errored upstream ancestor along the dep chain, when one exists and is distinct from `path`. */\n\tupstreamCause?: string;\n}\n\n/** Aggregate health snapshot. `ok=true` iff `problems.length === 0`. */\nexport interface HealthReport {\n\tok: boolean;\n\tproblems: readonly HealthProblem[];\n}\n\n/** One per-path flow entry stored in {@link LensGraph.flow}. */\nexport interface FlowEntry {\n\tpath: string;\n\t/** Cumulative DATA emissions observed since the lens activated. */\n\tcount: number;\n\t/** `monotonicNs()` at the most recent DATA emission, or `null` if none yet. */\n\tlastUpdate_ns: number | null;\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for {@link graphLens}. */\nexport interface GraphLensOptions {\n\tname?: string;\n\tgraph?: GraphOptions;\n\t/**\n\t * Limit which node paths `flow` tracks. When omitted, every path in\n\t * `target.describe()` is observed. Recommended for graphs with hundreds\n\t * of nodes since each tracked path adds one observe-event dispatch per\n\t * DATA emission.\n\t */\n\tpathFilter?: (path: string) => boolean;\n\t/**\n\t * LRU cap on the {@link LensGraph.flow} map. When set, the flow tracker\n\t * evicts least-recently-used paths (by insertion / set order) once the\n\t * entry count exceeds this bound. Omit for unbounded (not recommended\n\t * for long-running graphs with churning paths). Passed through to the\n\t * underlying {@link reactiveMap}'s `maxSize`.\n\t */\n\tmaxFlowPaths?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Stat computation\n// ---------------------------------------------------------------------------\n\nfunction lensMeta(kind: string): Record<string, unknown> {\n\treturn domainMeta(\"lens\", kind);\n}\n\nfunction computeTopologyStats(described: GraphDescribeOutput): TopologyStats {\n\tconst paths = Object.keys(described.nodes);\n\tconst depsByPath = new Map<string, readonly string[]>();\n\tconst dependents = new Map<string, Set<string>>();\n\tfor (const path of paths) {\n\t\tconst deps = described.nodes[path]?.deps ?? [];\n\t\tdepsByPath.set(path, deps);\n\t\tfor (const dep of deps) {\n\t\t\tif (!dependents.has(dep)) dependents.set(dep, new Set());\n\t\t\tdependents.get(dep)!.add(path);\n\t\t}\n\t}\n\tconst sources: string[] = [];\n\tconst sinks: string[] = [];\n\tfor (const path of paths) {\n\t\tif ((depsByPath.get(path) ?? []).length === 0) sources.push(path);\n\t\tif (!dependents.has(path)) sinks.push(path);\n\t}\n\tsources.sort();\n\tsinks.sort();\n\n\tconst edgeCount = described.edges.length;\n\n\t// Cycle detection + longest path (DFS with recursion stack). Longest path\n\t// is measured in edges; undefined deps are ignored. Running on the DAG\n\t// subset: if a cycle is detected we still return `depth` for the acyclic\n\t// portion (0 if the whole graph cycles).\n\tconst WHITE = 0;\n\tconst GRAY = 1;\n\tconst BLACK = 2;\n\tconst color = new Map<string, number>();\n\tfor (const p of paths) color.set(p, WHITE);\n\tlet hasCycles = false;\n\tconst longestFrom = new Map<string, number>();\n\n\tconst dfs = (path: string): number => {\n\t\tconst c = color.get(path) ?? WHITE;\n\t\tif (c === GRAY) {\n\t\t\thasCycles = true;\n\t\t\treturn 0;\n\t\t}\n\t\tif (c === BLACK) return longestFrom.get(path) ?? 0;\n\t\tcolor.set(path, GRAY);\n\t\tlet best = 0;\n\t\tconst kids = dependents.get(path);\n\t\tif (kids != null) {\n\t\t\tfor (const k of kids) {\n\t\t\t\tconst childLongest = dfs(k);\n\t\t\t\tif (childLongest + 1 > best) best = childLongest + 1;\n\t\t\t}\n\t\t}\n\t\tcolor.set(path, BLACK);\n\t\tlongestFrom.set(path, best);\n\t\treturn best;\n\t};\n\n\tlet depth = 0;\n\tfor (const src of sources) {\n\t\tconst d = dfs(src);\n\t\tif (d > depth) depth = d;\n\t}\n\t// Visit remaining nodes so cycle-only subgraphs still flip hasCycles.\n\tfor (const p of paths) {\n\t\tif (color.get(p) === WHITE) dfs(p);\n\t}\n\n\treturn {\n\t\tnodeCount: paths.length,\n\t\tedgeCount,\n\t\tsubgraphCount: described.subgraphs.length,\n\t\tsources,\n\t\tsinks,\n\t\tdepth,\n\t\thasCycles,\n\t};\n}\n\nfunction computeHealthReport(described: GraphDescribeOutput): HealthReport {\n\tconst problems: HealthProblem[] = [];\n\tfor (const [path, desc] of Object.entries(described.nodes)) {\n\t\tif (desc.status !== \"errored\") continue;\n\t\tconst entry: HealthProblem = { path, status: \"errored\" };\n\t\t// Walk upstream to find the first errored ancestor (if any) distinct from `path`.\n\t\t// Explicit empty options disambiguates the overload (otherwise both match\n\t\t// and TS picks the `withDetail:true` signature first).\n\t\tconst upstream = reachable(described, path, \"upstream\", {});\n\t\tfor (const p of upstream) {\n\t\t\tif (p === path) continue;\n\t\t\tif (described.nodes[p]?.status === \"errored\") {\n\t\t\t\tentry.upstreamCause = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tproblems.push(entry);\n\t}\n\tproblems.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n\treturn { ok: problems.length === 0, problems };\n}\n\nfunction topologyStatsEqual(a: TopologyStats, b: TopologyStats): boolean {\n\treturn (\n\t\ta.nodeCount === b.nodeCount &&\n\t\ta.edgeCount === b.edgeCount &&\n\t\ta.subgraphCount === b.subgraphCount &&\n\t\ta.depth === b.depth &&\n\t\ta.hasCycles === b.hasCycles &&\n\t\tstringArrayEqual(a.sources, b.sources) &&\n\t\tstringArrayEqual(a.sinks, b.sinks)\n\t);\n}\n\nfunction healthReportEqual(a: HealthReport, b: HealthReport): boolean {\n\tif (a.ok !== b.ok) return false;\n\tif (a.problems.length !== b.problems.length) return false;\n\tfor (let i = 0; i < a.problems.length; i++) {\n\t\tconst x = a.problems[i]!;\n\t\tconst y = b.problems[i]!;\n\t\tif (x.path !== y.path) return false;\n\t\tif (x.status !== y.status) return false;\n\t\tif (x.upstreamCause !== y.upstreamCause) return false;\n\t}\n\treturn true;\n}\n\nfunction stringArrayEqual(a: readonly string[], b: readonly string[]): boolean {\n\tif (a.length !== b.length) return false;\n\tfor (let i = 0; i < a.length; i++) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// LensGraph\n// ---------------------------------------------------------------------------\n\n/**\n * Reactive observability surface for a target {@link Graph}.\n * See {@link graphLens}.\n *\n * @category observability\n */\nexport class LensGraph extends Graph {\n\t/**\n\t * Aggregate structural stats — `nodeCount`, `edgeCount`, `sources`,\n\t * `sinks`, `depth`, `hasCycles`, `subgraphCount`. Recomputes on every\n\t * structural change via {@link watchTopologyTree} (transitive).\n\t *\n\t * Named `stats` (not `topology`) because `Graph.topology` already names\n\t * the raw `TopologyEvent` stream on every graph including `LensGraph`;\n\t * giving the lens its own `topology` accessor with an incompatible\n\t * `Node<TopologyStats>` type would break Liskov substitutability.\n\t */\n\treadonly stats: Node<TopologyStats>;\n\treadonly health: Node<HealthReport>;\n\t/**\n\t * Per-path flow tracker — a live {@link ReactiveMapBundle} keyed by\n\t * qualified path. Use `.get(path)` / `.has(path)` / `.size` for O(1)\n\t * sync queries; subscribe to `.entries` for a reactive snapshot of the\n\t * whole map. Lazy — the snapshot is materialized only while `.entries`\n\t * has subscribers.\n\t *\n\t * Shape intentionally differs from `stats` / `health` (which are plain\n\t * `Node<Report>`) because `flow` is a keyed collection, not a single\n\t * aggregate value. The map shape exposes cheaper queries than any\n\t * snapshot-based design.\n\t */\n\treadonly flow: ReactiveMapBundle<string, FlowEntry>;\n\tprivate readonly _target: Graph;\n\n\tconstructor(target: Graph, opts: GraphLensOptions = {}) {\n\t\tsuper(opts.name ?? `${target.name}_lens`, opts.graph);\n\t\tthis._target = target;\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// Shared tick counters (closure-held — COMPOSITION-GUIDE §28 pattern).\n\t\t// `.cache` reads on state() can be undefined before the derived\n\t\t// subscribes; using closure counters keeps the derived fn pure.\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tlet statsVersion = 0;\n\t\tlet healthVersion = 0;\n\t\tconst statsTick = state(0, { name: \"stats_tick\" });\n\t\tconst healthTick = state(0, { name: \"health_tick\" });\n\t\tthis.add(\"stats_tick\", statsTick);\n\t\tthis.add(\"health_tick\", healthTick);\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// flow — reactiveMap<qualifiedPath, FlowEntry>\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tconst mapOpts: { name: string; maxSize?: number } = { name: \"flow\" };\n\t\tif (opts.maxFlowPaths != null) mapOpts.maxSize = opts.maxFlowPaths;\n\t\tthis.flow = reactiveMap<string, FlowEntry>(mapOpts);\n\t\tthis.add(\"flow\", this.flow.entries);\n\n\t\tconst pathFilter = opts.pathFilter;\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// Single consolidated topology watcher (stats + health + flow cleanup)\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tconst offTopology = watchTopologyTree(target, (event, _emitter, prefix) => {\n\t\t\t// Any structural change bumps stats & health.\n\t\t\tstatsVersion += 1;\n\t\t\tstatsTick.emit(statsVersion);\n\t\t\thealthVersion += 1;\n\t\t\thealthTick.emit(healthVersion);\n\n\t\t\t// Flow cleanup for removed paths — use the prefix to compute the\n\t\t\t// qualified key that matches `flow`'s entries.\n\t\t\tif (event.kind === \"removed\") {\n\t\t\t\tif (event.nodeKind === \"node\") {\n\t\t\t\t\tconst qp = `${prefix}${event.name}`;\n\t\t\t\t\tthis.flow.delete(qp);\n\t\t\t\t} else {\n\t\t\t\t\t// Mount removal: audit.nodes are paths RELATIVE to the unmounted\n\t\t\t\t\t// subgraph. Qualify with the mount's prefix to match flow keys.\n\t\t\t\t\tconst mountPrefix = `${prefix}${event.name}::`;\n\t\t\t\t\tconst keysToDelete: string[] = [];\n\t\t\t\t\tfor (const relativePath of event.audit.nodes) {\n\t\t\t\t\t\tconst qualified =\n\t\t\t\t\t\t\trelativePath === \"\" ? `${prefix}${event.name}` : `${mountPrefix}${relativePath}`;\n\t\t\t\t\t\tkeysToDelete.push(qualified);\n\t\t\t\t\t}\n\t\t\t\t\t// deleteMany collapses N deletions into one snapshot emit.\n\t\t\t\t\tif (keysToDelete.length > 0) this.flow.deleteMany(keysToDelete);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.addDisposer(offTopology);\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// Single consolidated observe subscription (health + flow DATA counter)\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tconst observeHandle = target.observe({ timeline: true, structured: true });\n\t\tconst offObserve = observeHandle.onEvent((event) => {\n\t\t\tconst t = event.type;\n\t\t\t// Health: recompute on status transitions and ERROR resolution.\n\t\t\tif (t === \"error\" || t === \"complete\" || t === \"data\" || t === \"teardown\") {\n\t\t\t\thealthVersion += 1;\n\t\t\t\thealthTick.emit(healthVersion);\n\t\t\t}\n\t\t\t// Flow: per-path DATA counter. Writes into reactiveMap; the map's\n\t\t\t// version counter + lazy `.entries` emission takes care of downstream\n\t\t\t// propagation (O(P) snapshot only when `.entries` is subscribed).\n\t\t\tif (t === \"data\") {\n\t\t\t\tconst path = event.path ?? \"\";\n\t\t\t\tif (!path) return;\n\t\t\t\tif (pathFilter != null && !pathFilter(path)) return;\n\t\t\t\tconst existing = this.flow.get(path);\n\t\t\t\tconst count = existing != null ? existing.count + 1 : 1;\n\t\t\t\tthis.flow.set(path, { path, count, lastUpdate_ns: monotonicNs() });\n\t\t\t}\n\t\t});\n\t\tthis.addDisposer(() => {\n\t\t\toffObserve();\n\t\t\tobserveHandle.dispose();\n\t\t});\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// stats — derived from the tick\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tthis.stats = derived<TopologyStats>(\n\t\t\t[statsTick],\n\t\t\t() => computeTopologyStats(target.describe({ detail: \"minimal\" })),\n\t\t\t{\n\t\t\t\tname: \"stats\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tequals: topologyStatsEqual,\n\t\t\t\tmeta: lensMeta(\"stats\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"stats\", this.stats);\n\t\tthis.addDisposer(keepalive(this.stats));\n\n\t\t// ——————————————————————————————————————————————————————————————\n\t\t// health — derived from the tick\n\t\t// ——————————————————————————————————————————————————————————————\n\t\tthis.health = derived<HealthReport>(\n\t\t\t[healthTick],\n\t\t\t() => computeHealthReport(target.describe({ detail: \"standard\" })),\n\t\t\t{\n\t\t\t\tname: \"health\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tequals: healthReportEqual,\n\t\t\t\tmeta: lensMeta(\"health\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"health\", this.health);\n\t\tthis.addDisposer(keepalive(this.health));\n\t}\n\n\t/**\n\t * Live causal chain from `from` to `to`. Recomputes whenever the target\n\t * mutates. Disposed automatically when the lens is destroyed.\n\t *\n\t * **Lifetime note:** every call to `why()` registers a lens-owned disposer\n\t * that runs on `lens.destroy()`. The returned `dispose` function releases\n\t * the internal subscription but does NOT remove the lens-owned disposer —\n\t * so heavy calling (e.g. per render frame) accumulates no-op disposers\n\t * until lens teardown. Cache the returned handle for long-lived queries.\n\t *\n\t * @param from - Qualified path of the upstream endpoint.\n\t * @param to - Qualified path of the downstream endpoint.\n\t * @param opts - See {@link reactiveExplainPath}.\n\t */\n\twhy(\n\t\tfrom: string,\n\t\tto: string,\n\t\topts?: { maxDepth?: number; name?: string; findCycle?: boolean },\n\t): { node: Node<CausalChain>; dispose: () => void } {\n\t\tconst handle = reactiveExplainPath(this._target, from, to, opts);\n\t\tthis.addDisposer(handle.dispose);\n\t\treturn handle;\n\t}\n\n\t/** Reference to the lensed graph. */\n\tget target(): Graph {\n\t\treturn this._target;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reactive observability lens over a {@link Graph}. Returns a\n * {@link LensGraph} with three reactive surfaces (`stats`, `health`, `flow`)\n * plus the `why(from, to)` method.\n *\n * The returned graph is detached. Mount it via `target.mount(\"lens\", lens)`\n * if you want it to appear in the target's `describe()`, or keep it standalone.\n *\n * @param target - The graph to observe.\n * @param opts - See {@link GraphLensOptions}.\n *\n * @example\n * ```ts\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * const lens = graphLens(g);\n * lens.stats.subscribe((msgs) => console.log(msgs[0]?.[1])); // TopologyStats\n * // Flow queries — O(1) without subscribing to snapshots:\n * lens.flow.get(\"counter\"); // FlowEntry | undefined\n * lens.flow.size; // number\n * lens.flow.entries.subscribe(...); // reactive snapshot, lazy-materialized\n * ```\n *\n * @category observability\n */\nexport function graphLens(target: Graph, opts?: GraphLensOptions): LensGraph {\n\treturn new LensGraph(target, opts);\n}\n","/**\n * Resilience composition with correct nesting order (roadmap §9.0b).\n *\n * {@link resilientPipeline} composes the resilience primitives from\n * `extra/resilience.ts` in the order discovered during the §9.1 eval runs:\n *\n * ```text\n * rateLimit → budget → breaker → timeout → retry → fallback → status\n * ```\n *\n * Note on retry/timeout ordering: `timeout` is applied BEFORE `retry` so each\n * retry attempt resubscribes to a fresh deadline (per-attempt semantics). If\n * `timeout` wrapped `retry`, a single deadline would apply to the entire\n * retry chain — not what callers expect.\n *\n * Every step is optional — omit the option and that layer is skipped. The\n * returned bundle exposes the final `Node<T>` plus the status/error/breaker\n * companions so callers can wire them into dashboards, alerts, or\n * {@link graphLens}.\n *\n * Subsumes the pre-1.0 `resilientFetch` template — that template becomes a\n * preconfigured instance of this factory for the HTTP fetch case.\n *\n * @module\n */\nimport type { Node } from \"../core/node.js\";\nimport { NS_PER_MS, NS_PER_SEC } from \"../extra/backoff.js\";\nimport {\n\ttype CircuitBreakerOptions,\n\ttype CircuitState,\n\tcircuitBreaker,\n\ttype FallbackInput,\n\tfallback,\n\ttype RateLimiterOptions,\n\ttype RetryOptions,\n\trateLimiter,\n\tretry,\n\ttype StatusValue,\n\ttimeout,\n\twithBreaker,\n\twithStatus,\n} from \"../extra/resilience.js\";\nimport { type BudgetConstraint, budgetGate } from \"./reduction.js\";\n\n/** Options for {@link resilientPipeline}. Every field is optional — omit to skip that layer. */\nexport interface ResilientPipelineOptions<T> {\n\t/** Admission control — at most `maxEvents` DATA per `windowNs`. See {@link rateLimiter}. */\n\trateLimit?: RateLimiterOptions;\n\t/** Cost/constraint gate. See {@link budgetGate}. */\n\tbudget?: ReadonlyArray<BudgetConstraint>;\n\t/** Circuit breaker — fail-fast when the downstream resource is unhealthy. See {@link circuitBreaker}. */\n\tbreaker?: CircuitBreakerOptions;\n\t/**\n\t * Behavior when the breaker is open:\n\t * - `\"skip\"` — emit RESOLVED (default, lets downstream drop the beat)\n\t * - `\"error\"` — emit a `CircuitOpenError` so `retry`/`fallback` can react\n\t *\n\t * Only used when `breaker` is provided.\n\t */\n\tbreakerOnOpen?: \"skip\" | \"error\";\n\t/** Retry policy on terminal ERROR. See {@link retry}. */\n\tretry?: RetryOptions;\n\t/**\n\t * Per-attempt deadline in milliseconds. Converted to ns internally. Omit to skip the timeout wrap.\n\t *\n\t * Specified in ms (not ns) because callers consistently think in millisecond deadlines;\n\t * retry/breaker/ratelimit options take ns to match their primitives exactly.\n\t */\n\ttimeoutMs?: number;\n\t/** Final fallback value emitted on terminal ERROR after retry exhausts. See {@link fallback}. */\n\tfallback?: FallbackInput<T>;\n\t/** Initial status reported by the status node. Default `\"pending\"`. */\n\tinitialStatus?: StatusValue;\n}\n\n/** Output bundle of {@link resilientPipeline}. */\nexport interface ResilientPipelineBundle<T> {\n\t/** The final resilient node. Subscribe to this for DATA emissions. */\n\tnode: Node<T>;\n\t/** Live status: `\"pending\" | \"active\" | \"completed\" | \"errored\"`. */\n\tstatus: Node<StatusValue>;\n\t/** Last error payload, or `null` when not errored. */\n\terror: Node<unknown | null>;\n\t/** Breaker state when `opts.breaker` was provided; `undefined` otherwise. */\n\tbreakerState: Node<CircuitState> | undefined;\n}\n\n/**\n * Compose a resilient pipeline around `source` in the canonical nesting\n * order — `rateLimit → budget → breaker → timeout → retry → fallback → status`.\n * Omit any option to skip that layer.\n *\n * @param source - Upstream node to wrap.\n * @param opts - See {@link ResilientPipelineOptions}. All fields optional.\n *\n * @example\n * ```ts\n * const safeFetch = resilientPipeline(fetchNode, {\n * rateLimit: { maxEvents: 10, windowNs: NS_PER_SEC },\n * breaker: { failureThreshold: 5 },\n * retry: { count: 3, backoff: \"exponential\" },\n * timeoutMs: 10_000,\n * fallback: null,\n * });\n * safeFetch.status.subscribe(msgs => console.log(msgs));\n * ```\n *\n * @category patterns\n */\nexport function resilientPipeline<T>(\n\tsource: Node<T>,\n\topts: ResilientPipelineOptions<T> = {},\n): ResilientPipelineBundle<T> {\n\tlet current: Node<T> = source;\n\n\t// 1. Admission control — cheapest to drop / queue before any other work.\n\tif (opts.rateLimit != null) {\n\t\tcurrent = rateLimiter(current, opts.rateLimit);\n\t}\n\n\t// 2. Budget — block when constraints are exhausted. Also cheap (no I/O).\n\tif (opts.budget != null && opts.budget.length > 0) {\n\t\tcurrent = budgetGate(current, opts.budget);\n\t}\n\n\t// 3. Breaker — skip the resource when unhealthy (fail-fast before retry wastes time).\n\tlet breakerState: Node<CircuitState> | undefined;\n\tif (opts.breaker != null) {\n\t\tconst breaker = circuitBreaker(opts.breaker);\n\t\tconst onOpen = opts.breakerOnOpen ?? \"skip\";\n\t\tconst wrapped = withBreaker<T>(breaker, { onOpen })(current);\n\t\tcurrent = wrapped.node;\n\t\tbreakerState = wrapped.breakerState;\n\t}\n\n\t// 4. Timeout — per-attempt deadline. Applied BEFORE retry so each retry\n\t// resubscribes to a fresh timeout. Swapping the order (timeout OUTSIDE\n\t// retry) would apply one global deadline to the entire retry chain —\n\t// not what callers expect for \"per-attempt timeout.\"\n\tif (opts.timeoutMs != null) {\n\t\tif (opts.timeoutMs <= 0) throw new RangeError(\"timeoutMs must be > 0\");\n\t\t// Guard against `timeoutMs * NS_PER_MS` overflowing Number.MAX_SAFE_INTEGER\n\t\t// (~9.007e15). 9_000_000 ms ≈ 2.5 hours is a sane upper bound; callers\n\t\t// needing longer deadlines should express them at the primitive level.\n\t\tif (opts.timeoutMs > 9_000_000) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"timeoutMs must be <= 9_000_000 (≈2.5h) to stay within safe ns arithmetic\",\n\t\t\t);\n\t\t}\n\t\tcurrent = timeout(current, opts.timeoutMs * NS_PER_MS);\n\t}\n\n\t// 5. Retry — resubscribe on ERROR up to `count` times. Wraps timeout so\n\t// each retry gets its own fresh deadline.\n\tif (opts.retry != null) {\n\t\tcurrent = retry(current, opts.retry);\n\t}\n\n\t// 6. Fallback — last resort after retry+timeout exhaust.\n\tif (opts.fallback !== undefined) {\n\t\tcurrent = fallback(current, opts.fallback);\n\t}\n\n\t// 7. Status wrapping — observability. Always last so it sees the final shape.\n\tconst withStatusBundle = withStatus(current, { initialStatus: opts.initialStatus ?? \"pending\" });\n\n\treturn {\n\t\tnode: withStatusBundle.node,\n\t\tstatus: withStatusBundle.status,\n\t\terror: withStatusBundle.error,\n\t\tbreakerState,\n\t};\n}\n\n// Re-export NS constants for consumers authoring pipeline options at call sites.\nexport { NS_PER_MS, NS_PER_SEC };\n","/**\n * Surface layer (§9.3-core) — shared, JSON-safe operations consumed by\n * `@graphrefly/mcp-server` and `@graphrefly/cli`.\n *\n * The surface is a thin projection of existing Graph APIs (`describe`,\n * `observe`, `explain`, `snapshot`, `restore`, static `diff`), plus two\n * genuinely new operations:\n *\n * 1. {@link createGraph} — `compileSpec` wrapped with typed surface errors.\n * 2. {@link reduce} — one-shot `input → pipeline → output`.\n *\n * Snapshot persistence reuses the {@link StorageTier} substrate introduced\n * for `Graph.attachStorage`, so one-shot snapshots and auto-checkpoints\n * share the {@link GraphCheckpointRecord} envelope. No new wire format.\n *\n * Errors throw as {@link SurfaceError} — wrappers map to their native\n * error channel (MCP `isError`, CLI exit code). No `Result<T, E>` wrapper.\n *\n * @module\n */\n\n// Re-export the graphspec types the surface operates on, so MCP/CLI\n// wrappers get `GraphSpec`/`GraphSpecCatalog` from one import. The\n// runtime functions (`compileSpec`, `validateSpec`, `decompileGraph`,\n// etc.) stay inside `patterns.graphspec` — surface callers use\n// {@link createGraph}, not those directly.\nexport type {\n\tCatalogFnEntry,\n\tCatalogSourceEntry,\n\tConfigFieldSchema,\n\tFnFactory,\n\tGraphSpec,\n\tGraphSpecCatalog,\n\tGraphSpecFeedbackEdge,\n\tGraphSpecNode,\n\tGraphSpecTemplate,\n\tGraphSpecTemplateRef,\n\tGraphSpecValidation,\n\tSourceFactory,\n} from \"../graphspec.js\";\nexport type { CreateGraphOptions } from \"./create.js\";\nexport { createGraph } from \"./create.js\";\nexport type { SurfaceErrorCode, SurfaceErrorPayload } from \"./errors.js\";\nexport { asSurfaceError, SurfaceError } from \"./errors.js\";\nexport type { ReduceOptions } from \"./reduce.js\";\nexport { runReduction } from \"./reduce.js\";\nexport type {\n\tRestoreSnapshotOptions,\n\tSaveSnapshotResult,\n} from \"./snapshot.js\";\nexport {\n\tdeleteSnapshot,\n\tdiffSnapshots,\n\tlistSnapshots,\n\trestoreSnapshot,\n\tSNAPSHOT_WIRE_VERSION,\n\tsaveSnapshot,\n} from \"./snapshot.js\";\n","/**\n * Typed errors for the surface layer (§9.3-core).\n *\n * The surface layer is consumed by `@graphrefly/mcp-server` and\n * `@graphrefly/cli`. Both have native error channels (MCP's `isError` flag,\n * CLI's exit codes), so surface functions throw a {@link SurfaceError}\n * carrying a structured code + details payload that wrappers can map to\n * their native shape. No `Result` envelope — keep the callsite idiom\n * `try/catch` and let each wrapper surface the error its own way.\n *\n * @module\n */\n\n/** Structured error codes emitted by the surface layer. JSON-safe. */\nexport type SurfaceErrorCode =\n\t| \"invalid-spec\"\n\t| \"graph-not-found\"\n\t| \"graph-exists\"\n\t| \"snapshot-not-found\"\n\t| \"node-not-found\"\n\t| \"reduce-timeout\"\n\t| \"catalog-error\"\n\t| \"restore-failed\"\n\t| \"snapshot-failed\"\n\t| \"tier-no-list\"\n\t| \"internal-error\";\n\n/** JSON-safe shape surfaces should echo back through the wrapper. */\nexport interface SurfaceErrorPayload {\n\tcode: SurfaceErrorCode;\n\tmessage: string;\n\t/** Optional structured detail; must be JSON-safe. */\n\tdetails?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Thrown by surface layer functions on failure. `code` is the stable\n * machine-readable identifier; `details` carries structured context\n * (e.g. `validateSpec` errors, missing path name). Both fields round-trip\n * through `toJSON()` for wrappers that serialize errors over the wire.\n */\nexport class SurfaceError extends Error {\n\treadonly code: SurfaceErrorCode;\n\treadonly details?: Readonly<Record<string, unknown>>;\n\n\tconstructor(\n\t\tcode: SurfaceErrorCode,\n\t\tmessage: string,\n\t\tdetails?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"SurfaceError\";\n\t\tthis.code = code;\n\t\tif (details !== undefined) this.details = details;\n\t}\n\n\t/**\n\t * JSON-safe payload for wire serialization. Defensively validates\n\t * `details` — if it can't be round-tripped through `JSON.stringify`\n\t * (cyclic refs, `BigInt`, `Error` instance not pre-toJSON'd), the\n\t * payload falls back to `{code, message}` only rather than crashing\n\t * the MCP/CLI wrapper when it serializes this error onto the wire.\n\t */\n\ttoJSON(): SurfaceErrorPayload {\n\t\tconst out: SurfaceErrorPayload = { code: this.code, message: this.message };\n\t\tif (this.details !== undefined) {\n\t\t\tconst safe = safeDetails(this.details);\n\t\t\tif (safe !== undefined) out.details = safe;\n\t\t}\n\t\treturn out;\n\t}\n}\n\nfunction safeDetails(\n\tdetails: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> | undefined {\n\ttry {\n\t\t// Round-trip through JSON to strip non-serializable values (functions,\n\t\t// undefined) and reject cyclic structures with a thrown TypeError. The\n\t\t// round-trip result is the canonical wire shape.\n\t\treturn JSON.parse(JSON.stringify(details)) as Readonly<Record<string, unknown>>;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Wrap any thrown value as a SurfaceError. Idempotent on existing SurfaceError. */\nexport function asSurfaceError(\n\terr: unknown,\n\tfallbackCode: SurfaceErrorCode = \"internal-error\",\n): SurfaceError {\n\tif (err instanceof SurfaceError) return err;\n\tconst message = err instanceof Error ? err.message : String(err);\n\treturn new SurfaceError(fallbackCode, message);\n}\n","/**\n * Surface: create a graph from a {@link GraphSpec} (§9.3-core).\n *\n * Thin wrapper over {@link compileSpec} that converts the two failure modes\n * ({@link validateSpec} structural errors, and catalog-aware validation\n * errors) into typed {@link SurfaceError} throws. Consumers are MCP/CLI\n * wrappers, not end-user graph code — those should import `compileSpec`\n * directly.\n *\n * @module\n */\n\nimport type { Graph } from \"../../graph/graph.js\";\nimport type { CompileSpecOptions, GraphSpec } from \"../graphspec.js\";\nimport { compileSpec, validateSpec, validateSpecAgainstCatalog } from \"../graphspec.js\";\nimport { SurfaceError } from \"./errors.js\";\n\n/** Options for {@link createGraph}. Same shape as {@link CompileSpecOptions}. */\nexport type CreateGraphOptions = CompileSpecOptions;\n\n/**\n * Build a {@link Graph} from a parsed {@link GraphSpec} with surface-layer\n * error typing.\n *\n * @throws {SurfaceError} `invalid-spec` for structural errors;\n * `catalog-error` when fn/source names or config don't match the catalog.\n */\nexport function createGraph(spec: GraphSpec, opts?: CreateGraphOptions): Graph {\n\tconst structural = validateSpec(spec);\n\tif (!structural.valid) {\n\t\tthrow new SurfaceError(\n\t\t\t\"invalid-spec\",\n\t\t\t`GraphSpec validation failed:\\n${structural.errors.join(\"\\n\")}`,\n\t\t\t{ errors: structural.errors },\n\t\t);\n\t}\n\tconst catalog = opts?.catalog ?? {};\n\tconst catalogValidation = validateSpecAgainstCatalog(spec, catalog);\n\tif (!catalogValidation.valid) {\n\t\tthrow new SurfaceError(\n\t\t\t\"catalog-error\",\n\t\t\t`Catalog validation failed:\\n${catalogValidation.errors.join(\"\\n\")}`,\n\t\t\t{ errors: catalogValidation.errors },\n\t\t);\n\t}\n\ttry {\n\t\treturn compileSpec(spec, opts);\n\t} catch (err) {\n\t\t// compileSpec re-throws validation errors plus may throw on missing\n\t\t// catalog entries for template-inner deferred nodes. Surface as\n\t\t// catalog-error; callers can inspect the wrapped message.\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new SurfaceError(\"catalog-error\", message);\n\t}\n}\n","/**\n * Surface: one-shot `input → pipeline → output` (§9.3-core).\n *\n * `runReduction` compiles a {@link GraphSpec}, pushes an input value to a\n * named state node, awaits the first post-push DATA emission on a named\n * output, then disposes the graph. Stateless per call — no graphId, no\n * registry.\n *\n * Named `runReduction` (not `reduce`) to avoid collision with the\n * reactive {@link reduce} operator in `extra/operators.ts`. The MCP tool\n * name (`graphrefly_reduce`) and CLI subcommand (`graphrefly reduce`) use\n * the short form; the library export carries the verb.\n *\n * The subscribe-before-push ordering is deliberate. `graph.set` propagates\n * synchronously for sync derived/operator chains; for async sources\n * (`fromPromise`, `fromAsyncIter`, LLM adapters) the first post-push DATA\n * arrives on a later tick. Subscribing before the push catches both, and\n * skipping the priming push-on-subscribe emission avoids resolving with the\n * stale pre-push cache (spec §2.2).\n *\n * @module\n */\n\nimport { COMPLETE, DATA, ERROR, RESOLVED } from \"../../core/messages.js\";\nimport type { Node } from \"../../core/node.js\";\nimport type { GraphSpec, GraphSpecCatalog } from \"../graphspec.js\";\nimport { createGraph } from \"./create.js\";\nimport { SurfaceError } from \"./errors.js\";\n\n/** Options for {@link reduce}. */\nexport interface ReduceOptions {\n\t/** Fn/source catalog for {@link createGraph}. */\n\tcatalog?: GraphSpecCatalog;\n\t/** Path of the state node that receives the input. Default `\"input\"`. */\n\tinputPath?: string;\n\t/** Path of the node whose first post-push DATA is the result. Default `\"output\"`. */\n\toutputPath?: string;\n\t/** Hard deadline in milliseconds. Default `30_000`. */\n\ttimeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Run a spec as a one-shot reduction: `input → graph → output`.\n *\n * Resolves on the first `[DATA, v]` **or** `[RESOLVED]` emitted by\n * `outputPath` after the input push. The RESOLVED path handles spec\n * §1.3.3 equals-substitution (output recomputed to a value equal to its\n * cache, so the graph skips the DATA push) by returning `outputNode.cache`\n * — the caller always gets the settled value, never hangs on idempotent\n * inputs.\n *\n * @throws {SurfaceError} `invalid-spec` / `catalog-error` (propagated from\n * {@link createGraph}), `node-not-found` when `inputPath`/`outputPath`\n * can't be resolved, `reduce-timeout` when `timeoutMs` elapses without\n * a post-push emission, or the ERROR payload from the graph re-thrown\n * as `internal-error`.\n */\nexport async function runReduction(\n\tspec: GraphSpec,\n\tinput: unknown,\n\topts?: ReduceOptions,\n): Promise<unknown> {\n\tconst inputPath = opts?.inputPath ?? \"input\";\n\tconst outputPath = opts?.outputPath ?? \"output\";\n\tconst timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n\tconst graph = createGraph(spec, { catalog: opts?.catalog });\n\tlet outputNode: Node<unknown>;\n\ttry {\n\t\toutputNode = graph.resolve(outputPath);\n\t} catch {\n\t\tgraph.destroy();\n\t\tthrow new SurfaceError(\n\t\t\t\"node-not-found\",\n\t\t\t`reduce: output path \"${outputPath}\" is not registered`,\n\t\t\t{ path: outputPath },\n\t\t);\n\t}\n\t// Verify input path exists before we subscribe and push.\n\ttry {\n\t\tgraph.resolve(inputPath);\n\t} catch {\n\t\tgraph.destroy();\n\t\tthrow new SurfaceError(\n\t\t\t\"node-not-found\",\n\t\t\t`reduce: input path \"${inputPath}\" is not registered`,\n\t\t\t{ path: inputPath },\n\t\t);\n\t}\n\n\ttry {\n\t\treturn await new Promise<unknown>((resolve, reject) => {\n\t\t\tlet primed = false;\n\t\t\tlet settled = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet unsub: (() => void) | undefined;\n\t\t\tlet shouldUnsub = false;\n\n\t\t\tconst finish = (action: () => void): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tif (unsub !== undefined) {\n\t\t\t\t\tunsub();\n\t\t\t\t\tunsub = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tshouldUnsub = true;\n\t\t\t\t}\n\t\t\t\taction();\n\t\t\t};\n\n\t\t\tunsub = outputNode.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\t// Skip push-on-subscribe emissions that land before we\n\t\t\t\t\t// trigger the input push — those carry pre-push state.\n\t\t\t\t\tif (!primed) continue;\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tfinish(() => resolve(m[1]));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === RESOLVED) {\n\t\t\t\t\t\t// Spec §1.3.3 equals-substitution: the output recomputed to\n\t\t\t\t\t\t// a value equal to its cached value, so the graph emits\n\t\t\t\t\t\t// RESOLVED instead of DATA. For a one-shot reduce the\n\t\t\t\t\t\t// caller wants the output value — read the cache **before**\n\t\t\t\t\t\t// finish() runs unsub (which can trigger lazy deactivation\n\t\t\t\t\t\t// and clear the cache per the RAM-cache rule).\n\t\t\t\t\t\tconst cached = outputNode.cache;\n\t\t\t\t\t\tfinish(() => resolve(cached));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\t\tconst payload = m[1];\n\t\t\t\t\t\tconst message = payload instanceof Error ? payload.message : String(payload);\n\t\t\t\t\t\tconst cause = payload instanceof Error ? payload : undefined;\n\t\t\t\t\t\tfinish(() =>\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew SurfaceError(\n\t\t\t\t\t\t\t\t\t\"internal-error\",\n\t\t\t\t\t\t\t\t\t`reduce: output emitted ERROR: ${message}`,\n\t\t\t\t\t\t\t\t\tcause != null ? { cause } : undefined,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\t\tfinish(() =>\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew SurfaceError(\n\t\t\t\t\t\t\t\t\t\"internal-error\",\n\t\t\t\t\t\t\t\t\t`reduce: output COMPLETEd without a post-push DATA`,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (shouldUnsub) {\n\t\t\t\tunsub?.();\n\t\t\t\tunsub = undefined;\n\t\t\t}\n\n\t\t\tprimed = true;\n\t\t\ttry {\n\t\t\t\tgraph.set(inputPath, input);\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\tconst cause = err instanceof Error ? err : undefined;\n\t\t\t\tfinish(() =>\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew SurfaceError(\n\t\t\t\t\t\t\t\"internal-error\",\n\t\t\t\t\t\t\t`reduce: failed to set input on \"${inputPath}\": ${message}`,\n\t\t\t\t\t\t\tcause != null ? { path: inputPath, cause } : { path: inputPath },\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Synchronous wave may have already settled the promise via the\n\t\t\t// subscribe callback above; skip the timer in that case so we\n\t\t\t// don't leak an orphan setTimeout into the event loop (A1, E4).\n\t\t\tif (!settled && Number.isFinite(timeoutMs) && timeoutMs > 0) {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tfinish(() =>\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew SurfaceError(\n\t\t\t\t\t\t\t\t\"reduce-timeout\",\n\t\t\t\t\t\t\t\t`reduce: no output emitted within ${timeoutMs}ms`,\n\t\t\t\t\t\t\t\t{ timeoutMs, outputPath },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}, timeoutMs);\n\t\t\t\t// Belt-and-suspenders: if the caller drops the returned promise\n\t\t\t\t// we shouldn't keep the process alive.\n\t\t\t\ttimer.unref?.();\n\t\t\t}\n\t\t});\n\t} finally {\n\t\tgraph.destroy();\n\t}\n}\n","/**\n * Surface: snapshot save/restore/diff/list over {@link StorageTier} (§9.3-core).\n *\n * One-shot snapshot management for stateless callers (MCP tools, CLI\n * commands) layered on the existing multi-tier auto-checkpoint substrate.\n * A saved snapshot is a `mode: \"full\"` {@link GraphCheckpointRecord} with\n * `seq: 0` — byte-identical to the baseline anchor\n * {@link Graph.attachStorage} writes on its first flush. An\n * auto-checkpointed graph can therefore be restored through this surface,\n * and a surface-saved snapshot can be picked up by `attachStorage({\n * autoRestore: true })`.\n *\n * The wire envelope stays at {@link SNAPSHOT_WIRE_VERSION}; no new format.\n *\n * @module\n */\n\nimport { wallClockNs } from \"../../core/clock.js\";\nimport type { StorageTier } from \"../../extra/storage.js\";\nimport type {\n\tGraphCheckpointRecord,\n\tGraphDiffResult,\n\tGraphNodeFactory,\n\tGraphPersistSnapshot,\n} from \"../../graph/graph.js\";\nimport { Graph, SNAPSHOT_VERSION } from \"../../graph/graph.js\";\nimport { SurfaceError } from \"./errors.js\";\n\n/**\n * Current envelope version. Re-exported from `graph.ts` so the one-shot\n * surface path and `Graph.attachStorage` write byte-identical\n * `format_version` fields — no silent wire drift.\n */\nexport const SNAPSHOT_WIRE_VERSION = SNAPSHOT_VERSION;\n\n/** Shape returned by {@link saveSnapshot}. */\nexport interface SaveSnapshotResult {\n\tsnapshotId: string;\n\ttimestamp_ns: number;\n}\n\n/** Options for {@link restoreSnapshot}. */\nexport interface RestoreSnapshotOptions {\n\t/** Passthrough to `Graph.fromSnapshot`. First matching pattern wins. */\n\tfactories?: Record<string, GraphNodeFactory>;\n}\n\nfunction unwrapCheckpoint(raw: unknown, snapshotId: string): GraphPersistSnapshot {\n\tif (raw == null || typeof raw !== \"object\") {\n\t\tthrow new SurfaceError(\"snapshot-not-found\", `snapshot \"${snapshotId}\" not found in tier`, {\n\t\t\tsnapshotId,\n\t\t});\n\t}\n\t// Accept both wrapped (GraphCheckpointRecord) and bare\n\t// (GraphPersistSnapshot) payloads — attachStorage writes wrapped, a user\n\t// may also hand us a bare one via dictStorage for tests.\n\tconst record = raw as Record<string, unknown>;\n\tif (\"mode\" in record) {\n\t\tif (record.mode === \"full\" && \"snapshot\" in record) {\n\t\t\treturn record.snapshot as GraphPersistSnapshot;\n\t\t}\n\t\tif (record.mode === \"diff\") {\n\t\t\tthrow new SurfaceError(\n\t\t\t\t\"restore-failed\",\n\t\t\t\t`snapshot \"${snapshotId}\" is a diff record; restore the baseline and replay WAL instead`,\n\t\t\t\t{ snapshotId, mode: \"diff\" },\n\t\t\t);\n\t\t}\n\t\tthrow new SurfaceError(\n\t\t\t\"restore-failed\",\n\t\t\t`snapshot \"${snapshotId}\" has unknown mode \"${String(record.mode)}\"`,\n\t\t\t{ snapshotId, mode: String(record.mode) },\n\t\t);\n\t}\n\tif (\"nodes\" in record && \"edges\" in record && \"subgraphs\" in record && \"name\" in record) {\n\t\treturn record as unknown as GraphPersistSnapshot;\n\t}\n\tthrow new SurfaceError(\n\t\t\"restore-failed\",\n\t\t`snapshot \"${snapshotId}\" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,\n\t\t{ snapshotId },\n\t);\n}\n\n/**\n * Write a graph's current state as a one-shot `mode: \"full\"` record.\n *\n * Uses the same {@link GraphCheckpointRecord} envelope as\n * {@link Graph.attachStorage} so the two persistence paths interoperate.\n *\n * @throws {SurfaceError} `snapshot-failed` when the tier's `save` throws.\n */\nexport async function saveSnapshot(\n\tgraph: Graph,\n\tsnapshotId: string,\n\ttier: StorageTier,\n): Promise<SaveSnapshotResult> {\n\tlet snapshot: GraphPersistSnapshot;\n\ttry {\n\t\tsnapshot = graph.snapshot();\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new SurfaceError(\n\t\t\t\"snapshot-failed\",\n\t\t\t`snapshot \"${snapshotId}\" serialization failed: ${message}`,\n\t\t\t{ snapshotId },\n\t\t);\n\t}\n\tconst record: GraphCheckpointRecord = {\n\t\tmode: \"full\",\n\t\tseq: 0,\n\t\ttimestamp_ns: wallClockNs(),\n\t\tformat_version: SNAPSHOT_WIRE_VERSION,\n\t\tsnapshot,\n\t};\n\ttry {\n\t\tawait tier.save(snapshotId, record);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new SurfaceError(\"snapshot-failed\", `snapshot \"${snapshotId}\" save failed: ${message}`, {\n\t\t\tsnapshotId,\n\t\t});\n\t}\n\treturn { snapshotId, timestamp_ns: record.timestamp_ns };\n}\n\n/**\n * Load a snapshot from a tier and materialize it as a new {@link Graph}.\n *\n * Uses {@link Graph.fromSnapshot} to reconstruct topology; pass\n * `factories` when the graph includes non-state nodes that the default\n * hydrator can't rebuild on its own.\n *\n * **Requires a `mode: \"full\"` record.** Surface-written snapshots from\n * {@link saveSnapshot} always qualify. Records written by\n * {@link Graph.attachStorage} with `compactEvery > 1` may be\n * `mode: \"diff\"` between compacts — those throw `restore-failed` until\n * the tier's next compact flush (or until Phase 8.7 WAL replay lands).\n * If you need interop during development, either call\n * {@link saveSnapshot} explicitly (always full) or configure\n * `attachStorage({compactEvery: 1})`.\n *\n * @throws {SurfaceError} `snapshot-not-found` on miss; `restore-failed`\n * when the payload shape doesn't match, when the record is\n * `mode: \"diff\"`, or when `Graph.fromSnapshot` rejects.\n */\nexport async function restoreSnapshot(\n\tsnapshotId: string,\n\ttier: StorageTier,\n\topts?: RestoreSnapshotOptions,\n): Promise<Graph> {\n\tconst raw = await tier.load(snapshotId);\n\tconst snapshot = unwrapCheckpoint(raw, snapshotId);\n\ttry {\n\t\treturn Graph.fromSnapshot(\n\t\t\tsnapshot,\n\t\t\topts?.factories ? { factories: opts.factories } : undefined,\n\t\t);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new SurfaceError(\n\t\t\t\"restore-failed\",\n\t\t\t`snapshot \"${snapshotId}\" restore failed: ${message}`,\n\t\t\t{\n\t\t\t\tsnapshotId,\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Load two snapshots and compute a {@link GraphDiffResult} via static\n * {@link Graph.diff}. Returns the audit shape (structural + value diff,\n * no payload); use {@link diffForWAL} directly for WAL-oriented diffs.\n *\n * @throws {SurfaceError} `snapshot-not-found` on either miss.\n */\nexport async function diffSnapshots(\n\tsnapshotIdA: string,\n\tsnapshotIdB: string,\n\ttier: StorageTier,\n): Promise<GraphDiffResult> {\n\tconst [rawA, rawB] = await Promise.all([tier.load(snapshotIdA), tier.load(snapshotIdB)]);\n\tconst snapshotA = unwrapCheckpoint(rawA, snapshotIdA);\n\tconst snapshotB = unwrapCheckpoint(rawB, snapshotIdB);\n\treturn Graph.diff(snapshotA, snapshotB);\n}\n\n/**\n * Enumerate snapshot ids on a tier.\n *\n * **Scope caveat:** returns every key on the tier, not just those\n * written by {@link saveSnapshot}. When the same tier also backs\n * {@link Graph.attachStorage} (for auto-checkpoints keyed by\n * `graph.name`), those names appear in this list too. Wrappers that\n * want a namespaced snapshot store should use a dedicated tier or\n * encode an id prefix on write. Tracked in `docs/optimizations.md`\n * under \"surface `listSnapshots` namespacing\".\n *\n * @throws {SurfaceError} `tier-no-list` when the tier does not implement\n * the optional `list()` method. Check `typeof tier.list === \"function\"`\n * before calling if you want to branch on capability.\n */\nexport async function listSnapshots(tier: StorageTier): Promise<readonly string[]> {\n\tif (typeof tier.list !== \"function\") {\n\t\tthrow new SurfaceError(\n\t\t\t\"tier-no-list\",\n\t\t\t\"StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend\",\n\t\t);\n\t}\n\treturn tier.list();\n}\n\n/**\n * Delete a snapshot from a tier.\n *\n * Silent on miss (clear semantics). `tier.clear` is optional — throws\n * `snapshot-failed` when the tier is append-only.\n *\n * @throws {SurfaceError} `snapshot-failed` when `clear` is unsupported\n * or throws.\n */\nexport async function deleteSnapshot(snapshotId: string, tier: StorageTier): Promise<void> {\n\tif (typeof tier.clear !== \"function\") {\n\t\tthrow new SurfaceError(\n\t\t\t\"snapshot-failed\",\n\t\t\t`StorageTier is append-only (no clear()); cannot delete \"${snapshotId}\"`,\n\t\t\t{ snapshotId },\n\t\t);\n\t}\n\ttry {\n\t\tawait tier.clear(snapshotId);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new SurfaceError(\n\t\t\t\"snapshot-failed\",\n\t\t\t`snapshot \"${snapshotId}\" delete failed: ${message}`,\n\t\t\t{\n\t\t\t\tsnapshotId,\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * GraphRefly — public API surface.\n */\nexport const version = \"0.0.0\";\n\nexport * from \"./compat/index.js\";\nexport * as compat from \"./compat/index.js\";\n// Named re-exports enable finer-grained tree-shaking for consumers.\nexport * from \"./core/index.js\";\n// Keep namespace exports for ergonomic grouped imports.\nexport * as core from \"./core/index.js\";\nexport * from \"./extra/index.js\";\nexport * as extra from \"./extra/index.js\";\nexport * from \"./graph/index.js\";\nexport * as graph from \"./graph/index.js\";\nexport * from \"./patterns/index.js\";\nexport * as patterns from \"./patterns/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqCA,SAAS,SAAS,MAAc,MAAy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