@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/patterns/audit.ts","../../src/core/clock.ts","../../src/core/guard.ts","../../src/core/messages.ts","../../src/graph/codec.ts","../../src/core/actor.ts","../../src/core/batch.ts","../../src/core/config.ts","../../src/core/versioning.ts","../../src/core/node.ts","../../src/core/sugar.ts","../../src/extra/reactive-log.ts","../../src/extra/utils/sizeof.ts","../../src/graph/explain.ts","../../src/core/meta.ts","../../src/extra/timer.ts","../../src/extra/utils/ring-buffer.ts","../../src/graph/profile.ts","../../src/graph/graph.ts","../../src/graph/topology-tree.ts","../../src/extra/sources.ts","../../src/patterns/_internal.ts","../../src/patterns/messaging.ts"],"sourcesContent":["/**\n * Audit, policy enforcement, and compliance export (roadmap §9.2).\n *\n * Three composed factories that wrap any {@link Graph} with the harness\n * accountability layer:\n *\n * - {@link auditTrail} — reactive mutation log with by-node/by-actor/by-time\n * queries.\n * - {@link policyEnforcer} — reactive ABAC enforcement; in `\"audit\"` mode\n * records would-be denials, in `\"enforce\"` mode pushes guards onto target\n * nodes so subsequent writes throw {@link GuardDenied}.\n * - {@link complianceSnapshot} — point-in-time export of graph state +\n * audit trail + policies for regulatory archival.\n *\n * @module\n */\nimport type { Actor } from \"../core/actor.js\";\nimport { monotonicNs, wallClockNs } from \"../core/clock.js\";\nimport type { GuardAction, NodeGuard, PolicyRuleData } from \"../core/guard.js\";\nimport { policyFromRules } from \"../core/guard.js\";\nimport { DATA } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { NodeImpl } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport { defaultHash } from \"../core/versioning.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport {\n\ttype CausalChain,\n\ttype CausalStep,\n\tGraph,\n\ttype GraphOptions,\n\ttype GraphPersistSnapshot,\n\ttype TopologyEvent,\n\twatchTopologyTree,\n} from \"../graph/index.js\";\nimport { domainMeta, keepalive } from \"./_internal.js\";\nimport { TopicGraph } from \"./messaging.js\";\n\n// ---------------------------------------------------------------------------\n// Shared types\n// ---------------------------------------------------------------------------\n\n/** A single recorded mutation/event in an {@link AuditTrailGraph}. */\nexport interface AuditEntry {\n\tseq: number;\n\ttimestamp_ns: number;\n\twall_clock_ns: number;\n\tpath: string;\n\ttype:\n\t\t| \"data\"\n\t\t| \"dirty\"\n\t\t| \"resolved\"\n\t\t| \"invalidate\"\n\t\t| \"pause\"\n\t\t| \"resume\"\n\t\t| \"complete\"\n\t\t| \"error\"\n\t\t| \"teardown\";\n\tactor?: Actor;\n\tvalue?: unknown;\n\terror?: unknown;\n\treason?: string;\n}\n\nfunction auditMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"audit\", kind, extra);\n}\n\n// ---------------------------------------------------------------------------\n// auditTrail\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_INCLUDE_TYPES: ReadonlySet<AuditEntry[\"type\"]> = new Set([\n\t\"data\",\n\t\"error\",\n\t\"complete\",\n\t\"teardown\",\n]);\n\n/** Options for {@link auditTrail}. */\nexport interface AuditTrailOptions {\n\tname?: string;\n\tgraph?: GraphOptions;\n\t/** Ring-buffer cap for the underlying `reactiveLog`. Default: unbounded. */\n\tmaxSize?: number;\n\t/**\n\t * Which event types to record. Default: `[\"data\", \"error\", \"complete\",\n\t * \"teardown\"]` — the user-meaningful set. Opt in to mid-wave protocol\n\t * events (`\"dirty\"`, `\"resolved\"`, `\"invalidate\"`, `\"pause\"`, `\"resume\"`)\n\t * by listing them explicitly. Note: those tier-1/tier-2 events do not\n\t * carry an `actor` (no `lastMutation` populated) — record them only for\n\t * protocol-level diagnostics.\n\t */\n\tincludeTypes?: readonly AuditEntry[\"type\"][];\n\t/** Per-event filter; return false to skip. */\n\tfilter?: (entry: AuditEntry) => boolean;\n}\n\n/**\n * Mounted audit log — `entries` exposes the reactive `AuditEntry[]`; query\n * helpers are sync convenience wrappers over the cached snapshot.\n */\nexport class AuditTrailGraph extends Graph {\n\treadonly entries: Node<readonly AuditEntry[]>;\n\treadonly count: Node<number>;\n\tprivate readonly _log;\n\tprivate readonly _target: Graph;\n\n\tconstructor(target: Graph, opts: AuditTrailOptions) {\n\t\tsuper(opts.name ?? `${target.name}_audit`, opts.graph);\n\t\tthis._target = target;\n\t\tthis._log = reactiveLog<AuditEntry>([], {\n\t\t\tname: \"entries\",\n\t\t\t...(opts.maxSize != null ? { maxSize: opts.maxSize } : {}),\n\t\t});\n\t\tthis.entries = this._log.entries;\n\t\tthis.add(\"entries\", this.entries);\n\n\t\tthis.count = derived<number>(\n\t\t\t[this.entries],\n\t\t\t([snapshot]) => (snapshot as readonly AuditEntry[]).length,\n\t\t\t{ name: \"count\", describeKind: \"derived\", meta: auditMeta(\"count\") },\n\t\t);\n\t\tthis.add(\"count\", this.count);\n\t\tthis.addDisposer(keepalive(this.count));\n\n\t\tconst includeTypes =\n\t\t\topts.includeTypes != null ? new Set(opts.includeTypes) : DEFAULT_INCLUDE_TYPES;\n\t\tconst filter = opts.filter;\n\n\t\t// Monotonic per-trail. Wraps around at Number.MAX_SAFE_INTEGER (~9e15);\n\t\t// at 100k events/sec that's ~3000 years — not a practical concern.\n\t\tlet seq = 0;\n\t\tconst handle = target.observe({ timeline: true, structured: true });\n\t\tconst offEvent = handle.onEvent((event) => {\n\t\t\t// `event.type` includes \"derived\" (causal-trace recompute marker) which\n\t\t\t// isn't a recordable mutation — skip it. Cast through narrowed type\n\t\t\t// after the discriminator check.\n\t\t\tif (event.type === \"derived\") return;\n\t\t\tconst type = event.type as AuditEntry[\"type\"];\n\t\t\tif (!includeTypes.has(type)) return;\n\t\t\tconst path = event.path ?? \"\";\n\t\t\tconst entry: AuditEntry = {\n\t\t\t\tseq: seq++,\n\t\t\t\ttimestamp_ns: event.timestamp_ns ?? monotonicNs(),\n\t\t\t\twall_clock_ns: wallClockNs(),\n\t\t\t\tpath,\n\t\t\t\ttype,\n\t\t\t};\n\t\t\t// Attribution + value enrichment.\n\t\t\tconst node = path ? safeNode(target, path) : undefined;\n\t\t\tconst lastMutation = node?.lastMutation;\n\t\t\tif (lastMutation != null) entry.actor = lastMutation.actor;\n\t\t\tif (type === \"data\") entry.value = (event as { data: unknown }).data;\n\t\t\tif (type === \"error\") entry.error = (event as { data: unknown }).data;\n\t\t\tconst reason = path ? safeAnnotation(target, path) : undefined;\n\t\t\tif (reason != null) entry.reason = reason;\n\t\t\tif (filter != null && !filter(entry)) return;\n\t\t\tthis._log.append(entry);\n\t\t});\n\n\t\tthis.addDisposer(() => {\n\t\t\toffEvent();\n\t\t\thandle.dispose();\n\t\t});\n\t\tthis.addDisposer(() => this._log.disposeAllViews());\n\t}\n\n\t/** All entries currently in the ring (snapshot). */\n\tall(): readonly AuditEntry[] {\n\t\treturn (this.entries.cache as readonly AuditEntry[] | undefined) ?? [];\n\t}\n\n\t/** Entries matching `path`. Order preserved. */\n\tbyNode(path: string): readonly AuditEntry[] {\n\t\treturn this.all().filter((e) => e.path === path);\n\t}\n\n\t/** Entries whose `actor.id` matches. Use `byActorType` for type filtering. */\n\tbyActor(actorId: string): readonly AuditEntry[] {\n\t\treturn this.all().filter((e) => e.actor?.id === actorId);\n\t}\n\n\t/** Entries whose `actor.type` matches (e.g. `\"llm\"`, `\"human\"`). */\n\tbyActorType(type: string): readonly AuditEntry[] {\n\t\treturn this.all().filter((e) => e.actor?.type === type);\n\t}\n\n\t/**\n\t * Entries with `timestamp_ns` in `[start_ns, end_ns)` (end exclusive).\n\t * Omit `end_ns` to query open-ended.\n\t */\n\tbyTimeRange(start_ns: number, end_ns?: number): readonly AuditEntry[] {\n\t\treturn this.all().filter((e) => {\n\t\t\tif (e.timestamp_ns < start_ns) return false;\n\t\t\tif (end_ns != null && e.timestamp_ns >= end_ns) return false;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\t/** Reference to the audited graph (escape hatch for tooling). */\n\tget target(): Graph {\n\t\treturn this._target;\n\t}\n}\n\n/**\n * Wraps any {@link Graph} with a reactive audit trail recording every event\n * matching `includeTypes` (default: data + error + complete + teardown).\n *\n * Each entry carries `seq`, `timestamp_ns` (monotonic), `wall_clock_ns`,\n * `path`, `type`, and — when available — `actor`, `value`, `error`, and the\n * `graph.trace()` reasoning annotation for the path.\n *\n * The returned graph mounts an `entries` node + `count` derived. Query\n * helpers (`byNode`, `byActor`, `byTimeRange`) operate on the cached\n * snapshot synchronously.\n */\nexport function auditTrail(target: Graph, opts: AuditTrailOptions = {}): AuditTrailGraph {\n\treturn new AuditTrailGraph(target, opts);\n}\n\n// ---------------------------------------------------------------------------\n// policyEnforcer\n// ---------------------------------------------------------------------------\n\n/** A single policy denial recorded by {@link PolicyEnforcerGraph}. */\nexport interface PolicyViolation {\n\ttimestamp_ns: number;\n\twall_clock_ns: number;\n\tpath: string;\n\tactor: Actor;\n\taction: GuardAction;\n\tmode: \"audit\" | \"enforce\";\n\t/** `\"observed\"` (audit mode after-the-fact) or `\"blocked\"` (enforce mode pre-write). */\n\tresult: \"observed\" | \"blocked\";\n}\n\n/** Options for {@link policyEnforcer}. */\nexport interface PolicyEnforcerOptions {\n\tname?: string;\n\tgraph?: GraphOptions;\n\t/**\n\t * `\"audit\"` (default) — observe events and record would-be denials;\n\t * does not block writes. Audit mode requires `lastMutation` attribution\n\t * on the audited node — anonymous/internal writes (no `actor` passed,\n\t * unguarded node) are skipped silently because the policy cannot be\n\t * evaluated without an actor.\n\t *\n\t * `\"enforce\"` — push guards onto target nodes so disallowed writes\n\t * throw {@link GuardDenied}. Reverted on dispose.\n\t */\n\tmode?: \"audit\" | \"enforce\";\n\t/**\n\t * Restrict enforcement to specific node paths (qualified). When omitted,\n\t * applies to every node visible in `target.describe()` at construction\n\t * time (subgraphs are walked transitively) AND subscribes to the full\n\t * topology tree via {@link watchTopologyTree}, so nodes added to\n\t * `target` OR any transitively-mounted subgraph after construction are\n\t * guarded automatically (enforce mode only).\n\t *\n\t * **Cost:** unrestricted mode runs `describe({detail:\"minimal\"})` once\n\t * at construction (O(N) over the graph tree) plus one topology\n\t * subscription per graph instance in the mount tree. Restricted mode\n\t * skips both and disables dynamic coverage — callers providing\n\t * `paths` must re-create on subgraph changes.\n\t */\n\tpaths?: readonly string[];\n\t/** Ring-buffer cap for the violations topic. Default: 1000. */\n\tviolationsLimit?: number;\n}\n\n/**\n * Reactive ABAC enforcement layer. Policies are reactive — pass a\n * `Node<readonly PolicyRuleData[]>` to allow LLMs (or any reactive source)\n * to update them at runtime; the enforcer rebinds its internal\n * {@link NodeGuard} on every push.\n */\nexport class PolicyEnforcerGraph extends Graph {\n\treadonly policies: Node<readonly PolicyRuleData[]>;\n\treadonly violations: TopicGraph<PolicyViolation>;\n\treadonly violationCount: Node<number>;\n\tprivate readonly _target: Graph;\n\tprivate readonly _mode: \"audit\" | \"enforce\";\n\tprivate _currentGuard: NodeGuard;\n\n\tconstructor(\n\t\ttarget: Graph,\n\t\tpolicies: readonly PolicyRuleData[] | Node<readonly PolicyRuleData[]>,\n\t\topts: PolicyEnforcerOptions,\n\t) {\n\t\tsuper(opts.name ?? `${target.name}_policy`, opts.graph);\n\t\tthis._target = target;\n\t\tthis._mode = opts.mode ?? \"audit\";\n\n\t\tconst policiesNode = isNode(policies)\n\t\t\t? policies\n\t\t\t: state<readonly PolicyRuleData[]>(policies, { name: \"policies\" });\n\t\tthis.policies = policiesNode;\n\t\tthis.add(\"policies\", this.policies);\n\n\t\tthis.violations = new TopicGraph<PolicyViolation>(\"violations\", {\n\t\t\tretainedLimit: opts.violationsLimit ?? 1000,\n\t\t});\n\t\tthis.mount(\"violations\", this.violations);\n\n\t\tthis.violationCount = derived<number>(\n\t\t\t[this.violations.events],\n\t\t\t([snapshot]) => (snapshot as readonly PolicyViolation[]).length,\n\t\t\t{\n\t\t\t\tname: \"violationCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: auditMeta(\"policy_violation_count\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"violationCount\", this.violationCount);\n\t\tthis.addDisposer(keepalive(this.violationCount));\n\n\t\t// Factory-time seed (COMPOSITION-GUIDE §28): cache the latest rules\n\t\t// inside a closure, refresh on each subscribe-pushed update, and read\n\t\t// closure inside the guard so policy updates take effect immediately.\n\t\tconst initialRules = (policiesNode.cache as readonly PolicyRuleData[] | undefined) ?? [];\n\t\tlet latestRules: readonly PolicyRuleData[] = initialRules;\n\t\tthis._currentGuard = policyFromRules(latestRules);\n\t\tconst offPolicies = policiesNode.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tlatestRules = (m[1] as readonly PolicyRuleData[] | undefined) ?? [];\n\t\t\t\t\tthis._currentGuard = policyFromRules(latestRules);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.addDisposer(offPolicies);\n\n\t\t// Determine which target paths to watch.\n\t\tconst paths = opts.paths != null ? [...opts.paths] : collectPaths(target);\n\n\t\tif (this._mode === \"enforce\") {\n\t\t\t// Track which paths are currently guarded so dynamic adds don't\n\t\t\t// double-wrap and removed nodes release guard handles.\n\t\t\tconst restorers = new Map<string, () => void>();\n\t\t\tconst wrapAndPush = (path: string): void => {\n\t\t\t\tif (restorers.has(path)) return;\n\t\t\t\tconst node = safeNode(target, path);\n\t\t\t\tif (!(node instanceof NodeImpl)) return;\n\t\t\t\tconst pathGuard: NodeGuard = (actor, action) => {\n\t\t\t\t\tconst ok = this._currentGuard(actor, action);\n\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\tthis._publishViolation(actor, action, path, \"blocked\");\n\t\t\t\t\t}\n\t\t\t\t\treturn ok;\n\t\t\t\t};\n\t\t\t\trestorers.set(path, node._pushGuard(pathGuard));\n\t\t\t};\n\t\t\t// Initial sweep: guard every path present at construction.\n\t\t\tfor (const path of paths) wrapAndPush(path);\n\n\t\t\t// Dynamic coverage: when `paths` was NOT explicitly provided, follow\n\t\t\t// the full topology tree (target + every transitively-mounted\n\t\t\t// subgraph, including subgraphs mounted after construction) so late\n\t\t\t// adds at any depth get guarded. `prefix` carries the qualified\n\t\t\t// path-prefix from `target` to the emitter graph.\n\t\t\tif (opts.paths == null) {\n\t\t\t\tconst offTopology = watchTopologyTree(target, (event, emitter, prefix) => {\n\t\t\t\t\tif (event.kind === \"added\") {\n\t\t\t\t\t\tif (event.nodeKind === \"node\") {\n\t\t\t\t\t\t\twrapAndPush(`${prefix}${event.name}`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Mount added. Walk just the newly-mounted subgraph's local\n\t\t\t\t\t\t\t// paths (scoped describe — O(M) in the mounted subtree)\n\t\t\t\t\t\t\t// rather than re-describing the entire target tree. The\n\t\t\t\t\t\t\t// emitter is the PARENT of the new mount; resolve the child\n\t\t\t\t\t\t\t// via its `_mounts` map.\n\t\t\t\t\t\t\tconst child = emitter._mounts.get(event.name);\n\t\t\t\t\t\t\tif (!(child instanceof Graph)) return;\n\t\t\t\t\t\t\tconst mountPrefix = `${prefix}${event.name}::`;\n\t\t\t\t\t\t\tconst localPaths = collectPaths(child);\n\t\t\t\t\t\t\tfor (const localPath of localPaths) {\n\t\t\t\t\t\t\t\t// `localPath` is relative to `child`; qualify with the\n\t\t\t\t\t\t\t\t// mount prefix so guard keys stay target-rooted.\n\t\t\t\t\t\t\t\twrapAndPush(\n\t\t\t\t\t\t\t\t\tlocalPath === \"\" ? `${prefix}${event.name}` : `${mountPrefix}${localPath}`,\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} else if (event.kind === \"removed\") {\n\t\t\t\t\t\t// TEARDOWN already unhooks the guard; release bookkeeping so\n\t\t\t\t\t\t// re-adds under the same qualified path re-wrap cleanly.\n\t\t\t\t\t\tif (event.nodeKind === \"node\") {\n\t\t\t\t\t\t\tconst qp = `${prefix}${event.name}`;\n\t\t\t\t\t\t\tconst r = restorers.get(qp);\n\t\t\t\t\t\t\tif (r != null) {\n\t\t\t\t\t\t\t\tr();\n\t\t\t\t\t\t\t\trestorers.delete(qp);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst mountQp = `${prefix}${event.name}`;\n\t\t\t\t\t\t\tconst mountPrefix = `${mountQp}::`;\n\t\t\t\t\t\t\tfor (const [p, r] of restorers) {\n\t\t\t\t\t\t\t\tif (p === mountQp || p.startsWith(mountPrefix)) {\n\t\t\t\t\t\t\t\t\tr();\n\t\t\t\t\t\t\t\t\trestorers.delete(p);\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});\n\t\t\t\tthis.addDisposer(offTopology);\n\t\t\t} else {\n\t\t\t\t// Restricted mode: subscribe to target.topology (own-graph only —\n\t\t\t\t// explicit `paths` means caller owns the path set) so node removals\n\t\t\t\t// release their restorers instead of leaking until enforcer dispose.\n\t\t\t\tconst offCleanup = target.topology.subscribe((msgs) => {\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tif (m[0] !== DATA) continue;\n\t\t\t\t\t\tconst event = m[1] as TopologyEvent;\n\t\t\t\t\t\tif (event.kind !== \"removed\" || event.nodeKind !== \"node\") continue;\n\t\t\t\t\t\tconst r = restorers.get(event.name);\n\t\t\t\t\t\tif (r != null) {\n\t\t\t\t\t\t\tr();\n\t\t\t\t\t\t\trestorers.delete(event.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tthis.addDisposer(offCleanup);\n\t\t\t}\n\t\t\tthis.addDisposer(() => {\n\t\t\t\tfor (const r of restorers.values()) r();\n\t\t\t\trestorers.clear();\n\t\t\t});\n\t\t} else {\n\t\t\t// Audit mode: observe writes, evaluate against current guard, record\n\t\t\t// violations without blocking. Use the structured observe stream so\n\t\t\t// `path` is supplied without per-node subscription bookkeeping.\n\t\t\tconst handle = target.observe({ timeline: true, structured: true });\n\t\t\tconst off = handle.onEvent((event) => {\n\t\t\t\tif (event.type !== \"data\" && event.type !== \"error\") return;\n\t\t\t\tconst path = event.path ?? \"\";\n\t\t\t\tif (!path) return;\n\t\t\t\tif (opts.paths != null && !opts.paths.includes(path)) return;\n\t\t\t\tconst node = safeNode(target, path);\n\t\t\t\tconst lastMutation = node?.lastMutation;\n\t\t\t\tif (lastMutation == null) return; // cannot attribute → no policy decision\n\t\t\t\tconst action: GuardAction = \"write\";\n\t\t\t\tif (this._currentGuard(lastMutation.actor, action)) return;\n\t\t\t\tthis._publishViolation(lastMutation.actor, action, path, \"observed\");\n\t\t\t});\n\t\t\tthis.addDisposer(() => {\n\t\t\t\toff();\n\t\t\t\thandle.dispose();\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate _publishViolation(\n\t\tactor: Actor,\n\t\taction: GuardAction,\n\t\tpath: string,\n\t\tresult: \"observed\" | \"blocked\",\n\t): void {\n\t\tthis.violations.publish({\n\t\t\ttimestamp_ns: monotonicNs(),\n\t\t\twall_clock_ns: wallClockNs(),\n\t\t\tpath,\n\t\t\tactor,\n\t\t\taction,\n\t\t\tmode: this._mode,\n\t\t\tresult,\n\t\t});\n\t}\n\n\t/** Snapshot of recorded violations. */\n\tall(): readonly PolicyViolation[] {\n\t\treturn this.violations.retained();\n\t}\n\n\tget mode(): \"audit\" | \"enforce\" {\n\t\treturn this._mode;\n\t}\n\n\tget target(): Graph {\n\t\treturn this._target;\n\t}\n}\n\n/**\n * Wraps a {@link Graph} with reactive policy enforcement. Pass either a\n * static rule list or a {@link Node} of rules (LLM-updatable). Records\n * `PolicyViolation` entries to `violations` topic; in `\"enforce\"` mode also\n * pushes guards onto target nodes so disallowed writes throw.\n */\nexport function policyEnforcer(\n\ttarget: Graph,\n\tpolicies: readonly PolicyRuleData[] | Node<readonly PolicyRuleData[]>,\n\topts: PolicyEnforcerOptions = {},\n): PolicyEnforcerGraph {\n\treturn new PolicyEnforcerGraph(target, policies, opts);\n}\n\n// ---------------------------------------------------------------------------\n// reactiveExplainPath\n// ---------------------------------------------------------------------------\n\n/**\n * Reactive {@link CausalChain} that recomputes whenever the audited graph\n * changes. Returns a `Node<CausalChain>` suitable for subscription, mounting,\n * or composition (e.g. inside `graphLens.why(node)`).\n *\n * **How it stays live:** an internal `version` state is bumped by an observer\n * attached to `target.observe()`; the derived chain depends on `version`, so\n * each mutation triggers a recompute. To avoid stalling on no-op events, only\n * `data`, `error`, `complete`, and `teardown` bump the version (matching the\n * audit defaults).\n */\nexport function reactiveExplainPath(\n\ttarget: Graph,\n\tfrom: string,\n\tto: string,\n\topts?: { maxDepth?: number; name?: string; findCycle?: boolean },\n): { node: Node<CausalChain>; dispose: () => void } {\n\t// Closure-held counter (COMPOSITION-GUIDE §28 / spec §3.6 sanctioned\n\t// pattern). We do NOT read `version.cache` from inside the subscribe\n\t// callback — that would be a P3 violation under batched waves where\n\t// multiple events deliver to the same listener with stale cache.\n\tlet v = 0;\n\tconst version = state(v, { name: \"explain_version\" });\n\tconst handle = target.observe({ timeline: true, structured: true });\n\tconst off = handle.onEvent((event) => {\n\t\tconst t = event.type;\n\t\tif (t !== \"data\" && t !== \"error\" && t !== \"complete\" && t !== \"teardown\") return;\n\t\tv += 1;\n\t\tversion.emit(v);\n\t});\n\n\tconst explainOpts = {\n\t\t...(opts?.maxDepth != null ? { maxDepth: opts.maxDepth } : {}),\n\t\t...(opts?.findCycle === true ? { findCycle: true as const } : {}),\n\t};\n\tconst node = derived<CausalChain>([version], () => target.explain(from, to, explainOpts), {\n\t\tname: opts?.name ?? \"explain\",\n\t\tdescribeKind: \"derived\",\n\t\tequals: (a, b) =>\n\t\t\ta.found === b.found &&\n\t\t\ta.reason === b.reason &&\n\t\t\ta.steps.length === b.steps.length &&\n\t\t\tcausalStepsEqual(a.steps, b.steps),\n\t\tmeta: auditMeta(\"explain_path\", { from, to }),\n\t});\n\tconst stopKeepalive = keepalive(node);\n\n\treturn {\n\t\tnode,\n\t\tdispose() {\n\t\t\toff();\n\t\t\thandle.dispose();\n\t\t\tstopKeepalive();\n\t\t},\n\t};\n}\n\nfunction causalStepsEqual(a: readonly CausalStep[], b: readonly CausalStep[]): boolean {\n\tfor (let i = 0; i < a.length; i++) {\n\t\tconst x = a[i]!;\n\t\tconst y = b[i]!;\n\t\tif (x.path !== y.path) return false;\n\t\tif (x.type !== y.type) return false;\n\t\tif (x.status !== y.status) return false;\n\t\tif (x.hop !== y.hop) return false;\n\t\tif (x.dep_index !== y.dep_index) return false;\n\t\tif (x.reason !== y.reason) return false;\n\t\t// Value identity — derived snapshots reuse same refs unless changed.\n\t\tif (x.value !== y.value) return false;\n\t\t// `lastMutation` is `Readonly<{actor, timestamp_ns}>`; identity compare\n\t\t// is sufficient because `_lastMutation` is replaced on every mutation\n\t\t// (new object per write) — same identity ⇒ no actor/timestamp change.\n\t\tif (x.lastMutation !== y.lastMutation) return false;\n\t\tconst xv = x.v;\n\t\tconst yv = y.v;\n\t\tif (xv !== yv) {\n\t\t\tif (xv == null || yv == null) return false;\n\t\t\tif (xv.id !== yv.id || xv.version !== yv.version) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// complianceSnapshot\n// ---------------------------------------------------------------------------\n\n/** Options for {@link complianceSnapshot}. */\nexport interface ComplianceSnapshotOptions {\n\taudit?: AuditTrailGraph;\n\tpolicies?: PolicyEnforcerGraph;\n\t/** Actor recorded as the snapshot taker. */\n\tactor?: Actor;\n}\n\n/** Output of {@link complianceSnapshot}. JSON-serializable. */\nexport interface ComplianceSnapshotResult {\n\tformat_version: 1;\n\ttimestamp_ns: number;\n\twall_clock_ns: number;\n\tactor?: Actor;\n\tgraph: GraphPersistSnapshot;\n\taudit?: { count: number; entries: AuditEntry[] };\n\tpolicies?: {\n\t\tmode: \"audit\" | \"enforce\";\n\t\trules: readonly PolicyRuleData[];\n\t\tviolations: readonly PolicyViolation[];\n\t};\n\t/**\n\t * Truncated SHA-256 hex (16 chars / ~64 bits) over a canonical encoding\n\t * of every field above (excluding `fingerprint` itself). Deterministic\n\t * across runs given identical inputs. Suitable for casual tamper-evidence\n\t * and content-addressed dedup; for full cryptographic strength, hash the\n\t * canonical JSON externally with Web Crypto / Node `crypto`.\n\t */\n\tfingerprint: string;\n}\n\n/**\n * One-shot point-in-time export of a {@link Graph}'s state plus optional\n * audit + policy bundles. Returns a JSON-serializable object with a\n * deterministic truncated-SHA-256 {@link ComplianceSnapshotResult.fingerprint}\n * over the canonical payload for tamper-evidence in regulatory archival.\n *\n * **Cryptographic strength:** the fingerprint is truncated to 64 bits for\n * compact archival. Collision-resistant for casual integrity checks but NOT\n * sufficient for adversarial tamper-evidence — pair with a full SHA-256\n * (or stronger) over the canonical JSON when regulatory requirements demand\n * collision resistance.\n */\nexport function complianceSnapshot(\n\ttarget: Graph,\n\topts: ComplianceSnapshotOptions = {},\n): ComplianceSnapshotResult {\n\tconst result: Omit<ComplianceSnapshotResult, \"fingerprint\"> = {\n\t\tformat_version: 1,\n\t\ttimestamp_ns: monotonicNs(),\n\t\twall_clock_ns: wallClockNs(),\n\t\tgraph: target.snapshot() as GraphPersistSnapshot,\n\t};\n\tif (opts.actor != null) result.actor = opts.actor;\n\tif (opts.audit != null) {\n\t\tconst entries = [...opts.audit.all()];\n\t\tresult.audit = { count: entries.length, entries };\n\t}\n\tif (opts.policies != null) {\n\t\tconst rules = (opts.policies.policies.cache as readonly PolicyRuleData[] | undefined) ?? [];\n\t\tresult.policies = {\n\t\t\tmode: opts.policies.mode,\n\t\t\trules,\n\t\t\tviolations: [...opts.policies.all()],\n\t\t};\n\t}\n\tconst fingerprint = computeFingerprint(result);\n\treturn { ...result, fingerprint };\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nfunction isNode<T>(x: unknown): x is Node<T> {\n\treturn typeof x === \"object\" && x !== null && \"subscribe\" in (x as object);\n}\n\nfunction safeNode(target: Graph, path: string): Node | undefined {\n\ttry {\n\t\treturn target.node(path);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction safeAnnotation(target: Graph, path: string): string | undefined {\n\ttry {\n\t\treturn target.annotation(path);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks every locally-registered node path in `target`, descending through\n * mounted subgraphs. Returns qualified paths.\n */\nfunction collectPaths(target: Graph): string[] {\n\tconst described = target.describe({ detail: \"minimal\" });\n\treturn Object.keys(described.nodes);\n}\n\n/**\n * Stable canonical JSON → truncated SHA-256 hex fingerprint (16 hex chars,\n * ~64-bit). Uses the same vendored sync SHA-256 as `core/versioning.ts`\n * `defaultHash`, so cross-module fingerprints stay consistent.\n *\n * Canonicalization handles cycles (recursion-stack tracker), `undefined`,\n * `bigint`, `Map`, `Set`, `Date`, `RegExp`, and typed arrays via typed\n * markers — see {@link canonicalize}.\n *\n * **Note:** truncated to 16 hex chars (~64-bit) for compact archival. For\n * full 256-bit cryptographic strength, hash {@link complianceSnapshot} JSON\n * externally with Web Crypto / Node `crypto`.\n */\nfunction computeFingerprint(value: unknown): string {\n\t// Pre-stringify our canonical form so `defaultHash`'s\n\t// `canonicalizeForHash` (which rejects unsafe integers) only ever sees a\n\t// JSON string. Compliance payloads carry `timestamp_ns` values that\n\t// exceed `Number.MAX_SAFE_INTEGER` — JSON.stringify handles them fine,\n\t// the hash function only cares about deterministic input bytes.\n\treturn defaultHash(JSON.stringify(canonicalize(value)));\n}\n\n/**\n * Cycle-safe canonical encoding. Uses a recursion-stack `Set` (push on\n * descent, pop on return) so legitimate DAG re-references are encoded as\n * themselves; only true cycles produce a `__circular: true` marker. Typed\n * markers preserve `undefined` / `bigint` / `Map` / `Set` / `Date` / `RegExp`\n * / typed-array information that bare `JSON.stringify` would silently drop\n * or collide with strings.\n */\nfunction canonicalize(value: unknown): unknown {\n\tconst stack = new Set<object>();\n\tconst walk = (v: unknown): unknown => {\n\t\tif (v === undefined) return { __undefined: true };\n\t\tif (v === null) return null;\n\t\tconst t = typeof v;\n\t\tif (t === \"bigint\") return { __bigint: (v as bigint).toString() };\n\t\tif (t !== \"object\") return v;\n\t\tconst obj = v as object;\n\t\tif (stack.has(obj)) return { __circular: true };\n\t\tstack.add(obj);\n\t\ttry {\n\t\t\tif (Array.isArray(obj)) {\n\t\t\t\treturn (obj as unknown[]).map(walk);\n\t\t\t}\n\t\t\tif (obj instanceof Date) {\n\t\t\t\treturn { __date: obj.toISOString() };\n\t\t\t}\n\t\t\tif (obj instanceof RegExp) {\n\t\t\t\treturn { __regexp: { source: obj.source, flags: obj.flags } };\n\t\t\t}\n\t\t\tif (obj instanceof Map) {\n\t\t\t\tconst entries = [...(obj as Map<unknown, unknown>).entries()].map(([k, mv]) => [\n\t\t\t\t\twalk(k),\n\t\t\t\t\twalk(mv),\n\t\t\t\t]);\n\t\t\t\treturn { __map: entries };\n\t\t\t}\n\t\t\tif (obj instanceof Set) {\n\t\t\t\tconst items = [...(obj as Set<unknown>)].map(walk);\n\t\t\t\treturn { __set: items };\n\t\t\t}\n\t\t\tif (ArrayBuffer.isView(obj)) {\n\t\t\t\tconst ta = obj as unknown as { length: number; [i: number]: number };\n\t\t\t\tconst arr: number[] = new Array(ta.length);\n\t\t\t\tfor (let i = 0; i < ta.length; i++) arr[i] = ta[i] ?? 0;\n\t\t\t\treturn { __typed_array: { ctor: obj.constructor.name, data: arr } };\n\t\t\t}\n\t\t\tconst out: Record<string, unknown> = {};\n\t\t\tfor (const k of Object.keys(obj as Record<string, unknown>).sort()) {\n\t\t\t\tout[k] = walk((obj as Record<string, unknown>)[k]);\n\t\t\t}\n\t\t\treturn out;\n\t\t} finally {\n\t\t\tstack.delete(obj);\n\t\t}\n\t};\n\treturn walk(value);\n}\n\n// `explainPath` / `CausalChain` / `CausalStep` are exported from `graph/`\n// at module root; do not re-export here to keep the namespace boundary clean\n// and avoid duplicate-identifier issues in bundled .d.ts.\n","/**\n * Centralised timestamp utilities.\n *\n * Convention: all graphrefly-ts timestamps use nanoseconds (`_ns` suffix).\n *\n * - {@link monotonicNs} — monotonic clock (ordering, durations, timeline events).\n * - {@link wallClockNs} — wall-clock (mutation attribution, cron emission).\n *\n * **Precision limits (JS platform):**\n *\n * - `monotonicNs`: effective ~microsecond precision. `performance.now()` returns\n * milliseconds with ~5µs resolution; the last 3 digits of the nanosecond value\n * are always zero. Python's `time.monotonic_ns()` gives true nanoseconds.\n *\n * - `wallClockNs`: ~256ns precision loss at current epoch. `Date.now() * 1e6`\n * produces values around 1.8×10¹⁸ which exceed IEEE 754's 2⁵³ safe integer\n * limit. Python's `time.time_ns()` (arbitrary-precision `int`) has no loss.\n * In practice this is irrelevant — JS is single-threaded, so sub-microsecond\n * timestamp collisions cannot occur.\n */\n\n/** Monotonic nanosecond timestamp via `performance.now()`. */\nexport function monotonicNs(): number {\n\treturn Math.trunc(performance.now() * 1_000_000);\n}\n\n/** Wall-clock nanosecond timestamp via `Date.now()`. */\nexport function wallClockNs(): number {\n\treturn Date.now() * 1_000_000;\n}\n","import type { Actor } from \"./actor.js\";\n\n/**\n * Actions checked by {@link NodeGuard}. `write` covers both {@link Node.down} and\n * {@link Node.up} today; finer-grained strings may be added later (e.g. `\"write.data\"`).\n */\nexport type GuardAction = \"write\" | \"signal\" | \"observe\" | (string & {});\n\nexport type NodeGuard = (actor: Actor, action: GuardAction) => boolean;\n\nexport type GuardDeniedDetails = {\n\tactor: Actor;\n\taction: GuardAction;\n\t/** Registry or options name when known */\n\tnodeName?: string;\n};\n\n/**\n * Thrown when a {@link NodeGuard} denies an action for a given actor.\n *\n * Carries the rejected `actor`, `action`, and optional `nodeName` for diagnostic\n * messages and middleware error handling.\n *\n * @example\n * ```ts\n * import { GuardDenied, policy } from \"@graphrefly/graphrefly-ts\";\n *\n * const guard = policy((allow) => { allow(\"observe\"); });\n * try {\n * if (!guard({ type: \"llm\", id: \"agent-1\" }, \"write\")) {\n * throw new GuardDenied(\n * { actor: { type: \"llm\", id: \"agent-1\" }, action: \"write\", nodeName: \"userInput\" },\n * );\n * }\n * } catch (e) {\n * if (e instanceof GuardDenied) console.error(e.action, e.actor.type); // \"write\" \"llm\"\n * }\n * ```\n */\nexport class GuardDenied extends Error {\n\treadonly actor: Actor;\n\treadonly action: GuardAction;\n\treadonly nodeName?: string;\n\n\t/**\n\t * @param details - Actor, action, and optional node name for the denial.\n\t * @param message - Optional override for the default error message.\n\t */\n\tconstructor(details: GuardDeniedDetails, message?: string) {\n\t\tsuper(\n\t\t\tmessage ??\n\t\t\t\t`GuardDenied: action \"${String(details.action)}\" denied for actor type \"${String(details.actor.type)}\"`,\n\t\t);\n\t\tthis.name = \"GuardDenied\";\n\t\tthis.actor = details.actor;\n\t\tthis.action = details.action;\n\t\tthis.nodeName = details.nodeName;\n\t}\n\n\t/** Qualified registry path when known (roadmap diagnostics: same as {@link nodeName}). */\n\tget node(): string | undefined {\n\t\treturn this.nodeName;\n\t}\n}\n\ntype Where = (actor: Actor) => boolean;\n\ntype Rule = {\n\tkind: \"allow\" | \"deny\";\n\tactions: Set<GuardAction>;\n\twhere: Where;\n};\n\nfunction normalizeActions(action: GuardAction | readonly GuardAction[]): GuardAction[] {\n\tif (Array.isArray(action)) {\n\t\treturn [...action];\n\t}\n\treturn [action as GuardAction];\n}\n\nfunction matchesActions(set: Set<GuardAction>, action: GuardAction): boolean {\n\treturn set.has(action) || set.has(\"*\" as GuardAction);\n}\n\nexport type PolicyAllow = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyDeny = (\n\taction: GuardAction | readonly GuardAction[],\n\topts?: { where?: Where },\n) => void;\n\nexport type PolicyRuleData = {\n\teffect: \"allow\" | \"deny\";\n\taction: GuardAction | readonly GuardAction[];\n\tactorType?: string | readonly string[];\n\tactorId?: string | readonly string[];\n\tclaims?: Record<string, unknown>;\n};\n\n/**\n * Declarative guard builder. Precedence: any matching **deny** blocks even if an allow also matches.\n * If no rule matches, the guard returns `false` (deny-by-default). Aligned with graphrefly-py `policy()`.\n *\n * @param build - Callback that registers `allow(...)` / `deny(...)` rules in order.\n * @returns A `NodeGuard` for use as `node({ guard })`.\n *\n * @example\n * ```ts\n * const guard = policy((allow, deny) => {\n * allow(\"observe\");\n * deny(\"write\", { where: (a) => a.type === \"llm\" });\n * });\n * ```\n */\nexport function policy(build: (allow: PolicyAllow, deny: PolicyDeny) => void): NodeGuard {\n\tconst rules: Rule[] = [];\n\tconst allow: PolicyAllow = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"allow\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tconst deny: PolicyDeny = (action, opts) => {\n\t\trules.push({\n\t\t\tkind: \"deny\",\n\t\t\tactions: new Set(normalizeActions(action)),\n\t\t\twhere: opts?.where ?? (() => true),\n\t\t});\n\t};\n\tbuild(allow, deny);\n\treturn (actor, action) => {\n\t\tlet denied = false;\n\t\tlet allowed = false;\n\t\tfor (const r of rules) {\n\t\t\tif (!matchesActions(r.actions, action)) continue;\n\t\t\tif (!r.where(actor)) continue;\n\t\t\tif (r.kind === \"deny\") {\n\t\t\t\tdenied = true;\n\t\t\t} else {\n\t\t\t\tallowed = true;\n\t\t\t}\n\t\t}\n\t\tif (denied) return false;\n\t\treturn allowed;\n\t};\n}\n\n/**\n * Rebuild a declarative guard from persisted policy data (snapshot-safe).\n *\n * Rules are deny-overrides, same semantics as {@link policy}.\n */\nexport function policyFromRules(rules: readonly PolicyRuleData[]): NodeGuard {\n\treturn policy((allow, deny) => {\n\t\tfor (const rule of rules) {\n\t\t\tconst actorTypes =\n\t\t\t\trule.actorType == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorType) ? rule.actorType : [rule.actorType]);\n\t\t\tconst actorIds =\n\t\t\t\trule.actorId == null\n\t\t\t\t\t? null\n\t\t\t\t\t: new Set(Array.isArray(rule.actorId) ? rule.actorId : [rule.actorId]);\n\t\t\tconst claimEntries = Object.entries(rule.claims ?? {});\n\t\t\tconst where: Where = (actor) => {\n\t\t\t\tif (actorTypes !== null && !actorTypes.has(String(actor.type))) return false;\n\t\t\t\tif (actorIds !== null && !actorIds.has(String(actor.id ?? \"\"))) return false;\n\t\t\t\tfor (const [key, value] of claimEntries) {\n\t\t\t\t\tif ((actor as Record<string, unknown>)[key] !== value) return false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t};\n\t\t\tif (rule.effect === \"deny\") {\n\t\t\t\tdeny(rule.action, { where });\n\t\t\t} else {\n\t\t\t\tallow(rule.action, { where });\n\t\t\t}\n\t\t}\n\t});\n}\n\nconst STANDARD_WRITE_TYPES = [\"human\", \"llm\", \"wallet\", \"system\"] as const;\n\n/**\n * Derives a best-effort `meta.access` hint string by probing `guard` with the\n * standard actor types `human`, `llm`, `wallet`, `system` for the `\"write\"` action\n * (roadmap 1.5). Aligned with graphrefly-py `access_hint_for_guard`.\n *\n * @param guard - Guard function to probe (typically from {@link policy}).\n * @returns `\"restricted\"` when no standard type is allowed; `\"both\"` when both\n * `human` and `llm` are allowed (plus optionally `system`); the single allowed\n * type name when only one passes; or a `\"+\"` joined list otherwise.\n *\n * @example\n * ```ts\n * import { policy, accessHintForGuard } from \"@graphrefly/graphrefly-ts\";\n *\n * const guardBoth = policy((allow) => { allow(\"write\"); });\n * accessHintForGuard(guardBoth); // \"both\"\n *\n * const guardHuman = policy((allow) => {\n * allow(\"write\", { where: (a) => a.type === \"human\" });\n * });\n * accessHintForGuard(guardHuman); // \"human\"\n * ```\n */\nexport function accessHintForGuard(guard: NodeGuard): string {\n\tconst allowed = STANDARD_WRITE_TYPES.filter((t) => guard({ type: t, id: \"\" }, \"write\"));\n\tif (allowed.length === 0) return \"restricted\";\n\tif (\n\t\tallowed.includes(\"human\") &&\n\t\tallowed.includes(\"llm\") &&\n\t\tallowed.every((t) => t === \"human\" || t === \"llm\" || t === \"system\")\n\t) {\n\t\treturn \"both\";\n\t}\n\tif (allowed.length === 1) return allowed[0];\n\treturn allowed.join(\"+\");\n}\n","/**\n * GraphReFly message protocol — §1 `~/src/graphrefly/GRAPHREFLY-SPEC.md`.\n * Emissions are always `[[Type, Data?], ...]` (no single-tuple shorthand).\n *\n * This file is protocol-pure:\n * - Message type symbols (10 built-ins).\n * - `Message` / `Messages` tuple types.\n * - `MessageTypeRegistration` interface (shape of a registry entry).\n *\n * It does NOT own the registry, tier lookups, or any cross-cutting singleton\n * state — that lives in `GraphReFlyConfig` (see `config.ts`) so custom\n * protocols can build isolated instances. Import this module when you need\n * the symbol constants or the tuple types; import `config.ts` when you need\n * tier / wire-crossing / registry lookups.\n */\n\n/** Subscribe-time handshake. Delivered to each new sink at the top of `subscribe()`. Tier 0. */\nexport const START = Symbol.for(\"graphrefly/START\");\n/** Value delivery (`DATA`, value). Tier 3 — deferred inside `batch()`. */\nexport const DATA = Symbol.for(\"graphrefly/DATA\");\n/** Phase 1: value about to change. Tier 1 — immediate. */\nexport const DIRTY = Symbol.for(\"graphrefly/DIRTY\");\n/** Phase 2: dirty pass completed, value unchanged. Tier 3 — deferred inside `batch()`. */\nexport const RESOLVED = Symbol.for(\"graphrefly/RESOLVED\");\n/** Clear cached state; do not auto-emit. Tier 1 — immediate. */\nexport const INVALIDATE = Symbol.for(\"graphrefly/INVALIDATE\");\n/** Suspend activity. Tier 2 — immediate. */\nexport const PAUSE = Symbol.for(\"graphrefly/PAUSE\");\n/** Resume after pause. Tier 2 — immediate. */\nexport const RESUME = Symbol.for(\"graphrefly/RESUME\");\n/** Permanent cleanup. Tier 5 — deferred to batch phase 4. */\nexport const TEARDOWN = Symbol.for(\"graphrefly/TEARDOWN\");\n/** Clean termination. Tier 4 — deferred to batch phase 3. */\nexport const COMPLETE = Symbol.for(\"graphrefly/COMPLETE\");\n/** Error termination. Tier 4 — deferred to batch phase 3. */\nexport const ERROR = Symbol.for(\"graphrefly/ERROR\");\n\n/** One protocol tuple: `[Type, optional payload]`. */\nexport type Message = readonly [symbol, unknown?];\n\n/** A batch of tuples — the wire shape for `node.down()` / `node.up()`. */\nexport type Messages = readonly Message[];\n\n// ---------------------------------------------------------------------------\n// Interned singletons for payload-free tuples\n// ---------------------------------------------------------------------------\n//\n// Every emission path used to allocate fresh `[[DIRTY]]`, `[[RESOLVED]]`,\n// etc. — two arrays per emit in the hot path. Since none of these tuples\n// carry a payload, one frozen instance is indistinguishable from a\n// fresh one. We intern them at module load and reuse forever. Only\n// `[DATA, v]`, `[ERROR, e]`, `[PAUSE, lockId]`, `[RESUME, lockId]` still\n// allocate per-call because they carry payloads.\n//\n// Downstream code MUST treat these as immutable. `Object.freeze` makes\n// accidental mutation throw in strict mode. Do not `push`, splice, or\n// otherwise mutate a Messages array that came from one of these.\n\n/** Singleton `[DIRTY]` tuple — payload-free, interned. */\nexport const DIRTY_MSG: Message = Object.freeze([DIRTY]) as Message;\n/** Singleton `[RESOLVED]` tuple — payload-free, interned. */\nexport const RESOLVED_MSG: Message = Object.freeze([RESOLVED]) as Message;\n/** Singleton `[INVALIDATE]` tuple — payload-free, interned. */\nexport const INVALIDATE_MSG: Message = Object.freeze([INVALIDATE]) as Message;\n/** Singleton `[START]` tuple — payload-free, interned. */\nexport const START_MSG: Message = Object.freeze([START]) as Message;\n/** Singleton `[COMPLETE]` tuple — payload-free, interned. */\nexport const COMPLETE_MSG: Message = Object.freeze([COMPLETE]) as Message;\n/** Singleton `[TEARDOWN]` tuple — payload-free, interned. */\nexport const TEARDOWN_MSG: Message = Object.freeze([TEARDOWN]) as Message;\n\n/** Pre-wrapped `[[DIRTY]]` for `_emit([DIRTY_ONLY_BATCH])`-style callers. */\nexport const DIRTY_ONLY_BATCH: Messages = Object.freeze([DIRTY_MSG]) as Messages;\n/** Pre-wrapped `[[RESOLVED]]`. */\nexport const RESOLVED_ONLY_BATCH: Messages = Object.freeze([RESOLVED_MSG]) as Messages;\n/** Pre-wrapped `[[INVALIDATE]]`. */\nexport const INVALIDATE_ONLY_BATCH: Messages = Object.freeze([INVALIDATE_MSG]) as Messages;\n/** Pre-wrapped `[[COMPLETE]]`. */\nexport const COMPLETE_ONLY_BATCH: Messages = Object.freeze([COMPLETE_MSG]) as Messages;\n/** Pre-wrapped `[[TEARDOWN]]`. */\nexport const TEARDOWN_ONLY_BATCH: Messages = Object.freeze([TEARDOWN_MSG]) as Messages;\n\n// ---------------------------------------------------------------------------\n// Registry entry shape\n// ---------------------------------------------------------------------------\n\n/**\n * Per-type record stored in a {@link GraphReFlyConfig}'s registry.\n *\n * - `tier` — signal tier (0–5 built-in; custom tiers allowed but should fit\n * the phase model used by `batch.ts`).\n * - `wireCrossing` — when `true`, forwarded across SSE/WebSocket/worker\n * adapters. Defaults to `tier >= 3` if omitted in registration input.\n * - `metaPassthrough` — when `false`, this message type is filtered out of\n * `Graph.signal` deliveries to meta companion nodes (spec §2.3). Meta\n * companions still receive everything via their primary's own cascade.\n * Defaults to `true` (meta receives the message).\n */\nexport interface MessageTypeRegistration {\n\ttier: number;\n\twireCrossing: boolean;\n\tmetaPassthrough: boolean;\n}\n\n/**\n * Input accepted by {@link GraphReFlyConfig.registerMessageType}. Only `tier`\n * is required; `wireCrossing` defaults to `tier >= 3`; `metaPassthrough`\n * defaults to `true`.\n */\nexport interface MessageTypeRegistrationInput {\n\ttier: number;\n\twireCrossing?: boolean;\n\tmetaPassthrough?: boolean;\n}\n","/**\n * GraphCodec — pluggable serialization for graph snapshots (Phase 8.6).\n *\n * Design reference: `archive/docs/SESSION-serialization-memory-footprint.md`\n *\n * The codec interface decouples snapshot format from graph internals.\n * Default is JSON (current behavior). DAG-CBOR and compressed variants\n * ship as optional codecs. FlatBuffers/Arrow for advanced tiers.\n *\n * Tiered representation:\n * HOT — JS objects (live propagation, no codec involved)\n * WARM — DAG-CBOR in-memory buffer (lazy hydration, delta checkpoints)\n * COLD — Arrow/Parquet (bulk storage, ML pipelines, archival)\n * PEEK — FlatBuffers (zero-copy read from dormant graph)\n *\n * Wire-protocol envelope (v1):\n *\n * [envelope_v=1: u8][name_len: u8][name: utf8][codec_v: u16 BE][payload: rest]\n *\n * `graph.snapshot({format: \"bytes\", codec: name})` wraps the codec's\n * `encode` output in this envelope; `Graph.decode(bytes)` auto-dispatches\n * via the config's codec registry — no out-of-band content-type needed.\n */\n\nimport type { GraphReFlyConfig } from \"../core/config.js\";\nimport type { GraphCheckpointRecord, GraphPersistSnapshot } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Core codec interface\n// ---------------------------------------------------------------------------\n\n/**\n * Encode/decode graph snapshots to/from binary.\n *\n * Implementations must be deterministic: `encode(x)` always produces the\n * same bytes for the same input. This is critical for CID computation (V1)\n * and snapshot hash-comparison.\n */\nexport interface GraphCodec {\n\t/** Human-readable name; used as the lookup key in the envelope and config registry. */\n\treadonly name: string;\n\n\t/**\n\t * Codec version. Bumps on breaking wire format changes; `decode` receives\n\t * this via the envelope so codecs can dispatch on historical layouts.\n\t * Must fit in a `u16` (0–65535).\n\t */\n\treadonly version: number;\n\n\t/** MIME-like content type identifier (e.g. `\"application/dag-cbor+zstd\"`). */\n\treadonly contentType: string;\n\n\t/** Encode a snapshot to binary. */\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array;\n\n\t/**\n\t * Decode binary back to a snapshot.\n\t *\n\t * `codecVersion` is the version that produced `buffer` (read from the\n\t * envelope). Omit when the caller is sure of the version (tests, one-shot\n\t * round-trips). Codecs that support multiple historical layouts dispatch\n\t * on this value.\n\t *\n\t * For lazy codecs, this may return a proxy that decodes nodes on access\n\t * (see {@link LazyGraphCodec}).\n\t */\n\tdecode(buffer: Uint8Array, codecVersion?: number): GraphPersistSnapshot;\n}\n\n/**\n * Extended codec that supports lazy (on-demand) node decoding.\n *\n * `decodeLazy` returns a snapshot where `nodes` is a Proxy — individual\n * nodes are decoded only when accessed. This enables near-zero cold-start\n * for large graphs (decode envelope + topology, skip node values until read).\n */\nexport interface LazyGraphCodec extends GraphCodec {\n\t/** Decode envelope and topology; defer node value decoding to access time. */\n\tdecodeLazy(buffer: Uint8Array, codecVersion?: number): GraphPersistSnapshot;\n}\n\n// ---------------------------------------------------------------------------\n// Delta checkpoint types (requires V0 — Phase 6.0)\n// ---------------------------------------------------------------------------\n\n/**\n * WAL entry. Unified with {@link GraphCheckpointRecord} — every record\n * already carries `mode` / `seq` / `timestamp_ns` / `format_version`, so the\n * WAL is just an ordered list of records. `replayWAL` walks this list.\n */\nexport type WALEntry = GraphCheckpointRecord;\n\n// ---------------------------------------------------------------------------\n// Eviction policy (dormant subgraph management)\n// ---------------------------------------------------------------------------\n\n/**\n * Policy for evicting dormant subgraphs to reduce memory.\n *\n * When a subgraph hasn't propagated for `idleTimeoutMs`, it is serialized\n * using the graph's codec and JS objects are released. Re-hydrated on next\n * access (read, propagation, describe).\n */\nexport interface EvictionPolicy {\n\t/** Milliseconds of inactivity before eviction. */\n\tidleTimeoutMs: number;\n\t/** Codec to use for serializing evicted subgraphs (default: graph's codec). */\n\tcodec?: GraphCodec;\n}\n\n/** Metadata about an evicted subgraph, exposed via describe(). */\nexport interface EvictedSubgraphInfo {\n\t/** True if currently evicted (serialized, JS objects released). */\n\tevicted: true;\n\t/** Wall-clock ns of last propagation before eviction. */\n\tlastActiveNs: bigint;\n\t/** Size of serialized buffer in bytes. */\n\tserializedBytes: number;\n\t/** Codec used for serialization. */\n\tcodecName: string;\n}\n\n// ---------------------------------------------------------------------------\n// JSON codec (default — wraps current behavior)\n// ---------------------------------------------------------------------------\n\n/**\n * Default JSON codec. Wraps `JSON.stringify`/`JSON.parse` with deterministic\n * key ordering (matching current `snapshot()` behavior).\n */\nexport const JsonCodec: GraphCodec = {\n\tname: \"json\",\n\tversion: 1,\n\tcontentType: \"application/json\",\n\n\tencode(snapshot: GraphPersistSnapshot): Uint8Array {\n\t\t// Deterministic: snapshot() already sorts keys.\n\t\tconst json = JSON.stringify(snapshot);\n\t\treturn new TextEncoder().encode(json);\n\t},\n\n\tdecode(buffer: Uint8Array, _codecVersion?: number): GraphPersistSnapshot {\n\t\tconst json = new TextDecoder().decode(buffer);\n\t\treturn JSON.parse(json) as GraphPersistSnapshot;\n\t},\n};\n\n// ---------------------------------------------------------------------------\n// DAG-CBOR codec (factory — requires @ipld/dag-cbor DI)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a DAG-CBOR codec.\n *\n * Requires `@ipld/dag-cbor` as a peer dependency. ~40-50% smaller than JSON,\n * deterministic encoding (required for V1 CID), CID links as native type.\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * const codec = createDagCborCodec(dagCbor);\n * config.registerCodec(codec);\n * const bytes = graph.snapshot({ format: \"bytes\", codec: \"dag-cbor\" });\n * ```\n */\nexport function createDagCborCodec(dagCbor: {\n\tencode: (value: unknown) => Uint8Array;\n\tdecode: (bytes: Uint8Array) => unknown;\n}): GraphCodec {\n\treturn {\n\t\tname: \"dag-cbor\",\n\t\tversion: 1,\n\t\tcontentType: \"application/dag-cbor\",\n\t\tencode: (snapshot) => dagCbor.encode(snapshot),\n\t\tdecode: (buffer, _codecVersion) => dagCbor.decode(buffer) as GraphPersistSnapshot,\n\t};\n}\n\n/**\n * Create a DAG-CBOR + zstd codec. ~80-90% smaller than JSON.\n *\n * Requires `@ipld/dag-cbor` and a zstd implementation (e.g. `fzstd` for\n * browser, `node:zlib` for Node.js).\n *\n * @example\n * ```ts\n * import * as dagCbor from \"@ipld/dag-cbor\";\n * import { compressSync, decompressSync } from \"fzstd\";\n * const codec = createDagCborZstdCodec(dagCbor, { compressSync, decompressSync });\n * config.registerCodec(codec);\n * ```\n */\nexport function createDagCborZstdCodec(\n\tdagCbor: {\n\t\tencode: (value: unknown) => Uint8Array;\n\t\tdecode: (bytes: Uint8Array) => unknown;\n\t},\n\tzstd: {\n\t\tcompressSync: (data: Uint8Array) => Uint8Array;\n\t\tdecompressSync: (data: Uint8Array) => Uint8Array;\n\t},\n): GraphCodec {\n\treturn {\n\t\tname: \"dag-cbor-zstd\",\n\t\tversion: 1,\n\t\tcontentType: \"application/dag-cbor+zstd\",\n\t\tencode: (snapshot) => zstd.compressSync(dagCbor.encode(snapshot)),\n\t\tdecode: (buffer, _codecVersion) =>\n\t\t\tdagCbor.decode(zstd.decompressSync(buffer)) as GraphPersistSnapshot,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Envelope (v1) — self-describing codec metadata prepended to payload bytes\n// ---------------------------------------------------------------------------\n\n/** Current envelope format version. Bump on breaking layout changes. */\nexport const ENVELOPE_VERSION = 1;\n\nconst ENVELOPE_MIN_LEN = 4; // env_v(1) + name_len(1) + codec_v(2) + name/payload(≥0)\n\n/**\n * Prepend the v1 envelope to `payload` identifying `codec`. The resulting\n * bytes are self-describing — any caller with access to the registering\n * {@link GraphReFlyConfig} can {@link decodeEnvelope} without knowing the\n * codec up front.\n *\n * Layout:\n * `[envelope_v=1: u8][name_len: u8][name: utf8][codec_v: u16 BE][payload: rest]`\n *\n * @throws If `codec.name` encodes to more than 255 UTF-8 bytes or\n * `codec.version` doesn't fit in a u16.\n */\nexport function encodeEnvelope(\n\tcodec: Pick<GraphCodec, \"name\" | \"version\">,\n\tpayload: Uint8Array,\n): Uint8Array {\n\tconst nameBytes = new TextEncoder().encode(codec.name);\n\tif (nameBytes.length === 0 || nameBytes.length > 255) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: codec name \"${codec.name}\" encodes to ${nameBytes.length} bytes (must be 1–255)`,\n\t\t);\n\t}\n\tconst cv = codec.version;\n\tif (!Number.isInteger(cv) || cv < 0 || cv > 0xffff) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: codec.version ${cv} out of u16 range (expected integer 0–65535)`,\n\t\t);\n\t}\n\t// Guard against RangeError-on-alloc for very large payloads — we need\n\t// `Number.isSafeInteger` math on `1 + 1 + nameBytes.length + 2 +\n\t// payload.length` and the resulting Uint8Array must fit within the\n\t// platform limit (2³² − 1 bytes on 64-bit JS engines).\n\tconst totalLen = 1 + 1 + nameBytes.length + 2 + payload.length;\n\tif (totalLen > 0xffffffff) {\n\t\tthrow new Error(\n\t\t\t`encodeEnvelope: total envelope size ${totalLen} exceeds 2^32-1 bytes (payload ${payload.length} bytes)`,\n\t\t);\n\t}\n\tconst out = new Uint8Array(totalLen);\n\tlet i = 0;\n\tout[i++] = ENVELOPE_VERSION;\n\tout[i++] = nameBytes.length;\n\tout.set(nameBytes, i);\n\ti += nameBytes.length;\n\tout[i++] = (cv >>> 8) & 0xff;\n\tout[i++] = cv & 0xff;\n\tout.set(payload, i);\n\treturn out;\n}\n\n/**\n * Inverse of {@link encodeEnvelope}. Reads the header, resolves the codec\n * via `config.lookupCodec(name)`, and returns the codec + its version + the\n * inner payload slice. The caller feeds `payload` to `codec.decode(payload,\n * codecVersion)` — or uses {@link Graph.decode} which does both steps.\n *\n * @throws If the envelope is truncated, the version is unsupported, or the\n * named codec isn't registered on `config`.\n */\nexport function decodeEnvelope(\n\tbytes: Uint8Array,\n\tconfig: GraphReFlyConfig,\n): { codec: GraphCodec; codecVersion: number; payload: Uint8Array } {\n\tif (bytes.length < ENVELOPE_MIN_LEN) {\n\t\tthrow new Error(`decodeEnvelope: bytes too short (${bytes.length} < ${ENVELOPE_MIN_LEN})`);\n\t}\n\tlet i = 0;\n\tconst envVersion = bytes[i++]!;\n\tif (envVersion !== ENVELOPE_VERSION) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: unsupported envelope version ${envVersion} (expected ${ENVELOPE_VERSION})`,\n\t\t);\n\t}\n\tconst nameLen = bytes[i++]!;\n\tif (nameLen === 0) {\n\t\tthrow new Error(\"decodeEnvelope: name_len must be >= 1\");\n\t}\n\tif (i + nameLen + 2 > bytes.length) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: envelope truncated (need ${i + nameLen + 2} bytes, have ${bytes.length})`,\n\t\t);\n\t}\n\tconst name = new TextDecoder().decode(bytes.subarray(i, i + nameLen));\n\ti += nameLen;\n\tconst codecVersion = ((bytes[i]! << 8) | bytes[i + 1]!) >>> 0;\n\ti += 2;\n\tconst payload = bytes.subarray(i);\n\tconst codec = config.lookupCodec<GraphCodec>(name);\n\tif (codec == null) {\n\t\tthrow new Error(\n\t\t\t`decodeEnvelope: codec \"${name}\" not registered (envelope codec_v=${codecVersion})`,\n\t\t);\n\t}\n\treturn { codec, codecVersion, payload };\n}\n\n/**\n * Register the built-in {@link JsonCodec} on a config. Called once on\n * `defaultConfig` at module load so `graph.snapshot({format: \"bytes\", codec:\n * \"json\"})` works out of the box. Test / isolated configs should call this\n * manually before the first node is created.\n */\nexport function registerBuiltinCodecs(config: GraphReFlyConfig): void {\n\tconfig.registerCodec(JsonCodec);\n}\n\n// ---------------------------------------------------------------------------\n// WAL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a snapshot from a WAL (sequence of {@link GraphCheckpointRecord}s).\n *\n * - Must start with a `\"full\"` record carrying a baseline snapshot — that's\n * the anchor {@link Graph.attachStorage} always emits on the first flush\n * of any tier (and every `compactEvery`-th flush thereafter).\n * - Subsequent `\"full\"` entries (compaction points) **replace** the result\n * wholesale.\n * - `\"diff\"` entries roll forward by applying the structural diff —\n * added nodes (via `nodesAddedFull`), removed nodes, and changed fields\n * are reflected into the accumulated snapshot.\n *\n * Validates monotonic `seq` progression across entries.\n */\nexport function replayWAL(entries: readonly WALEntry[]): GraphPersistSnapshot {\n\tif (entries.length === 0) {\n\t\tthrow new Error(\"WAL is empty — need at least one full snapshot\");\n\t}\n\n\tconst first = entries[0]!;\n\tif (first.mode !== \"full\") {\n\t\tthrow new Error(\"WAL must start with a full record carrying a baseline snapshot\");\n\t}\n\n\tlet result: GraphPersistSnapshot = JSON.parse(JSON.stringify(first.snapshot));\n\tlet prevSeq: number = first.seq;\n\n\tfor (let i = 1; i < entries.length; i++) {\n\t\tconst entry = entries[i]!;\n\t\tif (entry.seq <= prevSeq) {\n\t\t\tthrow new Error(\n\t\t\t\t`WAL chain broken at index ${i}: seq=${entry.seq} must exceed prev seq=${prevSeq}`,\n\t\t\t);\n\t\t}\n\n\t\tif (entry.mode === \"full\") {\n\t\t\t// Replace baseline wholesale (Unit 23 D fix — Object.assign left\n\t\t\t// stale keys from pre-compact state visible).\n\t\t\tresult = JSON.parse(JSON.stringify(entry.snapshot));\n\t\t\tprevSeq = entry.seq;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// mode === \"diff\": apply structural diff to the accumulated snapshot.\n\t\tconst diff = entry.diff;\n\t\t// Apply removes first so a path reused across a remove+add in a single\n\t\t// diff lands on the `nodesAddedFull` slice rather than being wiped.\n\t\tfor (const path of diff.nodesRemoved) {\n\t\t\tdelete result.nodes[path];\n\t\t}\n\t\t// Reinstate added nodes from the full-slice payload carried by\n\t\t// GraphWALDiff. Deep-clone so later mutations don't alias the WAL\n\t\t// entry's source slice.\n\t\tconst addedFull = diff.nodesAddedFull;\n\t\tif (addedFull != null) {\n\t\t\tfor (const [path, slice] of Object.entries(addedFull)) {\n\t\t\t\tresult.nodes[path] = JSON.parse(JSON.stringify(slice));\n\t\t\t}\n\t\t}\n\t\tfor (const change of diff.nodesChanged) {\n\t\t\tconst existing = result.nodes[change.path];\n\t\t\tif (existing == null) continue;\n\t\t\t(existing as Record<string, unknown>)[change.field] = change.to;\n\t\t}\n\n\t\t// Edges are derived from node `_deps` at restore time (Unit 7) — no\n\t\t// separate edge-patch pass.\n\t\tprevSeq = entry.seq;\n\t}\n\n\treturn result;\n}\n","/**\n * Who is performing an operation (attribution + ABAC input).\n *\n * @see GRAPHREFLY-SPEC — roadmap Phase 1.5 (Actor & Guard).\n */\nexport type Actor = {\n\ttype: \"human\" | \"llm\" | \"wallet\" | \"system\" | string;\n\tid: string;\n} & Record<string, unknown>;\n\n/** Default actor when none is passed ({@link normalizeActor}). */\nexport const DEFAULT_ACTOR: Actor = { type: \"system\", id: \"\" };\n\n/**\n * Fills missing `type` / `id` on an actor and returns {@link DEFAULT_ACTOR} when input is undefined.\n *\n * @param actor - Optional partial actor from a transport hint.\n * @returns A normalized `Actor` safe to pass to guards and graph APIs.\n *\n * @example\n * ```ts\n * import { normalizeActor } from \"@graphrefly/graphrefly-ts\";\n *\n * normalizeActor({ type: \"human\", id: \"u1\" });\n * ```\n */\nexport function normalizeActor(actor?: Actor): Actor {\n\tif (actor == null) return DEFAULT_ACTOR;\n\tconst { type, id, ...rest } = actor;\n\treturn {\n\t\ttype: type ?? \"system\",\n\t\tid: id ?? \"\",\n\t\t...rest,\n\t} as Actor;\n}\n","/**\n * Batch deferral for tier-3+ messages, plus per-node emit coalescing inside\n * explicit `batch()` scopes.\n *\n * **Canonical invariant:** GRAPHREFLY-SPEC.md §1.3.7 — inside a batch,\n * tier 0–2 signals propagate immediately; tier 3 (DATA/RESOLVED), tier 4\n * (COMPLETE/ERROR), and tier 5 (TEARDOWN) are queued and drained in ascending\n * phase order after the outermost `batch()` callback returns.\n *\n * **Per-node emit coalescing (Bug 2 fix, 2026-04-17).** Inside an explicit\n * `batch()` scope, consecutive emissions from the same node accumulate in\n * `NodeImpl._batchPendingMessages` (see JSDoc there) instead of each producing\n * a separate downstream wave. K `.emit()` calls to the same source collapse to\n * one coalesced `downWithBatch` call per child edge at batch end. Outside batch\n * (or during drain), coalescing does NOT apply — each emit produces its own wave.\n *\n * **Phase vocabulary:**\n * - Phase 1 = tiers 0–2 — immediate, never queued.\n * - Phase 2 = tier 3 — {@link drainPhase2}. Value settlements.\n * - Phase 3 = tier 4 — {@link drainPhase3}. Terminal signals.\n * - Phase 4 = tier 5 — {@link drainPhase4}. TEARDOWN (unified deferral).\n *\n * Drain rule: fire any pending flush hooks first, then the lowest non-empty\n * phase. Re-enqueues during drain (and hooks registered by reentrant batches\n * inside subscriber callbacks) bump the loop back to the top so newly-added\n * hooks and closures get processed.\n */\n\nimport type { Messages } from \"./messages.js\";\n\nconst MAX_DRAIN_ITERATIONS = 1000;\n\nlet batchDepth = 0;\nlet flushInProgress = false;\n\n/** Tier 3 (DATA/RESOLVED) deferral queue — drained first. */\nconst drainPhase2: Array<() => void> = [];\n/** Tier 4 (COMPLETE/ERROR) deferral queue — drained after phase 2. */\nconst drainPhase3: Array<() => void> = [];\n/** Tier 5 (TEARDOWN) deferral queue — drained last. */\nconst drainPhase4: Array<() => void> = [];\n\n/**\n * Per-batch flush hooks. Each hook is registered by a node the first time\n * it accumulates an emission inside an explicit `batch()` scope (Bug 2 —\n * per-node emit coalescing). Hooks fire at the head of `drainPending`,\n * before the standard tier-3/4/5 drain queues — they call `downWithBatch`\n * with the node's accumulated multi-message batch, which enqueues the\n * tier-3+ portion into `drainPhase2/3/4` for the standard loop.\n *\n * On a `batch()` throw, hooks still fire so each node clears its pending\n * state (they're idempotent — the side-effects are wiped because the\n * drainPhase queues that they enqueue into are cleared in the same finally\n * block).\n */\nconst flushHooks: Array<() => void> = [];\n\n/**\n * Returns whether the current call stack is inside a batch scope **or** while\n * a deferred drain is in progress. Nested `downWithBatch` calls during drain\n * still defer (they bump the drain loop).\n */\nexport function isBatching(): boolean {\n\treturn batchDepth > 0 || flushInProgress;\n}\n\n/**\n * Returns whether the current call stack is inside an **explicit** `batch()`\n * scope. Excludes `flushInProgress` — i.e. emissions that happen during a\n * drain (e.g. inside a fn callback) are NOT explicitly batched and should\n * not trigger per-node coalescing (Bug 2).\n */\nexport function isExplicitlyBatching(): boolean {\n\treturn batchDepth > 0;\n}\n\n/**\n * Register a hook to fire at the head of the next `drainPending`. Used by\n * `NodeImpl._emit` to flush its per-batch accumulator (Bug 2). If called\n * outside an explicit batch the hook fires immediately, since there's no\n * drain coming.\n */\nexport function registerBatchFlushHook(hook: () => void): void {\n\tif (batchDepth > 0) {\n\t\tflushHooks.push(hook);\n\t} else {\n\t\thook();\n\t}\n}\n\n/**\n * Runs `fn` inside a batch scope. Nested `batch()` calls share one deferral\n * queue. If `fn` throws, deferred work for the outer frame is discarded\n * (unless a drain is already in progress — cross-language decision A4).\n */\nexport function batch(fn: () => void): void {\n\tbatchDepth += 1;\n\tlet threw = false;\n\ttry {\n\t\tfn();\n\t} catch (e) {\n\t\tthrew = true;\n\t\tthrow e;\n\t} finally {\n\t\tbatchDepth -= 1;\n\t\tif (batchDepth === 0) {\n\t\t\tif (threw) {\n\t\t\t\tif (!flushInProgress) {\n\t\t\t\t\t// Fire any per-node flush hooks so nodes clear their\n\t\t\t\t\t// pending state. The downWithBatch calls those hooks\n\t\t\t\t\t// make enqueue into drainPhase queues — those queues\n\t\t\t\t\t// are cleared right after, so the side-effects are\n\t\t\t\t\t// wiped. Net result: clean node state, no delivery.\n\t\t\t\t\tconst hooks = flushHooks.splice(0);\n\t\t\t\t\tfor (const h of hooks) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\th();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t/* best-effort */\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdrainPhase2.length = 0;\n\t\t\t\t\tdrainPhase3.length = 0;\n\t\t\t\t\tdrainPhase4.length = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdrainPending();\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction drainPending(): void {\n\tconst ownsFlush = !flushInProgress;\n\tif (ownsFlush) flushInProgress = true;\n\n\tconst errors: unknown[] = [];\n\n\tlet iterations = 0;\n\ttry {\n\t\t// Loop while EITHER tier-3+ deferred work OR pending flush hooks exist.\n\t\t// Hooks can be re-registered mid-drain by reentrant `batch()` calls\n\t\t// inside subscriber callbacks; checking `flushHooks` each iteration\n\t\t// (not just before the loop) ensures those late hooks fire too.\n\t\twhile (\n\t\t\tdrainPhase2.length > 0 ||\n\t\t\tdrainPhase3.length > 0 ||\n\t\t\tdrainPhase4.length > 0 ||\n\t\t\t(ownsFlush && flushHooks.length > 0)\n\t\t) {\n\t\t\t// Fire any pending flush hooks FIRST so their downWithBatch calls\n\t\t\t// enqueue tier-3+ work into drainPhase before we process it.\n\t\t\tif (ownsFlush && flushHooks.length > 0) {\n\t\t\t\tconst hooks = flushHooks.splice(0);\n\t\t\t\tfor (const h of hooks) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\th();\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue; // restart loop — hooks may have enqueued tier-3+ work or more hooks\n\t\t\t}\n\t\t\titerations += 1;\n\t\t\tif (iterations > MAX_DRAIN_ITERATIONS) {\n\t\t\t\tdrainPhase2.length = 0;\n\t\t\t\tdrainPhase3.length = 0;\n\t\t\t\tdrainPhase4.length = 0;\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`batch drain exceeded ${MAX_DRAIN_ITERATIONS} iterations — likely a reactive cycle`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Always drain the lowest non-empty phase. Re-enqueues at any level\n\t\t\t// cause the next iteration to restart from phase 2 if needed.\n\t\t\tconst queue =\n\t\t\t\tdrainPhase2.length > 0 ? drainPhase2 : drainPhase3.length > 0 ? drainPhase3 : drainPhase4;\n\t\t\tconst ops = queue.splice(0);\n\t\t\tfor (const run of ops) {\n\t\t\t\ttry {\n\t\t\t\t\trun();\n\t\t\t\t} catch (e) {\n\t\t\t\t\terrors.push(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tif (ownsFlush) flushInProgress = false;\n\t}\n\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1) {\n\t\tthrow new AggregateError(errors, \"batch drain: multiple callbacks threw\");\n\t}\n}\n\n/**\n * Deliver pre-sorted messages through `sink` with tier-based deferral applied.\n *\n * `messages` MUST be in ascending tier order (produced by `_frameBatch` in\n * `node.ts`); the walker exploits that invariant to find phase cuts in one\n * pass without re-sorting.\n *\n * Behavior:\n * - Tier 0–2 — delivered synchronously.\n * - Tier 3 — deferred to {@link drainPhase2} when batching, else synchronous.\n * - Tier 4 — deferred to {@link drainPhase3} when batching, else synchronous.\n * - Tier 5 — deferred to {@link drainPhase4} when batching, else synchronous.\n *\n * Tier-classification uses the caller-supplied `tierOf` so that batch stays\n * decoupled from `GraphReFlyConfig`. NodeImpl passes `config.tierOf` (a\n * pre-bound closure built once in the config constructor) at the emit site;\n * alternate configs can pass their own lookup.\n */\nexport function downWithBatch(\n\tsink: (messages: Messages) => void,\n\tmessages: Messages,\n\ttierOf: (t: symbol) => number,\n): void {\n\tif (messages.length === 0) return;\n\n\t// Fast path: single message (hot in propagation).\n\tif (messages.length === 1) {\n\t\tconst tier = tierOf(messages[0][0]);\n\t\tif (tier < 3 || !isBatching()) {\n\t\t\tsink(messages);\n\t\t\treturn;\n\t\t}\n\t\tconst queue = tier >= 5 ? drainPhase4 : tier === 4 ? drainPhase3 : drainPhase2;\n\t\tqueue.push(() => sink(messages));\n\t\treturn;\n\t}\n\n\t// Multi-message: walk once over pre-sorted input, find phase cuts.\n\t// Monotone tier order means `phase2Start <= phase3Start <= phase4Start`.\n\tconst n = messages.length;\n\tlet phase2Start = n;\n\tlet phase3Start = n;\n\tlet phase4Start = n;\n\n\tlet i = 0;\n\twhile (i < n && tierOf(messages[i][0]) < 3) i++;\n\tphase2Start = i;\n\twhile (i < n && tierOf(messages[i][0]) === 3) i++;\n\tphase3Start = i;\n\twhile (i < n && tierOf(messages[i][0]) === 4) i++;\n\tphase4Start = i;\n\t// Anything from phase4Start..n has tier >= 5.\n\n\tconst batching = isBatching();\n\n\tif (phase2Start > 0) {\n\t\t// Immediate tier 0–2 region.\n\t\tconst immediate = messages.slice(0, phase2Start);\n\t\tsink(immediate);\n\t}\n\n\tif (phase3Start > phase2Start) {\n\t\tconst phase2 = messages.slice(phase2Start, phase3Start);\n\t\tif (batching) drainPhase2.push(() => sink(phase2));\n\t\telse sink(phase2);\n\t}\n\n\tif (phase4Start > phase3Start) {\n\t\tconst phase3 = messages.slice(phase3Start, phase4Start);\n\t\tif (batching) drainPhase3.push(() => sink(phase3));\n\t\telse sink(phase3);\n\t}\n\n\tif (n > phase4Start) {\n\t\tconst phase4 = messages.slice(phase4Start, n);\n\t\tif (batching) drainPhase4.push(() => sink(phase4));\n\t\telse sink(phase4);\n\t}\n}\n","/**\n * Singleton protocol config. Holds the message-type registry, the\n * `onMessage` / `onSubscribe` hooks, versioning defaults, and the freeze flag.\n *\n * Layering: this file is protocol-pure. It imports only from `messages.ts`\n * and declares opaque type shapes for handlers — the concrete default\n * implementations and the `defaultConfig` instance live in `node.ts` so that\n * handler bodies can touch `NodeImpl` internals without creating a cycle.\n *\n * Two access paths:\n * 1. **Default instance** (`defaultConfig` in `node.ts`) — use\n * `configure((cfg) => ...)` at app startup; every node implicitly binds to it.\n * 2. **Isolated instance** (`new GraphReFlyConfig(...)`) — pass via\n * `opts.config` for test isolation or custom protocol stacks.\n *\n * A config **freezes on first getter read** of any hook (`onMessage`,\n * `onSubscribe`). `NodeImpl`'s constructor intentionally touches one of these\n * on first use so configuration cannot drift once nodes exist.\n */\n\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Message,\n\ttype Messages,\n\ttype MessageTypeRegistration,\n\ttype MessageTypeRegistrationInput,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tSTART,\n\tTEARDOWN,\n} from \"./messages.js\";\nimport type { HashFn, VersioningLevel } from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Handler type shapes\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal node surface visible to default handlers. Concrete `NodeImpl`\n * implements this plus a large set of package-private fields; handlers that\n * need the richer surface cast to the concrete type in `node.ts`.\n */\nexport interface NodeCtx {\n\treadonly name?: string;\n\treadonly status: string;\n\treadonly cache: unknown;\n}\n\n/** Imperative actions available inside a node's compute function (§5). */\nexport interface NodeActions {\n\t/**\n\t * Sugar for `down([[DATA, value]])`. One call = one wave with a\n\t * single DATA payload. The emit pipeline auto-prefixes `[DIRTY]`,\n\t * runs equals substitution against the live cache, and dispatches\n\t * to sinks with phase deferral. Diamond-safe by construction.\n\t */\n\temit(value: unknown): void;\n\t/**\n\t * Send one or more messages downstream. Accepts either a single\n\t * {@link Message} tuple or a {@link Messages} array of tuples. One\n\t * call = one wave: the emit pipeline tier-sorts the input,\n\t * auto-prefixes `[DIRTY]` when a tier-3 payload is present and the\n\t * node isn't already dirty, runs equals substitution, then\n\t * dispatches. Multiple calls produce multiple waves.\n\t */\n\tdown(messageOrMessages: Message | Messages): void;\n\t/**\n\t * Send one or more messages upstream. Accepts the same shapes as\n\t * {@link down}. Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR)\n\t * are downstream-only and will throw — up is for DIRTY, INVALIDATE,\n\t * PAUSE, RESUME, and TEARDOWN only. No cache advance, no equals,\n\t * no framing — a plain forward to every dep.\n\t */\n\tup(messageOrMessages: Message | Messages): void;\n}\n\n/**\n * Message-flow context passed to {@link OnMessageHandler}.\n *\n * - `\"down-in\"` — message arriving from a dep (identified by `depIndex`).\n * - `\"up-in\"` — message arriving from a sink.\n */\nexport type MessageContext = { direction: \"down-in\"; depIndex: number } | { direction: \"up-in\" };\n\n/**\n * Per-sink context passed to {@link OnSubscribeHandler}.\n */\nexport interface SubscribeContext {\n\t/** Post-subscribe sink count. `1` means first subscriber after 0. */\n\tsinkCount: number;\n\t/** True when this subscribe cleared a resubscribable terminal state. */\n\tafterTerminalReset: boolean;\n}\n\n/**\n * Singleton message interceptor. Called for every message in either direction\n * before the default per-tier dispatch runs. Return `\"consume\"` to suppress\n * default handling.\n */\nexport type OnMessageHandler = (\n\tnode: NodeCtx,\n\tmsg: Message,\n\tctx: MessageContext,\n\tactions: NodeActions,\n) => \"consume\" | undefined;\n\n/**\n * Singleton subscribe ceremony. Fires for every sink subscribe on every node.\n * Default implementation emits the START handshake (+ cached DATA when\n * present) to the new sink. Return a cleanup function to run on unsubscribe.\n */\nexport type OnSubscribeHandler = (\n\tnode: NodeCtx,\n\tsink: (messages: Messages) => void,\n\tctx: SubscribeContext,\n\tactions: NodeActions,\n) => (() => void) | undefined;\n\n/**\n * Event payload for {@link GlobalInspectorHook}. One event fires per outgoing\n * message batch from any node bound to the config.\n *\n * - `kind: \"emit\"` — fires after equals substitution (`finalMessages`) and\n * before sink dispatch. `messages` is the exact batch sinks see.\n */\nexport type GlobalInspectorEvent = {\n\tkind: \"emit\";\n\tnode: NodeCtx;\n\tmessages: Messages;\n};\n\n/**\n * Process-global observability hook for full-graph tracing\n * (Redux-DevTools-style action history). Fires from every node's `_emit`\n * waist whenever {@link GraphReFlyConfig.inspectorEnabled} is `true`.\n *\n * Distinct from per-node `_setInspectorHook` (which is the dep-message /\n * fn-run causal trace used by `Graph.observe(path, { causal, derived })`).\n * Use the global hook to record every emission across every node — useful for\n * time-travel debuggers, tracers, and replay tooling. Use the per-node hook\n * to attribute a single subscribed path's wave to its driving deps.\n *\n * Errors thrown from the hook are swallowed — instrumentation must not break\n * the data plane.\n */\nexport type GlobalInspectorHook = (event: GlobalInspectorEvent) => void;\n\n// ---------------------------------------------------------------------------\n// GraphReFlyConfig\n// ---------------------------------------------------------------------------\n\n/**\n * Singleton protocol config.\n *\n * A config freezes on first getter read of any hook. After freeze, any\n * attempt to mutate (register a message type, set a hook) throws.\n */\nexport class GraphReFlyConfig {\n\tprivate _messageTypes = new Map<symbol, MessageTypeRegistration>();\n\tprivate _codecs = new Map<string, { readonly name: string; readonly version: number }>();\n\tprivate _onMessage: OnMessageHandler;\n\tprivate _onSubscribe: OnSubscribeHandler;\n\tprivate _defaultVersioning: VersioningLevel | undefined;\n\tprivate _defaultHashFn: HashFn | undefined;\n\tprivate _inspectorEnabled: boolean = !(\n\t\ttypeof process !== \"undefined\" && process.env?.NODE_ENV === \"production\"\n\t);\n\tprivate _globalInspector?: GlobalInspectorHook;\n\tprivate _frozen = false;\n\n\t/**\n\t * Pre-bound tier lookup — shared by every node bound to this config. Since\n\t * the registry is frozen on first hook access, this closure can be built\n\t * once in the constructor and handed directly to `downWithBatch` /\n\t * `_frameBatch` paths without per-node or per-emission `.bind(config)`\n\t * allocation.\n\t */\n\treadonly tierOf: (t: symbol) => number;\n\n\tconstructor(init: {\n\t\tonMessage: OnMessageHandler;\n\t\tonSubscribe: OnSubscribeHandler;\n\t\tdefaultVersioning?: VersioningLevel;\n\t\tdefaultHashFn?: HashFn;\n\t}) {\n\t\tthis._onMessage = init.onMessage;\n\t\tthis._onSubscribe = init.onSubscribe;\n\t\tthis._defaultVersioning = init.defaultVersioning;\n\t\tthis._defaultHashFn = init.defaultHashFn;\n\t\t// Captured once. Calls back into `this._messageTypes` — still returns\n\t\t// the current registration, but post-freeze the registry is immutable\n\t\t// so the closure is effectively constant.\n\t\tthis.tierOf = (t: symbol): number => {\n\t\t\tconst reg = this._messageTypes.get(t);\n\t\t\treturn reg != null ? reg.tier : 1;\n\t\t};\n\t}\n\n\t// --- Hook getters (freeze on read) ---\n\n\tget onMessage(): OnMessageHandler {\n\t\tthis._frozen = true;\n\t\treturn this._onMessage;\n\t}\n\n\tget onSubscribe(): OnSubscribeHandler {\n\t\tthis._frozen = true;\n\t\treturn this._onSubscribe;\n\t}\n\n\t// --- Hook setters (throw when frozen) ---\n\n\tset onMessage(v: OnMessageHandler) {\n\t\tthis._assertUnfrozen();\n\t\tthis._onMessage = v;\n\t}\n\n\tset onSubscribe(v: OnSubscribeHandler) {\n\t\tthis._assertUnfrozen();\n\t\tthis._onSubscribe = v;\n\t}\n\n\t/**\n\t * Default versioning level applied to every node bound to this config,\n\t * unless the node's own `opts.versioning` provides an explicit override.\n\t * Setting this is only allowed before the config freezes (i.e., before\n\t * the first node is created) so every node in the graph sees a\n\t * consistent starting level. Individual nodes can still opt into a\n\t * higher level via `opts.versioning`, or post-hoc via\n\t * `NodeImpl._applyVersioning(level)` when the node is quiescent.\n\t *\n\t * v0 is the minimum opt-in — unversioned nodes (`undefined`) skip\n\t * the version counter entirely. v1 adds content-addressed cid.\n\t * Future levels (v2, v3) are reserved for linked-history and\n\t * cryptographic attestation extensions.\n\t */\n\tget defaultVersioning(): VersioningLevel | undefined {\n\t\treturn this._defaultVersioning;\n\t}\n\tset defaultVersioning(v: VersioningLevel | undefined) {\n\t\tthis._assertUnfrozen();\n\t\tthis._defaultVersioning = v;\n\t}\n\n\t/**\n\t * Default content-hash function applied to every versioned node bound\n\t * to this config, unless the node's own `opts.versioningHash` provides\n\t * an explicit override. Use this when a graph needs a non-default hash\n\t * — e.g., swap the vendored sync SHA-256 for a faster non-crypto hash\n\t * (xxHash, FNV-1a) in hot-path workloads, or a stronger hash when\n\t * versioning v1 cids are used as audit anchors.\n\t *\n\t * Only settable before the config freezes. Individual nodes can still\n\t * override via `opts.versioningHash`.\n\t */\n\tget defaultHashFn(): HashFn | undefined {\n\t\treturn this._defaultHashFn;\n\t}\n\tset defaultHashFn(v: HashFn | undefined) {\n\t\tthis._assertUnfrozen();\n\t\tthis._defaultHashFn = v;\n\t}\n\n\t/**\n\t * When `false`, structured observation options (`causal`, `timeline`)\n\t * and `Graph.trace()` writes are no-ops. Raw `Graph.observe()` always\n\t * works. Default: `true` outside production (`NODE_ENV !== \"production\"`).\n\t *\n\t * Settable at any time — inspector gating is an operational concern, not\n\t * a protocol invariant, so it does NOT require freeze before node creation.\n\t */\n\tget inspectorEnabled(): boolean {\n\t\treturn this._inspectorEnabled;\n\t}\n\tset inspectorEnabled(v: boolean) {\n\t\tthis._inspectorEnabled = v;\n\t}\n\n\t/**\n\t * Process-global observability hook (Redux-DevTools-style full-graph\n\t * tracer). Fires once per outgoing batch from every node bound to this\n\t * config, gated by {@link inspectorEnabled}. See {@link GlobalInspectorHook}.\n\t *\n\t * Settable at any time — like {@link inspectorEnabled} this is operational,\n\t * not protocol-shaping, so it does NOT trigger config freeze.\n\t */\n\tget globalInspector(): GlobalInspectorHook | undefined {\n\t\treturn this._globalInspector;\n\t}\n\tset globalInspector(v: GlobalInspectorHook | undefined) {\n\t\tthis._globalInspector = v;\n\t}\n\n\t// --- Registry (writes require unfrozen; reads are free lookups) ---\n\n\t/**\n\t * Register a custom message type. Must be called before any node that\n\t * uses this config has been created — otherwise throws. Default\n\t * `wireCrossing` is `tier >= 3`.\n\t */\n\tregisterMessageType(t: symbol, input: MessageTypeRegistrationInput): this {\n\t\tthis._assertUnfrozen();\n\t\tthis._messageTypes.set(t, {\n\t\t\ttier: input.tier,\n\t\t\twireCrossing: input.wireCrossing ?? input.tier >= 3,\n\t\t\tmetaPassthrough: input.metaPassthrough ?? true,\n\t\t});\n\t\treturn this;\n\t}\n\n\t/** Tier for `t`. Unknown types default to tier 1 (immediate, after START). */\n\tmessageTier(t: symbol): number {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.tier : 1;\n\t}\n\n\t/**\n\t * Whether `t` is registered as wire-crossing. Unknown types default to\n\t * `true` (spec §1.3.6 forward-compat — unknowns cross the wire).\n\t */\n\tisWireCrossing(t: symbol): boolean {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.wireCrossing : true;\n\t}\n\n\t/** Convenience inverse of {@link isWireCrossing}. */\n\tisLocalOnly(t: symbol): boolean {\n\t\treturn !this.isWireCrossing(t);\n\t}\n\n\t/**\n\t * Whether `t` is forwarded to meta companions by `Graph.signal`. Defaults\n\t * to `true` for unknowns (forward-compat — new types pass through meta by\n\t * default; opt-in filter via `registerMessageType({metaPassthrough: false})`).\n\t */\n\tisMetaPassthrough(t: symbol): boolean {\n\t\tconst reg = this._messageTypes.get(t);\n\t\treturn reg != null ? reg.metaPassthrough : true;\n\t}\n\n\t/** Whether `t` is a registered (built-in or custom) type. */\n\tisKnownMessageType(t: symbol): boolean {\n\t\treturn this._messageTypes.has(t);\n\t}\n\n\t// --- Codec registry (writes require unfrozen; reads are free lookups) ---\n\n\t/**\n\t * Register a graph codec by `codec.name`. Used by the envelope-based\n\t * `graph.snapshot({format: \"bytes\", codec: name})` path and\n\t * `Graph.decode(bytes)` auto-dispatch. Must be called before any node\n\t * bound to this config is created — otherwise throws.\n\t *\n\t * Re-registering the same name overwrites, so user codecs can shadow\n\t * built-in ones before freeze (e.g., to swap a zstd-wrapped dag-cbor in\n\t * for `\"dag-cbor\"`).\n\t */\n\tregisterCodec<T extends { readonly name: string; readonly version: number }>(codec: T): this {\n\t\tthis._assertUnfrozen();\n\t\tthis._codecs.set(codec.name, codec);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Resolve a registered codec by name. Returns `undefined` for unknown\n\t * names. Typed callers cast to their concrete codec interface (e.g.,\n\t * `config.lookupCodec<GraphCodec>(\"json\")`) — this method stays\n\t * layer-pure (no import of graph-layer types into `core/`).\n\t */\n\tlookupCodec<T = { readonly name: string; readonly version: number }>(\n\t\tname: string,\n\t): T | undefined {\n\t\treturn this._codecs.get(name) as T | undefined;\n\t}\n\n\t/** @internal Used by tests and dev tooling — check freeze state without triggering it. */\n\t_isFrozen(): boolean {\n\t\treturn this._frozen;\n\t}\n\n\tprivate _assertUnfrozen(): void {\n\t\tif (this._frozen) {\n\t\t\tthrow new Error(\n\t\t\t\t\"GraphReFlyConfig is frozen: a node has already captured this config. \" +\n\t\t\t\t\t\"Register custom types and set hooks before creating any node.\",\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Built-in registration\n// ---------------------------------------------------------------------------\n\n/**\n * Register the 10 built-in message types on a fresh config. Called by\n * `node.ts` when it constructs `defaultConfig` and by test code / advanced\n * users after `new GraphReFlyConfig(...)`.\n */\nexport function registerBuiltins(cfg: GraphReFlyConfig): void {\n\tcfg.registerMessageType(START, { tier: 0, wireCrossing: false });\n\tcfg.registerMessageType(DIRTY, { tier: 1, wireCrossing: false });\n\t// INVALIDATE, COMPLETE, ERROR, TEARDOWN do NOT pass through to meta\n\t// companions via Graph.signal (spec §2.3). Meta still sees them via the\n\t// primary's own down-cascade.\n\tcfg.registerMessageType(INVALIDATE, {\n\t\ttier: 1,\n\t\twireCrossing: false,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(PAUSE, { tier: 2, wireCrossing: false });\n\tcfg.registerMessageType(RESUME, { tier: 2, wireCrossing: false });\n\tcfg.registerMessageType(DATA, { tier: 3, wireCrossing: true });\n\tcfg.registerMessageType(RESOLVED, { tier: 3, wireCrossing: true });\n\tcfg.registerMessageType(COMPLETE, {\n\t\ttier: 4,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(ERROR, {\n\t\ttier: 4,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n\tcfg.registerMessageType(TEARDOWN, {\n\t\ttier: 5,\n\t\twireCrossing: true,\n\t\tmetaPassthrough: false,\n\t});\n}\n","/**\n * Node versioning — GRAPHREFLY-SPEC §7.\n *\n * Progressive, optional versioning for node identity and change tracking.\n *\n * - **V0**: `id` + `version` — identity & change detection (~16 bytes overhead)\n * - **V1**: + `cid` + `prev` — content addressing & linked history (~60 bytes overhead)\n *\n * **Lifecycle notes:**\n * - Version advances only on DATA (not RESOLVED, INVALIDATE, or TEARDOWN).\n * - `resetOnTeardown` clears the cached value but does NOT reset versioning state.\n * After teardown, `v.cid` still reflects the last DATA value, not the cleared cache.\n * The invariant `hash(node.cache) === v.cid` only holds in `settled`/`resolved` status.\n * - Resubscribable nodes preserve versioning across subscription lifetimes (monotonic counter).\n */\n\n// Runtime-agnostic — no `node:crypto` import. `randomUUID` comes from Web\n// Crypto (`globalThis.crypto.randomUUID()`), available in Node 14.17+,\n// browsers, Deno, Bun, and Cloudflare Workers. The default content hash is a\n// vendored sync SHA-256 (see `sha256Hex` below) so versioning stays callable\n// from any runtime — `crypto.subtle.digest` is async and can't back a\n// synchronous `defaultHash`.\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** V0: identity + monotonic version counter. */\nexport type V0 = {\n\treadonly id: string;\n\tversion: number;\n};\n\n/** V1: V0 + content-addressed identifier + previous cid link. */\nexport type V1 = V0 & {\n\tcid: string;\n\tprev: string | null;\n};\n\n/** Union of all versioning info shapes. */\nexport type NodeVersionInfo = V0 | V1;\n\n/** Supported versioning levels (extensible to 2, 3 later). */\nexport type VersioningLevel = 0 | 1;\n\n/** Function that hashes a value to a hex string (for V1 cid). */\nexport type HashFn = (value: unknown) => string;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface VersioningOptions {\n\t/** Override auto-generated id. */\n\tid?: string;\n\t/** Custom hash function for V1 cid (default: SHA-256 truncated to 16 hex chars). */\n\thash?: HashFn;\n}\n\n// ---------------------------------------------------------------------------\n// Default hash\n// ---------------------------------------------------------------------------\n\n/**\n * Canonicalize a value for deterministic cross-language hashing.\n *\n * - Integer-valued floats normalize to integer strings (`1.0` → `1`).\n * - `NaN`, `Infinity`, `-Infinity` are rejected (no JSON equivalent).\n * - `undefined` normalizes to `null`.\n * - Object keys are sorted lexicographically.\n *\n * This ensures TS `JSON.stringify` and Python `json.dumps(sort_keys=True)`\n * produce identical output for the same logical value.\n */\nexport function canonicalizeForHash(value: unknown): unknown {\n\tif (value === undefined) return null;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow new TypeError(`Cannot hash non-finite number: ${value}`);\n\t\t}\n\t\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot hash integer outside safe range (|n| > 2^53-1): ${value}. ` +\n\t\t\t\t\t\"Cross-language cid parity is not guaranteed for unsafe integers.\",\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\tif (typeof value === \"string\" || typeof value === \"boolean\" || value === null) {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(canonicalizeForHash);\n\t}\n\tif (typeof value === \"object\" && value !== null) {\n\t\tconst sorted: Record<string, unknown> = {};\n\t\tfor (const k of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tsorted[k] = canonicalizeForHash((value as Record<string, unknown>)[k]);\n\t\t}\n\t\treturn sorted;\n\t}\n\t// Fallback: coerce to null (bigint, symbol, function)\n\treturn null;\n}\n\n// SHA-256 round constants (FIPS 180-4).\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();\n\n/**\n * Sync SHA-256 of a UTF-8 string, returned as a lowercase hex digest. Matches\n * Node `crypto.createHash(\"sha256\").update(msg).digest(\"hex\")` byte-for-byte.\n *\n * Runtime-agnostic (no `node:crypto`, no `crypto.subtle`). Small enough to\n * inline rather than pulling a dependency; called only from `defaultHash`,\n * which runs once per DATA on versioned nodes, so per-call allocation is\n * acceptable. Callers that need a faster path override via\n * `NodeOptions.versioningHash`.\n */\nfunction sha256Hex(msg: string): string {\n\tconst bytes = UTF8_ENCODER.encode(msg);\n\tconst msgLen = bytes.length;\n\tconst bitLen = msgLen * 8;\n\t// Pad to multiple of 64: 0x80 byte + zeros + 8-byte big-endian bit length.\n\tconst totalLen = (msgLen + 9 + 63) & ~63;\n\tconst padded = new Uint8Array(totalLen);\n\tpadded.set(bytes);\n\tpadded[msgLen] = 0x80;\n\tconst dv = new DataView(padded.buffer);\n\t// Bit length as big-endian 64-bit int. JS numbers are 53-bit safe, so we\n\t// split into two 32-bit halves; messages up to 2^53 bits are supported.\n\tdv.setUint32(totalLen - 4, bitLen >>> 0, false);\n\tdv.setUint32(totalLen - 8, Math.floor(bitLen / 0x100000000) >>> 0, false);\n\n\t// Initial hash values (first 32 bits of fractional parts of sqrt of first 8 primes).\n\tlet h0 = 0x6a09e667;\n\tlet h1 = 0xbb67ae85;\n\tlet h2 = 0x3c6ef372;\n\tlet h3 = 0xa54ff53a;\n\tlet h4 = 0x510e527f;\n\tlet h5 = 0x9b05688c;\n\tlet h6 = 0x1f83d9ab;\n\tlet h7 = 0x5be0cd19;\n\n\tconst W = new Uint32Array(64);\n\tconst rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));\n\n\tfor (let off = 0; off < totalLen; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4, false);\n\t\tfor (let i = 16; i < 64; i++) {\n\t\t\tconst w15 = W[i - 15];\n\t\t\tconst w2 = W[i - 2];\n\t\t\tconst s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3);\n\t\t\tconst s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10);\n\t\t\tW[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0;\n\t\t}\n\n\t\tlet a = h0;\n\t\tlet b = h1;\n\t\tlet c = h2;\n\t\tlet d = h3;\n\t\tlet e = h4;\n\t\tlet f = h5;\n\t\tlet g = h6;\n\t\tlet h = h7;\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tconst S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n\t\t\tconst ch = (e & f) ^ (~e & g);\n\t\t\tconst t1 = (h + S1 + ch + SHA256_K[i] + W[i]) >>> 0;\n\t\t\tconst S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n\t\t\tconst mj = (a & b) ^ (a & c) ^ (b & c);\n\t\t\tconst t2 = (S0 + mj) >>> 0;\n\t\t\th = g;\n\t\t\tg = f;\n\t\t\tf = e;\n\t\t\te = (d + t1) >>> 0;\n\t\t\td = c;\n\t\t\tc = b;\n\t\t\tb = a;\n\t\t\ta = (t1 + t2) >>> 0;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t\th5 = (h5 + f) >>> 0;\n\t\th6 = (h6 + g) >>> 0;\n\t\th7 = (h7 + h) >>> 0;\n\t}\n\n\tconst toHex = (x: number): string => x.toString(16).padStart(8, \"0\");\n\treturn (\n\t\ttoHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4) + toHex(h5) + toHex(h6) + toHex(h7)\n\t);\n}\n\n/**\n * Default content hash: SHA-256 of deterministic JSON, truncated to 16 hex\n * chars (~64-bit). Uses {@link canonicalizeForHash} for cross-language parity\n * with Python `default_hash`.\n */\nexport function defaultHash(value: unknown): string {\n\tconst canonical = canonicalizeForHash(value ?? null);\n\tconst json = JSON.stringify(canonical);\n\treturn sha256Hex(json).slice(0, 16);\n}\n\n/**\n * Cross-runtime UUID generator. Uses Web Crypto (`globalThis.crypto.randomUUID`)\n * when available. Falls back to a tiny `Math.random`-seeded RFC 4122 v4\n * generator for environments that omit `crypto.randomUUID` — identity only,\n * not cryptographic.\n */\nfunction randomUuid(): string {\n\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n\tif (c?.randomUUID) return c.randomUUID();\n\t// Fallback (extremely rare — only hits on very old runtimes that expose no\n\t// Web Crypto at all). Not cryptographically strong.\n\tconst r = () =>\n\t\tMath.floor(Math.random() * 0x100000000)\n\t\t\t.toString(16)\n\t\t\t.padStart(8, \"0\");\n\tconst hex = r() + r() + r() + r();\n\treturn (\n\t\t`${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-` +\n\t\t`${((parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create initial versioning state for a node.\n *\n * @param level - 0 for V0, 1 for V1.\n * @param initialValue - The node's initial cached value (used for V1 cid).\n * @param opts - Optional overrides (id, hash).\n */\nexport function createVersioning(\n\tlevel: VersioningLevel,\n\tinitialValue: unknown,\n\topts?: VersioningOptions,\n): NodeVersionInfo {\n\tconst id = opts?.id ?? randomUuid();\n\tif (level === 0) {\n\t\treturn { id, version: 0 } satisfies V0;\n\t}\n\tconst hash = opts?.hash ?? defaultHash;\n\tconst cid = hash(initialValue);\n\treturn { id, version: 0, cid, prev: null } satisfies V1;\n}\n\n// ---------------------------------------------------------------------------\n// Advance\n// ---------------------------------------------------------------------------\n\n/**\n * Advance versioning state after a DATA emission (value changed).\n *\n * Mutates `info` in place for performance (called on every DATA).\n * Only call when the cached value has actually changed (not on RESOLVED).\n *\n * @param info - The node's current versioning state.\n * @param newValue - The new cached value.\n * @param hashFn - Hash function (only used for V1).\n */\nexport function advanceVersion(info: NodeVersionInfo, newValue: unknown, hashFn: HashFn): void {\n\tinfo.version += 1;\n\tif (\"cid\" in info) {\n\t\t(info as V1).prev = (info as V1).cid;\n\t\t(info as V1).cid = hashFn(newValue);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Guards\n// ---------------------------------------------------------------------------\n\n/** Type guard: is this V1 versioning info? */\nexport function isV1(info: NodeVersionInfo): info is V1 {\n\treturn \"cid\" in info;\n}\n","/**\n * `NodeImpl` — the single GraphReFly node primitive.\n *\n * Per-dep state lives in a `DepRecord[]` — one entry per declared dep —\n * consolidating subscription cleanup, latest-data tracking, dirty/settled\n * flags, and terminal state into a single structure per dep.\n *\n * This file also owns the default singleton handlers (`defaultOnMessage`,\n * `defaultOnSubscribe`), the `defaultConfig` instance, and the public\n * `configure(...)` entry point. They live here because their bodies touch\n * `NodeImpl` internals; `config.ts` stays NodeImpl-agnostic.\n *\n * See GRAPHREFLY-SPEC §2 and COMPOSITION-GUIDE §1/§9 for the behavior\n * contract. See SESSION-foundation-redesign.md §§1–10 for design history.\n */\n\nimport { registerBuiltinCodecs } from \"../graph/codec.js\";\nimport type { Actor } from \"./actor.js\";\nimport { normalizeActor } from \"./actor.js\";\nimport { downWithBatch, isExplicitlyBatching, registerBatchFlushHook } from \"./batch.js\";\nimport { wallClockNs } from \"./clock.js\";\nimport type {\n\tMessageContext,\n\tNodeActions,\n\tNodeCtx,\n\tOnMessageHandler,\n\tOnSubscribeHandler,\n\tSubscribeContext,\n} from \"./config.js\";\nimport { GraphReFlyConfig, registerBuiltins } from \"./config.js\";\nimport type { GuardAction, NodeGuard } from \"./guard.js\";\nimport { GuardDenied } from \"./guard.js\";\nimport {\n\tCOMPLETE,\n\tCOMPLETE_ONLY_BATCH,\n\tDATA,\n\tDIRTY,\n\tDIRTY_MSG,\n\tDIRTY_ONLY_BATCH,\n\tERROR,\n\tINVALIDATE,\n\tINVALIDATE_ONLY_BATCH,\n\ttype Message,\n\ttype Messages,\n\tPAUSE,\n\tRESOLVED,\n\tRESOLVED_MSG,\n\tRESOLVED_ONLY_BATCH,\n\tRESUME,\n\tSTART,\n\tSTART_MSG,\n\tTEARDOWN,\n\tTEARDOWN_ONLY_BATCH,\n} from \"./messages.js\";\nimport {\n\tadvanceVersion,\n\tcreateVersioning,\n\tdefaultHash,\n\ttype HashFn,\n\ttype NodeVersionInfo,\n\ttype VersioningLevel,\n} from \"./versioning.js\";\n\n// ---------------------------------------------------------------------------\n// Internal sentinel + type helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Placeholder unsubscribe used to mark a dep subscription as \"pending\" during\n * the synchronous window between `dep.unsub = noopUnsub` and the return of\n * `dep.node.subscribe(...)`. Ensures the liveness check `dep.unsub === null`\n * in the subscription callback correctly passes for synchronous push-on-\n * subscribe deliveries, while still blocking stale drainPhase2 closures that\n * fire after deactivation has set `dep.unsub = null`.\n */\nconst noopUnsub: () => void = () => {};\n\n/**\n * Maximum `_pendingRerun` depth before we give up and emit ERROR. Bounds\n * autoTrackNode / `_addDep` discovery loops — a well-formed discovery\n * converges in O(n) total rounds for n deps, so 100 is ample.\n */\nconst MAX_RERUN_DEPTH = 100;\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Lifecycle status of a node.\n *\n * @see GRAPHREFLY-SPEC.md §2.2\n */\nexport type NodeStatus =\n\t| \"sentinel\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\n/** Callback that receives downstream message batches. */\nexport type NodeSink = (messages: Messages) => void;\n\n/**\n * Observability hook events fired by a per-node inspector. Used by\n * `Graph.observe(path, { causal, derived })` to build causal traces.\n *\n * - `\"dep_message\"` — fires in `_onDepMessage` before default dispatch,\n * one event per message received from a dep. Includes `depIndex` and\n * the raw `Message` tuple.\n * - `\"run\"` — fires in `_execFn` just before the user fn runs. Includes\n * the per-dep `prevData` snapshot that will be passed to fn.\n */\nexport type NodeInspectorHookEvent =\n\t| { kind: \"dep_message\"; depIndex: number; message: Message }\n\t| {\n\t\t\tkind: \"run\";\n\t\t\tbatchData: readonly (readonly unknown[] | undefined)[];\n\t\t\tprevData: readonly unknown[];\n\t };\n\n/** Callback attached to a node for per-message/per-run inspection. */\nexport type NodeInspectorHook = (event: NodeInspectorHookEvent) => void;\n\n/** Describe `type` for `Graph.describe` (GRAPHREFLY-SPEC Appendix B). */\nexport type NodeDescribeKind = \"state\" | \"derived\" | \"producer\" | \"effect\";\n\n/** Actor/delivery context for {@link Node.down} and {@link Node.up}. */\nexport type NodeTransportOptions = {\n\tactor?: Actor;\n\t/** When `true`, skips guard checks. */\n\tinternal?: boolean;\n\t/** `signal` for `Graph.signal` deliveries; default `write`. */\n\tdelivery?: \"write\" | \"signal\";\n};\n\n/**\n * Cleanup return shape from a node {@link NodeFn}.\n * - `() => void` — fires before the next fn run AND on deactivation (default).\n * - `{ deactivation: () => void }` — fires only on deactivation (persistent\n * resources that should survive across fn re-runs).\n */\nexport type NodeFnCleanup = (() => void) | { deactivation: () => void };\n\n/**\n * Fn-time context exposing per-wave metadata and a per-node persistent\n * scratch pad.\n *\n * - `prevData[i]` — last DATA value from dep `i` as of the END of the\n * previous wave (i.e. the value that was stable before this wave started).\n * Use as the fallback when `data[i]` is `undefined` (not involved) or\n * `[]` (RESOLVED, no new values this wave).\n * `undefined` means dep `i` has never produced DATA (sentinel state).\n * `null` is a valid DATA value. `undefined` is not a valid DATA value —\n * the protocol reserves it as the \"never sent\" sentinel.\n * - `ctx.prevData[i] === undefined` → dep has never produced DATA\n * - `ctx.prevData[i] !== undefined` → last DATA value (may be `null`)\n * - `terminalDeps[i]` — runtime shape:\n * - `undefined` → dep `i` is still live.\n * - `true` → dep `i` sent COMPLETE.\n * - anything else → dep `i` sent ERROR, value is the error payload.\n * Type is `readonly unknown[]` because `true | unknown` collapses to\n * `unknown` anyway; the three states are documented contract, not type.\n * - `store` — mutable bag that persists across fn runs within one activation\n * cycle. Wiped on deactivation and on resubscribable terminal reset.\n */\nexport interface FnCtx {\n\treadonly prevData: readonly unknown[];\n\treadonly terminalDeps: readonly unknown[];\n\treadonly store: Record<string, unknown>;\n}\n\n/**\n * Compute function passed to `node(deps, fn, opts?)`.\n *\n * `data[i]` holds the batch of DATA values received from dep `i` during the\n * current wave. Shape contract:\n * - `undefined` — dep `i` was not involved in this wave (no DIRTY received).\n * - `[]` — dep `i` was involved (dirtied), but settled as RESOLVED (value\n * unchanged). Use `ctx.prevData[i]` to read its last known value from the\n * previous wave.\n * - `[v1, v2, ...]` — dep `i` sent one or more DATA values. `at(-1)` gives\n * the latest; iterate for multi-emission processing.\n *\n * Emission is explicit via `actions.emit(v)` (sugar: equals + framing) or\n * `actions.down(msgs)` (raw). Return a cleanup function (or\n * `{ deactivation }`) to register teardown — any non-cleanup return value\n * is ignored. The `| void` leg lets arrow-block bodies satisfy `NodeFn`\n * without an explicit `return undefined`.\n *\n * Sugar constructors (`derived`, `effect`, `dynamicNode`) unwrap `data[i]`\n * to a single scalar (`at(-1)` with `ctx.prevData[i]` fallback) so their\n * user-facing fn signatures stay unchanged. Use raw `node()` when you need\n * the full batch array.\n */\nexport type NodeFn = (\n\tdata: readonly (readonly unknown[] | undefined)[],\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: see JSDoc above.\n) => NodeFnCleanup | void;\n\n/** Options accepted by every node constructor. */\nexport interface NodeOptions<T = unknown> {\n\tname?: string;\n\tdescribeKind?: NodeDescribeKind;\n\tequals?: (a: T, b: T) => boolean;\n\t/**\n\t * Pre-populate the cache at construction. `null` is a valid initial value.\n\t * `undefined` is treated as absent (not a valid DATA payload).\n\t */\n\tinitial?: T | null;\n\tmeta?: Record<string, unknown>;\n\tresubscribable?: boolean;\n\tresetOnTeardown?: boolean;\n\t/** Auto-emit `[[COMPLETE]]` when all deps complete. Default `true`. */\n\tcompleteWhenDepsComplete?: boolean;\n\t/**\n\t * Auto-propagate `[[ERROR]]` when any dep errors. Default `true`.\n\t * Set `false` only for rescue/catchError operators that handle errors\n\t * explicitly via `ctx.terminalDeps`.\n\t */\n\terrorWhenDepsError?: boolean;\n\t/**\n\t * Tier-2 PAUSE/RESUME handling.\n\t * - `true` (default): wave completion suppressed while paused; fn fires\n\t * once on RESUME if gate is satisfied.\n\t * - `false`: node ignores PAUSE (sources like timers that must keep running).\n\t * - `\"resumeAll\"`: on RESUME, replay every buffered DATA (future).\n\t */\n\tpausable?: boolean | \"resumeAll\";\n\tguard?: NodeGuard;\n\tversioning?: VersioningLevel;\n\tversioningId?: string;\n\tversioningHash?: HashFn;\n\t/**\n\t * Override the config instance this node binds to. Defaults to\n\t * {@link defaultConfig}. Useful for test isolation and custom protocol\n\t * stacks. The first node that reads any hook on the config freezes it.\n\t */\n\tconfig?: GraphReFlyConfig;\n}\n\n/** A reactive node in the GraphReFly protocol. */\nexport interface Node<T = unknown> {\n\treadonly name?: string;\n\treadonly status: NodeStatus;\n\t/**\n\t * Current cached value. Returns `undefined` when the node is in\n\t * `\"sentinel\"` state (no DATA ever emitted). v5 reserves `undefined`\n\t * globally as the sentinel value — the valid DATA type is `T | null`.\n\t * Therefore `node.cache === undefined` is a valid \"never emitted\" guard.\n\t * `node.status` distinguishes the richer states (`\"sentinel\"`,\n\t * `\"settled\"`, `\"errored\"`, etc.) when you need more than has-value.\n\t */\n\treadonly cache: T | null | undefined;\n\treadonly meta: Record<string, Node>;\n\treadonly lastMutation: Readonly<{ actor: Actor; timestamp_ns: number }> | undefined;\n\treadonly v: Readonly<NodeVersionInfo> | undefined;\n\t/**\n\t * Send one or more messages downstream. Accepts either a single\n\t * {@link Message} tuple (e.g. `node.down([DATA, 42])`) or a\n\t * {@link Messages} array of tuples (e.g.\n\t * `node.down([[DIRTY], [DATA, 42]])`). One call = one wave: the\n\t * emit pipeline tier-sorts the input, auto-prefixes `[DIRTY]` when\n\t * any tier-3 payload is present and the node is not already dirty,\n\t * runs equals substitution against the live cache (§3.5.1), then\n\t * dispatches to sinks with phase deferral.\n\t */\n\tdown(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void;\n\t/**\n\t * Sugar for `down([[DATA, value]])`. One wave with a single DATA\n\t * payload — the pipeline adds the synthetic DIRTY prefix and runs\n\t * equals substitution against the live cache.\n\t */\n\temit(value: T | undefined | null, options?: NodeTransportOptions): void;\n\t/**\n\t * Send one or more messages upstream. Accepts the same shapes as\n\t * {@link down}. Upstream messages are tier <3 + tier 5 only\n\t * (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN); tier-3/4 payloads\n\t * throw — DATA/RESOLVED/COMPLETE/ERROR are downstream-only in this\n\t * protocol. No equals substitution, no cache advance, no DIRTY\n\t * auto-prefix — the up direction just forwards to every dep.\n\t */\n\tup?(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void;\n\tsubscribe(sink: NodeSink, actor?: Actor): () => void;\n\tallowsObserve(actor: Actor): boolean;\n\thasGuard(): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// DepRecord — per-dep state (§8.2)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-dep runtime state. One entry per upstream node.\n *\n * `terminal` is the single terminal-state slot, shaped to match\n * {@link FnCtx.terminalDeps}:\n * - `undefined` — dep is still live.\n * - `true` — dep sent COMPLETE.\n * - anything else — dep sent ERROR with that payload.\n *\n * Edge case: an ERROR carrying an `undefined` payload is indistinguishable\n * from \"live\". Pass meaningful error values (Error objects, domain tags).\n */\nexport interface DepRecord {\n\treadonly node: Node;\n\tunsub: (() => void) | null;\n\t/**\n\t * Last DATA value from this dep as of the end of the previous completed\n\t * wave. `undefined` until dep has produced at least one DATA (sentinel).\n\t * Committed by `_execFn` after snapshotting `ctx.prevData` and before\n\t * `_clearWaveFlags`. `undefined` is reserved as the \"never sent\" sentinel —\n\t * `undefined` is not a valid DATA payload.\n\t */\n\tprevData: unknown;\n\t/** True while awaiting DATA/RESOLVED for the current wave. */\n\tdirty: boolean;\n\t/**\n\t * True if this dep was dirtied in the current wave (set in `_depDirtied`,\n\t * cleared in `_clearWaveFlags`). Distinguishes \"RESOLVED\" (`involvedThisWave\n\t * && dataBatch.length === 0`) from \"not involved\" (`!involvedThisWave`) in\n\t * the `data[i]` batch snapshot passed to fn.\n\t */\n\tinvolvedThisWave: boolean;\n\t/**\n\t * DATA values accumulated from this dep during the current wave.\n\t * Populated by `_depSettledAsData`, cleared by `_clearWaveFlags`.\n\t * Snapshotted (copied) by `_execFn` before `_clearWaveFlags` runs so\n\t * that fn always sees the full wave batch.\n\t */\n\tdataBatch: unknown[];\n\t/** Terminal-state slot — see JSDoc on {@link DepRecord}. */\n\tterminal: unknown;\n}\n\nfunction createDepRecord(n: Node): DepRecord {\n\treturn {\n\t\tnode: n,\n\t\tunsub: null,\n\t\tprevData: undefined,\n\t\tdirty: false,\n\t\tinvolvedThisWave: false,\n\t\tdataBatch: [],\n\t\tterminal: undefined,\n\t};\n}\n\nfunction resetDepRecord(d: DepRecord): void {\n\td.prevData = undefined;\n\td.dirty = false;\n\td.involvedThisWave = false;\n\td.dataBatch.length = 0;\n\td.terminal = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization helper\n// ---------------------------------------------------------------------------\n\n/**\n * Accept either a single `Message` tuple or a `Messages` array and return\n * a `Messages` array. The discriminator is the type of the first element:\n * a `Message` has a symbol at index 0, while a `Messages` array has a\n * nested array at index 0. This lets `node.down(...)` and `actions.down(...)`\n * take either shape without a wrapper allocation on the common single-msg\n * path.\n */\nfunction normalizeMessages(input: Message | Messages): Messages {\n\tif (input.length === 0) return input as Messages;\n\treturn typeof (input as Message)[0] === \"symbol\" ? [input as Message] : (input as Messages);\n}\n\n// ---------------------------------------------------------------------------\n// Default handlers\n// ---------------------------------------------------------------------------\n\n/**\n * Default {@link OnMessageHandler}. For `\"down-in\"` messages (from a dep),\n * routes to `NodeImpl._onDepMessage`. For `\"up-in\"` messages (from a sink),\n * the up-path is wired directly via `Node.up()` and never passes through\n * onMessage — this hook is reserved for future P5 symmetry.\n */\nconst defaultOnMessage: OnMessageHandler = (\n\tnode: NodeCtx,\n\tmsg: Message,\n\tctx: MessageContext,\n\t_actions: NodeActions,\n): \"consume\" | undefined => {\n\tif (ctx.direction === \"down-in\") {\n\t\t(node as NodeImpl)._onDepMessage(ctx.depIndex, msg);\n\t}\n\t// up-in is currently unused; default is to do nothing.\n\treturn undefined;\n};\n\n/**\n * Default {@link OnSubscribeHandler}. Delivers the subscribe handshake —\n * `[[START]]` for a sentinel cache, or `[[START], [DATA, cached]]` when a\n * value exists. Terminal nodes skip entirely so absence of START tells the\n * sink the stream is over (spec §2.2). Delivered through `downWithBatch` so\n * `subscribe()` inside `batch()` still defers the paired DATA correctly.\n */\nconst defaultOnSubscribe: OnSubscribeHandler = (\n\tnode: NodeCtx,\n\tsink: NodeSink,\n\t_ctx: SubscribeContext,\n\t_actions: NodeActions,\n): (() => void) | undefined => {\n\tconst impl = node as NodeImpl;\n\tif (impl._status === \"completed\" || impl._status === \"errored\") return;\n\tconst cached = impl._cached;\n\tconst initial: Message[] =\n\t\tcached === undefined ? [START_MSG] : [START_MSG, [DATA, cached] as Message];\n\t// When the node is mid-wave (`\"dirty\"`), append a DIRTY so the late\n\t// joiner participates in the in-flight wave. Without this, the next\n\t// DATA/RESOLVED the sink receives lacks the preceding DIRTY required\n\t// by spec §1.3.1 — the emit-side DIRTY auto-prefix is suppressed when\n\t// `_status` is already `\"dirty\"`.\n\tif (impl._status === \"dirty\") initial.push(DIRTY_MSG);\n\tdownWithBatch(sink, initial, impl._config.tierOf);\n};\n\n// ---------------------------------------------------------------------------\n// defaultConfig + configure\n// ---------------------------------------------------------------------------\n\n/**\n * Default {@link GraphReFlyConfig} instance. Every `NodeImpl` constructed\n * without an explicit `opts.config` binds to this instance and freezes it\n * on first hook access.\n */\nexport const defaultConfig = new GraphReFlyConfig({\n\tonMessage: defaultOnMessage,\n\tonSubscribe: defaultOnSubscribe,\n});\nregisterBuiltins(defaultConfig);\nregisterBuiltinCodecs(defaultConfig);\n\n/**\n * Apply configuration to {@link defaultConfig}. Must be called before the\n * first node is created — otherwise throws. Custom message types, hook\n * overrides, etc. go through here at app startup.\n *\n * ```ts\n * configure((cfg) => {\n * cfg.registerMessageType(MY_TYPE, { tier: 3 });\n * cfg.onMessage = (node, msg, ctx, actions) => { ... };\n * });\n * ```\n */\nexport function configure(fn: (cfg: GraphReFlyConfig) => void): void {\n\tif (defaultConfig._isFrozen()) {\n\t\tthrow new Error(\n\t\t\t\"configure() called after a node was created — the default \" +\n\t\t\t\t\"GraphReFlyConfig is frozen. Call configure(...) at application \" +\n\t\t\t\t\"startup, before any node factories run.\",\n\t\t);\n\t}\n\tfn(defaultConfig);\n}\n\n// Re-export the class for advanced callers that want an isolated instance.\nexport { GraphReFlyConfig };\n\n// ---------------------------------------------------------------------------\n// NodeImpl\n// ---------------------------------------------------------------------------\n\n/**\n * Single-class node implementation. Covers state, producer, derived, effect,\n * and passthrough shapes. See `sugar.ts` for ergonomic factories and\n * `dynamicNode()` (sugar-level wrapper around plain `NodeImpl`).\n */\nexport class NodeImpl<T = unknown> implements Node<T> {\n\t// --- Identity ---\n\treadonly _optsName: string | undefined;\n\treadonly _describeKind: NodeDescribeKind | undefined;\n\treadonly meta: Record<string, Node>;\n\t/**\n\t * Cached `Object.keys(meta).length > 0` check. `meta` is frozen at\n\t * construction so this boolean never flips. Used by `_emit` to skip\n\t * the meta TEARDOWN fan-out block allocation on the common \"no meta\"\n\t * hot path.\n\t */\n\treadonly _hasMeta: boolean;\n\n\t// --- Config ---\n\treadonly _config: GraphReFlyConfig;\n\n\t// --- Topology ---\n\t/** Mutable for autoTrackNode / Graph.connect() post-construction dep addition. */\n\t_deps: DepRecord[];\n\t_sinks: NodeSink | Set<NodeSink> | null = null;\n\t_sinkCount = 0;\n\n\t// --- State ---\n\t_cached: T | undefined;\n\t_status: NodeStatus;\n\t_cleanup: NodeFnCleanup | undefined;\n\t_store: Record<string, unknown> = {};\n\t_waveHasNewData = false;\n\t_hasNewTerminal = false;\n\t_hasCalledFnOnce = false;\n\t_paused = false;\n\t_pendingWave = false;\n\t_isExecutingFn = false;\n\t_pendingRerun = false;\n\t_rerunDepth = 0;\n\n\t// --- Settlement counter (A3) ---\n\t/**\n\t * Count of deps currently in `dirty === true`. `_maybeRunFnOnSettlement`\n\t * treats `0` as \"wave settled\" — O(1) check for full dep settlement.\n\t */\n\t_dirtyDepCount = 0;\n\n\t// --- Per-batch emit accumulator (Bug 2: K+1 fan-in fix) ---\n\t/**\n\t * Inside an explicit `batch(() => ...)` scope, every `_emit` accumulates\n\t * its already-framed messages here instead of dispatching synchronously.\n\t * At batch end, `_flushBatchPending` runs (registered via\n\t * `registerBatchFlushHook`) and delivers the whole accumulated batch as\n\t * one `downWithBatch` call — collapsing what would otherwise be K\n\t * separate sink invocations into one. This is the fix for the diamond\n\t * fan-in K+1 over-fire.\n\t *\n\t * `null` outside batch (or after flush). Only ever appended to within\n\t * a single explicit batch lifetime; reset to `null` on flush. State\n\t * updates (cache, version, status) still happen per-emit via\n\t * `_updateState` — only the downstream delivery is coalesced.\n\t */\n\t_batchPendingMessages: Message[] | null = null;\n\n\t// --- PAUSE/RESUME lock tracking (C0) ---\n\t/**\n\t * Set of active pause locks held against this node. Every `[PAUSE, lockId]`\n\t * adds its `lockId` to the set; every `[RESUME, lockId]` removes it.\n\t * `_paused` is a derived quantity: `_pauseLocks.size > 0`. Multi-pauser\n\t * correctness — one controller releasing its lock does NOT resume the\n\t * node while another controller still holds its lock.\n\t */\n\t_pauseLocks: Set<unknown> | null = null;\n\t/**\n\t * Buffered DATA messages held while paused. Only populated when\n\t * `_pausable === \"resumeAll\"` (bufferAll mode). On final lock release\n\t * the buffer is replayed through the node's outgoing pipeline in the\n\t * order received. Non-bufferAll pause mode drops DATA on the floor\n\t * (upstream is expected to honor PAUSE by suppressing production).\n\t */\n\t_pauseBuffer: Message[] | null = null;\n\n\t// --- Options (frozen at construction) ---\n\treadonly _fn: NodeFn | undefined;\n\treadonly _equals: (a: T, b: T) => boolean;\n\treadonly _resubscribable: boolean;\n\treadonly _resetOnTeardown: boolean;\n\treadonly _autoComplete: boolean;\n\treadonly _autoError: boolean;\n\treadonly _pausable: boolean | \"resumeAll\";\n\treadonly _guard: NodeGuard | undefined;\n\t/**\n\t * @internal Additional guards stacked at runtime via {@link NodeImpl._pushGuard}\n\t * (e.g. by `policyEnforcer({ mode: \"enforce\" })`, roadmap §9.2). Effective\n\t * write/signal/observe checks AND the original `_guard` with every entry here.\n\t */\n\t_extraGuards: Set<NodeGuard> | undefined;\n\t_hashFn: HashFn;\n\t_versioning: NodeVersionInfo | undefined;\n\t/**\n\t * Explicit versioning level, tracked separately from `_versioning` so\n\t * monotonicity checks and future v2/v3 extensions don't rely on the\n\t * fragile `\"cid\" in _versioning` shape discriminator. `undefined` means\n\t * the node has no versioning attached; `0` / `1` / future levels name\n\t * the tier. Mutated in lockstep with `_versioning` by the constructor\n\t * and by `_applyVersioning`.\n\t */\n\t_versioningLevel: VersioningLevel | undefined;\n\n\t// --- ABAC ---\n\t_lastMutation: { actor: Actor; timestamp_ns: number } | undefined;\n\n\t/**\n\t * @internal Per-node inspector hooks for `Graph.observe(path,\n\t * { causal, derived })`. Fires in `_onDepMessage` and `_execFn`.\n\t * Attached via `_setInspectorHook` (returns a disposer). Multiple\n\t * observers can attach simultaneously — all registered hooks fire for\n\t * every event.\n\t */\n\t_inspectorHooks: Set<NodeInspectorHook> | undefined;\n\n\t// --- Actions (built once in the constructor) ---\n\treadonly _actions: NodeActions;\n\n\tconstructor(deps: readonly Node[], fn: NodeFn | undefined, opts: NodeOptions<T>) {\n\t\t// Bind to config FIRST so meta nodes inherit it. Touching a hook\n\t\t// getter below freezes the config on first node creation.\n\t\tthis._config = opts.config ?? defaultConfig;\n\t\tvoid this._config.onMessage;\n\n\t\tthis._optsName = opts.name;\n\t\tthis._describeKind = opts.describeKind;\n\t\tthis._equals = (opts.equals ?? (Object.is as (a: T, b: T) => boolean)) as (\n\t\t\ta: T,\n\t\t\tb: T,\n\t\t) => boolean;\n\t\tthis._resubscribable = opts.resubscribable ?? false;\n\t\tthis._resetOnTeardown = opts.resetOnTeardown ?? false;\n\t\tthis._autoComplete = opts.completeWhenDepsComplete ?? true;\n\t\tthis._autoError = opts.errorWhenDepsError ?? true;\n\t\tthis._pausable = opts.pausable ?? true;\n\t\tthis._guard = opts.guard;\n\t\tthis._fn = fn;\n\n\t\t// `undefined` is the sentinel (\"no cached value\") so `initial: undefined`\n\t\t// is treated as absent. `null` is a valid DATA value and sets the cache.\n\t\tthis._cached = opts.initial !== undefined ? (opts.initial as T) : undefined;\n\t\t// State-with-initial starts \"settled\"; everything else starts \"sentinel\".\n\t\tthis._status =\n\t\t\tdeps.length === 0 && fn == null && this._cached !== undefined ? \"settled\" : \"sentinel\";\n\n\t\t// Versioning\n\t\t// Hash resolution: per-node `opts.versioningHash` wins; then the\n\t\t// bound config's `defaultHashFn`; then the vendored sync SHA-256.\n\t\t// Hot-path workloads that want a faster hash (xxHash, FNV-1a) can\n\t\t// set it once at app init via `configure(cfg => { cfg.defaultHashFn = ... })`.\n\t\tthis._hashFn = opts.versioningHash ?? this._config.defaultHashFn ?? defaultHash;\n\t\t// Versioning level resolution: per-node `opts.versioning` wins; if\n\t\t// absent, fall back to the bound config's `defaultVersioning`. `null`\n\t\t// stays unversioned. Explicit levels (0, 1, …) attach the versioning\n\t\t// info at construction so the next DATA emit advances it.\n\t\tconst versioningLevel: VersioningLevel | undefined =\n\t\t\topts.versioning ?? this._config.defaultVersioning;\n\t\tthis._versioningLevel = versioningLevel;\n\t\tthis._versioning =\n\t\t\tversioningLevel != null\n\t\t\t\t? createVersioning(versioningLevel, this._cached === undefined ? undefined : this._cached, {\n\t\t\t\t\t\tid: opts.versioningId,\n\t\t\t\t\t\thash: this._hashFn,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\n\t\t// Per-dep records: one DepRecord per declared dep.\n\t\tthis._deps = deps.map(createDepRecord);\n\n\t\t// Meta companions (simple state children; inherit config + guard).\n\t\tconst meta: Record<string, Node> = {};\n\t\tfor (const [k, v] of Object.entries(opts.meta ?? {})) {\n\t\t\tconst metaOpts: NodeOptions<unknown> = {\n\t\t\t\tinitial: v,\n\t\t\t\tname: `${opts.name ?? \"node\"}:meta:${k}`,\n\t\t\t\tdescribeKind: \"state\",\n\t\t\t\tconfig: this._config,\n\t\t\t};\n\t\t\tif (opts.guard != null) metaOpts.guard = opts.guard;\n\t\t\tmeta[k] = new NodeImpl<unknown>([], undefined, metaOpts);\n\t\t}\n\t\tObject.freeze(meta);\n\t\tthis.meta = meta;\n\t\tthis._hasMeta = Object.keys(meta).length > 0;\n\n\t\t// Actions: built once, closure over `this`. Every call goes through\n\t\t// `_emit` which owns the full dispatch invariant — tier sort,\n\t\t// synthetic DIRTY prefix, equals substitution, and phase dispatch.\n\t\t// One call = one wave. Multiple calls produce multiple waves.\n\t\t// No accumulation, no user-facing bundle builder.\n\t\tconst self = this;\n\t\tthis._actions = {\n\t\t\temit(value: unknown): void {\n\t\t\t\tself._emit([[DATA, value] as Message]);\n\t\t\t},\n\t\t\tdown(messageOrMessages: Message | Messages): void {\n\t\t\t\tself._emit(normalizeMessages(messageOrMessages));\n\t\t\t},\n\t\t\tup(messageOrMessages: Message | Messages): void {\n\t\t\t\tself._emitUp(normalizeMessages(messageOrMessages));\n\t\t\t},\n\t\t};\n\n\t\t// Bind commonly detached protocol methods.\n\t\tthis.down = this.down.bind(this);\n\t\tthis.up = this.up.bind(this);\n\t}\n\n\t// --- Derived state ---\n\n\tprivate get _isTerminal(): boolean {\n\t\treturn this._status === \"completed\" || this._status === \"errored\";\n\t}\n\n\t// --- Public getters ---\n\n\tget name(): string | undefined {\n\t\treturn this._optsName;\n\t}\n\n\tget status(): NodeStatus {\n\t\treturn this._status;\n\t}\n\n\tget cache(): T | undefined | null {\n\t\treturn this._cached === undefined ? undefined : (this._cached as T);\n\t}\n\n\tget lastMutation(): Readonly<{ actor: Actor; timestamp_ns: number }> | undefined {\n\t\treturn this._lastMutation;\n\t}\n\n\tget v(): Readonly<NodeVersionInfo> | undefined {\n\t\treturn this._versioning;\n\t}\n\n\thasGuard(): boolean {\n\t\treturn this._guard != null;\n\t}\n\n\t/**\n\t * @internal Retroactively attach (or upgrade) versioning state on this\n\t * node. Intended for `Graph.setVersioning(level)` bulk application and\n\t * for rare cases where a specific node needs to be bumped to a higher\n\t * level (e.g., `v0 → v1`) after construction.\n\t *\n\t * **Safety:** the mutation is rejected mid-wave. Specifically,\n\t * throws if the node is currently executing its fn (`_isExecutingFn`).\n\t * Callers at quiescent points — before the first sink subscribes, or\n\t * after all sinks unsubscribe, or between external `down()` / `emit()`\n\t * invocations — are safe. The re-entrance window that motivated §10.6.4\n\t * removal was the \"transition `_versioning` from `undefined` to a fresh\n\t * object mid-`_updateState`\" case; that path is now guarded.\n\t *\n\t * **Monotonicity:** levels can only go up. Downgrade (e.g., `v1 → v0`)\n\t * is a no-op — once a node carries higher-level metadata, dropping it\n\t * mid-graph would tear the linked-history invariant for v1 and above.\n\t *\n\t * **Linked-history boundary (D1, 2026-04-13):** upgrading v0 → v1\n\t * produces a **fresh history root**. The new v1 state has `cid =\n\t * hash(currentCachedValue)` and `prev = null`, not a synthetic `prev`\n\t * anchored to any previous v0 value. The v0 monotonic `version` counter\n\t * is preserved across the upgrade, but the linked-cid chain (spec §7)\n\t * starts fresh at the upgrade point. Downstream audit tools that walk\n\t * `v.cid.prev` backwards through time will see a `null` boundary at\n\t * the upgrade — **this is intentional**: v0 had no cid to link to, and\n\t * fabricating one would lie about the hash. Callers that require an\n\t * unbroken cid chain from birth must attach versioning at construction\n\t * via `opts.versioning` or `config.defaultVersioning`, not retroactively.\n\t *\n\t * @param level - New minimum versioning level.\n\t * @param opts - Optional id / hash overrides; applied only if the\n\t * node currently has no versioning state.\n\t */\n\t_applyVersioning(level: VersioningLevel, opts?: { id?: string; hash?: HashFn }): void {\n\t\tif (this._isExecutingFn) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node \"${this.name}\": _applyVersioning cannot run mid-fn — ` +\n\t\t\t\t\t\"call it outside of `_execFn` (typically at graph setup time \" +\n\t\t\t\t\t\"before the first subscribe).\",\n\t\t\t);\n\t\t}\n\t\tconst currentLevel = this._versioningLevel;\n\t\tif (currentLevel != null && level <= currentLevel) {\n\t\t\t// Downgrade or no-op. Monotonic: higher levels only.\n\t\t\treturn;\n\t\t}\n\t\tconst hash = opts?.hash ?? this._hashFn;\n\t\tif (hash !== this._hashFn) this._hashFn = hash;\n\t\tconst initialValue = this._cached === undefined ? undefined : this._cached;\n\t\t// Preserve the existing id + version counter across upgrades so\n\t\t// downstream consumers watching `v.id` don't see an identity jump.\n\t\tconst current = this._versioning;\n\t\tconst preservedId = current?.id ?? opts?.id;\n\t\tconst preservedVersion = current?.version ?? 0;\n\t\tconst fresh = createVersioning(level, initialValue, {\n\t\t\tid: preservedId,\n\t\t\thash,\n\t\t});\n\t\tfresh.version = preservedVersion;\n\t\tthis._versioning = fresh;\n\t\tthis._versioningLevel = level;\n\t}\n\n\t/**\n\t * @internal Attach an inspector hook. Returns a disposer that removes\n\t * the hook. Used by `Graph.observe(path, { causal, derived })` to build\n\t * causal traces. Multiple hooks may be attached concurrently — all fire\n\t * for every event in registration order. Passing `undefined` is a no-op\n\t * and returns a no-op disposer.\n\t */\n\t_setInspectorHook(hook?: NodeInspectorHook): () => void {\n\t\tif (hook == null) return () => {};\n\t\tif (this._inspectorHooks == null) this._inspectorHooks = new Set();\n\t\tthis._inspectorHooks.add(hook);\n\t\treturn () => {\n\t\t\tthis._inspectorHooks?.delete(hook);\n\t\t\tif (this._inspectorHooks?.size === 0) this._inspectorHooks = undefined;\n\t\t};\n\t}\n\n\t/**\n\t * @internal Push an additional guard onto this node. Effective enforcement\n\t * is the AND of `_guard` and every guard pushed via this hook — any one\n\t * rejecting throws {@link GuardDenied}. Returns a disposer that removes\n\t * the pushed guard. Multiple guards may be stacked simultaneously.\n\t *\n\t * Used by `policyEnforcer({ mode: \"enforce\" })` (roadmap §9.2) to overlay\n\t * runtime constraint enforcement onto an existing graph without rebuilding\n\t * its nodes. Pre-1.0 internal API; not part of the public surface.\n\t *\n\t * **Identity semantics:** guards are tracked in a `Set`, so pushing the\n\t * same `NodeGuard` reference twice is a single registration. Wrap each\n\t * push in a unique closure if independent stacking is needed.\n\t *\n\t * **Iteration order:** insertion-ordered (`Set` semantics). Determinism\n\t * follows from single-threaded JS execution; nested re-entry from inside\n\t * a guard body (push/pop while iterating) is undefined-but-survivable.\n\t */\n\t_pushGuard(guard: NodeGuard): () => void {\n\t\tif (this._extraGuards == null) this._extraGuards = new Set();\n\t\tthis._extraGuards.add(guard);\n\t\treturn () => {\n\t\t\tthis._extraGuards?.delete(guard);\n\t\t\tif (this._extraGuards?.size === 0) this._extraGuards = undefined;\n\t\t};\n\t}\n\n\tallowsObserve(actor: Actor): boolean {\n\t\tif (this._guard == null && this._extraGuards == null) return true;\n\t\tconst a = normalizeActor(actor);\n\t\tif (this._guard != null && !this._guard(a, \"observe\")) return false;\n\t\tif (this._extraGuards != null) {\n\t\t\tfor (const eg of this._extraGuards) {\n\t\t\t\tif (!eg(a, \"observe\")) return false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// --- Guard helper ---\n\n\tprivate _checkGuard(options?: NodeTransportOptions): void {\n\t\tif (options?.internal) return;\n\t\tconst hasGuard = this._guard != null || this._extraGuards != null;\n\t\tconst hasActor = options?.actor != null;\n\t\t// Skip work entirely when there's nothing to check or attribute.\n\t\tif (!hasGuard && !hasActor) return;\n\t\tconst actor = normalizeActor(options?.actor);\n\t\tconst action: GuardAction = options?.delivery === \"signal\" ? \"signal\" : \"write\";\n\t\tif (this._guard != null && !this._guard(actor, action)) {\n\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t}\n\t\tif (this._extraGuards != null) {\n\t\t\tfor (const eg of this._extraGuards) {\n\t\t\t\tif (!eg(actor, action)) {\n\t\t\t\t\tthrow new GuardDenied({ actor, action, nodeName: this.name });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Populate `_lastMutation` whenever guards ran OR an explicit actor was\n\t\t// passed — `auditTrail` (roadmap §9.2) relies on this for attribution\n\t\t// on graphs without ABAC. Internal writes (no actor, no guard) skip\n\t\t// attribution to avoid recording derived recompute storms.\n\t\tthis._lastMutation = { actor, timestamp_ns: wallClockNs() };\n\t}\n\n\t// --- Public transport ---\n\n\tdown(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void {\n\t\tconst messages = normalizeMessages(messageOrMessages);\n\t\tif (messages.length === 0) return;\n\t\tthis._checkGuard(options);\n\t\tthis._emit(messages);\n\t}\n\n\temit(value: T | undefined | null, options?: NodeTransportOptions): void {\n\t\tthis._checkGuard(options);\n\t\tthis._emit([[DATA, value] as Message]);\n\t}\n\n\tup(messageOrMessages: Message | Messages, options?: NodeTransportOptions): void {\n\t\tif (this._deps.length === 0) return;\n\t\tconst messages = normalizeMessages(messageOrMessages);\n\t\tif (messages.length === 0) return;\n\t\tthis._checkGuard(options);\n\t\tconst forwardOpts: NodeTransportOptions = options ?? { internal: true };\n\t\t// Validate tier constraint before fanning out (B1.4 option a).\n\t\tthis._validateUpTiers(messages);\n\t\tfor (const d of this._deps) {\n\t\t\td.node.up?.(messages, forwardOpts);\n\t\t}\n\t}\n\n\t/**\n\t * @internal Internal up-path used by `actions.up(...)` from inside fn.\n\t * Same tier validation as public `up`, but bypasses the guard check\n\t * since the fn context is already inside an authorized operation.\n\t */\n\tprivate _emitUp(messages: Messages): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (messages.length === 0) return;\n\t\tthis._validateUpTiers(messages);\n\t\tfor (const d of this._deps) {\n\t\t\td.node.up?.(messages, { internal: true });\n\t\t}\n\t}\n\n\t/**\n\t * @internal Enforce spec §1.2 — up-direction messages are restricted to\n\t * tier 0–2 and tier 5 (START, DIRTY, INVALIDATE, PAUSE, RESUME,\n\t * TEARDOWN). Tier 3 (DATA/RESOLVED) and tier 4 (COMPLETE/ERROR) are\n\t * downstream-only. Emitting tier-3/4 via `up` would bypass equals\n\t * substitution and cache advance entirely and is a protocol bug.\n\t */\n\tprivate _validateUpTiers(messages: Messages): void {\n\t\tconst tierOf = this._config.tierOf;\n\t\tfor (const m of messages) {\n\t\t\tconst tier = tierOf(m[0]);\n\t\t\tif (tier === 3 || tier === 4) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${this.name}\": tier-${tier} messages cannot flow up — ` +\n\t\t\t\t\t\t\"DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \" +\n\t\t\t\t\t\t\"`down(...)` for value delivery; `up(...)` is for control \" +\n\t\t\t\t\t\t\"signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tsubscribe(sink: NodeSink, actor?: Actor): () => void {\n\t\tif (actor != null && this._guard != null) {\n\t\t\tconst a = normalizeActor(actor);\n\t\t\tif (!this._guard(a, \"observe\")) {\n\t\t\t\tthrow new GuardDenied({ actor: a, action: \"observe\", nodeName: this.name });\n\t\t\t}\n\t\t}\n\n\t\t// Resubscribable terminal reset.\n\t\tconst wasTerminal = this._isTerminal;\n\t\tconst afterTerminalReset = wasTerminal && this._resubscribable;\n\t\tif (afterTerminalReset) {\n\t\t\tthis._cached = undefined;\n\t\t\tthis._status = \"sentinel\";\n\t\t\tthis._store = {};\n\t\t\tthis._hasCalledFnOnce = false;\n\t\t\tthis._waveHasNewData = false;\n\t\t\tthis._hasNewTerminal = false;\n\t\t\tthis._paused = false;\n\t\t\tthis._pendingWave = false;\n\t\t\tthis._pendingRerun = false;\n\t\t\tthis._isExecutingFn = false;\n\t\t\tthis._rerunDepth = 0;\n\t\t\tthis._dirtyDepCount = 0;\n\t\t\t// C0: clear pause state so a new subscriber after terminal-reset\n\t\t\t// starts from a clean pause lockset — otherwise a lockId from\n\t\t\t// the previous lifecycle would leave the node stuck paused and\n\t\t\t// swallow every emit.\n\t\t\tthis._pauseLocks = null;\n\t\t\tthis._pauseBuffer = null;\n\t\t\tfor (const d of this._deps) resetDepRecord(d);\n\t\t}\n\n\t\tthis._sinkCount += 1;\n\n\t\t// Subscribe ceremony via singleton.\n\t\t// Rollback on throw: undo the sinkCount bump — sink is not yet registered,\n\t\t// no _activate() has run, nothing else to clean up.\n\t\tlet subCleanup: (() => void) | undefined;\n\t\ttry {\n\t\t\tsubCleanup = this._config.onSubscribe(\n\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\tsink,\n\t\t\t\t{ sinkCount: this._sinkCount, afterTerminalReset },\n\t\t\t\tthis._actions,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tthis._sinkCount -= 1;\n\t\t\tthrow err;\n\t\t}\n\n\t\t// Register sink AFTER START delivery (spec §2.2).\n\t\tif (this._sinks == null) {\n\t\t\tthis._sinks = sink;\n\t\t} else if (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks = new Set<NodeSink>([this._sinks, sink]);\n\t\t} else {\n\t\t\tthis._sinks.add(sink);\n\t\t}\n\n\t\t// First-subscriber activation.\n\t\t// Rollback on throw: undo sink registration, sinkCount bump, and subCleanup.\n\t\t// _activate() rolls back its own partial dep subscriptions before re-throwing.\n\t\tconst isTerminalNow = this._isTerminal;\n\t\tif (this._sinkCount === 1 && !isTerminalNow) {\n\t\t\ttry {\n\t\t\t\tthis._activate();\n\t\t\t} catch (err) {\n\t\t\t\tthis._sinkCount -= 1;\n\t\t\t\tthis._removeSink(sink);\n\t\t\t\t// Restore status: onSubscribe emitted START which set _status to\n\t\t\t\t// \"pending\". With zero sinks the node is back to its pre-subscribe\n\t\t\t\t// state; reset so node.status reflects no active subscription.\n\t\t\t\tif (this._sinkCount === 0) this._status = \"sentinel\";\n\t\t\t\tif (typeof subCleanup === \"function\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsubCleanup();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* best-effort: subCleanup errors are secondary */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\n\t\t// Reflect \"activated but no value yet\" as pending.\n\t\tif (this._status === \"sentinel\" && this._cached === undefined) {\n\t\t\tthis._status = \"pending\";\n\t\t}\n\n\t\tlet removed = false;\n\t\treturn (): void => {\n\t\t\tif (removed) return;\n\t\t\tremoved = true;\n\t\t\tthis._sinkCount -= 1;\n\t\t\tthis._removeSink(sink);\n\t\t\tif (typeof subCleanup === \"function\") subCleanup();\n\t\t\tif (this._sinks == null) this._deactivate();\n\t\t};\n\t}\n\n\tprivate _removeSink(sink: NodeSink): void {\n\t\tif (this._sinks === sink) {\n\t\t\tthis._sinks = null;\n\t\t} else if (this._sinks != null && typeof this._sinks !== \"function\") {\n\t\t\tthis._sinks.delete(sink);\n\t\t\tif (this._sinks.size === 1) {\n\t\t\t\tconst [only] = this._sinks;\n\t\t\t\tthis._sinks = only;\n\t\t\t} else if (this._sinks.size === 0) {\n\t\t\t\tthis._sinks = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Lifecycle ---\n\n\t/**\n\t * @internal First-sink activation. For a producer (no deps + fn),\n\t * invokes fn once. For a compute node (has deps), subscribes to every\n\t * dep with the pre-set-dirty trick so the first-run gate waits for\n\t * every dep to settle at least once.\n\t */\n\t_activate(): void {\n\t\tif (this._deps.length === 0) {\n\t\t\tif (this._fn) this._execFn();\n\t\t\treturn;\n\t\t}\n\t\t// Pre-set every dep as sentinel BEFORE subscribing. If the first dep\n\t\t// delivers DATA synchronously during its subscribe callback, the\n\t\t// sentinel gate holds fn until all deps have contributed at least one\n\t\t// value. _dirtyDepCount starts at 0 — actual DIRTY messages from deps\n\t\t// drive it; pre-dirtying all deps would cause any dep that only delivers\n\t\t// [[START]] (no DATA) to appear permanently \"mid-wave\", which blocks\n\t\t// terminal propagation from other deps incorrectly.\n\t\tthis._dirtyDepCount = 0;\n\t\t// Capture the initial length BEFORE subscribing. `_addDep` can fire\n\t\t// synchronously during a dep's subscribe callback (e.g., via\n\t\t// `autoTrackNode` discovery in `_execFn`) and push new DepRecords.\n\t\t// Iterating `this._deps.length` live would mean this loop also\n\t\t// subscribes the new dep that `_addDep` already subscribed — a\n\t\t// double-subscribe bug. Snapshot the length instead; `_addDep`\n\t\t// owns the subscribe + counter bump for any dep it adds.\n\t\tconst initialLen = this._deps.length;\n\t\t// subscribedCount tracks how many deps were successfully subscribed.\n\t\t// On failure, only those deps need to be rolled back.\n\t\tlet subscribedCount = 0;\n\t\ttry {\n\t\t\tfor (let i = 0; i < initialLen; i++) {\n\t\t\t\tconst depIdx = i;\n\t\t\t\tconst dep = this._deps[i];\n\t\t\t\t// Pre-set to noopUnsub so the liveness check inside the callback\n\t\t\t\t// passes during synchronous push-on-subscribe (dep.unsub is non-null),\n\t\t\t\t// while still blocking stale drainPhase2 closures that fire after\n\t\t\t\t// _deactivate sets dep.unsub = null.\n\t\t\t\tdep.unsub = noopUnsub;\n\t\t\t\tdep.unsub = dep.node.subscribe((msgs) => {\n\t\t\t\t\t// Liveness check: dep.unsub === null means this subscription was\n\t\t\t\t\t// cancelled by _deactivate. Drop deliveries from stale drainPhase2\n\t\t\t\t\t// closures that outlived the subscription.\n\t\t\t\t\tif (dep.unsub === null) return;\n\t\t\t\t\t// Track whether any tier-3+ settlement-class message arrived\n\t\t\t\t\t// (DATA/RESOLVED at tier 3, COMPLETE/ERROR at tier 4). Fire\n\t\t\t\t\t// `_maybeRunFnOnSettlement` once at the end of the iteration\n\t\t\t\t\t// loop when at least one settlement was seen — one invocation\n\t\t\t\t\t// per dep batch, not per message, so `fn` sees the full wave\n\t\t\t\t\t// (Bug 1 fix, 2026-04-17). Guarded by `config.tierOf(m[0])\n\t\t\t\t\t// >= 3` per spec §5.11 — never hardcode message-type checks.\n\t\t\t\t\tconst tierOf = this._config.tierOf;\n\t\t\t\t\tlet sawSettlement = false;\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tif (tierOf(m[0]) >= 3) sawSettlement = true;\n\t\t\t\t\t\tthis._config.onMessage(\n\t\t\t\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\t\t\t\tm,\n\t\t\t\t\t\t\t{ direction: \"down-in\", depIndex: depIdx },\n\t\t\t\t\t\t\tthis._actions,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (sawSettlement) this._maybeRunFnOnSettlement();\n\t\t\t\t});\n\t\t\t\tsubscribedCount++;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// Dep at index `subscribedCount` failed — its dep.unsub is still noopUnsub.\n\t\t\t// Mark it null so the liveness check treats any queued closures as stale.\n\t\t\tthis._deps[subscribedCount].unsub = null;\n\t\t\t// Unsubscribe all deps that DID subscribe successfully (0..subscribedCount-1).\n\t\t\tfor (let j = 0; j < subscribedCount; j++) {\n\t\t\t\tconst d = this._deps[j];\n\t\t\t\tif (d.unsub != null) {\n\t\t\t\t\tconst u = d.unsub;\n\t\t\t\t\td.unsub = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tu();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* best-effort: dep unsub errors are secondary */\n\t\t\t\t\t}\n\t\t\t\t\tresetDepRecord(d);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._dirtyDepCount = 0;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t/**\n\t * @internal Append a dep post-construction. Used by `autoTrackNode`\n\t * (runtime dep discovery) and `Graph.connect()` (post-construction\n\t * wiring). Subscribes immediately — if DATA arrives synchronously\n\t * during subscribe and fn is currently executing, the re-run is\n\t * deferred via `_pendingRerun` flag (see `_execFn` guard).\n\t *\n\t * **Dedup:** idempotent on duplicate `depNode` — if `depNode` is\n\t * already in `_deps`, returns the existing index without mutating\n\t * state. Callers can safely invoke `_addDep` without their own\n\t * \"already added\" check. `autoTrackNode` still keeps a `depIndexMap`\n\t * as a fast-path lookup for known deps (returning cached `data[idx]`\n\t * without calling `_addDep` at all); this internal dedup is the\n\t * backstop for any caller that doesn't track its own dep set.\n\t *\n\t * @returns The index of the new dep in `_deps`, or the existing index\n\t * if the dep was already present.\n\t */\n\t_addDep(depNode: Node): number {\n\t\t// Dedup: idempotent on repeated adds of the same dep. Matches\n\t\t// reference equality — the DepRecord is keyed by `node` identity,\n\t\t// so a caller with a fresh `depNode` that observes as equal but\n\t\t// is a distinct object is treated as a new dep.\n\t\tfor (let i = 0; i < this._deps.length; i++) {\n\t\t\tif (this._deps[i].node === depNode) return i;\n\t\t}\n\t\tconst depIdx = this._deps.length;\n\t\tconst record = createDepRecord(depNode);\n\t\tthis._deps.push(record);\n\n\t\t// If the node is inactive (no subscribers yet), defer subscribe to\n\t\t// _activate(). Subscribing here would create a duplicate subscription\n\t\t// because _activate() unconditionally subscribes to all _deps entries.\n\t\t// _activate() resets _dirtyDepCount to 0 before subscribing, so pre-\n\t\t// dirtying is wasted work and causes counter underflow on the first DATA.\n\t\tif (this._sinks == null) return depIdx;\n\n\t\trecord.dirty = true;\n\t\t// New dep starts dirty — bump the A3 counter to match the pre-set flag.\n\t\t// Skipping the helper here because the record isn't in the array yet when\n\t\t// the helper would early-return on `dep.dirty === true`.\n\t\tthis._dirtyDepCount++;\n\t\t// Topology change → downstream sees a new wave. Skip when already\n\t\t// dirty (we're inside an in-flight wave and have already emitted).\n\t\t// `_depDirtied` can't do this for us because `record.dirty` was\n\t\t// pre-set above, which short-circuits its DIRTY-emit path.\n\t\tif (this._status !== \"dirty\") this._emit(DIRTY_ONLY_BATCH);\n\t\trecord.unsub = noopUnsub;\n\t\ttry {\n\t\t\trecord.unsub = depNode.subscribe((msgs) => {\n\t\t\t\tif (record.unsub === null) return;\n\t\t\t\t// Tier-3+ classification via central `tierOf` per spec §5.11\n\t\t\t\t// (Bug 1 fix — see _activate for details).\n\t\t\t\tconst tierOf = this._config.tierOf;\n\t\t\t\tlet sawSettlement = false;\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (tierOf(m[0]) >= 3) sawSettlement = true;\n\t\t\t\t\tthis._config.onMessage(\n\t\t\t\t\t\tthis as unknown as NodeCtx,\n\t\t\t\t\t\tm,\n\t\t\t\t\t\t{ direction: \"down-in\", depIndex: depIdx },\n\t\t\t\t\t\tthis._actions,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (sawSettlement) this._maybeRunFnOnSettlement();\n\t\t\t});\n\t\t} catch (err) {\n\t\t\t// Rollback: remove the dep record we just pushed and undo the dirty\n\t\t\t// counter. record.unsub stays null (already cleared below) so any\n\t\t\t// drainPhase2 closures queued by subscribe before it threw are\n\t\t\t// treated as stale and dropped by the liveness check.\n\t\t\trecord.unsub = null;\n\t\t\tthis._deps.pop();\n\t\t\tthis._dirtyDepCount--;\n\t\t\t// Propagate: _execFn's catch block will emit ERROR, which settles\n\t\t\t// downstream nodes that received the DIRTY we emitted above.\n\t\t\tthrow err;\n\t\t}\n\t\treturn depIdx;\n\t}\n\n\t/**\n\t * @internal Unsubscribes from deps, fires fn cleanup (both shapes),\n\t * clears wave/store state, and (for compute nodes) drops `_cached` per\n\t * the ROM/RAM rule. Idempotent: second call is a no-op.\n\t *\n\t * @param skipStatusUpdate — When `true`, the caller takes responsibility\n\t * for setting `_status` after deactivation (e.g. TEARDOWN always sets\n\t * `\"sentinel\"` unconditionally). When `false` (default), deactivation\n\t * applies the ROM rule: compute nodes → `\"sentinel\"`, state nodes\n\t * preserve their current status.\n\t */\n\t_deactivate(skipStatusUpdate = false): void {\n\t\t// Fn cleanup — both () => void and { deactivation } forms fire here.\n\t\t// Note on cleanup-throw ERRORs: when deactivation runs as part of\n\t\t// last-sink-unsubscribe, `_sinks` is already `null` by the time this\n\t\t// method is reached, so any ERROR emitted here lands on\n\t\t// `_deliverToSinks`'s null-guard and is dropped by design. Cleanup\n\t\t// errors during teardown are best-effort — callers that need to\n\t\t// observe them should install a host-level error channel via\n\t\t// `configure()`.\n\t\tconst cleanup = this._cleanup;\n\t\tthis._cleanup = undefined;\n\t\tif (typeof cleanup === \"function\") {\n\t\t\ttry {\n\t\t\t\tcleanup();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup threw\", err)]]);\n\t\t\t}\n\t\t} else if (\n\t\t\tcleanup != null &&\n\t\t\ttypeof (cleanup as { deactivation?: unknown }).deactivation === \"function\"\n\t\t) {\n\t\t\ttry {\n\t\t\t\t(cleanup as { deactivation: () => void }).deactivation();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup.deactivation threw\", err)]]);\n\t\t\t}\n\t\t}\n\n\t\t// Disconnect from deps.\n\t\tfor (const d of this._deps) {\n\t\t\tif (d.unsub != null) {\n\t\t\t\tconst u = d.unsub;\n\t\t\t\td.unsub = null;\n\t\t\t\ttry {\n\t\t\t\t\tu();\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort teardown of upstream subscription */\n\t\t\t\t}\n\t\t\t}\n\t\t\tresetDepRecord(d);\n\t\t}\n\n\t\t// Clear wave + store state.\n\t\tthis._waveHasNewData = false;\n\t\tthis._hasNewTerminal = false;\n\t\tthis._hasCalledFnOnce = false;\n\t\tthis._paused = false;\n\t\tthis._pendingWave = false;\n\t\tthis._pendingRerun = false;\n\t\tthis._rerunDepth = 0;\n\t\tthis._store = {};\n\t\t// A3 counter reset with DepRecord bulk-reset.\n\t\tthis._dirtyDepCount = 0;\n\t\t// C0 pause state: TEARDOWN is a hard reset. Buffered tier-3/4\n\t\t// messages from a paused `resumeAll` node are DISCARDED rather than\n\t\t// drained, matching \"teardown wipes in-flight state\" semantics.\n\t\t// Clearing both structures also prevents a memory leak on\n\t\t// non-resubscribable teardown, and guarantees a resubscribable\n\t\t// re-activation starts from `_paused === false` with no stale\n\t\t// lockset carried over from the previous lifecycle.\n\t\tthis._pauseLocks = null;\n\t\tthis._pauseBuffer = null;\n\n\t\t// ROM/RAM: compute nodes clear cache; pure state nodes preserve it.\n\t\tif (this._fn != null) {\n\t\t\tthis._cached = undefined;\n\t\t}\n\n\t\tif (!skipStatusUpdate) {\n\t\t\t// Compute nodes → \"sentinel\" (cache cleared, no value).\n\t\t\t// - Non-terminal: always reset.\n\t\t\t// - Terminal + resubscribable: reset (resubscribable means\n\t\t\t// \"can be re-activated after terminal\" — the terminal state\n\t\t\t// doesn't persist across subscription cycles).\n\t\t\t// - Terminal + non-resubscribable: preserve (stream is over).\n\t\t\t// State nodes preserve status (ROM rule, value is intrinsic).\n\t\t\tif (this._fn != null || this._deps.length > 0) {\n\t\t\t\tif (!this._isTerminal || this._resubscribable) {\n\t\t\t\t\tthis._status = \"sentinel\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Dep message dispatch (§3.5 singleton default) ---\n\n\t/**\n\t * @internal Default per-tier dispatch for incoming dep messages. Called\n\t * by `defaultOnMessage`. Updates the DepRecord, triggers wave\n\t * completion, and forwards passthrough traffic.\n\t */\n\t_onDepMessage(depIndex: number, msg: Message): void {\n\t\tconst dep = this._deps[depIndex];\n\t\tconst t = msg[0];\n\n\t\t// Fire inspector hooks before default dispatch. Common case: no hooks\n\t\t// (undefined slot). Multiple observers can attach simultaneously.\n\t\tif (this._inspectorHooks != null) {\n\t\t\tconst ev: NodeInspectorHookEvent = { kind: \"dep_message\", depIndex, message: msg };\n\t\t\tfor (const hook of this._inspectorHooks) hook(ev);\n\t\t}\n\n\t\t// Tier 0 (START) — informational, no state change.\n\t\tif (t === START) return;\n\n\t\t// Tier 1\n\t\tif (t === DIRTY) {\n\t\t\tthis._depDirtied(dep);\n\t\t\treturn;\n\t\t}\n\t\tif (t === INVALIDATE) {\n\t\t\tthis._depInvalidated(dep);\n\t\t\tthis._emit(INVALIDATE_ONLY_BATCH);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 2 — PAUSE / RESUME flow downstream (spec §1.2). Lock bookkeeping\n\t\t// happens inside `_emit` so both `_onDepMessage` (PAUSE received from\n\t\t// a dep) and external `node.down([[PAUSE, lockId]])` (source\n\t\t// directly issuing PAUSE) hit the same path. Here we just forward —\n\t\t// `_emit` will consume the lock, update `_paused`, and broadcast.\n\t\tif (t === PAUSE || t === RESUME) {\n\t\t\tthis._emit([msg]);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 5\n\t\tif (t === TEARDOWN) {\n\t\t\tthis._emit(TEARDOWN_ONLY_BATCH);\n\t\t\treturn;\n\t\t}\n\n\t\t// Tier 3 / 4 — centralized transitions keep the settlement counters\n\t\t// (`_dirtyDepCount`, `_sentinelDepCount`) in sync with the flags on\n\t\t// every DepRecord. A3 optimization: the two counters let\n\t\t// `_maybeRunFnOnSettlement` check wave completion in O(1) instead\n\t\t// of two `every(...)` scans.\n\t\tif (t === DATA) {\n\t\t\tthis._depSettledAsData(dep, msg[1]);\n\t\t} else if (t === RESOLVED) {\n\t\t\tthis._depSettledAsResolved(dep);\n\t\t} else if (t === COMPLETE) {\n\t\t\tthis._depSettledAsTerminal(dep, true);\n\t\t} else if (t === ERROR) {\n\t\t\tthis._depSettledAsTerminal(dep, msg[1]);\n\t\t} else {\n\t\t\t// Unknown type: forward as-is (spec §1.3.6 forward-compat).\n\t\t\tthis._emit([msg]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._fn) {\n\t\t\t// Passthrough: forward DATA/RESOLVED 1:1 through the unified\n\t\t\t// emit pipeline. `_emit` owns tier sort + synthetic DIRTY\n\t\t\t// prefix + equals substitution uniformly — no manual framing.\n\t\t\tif (t === DATA || t === RESOLVED) {\n\t\t\t\tthis._emit([msg]);\n\t\t\t}\n\t\t\tif (t === COMPLETE || t === ERROR) {\n\t\t\t\tthis._maybeAutoTerminalAfterWave();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// NOTE: `_maybeRunFnOnSettlement()` is intentionally NOT called here.\n\t\t// It fires at the end of the dep-subscribe callback's message-iteration\n\t\t// loop in `_activate`/`_addDep`, guarded by `config.tierOf(m[0]) >= 3`\n\t\t// — one invocation per dep batch so `fn` sees the full wave (Bug 1).\n\t}\n\n\t// --- Centralized dep-state transitions (A3 settlement counters) ---\n\t//\n\t// Every mutation to `DepRecord.dirty` / `DepRecord.prevData` /\n\t// `DepRecord.terminal` must go through one of these helpers so the\n\t// `_dirtyDepCount` and `_sentinelDepCount` counters stay in sync with\n\t// the per-record flags. `_maybeRunFnOnSettlement` reads the counters\n\t// and never re-scans the `_deps` array.\n\n\t/**\n\t * Called when a dep transitions `dirty: false → true` (either from an\n\t * incoming DIRTY, or pre-set during `_activate` / `_addDep` /\n\t * `_depInvalidated`). No-op if the dep is already dirty. Fires the\n\t * downstream DIRTY emit if we're the first to dirty this wave.\n\t */\n\tprivate _depDirtied(dep: DepRecord): void {\n\t\tif (dep.dirty) return;\n\t\tdep.dirty = true;\n\t\tdep.involvedThisWave = true;\n\t\tthis._dirtyDepCount++;\n\t\t// First dep to dirty this wave → propagate DIRTY to our own sinks.\n\t\tif (this._status !== \"dirty\") {\n\t\t\tthis._emit(DIRTY_ONLY_BATCH);\n\t\t}\n\t}\n\n\t/**\n\t * Called when a dep delivers new DATA: clears dirty, stores the payload,\n\t * marks wave-has-data, and — if this is the dep's first DATA — clears\n\t * its sentinel slot so the first-run gate can open.\n\t */\n\tprivate _depSettledAsData(dep: DepRecord, value: unknown): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t\tdep.involvedThisWave = true;\n\t\tdep.dataBatch.push(value);\n\t\tthis._waveHasNewData = true;\n\t}\n\n\t/**\n\t * Called when a dep emits RESOLVED (wave settled, value unchanged).\n\t * Clears dirty; does NOT touch `prevData` / `terminal` / sentinel\n\t * count — sentinel only exits on first DATA or terminal, not RESOLVED.\n\t */\n\tprivate _depSettledAsResolved(dep: DepRecord): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t}\n\n\t/**\n\t * Called when a dep delivers COMPLETE (`terminal = true`) or ERROR\n\t * (`terminal = errorPayload`). Clears dirty, stores the terminal, and\n\t * — if the dep had never contributed a DATA yet — leaves sentinel\n\t * since the gate treats \"terminated without data\" as gate-open too.\n\t */\n\tprivate _depSettledAsTerminal(dep: DepRecord, terminal: unknown): void {\n\t\tif (dep.dirty) {\n\t\t\tdep.dirty = false;\n\t\t\tthis._dirtyDepCount--;\n\t\t}\n\t\tdep.terminal = terminal;\n\t\tdep.involvedThisWave = true;\n\t\tthis._hasNewTerminal = true;\n\t}\n\n\t/**\n\t * Called when a dep emits INVALIDATE: clears prevData, terminal, and\n\t * dataBatch. The dep is now back in the \"never delivered a real value\"\n\t * state — `prevData === undefined` so the sentinel check in fn will fire.\n\t */\n\tprivate _depInvalidated(dep: DepRecord): void {\n\t\tdep.prevData = undefined;\n\t\tdep.terminal = undefined;\n\t\tdep.dataBatch.length = 0;\n\t\tif (!dep.dirty) {\n\t\t\tdep.dirty = true;\n\t\t\tdep.involvedThisWave = true;\n\t\t\tthis._dirtyDepCount++;\n\t\t} else {\n\t\t\tdep.involvedThisWave = false; // cancel prior wave involvement\n\t\t}\n\t}\n\n\tprivate _maybeRunFnOnSettlement(): void {\n\t\tif (this._isTerminal && !this._resubscribable) return;\n\t\t// O(1) gate: `_dirtyDepCount === 0` means every dep has delivered its\n\t\t// settlement for this wave (DATA, RESOLVED, or terminal).\n\t\tif (this._dirtyDepCount > 0) return;\n\t\tif (this._paused) {\n\t\t\tthis._pendingWave = true;\n\t\t\treturn;\n\t\t}\n\t\t// Pre-fn skip: when no dep sent DATA this wave (all RESOLVED), skip\n\t\t// fn and emit RESOLVED directly. Transitive-skip optimization — leaf\n\t\t// fn is not re-run when a mid-chain node produces the same value.\n\t\tif (!this._waveHasNewData && !this._hasNewTerminal && this._hasCalledFnOnce) {\n\t\t\tthis._clearWaveFlags();\n\t\t\tthis._emit(RESOLVED_ONLY_BATCH);\n\t\t\tthis._maybeAutoTerminalAfterWave();\n\t\t\treturn;\n\t\t}\n\t\tif (this._fn) this._execFn();\n\t\tthis._maybeAutoTerminalAfterWave();\n\t}\n\n\tprivate _maybeAutoTerminalAfterWave(): void {\n\t\tif (this._deps.length === 0) return;\n\t\tif (this._isTerminal) return;\n\t\t// ERROR always propagates (unless rescue operator opts out via\n\t\t// errorWhenDepsError: false). Checked independently of _autoComplete\n\t\t// so operators with completeWhenDepsComplete: false still get\n\t\t// automatic error forwarding.\n\t\tconst erroredDep = this._deps.find((d) => d.terminal !== undefined && d.terminal !== true);\n\t\tif (erroredDep != null) {\n\t\t\tif (this._autoError) {\n\t\t\t\tthis._emit([[ERROR, erroredDep.terminal]]);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// COMPLETE only when autoComplete is true and ALL deps are terminal.\n\t\tif (this._autoComplete && this._deps.every((d) => d.terminal !== undefined)) {\n\t\t\tthis._emit(COMPLETE_ONLY_BATCH);\n\t\t}\n\t}\n\n\t// --- Fn execution ---\n\n\t/**\n\t * @internal Runs the node fn once. Default cleanup (function form) fires\n\t * before the new run; `{ deactivation }` cleanup survives.\n\t */\n\tprivate _execFn(): void {\n\t\tif (!this._fn) return;\n\t\tif (this._isTerminal && !this._resubscribable) return;\n\t\t// Re-entrance guard: if fn is currently executing (e.g. _addDep\n\t\t// triggered a synchronous DATA delivery → _maybeRunFnOnSettlement\n\t\t// → _execFn), defer the re-run until the current fn returns.\n\t\tif (this._isExecutingFn) {\n\t\t\tthis._pendingRerun = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Pre-run cleanup — only the function-form cleanup fires here.\n\t\tconst prevCleanup = this._cleanup;\n\t\tif (typeof prevCleanup === \"function\") {\n\t\t\tthis._cleanup = undefined;\n\t\t\ttry {\n\t\t\t\tprevCleanup();\n\t\t\t} catch (err) {\n\t\t\t\tthis._emit([[ERROR, this._wrapFnError(\"cleanup threw\", err)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// { deactivation } cleanup is preserved across runs.\n\n\t\t// Snapshot dep state BEFORE clearing wave flags so the snapshot\n\t\t// reflects \"this wave\" rather than \"next wave\".\n\t\t// dataBatch is copied here because _clearWaveFlags truncates the live\n\t\t// array in-place (length = 0) — the fn must see the full wave batch.\n\t\tconst batchData: (readonly unknown[] | undefined)[] = this._deps.map((d) =>\n\t\t\t!d.involvedThisWave ? undefined : d.dataBatch.length > 0 ? [...d.dataBatch] : [],\n\t\t);\n\t\t// Snapshot prevData BEFORE committing this wave's values — fn sees the\n\t\t// stable values from the end of the previous wave, not the current wave.\n\t\t// undefined = \"never sent DATA\". null is a valid DATA value.\n\t\tconst prevData: unknown[] = this._deps.map((d) => d.prevData);\n\t\t// Commit: advance each dep's prevData to this wave's last DATA so the\n\t\t// NEXT wave's fn snapshot sees the current wave as \"previous\".\n\t\t// Use the already-copied batchData rather than dep.dataBatch to avoid\n\t\t// any ordering dependency with _clearWaveFlags.\n\t\tfor (let i = 0; i < this._deps.length; i++) {\n\t\t\tconst batch = batchData[i];\n\t\t\tif (batch != null && batch.length > 0) {\n\t\t\t\tthis._deps[i].prevData = batch[batch.length - 1] as unknown;\n\t\t\t}\n\t\t}\n\t\tconst terminalDeps = this._deps.map((d) => d.terminal);\n\t\tconst ctx: FnCtx = { prevData, terminalDeps, store: this._store };\n\n\t\tthis._hasCalledFnOnce = true;\n\t\tthis._clearWaveFlags();\n\n\t\t// Fire inspector hooks before fn runs — for Graph.observe causal traces.\n\t\tif (this._inspectorHooks != null) {\n\t\t\tconst ev: NodeInspectorHookEvent = { kind: \"run\", batchData, prevData };\n\t\t\tfor (const hook of this._inspectorHooks) hook(ev);\n\t\t}\n\n\t\tthis._isExecutingFn = true;\n\t\ttry {\n\t\t\tconst result = this._fn(batchData, this._actions, ctx);\n\t\t\tif (typeof result === \"function\") {\n\t\t\t\tthis._cleanup = result;\n\t\t\t} else if (\n\t\t\t\tresult != null &&\n\t\t\t\ttypeof result === \"object\" &&\n\t\t\t\ttypeof (result as { deactivation?: unknown }).deactivation === \"function\"\n\t\t\t) {\n\t\t\t\tthis._cleanup = result as { deactivation: () => void };\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthis._emit([[ERROR, this._wrapFnError(\"fn threw\", err)]]);\n\t\t} finally {\n\t\t\tthis._isExecutingFn = false;\n\t\t\t// Run any pending rerun BEFORE clearing wave flags so the\n\t\t\t// rerun's settlement check sees \"this wave had new data\" and\n\t\t\t// skips the pre-fn-skip optimization. Without this ordering,\n\t\t\t// autoTrackNode discovery's second pass gets swallowed by\n\t\t\t// the pre-fn-skip path.\n\t\t\tif (this._pendingRerun) {\n\t\t\t\tthis._pendingRerun = false;\n\t\t\t\tthis._rerunDepth += 1;\n\t\t\t\tif (this._rerunDepth > MAX_RERUN_DEPTH) {\n\t\t\t\t\tthis._rerunDepth = 0;\n\t\t\t\t\tthis._emit([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tERROR,\n\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t`Node \"${this.name}\": _pendingRerun depth exceeded ${MAX_RERUN_DEPTH} — likely a reactive cycle`,\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} else {\n\t\t\t\t\tthis._maybeRunFnOnSettlement();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Chain converged — reset the depth counter for the next wave.\n\t\t\t\tthis._rerunDepth = 0;\n\t\t\t}\n\t\t\t// Clear flags after rerun so any involvedThisWave/dataBatch set by\n\t\t\t// fn's _addDep subscribe handshakes doesn't leak into the next\n\t\t\t// wave's snapshot. The inner _execFn (if any) already did\n\t\t\t// its own pre-snapshot clear; this is for the case where\n\t\t\t// fn added deps but no rerun fired.\n\t\t\tthis._clearWaveFlags();\n\t\t}\n\t}\n\n\tprivate _clearWaveFlags(): void {\n\t\tthis._waveHasNewData = false;\n\t\tthis._hasNewTerminal = false;\n\t\tfor (const d of this._deps) {\n\t\t\td.involvedThisWave = false;\n\t\t\td.dataBatch.length = 0;\n\t\t}\n\t}\n\n\tprivate _wrapFnError(label: string, err: unknown): Error {\n\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\treturn new Error(`Node \"${this.name}\": ${label}: ${msg}`, { cause: err });\n\t}\n\n\t// --- Framing (tier sort + synthetic DIRTY prefix) ---\n\n\t/**\n\t * @internal Stable tier sort + synthetic DIRTY prefix for an outgoing\n\t * batch. Fast path: already-monotone single-tier batches (the common\n\t * case from interned singletons like `DIRTY_ONLY_BATCH`) return the\n\t * input unchanged. General path: decorate-sort-undecorate into a new\n\t * array, then prepend `[DIRTY]` after any tier-0 START entries when\n\t * a tier-3 payload is present and the node isn't already dirty.\n\t *\n\t * Single source of truth for the spec §1.3.1 framing invariant. Every\n\t * outgoing path hits `_frameBatch` exactly once via `_emit`.\n\t */\n\tprivate _frameBatch(messages: Messages): Messages {\n\t\tconst tierOf = this._config.tierOf;\n\t\t// Fast path: single message.\n\t\tif (messages.length === 1) {\n\t\t\tconst t = tierOf(messages[0][0]);\n\t\t\tif (t === 3 && this._status !== \"dirty\") {\n\t\t\t\treturn [DIRTY_MSG, messages[0]];\n\t\t\t}\n\t\t\treturn messages;\n\t\t}\n\t\t// Check monotonicity and tier-3 presence in a single pass.\n\t\tlet monotone = true;\n\t\tlet hasTier3 = false;\n\t\tlet hasDirty = false;\n\t\tlet prevTier = -1;\n\t\tfor (const m of messages) {\n\t\t\tconst tier = tierOf(m[0]);\n\t\t\tif (tier < prevTier) monotone = false;\n\t\t\tif (tier === 3) hasTier3 = true;\n\t\t\tif (m[0] === DIRTY) hasDirty = true;\n\t\t\tprevTier = tier;\n\t\t}\n\t\tlet sorted: Messages = messages;\n\t\tif (!monotone) {\n\t\t\t// Stable sort via index-keyed decoration.\n\t\t\tconst indexed = messages.map((m, i) => ({ m, i, tier: tierOf(m[0]) }));\n\t\t\tindexed.sort((a, b) => a.tier - b.tier || a.i - b.i);\n\t\t\tsorted = indexed.map((x) => x.m);\n\t\t}\n\t\tif (hasTier3 && !hasDirty && this._status !== \"dirty\") {\n\t\t\t// Insert DIRTY after any tier-0 START entries to preserve\n\t\t\t// monotonicity.\n\t\t\tlet insertAt = 0;\n\t\t\twhile (insertAt < sorted.length && tierOf(sorted[insertAt][0]) === 0) insertAt++;\n\t\t\tif (insertAt === 0) return [DIRTY_MSG, ...sorted];\n\t\t\treturn [...sorted.slice(0, insertAt), DIRTY_MSG, ...sorted.slice(insertAt)];\n\t\t}\n\t\treturn sorted;\n\t}\n\n\t// --- Emit pipeline ---\n\n\t/**\n\t * @internal The unified dispatch waist — one call = one wave.\n\t * See `GRAPHREFLY-SPEC.md` §1.3.1 for protocol context — the stages\n\t * below are the implementation order.\n\t *\n\t * Pipeline stages, in order:\n\t *\n\t * 1. Terminal filter — post-COMPLETE/ERROR only TEARDOWN/INVALIDATE\n\t * still propagate so graph teardown and cache-clear still work.\n\t * 2. Tier sort (stable) — the batch can be in any order when it\n\t * arrives; the walker downstream (`downWithBatch`) assumes\n\t * ascending tier monotone, and so does `_updateState`'s tier-3\n\t * slice walk. This is the single source of truth for ordering.\n\t * 3. Synthetic DIRTY prefix — if a tier-3 payload is present, no\n\t * DIRTY is already in the batch, and the node isn't already in\n\t * `\"dirty\"` status, prepend `[DIRTY]` after any tier-0 START\n\t * entries. Guarantees spec §1.3.1 (DIRTY precedes DATA within\n\t * the same batch) uniformly across every entry point.\n\t * 4. PAUSE/RESUME lock bookkeeping (C0) — update `_pauseLocks`,\n\t * derive `_paused`, filter unknown-lockId RESUME, replay\n\t * bufferAll buffer on final lock release.\n\t * 5. Meta TEARDOWN fan-out — notify meta children before\n\t * `_updateState`'s TEARDOWN branch calls `_deactivate`. Hoisted\n\t * out of the walk to keep `_updateState` re-entrance-free.\n\t * 6. `_updateState` — walk the batch in tier order, advancing\n\t * `_cached` / `_status` / `_versioning` and running equals\n\t * substitution on tier-3 DATA (§3.5.1). Returns\n\t * `{finalMessages, equalsError?}`.\n\t * 7. `downWithBatch` dispatch (or bufferAll capture if paused with\n\t * `pausable: \"resumeAll\"`).\n\t * 8. Recursive ERROR emission if equals threw mid-walk.\n\t */\n\t_emit(messages: Messages): void {\n\t\tif (messages.length === 0) return;\n\n\t\t// Terminal filter: after COMPLETE/ERROR (non-resubscribable), only\n\t\t// TEARDOWN / INVALIDATE still propagate so graph teardown and cache-\n\t\t// clear still work.\n\t\tlet deliverable = messages;\n\t\tconst terminal = this._isTerminal;\n\t\tif (terminal && !this._resubscribable) {\n\t\t\tconst pass = messages.filter((m) => m[0] === TEARDOWN || m[0] === INVALIDATE);\n\t\t\tif (pass.length === 0) return;\n\t\t\tdeliverable = pass;\n\t\t}\n\n\t\t// Tier sort + synthetic DIRTY prefix (stages 3 + 4 of the emit\n\t\t// pipeline). `_frameBatch` is a no-op for pre-sorted single-msg\n\t\t// batches (the common case from the tuple-interning A2 call sites);\n\t\t// otherwise it produces a stable tier-sorted copy with `[DIRTY]`\n\t\t// auto-prepended after any tier-0 messages when a tier-3 payload\n\t\t// is present and the node isn't already dirty.\n\t\tdeliverable = this._frameBatch(deliverable);\n\n\t\t// C0 — PAUSE/RESUME lock tracking. Every tier-2 tuple MUST carry a\n\t\t// `lockId` payload. Each PAUSE / RESUME updates `_pauseLocks` and\n\t\t// derives `_paused` from set size — multi-pauser correctness\n\t\t// guarantees a node only resumes when every lock it holds is\n\t\t// released. All tier-2 messages are forwarded unconditionally so\n\t\t// downstream nodes on the propagation path keep their own lock\n\t\t// sets consistent (subscribers that joined the graph before any\n\t\t// PAUSE see the full lock history). `pausable: false` sources\n\t\t// forward PAUSE/RESUME but do not track locks — appropriate for\n\t\t// reactive timers that must keep ticking. Unknown-lockId RESUME\n\t\t// is swallowed to keep `dispose()` idempotent.\n\t\tlet filtered: Message[] | null = null;\n\t\tfor (let i = 0; i < deliverable.length; i++) {\n\t\t\tconst m = deliverable[i];\n\t\t\tconst t = m[0];\n\t\t\tif (t !== PAUSE && t !== RESUME) {\n\t\t\t\tif (filtered != null) filtered.push(m);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m.length < 2) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${this.name}\": [[${t === PAUSE ? \"PAUSE\" : \"RESUME\"}]] must ` +\n\t\t\t\t\t\t\"carry a lockId payload — bare PAUSE/RESUME is a protocol \" +\n\t\t\t\t\t\t\"violation (C0 rule). Use `[[PAUSE, lockId]]` / \" +\n\t\t\t\t\t\t\"`[[RESUME, lockId]]`.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet forward = true;\n\t\t\tif (this._pausable !== false) {\n\t\t\t\tconst lockId = m[1];\n\t\t\t\tif (t === PAUSE) {\n\t\t\t\t\tif (this._pauseLocks == null) this._pauseLocks = new Set();\n\t\t\t\t\tthis._pauseLocks.add(lockId);\n\t\t\t\t\tthis._paused = true;\n\t\t\t\t\tif (this._pausable === \"resumeAll\" && this._pauseBuffer == null) {\n\t\t\t\t\t\tthis._pauseBuffer = [];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// RESUME\n\t\t\t\t\tif (this._pauseLocks == null || !this._pauseLocks.has(lockId)) {\n\t\t\t\t\t\t// Unknown lockId — swallow to keep dispose idempotent.\n\t\t\t\t\t\tforward = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._pauseLocks.delete(lockId);\n\t\t\t\t\t\tif (this._pauseLocks.size === 0) {\n\t\t\t\t\t\t\tthis._paused = false;\n\t\t\t\t\t\t\t// Replay bufferAll buffer through the outgoing\n\t\t\t\t\t\t\t// pipeline BEFORE forwarding RESUME — subscribers\n\t\t\t\t\t\t\t// observe the deferred DATAs as part of the\n\t\t\t\t\t\t\t// pre-RESUME wake-up.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// D2 (2026-04-13) semantic note: the recursive\n\t\t\t\t\t\t\t// `_emit(drain)` goes through the full pipeline\n\t\t\t\t\t\t\t// including `_updateState`'s equals substitution.\n\t\t\t\t\t\t\t// A buffered `[DATA, v]` whose value matches the\n\t\t\t\t\t\t\t// *pre-pause* cache will collapse to RESOLVED on\n\t\t\t\t\t\t\t// replay — producer \"pulses\" that write the same\n\t\t\t\t\t\t\t// value while paused are absorbed. This matches\n\t\t\t\t\t\t\t// diamond-safety intent: `.cache` stays coherent\n\t\t\t\t\t\t\t// with \"the last DATA actually delivered to\n\t\t\t\t\t\t\t// sinks\". Producers that need pulse semantics\n\t\t\t\t\t\t\t// (every write observable regardless of value)\n\t\t\t\t\t\t\t// should set `equals: () => false` on the node.\n\t\t\t\t\t\t\tif (this._pauseBuffer != null && this._pauseBuffer.length > 0) {\n\t\t\t\t\t\t\t\tconst drain = this._pauseBuffer;\n\t\t\t\t\t\t\t\tthis._pauseBuffer = [];\n\t\t\t\t\t\t\t\tthis._emit(drain);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Kick the held wave forward if one was pending.\n\t\t\t\t\t\t\tif (this._pendingWave) {\n\t\t\t\t\t\t\t\tthis._pendingWave = false;\n\t\t\t\t\t\t\t\tthis._maybeRunFnOnSettlement();\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\tif (!forward) {\n\t\t\t\tif (filtered == null) filtered = deliverable.slice(0, i) as Message[];\n\t\t\t} else if (filtered != null) {\n\t\t\t\tfiltered.push(m);\n\t\t\t}\n\t\t}\n\t\tif (filtered != null) {\n\t\t\tif (filtered.length === 0) return;\n\t\t\tdeliverable = filtered;\n\t\t}\n\n\t\t// Meta TEARDOWN fan-out happens BEFORE `_updateState` so the walk\n\t\t// stays re-entrance-free: a meta node's own dispatch must not\n\t\t// re-enter the parent's outgoing pipeline while `this._cached` /\n\t\t// `this._status` are mid-commit. This preserves the spec ordering\n\t\t// \"meta propagates before deactivation\" — `_updateState`'s TEARDOWN\n\t\t// branch still runs `_deactivate` AFTER the meta children\n\t\t// have already been notified here.\n\t\tif (this._hasMeta && deliverable.some((m) => m[0] === TEARDOWN)) {\n\t\t\tfor (const k of Object.keys(this.meta)) {\n\t\t\t\ttry {\n\t\t\t\t\t(this.meta[k] as NodeImpl)._emit(TEARDOWN_ONLY_BATCH);\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// State update + equals substitution (§3.5.1 invariant). Returns the\n\t\t// possibly-rewritten batch and an optional equals-throw error. When\n\t\t// equals throws mid-walk we still deliver the successfully-walked\n\t\t// prefix to sinks before emitting ERROR, preserving cache/wire\n\t\t// coherence (user P2 option (i)).\n\t\tconst { finalMessages, equalsError } = this._updateState(deliverable);\n\n\t\t// Global inspector fan-out (Redux-DevTools-style tracer). Fires once\n\t\t// per outgoing batch, gated by `inspectorEnabled` so production paths\n\t\t// pay one boolean check. Hook errors are swallowed — instrumentation\n\t\t// must not break the data plane.\n\t\tif (finalMessages.length > 0 && this._config.inspectorEnabled) {\n\t\t\tconst inspector = this._config.globalInspector;\n\t\t\tif (inspector != null) {\n\t\t\t\ttry {\n\t\t\t\t\tinspector({ kind: \"emit\", node: this, messages: finalMessages });\n\t\t\t\t} catch {\n\t\t\t\t\t/* best-effort */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (finalMessages.length > 0) {\n\t\t\t// BufferAll: while paused with `pausable: \"resumeAll\"`, buffer\n\t\t\t// tier-3/4 payloads in order. Tier 0–2 and tier 5 continue to\n\t\t\t// dispatch synchronously — START/DIRTY/RESUME/PAUSE/TEARDOWN\n\t\t\t// must stay live so subscribers, downstream pausers, and graph\n\t\t\t// teardown all observe them. Cache/status advance has already\n\t\t\t// happened via `_updateState`, so the replay later just pushes\n\t\t\t// the deferred messages back through `downWithBatch`.\n\t\t\tif (this._paused && this._pausable === \"resumeAll\" && this._pauseBuffer != null) {\n\t\t\t\tconst tierOf = this._config.tierOf;\n\t\t\t\tconst immediate: Message[] = [];\n\t\t\t\tfor (const m of finalMessages) {\n\t\t\t\t\tconst tier = tierOf(m[0]);\n\t\t\t\t\tif (tier < 3 || tier === 5) {\n\t\t\t\t\t\timmediate.push(m);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._pauseBuffer.push(m);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (immediate.length > 0) {\n\t\t\t\t\tthis._dispatchOrAccumulate(immediate);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis._dispatchOrAccumulate(finalMessages);\n\t\t\t}\n\t\t}\n\n\t\tif (equalsError != null) {\n\t\t\tthis._emit([[ERROR, equalsError]]);\n\t\t}\n\t}\n\n\t/**\n\t * @internal Walk an outgoing (already-framed) batch, updating own\n\t * cache / status / versioning and running equals substitution on\n\t * every tier-3 DATA (§3.5.1). Framing — tier sort and synthetic\n\t * DIRTY prefix — has already happened upstream in `_frameBatch`.\n\t * This walk trusts the input is in monotone tier order and that the\n\t * spec §1.3.1 DIRTY/RESOLVED precedence invariant is already\n\t * satisfied by the frame.\n\t *\n\t * Equals substitution: every DATA payload is compared against the\n\t * live `_cached`; when equal, the tuple is rewritten to `[RESOLVED]`\n\t * in a per-call copy and cache is not re-advanced. `.cache` remains\n\t * coherent with \"the last DATA payload this node actually sent\n\t * downstream\".\n\t *\n\t * Returns `{ finalMessages, equalsError? }`:\n\t * - `finalMessages` — the array to deliver to sinks (may be\n\t * `messages` unchanged, a rewritten copy with DATA→RESOLVED\n\t * substitutions, or a truncated prefix when equals throws mid-walk).\n\t * - `equalsError` — present only when the configured `equals` function\n\t * threw on some DATA message. `_emit` delivers the prefix first,\n\t * then emits a fresh ERROR batch via a recursive `_emit` call so\n\t * subscribers observe `[...walked_prefix, ERROR]` in order.\n\t */\n\tprivate _updateState(messages: Messages): {\n\t\tfinalMessages: Messages;\n\t\tequalsError?: Error;\n\t} {\n\t\tconst tierOf = this._config.tierOf;\n\t\tlet rewritten: Message[] | undefined;\n\t\tlet equalsError: Error | undefined;\n\t\tlet abortedAt = -1;\n\t\t// Count tier-3 messages (DATA + RESOLVED) in the batch. Equals\n\t\t// substitution is only worthwhile for a single tier-3 message —\n\t\t// an unchanged value can be rewritten to RESOLVED, enabling the\n\t\t// downstream pre-fn skip. With multiple tier-3 messages the\n\t\t// downstream fn must run regardless, so equals on each is wasted.\n\t\tlet dataCount = 0;\n\t\tfor (const m of messages) {\n\t\t\tif (tierOf(m[0]) === 3) dataCount++;\n\t\t}\n\t\tconst checkEquals = dataCount <= 1;\n\t\t// Version advances once per batch wave, not per DATA in the batch.\n\t\t// _cached only retains the last DATA value, so intermediate version\n\t\t// entries would reference values that can never be retrieved from cache.\n\t\t// Pre-scan for the last DATA index so we know when to fire advanceVersion.\n\t\tlet lastDataIdx = -1;\n\t\tif (this._versioning != null && dataCount > 1) {\n\t\t\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\t\t\tif (messages[i][0] === DATA) {\n\t\t\t\t\tlastDataIdx = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (let i = 0; i < messages.length; i++) {\n\t\t\tconst m = messages[i];\n\t\t\tconst t = m[0];\n\t\t\tif (t === DATA) {\n\t\t\t\tif (m.length >= 2) {\n\t\t\t\t\tlet unchanged = false;\n\t\t\t\t\tif (checkEquals && this._cached !== undefined) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tunchanged = this._equals(this._cached as T, m[1] as T);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t// Abort walk on equals throw: deliver successfully-walked\n\t\t\t\t\t\t\t// prefix, then caller emits ERROR. Excludes the throwing\n\t\t\t\t\t\t\t// message from the prefix.\n\t\t\t\t\t\t\tequalsError = this._wrapFnError(\"equals threw\", err);\n\t\t\t\t\t\t\tabortedAt = i;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (unchanged) {\n\t\t\t\t\t\tif (rewritten == null) rewritten = messages.slice(0, i) as Message[];\n\t\t\t\t\t\trewritten.push(RESOLVED_MSG);\n\t\t\t\t\t\tthis._status = \"resolved\";\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis._cached = m[1] as T;\n\t\t\t\t\tif (this._versioning != null) {\n\t\t\t\t\t\t// dataCount <= 1: lastDataIdx is -1; advance unconditionally\n\t\t\t\t\t\t// (single DATA, correct as before).\n\t\t\t\t\t\t// dataCount > 1: only advance on the last DATA in the batch.\n\t\t\t\t\t\tif (lastDataIdx < 0 || i === lastDataIdx) {\n\t\t\t\t\t\t\tadvanceVersion(this._versioning, m[1], this._hashFn);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._status = \"settled\";\n\t\t\t\tif (rewritten != null) rewritten.push(m);\n\t\t\t} else {\n\t\t\t\tif (rewritten != null) rewritten.push(m);\n\t\t\t\tif (t === DIRTY) {\n\t\t\t\t\tthis._status = \"dirty\";\n\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\tthis._status = \"resolved\";\n\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\tthis._status = \"completed\";\n\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\tthis._status = \"errored\";\n\t\t\t\t} else if (t === INVALIDATE) {\n\t\t\t\t\tthis._cached = undefined;\n\t\t\t\t\tthis._status = \"dirty\";\n\t\t\t\t\t// Function-form cleanup fires on invalidate (treats as \"re-run\").\n\t\t\t\t\tconst c = this._cleanup;\n\t\t\t\t\tif (typeof c === \"function\") {\n\t\t\t\t\t\tthis._cleanup = undefined;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tc();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t/* best-effort */\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (t === TEARDOWN) {\n\t\t\t\t\tif (this._resetOnTeardown) this._cached = undefined;\n\t\t\t\t\t// Meta TEARDOWN fan-out was already performed by `_emit`\n\t\t\t\t\t// before this walk. Deactivate now that meta children\n\t\t\t\t\t// have been notified.\n\t\t\t\t\tthis._deactivate(/* skipStatusUpdate */ true);\n\t\t\t\t\t// TEARDOWN is a hard reset — unconditionally \"sentinel\",\n\t\t\t\t\t// even if the node was previously completed/errored.\n\t\t\t\t\tthis._status = \"sentinel\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst base: Messages =\n\t\t\tabortedAt >= 0\n\t\t\t\t? ((rewritten ?? (messages.slice(0, abortedAt) as Messages)) as Messages)\n\t\t\t\t: (rewritten ?? messages);\n\t\treturn equalsError != null ? { finalMessages: base, equalsError } : { finalMessages: base };\n\t}\n\n\tprivate _deliverToSinks = (messages: Messages): void => {\n\t\tif (this._sinks == null) return;\n\t\tif (typeof this._sinks === \"function\") {\n\t\t\tthis._sinks(messages);\n\t\t\treturn;\n\t\t}\n\t\t// Snapshot: a sink callback may unsubscribe itself or others\n\t\t// mid-iteration. Iterating the live Set would skip not-yet-visited\n\t\t// sinks that were removed.\n\t\tconst snapshot = [...this._sinks];\n\t\tfor (const sink of snapshot) sink(messages);\n\t};\n\n\t/**\n\t * @internal Dispatch entry point that respects the per-batch emit\n\t * accumulator (Bug 2). Inside an explicit `batch()` scope, append to\n\t * `_batchPendingMessages` and register a flush hook on first append.\n\t * Outside batch — or during a drain (where `flushInProgress` is true\n\t * but `batchDepth` is 0) — dispatch synchronously through `downWithBatch`.\n\t *\n\t * Per-emit state updates (`_frameBatch`, `_updateState`) have already\n\t * happened by the time we reach here; only the **downstream delivery**\n\t * is coalesced. Cache, version, and status are visible mid-batch on\n\t * the emitting node itself.\n\t */\n\tprivate _dispatchOrAccumulate(messages: Messages): void {\n\t\tif (isExplicitlyBatching()) {\n\t\t\tif (this._batchPendingMessages === null) {\n\t\t\t\tthis._batchPendingMessages = [];\n\t\t\t\tregisterBatchFlushHook(() => this._flushBatchPending());\n\t\t\t}\n\t\t\tfor (const m of messages) this._batchPendingMessages.push(m);\n\t\t\treturn;\n\t\t}\n\t\tdownWithBatch(this._deliverToSinks, messages, this._config.tierOf);\n\t}\n\n\t/**\n\t * @internal Flushes the accumulated batch through `downWithBatch` and\n\t * clears the pending state. Idempotent — safe to call when pending is\n\t * already null or empty (e.g. on a `batch()` throw, where the hook\n\t * fires for cleanup but the drainPhase queues are wiped after).\n\t *\n\t * Critical: the accumulated batch is interleaved per-emit framings like\n\t * `[DIRTY, DATA(1), DIRTY, DATA(2)]` — non-monotone tier order. We must\n\t * re-frame to sort by tier before handing to `downWithBatch`, which\n\t * assumes pre-sorted input. `_frameBatch` also handles the synthetic\n\t * DIRTY prepend rule (no-op here — `hasDirty` is true since each\n\t * accumulated emit already carries its own DIRTY prefix).\n\t */\n\tprivate _flushBatchPending(): void {\n\t\tconst pending = this._batchPendingMessages;\n\t\tif (pending === null) return;\n\t\tthis._batchPendingMessages = null;\n\t\tif (pending.length === 0) return;\n\t\tconst framed = this._frameBatch(pending);\n\t\tdownWithBatch(this._deliverToSinks, framed, this._config.tierOf);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nconst isNodeArray = (value: unknown): value is readonly Node[] => Array.isArray(value);\nconst isNodeOptionsObject = (value: unknown): value is NodeOptions<unknown> =>\n\ttypeof value === \"object\" && value != null && !Array.isArray(value);\n\n/**\n * Creates a reactive {@link Node} — the single GraphReFly primitive (§2).\n *\n * Typical shapes:\n * - `node([])` / `node({ initial: v })` — a manual source (state node).\n * - `node(producerFn, opts)` — a producer that runs on first-subscribe.\n * - `node(deps, computeFn, opts)` — a derived / effect node.\n *\n * For value-returning computations, prefer the sugar factories in `sugar.ts`\n * (`state`, `derived`, `effect`, `producer`, `dynamicNode`), which wrap user\n * fns with `actions.emit(userFn(data))`. Calling `node()` directly gives you\n * the raw `NodeFn` contract: explicit emission via `actions`, cleanup return.\n */\nexport function node<T = unknown>(\n\tdepsOrFn?: readonly Node[] | NodeFn | NodeOptions<T>,\n\tfnOrOpts?: NodeFn | NodeOptions<T>,\n\toptsArg?: NodeOptions<T>,\n): Node<T> {\n\tconst deps: readonly Node[] = isNodeArray(depsOrFn) ? depsOrFn : [];\n\tconst fn: NodeFn | undefined =\n\t\ttypeof depsOrFn === \"function\"\n\t\t\t? depsOrFn\n\t\t\t: typeof fnOrOpts === \"function\"\n\t\t\t\t? fnOrOpts\n\t\t\t\t: undefined;\n\tlet opts: NodeOptions<T> = {};\n\tif (isNodeArray(depsOrFn)) {\n\t\topts = ((isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {}) as NodeOptions<T>;\n\t} else if (isNodeOptionsObject(depsOrFn)) {\n\t\topts = depsOrFn as NodeOptions<T>;\n\t} else {\n\t\topts = ((isNodeOptionsObject(fnOrOpts) ? fnOrOpts : optsArg) ?? {}) as NodeOptions<T>;\n\t}\n\treturn new NodeImpl<T>(deps, fn, opts);\n}\n","/**\n * Sugar constructors over the raw `node()` primitive.\n *\n * Each factory wraps a user-friendly function into the canonical\n * `NodeFn = (data, actions, ctx) => cleanup | void` shape, then calls\n * `node(...)`. This is the only place `actions.emit(...)` is invoked\n * on behalf of the user — if you need finer control (multi-emission,\n * raw `actions.down` / `actions.up`, cleanup return), use the raw\n * `node()` factory from `./node.js` directly.\n *\n * See SESSION-foundation-redesign.md §8.5 + §10.6 for the rewrite.\n */\n\nimport type { NodeActions } from \"./config.js\";\nimport { RESOLVED } from \"./messages.js\";\nimport {\n\ttype FnCtx,\n\ttype Node,\n\ttype NodeFn,\n\ttype NodeFnCleanup,\n\tNodeImpl,\n\ttype NodeOptions,\n\tnode,\n} from \"./node.js\";\n\n// ---------------------------------------------------------------------------\n// Shared sentinel guard\n// ---------------------------------------------------------------------------\n\n/**\n * Returns `true` when fn should be suppressed (RESOLVED emitted instead).\n *\n * Fires when `allowPartial` is `false` and any dep has never delivered DATA:\n * `data[i]` absent this wave AND `ctx.prevData[i] === undefined`.\n *\n * `undefined` is the protocol-reserved \"never sent DATA\" sentinel. `null` is\n * a valid DATA value and will NOT trigger the guard.\n */\nfunction sentinelGuard(\n\tbatchData: readonly (readonly unknown[] | undefined)[],\n\tctx: FnCtx,\n\tallowPartial: boolean,\n): boolean {\n\tif (allowPartial) return false;\n\treturn batchData.some(\n\t\t(batch, i) => !(batch != null && batch.length > 0) && ctx.prevData[i] === undefined,\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// state — manual source with an optional initial value\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a manual source node. Drive it with `state.emit(v)` (framed,\n * diamond-safe) or `state.down([[DATA, v]])` (raw compat path).\n *\n * @param initial - Starting cached value. Pass `undefined` or `null`\n * explicitly to cache that value; omit to leave the node in `\"sentinel\"`.\n * @param opts - Optional {@link NodeOptions} (excluding `initial`).\n */\nexport function state<T>(initial: T, opts?: Omit<NodeOptions<T>, \"initial\">): Node<T> {\n\treturn node<T>([], { ...opts, initial });\n}\n\n// ---------------------------------------------------------------------------\n// producer — no-deps source with a compute body\n// ---------------------------------------------------------------------------\n\n/**\n * User-level producer compute: runs once on first-subscriber activation.\n * Receives `actions` for imperative emission and `ctx` for FnCtx (typically\n * only `store` is useful on a producer — no deps means `prevData` and\n * `terminalDeps` are empty).\n */\nexport type ProducerFn = (\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: matches NodeFn — see its JSDoc.\n) => NodeFnCleanup | void;\n\n/**\n * Creates a producer node with no deps; `fn` runs once when the first\n * subscriber connects. Return a cleanup function (`() => void`) or\n * `{ deactivation: () => void }` to register teardown.\n *\n * @example\n * ```ts\n * const ticker = producer((actions) => {\n * const id = setInterval(() => actions.emit(Date.now()), 1000);\n * return () => clearInterval(id);\n * });\n * ```\n */\nexport function producer<T = unknown>(fn: ProducerFn, opts?: NodeOptions<T>): Node<T> {\n\tconst wrapped: NodeFn = (_data, actions, ctx) => fn(actions, ctx) ?? undefined;\n\treturn node<T>(wrapped, { describeKind: \"producer\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// derived — dep-driven pure compute\n// ---------------------------------------------------------------------------\n\n/**\n * User-level derived compute: receives the latest DATA from each dep and\n * returns the new value. The sugar wraps it with `actions.emit(fn(...))`\n * so the return value flows through the framed emit pipeline.\n *\n * For derived nodes that need to inspect `ctx.prevData` / `ctx.terminalDeps`\n * / `ctx.store`, accept the optional second parameter.\n */\nexport type DerivedFn<T> = (data: readonly unknown[], ctx: FnCtx) => T | undefined | null;\n\n/**\n * Creates a derived node that computes **one output per wave** from the latest\n * value of each dependency — **snapshot / combine semantics**.\n *\n * `fn` receives one scalar per dep (the last DATA value seen this wave, or the\n * prior-wave value as fallback). It is called once per settled wave and emits\n * a single value via `actions.emit`. The equals check then suppresses the\n * emission as `RESOLVED` if the output has not changed.\n *\n * **Not for streaming one-to-one transforms.** If each DATA value in a batch\n * must produce a corresponding output (e.g. transforming every item emitted by\n * `fromIter` individually), use {@link map} or raw `node()` with full batch\n * iteration instead. `derived` only sees the *last* value per dep when a batch\n * carries multiple DATAs.\n *\n * @example\n * ```ts\n * const a = state(1);\n * const b = derived([a], ([x]) => (x as number) * 2);\n * ```\n */\nexport function derived<T = unknown>(\n\tdeps: readonly Node[],\n\tfn: DerivedFn<T>,\n\topts?: NodeOptions<T> & { partial?: boolean },\n): Node<T> {\n\tconst allowPartial = opts?.partial ?? false;\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\t// Sentinel guard: if any dep has never sent DATA, emit RESOLVED.\n\t\t// Uses ctx.prevData[i] === undefined (the \"never sent\" sentinel).\n\t\t// null is valid DATA and won't trigger this. Skipped when partial:true.\n\t\tif (sentinelGuard(batchData, ctx, allowPartial)) {\n\t\t\tactions.down([[RESOLVED]]);\n\t\t\treturn undefined;\n\t\t}\n\t\t// Unwrap batch-per-dep to single latest scalar per dep.\n\t\t// Batch non-null+non-empty → take last value from this wave;\n\t\t// otherwise fall back to ctx.prevData[i] (last value from prior wave).\n\t\t// undefined means \"never sent DATA\" — sentinelGuard already blocks this\n\t\t// fn when partial:false and any dep is unset, so partial:true callers\n\t\t// receive undefined for uninitiated deps (same as JS convention).\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\tactions.emit(fn(data, ctx));\n\t\treturn undefined;\n\t};\n\treturn node<T>(deps, wrapped, { describeKind: \"derived\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// effect — dep-driven side effect, no auto-emit\n// ---------------------------------------------------------------------------\n\n/**\n * User-level effect compute: fires when deps settle. Return value is NOT\n * auto-emitted — use `actions.emit(v)` / `actions.down(msgs)` explicitly if\n * the effect also wants to produce downstream messages. Return a cleanup\n * function or `{ deactivation }` to register teardown.\n */\nexport type EffectFn = (\n\tdata: readonly unknown[],\n\tactions: NodeActions,\n\tctx: FnCtx,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: matches NodeFn — see its JSDoc.\n) => NodeFnCleanup | void;\n\n/**\n * Runs a side-effect when deps settle. Return value is not auto-emitted.\n *\n * @example\n * ```ts\n * effect([source], ([v]) => {\n * console.log(v);\n * });\n * ```\n */\nexport function effect(\n\tdeps: readonly Node[],\n\tfn: EffectFn,\n\topts?: NodeOptions<unknown> & { partial?: boolean },\n): Node<unknown> {\n\tconst allowPartial = opts?.partial ?? false;\n\tconst wrapped: NodeFn = (batchData, actions, ctx) => {\n\t\t// Sentinel guard: hold effect until all deps have initialised.\n\t\t// Matches pre-wave2 framework gate behaviour. Use partial:true to allow\n\t\t// the effect to fire before all deps have delivered their first value.\n\t\tif (sentinelGuard(batchData, ctx, allowPartial)) {\n\t\t\tactions.down([[RESOLVED]]);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst data = batchData.map((batch, i) =>\n\t\t\tbatch != null && batch.length > 0 ? batch.at(-1) : ctx.prevData[i],\n\t\t);\n\t\treturn fn(data, actions, ctx) ?? undefined;\n\t};\n\treturn node(deps, wrapped, { describeKind: \"effect\", ...opts });\n}\n\n// ---------------------------------------------------------------------------\n// dynamicNode — track-proxy wrapper over `derived`\n// ---------------------------------------------------------------------------\n\n/**\n * Proxy handed to a {@link DynamicFn}. `track(dep)` returns the dep's\n * latest DATA payload, as delivered through the protocol. Reading from\n * `track` does NOT bypass the message protocol — it reads the internal\n * `DepRecord.prevData` (the stable end-of-previous-wave value) that\n * `_onDepMessage` already populated. If a dep has not yet sent DATA,\n * `track` returns `undefined`.\n */\nexport type TrackFn = (dep: Node) => unknown;\n\n/** User-level dynamicNode compute. */\nexport type DynamicFn<T> = (track: TrackFn, ctx: FnCtx) => T | undefined | null;\n\n/**\n * Sugar over `derived(...)` that exposes dep values via a `track(dep)`\n * proxy instead of positional `data[i]`. All declared `allDeps` participate\n * in wave tracking, so the first fn run waits for every dep to settle.\n * Unused deps that update just re-run fn; `equals` absorbs unchanged\n * outputs as RESOLVED.\n *\n * P3-compliant: `track(dep)` reads from the framework-managed\n * `DepRecord.prevData` populated by the protocol, never from\n * `dep.cache`.\n *\n * @example\n * ```ts\n * const a = state(1);\n * const b = state(10);\n * const sum = dynamicNode([a, b], (track) => (track(a) as number) + (track(b) as number));\n * ```\n */\nexport function dynamicNode<T = unknown>(\n\tallDeps: readonly Node[],\n\tfn: DynamicFn<T>,\n\topts?: NodeOptions<T> & { partial?: boolean },\n): Node<T> {\n\tconst depIndex = new Map<Node, number>();\n\tallDeps.forEach((d, i) => {\n\t\tdepIndex.set(d, i);\n\t});\n\treturn derived<T>(\n\t\tallDeps,\n\t\t// data[i] is already sugar-unwrapped to a scalar by derived()'s wrapper.\n\t\t(data, ctx) => {\n\t\t\tconst track: TrackFn = (dep) => {\n\t\t\t\tconst i = depIndex.get(dep);\n\t\t\t\tif (i == null) {\n\t\t\t\t\tthrow new Error(`dynamicNode: untracked dep \"${dep.name ?? \"<unnamed>\"}\"`);\n\t\t\t\t}\n\t\t\t\treturn data[i];\n\t\t\t};\n\t\t\treturn fn(track, ctx);\n\t\t},\n\t\topts,\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// pipe — left-to-right operator composition\n// ---------------------------------------------------------------------------\n// autoTrackNode — runtime dep discovery (Jotai/signals compat)\n// ---------------------------------------------------------------------------\n\n/**\n * Like {@link dynamicNode} but deps are discovered at runtime via `track()`\n * calls — no upfront `allDeps` array needed. Designed for pull-based compat\n * layers (Jotai atoms, TC39 Signals) where deps are unknown until fn runs.\n *\n * **Two-phase discovery:**\n * 1. fn runs. Each `track(dep)` for an unknown dep: subscribes immediately\n * via `_addDep`, returns `dep.cache` as a stub (P3 boundary exception).\n * Result is discarded (discovery run).\n * 2. New deps settle (DATA from subscribe handshake). Wave machinery\n * re-triggers fn. `track(dep)` now returns protocol-delivered `data[i]`.\n * If MORE unknown deps appear, repeat step 1.\n * 3. Converges when no new deps found → real run → `actions.emit(result)`.\n *\n * P3 violation is limited to discovery runs. Once all deps are known,\n * subsequent waves use protocol-delivered values exclusively.\n *\n * Re-entrance safety: `_addDep` subscribes immediately. If the dep delivers\n * DATA synchronously during fn execution, `_execFn`'s re-entrance guard\n * defers the re-run to after the current fn returns.\n *\n * @param opts - Optional {@link AutoTrackOptions}. Pass `{ partial: true }` to\n * allow fn to run before all known deps have delivered their first value\n * (useful for optional/secondary deps).\n *\n * @example\n * ```ts\n * const a = state(1), b = state(2);\n * const sum = autoTrackNode((track) => track(a) + track(b));\n * // deps [a, b] discovered automatically on first run\n * ```\n */\n/**\n * Options for {@link autoTrackNode}.\n */\nexport interface AutoTrackOptions<T> extends NodeOptions<T> {\n\t/**\n\t * When `true`, fn may run before all known deps have delivered their first\n\t * DATA. Unknown deps return `undefined` via `track()`, which the fn must\n\t * handle explicitly. Useful when some deps are \"nice-to-have\" — e.g. a\n\t * primary computation should continue while a secondary dep is still\n\t * initialising.\n\t *\n\t * When `false` (default), fn is held until every known dep has delivered at\n\t * least one DATA value — a RESOLVED is emitted for the wave instead.\n\t * This matches `derived()` semantics and is the correct default for\n\t * pull-based compat layers (Signals, Jotai) where all deps must be\n\t * initialised before the computation is meaningful.\n\t *\n\t * @default false\n\t */\n\tpartial?: boolean;\n}\n\nexport function autoTrackNode<T = unknown>(\n\tfn: (track: TrackFn, ctx: FnCtx) => T | undefined | null,\n\topts?: AutoTrackOptions<T>,\n): Node<T> {\n\tlet implRef: NodeImpl<T>;\n\tconst depIndexMap = new Map<Node, number>();\n\tconst allowPartial = opts?.partial ?? false;\n\n\tconst wrappedFn: NodeFn = (batchData, actions, ctx) => {\n\t\tlet foundNew = false;\n\t\tconst track: TrackFn = (dep) => {\n\t\t\tconst idx = depIndexMap.get(dep);\n\t\t\tif (idx !== undefined) {\n\t\t\t\t// Known dep — return latest protocol-delivered value.\n\t\t\t\t// batch non-null+non-empty → latest from this wave;\n\t\t\t\t// otherwise fall back to ctx.prevData (last known value).\n\t\t\t\tif (idx < batchData.length) {\n\t\t\t\t\tconst batch = batchData[idx];\n\t\t\t\t\tif (batch != null && batch.length > 0) return batch.at(-1);\n\t\t\t\t\treturn ctx.prevData[idx];\n\t\t\t\t}\n\t\t\t\treturn dep.cache;\n\t\t\t}\n\t\t\t// Unknown dep — discovery phase.\n\t\t\tfoundNew = true;\n\t\t\tconst newIdx = implRef._addDep(dep);\n\t\t\tdepIndexMap.set(dep, newIdx);\n\t\t\treturn dep.cache; // P3 boundary exception (discovery stub)\n\t\t};\n\n\t\t// Sentinel guard (skipped when partial:true): if any known dep has never\n\t\t// delivered DATA (no DATA this wave AND ctx.prevData[idx] === undefined), emit RESOLVED\n\t\t// and defer. Mirrors derived()'s guard for the same sequential-handshake\n\t\t// scenario: when a node re-activates outside a batch and dep A delivers\n\t\t// synchronously before dep B is even subscribed, this holds fn until all\n\t\t// known deps have initialised rather than running with B=undefined.\n\t\t// Uses ctx.prevData[idx] === undefined — the protocol sentinel for\n\t\t// \"dep never sent DATA\". null is valid DATA and won't trigger this.\n\t\t// Only active when depIndexMap is non-empty (initial discovery runs are\n\t\t// unaffected) and when partial:false (default).\n\t\tif (!allowPartial && depIndexMap.size > 0) {\n\t\t\tfor (const [, idx] of depIndexMap) {\n\t\t\t\tif (idx < batchData.length) {\n\t\t\t\t\tconst batch = batchData[idx];\n\t\t\t\t\tif (!(batch != null && batch.length > 0) && ctx.prevData[idx] === undefined) {\n\t\t\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = fn(track, ctx);\n\t\t\tif (!foundNew) {\n\t\t\t\t// Real run — all deps known, protocol-delivered values.\n\t\t\t\tactions.emit(result);\n\t\t\t\t// Clear any stale discovery error from a prior run.\n\t\t\t\tif (ctx.store.__autoTrackLastDiscoveryError != null) {\n\t\t\t\t\tdelete ctx.store.__autoTrackLastDiscoveryError;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Discovery run — result discarded. New deps are subscribed via\n\t\t\t// _addDep. Their DATA delivery triggers _maybeRunFnOnSettlement\n\t\t\t// via the _pendingRerun mechanism, which will re-call fn.\n\t\t} catch (err) {\n\t\t\tif (!foundNew) throw err;\n\t\t\t// Discovery run threw — most likely a stale `.cache` read (P3\n\t\t\t// boundary exception), which the protocol-delivered retry will\n\t\t\t// not hit. Preserve the error on `ctx.store` for inspection; if\n\t\t\t// the retry succeeds, the flag is cleared above. If fn has a\n\t\t\t// real bug unrelated to cache, the non-discovery retry will\n\t\t\t// re-throw it out of `_execFn`.\n\t\t\tctx.store.__autoTrackLastDiscoveryError = err;\n\t\t}\n\t\treturn undefined;\n\t};\n\n\timplRef = new NodeImpl<T>([], wrappedFn, {\n\t\tdescribeKind: \"derived\",\n\t\t...opts,\n\t});\n\treturn implRef;\n}\n\n// ---------------------------------------------------------------------------\n// pipe — left-to-right operator composition\n// ---------------------------------------------------------------------------\n\n/** Unary operator used by {@link pipe}. */\nexport type PipeOperator = (n: Node) => Node;\n\n/**\n * Composes unary operators left-to-right; returns the final node.\n *\n * @example\n * ```ts\n * const out = pipe(\n * source,\n * (n) => map(n, (x) => x + 1),\n * (n) => filter(n, (x) => x > 0),\n * );\n * ```\n */\nexport function pipe(source: Node, ...ops: PipeOperator[]): Node {\n\tlet current = source;\n\tfor (const op of ops) current = op(current);\n\treturn current;\n}\n","/**\n * Reactive append-only log (roadmap §3.2) — emits `readonly T[]` snapshots directly.\n *\n * Internal version counter drives efficient equality without leaking `Versioned`\n * into the public API (spec §5.12).\n *\n * **Wave 4 refactor (2026-04-15):** Introduces the `LogBackend<T>` pluggable-backend\n * interface. The default `NativeLogBackend` uses a ring buffer when `maxSize` is set\n * (O(1) append + trim) and a flat array otherwise. `tail(n)` and `slice(start, stop)`\n * are memoized — repeat calls with identical arguments return the same derived node,\n * bounding the keepalive-subscription footprint. The standalone `logSlice` factory\n * has been removed; use `log.slice(start, stop)` instead.\n */\nimport { batch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { derived, state } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\n\nexport type ReactiveLogOptions<T> = {\n\tname?: string;\n\tmaxSize?: number;\n\t/**\n\t * Optional versioning level for the underlying `entries` state node. Set\n\t * at construction time; cannot be changed later. Pass `0` for V0 identity\n\t * + monotonic version counter, or `1` for V1 + content-addressed cid.\n\t */\n\tversioning?: VersioningLevel;\n\t/**\n\t * Storage backend. Defaults to `NativeLogBackend` (ring buffer if `maxSize` is set,\n\t * flat array otherwise). Users can plug in persistent / RRB-tree backends via\n\t * the {@link LogBackend} interface.\n\t */\n\tbackend?: LogBackend<T>;\n};\n\nexport type ReactiveLogBundle<T> = {\n\t/** Emits `readonly T[]` on each append/clear/trim (two-phase). */\n\treadonly entries: Node<readonly T[]>;\n\t/** Current entry count (O(1)). */\n\treadonly size: number;\n\t/** Positional access (O(1)); returns `undefined` on out-of-range. Supports negative indices (Python-style). */\n\tat: (index: number) => T | undefined;\n\tappend: (value: T) => void;\n\t/**\n\t * Push all values, emit one snapshot. No-op if `values` is empty.\n\t * **Iterable consumption:** `values` is a `readonly T[]` — safe to pass arrays.\n\t */\n\tappendMany: (values: readonly T[]) => void;\n\tclear: () => void;\n\t/** Remove the first `n` entries (clamped to `size`). Throws on non-integer or negative `n`. */\n\ttrimHead: (n: number) => void;\n\t/**\n\t * Last `n` entries (or fewer) as a derived reactive view. Memoized with\n\t * an LRU cache (default cap 64) — repeat calls with the same `n` return\n\t * the same node. Throws on non-integer or negative `n`.\n\t *\n\t * **LRU eviction contract (D3(b)):** when a 65th distinct `n` is passed,\n\t * the least-recently-used cached view is evicted and its keepalive is\n\t * disposed. External holders of the evicted node will NOT receive further\n\t * updates — re-call `tail(n)` for a fresh node, or dispose proactively\n\t * via {@link disposeTail} / {@link disposeAllViews}. To avoid surprise:\n\t * resolve `tail(n)` at the point of use rather than caching the returned\n\t * node across many distinct `n`s.\n\t */\n\ttail: (n: number) => Node<readonly T[]>;\n\t/**\n\t * Reactive view of `entries.slice(start, stop)` — non-negative integer\n\t * `start`, non-negative integer `stop` (exclusive) or `undefined` (to end).\n\t * Memoized with an LRU cache (default cap 64) — repeat calls with the\n\t * same `(start, stop)` return the same node.\n\t *\n\t * Throws on non-integer `start`, negative `start`, non-integer `stop`, or\n\t * negative `stop` (P4 — the backend cannot cheaply honor JS-style\n\t * negative `stop` without scanning length; disallowed for a consistent\n\t * contract between backend, derived recomputation, and cached initial).\n\t *\n\t * **LRU eviction contract (D3(b)):** same as {@link tail} — past 64\n\t * distinct `(start, stop)` pairs, the oldest cached view is evicted and\n\t * its keepalive disposed. External holders stop receiving updates.\n\t */\n\tslice: (start: number, stop?: number) => Node<readonly T[]>;\n\t/**\n\t * Releases the cached `tail(n)` view if present (disposes its keepalive\n\t * subscription). Subsequent `tail(n)` calls create a fresh node. No-op if\n\t * `n` was not cached. Returns `true` if a view was disposed.\n\t */\n\tdisposeTail: (n: number) => boolean;\n\t/**\n\t * Releases the cached `slice(start, stop?)` view if present. No-op if not cached.\n\t */\n\tdisposeSlice: (start: number, stop?: number) => boolean;\n\t/** Releases all cached tail/slice views and their keepalive subscriptions. */\n\tdisposeAllViews: () => void;\n\t/**\n\t * Releases all internal keepalive subscriptions so the bundle can be\n\t * GC'd — currently equivalent to {@link disposeAllViews}, but exposed as\n\t * a uniform API across all reactive data structures for lifecycle\n\t * symmetry (mirrors `reactiveMap.dispose` / `reactiveList.dispose` /\n\t * `reactiveIndex.dispose`). Idempotent. D6(a).\n\t */\n\tdispose: () => void;\n};\n\n// ── Backend interface ─────────────────────────────────────────────────────\n\n/**\n * Storage contract for {@link reactiveLog}. Implementations own the mutable state and\n * expose a monotonic `version` counter that increments on every structural change.\n *\n * The reactive layer reads `version` to decide when to emit; it does not inspect\n * internal representation. Users can plug in persistent / ring-buffer / skip-list\n * backends without touching the reactive emission logic.\n *\n * @remarks Post-1.0 op-log changesets will extend this interface with a\n * `changesSince(version: number): Iterable<Change>` method. Current consumers\n * should treat all methods here as stable.\n *\n * @category extra\n */\nexport interface LogBackend<T> {\n\t/** Monotonic mutation counter; increments on every append/trim/clear that changes state. */\n\treadonly version: number;\n\t/** Number of entries currently stored. */\n\treadonly size: number;\n\t/** O(1) positional access; returns `undefined` on out-of-range. */\n\tat(index: number): T | undefined;\n\t/** Append a value. Applies `maxSize` head-drop if configured. Advances `version`. */\n\tappend(value: T): void;\n\t/** Append a batch; advances `version` once. No-op if `values.length === 0`. */\n\tappendMany(values: readonly T[]): void;\n\t/** Remove all entries. Returns count removed. Advances `version` only if non-zero. */\n\tclear(): number;\n\t/** Remove the first `n` entries (clamped). Returns count removed. Throws on negative `n`. */\n\ttrimHead(n: number): number;\n\t/** Fresh snapshot array for `[start, stop)`. Throws on negative `start`. */\n\tslice(start: number, stop?: number): readonly T[];\n\t/** Last `n` entries as a fresh array. Throws on negative `n`. */\n\ttail(n: number): readonly T[];\n\t/** Full snapshot as a fresh array. */\n\ttoArray(): readonly T[];\n}\n\n/**\n * Default append-only log backend.\n *\n * - When `maxSize` is set: uses a **ring buffer** with `_head` index and circular\n * modular arithmetic. Append and trim become O(1); snapshot is O(size) unrolling.\n * - When `maxSize` is unset: uses a flat array with standard push/splice.\n *\n * `appendMany` pre-trims oversize input: if `values.length > maxSize`, only the\n * tail of `values` is pushed (the rest would be immediately evicted).\n *\n * @category extra\n */\nexport class NativeLogBackend<T> implements LogBackend<T> {\n\tprivate _version = 0;\n\tprivate readonly _maxSize?: number;\n\tprivate readonly _buf: T[];\n\tprivate _head = 0;\n\tprivate _size = 0;\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tif (maxSize !== undefined && maxSize < 1) {\n\t\t\tthrow new RangeError(\"maxSize must be >= 1\");\n\t\t}\n\t\tthis._maxSize = maxSize;\n\t\tif (maxSize !== undefined) {\n\t\t\t// Ring buffer mode — pre-allocate fixed size\n\t\t\tthis._buf = new Array(maxSize);\n\t\t\tif (initial && initial.length > 0) {\n\t\t\t\tconst take = Math.min(initial.length, maxSize);\n\t\t\t\tconst start = initial.length - take;\n\t\t\t\tfor (let i = 0; i < take; i++) {\n\t\t\t\t\tthis._buf[i] = initial[start + i]!;\n\t\t\t\t}\n\t\t\t\tthis._size = take;\n\t\t\t}\n\t\t} else {\n\t\t\t// Unbounded mode — dynamic array\n\t\t\tthis._buf = initial ? [...initial] : [];\n\t\t\tthis._size = this._buf.length;\n\t\t}\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\t// P5: Python-style negative index — `-1` returns the last entry.\n\t\tconst i = index >= 0 ? index : this._size + index;\n\t\tif (i < 0 || i >= this._size) return undefined;\n\t\tif (this._maxSize !== undefined) {\n\t\t\treturn this._buf[(this._head + i) % this._maxSize];\n\t\t}\n\t\treturn this._buf[i];\n\t}\n\n\tappend(value: T): void {\n\t\tthis._rawAppend(value);\n\t\tthis._version += 1;\n\t}\n\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\t// Pre-trim oversize input in ring mode — skip values that would be\n\t\t// immediately evicted. Iterate with a start index instead of\n\t\t// allocating an intermediate slice. F2.\n\t\tconst start =\n\t\t\tthis._maxSize !== undefined && values.length > this._maxSize\n\t\t\t\t? values.length - this._maxSize\n\t\t\t\t: 0;\n\t\tfor (let i = start; i < values.length; i++) {\n\t\t\tthis._rawAppend(values[i] as T);\n\t\t}\n\t\tthis._version += 1;\n\t}\n\n\tclear(): number {\n\t\tif (this._size === 0) return 0;\n\t\tconst n = this._size;\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.length = 0;\n\t\t} else {\n\t\t\t// Ring buffer: only null the currently-live window so the GC can\n\t\t\t// reclaim ref-typed `T`. Iterating the full capacity would be O(cap)\n\t\t\t// even when only a few slots are in use (P6). Non-live slots are\n\t\t\t// already `undefined` (pre-allocation state) or whatever a prior\n\t\t\t// trim/clear left — they hold no live refs.\n\t\t\tfor (let i = 0; i < n; i++) {\n\t\t\t\tthis._buf[(this._head + i) % this._maxSize] = undefined as unknown as T;\n\t\t\t}\n\t\t}\n\t\tthis._head = 0;\n\t\tthis._size = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\ttrimHead(n: number): number {\n\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\tthrow new RangeError(`trimHead: n must be a non-negative integer (got ${n})`);\n\t\t}\n\t\tif (n === 0 || this._size === 0) return 0;\n\t\tconst removed = Math.min(n, this._size);\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.splice(0, removed);\n\t\t} else {\n\t\t\t// Null trimmed slots so the GC can reclaim ref-typed T (P4 extension).\n\t\t\tfor (let i = 0; i < removed; i++) {\n\t\t\t\tthis._buf[(this._head + i) % this._maxSize] = undefined as unknown as T;\n\t\t\t}\n\t\t\tthis._head = (this._head + removed) % this._maxSize;\n\t\t}\n\t\tthis._size -= removed;\n\t\tthis._version += 1;\n\t\treturn removed;\n\t}\n\n\tslice(start: number, stop?: number): readonly T[] {\n\t\tif (!Number.isInteger(start) || start < 0) {\n\t\t\tthrow new RangeError(`slice: start must be a non-negative integer (got ${start})`);\n\t\t}\n\t\t// P4: reject negative `stop` explicitly so the bundle / backend / derived\n\t\t// contract stays consistent. Previously stop was silently clamped to 0,\n\t\t// producing `[]` in the backend but a different value under JS semantics\n\t\t// in the derived recomputation — a latent bug for negative inputs.\n\t\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\tthrow new RangeError(`slice: stop must be a non-negative integer or undefined (got ${stop})`);\n\t\t}\n\t\tconst end = stop === undefined ? this._size : Math.min(Math.max(stop, 0), this._size);\n\t\tconst s = Math.min(start, this._size);\n\t\tif (s >= end) return [];\n\t\tconst len = end - s;\n\t\tif (this._maxSize === undefined) {\n\t\t\treturn this._buf.slice(s, end);\n\t\t}\n\t\tconst out: T[] = new Array(len);\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tout[i] = this._buf[(this._head + s + i) % this._maxSize]!;\n\t\t}\n\t\treturn out;\n\t}\n\n\ttail(n: number): readonly T[] {\n\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\tthrow new RangeError(`tail: n must be a non-negative integer (got ${n})`);\n\t\t}\n\t\tif (n === 0 || this._size === 0) return [];\n\t\tconst take = Math.min(n, this._size);\n\t\treturn this.slice(this._size - take, this._size);\n\t}\n\n\ttoArray(): readonly T[] {\n\t\tif (this._maxSize === undefined) {\n\t\t\treturn [...this._buf];\n\t\t}\n\t\tconst out: T[] = new Array(this._size);\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tout[i] = this._buf[(this._head + i) % this._maxSize]!;\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** Internal append without version bump — used by `appendMany`. */\n\tprivate _rawAppend(value: T): void {\n\t\tif (this._maxSize === undefined) {\n\t\t\tthis._buf.push(value);\n\t\t\tthis._size = this._buf.length;\n\t\t\treturn;\n\t\t}\n\t\tif (this._size < this._maxSize) {\n\t\t\tthis._buf[(this._head + this._size) % this._maxSize] = value;\n\t\t\tthis._size += 1;\n\t\t} else {\n\t\t\t// Overwrite slot at head, advance head.\n\t\t\tthis._buf[this._head] = value;\n\t\t\tthis._head = (this._head + 1) % this._maxSize;\n\t\t}\n\t}\n}\n\n// ── Reactive wrapper ──────────────────────────────────────────────────────\n\n/** Installs a keepalive subscription; returns the disposer so callers can release it. */\nfunction keepaliveDerived(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n/** Default cap on the LRU view cache for `tail(n)` / `slice(start, stop?)`. D2(c). */\nconst DEFAULT_VIEW_CACHE_MAX = 64;\n\n/**\n * Creates an append-only reactive log with immutable array snapshots.\n *\n * @param initial - Optional seed entries (copied; pre-trimmed to `maxSize` if set).\n * @param options - `name`, `maxSize`, and optional pluggable `backend`.\n * @returns Bundle with `entries` (state node), `append`/`appendMany`/`clear`/`trimHead`,\n * `size` / `at`, and memoized derived views `tail(n)` / `slice(start, stop?)`.\n *\n * @remarks\n * **Backend:** The default {@link NativeLogBackend} uses a ring buffer when `maxSize`\n * is set (O(1) append + trim) and a flat array otherwise. For persistent/structural-\n * sharing semantics plug in a custom {@link LogBackend}.\n *\n * **`initial` + custom `backend` (F5):** When you supply `options.backend`, the\n * `initial` argument is IGNORED — seed the backend yourself before passing it in.\n * The `initial` seed only applies to the default `NativeLogBackend`.\n *\n * **Memoized views:** {@link ReactiveLogBundle.tail} and {@link ReactiveLogBundle.slice}\n * cache derived nodes per-argument. Repeat calls with the same `n` / `(start, stop)`\n * return the same node, bounding keepalive-subscription count to one per unique argument.\n *\n * @example\n * ```ts\n * import { reactiveLog } from \"@graphrefly/graphrefly-ts\";\n *\n * const lg = reactiveLog<number>([1, 2], { name: \"audit\", maxSize: 100 });\n * lg.append(3);\n * lg.entries.subscribe((msgs) => console.log(msgs));\n * const last5 = lg.tail(5); // derived node\n * const window = lg.slice(10, 20); // derived node\n * ```\n *\n * @category extra\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions<T> = {},\n): ReactiveLogBundle<T> {\n\tconst { name, maxSize, versioning, backend: userBackend } = options;\n\tconst backend: LogBackend<T> = userBackend ?? new NativeLogBackend<T>(initial, maxSize);\n\n\tconst entries = state<readonly T[]>(backend.toArray(), {\n\t\tname,\n\t\tdescribeKind: \"state\",\n\t\tequals: (a, b) => a === b,\n\t\t...(versioning != null ? { versioning } : {}),\n\t});\n\n\tfunction pushSnapshot(): void {\n\t\tconst snapshot = backend.toArray();\n\t\tbatch(() => {\n\t\t\tentries.down([[DIRTY]]);\n\t\t\tentries.down([[DATA, snapshot]]);\n\t\t});\n\t}\n\n\t// Memoization caches for derived views (D2(c)). Each cache is an LRU keyed by\n\t// the unique view argument, bounded by `DEFAULT_VIEW_CACHE_MAX`. On cache miss\n\t// past the cap, the least-recently-used entry is evicted and its keepalive\n\t// disposer is called so the underlying derived node can be GC'd. Callers can\n\t// also release views proactively via `disposeTail` / `disposeSlice` /\n\t// `disposeAllViews`. Iteration order of `Map` is insertion order, so moving\n\t// an entry to the end on hit is the LRU \"touch\".\n\ttype ViewEntry = { node: Node<readonly T[]>; dispose: () => void };\n\tconst tailCache = new Map<number, ViewEntry>();\n\tconst sliceCache = new Map<string, ViewEntry>();\n\n\tfunction sliceKey(start: number, stop?: number): string {\n\t\treturn `${start}:${stop === undefined ? \"END\" : stop}`;\n\t}\n\n\tfunction evictOldestIfFull<K>(cache: Map<K, ViewEntry>): void {\n\t\tif (cache.size < DEFAULT_VIEW_CACHE_MAX) return;\n\t\tconst first = cache.keys().next();\n\t\tif (first.done) return;\n\t\tconst oldest = cache.get(first.value);\n\t\tif (oldest !== undefined) oldest.dispose();\n\t\tcache.delete(first.value);\n\t}\n\n\t/**\n\t * D4(a): try/finally defense-in-depth — if a custom backend op throws\n\t * mid-mutation, surface the partial state via pushSnapshot so subscribers\n\t * don't see a stale cache. Matches the pattern in reactive-map and\n\t * reactive-index. Native ops are atomic by contract; this only matters\n\t * for user-supplied backends.\n\t */\n\tfunction wrapMutation<R>(op: () => R): R {\n\t\tconst prev = backend.version;\n\t\ttry {\n\t\t\treturn op();\n\t\t} finally {\n\t\t\tif (backend.version !== prev) pushSnapshot();\n\t\t}\n\t}\n\n\treturn {\n\t\tentries,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\twrapMutation(() => backend.append(value));\n\t\t},\n\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\twrapMutation(() => backend.appendMany(values));\n\t\t},\n\n\t\tclear(): void {\n\t\t\twrapMutation(() => backend.clear());\n\t\t\t// NOTE: cached tail/slice derived views are intentionally NOT\n\t\t\t// disposed here. Disposing would kill the keepalive on any node\n\t\t\t// a caller already holds externally, silently stopping their\n\t\t\t// updates. The derived nodes recompute from the new empty\n\t\t\t// snapshot when `entries` emits post-clear, so `.cache` on an\n\t\t\t// outstanding view settles to `[]` without any manual\n\t\t\t// reset. (Initial snapshots, if inspected before the next wave,\n\t\t\t// may be stale — callers who care can `disposeTail` / `slice`\n\t\t\t// explicitly.)\n\t\t},\n\n\t\ttrimHead(n: number): void {\n\t\t\twrapMutation(() => backend.trimHead(n));\n\t\t},\n\n\t\ttail(n: number): Node<readonly T[]> {\n\t\t\tif (!Number.isInteger(n) || n < 0) {\n\t\t\t\tthrow new RangeError(`tail: n must be a non-negative integer (got ${n})`);\n\t\t\t}\n\t\t\tconst hit = tailCache.get(n);\n\t\t\tif (hit !== undefined) {\n\t\t\t\t// LRU touch: move to end of insertion order.\n\t\t\t\ttailCache.delete(n);\n\t\t\t\ttailCache.set(n, hit);\n\t\t\t\treturn hit.node;\n\t\t\t}\n\t\t\tevictOldestIfFull(tailCache);\n\t\t\tconst node_ = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = s as readonly T[];\n\t\t\t\t\tif (n === 0 || list.length === 0) return [];\n\t\t\t\t\treturn list.slice(Math.max(0, list.length - n));\n\t\t\t\t},\n\t\t\t\t{ initial: backend.tail(n), describeKind: \"derived\" },\n\t\t\t);\n\t\t\tconst dispose = keepaliveDerived(node_);\n\t\t\ttailCache.set(n, { node: node_, dispose });\n\t\t\treturn node_;\n\t\t},\n\n\t\tslice(start: number, stop?: number): Node<readonly T[]> {\n\t\t\tif (!Number.isInteger(start) || start < 0) {\n\t\t\t\tthrow new RangeError(`slice: start must be a non-negative integer (got ${start})`);\n\t\t\t}\n\t\t\t// P4: reject negative stop explicitly to keep bundle / backend / derived\n\t\t\t// consistent (JS `Array.prototype.slice` supports negative stop, but the\n\t\t\t// backend can't cheaply honor it without scanning length, so we disallow).\n\t\t\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\t\tthrow new RangeError(\n\t\t\t\t\t`slice: stop must be a non-negative integer or undefined (got ${stop})`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = sliceKey(start, stop);\n\t\t\tconst hit = sliceCache.get(key);\n\t\t\tif (hit !== undefined) {\n\t\t\t\tsliceCache.delete(key);\n\t\t\t\tsliceCache.set(key, hit);\n\t\t\t\treturn hit.node;\n\t\t\t}\n\t\t\tevictOldestIfFull(sliceCache);\n\t\t\tconst node_ = derived(\n\t\t\t\t[entries],\n\t\t\t\t([s]) => {\n\t\t\t\t\tconst list = s as readonly T[];\n\t\t\t\t\treturn stop === undefined ? list.slice(start) : list.slice(start, stop);\n\t\t\t\t},\n\t\t\t\t{ initial: backend.slice(start, stop), describeKind: \"derived\" },\n\t\t\t);\n\t\t\tconst dispose = keepaliveDerived(node_);\n\t\t\tsliceCache.set(key, { node: node_, dispose });\n\t\t\treturn node_;\n\t\t},\n\n\t\tdisposeTail(n: number): boolean {\n\t\t\tconst hit = tailCache.get(n);\n\t\t\tif (hit === undefined) return false;\n\t\t\thit.dispose();\n\t\t\ttailCache.delete(n);\n\t\t\treturn true;\n\t\t},\n\n\t\tdisposeSlice(start: number, stop?: number): boolean {\n\t\t\tconst key = sliceKey(start, stop);\n\t\t\tconst hit = sliceCache.get(key);\n\t\t\tif (hit === undefined) return false;\n\t\t\thit.dispose();\n\t\t\tsliceCache.delete(key);\n\t\t\treturn true;\n\t\t},\n\n\t\tdisposeAllViews(): void {\n\t\t\tfor (const entry of tailCache.values()) entry.dispose();\n\t\t\ttailCache.clear();\n\t\t\tfor (const entry of sliceCache.values()) entry.dispose();\n\t\t\tsliceCache.clear();\n\t\t},\n\n\t\tdispose(): void {\n\t\t\t// D6(a): currently identical to disposeAllViews. Exposed as a\n\t\t\t// uniform lifecycle API across all 4 reactive data structures.\n\t\t\tfor (const entry of tailCache.values()) entry.dispose();\n\t\t\ttailCache.clear();\n\t\t\tfor (const entry of sliceCache.values()) entry.dispose();\n\t\t\tsliceCache.clear();\n\t\t},\n\t};\n}\n","/**\n * Approximate in-memory size estimation for arbitrary JS values.\n *\n * Iterative walk with cycle detection via `WeakSet`. V8-tuned overhead\n * heuristics. Not exact — approximate enough for profiling and hotspot\n * detection.\n *\n * Use cases: `graphProfile` (per-node value size), reactive data structure\n * memory audits, heuristic cache admission.\n *\n * @module\n */\n\n/** Approximate per-type overhead in bytes (V8 heuristics). */\nexport const OVERHEAD = {\n\tobject: 56,\n\tarray: 64,\n\tstring: 40, // header; content added separately\n\tnumber: 8,\n\tboolean: 4,\n\tnull: 0,\n\tundefined: 0,\n\tsymbol: 40,\n\tbigint: 16, // base; scales with digit count (see `_bigintSize`)\n\tfunction: 120,\n\tmap: 72,\n\tset: 72,\n\tmapEntry: 40,\n\tsetEntry: 24,\n\tdate: 24,\n\tregexp: 48,\n\terror: 64,\n\turl: 80,\n\tpromise: 48,\n\tweakmap: 40,\n\tweakset: 40,\n} as const;\n\n/**\n * Optional user hook. Declare a `sizeof` symbol key on any object to return\n * a precomputed size (in bytes); the walker will honor it and skip recursion.\n *\n * @example\n * ```ts\n * const SIZEOF = Symbol.for(\"sizeof\");\n * class MyCache { [SIZEOF]() { return this.bytes; } }\n * ```\n */\nexport const SIZEOF_SYMBOL = Symbol.for(\"sizeof\");\n\n/**\n * Estimate the approximate retained memory (in bytes) of a JS value.\n *\n * Handles primitives, plain objects, arrays, Maps, Sets, ArrayBuffers +\n * TypedArrays (shared-buffer dedup), Date, RegExp, Error, URL, Promise,\n * WeakMap, WeakSet, nested combinations. Cyclic refs are counted once.\n *\n * @param value - The value to measure.\n * @returns Approximate size in bytes.\n */\nexport function sizeof(value: unknown): number {\n\tconst seen = new WeakSet<object>();\n\tconst seenBuffers = new WeakSet<ArrayBufferLike>();\n\t// Iterative walk via explicit stack — avoids blowing the call stack on\n\t// deeply nested values (linked lists, AST nodes, deep JSON).\n\tconst stack: unknown[] = [value];\n\tlet total = 0;\n\twhile (stack.length > 0) {\n\t\tconst v = stack.pop();\n\t\ttotal += _shallowSize(v, seen, seenBuffers, stack);\n\t}\n\treturn total;\n}\n\n/** Shallow size of `v`; pushes children onto `stack` for iterative traversal. */\nfunction _shallowSize(\n\tvalue: unknown,\n\tseen: WeakSet<object>,\n\tseenBuffers: WeakSet<ArrayBufferLike>,\n\tstack: unknown[],\n): number {\n\tif (value === null || value === undefined) return 0;\n\n\tconst t = typeof value;\n\tswitch (t) {\n\t\tcase \"number\":\n\t\t\treturn OVERHEAD.number;\n\t\tcase \"boolean\":\n\t\t\treturn OVERHEAD.boolean;\n\t\tcase \"string\":\n\t\t\treturn OVERHEAD.string + (value as string).length * 2;\n\t\tcase \"bigint\":\n\t\t\treturn OVERHEAD.bigint + _bigintSize(value as bigint);\n\t\tcase \"symbol\":\n\t\t\treturn OVERHEAD.symbol;\n\t\tcase \"function\":\n\t\t\tif (seen.has(value as object)) return 0;\n\t\t\tseen.add(value as object);\n\t\t\treturn OVERHEAD.function;\n\t\tcase \"undefined\":\n\t\t\treturn 0;\n\t}\n\n\tconst obj = value as object;\n\tif (seen.has(obj)) return 0;\n\tseen.add(obj);\n\n\t// User-supplied size hook wins — `Symbol.for(\"sizeof\")` method on the\n\t// object returns an exact byte count and we skip recursion.\n\tconst hook = (obj as Record<symbol, unknown>)[SIZEOF_SYMBOL];\n\tif (typeof hook === \"function\") {\n\t\ttry {\n\t\t\tconst reported = (hook as () => unknown).call(obj);\n\t\t\tif (typeof reported === \"number\" && Number.isFinite(reported)) return reported;\n\t\t} catch {\n\t\t\t/* ignore — fall through to default estimator */\n\t\t}\n\t}\n\n\tif (obj instanceof Date) return OVERHEAD.date;\n\tif (obj instanceof RegExp) return OVERHEAD.regexp + obj.source.length * 2;\n\tif (obj instanceof Error) {\n\t\tconst m = obj.message ? obj.message.length * 2 : 0;\n\t\tconst s = obj.stack ? obj.stack.length * 2 : 0;\n\t\treturn OVERHEAD.error + m + s;\n\t}\n\tif (typeof URL !== \"undefined\" && obj instanceof URL) {\n\t\treturn OVERHEAD.url + obj.href.length * 2;\n\t}\n\tif (typeof Promise !== \"undefined\" && obj instanceof Promise) {\n\t\treturn OVERHEAD.promise;\n\t}\n\tif (obj instanceof WeakMap) return OVERHEAD.weakmap;\n\tif (obj instanceof WeakSet) return OVERHEAD.weakset;\n\n\tif (obj instanceof Map) {\n\t\tlet size = OVERHEAD.map;\n\t\tfor (const [k, v] of obj) {\n\t\t\tsize += OVERHEAD.mapEntry;\n\t\t\tstack.push(k);\n\t\t\tstack.push(v);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (obj instanceof Set) {\n\t\tlet size = OVERHEAD.set;\n\t\tfor (const v of obj) {\n\t\t\tsize += OVERHEAD.setEntry;\n\t\t\tstack.push(v);\n\t\t}\n\t\treturn size;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\tconst size = OVERHEAD.array + obj.length * 8;\n\t\tfor (const item of obj) stack.push(item);\n\t\treturn size;\n\t}\n\n\t// ArrayBuffer — count once per buffer (multi-view dedup via `seenBuffers`).\n\tif (obj instanceof ArrayBuffer) {\n\t\tif (seenBuffers.has(obj)) return 0;\n\t\tseenBuffers.add(obj);\n\t\treturn obj.byteLength;\n\t}\n\tif (ArrayBuffer.isView(obj)) {\n\t\tconst view = obj as { byteLength: number; buffer: ArrayBufferLike };\n\t\tif (seenBuffers.has(view.buffer)) return 48; // view header only\n\t\tseenBuffers.add(view.buffer);\n\t\t// Charge the full underlying buffer — a small view over a large\n\t\t// buffer still retains all of it. Add the view header on top.\n\t\treturn view.buffer.byteLength + 48;\n\t}\n\n\t// Plain object — sum key overhead + recurse into values.\n\tlet size = OVERHEAD.object;\n\tconst keys = Object.keys(obj);\n\tfor (const key of keys) {\n\t\tsize += OVERHEAD.string + key.length * 2;\n\t\ttry {\n\t\t\tstack.push((obj as Record<string, unknown>)[key]);\n\t\t} catch {\n\t\t\t/* getter throw — skip this key */\n\t\t}\n\t}\n\treturn size;\n}\n\n/** BigInt digit-count-based sizing: each ~32-bit limb ≈ 8 bytes. */\nfunction _bigintSize(n: bigint): number {\n\tconst abs = n < 0n ? -n : n;\n\tif (abs === 0n) return 0;\n\tconst bits = abs.toString(2).length;\n\treturn Math.ceil(bits / 32) * 8;\n}\n","/**\n * Causal walkback over a {@link Graph.describe} snapshot (roadmap §9.2).\n *\n * `explainPath` finds the shortest dep-chain from `from` to `to` and returns a\n * step-by-step {@link CausalChain} enriched with each node's current value,\n * status, last-mutation actor, and any `graph.trace()` reasoning annotation.\n *\n * Pure function over the snapshot — peer to {@link reachable}. The\n * {@link Graph.explain} instance method auto-passes `describe({detail:\"standard\"})`\n * plus runtime annotations and `lastMutation` so callers get rich output by\n * default.\n *\n * @module\n */\nimport type { Actor } from \"../core/actor.js\";\nimport type { DescribeNodeOutput } from \"../core/meta.js\";\nimport type { GraphDescribeOutput } from \"./graph.js\";\n\n/** One node along the causal chain returned by {@link explainPath}. */\nexport interface CausalStep {\n\t/** Qualified node path. */\n\tpath: string;\n\t/** Node kind (`state` / `derived` / `producer` / etc.). */\n\ttype: DescribeNodeOutput[\"type\"];\n\t/** Status as of the source snapshot. */\n\tstatus?: DescribeNodeOutput[\"status\"];\n\t/** Cached value at snapshot time (omitted when describe didn't include it). */\n\tvalue?: unknown;\n\t/** Hop distance from `from` (0 = `from`, N = `to`). */\n\thop: number;\n\t/** Reason annotation set via `graph.trace(path, reason)`, when present. */\n\treason?: string;\n\t/** Most recent guarded mutation, when known. */\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/** V0/V1 versioning info, when present. */\n\tv?: DescribeNodeOutput[\"v\"];\n\t/** Index of this step in the next step's `deps` (i.e. which dep slot fed forward). */\n\tdep_index?: number;\n\t/**\n\t * All dep slots when the same dep appears multiple times in the next\n\t * step's `deps`. Present only for multi-edge connections; `dep_index`\n\t * always equals `dep_indices[0]` when set.\n\t */\n\tdep_indices?: number[];\n}\n\n/** Outcome of an {@link explainPath} call. */\nexport interface CausalChain {\n\tfrom: string;\n\tto: string;\n\t/** True when a path was found. */\n\tfound: boolean;\n\t/** Why the chain may be empty/incomplete. `\"ok\"` when `found` is true. */\n\treason: \"ok\" | \"no-such-from\" | \"no-such-to\" | \"no-path\" | \"max-depth-exceeded\";\n\t/** Ordered steps — first element is `from`, last is `to`. Empty when `!found`. */\n\tsteps: readonly CausalStep[];\n\t/** Pretty multi-line rendering. Always present, even on failure (one-line message). */\n\ttext: string;\n\t/** JSON-serializable form (drops `text` to keep payloads compact). */\n\ttoJSON(): {\n\t\tfrom: string;\n\t\tto: string;\n\t\tfound: boolean;\n\t\treason: CausalChain[\"reason\"];\n\t\tsteps: readonly CausalStep[];\n\t};\n}\n\n/** Options for {@link explainPath}. */\nexport interface ExplainPathOptions {\n\t/** Maximum hop distance to search. Omit for unbounded. */\n\tmaxDepth?: number;\n\t/** Per-path reasoning annotations (typically `graph.trace()` output map). */\n\tannotations?: ReadonlyMap<string, string>;\n\t/** Per-path `lastMutation` map (overrides describe-derived values). */\n\tlastMutations?: ReadonlyMap<string, Readonly<{ actor: Actor; timestamp_ns: number }>>;\n\t/**\n\t * When `true` and `from === to`, search for a non-trivial cycle (path\n\t * back to `from` through ≥1 other node) instead of returning the trivial\n\t * single-step. Use when debugging feedback loops (COMPOSITION-GUIDE §7).\n\t * If no real cycle exists, falls back to the trivial single-step. Default\n\t * `false` — backward-compatible.\n\t */\n\tfindCycle?: boolean;\n}\n\n/**\n * Walks backward from `to` through `deps` to find the shortest path to `from`,\n * then assembles an ordered, enriched {@link CausalChain}.\n *\n * @param described - `graph.describe()` output (any detail level; richer detail → richer steps).\n * @param from - Path of the upstream node (the cause).\n * @param to - Path of the downstream node (the effect).\n * @param opts - Optional `maxDepth` and per-path annotation overlays.\n * @returns A {@link CausalChain} — `found:false` with a `reason` when no path exists.\n *\n * @example\n * ```ts\n * import { explainPath } from \"@graphrefly/graphrefly-ts\";\n * const chain = explainPath(graph.describe({ detail: \"standard\" }), \"input\", \"result\");\n * console.log(chain.text);\n * ```\n */\nexport function explainPath(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tto: string,\n\topts: ExplainPathOptions = {},\n): CausalChain {\n\tconst fromExists = from in described.nodes;\n\tconst toExists = to in described.nodes;\n\tif (!fromExists) return makeFailure(from, to, \"no-such-from\");\n\tif (!toExists) return makeFailure(from, to, \"no-such-to\");\n\n\tconst maxDepth = opts.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`explainPath: maxDepth must be an integer >= 0`);\n\t}\n\n\tif (from === to) {\n\t\t// findCycle: search for shortest non-trivial cycle (a path of ≥2 hops\n\t\t// back to `from` through other nodes). Falls back to trivial single\n\t\t// step if no real cycle exists.\n\t\tif (opts.findCycle === true) {\n\t\t\tconst cycle = findShortestCycle(described, from, opts);\n\t\t\tif (cycle != null) return cycle;\n\t\t}\n\t\tconst step = buildStep(from, described.nodes[from]!, 0, opts);\n\t\treturn makeSuccess(from, to, [step]);\n\t}\n\n\tif (maxDepth === 0) return makeFailure(from, to, \"no-path\");\n\n\tconst result = bfsShortestPath(described, from, to, maxDepth);\n\tif (!result.found) {\n\t\treturn makeFailure(from, to, result.truncated ? \"max-depth-exceeded\" : \"no-path\");\n\t}\n\treturn makeSuccess(from, to, materializeSteps(described, result.pathOrder, opts));\n}\n\n// ── BFS helpers ──────────────────────────────────────────────────────────\n\ntype StepPlan = { path: string; depIndices?: number[] };\n\ninterface BfsResult {\n\tfound: boolean;\n\tpathOrder: StepPlan[];\n\ttruncated: boolean;\n}\n\n/**\n * Backward BFS from `to` to `from`. Returns the ordered chain `from → … → to`\n * with `depIndices` annotating each non-final step (which slot(s) in the next\n * step's `deps` list connect us — typically a single index, but multi-edges\n * preserve every matching slot).\n */\nfunction bfsShortestPath(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tto: string,\n\tmaxDepth: number | undefined,\n): BfsResult {\n\ttype Pred = { from: string; depIndices: number[] };\n\tconst pred = new Map<string, Pred>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: to, depth: 0 }];\n\tconst visited = new Set<string>([to]);\n\tlet head = 0;\n\tlet truncated = false;\n\n\twhile (head < queue.length) {\n\t\tconst cur = queue[head++]!;\n\t\tif (cur.path === from) break;\n\t\tif (maxDepth != null && cur.depth >= maxDepth) {\n\t\t\tconst node = described.nodes[cur.path];\n\t\t\tif (node?.deps && node.deps.length > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = described.nodes[cur.path];\n\t\tif (node == null) continue;\n\t\tconst deps = node.deps ?? [];\n\t\t// Aggregate all dep-slot indices for each unique dep — preserves\n\t\t// multi-edge information when the same dep appears twice.\n\t\tconst slots = new Map<string, number[]>();\n\t\tfor (let i = 0; i < deps.length; i++) {\n\t\t\tconst dep = deps[i]!;\n\t\t\tif (!dep) continue;\n\t\t\tlet arr = slots.get(dep);\n\t\t\tif (arr == null) {\n\t\t\t\tarr = [];\n\t\t\t\tslots.set(dep, arr);\n\t\t\t}\n\t\t\tarr.push(i);\n\t\t}\n\t\tfor (const [dep, indices] of slots) {\n\t\t\tif (visited.has(dep)) continue;\n\t\t\tvisited.add(dep);\n\t\t\tpred.set(dep, { from: cur.path, depIndices: indices });\n\t\t\tqueue.push({ path: dep, depth: cur.depth + 1 });\n\t\t}\n\t}\n\n\tif (!pred.has(from)) {\n\t\treturn { found: false, pathOrder: [], truncated };\n\t}\n\n\t// Reconstruct: walk pred from `from` forward to `to`.\n\tconst pathOrder: StepPlan[] = [{ path: from }];\n\tlet cursor = from;\n\twhile (cursor !== to) {\n\t\tconst p = pred.get(cursor);\n\t\tif (p == null) return { found: false, pathOrder: [], truncated: false };\n\t\t// Attach depIndices to the step we just came from (cursor) — dep_index\n\t\t// names \"which slot in the NEXT step's deps am I\".\n\t\tpathOrder[pathOrder.length - 1]!.depIndices = p.depIndices;\n\t\tpathOrder.push({ path: p.from });\n\t\tcursor = p.from;\n\t}\n\treturn { found: true, pathOrder, truncated: false };\n}\n\n/**\n * Find the shortest cycle starting and ending at `start`, excluding the\n * trivial 0-hop \"self-step\" case. Returns a {@link CausalChain} success when\n * a cycle of length ≥2 exists, otherwise `null`. Handles direct self-loops\n * (`start ∈ deps(start)`) and multi-hop cycles uniformly.\n */\nfunction findShortestCycle(\n\tdescribed: GraphDescribeOutput,\n\tstart: string,\n\topts: ExplainPathOptions,\n): CausalChain | null {\n\tconst startNode = described.nodes[start];\n\tif (startNode == null) return null;\n\tconst startDeps = startNode.deps ?? [];\n\n\t// Direct self-loop: start ∈ deps(start). Return [start, start] with\n\t// dep_index pointing at the matching slot(s).\n\tconst selfSlots: number[] = [];\n\tfor (let i = 0; i < startDeps.length; i++) if (startDeps[i] === start) selfSlots.push(i);\n\tif (selfSlots.length > 0) {\n\t\tconst step0 = buildStep(start, startNode, 0, opts);\n\t\tstep0.dep_index = selfSlots[0]!;\n\t\tconst step1 = buildStep(start, startNode, 1, opts);\n\t\treturn makeSuccess(start, start, [step0, step1]);\n\t}\n\n\t// Multi-hop cycle: BFS from each direct dep of start back to start.\n\tlet best: BfsResult | null = null;\n\tfor (let i = 0; i < startDeps.length; i++) {\n\t\tconst dep = startDeps[i]!;\n\t\tif (!dep || dep === start) continue;\n\t\tconst sub = bfsShortestPath(described, dep, start, opts.maxDepth);\n\t\tif (!sub.found) continue;\n\t\tif (best == null || sub.pathOrder.length < best.pathOrder.length) {\n\t\t\tbest = sub;\n\t\t\t// Prepend `start` so the cycle reads: start → dep → … → start.\n\t\t\t// The slot index from start to its first dep needs preserving.\n\t\t\tbest = {\n\t\t\t\tfound: true,\n\t\t\t\tpathOrder: [{ path: start, depIndices: [i] }, ...sub.pathOrder],\n\t\t\t\ttruncated: false,\n\t\t\t};\n\t\t}\n\t}\n\tif (best == null) return null;\n\treturn makeSuccess(start, start, materializeSteps(described, best.pathOrder, opts));\n}\n\nfunction materializeSteps(\n\tdescribed: GraphDescribeOutput,\n\tpathOrder: readonly StepPlan[],\n\topts: ExplainPathOptions,\n): CausalStep[] {\n\treturn pathOrder.map((entry, i) => {\n\t\tconst node = described.nodes[entry.path]!;\n\t\tconst step = buildStep(entry.path, node, i, opts);\n\t\tif (entry.depIndices != null && entry.depIndices.length > 0) {\n\t\t\tstep.dep_index = entry.depIndices[0]!;\n\t\t\tif (entry.depIndices.length > 1) step.dep_indices = [...entry.depIndices];\n\t\t}\n\t\treturn step;\n\t});\n}\n\nfunction buildStep(\n\tpath: string,\n\tnode: DescribeNodeOutput,\n\thop: number,\n\topts: ExplainPathOptions,\n): CausalStep {\n\tconst step: CausalStep = {\n\t\tpath,\n\t\ttype: node.type,\n\t\thop,\n\t};\n\tif (node.status !== undefined) step.status = node.status;\n\tif (\"value\" in node) step.value = node.value;\n\tif (node.v != null) step.v = node.v;\n\tconst annotation = opts.annotations?.get(path) ?? node.reason;\n\tif (annotation != null) step.reason = annotation;\n\tconst lastMutation = opts.lastMutations?.get(path) ?? node.lastMutation;\n\tif (lastMutation != null) step.lastMutation = lastMutation;\n\treturn step;\n}\n\nfunction makeSuccess(from: string, to: string, steps: readonly CausalStep[]): CausalChain {\n\treturn finalize(from, to, true, \"ok\", steps);\n}\n\nfunction makeFailure(from: string, to: string, reason: CausalChain[\"reason\"]): CausalChain {\n\treturn finalize(from, to, false, reason, []);\n}\n\nfunction finalize(\n\tfrom: string,\n\tto: string,\n\tfound: boolean,\n\treason: CausalChain[\"reason\"],\n\tsteps: readonly CausalStep[],\n): CausalChain {\n\tconst text = renderChain(from, to, found, reason, steps);\n\treturn {\n\t\tfrom,\n\t\tto,\n\t\tfound,\n\t\treason,\n\t\tsteps,\n\t\ttext,\n\t\ttoJSON() {\n\t\t\treturn { from, to, found, reason, steps };\n\t\t},\n\t};\n}\n\nfunction renderChain(\n\tfrom: string,\n\tto: string,\n\tfound: boolean,\n\treason: CausalChain[\"reason\"],\n\tsteps: readonly CausalStep[],\n): string {\n\tif (!found) {\n\t\tswitch (reason) {\n\t\t\tcase \"no-such-from\":\n\t\t\t\treturn `explainPath: no node named \"${from}\"`;\n\t\t\tcase \"no-such-to\":\n\t\t\t\treturn `explainPath: no node named \"${to}\"`;\n\t\t\tcase \"max-depth-exceeded\":\n\t\t\t\treturn `explainPath: no path from \"${from}\" to \"${to}\" within maxDepth`;\n\t\t\tdefault:\n\t\t\t\treturn `explainPath: no path from \"${from}\" to \"${to}\"`;\n\t\t}\n\t}\n\tconst lines: string[] = [`Causal path: ${from} → ${to} (${steps.length} step(s))`];\n\tfor (const step of steps) {\n\t\tconst arrow = step.hop === 0 ? \"·\" : \"↓\";\n\t\tconst head = ` ${arrow} ${step.path} (${step.type}${step.status ? `/${step.status}` : \"\"})`;\n\t\tlines.push(head);\n\t\tif (\"value\" in step) {\n\t\t\tlines.push(` value: ${formatValue(step.value)}`);\n\t\t}\n\t\tif (step.reason != null) {\n\t\t\tlines.push(` reason: ${step.reason}`);\n\t\t}\n\t\tif (step.lastMutation != null) {\n\t\t\tconst a = step.lastMutation.actor;\n\t\t\tlines.push(` actor: ${a.type}${a.id ? `:${a.id}` : \"\"}`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatValue(v: unknown): string {\n\tif (v === undefined) return \"<sentinel>\";\n\tif (v === null) return \"null\";\n\tif (typeof v === \"string\") return JSON.stringify(v);\n\tif (typeof v === \"number\" || typeof v === \"boolean\" || typeof v === \"bigint\") return String(v);\n\ttry {\n\t\tconst s = JSON.stringify(v);\n\t\treturn s.length > 80 ? `${s.slice(0, 77)}...` : s;\n\t} catch {\n\t\treturn String(v);\n\t}\n}\n","import type { Actor } from \"./actor.js\";\nimport { accessHintForGuard } from \"./guard.js\";\nimport { type Node, type NodeDescribeKind, NodeImpl } from \"./node.js\";\n\n/**\n * JSON-shaped slice of a node for `Graph.describe()`\n * (GRAPHREFLY-SPEC §3.6, Appendix B).\n */\nexport type DescribeNodeOutput = {\n\ttype: NodeDescribeKind;\n\tstatus?: Node[\"status\"];\n\tdeps: string[];\n\tmeta?: Record<string, unknown>;\n\tname?: string;\n\tvalue?: unknown;\n\t/** True when the node is in `\"sentinel\"` state (no value ever). */\n\tsentinel?: boolean;\n\tv?: { id: string; version: number; cid?: string; prev?: string | null };\n\tguard?: string;\n\tlastMutation?: Readonly<{ actor: Actor; timestamp_ns: number }>;\n\t/**\n\t * Latest reason annotation attached via `graph.trace(path, reason)`,\n\t * when present. Populated by `Graph.describe` only — `describeNode`\n\t * has no graph context.\n\t */\n\treason?: string;\n};\n\n/** Detail level for progressive disclosure (Phase 3.3b). */\nexport type DescribeDetail = \"minimal\" | \"standard\" | \"full\";\n\n/** Valid field names for `describe({ fields: [...] })`. */\nexport type DescribeField =\n\t| \"type\"\n\t| \"status\"\n\t| \"value\"\n\t| \"deps\"\n\t| \"meta\"\n\t| \"v\"\n\t| \"guard\"\n\t| \"lastMutation\"\n\t| `meta.${string}`;\n\n/** Resolve which fields to include based on detail level or explicit field list. */\nexport function resolveDescribeFields(\n\tdetail?: DescribeDetail,\n\tfields?: readonly DescribeField[],\n): Set<string> | null {\n\tif (fields != null && fields.length > 0) return new Set(fields);\n\tswitch (detail) {\n\t\tcase \"standard\":\n\t\t\treturn new Set([\"type\", \"status\", \"value\", \"deps\", \"meta\", \"v\"]);\n\t\tcase \"full\":\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn new Set([\"type\", \"deps\"]);\n\t}\n}\n\nfunction inferDescribeType(n: NodeImpl): NodeDescribeKind {\n\tif (n._describeKind != null) return n._describeKind;\n\tconst hasDeps = n._deps.length > 0;\n\tif (!hasDeps) return n._fn != null ? \"producer\" : \"state\";\n\t// With deps: derived (passthrough falls under derived, no fn → derived shape).\n\treturn \"derived\";\n}\n\n/**\n * Reads the current cached value of every companion meta field on a node,\n * suitable for merging into `describe()`-style JSON.\n *\n * Values come from {@link Node.cache}, which returns the last settled cache.\n * If a meta field is in `\"dirty\"` status (DIRTY received, DATA pending), the\n * snapshot contains the *previous* value — check `node.meta[key].status`\n * when freshness matters.\n */\nexport function metaSnapshot(node: Node): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(node.meta)) {\n\t\ttry {\n\t\t\tout[key] = child.cache;\n\t\t} catch {\n\t\t\t/* omit key — describe tooling still gets other fields */\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Builds a single-node slice of `Graph.describe()` JSON (structure + `meta`\n * snapshot). Parity with `graphrefly-py` `describe_node`.\n */\nexport function describeNode(node: Node, includeFields?: Set<string> | null): DescribeNodeOutput {\n\tconst all = includeFields == null;\n\tconst metaKeys: string[] | null =\n\t\t!all && includeFields != null\n\t\t\t? [...includeFields].filter((f) => f.startsWith(\"meta.\")).map((f) => f.slice(5))\n\t\t\t: null;\n\tconst wantsMeta = all || includeFields!.has(\"meta\") || (metaKeys != null && metaKeys.length > 0);\n\n\tlet type: NodeDescribeKind = \"state\";\n\tlet deps: string[] = [];\n\n\tif (node instanceof NodeImpl) {\n\t\ttype = inferDescribeType(node);\n\t\tdeps = node._deps.map((d) => d.node.name ?? \"\");\n\t}\n\n\tconst out: DescribeNodeOutput = { type, deps };\n\n\tif (all || includeFields!.has(\"status\")) {\n\t\tout.status = node.status;\n\t}\n\n\tconst guard = node instanceof NodeImpl ? node._guard : undefined;\n\n\tif (wantsMeta) {\n\t\tconst rawMeta: Record<string, unknown> = { ...metaSnapshot(node) };\n\t\tif (guard != null && rawMeta.access === undefined) {\n\t\t\trawMeta.access = accessHintForGuard(guard);\n\t\t}\n\t\tif (metaKeys != null && metaKeys.length > 0 && !includeFields!.has(\"meta\")) {\n\t\t\tconst filtered: Record<string, unknown> = {};\n\t\t\tfor (const k of metaKeys) {\n\t\t\t\tif (k in rawMeta) filtered[k] = rawMeta[k];\n\t\t\t}\n\t\t\tout.meta = filtered;\n\t\t} else {\n\t\t\tout.meta = rawMeta;\n\t\t}\n\t}\n\n\tif (node.name != null) {\n\t\tout.name = node.name;\n\t}\n\n\tif (all || includeFields!.has(\"value\")) {\n\t\tif (node.status === \"sentinel\") out.sentinel = true;\n\t\ttry {\n\t\t\tout.value = node.cache;\n\t\t} catch {\n\t\t\t/* omit value */\n\t\t}\n\t}\n\n\tif ((all || includeFields!.has(\"v\")) && node.v != null) {\n\t\tconst vInfo: NonNullable<DescribeNodeOutput[\"v\"]> = {\n\t\t\tid: node.v.id,\n\t\t\tversion: node.v.version,\n\t\t};\n\t\tif (\"cid\" in node.v) {\n\t\t\tvInfo.cid = (node.v as { cid: string }).cid;\n\t\t\tvInfo.prev = (node.v as { prev: string | null }).prev;\n\t\t}\n\t\tout.v = vInfo;\n\t}\n\n\tif (all || includeFields!.has(\"guard\")) {\n\t\tif (guard != null) out.guard = accessHintForGuard(guard);\n\t}\n\n\tif (all || includeFields!.has(\"lastMutation\")) {\n\t\tif (node.lastMutation != null) out.lastMutation = node.lastMutation;\n\t}\n\n\treturn out;\n}\n","/**\n * Creates a resettable deadline timer for internal timeout, retry, and rate-limiting use.\n *\n * @remarks **Centralised primitive:** wraps `setTimeout`/`clearTimeout` with a generation guard\n * so that stale callbacks never fire after `cancel()` or a new `start()`.\n *\n * @remarks **Spec §5.10 exception:** resilience operators (`timeout`, `retry`, `rateLimiter`)\n * need raw timers — `fromTimer` creates a new Node per reset, which is too heavy here.\n * Lives in `src/extra/` (not `src/core/`) because it is a documented escape hatch from\n * the protocol-pure core layer.\n *\n * @example\n * ```ts\n * import { ResettableTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * const timer = new ResettableTimer();\n * timer.start(1000, () => console.log(\"fired\"));\n * timer.cancel(); // cancels before firing\n * timer.start(500, () => console.log(\"new deadline\"));\n * console.log(timer.pending); // true\n * ```\n *\n * @category extra\n */\nexport class ResettableTimer {\n\tprivate _timer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _gen = 0;\n\n\t/** Schedule callback after delayMs. Cancels any pending timer. */\n\tstart(delayMs: number, callback: () => void): void {\n\t\tthis.cancel();\n\t\tthis._gen += 1;\n\t\tconst gen = this._gen;\n\t\tthis._timer = setTimeout(() => {\n\t\t\tthis._timer = undefined;\n\t\t\tif (gen !== this._gen) return;\n\t\t\tcallback();\n\t\t}, delayMs);\n\t}\n\n\t/** Cancel the pending timer (if any). */\n\tcancel(): void {\n\t\tif (this._timer !== undefined) {\n\t\t\tclearTimeout(this._timer);\n\t\t\tthis._timer = undefined;\n\t\t}\n\t}\n\n\t/** Whether a timer is currently pending. */\n\tget pending(): boolean {\n\t\treturn this._timer !== undefined;\n\t}\n}\n","/**\n * Fixed-capacity ring buffer — O(1) push and drop-oldest eviction.\n *\n * Used by `Graph._traceRing` (reasoning trace), `reactiveLog` (append-only\n * log backend), and `reactiveSink` (drop-oldest backpressure buffer). One\n * implementation, three use sites.\n *\n * @module\n * @internal\n */\n\n/**\n * Fixed-capacity ring buffer. Once `capacity` entries are stored, subsequent\n * `push` calls evict the oldest entry (drop-oldest / FIFO eviction).\n *\n * Operations:\n * - `push(item)` — O(1).\n * - `shift()` — O(1) remove oldest (returns `undefined` when empty).\n * - `at(i)` — O(1) index lookup, with Python-style negative indexing.\n * - `toArray()` — O(n) materialize in insertion order.\n * - `clear()` — O(1) reset to empty.\n *\n * Not thread-safe; JS semantics assumed (single-threaded within a sync call).\n */\nexport class RingBuffer<T> {\n\tprivate buf: (T | undefined)[];\n\tprivate head = 0;\n\tprivate _size = 0;\n\n\tconstructor(private capacity: number) {\n\t\tif (!Number.isInteger(capacity) || capacity <= 0) {\n\t\t\tthrow new Error(`RingBuffer capacity must be a positive integer (got ${capacity})`);\n\t\t}\n\t\tthis.buf = new Array(capacity);\n\t}\n\n\t/** Current number of stored entries. */\n\tget size(): number {\n\t\treturn this._size;\n\t}\n\n\t/** Configured maximum before drop-oldest eviction fires. */\n\tget maxSize(): number {\n\t\treturn this.capacity;\n\t}\n\n\t/**\n\t * Append an item. If size equals capacity, drops the oldest entry and\n\t * advances the head pointer.\n\t */\n\tpush(item: T): void {\n\t\tconst idx = (this.head + this._size) % this.capacity;\n\t\tthis.buf[idx] = item;\n\t\tif (this._size < this.capacity) this._size++;\n\t\telse this.head = (this.head + 1) % this.capacity;\n\t}\n\n\t/** Remove and return the oldest entry; `undefined` when empty. */\n\tshift(): T | undefined {\n\t\tif (this._size === 0) return undefined;\n\t\tconst item = this.buf[this.head];\n\t\tthis.buf[this.head] = undefined;\n\t\tthis.head = (this.head + 1) % this.capacity;\n\t\tthis._size--;\n\t\treturn item;\n\t}\n\n\t/**\n\t * O(1) index lookup. Negative indices count from the tail (Python-style).\n\t * Returns `undefined` for out-of-range.\n\t */\n\tat(i: number): T | undefined {\n\t\tif (this._size === 0) return undefined;\n\t\tconst n = i < 0 ? this._size + i : i;\n\t\tif (n < 0 || n >= this._size) return undefined;\n\t\treturn this.buf[(this.head + n) % this.capacity];\n\t}\n\n\t/**\n\t * Materialize the contents in insertion order (oldest → newest).\n\t * Returns a new array each call.\n\t */\n\ttoArray(): T[] {\n\t\tconst result: T[] = new Array(this._size);\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tresult[i] = this.buf[(this.head + i) % this.capacity]!;\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Reset to empty. Storage slots are released so held refs can GC. */\n\tclear(): void {\n\t\tfor (let i = 0; i < this._size; i++) {\n\t\t\tthis.buf[(this.head + i) % this.capacity] = undefined;\n\t\t}\n\t\tthis.head = 0;\n\t\tthis._size = 0;\n\t}\n}\n","/**\n * Graph profiling and inspection utilities.\n *\n * Provides per-node memory estimation, connectivity stats, and hotspot\n * detection. Non-invasive — reads from `describe()` and node internals\n * without modifying state.\n *\n * @module\n */\n\nimport { type Node, NodeImpl } from \"../core/node.js\";\nimport { sizeof } from \"../extra/utils/sizeof.js\";\nimport type { Graph, GraphDescribeOutput } from \"./graph.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Per-node profile entry. */\nexport interface NodeProfile {\n\t/** Qualified path within the graph. */\n\tpath: string;\n\t/** Node type (state, derived, producer, effect). */\n\ttype: string;\n\t/** Node status (disconnected, dirty, settled, errored, completed). */\n\tstatus: string;\n\t/** Approximate retained bytes for the node's cached value. */\n\tvalueSizeBytes: number;\n\t/** Number of downstream subscribers (sinks). */\n\tsubscriberCount: number;\n\t/** Number of upstream dependencies. */\n\tdepCount: number;\n\t/**\n\t * True if this is an effect node with no external subscribers — a classic\n\t * leak pattern. See {@link GraphProfileResult.orphans} for the broader\n\t * orphan-node detection across `derived` / `producer` / `effect`.\n\t */\n\tisOrphanEffect: boolean;\n\t/**\n\t * Orphan category (batch 8 Unit 13 D). `null` when the node is healthy.\n\t * - `\"orphan-effect\"` — effect with zero subscribers (pre-existing class).\n\t * - `\"idle-derived\"` — derived with zero subscribers (wasted compute path\n\t * if it ever activates; may indicate a factory forgot keepalive).\n\t * - `\"idle-producer\"` — producer with zero subscribers (no external\n\t * consumer; may be an over-eager factory or forgotten cleanup).\n\t */\n\torphanKind: \"orphan-effect\" | \"idle-derived\" | \"idle-producer\" | null;\n}\n\n/** Aggregate graph profile. */\nexport interface GraphProfileResult {\n\t/** Total node count. */\n\tnodeCount: number;\n\t/** Total edge count. */\n\tedgeCount: number;\n\t/** Subgraph count. */\n\tsubgraphCount: number;\n\t/** All node profiles. */\n\tnodes: NodeProfile[];\n\t/** Total approximate value memory across all nodes. */\n\ttotalValueSizeBytes: number;\n\t/**\n\t * Top-N hotspots by dimension. Each list is sorted descending. See\n\t * {@link GraphProfileOptions.topN} for the cap (default 10).\n\t */\n\thotspots: {\n\t\tbyValueSize: NodeProfile[];\n\t\tbySubscriberCount: NodeProfile[];\n\t\tbyDepCount: NodeProfile[];\n\t};\n\t/**\n\t * Every orphan across types — `effect`, `derived`, `producer` with zero\n\t * subscribers. See {@link NodeProfile.orphanKind} for category.\n\t */\n\torphans: NodeProfile[];\n\t/** Effect nodes with no external subscribers (legacy; subset of `orphans`). */\n\torphanEffects: NodeProfile[];\n}\n\n/** Options for {@link graphProfile}. */\nexport interface GraphProfileOptions {\n\t/** Limit hotspot list (default 10). */\n\ttopN?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Profile a graph's memory and connectivity characteristics.\n *\n * Uses `describe({ detail: \"standard\" })` for node metadata and direct\n * `NodeImpl` access for subscriber counts and cached values.\n *\n * @param graph - The graph to profile.\n * @param opts - Optional configuration.\n * @returns Aggregate profile with per-node details, hotspots (multi-dim), and orphans.\n */\nexport function graphProfile(graph: Graph, opts?: GraphProfileOptions): GraphProfileResult {\n\tconst topN = opts?.topN ?? 10;\n\n\tconst desc: GraphDescribeOutput = graph.describe({ detail: \"standard\" });\n\n\t// Build path→Node lookup via _collectObserveTargets (same as describe uses).\n\t// Runtime guard: if the internal method is missing (refactored), degrade\n\t// gracefully — profiles will show 0 for valueSizeBytes and subscriberCount.\n\tconst targets: [string, Node][] = [];\n\tconst collector = (\n\t\tgraph as unknown as { _collectObserveTargets?: (prefix: string, out: [string, Node][]) => void }\n\t)._collectObserveTargets;\n\tif (typeof collector === \"function\") {\n\t\tcollector.call(graph, \"\", targets);\n\t}\n\tconst pathToNode = new Map<string, Node>();\n\tfor (const [p, n] of targets) pathToNode.set(p, n);\n\n\tconst profiles: NodeProfile[] = [];\n\n\tfor (const [path, nodeDesc] of Object.entries(desc.nodes)) {\n\t\tconst nd = pathToNode.get(path);\n\t\tconst impl = nd instanceof NodeImpl ? nd : null;\n\n\t\tconst valueSizeBytes = impl ? sizeof(impl.cache) : 0;\n\t\tconst subscriberCount = impl ? impl._sinkCount : 0;\n\t\tconst depCount = nodeDesc.deps?.length ?? 0;\n\n\t\tconst isOrphanEffect = nodeDesc.type === \"effect\" && subscriberCount === 0;\n\t\tconst orphanKind: NodeProfile[\"orphanKind\"] =\n\t\t\tsubscriberCount === 0\n\t\t\t\t? nodeDesc.type === \"effect\"\n\t\t\t\t\t? \"orphan-effect\"\n\t\t\t\t\t: nodeDesc.type === \"derived\"\n\t\t\t\t\t\t? \"idle-derived\"\n\t\t\t\t\t\t: nodeDesc.type === \"producer\"\n\t\t\t\t\t\t\t? \"idle-producer\"\n\t\t\t\t\t\t\t: null\n\t\t\t\t: null;\n\n\t\tprofiles.push({\n\t\t\tpath,\n\t\t\ttype: nodeDesc.type,\n\t\t\tstatus: nodeDesc.status ?? \"unknown\",\n\t\t\tvalueSizeBytes,\n\t\t\tsubscriberCount,\n\t\t\tdepCount,\n\t\t\tisOrphanEffect,\n\t\t\torphanKind,\n\t\t});\n\t}\n\n\tconst totalValueSizeBytes = profiles.reduce((sum, p) => sum + p.valueSizeBytes, 0);\n\n\tconst topBy = <K extends keyof NodeProfile>(\n\t\tkey: K,\n\t\tcmp?: (a: NodeProfile, b: NodeProfile) => number,\n\t): NodeProfile[] =>\n\t\t[...profiles].sort(cmp ?? ((a, b) => (b[key] as number) - (a[key] as number))).slice(0, topN);\n\n\tconst orphans = profiles.filter((p) => p.orphanKind != null);\n\tconst orphanEffects = profiles.filter((p) => p.isOrphanEffect);\n\n\treturn {\n\t\tnodeCount: profiles.length,\n\t\tedgeCount: desc.edges.length,\n\t\tsubgraphCount: desc.subgraphs.length,\n\t\tnodes: profiles,\n\t\ttotalValueSizeBytes,\n\t\thotspots: {\n\t\t\tbyValueSize: topBy(\"valueSizeBytes\"),\n\t\t\tbySubscriberCount: topBy(\"subscriberCount\"),\n\t\t\tbyDepCount: topBy(\"depCount\"),\n\t\t},\n\t\torphans,\n\t\torphanEffects,\n\t};\n}\n","import type { Actor } from \"../core/actor.js\";\nimport { batch, isBatching } from \"../core/batch.js\";\nimport { monotonicNs, wallClockNs } from \"../core/clock.js\";\nimport type { GraphReFlyConfig } from \"../core/config.js\";\nimport { GuardDenied } from \"../core/guard.js\";\nimport {\n\tCOMPLETE,\n\tDATA,\n\tDIRTY,\n\tERROR,\n\tINVALIDATE,\n\ttype Messages,\n\tPAUSE,\n\tRESOLVED,\n\tRESUME,\n\tTEARDOWN,\n} from \"../core/messages.js\";\nimport {\n\ttype DescribeDetail,\n\ttype DescribeField,\n\ttype DescribeNodeOutput,\n\tdescribeNode,\n\tresolveDescribeFields,\n} from \"../core/meta.js\";\nimport {\n\tdefaultConfig,\n\ttype Node,\n\tNodeImpl,\n\ttype NodeSink,\n\ttype NodeTransportOptions,\n} from \"../core/node.js\";\nimport { producer, state as stateNode } from \"../core/sugar.js\";\nimport type { VersioningLevel } from \"../core/versioning.js\";\nimport type { StorageHandle, StorageTier } from \"../extra/storage.js\";\nimport { ResettableTimer } from \"../extra/timer.js\";\nimport { RingBuffer } from \"../extra/utils/ring-buffer.js\";\nimport { decodeEnvelope, encodeEnvelope, type GraphCodec } from \"./codec.js\";\nimport { type CausalChain, explainPath } from \"./explain.js\";\nimport { type GraphProfileOptions, type GraphProfileResult, graphProfile } from \"./profile.js\";\n\n/** The separator used for qualified paths in {@link Graph.resolve} et al. */\nconst PATH_SEP = \"::\";\n\n/**\n * Reserved segment for meta companion paths: `nodeName::__meta__::metaKey` (GRAPHREFLY-SPEC §3.6).\n * Forbidden as a local node or mount name.\n */\nexport const GRAPH_META_SEGMENT = \"__meta__\";\n\n/**\n * Options for {@link Graph}. Named fields documented below; the open index\n * signature is preserved so callers can stash extension data on the graph\n * without losing type discipline on the reserved names.\n *\n * - `config` — bind this graph to a specific {@link GraphReFlyConfig} for\n * tier/metaPassthrough/inspector lookups. Defaults to the singleton\n * `defaultConfig` exported from `core/node.ts`.\n * - `versioning` — convenience for `graph.setVersioning(level)` at\n * construction time. Monotonic bulk-apply; see {@link Graph.setVersioning}.\n * - `factories` — reserved for future per-graph factory registration;\n * currently factories flow through `Graph.fromSnapshot(data, {factories})`.\n */\nexport interface GraphOptions {\n\tconfig?: GraphReFlyConfig;\n\tversioning?: VersioningLevel;\n\tfactories?: Record<string, GraphNodeFactory>;\n\t/**\n\t * Capacity of the reasoning-trace ring buffer. Default: `1000`. Set lower\n\t * to reduce memory; higher for audit-heavy workloads. Set at construction\n\t * time — not mutable afterward (ring buffers can't resize cleanly).\n\t */\n\ttraceCapacity?: number;\n\t[key: string]: unknown;\n}\n\n/** Filter for {@link Graph.describe} — object-style partial match or predicate. */\nexport type DescribeFilter =\n\t| Partial<Pick<DescribeNodeOutput, \"type\" | \"status\">>\n\t| {\n\t\t\ttype?: DescribeNodeOutput[\"type\"];\n\t\t\tstatus?: DescribeNodeOutput[\"status\"];\n\t\t\t/** Keep nodes whose `deps` includes this qualified path. */\n\t\t\tdepsIncludes?: string;\n\t\t\t/** Snake-case alias for `depsIncludes` (Python parity). */\n\t\t\tdeps_includes?: string;\n\t\t\t/** Keep nodes whose `meta` contains this key. */\n\t\t\tmetaHas?: string;\n\t\t\t/** Snake-case alias for `metaHas` (Python parity). */\n\t\t\tmeta_has?: string;\n\t }\n\t| ((node: DescribeNodeOutput) => boolean)\n\t| ((nodePath: string, node: DescribeNodeOutput) => boolean);\n\n/** Options for {@link Graph.signal} and {@link Graph.set} (actor context, internal lifecycle). */\nexport type GraphActorOptions = {\n\tactor?: Actor;\n\t/**\n\t * When `true`, skips node guards (graph lifecycle TEARDOWN, unmount teardown, etc.).\n\t */\n\tinternal?: boolean;\n};\n\n/** Options for {@link Graph.describe} (Phase 3.3b progressive disclosure). */\nexport type GraphDescribeOptions = {\n\tactor?: Actor;\n\t/**\n\t * Node filter. Filters operate on whatever fields the chosen `detail` level\n\t * provides. For `metaHas` and `status` filters, use `detail: \"standard\"` or\n\t * higher — at `\"minimal\"` those fields are absent and the filter silently\n\t * excludes all nodes.\n\t */\n\tfilter?: DescribeFilter;\n\t/**\n\t * Detail level (Phase 3.3b). Default: `\"minimal\"`.\n\t * - `\"minimal\"` — type + deps only\n\t * - `\"standard\"` — type, status, value, deps, meta, versioning (`v`)\n\t * - `\"full\"` — standard + guard, lastMutation\n\t */\n\tdetail?: DescribeDetail;\n\t/**\n\t * Explicit field selection (GraphQL-style). Overrides `detail` when provided.\n\t * Dotted paths like `\"meta.label\"` select specific meta keys.\n\t */\n\tfields?: DescribeField[];\n\t/**\n\t * Output format.\n\t * - `undefined` / omitted — return the full {@link GraphDescribeOutput} object.\n\t * - `\"spec\"` — GraphSpec input format (object; no status/value, deps as edges).\n\t * - `\"json\"` — stable JSON **text** with sorted keys.\n\t * - `\"pretty\"` — human-readable plaintext (optionally colorized; see\n\t * `colorize` / `indent` / `logger` / `includeEdges` / `includeSubgraphs`).\n\t * - `\"mermaid\"` — Mermaid flowchart text.\n\t * - `\"d2\"` — D2 diagram text.\n\t */\n\tformat?: \"spec\" | \"json\" | \"pretty\" | \"mermaid\" | \"d2\";\n\t/** Pretty/diagram render: direction for diagram formats (default `LR`). */\n\tdirection?: GraphDiagramDirection;\n\t/** Pretty/JSON render: indent (default 2 for JSON, ignored for pretty). */\n\tindent?: number;\n\t/** Pretty render: optional logger hook; fires with the rendered text before return. */\n\tlogger?: (text: string) => void;\n\t/** Pretty render: include an Edges section (default `true`). */\n\tincludeEdges?: boolean;\n\t/** Pretty render: include a Subgraphs section (default `true`). */\n\tincludeSubgraphs?: boolean;\n};\n\n/** JSON snapshot from {@link Graph.describe} (GRAPHREFLY-SPEC §3.6, Appendix B). */\nexport type GraphDescribeOutput = {\n\tname: string;\n\tnodes: Record<string, DescribeNodeOutput>;\n\tedges: ReadonlyArray<{ from: string; to: string }>;\n\tsubgraphs: string[];\n\t/**\n\t * Re-read the live graph with higher detail (Phase 3.3b).\n\t * Returns a new `GraphDescribeOutput`; the original remains a snapshot.\n\t * Present on live describe results; absent on deserialized snapshots.\n\t */\n\texpand?: (detailOrFields: DescribeDetail | DescribeField[]) => GraphDescribeOutput;\n};\n\n/**\n * Persisted graph snapshot: {@link GraphDescribeOutput} plus optional format version\n * ({@link Graph.snapshot}, {@link Graph.restore}, {@link Graph.fromSnapshot}, {@link Graph.toObject},\n * {@link Graph.toJSONString} — §3.8).\n */\nexport type GraphPersistSnapshot = GraphDescribeOutput & {\n\tversion?: number;\n};\n\nexport type GraphFactoryContext = {\n\tpath: string;\n\ttype: DescribeNodeOutput[\"type\"];\n\tvalue: unknown;\n\tmeta: Record<string, unknown>;\n\tdeps: readonly string[];\n\tresolvedDeps: readonly Node[];\n};\n\nexport type GraphNodeFactory = (name: string, context: GraphFactoryContext) => Node;\n\n/**\n * Checkpoint record shape passed to `StorageTier.save`. Written by\n * {@link Graph.attachStorage} per-tier according to each tier's\n * `compactEvery` cadence.\n *\n * `mode: \"full\"` → full snapshot. Baseline anchor emitted on the first save\n * and every `compactEvery`-th save thereafter. Sufficient to recover state\n * on its own without WAL replay.\n * `mode: \"diff\"` → delta payload only, relative to this tier's most recent\n * `\"full\"` baseline. Between compacts. Wire-efficient; requires WAL replay\n * over the preceding `\"full\"` record to reconstruct state.\n *\n * Every record includes `seq` (per-tier monotonic counter), `timestamp_ns`\n * (wall-clock at flush time), and `format_version` (envelope version for\n * cross-version WAL replay).\n */\nexport type GraphCheckpointRecord = {\n\tseq: number;\n\ttimestamp_ns: number;\n\tformat_version: number;\n} & ({ mode: \"full\"; snapshot: GraphPersistSnapshot } | { mode: \"diff\"; diff: GraphWALDiff });\n\n/** Options for {@link Graph.attachStorage}. */\nexport type GraphAttachStorageOptions = {\n\t/**\n\t * Before the first save, attempt to restore from the first tier whose\n\t * `load(graph.name)` hits. Runs asynchronously in the background for\n\t * async tiers; errors surface via `onError`. Default `false`.\n\t */\n\tautoRestore?: boolean;\n\t/**\n\t * Limit the subscription surface (scoped observe). By default\n\t * `attachStorage` observes every node in the graph tree; on large graphs\n\t * that's thousands of subscriptions just for tier-gating. Pass a path\n\t * list (or a single glob) to observe only those nodes.\n\t */\n\tpaths?: readonly string[] | string;\n\t/** Pre-save path-level filter — skip records triggered by paths that fail this predicate. */\n\tfilter?: (name: string, described: DescribeNodeOutput) => boolean;\n\t/** Surfaced on tier save errors and autoRestore failures. */\n\tonError?: (error: unknown, tier: StorageTier) => void;\n};\n\n/**\n * Event emitted by {@link Graph.topology} on every structural change to the\n * graph's own registry. Does NOT include value mutations (use `observe()` for\n * those) or transitively nested subgraph events (subscribe to each mounted\n * child's `topology` for that).\n *\n * - `\"added\"` — `name` is the local key registered via {@link Graph.add}\n * (`nodeKind: \"node\"`) or {@link Graph.mount} (`nodeKind: \"mount\"`).\n * - `\"removed\"` — emitted AFTER {@link Graph.remove} completes teardown.\n * `audit` is the full {@link GraphRemoveAudit} returned to the caller.\n */\nexport type TopologyEvent =\n\t| { kind: \"added\"; name: string; nodeKind: \"node\" | \"mount\" }\n\t| {\n\t\t\tkind: \"removed\";\n\t\t\tname: string;\n\t\t\tnodeKind: \"node\" | \"mount\";\n\t\t\taudit: GraphRemoveAudit;\n\t };\n\n/** Direction options for diagram export helpers. */\nexport type GraphDiagramDirection = \"TD\" | \"LR\" | \"BT\" | \"RL\";\n\n/** Options for {@link Graph.toMermaid} / {@link Graph.toD2}. */\nexport type GraphDiagramOptions = {\n\t/**\n\t * Diagram flow direction.\n\t * - `TD`: top-down\n\t * - `LR`: left-right (default)\n\t * - `BT`: bottom-top\n\t * - `RL`: right-left\n\t */\n\tdirection?: GraphDiagramDirection;\n};\n\n/**\n * Snapshot format version (§3.8). Exported so the surface layer's\n * `saveSnapshot` writes the same `format_version` as\n * `Graph.attachStorage` — one source of truth prevents silent wire\n * drift between auto-checkpoint and one-shot persistence paths.\n */\nexport const SNAPSHOT_VERSION = 1;\n\n/**\n * Drain a disposer set iteratively — pop, remove, run. Disposers registered\n * mid-drain are picked up by the next iteration. Capped to guard against a\n * disposer that re-registers itself in an infinite loop. Exceptions are\n * surfaced via `console.error` rather than silently swallowed so leaks in\n * cleanup code remain visible.\n */\nfunction drainDisposers(set: Set<() => void>, graphName: string): void {\n\tconst cap = Math.max(16, set.size * 4);\n\tlet iterations = 0;\n\twhile (set.size > 0) {\n\t\tif (iterations++ >= cap) {\n\t\t\tconsole.error(\n\t\t\t\t`[Graph \"${graphName}\".destroy] disposer drain exceeded cap (${cap}); ${set.size} disposer(s) discarded`,\n\t\t\t);\n\t\t\tset.clear();\n\t\t\treturn;\n\t\t}\n\t\tconst it = set.values().next();\n\t\tif (it.done) return;\n\t\tconst dispose = it.value;\n\t\tset.delete(dispose);\n\t\ttry {\n\t\t\tdispose();\n\t\t} catch (err) {\n\t\t\tconsole.error(`[Graph \"${graphName}\".destroy] disposer threw:`, err);\n\t\t}\n\t}\n}\n\n/**\n * Cheap graph-level V0 version fingerprint: concatenate `v.id@v.version` for\n * every node that carries V0 info. Used by {@link Graph.attachStorage} to\n * short-circuit per-tier flushes when nothing versioned has changed since\n * the tier's last save. Non-versioned graphs produce an empty string so the\n * shortcut is a no-op for them (every scheduled flush writes).\n */\nfunction computeVersionFingerprint(nodes: Record<string, DescribeNodeOutput>): string {\n\tconst parts: string[] = [];\n\tfor (const path of Object.keys(nodes).sort()) {\n\t\tconst v = nodes[path]!.v;\n\t\tif (v != null) parts.push(`${path}\\t${v.id}\\t${v.version}`);\n\t}\n\treturn parts.join(\"\\n\");\n}\n\n/**\n * Validate the snapshot envelope: version, required keys, types. Aligned with\n * Python `_parse_snapshot_envelope`. Throws on invalid data.\n */\nfunction parseSnapshotEnvelope(data: GraphPersistSnapshot): void {\n\tif (data.version !== SNAPSHOT_VERSION) {\n\t\tthrow new Error(\n\t\t\t`unsupported snapshot version ${String(data.version)} (expected ${SNAPSHOT_VERSION})`,\n\t\t);\n\t}\n\tfor (const key of [\"name\", \"nodes\", \"edges\", \"subgraphs\"] as const) {\n\t\tif (!(key in data)) {\n\t\t\tthrow new Error(`snapshot missing required key \"${key}\"`);\n\t\t}\n\t}\n\tif (typeof data.name !== \"string\") {\n\t\tthrow new TypeError(`snapshot 'name' must be a string`);\n\t}\n\tif (typeof data.nodes !== \"object\" || data.nodes === null || Array.isArray(data.nodes)) {\n\t\tthrow new TypeError(`snapshot 'nodes' must be an object`);\n\t}\n\tif (!Array.isArray(data.edges)) {\n\t\tthrow new TypeError(`snapshot 'edges' must be an array`);\n\t}\n\tif (!Array.isArray(data.subgraphs)) {\n\t\tthrow new TypeError(`snapshot 'subgraphs' must be an array`);\n\t}\n}\n\n/**\n * Structural deep equality — handles cycles, BigInt, Map, Set, Date, RegExp,\n * TypedArray, and nested objects/arrays. Used by `Graph.diff` to compare\n * node values without the cycle/BigInt/Map/Set footguns of `JSON.stringify`.\n *\n * Semantics: `Object.is` on primitives (so `NaN === NaN`, `-0 !== 0`), same\n * constructor required for object types, key-order-insensitive for plain\n * objects, order-sensitive for arrays + TypedArrays, unordered for Set,\n * key-equality for Map.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tconst seen = new WeakMap<object, WeakSet<object>>();\n\tconst walk = (x: unknown, y: unknown): boolean => {\n\t\tif (Object.is(x, y)) return true;\n\t\tif (x == null || y == null || typeof x !== \"object\" || typeof y !== \"object\") return false;\n\t\t// Cycle handling: assume equal on re-encounter (cycles match iff they\n\t\t// correspond structurally — standard \"optimistic\" deep-equal rule).\n\t\tlet seenRhs = seen.get(x as object);\n\t\tif (seenRhs == null) {\n\t\t\tseenRhs = new WeakSet();\n\t\t\tseen.set(x as object, seenRhs);\n\t\t}\n\t\tif (seenRhs.has(y as object)) return true;\n\t\tseenRhs.add(y as object);\n\n\t\tconst ctorA = (x as object).constructor;\n\t\tconst ctorB = (y as object).constructor;\n\t\tif (ctorA !== ctorB) return false;\n\n\t\tif (x instanceof Date) return (x as Date).getTime() === (y as Date).getTime();\n\t\tif (x instanceof RegExp)\n\t\t\treturn (\n\t\t\t\t(x as RegExp).source === (y as RegExp).source && (x as RegExp).flags === (y as RegExp).flags\n\t\t\t);\n\t\tif (Array.isArray(x)) {\n\t\t\tconst arrB = y as unknown[];\n\t\t\tif ((x as unknown[]).length !== arrB.length) return false;\n\t\t\tfor (let i = 0; i < (x as unknown[]).length; i++) {\n\t\t\t\tif (!walk((x as unknown[])[i], arrB[i])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (x instanceof Map) {\n\t\t\tconst mB = y as Map<unknown, unknown>;\n\t\t\tif ((x as Map<unknown, unknown>).size !== mB.size) return false;\n\t\t\tfor (const [k, v] of x as Map<unknown, unknown>) {\n\t\t\t\tif (!mB.has(k) || !walk(v, mB.get(k))) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (x instanceof Set) {\n\t\t\tconst sB = y as Set<unknown>;\n\t\t\tif ((x as Set<unknown>).size !== sB.size) return false;\n\t\t\t// O(n²) fallback — Sets have no ordering, and walking each pair\n\t\t\t// is the only way to support structural equality on non-primitive\n\t\t\t// members. Acceptable: diff scale is describe-output-sized.\n\t\t\tfor (const v of x as Set<unknown>) {\n\t\t\t\tlet found = false;\n\t\t\t\tfor (const w of sB) {\n\t\t\t\t\tif (walk(v, w)) {\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (ArrayBuffer.isView(x)) {\n\t\t\tconst taA = x as unknown as { length: number; [i: number]: number };\n\t\t\tconst taB = y as unknown as { length: number; [i: number]: number };\n\t\t\tif (taA.length !== taB.length) return false;\n\t\t\tfor (let i = 0; i < taA.length; i++) if (taA[i] !== taB[i]) return false;\n\t\t\treturn true;\n\t\t}\n\t\t// Plain object: same key-set, same values (key order irrelevant).\n\t\tconst keysA = Object.keys(x as Record<string, unknown>);\n\t\tconst keysB = Object.keys(y as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tconst setB = new Set(keysB);\n\t\tfor (const k of keysA) {\n\t\t\tif (!setB.has(k)) return false;\n\t\t\tif (!walk((x as Record<string, unknown>)[k], (y as Record<string, unknown>)[k])) return false;\n\t\t}\n\t\treturn true;\n\t};\n\treturn walk(a, b);\n}\n\n/** Recursively sort object keys for deterministic JSON (git-diffable). */\nfunction sortJsonValue(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") {\n\t\treturn value;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sortJsonValue);\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\tconst out: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tout[k] = sortJsonValue(obj[k]);\n\t}\n\treturn out;\n}\n\nfunction escapeMermaidLabel(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction escapeD2Label(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"');\n}\n\nfunction d2DirectionFromGraphDirection(direction: GraphDiagramDirection): string {\n\tif (direction === \"TD\") return \"down\";\n\tif (direction === \"BT\") return \"up\";\n\tif (direction === \"RL\") return \"left\";\n\treturn \"right\";\n}\n\n/** Collect deduplicated (from, to) arrows from deps + edges. */\nfunction collectDiagramArrows(described: GraphDescribeOutput): [string, string][] {\n\tconst seen = new Set<string>();\n\tconst arrows: [string, string][] = [];\n\tfunction add(from: string, to: string): void {\n\t\tconst key = `${from}\\0${to}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tarrows.push([from, to]);\n\t}\n\tfor (const [path, info] of Object.entries(described.nodes)) {\n\t\tconst deps: string[] | undefined = (info as Record<string, unknown>).deps as\n\t\t\t| string[]\n\t\t\t| undefined;\n\t\tif (deps) {\n\t\t\tfor (const dep of deps) add(dep, path);\n\t\t}\n\t}\n\tfor (const edge of described.edges) add(edge.from, edge.to);\n\treturn arrows;\n}\n\nfunction normalizeDiagramDirection(direction: unknown): GraphDiagramDirection {\n\tif (direction === undefined) return \"LR\";\n\tif (direction === \"TD\" || direction === \"LR\" || direction === \"BT\" || direction === \"RL\") {\n\t\treturn direction;\n\t}\n\tthrow new Error(\n\t\t`invalid diagram direction ${String(direction)}; expected one of: TD, LR, BT, RL`,\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// describe({format}) renderers — consolidated from the ex-dumpGraph /\n// ex-toMermaid / ex-toD2 methods (Unit 12 + Unit 20).\n// ---------------------------------------------------------------------------\n\nfunction renderDescribeAsJson(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst includeEdges = options.includeEdges ?? true;\n\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\tconst { expand: _expand, ...rest } = d;\n\tconst payload: GraphDescribeOutput = {\n\t\t...rest,\n\t\tedges: includeEdges ? d.edges : [],\n\t\tsubgraphs: includeSubgraphs ? d.subgraphs : [],\n\t};\n\tconst text = JSON.stringify(sortJsonValue(payload), null, options.indent ?? 2);\n\toptions.logger?.(text);\n\treturn text;\n}\n\nfunction renderDescribeAsPretty(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst includeEdges = options.includeEdges ?? true;\n\tconst includeSubgraphs = options.includeSubgraphs ?? true;\n\tconst lines: string[] = [];\n\tlines.push(`Graph ${d.name}`);\n\tlines.push(\"Nodes:\");\n\tfor (const path of Object.keys(d.nodes).sort()) {\n\t\tconst n = d.nodes[path]!;\n\t\tlines.push(`- ${path} (${n.type}/${n.status}): ${describeData(n.value)}`);\n\t}\n\tif (includeEdges) {\n\t\tlines.push(\"Edges:\");\n\t\tfor (const edge of d.edges) {\n\t\t\tlines.push(`- ${edge.from} -> ${edge.to}`);\n\t\t}\n\t}\n\tif (includeSubgraphs) {\n\t\tlines.push(\"Subgraphs:\");\n\t\tfor (const sg of d.subgraphs) {\n\t\t\tlines.push(`- ${sg}`);\n\t\t}\n\t}\n\tconst text = lines.join(\"\\n\");\n\toptions.logger?.(text);\n\treturn text;\n}\n\nfunction renderDescribeAsMermaid(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst direction = normalizeDiagramDirection(options.direction);\n\tconst paths = Object.keys(d.nodes).sort();\n\tconst ids = new Map<string, string>();\n\tfor (let i = 0; i < paths.length; i += 1) ids.set(paths[i]!, `n${i}`);\n\tconst lines: string[] = [`flowchart ${direction}`];\n\tfor (const path of paths) {\n\t\tconst id = ids.get(path)!;\n\t\tlines.push(` ${id}[\"${escapeMermaidLabel(path)}\"]`);\n\t}\n\tfor (const [from, to] of collectDiagramArrows(d)) {\n\t\tconst fromId = ids.get(from);\n\t\tconst toId = ids.get(to);\n\t\tif (!fromId || !toId) continue;\n\t\tlines.push(` ${fromId} --> ${toId}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction renderDescribeAsD2(d: GraphDescribeOutput, options: GraphDescribeOptions): string {\n\tconst direction = normalizeDiagramDirection(options.direction);\n\tconst paths = Object.keys(d.nodes).sort();\n\tconst ids = new Map<string, string>();\n\tfor (let i = 0; i < paths.length; i += 1) ids.set(paths[i]!, `n${i}`);\n\tconst lines: string[] = [`direction: ${d2DirectionFromGraphDirection(direction)}`];\n\tfor (const path of paths) {\n\t\tconst id = ids.get(path)!;\n\t\tlines.push(`${id}: \"${escapeD2Label(path)}\"`);\n\t}\n\tfor (const [from, to] of collectDiagramArrows(d)) {\n\t\tconst fromId = ids.get(from);\n\t\tconst toId = ids.get(to);\n\t\tif (!fromId || !toId) continue;\n\t\tlines.push(`${fromId} -> ${toId}`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeRegexLiteral(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction globToRegex(pattern: string): RegExp {\n\tlet re = \"^\";\n\tfor (let i = 0; i < pattern.length; i += 1) {\n\t\tconst ch = pattern[i]!;\n\t\tif (ch === \"*\") {\n\t\t\tre += \".*\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"?\") {\n\t\t\tre += \".\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tconst end = pattern.indexOf(\"]\", i + 1);\n\t\t\tif (end <= i + 1) {\n\t\t\t\tre += \"\\\\[\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet cls = pattern.slice(i + 1, end);\n\t\t\tif (cls.startsWith(\"!\")) cls = `^${cls.slice(1)}`;\n\t\t\tcls = cls.replace(/\\\\/g, \"\\\\\\\\\");\n\t\t\tre += `[${cls}]`;\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tre += escapeRegexLiteral(ch);\n\t}\n\tre += \"$\";\n\treturn new RegExp(re);\n}\n\nconst OBSERVE_ANSI_THEME: Required<ObserveTheme> = {\n\tdata: \"\\u001b[32m\",\n\tdirty: \"\\u001b[33m\",\n\tresolved: \"\\u001b[36m\",\n\tinvalidate: \"\\u001b[93m\",\n\tpause: \"\\u001b[90m\",\n\tresume: \"\\u001b[96m\",\n\tcomplete: \"\\u001b[34m\",\n\terror: \"\\u001b[31m\",\n\tteardown: \"\\u001b[91m\",\n\tderived: \"\\u001b[35m\",\n\tpath: \"\\u001b[90m\",\n\treset: \"\\u001b[0m\",\n};\n\nconst OBSERVE_NO_COLOR_THEME: Required<ObserveTheme> = {\n\tdata: \"\",\n\tdirty: \"\",\n\tresolved: \"\",\n\tinvalidate: \"\",\n\tpause: \"\",\n\tresume: \"\",\n\tcomplete: \"\",\n\terror: \"\",\n\tteardown: \"\",\n\tderived: \"\",\n\tpath: \"\",\n\treset: \"\",\n};\n\nfunction describeData(value: unknown): string {\n\tif (typeof value === \"string\") return JSON.stringify(value);\n\tif (typeof value === \"number\" || typeof value === \"boolean\" || value == null)\n\t\treturn String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\n\nfunction resolveObserveTheme(theme: ObserveOptions[\"theme\"]): Required<ObserveTheme> {\n\tif (theme === \"none\") return OBSERVE_NO_COLOR_THEME;\n\tif (theme === \"ansi\" || theme == null) return OBSERVE_ANSI_THEME;\n\treturn {\n\t\tdata: theme.data ?? \"\",\n\t\tdirty: theme.dirty ?? \"\",\n\t\tresolved: theme.resolved ?? \"\",\n\t\tinvalidate: theme.invalidate ?? \"\",\n\t\tpause: theme.pause ?? \"\",\n\t\tresume: theme.resume ?? \"\",\n\t\tcomplete: theme.complete ?? \"\",\n\t\terror: theme.error ?? \"\",\n\t\tteardown: theme.teardown ?? \"\",\n\t\tderived: theme.derived ?? \"\",\n\t\tpath: theme.path ?? \"\",\n\t\treset: theme.reset ?? \"\",\n\t};\n}\n\n/** Resolve observe `detail` level into effective boolean flags. */\nfunction resolveObserveDetail(opts?: ObserveOptions): ObserveOptions {\n\tif (opts == null) return {};\n\tconst detail = opts.detail;\n\tif (detail === \"full\") {\n\t\treturn {\n\t\t\t...opts,\n\t\t\tstructured: opts.structured ?? true,\n\t\t\ttimeline: opts.timeline ?? true,\n\t\t\tcausal: opts.causal ?? true,\n\t\t\tderived: opts.derived ?? true,\n\t\t};\n\t}\n\tif (detail === \"minimal\") {\n\t\treturn { ...opts, structured: opts.structured ?? true };\n\t}\n\treturn opts;\n}\n\n/**\n * Option shapes that trigger structured-mode dispatch in {@link Graph.observe}.\n * Presence of any of these fields (truthy) → returns {@link ObserveResult};\n * otherwise `observe()` returns the raw-stream variants.\n */\nexport type StructuredTriggers = {\n\tstructured?: true;\n\ttimeline?: true;\n\tcausal?: true;\n\tderived?: true;\n\tformat?: \"pretty\" | \"json\";\n\tdetail?: \"minimal\" | \"full\";\n};\n\n/** {@link Graph.observe} on a single node or meta path — sink receives plain message batches. */\nexport type GraphObserveOne = {\n\tsubscribe(sink: NodeSink): () => void;\n\t/** Send messages upstream toward the observed node's sources (e.g. PAUSE/RESUME). */\n\tup(messages: Messages): void;\n};\n\n/**\n * {@link Graph.observe} on the whole graph — sink receives each batch with the qualified source path.\n * Subscription order follows code-point sort on paths (mounts-first walk, then sorted locals/meta).\n */\nexport type GraphObserveAll = {\n\tsubscribe(sink: (nodePath: string, messages: Messages) => void): () => void;\n\t/** Send messages upstream toward a specific observed node's sources (e.g. PAUSE/RESUME). */\n\tup(path: string, messages: Messages): void;\n};\n\n/**\n * Detail level for `observe()` progressive disclosure (Phase 3.3b).\n * - `\"minimal\"` — DATA events only, no timestamps, no causal info.\n * - `\"standard\"` — all message types (DATA, DIRTY, RESOLVED, INVALIDATE,\n * PAUSE, RESUME, COMPLETE, ERROR, TEARDOWN).\n * - `\"full\"` — standard + timeline + causal + derived.\n */\nexport type ObserveDetail = \"minimal\" | \"standard\" | \"full\";\n\n/** Options for structured observation modes on {@link Graph.observe}. */\nexport type ObserveOptions = {\n\tactor?: Actor;\n\t/** Return an {@link ObserveResult} accumulator instead of a raw stream. */\n\tstructured?: boolean;\n\t/** Include causal trace info (which dep triggered each recomputation). */\n\tcausal?: boolean;\n\t/** Include timestamps and batch context on each event. */\n\ttimeline?: boolean;\n\t/** Include per-evaluation dep snapshots for compute/derived nodes. */\n\tderived?: boolean;\n\t/**\n\t * Detail level (Phase 3.3b). Individual flags (`causal`, `timeline`, `derived`)\n\t * override. `\"full\"` implies all three plus structured.\n\t * `\"minimal\"` filters to DATA-only events.\n\t */\n\tdetail?: ObserveDetail;\n\n\t// ——— Format / logging (merged from spy) ———\n\n\t/**\n\t * When set, auto-enables structured mode and attaches a logger.\n\t * `\"pretty\"` renders colored one-line output; `\"json\"` emits one JSON object per event.\n\t */\n\tformat?: \"pretty\" | \"json\";\n\t/** Sink for rendered lines (`console.log` by default). Only used when `format` is set. */\n\tlogger?: (line: string, event: ObserveEvent) => void;\n\t/** Keep only these event types in formatted output. Only used when `format` is set. */\n\tincludeTypes?: ObserveEvent[\"type\"][];\n\t/** Exclude these event types from formatted output. Only used when `format` is set. */\n\texcludeTypes?: ObserveEvent[\"type\"][];\n\t/** Built-in color preset (`ansi` default) or explicit color tokens. Only used when `format` is set. */\n\ttheme?: ObserveThemeName | ObserveTheme;\n\t/**\n\t * Cap the `events` buffer. When set, the result uses a {@link RingBuffer}\n\t * under the hood: oldest events are dropped on overflow. Unbounded when\n\t * omitted (default).\n\t */\n\tmaxEvents?: number;\n};\n\n/** Accumulated observation result (structured mode). */\nexport type ObserveResult<T = unknown> = AsyncIterable<ObserveEvent> & {\n\t/** Latest DATA value by observed path. */\n\treadonly values: Record<string, T>;\n\t/** Number of DIRTY messages received. */\n\treadonly dirtyCount: number;\n\t/** Number of RESOLVED messages received. */\n\treadonly resolvedCount: number;\n\t/** Number of INVALIDATE messages received (tier 1 cache-clear). */\n\treadonly invalidateCount: number;\n\t/** Number of PAUSE messages received (tier 2 backpressure). */\n\treadonly pauseCount: number;\n\t/** Number of RESUME messages received (tier 2 backpressure). */\n\treadonly resumeCount: number;\n\t/** Number of TEARDOWN messages received (tier 5 permanent cleanup). */\n\treadonly teardownCount: number;\n\t/**\n\t * All events in order — ring-buffered when `options.maxEvents` is set,\n\t * unbounded otherwise. Always materialized as an `ObserveEvent[]`\n\t * snapshot on read.\n\t */\n\treadonly events: ObserveEvent[];\n\t/** True if any observed node sent COMPLETE without prior ERROR on that node. */\n\treadonly anyCompletedCleanly: boolean;\n\t/** True if any observed node sent ERROR. */\n\treadonly anyErrored: boolean;\n\t/** True if at least one COMPLETE received and no ERROR from any observed node. */\n\treadonly completedWithoutErrors: boolean;\n\t/**\n\t * Attach a live listener that fires for each event as it arrives.\n\t * Returns an unsubscribe fn. Independent of the `events` buffer.\n\t */\n\tonEvent(listener: (event: ObserveEvent) => void): () => void;\n\t/** Stop observing. */\n\tdispose(): void;\n\t/**\n\t * Resubscribe with higher detail (Phase 3.3b).\n\t * Disposes current observation, returns new `ObserveResult` with merged options.\n\t */\n\texpand(\n\t\textra: Partial<Pick<ObserveOptions, \"causal\" | \"timeline\" | \"derived\">> | ObserveDetail,\n\t): ObserveResult<T>;\n};\n\n/** Fields common to every {@link ObserveEvent} variant. */\nexport interface ObserveEventBase {\n\tpath?: string;\n\t/** Optional `timeline` context — wall-clock when `options.timeline === true`. */\n\ttimestamp_ns?: number;\n\tin_batch?: boolean;\n\t/** Monotonically increasing counter per subscribe-callback invocation. All events in one delivery share the same id. */\n\tbatch_id?: number;\n}\n\n/** Optional `causal` context present on `data`/`resolved`/`derived` events. */\nexport interface ObserveCausalContext {\n\ttrigger_dep_index?: number;\n\ttrigger_dep_name?: string;\n\t/**\n\t * V0 version of the triggering dep at observation time (§6.0b).\n\t * This is the dep's post-emission version (after its own `advanceVersion`),\n\t * not the pre-emission version that caused this node's recomputation.\n\t */\n\ttrigger_version?: { id: string; version: number };\n\t/**\n\t * One scalar per dep: the last value that arrived in the current wave,\n\t * or the pre-wave cached value for deps that didn't fire. Convenient\n\t * for single-value-wave tooling (the common case).\n\t */\n\tdep_values?: unknown[];\n\t/**\n\t * Full per-dep batches for the wave that fired the fn — `dep_batches[i]`\n\t * is the array of values dep `i` delivered this wave (`undefined` for\n\t * deps that didn't fire). Use this to distinguish a single-value wave\n\t * from a multi-value wave; `dep_values` compresses each batch to its\n\t * last element and hides that difference.\n\t */\n\tdep_batches?: ReadonlyArray<ReadonlyArray<unknown> | undefined>;\n}\n\n/** A single event in the structured observation log (discriminated on `type`). */\nexport type ObserveEvent =\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"data\"; data: unknown })\n\t| (ObserveEventBase & { type: \"dirty\" })\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"resolved\" })\n\t| (ObserveEventBase & { type: \"invalidate\" })\n\t| (ObserveEventBase & { type: \"pause\"; lockId: unknown })\n\t| (ObserveEventBase & { type: \"resume\"; lockId: unknown })\n\t| (ObserveEventBase & { type: \"complete\" })\n\t| (ObserveEventBase & { type: \"error\"; data: unknown })\n\t| (ObserveEventBase & { type: \"teardown\" })\n\t| (ObserveEventBase & ObserveCausalContext & { type: \"derived\"; dep_values: unknown[] });\n\n/** Built-in color preset names for observe `format` rendering. */\nexport type ObserveThemeName = \"none\" | \"ansi\";\n\n/** ANSI/style overrides for observe `format` event rendering. */\nexport type ObserveTheme = Partial<Record<ObserveEvent[\"type\"] | \"path\" | \"reset\", string>>;\n\n/**\n * Reject characters that would collide with internal serialization or path\n * grammar. Control chars (0x00–0x1F, 0x7F) break `describe()` key stability,\n * diagram rendering, and any tab-delimited log/trace format. Keep the test\n * tight so the error message points at the first offending code point.\n */\nfunction assertNoControlChars(name: string, graphName: string, label: string): void {\n\tfor (let i = 0; i < name.length; i++) {\n\t\tconst c = name.charCodeAt(i);\n\t\tif (c < 0x20 || c === 0x7f) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain control character (U+${c.toString(16).padStart(4, \"0\").toUpperCase()} at index ${i})`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate a registerable local name (`add`, `mount`, `remove` inputs):\n * non-empty, no `::` separator, not the reserved `__meta__` segment, and no\n * control characters.\n */\nfunction assertRegisterableName(name: string, graphName: string, label: string): void {\n\tif (name === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": ${label} name must be non-empty`);\n\t}\n\tif (name.includes(PATH_SEP)) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} \"${name}\" must not contain '${PATH_SEP}' (path separator)`,\n\t\t);\n\t}\n\tif (name === GRAPH_META_SEGMENT) {\n\t\tthrow new Error(\n\t\t\t`Graph \"${graphName}\": ${label} name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`,\n\t\t);\n\t}\n\tassertNoControlChars(name, graphName, label);\n}\n\nfunction splitPath(path: string, graphName: string): string[] {\n\tif (path === \"\") {\n\t\tthrow new Error(`Graph \"${graphName}\": resolve path must be non-empty`);\n\t}\n\tconst segments = path.split(PATH_SEP);\n\tfor (const s of segments) {\n\t\tif (s === \"\") {\n\t\t\tthrow new Error(`Graph \"${graphName}\": resolve path has empty segment`);\n\t\t}\n\t}\n\treturn segments;\n}\n\n/**\n * Strip messages that are not marked `metaPassthrough` on the given config\n * (spec §2.3 Companion lifecycle). Built-ins: `INVALIDATE`, `COMPLETE`,\n * `ERROR`, `TEARDOWN` are registered `metaPassthrough: false` in\n * `registerBuiltins`. Custom types default to `true` (meta receives them).\n *\n * To target a meta node directly without the filter, call `meta.down(...)`.\n *\n * Returns empty array when nothing remains.\n */\nfunction filterMetaMessages(messages: Messages, config: GraphReFlyConfig): Messages {\n\t// Fast path: if every message is metaPassthrough, reuse the input array.\n\tlet anyFiltered = false;\n\tfor (const m of messages) {\n\t\tif (!config.isMetaPassthrough(m[0])) {\n\t\t\tanyFiltered = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!anyFiltered) return messages;\n\tconst kept = messages.filter((m) => config.isMetaPassthrough(m[0]));\n\treturn kept as unknown as Messages;\n}\n\n/**\n * TEARDOWN every node in a mounted graph tree (depth-first into mounts).\n * Errors from individual node teardowns are swallowed — a single bad handler\n * must not abort cleanup of the rest of the subtree.\n */\nfunction teardownMountedGraph(root: Graph): void {\n\tfor (const child of root._mounts.values()) {\n\t\tteardownMountedGraph(child);\n\t}\n\tfor (const n of root._nodes.values()) {\n\t\ttry {\n\t\t\tn.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\t} catch {\n\t\t\t/* resilience: keep tearing down siblings */\n\t\t}\n\t}\n}\n\n/**\n * Named container for nodes and explicit edges (GRAPHREFLY-SPEC §3.1–§3.7).\n *\n * Qualified paths use `::` as the segment separator (for example `parent::child::node`).\n *\n * Edges are pure wires: `connect` only validates wiring — the target must already list the source in\n * its dependency array; no transforms run on the edge.\n *\n * @example\n * ```ts\n * import { Graph, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const g = new Graph(\"app\");\n * g.add(\"counter\", state(0));\n * ```\n *\n * @category graph\n */\nexport class Graph {\n\treadonly name: string;\n\treadonly opts: Readonly<GraphOptions>;\n\t/** Protocol config bound to this graph (defaults to `defaultConfig`). */\n\treadonly config: GraphReFlyConfig;\n\t/** @internal — exposed for {@link teardownMountedGraph} and cross-graph helpers. */\n\treadonly _nodes = new Map<string, Node>();\n\t/**\n\t * @internal Reverse lookup for duplicate-instance detection in\n\t * {@link Graph.add} — O(1) replacement for an O(n) scan of `_nodes`.\n\t * Weak so nodes can be GC'd after `remove()` even if a caller keeps the\n\t * map alive via some unusual pattern.\n\t */\n\tprivate readonly _nodeToName = new WeakMap<Node, string>();\n\t/** @internal — exposed for {@link teardownMountedGraph}. */\n\treadonly _mounts = new Map<string, Graph>();\n\t/**\n\t * @internal Parent graph if this instance is mounted. `undefined` when\n\t * this is the root or when the graph has been unmounted. Used for\n\t * reparenting rejection + O(depth) ancestor walks.\n\t */\n\t_parent: Graph | undefined = undefined;\n\tprivate readonly _storageDisposers = new Set<() => void>();\n\tprivate readonly _disposers = new Set<() => void>();\n\t/**\n\t * @internal Lazy `TopologyEvent` producer. Created on first `.topology`\n\t * access. Zero cost until something subscribes — producer fn only runs when\n\t * the first sink attaches, registering one handler into\n\t * {@link Graph._topologyEmitters}.\n\t */\n\tprivate _topology: Node<TopologyEvent> | undefined;\n\t/**\n\t * @internal Active emit handlers for the topology producer. Each entry is\n\t * the closure registered by the producer fn on activation; cleared on\n\t * deactivation. `_emitTopology` broadcasts through every entry (there is at\n\t * most one per activation cycle of the producer).\n\t */\n\tprivate readonly _topologyEmitters = new Set<(event: TopologyEvent) => void>();\n\n\t/**\n\t * @param name - Non-empty graph id (must not contain `::` and must not\n\t * equal the reserved meta segment `__meta__`).\n\t * @param opts - See {@link GraphOptions}. Stored frozen on the instance.\n\t */\n\tconstructor(name: string, opts?: GraphOptions) {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(\"Graph name must be non-empty\");\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\tthrow new Error(`Graph name must not contain '${PATH_SEP}' (got \"${name}\")`);\n\t\t}\n\t\tif (name === GRAPH_META_SEGMENT) {\n\t\t\tthrow new Error(`Graph name \"${GRAPH_META_SEGMENT}\" is reserved for meta companion paths`);\n\t\t}\n\t\tthis.name = name;\n\t\tthis.opts = Object.freeze({ ...(opts ?? {}) });\n\t\tthis.config = opts?.config ?? defaultConfig;\n\t\tthis._traceRing = new RingBuffer<TraceEntry>(opts?.traceCapacity ?? 1000);\n\t\tif (opts?.versioning != null) {\n\t\t\t// No nodes yet, but keep the API consistent — apply at construction\n\t\t\t// so opts.versioning is honored as a startup default via this helper.\n\t\t\tthis.setVersioning(opts.versioning);\n\t\t}\n\t}\n\n\t/**\n\t * Walk ancestors up through `_parent`. Returns the chain starting at this\n\t * instance, ending at the root (a graph with no parent). O(depth).\n\t *\n\t * @param includeSelf - Include `this` in the chain (default `true`).\n\t */\n\tancestors(includeSelf = true): Graph[] {\n\t\tconst out: Graph[] = [];\n\t\tlet p: Graph | undefined = includeSelf ? this : this._parent;\n\t\twhile (p != null) {\n\t\t\tout.push(p);\n\t\t\tp = p._parent;\n\t\t}\n\t\treturn out;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Topology companion (structural-change event stream)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Reactive stream of structural changes to this graph's own registry\n\t * (add / mount / remove). Value mutations live on `observe()`; this\n\t * companion only fires when the topology shape changes.\n\t *\n\t * Lazy: the underlying node is created on first access and activates when\n\t * something subscribes. No emission replay — late subscribers do not\n\t * receive historical events and should snapshot via {@link Graph.describe}\n\t * before listening for incremental changes. Events that fire while the\n\t * producer has zero subscribers are dropped (no retention).\n\t *\n\t * Own-graph only: a parent's `topology` does NOT emit for structural\n\t * changes inside a mounted child. Transitive consumers subscribe to each\n\t * child's topology separately (recurse through `topology`'s own \"added\"\n\t * events with `nodeKind: \"mount\"` to discover new children).\n\t *\n\t * See {@link TopologyEvent} for payload shape.\n\t *\n\t * @category observability\n\t */\n\tget topology(): Node<TopologyEvent> {\n\t\tif (this._topology == null) {\n\t\t\tthis._topology = producer<TopologyEvent>(\n\t\t\t\t(actions) => {\n\t\t\t\t\tconst handler = (event: TopologyEvent): void => {\n\t\t\t\t\t\tactions.emit(event);\n\t\t\t\t\t};\n\t\t\t\t\tthis._topologyEmitters.add(handler);\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tthis._topologyEmitters.delete(handler);\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\t{ name: `${this.name}_topology` },\n\t\t\t);\n\t\t}\n\t\treturn this._topology;\n\t}\n\n\t/**\n\t * @internal Fire a {@link TopologyEvent} to every active subscriber of\n\t * `this.topology`. No-op when the topology node has never been accessed or\n\t * currently has no sinks — zero cost for graphs nobody observes.\n\t */\n\tprivate _emitTopology(event: TopologyEvent): void {\n\t\tif (this._topology == null || this._topologyEmitters.size === 0) return;\n\t\tfor (const h of this._topologyEmitters) h(event);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Node registry\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Registers a node under a local name. Fails if the name is already used,\n\t * reserved by a mount, the same node instance is already registered, or\n\t * the node is torn down.\n\t *\n\t * Returns the registered node so callers can chain:\n\t * `const counter = g.add(\"counter\", state(0))`.\n\t *\n\t * @param name - Local key (no `::`).\n\t * @param node - Node instance to own.\n\t */\n\tadd<T extends Node>(name: string, node: T): T {\n\t\tassertRegisterableName(name, this.name, \"add\");\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": name \"${name}\" is already a mount point`);\n\t\t}\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node \"${name}\" already exists`);\n\t\t}\n\t\tconst existingName = this._nodeToName.get(node);\n\t\tif (existingName !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": node instance already registered as \"${existingName}\"`,\n\t\t\t);\n\t\t}\n\t\tthis._nodes.set(name, node);\n\t\tthis._nodeToName.set(node, name);\n\t\t// Edges are derived on demand from node `_deps` (see `edges()`) — no\n\t\t// stored registry to keep in sync. See Unit 7 of the graph review.\n\t\tthis._emitTopology({ kind: \"added\", name, nodeKind: \"node\" });\n\t\treturn node;\n\t}\n\n\t/**\n\t * Bulk-apply a minimum versioning level to every currently-registered node\n\t * in this graph (roadmap §6.0). `_applyVersioning` is monotonic — nodes\n\t * already at a higher level are untouched. The method refuses to run\n\t * mid-wave; invoke at setup time before any external subscribers attach.\n\t *\n\t * **Not** a default-for-future-adds mechanism — that's what\n\t * `config.defaultVersioning` is for. Nodes added after this call do NOT\n\t * automatically inherit `level`; register new nodes with their own\n\t * `opts.versioning` or set `config.defaultVersioning` before construction.\n\t *\n\t * **Scope:** local only. Does not propagate to mounted subgraphs.\n\t *\n\t * @param level - `0` for V0, `1` for V1, or `undefined` to no-op.\n\t */\n\tsetVersioning(level: VersioningLevel | undefined): void {\n\t\tif (level == null) return;\n\t\tfor (const node of this._nodes.values()) {\n\t\t\tif (node instanceof NodeImpl) {\n\t\t\t\tnode._applyVersioning(level);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters a node or unmounts a subgraph and sends `[[TEARDOWN]]` to the\n\t * removed node or recursively through the mounted subtree (§3.2).\n\t *\n\t * @param name - Local mount or node name.\n\t * @returns Audit record of what was removed: `{kind, nodes, mounts}`.\n\t * `kind: \"node\"` → `nodes: [name]`, `mounts: []`. `kind: \"mount\"` →\n\t * `nodes` lists every primary node torn down across the subtree (sorted\n\t * qualified paths relative to the unmounted subgraph) and `mounts` lists\n\t * the mounted subgraphs in depth-first order including `name` itself.\n\t */\n\tremove(name: string): GraphRemoveAudit {\n\t\tassertRegisterableName(name, this.name, \"remove\");\n\n\t\t// Case 1: unmount a subgraph\n\t\tconst child = this._mounts.get(name);\n\t\tif (child) {\n\t\t\tconst audit: GraphRemoveAudit = { kind: \"mount\", nodes: [], mounts: [] };\n\t\t\tconst targets: [string, Node][] = [];\n\t\t\tchild._collectObserveTargets(\"\", targets);\n\t\t\tfor (const [p, n] of targets) {\n\t\t\t\t// Only primary nodes (not meta companions) — meta cascades via\n\t\t\t\t// the primary's TEARDOWN.\n\t\t\t\tif (!p.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`)) {\n\t\t\t\t\taudit.nodes.push(p);\n\t\t\t\t}\n\t\t\t\tvoid n;\n\t\t\t}\n\t\t\taudit.nodes.sort();\n\t\t\taudit.mounts.push(name);\n\t\t\taudit.mounts.push(...child._collectSubgraphs(`${name}${PATH_SEP}`));\n\t\t\tthis._mounts.delete(name);\n\t\t\tchild._parent = undefined;\n\t\t\tteardownMountedGraph(child);\n\t\t\tthis._emitTopology({ kind: \"removed\", name, nodeKind: \"mount\", audit });\n\t\t\treturn audit;\n\t\t}\n\n\t\t// Case 2: remove a local node\n\t\tconst node = this._nodes.get(name);\n\t\tif (!node) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node or mount \"${name}\"`);\n\t\t}\n\t\tthis._nodes.delete(name);\n\t\tthis._nodeToName.delete(node);\n\t\tnode.down([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tconst audit: GraphRemoveAudit = { kind: \"node\", nodes: [name], mounts: [] };\n\t\tthis._emitTopology({ kind: \"removed\", name, nodeKind: \"node\", audit });\n\t\treturn audit;\n\t}\n\n\t/**\n\t * Bulk remove — invokes {@link Graph.remove} for every local name matching\n\t * `filter`. Audit records merge into a single result. Mounted subgraphs\n\t * are included via `filter` receiving the mount name; internal subtree\n\t * entries are not walked directly (use describe + scan for tree-level\n\t * queries).\n\t *\n\t * @param filter - Predicate or glob. Glob strings support `*` within a\n\t * segment and `**` across segments (same grammar as `restore({only})`).\n\t * @returns Combined audit of all nodes + mounts removed.\n\t */\n\tremoveAll(filter: ((name: string) => boolean) | string): GraphRemoveAudit {\n\t\tconst match =\n\t\t\ttypeof filter === \"function\"\n\t\t\t\t? filter\n\t\t\t\t: (() => {\n\t\t\t\t\t\tconst re = globToRegex(filter);\n\t\t\t\t\t\treturn (n: string) => re.test(n);\n\t\t\t\t\t})();\n\t\tconst audit: GraphRemoveAudit = { kind: \"mount\", nodes: [], mounts: [] };\n\t\t// Snapshot names first — remove mutates the maps.\n\t\tconst localNames = [...this._nodes.keys(), ...this._mounts.keys()].filter((n) => match(n));\n\t\tfor (const name of localNames) {\n\t\t\tconst sub = this.remove(name);\n\t\t\taudit.nodes.push(...sub.nodes);\n\t\t\taudit.mounts.push(...sub.mounts);\n\t\t}\n\t\taudit.nodes.sort();\n\t\taudit.mounts.sort();\n\t\treturn audit;\n\t}\n\n\t/**\n\t * Iterable over locally-registered `[localName, Node]` pairs (sorted).\n\t * Does not recurse into mounts.\n\t */\n\t[Symbol.iterator](): IterableIterator<[string, Node]> {\n\t\tconst sorted = [...this._nodes.keys()].sort();\n\t\tconst nodes = this._nodes;\n\t\tlet i = 0;\n\t\treturn {\n\t\t\t[Symbol.iterator]() {\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tnext(): IteratorResult<[string, Node]> {\n\t\t\t\tif (i >= sorted.length) return { value: undefined, done: true };\n\t\t\t\tconst name = sorted[i++];\n\t\t\t\treturn { value: [name, nodes.get(name)!], done: false };\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Returns a node by local name or `::` qualified path.\n\t * Local names are looked up directly; paths with `::` delegate to {@link resolve}.\n\t *\n\t * @param name - Local name or qualified path.\n\t */\n\tnode(name: string): Node {\n\t\tif (name === \"\") {\n\t\t\tthrow new Error(`Graph \"${this.name}\": node name must be non-empty`);\n\t\t}\n\t\tif (name.includes(PATH_SEP)) {\n\t\t\treturn this.resolve(name);\n\t\t}\n\t\tconst n = this._nodes.get(name);\n\t\tif (!n) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown node \"${name}\"`);\n\t\t}\n\t\treturn n;\n\t}\n\n\t/**\n\t * Reads `graph.node(name).get()` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @returns Cached value or `undefined`.\n\t */\n\tget(name: string): unknown {\n\t\treturn this.node(name).cache;\n\t}\n\n\t/**\n\t * Shorthand for `graph.node(name).down([[DATA, value]], { actor })` — accepts `::` qualified paths (§3.2).\n\t *\n\t * @param name - Local name or qualified path.\n\t * @param value - Next `DATA` payload.\n\t * @param options - Optional `actor` and `internal` guard bypass.\n\t */\n\tset(name: string, value: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[DATA, value]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t/**\n\t * Atomic multi-node DATA write. Wraps every {@link Graph.set} call in a\n\t * single `batch(...)` so downstream dependents see one coalesced wave\n\t * instead of N cascading ones.\n\t *\n\t * @param entries - `{name → value}` map or `[name, value]` pairs.\n\t * @param options - Passed to each underlying `set` call (same `actor` + `internal` semantics).\n\t */\n\tsetAll(\n\t\tentries: Record<string, unknown> | Iterable<readonly [string, unknown]>,\n\t\toptions?: GraphActorOptions,\n\t): void {\n\t\tconst iter: Iterable<readonly [string, unknown]> =\n\t\t\tSymbol.iterator in entries\n\t\t\t\t? (entries as Iterable<readonly [string, unknown]>)\n\t\t\t\t: Object.entries(entries as Record<string, unknown>);\n\t\tbatch(() => {\n\t\t\tfor (const [name, value] of iter) this.set(name, value, options);\n\t\t});\n\t}\n\n\t/**\n\t * Emit a single `[[INVALIDATE]]` (tier 1) on a node. Thin wrapper over\n\t * `node.down([[INVALIDATE]], …)` matching the {@link Graph.set} ergonomics.\n\t */\n\tinvalidate(name: string, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[INVALIDATE]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t/**\n\t * Emit a single `[[ERROR, err]]` (tier 4) on a node.\n\t */\n\terror(name: string, err: unknown, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[ERROR, err]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t/**\n\t * Emit a single `[[COMPLETE]]` (tier 4) on a node, declaring the stream\n\t * cleanly finished. Distinct from {@link Graph.remove} (which emits\n\t * TEARDOWN and unregisters the node).\n\t */\n\tcomplete(name: string, options?: GraphActorOptions): void {\n\t\tconst internal = options?.internal === true;\n\t\tthis.node(name).down([[COMPLETE]] satisfies Messages, {\n\t\t\tactor: options?.actor,\n\t\t\tinternal,\n\t\t\tdelivery: \"write\",\n\t\t});\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Edges (derived on-demand from node `_deps`)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Returns the full edge list for this graph tree, derived on demand from\n\t * each registered node's `_deps` (no stored registry). Local-only\n\t * (non-recursive) by default to match the historical `edges()` surface;\n\t * pass `{recursive: true}` to include mounted subgraphs with qualified\n\t * paths relative to this graph.\n\t *\n\t * Use {@link Graph.describe} for full-tree snapshots with edges already\n\t * qualified and paired with node metadata.\n\t */\n\tedges(opts?: { recursive?: boolean }): ReadonlyArray<[string, string]> {\n\t\tconst recursive = opts?.recursive === true;\n\t\tconst nodeToLocal = new Map<Node, string>();\n\t\tif (!recursive) {\n\t\t\tfor (const [localName, n] of this._nodes) nodeToLocal.set(n, localName);\n\t\t\tconst result: [string, string][] = [];\n\t\t\tfor (const [localName, n] of this._nodes) {\n\t\t\t\tif (!(n instanceof NodeImpl)) continue;\n\t\t\t\tfor (const dep of n._deps) {\n\t\t\t\t\tconst from = nodeToLocal.get(dep.node);\n\t\t\t\t\tif (from != null) result.push([from, localName]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult.sort((a, b) =>\n\t\t\t\ta[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0,\n\t\t\t);\n\t\t\treturn result;\n\t\t}\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) nodeToPath.set(n, p);\n\t\tconst result: [string, string][] = [];\n\t\tfor (const [path, n] of targets) {\n\t\t\tif (!(n instanceof NodeImpl)) continue;\n\t\t\tfor (const dep of n._deps) {\n\t\t\t\tconst from = nodeToPath.get(dep.node);\n\t\t\t\tif (from != null) result.push([from, path]);\n\t\t\t}\n\t\t}\n\t\tresult.sort((a, b) =>\n\t\t\ta[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0,\n\t\t);\n\t\treturn result;\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Composition\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Embed a child graph at a local mount name (§3.4). Child nodes are reachable via\n\t * {@link Graph.resolve} using `::` delimited paths (§3.5). Lifecycle\n\t * {@link Graph.signal} visits mounted subgraphs recursively.\n\t *\n\t * Rejects: same name as existing node or mount, self-mount, mount cycles,\n\t * and the same child graph instance mounted twice on one parent.\n\t *\n\t * @param name - Local mount point.\n\t * @param child - Nested `Graph` instance.\n\t * @returns The mounted `child`, for chaining.\n\t */\n\tmount<G extends Graph>(name: string, child: G): G {\n\t\tassertRegisterableName(name, this.name, \"mount\");\n\t\tif (this._nodes.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": cannot mount at \"${name}\" — node with that name exists`,\n\t\t\t);\n\t\t}\n\t\tif (this._mounts.has(name)) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": mount \"${name}\" already exists`);\n\t\t}\n\t\tif ((child as Graph) === this) {\n\t\t\tthrow new Error(`Graph \"${this.name}\": cannot mount a graph into itself`);\n\t\t}\n\t\t// Reject reparenting (Unit 6 B): same child instance may only be\n\t\t// mounted once across the entire tree. Cheap O(1) check via the\n\t\t// back-pointer (replaces both the \"mounted twice on this parent\"\n\t\t// loop AND the O(G) cycle DFS).\n\t\tif (child._parent != null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": this child graph is already mounted on \"${child._parent.name}\"`,\n\t\t\t);\n\t\t}\n\t\t// Cycle rejection — walk UP from `this` to detect if we are already in\n\t\t// `child`'s descendant tree. O(depth), independent of tree size.\n\t\tfor (let p: Graph | undefined = this; p != null; p = p._parent) {\n\t\t\tif (p === (child as Graph)) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": mount(\"${name}\", …) would create a mount cycle`);\n\t\t\t}\n\t\t}\n\t\tthis._mounts.set(name, child);\n\t\tchild._parent = this;\n\t\tthis._emitTopology({ kind: \"added\", name, nodeKind: \"mount\" });\n\t\treturn child;\n\t}\n\n\t/**\n\t * Look up a node by qualified path (§3.5). Segments are separated by `::`.\n\t *\n\t * If the first segment equals this graph's {@link Graph.name}, it is stripped\n\t * (so `root.resolve(\"app::a\")` works when `root.name === \"app\"`). The strip\n\t * is applied **recursively** when descending into mounted children, so\n\t * `child.resolve(\"child::x\")` also works when `child.name === \"child\"`.\n\t *\n\t * @param path - Qualified `::` path or local name.\n\t * @returns The resolved `Node`.\n\t */\n\tresolve(path: string): Node {\n\t\tconst segments = splitPath(path, this.name);\n\t\treturn this._resolveFromSegments(segments);\n\t}\n\n\t/**\n\t * Non-throwing {@link Graph.resolve}. Returns `undefined` instead of\n\t * throwing when the path does not resolve to a node.\n\t */\n\ttryResolve(path: string): Node | undefined {\n\t\ttry {\n\t\t\treturn this.resolve(path);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _resolveFromSegments(segments: readonly string[]): Node {\n\t\t// Recursive self-name strip: if the first segment equals this graph's\n\t\t// own name, peel it off. Applied at every recursion level so nested\n\t\t// resolution of `child::x` inside `child` works uniformly.\n\t\tlet seg = segments;\n\t\tif (seg[0] === this.name) {\n\t\t\tseg = seg.slice(1);\n\t\t\tif (seg.length === 0) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": resolve path ends at graph name only`);\n\t\t\t}\n\t\t}\n\t\tconst head = seg[0] as string;\n\t\tconst rest = seg.slice(1);\n\n\t\tif (rest.length === 0) {\n\t\t\tconst n = this._nodes.get(head);\n\t\t\tif (n) return n;\n\t\t\tif (this._mounts.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": path ends at subgraph \"${head}\" — not a node (GRAPHREFLY-SPEC §3.5)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown name \"${head}\"`);\n\t\t}\n\n\t\tconst localN = this._nodes.get(head);\n\t\tif (localN && rest.length > 0 && rest[0] === GRAPH_META_SEGMENT) {\n\t\t\treturn this._resolveMetaChainFromNode(localN, rest, seg.join(PATH_SEP));\n\t\t}\n\n\t\tconst child = this._mounts.get(head);\n\t\tif (!child) {\n\t\t\tif (this._nodes.has(head)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": \"${head}\" is a node; trailing path \"${rest.join(PATH_SEP)}\" is invalid`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(`Graph \"${this.name}\": unknown mount or node \"${head}\"`);\n\t\t}\n\n\t\treturn child.resolve(rest.join(PATH_SEP));\n\t}\n\n\t/**\n\t * Resolve `::__meta__::key` segments from a registered primary node (possibly chained).\n\t */\n\tprivate _resolveMetaChainFromNode(n: Node, parts: readonly string[], fullPath: string): Node {\n\t\tlet current = n;\n\t\tlet i = 0;\n\t\tconst p = [...parts];\n\t\twhile (i < p.length) {\n\t\t\tif (p[i] !== GRAPH_META_SEGMENT) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": expected ${GRAPH_META_SEGMENT} segment in meta path \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (i + 1 >= p.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Graph \"${this.name}\": meta path requires a key after ${GRAPH_META_SEGMENT} in \"${fullPath}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = p[i + 1] as string;\n\t\t\tconst next = current.meta[key];\n\t\t\tif (!next) {\n\t\t\t\tthrow new Error(`Graph \"${this.name}\": unknown meta \"${key}\" in path \"${fullPath}\"`);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t\ti += 2;\n\t\t}\n\t\treturn current;\n\t}\n\n\t/**\n\t * Deliver a message batch to every registered node in this graph and, recursively,\n\t * in mounted child graphs (§3.7). Recurses into mounts first, then delivers to\n\t * local nodes (sorted by name). Each {@link Node} receives at most one delivery\n\t * per call (deduped by reference).\n\t *\n\t * **Primary-vs-meta filter asymmetry (intentional):** primary nodes receive the\n\t * unfiltered `messages` batch — that's the canonical data-plane flow. Companion\n\t * `meta` nodes receive a filtered subset keyed by the per-type `metaPassthrough`\n\t * flag on {@link GraphReFlyConfig}. Built-in defaults: PAUSE / RESUME / DATA /\n\t * RESOLVED pass through to meta; INVALIDATE / COMPLETE / ERROR / TEARDOWN do\n\t * not.\n\t *\n\t * **Where lifecycle terminals reach meta:**\n\t * - **TEARDOWN** — primary's `_emit` cascades to meta children directly (see\n\t * `core/node.ts` \"Meta TEARDOWN fan-out\" block) so meta is torn down with\n\t * its primary regardless of the signal-level filter.\n\t * - **COMPLETE / ERROR / INVALIDATE** — scoped to primaries on the broadcast\n\t * path. Meta companions are an attribution side-channel, not a lifecycle\n\t * participant; address meta directly via `meta.down(...)` if you need to\n\t * forward these. Audit confirmed 2026-04-17: no current meta consumer\n\t * relies on broadcast COMPLETE/ERROR/INVALIDATE delivery.\n\t *\n\t * @param messages - Batch to deliver to every registered node (and mounts, recursively).\n\t * @param options - Optional `actor` / `internal` for transport.\n\t */\n\tsignal(messages: Messages, options?: GraphActorOptions): void {\n\t\t// Reject tier ≥ 3 (DATA / RESOLVED / COMPLETE / ERROR / TEARDOWN when\n\t\t// called externally — destroy() routes through signal with\n\t\t// `{internal: true}` which bypasses this check). Broadcasting per-flow\n\t\t// values to every node in the tree is almost always a mistake.\n\t\tif (options?.internal !== true) {\n\t\t\tfor (const m of messages) {\n\t\t\t\tconst tier = this.config.messageTier(m[0]);\n\t\t\t\t// Tier 3 (DATA / RESOLVED) is per-flow state — broadcasting it\n\t\t\t\t// to every node overwrites unrelated caches. Tier 4/5 stays\n\t\t\t\t// allowed: ERROR/COMPLETE/TEARDOWN have legitimate broadcast\n\t\t\t\t// use (graceful shutdown, error cascade).\n\t\t\t\tif (tier === 3) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Graph \"${this.name}\": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). ` +\n\t\t\t\t\t\t\t`Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). ` +\n\t\t\t\t\t\t\t`For per-node value writes, use Graph.set or graph.node(name).down(...).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst errors: unknown[] = [];\n\t\tthis._signalDeliver(messages, options ?? {}, new Set(), errors);\n\t\t// Surface the first collected error so callers see failures without\n\t\t// aborting the rest of the broadcast. Guard denials are re-thrown\n\t\t// immediately in _signalDeliver (deliberate access-control rejections).\n\t\tif (errors.length > 0) throw errors[0];\n\t}\n\n\tprivate _signalDeliver(\n\t\tmessages: Messages,\n\t\topts: GraphActorOptions,\n\t\tvis: Set<Node>,\n\t\terrors: unknown[],\n\t): void {\n\t\tfor (const sub of this._mounts.values()) {\n\t\t\tsub._signalDeliver(messages, opts, vis, errors);\n\t\t}\n\t\tconst internal = opts.internal === true;\n\t\tconst downOpts: NodeTransportOptions = internal\n\t\t\t? { internal: true }\n\t\t\t: { actor: opts.actor, delivery: \"signal\" };\n\t\tconst metaMessages = filterMetaMessages(messages, this.config);\n\t\tfor (const localName of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(localName)!;\n\t\t\tif (vis.has(n)) continue;\n\t\t\tvis.add(n);\n\t\t\ttry {\n\t\t\t\tn.down(messages, downOpts);\n\t\t\t} catch (err) {\n\t\t\t\t// Guard denials bubble — they're deliberate rejections, not\n\t\t\t\t// resilience failures. Other errors collect so one bad handler\n\t\t\t\t// doesn't abort the rest of the broadcast.\n\t\t\t\tif (err instanceof GuardDenied) throw err;\n\t\t\t\terrors.push(err);\n\t\t\t}\n\t\t\tif (metaMessages.length === 0) continue;\n\t\t\tthis._signalMetaSubtree(n, metaMessages, vis, downOpts, errors);\n\t\t}\n\t}\n\n\tprivate _signalMetaSubtree(\n\t\troot: Node,\n\t\tmessages: Messages,\n\t\tvis: Set<Node>,\n\t\tdownOpts: NodeTransportOptions,\n\t\terrors: unknown[],\n\t): void {\n\t\tfor (const mk of Object.keys(root.meta).sort()) {\n\t\t\tconst mnode = root.meta[mk];\n\t\t\tif (vis.has(mnode)) continue;\n\t\t\tvis.add(mnode);\n\t\t\ttry {\n\t\t\t\tmnode.down(messages, downOpts);\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof GuardDenied) throw err;\n\t\t\t\terrors.push(err);\n\t\t\t}\n\t\t\tthis._signalMetaSubtree(mnode, messages, vis, downOpts, errors);\n\t\t}\n\t}\n\n\t/**\n\t * Static structure snapshot: qualified node keys, edges, mount names (GRAPHREFLY-SPEC §3.6, Appendix B).\n\t *\n\t * `format` controls the return type:\n\t * - omitted or `\"spec\"` → {@link GraphDescribeOutput} object.\n\t * - `\"json\"` / `\"pretty\"` / `\"mermaid\"` / `\"d2\"` → rendered string.\n\t *\n\t * @param options - Optional `actor` for guard-scoped visibility, `filter` for\n\t * selective output, or `format` to render.\n\t *\n\t * @example\n\t * ```ts\n\t * graph.describe() // full snapshot object\n\t * graph.describe({ filter: { status: \"errored\" } }) // filtered object\n\t * graph.describe({ format: \"pretty\" }) // human-readable text\n\t * graph.describe({ format: \"mermaid\" }) // Mermaid flowchart\n\t * graph.describe({ format: \"d2\", direction: \"TD\" }) // D2 top-down\n\t * ```\n\t */\n\tdescribe(\n\t\toptions: GraphDescribeOptions & { format: \"json\" | \"pretty\" | \"mermaid\" | \"d2\" },\n\t): string;\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput;\n\tdescribe(options?: GraphDescribeOptions): GraphDescribeOutput | string {\n\t\tconst actor = options?.actor;\n\t\tconst filter = options?.filter;\n\t\tconst includeFields = resolveDescribeFields(options?.detail, options?.fields);\n\t\tconst isSpec = options?.format === \"spec\";\n\t\t// For spec format, force minimal fields (type + deps only, no status/value)\n\t\tconst effectiveFields = isSpec ? resolveDescribeFields(\"minimal\") : includeFields;\n\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\tconst nodeToPath = new Map<Node, string>();\n\t\tfor (const [p, n] of targets) {\n\t\t\tnodeToPath.set(n, p);\n\t\t}\n\t\tconst nodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const [p, n] of targets) {\n\t\t\tif (actor != null && !n.allowsObserve(actor)) continue;\n\t\t\tconst raw = describeNode(n, effectiveFields);\n\t\t\tconst deps =\n\t\t\t\tn instanceof NodeImpl\n\t\t\t\t\t? n._deps.map((d) => nodeToPath.get(d.node) ?? d.node.name ?? \"\")\n\t\t\t\t\t: [];\n\t\t\tconst { name: _name, ...rest } = raw;\n\t\t\tconst entry: DescribeNodeOutput = { ...rest, deps };\n\t\t\t// Unit 14 A: attach reason annotation from `trace(path, reason)`\n\t\t\t// when one exists. Skipped for the `\"spec\"` format (input-schema\n\t\t\t// use case — annotations don't round-trip through GraphSpec).\n\t\t\tif (!isSpec) {\n\t\t\t\tconst reason = this._annotations.get(p);\n\t\t\t\tif (reason != null) entry.reason = reason;\n\t\t\t}\n\t\t\tif (filter != null) {\n\t\t\t\tif (typeof filter === \"function\") {\n\t\t\t\t\tconst fn = filter as\n\t\t\t\t\t\t| ((nodePath: string, node: DescribeNodeOutput) => boolean)\n\t\t\t\t\t\t| ((node: DescribeNodeOutput) => boolean);\n\t\t\t\t\tconst pass =\n\t\t\t\t\t\tfn.length >= 2\n\t\t\t\t\t\t\t? (fn as (nodePath: string, node: DescribeNodeOutput) => boolean)(p, entry)\n\t\t\t\t\t\t\t: (fn as (node: DescribeNodeOutput) => boolean)(entry);\n\t\t\t\t\tif (!pass) continue;\n\t\t\t\t} else {\n\t\t\t\t\tlet match = true;\n\t\t\t\t\tfor (const [fk, fv] of Object.entries(filter)) {\n\t\t\t\t\t\tconst normalizedKey =\n\t\t\t\t\t\t\tfk === \"deps_includes\" ? \"depsIncludes\" : fk === \"meta_has\" ? \"metaHas\" : fk;\n\t\t\t\t\t\tif (normalizedKey === \"depsIncludes\") {\n\t\t\t\t\t\t\tif (!entry.deps.includes(String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (normalizedKey === \"metaHas\") {\n\t\t\t\t\t\t\tif (!Object.hasOwn(entry.meta ?? {}, String(fv))) {\n\t\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((entry as Record<string, unknown>)[normalizedKey] !== fv) {\n\t\t\t\t\t\t\tmatch = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!match) continue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodes[p] = entry;\n\t\t}\n\t\tconst nodeKeys = new Set(Object.keys(nodes));\n\t\t// Edges are derived from node `_deps` via `edges({recursive: true})`\n\t\t// (sorted, fully qualified relative to this graph).\n\t\tlet edges: { from: string; to: string }[] = this.edges({ recursive: true }).map(\n\t\t\t([from, to]) => ({ from, to }),\n\t\t);\n\t\tif (actor != null || filter != null) {\n\t\t\tedges = edges.filter((e) => nodeKeys.has(e.from) && nodeKeys.has(e.to));\n\t\t}\n\t\tconst allSubgraphs = this._collectSubgraphs(\"\");\n\t\tconst subgraphs =\n\t\t\tactor != null || filter != null\n\t\t\t\t? allSubgraphs.filter((sg) => {\n\t\t\t\t\t\tconst prefix = `${sg}${PATH_SEP}`;\n\t\t\t\t\t\treturn [...nodeKeys].some((k) => k === sg || k.startsWith(prefix));\n\t\t\t\t\t})\n\t\t\t\t: allSubgraphs;\n\n\t\t// Capture graph ref and base options for expand()\n\t\tconst graph = this;\n\t\tconst baseOpts = options;\n\n\t\tconst struct: GraphDescribeOutput = {\n\t\t\tname: this.name,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t\tsubgraphs,\n\t\t\texpand(detailOrFields: DescribeDetail | DescribeField[]): GraphDescribeOutput {\n\t\t\t\tconst merged: GraphDescribeOptions = { ...baseOpts, format: undefined };\n\t\t\t\tif (Array.isArray(detailOrFields)) {\n\t\t\t\t\tmerged.fields = detailOrFields;\n\t\t\t\t\tmerged.detail = undefined;\n\t\t\t\t} else {\n\t\t\t\t\tmerged.detail = detailOrFields;\n\t\t\t\t\tmerged.fields = undefined;\n\t\t\t\t}\n\t\t\t\treturn graph.describe(merged);\n\t\t\t},\n\t\t};\n\n\t\t// Text-format dispatch. `\"spec\"` and undefined return the struct as-is.\n\t\tconst opts = options ?? {};\n\t\tconst fmt = opts.format;\n\t\tif (fmt === \"json\") return renderDescribeAsJson(struct, opts);\n\t\tif (fmt === \"pretty\") return renderDescribeAsPretty(struct, opts);\n\t\tif (fmt === \"mermaid\") return renderDescribeAsMermaid(struct, opts);\n\t\tif (fmt === \"d2\") return renderDescribeAsD2(struct, opts);\n\t\treturn struct;\n\t}\n\n\tprivate _collectSubgraphs(prefix: string): string[] {\n\t\tconst out: string[] = [];\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst q = prefix === \"\" ? m : `${prefix}${m}`;\n\t\t\tout.push(q);\n\t\t\tout.push(...this._mounts.get(m)!._collectSubgraphs(`${q}${PATH_SEP}`));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Snapshot-based resource profile: per-node stats, orphan effect detection,\n\t * memory hotspots. Zero runtime overhead — walks nodes on demand.\n\t *\n\t * @param opts - Optional `topN` for hotspot limit (default 10).\n\t * @returns Aggregate profile with per-node details, hotspots, and orphan effects.\n\t */\n\tresourceProfile(opts?: GraphProfileOptions): GraphProfileResult {\n\t\treturn graphProfile(this, opts);\n\t}\n\n\t/**\n\t * Reachability query rooted at `from`. Instance convenience — wraps\n\t * `reachable(this.describe(), from, direction, opts)`. See\n\t * {@link reachable} for semantics.\n\t */\n\treachable(\n\t\tfrom: string,\n\t\tdirection: ReachableDirection,\n\t\topts: ReachableOptions & { withDetail: true },\n\t): ReachableResult;\n\treachable(from: string, direction: ReachableDirection, opts?: ReachableOptions): string[];\n\treachable(\n\t\tfrom: string,\n\t\tdirection: ReachableDirection,\n\t\topts: ReachableOptions = {},\n\t): string[] | ReachableResult {\n\t\tif (opts.withDetail === true) {\n\t\t\treturn reachable(this.describe(), from, direction, {\n\t\t\t\t...opts,\n\t\t\t\twithDetail: true,\n\t\t\t});\n\t\t}\n\t\treturn reachable(this.describe(), from, direction, opts);\n\t}\n\n\t/**\n\t * Causal walkback: shortest dep-chain from `from` to `to`, enriched with\n\t * each node's value, status, last-mutation actor, and reasoning annotation\n\t * from {@link Graph.trace}. Wraps {@link explainPath} (roadmap §9.2).\n\t *\n\t * @param from - Upstream node (the cause).\n\t * @param to - Downstream node (the effect).\n\t * @param opts - Optional `maxDepth` and `findCycle`. When `findCycle:true`\n\t * and `from === to`, returns the shortest cycle through other nodes\n\t * (useful for diagnosing feedback loops, COMPOSITION-GUIDE §7).\n\t * Annotations and lastMutations are collected automatically from the\n\t * live graph.\n\t */\n\texplain(\n\t\tfrom: string,\n\t\tto: string,\n\t\topts?: { maxDepth?: number; findCycle?: boolean },\n\t): CausalChain {\n\t\t// `detail: \"full\"` includes `value`, `status`, `lastMutation`, `v`, etc.\n\t\t// — everything `explainPath` enriches each step with.\n\t\tconst described = this.describe({ detail: \"full\" });\n\t\tconst annotations = new Map<string, string>(this._annotations);\n\t\tconst lastMutations = new Map<string, Readonly<{ actor: Actor; timestamp_ns: number }>>();\n\t\tfor (const [path, n] of Object.entries(described.nodes)) {\n\t\t\tif (n.lastMutation != null) lastMutations.set(path, n.lastMutation);\n\t\t}\n\t\treturn explainPath(described, from, to, {\n\t\t\t...(opts?.maxDepth != null ? { maxDepth: opts.maxDepth } : {}),\n\t\t\t...(opts?.findCycle === true ? { findCycle: true as const } : {}),\n\t\t\tannotations,\n\t\t\tlastMutations,\n\t\t});\n\t}\n\n\t/**\n\t * @internal Collect all qualified paths in this graph tree matching a\n\t * glob pattern. Used by scoped autoCheckpoint subscription.\n\t */\n\tprivate _pathsMatching(glob: string): string[] {\n\t\tconst re = globToRegex(glob);\n\t\tconst targets: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", targets);\n\t\treturn targets.map(([p]) => p).filter((p) => re.test(p));\n\t}\n\n\tprivate _collectObserveTargets(prefix: string, out: [string, Node][]): void {\n\t\tfor (const m of [...this._mounts.keys()].sort()) {\n\t\t\tconst p2 = prefix === \"\" ? m : `${prefix}${PATH_SEP}${m}`;\n\t\t\tthis._mounts.get(m)!._collectObserveTargets(p2, out);\n\t\t}\n\t\tfor (const loc of [...this._nodes.keys()].sort()) {\n\t\t\tconst n = this._nodes.get(loc)!;\n\t\t\tconst p = prefix === \"\" ? loc : `${prefix}${PATH_SEP}${loc}`;\n\t\t\tout.push([p, n]);\n\t\t\tthis._appendMetaObserveTargets(p, n, out);\n\t\t}\n\t}\n\n\tprivate _appendMetaObserveTargets(basePath: string, n: Node, out: [string, Node][]): void {\n\t\tfor (const mk of Object.keys(n.meta).sort()) {\n\t\t\tconst m = n.meta[mk];\n\t\t\tconst mp = `${basePath}${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}${mk}`;\n\t\t\tout.push([mp, m]);\n\t\t\tthis._appendMetaObserveTargets(mp, m, out);\n\t\t}\n\t}\n\n\t/**\n\t * Live message stream from one node (or meta path), or from the whole graph (§3.6).\n\t *\n\t * Two modes dispatched on first argument:\n\t * - `observe(path, options?)` — one node. Returns {@link GraphObserveOne}\n\t * (raw stream), or {@link ObserveResult} when `options` requests structured\n\t * accumulation (`structured`, `timeline`, `causal`, `derived`, `format`,\n\t * `detail: \"minimal\"|\"full\"`).\n\t * - `observe(options?)` — all nodes. Returns {@link GraphObserveAll} (raw),\n\t * or {@link ObserveResult} under the same structured trigger conditions.\n\t *\n\t * Structured mode subscribes in sorted path order (code-point). Inspector\n\t * extras (`causal`/`derived`) require `graph.config.inspectorEnabled`;\n\t * when disabled, those fields silently drop and the rest still works.\n\t *\n\t * `ObserveResult` is also an `AsyncIterable<ObserveEvent>` — use\n\t * `for await (const ev of result)` for pull-based consumption.\n\t */\n\tobserve(path: string, options?: ObserveOptions & StructuredTriggers): ObserveResult;\n\tobserve(path: string, options?: ObserveOptions): GraphObserveOne;\n\tobserve(options: ObserveOptions & StructuredTriggers): ObserveResult;\n\tobserve(options?: ObserveOptions): GraphObserveAll;\n\tobserve(\n\t\tpathOrOpts?: string | ObserveOptions,\n\t\toptions?: ObserveOptions,\n\t): GraphObserveOne | GraphObserveAll | ObserveResult {\n\t\tconst isPath = typeof pathOrOpts === \"string\";\n\t\tconst rawOpts = isPath ? options : (pathOrOpts as ObserveOptions | undefined);\n\t\tconst resolved = resolveObserveDetail(rawOpts);\n\t\tconst wantsStructured =\n\t\t\tresolved.structured === true ||\n\t\t\tresolved.timeline === true ||\n\t\t\tresolved.causal === true ||\n\t\t\tresolved.derived === true ||\n\t\t\tresolved.detail === \"minimal\" ||\n\t\t\tresolved.detail === \"full\" ||\n\t\t\tresolved.format != null;\n\t\tconst actor = resolved.actor;\n\n\t\tif (isPath) {\n\t\t\tconst path = pathOrOpts as string;\n\t\t\tconst target = this.resolve(path);\n\t\t\tif (actor != null && !target.allowsObserve(actor)) {\n\t\t\t\tthrow new GuardDenied({ actor, action: \"observe\", nodeName: path });\n\t\t\t}\n\t\t\tif (wantsStructured) return this._buildStructuredObserver([[path, target]], resolved, \"one\");\n\t\t\treturn {\n\t\t\t\tsubscribe(sink: NodeSink) {\n\t\t\t\t\treturn target.subscribe(sink);\n\t\t\t\t},\n\t\t\t\tup(messages: Messages) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttarget.up?.(messages);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (err instanceof GuardDenied) return;\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst collected: [string, Node][] = [];\n\t\tthis._collectObserveTargets(\"\", collected);\n\t\tcollected.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst picked =\n\t\t\tactor == null ? collected : collected.filter(([, nd]) => nd.allowsObserve(actor));\n\t\tif (wantsStructured) return this._buildStructuredObserver(picked, resolved, \"all\");\n\t\treturn {\n\t\t\tsubscribe: (sink: (nodePath: string, messages: Messages) => void) => {\n\t\t\t\tconst unsubs = picked.map(([p, nd]) =>\n\t\t\t\t\tnd.subscribe((msgs) => {\n\t\t\t\t\t\tsink(p, msgs);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const u of unsubs) u();\n\t\t\t\t};\n\t\t\t},\n\t\t\tup: (upPath: string, messages: Messages) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst nd = this.resolve(upPath);\n\t\t\t\t\tnd.up?.(messages);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tif (err instanceof GuardDenied) return;\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Dispatch helper — builds a unified observer + its expand closure. */\n\tprivate _buildStructuredObserver<T>(\n\t\ttargets: ReadonlyArray<[string, Node]>,\n\t\toptions: ObserveOptions,\n\t\tmode: \"one\" | \"all\",\n\t): ObserveResult<T> {\n\t\tconst firstPath = mode === \"one\" ? targets[0]?.[0] : undefined;\n\t\tconst expand = (merged: ObserveOptions): ObserveResult<T> => {\n\t\t\tif (mode === \"one\" && firstPath != null) {\n\t\t\t\tconst target = this.resolve(firstPath);\n\t\t\t\treturn this._buildStructuredObserver([[firstPath, target]], merged, \"one\");\n\t\t\t}\n\t\t\tconst collected: [string, Node][] = [];\n\t\t\tthis._collectObserveTargets(\"\", collected);\n\t\t\tcollected.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\t\tconst actor = merged.actor;\n\t\t\tconst picked =\n\t\t\t\tactor == null ? collected : collected.filter(([, nd]) => nd.allowsObserve(actor));\n\t\t\treturn this._buildStructuredObserver(picked, merged, \"all\");\n\t\t};\n\t\treturn this._createObserveResult<T>(targets, options, expand);\n\t}\n\n\t/**\n\t * Unified observer builder — replaces the four ex-creators\n\t * (`_createObserveResult` / `...ForAll` / `_createFallback…`). Accepts a\n\t * list of `[path, node]` targets (single-element for one-node observe,\n\t * N-element for all-nodes). Inspector hooks attach per-target when\n\t * `causal`/`derived` requested AND `config.inspectorEnabled`; otherwise\n\t * those fields gracefully drop.\n\t *\n\t * Events flow through a `recordEvent()` helper so the format logger,\n\t * ring-buffer, and async-iterable hooks all share one push path.\n\t */\n\tprivate _createObserveResult<T>(\n\t\ttargets: ReadonlyArray<[string, Node]>,\n\t\toptions: ObserveOptions,\n\t\texpand: (merged: ObserveOptions) => ObserveResult<T>,\n\t): ObserveResult<T> {\n\t\tconst timeline = options.timeline === true;\n\t\tconst causal = options.causal === true;\n\t\tconst derived = options.derived === true;\n\t\tconst minimal = options.detail === \"minimal\";\n\t\tconst inspectorOn = this.config.inspectorEnabled;\n\t\tconst wantInspector = (causal || derived) && inspectorOn;\n\n\t\t// Event buffer: unbounded array, or RingBuffer when maxEvents capped.\n\t\tconst maxEvents = options.maxEvents;\n\t\tconst ring =\n\t\t\tmaxEvents != null && maxEvents > 0 ? new RingBuffer<ObserveEvent>(maxEvents) : null;\n\t\tconst events: ObserveEvent[] = [];\n\n\t\t// Listener set — format logger, async iterable, and user `onEvent` hooks.\n\t\tconst listeners = new Set<(event: ObserveEvent) => void>();\n\n\t\tconst values: Record<string, T> = {};\n\t\tconst nodeErrored = new Set<string>();\n\t\tlet dirtyCount = 0;\n\t\tlet resolvedCount = 0;\n\t\tlet invalidateCount = 0;\n\t\tlet pauseCount = 0;\n\t\tlet resumeCount = 0;\n\t\tlet teardownCount = 0;\n\t\tlet anyCompletedCleanly = false;\n\t\tlet anyErrored = false;\n\t\tlet batchSeq = 0;\n\n\t\t// Per-target causal context (keyed by target index).\n\t\tconst lastTriggerDepIndex = new Map<Node, number>();\n\t\tconst lastRunDepValues = new Map<Node, readonly unknown[]>();\n\t\tconst lastRunDepBatches = new Map<Node, ReadonlyArray<ReadonlyArray<unknown> | undefined>>();\n\n\t\tconst recordEvent = (event: ObserveEvent): void => {\n\t\t\tif (ring) ring.push(event);\n\t\t\telse events.push(event);\n\t\t\tfor (const listener of listeners) listener(event);\n\t\t};\n\n\t\tconst baseMeta = (): Partial<ObserveEventBase> =>\n\t\t\ttimeline ? { timestamp_ns: monotonicNs(), in_batch: isBatching(), batch_id: batchSeq } : {};\n\n\t\tconst attachInspector = (target: Node, path: string): (() => void) | undefined => {\n\t\t\tif (!wantInspector || !(target instanceof NodeImpl)) return undefined;\n\t\t\treturn target._setInspectorHook((ev) => {\n\t\t\t\tif (ev.kind === \"dep_message\") {\n\t\t\t\t\tlastTriggerDepIndex.set(target, ev.depIndex);\n\t\t\t\t} else if (ev.kind === \"run\") {\n\t\t\t\t\tconst effective = ev.batchData.map((b, i) =>\n\t\t\t\t\t\tb != null && b.length > 0 ? b.at(-1) : ev.prevData[i],\n\t\t\t\t\t);\n\t\t\t\t\tlastRunDepValues.set(target, effective);\n\t\t\t\t\t// Snapshot the full per-dep batches so multi-value waves stay\n\t\t\t\t\t// visible to observers. `ev.batchData` references run-local\n\t\t\t\t\t// arrays, so clone the outer array (inner arrays are\n\t\t\t\t\t// effectively immutable from the observer's POV).\n\t\t\t\t\tconst batches: ReadonlyArray<ReadonlyArray<unknown> | undefined> = ev.batchData.map(\n\t\t\t\t\t\t(b) => (b != null ? [...b] : undefined),\n\t\t\t\t\t);\n\t\t\t\t\tlastRunDepBatches.set(target, batches);\n\t\t\t\t\tif (derived) {\n\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\ttype: \"derived\",\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tdep_values: effective,\n\t\t\t\t\t\t\tdep_batches: batches,\n\t\t\t\t\t\t\t...baseMeta(),\n\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\n\t\tconst buildCausal = (target: Node): ObserveCausalContext => {\n\t\t\tconst idx = lastTriggerDepIndex.get(target);\n\t\t\tconst depValues = lastRunDepValues.get(target);\n\t\t\tif (!causal || depValues == null) return {};\n\t\t\tconst triggerDep =\n\t\t\t\tidx != null && idx >= 0 && target instanceof NodeImpl ? target._deps[idx] : undefined;\n\t\t\tconst triggerNode = triggerDep?.node;\n\t\t\tconst tv = triggerNode?.v;\n\t\t\tconst depBatches = lastRunDepBatches.get(target);\n\t\t\treturn {\n\t\t\t\ttrigger_dep_index: idx,\n\t\t\t\ttrigger_dep_name: triggerNode?.name,\n\t\t\t\t...(tv != null ? { trigger_version: { id: tv.id, version: tv.version } } : {}),\n\t\t\t\tdep_values: [...depValues],\n\t\t\t\t...(depBatches != null ? { dep_batches: depBatches } : {}),\n\t\t\t};\n\t\t};\n\n\t\tconst inspectorDetaches: Array<() => void> = [];\n\t\tconst unsubs: Array<() => void> = [];\n\t\tfor (const [path, target] of targets) {\n\t\t\tconst detach = attachInspector(target, path);\n\t\t\tif (detach) inspectorDetaches.push(detach);\n\t\t\tunsubs.push(\n\t\t\t\ttarget.subscribe((msgs) => {\n\t\t\t\t\tbatchSeq++;\n\t\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\t\tconst t = m[0];\n\t\t\t\t\t\tconst base = baseMeta();\n\t\t\t\t\t\tif (t === DATA) {\n\t\t\t\t\t\t\tvalues[path] = m[1] as T;\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"data\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tdata: m[1],\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t...buildCausal(target),\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (minimal) {\n\t\t\t\t\t\t\tif (t === DIRTY) dirtyCount++;\n\t\t\t\t\t\t\telse if (t === RESOLVED) resolvedCount++;\n\t\t\t\t\t\t\telse if (t === INVALIDATE) invalidateCount++;\n\t\t\t\t\t\t\telse if (t === PAUSE) pauseCount++;\n\t\t\t\t\t\t\telse if (t === RESUME) resumeCount++;\n\t\t\t\t\t\t\telse if (t === TEARDOWN) teardownCount++;\n\t\t\t\t\t\t\telse if (t === COMPLETE && !nodeErrored.has(path)) anyCompletedCleanly = true;\n\t\t\t\t\t\t\telse if (t === ERROR) {\n\t\t\t\t\t\t\t\tanyErrored = true;\n\t\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (t === DIRTY) {\n\t\t\t\t\t\t\tdirtyCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"dirty\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === RESOLVED) {\n\t\t\t\t\t\t\tresolvedCount++;\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"resolved\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t...buildCausal(target),\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (t === INVALIDATE) {\n\t\t\t\t\t\t\tinvalidateCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"invalidate\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === PAUSE) {\n\t\t\t\t\t\t\tpauseCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"pause\", path, lockId: m[1], ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === RESUME) {\n\t\t\t\t\t\t\tresumeCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"resume\", path, lockId: m[1], ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === COMPLETE) {\n\t\t\t\t\t\t\tif (!nodeErrored.has(path)) anyCompletedCleanly = true;\n\t\t\t\t\t\t\trecordEvent({ type: \"complete\", path, ...base } as ObserveEvent);\n\t\t\t\t\t\t} else if (t === ERROR) {\n\t\t\t\t\t\t\tanyErrored = true;\n\t\t\t\t\t\t\tnodeErrored.add(path);\n\t\t\t\t\t\t\trecordEvent({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tdata: m[1],\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t} as ObserveEvent);\n\t\t\t\t\t\t} else if (t === TEARDOWN) {\n\t\t\t\t\t\t\tteardownCount++;\n\t\t\t\t\t\t\trecordEvent({ type: \"teardown\", path, ...base } as ObserveEvent);\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\n\t\tlet disposed = false;\n\t\tconst dispose = (): void => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const u of unsubs) u();\n\t\t\tfor (const d of inspectorDetaches) d();\n\t\t\tfor (const resolve of asyncResolvers) resolve({ value: undefined, done: true });\n\t\t\tasyncResolvers.length = 0;\n\t\t};\n\n\t\t// AsyncIterator plumbing: queue events until a pull arrives, or wake\n\t\t// a pending pull when a new event lands.\n\t\tconst asyncQueue: ObserveEvent[] = [];\n\t\tconst asyncResolvers: Array<(r: IteratorResult<ObserveEvent>) => void> = [];\n\t\tlisteners.add((ev) => {\n\t\t\tconst resolve = asyncResolvers.shift();\n\t\t\tif (resolve) resolve({ value: ev, done: false });\n\t\t\telse asyncQueue.push(ev);\n\t\t});\n\n\t\tconst result: ObserveResult<T> = {\n\t\t\tget values() {\n\t\t\t\treturn values;\n\t\t\t},\n\t\t\tget dirtyCount() {\n\t\t\t\treturn dirtyCount;\n\t\t\t},\n\t\t\tget resolvedCount() {\n\t\t\t\treturn resolvedCount;\n\t\t\t},\n\t\t\tget invalidateCount() {\n\t\t\t\treturn invalidateCount;\n\t\t\t},\n\t\t\tget pauseCount() {\n\t\t\t\treturn pauseCount;\n\t\t\t},\n\t\t\tget resumeCount() {\n\t\t\t\treturn resumeCount;\n\t\t\t},\n\t\t\tget teardownCount() {\n\t\t\t\treturn teardownCount;\n\t\t\t},\n\t\t\tget events() {\n\t\t\t\treturn ring ? ring.toArray() : [...events];\n\t\t\t},\n\t\t\tget anyCompletedCleanly() {\n\t\t\t\treturn anyCompletedCleanly;\n\t\t\t},\n\t\t\tget anyErrored() {\n\t\t\t\treturn anyErrored;\n\t\t\t},\n\t\t\tget completedWithoutErrors() {\n\t\t\t\treturn anyCompletedCleanly && !anyErrored;\n\t\t\t},\n\t\t\tonEvent(listener) {\n\t\t\t\tlisteners.add(listener);\n\t\t\t\treturn () => listeners.delete(listener);\n\t\t\t},\n\t\t\tdispose,\n\t\t\texpand(extra) {\n\t\t\t\tdispose();\n\t\t\t\tconst merged: ObserveOptions = { ...options };\n\t\t\t\tif (typeof extra === \"string\") {\n\t\t\t\t\tmerged.detail = extra;\n\t\t\t\t} else {\n\t\t\t\t\tObject.assign(merged, extra);\n\t\t\t\t}\n\t\t\t\treturn expand(resolveObserveDetail(merged));\n\t\t\t},\n\t\t\t[Symbol.asyncIterator](): AsyncIterator<ObserveEvent> {\n\t\t\t\treturn {\n\t\t\t\t\tnext(): Promise<IteratorResult<ObserveEvent>> {\n\t\t\t\t\t\tif (asyncQueue.length > 0) {\n\t\t\t\t\t\t\treturn Promise.resolve({ value: asyncQueue.shift()!, done: false });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (disposed) return Promise.resolve({ value: undefined, done: true });\n\t\t\t\t\t\treturn new Promise((resolve) => asyncResolvers.push(resolve));\n\t\t\t\t\t},\n\t\t\t\t\treturn(): Promise<IteratorResult<ObserveEvent>> {\n\t\t\t\t\t\tdispose();\n\t\t\t\t\t\treturn Promise.resolve({ value: undefined, done: true });\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\n\t\t// Format logger: subscribes to event stream, renders via theme/format.\n\t\tif (options.format != null) this._attachFormatLogger(result, options);\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Attach format-rendering logger to an ObserveResult by subscribing to its\n\t * event stream (no monkey-patching). Renders each event per `format` and\n\t * `theme`, filtered by `includeTypes` / `excludeTypes`.\n\t */\n\tprivate _attachFormatLogger(result: ObserveResult, options: ObserveOptions): void {\n\t\tconst format = options.format;\n\t\tif (format == null) return;\n\t\tconst logger = options.logger ?? ((line: string) => console.log(line));\n\t\t// Compile include/exclude predicates once.\n\t\tconst include = options.includeTypes ? new Set(options.includeTypes) : null;\n\t\tconst exclude = options.excludeTypes ? new Set(options.excludeTypes) : null;\n\t\tconst shouldLog =\n\t\t\tinclude == null && exclude == null\n\t\t\t\t? () => true\n\t\t\t\t: (type: ObserveEvent[\"type\"]): boolean =>\n\t\t\t\t\t\t(include == null || include.has(type)) && (exclude == null || !exclude.has(type));\n\t\tconst theme = resolveObserveTheme(options.theme);\n\n\t\tconst renderEvent = (event: ObserveEvent): string => {\n\t\t\tif (format === \"json\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.stringify(event);\n\t\t\t\t} catch {\n\t\t\t\t\treturn JSON.stringify({\n\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\tpath: event.path,\n\t\t\t\t\t\tdata: \"[unserializable]\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst color = theme[event.type] ?? \"\";\n\t\t\tconst pathPart = event.path ? `${theme.path}${event.path}${theme.reset} ` : \"\";\n\t\t\tconst isDataBearing = event.type === \"data\" || event.type === \"error\";\n\t\t\tconst isLockBearing = event.type === \"pause\" || event.type === \"resume\";\n\t\t\tconst dataPart = isDataBearing\n\t\t\t\t? ` ${describeData((event as { data: unknown }).data)}`\n\t\t\t\t: isLockBearing\n\t\t\t\t\t? ` ${describeData((event as { lockId: unknown }).lockId)}`\n\t\t\t\t\t: \"\";\n\t\t\tconst causal =\n\t\t\t\tevent.type === \"data\" || event.type === \"resolved\" || event.type === \"derived\"\n\t\t\t\t\t? (event as ObserveCausalContext)\n\t\t\t\t\t: undefined;\n\t\t\tconst triggerPart =\n\t\t\t\tcausal?.trigger_dep_name != null\n\t\t\t\t\t? ` <- ${causal.trigger_dep_name}`\n\t\t\t\t\t: causal?.trigger_dep_index != null\n\t\t\t\t\t\t? ` <- #${causal.trigger_dep_index}`\n\t\t\t\t\t\t: \"\";\n\t\t\tconst batchPart = event.in_batch ? \" [batch]\" : \"\";\n\t\t\treturn `${pathPart}${color}${event.type.toUpperCase()}${theme.reset}${dataPart}${triggerPart}${batchPart}`;\n\t\t};\n\n\t\tresult.onEvent((event) => {\n\t\t\tif (shouldLog(event.type)) logger(renderEvent(event), event);\n\t\t});\n\t}\n\n\t// `dumpGraph` is folded into `describe({format: \"pretty\" | \"json\"})` (Unit 12).\n\t// `toMermaid` / `toD2` are folded into `describe({format: \"mermaid\" | \"d2\"})` (Unit 20).\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Lifecycle & persistence (§3.7–§3.8)\n\t// ——————————————————————————————————————————————————————————————\n\n\t/**\n\t * Register a cleanup function to be called on {@link Graph.destroy}.\n\t *\n\t * Factories use this to attach teardown logic for internal nodes, keepalive\n\t * subscriptions, or other resources that are not registered on the graph and\n\t * would otherwise leak on repeated create/destroy cycles.\n\t *\n\t * Returns a removal function — call it to unregister the disposer early.\n\t */\n\taddDisposer(fn: () => void): () => void {\n\t\tthis._disposers.add(fn);\n\t\treturn () => {\n\t\t\tthis._disposers.delete(fn);\n\t\t};\n\t}\n\n\t/**\n\t * Drains disposers (registered via {@link addDisposer}), then sends `[[TEARDOWN]]` to all\n\t * nodes and clears registries on this graph and every mounted subgraph (§3.7).\n\t * The instance is left empty and may be reused with {@link Graph.add}.\n\t */\n\tdestroy(): void {\n\t\t// Drain disposers (keepalive unsubs etc.) BEFORE TEARDOWN so that\n\t\t// internal effect nodes are disconnected before the cascade fires.\n\t\t// Drain iteratively so disposers registered mid-drain also run; cap\n\t\t// iterations to guard against a disposer that re-registers itself.\n\t\tdrainDisposers(this._disposers, this.name);\n\t\t// TEARDOWN is tier 5 — below `attachStorage`'s `tier < 5` gate, so no\n\t\t// final checkpoint fires; storage disposers unsubscribe after TEARDOWN\n\t\t// has propagated through the subscription pipeline.\n\t\tthis.signal([[TEARDOWN]] satisfies Messages, { internal: true });\n\t\tdrainDisposers(this._storageDisposers, this.name);\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._parent = undefined;\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._parent = undefined;\n\t}\n\n\t/** Clear structure after parent already signaled TEARDOWN through this subtree. */\n\tprivate _destroyClearOnly(): void {\n\t\tfor (const child of [...this._mounts.values()]) {\n\t\t\tchild._parent = undefined;\n\t\t\tchild._destroyClearOnly();\n\t\t}\n\t\tthis._mounts.clear();\n\t\tthis._nodes.clear();\n\t\tthis._parent = undefined;\n\t}\n\n\t/**\n\t * Serializes structure and current values to JSON-shaped data (§3.8). Same\n\t * information as {@link Graph.describe} plus a `version` field for format\n\t * evolution.\n\t *\n\t * The overload path supports three outputs:\n\t * - no arg → `GraphPersistSnapshot` (plain JS object).\n\t * - `{format: \"json-string\"}` → deterministic JSON `string`\n\t * (key-sorted; safe for hashing or file write).\n\t * - `{format: \"bytes\", codec: name}` → `Uint8Array` wrapped in the v1\n\t * envelope from {@link encodeEnvelope}. The codec must be registered\n\t * on this graph's {@link GraphReFlyConfig} via `config.registerCodec`.\n\t * Paired with {@link Graph.decode} for auto-dispatch on the read side.\n\t */\n\tsnapshot(): GraphPersistSnapshot;\n\tsnapshot(opts: { format: \"json-string\" }): string;\n\tsnapshot(opts: { format: \"bytes\"; codec: string }): Uint8Array;\n\tsnapshot(opts?: {\n\t\tformat?: \"json-string\" | \"bytes\";\n\t\tcodec?: string;\n\t}): GraphPersistSnapshot | string | Uint8Array {\n\t\tconst { expand: _, ...d } = this.describe({ detail: \"full\" });\n\t\t// Explicit key sorting for deterministic output — don't rely on\n\t\t// describe() iteration order (audit batch-3, §3.8).\n\t\t// Strip non-restorable fields (runtime attribution) so snapshot → restore → snapshot\n\t\t// is idempotent. Use describe({ detail: \"full\" }) for audit snapshots instead.\n\t\tconst sortedNodes: Record<string, DescribeNodeOutput> = {};\n\t\tfor (const key of Object.keys(d.nodes).sort()) {\n\t\t\tconst { lastMutation: _lm, guard: _g, ...node } = d.nodes[key]!;\n\t\t\tsortedNodes[key] = node;\n\t\t}\n\t\tconst sortedSubgraphs = [...d.subgraphs].sort();\n\t\tconst snap: GraphPersistSnapshot = {\n\t\t\t...d,\n\t\t\tversion: 1,\n\t\t\tnodes: sortedNodes,\n\t\t\tsubgraphs: sortedSubgraphs,\n\t\t};\n\t\tif (opts?.format == null) return snap;\n\t\tif (opts.format === \"json-string\") return JSON.stringify(snap);\n\t\tif (opts.format === \"bytes\") {\n\t\t\tif (opts.codec == null) {\n\t\t\t\tthrow new Error(\"snapshot({format: 'bytes'}) requires a `codec` name\");\n\t\t\t}\n\t\t\tconst codec = this.config.lookupCodec<GraphCodec>(opts.codec);\n\t\t\tif (codec == null) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`snapshot: codec \"${opts.codec}\" is not registered on this graph's config. ` +\n\t\t\t\t\t\t`Call config.registerCodec(...) before creating nodes.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn encodeEnvelope(codec, codec.encode(snap));\n\t\t}\n\t\tthrow new Error(`snapshot: unknown format \"${String(opts.format)}\"`);\n\t}\n\n\t/**\n\t * Auto-dispatch a byte buffer produced by {@link Graph.snapshot} with\n\t * `{format: \"bytes\", codec: name}`. Reads the v1 envelope, resolves the\n\t * named codec on `config` (defaults to `defaultConfig`), and returns the\n\t * decoded snapshot. Combine with {@link Graph.fromSnapshot} to rehydrate\n\t * a full graph topology from bytes.\n\t *\n\t * @throws If the envelope is malformed or the named codec isn't\n\t * registered on the target config.\n\t */\n\tstatic decode(bytes: Uint8Array, opts?: { config?: GraphReFlyConfig }): GraphPersistSnapshot {\n\t\tconst cfg = opts?.config ?? defaultConfig;\n\t\tconst { codec, codecVersion, payload } = decodeEnvelope(bytes, cfg);\n\t\treturn codec.decode(payload, codecVersion);\n\t}\n\n\t/**\n\t * Apply persisted values onto an existing graph whose topology matches the snapshot\n\t * (§3.8). Only {@link DescribeNodeOutput.type} `state` entries with a `value` field\n\t * are written by default; `derived` / `operator` / `effect` are always skipped so\n\t * deps drive recomputation. `producer` entries are skipped unless `includeProducers`\n\t * is set (producers recompute on activation, so restoring is usually a no-op\n\t * overwritten on the next wave — opt in for audit / forensic round-trip use cases).\n\t * Unknown paths are ignored.\n\t *\n\t * @param data - Snapshot envelope with matching `name` and node slices.\n\t * @throws If `data.name` does not equal {@link Graph.name}.\n\t */\n\trestore(\n\t\tdata: GraphPersistSnapshot,\n\t\toptions?: {\n\t\t\tonly?: string | readonly string[];\n\t\t\t/**\n\t\t\t * Fires per failing write. Default behavior (omitted) is silent —\n\t\t\t * missing paths and guard denials are swallowed to match the\n\t\t\t * historical semantics. Provide a callback to surface failures\n\t\t\t * without aborting the remaining restores.\n\t\t\t */\n\t\t\tonError?: (path: string, err: unknown) => void;\n\t\t\t/**\n\t\t\t * Restore `producer` node values alongside `state`. Default `false`:\n\t\t\t * producers are reactive sources whose value recomputes on\n\t\t\t * activation, so restoring from a snapshot is usually a no-op\n\t\t\t * overwritten on the next wave. Audit / forensic round-trip use\n\t\t\t * cases that need the stored value to survive restoration can\n\t\t\t * opt in. Does not change `derived` / `effect` handling — those\n\t\t\t * are always skipped.\n\t\t\t */\n\t\t\tincludeProducers?: boolean;\n\t\t},\n\t): void {\n\t\tparseSnapshotEnvelope(data);\n\t\tif (data.name !== this.name) {\n\t\t\tthrow new Error(\n\t\t\t\t`Graph \"${this.name}\": restore snapshot name \"${data.name}\" does not match this graph`,\n\t\t\t);\n\t\t}\n\t\tconst onlyPatterns =\n\t\t\toptions?.only == null\n\t\t\t\t? null\n\t\t\t\t: (Array.isArray(options.only) ? options.only : [options.only]).map((p) => globToRegex(p));\n\t\tconst includeProducers = options?.includeProducers === true;\n\t\tfor (const path of Object.keys(data.nodes).sort()) {\n\t\t\tif (onlyPatterns !== null && !onlyPatterns.some((re) => re.test(path))) continue;\n\t\t\tconst slice = data.nodes[path];\n\t\t\tif (slice === undefined) continue;\n\t\t\tif (!(\"value\" in slice) || slice.value === undefined) {\n\t\t\t\t// Value absent (valid slice with no snapshotted value) or\n\t\t\t\t// value === undefined (malformed — undefined is the global\n\t\t\t\t// SENTINEL per spec §2.5, not valid DATA). Surface the\n\t\t\t\t// malformed case so torn snapshots don't round-trip silently.\n\t\t\t\tif (\"value\" in slice && slice.value === undefined) {\n\t\t\t\t\toptions?.onError?.(\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`restore: slice.value is undefined for \"${path}\" (undefined is the global SENTINEL; not valid DATA)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (slice.type === \"derived\" || slice.type === \"effect\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (slice.type === \"producer\" && !includeProducers) {\n\t\t\t\t// Reactive producers recompute on activation — restoring would\n\t\t\t\t// be overwritten on the first wave. Opt in via\n\t\t\t\t// `{includeProducers: true}` for audit use cases.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// V0 shortcut: if the snapshot slice and the live node both carry\n\t\t\t// matching versioning info (`v.id` + `v.version`), skip the\n\t\t\t// `set()` — the state is already what the snapshot represents.\n\t\t\t// Avoids redundant DATA waves on idempotent restores.\n\t\t\tif (slice.v != null) {\n\t\t\t\tconst live = this.tryResolve(path);\n\t\t\t\tconst lv = live?.v;\n\t\t\t\tif (lv != null && lv.id === slice.v.id && lv.version === slice.v.version) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.set(path, slice.value);\n\t\t\t} catch (err) {\n\t\t\t\toptions?.onError?.(path, err);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a graph named from the snapshot, optionally runs `build` to register nodes\n\t * and mounts, then {@link Graph.restore} values (§3.8).\n\t *\n\t * @param data - Snapshot envelope (`version` checked).\n\t * @param opts - Either a legacy `build(g)` callback, or an options object:\n\t * - `build?` — topology constructor; skips auto-hydration when present.\n\t * - `factories?` — map from glob pattern to {@link GraphNodeFactory},\n\t * used by auto-hydration to reconstruct non-state nodes. Per-call (no\n\t * process-global registry). First matching pattern wins.\n\t * @returns Hydrated `Graph` instance.\n\t */\n\tstatic fromSnapshot(\n\t\tdata: GraphPersistSnapshot,\n\t\topts?:\n\t\t\t| ((g: Graph) => void)\n\t\t\t| { build?: (g: Graph) => void; factories?: Record<string, GraphNodeFactory> },\n\t): Graph {\n\t\tparseSnapshotEnvelope(data);\n\t\tconst build = typeof opts === \"function\" ? opts : opts?.build;\n\t\tconst factoryMap = typeof opts === \"function\" ? undefined : opts?.factories;\n\t\tconst g = new Graph(data.name);\n\t\tif (build) {\n\t\t\tbuild(g);\n\t\t\tg.restore(data);\n\t\t\treturn g;\n\t\t}\n\t\t// Auto-create mount hierarchy from subgraphs.\n\t\tfor (const mount of [...data.subgraphs].sort((a, b) => {\n\t\t\tconst da = a.split(PATH_SEP).length;\n\t\t\tconst db = b.split(PATH_SEP).length;\n\t\t\tif (da !== db) return da - db;\n\t\t\tif (a < b) return -1;\n\t\t\tif (a > b) return 1;\n\t\t\treturn 0;\n\t\t})) {\n\t\t\tconst parts = mount.split(PATH_SEP);\n\t\t\tlet target: Graph = g;\n\t\t\tfor (const seg of parts) {\n\t\t\t\tif (!target._mounts.has(seg)) {\n\t\t\t\t\ttarget.mount(seg, new Graph(seg));\n\t\t\t\t}\n\t\t\t\ttarget = target._mounts.get(seg)!;\n\t\t\t}\n\t\t}\n\n\t\t// Compile factory glob patterns once. First match in insertion order wins.\n\t\tconst factories = factoryMap\n\t\t\t? Object.entries(factoryMap).map(([pattern, factory]) => ({\n\t\t\t\t\tre: globToRegex(pattern),\n\t\t\t\t\tfactory,\n\t\t\t\t}))\n\t\t\t: [];\n\t\tconst factoryForPath = (path: string): GraphNodeFactory | undefined => {\n\t\t\tfor (const entry of factories) {\n\t\t\t\tif (entry.re.test(path)) return entry.factory;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t};\n\n\t\t// Resolve the owning graph + local name for a qualified snapshot path.\n\t\tconst ownerForPath = (path: string): [Graph, string] => {\n\t\t\tconst segments = path.split(PATH_SEP);\n\t\t\tconst local = segments.pop();\n\t\t\tif (local == null || local.length === 0) {\n\t\t\t\tthrow new Error(`invalid snapshot path \"${path}\"`);\n\t\t\t}\n\t\t\tlet owner: Graph = g;\n\t\t\tfor (const seg of segments) {\n\t\t\t\tconst next = owner._mounts.get(seg);\n\t\t\t\tif (!next) throw new Error(`unknown mount \"${seg}\" in path \"${path}\"`);\n\t\t\t\towner = next;\n\t\t\t}\n\t\t\treturn [owner, local];\n\t\t};\n\n\t\tconst primaryEntries = Object.entries(data.nodes)\n\t\t\t.filter(([path]) => !path.includes(`${PATH_SEP}${GRAPH_META_SEGMENT}${PATH_SEP}`))\n\t\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n\t\tconst pending = new Map(primaryEntries);\n\t\tconst created = new Map<string, Node>();\n\n\t\tlet progressed = true;\n\t\twhile (pending.size > 0 && progressed) {\n\t\t\tprogressed = false;\n\t\t\tfor (const [path, slice] of [...pending.entries()]) {\n\t\t\t\tconst deps = slice?.deps ?? [];\n\t\t\t\tif (!deps.every((dep) => created.has(dep))) continue;\n\t\t\t\tconst [owner, localName] = ownerForPath(path);\n\t\t\t\tconst meta: Record<string, unknown> = { ...(slice?.meta ?? {}) };\n\t\t\t\tconst factory = factoryForPath(path);\n\t\t\t\tlet node: Node;\n\t\t\t\tif (slice?.type === \"state\") {\n\t\t\t\t\tnode = stateNode(slice.value, { meta });\n\t\t\t\t} else {\n\t\t\t\t\tif (factory == null) continue;\n\t\t\t\t\tnode = factory(localName, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\ttype: slice.type,\n\t\t\t\t\t\tvalue: slice.value,\n\t\t\t\t\t\tmeta,\n\t\t\t\t\t\tdeps,\n\t\t\t\t\t\tresolvedDeps: deps.map((dep) => created.get(dep)!),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\towner.add(localName, node);\n\t\t\t\tcreated.set(path, node);\n\t\t\t\tpending.delete(path);\n\t\t\t\tprogressed = true;\n\t\t\t}\n\t\t}\n\t\tif (pending.size > 0) {\n\t\t\tconst unresolved = [...pending.keys()].sort().join(\", \");\n\t\t\tthrow new Error(\n\t\t\t\t`Graph.fromSnapshot could not reconstruct nodes without build callback: ${unresolved}. ` +\n\t\t\t\t\t`Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`,\n\t\t\t);\n\t\t}\n\t\t// Edges are derived from node `_deps` reconstructed during node\n\t\t// creation above — no explicit edge replay needed (Unit 7).\n\t\tg.restore(data);\n\t\treturn g;\n\t}\n\n\t/**\n\t * ECMAScript `JSON.stringify` hook — returns the same object as\n\t * {@link Graph.snapshot}. Makes `JSON.stringify(graph)` \"just work\"\n\t * without double-encoding.\n\t */\n\ttoJSON(): GraphPersistSnapshot {\n\t\treturn this.snapshot();\n\t}\n\n\t/**\n\t * Unified persistence surface (§3.8). Cascades snapshot records through\n\t * one or more {@link StorageTier}s, each with its own `debounceMs` /\n\t * `compactEvery` cadence and independent diff baseline.\n\t *\n\t * Subscription gates on {@link messageTier} ≥ 3 (DATA/RESOLVED/terminal),\n\t * never on tier-0/1/2 control waves (START/DIRTY/INVALIDATE/PAUSE/RESUME)\n\t * or tier-5 TEARDOWN (graceful shutdown is the caller's responsibility).\n\t *\n\t * Per-tier cadence lets the hot tier stay sync while cold tiers absorb\n\t * async writes without blocking the hot path. Each tier holds its own\n\t * `{lastSnapshot, lastVersionFingerprint}` so cold-tier diff baselines\n\t * aren't polluted by hot-tier flushes. Tiers with `debounceMs === 0`\n\t * share a single snapshot computation per observe event; debounced tiers\n\t * compute their own snapshot when their timer fires.\n\t */\n\tattachStorage(\n\t\ttiers: readonly StorageTier[],\n\t\toptions: GraphAttachStorageOptions = {},\n\t): StorageHandle {\n\t\ttype TierState = {\n\t\t\ttier: StorageTier;\n\t\t\tdebounceMs: number;\n\t\t\tcompactEvery: number;\n\t\t\ttimer: ResettableTimer | undefined;\n\t\t\tseq: number;\n\t\t\tlastSnapshot: GraphPersistSnapshot | undefined;\n\t\t\tlastFingerprint: string;\n\t\t\tdisposed: boolean;\n\t\t\t// Chain of pending async saves for this tier. Each flush awaits the\n\t\t\t// previous one so baseline advances only after persistence confirms;\n\t\t\t// on rejection the chain resets (next flush starts from the last\n\t\t\t// successfully-persisted baseline). Sync tiers never populate this.\n\t\t\tsavePending: Promise<void> | undefined;\n\t\t};\n\t\tconst states: TierState[] = tiers.map((tier) => ({\n\t\t\ttier,\n\t\t\tdebounceMs: Math.max(0, tier.debounceMs ?? 0),\n\t\t\tcompactEvery: Math.max(1, tier.compactEvery ?? 10),\n\t\t\ttimer: undefined,\n\t\t\tseq: 0,\n\t\t\tlastSnapshot: undefined,\n\t\t\tlastFingerprint: \"\",\n\t\t\tdisposed: false,\n\t\t\tsavePending: undefined,\n\t\t}));\n\n\t\tif (options.autoRestore === true) {\n\t\t\t// Fire-and-forget cascade restore; errors surface via onError with\n\t\t\t// the specific tier that failed.\n\t\t\tvoid this._cascadeRestore(tiers, options.onError);\n\t\t}\n\n\t\tconst runFlush = (s: TierState, snapshot: GraphPersistSnapshot): void => {\n\t\t\tif (s.disposed) return;\n\t\t\tconst fingerprint = computeVersionFingerprint(snapshot.nodes);\n\t\t\tif (s.lastSnapshot != null && fingerprint !== \"\" && fingerprint === s.lastFingerprint) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nextSeq = s.seq + 1;\n\t\t\t// Persisted records carry wall-clock attribution (CLAUDE.md time-util\n\t\t\t// rule). Internal event-order timestamps use monotonicNs — this is the\n\t\t\t// output-to-durable-store boundary, so wall clock is correct and\n\t\t\t// cross-source comparable with surface.saveSnapshot records.\n\t\t\tconst timestamp_ns = wallClockNs();\n\t\t\tconst isFirst = s.lastSnapshot == null;\n\t\t\tconst shouldCompact = isFirst || nextSeq % s.compactEvery === 0;\n\t\t\tconst record: GraphCheckpointRecord = shouldCompact\n\t\t\t\t? {\n\t\t\t\t\t\tmode: \"full\",\n\t\t\t\t\t\tsnapshot,\n\t\t\t\t\t\tseq: nextSeq,\n\t\t\t\t\t\ttimestamp_ns,\n\t\t\t\t\t\tformat_version: SNAPSHOT_VERSION,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tmode: \"diff\",\n\t\t\t\t\t\tdiff: diffForWAL(s.lastSnapshot!, snapshot),\n\t\t\t\t\t\tseq: nextSeq,\n\t\t\t\t\t\ttimestamp_ns,\n\t\t\t\t\t\tformat_version: SNAPSHOT_VERSION,\n\t\t\t\t\t};\n\t\t\tif (s.tier.filter && !s.tier.filter(this.name, record)) {\n\t\t\t\t// Filter rejected — don't advance seq or baseline.\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet result: void | Promise<void>;\n\t\t\ttry {\n\t\t\t\tresult = s.tier.save(this.name, record);\n\t\t\t} catch (error) {\n\t\t\t\t// Synchronous throw — baseline untouched; surface and bail.\n\t\t\t\toptions.onError?.(error, s.tier);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result && typeof (result as Promise<void>).then === \"function\") {\n\t\t\t\t// Async tier: defer baseline + seq advance until the promise\n\t\t\t\t// settles. Chain saves per-tier so they land in order without\n\t\t\t\t// overlapping baselines. On rejection, baseline is left intact\n\t\t\t\t// so the next flush diffs against the last successfully\n\t\t\t\t// persisted snapshot.\n\t\t\t\tconst prev = s.savePending ?? Promise.resolve();\n\t\t\t\tconst chained = prev.then(\n\t\t\t\t\t() => result as Promise<void>,\n\t\t\t\t\t// Previous rejection already surfaced; don't block this save.\n\t\t\t\t\t() => result as Promise<void>,\n\t\t\t\t);\n\t\t\t\tconst final = chained.then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tif (s.disposed) return;\n\t\t\t\t\t\ts.seq = nextSeq;\n\t\t\t\t\t\ts.lastSnapshot = snapshot;\n\t\t\t\t\t\ts.lastFingerprint = fingerprint;\n\t\t\t\t\t},\n\t\t\t\t\t(err) => {\n\t\t\t\t\t\toptions.onError?.(err, s.tier);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\ts.savePending = final.finally(() => {\n\t\t\t\t\tif (s.savePending === final) s.savePending = undefined;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ts.seq = nextSeq;\n\t\t\t\ts.lastSnapshot = snapshot;\n\t\t\t\ts.lastFingerprint = fingerprint;\n\t\t\t}\n\t\t};\n\n\t\tconst flushTier = (s: TierState, snapshot: GraphPersistSnapshot): void => {\n\t\t\ttry {\n\t\t\t\trunFlush(s, snapshot);\n\t\t\t} catch (error) {\n\t\t\t\toptions.onError?.(error, s.tier);\n\t\t\t}\n\t\t};\n\n\t\tconst onEvent = (path: string, messages: Messages): void => {\n\t\t\tconst triggeredByTier = messages.some((m) => {\n\t\t\t\tconst tier = this.config.messageTier(m[0]);\n\t\t\t\treturn tier >= 3 && tier < 5;\n\t\t\t});\n\t\t\tif (!triggeredByTier) return;\n\t\t\tif (options.filter) {\n\t\t\t\tconst nd = this.tryResolve(path);\n\t\t\t\tif (nd == null) return;\n\t\t\t\tconst described = describeNode(nd, resolveDescribeFields(\"standard\"));\n\t\t\t\tif (!options.filter(path, described)) return;\n\t\t\t}\n\t\t\t// Shared snapshot for all sync (debounceMs=0) tiers firing on this event.\n\t\t\tlet sharedSnapshot: GraphPersistSnapshot | undefined;\n\t\t\tconst getSnapshot = (): GraphPersistSnapshot => {\n\t\t\t\tif (sharedSnapshot == null) sharedSnapshot = this.snapshot();\n\t\t\t\treturn sharedSnapshot;\n\t\t\t};\n\t\t\tfor (const s of states) {\n\t\t\t\tif (s.disposed) continue;\n\t\t\t\tif (s.debounceMs === 0) {\n\t\t\t\t\tflushTier(s, getSnapshot());\n\t\t\t\t} else {\n\t\t\t\t\tif (s.timer == null) s.timer = new ResettableTimer();\n\t\t\t\t\ts.timer.start(s.debounceMs, () => {\n\t\t\t\t\t\tif (s.disposed) return;\n\t\t\t\t\t\tflushTier(s, this.snapshot());\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tlet off: () => void;\n\t\tif (options.paths != null) {\n\t\t\tconst paths =\n\t\t\t\ttypeof options.paths === \"string\"\n\t\t\t\t\t? this._pathsMatching(options.paths)\n\t\t\t\t\t: (options.paths as readonly string[]);\n\t\t\tconst unsubs = paths.map((p) => {\n\t\t\t\tconst nd = this.tryResolve(p);\n\t\t\t\tif (nd == null) return () => {};\n\t\t\t\treturn nd.subscribe((msgs) => onEvent(p, msgs));\n\t\t\t});\n\t\t\toff = () => {\n\t\t\t\tfor (const u of unsubs) u();\n\t\t\t};\n\t\t} else {\n\t\t\toff = this.observe().subscribe((path, messages) => onEvent(path, messages));\n\t\t}\n\n\t\tconst dispose = () => {\n\t\t\toff();\n\t\t\tfor (const s of states) {\n\t\t\t\ts.disposed = true;\n\t\t\t\ts.timer?.cancel();\n\t\t\t}\n\t\t\tthis._storageDisposers.delete(dispose);\n\t\t};\n\t\tthis._storageDisposers.add(dispose);\n\t\treturn { dispose };\n\t}\n\n\t/**\n\t * Try tiers in order (hottest first); apply the first record that hits\n\t * via {@link Graph.restore}. Returns `true` if any tier produced a\n\t * restorable snapshot, `false` if all missed.\n\t *\n\t * Resilience: a tier that returns data which cannot be restored (load\n\t * throws, shape unrecognized, or `restore()` itself throws) does not abort\n\t * the cascade — the error is routed through `onError` (if supplied) and\n\t * the next colder tier is tried. This mirrors how a multi-tier cache\n\t * falls through on a corrupt hot entry.\n\t *\n\t * Note: `restore()` mutates state incrementally. If a restore throws\n\t * partway through, the graph may hold a mixed state (some slices from\n\t * the bad tier, some pre-existing). A subsequent successful tier's\n\t * `restore()` overwrites the overlapping slices.\n\t *\n\t * Internal helper shared by {@link Graph.attachStorage}'s `autoRestore`\n\t * option and the static {@link Graph.fromStorage} factory.\n\t */\n\tprivate async _cascadeRestore(\n\t\ttiers: readonly StorageTier[],\n\t\tonError?: (err: unknown, tier: StorageTier) => void,\n\t): Promise<boolean> {\n\t\tfor (const tier of tiers) {\n\t\t\tlet raw: unknown;\n\t\t\ttry {\n\t\t\t\traw = await tier.load(this.name);\n\t\t\t} catch (err) {\n\t\t\t\tonError?.(err, tier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (raw == null) continue;\n\t\t\tif (typeof raw !== \"object\" || Array.isArray(raw)) continue;\n\t\t\tconst record = raw as Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\t// Accept both a `GraphCheckpointRecord` envelope\n\t\t\t\t// (`mode === \"full\"`) and a bare `GraphPersistSnapshot` (the\n\t\t\t\t// shape written by `saveGraphCheckpoint`). Bare snapshots\n\t\t\t\t// carry `version: 1`.\n\t\t\t\tif (record.mode === \"full\" && record.snapshot != null) {\n\t\t\t\t\tthis.restore(record.snapshot as GraphPersistSnapshot);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (record.version === SNAPSHOT_VERSION && record.nodes != null) {\n\t\t\t\t\tthis.restore(record as GraphPersistSnapshot);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tonError?.(err, tier);\n\t\t\t\t// Fall through to the next tier.\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Construct a fresh {@link Graph} pre-hydrated from the first tier that\n\t * hits. Delegates topology reconstruction to {@link Graph.fromSnapshot}\n\t * on `\"full\"` records and direct {@link Graph.restore} on bare snapshots.\n\t *\n\t * Always asynchronous — awaits `tier.load()` for async tier support even\n\t * when all tiers are sync. Callers that know they only pass sync tiers\n\t * can safely `await` immediately.\n\t *\n\t * @throws If no tier holds a restorable record matching `name` *and* no\n\t * `factories` override is provided for dynamic nodes.\n\t */\n\tstatic async fromStorage(\n\t\tname: string,\n\t\ttiers: readonly StorageTier[],\n\t\topts?: GraphOptions & {\n\t\t\tfactories?: Record<string, GraphNodeFactory>;\n\t\t\t/**\n\t\t\t * Called when a tier throws during `load()` or when\n\t\t\t * {@link Graph.fromSnapshot} rejects a tier's record. The cascade\n\t\t\t * falls through to the next colder tier regardless.\n\t\t\t */\n\t\t\tonError?: (err: unknown, tier: StorageTier) => void;\n\t\t},\n\t): Promise<Graph> {\n\t\tfor (const tier of tiers) {\n\t\t\tlet raw: unknown;\n\t\t\ttry {\n\t\t\t\traw = await tier.load(name);\n\t\t\t} catch (err) {\n\t\t\t\topts?.onError?.(err, tier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (raw == null) continue;\n\t\t\tif (typeof raw !== \"object\" || Array.isArray(raw)) continue;\n\t\t\tconst record = raw as Record<string, unknown>;\n\t\t\tconst snapshot: GraphPersistSnapshot | undefined =\n\t\t\t\trecord.mode === \"full\" && record.snapshot != null\n\t\t\t\t\t? (record.snapshot as GraphPersistSnapshot)\n\t\t\t\t\t: record.version === SNAPSHOT_VERSION && record.nodes != null\n\t\t\t\t\t\t? (record as GraphPersistSnapshot)\n\t\t\t\t\t\t: undefined;\n\t\t\tif (snapshot == null) continue;\n\t\t\ttry {\n\t\t\t\treturn Graph.fromSnapshot(snapshot, opts);\n\t\t\t} catch (err) {\n\t\t\t\topts?.onError?.(err, tier);\n\t\t\t\t// Fall through to colder tier.\n\t\t\t}\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Graph.fromStorage: no tier held a restorable record for \"${name}\" across ${tiers.length} tier(s)`,\n\t\t);\n\t}\n\n\t// ——————————————————————————————————————————————————————————————\n\t// Inspector (roadmap 3.3) — reasoning trace, overhead gating\n\t// ——————————————————————————————————————————————————————————————\n\n\t// Inspector gating lives on `this.config.inspectorEnabled` (see\n\t// `core/config.ts`). Default: `true` outside `NODE_ENV === \"production\"`.\n\n\tprivate _annotations = new Map<string, string>();\n\tprivate readonly _traceRing: RingBuffer<TraceEntry>;\n\n\t/**\n\t * Unified reasoning trace: write annotations or read the ring buffer.\n\t *\n\t * Write: `graph.trace(\"path\", \"reason\")` — attaches a reasoning annotation\n\t * to a node, capturing *why* an AI agent set a value. Unknown paths are\n\t * silently dropped (matching `observe` resilience). No-op when\n\t * `config.inspectorEnabled` is `false`.\n\t *\n\t * Read: `graph.trace()` — returns a chronological log of all annotations.\n\t * Returns `[]` when `config.inspectorEnabled` is `false`.\n\t */\n\ttrace(path: string, reason: string, opts?: { actor?: Actor }): void;\n\ttrace(): readonly TraceEntry[];\n\ttrace(\n\t\tpath?: string,\n\t\treason?: string,\n\t\topts?: { actor?: Actor },\n\t): undefined | readonly TraceEntry[] {\n\t\tif (path != null && reason != null) {\n\t\t\tif (!this.config.inspectorEnabled) return;\n\t\t\t// Silent-drop unknown paths — matches `observe` resilience. Callers\n\t\t\t// with robust path-hygiene needs can pre-check via `tryResolve`.\n\t\t\tif (this.tryResolve(path) == null) return;\n\t\t\tthis._annotations.set(path, reason);\n\t\t\tconst entry: TraceEntry = {\n\t\t\t\tpath,\n\t\t\t\treason,\n\t\t\t\ttimestamp_ns: monotonicNs(),\n\t\t\t\t...(opts?.actor != null ? { actor: opts.actor } : {}),\n\t\t\t};\n\t\t\tthis._traceRing.push(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.config.inspectorEnabled) return [];\n\t\treturn this._traceRing.toArray();\n\t}\n\n\t/**\n\t * Latest reason annotation attached to `path` via {@link Graph.trace},\n\t * or `undefined` if none. `describe()` surfaces this via the `reason`\n\t * field on each node entry (when present).\n\t */\n\tannotation(path: string): string | undefined {\n\t\treturn this._annotations.get(path);\n\t}\n\n\t/**\n\t * Clear all reasoning-trace state (both the per-path annotations map and\n\t * the ring buffer). Useful for long-running processes that want periodic\n\t * resets, or tests that need a clean slate.\n\t */\n\tclearTrace(): void {\n\t\tthis._annotations.clear();\n\t\tthis._traceRing.clear();\n\t}\n\n\t/**\n\t * Remove trace entries matching `predicate`. Returns the number of\n\t * entries removed. Does not touch the per-path annotations map — call\n\t * {@link Graph.clearTrace} for a full reset.\n\t */\n\tpruneTrace(predicate: (entry: TraceEntry) => boolean): number {\n\t\tconst kept = this._traceRing.toArray().filter((e) => !predicate(e));\n\t\tconst removed = this._traceRing.size - kept.length;\n\t\tthis._traceRing.clear();\n\t\tfor (const e of kept) this._traceRing.push(e);\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Computes structural + value diff between two {@link Graph.describe} snapshots.\n\t *\n\t * @param a - Earlier describe output.\n\t * @param b - Later describe output.\n\t * @returns Added/removed nodes, changed fields, and edge deltas.\n\t */\n\tstatic diff(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphDiffResult {\n\t\tconst aKeys = new Set(Object.keys(a.nodes));\n\t\tconst bKeys = new Set(Object.keys(b.nodes));\n\n\t\tconst nodesAdded = [...bKeys].filter((k) => !aKeys.has(k)).sort();\n\t\tconst nodesRemoved = [...aKeys].filter((k) => !bKeys.has(k)).sort();\n\t\tconst nodesChanged: GraphDiffChange[] = [];\n\t\tconst versionChanges: GraphVersionChange[] = [];\n\n\t\tfor (const key of aKeys) {\n\t\t\tif (!bKeys.has(key)) continue;\n\t\t\tconst na = a.nodes[key];\n\t\t\tconst nb = b.nodes[key];\n\t\t\tconst av = na.v;\n\t\t\tconst bv = nb.v;\n\t\t\t// Surface version bumps (even if value is identical, the bump itself\n\t\t\t// is meaningful for audit / wire-efficient sync).\n\t\t\tif (av != null && bv != null && av.id === bv.id && av.version !== bv.version) {\n\t\t\t\tversionChanges.push({\n\t\t\t\t\tpath: key,\n\t\t\t\t\tid: av.id,\n\t\t\t\t\tfrom: av.version,\n\t\t\t\t\tto: bv.version,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst versionMatches =\n\t\t\t\tav != null && bv != null && av.id === bv.id && av.version === bv.version;\n\t\t\t// V0 fast path: when versions match, skip value / meta compare —\n\t\t\t// upstream is guaranteed unchanged by protocol. Only type/status\n\t\t\t// (cheap string compare) + sentinel flip are possible.\n\t\t\tfor (const field of [\"type\", \"status\", \"sentinel\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (va !== vb) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (versionMatches) continue;\n\t\t\t// Full slow-path: deep-equal on value + meta.\n\t\t\tfor (const field of [\"value\", \"meta\"] as const) {\n\t\t\t\tconst va = (na as Record<string, unknown>)[field];\n\t\t\t\tconst vb = (nb as Record<string, unknown>)[field];\n\t\t\t\tif (!deepEqual(va, vb)) {\n\t\t\t\t\tnodesChanged.push({ path: key, field, from: va, to: vb });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst edgeKey = (e: { from: string; to: string }) => `${e.from}\\t${e.to}`;\n\t\tconst aEdges = new Set(a.edges.map(edgeKey));\n\t\tconst bEdges = new Set(b.edges.map(edgeKey));\n\n\t\tconst edgesAdded = b.edges.filter((e) => !aEdges.has(edgeKey(e)));\n\t\tconst edgesRemoved = a.edges.filter((e) => !bEdges.has(edgeKey(e)));\n\t\tconst aSubgraphs = new Set(a.subgraphs);\n\t\tconst bSubgraphs = new Set(b.subgraphs);\n\t\tconst subgraphsAdded = [...bSubgraphs].filter((s) => !aSubgraphs.has(s)).sort();\n\t\tconst subgraphsRemoved = [...aSubgraphs].filter((s) => !bSubgraphs.has(s)).sort();\n\n\t\treturn {\n\t\t\tnodesAdded,\n\t\t\tnodesRemoved,\n\t\t\tnodesChanged,\n\t\t\tversionChanges,\n\t\t\tedgesAdded,\n\t\t\tedgesRemoved,\n\t\t\tsubgraphsAdded,\n\t\t\tsubgraphsRemoved,\n\t\t};\n\t}\n}\n\n/** Entry in the reasoning trace ring buffer (roadmap 3.3). */\nexport type TraceEntry = {\n\tpath: string;\n\treason: string;\n\ttimestamp_ns: number;\n\t/**\n\t * Actor that produced the annotation (optional). Enables multi-agent\n\t * attribution: distinguish \"LLM set this rootCause\" from \"human approved\n\t * this intervention\" in the trace log.\n\t */\n\tactor?: Actor;\n};\n\n/** Result of {@link Graph.diff}. */\nexport type GraphDiffResult = {\n\tnodesAdded: string[];\n\tnodesRemoved: string[];\n\tnodesChanged: GraphDiffChange[];\n\t/**\n\t * V0 version bumps (same `v.id`, different `v.version`). Surfaced even\n\t * when values are identical — the bump itself is audit-meaningful.\n\t */\n\tversionChanges: GraphVersionChange[];\n\tedgesAdded: Array<{ from: string; to: string }>;\n\tedgesRemoved: Array<{ from: string; to: string }>;\n\tsubgraphsAdded: string[];\n\tsubgraphsRemoved: string[];\n};\n\n/**\n * WAL-oriented diff — extends {@link GraphDiffResult} with the full node\n * slice for each added path so {@link replayWAL} can reconstruct nodes added\n * between full anchors (topology mutations inside a `compactEvery` window).\n *\n * `Graph.diff()` returns the audit shape (no payload); `attachStorage` writes\n * this WAL shape. The two shapes stay structurally compatible — `GraphWALDiff`\n * is a superset.\n */\nexport type GraphWALDiff = GraphDiffResult & {\n\t/**\n\t * Full node slices for every path in `nodesAdded`, keyed by path. Applied\n\t * verbatim to `snapshot.nodes[path]` during replay.\n\t */\n\tnodesAddedFull: Record<string, DescribeNodeOutput>;\n};\n\n/**\n * Build a WAL-ready diff between two snapshots: the structural diff from\n * {@link Graph.diff} plus the full node slice for each added path (pulled\n * from `b.nodes`). Callers that only need the audit shape should use\n * `Graph.diff` directly.\n */\nexport function diffForWAL(a: GraphDescribeOutput, b: GraphDescribeOutput): GraphWALDiff {\n\tconst base = Graph.diff(a, b);\n\tconst nodesAddedFull: Record<string, DescribeNodeOutput> = {};\n\tfor (const path of base.nodesAdded) {\n\t\tconst slice = b.nodes[path];\n\t\tif (slice != null) nodesAddedFull[path] = slice;\n\t}\n\treturn { ...base, nodesAddedFull };\n}\n\n/** A single field change within a diff. */\nexport type GraphDiffChange = {\n\tpath: string;\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n};\n\n/** A single V0 version bump within a diff. */\nexport type GraphVersionChange = {\n\tpath: string;\n\tid: string;\n\tfrom: number;\n\tto: number;\n};\n\n/** Audit record returned by {@link Graph.remove}. */\nexport type GraphRemoveAudit = {\n\t/** Whether the removed entry was a local node or a mount. */\n\tkind: \"node\" | \"mount\";\n\t/**\n\t * Primary nodes torn down by this `remove()`. For `kind: \"node\"` contains\n\t * just the removed name; for `kind: \"mount\"` lists every primary node in\n\t * the unmounted subtree (qualified paths relative to the mount point,\n\t * sorted).\n\t */\n\tnodes: string[];\n\t/**\n\t * Mounted subgraphs that were unmounted. For `kind: \"node\"` this is empty;\n\t * for `kind: \"mount\"` starts with the top-level mount name and lists its\n\t * descendants in depth-first order.\n\t */\n\tmounts: string[];\n};\n\n/** Direction for {@link reachable} graph traversal. */\nexport type ReachableDirection = \"upstream\" | \"downstream\";\n\n/** Options for {@link reachable}. */\nexport type ReachableOptions = {\n\t/** Maximum hop depth from `from` (0 returns `[]`). Omit for unbounded traversal. */\n\tmaxDepth?: number;\n\t/**\n\t * Traverse both directions in one pass (union of upstream + downstream).\n\t * Ignores the `direction` arg when set.\n\t */\n\tboth?: boolean;\n\t/**\n\t * Return the richer {@link ReachableResult} shape (paths + per-path\n\t * hop depth + truncation flag) instead of the flat sorted string array.\n\t */\n\twithDetail?: boolean;\n};\n\n/** Rich reachable result (opt-in via `{withDetail: true}`). */\nexport type ReachableResult = {\n\t/** Reachable paths, sorted lexicographically. */\n\tpaths: string[];\n\t/** Hop depth from `from` to each reachable path. */\n\tdepths: Map<string, number>;\n\t/** True when traversal hit `maxDepth` and some neighbors were not explored. */\n\ttruncated: boolean;\n};\n\n/**\n * Reachability query over a {@link Graph.describe} snapshot.\n *\n * Traversal follows `deps` (upstream) and reverse-`deps` (downstream). Edges\n * are derived from deps post Unit 7, so `edges[]` in the snapshot is\n * redundant with deps — it's walked defensively in case a caller supplied a\n * pre-Unit-7 snapshot.\n *\n * @param described - `graph.describe()` output to traverse.\n * @param from - Start path (qualified node path).\n * @param direction - Traversal direction (ignored when `opts.both` is `true`).\n * @param options - Optional `maxDepth`, `both`, `withDetail`.\n * @returns Sorted paths (flat) — or {@link ReachableResult} when `withDetail: true`.\n */\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions & { withDetail: true },\n): ReachableResult;\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions?: ReachableOptions,\n): string[];\nexport function reachable(\n\tdescribed: GraphDescribeOutput,\n\tfrom: string,\n\tdirection: ReachableDirection,\n\toptions: ReachableOptions = {},\n): string[] | ReachableResult {\n\tconst empty: ReachableResult = { paths: [], depths: new Map(), truncated: false };\n\tif (!from) return options.withDetail ? empty : [];\n\tif (!options.both && direction !== \"upstream\" && direction !== \"downstream\") {\n\t\tthrow new Error(`reachable: direction must be \"upstream\" or \"downstream\"`);\n\t}\n\tconst maxDepth = options.maxDepth;\n\tif (maxDepth != null && (!Number.isInteger(maxDepth) || maxDepth < 0)) {\n\t\tthrow new Error(`reachable: maxDepth must be an integer >= 0`);\n\t}\n\tif (maxDepth === 0) return options.withDetail ? empty : [];\n\n\tconst depsByPath = new Map<string, readonly string[]>();\n\tconst reverseDeps = new Map<string, Set<string>>();\n\tconst incomingEdges = new Map<string, Set<string>>();\n\tconst outgoingEdges = new Map<string, Set<string>>();\n\tconst universe = new Set<string>();\n\n\tfor (const [path, node] of Object.entries(described.nodes)) {\n\t\tif (!path) continue;\n\t\tuniverse.add(path);\n\t\tconst deps = node.deps ?? [];\n\t\tdepsByPath.set(path, deps);\n\t\tfor (const dep of deps) {\n\t\t\tif (!dep) continue;\n\t\t\tuniverse.add(dep);\n\t\t\tif (!reverseDeps.has(dep)) reverseDeps.set(dep, new Set());\n\t\t\treverseDeps.get(dep)!.add(path);\n\t\t}\n\t}\n\t// Edges are normally derived from deps post Unit 7, but synthetic snapshots\n\t// (e.g. test fixtures) may declare edges independently — walk both for\n\t// compatibility. Minimal null/string checks for malformed JSON.\n\tfor (const edge of described.edges) {\n\t\tif (edge == null || typeof edge !== \"object\") continue;\n\t\tconst from = typeof edge.from === \"string\" ? edge.from : \"\";\n\t\tconst to = typeof edge.to === \"string\" ? edge.to : \"\";\n\t\tif (!from || !to) continue;\n\t\tuniverse.add(from);\n\t\tuniverse.add(to);\n\t\tif (!outgoingEdges.has(from)) outgoingEdges.set(from, new Set());\n\t\toutgoingEdges.get(from)!.add(to);\n\t\tif (!incomingEdges.has(to)) incomingEdges.set(to, new Set());\n\t\tincomingEdges.get(to)!.add(from);\n\t}\n\n\tif (!universe.has(from)) return options.withDetail ? empty : [];\n\n\tconst doBoth = options.both === true;\n\tconst visit = (path: string): readonly string[] => {\n\t\tif (doBoth) {\n\t\t\tconst up = depsByPath.get(path) ?? [];\n\t\t\tconst upEdges = incomingEdges.get(path);\n\t\t\tconst down = reverseDeps.get(path);\n\t\t\tconst downEdges = outgoingEdges.get(path);\n\t\t\tconst acc: string[] = [...up];\n\t\t\tif (upEdges) acc.push(...upEdges);\n\t\t\tif (down) acc.push(...down);\n\t\t\tif (downEdges) acc.push(...downEdges);\n\t\t\treturn acc;\n\t\t}\n\t\tif (direction === \"upstream\") {\n\t\t\tconst up = depsByPath.get(path) ?? [];\n\t\t\tconst upEdges = incomingEdges.get(path);\n\t\t\tif (!upEdges) return up;\n\t\t\treturn [...up, ...upEdges];\n\t\t}\n\t\tconst down = reverseDeps.get(path);\n\t\tconst downEdges = outgoingEdges.get(path);\n\t\tconst acc: string[] = down ? [...down] : [];\n\t\tif (downEdges) acc.push(...downEdges);\n\t\treturn acc;\n\t};\n\n\t// Head-index BFS — avoids O(n²) from `Array.prototype.shift`.\n\tconst visited = new Set<string>([from]);\n\tconst depths = new Map<string, number>();\n\tconst queue: Array<{ path: string; depth: number }> = [{ path: from, depth: 0 }];\n\tlet head = 0;\n\tlet truncated = false;\n\twhile (head < queue.length) {\n\t\tconst next = queue[head++]!;\n\t\tif (maxDepth != null && next.depth >= maxDepth) {\n\t\t\t// Flag truncation only if this node actually has unexplored neighbors.\n\t\t\tif (visit(next.path).length > 0) truncated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const nb of visit(next.path)) {\n\t\t\tif (!nb || visited.has(nb)) continue;\n\t\t\tvisited.add(nb);\n\t\t\tdepths.set(nb, next.depth + 1);\n\t\t\tqueue.push({ path: nb, depth: next.depth + 1 });\n\t\t}\n\t}\n\n\tconst paths = [...depths.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n\tif (options.withDetail) return { paths, depths, truncated };\n\treturn paths;\n}\n","/**\n * Transitive structural-change subscription helper.\n *\n * Subscribes to a graph's {@link Graph.topology} event stream AND recurses\n * into every mounted subgraph, auto-wiring new mounts when they appear\n * (via parent `added: mount` events) and tearing down subscriptions for\n * unmounted subgraphs (via `removed: mount` events + the audit record).\n *\n * Lives in `graph/` rather than `patterns/` because it depends only on\n * the `Graph` primitive and the `TopologyEvent` type — no domain-layer\n * factories. Consumers that need full-tree dynamic coverage (e.g.\n * `policyEnforcer`, `graphLens`) import from here to avoid circular\n * references between audit/lens modules.\n *\n * @module\n */\nimport { DATA } from \"../core/messages.js\";\nimport type { TopologyEvent } from \"./graph.js\";\nimport { Graph } from \"./graph.js\";\n\n/**\n * Subscribe to structural changes across `graph` and every transitively\n * mounted subgraph. `cb` fires on every {@link TopologyEvent} from any\n * graph in the tree. Newly-mounted subgraphs are auto-wired when their\n * parent emits `{kind: \"added\", nodeKind: \"mount\"}`; newly-unmounted\n * subgraphs' subscriptions are disposed via the parent's\n * `{kind: \"removed\", nodeKind: \"mount\"}` event plus the returned\n * `GraphRemoveAudit`.\n *\n * The callback receives a third argument `prefix`: the `::`-delimited\n * path from the root watched graph to the emitter, ending with `\"::\"`\n * (empty string when the event comes from the root itself). Compute\n * a qualified path for an added/removed entry as `prefix + event.name`.\n *\n * @param graph - Root graph to watch.\n * @param cb - Receives `(event, emitterGraph, prefix)`.\n * @returns Dispose function — tears down every active subscription.\n *\n * @category observability\n */\nexport function watchTopologyTree(\n\tgraph: Graph,\n\tcb: (event: TopologyEvent, emitter: Graph, prefix: string) => void,\n): () => void {\n\t// Tracks every wired graph with its qualified prefix (path from root).\n\t// Prefix is used for both qualified-path emission to `cb` AND prefix-match\n\t// disposal when a mount is removed — more robust than relying on\n\t// `_parent == null` which only nulls on the direct child, not on\n\t// grandchildren within an unmounted subtree.\n\ttype Entry = { off: () => void; prefix: string };\n\tconst subs = new Map<Graph, Entry>();\n\n\tconst wire = (g: Graph, prefix: string): void => {\n\t\tif (subs.has(g)) return;\n\t\t// Placeholder entry set BEFORE subscribe so any synchronous reentry\n\t\t// (e.g. a mount-added handler firing during subscribe's initial push)\n\t\t// sees this graph as already wired and skips rewiring.\n\t\tconst placeholder: Entry = { off: () => {}, prefix };\n\t\tsubs.set(g, placeholder);\n\t\tconst off = g.topology.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (m[0] !== DATA) continue;\n\t\t\t\tconst event = m[1] as TopologyEvent;\n\t\t\t\tcb(event, g, prefix);\n\t\t\t\tif (event.kind === \"added\" && event.nodeKind === \"mount\") {\n\t\t\t\t\tconst child = g._mounts.get(event.name);\n\t\t\t\t\tif (child instanceof Graph) {\n\t\t\t\t\t\tconst childPrefix = `${prefix}${event.name}::`;\n\t\t\t\t\t\twire(child, childPrefix);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.kind === \"removed\" && event.nodeKind === \"mount\") {\n\t\t\t\t\t// Dispose every tracked sub whose prefix is under the removed\n\t\t\t\t\t// mount. Matches on qualified-prefix rather than `_parent`\n\t\t\t\t\t// so deep descendants are released even when their parent\n\t\t\t\t\t// pointers haven't been nulled.\n\t\t\t\t\tconst removedPrefix = `${prefix}${event.name}::`;\n\t\t\t\t\tfor (const [trackedGraph, trackedEntry] of Array.from(subs.entries())) {\n\t\t\t\t\t\tif (trackedGraph === graph) continue;\n\t\t\t\t\t\tif (trackedEntry.prefix.startsWith(removedPrefix)) {\n\t\t\t\t\t\t\ttrackedEntry.off();\n\t\t\t\t\t\t\tsubs.delete(trackedGraph);\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\tplaceholder.off = off;\n\t\t// Recursively wire any children already mounted when this call runs.\n\t\tfor (const [mountName, child] of g._mounts) {\n\t\t\tif (child instanceof Graph) {\n\t\t\t\tconst childPrefix = `${prefix}${mountName}::`;\n\t\t\t\twire(child, childPrefix);\n\t\t\t}\n\t\t}\n\t};\n\n\twire(graph, \"\");\n\n\treturn () => {\n\t\tfor (const entry of subs.values()) entry.off();\n\t\tsubs.clear();\n\t};\n}\n","/**\n * Core reactive sources, sinks, and utilities (roadmap §2.3).\n *\n * Each API returns a {@link Node} built with {@link node}, {@link producer},\n * {@link derived}, or {@link effect} — no second protocol.\n *\n * Protocol/system/ingest adapters (fromHTTP, fromWebSocket, fromKafka, etc.)\n * live in {@link ./adapters.ts}.\n */\n\nimport { wallClockNs } from \"../core/clock.js\";\nimport { COMPLETE, DATA, DIRTY, ERROR, RESOLVED } from \"../core/messages.js\";\nimport { type Node, type NodeOptions, type NodeSink, node } from \"../core/node.js\";\nimport { producer, state } from \"../core/sugar.js\";\nimport { type CronSchedule, matchesCron, parseCron } from \"./cron.js\";\n\ntype ExtraOpts = Omit<NodeOptions<unknown>, \"describeKind\">;\n\nfunction sourceOpts<T = unknown>(opts?: ExtraOpts): NodeOptions<T> {\n\treturn { describeKind: \"producer\", ...opts } as NodeOptions<T>;\n}\n\n/** Options for {@link fromTimer} / {@link fromPromise} / {@link fromAsyncIter}. */\nexport type AsyncSourceOpts = ExtraOpts & { signal?: AbortSignal };\n\n/**\n * Values accepted by {@link fromAny}.\n *\n * @category extra\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Options for {@link fromCron}. */\nexport type FromCronOptions = ExtraOpts & {\n\t/** Polling interval in ms. Default `60_000`. */\n\ttickMs?: number;\n\t/** Output format: `\"timestamp_ns\"` (default) emits wall-clock nanoseconds; `\"date\"` emits a `Date` object. */\n\toutput?: \"timestamp_ns\" | \"date\";\n};\n\n/** DOM-style event target (browser or `node:events`). */\nexport type EventTargetLike = {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (ev: unknown) => void,\n\t\toptions?: boolean | { capture?: boolean; passive?: boolean; once?: boolean },\n\t): void;\n};\n\n/** @internal Shared with adapters.ts and sources-fs.ts for glob matching. */\nexport function escapeRegexChar(ch: string): string {\n\treturn /[\\\\^$+?.()|[\\]{}]/.test(ch) ? `\\\\${ch}` : ch;\n}\n\n/** @internal */\nexport function globToRegExp(glob: string): RegExp {\n\tlet out = \"^\";\n\tfor (let i = 0; i < glob.length; i += 1) {\n\t\tconst ch = glob[i];\n\t\tif (ch === \"*\") {\n\t\t\tconst next = glob[i + 1];\n\t\t\tif (next === \"*\") {\n\t\t\t\tout += \".*\";\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tout += \"[^/]*\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tout += escapeRegexChar(ch);\n\t}\n\tout += \"$\";\n\treturn new RegExp(out);\n}\n\n/** @internal */\nexport function matchesAnyPattern(path: string, patterns: RegExp[]): boolean {\n\tfor (const pattern of patterns) {\n\t\tif (pattern.test(path)) return true;\n\t}\n\treturn false;\n}\n\nfunction wrapSubscribeHook<T>(inner: Node<T>, before: (sink: NodeSink) => void): Node<T> {\n\t// node() passthrough instead of derived([inner], ([v]) => v) — derived uses\n\t// .at(-1) and would drop intermediate values from multi-DATA batches (D1 gap).\n\tconst wrapper = node<T>(\n\t\t[inner as Node],\n\t\t(data, a) => {\n\t\t\tconst batch0 = data[0];\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\ta.down([[RESOLVED]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (const v of batch0) a.emit(v as T);\n\t\t},\n\t\t{ describeKind: \"derived\", initial: inner.cache as T },\n\t);\n\tconst origSubscribe = wrapper.subscribe.bind(wrapper);\n\t(wrapper as { subscribe: typeof wrapper.subscribe }).subscribe = (sink, actor) => {\n\t\tbefore(sink);\n\t\treturn origSubscribe(sink, actor);\n\t};\n\treturn wrapper;\n}\n\n/**\n * Builds a timer-driven source: one-shot (first tick then `COMPLETE`) or periodic (`0`, `1`, `2`, …).\n *\n * @param ms - Milliseconds before the first emission.\n * @param opts - Producer options plus optional `period` for repeating ticks and optional `signal` (`AbortSignal`) to cancel with `ERROR`.\n * @returns `Node<number>` — tick counter from `0`; teardown clears timers.\n *\n * @example\n * ```ts\n * import { fromTimer } from \"@graphrefly/graphrefly-ts\";\n *\n * fromTimer(250, { period: 1_000 });\n * ```\n *\n * @category extra\n */\nexport function fromTimer(ms: number, opts?: AsyncSourceOpts & { period?: number }): Node<number> {\n\tconst { signal, period, ...rest } = opts ?? {};\n\treturn producer<number>((a) => {\n\t\tlet done = false;\n\t\tlet count = 0;\n\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tdone = true;\n\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst finish = () => {\n\t\t\tif (done) return;\n\t\t\tif (period != null) {\n\t\t\t\ta.emit(count++);\n\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\tif (done) return;\n\t\t\t\t\ta.emit(count++);\n\t\t\t\t}, period);\n\t\t\t} else {\n\t\t\t\t// One-shot: mark done, emit, complete synchronously.\n\t\t\t\t// a.emit() delivers DATA to downstream synchronously before\n\t\t\t\t// COMPLETE arrives — no queueMicrotask needed.\n\t\t\t\tdone = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.emit(count++);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t}\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (done) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tt = setTimeout(finish, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\treturn cleanup;\n\t}, sourceOpts(rest));\n}\n\n/**\n * Animation-frame-driven source. Emits on every `requestAnimationFrame` tick,\n * yielding the frame timestamp (DOMHighResTimeStamp, ms since navigation).\n *\n * Use instead of `fromTimer({ period: 16 })` when animation smoothness matters.\n * In a real browser, `requestAnimationFrame` synchronizes with the display\n * refresh. The source keeps ticking even when the tab is hidden — it\n * transparently switches to `setTimeout` while the tab is backgrounded (so\n * downstream state updates continue) and returns to `requestAnimationFrame`\n * when the tab regains focus.\n *\n * When `requestAnimationFrame` is unavailable (Node test environments, SSR),\n * this falls back to `setTimeout(~16ms)` unconditionally. Abortable via\n * `signal` (emits `ERROR`).\n *\n * @example\n * ```ts\n * import { fromRaf, derived } from \"@graphrefly/graphrefly-ts\";\n *\n * const frame = fromRaf();\n * const bouncingX = derived([frame], ([t]) => 50 + 40 * Math.sin((t as number) * 0.001));\n * ```\n *\n * @category extra\n */\nexport function fromRaf(opts?: AsyncSourceOpts): Node<number> {\n\tconst { signal, ...rest } = opts ?? {};\n\treturn producer<number>((a) => {\n\t\tlet done = false;\n\t\tlet rafId: number | undefined;\n\t\tlet fallbackTimer: ReturnType<typeof setTimeout> | undefined;\n\t\tlet abortListenerAdded = false;\n\t\tlet visibilityListenerAdded = false;\n\n\t\tconst raf: typeof requestAnimationFrame | undefined =\n\t\t\ttypeof requestAnimationFrame === \"function\" ? requestAnimationFrame : undefined;\n\t\tconst caf: typeof cancelAnimationFrame | undefined =\n\t\t\ttypeof cancelAnimationFrame === \"function\" ? cancelAnimationFrame : undefined;\n\t\tconst doc: Document | undefined = typeof document !== \"undefined\" ? document : undefined;\n\n\t\tconst clearPending = () => {\n\t\t\tif (rafId !== undefined && caf) caf(rafId);\n\t\t\tif (fallbackTimer !== undefined) clearTimeout(fallbackTimer);\n\t\t\trafId = undefined;\n\t\t\tfallbackTimer = undefined;\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tdone = true;\n\t\t\tclearPending();\n\t\t\tif (abortListenerAdded) {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tabortListenerAdded = false;\n\t\t\t}\n\t\t\tif (visibilityListenerAdded && doc) {\n\t\t\t\tdoc.removeEventListener(\"visibilitychange\", onVisibilityChange);\n\t\t\t\tvisibilityListenerAdded = false;\n\t\t\t}\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (done) return;\n\t\t\tcleanup();\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tconst tick = (now: number) => {\n\t\t\tif (done) return;\n\t\t\ta.emit(now);\n\t\t\tscheduleNext();\n\t\t};\n\t\tconst scheduleNext = () => {\n\t\t\tif (done) return;\n\t\t\t// Prefer rAF for display-synced ticks when the tab is visible; when\n\t\t\t// hidden, rAF is throttled to ~0 by the browser, so fall back to\n\t\t\t// setTimeout so downstream state continues updating.\n\t\t\tif (raf && (!doc || doc.visibilityState !== \"hidden\")) {\n\t\t\t\trafId = raf(tick);\n\t\t\t} else {\n\t\t\t\tfallbackTimer = setTimeout(() => tick(performance.now()), 16);\n\t\t\t}\n\t\t};\n\t\tconst onVisibilityChange = () => {\n\t\t\tif (done) return;\n\t\t\t// Cancel any pending schedule and re-schedule via the path now\n\t\t\t// appropriate for the current visibility state.\n\t\t\tclearPending();\n\t\t\tscheduleNext();\n\t\t};\n\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn cleanup;\n\t\t}\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tabortListenerAdded = signal !== undefined;\n\t\tif (doc && raf) {\n\t\t\tdoc.addEventListener(\"visibilitychange\", onVisibilityChange);\n\t\t\tvisibilityListenerAdded = true;\n\t\t}\n\t\tscheduleNext();\n\t\treturn cleanup;\n\t}, sourceOpts(rest));\n}\n\n/**\n * Polls on an interval; when the current minute matches a 5-field cron expression, emits once (see {@link parseCron}).\n *\n * @param expr - Cron string (`min hour dom month dow`).\n * @param opts - Producer options plus `tickMs` (default `60_000`) and `output` (`timestamp_ns` default, or `date` for `Date` values).\n * @returns `Node<number>` (nanosecond timestamp) or `Node<Date>` when `output: \"date\"`.\n *\n * @example\n * ```ts\n * import { fromCron } from \"@graphrefly/graphrefly-ts\";\n *\n * fromCron(\"0 9 * * 1\");\n * ```\n *\n * @category extra\n */\nexport function fromCron(expr: string, opts?: FromCronOptions & { output: \"date\" }): Node<Date>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number>;\nexport function fromCron(expr: string, opts?: FromCronOptions): Node<number | Date> {\n\tconst schedule: CronSchedule = parseCron(expr);\n\tconst { tickMs: tickOpt, output, ...rest } = opts ?? {};\n\tconst tickMs = tickOpt ?? 60_000;\n\tconst emitDate = output === \"date\";\n\treturn producer<number | Date>(\n\t\t(a) => {\n\t\t\tlet lastFiredKey = -1;\n\t\t\tconst check = () => {\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key =\n\t\t\t\t\tnow.getFullYear() * 100_000_000 +\n\t\t\t\t\t(now.getMonth() + 1) * 1_000_000 +\n\t\t\t\t\tnow.getDate() * 10_000 +\n\t\t\t\t\tnow.getHours() * 100 +\n\t\t\t\t\tnow.getMinutes();\n\t\t\t\tif (key !== lastFiredKey && matchesCron(schedule, now)) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\ta.emit(emitDate ? now : wallClockNs());\n\t\t\t\t}\n\t\t\t};\n\t\t\tcheck();\n\t\t\tconst id = setInterval(check, tickMs);\n\t\t\treturn () => clearInterval(id);\n\t\t},\n\t\t{ ...sourceOpts(rest), name: rest.name ?? `cron:${expr}` },\n\t);\n}\n\n/**\n * Wraps a DOM-style `addEventListener` target; each event becomes a `DATA` emission.\n *\n * @param target - Object with `addEventListener` / `removeEventListener`.\n * @param type - Event name (e.g. `\"click\"`).\n * @param opts - Producer options plus listener options (`capture`, `passive`, `once`).\n * @returns `Node<T>` — event payloads; teardown removes the listener.\n *\n * @example\n * ```ts\n * import { fromEvent } from \"@graphrefly/graphrefly-ts\";\n *\n * fromEvent(document.body, \"click\");\n * ```\n *\n * @category extra\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts?: ExtraOpts & { capture?: boolean; passive?: boolean; once?: boolean },\n): Node<T> {\n\tconst { capture, passive, once, ...rest } = opts ?? {};\n\treturn producer<T>((a) => {\n\t\tconst handler = (e: unknown) => {\n\t\t\ta.emit(e as T);\n\t\t};\n\t\tconst options = { capture, passive, once };\n\t\ttarget.addEventListener(type, handler, options);\n\t\treturn () => target.removeEventListener(type, handler, options);\n\t}, sourceOpts(rest));\n}\n\n/**\n * Drains a synchronous iterable; each item is `DATA`, then `COMPLETE`, or `ERROR` if iteration throws.\n *\n * @param iterable - Values to emit in order.\n * @param opts - Optional producer options.\n * @returns `Node<T>` — one emission per element.\n *\n * @example\n * ```ts\n * import { fromIter } from \"@graphrefly/graphrefly-ts\";\n *\n * fromIter([1, 2, 3]);\n * ```\n *\n * @category extra\n */\nexport function fromIter<T>(iterable: Iterable<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((a) => {\n\t\tlet cancelled = false;\n\t\ttry {\n\t\t\tfor (const x of iterable) {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ta.emit(x);\n\t\t\t}\n\t\t\tif (!cancelled) a.down([[COMPLETE]]);\n\t\t} catch (e) {\n\t\t\tif (!cancelled) a.down([[ERROR, e]]);\n\t\t}\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t};\n\t}, sourceOpts(opts));\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\n/**\n * Lifts a Promise (or thenable) to a single-value stream: one `DATA` then `COMPLETE`, or `ERROR` on rejection.\n *\n * @param p - Promise to await.\n * @param opts - Producer options plus optional `signal` for abort → `ERROR` with reason.\n * @returns `Node<T>` — settles once.\n *\n * @example\n * ```ts\n * import { fromPromise } from \"@graphrefly/graphrefly-ts\";\n *\n * fromPromise(Promise.resolve(42));\n * ```\n *\n * @category extra\n */\nexport function fromPromise<T>(p: Promise<T> | PromiseLike<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal, ...rest } = opts ?? {};\n\treturn producer<T>((a) => {\n\t\tlet settled = false;\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\ta.down([[ERROR, signal!.reason]]);\n\t\t};\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tvoid Promise.resolve(p).then(\n\t\t\t(v) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.emit(v as T);\n\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t},\n\t\t\t(e) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\ta.down([[ERROR, e]]);\n\t\t\t},\n\t\t);\n\t\treturn () => {\n\t\t\tsettled = true;\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\n/**\n * Reads an async iterable; each `next()` value becomes `DATA`; `COMPLETE` when done; `ERROR` on failure.\n *\n * @param iterable - Async source (`for await` shape).\n * @param opts - Producer options plus optional `signal` to abort the pump.\n * @returns `Node<T>` — async pull stream.\n *\n * @example\n * ```ts\n * import { fromAsyncIter } from \"@graphrefly/graphrefly-ts\";\n *\n * async function* gen() {\n * yield 1;\n * }\n * fromAsyncIter(gen());\n * ```\n *\n * @category extra\n */\nexport function fromAsyncIter<T>(iterable: AsyncIterable<T>, opts?: AsyncSourceOpts): Node<T> {\n\tconst { signal: outerSignal, ...rest } = opts ?? {};\n\treturn producer<T>((a) => {\n\t\tconst ac = new AbortController();\n\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\tif (outerSignal?.aborted) {\n\t\t\tac.abort(outerSignal.reason);\n\t\t} else {\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t}\n\t\tconst signal = outerSignal ?? ac.signal;\n\t\tlet cancelled = false;\n\t\tconst it = iterable[Symbol.asyncIterator]();\n\t\t// Each pump() call chains directly into the next via Promise.then —\n\t\t// no queueMicrotask needed; Promise resolution already yields to the\n\t\t// microtask queue. COMPLETE is delivered synchronously after the last\n\t\t// value, same as fromIter semantics.\n\t\tconst pump = (): void => {\n\t\t\tif (cancelled || signal.aborted) return;\n\t\t\tvoid Promise.resolve(it.next()).then(\n\t\t\t\t(step) => {\n\t\t\t\t\tif (cancelled || signal.aborted) return;\n\t\t\t\t\tif (step.done) {\n\t\t\t\t\t\ta.down([[COMPLETE]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ta.emit(step.value as T);\n\t\t\t\t\tpump();\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (!cancelled && !signal.aborted) a.down([[ERROR, e]]);\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\t\tpump();\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\tac.abort();\n\t\t\tvoid Promise.resolve(it.return?.()).catch(() => undefined);\n\t\t};\n\t}, sourceOpts(rest));\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\t\"cache\" in x &&\n\t\ttypeof (x as Node).subscribe === \"function\"\n\t);\n}\n\n/**\n * Coerces a value to a `Node` by shape: existing `Node` passthrough, thenable → {@link fromPromise},\n * async iterable → {@link fromAsyncIter}, sync iterable → {@link fromIter}, else scalar → {@link of}.\n *\n * @param input - Any value to wrap.\n * @param opts - Passed through when a Promise/async path is chosen.\n * @returns `Node` of the inferred element type.\n *\n * @example\n * ```ts\n * import { fromAny, state } from \"@graphrefly/graphrefly-ts\";\n *\n * fromAny(state(1));\n * fromAny(Promise.resolve(2));\n * ```\n *\n * @category extra\n */\nexport function fromAny<T>(input: NodeInput<T>, opts?: AsyncSourceOpts): Node<T> {\n\tif (isNode(input)) {\n\t\treturn input as Node<T>;\n\t}\n\tif (isThenable(input)) {\n\t\treturn fromPromise(input as PromiseLike<T>, opts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as { [Symbol.asyncIterator]?: unknown; [Symbol.iterator]?: unknown };\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn fromAsyncIter(input as AsyncIterable<T>, opts);\n\t\t}\n\t\tif (typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn fromIter(input as Iterable<T>, opts);\n\t\t}\n\t}\n\t// scalar fallback\n\treturn of(input as T);\n}\n\n/**\n * Emits each argument as `DATA` in order, then `COMPLETE` (implemented via {@link fromIter}).\n *\n * @param values - Values to emit.\n * @returns `Node<T>` — finite sequence.\n *\n * @example\n * ```ts\n * import { of } from \"@graphrefly/graphrefly-ts\";\n *\n * of(1, 2, 3);\n * ```\n *\n * @category extra\n */\nexport function of<T>(...values: T[]): Node<T> {\n\treturn fromIter(values, undefined);\n}\n\n/**\n * Completes immediately with no `DATA` (cold `EMPTY` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — terminal `COMPLETE` only.\n *\n * @example\n * ```ts\n * import { empty } from \"@graphrefly/graphrefly-ts\";\n *\n * empty();\n * ```\n *\n * @category extra\n */\nexport function empty<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>((a) => {\n\t\ta.down([[COMPLETE]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Never emits and never completes until teardown (cold `NEVER` analogue).\n *\n * @param opts - Optional producer options.\n * @returns `Node<T>` — silent until unsubscribed.\n *\n * @example\n * ```ts\n * import { never } from \"@graphrefly/graphrefly-ts\";\n *\n * never();\n * ```\n *\n * @category extra\n */\nexport function never<T = never>(opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(() => undefined, sourceOpts(opts));\n}\n\n/**\n * Emits `ERROR` as soon as the producer starts (cold error source).\n *\n * @param err - Error payload forwarded as `ERROR` data.\n * @param opts - Optional producer options.\n * @returns `Node<never>` — terminates with `ERROR`.\n *\n * @example\n * ```ts\n * import { throwError } from \"@graphrefly/graphrefly-ts\";\n *\n * throwError(new Error(\"fail\"));\n * ```\n *\n * @category extra\n */\nexport function throwError(err: unknown, opts?: ExtraOpts): Node<never> {\n\treturn producer<never>((a) => {\n\t\ta.down([[ERROR, err]]);\n\t\treturn undefined;\n\t}, sourceOpts(opts));\n}\n\n/**\n * Subscribes immediately and runs `fn` for each upstream `DATA`; returns unsubscribe.\n *\n * @param source - Upstream node.\n * @param fn - Side effect per value.\n * @param opts - Effect node options.\n * @returns Unsubscribe function (idempotent).\n *\n * @example\n * ```ts\n * import { forEach, state } from \"@graphrefly/graphrefly-ts\";\n *\n * const u = forEach(state(1), (v) => console.log(v));\n * u();\n * ```\n *\n * @category extra\n */\nexport function forEach<T>(source: Node<T>, fn: (value: T) => void, opts?: ExtraOpts): () => void {\n\tconst inner = node(\n\t\t[source as Node],\n\t\t(data, _actions) => {\n\t\t\tconst batch0 = data[0];\n\t\t\tif (batch0 != null && batch0.length > 0) {\n\t\t\t\tfor (const v of batch0) fn(v as T);\n\t\t\t}\n\t\t},\n\t\t{ describeKind: \"effect\", ...opts } as NodeOptions,\n\t);\n\treturn inner.subscribe(() => {});\n}\n\n/**\n * Buffers every `DATA`; on upstream `COMPLETE` emits one `DATA` with the full array then `COMPLETE`.\n *\n * @param source - Upstream node.\n * @param opts - Optional node options (derived describe kind).\n * @returns `Node<T[]>` — single array emission before completion.\n *\n * @example\n * ```ts\n * import { of, toArray } from \"@graphrefly/graphrefly-ts\";\n *\n * toArray(of(1, 2, 3));\n * ```\n *\n * @category extra\n */\nexport function toArray<T>(source: Node<T>, opts?: ExtraOpts): Node<T[]> {\n\treturn node<T[]>(\n\t\t[source as Node],\n\t\t(data, actions, ctx) => {\n\t\t\tif (!ctx.store.buf) ctx.store.buf = [];\n\t\t\tconst buf = ctx.store.buf as T[];\n\t\t\t// Accumulate DATA first — must happen before the COMPLETE check so\n\t\t\t// that a same-wave DATA+COMPLETE batch (e.g. fromTimer one-shot,\n\t\t\t// fromIter last item) is included in the emitted array.\n\t\t\tconst batch0 = data[0];\n\t\t\tif (batch0 != null && batch0.length > 0) {\n\t\t\t\tfor (const v of batch0) buf.push(v as T);\n\t\t\t}\n\t\t\t// COMPLETE: emit accumulated array then complete.\n\t\t\t// ERROR: autoError propagates; do NOT emit the partial buffer.\n\t\t\tif (ctx.terminalDeps[0] === true) {\n\t\t\t\tactions.emit([...buf]);\n\t\t\t\tactions.down([[COMPLETE]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// RESOLVED wave: propagate RESOLVED. Covers first-wave case; after first\n\t\t\t// call the pre-fn skip handles this automatically.\n\t\t\tif (batch0 == null || batch0.length === 0) {\n\t\t\t\tactions.down([[RESOLVED]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tdescribeKind: \"derived\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t...opts,\n\t\t} as NodeOptions<T[]>,\n\t);\n}\n\n/**\n * Multicasts upstream: one subscription to `source` while this wrapper has subscribers (via {@link producer}).\n *\n * @param source - Upstream node to share.\n * @param opts - Producer options; `initial` seeds from `source.cache` when set by factory.\n * @returns `Node<T>` — hot ref-counted bridge.\n *\n * @example\n * ```ts\n * import { share, state } from \"@graphrefly/graphrefly-ts\";\n *\n * share(state(0));\n * ```\n *\n * @category extra\n */\nexport function share<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn producer<T>(\n\t\t(a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts<T>(opts), initial: source.cache },\n\t);\n}\n\n/**\n * Like {@link share} with a bounded replay buffer: new subscribers receive the last `bufferSize`\n * `DATA` payloads (as separate batches) before live updates.\n *\n * @param source - Upstream node.\n * @param bufferSize - Maximum past values to replay (≥ 1).\n * @param opts - Producer options.\n * @returns `Node<T>` — multicast with replay on subscribe.\n *\n * @example\n * ```ts\n * import { replay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * replay(state(0), 3);\n * ```\n *\n * @category extra\n */\nexport function replay<T>(source: Node<T>, bufferSize: number, opts?: ExtraOpts): Node<T> {\n\tif (bufferSize < 1) throw new RangeError(\"replay expects bufferSize >= 1\");\n\tconst buf: T[] = [];\n\tconst inner = producer<T>(\n\t\t(a) =>\n\t\t\tsource.subscribe((msgs) => {\n\t\t\t\tfor (const m of msgs) {\n\t\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\t\tbuf.push(m[1] as T);\n\t\t\t\t\t\tif (buf.length > bufferSize) buf.shift();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ta.down(msgs);\n\t\t\t}),\n\t\t{ ...sourceOpts<T>(opts), initial: source.cache },\n\t);\n\treturn wrapSubscribeHook(inner, (sink) => {\n\t\tfor (const v of buf) {\n\t\t\tsink([[DATA, v]]);\n\t\t}\n\t});\n}\n\n/**\n * {@link replay} with `bufferSize === 1` — replays the latest `DATA` to new subscribers.\n *\n * @param source - Upstream node.\n * @param opts - Producer options.\n * @returns `Node<T>` — share + last-value replay.\n *\n * @example\n * ```ts\n * import { cached, state } from \"@graphrefly/graphrefly-ts\";\n *\n * cached(state(0));\n * ```\n *\n * @category extra\n */\nexport function cached<T>(source: Node<T>, opts?: ExtraOpts): Node<T> {\n\treturn replay(source, 1, opts);\n}\n\n/**\n * Converts the first `DATA` on `source` into a Promise; rejects on `ERROR` or `COMPLETE` without data.\n *\n * **Important:** This subscribes and waits for a **future** emission. Data that\n * has already flowed is gone and will not be seen. Call this *before* the upstream\n * emits, or use `source.cache` / `source.status` for already-cached state.\n * See COMPOSITION-GUIDE §2 (subscription ordering).\n *\n * @param source - Node to read once.\n * @returns Promise of the first value.\n *\n * @example\n * ```ts\n * import { firstValueFrom, of } from \"@graphrefly/graphrefly-ts\";\n *\n * await firstValueFrom(of(42));\n * ```\n *\n * @category extra\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet shouldUnsub = false;\n\t\tlet unsub: (() => void) | undefined;\n\t\tunsub = source.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (settled) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tresolve(m[1] as T);\n\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\tunsub();\n\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(m[1]);\n\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\tunsub();\n\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(new Error(\"completed without DATA\"));\n\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\tunsub();\n\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (shouldUnsub) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t}\n\t});\n}\n\n/**\n * Wait for the first DATA value from `source` that satisfies `predicate`.\n *\n * Subscribes directly and resolves on the first DATA value where\n * `predicate` returns true. Reactive, no polling. Use in tests and\n * bridging code where you need a single matching value as a Promise.\n *\n * **Important:** This only captures **future** emissions — data that has\n * already flowed through the node is gone. Call this *before* the upstream\n * emits. For already-cached values, use `source.cache` / `source.status`.\n * See COMPOSITION-GUIDE §2 (subscription ordering).\n *\n * ```ts\n * const val = await firstWhere(strategy.node, snap => snap.size > 0);\n * ```\n *\n * @category extra\n */\nexport function firstWhere<T>(source: Node<T>, predicate: (value: T) => boolean): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet shouldUnsub = false;\n\t\tlet unsub: (() => void) | undefined;\n\t\tunsub = source.subscribe((msgs) => {\n\t\t\tfor (const m of msgs) {\n\t\t\t\tif (settled) return;\n\t\t\t\tif (m[0] === DATA) {\n\t\t\t\t\tconst v = m[1] as T;\n\t\t\t\t\tif (predicate(v)) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tresolve(v);\n\t\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\t\tunsub();\n\t\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (m[0] === ERROR) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(m[1]);\n\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\tunsub();\n\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (m[0] === COMPLETE) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treject(new Error(\"completed without matching value\"));\n\t\t\t\t\tif (unsub) {\n\t\t\t\t\t\tunsub();\n\t\t\t\t\t\tunsub = undefined;\n\t\t\t\t\t} else shouldUnsub = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (shouldUnsub) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t}\n\t});\n}\n\n// ——————————————————————————————————————————————————————————————\n// RxJS-compatible aliases\n// ——————————————————————————————————————————————————————————————\n\n/**\n * RxJS-named alias for {@link replay} — multicast with a replay buffer of size `bufferSize`.\n *\n * @param source - Upstream node.\n * @param bufferSize - Replay depth (≥ 1).\n * @param opts - Producer options.\n * @returns Same behavior as `replay`.\n *\n * @example\n * ```ts\n * import { shareReplay, state } from \"@graphrefly/graphrefly-ts\";\n *\n * shareReplay(state(0), 5);\n * ```\n *\n * @category extra\n */\nexport const shareReplay = replay;\n\n// ---------------------------------------------------------------------------\n// keepalive\n// ---------------------------------------------------------------------------\n\n/**\n * Activate a compute node's upstream wiring without a real sink.\n *\n * Derived/effect nodes are lazy — they don't compute until at least one\n * subscriber exists (COMPOSITION-GUIDE §5). `keepalive` subscribes with an\n * empty sink so the node stays wired for `.cache` and upstream propagation.\n *\n * Returns the unsubscribe handle. Common usage:\n * `graph.addDisposer(keepalive(node))`.\n *\n * @category extra\n */\nexport function keepalive(n: Node<unknown>): () => void {\n\treturn n.subscribe(() => {});\n}\n\n// ---------------------------------------------------------------------------\n// reactiveCounter\n// ---------------------------------------------------------------------------\n\n/** Bundle returned by {@link reactiveCounter}. */\nexport type ReactiveCounterBundle = {\n\t/** Reactive node holding the current count. */\n\treadonly node: Node<number>;\n\t/** Increment by 1. Returns `false` if cap would be exceeded. */\n\tincrement(): boolean;\n\t/** Current count (synchronous read). */\n\tget(): number;\n\t/** Whether the counter has reached its cap. */\n\tatCap(): boolean;\n};\n\n/**\n * Reactive counter with a cap — the building block for circuit breakers.\n *\n * Wraps a `state(0)` node with `increment()` that respects a maximum.\n * The `node` is subscribable and composable like any reactive node. When\n * the cap is reached, `increment()` returns `false`.\n *\n * ```ts\n * const retries = reactiveCounter(10);\n * retries.increment(); // true — count is now 1\n * retries.node.subscribe(...); // reactive updates\n * retries.atCap(); // false\n * ```\n *\n * @param cap - Maximum value (inclusive). 0 = no increments allowed.\n * @category extra\n */\nexport function reactiveCounter(cap: number): ReactiveCounterBundle {\n\tconst counter = state(0);\n\treturn {\n\t\tnode: counter,\n\t\tincrement() {\n\t\t\tconst current = counter.cache ?? 0;\n\t\t\tif (current >= cap) return false;\n\t\t\tcounter.down([[DIRTY], [DATA, current + 1]]);\n\t\t\treturn true;\n\t\t},\n\t\tget() {\n\t\t\treturn counter.cache ?? 0;\n\t\t},\n\t\tatCap() {\n\t\t\treturn (counter.cache ?? 0) >= cap;\n\t\t},\n\t};\n}\n","/**\n * Shared internal utilities for the patterns layer.\n *\n * These are private helpers used across multiple pattern modules. They are NOT\n * part of the public API — import from `./patterns/index.js` for public exports.\n *\n * General-purpose reactive utilities (`keepalive`, `reactiveCounter`) live in\n * `extra/sources.ts` and are re-exported here for convenience.\n *\n * @internal\n * @module\n */\n\nimport { downWithBatch } from \"../core/batch.js\";\nimport { DATA, DIRTY } from \"../core/messages.js\";\nimport type { Node } from \"../core/node.js\";\nimport { defaultConfig } from \"../core/node.js\";\n\n// Re-export general-purpose utilities from extra (canonical home).\nexport { keepalive, reactiveCounter } from \"../extra/sources.js\";\n\n// ---------------------------------------------------------------------------\n// emitToMeta\n// ---------------------------------------------------------------------------\n\n/**\n * Forward a single `[DATA, value]` to a meta companion node via tier-3\n * deferral, tolerating absent companions. Used by patterns that publish\n * per-wave statistics alongside their main output (cache-hit-rate,\n * segment-count, layout-time-ns, etc.) — subscribers see the parent's\n * DATA first because phase-2 completes before phase-3 during drain.\n *\n * // Expands to: `if (meta) downWithBatch(meta, [[Type, value]])` with null-guard.\n *\n * @internal\n */\nexport function emitToMeta<T>(metaNode: Node<T> | undefined, value: T): void {\n\tif (metaNode == null) return;\n\tdownWithBatch((msgs) => metaNode.down(msgs), [[DATA, value]], defaultConfig.tierOf);\n}\n\n// ---------------------------------------------------------------------------\n// tryIncrementBounded\n// ---------------------------------------------------------------------------\n\n/**\n * Bounded increment for a self-owned counter state node.\n *\n * Reads `counter.cache`, bumps by 1 if under `cap`, writes back. Returns\n * `false` when the cap is reached. Documented P3 exception: the counter is\n * not a declared dep of the caller — it's a private budget read+written from\n * a single call site. This helper keeps the `.cache` access in one named\n * place.\n *\n * **Safety today:**\n * 1. Single-threaded JS runner never invokes the caller concurrently.\n * 2. `counter.down` writes the cache synchronously before returning, so\n * synchronous re-entry through a downstream publish reads the\n * freshly-incremented value — no double-count.\n *\n * **Future risk:** under a free-threaded runner (PY no-GIL or hypothetical\n * concurrent TS runner), two concurrent firings could still race. Revisit\n * when that surfaces.\n *\n * @internal\n */\nexport function tryIncrementBounded(counter: Node<number>, cap: number): boolean {\n\tconst cur = (counter.cache as number | undefined) ?? 0;\n\tif (cur >= cap) return false;\n\tcounter.down([[DIRTY], [DATA, cur + 1]]);\n\treturn true;\n}\n\n// ---------------------------------------------------------------------------\n// domainMeta\n// ---------------------------------------------------------------------------\n\n/**\n * Build a domain metadata object for pattern-layer nodes.\n *\n * Each domain (orchestration, messaging, reduction, ai, cqrs, domain_template)\n * follows the same shape: `{ [domain]: true, [domain]_type: kind, ...extra }`.\n *\n * @param domain - The domain tag (e.g. `\"orchestration\"`, `\"ai\"`, `\"cqrs\"`).\n * @param kind - The specific type within the domain (e.g. `\"gate\"`, `\"prompt\"`).\n * @param extra - Additional metadata to merge.\n * @returns Metadata object.\n *\n * @internal\n */\nexport function domainMeta(\n\tdomain: string,\n\tkind: string,\n\textra?: Record<string, unknown>,\n): Record<string, unknown> {\n\treturn {\n\t\t[domain]: true,\n\t\t[`${domain}_type`]: kind,\n\t\t...(extra ?? {}),\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// trackingKey\n// ---------------------------------------------------------------------------\n\n/**\n * Stable tracking key for an item with retry/reingestion decoration.\n *\n * Uses `relatedTo[0]` if present (carries the original key forward through\n * retries and reingestions). Falls back to `summary` for first-time items.\n *\n * This avoids deriving keys from mutated summary strings — retries decorate\n * the summary with `[RETRY N/M]` and failure context, so regex-stripping\n * would be fragile and any new decoration pattern would risk infinite loops\n * by generating novel keys.\n *\n * @internal\n */\nexport function trackingKey(item: { summary: string; relatedTo?: string[] }): string {\n\treturn item.relatedTo?.[0] ?? item.summary;\n}\n","/**\n * Messaging patterns (roadmap §4.2).\n *\n * Pulsar-inspired messaging features modeled as graph factories:\n * - `topic()` for append-only topic streams\n * - `subscription()` for cursor-based consumers\n * - `jobQueue()` for queue claim/ack flow\n */\n\nimport { batch, COMPLETE, DATA, derived, type Node, node, state } from \"../core/index.js\";\nimport { reactiveList } from \"../extra/reactive-list.js\";\nimport { reactiveLog } from \"../extra/reactive-log.js\";\nimport { reactiveMap } from \"../extra/reactive-map.js\";\nimport { Graph, type GraphOptions } from \"../graph/index.js\";\n\nconst DEFAULT_MAX_PER_PUMP = 2_147_483_647;\n\nfunction requireNonNegativeInt(value: number, label: string): number {\n\tif (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n\t\tthrow new Error(`${label} must be a non-negative integer`);\n\t}\n\treturn value;\n}\n\nimport { domainMeta, keepalive } from \"./_internal.js\";\n\nfunction messagingMeta(kind: string, extra?: Record<string, unknown>): Record<string, unknown> {\n\treturn domainMeta(\"messaging\", kind, extra);\n}\n\nexport type TopicOptions = {\n\tgraph?: GraphOptions;\n\tretainedLimit?: number;\n};\n\nexport class TopicGraph<T> extends Graph {\n\tprivate readonly _log;\n\treadonly events: Node<readonly T[]>;\n\t/**\n\t * Most recently published value, or `null` when the topic has no entries\n\t * yet. Spec §5.12 reserves `undefined` as the protocol-internal \"never\n\t * sent DATA\" sentinel — `null` is the idiomatic \"empty / no value\" signal\n\t * for domain nodes. F7.\n\t *\n\t * **Caveat when `T` itself includes `null`** (e.g., `topic<number | null>`):\n\t * `latest === null` is ambiguous — it could mean \"no publish yet\" OR \"a\n\t * `null` value was published\". Use {@link hasLatest} to disambiguate, or\n\t * observe {@link events} directly and track length yourself.\n\t */\n\treadonly latest: Node<T | null>;\n\t/**\n\t * Reactive `true` once the topic has at least one published entry.\n\t * Disambiguates \"`null` never published\" from \"`null` was published\" when\n\t * `T` includes `null`.\n\t */\n\treadonly hasLatest: Node<boolean>;\n\n\tconstructor(name: string, opts: TopicOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._log = reactiveLog<T>([], { name: \"events\", maxSize: opts.retainedLimit });\n\t\tthis.events = this._log.entries;\n\t\tthis.add(\"events\", this.events);\n\t\tthis.latest = derived<T | null>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => {\n\t\t\t\tconst entries = snapshot as readonly T[];\n\t\t\t\treturn entries.length === 0 ? null : (entries[entries.length - 1] as T);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"latest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"latest\", this.latest);\n\t\tthis.addDisposer(keepalive(this.latest));\n\n\t\tthis.hasLatest = derived<boolean>(\n\t\t\t[this.events],\n\t\t\t([snapshot]) => (snapshot as readonly T[]).length > 0,\n\t\t\t{\n\t\t\t\tname: \"hasLatest\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"topic_has_latest\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"hasLatest\", this.hasLatest);\n\t\tthis.addDisposer(keepalive(this.hasLatest));\n\n\t\t// D1(a): on teardown, propagate COMPLETE on `events` so downstream\n\t\t// derived chains (including any externally-held SubscriptionGraph\n\t\t// sources) see the termination via their `terminalDeps` and can stop\n\t\t// serving stale caches. Tier-3 terminal per spec §2.2.\n\t\tthis.addDisposer(() => {\n\t\t\tthis.events.down([[COMPLETE]]);\n\t\t});\n\t\t// P9: release any memoized tail/slice view keepalives held by the log.\n\t\t// TopicGraph itself doesn't call log.tail/slice, but plugins may have\n\t\t// attached views via `_log` — defensive.\n\t\tthis.addDisposer(() => this._log.disposeAllViews());\n\t}\n\n\tpublish(value: T): void {\n\t\tthis._log.append(value);\n\t}\n\n\tretained(): readonly T[] {\n\t\treturn this.events.cache as readonly T[];\n\t}\n}\n\nexport type SubscriptionOptions = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n};\n\nexport class SubscriptionGraph<T> extends Graph {\n\treadonly source: Node<readonly T[]>;\n\treadonly cursor: Node<number>;\n\treadonly available: Node<readonly T[]>;\n\t/**\n\t * Reference to the upstream topic graph. Intentionally NOT mounted\n\t * under this subscription: a subscription is a VIEW over an\n\t * externally-owned topic. Double-mounting (e.g. hub-owned topic +\n\t * sub-mount here) would make either-side teardown leave the other\n\t * holding a dead reference. Node-level `derived([topicEvents], …)`\n\t * still wires the data dependency across graph boundaries. D1(e).\n\t */\n\treadonly topic: TopicGraph<T>;\n\n\tconstructor(name: string, topicGraph: TopicGraph<T>, opts: SubscriptionOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst initialCursor = requireNonNegativeInt(opts.cursor ?? 0, \"subscription cursor\");\n\t\tthis.topic = topicGraph;\n\t\tconst topicEvents = topicGraph.events;\n\t\tthis.source = derived([topicEvents], ([snapshot]) => snapshot as readonly T[], {\n\t\t\tname: \"source\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"subscription_source\"),\n\t\t\tinitial: topicEvents.cache as readonly T[],\n\t\t});\n\t\tthis.add(\"source\", this.source);\n\t\tthis.cursor = state(initialCursor, {\n\t\t\tname: \"cursor\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"subscription_cursor\"),\n\t\t});\n\t\tthis.add(\"cursor\", this.cursor);\n\t\tthis.available = derived(\n\t\t\t[this.source, this.cursor],\n\t\t\t([sourceSnapshot, cursor]) => {\n\t\t\t\tconst entries = sourceSnapshot as readonly T[];\n\t\t\t\tconst start = Math.max(0, Math.trunc((cursor as number) ?? 0));\n\t\t\t\treturn entries.slice(start);\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"available\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"subscription_available\"),\n\t\t\t\tinitial: [],\n\t\t\t},\n\t\t);\n\t\tthis.add(\"available\", this.available);\n\t\t// No `connect(\"topic::events\", \"source\")` — topic is not mounted here.\n\t\t// The node-level dep `derived([topicEvents], …)` above is the live wire.\n\t\tthis.addDisposer(keepalive(this.source));\n\t\tthis.addDisposer(keepalive(this.available));\n\t}\n\n\tack(count?: number): number {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst requested =\n\t\t\tcount === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(count, \"subscription ack count\");\n\t\tconst step = Math.min(requested, available.length);\n\t\tif (step <= 0) return this.cursor.cache as number;\n\t\tconst next = (this.cursor.cache as number) + step;\n\t\t// F8: use emit() so the pipeline auto-prefixes DIRTY, runs equals\n\t\t// substitution, and produces a proper two-phase wave (the raw\n\t\t// `down([[DATA, next]])` path bypassed those contracts).\n\t\tthis.cursor.emit(next);\n\t\treturn next;\n\t}\n\n\tpull(limit?: number, opts: { ack?: boolean } = {}): readonly T[] {\n\t\tconst available = this.available.cache as readonly T[];\n\t\tconst max =\n\t\t\tlimit === undefined\n\t\t\t\t? available.length\n\t\t\t\t: requireNonNegativeInt(limit, \"subscription pull limit\");\n\t\tconst out = available.slice(0, max);\n\t\tif (opts.ack && out.length > 0) this.ack(out.length);\n\t\treturn out;\n\t}\n}\n\nexport type JobState = \"queued\" | \"inflight\";\n\nexport type JobEnvelope<T> = {\n\tid: string;\n\tpayload: T;\n\tattempts: number;\n\tmetadata: Readonly<Record<string, unknown>>;\n\tstate: JobState;\n};\n\nexport type JobQueueOptions = {\n\tgraph?: GraphOptions;\n};\n\nexport class JobQueueGraph<T> extends Graph {\n\tprivate readonly _pending;\n\tprivate readonly _jobs;\n\tprivate _seq = 0;\n\treadonly pending: Node<readonly string[]>;\n\treadonly jobs: Node<ReadonlyMap<string, JobEnvelope<T>>>;\n\treadonly depth: Node<number>;\n\n\tconstructor(name: string, opts: JobQueueOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tthis._pending = reactiveList<string>([], { name: \"pending\" });\n\t\tthis._jobs = reactiveMap<string, JobEnvelope<T>>({ name: \"jobs\" });\n\t\tthis.pending = this._pending.items;\n\t\tthis.jobs = this._jobs.entries;\n\t\tthis.add(\"pending\", this.pending);\n\t\tthis.add(\"jobs\", this.jobs);\n\t\tthis.depth = derived([this.pending], ([snapshot]) => (snapshot as readonly string[]).length, {\n\t\t\tname: \"depth\",\n\t\t\tdescribeKind: \"derived\",\n\t\t\tmeta: messagingMeta(\"queue_depth\"),\n\t\t\tinitial: 0,\n\t\t});\n\t\tthis.add(\"depth\", this.depth);\n\t\tthis.addDisposer(keepalive(this.depth));\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\tconst id = opts.id ?? `${this.name}-${++this._seq}`;\n\t\tif (this._jobs.get(id) !== undefined) {\n\t\t\tthrow new Error(`jobQueue(\"${this.name}\"): duplicate job id \"${id}\"`);\n\t\t}\n\t\tconst job: JobEnvelope<T> = {\n\t\t\tid,\n\t\t\tpayload,\n\t\t\tattempts: 0,\n\t\t\tmetadata: Object.freeze({ ...(opts.metadata ?? {}) }),\n\t\t\tstate: \"queued\",\n\t\t};\n\t\tthis._jobs.set(id, job);\n\t\tthis._pending.append(id);\n\t\treturn id;\n\t}\n\n\tclaim(limit = 1): readonly JobEnvelope<T>[] {\n\t\tconst max = requireNonNegativeInt(limit, \"job queue claim limit\");\n\t\tif (max === 0) return [];\n\t\tconst out: JobEnvelope<T>[] = [];\n\t\twhile (out.length < max) {\n\t\t\tconst ids = this.pending.cache as readonly string[];\n\t\t\tif (ids.length === 0) break;\n\t\t\tconst id = this._pending.pop(0);\n\t\t\tconst job = this._jobs.get(id);\n\t\t\tif (!job || job.state !== \"queued\") continue;\n\t\t\tconst inflight: JobEnvelope<T> = {\n\t\t\t\t...job,\n\t\t\t\tstate: \"inflight\",\n\t\t\t\tattempts: job.attempts + 1,\n\t\t\t};\n\t\t\tthis._jobs.set(id, inflight);\n\t\t\tout.push(inflight);\n\t\t}\n\t\treturn out;\n\t}\n\n\tack(id: string): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n\n\tnack(id: string, opts: { requeue?: boolean } = {}): boolean {\n\t\tconst job = this._jobs.get(id);\n\t\tif (!job || job.state !== \"inflight\") return false;\n\t\tif (opts.requeue ?? true) {\n\t\t\tthis._jobs.set(id, { ...job, state: \"queued\" });\n\t\t\tthis._pending.append(id);\n\t\t\treturn true;\n\t\t}\n\t\tthis._jobs.delete(id);\n\t\treturn true;\n\t}\n}\n\nexport type JobFlowOptions = {\n\tgraph?: GraphOptions;\n\tstages?: readonly string[];\n\tmaxPerPump?: number;\n};\n\nexport class JobFlowGraph<T> extends Graph {\n\tprivate readonly _stageNames: readonly string[];\n\tprivate readonly _queues = new Map<string, JobQueueGraph<T>>();\n\tprivate readonly _completed;\n\treadonly completed: Node<readonly JobEnvelope<T>[]>;\n\treadonly completedCount: Node<number>;\n\n\tconstructor(name: string, opts: JobFlowOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\tconst stages = (opts.stages ?? [\"incoming\", \"processing\", \"done\"]).map((v) => v.trim());\n\t\tif (stages.length < 2) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): requires at least 2 stages`);\n\t\t}\n\t\tconst unique = new Set(stages);\n\t\tif (unique.size !== stages.length) {\n\t\t\tthrow new Error(`jobFlow(\"${name}\"): stage names must be unique`);\n\t\t}\n\t\tthis._stageNames = Object.freeze([...stages]);\n\t\tfor (const stage of this._stageNames) {\n\t\t\tconst q = jobQueue<T>(`${name}-${stage}`);\n\t\t\tthis._queues.set(stage, q);\n\t\t\tthis.mount(stage, q);\n\t\t}\n\t\tthis._completed = reactiveLog<JobEnvelope<T>>([], { name: \"completed\" });\n\t\tthis.completed = this._completed.entries;\n\t\tthis.add(\"completed\", this.completed);\n\t\tthis.completedCount = derived(\n\t\t\t[this.completed],\n\t\t\t([snapshot]) => (snapshot as readonly JobEnvelope<T>[]).length,\n\t\t\t{\n\t\t\t\tname: \"completedCount\",\n\t\t\t\tdescribeKind: \"derived\",\n\t\t\t\tmeta: messagingMeta(\"job_flow_completed_count\"),\n\t\t\t\tinitial: 0,\n\t\t\t},\n\t\t);\n\t\tthis.add(\"completedCount\", this.completedCount);\n\t\tthis.addDisposer(keepalive(this.completedCount));\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"job flow maxPerPump\"),\n\t\t);\n\t\tfor (let i = 0; i < this._stageNames.length; i += 1) {\n\t\t\tconst stage = this._stageNames[i] as string;\n\t\t\tconst current = this.queue(stage);\n\t\t\tconst next =\n\t\t\t\ti + 1 < this._stageNames.length ? this.queue(this._stageNames[i + 1] as string) : null;\n\t\t\tconst pump = node<unknown>(\n\t\t\t\t[current.pending],\n\t\t\t\t() => {\n\t\t\t\t\tlet moved = 0;\n\t\t\t\t\twhile (moved < maxPerPump) {\n\t\t\t\t\t\tconst claim = current.claim(1);\n\t\t\t\t\t\tif (claim.length === 0) break;\n\t\t\t\t\t\tconst job = claim[0] as JobEnvelope<T>;\n\t\t\t\t\t\tif (!job) break;\n\t\t\t\t\t\tif (next) {\n\t\t\t\t\t\t\tnext.enqueue(job.payload, {\n\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t...job.metadata,\n\t\t\t\t\t\t\t\t\tjob_flow_from: stage,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis._completed.append(job);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrent.ack(job.id);\n\t\t\t\t\t\tmoved += 1;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: `pump_${stage}`,\n\t\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\t\tmeta: messagingMeta(\"job_flow_pump\"),\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.add(`pump_${stage}`, pump);\n\t\t\tthis.addDisposer(keepalive(pump));\n\t\t}\n\t}\n\n\tstages(): readonly string[] {\n\t\treturn this._stageNames;\n\t}\n\n\tqueue(stage: string): JobQueueGraph<T> {\n\t\tconst q = this._queues.get(stage);\n\t\tif (!q) throw new Error(`jobFlow(\"${this.name}\"): unknown stage \"${stage}\"`);\n\t\treturn q;\n\t}\n\n\tenqueue(payload: T, opts: { id?: string; metadata?: Record<string, unknown> } = {}): string {\n\t\treturn this.queue(this._stageNames[0] as string).enqueue(payload, opts);\n\t}\n\n\tretainedCompleted(): readonly JobEnvelope<T>[] {\n\t\treturn this.completed.cache as readonly JobEnvelope<T>[];\n\t}\n}\n\nexport type TopicBridgeOptions<TIn, TOut> = {\n\tgraph?: GraphOptions;\n\tcursor?: number;\n\tmaxPerPump?: number;\n\tmap?: (value: TIn) => TOut | undefined;\n};\n\nexport class TopicBridgeGraph<TIn, TOut = TIn> extends Graph {\n\tprivate readonly _sourceSub;\n\tprivate readonly _target;\n\treadonly bridgedCount: Node<number>;\n\n\tconstructor(\n\t\tname: string,\n\t\tsourceTopic: TopicGraph<TIn>,\n\t\ttargetTopic: TopicGraph<TOut>,\n\t\topts: TopicBridgeOptions<TIn, TOut> = {},\n\t) {\n\t\tsuper(name, opts.graph);\n\t\tthis._sourceSub = subscription<TIn>(`${name}-subscription`, sourceTopic, {\n\t\t\tcursor: opts.cursor,\n\t\t});\n\t\tthis._target = targetTopic;\n\t\tthis.mount(\"subscription\", this._sourceSub);\n\t\tthis.bridgedCount = state(0, {\n\t\t\tname: \"bridgedCount\",\n\t\t\tdescribeKind: \"state\",\n\t\t\tmeta: messagingMeta(\"topic_bridge_count\"),\n\t\t});\n\t\tthis.add(\"bridgedCount\", this.bridgedCount);\n\n\t\tconst maxPerPump = Math.max(\n\t\t\t1,\n\t\t\trequireNonNegativeInt(opts.maxPerPump ?? DEFAULT_MAX_PER_PUMP, \"topic bridge maxPerPump\"),\n\t\t);\n\t\tconst mapValue = opts.map ?? ((value: TIn) => value as unknown as TOut);\n\t\tconst pump = node<unknown>(\n\t\t\t[this._sourceSub.available],\n\t\t\t() => {\n\t\t\t\tconst available = this._sourceSub.pull(maxPerPump, { ack: true });\n\t\t\t\tif (available.length === 0) return;\n\t\t\t\tlet bridged = 0;\n\t\t\t\tfor (const value of available) {\n\t\t\t\t\tconst mapped = mapValue(value as TIn);\n\t\t\t\t\tif (mapped === undefined) continue;\n\t\t\t\t\tthis._target.publish(mapped);\n\t\t\t\t\tbridged += 1;\n\t\t\t\t}\n\t\t\t\tif (bridged > 0) {\n\t\t\t\t\tconst current = this.bridgedCount.cache as number;\n\t\t\t\t\tthis.bridgedCount.down([[DATA, current + bridged]]);\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"pump\",\n\t\t\t\tdescribeKind: \"effect\",\n\t\t\t\tmeta: messagingMeta(\"topic_bridge_pump\"),\n\t\t\t},\n\t\t);\n\t\tthis.add(\"pump\", pump);\n\t\tthis.addDisposer(keepalive(pump));\n\t}\n}\n\n// ── MessagingHubGraph ─────────────────────────────────────────────────────\n\nexport type MessagingHubOptions = {\n\tgraph?: GraphOptions;\n\t/**\n\t * Default `TopicOptions` applied to every topic created via `topic(name)`\n\t * without explicit options. Per-call opts override. Default: `{}`\n\t * (unbounded retention per topic unless `retainedLimit` is set per call).\n\t */\n\tdefaultTopicOptions?: TopicOptions;\n};\n\n/**\n * Lazy Pulsar-inspired topic registry. Manages a named set of {@link TopicGraph}\n * instances with retention + cursor semantics. Topics are created on first\n * access; `removeTopic(name)` unmounts and tears down via {@link Graph.remove}.\n *\n * **Relationship to `pubsub()` in `src/extra/pubsub.ts`:** `pubsub` is a\n * lightweight last-value state hub (no retention, no cursors). `MessagingHubGraph`\n * is the full messaging hub — retained message logs, cursor-based subscriptions,\n * and pattern-layer lifecycle management.\n *\n * @category patterns\n */\nexport class MessagingHubGraph extends Graph {\n\tprivate readonly _topics = new Map<string, TopicGraph<unknown>>();\n\tprivate _version = 0;\n\tprivate readonly _defaultTopicOptions: TopicOptions;\n\n\tconstructor(name: string, opts: MessagingHubOptions = {}) {\n\t\tsuper(name, opts.graph);\n\t\t// P8: shallow-copy caller-provided defaults so post-construction\n\t\t// mutations by the caller don't leak into every future `topic()` call.\n\t\tthis._defaultTopicOptions = { ...(opts.defaultTopicOptions ?? {}) };\n\t}\n\n\t/** Monotonic counter advancing on topic create/remove. */\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\t/** Number of topics currently in the hub. */\n\tget size(): number {\n\t\treturn this._topics.size;\n\t}\n\n\t/** Checks topic existence without creating. */\n\thas(name: string): boolean {\n\t\treturn this._topics.has(name);\n\t}\n\n\t/** Iterator over topic names. */\n\ttopicNames(): IterableIterator<string> {\n\t\treturn this._topics.keys();\n\t}\n\n\t/**\n\t * Returns the {@link TopicGraph} for `name`, creating lazily on first call.\n\t * Subsequent calls with the same name return the same instance (options on\n\t * repeat calls are ignored — the topic is already configured).\n\t */\n\ttopic<T = unknown>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\t\tlet t = this._topics.get(name) as TopicGraph<T> | undefined;\n\t\tif (t === undefined) {\n\t\t\tconst effective: TopicOptions = { ...this._defaultTopicOptions, ...(opts ?? {}) };\n\t\t\tt = new TopicGraph<T>(name, effective);\n\t\t\tthis._topics.set(name, t as TopicGraph<unknown>);\n\t\t\tthis.mount(name, t);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn t;\n\t}\n\n\t/**\n\t * Publishes a value to the topic, lazily creating it on first publish.\n\t *\n\t * **Late-subscriber caveat:** the topic is created lazily, so subscribers\n\t * that attach AFTER a publish only see the retained window (governed by\n\t * `retainedLimit` on `TopicOptions` / `defaultTopicOptions`). If\n\t * `retainedLimit === 0` is set explicitly, early publishes are\n\t * effectively dropped — prefer an unset `retainedLimit` (unbounded\n\t * retention) or subscribe before publishing when late-subscribers matter.\n\t */\n\tpublish<T = unknown>(name: string, value: T): void {\n\t\tthis.topic<T>(name).publish(value);\n\t}\n\n\t/**\n\t * Bulk publish — issues all publishes inside one outer batch. New topics\n\t * are created on demand. No-op if `entries` yields nothing.\n\t *\n\t * **Iterable consumption (F6):** `entries` is consumed once (single-pass)\n\t * INSIDE the batch frame. If the iterator throws mid-way, the batch is\n\t * discarded and NO publishes are visible to subscribers (all-or-nothing).\n\t * Pass an array or `Set` for multi-shot callers.\n\t */\n\tpublishMany(entries: Iterable<[string, unknown]>): void {\n\t\t// P2: iterate inside batch — no `[...entries]` materialization so large\n\t\t// / infinite iterables don't OOM, and iterator throws are contained.\n\t\tbatch(() => {\n\t\t\tfor (const [name, value] of entries) {\n\t\t\t\tthis.topic(name).publish(value);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Creates a {@link SubscriptionGraph} over a named topic. The topic is\n\t * lazily created if missing. Subscription lifecycle is owned by the caller —\n\t * the hub does NOT mount the subscription.\n\t *\n\t * @param subName - Local name for the subscription graph.\n\t * @param topicName - Hub topic to subscribe to.\n\t * @param opts - `SubscriptionOptions` (initial cursor, etc.).\n\t */\n\tsubscribe<T = unknown>(\n\t\tsubName: string,\n\t\ttopicName: string,\n\t\topts?: SubscriptionOptions,\n\t): SubscriptionGraph<T> {\n\t\tconst t = this.topic<T>(topicName);\n\t\treturn new SubscriptionGraph<T>(subName, t, opts);\n\t}\n\n\t/**\n\t * Unmounts and tears down the topic's graph. Returns `true` if the topic\n\t * existed. Subscribers receive `TEARDOWN` via {@link Graph.remove}.\n\t */\n\tremoveTopic(name: string): boolean {\n\t\tif (!this._topics.has(name)) return false;\n\t\t// P1 / P3: Graph.remove first — if it throws, `_topics` must NOT still\n\t\t// hold the broken half-disposed topic (otherwise the next\n\t\t// `hub.topic(name)` returns the corrupted reference). Wrap in\n\t\t// try/finally so `_topics` / `_version` converge to a consistent state\n\t\t// regardless of whether `remove` throws. Mount-orphan safety is\n\t\t// preserved by removing before deleting.\n\t\ttry {\n\t\t\tthis.remove(name); // unmounts, drops edges, tears down\n\t\t} finally {\n\t\t\tthis._topics.delete(name);\n\t\t\tthis._version += 1;\n\t\t}\n\t\treturn true;\n\t}\n}\n\n/**\n * Creates a Pulsar-inspired topic graph (append-only retained stream + latest value).\n */\nexport function topic<T>(name: string, opts?: TopicOptions): TopicGraph<T> {\n\treturn new TopicGraph<T>(name, opts);\n}\n\n/**\n * Creates a lazy Pulsar-inspired messaging hub. Topics are created on first access\n * via `hub.topic(name)`; `hub.publish(name, value)` shortcuts through the registry.\n *\n * @example\n * ```ts\n * import { messagingHub } from \"@graphrefly/graphrefly-ts\";\n *\n * const hub = messagingHub(\"main\", { defaultTopicOptions: { retainedLimit: 256 } });\n * hub.publish(\"orders\", { id: 1 });\n * hub.publishMany([[\"shipments\", { id: 1 }], [\"orders\", { id: 2 }]]);\n * const sub = hub.subscribe(\"orders-worker\", \"orders\", { cursor: 0 });\n * ```\n */\nexport function messagingHub(name: string, opts?: MessagingHubOptions): MessagingHubGraph {\n\treturn new MessagingHubGraph(name, opts);\n}\n\n/**\n * Creates a cursor-based subscription graph over a topic.\n */\nexport function subscription<T>(\n\tname: string,\n\ttopicGraph: TopicGraph<T>,\n\topts?: SubscriptionOptions,\n): SubscriptionGraph<T> {\n\treturn new SubscriptionGraph<T>(name, topicGraph, opts);\n}\n\n/**\n * Creates a Pulsar-inspired job queue graph with claim/ack/nack workflow.\n */\nexport function jobQueue<T>(name: string, opts?: JobQueueOptions): JobQueueGraph<T> {\n\treturn new JobQueueGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous multi-stage queue chain graph.\n */\nexport function jobFlow<T>(name: string, opts?: JobFlowOptions): JobFlowGraph<T> {\n\treturn new JobFlowGraph<T>(name, opts);\n}\n\n/**\n * Creates an autonomous cursor-based topic relay graph.\n */\nexport function topicBridge<TIn, TOut = TIn>(\n\tname: string,\n\tsourceTopic: TopicGraph<TIn>,\n\ttargetTopic: TopicGraph<TOut>,\n\topts?: TopicBridgeOptions<TIn, TOut>,\n): TopicBridgeGraph<TIn, TOut> {\n\treturn new TopicBridgeGraph<TIn, TOut>(name, sourceTopic, targetTopic, opts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAAS,cAAsB;AACrC,SAAO,KAAK,MAAM,YAAY,IAAI,IAAI,GAAS;AAChD;AAGO,SAAS,cAAsB;AACrC,SAAO,KAAK,IAAI,IAAI;AACrB;;;ACUO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMT,YAAY,SAA6B,SAAkB;AAC1D;AAAA,MACC,WACC,wBAAwB,OAAO,QAAQ,MAAM,CAAC,4BAA4B,OAAO,QAA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C;AACA,UAAI,eAAe,QAAQ;AAC1B,eAAO,EAAE,UAAU,EAAE,QAAQ,IAAI,QAAQ,OAAO,IAAI,MAAM,EAAE;AAAA,MAC7D;AACA,UAAI,eAAe,KAAK;AACvB,cAAM,UAAU,CAAC,GAAI,IAA8B,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,MAAM;AAAA,UAC9E,KAAK,CAAC;AAAA,UACN,KAAK,EAAE;AAAA,QACR,CAAC;AACD,eAAO,EAAE,OAAO,QAAQ;AAAA,MACzB;AACA,UAAI,eAAe,KAAK;AACvB,cAAM,QAAQ,CAAC,GAAI,GAAoB,EAAE,IAAI,IAAI;AACjD,eAAO,EAAE,OAAO,MAAM;AAAA,MACvB;AACA,UAAI,YAAY,OAAO,GAAG,GAAG;AAC5B,cAAM,KAAK;AACX,cAAM,MAAgB,IAAI,MAAM,GAAG,MAAM;AACzC,iBAAS,IAAI,GAAG,IAAI,GAAG,QAAQ,IAAK,KAAI,CAAC,IAAI,GAAG,CAAC,KAAK;AACtD,eAAO,EAAE,eAAe,EAAE,MAAM,IAAI,YAAY,MAAM,MAAM,IAAI,EAAE;AAAA,MACnE;AACA,YAAM,MAA+B,CAAC;AACtC,iBAAW,KAAK,OAAO,KAAK,GAA8B,EAAE,KAAK,GAAG;AACnE,YAAI,CAAC,IAAI,KAAM,IAAgC,CAAC,CAAC;AAAA,MAClD;AACA,aAAO;AAAA,IACR,UAAE;AACD,YAAM,OAAO,GAAG;AAAA,IACjB;AAAA,EACD;AACA,SAAO,KAAK,KAAK;AAClB;","names":["node","batch","batch","size","node","node","node","audit","result","derived","from","down","downEdges","acc","node"]}
|