@graphrefly/ts 0.0.1 → 0.0.3
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/README.md +197 -117
- package/dist/actions-types-CH-XCU9O.d.cts +657 -0
- package/dist/actions-types-w2iPQTkv.d.ts +657 -0
- package/dist/adapters/index.cjs +5157 -2951
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +207 -70
- package/dist/adapters/index.d.ts +207 -70
- package/dist/adapters/index.js +3738 -1688
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/nestjs/microservices.cjs +841 -0
- package/dist/adapters/nestjs/microservices.cjs.map +1 -0
- package/dist/adapters/nestjs/microservices.d.cts +45 -0
- package/dist/adapters/nestjs/microservices.d.ts +45 -0
- package/dist/adapters/nestjs/microservices.js +206 -0
- package/dist/adapters/nestjs/microservices.js.map +1 -0
- package/dist/adapters/nestjs/native.cjs +1391 -0
- package/dist/adapters/nestjs/native.cjs.map +1 -0
- package/dist/adapters/nestjs/native.d.cts +111 -0
- package/dist/adapters/nestjs/native.d.ts +111 -0
- package/dist/adapters/nestjs/native.js +577 -0
- package/dist/adapters/nestjs/native.js.map +1 -0
- package/dist/adapters/nestjs/websockets.cjs +924 -0
- package/dist/adapters/nestjs/websockets.cjs.map +1 -0
- package/dist/adapters/nestjs/websockets.d.cts +47 -0
- package/dist/adapters/nestjs/websockets.d.ts +47 -0
- package/dist/adapters/nestjs/websockets.js +286 -0
- package/dist/adapters/nestjs/websockets.js.map +1 -0
- package/dist/adapters/nestjs.cjs +1085 -0
- package/dist/adapters/nestjs.cjs.map +1 -0
- package/dist/adapters/nestjs.d.cts +385 -0
- package/dist/adapters/nestjs.d.ts +385 -0
- package/dist/adapters/nestjs.js +112 -0
- package/dist/adapters/nestjs.js.map +1 -0
- package/dist/adapters/observe-storage.d.cts +3 -3
- package/dist/adapters/observe-storage.d.ts +3 -3
- package/dist/adapters/observe-storage.js +4 -4
- package/dist/adapters/react.cjs.map +1 -1
- package/dist/adapters/react.d.cts +2 -2
- package/dist/adapters/react.d.ts +2 -2
- package/dist/adapters/react.js +1 -1
- package/dist/adapters/solid.cjs.map +1 -1
- package/dist/adapters/solid.d.cts +2 -2
- package/dist/adapters/solid.d.ts +2 -2
- package/dist/adapters/solid.js +1 -1
- package/dist/adapters/svelte.cjs.map +1 -1
- package/dist/adapters/svelte.d.cts +2 -2
- package/dist/adapters/svelte.d.ts +2 -2
- package/dist/adapters/svelte.js +1 -1
- package/dist/adapters/vue.cjs.map +1 -1
- package/dist/adapters/vue.d.cts +2 -2
- package/dist/adapters/vue.d.ts +2 -2
- package/dist/adapters/vue.js +1 -1
- package/dist/{agent-runtime-BesGDZcB.d.ts → agent-runtime-types-core-CKwrBDyi.d.ts} +171 -320
- package/dist/{agent-runtime-DZTJ3C-p.d.cts → agent-runtime-types-core-bfl4m0vM.d.cts} +171 -320
- package/dist/agent-runtime-types-tool-BLPV3azj.d.cts +695 -0
- package/dist/agent-runtime-types-tool-hwqvVqNt.d.ts +695 -0
- package/dist/agentic-memory-retention-CLwI76JK.d.ts +14 -0
- package/dist/agentic-memory-retention-Cz8GR6ie.d.cts +14 -0
- package/dist/{agentic-memory-DfuVZ-lY.d.cts → agentic-memory-types-JDr7MPhh.d.cts} +13 -57
- package/dist/{agentic-memory-BmRCvh0d.d.ts → agentic-memory-types-khYJgzKL.d.ts} +13 -57
- package/dist/{capability-admission-B0BzqAm5.d.cts → capability-admission-B8RNFyaZ.d.cts} +3 -3
- package/dist/{capability-admission-g0mn9hpq.d.ts → capability-admission-Dkw1Xz3r.d.ts} +3 -3
- package/dist/chunk-2KUAG2GZ.js +9693 -0
- package/dist/chunk-2KUAG2GZ.js.map +1 -0
- package/dist/{chunk-CZNV3VXM.js → chunk-3J7UPZL5.js} +11 -11
- package/dist/{chunk-HKK2JD7Z.js → chunk-3LYI6ADX.js} +12 -125
- package/dist/chunk-3LYI6ADX.js.map +1 -0
- package/dist/{chunk-YXMZ2N6J.js → chunk-4M37FH2I.js} +1071 -1025
- package/dist/chunk-4M37FH2I.js.map +1 -0
- package/dist/{chunk-YDSIVHRR.js → chunk-4NWSNI4K.js} +1598 -1584
- package/dist/chunk-4NWSNI4K.js.map +1 -0
- package/dist/{chunk-Z2ANQ6JW.js → chunk-4Q77MMJY.js} +2 -2
- package/dist/{chunk-SS2A464I.js → chunk-54WPEODM.js} +3 -3
- package/dist/chunk-54WPEODM.js.map +1 -0
- package/dist/chunk-6E76H4OU.js +132 -0
- package/dist/chunk-6E76H4OU.js.map +1 -0
- package/dist/chunk-7GOTIIQ7.js +819 -0
- package/dist/chunk-7GOTIIQ7.js.map +1 -0
- package/dist/{chunk-V7CIJE4B.js → chunk-DKFWDTVY.js} +92 -9
- package/dist/chunk-DKFWDTVY.js.map +1 -0
- package/dist/{chunk-FBUU43PM.js → chunk-E4QCH32M.js} +448 -446
- package/dist/chunk-E4QCH32M.js.map +1 -0
- package/dist/{chunk-XKXWK2KP.js → chunk-GXU6WFEJ.js} +1157 -1021
- package/dist/chunk-GXU6WFEJ.js.map +1 -0
- package/dist/{chunk-K3FXTC3I.js → chunk-HJACH5PU.js} +3 -3
- package/dist/{chunk-GTPCOEOZ.js → chunk-IDMLXLLG.js} +3 -3
- package/dist/{chunk-DKP56CSW.js → chunk-JKAYLDQV.js} +2 -2
- package/dist/{chunk-4VLAQHZI.js → chunk-K7FB3JTD.js} +17 -1
- package/dist/chunk-K7FB3JTD.js.map +1 -0
- package/dist/{chunk-43BKLFZU.js → chunk-KFURM6FM.js} +10 -10
- package/dist/{chunk-H75VXTGT.js → chunk-L6LDXRWE.js} +3 -3
- package/dist/{chunk-H75VXTGT.js.map → chunk-L6LDXRWE.js.map} +1 -1
- package/dist/chunk-MCOFHMUU.js +4131 -0
- package/dist/chunk-MCOFHMUU.js.map +1 -0
- package/dist/chunk-MQEQMS7B.js +1009 -0
- package/dist/chunk-MQEQMS7B.js.map +1 -0
- package/dist/chunk-MTELVIYR.js +1421 -0
- package/dist/chunk-MTELVIYR.js.map +1 -0
- package/dist/{chunk-3JR3EDB2.js → chunk-NNDIFUKX.js} +121 -115
- package/dist/chunk-NNDIFUKX.js.map +1 -0
- package/dist/{chunk-2747WN4Y.js → chunk-PUSRRALM.js} +3 -3
- package/dist/{chunk-QFY4AFY4.js → chunk-PVC7WDKI.js} +58 -52
- package/dist/chunk-PVC7WDKI.js.map +1 -0
- package/dist/{chunk-VTHLCFN4.js → chunk-RAHNUYA5.js} +2 -2
- package/dist/chunk-TQPCAIQI.js +612 -0
- package/dist/chunk-TQPCAIQI.js.map +1 -0
- package/dist/{chunk-IXZBUWSP.js → chunk-UEMN5URK.js} +2 -2
- package/dist/chunk-WOS7RJYZ.js +1320 -0
- package/dist/chunk-WOS7RJYZ.js.map +1 -0
- package/dist/{chunk-6PHB5CJS.js → chunk-ZLFRB6FI.js} +2 -2
- package/dist/composition/index.cjs +1228 -1076
- package/dist/composition/index.cjs.map +1 -1
- package/dist/composition/index.d.cts +3 -3
- package/dist/composition/index.d.ts +3 -3
- package/dist/composition/index.js +4 -4
- package/dist/core/index.cjs +1198 -1046
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +23 -2
- package/dist/core/index.d.ts +23 -2
- package/dist/core/index.js +2 -2
- package/dist/cqrs/index.d.cts +3 -3
- package/dist/cqrs/index.d.ts +3 -3
- package/dist/cqrs/messaging.d.cts +4 -4
- package/dist/cqrs/messaging.d.ts +4 -4
- package/dist/cqrs/work-queue.d.cts +5 -5
- package/dist/cqrs/work-queue.d.ts +5 -5
- package/dist/data-structures/index.cjs +1226 -1074
- package/dist/data-structures/index.cjs.map +1 -1
- package/dist/data-structures/index.d.cts +8 -7
- package/dist/data-structures/index.d.ts +8 -7
- package/dist/data-structures/index.js +6 -5
- package/dist/{describe-DYMw_l1C.d.cts → describe-BumQ-3_0.d.cts} +1 -1
- package/dist/{describe-BpyJuWkw.d.ts → describe-cYr_Z5zm.d.ts} +1 -1
- package/dist/executors/tool-provider-adapters.cjs +3091 -0
- package/dist/executors/tool-provider-adapters.cjs.map +1 -0
- package/dist/executors/tool-provider-adapters.d.cts +174 -0
- package/dist/executors/tool-provider-adapters.d.ts +174 -0
- package/dist/executors/tool-provider-adapters.js +1336 -0
- package/dist/executors/tool-provider-adapters.js.map +1 -0
- package/dist/executors/tool-provider-runtime.cjs +5178 -0
- package/dist/executors/tool-provider-runtime.cjs.map +1 -0
- package/dist/executors/tool-provider-runtime.d.cts +17 -0
- package/dist/executors/tool-provider-runtime.d.ts +17 -0
- package/dist/executors/tool-provider-runtime.js +15 -0
- package/dist/executors/tool-provider-runtime.js.map +1 -0
- package/dist/executors/tool-provider.cjs +6392 -0
- package/dist/executors/tool-provider.cjs.map +1 -0
- package/dist/executors/tool-provider.d.cts +60 -0
- package/dist/executors/tool-provider.d.ts +60 -0
- package/dist/executors/tool-provider.js +89 -0
- package/dist/executors/tool-provider.js.map +1 -0
- package/dist/executors/work-queue.d.cts +6 -6
- package/dist/executors/work-queue.d.ts +6 -6
- package/dist/graph/index.cjs +1499 -1341
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +9 -8
- package/dist/graph/index.d.ts +9 -8
- package/dist/graph/index.js +23 -22
- package/dist/{graph-DCEWh4T2.d.cts → graph-C1C-wb0L.d.cts} +266 -137
- package/dist/{graph-D-1-SQeC.d.ts → graph-CS0b4V9B.d.ts} +266 -137
- package/dist/{index-72VZC0-E.d.cts → index-DLrNopda.d.cts} +151 -10
- package/dist/{index-Bmxeu0nK.d.ts → index-DzJni3_6.d.ts} +151 -10
- package/dist/index.cjs +3397 -3140
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -9
- package/dist/index.d.ts +12 -9
- package/dist/index.js +110 -109
- package/dist/inspection/boundary.d.cts +4 -4
- package/dist/inspection/boundary.d.ts +4 -4
- package/dist/measurements-BWAnochv.d.ts +294 -0
- package/dist/measurements-B_gJfD8h.d.cts +294 -0
- package/dist/messaging/index.cjs +57 -51
- package/dist/messaging/index.cjs.map +1 -1
- package/dist/messaging/index.d.cts +11 -276
- package/dist/messaging/index.d.ts +11 -276
- package/dist/messaging/index.js +1 -1
- package/dist/operators/index.cjs +1228 -1076
- package/dist/operators/index.cjs.map +1 -1
- package/dist/operators/index.d.cts +5 -5
- package/dist/operators/index.d.ts +5 -5
- package/dist/operators/index.js +5 -5
- package/dist/orchestration/index.cjs +8844 -6071
- package/dist/orchestration/index.cjs.map +1 -1
- package/dist/orchestration/index.d.cts +171 -224
- package/dist/orchestration/index.d.ts +171 -224
- package/dist/orchestration/index.js +42 -991
- package/dist/orchestration/index.js.map +1 -1
- package/dist/orchestration/messaging.d.cts +5 -8
- package/dist/orchestration/messaging.d.ts +5 -8
- package/dist/orchestration/work-queue.cjs +1243 -5
- package/dist/orchestration/work-queue.cjs.map +1 -1
- package/dist/orchestration/work-queue.d.cts +121 -10
- package/dist/orchestration/work-queue.d.ts +121 -10
- package/dist/orchestration/work-queue.js +1067 -4
- package/dist/orchestration/work-queue.js.map +1 -1
- package/dist/patterns/event-flow.cjs +6 -20
- package/dist/patterns/event-flow.cjs.map +1 -1
- package/dist/patterns/event-flow.d.cts +4 -4
- package/dist/patterns/event-flow.d.ts +4 -4
- package/dist/patterns/event-flow.js +2 -2
- package/dist/patterns/index.cjs +453 -465
- package/dist/patterns/index.cjs.map +1 -1
- package/dist/patterns/index.d.cts +6 -5
- package/dist/patterns/index.d.ts +6 -5
- package/dist/patterns/index.js +3 -3
- package/dist/process-types-BB7oRhX3.d.cts +200 -0
- package/dist/process-types-QNhyoYJ8.d.ts +200 -0
- package/dist/{reactive-collection-DNV0-gFi.d.cts → reactive-collection-BYlWvtnp.d.cts} +4 -34
- package/dist/{reactive-collection-BAmfrGjd.d.ts → reactive-collection-efOEdGFN.d.ts} +4 -34
- package/dist/{reactive-collection-storage-BNEldDyi.d.cts → reactive-collection-storage-BjoLsoiC.d.cts} +5 -5
- package/dist/{reactive-collection-storage-YZsAQsWK.d.ts → reactive-collection-storage-DwW6UuK_.d.ts} +5 -5
- package/dist/{reactive-map-DRD1LJ2H.d.cts → reactive-map-BHacbIqz.d.cts} +7 -2
- package/dist/{reactive-map-EsDiCmJk.d.ts → reactive-map-DN4Jyqnf.d.ts} +7 -2
- package/dist/render/index.d.cts +2 -2
- package/dist/render/index.d.ts +2 -2
- package/dist/scheduled-readiness-BmqXxnzX.d.ts +91 -0
- package/dist/scheduled-readiness-CYSw7KDE.d.cts +91 -0
- package/dist/semantic-memory-graph-B_LwbM-E.d.cts +30 -0
- package/dist/semantic-memory-graph-rsFNNhwn.d.ts +30 -0
- package/dist/{semantic-memory-graph-DKuNzuWw.d.cts → semantic-memory-graph-types-Y73bbwVI.d.cts} +2 -28
- package/dist/{semantic-memory-graph-uwbwJdhe.d.ts → semantic-memory-graph-types-safmPkuX.d.ts} +2 -28
- package/dist/solutions/index.cjs +6353 -6169
- package/dist/solutions/index.cjs.map +1 -1
- package/dist/solutions/index.d.cts +12 -10
- package/dist/solutions/index.d.ts +12 -10
- package/dist/solutions/index.js +5 -5
- package/dist/solutions/reactive-layout/browser/index.cjs +116 -108
- package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/browser/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/browser/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/browser/index.js +3 -3
- package/dist/solutions/reactive-layout/index.cjs +3578 -3350
- package/dist/solutions/reactive-layout/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/index.d.cts +32 -576
- package/dist/solutions/reactive-layout/index.d.ts +32 -576
- package/dist/solutions/reactive-layout/index.js +65 -5
- package/dist/solutions/reactive-layout/node-canvas/index.cjs +127 -117
- package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/node-canvas/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/node-canvas/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/node-canvas/index.js +3 -3
- package/dist/solutions/reactive-layout/react-native/index.cjs +127 -117
- package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/react-native/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/react-native/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/react-native/index.js +3 -3
- package/dist/solutions/reactive-layout/skia/index.cjs +127 -117
- package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/skia/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/skia/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/skia/index.js +3 -3
- package/dist/solutions/work-item/actions.cjs +1609 -1428
- package/dist/solutions/work-item/actions.cjs.map +1 -1
- package/dist/solutions/work-item/actions.d.cts +23 -184
- package/dist/solutions/work-item/actions.d.ts +23 -184
- package/dist/solutions/work-item/actions.js +1558 -934
- package/dist/solutions/work-item/actions.js.map +1 -1
- package/dist/solutions/work-item/scheduling.cjs +9181 -1838
- package/dist/solutions/work-item/scheduling.cjs.map +1 -1
- package/dist/solutions/work-item/scheduling.d.cts +1763 -328
- package/dist/solutions/work-item/scheduling.d.ts +1763 -328
- package/dist/solutions/work-item/scheduling.js +117 -3
- package/dist/solutions/work-item/work-queue.d.cts +7 -7
- package/dist/solutions/work-item/work-queue.d.ts +7 -7
- package/dist/sources/browser.cjs +1318 -1083
- package/dist/sources/browser.cjs.map +1 -1
- package/dist/sources/browser.d.cts +22 -6
- package/dist/sources/browser.d.ts +22 -6
- package/dist/sources/browser.js +4 -4
- package/dist/sources/browser.js.map +1 -1
- package/dist/sources/index.cjs +1318 -1083
- package/dist/sources/index.cjs.map +1 -1
- package/dist/sources/index.d.cts +4 -4
- package/dist/sources/index.d.ts +4 -4
- package/dist/sources/index.js +4 -4
- package/dist/sources/node.d.cts +3 -3
- package/dist/sources/node.d.ts +3 -3
- package/dist/storage/browser.cjs +16 -0
- package/dist/storage/browser.cjs.map +1 -1
- package/dist/storage/browser.js +3 -3
- package/dist/storage/index.cjs +16 -0
- package/dist/storage/index.cjs.map +1 -1
- package/dist/storage/index.d.cts +5 -4
- package/dist/storage/index.d.ts +5 -4
- package/dist/storage/index.js +6 -6
- package/dist/storage/node.cjs +16 -0
- package/dist/storage/node.cjs.map +1 -1
- package/dist/storage/node.js +3 -3
- package/dist/{store-C-joM4gh.d.ts → store-6_CHF6Ge.d.ts} +1 -1
- package/dist/{store-CNJwmT-h.d.cts → store-BljX8RkQ.d.cts} +1 -1
- package/dist/types-BAw2QVVE.d.cts +274 -0
- package/dist/types-BUbbbh4f.d.cts +34 -0
- package/dist/types-CMnzoL54.d.cts +457 -0
- package/dist/{types-CcPIn7sy.d.cts → types-CTN3XoMl.d.cts} +57 -108
- package/dist/types-CV_ohy5T.d.cts +357 -0
- package/dist/{types-BsJvElYZ.d.ts → types-DChxk1vK.d.ts} +57 -108
- package/dist/types-DRu7SnLV.d.ts +274 -0
- package/dist/types-DeID_FRl.d.ts +34 -0
- package/dist/types-IhKH0hGW.d.ts +357 -0
- package/dist/types-ePlD2uyT.d.ts +457 -0
- package/dist/{work-item-runtime-qaVgsL0T.d.cts → work-item-runtime-types-BTxLskN5.d.cts} +3 -93
- package/dist/{work-item-runtime-C3M79vE9.d.ts → work-item-runtime-types-DAsZbb2y.d.ts} +3 -93
- package/dist/work-queue/index.cjs +957 -953
- package/dist/work-queue/index.cjs.map +1 -1
- package/dist/work-queue/index.d.cts +9 -357
- package/dist/work-queue/index.d.ts +9 -357
- package/dist/work-queue/index.js +957 -953
- package/dist/work-queue/index.js.map +1 -1
- package/package.json +611 -513
- package/dist/chunk-3JR3EDB2.js.map +0 -1
- package/dist/chunk-4VLAQHZI.js.map +0 -1
- package/dist/chunk-6XAIOL3X.js +0 -2407
- package/dist/chunk-6XAIOL3X.js.map +0 -1
- package/dist/chunk-FBUU43PM.js.map +0 -1
- package/dist/chunk-HKK2JD7Z.js.map +0 -1
- package/dist/chunk-PC3BTTBE.js +0 -3217
- package/dist/chunk-PC3BTTBE.js.map +0 -1
- package/dist/chunk-QFY4AFY4.js.map +0 -1
- package/dist/chunk-SS2A464I.js.map +0 -1
- package/dist/chunk-V7CIJE4B.js.map +0 -1
- package/dist/chunk-XKXWK2KP.js.map +0 -1
- package/dist/chunk-YDSIVHRR.js.map +0 -1
- package/dist/chunk-YXMZ2N6J.js.map +0 -1
- /package/dist/{chunk-CZNV3VXM.js.map → chunk-3J7UPZL5.js.map} +0 -0
- /package/dist/{chunk-Z2ANQ6JW.js.map → chunk-4Q77MMJY.js.map} +0 -0
- /package/dist/{chunk-K3FXTC3I.js.map → chunk-HJACH5PU.js.map} +0 -0
- /package/dist/{chunk-GTPCOEOZ.js.map → chunk-IDMLXLLG.js.map} +0 -0
- /package/dist/{chunk-DKP56CSW.js.map → chunk-JKAYLDQV.js.map} +0 -0
- /package/dist/{chunk-43BKLFZU.js.map → chunk-KFURM6FM.js.map} +0 -0
- /package/dist/{chunk-2747WN4Y.js.map → chunk-PUSRRALM.js.map} +0 -0
- /package/dist/{chunk-VTHLCFN4.js.map → chunk-RAHNUYA5.js.map} +0 -0
- /package/dist/{chunk-IXZBUWSP.js.map → chunk-UEMN5URK.js.map} +0 -0
- /package/dist/{chunk-6PHB5CJS.js.map → chunk-ZLFRB6FI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/index.ts","../../src/batch/boundary.ts","../../src/batch/batch.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/dispatcher/index.ts","../../src/node/core.ts","../../src/graph/environment.ts","../../src/json/codec.ts","../../src/node/versioning.ts","../../src/node/node.ts","../../src/graph/checkpoint.ts","../../src/graph/operators.ts","../../src/graph/graph.ts","../../src/patterns/semantic-memory.ts","../../src/solutions/agentic-memory.ts","../../src/adapters/agentic-memory-storage.ts","../../src/graph/resilience.ts","../../src/adapters/bridge.ts","../../src/adapters/environment.ts","../../src/adapters/nestjs.ts","../../src/graph/data-structures/core.ts","../../src/graph/data-structures/reactive-index.ts","../../src/graph/policies/collection.ts","../../src/graph/data-structures/reactive-list.ts","../../src/graph/data-structures/reactive-log.ts","../../src/graph/sources.ts","../../src/graph/data-structures/reactive-map.ts","../../src/data-structures/persistence.ts","../../src/storage/reactive-collection.ts","../../src/adapters/reactive-collection-storage.ts","../../src/adapters/store.ts"],"sourcesContent":["/**\n * Graph/framework/environment adapter namespace.\n *\n * Use focused adapter subpaths for graph-bound bridges such as\n * `@graphrefly/ts/adapters/observe-storage`.\n */\n\nexport * from \"./agentic-memory-storage.js\";\nexport * from \"./bridge.js\";\nexport * from \"./environment.js\";\nexport * from \"./nestjs.js\";\nexport * from \"./reactive-collection-storage.js\";\nexport * from \"./store.js\";\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Declarative batch (R-batch-coalesce / D12).\n *\n * Inside a batch, DIRTY propagates immediately but the tier-3 settle slice\n * (DATA/RESOLVED/INVALIDATE) is deferred to commit, so a shared downstream\n * recomputes ONCE after all batched sources settle. Success -> commit; a thrown\n * error -> rollback; `bctx.rollback()` is the explicit escape hatch.\n *\n * Coalescing note: this kernel coalesces multiple emits to the SAME node within\n * one batch to the latest tier-3 wave (last-value-wins). Full per-item batch-array\n * delivery (downstream fn receiving [v1..vK]) is a documented refinement — the\n * dominant use (coalescing a diamond join to one recompute) is exact here.\n */\n\nimport type { Wave } from \"../protocol/messages.js\";\nimport { dropBoundaryTasksForBatch, enterWave, exitWave } from \"./boundary.js\";\n\n/** A node target the batch can commit/rollback against (structural, avoids an import cycle). */\nexport interface BatchTarget {\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport interface BatchCtx {\n\t/** Discard all deferred emissions in this batch instead of committing. */\n\trollback(): void;\n}\n\ninterface ActiveBatch {\n\torder: BatchTarget[];\n\tdeferred: Map<BatchTarget, Wave>;\n\tcommitted: boolean;\n\trolledBack: boolean;\n}\n\nlet active: ActiveBatch | null = null;\nlet boundaryOwner: ActiveBatch | null = null;\n\nexport function currentBatch(): boolean {\n\treturn active !== null;\n}\n\nexport function currentBoundaryBatchToken(): object | undefined {\n\treturn active ?? boundaryOwner ?? undefined;\n}\n\n/**\n * Defer a node's tier-3 settle slice into the active batch. Returns true if a batch\n * captured it; false if there is no active batch (caller emits normally).\n */\nexport function deferToBatch(target: BatchTarget, tier3Wave: Wave): boolean {\n\tif (active === null) return false;\n\tif (!active.deferred.has(target)) active.order.push(target);\n\tactive.deferred.set(target, tier3Wave); // last-value coalescing\n\treturn true;\n}\n\n/**\n * Defer a topology mutation until after the active batch has committed/rolled back,\n * but only when this target has an uncommitted settle slice in the current batch.\n */\nexport function deferAfterBatchForTarget(target: BatchTarget, fn: () => void): boolean {\n\tif (active === null || !active.deferred.has(target)) return false;\n\tconst owner = active;\n\ttarget.__deferBoundary(() => {\n\t\tif (owner.committed) fn();\n\t}, owner);\n\treturn true;\n}\n\nfunction commit(b: ActiveBatch): void {\n\tconst prev = boundaryOwner;\n\tboundaryOwner = b;\n\ttry {\n\t\tfor (const target of b.order) {\n\t\t\tconst wave = b.deferred.get(target);\n\t\t\tif (wave) target.__commitBatchedWave(wave);\n\t\t}\n\t\tb.committed = true;\n\t} catch (e) {\n\t\tdropBoundaryTasksForBatch(b);\n\t\tthrow e;\n\t} finally {\n\t\tboundaryOwner = prev;\n\t}\n}\n\nfunction rollback(b: ActiveBatch): void {\n\tdropBoundaryTasksForBatch(b);\n\tfor (const target of b.order) target.__rollbackBatched();\n}\n\n/** Run `fn` as a batch (D12). DATA deferred to commit; throw/rollback discards. */\nexport function batch<R>(fn: (bctx: BatchCtx) => R): R {\n\t// Wave-owner boundary (R-rewire-deferred / D47): bracket the whole batch (fn + commit) so a\n\t// ctx.rewireNext issued by a fn that runs during COMMIT drains AFTER the commit, never on the\n\t// un-committed view. Inner waves (state.set, commit cascade) nest under this owner.\n\tenterWave();\n\ttry {\n\t\tif (active !== null) {\n\t\t\t// Nested batch joins the outer frame (one commit at the outermost exit).\n\t\t\tconst outer = active;\n\t\t\treturn fn({\n\t\t\t\trollback: () => {\n\t\t\t\t\touter.rolledBack = true;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst b: ActiveBatch = { order: [], deferred: new Map(), committed: false, rolledBack: false };\n\t\tactive = b;\n\t\tconst bctx: BatchCtx = {\n\t\t\trollback: () => {\n\t\t\t\tb.rolledBack = true;\n\t\t\t},\n\t\t};\n\t\tlet result: R;\n\t\ttry {\n\t\t\tresult = fn(bctx);\n\t\t} catch (e) {\n\t\t\tactive = null;\n\t\t\trollback(b);\n\t\t\tthrow e;\n\t\t}\n\t\tactive = null;\n\t\tif (b.rolledBack) rollback(b);\n\t\telse {\n\t\t\tcommit(b);\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\texitWave();\n\t}\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated handle-dispatch PoC (packages/pure-ts r8-poc, R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/**\n * First-class dispatcher (D21). Owns pools; graph binds to one (default = process-global,\n * D26 — the only global singleton). Pool trait is pluggable for WorkerPool/RemotePool (D20).\n */\n/** Per-handle profiling counters (D39 / R-profile). Lives on the dispatcher — the invoke\n * funnel (F-DISPATCH-ALL) — NEVER on the thin node (R-node-thin). */\nexport interface HandleStat {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n}\n\nconst statKey = (h: Handle): string => `${h.poolId}:${h.handleId}`;\n\nexport class Dispatcher {\n\tprivate pools: Pool[] = [];\n\treadonly syncPoolId: number;\n\treadonly asyncPoolId: number;\n\n\t// opt-in profile recorder (default OFF → zero overhead, F-PERF).\n\tprivate _recording = false;\n\tprivate _stats = new Map<string, HandleStat>();\n\tprivate _totalInvokes = 0;\n\n\tconstructor() {\n\t\tthis.syncPoolId = this.addPool(new PoolTable(\"sync\"));\n\t\tthis.asyncPoolId = this.addPool(new PoolTable(\"async\"));\n\t}\n\n\t/** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */\n\tsetRecording(on: boolean): void {\n\t\tthis._recording = on;\n\t}\n\t/** Reset accumulated profiling counters. */\n\tclearStats(): void {\n\t\tthis._stats.clear();\n\t\tthis._totalInvokes = 0;\n\t}\n\t/** Read a handle's accumulated counters (undefined if it never ran while recording). */\n\tstatFor(handle: Handle): HandleStat | undefined {\n\t\treturn this._stats.get(statKey(handle));\n\t}\n\t/** Total fn invocations recorded across the dispatcher. */\n\tget totalInvokes(): number {\n\t\treturn this._totalInvokes;\n\t}\n\n\taddPool(pool: Pool): number {\n\t\tconst id = this.pools.length;\n\t\tthis.pools.push(pool);\n\t\treturn id;\n\t}\n\n\t/** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */\n\tregister(fn: NodeFn, pool: PoolKind | number = \"sync\"): Handle {\n\t\tconst poolId = pool === \"sync\" ? this.syncPoolId : pool === \"async\" ? this.asyncPoolId : pool;\n\t\tconst handleId = this.pools[poolId].register(fn);\n\t\treturn { poolId, handleId };\n\t}\n\n\t/**\n\t * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any\n\t * accumulated profile stat so a reused id never inherits the previous tenant's counters.\n\t * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node\n\t * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives\n\t * activate↔deactivate and is reused on reactivation; only a rewire swaps it).\n\t */\n\tunregister(handle: Handle): void {\n\t\tthis.pools[handle.poolId].unregister(handle.handleId);\n\t\t// Drop the stat UNCONDITIONALLY (QA F2.1), not only while recording: if recording was\n\t\t// OFF at unregister time the key would linger, and a later register reusing this id (the\n\t\t// free-list) would inherit the prior tenant's counters once recording resumes. delete of\n\t\t// an absent key is a cheap no-op; unregister is off the hot invoke path (F-PERF intact).\n\t\tthis._stats.delete(statKey(handle));\n\t}\n\n\t/** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */\n\tinvoke(handle: Handle, ctx: Ctx): void {\n\t\tif (!this._recording) {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t\treturn;\n\t\t}\n\t\tthis._totalInvokes++;\n\t\tconst t0 = performance.now();\n\t\ttry {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t} finally {\n\t\t\tconst dur = (performance.now() - t0) * 1e6; // ms → ns\n\t\t\tconst key = statKey(handle);\n\t\t\tconst s = this._stats.get(key) ?? {\n\t\t\t\tinvokes: 0,\n\t\t\t\ttotalDurationNs: 0,\n\t\t\t\tlastDurationNs: 0,\n\t\t\t};\n\t\t\ts.invokes++;\n\t\t\ts.lastDurationNs = dur;\n\t\t\ts.totalDurationNs += dur;\n\t\t\tthis._stats.set(key, s);\n\t\t}\n\t}\n\n\tpoolKind(poolId: number): PoolKind {\n\t\treturn this.pools[poolId].kind;\n\t}\n}\n\n/** The only global singleton (D26). Overridable by passing an explicit dispatcher. */\nexport const defaultDispatcher = new Dispatcher();\n","import type { Ctx, Sink } from \"../ctx/types.js\";\nimport type { Dispatcher, Handle } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport { type LockId, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\nimport type { Node, Status } from \"./node.js\";\nimport type { NodeVersion, ResolvedNodeVersioningPolicy } from \"./versioning.js\";\n\nexport type NodeId = number & { readonly __nodeId: unique symbol };\n\nexport interface DepBookkeeping {\n\tbatch: Array<unknown[] | null>;\n\twaveData: unknown[][][];\n\twaveTokens: Array<object | undefined>;\n\tprev: unknown[];\n\thasData: boolean[];\n\tdirty: boolean[];\n\ttier: number[];\n\tterminal: Array<true | unknown | undefined>;\n\tterminalInput: Array<true | unknown | undefined>;\n\tunsubs: Array<() => void>;\n\tidxBoxes: Array<{ v: number }>;\n}\n\nexport interface ValueState<T> {\n\tcache: T | undefined;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasTorndown: boolean;\n\treplayRing: T[];\n}\n\nexport interface VersionState {\n\tpolicy: ResolvedNodeVersioningPolicy;\n\tvalue: NodeVersion | undefined;\n}\n\nexport interface WaveState {\n\tpending: number;\n\thasCalledFnOnce: boolean;\n\temittedDirtyThisWave: boolean;\n\temittedSettleThisWave: boolean;\n\tinsideRunWave: boolean;\n\tinDepMutation: boolean;\n\trewireRunPending: boolean;\n\tbatchDirtyOwed: boolean;\n}\n\nexport interface ControlState {\n\tpauseLockset: Set<unknown>;\n\tpausedDepWaveOccurred: boolean;\n\tpauseBuffer: Wave[];\n\tdemandOwed: PullDemand | undefined;\n\tactivePull: PullDemand | undefined;\n\tpullDirtyOwed: boolean;\n\tinDeliverDemand: boolean;\n}\n\nexport interface PrivateState {\n\tvalue: unknown;\n\tpersist: boolean;\n}\n\nexport interface CleanupHooks {\n\tonDeactivation: Array<() => void>;\n\tonInvalidate: Array<() => void>;\n}\n\nexport interface SyncCtxState {\n\tvalue: Ctx | null;\n}\n\nexport interface LifecycleState {\n\tsubscribers: Set<Sink>;\n\tactivated: boolean;\n}\n\nexport interface BoundaryTask {\n\tapply: () => void;\n\tbatchToken?: object;\n\tisReady?: () => boolean;\n}\n\nexport interface BoundaryState {\n\tqueue: BoundaryTask[];\n\thead: number;\n}\n\nexport interface NodeSlot<_T> {\n\tid: NodeId;\n\tdeps: Node<unknown>[];\n\thandle: Handle | null;\n\tpool: \"sync\" | \"async\";\n\tdispatcher: Dispatcher;\n\tenvironment: EnvironmentDrivers;\n\tpartial: boolean;\n\tterminalAsRealInput: boolean;\n\tcompleteWhenDepsComplete: boolean;\n\terrorWhenDepsError: boolean;\n\tresubscribable: boolean;\n\tresetOnTeardown: boolean;\n\tpausable: boolean | \"resumeAll\";\n\tpull: boolean;\n\tpullLock: LockId | undefined;\n\treplayN: number;\n\tdynamic: boolean;\n\tname?: string;\n\tfactory?: string;\n}\n\nexport interface NodeState<T> {\n\tdep: DepBookkeeping;\n\tlifecycle: LifecycleState;\n\tvalue: ValueState<T>;\n\tversion: VersionState;\n\twave: WaveState;\n\tcontrol: ControlState;\n\tprivateState: PrivateState;\n\thooks: CleanupHooks;\n\tsyncCtx: SyncCtxState;\n}\n\nexport class NodeCore {\n\tprivate nextId = 0;\n\tprivate readonly slots: Array<NodeSlot<unknown> | undefined> = [];\n\tprivate readonly values: Array<ValueState<unknown> | undefined> = [];\n\tprivate readonly waves: Array<WaveState | undefined> = [];\n\tprivate readonly controls: Array<ControlState | undefined> = [];\n\tprivate readonly lifecycles: Array<LifecycleState | undefined> = [];\n\tprivate readonly depStates: Array<DepBookkeeping | undefined> = [];\n\tprivate readonly privateStates: Array<PrivateState | undefined> = [];\n\tprivate readonly hooks: Array<CleanupHooks | undefined> = [];\n\tprivate readonly syncCtxs: Array<SyncCtxState | undefined> = [];\n\tprivate readonly versionStates: Array<VersionState | undefined> = [];\n\tprivate readonly boundary: BoundaryState = { queue: [], head: 0 };\n\n\tcreateSlot<T>(\n\t\tslot: Omit<NodeSlot<T>, \"id\">,\n\t\tstate: NodeState<T>,\n\t): { id: NodeId; slot: NodeSlot<T> } {\n\t\tconst id = this.nextId++ as NodeId;\n\t\tconst full = { ...slot, id };\n\t\tthis.slots[id] = full as NodeSlot<unknown>;\n\t\tthis.depStates[id] = state.dep;\n\t\tthis.lifecycles[id] = state.lifecycle;\n\t\tthis.values[id] = state.value as ValueState<unknown>;\n\t\tthis.waves[id] = state.wave;\n\t\tthis.controls[id] = state.control;\n\t\tthis.privateStates[id] = state.privateState;\n\t\tthis.hooks[id] = state.hooks;\n\t\tthis.syncCtxs[id] = state.syncCtx;\n\t\tthis.versionStates[id] = state.version;\n\t\treturn { id, slot: full };\n\t}\n\n\tget<T>(id: NodeId): NodeSlot<T> {\n\t\tconst slot = this.slots[id];\n\t\tif (slot === undefined) throw new Error(\"NodeCore: unknown node slot\");\n\t\treturn slot as NodeSlot<T>;\n\t}\n\n\tgetValue<T>(id: NodeId): ValueState<T> {\n\t\tconst value = this.values[id];\n\t\tif (value === undefined) throw new Error(\"NodeCore: unknown node value state\");\n\t\treturn value as ValueState<T>;\n\t}\n\n\tgetWave(id: NodeId): WaveState {\n\t\tconst wave = this.waves[id];\n\t\tif (wave === undefined) throw new Error(\"NodeCore: unknown node wave state\");\n\t\treturn wave;\n\t}\n\n\tgetControl(id: NodeId): ControlState {\n\t\tconst control = this.controls[id];\n\t\tif (control === undefined) throw new Error(\"NodeCore: unknown node control state\");\n\t\treturn control;\n\t}\n\n\tgetLifecycle(id: NodeId): LifecycleState {\n\t\tconst lifecycle = this.lifecycles[id];\n\t\tif (lifecycle === undefined) throw new Error(\"NodeCore: unknown node lifecycle state\");\n\t\treturn lifecycle;\n\t}\n\n\tgetDep(id: NodeId): DepBookkeeping {\n\t\tconst dep = this.depStates[id];\n\t\tif (dep === undefined) throw new Error(\"NodeCore: unknown node dep state\");\n\t\treturn dep;\n\t}\n\n\tgetPrivateState(id: NodeId): PrivateState {\n\t\tconst state = this.privateStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node private state\");\n\t\treturn state;\n\t}\n\n\tgetHooks(id: NodeId): CleanupHooks {\n\t\tconst hooks = this.hooks[id];\n\t\tif (hooks === undefined) throw new Error(\"NodeCore: unknown node cleanup hooks\");\n\t\treturn hooks;\n\t}\n\n\tgetSyncCtx(id: NodeId): SyncCtxState {\n\t\tconst state = this.syncCtxs[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node ctx state\");\n\t\treturn state;\n\t}\n\n\tgetVersion(id: NodeId): VersionState {\n\t\tconst state = this.versionStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node version state\");\n\t\treturn state;\n\t}\n\n\t/** @internal D122: release graph-owned ephemeral node runtime state from core retention. */\n\treleaseSlot(id: NodeId): void {\n\t\tthis.slots[id] = undefined;\n\t\tthis.depStates[id] = undefined;\n\t\tthis.lifecycles[id] = undefined;\n\t\tthis.values[id] = undefined;\n\t\tthis.waves[id] = undefined;\n\t\tthis.controls[id] = undefined;\n\t\tthis.privateStates[id] = undefined;\n\t\tthis.hooks[id] = undefined;\n\t\tthis.syncCtxs[id] = undefined;\n\t\tthis.versionStates[id] = undefined;\n\t}\n\n\t/** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */\n\tenqueueBoundaryTask(task: BoundaryTask): void {\n\t\tthis.boundary.queue.push(task);\n\t}\n\n\t/** @internal */\n\thasBoundaryTasks(): boolean {\n\t\treturn this.boundary.head < this.boundary.queue.length;\n\t}\n\n\t/** @internal */\n\tboundaryTaskCount(): number {\n\t\treturn this.boundary.queue.length - this.boundary.head;\n\t}\n\n\t/** @internal */\n\tshiftBoundaryTask(): BoundaryTask | undefined {\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst task = this.boundary.queue[this.boundary.head++];\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** @internal Put a not-yet-ready task back at this core's FIFO head. */\n\tunshiftBoundaryTask(task: BoundaryTask): void {\n\t\tconst remaining = this.boundary.queue.slice(this.boundary.head);\n\t\tthis.boundary.queue = [task, ...remaining];\n\t\tthis.boundary.head = 0;\n\t}\n\n\t/** @internal D110: discard all pending tasks caused by an uncommitted batch. */\n\tdropBoundaryTasksForBatch(batchToken: object): void {\n\t\tconst remaining = this.boundary.queue\n\t\t\t.slice(this.boundary.head)\n\t\t\t.filter((task) => task.batchToken !== batchToken);\n\t\tthis.boundary.queue = remaining;\n\t\tthis.boundary.head = 0;\n\t}\n}\n\nexport function makeDepBookkeeping(depCount: number): DepBookkeeping {\n\treturn {\n\t\tbatch: new Array(depCount).fill(null),\n\t\twaveData: Array.from({ length: depCount }, () => []),\n\t\twaveTokens: new Array(depCount).fill(undefined),\n\t\tprev: new Array(depCount).fill(SENTINEL),\n\t\thasData: new Array(depCount).fill(false),\n\t\tdirty: new Array(depCount).fill(false),\n\t\ttier: new Array(depCount).fill(0),\n\t\tterminal: new Array(depCount).fill(undefined),\n\t\tterminalInput: new Array(depCount).fill(undefined),\n\t\tunsubs: [],\n\t\tidxBoxes: [],\n\t};\n}\n","/**\n * Graph-owned environment driver bag (D130/D131).\n *\n * Drivers host process/network/messaging/runtime boundary work outside the synchronous wave core.\n * The bag is graph-local and is read from ctx by source/adapter bodies.\n */\n\nexport type DriverCancel = () => void;\n\nexport type DriverResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport interface ProcessCommand {\n\treadonly program: string;\n\treadonly args: readonly string[];\n\treadonly cwd?: string;\n\treadonly env?: readonly (readonly [string, string])[];\n}\n\nexport interface ProcessResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number | null;\n\treadonly signal: string | null;\n}\n\nexport interface HttpRequest {\n\treadonly method: string;\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n\treadonly body?: Uint8Array | string;\n}\n\nexport interface HttpResponse {\n\treadonly status: number;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport interface SseRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport interface SseEvent {\n\treadonly event?: string;\n\treadonly data: string;\n\treadonly id?: string;\n\treadonly retryMs?: number;\n}\n\nexport type SseDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: SseEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebSocketRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport type WebSocketEvent =\n\t| { readonly kind: \"open\" }\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\nexport interface WebSocketSend {\n\treadonly data: string | Uint8Array;\n}\n\nexport interface WebSocketSendResult {\n\treadonly sent: true;\n}\n\n/** Live WebSocket session handle for D133 SessionBundle adapters. */\nexport interface WebSocketSessionHandle {\n\tsend(\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\tclose(code?: number, reason?: string): void;\n\tcancel(): void;\n}\n\nexport type WebSocketDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebSocketEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebhookRegistration {\n\treadonly id: string;\n\treadonly method?: string;\n\treadonly path?: string;\n}\n\nexport interface WebhookEvent {\n\treadonly registrationId: string;\n\treadonly method: string;\n\treadonly path: string;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly query: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport type WebhookDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebhookEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface LocalProcessDriver {\n\trun(\n\t\tcommand: ProcessCommand,\n\t\tcallback: (result: DriverResult<ProcessResult>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalHttpDriver {\n\trequest(\n\t\trequest: HttpRequest,\n\t\tcallback: (result: DriverResult<HttpResponse>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalSseDriver {\n\tconnect(request: SseRequest, callback: (event: SseDriverEvent) => void): DriverCancel;\n}\n\nexport interface LocalWebSocketDriver {\n\tconnect(request: WebSocketRequest, callback: (event: WebSocketDriverEvent) => void): DriverCancel;\n\tsend?(\n\t\trequest: WebSocketRequest,\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\t/** Open a live bidirectional session; unlike send(), outbound messages use this same connection. */\n\tconnectSession?(\n\t\trequest: WebSocketRequest,\n\t\tcallback: (event: WebSocketDriverEvent) => void,\n\t): WebSocketSessionHandle;\n}\n\nexport interface LocalWebhookDriver {\n\tregister(\n\t\tregistration: WebhookRegistration,\n\t\tcallback: (event: WebhookDriverEvent) => void,\n\t): DriverCancel;\n}\n\nexport interface FetchResponseLike {\n\treadonly status: number;\n\treadonly headers?: { forEach?(fn: (value: string, key: string) => void): void };\n\tarrayBuffer(): PromiseLike<ArrayBuffer>;\n}\n\nexport type FetchLike = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: readonly (readonly [string, string])[];\n\t\treadonly body?: Uint8Array | string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => PromiseLike<FetchResponseLike>;\n\nexport interface WebSocketLike {\n\tsend(data: string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n\tremoveEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n}\n\nexport type WebSocketConstructorLike = new (url: string) => WebSocketLike;\n\nexport interface EnvironmentDriversInit {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n}\n\nexport class EnvironmentDrivers {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n\n\tconstructor(init: EnvironmentDriversInit = {}) {\n\t\tthis.process = init.process;\n\t\tthis.http = init.http;\n\t\tthis.sse = init.sse;\n\t\tthis.websocket = init.websocket;\n\t\tthis.webhook = init.webhook;\n\t\tObject.freeze(this);\n\t}\n\n\tstatic empty(): EnvironmentDrivers {\n\t\treturn EMPTY_ENVIRONMENT;\n\t}\n\n\twithProcess(driver: LocalProcessDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, process: driver });\n\t}\n\n\twithHttp(driver: LocalHttpDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, http: driver });\n\t}\n\n\twithSse(driver: LocalSseDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, sse: driver });\n\t}\n\n\twithWebSocket(driver: LocalWebSocketDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, websocket: driver });\n\t}\n\n\twithWebhook(driver: LocalWebhookDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, webhook: driver });\n\t}\n\n\tprocessDriver(): LocalProcessDriver | undefined {\n\t\treturn this.process;\n\t}\n\n\thttpDriver(): LocalHttpDriver | undefined {\n\t\treturn this.http;\n\t}\n\n\tsseDriver(): LocalSseDriver | undefined {\n\t\treturn this.sse;\n\t}\n\n\twebSocketDriver(): LocalWebSocketDriver | undefined {\n\t\treturn this.websocket;\n\t}\n\n\twebhookDriver(): LocalWebhookDriver | undefined {\n\t\treturn this.webhook;\n\t}\n}\n\nconst EMPTY_ENVIRONMENT = new EnvironmentDrivers();\n\nexport function fetchHttpDriver(fetchFn: FetchLike = requireGlobalFetch()): LocalHttpDriver {\n\treturn {\n\t\trequest(request, callback) {\n\t\t\tconst controller = new AbortController();\n\t\t\tvoid Promise.resolve(\n\t\t\t\tfetchFn(request.url, {\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\theaders: request.headers,\n\t\t\t\t\tbody: request.body,\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t}),\n\t\t\t).then(\n\t\t\t\tasync (response) => {\n\t\t\t\t\tconst headers: Array<readonly [string, string]> = [];\n\t\t\t\t\tresponse.headers?.forEach?.((value, key) => {\n\t\t\t\t\t\theaders.push([key, value]);\n\t\t\t\t\t});\n\t\t\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\tcallback({ ok: true, value: { status: response.status, headers, body } });\n\t\t\t\t},\n\t\t\t\t(error) => callback({ ok: false, error }),\n\t\t\t);\n\t\t\treturn () => controller.abort();\n\t\t},\n\t};\n}\n\nexport function domWebSocketDriver(\n\tWebSocketCtor: WebSocketConstructorLike = requireGlobalWebSocket(),\n): LocalWebSocketDriver {\n\treturn {\n\t\tconnect(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tsend(request, message, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet settled = false;\n\t\t\tconst finish = (result: DriverResult<WebSocketSendResult>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcallback(result);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t\tconst onOpen = () => {\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\tfinish({ ok: true, value: { sent: true } });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinish({ ok: false, error });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => finish({ ok: false, error: event });\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tconnectSession(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet active = true;\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tconst removeListeners = () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn {\n\t\t\t\tsend(message, sendCallback) {\n\t\t\t\t\tlet canceled = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: true, value: { sent: true } });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: false, error });\n\t\t\t\t\t}\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tclose(code, reason) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t},\n\t\t\t\tcancel() {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tactive = false;\n\t\t\t\t\tremoveListeners();\n\t\t\t\t\tsocket.close();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction requireGlobalFetch(): FetchLike {\n\tconst fetchFn = (globalThis as { fetch?: FetchLike }).fetch;\n\tif (fetchFn === undefined) throw new Error(\"fetchHttpDriver: global fetch is not available\");\n\treturn fetchFn;\n}\n\nfunction requireGlobalWebSocket(): WebSocketConstructorLike {\n\tconst ctor = (globalThis as { WebSocket?: WebSocketConstructorLike }).WebSocket;\n\tif (ctor === undefined) throw new Error(\"domWebSocketDriver: global WebSocket is not available\");\n\treturn ctor;\n}\n","/**\n * Neutral JSON/encoding utilities (D96).\n *\n * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON\n * scanner/canonicalization contract.\n */\n\n/** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */\nexport interface Codec<T> {\n\tencode(value: T): Uint8Array;\n\tdecode(bytes: Uint8Array): T;\n}\n\nexport type StrictJsonScalar = null | boolean | number | string;\nexport type StrictJsonValue =\n\t| StrictJsonScalar\n\t| readonly StrictJsonValue[]\n\t| { readonly [key: string]: StrictJsonValue };\nexport type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;\n\ntype JsonValue = StrictJsonValue;\n\nconst JS_MIN_NORMAL_NUMBER = 2 ** -1022;\n\nfunction assertStableJsonNumber(value: number, path: string): void {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new TypeError(`stableJsonString: non-finite number at ${path}`);\n\t}\n}\n\nfunction assertStrictJsonNumber(value: number, path: string): void {\n\tassertStableJsonNumber(value, path);\n\tif (Object.is(value, -0)) {\n\t\tthrow new TypeError(`stableJsonString: non-canonical number at ${path}`);\n\t}\n\tconst abs = Math.abs(value);\n\tif (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {\n\t\tthrow new TypeError(`stableJsonString: subnormal number at ${path}`);\n\t}\n\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`stableJsonString: integer outside safe range at ${path}`);\n\t}\n}\n\nfunction sortedJsonValue(\n\tvalue: unknown,\n\tseen = new Set<object>(),\n\tpath = \"$\",\n\tstrictNumbers = false,\n): JsonValue {\n\tif (value === null) return null;\n\tif (typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (strictNumbers) assertStrictJsonNumber(value, path);\n\t\telse assertStableJsonNumber(value, path);\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);\n\t}\n\tif (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\tthrow new TypeError(`stableJsonString: non-plain object at ${path}`);\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst isIndex =\n\t\t\t\t\t/^(0|[1-9]\\d*)$/.test(key) &&\n\t\t\t\t\tNumber.isSafeInteger(Number(key)) &&\n\t\t\t\t\tNumber(key) < value.length;\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: JsonValue[] = [];\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tif (!(i in value)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);\n\t\t\t\t}\n\t\t\t\tout.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t}\n\t\tconst out: Record<string, JsonValue> = Object.create(null);\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tout[key] = sortedJsonValue(\n\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\tseen,\n\t\t\t\t`${path}.${key}`,\n\t\t\t\tstrictNumbers,\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value, new Set<object>(), \"$\", true));\n}\n\n/** Build a JSON codec using stable object-key ordering. */\nexport function jsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder();\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\treturn encoder.encode(stableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\treturn JSON.parse(decoder.decode(bytes)) as T;\n\t\t},\n\t};\n}\n\n/** Default stable JSON codec for unknown values. */\nexport const jsonCodec: Codec<unknown> = jsonCodecFor<unknown>();\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.byteLength !== b.byteLength) return false;\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction hasUnpairedSurrogate(value: string): boolean {\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tconst code = value.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (code >= 0xdc00 && code <= 0xdfff) return true;\n\t}\n\treturn false;\n}\n\nfunction assertNoUnpairedSurrogates(value: unknown, seen = new Set<object>(), path = \"$\"): void {\n\tif (typeof value === \"string\") {\n\t\tif (hasUnpairedSurrogate(value)) {\n\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (value === null || typeof value !== \"object\") return;\n\tif (seen.has(value)) return;\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tassertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value as Record<string, unknown>)) {\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertNoUnpairedSurrogates((value as Record<string, unknown>)[key], seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction assertNoDuplicateJsonObjectKeys(text: string): void {\n\tlet index = 0;\n\n\tfunction fail(message: string): never {\n\t\tthrow new TypeError(`strictJsonCodec: ${message}`);\n\t}\n\n\tfunction skipWhitespace(): void {\n\t\twhile (/\\s/.test(text[index] ?? \"\")) index += 1;\n\t}\n\n\tfunction readJsonString(): string {\n\t\tconst start = index;\n\t\tindex += 1;\n\t\twhile (index < text.length) {\n\t\t\tconst ch = text[index];\n\t\t\tif (ch === '\"') {\n\t\t\t\tindex += 1;\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.parse(text.slice(start, index)) as string;\n\t\t\t\t} catch {\n\t\t\t\t\tfail(\"malformed JSON string\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ch === \"\\\\\") {\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t\tfail(\"unterminated JSON string\");\n\t}\n\n\tfunction consumeLiteral(literal: string): void {\n\t\tif (text.slice(index, index + literal.length) !== literal) {\n\t\t\tfail(`malformed JSON near byte ${index}`);\n\t\t}\n\t\tindex += literal.length;\n\t}\n\n\tfunction consumeNumber(): void {\n\t\tconst match = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/.exec(text.slice(index));\n\t\tif (!match) fail(`malformed JSON number near byte ${index}`);\n\t\tindex += match[0].length;\n\t}\n\n\tfunction parseValue(path: string): void {\n\t\tskipWhitespace();\n\t\tconst ch = text[index];\n\t\tif (ch === \"{\") {\n\t\t\tparseObject(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tparseArray(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\treadJsonString();\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"t\") {\n\t\t\tconsumeLiteral(\"true\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"f\") {\n\t\t\tconsumeLiteral(\"false\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"n\") {\n\t\t\tconsumeLiteral(\"null\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"-\" || (ch !== undefined && ch >= \"0\" && ch <= \"9\")) {\n\t\t\tconsumeNumber();\n\t\t\treturn;\n\t\t}\n\t\tfail(`malformed JSON near byte ${index}`);\n\t}\n\n\tfunction parseObject(path: string): void {\n\t\tconst keys = new Set<string>();\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"}\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\twhile (index < text.length) {\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== '\"') fail(`expected object key near byte ${index}`);\n\t\t\tconst key = readJsonString();\n\t\t\tif (keys.has(key)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tkeys.add(key);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== \":\") fail(`expected ':' after object key near byte ${index}`);\n\t\t\tindex += 1;\n\t\t\tparseValue(`${path}.${key}`);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"}\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or '}' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON object\");\n\t}\n\n\tfunction parseArray(path: string): void {\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"]\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\tlet item = 0;\n\t\twhile (index < text.length) {\n\t\t\tparseValue(`${path}[${item}]`);\n\t\t\titem += 1;\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"]\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or ']' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON array\");\n\t}\n\n\tparseValue(\"$\");\n\tskipWhitespace();\n\tif (index !== text.length) fail(`trailing JSON token near byte ${index}`);\n}\n\n/**\n * Build a strict canonical JSON codec (D84/D87/D96).\n * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,\n * unpaired surrogates, and values that cannot round-trip through stable JSON.\n */\nexport function strictJsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\tassertNoUnpairedSurrogates(value);\n\t\t\treturn encoder.encode(strictStableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\tconst text = decoder.decode(bytes);\n\t\t\tassertNoDuplicateJsonObjectKeys(text);\n\t\t\tconst decoded = JSON.parse(text) as unknown;\n\t\t\tassertNoUnpairedSurrogates(decoded);\n\t\t\tconst canonical = encoder.encode(strictStableJsonString(decoded));\n\t\t\tif (!bytesEqual(bytes, canonical)) {\n\t\t\t\tthrow new TypeError(\"strictJsonCodec: bytes are not canonical stable JSON\");\n\t\t\t}\n\t\t\treturn decoded as T;\n\t\t},\n\t};\n}\n\n/** Default strict canonical JSON codec for unknown values. */\nexport const strictJsonCodec: Codec<unknown> = strictJsonCodecFor<unknown>();\n\n/** D113 neutral helper for strict canonical JSON UTF-8 bytes. */\nexport function strictCanonicalJsonBytes(value: unknown): Uint8Array {\n\treturn strictJsonCodec.encode(value);\n}\n\n/** Validate and normalize a host value into strict canonical JSON data. */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as StrictJsonValue;\n\t} catch (cause) {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tthrow new TypeError(`${label}: value is not strict JSON compatible: ${message}`, { cause });\n\t}\n}\n\n/** Validate and normalize a host value into a strict canonical JSON object. */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst normalized = assertStrictJsonValue(value, label);\n\tif (normalized === null || typeof normalized !== \"object\" || Array.isArray(normalized)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn normalized as StrictJsonObject;\n}\n","import { strictCanonicalJsonBytes, strictJsonCodec } from \"../json/codec.js\";\n\nexport type NodeVersioningLevel = 0 | 1;\n\n/**\n * D112 V1 node-version hash callback.\n *\n * The callback receives strict canonical JSON UTF-8 DATA bytes, not the raw host value.\n * Runtime V1 versioning encodes DATA with `strictCanonicalJsonBytes(value)` before calling hash.\n */\nexport type NodeVersionHashFn = (bytes: Uint8Array) => string;\n\nexport type NodeVersioningPolicy =\n\t| false\n\t| 0\n\t| 1\n\t| {\n\t\t\tlevel: NodeVersioningLevel;\n\t\t\thash?: NodeVersionHashFn;\n\t };\n\nexport type ResolvedNodeVersioningPolicy =\n\t| { readonly enabled: false }\n\t| { readonly enabled: true; readonly level: 0 }\n\t| { readonly enabled: true; readonly level: 1; readonly hash: NodeVersionHashFn };\n\nexport type NodeVersionV0 = {\n\treadonly level: 0;\n\treadonly counter: number;\n};\n\nexport type NodeVersionV1 = {\n\treadonly level: 1;\n\treadonly counter: number;\n\treadonly cid: string;\n\treadonly prev: string | null;\n};\n\nexport type NodeVersion = NodeVersionV0 | NodeVersionV1;\n\nexport type NodeVersionJson = NodeVersion;\n\nconst ABSENT_V1_SEED = Object.freeze({\n\t\"@graphrefly/node-version\": \"v1-absent\",\n});\n\nfunction fnv1a64(input: Uint8Array): string {\n\tlet hash = 0xcbf29ce484222325n;\n\tconst prime = 0x100000001b3n;\n\tfor (const byte of input) {\n\t\thash ^= BigInt(byte);\n\t\thash = BigInt.asUintN(64, hash * prime);\n\t}\n\treturn hash.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Default synchronous D112 V1 node-version hash over strict canonical JSON UTF-8 bytes.\n *\n * When hashing a host value directly, encode first:\n * `defaultNodeVersionHash(strictCanonicalJsonBytes(value))`.\n */\nexport function defaultNodeVersionHash(bytes: Uint8Array): string {\n\treturn `fnv1a64:${fnv1a64(bytes)}`;\n}\n\nfunction computeV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\tvalue: unknown,\n): string {\n\treturn policy.hash(strictCanonicalJsonBytes(value));\n}\n\nexport function assertNodeVersionDataCompatible(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): void {\n\tif (!policy.enabled || policy.level === 0) return;\n\tstrictCanonicalJsonBytes(value);\n}\n\nexport function snapshotNodeVersionData(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): unknown {\n\tif (!policy.enabled || policy.level === 0) return value;\n\tconst bytes = strictCanonicalJsonBytes(value);\n\treturn strictJsonCodec.decode(bytes);\n}\n\nexport function resolveNodeVersioningPolicy(\n\tpolicy: NodeVersioningPolicy | undefined,\n): ResolvedNodeVersioningPolicy {\n\tif (policy === false) return { enabled: false };\n\tif (policy === undefined || policy === 0) return { enabled: true, level: 0 };\n\tif (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };\n\tif (typeof policy === \"object\" && policy !== null) {\n\t\tif (policy.level === 0) return { enabled: true, level: 0 };\n\t\tif (policy.level === 1) {\n\t\t\treturn { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };\n\t\t}\n\t}\n\tthrow new Error(\"node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)\");\n}\n\nexport function createNodeVersion(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tinitialValue: unknown = ABSENT_V1_SEED,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: 0,\n\t\tcid: computeV1Cid(policy, initialValue),\n\t\tprev: null,\n\t});\n}\n\nexport function advanceNodeVersion(\n\tcurrent: NodeVersion | undefined,\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (current === undefined) return createNodeVersion(policy, value);\n\tif (policy.level === 0) {\n\t\treturn Object.freeze({ level: 0, counter: current.counter + 1 });\n\t}\n\tconst previous = current.level === 1 ? current.cid : null;\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: current.counter + 1,\n\t\tcid: computeV1Cid(policy, value),\n\t\tprev: previous,\n\t});\n}\n\nexport function cloneNodeVersion(version: NodeVersion | undefined): NodeVersion | undefined {\n\tif (version === undefined) return undefined;\n\tif (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: version.counter,\n\t\tcid: version.cid,\n\t\tprev: version.prev,\n\t});\n}\n\nexport function restoredV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\thasData: boolean,\n\tcache: unknown,\n): string {\n\treturn computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);\n}\n\nexport function validateNodeVersionJson(value: unknown, path: string): NodeVersionJson {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new Error(`restoreGraph: ${path} must be an object`);\n\t}\n\tconst record = value as Record<string, unknown>;\n\tif (record.level === 0) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\treturn Object.freeze({ level: 0, counter: record.counter as number });\n\t}\n\tif (record.level === 1) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\tif (typeof record.cid !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.cid must be a string`);\n\t\t}\n\t\tif (record.prev !== null && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string or null`);\n\t\t}\n\t\tif ((record.counter as number) === 0 && record.prev !== null) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be null when counter is 0`);\n\t\t}\n\t\tif ((record.counter as number) > 0 && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string when counter is > 0`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tlevel: 1,\n\t\t\tcounter: record.counter as number,\n\t\t\tcid: record.cid,\n\t\t\tprev: record.prev,\n\t\t});\n\t}\n\tthrow new Error(`restoreGraph: ${path}.level must be 0 or 1`);\n}\n","/**\n * The node primitive — the thinnest substrate object (R-node-thin / D5).\n *\n * Holds a fn handle + deps + the wave state machine; ZERO inspection cruft\n * (naming/find/describe are the graph layer, CSP-2). Canonical authority:\n * ~/src/graphrefly/spec/rules.jsonl (R-node-*, R-two-phase, R-diamond, R-resolved-undirty,\n * R-first-run-gate, R-push-subscribe, R-rom-ram, R-fn-contract, R-initial, R-ctx-up).\n *\n * Slice 1 = core wave: state node, compute node, two-phase DIRTY->DATA, diamond\n * pending-counter join, first-run gate, substrate-synthesized undirty RESOLVED\n * (R-resolved-undirty / D49 — no equals-substitution; every occurrence is DATA),\n * push-on-subscribe, lazy activation, ROM/RAM. Lifecycle (terminal/INVALIDATE/cleanup),\n * control (PAUSE/async), batch, and dynamicNode land in later slices.\n */\n\nimport {\n\tcurrentBatch,\n\tcurrentBoundaryBatchToken,\n\tdeferAfterBatchForTarget,\n\tdeferToBatch,\n} from \"../batch/batch.js\";\nimport { deferRewire, enterWave, exitWave, scheduleBoundaryDrain } from \"../batch/boundary.js\";\nimport {\n\tCTX_DEP_CACHE,\n\tCTX_NODE_BINDING,\n\ttype Ctx,\n\ttype CtxState,\n\ttype DeliveryMeta,\n\ttype NodeFn,\n\ttype Sink,\n\ttype TerminalData,\n\ttype WaveData,\n} from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher, type Handle } from \"../dispatcher/index.js\";\nimport { EnvironmentDrivers } from \"../graph/environment.js\";\nimport {\n\terrorPayload,\n\tisDeferredTier,\n\tisInvalidErrorPayload,\n\tisPauseBufferedTier,\n\tisTerminal,\n\tisUpAllowed,\n\tisValueTier,\n\ttype LockId,\n\ttype Message,\n\tmessageTier,\n\ttype PullDemand,\n\tSENTINEL,\n\ttype Wave,\n} from \"../protocol/messages.js\";\nimport {\n\ttype CleanupHooks,\n\ttype ControlState,\n\ttype DepBookkeeping,\n\ttype LifecycleState,\n\tmakeDepBookkeeping,\n\tNodeCore,\n\ttype NodeId,\n\ttype NodeSlot,\n\ttype PrivateState,\n\ttype SyncCtxState,\n\ttype ValueState,\n\ttype VersionState,\n\ttype WaveState,\n} from \"./core.js\";\nimport {\n\tadvanceNodeVersion,\n\tassertNodeVersionDataCompatible,\n\tcloneNodeVersion,\n\tcreateNodeVersion,\n\ttype NodeVersion,\n\ttype NodeVersioningPolicy,\n\tresolveNodeVersioningPolicy,\n\trestoredV1Cid,\n\tsnapshotNodeVersionData,\n} from \"./versioning.js\";\n\nexport type Status =\n\t| \"sentinel\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\nexport interface NodeOptions<T = unknown> {\n\t/** Pre-populate cache; source pushes [DATA, initial] on subscribe (R-initial). `null` is valid. */\n\tinitial?: T | null;\n\t/** First-run gate off when true; fn body must guard SENTINEL per dep (R-first-run-gate). */\n\tpartial?: boolean;\n\t/** A dep terminal also settles the first-run gate (Reduce-class, R-first-run-gate). */\n\tterminalAsRealInput?: boolean;\n\t/** Auto-emit COMPLETE when ALL deps complete (R-deps-terminal). Default true. */\n\tcompleteWhenDepsComplete?: boolean;\n\t/** Auto-emit ERROR when any dep errors (R-deps-terminal). Default true. */\n\terrorWhenDepsError?: boolean;\n\t/** Allow re-activation after terminal; late subscribe resets the lifecycle (R-terminal). Default false. */\n\tresubscribable?: boolean;\n\t/** Clear cached value on TEARDOWN. Default false. */\n\tresetOnTeardown?: boolean;\n\t/** PAUSE/RESUME behavior (R-pause-modes). Default true. */\n\tpausable?: boolean | \"resumeAll\";\n\t/**\n\t * Pull-mode node (R-pull / D269): a quiet-until-demanded source, identified by this\n\t * author-supplied `pullId` (a unique LockId — a `Symbol` recommended; NOT the node name, NOT a\n\t * bare string if callers may also use strings as pause locks). QUIET by default: it ABSORBS\n\t * an upstream DIRTY WITHOUT relaying it downstream\n\t * (the wedge fix) and does NOT push-on-subscribe its cached value (START only). A DEMAND =\n\t * cone-routed `PULL({pullId, params?})`: a downstream consumer issues\n\t * `ctx.up([[\"PULL\", { pullId, params }]])` (broadcast up the declared cone) or\n\t * `ctx.up(msgs, towardDep)` (directed) WITHOUT holding this node's reference; the PULL travels\n\t * up to the pullId-holder, which fires EXACTLY ONE delivery (DIRTY-before-DATA when it emits)\n\t * then RE-QUIETS (1:1). Delivery content =\n\t * the orthogonal `pausable` mode: `true` → coalesced LATEST (one DATA); `'resumeAll'` → buffered\n\t * BACKLOG. `pullId` + `pausable:false` is REJECTED at construction. A SELF-triggered demand (a\n\t * consumer demanding a dep it ALSO reads) must defer via {@link Ctx.upNext} (R-rewire-deferred /\n\t * D37). Author the pullId as a shared module const used at both this node and the demander's fn.\n\t */\n\tpullId?: LockId;\n\t/** Buffer the last N outgoing DATA for late subscribers (R-replay-buffer). */\n\treplayBuffer?: number;\n\t/**\n\t * D109 node runtime versioning policy. Default is nodev0 (`{level:0,counter}`); `false`\n\t * disables runtime version metadata for this node.\n\t */\n\tversioning?: NodeVersioningPolicy;\n\t/** Mark this as a dynamicNode — fn gets ctx.track(i) for read-selection (R-dynamic-node / D35). */\n\tdynamic?: boolean;\n\t/** Dispatch pool for the fn (R-sync-core). Default sync. */\n\tpool?: \"sync\" | \"async\";\n\t/** Dispatcher to register/invoke against. Default = process-global (D26). */\n\tdispatcher?: Dispatcher;\n\t/** Optional debug name (graph layer owns real naming/inspection). */\n\tname?: string;\n\t/**\n\t * Real operator/source factory name for a STANDALONE graph-less node (D43-reserved; D51).\n\t * The graph index (`_entries`) carries the factory for g.*-registered nodes, so this is only\n\t * read for a node NOT in any graph index — a runtime *Map inner (bare `fromAny`/`initNode`\n\t * node) auto-discovered by `describe` (R-describe / R-edges-derived / D51). Off the canonical\n\t * wave path (R-node-thin intact — a pure annotation, never touched by the wave machinery).\n\t */\n\tfactory?: string;\n}\n\nexport interface NodeCheckpointState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly terminal: true | unknown | undefined;\n\treadonly activated: boolean;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | undefined;\n\treadonly handle: Handle | null;\n}\n\nexport interface NodeRestoreState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly status: Status;\n\treadonly terminal: true | unknown | undefined;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | false;\n}\n\ntype TopologyDepsChangedObserver = (\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n) => void;\n\nlet constructingCore: NodeCore | undefined;\nlet constructingEnvironment: EnvironmentDrivers | undefined;\nconst ownerTokens = new WeakMap<Node<unknown>, unknown>();\nconst topologyDepsChangedObservers = new WeakMap<Node<unknown>, TopologyDepsChangedObserver>();\nconst checkpointReaders = new WeakMap<Node<unknown>, () => NodeCheckpointState>();\nconst restoreWriters = new WeakMap<Node<unknown>, (state: NodeRestoreState) => void>();\nconst runtimeReleasers = new WeakMap<Node<unknown>, () => void>();\nconst runtimeQuiescenceReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst subscriberCountReaders = new WeakMap<Node<unknown>, () => number>();\nconst activationReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst releasedNodes = new WeakSet<Node<unknown>>();\n\n/** @internal Run a Node/StateNode constructor against a graph-local core without widening the public constructor. */\nexport function withNodeCore<TNode extends Node<unknown>>(\n\tcore: NodeCore,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingCore;\n\tconstructingCore = core;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingCore = prev;\n\t}\n}\n\n/** @internal Run a Node/StateNode constructor with graph-owned environment drivers (D130/D131). */\nexport function withEnvironmentDrivers<TNode extends Node<unknown>>(\n\tenvironment: EnvironmentDrivers,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingEnvironment;\n\tconstructingEnvironment = environment;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingEnvironment = prev;\n\t}\n}\n\n/** @internal Graph-domain ownership token for D22 intra-graph guards. */\nexport function getNodeOwner(n: Node<unknown>): unknown {\n\treturn ownerTokens.get(n);\n}\n\n/** @internal Assign graph-domain ownership after graph registration. */\nexport function setNodeOwner(n: Node<unknown>, owner: unknown): void {\n\townerTokens.set(n, owner);\n}\n\n/** @internal Graph-layer D145 topology egress hook. */\nexport function setNodeTopologyDepsChangedObserver(\n\tn: Node<unknown>,\n\tobserver: TopologyDepsChangedObserver,\n): void {\n\ttopologyDepsChangedObservers.set(n, observer);\n}\n\nfunction notifyTopologyDepsChanged(\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n): void {\n\ttopologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);\n}\n\n/** @internal Graph checkpoint inspection, kept as a module helper so Node stays method-thin. */\nexport function checkpointStateOfNode(n: Node<unknown>): NodeCheckpointState {\n\tconst read = checkpointReaders.get(n);\n\tif (read === undefined) throw new Error(\"checkpoint: unknown node state\");\n\treturn read();\n}\n\n/** @internal D94 restore commit: install runtime state without a protocol wave or subscription. */\nexport function restoreStateOfNode(n: Node<unknown>, state: NodeRestoreState): void {\n\tconst write = restoreWriters.get(n);\n\tif (write === undefined) throw new Error(\"restoreGraph: unknown node state\");\n\twrite(state);\n}\n\n/** @internal D122 graph-owned ephemeral lifecycle release. */\nexport function releaseRuntimeOfNode(n: Node<unknown>): void {\n\truntimeReleasers.get(n)?.();\n}\n\n/** @internal D124 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeQuiescentForRelease(n: Node<unknown>): boolean {\n\treturn runtimeQuiescenceReaders.get(n)?.() ?? false;\n}\n\n/** @internal D124 graph-owned release subscriber accounting. */\nexport function subscriberCountOfNode(n: Node<unknown>): number {\n\treturn subscriberCountReaders.get(n)?.() ?? 0;\n}\n\n/** @internal D124 graph-owned release internal-subscriber accounting. */\nexport function isNodeActiveForRelease(n: Node<unknown>): boolean {\n\treturn activationReaders.get(n)?.() ?? false;\n}\n\n/** @internal D122 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeReleased(n: Node<unknown>): boolean {\n\treturn releasedNodes.has(n);\n}\n\nfunction terminalView(t: unknown): unknown {\n\treturn t === undefined ? false : t;\n}\n\nfunction normalizePullDemand(demand: PullDemand): PullDemand {\n\tif (typeof demand !== \"object\" || demand === null || Array.isArray(demand)) {\n\t\tthrow new Error(\"ctx.up: PULL requires { pullId, params? } demand payload (D269)\");\n\t}\n\tconst pullId = (demand as { pullId?: unknown }).pullId;\n\tif (typeof pullId !== \"string\" && typeof pullId !== \"symbol\") {\n\t\tthrow new Error(\"ctx.up: PULL demand requires a string or symbol pullId (D269)\");\n\t}\n\tconst params = (demand as { params?: unknown }).params;\n\treturn params === undefined ? { pullId } : { pullId, params };\n}\n\nfunction validateDownPayloads(msgs: Wave): void {\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"DATA\" && m[1] === undefined) {\n\t\t\tthrow new Error(\"down: DATA requires a non-SENTINEL payload (R-data-payload)\");\n\t\t}\n\t\tif (m[0] === \"ERROR\" && isInvalidErrorPayload(m[1])) {\n\t\t\tthrow new Error(\"down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)\");\n\t\t}\n\t}\n}\n\n/** A queued deferred self-rewire op (R-rewire-deferred / D47), drained at the wave boundary. */\ntype RewireOp =\n\t| { kind: \"add\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"remove\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"set\"; deps: Node<unknown>[]; fn: NodeFn };\n\n/** Internal routing state for one up-going control wave. */\ntype UpRouteState = {\n\tdemandFired: Map<LockId, Set<Node<unknown>>>;\n};\n\nexport class Node<T = unknown> {\n\tprivate readonly _core: NodeCore;\n\tprivate readonly _id: NodeId;\n\tprivate readonly _slot: NodeSlot<T>;\n\tprivate readonly _dep: DepBookkeeping;\n\tprivate readonly _value: ValueState<T>;\n\tprivate readonly _wave: WaveState;\n\tprivate readonly _control: ControlState;\n\tprivate readonly _lifecycle: LifecycleState;\n\tprivate readonly _privateState: PrivateState;\n\tprivate readonly _hooks: CleanupHooks;\n\tprivate readonly _syncCtxState: SyncCtxState;\n\tprivate readonly _version: VersionState;\n\tprivate _restoredActivationPending = false;\n\tprivate _released = false;\n\n\tprivate get _syncCtx(): Ctx | null {\n\t\treturn this._syncCtxState.value;\n\t}\n\n\tprivate set _syncCtx(ctx: Ctx | null) {\n\t\tthis._syncCtxState.value = ctx;\n\t}\n\n\tconstructor(\n\t\tdeps: Node<unknown>[],\n\t\thandleOrFn: Handle | NodeFn | null,\n\t\topts: NodeOptions<T> = {},\n\t) {\n\t\tconst core = constructingCore;\n\t\tconstructingCore = undefined;\n\t\tconst dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tconst environment = constructingEnvironment ?? EnvironmentDrivers.empty();\n\t\tconstructingEnvironment = undefined;\n\t\tconst pool = opts.pool ?? \"sync\";\n\t\tconst pausable = opts.pausable ?? true;\n\t\tconst pullLock = opts.pullId;\n\t\tconst pull = opts.pullId !== undefined;\n\t\t// R-pull (D269): pull-mode is keyed by an author-supplied pullId (its quiet latch).\n\t\t// R-pull (D55, pin 3): pull still uses the pausable delivery-content axis; pausable:false\n\t\t// ignores PAUSE/RESUME buffering and contradicts quiet pull delivery. Reject at construction.\n\t\tif (pull && pausable === false)\n\t\t\tthrow new Error(\n\t\t\t\t\"node: pullId is incompatible with pausable:false — a pull node uses the pausable delivery-content axis (R-pull / R-pause-modes / D55,D269)\",\n\t\t\t);\n\n\t\tlet handle: Handle | null;\n\t\tif (handleOrFn === null) handle = null;\n\t\telse if (typeof handleOrFn === \"function\") handle = dispatcher.register(handleOrFn, pool);\n\t\telse handle = handleOrFn;\n\n\t\tconst n = deps.length;\n\t\tconst dep = makeDepBookkeeping(n);\n\t\tconst versioning = resolveNodeVersioningPolicy(opts.versioning);\n\t\tconst value = {\n\t\t\tcache: SENTINEL as T | undefined,\n\t\t\thasData: false,\n\t\t\tstatus: \"sentinel\" as Status,\n\t\t\tterminal: undefined,\n\t\t\thasTorndown: false,\n\t\t\treplayRing: [] as T[],\n\t\t};\n\t\tif (opts.initial !== undefined) {\n\t\t\tvalue.cache = opts.initial as T;\n\t\t\tvalue.hasData = true;\n\t\t\tvalue.status = \"settled\";\n\t\t}\n\t\tconst pauseLockset = new Set<unknown>();\n\t\tthis._core = core ?? new NodeCore();\n\t\tconst created = this._core.createSlot<T>(\n\t\t\t{\n\t\t\t\tdeps,\n\t\t\t\thandle,\n\t\t\t\tpool,\n\t\t\t\tdispatcher,\n\t\t\t\tenvironment,\n\t\t\t\tpartial: opts.partial ?? false,\n\t\t\t\tterminalAsRealInput: opts.terminalAsRealInput ?? false,\n\t\t\t\tcompleteWhenDepsComplete: opts.completeWhenDepsComplete ?? true,\n\t\t\t\terrorWhenDepsError: opts.errorWhenDepsError ?? true,\n\t\t\t\tresubscribable: opts.resubscribable ?? false,\n\t\t\t\tresetOnTeardown: opts.resetOnTeardown ?? false,\n\t\t\t\tpausable,\n\t\t\t\tpull,\n\t\t\t\tpullLock,\n\t\t\t\treplayN: opts.replayBuffer ?? 0,\n\t\t\t\tdynamic: opts.dynamic ?? false,\n\t\t\t\tname: opts.name,\n\t\t\t\tfactory: opts.factory,\n\t\t\t},\n\t\t\t{\n\t\t\t\tdep,\n\t\t\t\tlifecycle: { subscribers: new Set<Sink>(), activated: false },\n\t\t\t\tvalue,\n\t\t\t\twave: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\thasCalledFnOnce: false,\n\t\t\t\t\temittedDirtyThisWave: false,\n\t\t\t\t\temittedSettleThisWave: false,\n\t\t\t\t\tinsideRunWave: false,\n\t\t\t\t\tinDepMutation: false,\n\t\t\t\t\trewireRunPending: false,\n\t\t\t\t\tbatchDirtyOwed: false,\n\t\t\t\t},\n\t\t\t\tcontrol: {\n\t\t\t\t\tpauseLockset,\n\t\t\t\t\tpausedDepWaveOccurred: false,\n\t\t\t\t\tpauseBuffer: [],\n\t\t\t\t\tdemandOwed: undefined,\n\t\t\t\t\tactivePull: undefined,\n\t\t\t\t\tpullDirtyOwed: false,\n\t\t\t\t\tinDeliverDemand: false,\n\t\t\t\t},\n\t\t\t\tprivateState: { value: SENTINEL, persist: false },\n\t\t\t\thooks: { onDeactivation: [], onInvalidate: [] },\n\t\t\t\tsyncCtx: { value: null },\n\t\t\t\tversion: {\n\t\t\t\t\tpolicy: versioning,\n\t\t\t\t\tvalue: createNodeVersion(\n\t\t\t\t\t\tversioning,\n\t\t\t\t\t\topts.initial !== undefined ? opts.initial : undefined,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tthis._id = created.id;\n\t\tthis._slot = this._core.get<T>(this._id);\n\t\tthis._dep = this._core.getDep(this._id);\n\t\tthis._value = this._core.getValue<T>(this._id);\n\t\tthis._wave = this._core.getWave(this._id);\n\t\tthis._control = this._core.getControl(this._id);\n\t\tthis._lifecycle = this._core.getLifecycle(this._id);\n\t\tthis._privateState = this._core.getPrivateState(this._id);\n\t\tthis._hooks = this._core.getHooks(this._id);\n\t\tthis._syncCtxState = this._core.getSyncCtx(this._id);\n\t\tthis._version = this._core.getVersion(this._id);\n\t\tcheckpointReaders.set(this as Node<unknown>, () => ({\n\t\t\tcache: this._value.cache,\n\t\t\thasData: this._value.hasData,\n\t\t\tterminal: this._value.terminal,\n\t\t\tactivated: this._lifecycle.activated,\n\t\t\thasCalledFnOnce: this._wave.hasCalledFnOnce,\n\t\t\tctxState: {\n\t\t\t\tvalue: this._privateState.value,\n\t\t\t\tpersist: this._privateState.persist,\n\t\t\t},\n\t\t\tversion: cloneNodeVersion(this._version.value),\n\t\t\thandle: this._slot.handle,\n\t\t}));\n\t\trestoreWriters.set(this as Node<unknown>, (state) => {\n\t\t\tthis._assertNotReleased(\"restoreGraph\");\n\t\t\tthis._value.cache = state.cache as T;\n\t\t\tthis._value.hasData = state.hasData;\n\t\t\tthis._value.status = state.status;\n\t\t\tthis._value.terminal = state.terminal;\n\t\t\tthis._value.hasTorndown = false;\n\t\t\tthis._value.replayRing = [];\n\t\t\tthis._wave.hasCalledFnOnce = state.hasCalledFnOnce;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._wave.emittedSettleThisWave = false;\n\t\t\tthis._wave.pending = 0;\n\t\t\tthis._wave.insideRunWave = false;\n\t\t\tthis._wave.inDepMutation = false;\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t\tthis._control.pauseLockset.clear();\n\t\t\tthis._privateState.value = state.ctxState.value;\n\t\t\tthis._privateState.persist = state.ctxState.persist;\n\t\t\tif (state.version === false) {\n\t\t\t\tthis._version.policy = { enabled: false };\n\t\t\t\tthis._version.value = undefined;\n\t\t\t} else if (state.version.level === 0) {\n\t\t\t\tthis._version.policy = { enabled: true, level: 0 };\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t} else {\n\t\t\t\tif (!this._version.policy.enabled || this._version.policy.level !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// D109: V1 restore must match the selected hash lane. After DATA then\n\t\t\t\t// INVALIDATE/resetOnTeardown, cache is absent while cid remains the last DATA cid;\n\t\t\t\t// without the DATA value, restore cannot verify the lane, so fail honestly.\n\t\t\t\tif (!state.hasData && state.version.counter > 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);\n\t\t\t\tif (expectedCid !== state.version.cid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t}\n\t\t\tthis._syncCtx = null;\n\t\t\tthis._resetDepState();\n\t\t\t// A fresh restored graph has no subscribers before return. Keep activation closed so the\n\t\t\t// first real subscriber wires deps normally; D94's preserved lifecycle bit is the first-run\n\t\t\t// gate (`hasCalledFnOnce`), not a hidden subscription graph.\n\t\t\tthis._lifecycle.activated = false;\n\t\t\tthis._lifecycle.subscribers.clear();\n\t\t\tthis._restoredActivationPending = true;\n\t\t});\n\t\truntimeReleasers.set(this as Node<unknown>, () => this._releaseRuntime());\n\t\truntimeQuiescenceReaders.set(this as Node<unknown>, () => this._isRuntimeQuiescentForRelease());\n\t\tsubscriberCountReaders.set(this as Node<unknown>, () => this._subscriberCount());\n\t\tactivationReaders.set(this as Node<unknown>, () => this._lifecycle.activated);\n\t}\n\n\t/** R-pull (D55/D272): true while a pull node is not serving a PULL demand pulse. */\n\tprivate _isPullQuiet(): boolean {\n\t\treturn this._slot.pull && this._control.activePull === undefined;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): this pull node's pullId (pure data, like {@link cache}/{@link handle} —\n\t * never triggers computation). A consumer demands one delivery by cone-routing PULL of it (no\n\t * node reference): `ctx.up([[\"PULL\", { pullId }]])` (immediate; loops back → D37 for a self-read\n\t * dep) or `ctx.upNext([[\"PULL\", { pullId }]])` (boundary-deferred self-demand). Undefined for a\n\t * non-pull node. The author writes the pullId verbatim; routing matches by identity.\n\t */\n\tget pullId(): LockId | undefined {\n\t\treturn this._slot.pullLock;\n\t}\n\n\tget cache(): T | undefined {\n\t\treturn this._value.cache;\n\t}\n\n\tget status(): Status {\n\t\treturn this._value.status;\n\t}\n\n\tget version(): NodeVersion | undefined {\n\t\treturn cloneNodeVersion(this._version.value);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._slot.name;\n\t}\n\n\t/** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */\n\tget factory(): string | undefined {\n\t\treturn this._slot.factory;\n\t}\n\n\t/**\n\t * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the\n\t * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a\n\t * construction-time snapshot) so every edge corresponds to a real current subscription (D3).\n\t * Inspection-only, like cache/status; never triggers computation.\n\t */\n\tget deps(): readonly Node<unknown>[] {\n\t\treturn this._slot.deps;\n\t}\n\n\t/**\n\t * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough\n\t * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph\n\t * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node\n\t * (R-node-thin / D39).\n\t */\n\tget handle(): Handle | null {\n\t\treturn this._slot.handle;\n\t}\n\n\t/** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */\n\tsubscribe(sink: Sink): () => void {\n\t\tthis._assertNotReleased(\"subscribe\");\n\t\t// Wave-owner boundary (R-rewire-deferred / D47): the activation cascade can run fns that\n\t\t// issue ctx.rewireNext; the OUTERMOST exit drains them. Nested subscribes (dep wiring)\n\t\t// just inc/dec the depth.\n\t\tenterWave();\n\t\ttry {\n\t\t\t// R-terminal: late subscribe to a terminal node either resets (resubscribable)\n\t\t\t// or is rejected (non-resubscribable, R2.2.7.b).\n\t\t\tif (this._value.terminal !== undefined) {\n\t\t\t\tif (this._slot.resubscribable) {\n\t\t\t\t\tthis._restoredActivationPending = false;\n\t\t\t\t\tthis._resetLifecycle();\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)\",\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis._lifecycle.subscribers.add(sink);\n\t\t\tsink([\"START\"]);\n\t\t\tif (this._slot.replayN > 0 && this._value.replayRing.length > 0) {\n\t\t\t\t// R-replay-buffer: late subscriber gets the last N DATA after START.\n\t\t\t\tfor (const v of this._value.replayRing) sink([\"DATA\", v]);\n\t\t\t} else if (this._value.hasData && !this._slot.pull) {\n\t\t\t\t// R-pull (D55): a pull node NEVER push-on-subscribes its cached value — quiet by\n\t\t\t\t// default, it stays silent until demanded (START only). QA-B4: gated on `_pull`, not\n\t\t\t\t// activePull, so a REACTIVATED pull node still does not leak its cache.\n\t\t\t\tsink([\"DATA\", this._value.cache]);\n\t\t\t} else if (this._value.status === \"dirty\" && !this._slot.pull) {\n\t\t\t\tsink([\"DIRTY\"]);\n\t\t\t}\n\n\t\t\tif (!this._lifecycle.activated) this._activate();\n\n\t\t\treturn () => {\n\t\t\t\tif (!this._lifecycle.subscribers.delete(sink)) return;\n\t\t\t\tif (this._lifecycle.subscribers.size === 0) this._deactivate();\n\t\t\t};\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */\n\tdown(msgs: Wave): void {\n\t\tthis._assertNotReleased(\"down\");\n\t\t// Wave-owner boundary (D47): a state.set / external push that drives a fn issuing\n\t\t// ctx.rewireNext drains at this outermost exit.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._down(msgs);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up\n\t * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t */\n\tup(msgs: Wave, towardDep?: number): void {\n\t\tthis._assertNotReleased(\"up\");\n\t\t// Wave-owner boundary (D47). Internal dep-forwarding calls dep.up() nest under this.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._up(msgs, towardDep);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t// ── deferred self-rewire (R-rewire-deferred / D47): ctx.rewireNext drain support ──\n\n\t/**\n\t * Enqueue a deferred self-rewire op (issued from this node's fn via `ctx.rewireNext`).\n\t * Applied at the committed wave boundary (boundary.ts drain), never in place — the in-fn\n\t * immediate path (`subscribeDep`/`replaceDeps`/`unsubscribeDep`) still throws mid-run (D37/R-reentrancy).\n\t */\n\tprivate _requestRewireNext(op: RewireOp): void {\n\t\tdeferRewire(this._core, () => this._applyRewireNext(op), {\n\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n\n\t/**\n\t * Enqueue a deferred up-going control/demand wave (R-up-routing / R-pull / D269): at the committed wave\n\t * boundary, route `msgs` up from THIS node (broadcast, or up the single `towardDep` edge). The\n\t * deferred form of `ctx.up` — the SELF-demand path: a consumer issues `ctx.upNext([[PULL,\n\t * { pullId }]])` to demand a dep it ALSO reads; the demand applies at the boundary (not mid-fn), so\n\t * the pull node's delivery loops back as a FRESH wave rather than re-entering the consumer (D37 /\n\t * R-reentrancy). Rides the same R-rewire-deferred (D47) drain as ctx.rewireNext.\n\t */\n\tprivate _requestUpNext(msgs: Wave, towardDep?: number): void {\n\t\tdeferRewire(\n\t\t\tthis._core,\n\t\t\t() => {\n\t\t\t\tif (!this._released) this._up(msgs, towardDep);\n\t\t\t},\n\t\t\t{\n\t\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Apply one queued self-rewire at the boundary (drain thunk). */\n\tprivate _applyRewireNext(op: RewireOp): void {\n\t\tif (this._released) return;\n\t\ttry {\n\t\t\t// D62 / R-rewire-deferred: terminal seals output but does NOT cancel queued topology.\n\t\t\t// Public/immediate rewire of a terminal node still rejects; the exception is only for\n\t\t\t// self-triggered ops already issued before terminal and now draining at the boundary.\n\t\t\tif (op.kind === \"add\") {\n\t\t\t\tconst next = this._slot.deps.includes(op.dep)\n\t\t\t\t\t? [...this._slot.deps]\n\t\t\t\t\t: [...this._slot.deps, op.dep];\n\t\t\t\tthis._rewire(next, op.fn, { allowTerminalOwner: true });\n\t\t\t} else if (op.kind === \"remove\") {\n\t\t\t\tthis._rewire(\n\t\t\t\t\tthis._slot.deps.filter((d) => d !== op.dep),\n\t\t\t\t\top.fn,\n\t\t\t\t\t{ allowTerminalOwner: true },\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis._rewire(this._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// An invalid deferred op (cycle / self / non-resubscribable terminal dep) surfaces as\n\t\t\t// an ERROR on this node (D30-consistent) rather than stranding the rest of the drain\n\t\t\t// queue. Reachable only on misuse — higher-order operator inners are fresh, acyclic\n\t\t\t// leaf sources. Coerce a SENTINEL reason (a rewire fn that `throw undefined`s) to a real\n\t\t\t// Error so _down's R-data-payload guard does not itself throw out of the drain.\n\t\t\tthis._down([[\"ERROR\", errorPayload(e, \"rewireNext op failed\")]]);\n\t\t}\n\t}\n\n\t// ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──\n\n\t/**\n\t * Replace this node's deps atomically (surgical, Option-C). Requires an explicit\n\t * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps\n\t * keep their subscription + per-dep state; only removed deps unsubscribe and only\n\t * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The\n\t * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).\n\t */\n\treplaceDeps(newDeps: Node<unknown>[], fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"replaceDeps\");\n\t\tthis._rewire(this._dedupDeps(newDeps), fn);\n\t}\n\n\t/** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */\n\tsubscribeDep(depNode: Node<unknown>, fn: NodeFn): number {\n\t\tthis._assertNotReleased(\"subscribeDep\");\n\t\tconst next = this._slot.deps.includes(depNode)\n\t\t\t? [...this._slot.deps]\n\t\t\t: [...this._slot.deps, depNode];\n\t\tconst deferred = this._rewire(next, fn);\n\t\treturn deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);\n\t}\n\n\t/** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */\n\tunsubscribeDep(depNode: Node<unknown>, fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"unsubscribeDep\");\n\t\tthis._rewire(\n\t\t\tthis._slot.deps.filter((d) => d !== depNode),\n\t\t\tfn,\n\t\t);\n\t}\n\n\tprivate _dedupDeps(deps: Node<unknown>[]): Node<unknown>[] {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst out: Node<unknown>[] = [];\n\t\tfor (const d of deps)\n\t\t\tif (!seen.has(d)) {\n\t\t\t\tseen.add(d);\n\t\t\t\tout.push(d);\n\t\t\t}\n\t\treturn out;\n\t}\n\n\t/** Is `target` reachable upstream from `from` (following deps)? Cycle-prevention DFS. */\n\tprivate _reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst stack: Node<unknown>[] = [from];\n\t\twhile (stack.length > 0) {\n\t\t\tconst n = stack.pop();\n\t\t\tif (n === undefined) continue;\n\t\t\tif (n === target) return true;\n\t\t\tif (seen.has(n)) continue;\n\t\t\tseen.add(n);\n\t\t\tfor (const d of n._slot.deps) stack.push(d);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _assertRewireDepOwner(dep: Node<unknown>): void {\n\t\tconst selfOwner = getNodeOwner(this as unknown as Node<unknown>);\n\t\tconst depOwner = getNodeOwner(dep);\n\t\tif (selfOwner !== undefined && depOwner !== undefined && selfOwner !== depOwner) {\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _rewire(\n\t\tnewDeps: Node<unknown>[],\n\t\tfn: NodeFn,\n\t\topts: { allowTerminalOwner?: boolean } = {},\n\t): boolean {\n\t\t// ── rejects (R-rewire / D42) ──\n\t\tif (this._value.terminal !== undefined && !opts.allowTerminalOwner)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: node is terminal (completed/errored) — cannot rewire (R-rewire / D42)\",\n\t\t\t);\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: mid-fn topology mutation — a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)\",\n\t\t\t);\n\t\tif (this._wave.inDepMutation)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: reentrant dep mutation — another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)\",\n\t\t\t);\n\t\tif (newDeps.includes(this as unknown as Node<unknown>))\n\t\t\tthrow new Error(\"rewire: self-dependency rejected (R-rewire / D42)\");\n\t\tconst oldDeps = this._slot.deps;\n\t\tconst added = newDeps.filter((d) => !oldDeps.includes(d));\n\t\tfor (const d of added) {\n\t\t\tif (this._reachableUpstream(d, this as unknown as Node<unknown>))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: would create a cycle — dep already transitively depends on this node (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tif (d._value.terminal !== undefined && !d._slot.resubscribable)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: cannot add a non-resubscribable terminal dep — would wedge (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tthis._assertRewireDepOwner(d);\n\t\t}\n\n\t\tif (\n\t\t\tdeferAfterBatchForTarget(this, () => {\n\t\t\t\tthis._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });\n\t\t\t})\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!this._lifecycle.activated) this._restoredActivationPending = false;\n\n\t\tthis._wave.inDepMutation = true;\n\t\tthis._wave.rewireRunPending = false;\n\t\tlet zeroDepUnDirty = false;\n\t\ttry {\n\t\t\t// fn swap (SD-1): re-register against the same pool, then release the old handle\n\t\t\t// (B15) so the rewired-away fn closure is GC'd and its dispatcher slot is reused —\n\t\t\t// a rewire-heavy graph (CSP-2.7 *Map) no longer leaks a handle per swap. Register\n\t\t\t// first, then unregister the old: this._slot.handle never points at a freed slot, and a\n\t\t\t// null old handle (a passthrough/state node gaining a fn) has nothing to free.\n\t\t\tconst oldHandle = this._slot.handle;\n\t\t\tthis._slot.handle = this._slot.dispatcher.register(fn, this._slot.pool);\n\t\t\tif (oldHandle !== null) this._slot.dispatcher.unregister(oldHandle);\n\n\t\t\tconst removed = oldDeps.filter((d) => !newDeps.includes(d));\n\t\t\tlet removedDirtyContributor = false;\n\t\t\tfor (const d of removed) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(d);\n\t\t\t\tif (this._dep.dirty[oldIdx]) {\n\t\t\t\t\tremovedDirtyContributor = true;\n\t\t\t\t\tthis._wave.pending--;\n\t\t\t\t}\n\t\t\t\tif (this._lifecycle.activated) {\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = -1; // drain: any stale in-flight callback drops\n\t\t\t\t\tconst unsub = this._dep.unsubs[oldIdx];\n\t\t\t\t\tif (unsub) unsub(); // stops the removed dep's edge — no further delivery\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rebuild per-dep parallel arrays in newDeps order; kept deps carry their state\n\t\t\t// + subscription, added deps start fresh (R-rewire Q1/Q4).\n\t\t\tconst n = newDeps.length;\n\t\t\tconst newBatch: Array<unknown[] | null> = new Array(n).fill(null);\n\t\t\tconst newPrev: unknown[] = new Array(n).fill(SENTINEL);\n\t\t\tconst newHasData: boolean[] = new Array(n).fill(false);\n\t\t\tconst newDirty: boolean[] = new Array(n).fill(false);\n\t\t\tconst newTier: number[] = new Array(n).fill(0);\n\t\t\tconst newTerminal: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newTerminalInput: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newUnsubs: Array<() => void> = new Array(n);\n\t\t\tconst newBoxes: Array<{ v: number }> = new Array(n);\n\t\t\tfor (let j = 0; j < n; j++) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(newDeps[j]);\n\t\t\t\tif (oldIdx !== -1) {\n\t\t\t\t\tnewBatch[j] = this._dep.batch[oldIdx];\n\t\t\t\t\tnewPrev[j] = this._dep.prev[oldIdx];\n\t\t\t\t\tnewHasData[j] = this._dep.hasData[oldIdx];\n\t\t\t\t\tnewDirty[j] = this._dep.dirty[oldIdx];\n\t\t\t\t\tnewTier[j] = this._dep.tier[oldIdx];\n\t\t\t\t\tnewTerminal[j] = this._dep.terminal[oldIdx];\n\t\t\t\t\tnewUnsubs[j] = this._dep.unsubs[oldIdx];\n\t\t\t\t\t// carry the kept dep's subscription box and point it at the new index (O(1) reroute)\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = j;\n\t\t\t\t\tnewBoxes[j] = box;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._slot.deps = newDeps;\n\t\t\tthis._dep.batch = newBatch;\n\t\t\tthis._dep.prev = newPrev;\n\t\t\tthis._dep.hasData = newHasData;\n\t\t\tthis._dep.dirty = newDirty;\n\t\t\tthis._dep.tier = newTier;\n\t\t\tthis._dep.terminal = newTerminal;\n\t\t\tthis._dep.terminalInput = newTerminalInput;\n\t\t\tthis._dep.unsubs = newUnsubs;\n\t\t\tthis._dep.idxBoxes = newBoxes;\n\t\t\tthis._dep.waveData = newDeps.map(() => []);\n\t\t\tthis._dep.waveTokens = new Array(newDeps.length).fill(undefined);\n\t\t\tthis._syncCtx = null;\n\n\t\t\t// Subscribe added deps — push-on-subscribe (R-push-subscribe) delivers a cached\n\t\t\t// dep's DATA here, which drives _maybeRun; a SENTINEL dep delivers START only.\n\t\t\tif (this._lifecycle.activated) {\n\t\t\t\tfor (const d of added) this._subscribeDepAt(d);\n\t\t\t}\n\t\t\tnotifyTopologyDepsChanged(this as unknown as Node<unknown>, oldDeps, newDeps);\n\n\t\t\t// Q6 auto-settle: removing the sole dirty contributor closes the wave. With deps\n\t\t\t// remaining, request the atomic settle (recompute → DATA for a value; a no-emit fn\n\t\t\t// gets a substrate-synthesized undirty RESOLVED per R-resolved-undirty/D49 — NOT\n\t\t\t// equals-absorption, which is gone). With zero deps the node is inert (degenerate\n\t\t\t// fn-no-deps) — just un-dirty downstream. Cache is preserved either way (Q7).\n\t\t\tif (removedDirtyContributor && this._wave.pending === 0 && this._value.status === \"dirty\") {\n\t\t\t\tif (newDeps.length > 0) this._wave.rewireRunPending = true;\n\t\t\t\telse zeroDepUnDirty = true;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._wave.inDepMutation = false;\n\t\t}\n\n\t\t// Atomic post-mutation settle (outside the reentrancy guard so a fresh wave runs\n\t\t// normally): ONE two-phase DIRTY→DATA recompute if any added dep delivered data or a\n\t\t// sole-dirty dep was removed; else the zero-dep un-dirty via _down (pause/batch-safe).\n\t\tif (this._wave.rewireRunPending) {\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._settleRewire();\n\t\t} else if (zeroDepUnDirty) {\n\t\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t\t\telse this._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\treturn false;\n\t}\n\n\t// ── activation / deactivation (lazy; R-rom-ram) ──\n\n\tprivate _activate(): void {\n\t\tthis._lifecycle.activated = true;\n\t\tconst seedRestoredDeps = this._restoredActivationPending;\n\t\tthis._restoredActivationPending = false;\n\t\t// R-pull (D55/D272): activePull is undefined before wiring deps, so each dep's\n\t\t// push-on-subscribe DIRTY/DATA is absorbed quietly, not relayed downstream.\n\t\tthis._dep.unsubs = new Array(this._slot.deps.length);\n\t\tthis._dep.idxBoxes = new Array(this._slot.deps.length);\n\t\tfor (const dep of this._slot.deps)\n\t\t\tthis._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });\n\t\t// Depless producer (fn, no deps): run once on activation.\n\t\tif (this._slot.deps.length === 0 && this._slot.handle !== null && !this._wave.hasCalledFnOnce) {\n\t\t\tthis._runWave();\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to a dep. The dispatch callback reads the dep's CURRENT index from a\n\t * mutable box (O(1)); a surgical rewire that reorders kept deps just updates the box\n\t * (R-rewire Option-C / D42) — no re-subscribe, no per-message indexOf scan. A removed\n\t * dep's box is set to -1 so any stale in-flight callback drops (drain).\n\t */\n\tprivate _subscribeDepAt(depNode: Node<unknown>, opts: { seedRestored?: boolean } = {}): void {\n\t\tconst idx0 = this._slot.deps.indexOf(depNode);\n\t\tconst box = { v: idx0 };\n\t\tlet ignoreInitialPush = opts.seedRestored === true;\n\t\tif (ignoreInitialPush && idx0 !== -1) {\n\t\t\tthis._seedRestoredDepAt(idx0, depNode);\n\t\t\tif (depNode._value.terminal !== undefined && !depNode._slot.resubscribable) {\n\t\t\t\tthis._dep.unsubs[idx0] = () => {};\n\t\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst unsub = depNode.subscribe((msg, delivery) => {\n\t\t\tif (ignoreInitialPush && delivery === undefined) return;\n\t\t\tif (ignoreInitialPush) ignoreInitialPush = false;\n\t\t\tif (box.v === -1) return; // dep removed — stale callback, drop (drain)\n\t\t\tthis._receiveFromDep(box.v, msg, delivery);\n\t\t});\n\t\tif (ignoreInitialPush && idx0 !== -1 && box.v !== -1) this._seedRestoredDepAt(idx0, depNode);\n\t\tignoreInitialPush = false;\n\t\tif (idx0 !== -1) {\n\t\t\tthis._dep.unsubs[idx0] = unsub;\n\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t}\n\t}\n\n\tprivate _seedRestoredDepAt(idx: number, depNode: Node<unknown>): void {\n\t\tconst seedData = depNode._value.hasData && !depNode._slot.pull;\n\t\tthis._dep.batch[idx] = null;\n\t\tthis._dep.waveData[idx] = [];\n\t\tthis._dep.waveTokens[idx] = undefined;\n\t\tthis._dep.prev[idx] = seedData ? depNode._value.cache : SENTINEL;\n\t\tthis._dep.hasData[idx] = seedData;\n\t\tthis._dep.dirty[idx] = false;\n\t\tthis._dep.tier[idx] = seedData ? 3 : 0;\n\t\tthis._dep.terminal[idx] = depNode._value.terminal;\n\t\tthis._dep.terminalInput[idx] = undefined;\n\t}\n\n\tprivate _deactivate(): void {\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tfor (const fn of this._hooks.onDeactivation) fn();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\t// RAM: compute nodes clear cache; reconnect re-runs fn fresh.\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t}\n\t\tthis._resetDepState();\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._value.replayRing = []; // BH6: don't replay stale values to a post-reactivation subscriber\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _assertNotReleased(op: string): void {\n\t\tif (this._released)\n\t\t\tthrow new Error(`${op}: node has been released from its graph lifecycle (D122)`);\n\t}\n\n\tprivate _subscriberCount(): number {\n\t\treturn this._lifecycle.subscribers.size;\n\t}\n\n\tprivate _isRuntimeQuiescentForRelease(): boolean {\n\t\treturn (\n\t\t\t!this._released &&\n\t\t\tthis._value.status !== \"dirty\" &&\n\t\t\tthis._value.status !== \"pending\" &&\n\t\t\tthis._wave.pending === 0 &&\n\t\t\t!this._wave.insideRunWave &&\n\t\t\t!this._wave.inDepMutation &&\n\t\t\t!this._wave.rewireRunPending &&\n\t\t\t!this._wave.batchDirtyOwed &&\n\t\t\tthis._dep.dirty.every((dirty) => !dirty) &&\n\t\t\tthis._control.pauseBuffer.length === 0 &&\n\t\t\t!this._control.pausedDepWaveOccurred &&\n\t\t\tthis._control.demandOwed === undefined &&\n\t\t\tthis._control.activePull === undefined &&\n\t\t\t!this._control.inDeliverDemand &&\n\t\t\tthis._control.pauseLockset.size === 0\n\t\t);\n\t}\n\n\tprivate _releaseRuntime(): void {\n\t\tif (this._released) return;\n\t\tthis._released = true;\n\t\treleasedNodes.add(this as Node<unknown>);\n\t\tlet releaseError: unknown;\n\t\tconst recordReleaseError = (error: unknown): void => {\n\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t};\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) {\n\t\t\ttry {\n\t\t\t\tu();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release is graph-owned and atomic; user cleanup must not split commit.\n\t\t\t}\n\t\t}\n\t\tfor (const fn of this._hooks.onDeactivation) {\n\t\t\ttry {\n\t\t\t\tfn();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release cleans runtime without synthesizing protocol ERROR/COMPLETE.\n\t\t\t}\n\t\t}\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tif (this._slot.handle !== null) {\n\t\t\tthis._slot.dispatcher.unregister(this._slot.handle);\n\t\t\tthis._slot.handle = null;\n\t\t}\n\t\tthis._slot.deps = [];\n\t\tthis._dep.batch = [];\n\t\tthis._dep.waveData = [];\n\t\tthis._dep.waveTokens = [];\n\t\tthis._dep.prev = [];\n\t\tthis._dep.hasData = [];\n\t\tthis._dep.dirty = [];\n\t\tthis._dep.tier = [];\n\t\tthis._dep.terminal = [];\n\t\tthis._dep.terminalInput = [];\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.replayRing = [];\n\t\tthis._privateState.value = SENTINEL;\n\t\tthis._privateState.persist = false;\n\t\tthis._syncCtx = null;\n\t\tthis._resetDepState();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined;\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._restoredActivationPending = false;\n\t\tcheckpointReaders.delete(this as Node<unknown>);\n\t\trestoreWriters.delete(this as Node<unknown>);\n\t\truntimeReleasers.delete(this as Node<unknown>);\n\t\truntimeQuiescenceReaders.delete(this as Node<unknown>);\n\t\tsubscriberCountReaders.delete(this as Node<unknown>);\n\t\tactivationReaders.delete(this as Node<unknown>);\n\t\townerTokens.delete(this as Node<unknown>);\n\t\ttopologyDepsChangedObservers.delete(this as Node<unknown>);\n\t\tthis._core.releaseSlot(this._id);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\tprivate _resetDepState(): void {\n\t\tconst n = this._slot.deps.length;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.prev[i] = SENTINEL;\n\t\t\tthis._dep.hasData[i] = false;\n\t\t\tthis._dep.dirty[i] = false;\n\t\t\tthis._dep.tier[i] = 0;\n\t\t\tthis._dep.terminal[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.pending = 0;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── upstream wave receive (two-phase + diamond) ──\n\n\tprivate _recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[] {\n\t\tconst token = delivery?.wave ?? {};\n\t\tif (this._dep.waveTokens[idx] !== token) {\n\t\t\tthis._dep.waveData[idx].push([]);\n\t\t\tthis._dep.waveTokens[idx] = token;\n\t\t}\n\t\treturn this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t}\n\n\tprivate _depProjectionHasData(idx: number): boolean {\n\t\tconst projection = this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t\treturn projection?.some((v) => v !== SENTINEL) ?? false;\n\t}\n\n\tprivate _receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\tconst t = msg[0];\n\t\tif (t === \"START\") return;\n\t\tconst isLastInDeliveredWave = delivery?.last ?? true;\n\t\t// Terminal-is-forever, except terminal intermediates still relay upstream TEARDOWN\n\t\t// downstream for lifecycle unwire (R-teardown-terminal-relay / D65).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (t === \"TEARDOWN\") this._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"INVALIDATE\") {\n\t\t\tconst projection = this._recordDepProjection(idx, delivery);\n\t\t\tprojection.push(SENTINEL);\n\t\t\tif (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) this._maybeRun();\n\t\t\t// The dep's value is gone — drop our cached latest view to SENTINEL so the\n\t\t\t// never-emitted detector reads correctly, C-3) and cascade (idempotent).\n\t\t\tthis._dep.prev[idx] = SENTINEL;\n\t\t\tthis._dep.hasData[idx] = false;\n\t\t\tthis._dep.batch[idx] = null;\n\t\t\t// EC3: un-wedge the dirty bookkeeping if this dep had gone DIRTY first, so an\n\t\t\t// INVALIDATE-before-DATA doesn't strand _pending / downstream forever\n\t\t\t// (R-invalidate-idempotent — exists to prevent the wedged-DIRTY deadlock).\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\t// D50 / R-paused-invalidate: this INVALIDATE SUPERSEDES the dep's buffered\n\t\t\t// paused dep-wave (_depBatch[idx] just cleared). Re-derive the paused-recompute\n\t\t\t// flag — if no dep still carries a buffered DATA, CANCEL the paused recompute\n\t\t\t// (attributed cancellation; the node has settled to SENTINEL via its own\n\t\t\t// INVALIDATE, so a RESUME must not recompute against a now-SENTINEL dep). A\n\t\t\t// surviving dep keeps it set; a later DATA re-arms it ([DATA,INVALIDATE,DATA2]).\n\t\t\tif (this._control.pausedDepWaveOccurred && this._dep.batch.every((b) => b === null)) {\n\t\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\t}\n\t\t\tconst hadData = this._value.hasData;\n\t\t\tthis._invalidate(); // cascades INVALIDATE iff populated; no-op otherwise\n\t\t\t// If we broadcast DIRTY this wave but _invalidate produced no settle (the node\n\t\t\t// was never populated, so the cascade is suppressed per the rule), un-dirty\n\t\t\t// downstream with a RESOLVED once all deps have settled.\n\t\t\tif (this._wave.pending === 0 && this._wave.emittedDirtyThisWave) {\n\t\t\t\tif (!hadData) this._down([[\"RESOLVED\"]]);\n\t\t\t\telse this._wave.emittedDirtyThisWave = false;\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): an INVALIDATE settle can drain _pending → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (isTerminal(t)) {\n\t\t\t// Tier 5 (R-tier / D34): COMPLETE | ERROR — ONE branch routed by the CENTRAL tier table,\n\t\t\t// not a per-variant string check (feedback_use_tier_for_signal_routing). The shared terminal\n\t\t\t// bookkeeping (record the terminal + release the in-wave DIRTY) runs for ANY tier-5 message;\n\t\t\t// only the COMPLETE-vs-ERROR cascade differs, so discriminate by the type within the tier.\n\t\t\tconst isError = t === \"ERROR\";\n\t\t\tconst errPayload = isError ? (msg as readonly [\"ERROR\", unknown])[1] : undefined;\n\t\t\tthis._dep.terminal[idx] = isError ? errPayload : true;\n\t\t\tthis._dep.terminalInput[idx] = isError ? errPayload : true;\n\t\t\t// R-terminal-settles-dirty (B35): a terminal RELEASES this dep's outstanding in-wave DIRTY\n\t\t\t// contribution (the exactly-one-settle invariant) — exactly as DATA/RESOLVED/INVALIDATE do\n\t\t\t// (a dirty-then-terminal-without-DATA dep would otherwise strand _pending and wedge the node,\n\t\t\t// the deadlock R-invalidate-idempotent prevents for INVALIDATE).\n\t\t\tthis._releaseDepDirty(idx);\n\t\t\tconst ranValueBeforeTerminal = this._depProjectionHasData(idx) && isLastInDeliveredWave;\n\t\t\tif (ranValueBeforeTerminal) this._maybeRun();\n\t\t\tif (isError && this._slot.errorWhenDepsError) {\n\t\t\t\tthis._down([[\"ERROR\", errPayload]]); // auto-cascade ERROR → node itself terminal\n\t\t\t} else if (this._slot.terminalAsRealInput) {\n\t\t\t\tif (ranValueBeforeTerminal) {\n\t\t\t\t\tthis._fireOwedDemandIfReady();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis._maybeRun(); // rescue/reduce/catch/*Map: the fn reads depTerminal(ctx, idx)\n\t\t\t} else if (this._slot.completeWhenDepsComplete && this._allDepsTerminal()) {\n\t\t\t\t// R-deps-terminal auto-COMPLETE + B42: COMPLETE once ALL deps are TERMINAL (each COMPLETE\n\t\t\t\t// or an absorbed ERROR) — so an absorbed-error dep terminating LAST still fires the\n\t\t\t\t// cascade. terminalAsRealInput is checked FIRST so a rescue recovers via _maybeRun rather\n\t\t\t\t// than being preempted (no operator sets both completeWhenDepsComplete:true + tari:true).\n\t\t\t\tthis._down([[\"COMPLETE\"]]);\n\t\t\t} else {\n\t\t\t\t// absorbed terminal, NOT an input + not auto-completing: the dep's signalled change did\n\t\t\t\t// not materialise (no DATA) → un-dirty downstream, keep cache (R-resolved-undirty balance).\n\t\t\t\tthis._settleAfterAbsorbedTerminal();\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): a dep terminal can drain _pending → fire a deferred demand (no-op if this node went terminal)\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"TEARDOWN\") {\n\t\t\tthis._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DIRTY\") {\n\t\t\tif (!this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = true;\n\t\t\t\tthis._wave.pending++;\n\t\t\t\tthis._dep.tier[idx] = 2;\n\t\t\t\tthis._markDirty();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DATA\") {\n\t\t\tconst v = msg[1];\n\t\t\tthis._recordDepProjection(idx, delivery).push(v);\n\t\t\tconst b = this._dep.batch[idx];\n\t\t\tif (b === null) this._dep.batch[idx] = [v];\n\t\t\telse b.push(v);\n\t\t\tthis._dep.prev[idx] = v;\n\t\t\tthis._dep.hasData[idx] = true;\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"RESOLVED\") {\n\t\t\tthis._recordDepProjection(idx, delivery);\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\t\t// PAUSE / RESUME are not delivered downstream to a dep-subscriber; a node is\n\t\t// paused via its own up() (lockset), not by an upstream dep.\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): release a dep's outstanding in-wave DIRTY contribution.\n\t * A settle-class event for that dep (DATA/RESOLVED inline above, INVALIDATE, and now\n\t * COMPLETE/ERROR) clears its dirty flag + decrements _pending. No-op if the dep already\n\t * settled this wave (DATA/RESOLVED ran first) — so the normal DATA-then-COMPLETE flow is\n\t * unaffected. This makes the exactly-one-settle invariant a single, shared step.\n\t */\n\tprivate _releaseDepDirty(idx: number): void {\n\t\tif (this._dep.dirty[idx]) {\n\t\t\tthis._dep.dirty[idx] = false;\n\t\t\tthis._wave.pending--;\n\t\t}\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): settle a node whose dirtied dep was released by an ABSORBED\n\t * terminal that is NOT a real input (a plain derived/effect — the common default-node case when\n\t * one of several deps completes while others stay live). Runs only when the release drained\n\t * _pending while the node still owes a downstream settle (it broadcast DIRTY this wave):\n\t * - if some OTHER dep delivered real DATA this wave (a value occurred) → recompute (→ DATA);\n\t * - else the terminal's signalled change did not materialise (no value) → one undirty RESOLVED\n\t * (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t * A terminalAsRealInput node instead recomputes unconditionally (its fn reads the terminal).\n\t */\n\tprivate _settleAfterAbsorbedTerminal(): void {\n\t\tif (this._wave.pending !== 0 || !this._wave.emittedDirtyThisWave) return;\n\t\t// A real value occurred this wave (some OTHER dep delivered DATA) → recompute. _maybeRun\n\t\t// runs the fn ONLY if it's not gated (first-run gate open, not paused); it may emit DATA, a\n\t\t// fn-synthesized undirty RESOLVED, or nothing (gated / gate still holds).\n\t\tconst sawData = this._dep.batch.some((b) => b !== null && b.length > 0);\n\t\tif (sawData) this._maybeRun();\n\t\t// If after that the node STILL owes a downstream settle (no DATA occurred, OR the recompute\n\t\t// was gated — e.g. the first-run gate holds because the terminated dep never delivered and\n\t\t// terminalAsRealInput is false), balance the broadcast DIRTY with one undirty RESOLVED\n\t\t// (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t\t// Without this fallback a DIRTY-then-terminal-without-DATA dep on a pre-first-run multi-dep\n\t\t// node would strand the DIRTY → downstream wedged (the B35 class, in the gate-holds corner).\n\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t}\n\n\tprivate _markDirty(): void {\n\t\tthis._value.status = \"dirty\";\n\t\t// SPIKE (protocol-pull): while quiet, ABSORB the upstream DIRTY — do NOT relay it downstream.\n\t\t// This is the P0b wedge fix: a quiet pull node that relayed DIRTY but withheld the settle\n\t\t// (coalesced by pause) wedged every downstream's two-phase _pending. The downstream learns of\n\t\t// changes via the push STREAM port, not the silent snapshot port; on demand the pull node\n\t\t// emits a fresh wave. Internal dep dirty-accounting (the DIRTY-branch _pending++) is untouched.\n\t\tif (this._isPullQuiet()) return;\n\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._emitToSubs([\"DIRTY\"]);\n\t\t}\n\t}\n\n\tprivate _maybeRun(): void {\n\t\t// R-rewire: an added cached dep's push-on-subscribe lands here mid-mutation. Defer\n\t\t// the fn-run to ONE atomic two-phase settle after every added dep is wired, so the\n\t\t// fn never fires on a partially-populated added-dep view (multi-add) — _settleRewire\n\t\t// drains this flag.\n\t\tif (this._wave.inDepMutation) {\n\t\t\tthis._wave.rewireRunPending = true;\n\t\t\treturn;\n\t\t}\n\t\t// R-pause-modes + R-pull: while externally paused or pull-quiet, default pull mode\n\t\t// coalesces. `resumeAll` still runs so its outgoing settle slice can enter pauseBuffer.\n\t\tif (this._slot.pausable === true && (this._isPaused() || this._isPullQuiet())) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tthis._tryRun();\n\t}\n\n\t/**\n\t * R-rewire atomic settle (after a rewire that warrants a recompute): emit a proper\n\t * two-phase DIRTY→DATA wave (R-dirty-before-data — a rewire-triggered settle is a wave),\n\t * once, with every added dep already wired. Mirrors _maybeRun/_tryRun's pause + gate +\n\t * pending guards, then injects the phase-1 DIRTY the added dep's [START,DATA] handshake\n\t * did not carry.\n\t */\n\tprivate _settleRewire(): void {\n\t\tif (this._slot.pausable === true && this._isPaused()) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;\n\t\tthis._markDirty(); // phase 1 (no-op if already dirty, e.g. unsubscribeDep auto-settle)\n\t\tthis._runWave(); // phase 2: fn → DATA/RESOLVED\n\t}\n\n\tprivate _tryRun(): void {\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\t// Passthrough wire (deps, no fn): forward the latest dep DATA downstream.\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce) {\n\t\t\tif (this._slot.partial || this._allDepsSettled()) this._runWave();\n\t\t\t// else: first-run gate holds fn until every dep has settled (R-first-run-gate).\n\t\t\treturn;\n\t\t}\n\t\tthis._runWave();\n\t}\n\n\tprivate _allDepsSettled(): boolean {\n\t\tfor (let i = 0; i < this._slot.deps.length; i++) {\n\t\t\tif (this._dep.hasData[i]) continue;\n\t\t\tif (this._slot.terminalAsRealInput && this._dep.terminal[i] !== undefined) continue;\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate _passthroughEmit(): void {\n\t\t// Single-dep wire: relay dep 0's latest batch value as DATA.\n\t\tconst b = this._dep.batch[0];\n\t\tif (b !== null && b.length > 0) {\n\t\t\tthis._down([[\"DATA\", b[b.length - 1]]]);\n\t\t} else if (this._wave.emittedDirtyThisWave) {\n\t\t\t// R-resolved-undirty (D49): the dep settled via an undirty RESOLVED (no DATA in the\n\t\t\t// batch), but this wire already broadcast DIRTY downstream this wave — balance it with\n\t\t\t// a RESOLVED so downstream un-dirties instead of wedging. Routed through _down (NOT a\n\t\t\t// bare _emitToSubs) so the balance respects batch-defer (D12) + pause-buffer, matching\n\t\t\t// the zero-dep un-dirty path. Without this, a passthrough over a filter-reject /\n\t\t\t// distinctUntilChanged-dup leaves a dangling DIRTY (the wedge D49 made common).\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\t\tthis._dep.batch[0] = null;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _runWave(): void {\n\t\t// R-reentrancy (D37): a fn that re-drives its own dep mid-wave re-enters here while\n\t\t// _insideRunWave is still set — a synchronous feedback cycle. Reject (throw); the graph\n\t\t// layer catches it and converts to [[ERROR, e]] (D30). The try/finally resets the flag\n\t\t// on every frame as the throw unwinds, leaving the graph clean for the catch. Detection\n\t\t// is node-local and free — it reuses the existing _insideRunWave flag (no new structure,\n\t\t// dispatcher stays a pure funnel).\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)\",\n\t\t\t);\n\t\tthis._wave.hasCalledFnOnce = true;\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification): clear BOTH hook lists\n\t\t// before the fn runs; the fn body re-registers the current run's hooks. Only the\n\t\t// latest run's registrations are live — a re-run supersedes the prior run's hooks,\n\t\t// discarded WITHOUT firing (no fire-on-rerun; onRerun stays cut). Fixes the push-only\n\t\t// accumulation (K stale hooks fired after K runs). C-14.\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._hooks.onDeactivation = [];\n\t\tconst ctx = this._buildCtx();\n\t\tconst wasDirty = this._wave.emittedDirtyThisWave;\n\t\tthis._wave.emittedSettleThisWave = false;\n\t\tthis._wave.insideRunWave = true;\n\t\ttry {\n\t\t\tthis._slot.dispatcher.invoke(this._slot.handle as Handle, ctx);\n\t\t} finally {\n\t\t\tthis._wave.insideRunWave = false;\n\t\t}\n\n\t\t// R-resolved-undirty (D49): a SYNC fn DIRTY'd in phase 1 that produced NO tier-3 value\n\t\t// this wave (filter-reject / distinctUntilChanged-dup / any no-emit fn) gets a substrate-\n\t\t// SYNTHESIZED undirty RESOLVED to clear the downstream dirty — operator bodies stay\n\t\t// protocol-clean (R-primary-api-clean). Status reflects cache freshness: a carried value\n\t\t// -> resolved, never-valued -> sentinel. EXEMPT: terminal/INVALIDATE waves (they set\n\t\t// _emittedSettleThisWave and balance their own dirty), and ASYNC-pool nodes — an async fn\n\t\t// that returns without emitting has DEFERRED its result (it emits later via the stashed\n\t\t// ctx), NOT rejected; synthesizing here would prematurely settle a still-pending diamond\n\t\t// leg (R-async-paused / C-4). The eventual async ctx.down carries its own DIRTY balance.\n\t\tif (\n\t\t\twasDirty &&\n\t\t\t!this._wave.emittedSettleThisWave &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._isAsyncPool()\n\t\t) {\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\n\t\t// roll wave-local state forward\n\t\tfor (let i = 0; i < this._dep.batch.length; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── ctx construction (L3-Q5: sync = node-stable reused ctx; async = per-invocation) ──\n\n\tprivate _buildCtx(): Ctx {\n\t\tconst kind = this._slot.handle\n\t\t\t? this._slot.dispatcher.poolKind(this._slot.handle.poolId)\n\t\t\t: \"sync\";\n\t\tif (kind === \"sync\") {\n\t\t\tif (this._syncCtx === null) this._syncCtx = this._makeCtx();\n\t\t\tthis._refreshCtx(this._syncCtx);\n\t\t\treturn this._syncCtx;\n\t\t}\n\t\t// async: snapshot dep inputs so a deferred late-emit reads this wave's view.\n\t\treturn this._makeCtx({\n\t\t\twaveData: this._dep.waveData.map((waves) => waves.map((w) => [...w])),\n\t\t\tterminal: this._dep.terminalInput.map(terminalView),\n\t\t\tlatest: [...this._dep.prev],\n\t\t});\n\t}\n\n\tprivate _makeCtx(snapshot?: {\n\t\twaveData: unknown[][][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): Ctx {\n\t\tconst ctx: Ctx = {\n\t\t\t// Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove\n\t\t\t// it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed\n\t\t\t// ctx at depth 0, so this is the boundary that drains any rewireNext it issued.\n\t\t\tup: (msgs, towardDep) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._up(msgs, towardDep);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\tdown: (msgs) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._down(msgs);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\twaveData: snapshot?.waveData ?? this._dep.waveData,\n\t\t\tterminal: snapshot?.terminal ?? this._dep.terminalInput.map(terminalView),\n\t\t\tstate: this._makeState(),\n\t\t\tonDeactivation: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onDeactivation.push(fn);\n\t\t\t},\n\t\t\tonInvalidate: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onInvalidate.push(fn);\n\t\t\t},\n\t\t\tenvironment: () => this._slot.environment,\n\t\t\t// R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.\n\t\t\trewireNext: {\n\t\t\t\tsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"add\", dep, fn }),\n\t\t\t\tunsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"remove\", dep, fn }),\n\t\t\t\treplaceDeps: (deps, fn) => this._requestRewireNext({ kind: \"set\", deps, fn }),\n\t\t\t},\n\t\t\t// R-up-routing / R-pull (D269): deferred up — route a control/demand wave (e.g. PULL)\n\t\t\t// up the declared cone at the committed boundary. The SELF-demand path: an\n\t\t\t// immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).\n\t\t\tupNext: (msgs, towardDep) => this._requestUpNext(msgs, towardDep),\n\t\t\t...(this._control.activePull === undefined ? {} : { pull: this._control.activePull }),\n\t\t\t[CTX_DEP_CACHE]: { latest: snapshot?.latest ?? this._dep.prev },\n\t\t\t[CTX_NODE_BINDING]: {\n\t\t\t\tdispatcher: this._slot.dispatcher,\n\t\t\t\tcreate: <U>(factory: () => Node<U>) =>\n\t\t\t\t\twithEnvironmentDrivers(this._slot.environment, () => withNodeCore(this._core, factory)),\n\t\t\t},\n\t\t};\n\t\tif (this._slot.dynamic) {\n\t\t\t// R-dynamic-node: read a dep's latest by index. Untracked deps still drive waves and\n\t\t\t// re-run the fn; under D49 (no equals-substitution) the fn re-emits its current value\n\t\t\t// as DATA — to suppress redundant downstream propagation, pair with distinctUntilChanged.\n\t\t\tctx.track = (i: number) => ctx[CTX_DEP_CACHE]?.latest[i];\n\t\t}\n\t\treturn ctx;\n\t}\n\n\tprivate _refreshCtx(ctx: Ctx): void {\n\t\t(ctx as { waveData: WaveData }).waveData = this._dep.waveData;\n\t\t(ctx as { terminal: TerminalData }).terminal = this._dep.terminalInput.map(terminalView);\n\t\tif (this._control.activePull === undefined) {\n\t\t\tdelete (ctx as { pull?: PullDemand }).pull;\n\t\t} else {\n\t\t\t(ctx as { pull?: PullDemand }).pull = this._control.activePull;\n\t\t}\n\t\tctx[CTX_DEP_CACHE] = { latest: this._dep.prev };\n\t}\n\n\tprivate _makeState(): CtxState {\n\t\treturn {\n\t\t\tget: <S>() => this._privateState.value as S | undefined,\n\t\t\tset: <S>(v: S) => {\n\t\t\t\tthis._privateState.value = v;\n\t\t\t},\n\t\t\tpersist: (on = true) => {\n\t\t\t\tthis._privateState.persist = on;\n\t\t\t},\n\t\t};\n\t}\n\n\t// ── downstream emission pipeline (the unified waist) ──\n\n\tprivate _down(msgs: Wave): void {\n\t\tif (this._released) return;\n\t\tvalidateDownPayloads(msgs);\n\t\tconst deliveryWave = {};\n\t\tconst assertVersionDataCompatible = (wave: readonly Message[]) => {\n\t\t\tfor (const m of wave) {\n\t\t\t\tif (m[0] === \"DATA\") assertNodeVersionDataCompatible(this._version.policy, m[1]);\n\t\t\t}\n\t\t};\n\t\tconst snapshotVersionData = (wave: readonly Message[]): Message[] =>\n\t\t\twave.map((m) =>\n\t\t\t\tm[0] === \"DATA\"\n\t\t\t\t\t? ([\"DATA\", snapshotNodeVersionData(this._version.policy, m[1])] as Message)\n\t\t\t\t\t: m,\n\t\t\t);\n\t\tassertVersionDataCompatible(msgs);\n\t\t// Terminal-is-forever (R-terminal / D17 / B30): once COMPLETE/ERROR has been emitted the\n\t\t// node is final — a self-emit (state.set / ctx.down) in a LATER wave is a no-op, never\n\t\t// resurrecting the cache or re-emitting. The COMPLETE/ERROR arms below also self-guard\n\t\t// against a double terminal, but DATA/RESOLVED/INVALIDATE had no entry guard, so a\n\t\t// post-terminal set() would overwrite cache + emit DATA. R-teardown-terminal-relay / D65\n\t\t// carves out the only post-terminal exception: TEARDOWN still relays downstream for unwire\n\t\t// without reopening value output. A single wave that goes terminal mid-loop (e.g.\n\t\t// [COMPLETE, TEARDOWN]) is unaffected: _terminal is still undefined at entry.\n\t\t// Resubscribable reset clears _terminal before any re-emit.\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (!msgs.some((m) => m[0] === \"TEARDOWN\")) return;\n\t\t\tthis._value.hasTorndown = true;\n\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\tthis._value.hasData = false;\n\t\t\t}\n\t\t\tthis._emitToSubs([\"TEARDOWN\"], { wave: deliveryWave, last: true });\n\t\t\treturn;\n\t\t}\n\t\tlet sorted: Message[] = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));\n\t\t// R-same-wave-merge: collapse repeated INVALIDATE in one wave (Q9) so the\n\t\t// cleanup hook + downstream broadcast fire at most once.\n\t\tconst firstInvalidate = sorted.findIndex((m) => m[0] === \"INVALIDATE\");\n\t\tif (firstInvalidate !== -1) {\n\t\t\tsorted = sorted.filter((m, i) => m[0] !== \"INVALIDATE\" || i === firstInvalidate);\n\t\t}\n\t\t// R-teardown-complete: a TEARDOWN reaching a non-terminal node synthesizes a\n\t\t// COMPLETE prefix (so firstValueFrom-style bridges resolve), unless the wave\n\t\t// already carries a terminal or the node already tore down.\n\t\tconst hasTeardown = sorted.some((m) => m[0] === \"TEARDOWN\");\n\t\tconst hasTerminal = sorted.some((m) => m[0] === \"COMPLETE\" || m[0] === \"ERROR\");\n\t\tif (\n\t\t\thasTeardown &&\n\t\t\t!hasTerminal &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._value.hasTorndown\n\t\t) {\n\t\t\tsorted = [[\"COMPLETE\"], ...sorted];\n\t\t}\n\t\t// R-batch-coalesce (D12): inside a batch, emit DIRTY immediately but defer the\n\t\t// tier-3 settle slice to commit so a shared downstream recomputes once. Only\n\t\t// external emits defer (fn emits during commit run normally).\n\t\tif (!this._wave.insideRunWave && currentBatch()) {\n\t\t\tconst deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));\n\t\t\tif (deferred.length > 0) {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t\t\t}\n\t\t\t\tthis._wave.batchDirtyOwed = true; // BH1: owe a balancing RESOLVED on rollback\n\t\t\t\tdeferToBatch(this, deferred);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// R-pause-modes / R-async-paused: defer the settle slice (tier 3/4) into the\n\t\t// pause buffer while paused; tier 0-2 (DIRTY/PAUSE/RESUME), tier 5 (terminal),\n\t\t// tier 6 (TEARDOWN) bypass so end-of-stream + control always reach observers.\n\t\tif (this._shouldBufferOnPause()) {\n\t\t\tconst buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));\n\t\t\tif (buffered.length > 0) {\n\t\t\t\t// B36 / R-resolved-undirty: buffering a settle slice still means this fn wave\n\t\t\t\t// produced a settle. Without this, _runWave sees \"dirty + no settle\" and\n\t\t\t\t// synthesizes a RESOLVED that pierces the pause while the DATA waits in the buffer.\n\t\t\t\tthis._wave.emittedSettleThisWave = true;\n\t\t\t\tthis._control.pauseBuffer.push(buffered);\n\t\t\t}\n\t\t\tsorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));\n\t\t\tif (sorted.length === 0) return;\n\t\t}\n\t\tlet dataCount = 0;\n\t\tlet hasTier3 = false;\n\t\tlet hasResolved = false;\n\t\tfor (const m of sorted) {\n\t\t\tif (m[0] === \"DATA\") dataCount++;\n\t\t\tif (m[0] === \"RESOLVED\") hasResolved = true;\n\t\t\tif (isValueTier(m[0])) hasTier3 = true;\n\t\t}\n\t\t// EC2 / R-resolved-undirty tier-3 exclusivity: a wave's tier-3 slot is >=1 DATA\n\t\t// (occurrence) XOR exactly 1 RESOLVED (undirty) — never mixed. Reject fail-fast.\n\t\tif (dataCount >= 1 && hasResolved) {\n\t\t\tthrow new Error(\n\t\t\t\t\"down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)\",\n\t\t\t);\n\t\t}\n\t\tconst plannedVersions: Array<NodeVersion | undefined> = new Array(sorted.length);\n\t\tif (dataCount > 0) {\n\t\t\tlet plannedVersion = this._version.value;\n\t\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\t\tconst m = sorted[i];\n\t\t\t\tif (m[0] !== \"DATA\") continue;\n\t\t\t\tplannedVersion = advanceNodeVersion(plannedVersion, this._version.policy, m[1]);\n\t\t\t\tplannedVersions[i] = plannedVersion;\n\t\t\t}\n\t\t}\n\n\t\t// Synthesize a leading DIRTY for an EXTERNAL tier-3 emit (R-dirty-before-data), and for\n\t\t// PULL demand fns only when they actually emit tier-3. A no-op pull helper must stay silent.\n\t\tif (\n\t\t\thasTier3 &&\n\t\t\t(!this._wave.insideRunWave || this._control.pullDirtyOwed) &&\n\t\t\t!this._wave.emittedDirtyThisWave\n\t\t) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._value.status = \"dirty\";\n\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t}\n\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst m = sorted[i];\n\t\t\tconst delivery = { wave: deliveryWave, last: i === sorted.length - 1 };\n\t\t\t// R-resolved-undirty (D49): a tier-3+ emit this wave means the fn produced a settle,\n\t\t\t// so no synthesized undirty RESOLVED is owed (see _runWave).\n\t\t\tif (isDeferredTier(m[0])) this._wave.emittedSettleThisWave = true;\n\t\t\tif (m[0] === \"DIRTY\") {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], delivery);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"DATA\") {\n\t\t\t\tconst v = m[1] as T;\n\t\t\t\t// R-resolved-undirty (D49): every value-occurrence is emitted as DATA — the\n\t\t\t\t// substrate never substitutes DATA->RESOLVED on value-equality. Dedup is opt-in\n\t\t\t\t// at the operator layer (distinctUntilChanged), never a substrate behavior.\n\t\t\t\tthis._value.cache = v;\n\t\t\t\tthis._value.hasData = true;\n\t\t\t\tthis._value.status = \"settled\";\n\t\t\t\tthis._version.value = plannedVersions[i];\n\t\t\t\tif (this._slot.replayN > 0) {\n\t\t\t\t\tthis._value.replayRing.push(v);\n\t\t\t\t\tif (this._value.replayRing.length > this._slot.replayN) this._value.replayRing.shift();\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"DATA\", v], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"RESOLVED\") {\n\t\t\t\tthis._value.status = this._value.hasData ? \"resolved\" : \"sentinel\";\n\t\t\t\tthis._emitToSubs([\"RESOLVED\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"INVALIDATE\") {\n\t\t\t\tthis._invalidate(delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"COMPLETE\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = true;\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"completed\";\n\t\t\t\tthis._emitToSubs([\"COMPLETE\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"ERROR\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = m[1];\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"errored\";\n\t\t\t\tthis._emitToSubs([\"ERROR\", m[1]], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"TEARDOWN\") {\n\t\t\t\tthis._value.hasTorndown = true;\n\t\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\t\tthis._value.hasData = false;\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"TEARDOWN\"], delivery);\n\t\t\t}\n\t\t\t// PAUSE / RESUME — control slice.\n\t\t}\n\n\t\tif (!this._wave.insideRunWave) this._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _up(msgs: Wave, towardDep?: number, route?: UpRouteState): void {\n\t\tif (this._released) return;\n\t\tconst routeState = route ?? { demandFired: new Map() };\n\t\tfor (const m of msgs) {\n\t\t\tif (!isUpAllowed(m[0])) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === \"PAUSE\") {\n\t\t\t\t// PAUSE is NODE-TARGETED (R-up-routing): it ACQUIRES a lock, so there is no\n\t\t\t\t// pre-existing holder to route to — a controller targets the node directly.\n\t\t\t\tthis._pauseAcquire(m[1]);\n\t\t\t} else if (m[0] === \"RESUME\") {\n\t\t\t\t// R-up-routing (D269): RESUME is pause-lock release only.\n\t\t\t\tif (this._control.pauseLockset.has(m[1])) {\n\t\t\t\t\t// a pause lock held HERE → release LOCALLY (normal pause/resume, R-pause-lockset).\n\t\t\t\t\tthis._pauseRelease(m[1]);\n\t\t\t\t} else {\n\t\t\t\t\t// not held here → forward UP the declared cone to find the holder.\n\t\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t\t}\n\t\t\t} else if (m[0] === \"PULL\") {\n\t\t\t\t// R-up-routing / R-pull (D269/D272): DEMAND-IF-PULL-HOLDER-ELSE-FORWARD-UP.\n\t\t\t\tconst demand = normalizePullDemand(m[1]);\n\t\t\t\tif (this._slot.pull && demand.pullId === this._slot.pullLock) {\n\t\t\t\t\tif (!this._markDemandRouted(demand.pullId, routeState)) this._onDemand(demand);\n\t\t\t\t} else {\n\t\t\t\t\tthis._forwardUp([\"PULL\", demand], towardDep, routeState);\n\t\t\t\t}\n\t\t\t} else if (this._slot.deps.length === 0) {\n\t\t\t\t// R-up-at-source (D38): a depless source is the terminus of upstream control.\n\t\t\t\t// INVALIDATE → HONOR the invalidate-request. Routed through _down (NOT a direct\n\t\t\t\t// _invalidate call, QA A-2) so the invalidate-request respects batch-defer (D12)\n\t\t\t\t// and pause-buffer exactly like a downstream-originated INVALIDATE; _down's\n\t\t\t\t// INVALIDATE branch calls _invalidate() (clear cache → SENTINEL, fire onInvalidate,\n\t\t\t\t// broadcast downstream). Outside batch/pause it is identical to a direct call.\n\t\t\t\t// DIRTY / TEARDOWN → DROP (no coherent terminus action; self-dirty would wedge\n\t\t\t\t// downstream awaiting a settle that never comes; source lifecycle is source-owned).\n\t\t\t\tif (m[0] === \"INVALIDATE\") this._down([[\"INVALIDATE\"]]);\n\t\t\t} else {\n\t\t\t\t// dep-bearing intermediate: forward DIRTY/INVALIDATE/TEARDOWN up toward deps.\n\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _markDemandRouted(lockId: LockId, route: UpRouteState): boolean {\n\t\tlet holders = route.demandFired.get(lockId);\n\t\tif (holders === undefined) {\n\t\t\tholders = new Set();\n\t\t\troute.demandFired.set(lockId, holders);\n\t\t}\n\t\tif (holders.has(this as unknown as Node<unknown>)) return true;\n\t\tholders.add(this as unknown as Node<unknown>);\n\t\treturn false;\n\t}\n\n\t/**\n\t * Forward one up-going control message toward deps (R-up-routing): up the single declared edge\n\t * `towardDep` (directed — prunes other branches; only meaningful on the issuer's FIRST hop) or\n\t * broadcast up ALL deps. A depless source has no deps → the message DROPS here (the terminus —\n\t * e.g. a cone-routed PULL whose pullId no node up this cone holds, R-up-at-source). Recursive\n\t * forwarding carries the same per-wave route state and no `towardDep` → broadcast beyond the\n\t * first hop.\n\t */\n\tprivate _forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void {\n\t\tif (this._slot.deps.length === 0) return; // depless source terminus → drop\n\t\tif (towardDep !== undefined) {\n\t\t\tconst d = this._slot.deps[towardDep];\n\t\t\tif (d !== undefined) d._up([m], undefined, route);\n\t\t} else {\n\t\t\tfor (const dep of this._slot.deps) dep._up([m], undefined, route);\n\t\t}\n\t}\n\n\t// ── PAUSE/RESUME lockset (R-pause-lockset) + modes (R-pause-modes) ──\n\n\tprivate _isPaused(): boolean {\n\t\treturn this._control.pauseLockset.size > 0;\n\t}\n\n\tprivate _hasBoundaryPauseLock(): boolean {\n\t\tif (this._slot.pausable === false) return false;\n\t\treturn this._control.pauseLockset.size > 0;\n\t}\n\n\tprivate _isAsyncPool(): boolean {\n\t\treturn (\n\t\t\tthis._slot.handle !== null &&\n\t\t\tthis._slot.dispatcher.poolKind(this._slot.handle.poolId) === \"async\"\n\t\t);\n\t}\n\n\tprivate _pauseAcquire(lockId: unknown): void {\n\t\tthis._control.pauseLockset.add(lockId); // Set => same-id repeat PAUSE is idempotent\n\t}\n\n\tprivate _pauseRelease(lockId: unknown): void {\n\t\tif (!this._control.pauseLockset.has(lockId)) return; // unknown id => no-op\n\t\tthis._control.pauseLockset.delete(lockId);\n\t\t// R-pull (D59 / D272): releasing an EXTERNAL pause lock can unblock an owed demand.\n\t\t// Pull quiet is activePull-derived and never stored in pauseLockset.\n\t\tif (this._slot.pull && this._control.demandOwed !== undefined) this._fireOwedDemandIfReady();\n\t\tif (this._hasBoundaryPauseLock()) return; // another external lock still held => stay paused\n\t\tscheduleBoundaryDrain(this._core);\n\t\tif (this._slot.pull) return; // pull nodes stay quiet until PULL, even after external resume\n\t\tthis._onResume();\n\t}\n\n\tprivate _onResume(): void {\n\t\t// BH3: a node that terminated while paused discards its buffer and never\n\t\t// replays/recomputes (terminal-is-forever).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\treturn;\n\t\t}\n\t\t// Non-pull pause/resume (R-pause-modes): drain buffered settle slices (resumeAll /\n\t\t// async-at-paused, R-async-paused), then fire a coalesced dep-wave once (default mode).\n\t\t// A PULL node does not resume by draining here; its demand fires through _onDemand.\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t}\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._tryRun();\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): can this pull node fire a demand NOW? — not terminal, settle-ready (_pending===0),\n\t * and no OTHER (non-pullId) lock holds it paused. The gate that decides fire-now vs OWE.\n\t */\n\tprivate _canFireDemand(): boolean {\n\t\tif (this._value.terminal !== undefined || this._wave.pending > 0) return false;\n\t\treturn this._control.pauseLockset.size === 0;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): deliver ONE demand pulse — install activePull so the demand wave may\n\t * emit, fire it, then clear activePull so the node is quiet again (1:1).\n\t */\n\tprivate _deliverPullDemand(demand: PullDemand): void {\n\t\tthis._control.demandOwed = undefined;\n\t\tthis._control.activePull = demand;\n\t\tthis._control.inDeliverDemand = true;\n\t\ttry {\n\t\t\tthis._firePullDemand();\n\t\t} finally {\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): a cone-routed PULL of THIS node's pullId arrived (R-up-routing) = a DEMAND.\n\t * Fire immediately if able; else OWE it — pin-5 (a dep DIRTY in flight, _pending>0) or F4/F5 (an\n\t * external PAUSE lock co-holds the node) — and fire when the node next becomes able. A demand\n\t * arriving WHILE a delivery is in flight (synchronous re-entry) is DROPPED (1:1, QA guard).\n\t */\n\tprivate _onDemand(demand: PullDemand): void {\n\t\tif (this._control.inDeliverDemand) return; // re-entrant demand during an active delivery → drop (1:1)\n\t\tif (this._canFireDemand()) this._deliverPullDemand(demand);\n\t\telse this._control.demandOwed = demand; // latest owed params wins (D269/D272)\n\t}\n\n\t/**\n\t * R-pull (D55): service ONE demand. Delivery content = the orthogonal pausable mode:\n\t * - 'resumeAll' → drain the buffered BACKLOG (each `_down` re-synthesizes a leading DIRTY, so\n\t * the per-entry replay is DIRTY-before-DATA — R-pause-modes per-entry arrival order);\n\t * - true → deliver the coalesced LATEST as ONE DIRTY-before-DATA wave (pin 2: the quiet absorb\n\t * suppressed the dep's original DIRTY, so the demand wave restores it before the value).\n\t * Neither branch fires when nothing changed since the last demand → the demand is SILENT.\n\t * Called by `_deliverPullDemand` only when settle-ready; the caller has released the pullId, so\n\t * `_markDirty` relays the leading DIRTY (not absorbed).\n\t */\n\tprivate _firePullDemand(): void {\n\t\tlet drainedBuffer = false;\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t\tdrainedBuffer = true;\n\t\t}\n\t\tif (drainedBuffer) return;\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\t// QA-B2: only deliver if the fn can actually run this wave (settle-ready + first-run gate\n\t\t\t// open). A gated run emits no DATA, so emitting the leading DIRTY would STRAND downstream\n\t\t\t// — the exact wedge this feature exists to prevent (NoWedgeWhileQuiet). When gated, stay\n\t\t\t// SILENT and KEEP _pausedDepWaveOccurred so a later demand (once every dep has settled)\n\t\t\t// delivers. Mirrors _settleRewire's pre-_markDirty gate.\n\t\t\tconst gated =\n\t\t\t\tthis._slot.handle !== null &&\n\t\t\t\t!this._wave.hasCalledFnOnce &&\n\t\t\t\t!(this._slot.partial || this._allDepsSettled());\n\t\t\tif (this._wave.pending > 0 || gated) return;\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._control.pullDirtyOwed = true;\n\t\t\ttry {\n\t\t\t\tthis._tryRun(); // fn DATA triggers DIRTY-before-DATA; no DATA means no output.\n\t\t\t} finally {\n\t\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this._slot.handle !== null) {\n\t\t\tif (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._control.pullDirtyOwed = true;\n\t\t\ttry {\n\t\t\t\tthis._runWave();\n\t\t\t} finally {\n\t\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): fire a demand that was OWED (deferred at demand time) once the node becomes\n\t * able — called from the dep-settle arms (DATA/RESOLVED/INVALIDATE/terminal drain _pending, pin-5\n\t * + B1/F6) and from `_pauseRelease` (an external PAUSE lock releases, F4/F5).\n\t */\n\tprivate _fireOwedDemandIfReady(): void {\n\t\tif (this._control.inDeliverDemand) return; // don't re-enter during an active delivery (1:1, QA guard)\n\t\tif (this._slot.pull && this._control.demandOwed !== undefined && this._canFireDemand()) {\n\t\t\tthis._deliverPullDemand(this._control.demandOwed);\n\t\t}\n\t}\n\n\t/** Should an outgoing settle slice be deferred into the pause buffer? */\n\tprivate _shouldBufferOnPause(): boolean {\n\t\t// D44: pausable mode is the OUTER gate over R-async-paused buffering.\n\t\t// false: ignore PAUSE/RESUME ENTIRELY — never buffer, keep producing (R-pause-modes; resolves B20).\n\t\tif (this._slot.pausable === false) return false;\n\t\tif (!this._isPaused() && !this._isPullQuiet()) return false;\n\t\t// resumeAll: production-gating — buffer the node's own (sync/async) settle slice too.\n\t\tif (this._slot.pausable === \"resumeAll\") return true;\n\t\t// true (default): PAUSE gates recomputation/propagation, NOT a leaf source's own production.\n\t\t// An async COMPUTE node's (deps>0) in-flight result buffers (R-async-paused / C-2); a depless\n\t\t// async leaf source's own production delivers immediately (R-pause-modes / C-10).\n\t\tif (!this._wave.insideRunWave && this._isAsyncPool() && this._slot.deps.length > 0) return true;\n\t\treturn false;\n\t}\n\n\t/** R-invalidate-idempotent: clear cache + flush + cascade; no-op if nothing cached. */\n\tprivate _invalidate(delivery?: DeliveryMeta): void {\n\t\tif (!this._value.hasData) return; // never-populated or already-reset → no-op\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.replayRing = []; // BH6: invalidated values are stale — don't replay them\n\t\tfor (const fn of this._hooks.onInvalidate) fn();\n\t\tthis._emitToSubs([\"INVALIDATE\"], delivery);\n\t}\n\n\t// B42 (R-deps-terminal): ALL deps TERMINAL = every dep has reached COMPLETE *or* an ABSORBED\n\t// ERROR. Block only on a LIVE dep (_depTerminal[i] === undefined); an errored dep (terminal = the\n\t// error payload, which R-data-payload guarantees is !== undefined and non-boolean) COUNTS as\n\t// terminal-done. Was\n\t// `tm !== true`, which wedged a node whose errorWhenDepsError:false dep ERRORed (it never\n\t// auto-completed even after every other dep completed). Drives the completeWhenDepsComplete cascade.\n\tprivate _allDepsTerminal(): boolean {\n\t\tif (this._slot.deps.length === 0) return false;\n\t\tfor (const tm of this._dep.terminal) if (tm === undefined) return false;\n\t\treturn true;\n\t}\n\n\t/** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */\n\tprivate _resetLifecycle(): void {\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tthis._lifecycle.activated = false;\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.hasTorndown = false;\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._resetDepState();\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._value.replayRing = []; // BH6\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t} else {\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _emitToSubs(msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\t// Copy guards against subscribe/unsubscribe during iteration.\n\t\tconst subs = [...this._lifecycle.subscribers];\n\t\tfor (const sink of subs) sink(msg, delivery);\n\t}\n\n\t/** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */\n\t__commitBatchedWave(wave: Wave): void {\n\t\tthis._wave.batchDirtyOwed = false; // commit delivers the real settle (BH1)\n\t\tthis._down(wave); // batch is inactive at commit -> processes normally\n\t}\n\n\t/** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */\n\t__rollbackBatched(): void {\n\t\t// BH1: keyed on _batchDirtyOwed (not _emittedDirtyThisWave, which a fn wave between\n\t\t// defer and rollback would have reset) so the balancing RESOLVED is never skipped.\n\t\tif (this._wave.batchDirtyOwed) {\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t\tthis._emitToSubs([\"RESOLVED\"]);\n\t\t}\n\t}\n\n\t/** B49: enqueue a committed-boundary task on this node's graph-local core. */\n\t__deferBoundary(fn: () => void, batchToken?: object): void {\n\t\tdeferRewire(this._core, fn, {\n\t\t\tbatchToken,\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n}\n\n/**\n * Construct a node (R-node-iface / D5 / L1.9 deps-first).\n * node([], null, { initial }) — state node (manual source; emit via .down)\n * node([], fn) — producer (runs on activation)\n * node([a, b], fn) — compute / derived\n * node([dep]) — passthrough wire\n */\nexport function node<T = unknown>(\n\tdeps: Node<unknown>[] = [],\n\thandleOrFn: Handle | NodeFn | null = null,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, handleOrFn, opts);\n}\n\n/**\n * Construct a dynamicNode (R-dynamic-node / D35) — a node variant whose fn reads a\n * subset of a fixed superset of deps per invocation via `ctx.track(i)`. All declared\n * deps participate in wave tracking; an unread dep's change re-runs the fn, which re-emits\n * its current value as DATA (D49 removed equals-absorption — dedup is opt-in via\n * distinctUntilChanged). Intra-graph only (D22).\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","/**\n * Graph checkpoint public data shape (D83/D86/D90/D116).\n *\n * Checkpoint is a graph lifecycle snapshot: strict-JSON-compatible data, no storage I/O,\n * no observe-log replay, and no restore runtime in this first TS slice.\n */\n\nimport { type StrictJsonValue, strictJsonCodec } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { NodeVersionJson } from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\n\nexport const GRAPH_CHECKPOINT_VERSION = \"graphrefly.checkpoint.v1\" as const;\n\nexport type GraphCheckpointVersion = typeof GRAPH_CHECKPOINT_VERSION;\n\nexport type GraphCheckpointJson = StrictJsonValue;\n\nexport type GraphCheckpointValue =\n\t| { kind: \"SENTINEL\" }\n\t| { kind: \"DATA\"; data: GraphCheckpointJson };\n\nexport type GraphCheckpointTerminal =\n\t| { kind: \"none\" }\n\t| { kind: \"COMPLETE\" }\n\t| { kind: \"ERROR\"; error: GraphCheckpointJson };\n\nexport type GraphCheckpointFactory =\n\t| {\n\t\t\tkind: \"registry-ref\";\n\t\t\tref: string;\n\t\t\tconfig?: GraphCheckpointJson;\n\t\t\tconfigVersion?: GraphCheckpointJson;\n\t }\n\t| { kind: \"local-only\"; name: string; reason: string };\n\nexport interface GraphCheckpointNode {\n\tid: string;\n\tname?: string;\n\tfactory: GraphCheckpointFactory;\n\tstatus: string;\n\tdeps: string[];\n\tvalue: GraphCheckpointValue;\n\tbackendState?: GraphCheckpointJson;\n\tversion?: NodeVersionJson;\n\tterminal: GraphCheckpointTerminal;\n\tlifecycle: { activated: boolean; hasCalledFnOnce: boolean };\n\tctxState: { persist: boolean; value: GraphCheckpointValue };\n\tmeta?: { [key: string]: GraphCheckpointJson };\n}\n\nexport interface GraphCheckpointEdge {\n\tfrom: string;\n\tto: string;\n}\n\nexport interface GraphCheckpointMount {\n\tat: string;\n\tcheckpoint: GraphCheckpoint;\n}\n\nexport interface GraphCheckpoint {\n\tversion: GraphCheckpointVersion;\n\tname?: string;\n\tnodes: GraphCheckpointNode[];\n\tedges: GraphCheckpointEdge[];\n\tmounts?: GraphCheckpointMount[];\n}\n\nexport function toCheckpointJson(value: unknown, path = \"$\"): GraphCheckpointJson {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as GraphCheckpointJson;\n\t} catch (cause) {\n\t\tthrow new TypeError(`checkpoint: value at ${path} is not strict JSON compatible`, {\n\t\t\tcause,\n\t\t});\n\t}\n}\n\nexport function checkpointValue(\n\tvalue: unknown,\n\thasData: boolean,\n\tpath: string,\n): GraphCheckpointValue {\n\tif (!hasData || value === SENTINEL) return { kind: \"SENTINEL\" };\n\treturn { kind: \"DATA\", data: toCheckpointJson(value, path) };\n}\n\nexport function checkpointTerminal(value: unknown, path: string): GraphCheckpointTerminal {\n\tif (value === undefined) return { kind: \"none\" };\n\tif (value === true) return { kind: \"COMPLETE\" };\n\treturn { kind: \"ERROR\", error: toCheckpointJson(value, path) };\n}\n\ntype BackendStateContributor = () => unknown;\n\nconst backendStateContributors = new WeakMap<Node<unknown>, BackendStateContributor>();\n\n/** @internal D160: collection-owned backend checkpoint contributor for graph checkpoint. */\nexport function registerBackendStateContributor(\n\tnode: Node<unknown>,\n\tcontributor: BackendStateContributor,\n): void {\n\tbackendStateContributors.set(node, contributor);\n}\n\n/** @internal D160: capture a node's collection backend state when it has a contributor. */\nexport function checkpointBackendStateOfNode(\n\tnode: Node<unknown>,\n\tpath: string,\n): GraphCheckpointJson | undefined {\n\tconst contributor = backendStateContributors.get(node);\n\tif (contributor === undefined) return undefined;\n\treturn toCheckpointJson(contributor(), path);\n}\n","/**\n * Operators as free-standing factory definitions (D43 / D6 / D40 Catalog-first).\n *\n * Operators are `node` sugar (D6), NOT verbs (D4) and NEVER in parity (D24). Each is a\n * pure {@link Operator} spec — `{factory, body, opts}` — built on the bare `node` primitive\n * (NOT the `derived` verb): `body` reads ctx dep slots positionally and emits via\n * `ctx.down`. Two ways to instantiate:\n *\n * - {@link initNode}(op, deps, opts?) — bare, no Graph; returns a working `Node<T>`.\n * - `g.initNode(op, deps, opts?)` — graph-bound; the SAME call, plus inspection registration\n * (the real factory name lands in the graph's `_entries`, so describe/observe/profile\n * show it — D6/R-describe — while the node stays thin, R-node-thin).\n *\n * The D30 throw→ERROR boundary lives once, in the free {@link initNode} (which `g.initNode`\n * funnels through). The pure-ts `operatorOpts/partialOperatorOpts/gatedOperatorOpts` trio is\n * NOT ported: its sole job (`describeKind:\"derived\"`) is dead under D6/D39 (factory = the\n * REAL operator name); only the `partial`/`terminalAsRealInput` flags survive, carried\n * per-operator in `op.opts`.\n *\n * Config is folded into the factory (`map(fn)`, `scan(reducer, seed)`, `take(n)`, `merge()`),\n * so fn params are annotated where the source type can't be inferred (RxJS-pipe cost);\n * dep-type safety is recovered by the typed `g.initNode` overloads.\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepLatest,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { NodeCore } from \"../node/core.js\";\nimport { Node, type NodeOptions, withNodeCore } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { type GraphCheckpointJson, toCheckpointJson } from \"./checkpoint.js\";\nimport type { GraphRestoreDefinition, GraphRestoreEntry, GraphRestoreRegistry } from \"./restore.js\";\n\n/**\n * A free-standing operator definition (D43). `TIn` = the element type each dep delivers\n * (the operator reads `depLatest(ctx, i) as TIn`); `TOut` = the emitted value type.\n * `__in`/`__out` are phantom-only (never assigned) — they let `g.initNode` infer + check the\n * dep tuple against the operator without an explicit type argument.\n */\nexport interface Operator<TIn = unknown, TOut = unknown> {\n\t/** Real operator name shown in describe (D6/L1.5) — recorded at `_add` by `g.initNode`. */\n\treadonly factory: string;\n\t/** The ctx-body: reads ctx dep slots positionally, emits via `ctx.down`. */\n\treadonly body: (ctx: Ctx) => void;\n\t/** Behavioral node options the operator needs (e.g. `partial:true` for combine-family). */\n\treadonly opts?: Partial<NodeOptions<TOut>>;\n\t/**\n\t * D97/D100 restore metadata derived from a named definition or static built-in config.\n\t * This is semantic metadata only; dispatcher handles stay graph-local runtime state.\n\t */\n\treadonly restore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t};\n\t/** @internal phantom — never set; carries the dep element type for `g.initNode` inference. */\n\treadonly __in?: TIn;\n\t/** @internal phantom — never set; carries the output value type. */\n\treadonly __out?: TOut;\n}\n\ntype MutableRestoreRegistry = Map<string, GraphRestoreEntry> | Record<string, GraphRestoreEntry>;\n\nexport type RestoreRegistryEntry = GraphRestoreEntry;\n\nexport interface Definition<S = unknown, T = unknown> extends GraphRestoreDefinition<S, T> {\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport interface DefineOpts {\n\tregistry?: MutableRestoreRegistry;\n}\n\nfunction registryHas(registry: MutableRestoreRegistry, ref: string): boolean {\n\treturn registry instanceof Map ? registry.has(ref) : Object.hasOwn(registry, ref);\n}\n\nfunction registrySet(\n\tregistry: MutableRestoreRegistry,\n\tref: string,\n\tentry: GraphRestoreEntry,\n): void {\n\tif (registryHas(registry, ref)) {\n\t\tthrow new Error(`restoreRegistry: duplicate ref '${ref}'`);\n\t}\n\tif (registry instanceof Map) registry.set(ref, entry);\n\telse registry[ref] = entry;\n}\n\nexport function addToRestoreRegistry(\n\tregistry: MutableRestoreRegistry,\n\tentry: GraphRestoreEntry,\n): void {\n\tregistrySet(registry, entry.ref, entry);\n}\n\nexport function restoreRegistry(\n\tentries: readonly GraphRestoreEntry[] = [],\n\tbase?: GraphRestoreRegistry,\n): Map<string, GraphRestoreEntry> {\n\tconst out = new Map<string, GraphRestoreEntry>();\n\tif (base instanceof Map) {\n\t\tfor (const [ref, entry] of base) registrySet(out, ref, entry);\n\t} else if (base !== undefined) {\n\t\tfor (const [ref, entry] of Object.entries(base)) registrySet(out, ref, entry);\n\t}\n\tfor (const entry of entries) addToRestoreRegistry(out, entry);\n\treturn out;\n}\n\nfunction isDefinition<S, T>(fn: ((v: S) => T) | Definition<S, T>): fn is Definition<S, T> {\n\treturn typeof fn === \"object\" && fn !== null && (fn as Definition<S, T>).kind === \"definition\";\n}\n\nexport function define<S, T>(\n\tref: string,\n\tfn: (v: S) => T,\n\topts: DefineOpts = {},\n): Definition<S, T> {\n\tconst jsonRef = toCheckpointJson(ref, \"define.ref\");\n\tif (typeof jsonRef !== \"string\") throw new TypeError(\"define: ref must be a string\");\n\tconst definition: Definition<S, T> = {\n\t\tkind: \"definition\",\n\t\tref: jsonRef,\n\t\tfn,\n\t};\n\tif (opts.registry !== undefined) addToRestoreRegistry(opts.registry, definition);\n\treturn definition;\n}\n\n/**\n * Instantiate an operator as a bare `Node<T>` — NO Graph required (D43 bare-node path).\n * Wraps `op.body` in the D30 value-throw→ERROR boundary; merges `op.opts` with caller `opts`\n * (caller wins, so `partial`/`pool`/`dispatcher` overrides take effect). The\n * dispatcher defaults to the process-global (D26) unless `opts.dispatcher` is passed.\n *\n * `g.initNode` is the same call PLUS graph registration; graph inspection\n * (describe/observe/profile) requires that path — a node built bare here is not registered in\n * any graph's index.\n */\nexport function initNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn makeInitNode(op, deps, opts);\n}\n\n/** @internal Graph-bound operator instantiation into a graph-local B49 core. */\nexport function initNodeWithCore<TIn, TOut>(\n\tcore: NodeCore,\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn withNodeCore(core, () => makeInitNode(op, deps, opts));\n}\n\nfunction makeInitNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut>,\n): Node<TOut> {\n\tconst body = operatorNodeFn(op);\n\t// D43-reserved / D51: stamp the operator's real factory onto the bare node so a runtime *Map\n\t// inner (created here via fromAny, NOT registered in any graph) is named in describe's\n\t// auto-discovery. A graph-bound g.initNode also records it in `_entries` (entry.factory wins\n\t// there); this field is only read for a node absent from the graph index. Caller opts win.\n\treturn new Node<TOut>([...deps], body, { factory: op.factory, ...op.opts, ...opts });\n}\n\n/** @internal Build the dispatcher body for an Operator spec. */\nexport function operatorNodeFn<TIn, TOut>(op: Operator<TIn, TOut>): NodeFn {\n\treturn (ctx) => {\n\t\ttry {\n\t\t\top.body(ctx);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"operator threw without a valid error payload\")]]); // D30: value-level throw → ERROR\n\t\t}\n\t};\n}\n\n// ── Slice 1 — single-dep map / take / control (CSP-2.7 catalog re-derive, D40) ──\n// All read dep 0 positionally + emit via ctx.down. Under D49 every occurrence is DATA (no\n// equals-absorption); a body that returns WITHOUT emitting gets a substrate-synthesized undirty\n// RESOLVED (R-resolved-undirty) — so a \"skip this wave\" is a bare `return`. Terminal-emitting\n// operators (reduce/last/find/elementAt) read `depTerminal(ctx, 0)` via the\n// `completeWhenDepsComplete:false + terminalAsRealInput:true` flags (R-deps-terminal): the fn fires\n// on the source's COMPLETE and emits its final value. NOT 1:1 pure-ts ports — the frozen reference\n// (D41) uses a producer + internal `subscribeOr`, the D45-banned describe island; these are\n// declared-dep nodes whose single edge `describe` shows truthfully.\n\n/** map: emit fn(value). A named {@link define} makes the map restorable via the map descriptor (D101). */\nexport function map<S, T>(fn: ((v: S) => T) | Definition<S, T>): Operator<S, T> {\n\tif (isDefinition(fn)) {\n\t\treturn mapFromFunction(fn.fn, {\n\t\t\tref: \"map\",\n\t\t\tconfig: { fn: toCheckpointJson(fn.ref, `map.fn`) },\n\t\t});\n\t}\n\treturn mapFromFunction(fn);\n}\n\nfunction mapFromFunction<S, T>(\n\tfn: (v: S) => T,\n\trestore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t},\n): Operator<S, T> {\n\treturn {\n\t\tfactory: \"map\",\n\t\t...(restore ? { restore } : {}),\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) ctx.down([[\"DATA\", fn(v as S)]]);\n\t\t},\n\t};\n}\n\n/** filter: emit value only when pred(value) (else skip the wave). */\nexport function filter<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"filter\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) if (pred(v as S)) ctx.down([[\"DATA\", v]]);\n\t\t},\n\t};\n}\n\n/** scan: stateful accumulator over the upstream (acc seeded once, kept in ctx.state). */\nexport function scan<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"scan\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tfor (const v of b) {\n\t\t\t\tacc = reducer(acc, v as S);\n\t\t\t\tctx.down([[\"DATA\", acc]]);\n\t\t\t}\n\t\t\tctx.state.set(acc);\n\t\t},\n\t};\n}\n\n/** take: emit the first n values, then COMPLETE (terminal-is-forever). */\nexport function take<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"take\",\n\t\trestore: { ref: \"take\", config: { n: toCheckpointJson(n, \"take.n\") } },\n\t\tbody: (ctx) => {\n\t\t\tif (n <= 0) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (count >= n) return; // already satisfied\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count >= n) break;\n\t\t\t\tcount += 1;\n\t\t\t\tctx.down(count >= n ? [[\"DATA\", v], [\"COMPLETE\"]] : [[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/** distinctUntilChanged: emit only when the value differs from the previous emit. */\nexport function distinctUntilChanged<S>(eq: (a: S, b: S) => boolean = Object.is): Operator<S, S> {\n\treturn {\n\t\tfactory: \"distinctUntilChanged\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst prev = ctx.state.get<{ v: S }>();\n\t\t\tlet last = prev?.v;\n\t\t\tlet hasLast = prev !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasLast && eq(last as S, v)) continue;\n\t\t\t\tlast = v;\n\t\t\t\thasLast = true;\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tif (hasLast) ctx.state.set({ v: last as S });\n\t\t},\n\t};\n}\n\n/**\n * merge: interleave several sources — emit each DATA from whichever dep fired. `partial:true`\n * (combine-family): fires on any single dep, not gated on all deps settling.\n */\nexport function merge<T>(): Operator<T, T> {\n\treturn {\n\t\tfactory: \"merge\",\n\t\topts: { partial: true },\n\t\tbody: (ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b && b.length > 0) {\n\t\t\t\t\tfor (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * reduce: accumulate over the whole source, emit ONE final value on the source's COMPLETE\n * (RxJS `reduce`). Unlike {@link scan} (which emits every step), reduce stays quiet until the\n * source terminates. `completeWhenDepsComplete:false + terminalAsRealInput:true`: the fn fires on\n * the source COMPLETE (reading `terminal===true`) and emits the accumulator + COMPLETE. An empty\n * source emits the seed (RxJS parity). A source ERROR auto-forwards (errorWhenDepsError default).\n */\nexport function reduce<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"reduce\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tif (b) for (const v of b) acc = reducer(acc, v as S);\n\t\t\tctx.state.set(acc);\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"DATA\", acc], [\"COMPLETE\"]]);\n\t\t\t// else (live DATA wave): no emit → substrate-synthesized undirty RESOLVED (D49).\n\t\t},\n\t};\n}\n\n/**\n * pairwise: emit `[previous, current]` for each consecutive pair; the very first value produces no\n * pair (quiet → undirty RESOLVED). Previous value is kept in `ctx.state`.\n */\nexport function pairwise<S>(): Operator<S, readonly [S, S]> {\n\treturn {\n\t\tfactory: \"pairwise\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst st = ctx.state.get<{ prev: S }>();\n\t\t\tlet prev = st?.prev;\n\t\t\tlet hasPrev = st !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasPrev) ctx.down([[\"DATA\", [prev as S, v] as const]]);\n\t\t\t\tprev = v;\n\t\t\t\thasPrev = true;\n\t\t\t}\n\t\t\tif (hasPrev) ctx.state.set({ prev: prev as S });\n\t\t},\n\t};\n}\n\n/** skip: drop the first `n` DATA values, then pass the rest through. */\nexport function skip<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"skip\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count < n) {\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * takeWhile: emit values while `pred` holds; on the first value that fails `pred`, COMPLETE\n * WITHOUT emitting it (RxJS default, non-inclusive). Terminal-is-forever once it completes.\n */\nexport function takeWhile<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"takeWhile\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (pred(v)) ctx.down([[\"DATA\", v]]);\n\t\t\t\telse {\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * first: emit the first value matching `pred` (or simply the first value), then COMPLETE. EDGE\n * (RxJS divergence, flagged — same class as last/find/elementAt): if the source COMPLETEs with no\n * matching value, the substrate auto-cascades a bare COMPLETE (no value); RxJS `first()` throws\n * EmptyError. Could align to `[[ERROR, EmptyError]]` (expressible) if strict RxJS parity is wanted.\n */\nexport function first<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"first\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (!pred || pred(v)) {\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no match in this wave → undirty RESOLVED (await next match)\n\t\t},\n\t};\n}\n\n/**\n * last: emit the last value matching `pred` (or the last value) on the source's COMPLETE.\n * `completeWhenDepsComplete:false + terminalAsRealInput:true`. EDGE (RxJS divergence, flagged):\n * RxJS `last()` throws EmptyError when no value matched; we COMPLETE without a value (no throw) —\n * the clean-slate substrate has no \"complete-or-throw\" terminal and SENTINEL forbids emitting a\n * placeholder.\n */\nexport function last<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"last\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) for (const v of b) if (!pred || pred(v as S)) ctx.state.set({ v });\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) {\n\t\t\t\tconst st = ctx.state.get<{ v: S }>();\n\t\t\t\tctx.down(st ? [[\"DATA\", st.v], [\"COMPLETE\"]] : [[\"COMPLETE\"]]);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * find: emit the first value matching `pred`, then COMPLETE. EDGE (RxJS divergence, flagged): RxJS\n * `find` emits `undefined` then COMPLETE when nothing matched — but `undefined` IS the SENTINEL\n * (R-sentinel), so a not-found source COMPLETE here emits a bare COMPLETE (no value).\n */\nexport function find<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"find\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (pred(v as S)) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // not found → bare COMPLETE\n\t\t},\n\t};\n}\n\n/**\n * elementAt: emit the value at zero-based `index`, then COMPLETE. EDGE (RxJS divergence, flagged):\n * RxJS throws ArgumentOutOfRangeError if the source completes before `index`; we COMPLETE without\n * a value (no throw), consistent with last/find.\n */\nexport function elementAt<S>(index: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"elementAt\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (count === index) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\tctx.state.set(count);\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // index out of range → bare COMPLETE\n\t\t},\n\t};\n}\n\n/** Observer object for {@link tap} — lifecycle-aware side effects (RxJS tap observer form). */\nexport interface TapObserver<T> {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n}\n\n/**\n * tap: invoke a side effect on each DATA (function form) or on data/error/complete (observer form);\n * values pass through unchanged. The observer form reads source terminals\n * (`completeWhenDepsComplete:false + errorWhenDepsError:false + terminalAsRealInput:true`) so it can\n * call `error`/`complete` then forward the terminal; the function form lets the substrate\n * auto-cascade terminals.\n */\nexport function tap<S>(fnOrObserver: ((v: S) => void) | TapObserver<S>): Operator<S, S> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\tconst fn = fnOrObserver;\n\t\treturn {\n\t\t\tfactory: \"tap\",\n\t\t\tbody: (ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\tif (b)\n\t\t\t\t\tfor (const v of b) {\n\t\t\t\t\t\tfn(v as S);\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\tconst obs = fnOrObserver;\n\treturn {\n\t\tfactory: \"tap\",\n\t\topts: {\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tobs.complete?.();\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(terminal)) {\n\t\t\t\tconst err = terminalErrorValue(terminal);\n\t\t\t\tobs.error?.(err);\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b)\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tobs.data?.(v as S);\n\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * onFirstData (alias `tapFirst`): invoke `fn` exactly once on the first qualifying value (default\n * `where: v => v != null` — null/undefined pass through without counting as \"first\"), then pass all\n * values through unchanged. The one-shot guard is per-node `ctx.state` (NOT a factory closure, so a\n * second instantiation of the same factory re-arms — R-ctx-state).\n */\nexport function onFirstData<S>(\n\tfn: (v: S) => void,\n\topts?: { where?: (v: S) => boolean },\n): Operator<S, S> {\n\tconst where = opts?.where ?? ((v: S) => v != null);\n\treturn {\n\t\tfactory: \"onFirstData\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet fired = ctx.state.get<boolean>() ?? false;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (!fired && where(v as S)) {\n\t\t\t\t\tfired = true;\n\t\t\t\t\tfn(v as S);\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(fired);\n\t\t},\n\t};\n}\n\n/** tapFirst: alias of {@link onFirstData} (the one-shot companion to {@link tap}). */\nexport const tapFirst = onFirstData;\n\n/** Options for {@link settle}. */\nexport interface SettleOpts<S> {\n\t/** Consecutive no-change waves before declaring convergence + COMPLETE. */\n\tquietWaves: number;\n\t/** Optional hard cap on total waves before forced COMPLETE. */\n\tmaxWaves?: number;\n\t/** Optional comparator; a DATA equal to the previous one does NOT reset the quiet counter. */\n\tequals?: (a: S, b: S) => boolean;\n}\n\n/** Internal settle accumulator state (per-node, R-ctx-state). */\ninterface SettleState<S> {\n\tlast: S | undefined;\n\thasValue: boolean;\n\tquiet: number;\n\twaves: number;\n\tdone: boolean;\n}\n\n/**\n * settle: forward each DATA unchanged, watch for convergence, COMPLETE once the source has been\n * quiet for `quietWaves` consecutive waves (or `maxWaves` elapsed). \"Wave\" = one fn invocation\n * (a DATA batch OR a bare undirty RESOLVED end-of-wave). No polling (R-no-polling) — the counter\n * advances only on real upstream waves. `settle`'s own `equals` is a body comparator, NOT the\n * removed substrate `equals` (D49).\n */\nexport function settle<S>(opts: SettleOpts<S>): Operator<S, S> {\n\tconst { quietWaves, maxWaves, equals } = opts;\n\tif (!Number.isInteger(quietWaves) || quietWaves < 1) {\n\t\tthrow new RangeError(`settle: quietWaves must be a positive integer (got ${quietWaves})`);\n\t}\n\tif (maxWaves != null && (!Number.isInteger(maxWaves) || maxWaves < 1)) {\n\t\tthrow new RangeError(`settle: maxWaves must be a positive integer when set (got ${maxWaves})`);\n\t}\n\treturn {\n\t\tfactory: \"settle\",\n\t\tbody: (ctx) => {\n\t\t\tconst st: SettleState<S> = ctx.state.get<SettleState<S>>() ?? {\n\t\t\t\tlast: undefined,\n\t\t\t\thasValue: false,\n\t\t\t\tquiet: 0,\n\t\t\t\twaves: 0,\n\t\t\t\tdone: false,\n\t\t\t};\n\t\t\tif (st.done) return;\n\t\t\tst.waves++;\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet sawChange = false;\n\t\t\tif (b && b.length > 0) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tconst next = v as S;\n\t\t\t\t\tconst isChange = !st.hasValue || equals == null || !equals(st.last as S, next);\n\t\t\t\t\tif (isChange) sawChange = true;\n\t\t\t\t\tst.last = next;\n\t\t\t\t\tst.hasValue = true;\n\t\t\t\t\tctx.down([[\"DATA\", next]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.quiet = sawChange ? 0 : st.quiet + 1;\n\t\t\tconst settled = st.hasValue && st.quiet >= quietWaves;\n\t\t\tconst exhausted = maxWaves != null && st.waves >= maxWaves;\n\t\t\tif (settled || exhausted) {\n\t\t\t\tst.done = true;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t\t// A no-DATA wave that didn't converge → bare undirty RESOLVED is synthesized by the\n\t\t\t// substrate (D49); nothing to emit here.\n\t\t},\n\t};\n}\n\n// ── Slice 3 — error-handling control (CSP-2.7, D40) ──\n// rescue/catchError ABSORB the source ERROR (errorWhenDepsError:false) and read the error payload\n// from `depTerminal(ctx, 0)` (R-deps-terminal). They set completeWhenDepsComplete:false so a\n// normal source COMPLETE is forwarded explicitly — which ALSO sidesteps B40 (the\n// completeWhenDepsComplete:true × absorbed-errored-dep auto-complete gap): there is no auto-complete\n// to block. valve is a [source, control] gate (state-verb-legitimate control input).\n\n/**\n * rescue (alias `catchError`): replace an upstream ERROR with a recovered value. On source DATA →\n * forward; on source ERROR → emit `recover(err)` as DATA (if `recover` throws, forward THAT as\n * ERROR); on source COMPLETE → COMPLETE. After recovery the source is terminal-errored (dead) so no\n * further values flow — the recovered value is the final cached value (matches the frozen pure-ts\n * reference; it does NOT auto-COMPLETE, RxJS-`catchError(()=>of(x))` divergence, flagged).\n */\nexport function rescue<S>(recover: (err: unknown) => S): Operator<S, S> {\n\treturn {\n\t\tfactory: \"rescue\",\n\t\topts: {\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (b) for (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t} else if (isTerminalError(terminal)) {\n\t\t\t\t// ERROR payload absorbed → recover.\n\t\t\t\ttry {\n\t\t\t\t\tctx.down([[\"DATA\", recover(terminalErrorValue(terminal))]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"rescue threw without a valid error payload\")]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** catchError: RxJS-named alias of {@link rescue}. */\nexport const catchError = rescue;\n\n/** Options for {@link valve}. */\nexport interface ValveOpts {\n\t/**\n\t * Optional AbortController (or a `() => AbortController | undefined` factory): on the control's\n\t * truthy→falsy edge, `valve` calls `controller.abort()` — cancel an in-flight async boundary\n\t * (LLM/fetch) the caller threaded `controller.signal` into. An external-resource cleanup (like\n\t * `ctx.onDeactivation`), NOT an imperative reactive trigger (R-no-imperative).\n\t */\n\tabortInFlight?: AbortController | (() => AbortController | undefined);\n}\n\n/**\n * valve: forward the source's DATA only while `control` (dep 1) is truthy; when closed, stay quiet\n * (undirty RESOLVED). `[source, control]` declared deps + `partial:true` (the control wave can fire\n * before the source ever delivers). `completeWhenDepsComplete:false` — closing the gate (control\n * terminating) does NOT complete the valve; only the SOURCE's terminal (read via\n * `terminalAsRealInput`) is forwarded. The `state`-verb control input is a legitimate external\n * boundary (D4 / D54), not a forbidden imperative trigger.\n */\nexport function valve<S>(opts?: ValveOpts): Operator<S, S> {\n\tconst abortInFlight = opts?.abortInFlight;\n\treturn {\n\t\tfactory: \"valve\",\n\t\topts: { partial: true, completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst ctlBatch = depBatch(ctx, 1);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\t\tconst controlValue = depLatest(ctx, 1) as boolean | undefined;\n\n\t\t\tif (abortInFlight != null) {\n\t\t\t\t// Fire abort on the truthy→falsy edge only (never on activation / no prior state).\n\t\t\t\tconst prev = ctx.state.get<{ ctl: boolean | undefined }>();\n\t\t\t\tif (prev?.ctl === true && !controlValue) {\n\t\t\t\t\tconst c = typeof abortInFlight === \"function\" ? abortInFlight() : abortInFlight;\n\t\t\t\t\tc?.abort();\n\t\t\t\t}\n\t\t\t\tctx.state.set({\n\t\t\t\t\tctl: controlValue === true ? true : controlValue == null ? undefined : false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Source terminal forwarding (control terminal is absorbed by completeWhenDepsComplete:false).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!controlValue) return; // gate closed → quiet (undirty RESOLVED)\n\n\t\t\tif (srcBatch && srcBatch.length > 0) {\n\t\t\t\tfor (const v of srcBatch) ctx.down([[\"DATA\", v]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Gate just opened this wave (control fired, source didn't): re-emit the last source value.\n\t\t\tconst srcLatest = depLatest(ctx, 0);\n\t\t\tif (ctlBatch && ctlBatch.length > 0 && srcLatest !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", srcLatest as S]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * The Graph layer (CSP-2): convenience + inspection entry (D5 / R-graph-role).\n *\n * g.* sugar desugars to dispatcher.register + Node and auto-registers into the graph\n * inspection index (D27: sugar→ctx-fn conversion lives strictly here; the substrate node\n * only ever sees `(ctx)=>void`). The Graph owns naming, describe, mount, and the D30\n * value-level throw→ERROR boundary. The bare node()/dispatcher stay inspection-free\n * (R-node-thin).\n *\n * Canonical authority: ~/src/graphrefly — D3/D5/D27/D30/D36/D37/D39, R-graph-role,\n * R-describe, R-fn-contract, R-edges-derived, R-meta-presentation.\n */\n\nimport { type BatchCtx, batch as batchRun } from \"../batch/batch.js\";\nimport { type Ctx, depCount, depLatest, type NodeFn } from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher } from \"../dispatcher/index.js\";\nimport { NodeCore } from \"../node/core.js\";\nimport {\n\tcheckpointStateOfNode,\n\tgetNodeOwner,\n\tisNodeActiveForRelease,\n\tisNodeRuntimeQuiescentForRelease,\n\tisNodeRuntimeReleased,\n\tNode,\n\ttype NodeOptions,\n\treleaseRuntimeOfNode,\n\tsetNodeOwner,\n\tsetNodeTopologyDepsChangedObserver,\n\tsubscriberCountOfNode,\n\twithEnvironmentDrivers,\n\twithNodeCore,\n} from \"../node/node.js\";\nimport type { NodeVersioningPolicy } from \"../node/versioning.js\";\nimport { errorPayload, messageTier, SENTINEL } from \"../protocol/messages.js\";\nimport {\n\tGRAPH_BLUEPRINT_VERSION,\n\ttype GraphBlueprint,\n\ttype GraphBlueprintOptions,\n\tgraphBlueprintDiagnostics,\n\tnormalizeTopology,\n\tnormalizeTopologyMeta,\n} from \"./blueprint.js\";\nimport {\n\tcheckpointBackendStateOfNode,\n\tcheckpointTerminal,\n\tcheckpointValue,\n\tGRAPH_CHECKPOINT_VERSION,\n\ttype GraphCheckpoint,\n\ttype GraphCheckpointFactory,\n\ttype GraphCheckpointJson,\n\ttype GraphCheckpointNode,\n\ttoCheckpointJson,\n} from \"./checkpoint.js\";\nimport {\n\ttype DescribeEdge,\n\ttype DescribeNode,\n\ttype DescribeOpts,\n\ttype DescribeSnapshot,\n\ttype GraphTopologySnapshot,\n\ttopologyFromDescribe,\n} from \"./describe.js\";\nimport { EnvironmentDrivers } from \"./environment.js\";\nimport type {\n\tNodeProfile,\n\tObserveStream,\n\tProfile,\n\tTopologyEvent,\n\tTopologyStream,\n} from \"./inspect.js\";\nimport { initNodeWithCore, type Operator } from \"./operators.js\";\n\n/** Map a tuple of Nodes to the tuple of their value types (typed value-level fn args). */\ntype DepValues<D extends readonly Node<unknown>[]> = {\n\t[K in keyof D]: D[K] extends Node<infer V> ? V : never;\n};\n\n/** Value-level derived fn: receives dep values, returns the next value (undefined = no emit). */\nexport type DerivedFn<D extends readonly Node<unknown>[], T> = (\n\t...values: DepValues<D>\n) => T | undefined;\n\n/** Value-level effect fn: receives dep values, optionally returns a deactivation cleanup. */\nexport type EffectFn<D extends readonly Node<unknown>[]> = (\n\t...values: DepValues<D>\n\t// biome-ignore lint/suspicious/noConfusingVoidType: effect returns void OR a cleanup fn — the void arm keeps `(v) => { sideEffect(v) }` ergonomic (React EffectCallback idiom); dropping it would force an explicit `return undefined`.\n) => void | (() => void);\n\n/** Sugar options — node options minus graph-owned dispatcher plus naming/meta. */\nexport interface SugarOpts<T = unknown> extends Omit<NodeOptions<T>, \"dispatcher\"> {\n\tname?: string;\n\tmeta?: Record<string, unknown>;\n\t/**\n\t * D95: explicit restorable factory metadata. Static JSON-compatible config may live here;\n\t * reactive options must remain graph deps. Without this, function-backed nodes are local-only.\n\t */\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown };\n}\n\nexport interface GraphOptions {\n\tname?: string;\n\t/** Bind to a dispatcher (default = process-global, D26). */\n\tdispatcher?: Dispatcher;\n\t/** D109 default node runtime versioning policy for graph-owned nodes. Default is nodev0. */\n\tversioning?: NodeVersioningPolicy;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment?: EnvironmentDrivers;\n\t/**\n\t * Turn on the dispatcher profile recorder (D39 / F-PERF default off). NOTE: this\n\t * switches recording on for the WHOLE bound dispatcher (the default is process-global,\n\t * D26) — every graph sharing it then pays the recorder cost. For isolated profiling\n\t * use a dedicated dispatcher: `graph({ dispatcher: new Dispatcher(), profile: true })`.\n\t */\n\tprofile?: boolean;\n}\n\ninterface Entry {\n\tnode: Node<unknown>;\n\tid: string;\n\tname?: string;\n\tfactory: string;\n\tdeps: readonly Node<unknown>[];\n\tmeta?: Record<string, unknown>;\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown };\n}\n\ninterface TopologyObserver {\n\tpath?: string;\n\tsink(event: TopologyEvent): void;\n}\n\ninterface MountedGraph {\n\tat: string;\n\tgraph: Graph;\n\ttopologyUnsub?: () => void;\n}\n\ninterface GraphRestoreRegistrar {\n\tstateNode<T>(id: string, opts?: SugarOpts<T>): StateNode<T>;\n\tnode<T>(\n\t\tid: string,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\tfn: NodeFn | null,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n}\n\nconst restoreRegistrars = new WeakMap<Graph, GraphRestoreRegistrar>();\n\ninterface GraphLifecycleRegistrar {\n\tassertRegisteredNode(node: Node<unknown>, label: string): void;\n\treleaseNodes(nodes: readonly Node<unknown>[], opts?: { reason?: string }): void;\n}\n\nconst lifecycleRegistrars = new WeakMap<Graph, GraphLifecycleRegistrar>();\n\nfunction nodeOwner(n: Node<unknown>): Graph | undefined {\n\treturn getNodeOwner(n) as Graph | undefined;\n}\n\nexport function assertGraphLocalNode(owner: Graph, n: Node<unknown>, label: string): void {\n\tif (isNodeRuntimeReleased(n)) {\n\t\tthrow new Error(`${label} has been released from its graph lifecycle (D122)`);\n\t}\n\tconst existing = nodeOwner(n);\n\tif (existing !== undefined && existing !== owner) {\n\t\tthrow new Error(\n\t\t\t`${label} belongs to a different graph; cross-graph deps require a wire bridge`,\n\t\t);\n\t}\n}\n\n/**\n * A state node (L4-Q1): a manual source whose `.set(v)` is `node.down([[DATA, v]])` sugar.\n * Extends the substrate Node so it is usable as a dep AND carries the graph-layer `.set`.\n */\nexport class StateNode<T> extends Node<T> {\n\tset(v: T): void {\n\t\tthis.down([[\"DATA\", v]]);\n\t}\n}\n\nexport interface TopologyGroupOptions {\n\t/** Optional inspection/release reason label for this graph-owned topology group. */\n\tname?: string;\n}\n\nexport interface TopologyGroupReleaseOptions {\n\t/** Optional diagnostic reason. No protocol/control messages are synthesized. */\n\treason?: string;\n}\n\n/**\n * Graph-owned D152 release group: a label over ordinary graph-registered nodes.\n * The graph registry remains the source of truth; helper-local membership is only\n * a memo for atomic quiescent release.\n */\nexport interface TopologyGroup {\n\treadonly name?: string;\n\treadonly released: boolean;\n\tadd<T extends Node<unknown>>(node: T): T;\n\tnode<T = unknown>(\n\t\tdeps?: readonly Node<unknown>[],\n\t\tfn?: NodeFn | null,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n\tstate<T>(initial: T, opts?: SugarOpts<T>): StateNode<T>;\n\tproducer<T = unknown>(fn: NodeFn, opts?: SugarOpts<T>): Node<T>;\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts?: SugarOpts<T>,\n\t): Node<T>;\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts?: SugarOpts<void>,\n\t): Node<void>;\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts?: SugarOpts<TOut>,\n\t): Node<TOut>;\n\trelease(opts?: TopologyGroupReleaseOptions): void;\n}\n\nclass GraphTopologyGroup implements TopologyGroup {\n\treadonly name?: string;\n\tprivate readonly _graph: Graph;\n\tprivate readonly _members: Node<unknown>[] = [];\n\tprivate _released = false;\n\n\tconstructor(graph: Graph, opts: TopologyGroupOptions = {}) {\n\t\tthis._graph = graph;\n\t\tthis.name = opts.name;\n\t}\n\n\tget released(): boolean {\n\t\treturn this._released;\n\t}\n\n\tadd<T extends Node<unknown>>(node: T): T {\n\t\tthis._assertLive();\n\t\tconst lifecycle = lifecycleRegistrars.get(this._graph);\n\t\tif (lifecycle === undefined) throw new Error(\"topologyGroup: graph lifecycle unavailable\");\n\t\tlifecycle.assertRegisteredNode(node, `topology group '${this.name ?? \"group\"}' member`);\n\t\tif (!this._members.includes(node)) this._members.push(node);\n\t\treturn node;\n\t}\n\n\tnode<T = unknown>(\n\t\tdeps: readonly Node<unknown>[] = [],\n\t\tfn: NodeFn | null = null,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.node(deps, fn, opts));\n\t}\n\n\tstate<T>(initial: T, opts: SugarOpts<T> = {}): StateNode<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.state(initial, opts));\n\t}\n\n\tproducer<T = unknown>(fn: NodeFn, opts: SugarOpts<T> = {}): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.producer(fn, opts));\n\t}\n\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.derived(deps, fn, opts));\n\t}\n\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts: SugarOpts<void> = {},\n\t): Node<void> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.effect(deps, fn, opts));\n\t}\n\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts: SugarOpts<TOut> = {},\n\t): Node<TOut> {\n\t\tthis._assertLive();\n\t\treturn this.add(this._graph.initNode(op, deps, opts));\n\t}\n\n\trelease(opts: TopologyGroupReleaseOptions = {}): void {\n\t\tif (this._released) return;\n\t\tconst lifecycle = lifecycleRegistrars.get(this._graph);\n\t\tif (lifecycle === undefined) throw new Error(\"topologyGroup: graph lifecycle unavailable\");\n\t\tlifecycle.releaseNodes([...this._members], {\n\t\t\treason: opts.reason ?? this.name,\n\t\t});\n\t\tthis._members.length = 0;\n\t\tthis._released = true;\n\t}\n\n\tprivate _assertLive(): void {\n\t\tif (this._released) {\n\t\t\tthrow new Error(`topology group '${this.name ?? \"group\"}' has been released (D152)`);\n\t\t}\n\t}\n}\n\nexport class Graph {\n\treadonly name?: string;\n\tprivate readonly _dispatcher: Dispatcher;\n\tprivate readonly _versioning: NodeVersioningPolicy | undefined;\n\tprivate readonly _environment: EnvironmentDrivers;\n\tprivate readonly _core = new NodeCore();\n\tprivate readonly _entries = new Map<Node<unknown>, Entry>();\n\tprivate readonly _byId = new Map<string, Node<unknown>>();\n\tprivate readonly _retiredIds = new Set<string>();\n\tprivate readonly _mounts: MountedGraph[] = [];\n\tprivate _seq = 0;\n\tprivate _clock = 0; // graph-local monotonic clock for observe seq (D26)\n\tprivate _topologyObserverSeq = 0;\n\tprivate readonly _topologyObservers = new Map<number, TopologyObserver>();\n\tprivate _topologyDelivering = false;\n\tprivate readonly _topologyQueue: TopologyEvent[] = [];\n\t// D51: stable synthetic ids for unregistered live deps (runtime *Map inners) auto-discovered by\n\t// describe(). WeakMap-cached so successive describes agree + the inner's id is freed when it is.\n\t// A dedicated counter (NOT _seq) so a describe() call never perturbs registered-node id numbering.\n\tprivate _synthSeq = 0;\n\tprivate readonly _synthIds = new WeakMap<Node<unknown>, string>();\n\n\tconstructor(opts: GraphOptions = {}) {\n\t\tthis.name = opts.name;\n\t\tthis._dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tthis._versioning = opts.versioning;\n\t\tthis._environment = opts.environment ?? EnvironmentDrivers.empty();\n\t\tif (opts.profile) this._dispatcher.setRecording(true);\n\t\trestoreRegistrars.set(this, {\n\t\t\tstateNode: <T = unknown>(id: string, stateOpts: SugarOpts<T> = {}) => {\n\t\t\t\tconst n = this._construct(() => new StateNode<T>([], null, this._nodeOpts(stateOpts)));\n\t\t\t\tthis._addWithId(n, \"state\", [], stateOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t\tnode: <T = unknown>(\n\t\t\t\tid: string,\n\t\t\t\tfactory: string,\n\t\t\t\tdeps: readonly Node<unknown>[],\n\t\t\t\tfn: NodeFn | null,\n\t\t\t\tnodeOpts: SugarOpts<T> = {},\n\t\t\t) => {\n\t\t\t\tthis._assertDepsLocal(deps, `dep of restored '${id}'`);\n\t\t\t\tconst n = this._construct(() => new Node<T>([...deps], fn, this._nodeOpts(nodeOpts)));\n\t\t\t\tthis._addWithId(n, factory, deps, nodeOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t});\n\t\tlifecycleRegistrars.set(this, {\n\t\t\tassertRegisteredNode: (node, label) => this._assertRegisteredNode(node, label),\n\t\t\treleaseNodes: (nodes, releaseOpts) => this._releaseNodes(nodes, releaseOpts),\n\t\t});\n\t}\n\n\t// ── registration / inspection index ──\n\n\tprivate _add<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t): Node<T> {\n\t\tconst id = opts.name ?? `${factory}#${this._seq++}`;\n\t\treturn this._addWithId(n, factory, deps, opts, id);\n\t}\n\n\tprivate _addWithId<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t\tid: string,\n\t): Node<T> {\n\t\tassertGraphLocalNode(this, n as Node<unknown>, `graph node '${opts.name ?? factory}'`);\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, `dep of '${opts.name ?? factory}'`);\n\t\tif (this._byId.has(id)) {\n\t\t\tthrow new Error(`graph: duplicate node id '${id}' (checkpoint/describe ids must be unique)`);\n\t\t}\n\t\tif (this._retiredIds.has(id)) {\n\t\t\tthrow new Error(`graph: node id '${id}' was released and cannot be reused (D152/D153)`);\n\t\t}\n\t\tconst meta =\n\t\t\topts.meta === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (normalizeTopologyMeta(opts.meta, `graph node '${id}' meta`) as Record<string, unknown>);\n\t\tthis._entries.set(n as Node<unknown>, {\n\t\t\tnode: n as Node<unknown>,\n\t\t\tid,\n\t\t\tname: opts.name,\n\t\t\tfactory,\n\t\t\tdeps,\n\t\t\tmeta,\n\t\t\trestore: opts.restore,\n\t\t});\n\t\tsetNodeOwner(n as Node<unknown>, this);\n\t\tthis._byId.set(id, n as Node<unknown>);\n\t\tsetNodeTopologyDepsChangedObserver(n as Node<unknown>, (_node, prevDeps, nextDeps) => {\n\t\t\tthis._emitTopologyDepsChanged(n as Node<unknown>, prevDeps, nextDeps);\n\t\t});\n\t\tconst seqMatch = /#(\\d+)$/.exec(id);\n\t\tif (seqMatch) this._seq = Math.max(this._seq, Number(seqMatch[1]) + 1);\n\t\tthis._emitTopologyNodeRegistered(n as Node<unknown>);\n\t\treturn n;\n\t}\n\n\tprivate _assertDepsLocal(deps: readonly Node<unknown>[], label: string): void {\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, label);\n\t}\n\n\tprivate _assertRegisteredNode(node: Node<unknown>, label: string): void {\n\t\tassertGraphLocalNode(this, node, label);\n\t\tif (!this._entries.has(node)) {\n\t\t\tthrow new Error(`${label} is not a registered graph node (D152)`);\n\t\t}\n\t}\n\n\tprivate _nodeOpts<T>(opts: SugarOpts<T>): NodeOptions<T> {\n\t\tif (opts.meta !== undefined) {\n\t\t\tnormalizeTopologyMeta(opts.meta, `graph node '${opts.name ?? opts.factory ?? \"node\"}' meta`);\n\t\t}\n\t\t// strip graph-only fields; inject the bound dispatcher\n\t\tconst { name: _n, meta: _m, restore: _r, ...rest } = opts;\n\t\treturn {\n\t\t\t...rest,\n\t\t\tversioning: rest.versioning ?? this._versioning,\n\t\t\tdispatcher: this._dispatcher,\n\t\t};\n\t}\n\n\tprivate _construct<TNode extends Node<unknown>>(create: () => TNode): TNode {\n\t\treturn withEnvironmentDrivers(this._environment, () => withNodeCore(this._core, create));\n\t}\n\n\t/** Look up a registered node by its id. */\n\tfind(id: string): Node<unknown> | undefined {\n\t\tconst local = this._byId.get(id);\n\t\tif (local !== undefined) return local;\n\t\tconst separator = id.indexOf(\"::\");\n\t\tif (separator < 0) return undefined;\n\t\tconst mountPath = id.slice(0, separator);\n\t\tconst childPath = id.slice(separator + 2);\n\t\treturn this._mounts.find((mount) => mount.at === mountPath)?.graph.find(childPath);\n\t}\n\n\tprivate _releaseNodes(nodes: readonly Node<unknown>[], _opts: { reason?: string } = {}): void {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst entries: Array<{ node: Node<unknown>; entry: Entry }> = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (seen.has(node)) continue;\n\t\t\tseen.add(node);\n\t\t\tconst entry = this._entries.get(node);\n\t\t\tif (entry === undefined) continue;\n\t\t\tentries.push({ node, entry });\n\t\t}\n\t\tconst releaseSet = new Set(entries.map(({ node }) => node));\n\t\tconst releaseIds = new Map(entries.map(({ node, entry }) => [node, entry.id] as const));\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tif (releaseSet.has(entry.node)) continue;\n\t\t\tfor (const dep of entry.node.deps) {\n\t\t\t\tif (!releaseSet.has(dep)) continue;\n\t\t\t\tconst depId = releaseIds.get(dep) ?? dep.name ?? dep.factory ?? \"released node\";\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still depends on '${depId}' (D122)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const { node, entry } of entries) {\n\t\t\tif (!isNodeRuntimeQuiescentForRelease(node)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' is not runtime-quiescent (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet internalSubscribers = 0;\n\t\t\tfor (const { node: dependent } of entries) {\n\t\t\t\tif (dependent === node || !isNodeActiveForRelease(dependent)) continue;\n\t\t\t\tfor (const dep of dependent.deps) {\n\t\t\t\t\tif (dep === node) internalSubscribers += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (subscriberCountOfNode(node) > internalSubscribers) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still has live subscribers (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst releasedEvents =\n\t\t\tthis._topologyObservers.size === 0\n\t\t\t\t? []\n\t\t\t\t: entries.map(({ node, entry }) => ({\n\t\t\t\t\t\tpath: entry.id,\n\t\t\t\t\t\tfactory: entry.factory,\n\t\t\t\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\t\t\t}));\n\t\tfor (const { node, entry } of entries) {\n\t\t\tthis._entries.delete(node);\n\t\t\tthis._byId.delete(entry.id);\n\t\t\tthis._retiredIds.add(entry.id);\n\t\t}\n\t\tlet releaseError: unknown;\n\t\tfor (const { node } of entries) {\n\t\t\ttry {\n\t\t\t\treleaseRuntimeOfNode(node);\n\t\t\t} catch (error) {\n\t\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t\t}\n\t\t}\n\t\tfor (const event of releasedEvents) this._emitTopologyNodeReleased(event);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\t// ── 8 verbs (core: node/state/batch + sugar: producer/derived/effect/mount) ──\n\n\t/** ctx-level power surface: a raw `(ctx)=>void` fn (or a passthrough/state when null). */\n\tnode<T = unknown>(\n\t\tdeps: readonly Node<unknown>[] = [],\n\t\tfn: NodeFn | null = null,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"node\"}'`);\n\t\tconst n = this._construct(() => new Node<T>(deps as Node<unknown>[], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, opts.factory ?? \"node\", deps, opts);\n\t}\n\n\t/** A manual source with `.set(v)` (L4-Q1). */\n\tstate<T>(initial: T, opts: SugarOpts<T> = {}): StateNode<T> {\n\t\tconst n = this._construct(\n\t\t\t() => new StateNode<T>([], null, { ...this._nodeOpts(opts), initial }),\n\t\t);\n\t\tthis._add(n, \"state\", [], opts);\n\t\treturn n;\n\t}\n\n\t/** ctx-level depless source; its fn runs on activation (R-rom-ram). */\n\tproducer<T = unknown>(fn: NodeFn, opts: SugarOpts<T> = {}): Node<T> {\n\t\tconst n = this._construct(() => new Node<T>([], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"producer\", [], opts);\n\t}\n\n\t/** value-level pure transform: deps → value (D27 wrapped; D30 throw→ERROR). */\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"derived\"}'`);\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst result = fn(...args);\n\t\t\t\tif (result !== undefined) ctx.down([[\"DATA\", result]]);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"derived threw without a valid error payload\")]]); // D30: value-level throw → graph-layer ERROR\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<T>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"derived\", deps, opts);\n\t}\n\n\t/** value-level sink: deps → effect; return value (a fn) becomes onDeactivation (D28). */\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts: SugarOpts<void> = {},\n\t): Node<void> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"effect\"}'`);\n\t\t// effect cleanup = deactivation-only (D28 / Flag 3): the LATEST returned cleanup\n\t\t// fires ONCE when the effect deactivates (not between re-runs — onRerun was cut).\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification / C-14): the substrate clears\n\t\t// the hook list before EACH fn run, so the effect re-registers its returned cleanup\n\t\t// every run — only the latest run's registration is live (or none, if the latest run\n\t\t// returned void). No st.registered/ctx.state bookkeeping; re-registering every run is\n\t\t// safe (the per-run clear prevents accumulation).\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst cleanup = fn(...args);\n\t\t\t\tif (typeof cleanup === \"function\") ctx.onDeactivation(cleanup);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"effect threw without a valid error payload\")]]);\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<void>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"effect\", deps, opts);\n\t}\n\n\t/** Declarative batch (D12): one wave, success→commit / throw→rollback. */\n\tbatch<T>(fn: (bctx: BatchCtx) => T): T {\n\t\treturn batchRun(fn);\n\t}\n\n\t/** Embed a child graph addressable under `at` (R-mount; mount has no deps). */\n\tmount(child: Graph, opts: { at: string }): void {\n\t\tconst mount = { at: opts.at, graph: child };\n\t\tthis._mounts.push(mount);\n\t\tif (this._topologyObservers.size > 0) this._ensureMountedTopologyForwarders();\n\t\tthis._emitTopologyMountChanged(opts.at);\n\t}\n\n\t// ── operator funnel (D43): instantiate any free-standing Operator (node sugar, D6/L1.5) ──\n\t// g.initNode is the single graph-bound entry for the whole operator/source catalog (D40):\n\t// it delegates to the FREE initNode (graph/operators.ts — the D30 throw→ERROR boundary +\n\t// dispatcher binding live there) and records the operator's REAL factory name in the\n\t// inspection index (_add) so describe shows it (D6/R-describe) while the node stays thin\n\t// (R-node-thin). Operators are free-standing factory definitions (graph/operators.ts,\n\t// graph/sources.ts) usable bare via the free initNode(); this funnel is the inspectable\n\t// path. Replaces the per-operator methods.\n\n\t/**\n\t * Instantiate an operator (or source) factory as a registered graph node. `deps` are\n\t * type-checked against the operator's input element type; the output type flows from the\n\t * operator. A source is a depless operator — pass `[]`. Caller `opts` (name/meta/behavioral\n\t * overrides) win over the operator's baked-in `opts`.\n\t */\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts: SugarOpts<TOut> = {},\n\t): Node<TOut> {\n\t\tconst entryOpts =\n\t\t\top.restore !== undefined && !(\"restore\" in opts) ? { ...opts, restore: op.restore } : opts;\n\t\tfor (const dep of deps as readonly Node<unknown>[])\n\t\t\tassertGraphLocalNode(this, dep, `dep of '${entryOpts.name ?? op.factory}'`);\n\t\t// Node<T> is invariant (T appears in NodeOptions.initial); widen the typed deps to the\n\t\t// erased Node surface the free initNode / _add accept (same cast the old methods used).\n\t\tconst erased = deps as readonly Node<unknown>[];\n\t\tconst n = withEnvironmentDrivers(this._environment, () =>\n\t\t\tinitNodeWithCore(this._core, op, erased, this._nodeOpts(entryOpts)),\n\t\t);\n\t\treturn this._add(n, op.factory, erased, entryOpts);\n\t}\n\n\t/**\n\t * Graph-owned activation root for internal helper nodes. This is the sanctioned keepalive shape:\n\t * a graph, not a helper closure, owns the subscription and returns the release handle.\n\t */\n\tretain<T>(node: Node<T>, opts: { reason?: string } = {}): () => void {\n\t\tassertGraphLocalNode(this, node as Node<unknown>, opts.reason ?? \"retained node\");\n\t\treturn node.subscribe(() => {});\n\t}\n\n\t/**\n\t * D152 graph-owned topology/release group. Members are ordinary registered graph nodes;\n\t * release is quiescent-only and removes ids atomically without synthesizing protocol messages.\n\t */\n\ttopologyGroup(opts: TopologyGroupOptions = {}): TopologyGroup {\n\t\treturn new GraphTopologyGroup(this, opts);\n\t}\n\n\t// ── inspection: describe / observe / profile (D39) ──\n\n\t/** Live point-in-time structure snapshot (R-describe / D39 / D51). `_prefix` carries the mount path. */\n\tdescribe(opts: DescribeOpts = {}, _prefix = \"\"): DescribeSnapshot {\n\t\t// D51: edges derive from each node's CURRENT/LIVE deps (entry.node.deps, NOT the\n\t\t// construction-time entry.deps), so a rewire (C-8 immediate / C-11 *Map deferred) is\n\t\t// reflected and every edge is a real current subscription (D3). A live dep absent from this\n\t\t// graph's index (a runtime *Map inner / bare fromAny node) is AUTO-DISCOVERED as a snapshot\n\t\t// node with a synthesized stable id (B2). B38 extends this to transitive live-reachability:\n\t\t// discovered unregistered nodes are recursively expanded through their own live deps.\n\t\tconst discovered = new Map<Node<unknown>, string>(); // unregistered live dep → synth local id\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\t// unregistered: a stable synthetic id, cached so successive describes + both call sites\n\t\t\t// agree; the `~` prefix can't collide with a registered name or `factory#seq`.\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\t// the `~` prefix avoids the registered `name`/`factory#seq` space; guard the\n\t\t\t\t// pathological case of a user node literally named `~factory#n` (bump until free).\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: DescribeNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\t// pass 1: registered nodes, reading LIVE deps (localId records any unregistered inner).\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid,\n\t\t\t\tfactory: entry.factory,\n\t\t\t\tstatus: entry.node.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (entry.name !== undefined) dnode.name = entry.name;\n\t\t\tif (entry.node.cache !== undefined) dnode.value = entry.node.cache; // absent = SENTINEL\n\t\t\tif (entry.node.version !== undefined) dnode.version = entry.node.version;\n\t\t\tif (entry.meta !== undefined) dnode.meta = entry.meta;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\t// pass 2: recursively emit auto-discovered unregistered nodes (D51+B38). localId() may add\n\t\t// further unregistered deps to `discovered` while this loop runs; a visited set keeps each\n\t\t// discovered node emitted once (stable ids via _synthIds).\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid: `${_prefix}${sid}`,\n\t\t\t\tfactory: inner.factory ?? \"?\",\n\t\t\t\tstatus: inner.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (inner.cache !== undefined) dnode.value = inner.cache;\n\t\t\tif (inner.version !== undefined) dnode.version = inner.version;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: dnode.id });\n\t\t}\n\t\tconst snap: DescribeSnapshot = { nodes, edges };\n\t\tif (this.name !== undefined) snap.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tsnap.subgraphs = this._mounts.map((m) => m.graph.describe({}, `${_prefix}${m.at}::`));\n\t\t}\n\t\treturn opts.explain ? explainSubset(snap, opts.explain) : snap;\n\t}\n\n\t/**\n\t * D173 pure-structure topology snapshot over the same live truth source as describe().\n\t * Runtime status/value/version remain on describe(); blueprint metadata is a later envelope.\n\t */\n\ttopology(): GraphTopologySnapshot {\n\t\treturn topologyFromDescribe(this.describe());\n\t}\n\n\t/**\n\t * D177 synchronous audit/collaboration envelope over the pure topology snapshot.\n\t * Hashing and environment provenance enrichment stay in pure helpers outside Graph core.\n\t */\n\tblueprint(opts: GraphBlueprintOptions = {}): GraphBlueprint {\n\t\tconst topology = normalizeTopology(this.topology());\n\t\tconst out: GraphBlueprint = {\n\t\t\tversion: GRAPH_BLUEPRINT_VERSION,\n\t\t\ttopology,\n\t\t};\n\t\tif (opts.diagnostics) {\n\t\t\t(out as { diagnostics?: ReturnType<typeof graphBlueprintDiagnostics> }).diagnostics =\n\t\t\t\tgraphBlueprintDiagnostics(topology);\n\t\t}\n\t\tif (opts.provenance !== undefined) {\n\t\t\t(out as { provenance?: GraphBlueprint[\"provenance\"] }).provenance = normalizeTopologyMeta(\n\t\t\t\topts.provenance,\n\t\t\t\t\"graph blueprint provenance\",\n\t\t\t\t\"provenance\",\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _observeTargets(path?: string): Array<[string, Node<unknown>]> {\n\t\tconst all: Array<[string, Node<unknown>]> = [...this._entries.values()].map((e) => [\n\t\t\te.id,\n\t\t\te.node,\n\t\t]);\n\t\tif (path === undefined) return all; // whole graph\n\t\tconst exact = this._byId.get(path);\n\t\tif (exact) return [[path, exact]]; // single node\n\t\treturn all.filter(([id]) => id.startsWith(`${path}::`)); // subtree (mount-aware :: boundary, QA A-1)\n\t}\n\n\t/**\n\t * observe(path?) = read-only enveloped EGRESS (R-observe / D39). NOT a graph node — it\n\t * taps the target node(s) via subscribe and forwards each Message as an ObserveEvent.\n\t * No path = whole graph; an exact id = a single node; otherwise a `::`-prefix subtree.\n\t */\n\t// NOTE (R-observe/D19): observe is a real, lazily-ACTIVATING subscriber — observing a\n\t// cold node runs its fn (and activates upstream); whole-graph observe() activates the\n\t// graph. \"Read-only\" means it never emits/mutates node state, NOT that it avoids\n\t// activation. Use it knowing inspection of a cold graph wakes it.\n\tobserve(path?: string): ObserveStream {\n\t\tconst targets = this._observeTargets(path);\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst unsubs = targets.map(([id, n]) =>\n\t\t\t\t\tn.subscribe((msg) => {\n\t\t\t\t\t\tsink({ path: id, msg, tier: messageTier(msg[0]), seq: this._clock++ });\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};\n\t}\n\n\t/**\n\t * D145 observeTopology(path?) = read-only graph lifecycle egress over the existing\n\t * graph registry. It is not a graph node, does not subscribe to nodes, and emits no DATA.\n\t */\n\tobserveTopology(path?: string): TopologyStream {\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst id = this._topologyObserverSeq++;\n\t\t\t\tthis._topologyObservers.set(id, { path, sink });\n\t\t\t\tthis._ensureMountedTopologyForwarders();\n\t\t\t\treturn () => {\n\t\t\t\t\tthis._topologyObservers.delete(id);\n\t\t\t\t\tif (this._topologyObservers.size === 0) this._releaseMountedTopologyForwarders();\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _idForTopologyNode(n: Node<unknown>): string {\n\t\tconst e = this._entries.get(n);\n\t\tif (e) return e.id;\n\t\tlet sid = this._synthIds.get(n);\n\t\tif (sid === undefined) {\n\t\t\tdo {\n\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t} while (this._byId.has(sid));\n\t\t\tthis._synthIds.set(n, sid);\n\t\t}\n\t\treturn sid;\n\t}\n\n\tprivate _topologyDeps(deps: readonly Node<unknown>[]): string[] {\n\t\treturn deps.map((dep) => this._idForTopologyNode(dep));\n\t}\n\n\tprivate _emitTopologyNodeRegistered(node: Node<unknown>): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-registered\",\n\t\t\tpath: entry.id,\n\t\t\tfactory: entry.factory,\n\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyDepsChanged(\n\t\tnode: Node<unknown>,\n\t\tprevDeps: readonly Node<unknown>[],\n\t\tnextDeps: readonly Node<unknown>[],\n\t): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"deps-changed\",\n\t\t\tpath: entry.id,\n\t\t\tprevDeps: this._topologyDeps(prevDeps),\n\t\t\tdeps: this._topologyDeps(nextDeps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyNodeReleased(event: {\n\t\tpath: string;\n\t\tfactory: string;\n\t\tdeps: readonly string[];\n\t}): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-released\",\n\t\t\tpath: event.path,\n\t\t\tfactory: event.factory,\n\t\t\tdeps: [...event.deps],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyMountChanged(path: string): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"mount-changed\",\n\t\t\tpath,\n\t\t\tfactory: \"mount\",\n\t\t\tdeps: [],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _ensureMountedTopologyForwarders(): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tfor (const mount of this._mounts) {\n\t\t\tif (mount.topologyUnsub !== undefined) continue;\n\t\t\tconst mountPath = mount.at;\n\t\t\tmount.topologyUnsub = mount.graph.observeTopology().subscribe((event) => {\n\t\t\t\tthis._emitMountedTopologyEvent(mountPath, event);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate _releaseMountedTopologyForwarders(): void {\n\t\tfor (const mount of this._mounts) {\n\t\t\tmount.topologyUnsub?.();\n\t\t\tmount.topologyUnsub = undefined;\n\t\t}\n\t}\n\n\tprivate _emitMountedTopologyEvent(mountPath: string, event: TopologyEvent): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: event.kind,\n\t\t\tpath: prefixTopologyPath(mountPath, event.path),\n\t\t\tdeps: event.deps.map((dep) => prefixTopologyPath(mountPath, dep)),\n\t\t\t...(event.prevDeps !== undefined\n\t\t\t\t? { prevDeps: event.prevDeps.map((dep) => prefixTopologyPath(mountPath, dep)) }\n\t\t\t\t: {}),\n\t\t\t...(event.factory !== undefined ? { factory: event.factory } : {}),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyEvent(event: TopologyEvent): void {\n\t\tif (this._topologyDelivering) {\n\t\t\tthis._topologyQueue.push(event);\n\t\t\treturn;\n\t\t}\n\t\tthis._topologyDelivering = true;\n\t\ttry {\n\t\t\tlet current: TopologyEvent | undefined = event;\n\t\t\twhile (current !== undefined) {\n\t\t\t\tconst observers = [...this._topologyObservers.entries()];\n\t\t\t\tfor (const [id, observer] of observers) {\n\t\t\t\t\tif (this._topologyObservers.get(id) !== observer) continue;\n\t\t\t\t\tif (observer.path !== undefined && !topologyPathMatches(current.path, observer.path))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tobserver.sink(cloneTopologyEvent(current));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// D145 egress is read-only inspection; observer failure must not veto a\n\t\t\t\t\t\t// graph registry/rewire mutation that already committed.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = this._topologyQueue.shift();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._topologyDelivering = false;\n\t\t}\n\t}\n\n\t/**\n\t * profile() = accumulated-counter snapshot (R-profile / D39). invokes + duration are\n\t * dispatcher-backed (the invoke funnel, F-DISPATCH-ALL) — counters never live on the\n\t * thin node (R-node-thin). Requires `graph({ profile: true })` (opt-in, F-PERF).\n\t */\n\tprofile(): Profile {\n\t\tconst nodes: Record<string, NodeProfile> = {};\n\t\tlet totalInvokes = 0;\n\t\tfor (const e of this._entries.values()) {\n\t\t\tconst h = e.node.handle;\n\t\t\tconst stat = h ? this._dispatcher.statFor(h) : undefined;\n\t\t\tconst invokes = stat?.invokes ?? 0;\n\t\t\tnodes[e.id] = {\n\t\t\t\tinvokes,\n\t\t\t\ttotalDurationNs: stat?.totalDurationNs ?? 0,\n\t\t\t\tlastDurationNs: stat?.lastDurationNs ?? 0,\n\t\t\t\tstatus: e.node.status,\n\t\t\t};\n\t\t\t// graph-scoped (QA D-2): sum THIS graph's nodes, NOT the dispatcher-global\n\t\t\t// counter (which would leak invokes from other graphs sharing the dispatcher).\n\t\t\ttotalInvokes += invokes;\n\t\t}\n\t\treturn { totalInvokes, nodes };\n\t}\n\n\t/** Versioned graph lifecycle checkpoint (R-snapshot / D83 / D90). Pure capture, no storage I/O. */\n\tcheckpoint(): GraphCheckpoint {\n\t\treturn this._checkpoint(\"\", new WeakSet());\n\t}\n\n\tprivate _checkpoint(_prefix: string, stack: WeakSet<Graph>): GraphCheckpoint {\n\t\tif (stack.has(this)) {\n\t\t\tthrow new Error(\"checkpoint: cyclic graph mount detected\");\n\t\t}\n\t\tstack.add(this);\n\t\tconst discovered = new Map<Node<unknown>, string>();\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: GraphCheckpointNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(entry.node, id, {\n\t\t\t\t\tname: entry.name,\n\t\t\t\t\tfactory: checkpointFactory(entry.factory, entry.node, false, entry.restore, entry.meta),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst id = `${_prefix}${sid}`;\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(inner, id, {\n\t\t\t\t\tfactory: checkpointFactory(inner.factory ?? \"?\", inner, true),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst checkpoint: GraphCheckpoint = {\n\t\t\tversion: GRAPH_CHECKPOINT_VERSION,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t};\n\t\tif (this.name !== undefined) checkpoint.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tcheckpoint.mounts = this._mounts.map((m) => ({\n\t\t\t\tat: m.at,\n\t\t\t\tcheckpoint: m.graph._checkpoint(\"\", stack),\n\t\t\t}));\n\t\t}\n\t\tstack.delete(this);\n\t\treturn toCheckpointJson(checkpoint, \"checkpoint\") as unknown as GraphCheckpoint;\n\t}\n\n\tprivate _checkpointNode(\n\t\tnode: Node<unknown>,\n\t\tid: string,\n\t\topts: {\n\t\t\tname?: string;\n\t\t\tfactory: GraphCheckpointFactory;\n\t\t\tdeps: string[];\n\t\t\tmeta?: Record<string, unknown>;\n\t\t},\n\t): GraphCheckpointNode {\n\t\tconst state = checkpointStateOfNode(node);\n\t\tassertCheckpointQuiescentStatus(node.status, id, \"checkpoint\");\n\t\tconst nonAuthoritativeCollectionHelper = isNonAuthoritativeCollectionHelperMeta(opts.meta);\n\t\tconst out: GraphCheckpointNode = {\n\t\t\tid,\n\t\t\tfactory: opts.factory,\n\t\t\tstatus: node.status,\n\t\t\tdeps: opts.deps,\n\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t: checkpointValue(state.cache, state.hasData, `${id}.value`),\n\t\t\tterminal: checkpointTerminal(state.terminal, `${id}.terminal`),\n\t\t\tlifecycle: { activated: state.activated, hasCalledFnOnce: state.hasCalledFnOnce },\n\t\t\tctxState: {\n\t\t\t\tpersist: state.ctxState.persist,\n\t\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t\t: checkpointValue(\n\t\t\t\t\t\t\tstate.ctxState.value,\n\t\t\t\t\t\t\tstate.ctxState.value !== SENTINEL,\n\t\t\t\t\t\t\t`${id}.ctxState`,\n\t\t\t\t\t\t),\n\t\t\t},\n\t\t};\n\t\tif (opts.name !== undefined) out.name = opts.name;\n\t\tconst backendState = checkpointBackendStateOfNode(node, `${id}.backendState`);\n\t\tif (backendState !== undefined) out.backendState = backendState;\n\t\tif (state.version !== undefined) out.version = state.version;\n\t\tif (opts.meta !== undefined)\n\t\t\tout.meta = toCheckpointJson(opts.meta, `${id}.meta`) as {\n\t\t\t\t[key: string]: GraphCheckpointJson;\n\t\t\t};\n\t\treturn out;\n\t}\n}\n\nfunction isNonAuthoritativeCollectionHelperMeta(\n\tmeta: Record<string, unknown> | undefined,\n): boolean {\n\treturn (\n\t\tmeta?.kind === \"collection_delta\" ||\n\t\tmeta?.kind === \"collection_intent\" ||\n\t\tmeta?.kind === \"collection_policy_apply\" ||\n\t\tmeta?.kind === \"collection_snapshot\" ||\n\t\tmeta?.kind === \"collection_snapshot_prep\"\n\t);\n}\n\nfunction assertCheckpointQuiescentStatus(status: string, id: string, op: string): void {\n\tif (status === \"pending\" || status === \"dirty\") {\n\t\tthrow new Error(\n\t\t\t`${op}: node '${id}' has non-quiescent status '${status}' that cannot be checkpoint-restored yet`,\n\t\t);\n\t}\n}\n\nfunction topologyPathMatches(eventPath: string, path: string): boolean {\n\treturn eventPath === path || eventPath.startsWith(`${path}::`);\n}\n\nfunction prefixTopologyPath(prefix: string, path: string): string {\n\treturn `${prefix}::${path}`;\n}\n\nfunction cloneTopologyEvent(event: TopologyEvent): TopologyEvent {\n\tconst deps = Object.freeze([...event.deps]);\n\tconst prevDeps = event.prevDeps === undefined ? undefined : Object.freeze([...event.prevDeps]);\n\treturn Object.freeze({\n\t\tkind: event.kind,\n\t\tpath: event.path,\n\t\tdeps,\n\t\t...(prevDeps !== undefined ? { prevDeps } : {}),\n\t\t...(event.factory !== undefined ? { factory: event.factory } : {}),\n\t\tseq: event.seq,\n\t});\n}\n\nfunction checkpointFactory(\n\tname: string,\n\tnode: Node<unknown>,\n\tunregistered: boolean,\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown },\n\tmeta?: Record<string, unknown>,\n): GraphCheckpointFactory {\n\tconst state = checkpointStateOfNode(node);\n\tif (unregistered) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"node is an unregistered live dependency auto-discovered from topology\",\n\t\t};\n\t}\n\tif (\n\t\trestore === undefined &&\n\t\ttypeof meta?.kind === \"string\" &&\n\t\tmeta.kind.startsWith(\"collection_\")\n\t) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"collection helper node has no backend checkpoint restore metadata\",\n\t\t};\n\t}\n\tif (restore !== undefined) {\n\t\tconst out: GraphCheckpointFactory = {\n\t\t\tkind: \"registry-ref\",\n\t\t\tref: toCheckpointJson(restore.ref, `${name}.factory.ref`) as string,\n\t\t};\n\t\tif (restore.config !== undefined)\n\t\t\tout.config = toCheckpointJson(restore.config, `${name}.factory.config`);\n\t\tif (restore.configVersion !== undefined)\n\t\t\tout.configVersion = toCheckpointJson(restore.configVersion, `${name}.factory.configVersion`);\n\t\treturn out;\n\t}\n\tif (state.handle !== null) {\n\t\treturn {\n\t\t\tkind: \"local-only\",\n\t\t\tname,\n\t\t\treason: \"node uses a function body; first-cut checkpoints do not serialize local functions\",\n\t\t};\n\t}\n\treturn { kind: \"registry-ref\", ref: name };\n}\n\n/** Filter a snapshot to the causal chain from→to (forward-reachable(from) ∩ back-reachable(to)). */\nfunction explainSubset(\n\tsnap: DescribeSnapshot,\n\tchain: { from: string; to: string },\n): DescribeSnapshot {\n\tconst fwd = new Map<string, string[]>();\n\tconst rev = new Map<string, string[]>();\n\tconst push = (map: Map<string, string[]>, k: string, v: string): void => {\n\t\tconst a = map.get(k);\n\t\tif (a) a.push(v);\n\t\telse map.set(k, [v]);\n\t};\n\tfor (const e of snap.edges) {\n\t\tpush(fwd, e.from, e.to);\n\t\tpush(rev, e.to, e.from);\n\t}\n\tconst reach = (start: string, adj: Map<string, string[]>): Set<string> => {\n\t\tconst seen = new Set<string>([start]);\n\t\tconst stack = [start];\n\t\twhile (stack.length > 0) {\n\t\t\tconst cur = stack.pop() as string;\n\t\t\tfor (const nxt of adj.get(cur) ?? []) {\n\t\t\t\tif (!seen.has(nxt)) {\n\t\t\t\t\tseen.add(nxt);\n\t\t\t\t\tstack.push(nxt);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn seen;\n\t};\n\tconst onPath = new Set([...reach(chain.from, fwd)].filter((id) => reach(chain.to, rev).has(id)));\n\treturn {\n\t\t...(snap.name !== undefined ? { name: snap.name } : {}),\n\t\tnodes: snap.nodes.filter((n) => onPath.has(n.id)),\n\t\tedges: snap.edges.filter((e) => onPath.has(e.from) && onPath.has(e.to)),\n\t};\n}\n\n/** Construct a Graph (default global dispatcher; L4-Q4). */\nexport function graph(opts: GraphOptions = {}): Graph {\n\treturn new Graph(opts);\n}\n\n/** @internal D122 graph-owned ephemeral node-group release. */\nexport function releaseGraphNodes(\n\tgraph: Graph,\n\tnodes: readonly Node<unknown>[],\n\topts: { reason?: string } = {},\n): void {\n\tconst registrar = lifecycleRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"graph: unknown lifecycle registrar\");\n\tregistrar.releaseNodes(nodes, opts);\n}\n\n/** @internal D94 descriptor path: register a restored state node without widening Graph. */\nexport function restoreStateNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\topts: SugarOpts<T> = {},\n): StateNode<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.stateNode(id, opts);\n}\n\n/** @internal D94 descriptor path: register a restored ctx-level node without widening Graph. */\nexport function restoreNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\tfactory: string,\n\tdeps: readonly Node<unknown>[],\n\tfn: NodeFn | null,\n\topts: SugarOpts<T> = {},\n): Node<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.node(id, factory, deps, fn, opts);\n}\n","/**\n * Passive semantic-memory vocabulary and deterministic helpers.\n *\n * D158 splits semantic memory into horizontal patterns and vertical solutions.\n * This module intentionally owns no graph nodes, storage restore, timers,\n * subscriptions, vector indexes, knowledge graphs, or agentic runtime.\n */\n\nimport type { StrictJsonValue } from \"../json/codec.js\";\n\n/** Stable identity for a semantic-memory fact. */\nexport type FactId = string;\n\n/** Shard partition key used by passive sharding helpers. */\nexport type ShardKey = string | number;\n\n/**\n * A single semantic-memory fact. Pattern convention only: this is not a\n * protocol message, storage record owner, restore contract, or graph runtime.\n */\nexport interface MemoryFragment<T = unknown> {\n\treadonly id: FactId;\n\treadonly payload: T;\n\t/** Transaction time, typically monotonic nanoseconds. */\n\treadonly tNs: bigint;\n\t/** Valid-time start. Undefined means unbounded past. */\n\treadonly validFrom?: bigint;\n\t/** Valid-time end. Undefined means currently valid. */\n\treadonly validTo?: bigint;\n\t/** Confidence score in the closed interval [0, 1]. */\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\t/** Fact ids this fragment derives from or depends on. */\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** Columnar passive store vocabulary for callers that keep memory facts outside GraphReFly. */\nexport interface FactStore<T = unknown> {\n\treadonly byId: ReadonlyMap<FactId, MemoryFragment<T>>;\n}\n\n/** Read-only projection passed to scoring policies; it exposes no mutation surface. */\nexport interface StoreReadHandle<T = unknown> {\n\tget(id: FactId): MemoryFragment<T> | undefined;\n\thas(id: FactId): boolean;\n\treadonly size: number;\n\tvalues(): IterableIterator<MemoryFragment<T>>;\n}\n\nexport type ScoringPolicy<T = unknown> = (\n\tfragment: MemoryFragment<T>,\n\tstore: StoreReadHandle<T>,\n) => number;\nexport type DecayPolicy = (confidence: number, ageNs: bigint) => number;\nexport type AdmissionFilter<T = unknown> = (fragment: MemoryFragment<T>) => boolean;\n\n/** Outcome signal for policy learning. This is an application fact, not a protocol event. */\nexport interface OutcomeSignal {\n\treadonly factId: FactId;\n\treadonly reward: number;\n}\n\n/** Passive structured query over semantic-memory facts. */\nexport interface MemoryQuery {\n\treadonly tags?: readonly string[];\n\treadonly asOf?: bigint;\n\treadonly minConfidence?: number;\n\treadonly limit?: number;\n}\n\nexport interface MemoryAnswer<T = unknown> {\n\treadonly query: MemoryQuery;\n\treadonly results: readonly MemoryFragment<T>[];\n}\n\nexport type KnowledgeAssertionStrictJsonValue = StrictJsonValue;\n\n/** Passive KG endpoint vocabulary. Entity ids are DATA keys, not graph node ids. */\nexport interface KnowledgeAssertionSubject {\n\treadonly id: FactId;\n\treadonly type?: string;\n}\n\n/** Passive KG object/value vocabulary. */\nexport type KnowledgeAssertionObject =\n\t| {\n\t\t\treadonly kind: \"entity\";\n\t\t\treadonly id: FactId;\n\t\t\treadonly type?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"value\";\n\t\t\treadonly value: KnowledgeAssertionStrictJsonValue;\n\t\t\treadonly valueType?: string;\n\t };\n\n/** Passive KG assertion fact consumed by lower semantic-memory graph patterns. */\nexport interface KnowledgeAssertion {\n\treadonly id: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\n/** Entry vocabulary for ranked collection-like memory views. */\nexport interface CollectionEntry<T = unknown> {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: bigint;\n\treadonly lastAccessNs: bigint;\n\treadonly baseScore: number;\n}\n\nexport type RankedCollectionEntry<T = unknown> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionScoreFn<T = unknown> = (value: T) => number;\n\n/** Query shape shared by passive retrieval/ranking helpers. */\nexport interface RetrievalQuery {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n\treadonly context?: readonly string[];\n}\n\nexport interface VectorSearchResult<TMeta = unknown> {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n}\n\nexport interface RetrievalEntry<TMem = unknown> {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n\treadonly context?: readonly string[];\n}\n\nexport interface RetrievalTrace<TMem = unknown> {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n}\n\n/** Generic per-dimension thresholds. Any configured dimension below threshold is rejected. */\nexport type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;\n\nexport interface AdmissionScoredOptions<Dims extends string, TRaw = unknown> {\n\treadonly scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;\n\treadonly thresholds?: AdmissionThresholds<Dims>;\n}\n\nexport interface AdmissionScores {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n}\n\nexport interface AdmissionScore3DOptions {\n\treadonly scoreFn: (raw: unknown) => AdmissionScores;\n\treadonly persistenceThreshold?: number;\n\treadonly personalValueThreshold?: number;\n\treadonly requireStructured?: boolean;\n}\n\nexport interface ShardByTenantOptions {\n\treadonly tenants?: readonly string[];\n\treadonly shardCount?: number;\n}\n\nexport interface ShardByTenantConfig<T = unknown> {\n\treadonly shardBy: (fragment: MemoryFragment<T>) => ShardKey;\n\treadonly shardCount: number;\n}\n\nexport interface MemoryFragmentValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n}\n\n/** Cosine similarity over zero-padded vectors. Non-finite results normalize to 0. */\nexport function cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\tconst score = dot / Math.sqrt(na * nb);\n\treturn Number.isFinite(score) ? score : 0;\n}\n\n/**\n * Returns true when a fragment is valid at `asOf`.\n *\n * Omitted `asOf` has no clock to compare against, so it admits only fragments\n * that are live and not valid-time delayed.\n */\nexport function memoryFragmentValidAt(fragment: MemoryFragment, asOf?: bigint): boolean {\n\tif (asOf === undefined) return fragment.validTo === undefined && fragment.validFrom === undefined;\n\tif (fragment.validFrom !== undefined && fragment.validFrom > asOf) return false;\n\tif (fragment.validTo !== undefined && fragment.validTo <= asOf) return false;\n\treturn true;\n}\n\n/** Pure structured-query predicate over a single fragment. */\nexport function memoryFragmentMatchesQuery(\n\tfragment: MemoryFragment,\n\tquery: MemoryQuery = {},\n): boolean {\n\tif (!memoryFragmentValidAt(fragment, query.asOf)) return false;\n\tif (query.minConfidence !== undefined && fragment.confidence < query.minConfidence) return false;\n\tif (\n\t\tquery.tags &&\n\t\tquery.tags.length > 0 &&\n\t\t!query.tags.some((tag) => fragment.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filter and rank fragments by confidence desc, then transaction time desc. */\nexport function filterMemoryFragments<T>(\n\tfragments: Iterable<MemoryFragment<T>>,\n\tquery: MemoryQuery = {},\n): readonly MemoryFragment<T>[] {\n\tconst results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tresults.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));\n\treturn query.limit === undefined ? results : results.slice(0, Math.max(0, query.limit));\n}\n\n/** Validate the passive MemoryFragment shape without throwing. */\nexport function validateMemoryFragment(value: unknown): MemoryFragmentValidation {\n\tconst errors: string[] = [];\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn { ok: false, errors: [\"fragment must be an object\"] };\n\t}\n\tconst fragment = value as Partial<MemoryFragment>;\n\tif (typeof fragment.id !== \"string\" || fragment.id.length === 0) {\n\t\terrors.push(\"id must be a non-empty string\");\n\t}\n\tif (!Object.hasOwn(fragment, \"payload\")) {\n\t\terrors.push(\"payload must be present\");\n\t}\n\tif (typeof fragment.tNs !== \"bigint\") {\n\t\terrors.push(\"tNs must be a bigint\");\n\t}\n\tconst confidence = fragment.confidence;\n\tif (\n\t\t!Number.isFinite(confidence) ||\n\t\tconfidence === undefined ||\n\t\tconfidence < 0 ||\n\t\tconfidence > 1\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1]\");\n\t}\n\tif (!isDenseArrayOf(fragment.tags, (tag): tag is string => typeof tag === \"string\")) {\n\t\terrors.push(\"tags must be a readonly string array\");\n\t}\n\tif (!isDenseArrayOf(fragment.sources, (source): source is string => typeof source === \"string\")) {\n\t\terrors.push(\"sources must be a readonly string array\");\n\t}\n\tif (fragment.validFrom !== undefined && typeof fragment.validFrom !== \"bigint\") {\n\t\terrors.push(\"validFrom must be a bigint when present\");\n\t}\n\tif (fragment.validTo !== undefined && typeof fragment.validTo !== \"bigint\") {\n\t\terrors.push(\"validTo must be a bigint when present\");\n\t}\n\tif (\n\t\ttypeof fragment.validFrom === \"bigint\" &&\n\t\ttypeof fragment.validTo === \"bigint\" &&\n\t\tfragment.validFrom >= fragment.validTo\n\t) {\n\t\terrors.push(\"validFrom must be earlier than validTo\");\n\t}\n\tif (\n\t\tfragment.embedding !== undefined &&\n\t\t!isDenseArrayOf(fragment.embedding, (component): component is number =>\n\t\t\tNumber.isFinite(component),\n\t\t)\n\t) {\n\t\terrors.push(\"embedding must be a finite number array when present\");\n\t}\n\tif (fragment.parentFragmentId !== undefined && typeof fragment.parentFragmentId !== \"string\") {\n\t\terrors.push(\"parentFragmentId must be a string when present\");\n\t}\n\tif (fragment.provenance !== undefined && typeof fragment.provenance !== \"string\") {\n\t\terrors.push(\"provenance must be a string when present\");\n\t}\n\treturn { ok: errors.length === 0, errors };\n}\n\nexport function isMemoryFragment(value: unknown): value is MemoryFragment {\n\treturn validateMemoryFragment(value).ok;\n}\n\n/**\n * Generic N-dimension admission filter. Missing or non-finite thresholded scores reject.\n */\nexport function admissionScored<Dims extends string, TRaw = unknown>(\n\topts: AdmissionScoredOptions<Dims, TRaw>,\n): (raw: TRaw) => boolean {\n\tconst thresholds = opts.thresholds ?? ({} as AdmissionThresholds<Dims>);\n\treturn (raw: TRaw): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tfor (const dim of Object.keys(thresholds) as Dims[]) {\n\t\t\tconst min = thresholds[dim];\n\t\t\tif (min === undefined) continue;\n\t\t\tconst score = scores[dim];\n\t\t\tconst safe = Number.isFinite(score) ? (score as number) : Number.NEGATIVE_INFINITY;\n\t\t\tif (safe < min) return false;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/** Three-axis admission sugar for persistence / structure / personal-value scoring. */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean {\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tif (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;\n\t\tif (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;\n\t\tif (!opts.requireStructured) return true;\n\t\treturn scoreAtLeast(scores.structure, Number.MIN_VALUE);\n\t};\n}\n\n/** Build a passive `{ shardBy, shardCount }` pair for tenant-isolated sharding. */\nexport function shardByTenant<T>(\n\ttenantOf: (fragment: MemoryFragment<T>) => string,\n\topts: ShardByTenantOptions = {},\n): ShardByTenantConfig<T> {\n\tif (opts.tenants && opts.tenants.length > 0) {\n\t\tconst tenants = [...new Set(opts.tenants)];\n\t\tconst index = new Map(tenants.map((tenant, i) => [tenant, i] as const));\n\t\tconst overflow = tenants.length;\n\t\treturn {\n\t\t\tshardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,\n\t\t\tshardCount: tenants.length + 1,\n\t\t};\n\t}\n\tconst configuredShardCount = opts.shardCount ?? 4;\n\tconst shardCount = Number.isSafeInteger(configuredShardCount)\n\t\t? Math.max(1, configuredShardCount)\n\t\t: 4;\n\treturn { shardBy: (fragment) => tenantOf(fragment), shardCount };\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction scoreAtLeast(score: number, min: number): boolean {\n\treturn Number.isFinite(score) && score >= min;\n}\n","/**\n * Thin agentic-memory solution surface.\n *\n * D125 places vertical application kits under solutions, while D158 keeps\n * semantic-memory retrieval/ranking in horizontal patterns. This v0 bundle\n * composes those lower layers into graph-visible facts only: no agent runtime,\n * hidden scheduler, storage restore/hydration, LLM loop, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\ttype Codec,\n\ttype StrictJsonValue as SharedStrictJsonValue,\n\tstrictJsonCodec,\n} from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\ttype FactId,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\tvalidateMemoryFragment,\n} from \"../patterns/semantic-memory.js\";\nimport {\n\ttype MemoryRetrievalBundle,\n\ttype MemoryRetrievalCursor,\n\ttype MemoryRetrievalError,\n\ttype MemoryRetrievalIndex,\n\ttype MemoryRetrievalQuery,\n\ttype MemoryRetrievalSnapshot,\n\ttype MemoryRetrievalStatus,\n\tmemoryRetrievalBundle,\n} from \"../patterns/semantic-memory-graph.js\";\n\nexport type AgenticMemoryStrictJsonValue = SharedStrictJsonValue;\n\ntype StrictJsonValue = SharedStrictJsonValue;\n\nexport type {\n\tKnowledgeAssertion,\n\tKnowledgeAssertionObject,\n\tKnowledgeAssertionSubject,\n} from \"../patterns/semantic-memory.js\";\n\n/** Agent-facing memory category. D164 keeps this separate from durability and artifact kind. */\nexport type AgenticMemoryKind = \"working\" | \"episodic\" | \"semantic\" | \"procedural\" | \"profile\";\n\n/** Semantic durability/retention policy metadata. This is not a storage tier handle. */\nexport type AgenticMemoryPersistenceLevel =\n\t| \"turn\"\n\t| \"session\"\n\t| \"project\"\n\t| \"longTerm\"\n\t| \"permanent\"\n\t| \"archived\";\n\n/** Whether the record is raw evidence or a derived artifact. */\nexport type AgenticMemoryArtifactKind = \"raw\" | \"insight\" | \"profile\" | \"procedure\";\n\n/** Optional solution-facing scope metadata. Scope ids are ordinary DATA facts. */\nexport interface AgenticMemoryScope {\n\treadonly sessionId?: string;\n\treadonly projectId?: string;\n\treadonly userId?: string;\n\treadonly tenantId?: string;\n}\n\n/**\n * D164 solution envelope over a lower-layer MemoryFragment.\n *\n * The envelope carries agentic-memory metadata only. It intentionally owns no\n * storage tiers/keys/adapters, restore/hydration behavior, timers, schedulers,\n * LLM/tool/runner handles, or protocol semantics.\n */\nexport interface AgenticMemoryRecord<T = unknown> {\n\treadonly id: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport interface AgenticMemoryRecordMetadata {\n\treadonly recordId: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n}\n\nexport interface AgenticMemoryProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly invalidRecords: number;\n\treadonly projectedFragments: number;\n}\n\nexport type AgenticMemoryStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface AgenticMemoryStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport type AgenticMemoryErrorCode =\n\t| \"duplicate-record-id\"\n\t| \"duplicate-fragment-id\"\n\t| \"invalid-records-input\"\n\t| \"invalid-record\"\n\t| \"invalid-record-kind\"\n\t| \"invalid-persistence-level\"\n\t| \"invalid-artifact-kind\"\n\t| \"invalid-scope\"\n\t| \"invalid-fragment\";\n\nexport interface AgenticMemoryError {\n\treadonly code: AgenticMemoryErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport interface AgenticMemoryProjectionSnapshot<T = unknown> {\n\treadonly records: readonly AgenticMemoryRecord<T>[];\n\treadonly fragments: readonly MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Readonly<Record<FactId, AgenticMemoryRecordMetadata>>;\n\treadonly status: AgenticMemoryStatus;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\n/** Source/provenance projection for a valid memory fragment. */\nexport interface AgenticMemorySourceProjection {\n\treadonly fragmentId: FactId;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly sources: readonly FactId[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** A context-ready item derived from ranked memory retrieval results. */\nexport interface AgenticMemoryContextEntry<T = unknown> {\n\treadonly fragmentId: FactId;\n\treadonly payload: T;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport type AgenticMemoryContextState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\n/**\n * Context-ready ranked memory output for callers such as prompt builders.\n *\n * This is still only a DATA fact. It does not extract, summarize, reflect, run\n * tools, or choose an autonomous action.\n */\nexport interface AgenticMemoryContext<T = unknown> {\n\treadonly state: AgenticMemoryContextState;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly entries: readonly AgenticMemoryContextEntry<T>[];\n\treadonly cursor: MemoryRetrievalCursor;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly retrievalErrors: readonly MemoryRetrievalError[];\n\treadonly contextReady: boolean;\n}\n\n/** Explicit KG assertion draft fact; extraction/LLM work happens outside this bundle. */\nexport interface AgenticMemoryKgAssertionDraft {\n\treadonly id: FactId;\n\treadonly recordId: FactId;\n\treadonly fragmentId: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryKgProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validDrafts: number;\n\treadonly invalidDrafts: number;\n\treadonly projectedAssertions: number;\n}\n\nexport type AgenticMemoryKgProjectionStatusState = AgenticMemoryStatusState;\n\nexport interface AgenticMemoryKgProjectionStatus {\n\treadonly state: AgenticMemoryKgProjectionStatusState;\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport type AgenticMemoryKgProjectionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-drafts-input\"\n\t| \"invalid-draft\"\n\t| \"duplicate-assertion-id\"\n\t| \"missing-record-ref\"\n\t| \"missing-fragment-ref\"\n\t| \"fragment-record-mismatch\"\n\t| \"invalid-assertion-shape\";\n\nexport interface AgenticMemoryKgProjectionError {\n\treadonly code: AgenticMemoryKgProjectionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly assertionId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly draft?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionSnapshot {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly status: AgenticMemoryKgProjectionStatus;\n\treadonly errors: readonly AgenticMemoryKgProjectionError[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionBundle {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\t\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryKgProjectionSnapshot>;\n\treadonly assertions: Node<readonly KnowledgeAssertion[]>;\n\treadonly status: Node<AgenticMemoryKgProjectionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryKgProjectionError[]>;\n\treadonly cursor: Node<AgenticMemoryKgProjectionCursor>;\n}\n\nexport interface AgenticMemoryKgProjectionBundleOptions {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n}\n\nexport const AGENTIC_MEMORY_RECORD_FRAME_FORMAT = \"graphrefly.agenticMemoryRecord\";\nexport const AGENTIC_MEMORY_RECORD_FRAME_VERSION = 1;\n\nexport interface AgenticMemoryFragmentFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly id: FactId;\n\treadonly payload: TJson;\n\treadonly tNs: string;\n\treadonly validFrom?: string;\n\treadonly validTo?: string;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_FRAME_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_FRAME_VERSION;\n\treadonly record: {\n\t\treadonly id: FactId;\n\t\treadonly kind: AgenticMemoryKind;\n\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\treadonly artifactKind: AgenticMemoryArtifactKind;\n\t\treadonly scope?: AgenticMemoryScope;\n\t\treadonly fragment: AgenticMemoryFragmentFrame<TJson>;\n\t};\n}\n\nexport type AgenticMemoryRetentionCommand =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"archive\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"restore\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel?: Exclude<AgenticMemoryPersistenceLevel, \"archived\">;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"setPersistenceLevel\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"requestConsolidation\";\n\t\t\treadonly recordIds: readonly FactId[];\n\t\t\treadonly requestId?: FactId;\n\t\t\treadonly reason?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRequest {\n\treadonly id: FactId;\n\treadonly commandId: FactId;\n\treadonly recordIds: readonly FactId[];\n\treadonly reason?: string;\n}\n\nexport interface AgenticMemoryRetentionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n\treadonly activeRecords: number;\n\treadonly archivedRecords: number;\n\treadonly consolidationRequests: number;\n}\n\nexport interface AgenticMemoryRetentionStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport type AgenticMemoryRetentionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-commands-input\"\n\t| \"invalid-command\"\n\t| \"duplicate-command-id\"\n\t| \"missing-record-ref\";\n\nexport interface AgenticMemoryRetentionError {\n\treadonly code: AgenticMemoryRetentionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly commandId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly recordIds?: readonly FactId[];\n\treadonly command?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionSnapshot<T = unknown> {\n\treadonly activeRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly status: AgenticMemoryRetentionStatus;\n\treadonly errors: readonly AgenticMemoryRetentionError[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryRetentionSnapshot<T>>;\n\treadonly activeRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly archivedRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly consolidationRequests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly status: Node<AgenticMemoryRetentionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryRetentionError[]>;\n\treadonly cursor: Node<AgenticMemoryRetentionCursor>;\n}\n\nexport interface AgenticMemoryRetentionBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n}\n\nexport type AgenticMemoryConsolidationOutcome<T = unknown> =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"proposedRecords\";\n\t\t\treadonly records: readonly AgenticMemoryRecord<T>[];\n\t\t\treadonly provenance?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"failed\";\n\t\t\treadonly message: string;\n\t\t\treadonly provenance?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRecordDraft<T = unknown> {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly record: AgenticMemoryRecord<T>;\n}\n\nexport interface AgenticMemoryConsolidationCommand {\n\treadonly id: FactId;\n\treadonly kind: \"proposeRecords\" | \"markFailed\";\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly draftIds?: readonly FactId[];\n\treadonly message?: string;\n}\n\nexport interface AgenticMemoryConsolidationResult {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly state: \"proposed\" | \"failed\";\n\treadonly sourceRecordIds: readonly FactId[];\n\treadonly proposedRecordIds: readonly FactId[];\n\treadonly message?: string;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryConsolidationCursor {\n\treadonly evaluation: number;\n\treadonly validRequests: number;\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n\treadonly results: number;\n\treadonly proposedRecordDrafts: number;\n}\n\nexport interface AgenticMemoryConsolidationStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport type AgenticMemoryConsolidationErrorCode =\n\t| AgenticMemoryRetentionErrorCode\n\t| \"invalid-outcomes-input\"\n\t| \"invalid-outcome\"\n\t| \"duplicate-outcome-id\"\n\t| \"missing-request-ref\"\n\t| \"invalid-proposed-record\";\n\nexport interface AgenticMemoryConsolidationError {\n\treadonly code: AgenticMemoryConsolidationErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly outcomeId?: FactId;\n\treadonly requestId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly outcome?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationSnapshot<T = unknown> {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly status: AgenticMemoryConsolidationStatus;\n\treadonly errors: readonly AgenticMemoryConsolidationError[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\t\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryConsolidationSnapshot<T>>;\n\treadonly results: Node<readonly AgenticMemoryConsolidationResult[]>;\n\treadonly proposedRecordDrafts: Node<readonly AgenticMemoryConsolidationRecordDraft<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryConsolidationCommand[]>;\n\treadonly status: Node<AgenticMemoryConsolidationStatus>;\n\treadonly errors: Node<readonly AgenticMemoryConsolidationError[]>;\n\treadonly cursor: Node<AgenticMemoryConsolidationCursor>;\n}\n\nexport interface AgenticMemoryConsolidationBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n}\n\nexport interface AgenticMemoryContextText {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost?: number;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryContextPackingPolicy {\n\treadonly maxEntries?: number;\n\treadonly maxChars?: number;\n\treadonly maxCost?: number;\n\treadonly includeMetadata?: boolean;\n}\n\nexport interface AgenticMemoryPackedContextEntry {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost: number;\n\treadonly chars: number;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryPackedContext {\n\treadonly entries: readonly AgenticMemoryPackedContextEntry[];\n\treadonly text: string;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n\treadonly truncated: boolean;\n}\n\nexport interface AgenticMemoryContextPackingCursor {\n\treadonly evaluation: number;\n\treadonly inputEntries: number;\n\treadonly packedEntries: number;\n\treadonly omittedEntries: number;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n}\n\nexport interface AgenticMemoryContextPackingStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport type AgenticMemoryContextPackingErrorCode =\n\t| \"invalid-context\"\n\t| \"invalid-texts-input\"\n\t| \"invalid-text\"\n\t| \"duplicate-text-fragment-id\"\n\t| \"missing-text\"\n\t| \"invalid-policy\";\n\nexport interface AgenticMemoryContextPackingError {\n\treadonly code: AgenticMemoryContextPackingErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly fragmentId?: FactId;\n\treadonly value?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingSnapshot {\n\treadonly packedContext: AgenticMemoryPackedContext;\n\treadonly status: AgenticMemoryContextPackingStatus;\n\treadonly errors: readonly AgenticMemoryContextPackingError[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly context: Node<AgenticMemoryContext<T>>;\n\t\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\t\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n\t};\n\treadonly projection: Node<AgenticMemoryContextPackingSnapshot>;\n\treadonly packedContext: Node<AgenticMemoryPackedContext>;\n\treadonly status: Node<AgenticMemoryContextPackingStatus>;\n\treadonly errors: Node<readonly AgenticMemoryContextPackingError[]>;\n\treadonly cursor: Node<AgenticMemoryContextPackingCursor>;\n}\n\nexport interface AgenticMemoryContextPackingBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n}\n\ninterface ValidatedPackingContext {\n\treadonly entries: readonly AgenticMemoryContextEntry[];\n}\n\nexport interface AgenticMemoryBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly query: Node<MemoryRetrievalQuery>;\n\t};\n\treadonly projection: Node<AgenticMemoryProjectionSnapshot<T>>;\n\treadonly retrieval: MemoryRetrievalBundle<T>;\n\treadonly retrievalSnapshot: Node<MemoryRetrievalSnapshot<T>>;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly fragments: Node<readonly MemoryFragment<T>[]>;\n\treadonly sources: Node<readonly AgenticMemorySourceProjection[]>;\n\treadonly indexed: Node<MemoryRetrievalIndex<T>>;\n\treadonly ranked: Node<MemoryAnswer<T>>;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly status: Node<AgenticMemoryStatus>;\n\treadonly errors: Node<readonly AgenticMemoryError[]>;\n\treadonly retrievalStatus: Node<MemoryRetrievalStatus>;\n\treadonly retrievalErrors: Node<readonly MemoryRetrievalError[]>;\n\treadonly cursor: Node<MemoryRetrievalCursor>;\n}\n\nexport interface AgenticMemoryBundleOptions<T = unknown> {\n\treadonly name?: string;\n\t/** Explicit record-envelope input. Persistence, if needed, composes D161 outside this bundle. */\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t/** Explicit retrieval query input. */\n\treadonly query: Node<MemoryRetrievalQuery>;\n}\n\n/**\n * Compose graph-visible semantic-memory retrieval into an agentic-memory v0 bundle.\n *\n * The returned nodes are ordinary graph nodes with declared deps and DATA facts.\n * Invalid record envelopes and duplicate record ids stay graph-visible through\n * solution-level status/errors DATA facts. The lower retrieval bundle remains\n * visible and receives only projected MemoryFragment values.\n */\nexport function agenticMemoryBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryBundleOptions<T>,\n): AgenticMemoryBundle<T> {\n\tconst name = opts.name ?? \"agenticMemory\";\n\tconst projection = agenticMemoryRecordProjection<T>(graph, opts.records, `${name}/projection`);\n\tconst projectedRecords = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/records`,\n\t\t\"agenticMemoryRecords\",\n\t\t(fact) => fact.records,\n\t);\n\tconst projectedFragments = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/fragments`,\n\t\t\"agenticMemoryFragments\",\n\t\t(fact) => fact.fragments,\n\t);\n\tconst status = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/status`,\n\t\t\"agenticMemoryStatus\",\n\t\t(fact) => fact.status,\n\t);\n\tconst errors = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/errors`,\n\t\t\"agenticMemoryErrors\",\n\t\t(fact) => fact.errors,\n\t);\n\tconst retrieval = memoryRetrievalBundle<T>(graph, {\n\t\tname: `${name}/retrieval`,\n\t\tfragments: projectedFragments,\n\t\tquery: opts.query,\n\t});\n\tconst sources = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/sources`,\n\t\t\"agenticMemorySources\",\n\t\t(fact) =>\n\t\t\tObject.freeze(\n\t\t\t\tfact.fragments.map((fragment) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragmentId: fragment.id,\n\t\t\t\t\t\t...(fact.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { record: fact.metadataByFragmentId[fragment.id] }),\n\t\t\t\t\t\tsources: Object.freeze([...fragment.sources]),\n\t\t\t\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t\t\t\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t);\n\tconst context = agenticMemoryContextProjection(\n\t\tgraph,\n\t\tprojection,\n\t\tretrieval.snapshot,\n\t\t`${name}/context`,\n\t);\n\n\treturn {\n\t\tinput: { records: opts.records, query: opts.query },\n\t\tprojection,\n\t\tretrieval,\n\t\tretrievalSnapshot: retrieval.snapshot,\n\t\trecords: projectedRecords,\n\t\tfragments: projectedFragments,\n\t\tsources,\n\t\tindexed: retrieval.indexed,\n\t\tranked: retrieval.ranked,\n\t\tcontext,\n\t\tstatus,\n\t\terrors,\n\t\tretrievalStatus: retrieval.status,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcursor: retrieval.cursor,\n\t};\n}\n\n/**\n * D165 solution-level KG assertion projection.\n *\n * Records and explicit assertion drafts stay visible as declared deps. This\n * bundle validates references and shape, then emits DATA facts only; it does\n * not extract assertions, call LLMs, read/write storage, or mutate topology.\n */\nexport function agenticMemoryKgProjectionBundle(\n\tgraph: Graph,\n\topts: AgenticMemoryKgProjectionBundleOptions,\n): AgenticMemoryKgProjectionBundle {\n\tconst name = opts.name ?? \"agenticMemoryKgProjection\";\n\tconst projection = graph.node<AgenticMemoryKgProjectionSnapshot>(\n\t\t[opts.records, opts.drafts],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords(depLatest(ctx, 0));\n\t\t\tconst draftProjection = validateAndProjectKgDrafts(\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\trecordProjection.records,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryKgProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidDrafts: draftProjection.assertions.length,\n\t\t\t\tinvalidDrafts: draftProjection.invalidDrafts,\n\t\t\t\tprojectedAssertions: draftProjection.assertions.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(kgErrorFromRecordError), ...draftProjection.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryKgProjectionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, draftProjection.assertions.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(draftProjection.assertions),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryKgProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, drafts: opts.drafts },\n\t\tprojection,\n\t\tassertions: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/assertions`,\n\t\t\t\"agenticMemoryKgAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryKgStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryKgErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryKgCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** Build a D166 strict-JSON frame from an in-memory AgenticMemoryRecord. */\nexport function agenticMemoryRecordFrame<TJson extends StrictJsonValue>(\n\trecord: AgenticMemoryRecord<TJson>,\n): AgenticMemoryRecordFrame<TJson> {\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: invalid record: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\tassertAgenticMemoryRecordCodecShape(record);\n\tassertStrictJsonValue(result.record.fragment.payload, \"record.fragment.payload\");\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\t\trecord: Object.freeze({\n\t\t\tid: result.record.id,\n\t\t\tkind: result.record.kind,\n\t\t\tpersistenceLevel: result.record.persistenceLevel,\n\t\t\tartifactKind: result.record.artifactKind,\n\t\t\t...(result.record.scope === undefined ? {} : { scope: result.record.scope }),\n\t\t\tfragment: fragmentFrame(result.record.fragment as MemoryFragment<TJson>),\n\t\t}),\n\t});\n}\n\n/** Assert and snapshot a decoded D166 record frame. Unknown fields fail honestly. */\nexport function assertAgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue>(\n\tvalue: unknown,\n): AgenticMemoryRecordFrame<TJson> {\n\tif (!isPlainRecord(value))\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: frame must be an object\");\n\tassertStrictJsonValue(value, \"agenticMemoryRecordFrame\");\n\tassertExactKeys(value, [\"format\", \"record\", \"version\"], \"agenticMemoryRecordFrame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_FRAME_FORMAT) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid version\");\n\t}\n\tconst rawRecord = value.record;\n\tif (!isPlainRecord(rawRecord)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawRecord,\n\t\trawRecord.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst rawFragment = rawRecord.fragment;\n\tif (!isPlainRecord(rawFragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawFragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(rawFragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(rawFragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(rawFragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(rawFragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(rawFragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tif (rawRecord.scope !== undefined) assertScopeFrame(rawRecord.scope);\n\tconst frame = value as unknown as AgenticMemoryRecordFrame<TJson>;\n\tconst decoded = recordFromFrame(frame);\n\tconst roundtrip = agenticMemoryRecordFrame(decoded);\n\treturn roundtrip as AgenticMemoryRecordFrame<TJson>;\n}\n\n/** Strict canonical JSON codec for D166 AgenticMemoryRecordFrame values. */\nexport function agenticMemoryRecordFrameCodec<\n\tTJson extends StrictJsonValue = StrictJsonValue,\n>(): Codec<AgenticMemoryRecordFrame<TJson>> {\n\treturn {\n\t\tencode(value: AgenticMemoryRecordFrame<TJson>): Uint8Array {\n\t\t\treturn strictJsonCodec.encode(assertAgenticMemoryRecordFrame<TJson>(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecordFrame<TJson> {\n\t\t\treturn assertAgenticMemoryRecordFrame<TJson>(strictJsonCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/** Strict canonical JSON codec that persists records and decodes bigint fields back to bigint. */\nexport function agenticMemoryRecordCodec<TJson extends StrictJsonValue = StrictJsonValue>(): Codec<\n\tAgenticMemoryRecord<TJson>\n> {\n\tconst frameCodec = agenticMemoryRecordFrameCodec<TJson>();\n\treturn {\n\t\tencode(value: AgenticMemoryRecord<TJson>): Uint8Array {\n\t\t\treturn frameCodec.encode(agenticMemoryRecordFrame(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecord<TJson> {\n\t\t\treturn recordFromFrame(frameCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/**\n * D167 solution-level retention command projection.\n *\n * Archive/restore/setPersistenceLevel are derived views over current records;\n * requestConsolidation emits request facts only.\n */\nexport function agenticMemoryRetentionBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryRetentionBundleOptions<T>,\n): AgenticMemoryRetentionBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryRetention\";\n\tconst projection = graph.node<AgenticMemoryRetentionSnapshot<T>>(\n\t\t[opts.records, opts.commands],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst retention = projectRetention<T>(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst cursor: AgenticMemoryRetentionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidCommands: retention.validCommands,\n\t\t\t\tinvalidCommands: retention.invalidCommands,\n\t\t\t\tactiveRecords: retention.activeRecords.length,\n\t\t\t\tarchivedRecords: retention.archivedRecords.length,\n\t\t\t\tconsolidationRequests: retention.consolidationRequests.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(retentionErrorFromRecordError), ...retention.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryRetentionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, recordProjection.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tactiveRecords: Object.freeze(retention.activeRecords),\n\t\t\t\t\t\tarchivedRecords: Object.freeze(retention.archivedRecords),\n\t\t\t\t\t\tconsolidationRequests: Object.freeze(retention.consolidationRequests),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryRetention\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, commands: opts.commands },\n\t\tprojection,\n\t\tactiveRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/activeRecords`,\n\t\t\t\"agenticMemoryRetentionActiveRecords\",\n\t\t\t(fact) => fact.activeRecords,\n\t\t),\n\t\tarchivedRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/archivedRecords`,\n\t\t\t\"agenticMemoryRetentionArchivedRecords\",\n\t\t\t(fact) => fact.archivedRecords,\n\t\t),\n\t\tconsolidationRequests: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/consolidationRequests`,\n\t\t\t\"agenticMemoryRetentionConsolidationRequests\",\n\t\t\t(fact) => fact.consolidationRequests,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryRetentionStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryRetentionErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryRetentionCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D171 consolidation outcome projection.\n *\n * The bundle does not execute consolidation. External adapters may publish\n * outcome facts, and this projection turns them into visible result/proposal\n * facts for downstream record-creation policy.\n */\nexport function agenticMemoryConsolidationBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryConsolidationBundleOptions<T>,\n): AgenticMemoryConsolidationBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryConsolidation\";\n\tconst projection = graph.node<AgenticMemoryConsolidationSnapshot<T>>(\n\t\t[opts.records, opts.requests, opts.outcomes],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst requests = validateConsolidationRequests(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst outcomes = projectConsolidationOutcomes<T>(\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\trequests.requests,\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryConsolidationCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRequests: requests.requests.length,\n\t\t\t\tvalidOutcomes: outcomes.validOutcomes,\n\t\t\t\tinvalidOutcomes: outcomes.invalidOutcomes,\n\t\t\t\tresults: outcomes.results.length,\n\t\t\t\tproposedRecordDrafts: outcomes.proposedRecordDrafts.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...recordProjection.errors.map(consolidationErrorFromRecordError),\n\t\t\t\t\t...requests.errors.map(consolidationErrorFromRetentionError),\n\t\t\t\t\t...outcomes.errors,\n\t\t\t\t].map((error) => freezeError({ ...error, cursor })),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryConsolidationStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, outcomes.results.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tresults: Object.freeze(outcomes.results),\n\t\t\t\t\t\tproposedRecordDrafts: Object.freeze(outcomes.proposedRecordDrafts),\n\t\t\t\t\t\tcommands: Object.freeze(outcomes.commands),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryConsolidation\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, requests: opts.requests, outcomes: opts.outcomes },\n\t\tprojection,\n\t\tresults: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/results`,\n\t\t\t\"agenticMemoryConsolidationResults\",\n\t\t\t(fact) => fact.results,\n\t\t),\n\t\tproposedRecordDrafts: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/proposedRecordDrafts`,\n\t\t\t\"agenticMemoryConsolidationRecordDrafts\",\n\t\t\t(fact) => fact.proposedRecordDrafts,\n\t\t),\n\t\tcommands: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/commands`,\n\t\t\t\"agenticMemoryConsolidationCommands\",\n\t\t\t(fact) => fact.commands,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryConsolidationStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryConsolidationErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryConsolidationCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** D168 deterministic context-packing bundle over explicit context text facts. */\nexport function agenticMemoryContextPackingBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryContextPackingBundleOptions<T>,\n): AgenticMemoryContextPackingBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryContextPacking\";\n\tconst projection = graph.node<AgenticMemoryContextPackingSnapshot>(\n\t\t[opts.context, opts.texts, opts.policy],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst packed = packContext(\n\t\t\t\tdepLatest(ctx, 0),\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", packed]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryContextPacking\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { context: opts.context, texts: opts.texts, policy: opts.policy },\n\t\tprojection,\n\t\tpackedContext: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/packedContext`,\n\t\t\t\"agenticMemoryPackedContext\",\n\t\t\t(fact) => fact.packedContext,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryContextPackingStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryContextPackingErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryContextPackingCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction solutionProjection<TFact, TSnapshot>(\n\tgraph: Graph,\n\tsnapshot: Node<TSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: TSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as TSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: AgenticMemoryProjectionSnapshot<T>) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as AgenticMemoryProjectionSnapshot<T>)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryContextProjection<T>(\n\tgraph: Graph,\n\tprojection: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tretrieval: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n): Node<AgenticMemoryContext<T>> {\n\treturn graph.node<AgenticMemoryContext<T>>(\n\t\t[projection, retrieval],\n\t\t(ctx) => {\n\t\t\tconst projectionFact = depLatest(ctx, 0) as AgenticMemoryProjectionSnapshot<T> | undefined;\n\t\t\tconst retrievalFacts = depBatch(ctx, 1) ?? [];\n\t\t\tif (projectionFact === undefined || retrievalFacts.length === 0) return;\n\t\t\tfor (const raw of retrievalFacts) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", contextFromSnapshot(projectionFact, raw as MemoryRetrievalSnapshot<T>)],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryContext\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction contextFromSnapshot<T>(\n\tprojection: AgenticMemoryProjectionSnapshot<T>,\n\tretrieval: MemoryRetrievalSnapshot<T>,\n): AgenticMemoryContext<T> {\n\tconst entries = retrieval.ranked.results.map((fragment) =>\n\t\tObject.freeze({\n\t\t\tfragmentId: fragment.id,\n\t\t\tpayload: fragment.payload,\n\t\t\tconfidence: fragment.confidence,\n\t\t\ttags: fragment.tags,\n\t\t\tsources: fragment.sources,\n\t\t\t...(projection.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t? {}\n\t\t\t\t: { record: projection.metadataByFragmentId[fragment.id] }),\n\t\t\tfragment,\n\t\t}),\n\t);\n\tconst hasContext = entries.length > 0;\n\tconst state = contextState(projection.status.state, retrieval.status.state);\n\treturn Object.freeze({\n\t\tstate,\n\t\tquery: retrieval.ranked.query,\n\t\tentries: Object.freeze(entries),\n\t\tcursor: retrieval.cursor,\n\t\terrors: projection.errors,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcontextReady: hasContext && (state === \"ready\" || state === \"partial\"),\n\t});\n}\n\nfunction agenticMemoryRecordProjection<T>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<T>[]>,\n\tname: string,\n): Node<AgenticMemoryProjectionSnapshot<T>> {\n\treturn graph.node<AgenticMemoryProjectionSnapshot<T>>(\n\t\t[records],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawRecords = (depBatch(ctx, 0) ?? []).at(-1);\n\t\t\tconst projected = validateAndProjectRecords<T>(rawRecords);\n\t\t\tconst cursor: AgenticMemoryProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: projected.records.length,\n\t\t\t\tinvalidRecords: projected.invalidRecordIndexes.size,\n\t\t\t\tprojectedFragments: projected.fragments.length,\n\t\t\t});\n\t\t\tconst status: AgenticMemoryStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(projected.errors.length, projected.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tprojected.errors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\trecords: Object.freeze(projected.records),\n\t\t\t\t\t\tfragments: Object.freeze(projected.fragments),\n\t\t\t\t\t\tmetadataByFragmentId: Object.freeze(projected.metadataByFragmentId),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction validateAndProjectKgDrafts(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord[],\n): {\n\treadonly assertions: KnowledgeAssertion[];\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n\treadonly invalidDrafts: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tlet invalidDrafts = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input must be an array\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input length could not be read\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst recordById = new Map(records.map((record) => [record.id, record]));\n\tconst fragmentToRecord = new Map(records.map((record) => [record.fragment.id, record.id]));\n\tconst seenAssertions = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateKgDraft(raw, i);\n\t\t\tif (result.errors.length > 0 || result.draft === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst draft = result.draft;\n\t\t\tif (seenAssertions.has(draft.id)) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: duplicate assertion id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate assertion id '${draft.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = recordById.get(draft.recordId);\n\t\t\tif (record === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing record\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`record '${draft.recordId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst owner = fragmentToRecord.get(draft.fragmentId);\n\t\t\tif (owner === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-fragment-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing fragment\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`fragment '${draft.fragmentId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (owner !== draft.recordId || record.fragment.id !== draft.fragmentId) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"fragment-record-mismatch\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft record and fragment refs disagree\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [\n\t\t\t\t\t\t`fragment '${draft.fragmentId}' belongs to record '${owner}', not '${draft.recordId}'`,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenAssertions.add(draft.id);\n\t\t\tassertions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tsubject: draft.subject,\n\t\t\t\t\tpredicate: draft.predicate,\n\t\t\t\t\tobject: draft.object,\n\t\t\t\t\t...(draft.confidence === undefined ? {} : { confidence: draft.confidence }),\n\t\t\t\t\tsources: Object.freeze(draft.sources ?? [draft.fragmentId]),\n\t\t\t\t\t...(draft.provenance === undefined ? {} : { provenance: draft.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tinvalidDrafts += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\tmessage: `agenticMemoryKgProjectionBundle: draft access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tdraft: raw,\n\t\t\t\tvalidationErrors: [\"draft access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn { assertions, errors, invalidDrafts };\n}\n\nfunction validateKgDraft(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly draft?: AgenticMemoryKgAssertionDraft;\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst raw = value as Partial<AgenticMemoryKgAssertionDraft>;\n\tconst id = typeof raw.id === \"string\" && raw.id.length > 0 ? raw.id : undefined;\n\tconst recordId =\n\t\ttypeof raw.recordId === \"string\" && raw.recordId.length > 0 ? raw.recordId : undefined;\n\tconst fragmentId =\n\t\ttypeof raw.fragmentId === \"string\" && raw.fragmentId.length > 0 ? raw.fragmentId : undefined;\n\tconst subject = validateAssertionSubject(raw.subject);\n\tconst object = validateAssertionObject(raw.object);\n\tconst shapeErrors: string[] = [];\n\tif (id === undefined) shapeErrors.push(\"draft.id must be a non-empty string\");\n\tif (recordId === undefined) {\n\t\tshapeErrors.push(\"draft.recordId must be a non-empty string\");\n\t}\n\tif (fragmentId === undefined) {\n\t\tshapeErrors.push(\"draft.fragmentId must be a non-empty string\");\n\t}\n\tshapeErrors.push(...subject.errors);\n\tif (typeof raw.predicate !== \"string\" || raw.predicate.length === 0) {\n\t\tshapeErrors.push(\"draft.predicate must be a non-empty string\");\n\t}\n\tshapeErrors.push(...object.errors);\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\tshapeErrors.push(\"draft.confidence must be a finite number in [0, 1]\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\tshapeErrors.push(\"draft.sources must be a readonly string array\");\n\t}\n\tif (raw.provenance !== undefined && typeof raw.provenance !== \"string\") {\n\t\tshapeErrors.push(\"draft.provenance must be a string when present\");\n\t}\n\tif (shapeErrors.length > 0) errors.push(kgShapeError(index, value, ...shapeErrors));\n\tif (errors.length > 0 || id === undefined || recordId === undefined || fragmentId === undefined) {\n\t\treturn { errors };\n\t}\n\treturn {\n\t\tdraft: Object.freeze({\n\t\t\tid,\n\t\t\trecordId,\n\t\t\tfragmentId,\n\t\t\tsubject: subject.subject as KnowledgeAssertionSubject,\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: object.object as KnowledgeAssertionObject,\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\t...(raw.sources === undefined ? {} : { sources: Object.freeze([...raw.sources]) }),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionSubject(value: unknown): {\n\treadonly subject?: KnowledgeAssertionSubject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"subject must be an object\"] };\n\tconst id = value.id;\n\tconst type = value.type;\n\tconst errors: string[] = [];\n\tif (typeof id !== \"string\" || id.length === 0) errors.push(\"subject.id must be non-empty\");\n\tif (type !== undefined && (typeof type !== \"string\" || type.length === 0)) {\n\t\terrors.push(\"subject.type must be a non-empty string when present\");\n\t}\n\tif (errors.length > 0) return { errors };\n\treturn {\n\t\tsubject: Object.freeze({\n\t\t\tid: id as string,\n\t\t\t...(type === undefined ? {} : { type: type as string }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionObject(value: unknown): {\n\treadonly object?: KnowledgeAssertionObject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"object must be an object\"] };\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (kind === \"entity\") {\n\t\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\t\terrors.push(\"object.id must be non-empty for entity objects\");\n\t\t}\n\t\tif (value.type !== undefined && (typeof value.type !== \"string\" || value.type.length === 0)) {\n\t\t\terrors.push(\"object.type must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"value\")) errors.push(\"entity object must not include value\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: value.id as string,\n\t\t\t\t...(value.type === undefined ? {} : { type: value.type as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\tif (kind === \"value\") {\n\t\tif (!Object.hasOwn(value, \"value\")) errors.push(\"value object must include value\");\n\t\telse {\n\t\t\ttry {\n\t\t\t\tassertStrictJsonValue(value.value, \"object.value\");\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(errorMessage(error));\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tvalue.valueType !== undefined &&\n\t\t\t(typeof value.valueType !== \"string\" || value.valueType.length === 0)\n\t\t) {\n\t\t\terrors.push(\"object.valueType must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"id\")) errors.push(\"value object must not include id\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: value.value as StrictJsonValue,\n\t\t\t\t...(value.valueType === undefined ? {} : { valueType: value.valueType as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\treturn { errors: [\"object.kind must be entity or value\"] };\n}\n\nfunction kgShapeError(\n\tindex: number,\n\tdraft: unknown,\n\t...validationErrors: readonly string[]\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\tcode: \"invalid-assertion-shape\",\n\t\tmessage: \"agenticMemoryKgProjectionBundle: draft assertion shape is invalid\",\n\t\tindex,\n\t\tdraft,\n\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t};\n}\n\nfunction kgErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction fragmentFrame<TJson extends StrictJsonValue>(\n\tfragment: MemoryFragment<TJson>,\n): AgenticMemoryFragmentFrame<TJson> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: decimalBigIntString(fragment.tNs, \"fragment.tNs\"),\n\t\t...(fragment.validFrom === undefined\n\t\t\t? {}\n\t\t\t: { validFrom: decimalBigIntString(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t...(fragment.validTo === undefined\n\t\t\t? {}\n\t\t\t: { validTo: decimalBigIntString(fragment.validTo, \"fragment.validTo\") }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordFromFrame<TJson extends StrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\tconst fragment = frame.record.fragment;\n\tconst record: AgenticMemoryRecord<TJson> = {\n\t\tid: assertNonEmptyString(frame.record.id, \"record.id\"),\n\t\tkind: assertKindValue(frame.record.kind),\n\t\tpersistenceLevel: assertPersistenceLevelValue(frame.record.persistenceLevel),\n\t\tartifactKind: assertArtifactKindValue(frame.record.artifactKind),\n\t\t...(frame.record.scope === undefined ? {} : { scope: assertScopeFrame(frame.record.scope) }),\n\t\tfragment: {\n\t\t\tid: assertNonEmptyString(fragment.id, \"fragment.id\"),\n\t\t\tpayload: assertStrictJsonValue(fragment.payload, \"fragment.payload\") as TJson,\n\t\t\ttNs: parseDecimalBigInt(fragment.tNs, \"fragment.tNs\"),\n\t\t\t...(fragment.validFrom === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validFrom: parseDecimalBigInt(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t\t...(fragment.validTo === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validTo: parseDecimalBigInt(fragment.validTo, \"fragment.validTo\") }),\n\t\t\tconfidence: assertConfidence(fragment.confidence, \"fragment.confidence\"),\n\t\t\ttags: assertStringArray(fragment.tags, \"fragment.tags\"),\n\t\t\tsources: assertStringArray(fragment.sources, \"fragment.sources\"),\n\t\t\t...(fragment.embedding === undefined\n\t\t\t\t? {}\n\t\t\t\t: { embedding: assertFiniteNumberArray(fragment.embedding, \"fragment.embedding\") }),\n\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparentFragmentId: assertNonEmptyString(fragment.parentFragmentId, \"parentFragmentId\"),\n\t\t\t\t\t}),\n\t\t\t...(fragment.provenance === undefined\n\t\t\t\t? {}\n\t\t\t\t: { provenance: assertString(fragment.provenance, \"provenance\") }),\n\t\t},\n\t};\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: decoded record is invalid: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn result.record;\n}\n\nfunction projectRetention<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly activeRecords: AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: AgenticMemoryConsolidationRequest[];\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst view = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tlet validCommands = 0;\n\tlet invalidCommands = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenCommands = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateRetentionCommand(raw, i);\n\t\t\tif (result.errors.length > 0 || result.command === undefined) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst command = result.command;\n\t\t\tif (seenCommands.has(command.id)) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-command-id\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: duplicate command id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate command id '${command.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst missing = retentionMissingRecords(command, byId);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command references missing records\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\trecordId: \"recordId\" in command ? command.recordId : undefined,\n\t\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(missing.map((id) => `record '${id}' is not projected`)),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenCommands.add(command.id);\n\t\t\tvalidCommands += 1;\n\t\t\tapplyRetentionCommand(command, byId, view, requests);\n\t\t} catch (error) {\n\t\t\tinvalidCommands += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryRetentionBundle: command access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: [\"command access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\tconst projected = records.map((record) => view.get(record.id) ?? record);\n\treturn {\n\t\tactiveRecords: projected.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\tarchivedRecords: projected.filter((record) => record.persistenceLevel === \"archived\"),\n\t\tconsolidationRequests: requests,\n\t\terrors,\n\t\tvalidCommands,\n\t\tinvalidCommands,\n\t};\n}\n\nfunction validateRetentionCommand(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly command?: AgenticMemoryRetentionCommand;\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst id = typeof value.id === \"string\" && value.id.length > 0 ? value.id : undefined;\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (id === undefined) errors.push(\"command.id must be a non-empty string\");\n\tif (\n\t\tkind !== \"archive\" &&\n\t\tkind !== \"restore\" &&\n\t\tkind !== \"setPersistenceLevel\" &&\n\t\tkind !== \"requestConsolidation\"\n\t) {\n\t\terrors.push(\"command.kind is invalid\");\n\t}\n\tif (value.reason !== undefined && typeof value.reason !== \"string\") {\n\t\terrors.push(\"command.reason must be a string when present\");\n\t}\n\tif (kind === \"archive\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t} else if (kind === \"restore\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (\n\t\t\tvalue.persistenceLevel !== undefined &&\n\t\t\t(!isAgenticMemoryPersistenceLevel(value.persistenceLevel) ||\n\t\t\t\tvalue.persistenceLevel === \"archived\")\n\t\t) {\n\t\t\terrors.push(\"restore.persistenceLevel must be a non-archived persistence level when present\");\n\t\t}\n\t} else if (kind === \"setPersistenceLevel\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\t\terrors.push(\"setPersistenceLevel.persistenceLevel is invalid\");\n\t\t}\n\t} else if (kind === \"requestConsolidation\") {\n\t\tif (!isDenseArrayOf(value.recordIds, isNonEmptyString) || value.recordIds.length === 0) {\n\t\t\terrors.push(\"requestConsolidation.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (\n\t\t\tvalue.requestId !== undefined &&\n\t\t\t(typeof value.requestId !== \"string\" || value.requestId.length === 0)\n\t\t) {\n\t\t\terrors.push(\"requestConsolidation.requestId must be non-empty when present\");\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command is invalid\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommandId: id,\n\t\t\t\t\tcommand: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst base = { id, reason: value.reason as string | undefined };\n\tif (kind === \"archive\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"restore\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(value.persistenceLevel === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tpersistenceLevel: value.persistenceLevel as Exclude<\n\t\t\t\t\t\t\t\tAgenticMemoryPersistenceLevel,\n\t\t\t\t\t\t\t\t\"archived\"\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t}),\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"setPersistenceLevel\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: Object.freeze({\n\t\t\t...base,\n\t\t\tkind: \"requestConsolidation\",\n\t\t\trecordIds: Object.freeze([...(value.recordIds as readonly string[])]),\n\t\t\t...(value.requestId === undefined ? {} : { requestId: value.requestId as string }),\n\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction retentionMissingRecords(\n\tcommand: AgenticMemoryRetentionCommand,\n\trecords: ReadonlyMap<FactId, AgenticMemoryRecord>,\n): readonly FactId[] {\n\tif (\"recordId\" in command) return records.has(command.recordId) ? [] : [command.recordId];\n\treturn command.recordIds.filter((recordId) => !records.has(recordId));\n}\n\nfunction applyRetentionCommand<T>(\n\tcommand: AgenticMemoryRetentionCommand,\n\tsource: ReadonlyMap<FactId, AgenticMemoryRecord<T>>,\n\tview: Map<FactId, AgenticMemoryRecord<T>>,\n\trequests: AgenticMemoryConsolidationRequest[],\n): void {\n\tif (command.kind === \"requestConsolidation\") {\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: command.requestId ?? command.id,\n\t\t\t\tcommandId: command.id,\n\t\t\t\trecordIds: Object.freeze([...command.recordIds]),\n\t\t\t\t...(command.reason === undefined ? {} : { reason: command.reason }),\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tconst record = view.get(command.recordId) ?? source.get(command.recordId);\n\tif (record === undefined) return;\n\tconst persistenceLevel =\n\t\tcommand.kind === \"archive\"\n\t\t\t? \"archived\"\n\t\t\t: command.kind === \"restore\"\n\t\t\t\t? (command.persistenceLevel ?? nonArchivedLevel(source.get(command.recordId) ?? record))\n\t\t\t\t: command.persistenceLevel;\n\tview.set(command.recordId, withPersistenceLevel(record, persistenceLevel));\n}\n\nfunction nonArchivedLevel(\n\trecord: AgenticMemoryRecord,\n): Exclude<AgenticMemoryPersistenceLevel, \"archived\"> {\n\treturn record.persistenceLevel === \"archived\" ? \"session\" : record.persistenceLevel;\n}\n\nfunction withPersistenceLevel<T>(\n\trecord: AgenticMemoryRecord<T>,\n\tpersistenceLevel: AgenticMemoryPersistenceLevel,\n): AgenticMemoryRecord<T> {\n\treturn Object.freeze({\n\t\t...record,\n\t\tpersistenceLevel,\n\t});\n}\n\nfunction retentionErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryRetentionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction validateConsolidationRequests<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly requests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly errors: readonly Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seen = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"request array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: request access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"request access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!isPlainRecord(raw)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request must be an object\",\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = isNonEmptyString(raw.id) ? raw.id : undefined;\n\t\tconst commandId = isNonEmptyString(raw.commandId) ? raw.commandId : undefined;\n\t\tconst recordIds = isDenseArrayOf(raw.recordIds, isNonEmptyString)\n\t\t\t? Object.freeze([...raw.recordIds])\n\t\t\t: undefined;\n\t\tconst validationErrors: string[] = [];\n\t\tif (id === undefined) validationErrors.push(\"request.id must be a non-empty string\");\n\t\tif (commandId === undefined) {\n\t\t\tvalidationErrors.push(\"request.commandId must be a non-empty string\");\n\t\t}\n\t\tif (recordIds === undefined || recordIds.length === 0) {\n\t\t\tvalidationErrors.push(\"request.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (raw.reason !== undefined && typeof raw.reason !== \"string\") {\n\t\t\tvalidationErrors.push(\"request.reason must be a string when present\");\n\t\t}\n\t\tif (id !== undefined && seen.has(id)) {\n\t\t\tvalidationErrors.push(`duplicate request id '${id}'`);\n\t\t}\n\t\tconst missing = (recordIds ?? []).filter((recordId) => !byId.has(recordId));\n\t\tif (missing.length > 0) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request references missing records\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\t\tmissing.map((recordId) => `record '${recordId}' is not projected`),\n\t\t\t\t),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tvalidationErrors.length > 0 ||\n\t\t\tid === undefined ||\n\t\t\tcommandId === undefined ||\n\t\t\trecordIds === undefined\n\t\t) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request is invalid\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(validationErrors),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(id);\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\t...(raw.reason === undefined ? {} : { reason: raw.reason as string }),\n\t\t\t}),\n\t\t);\n\t}\n\treturn { requests: Object.freeze(requests), errors };\n}\n\nfunction projectConsolidationOutcomes<T>(\n\tvalue: unknown,\n\trequests: readonly AgenticMemoryConsolidationRequest[],\n\tevaluation: number,\n): {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly errors: readonly Omit<AgenticMemoryConsolidationError, \"cursor\">[];\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n} {\n\tconst byRequest = new Map(requests.map((request) => [request.id, request]));\n\tconst results: AgenticMemoryConsolidationResult[] = [];\n\tconst proposedRecordDrafts: AgenticMemoryConsolidationRecordDraft<T>[] = [];\n\tconst commands: AgenticMemoryConsolidationCommand[] = [];\n\tconst errors: Omit<AgenticMemoryConsolidationError, \"cursor\">[] = [];\n\tlet validOutcomes = 0;\n\tlet invalidOutcomes = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input must be an array\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input length could not be read\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenOutcomes = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\tlet outcome: {\n\t\t\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\t\t\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n\t\t};\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"outcome array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t\toutcome = validateConsolidationOutcome<T>(raw, i);\n\t\t} catch (error) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: outcome access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"outcome access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.error !== undefined || outcome.outcome === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\tif (outcome.error !== undefined) errors.push(outcome.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst validOutcome = outcome.outcome;\n\t\tif (seenOutcomes.has(validOutcome.id)) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-outcome-id\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: duplicate outcome id\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate outcome id '${validOutcome.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst request = byRequest.get(validOutcome.requestId);\n\t\tif (request === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-request-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome references missing request\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`request '${validOutcome.requestId}' is not projected`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenOutcomes.add(validOutcome.id);\n\t\tvalidOutcomes += 1;\n\t\tif (validOutcome.kind === \"failed\") {\n\t\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: resultId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\t\tproposedRecordIds: Object.freeze([]),\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcommands.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: `${resultId}:markFailed`,\n\t\t\t\t\tkind: \"markFailed\",\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst draftIds = validOutcome.records.map(\n\t\t\t(record) => `${validOutcome.requestId}:${validOutcome.id}:${record.id}`,\n\t\t);\n\t\tfor (let recordIndex = 0; recordIndex < validOutcome.records.length; recordIndex += 1) {\n\t\t\tproposedRecordDrafts.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draftIds[recordIndex] as FactId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\trecord: validOutcome.records[recordIndex] as AgenticMemoryRecord<T>,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\tresults.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: resultId,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tstate: \"proposed\",\n\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\tproposedRecordIds: Object.freeze(validOutcome.records.map((record) => record.id)),\n\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t}),\n\t\t);\n\t\tcommands.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: `${resultId}:proposeRecords`,\n\t\t\t\tkind: \"proposeRecords\",\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tdraftIds: Object.freeze(draftIds),\n\t\t\t}),\n\t\t);\n\t}\n\tvoid evaluation;\n\treturn {\n\t\tresults: Object.freeze(results),\n\t\tproposedRecordDrafts: Object.freeze(proposedRecordDrafts),\n\t\tcommands: Object.freeze(commands),\n\t\terrors,\n\t\tvalidOutcomes,\n\t\tinvalidOutcomes,\n\t};\n}\n\nfunction validateConsolidationOutcome<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome must be an object\",\n\t\t\t\tindex,\n\t\t\t\toutcome: value,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst id = isNonEmptyString(value.id) ? value.id : undefined;\n\tconst requestId = isNonEmptyString(value.requestId) ? value.requestId : undefined;\n\tif (id === undefined) errors.push(\"outcome.id must be a non-empty string\");\n\tif (requestId === undefined) errors.push(\"outcome.requestId must be a non-empty string\");\n\tif (value.kind !== \"proposedRecords\" && value.kind !== \"failed\") {\n\t\terrors.push(\"outcome.kind must be proposedRecords or failed\");\n\t}\n\tif (value.provenance !== undefined && typeof value.provenance !== \"string\") {\n\t\terrors.push(\"outcome.provenance must be a string when present\");\n\t}\n\tif (value.kind === \"failed\" && !isNonEmptyString(value.message)) {\n\t\terrors.push(\"failed outcome.message must be a non-empty string\");\n\t}\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tif (value.kind === \"proposedRecords\") {\n\t\tif (!Array.isArray(value.records)) {\n\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t} else {\n\t\t\tconst recordsLength = safeArrayLength(value.records);\n\t\t\tconst seenRecordIds = new Set<FactId>();\n\t\t\tif (recordsLength === undefined || recordsLength === 0) {\n\t\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t\t}\n\t\t\tfor (let i = 0; i < (recordsLength ?? 0); i += 1) {\n\t\t\t\tlet result: {\n\t\t\t\t\treadonly record?: AgenticMemoryRecord<T>;\n\t\t\t\t\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (!Object.hasOwn(value.records, i)) {\n\t\t\t\t\t\tthrow new TypeError(\"proposedRecords.records must be dense\");\n\t\t\t\t\t}\n\t\t\t\t\tresult = validateAndSnapshotRecord<T>(value.records[i], i);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(`records[${i}]: record access failed: ${errorMessage(error)}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (result.record === undefined || result.errors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...result.errors\n\t\t\t\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t\t\t\t.map((error) => `records[${i}]: ${error}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (seenRecordIds.has(result.record.id)) {\n\t\t\t\t\terrors.push(`records[${i}]: duplicate proposed record id '${result.record.id}'`);\n\t\t\t\t} else {\n\t\t\t\t\tseenRecordIds.add(result.record.id);\n\t\t\t\t\trecords.push(result.record);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined || requestId === undefined) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: value.kind === \"proposedRecords\" ? \"invalid-proposed-record\" : \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome is invalid\",\n\t\t\t\tindex,\n\t\t\t\toutcomeId: id,\n\t\t\t\trequestId,\n\t\t\t\toutcome: value,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\tif (value.kind === \"failed\") {\n\t\treturn {\n\t\t\toutcome: Object.freeze({\n\t\t\t\tid,\n\t\t\t\trequestId,\n\t\t\t\tkind: \"failed\",\n\t\t\t\tmessage: value.message as string,\n\t\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t\t}),\n\t\t};\n\t}\n\treturn {\n\t\toutcome: Object.freeze({\n\t\t\tid,\n\t\t\trequestId,\n\t\t\tkind: \"proposedRecords\",\n\t\t\trecords: Object.freeze(records),\n\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t}),\n\t};\n}\n\nfunction consolidationErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction consolidationErrorFromRetentionError(\n\terror: Omit<AgenticMemoryRetentionError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction packContext(\n\tcontextValue: unknown,\n\ttextsValue: unknown,\n\tpolicyValue: unknown,\n\tevaluation: number,\n): AgenticMemoryContextPackingSnapshot {\n\tconst errors: Omit<AgenticMemoryContextPackingError, \"cursor\">[] = [];\n\tconst context = validatePackingContext(contextValue, errors);\n\tconst texts = validateContextTexts(textsValue, errors);\n\tconst policy = validatePackingPolicy(policyValue, errors);\n\tconst packedEntries: AgenticMemoryPackedContextEntry[] = [];\n\tlet omittedEntries = 0;\n\tlet totalChars = 0;\n\tlet totalCost = 0;\n\tif (context !== undefined && policy !== undefined) {\n\t\tfor (const entry of context.entries) {\n\t\t\tconst textFact = texts.get(entry.fragmentId);\n\t\t\tif (textFact === undefined) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: missing text projection for context entry\",\n\t\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\t\tvalidationErrors: [`missing text for fragment '${entry.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst cost = textFact.cost ?? textFact.text.length;\n\t\t\tconst nextEntries = packedEntries.length + 1;\n\t\t\tconst separatorChars = packedEntries.length === 0 ? 0 : 2;\n\t\t\tconst nextChars = totalChars + separatorChars + textFact.text.length;\n\t\t\tconst nextCost = totalCost + cost;\n\t\t\tconst exceeds =\n\t\t\t\t(policy.maxEntries !== undefined && nextEntries > policy.maxEntries) ||\n\t\t\t\t(policy.maxChars !== undefined && nextChars > policy.maxChars) ||\n\t\t\t\t(policy.maxCost !== undefined && nextCost > policy.maxCost);\n\t\t\tif (exceeds) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst packedEntry: AgenticMemoryPackedContextEntry = Object.freeze({\n\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\ttext: textFact.text,\n\t\t\t\tcost,\n\t\t\t\tchars: textFact.text.length,\n\t\t\t\t...(entry.record === undefined ? {} : { record: entry.record }),\n\t\t\t\t...(policy.includeMetadata && textFact.metadata !== undefined\n\t\t\t\t\t? { metadata: textFact.metadata }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tpackedEntries.push(packedEntry);\n\t\t\ttotalChars = nextChars;\n\t\t\ttotalCost = nextCost;\n\t\t}\n\t}\n\tconst cursor: AgenticMemoryContextPackingCursor = Object.freeze({\n\t\tevaluation,\n\t\tinputEntries: context?.entries.length ?? 0,\n\t\tpackedEntries: packedEntries.length,\n\t\tomittedEntries,\n\t\ttotalChars,\n\t\ttotalCost,\n\t});\n\tconst errorFacts = Object.freeze(\n\t\terrors.map((error) =>\n\t\t\tfreezeError({\n\t\t\t\t...error,\n\t\t\t\tcursor,\n\t\t\t}),\n\t\t),\n\t);\n\tconst packedContext: AgenticMemoryPackedContext = Object.freeze({\n\t\tentries: Object.freeze(packedEntries),\n\t\ttext: packedEntries.map((entry) => entry.text).join(\"\\n\\n\"),\n\t\ttotalChars,\n\t\ttotalCost,\n\t\ttruncated: omittedEntries > 0,\n\t});\n\tconst status: AgenticMemoryContextPackingStatus = Object.freeze({\n\t\tstate: agenticStatusState(errorFacts.length, packedEntries.length),\n\t\tcursor,\n\t});\n\treturn Object.freeze({\n\t\tpackedContext,\n\t\tstatus,\n\t\terrors: errorFacts,\n\t\tcursor,\n\t});\n}\n\nfunction validatePackingContext(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): ValidatedPackingContext | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tlet entriesValue: unknown;\n\ttry {\n\t\tentriesValue = value.entries;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: context entries access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context entries access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(entriesValue)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries must be an array\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst length = safeArrayLength(entriesValue);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entries length could not be read\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries length could not be read\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst entries: AgenticMemoryContextEntry[] = [];\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = entriesValue[i];\n\t\t\tif (!isPlainRecord(raw) || !isNonEmptyString(raw.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"context entry fragmentId must be a non-empty string\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = validateRecordMetadata(raw.record);\n\t\t\tif (!record.ok) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry record metadata is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(record.errors),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tentries.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\t...(record.metadata === undefined ? {} : { record: record.metadata }),\n\t\t\t\t}) as AgenticMemoryContextEntry,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-context\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: context entry access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalue: raw,\n\t\t\t\tvalidationErrors: [\"context entry access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn Object.freeze({\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction validateContextTexts(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): Map<FactId, AgenticMemoryContextText> {\n\tconst out = new Map<FactId, AgenticMemoryContextText>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input must be an array\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input length could not be read\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\ttry {\n\t\t\tconst raw = value[i];\n\t\t\tconst result = validateContextText(raw, i);\n\t\t\tif (result.error !== undefined) {\n\t\t\t\terrors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.text === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"text validation returned no fact\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (out.has(result.text.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-text-fragment-id\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: duplicate text fragment id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: result.text.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate text fragment id '${result.text.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.set(result.text.fragmentId, result.text);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: text access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: [\"text access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction validateContextText(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly text?: AgenticMemoryContextText;\n\treadonly error?: Omit<AgenticMemoryContextPackingError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact must be an object\",\n\t\t\t\tindex,\n\t\t\t\tvalue,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(value.fragmentId)) errors.push(\"fragmentId must be a non-empty string\");\n\tif (typeof value.text !== \"string\") errors.push(\"text must be a string\");\n\tif (\n\t\tvalue.cost !== undefined &&\n\t\t(typeof value.cost !== \"number\" || !Number.isFinite(value.cost) || value.cost < 0)\n\t) {\n\t\terrors.push(\"cost must be a finite number >= 0\");\n\t}\n\tif (value.metadata !== undefined) {\n\t\ttry {\n\t\t\tif (!isPlainRecord(value.metadata)) {\n\t\t\t\tthrow new TypeError(\"metadata must be a plain object when present\");\n\t\t\t}\n\t\t\tassertStrictJsonValue(value.metadata, \"metadata\");\n\t\t} catch (error) {\n\t\t\terrors.push(errorMessage(error));\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\tindex,\n\t\t\t\tfragmentId: typeof value.fragmentId === \"string\" ? value.fragmentId : undefined,\n\t\t\t\tvalue,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\ttext: Object.freeze({\n\t\t\tfragmentId: value.fragmentId as string,\n\t\t\ttext: value.text as string,\n\t\t\t...(value.cost === undefined ? {} : { cost: value.cost as number }),\n\t\t\t...(value.metadata === undefined\n\t\t\t\t? {}\n\t\t\t\t: { metadata: Object.freeze({ ...(value.metadata as Record<string, StrictJsonValue>) }) }),\n\t\t}),\n\t};\n}\n\nfunction validatePackingPolicy(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): AgenticMemoryContextPackingPolicy | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy must be an object\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst validation: string[] = [];\n\tlet maxEntries: unknown;\n\tlet maxChars: unknown;\n\tlet maxCost: unknown;\n\tlet includeMetadata: unknown;\n\ttry {\n\t\tmaxEntries = value.maxEntries;\n\t\tmaxChars = value.maxChars;\n\t\tmaxCost = value.maxCost;\n\t\tincludeMetadata = value.includeMetadata;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: policy access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"policy access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (\n\t\tmaxEntries !== undefined &&\n\t\t(typeof maxEntries !== \"number\" || !Number.isSafeInteger(maxEntries) || maxEntries < 0)\n\t) {\n\t\tvalidation.push(\"maxEntries must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxChars !== undefined &&\n\t\t(typeof maxChars !== \"number\" || !Number.isSafeInteger(maxChars) || maxChars < 0)\n\t) {\n\t\tvalidation.push(\"maxChars must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxCost !== undefined &&\n\t\t(typeof maxCost !== \"number\" || !Number.isFinite(maxCost) || maxCost < 0)\n\t) {\n\t\tvalidation.push(\"maxCost must be a finite number >= 0\");\n\t}\n\tif (includeMetadata !== undefined && typeof includeMetadata !== \"boolean\") {\n\t\tvalidation.push(\"includeMetadata must be a boolean when present\");\n\t}\n\tif (validation.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy is invalid\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: Object.freeze(validation),\n\t\t});\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\t...(maxEntries === undefined ? {} : { maxEntries: maxEntries as number }),\n\t\t...(maxChars === undefined ? {} : { maxChars: maxChars as number }),\n\t\t...(maxCost === undefined ? {} : { maxCost: maxCost as number }),\n\t\t...(includeMetadata === undefined ? {} : { includeMetadata: includeMetadata as boolean }),\n\t});\n}\n\nfunction validateAndProjectRecords<T>(value: unknown): {\n\treadonly records: AgenticMemoryRecord<T>[];\n\treadonly fragments: MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Record<FactId, AgenticMemoryRecordMetadata>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\treadonly invalidRecordIndexes: Set<number>;\n} {\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tconst fragments: MemoryFragment<T>[] = [];\n\tconst metadataByFragmentId = Object.create(null) as Record<FactId, AgenticMemoryRecordMetadata>;\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tconst invalidRecordIndexes = new Set<number>();\n\tconst seenRecordIds = new Set<FactId>();\n\tconst seenFragmentIds = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input must be an array\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input length could not be read\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-record\",\n\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = validateAndSnapshotRecord<T>(raw, i);\n\t\tif (result.errors.length > 0) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push(...result.errors);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.record === undefined) continue;\n\t\tif (seenRecordIds.has(result.record.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-record-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate record id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate record id '${result.record.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (seenFragmentIds.has(result.record.fragment.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate fragment id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\tfragmentId: result.record.fragment.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate fragment id '${result.record.fragment.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenRecordIds.add(result.record.id);\n\t\tseenFragmentIds.add(result.record.fragment.id);\n\t\trecords.push(result.record);\n\t\tfragments.push(result.record.fragment);\n\t\tmetadataByFragmentId[result.record.fragment.id] = recordMetadata(result.record);\n\t}\n\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n}\n\nfunction validateAndSnapshotRecord<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\ttry {\n\t\treturn validateAndSnapshotRecordInner<T>(value, index);\n\t} catch (error) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateAndSnapshotRecordInner<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: \"agenticMemoryBundle: record must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst record = value as Partial<AgenticMemoryRecord<T>> & Record<string, unknown>;\n\tconst recordId = typeof record.id === \"string\" ? record.id : undefined;\n\tif (recordId === undefined || recordId.length === 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record.id must be a non-empty string\",\n\t\t\tindex,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"record.id must be a non-empty string\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryKind(record.kind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.kind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"kind must be one of working, episodic, semantic, procedural, profile\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(record.persistenceLevel)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-persistence-level\",\n\t\t\tmessage: \"agenticMemoryBundle: record.persistenceLevel is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\n\t\t\t\t\"persistenceLevel must be one of turn, session, project, longTerm, permanent, archived\",\n\t\t\t],\n\t\t});\n\t}\n\tif (!isAgenticMemoryArtifactKind(record.artifactKind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-artifact-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.artifactKind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"artifactKind must be one of raw, insight, profile, procedure\"],\n\t\t});\n\t}\n\tconst scopeValidation = validateScope(record.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-scope\",\n\t\t\tmessage: \"agenticMemoryBundle: record.scope is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(scopeValidation.errors),\n\t\t});\n\t}\n\tconst fragmentValidation = validateMemoryFragment(record.fragment);\n\tif (!fragmentValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-fragment\",\n\t\t\tmessage: \"agenticMemoryBundle: record.fragment is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\tfragmentId:\n\t\t\t\ttypeof record.fragment === \"object\" &&\n\t\t\t\trecord.fragment !== null &&\n\t\t\t\ttypeof (record.fragment as Partial<MemoryFragment>).id === \"string\"\n\t\t\t\t\t? (record.fragment as Partial<MemoryFragment>).id\n\t\t\t\t\t: undefined,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze([...fragmentValidation.errors]),\n\t\t});\n\t}\n\tconst forbiddenFields = [\n\t\t\"storageTier\",\n\t\t\"storageKey\",\n\t\t\"adapter\",\n\t\t\"collection\",\n\t\t\"collections\",\n\t\t\"ttl\",\n\t\t\"ttlMs\",\n\t\t\"ttlNs\",\n\t\t\"expiresAt\",\n\t\t\"timer\",\n\t\t\"scheduler\",\n\t\t\"schedule\",\n\t\t\"retentionTimer\",\n\t\t\"consolidationSchedule\",\n\t\t\"reflectionSchedule\",\n\t\t\"llm\",\n\t\t\"llmHandle\",\n\t\t\"tool\",\n\t\t\"toolHandle\",\n\t\t\"runner\",\n\t\t\"runnerHandle\",\n\t\t\"restore\",\n\t\t\"hydrate\",\n\t\t\"hydration\",\n\t\t\"graphMutation\",\n\t\t\"protocol\",\n\t] as const;\n\tconst presentForbidden = forbiddenFields.filter((field) => Object.hasOwn(record, field));\n\tif (presentForbidden.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record contains forbidden runtime/persistence fields\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\tpresentForbidden.map((field) => `${field} is not part of AgenticMemoryRecord`),\n\t\t\t),\n\t\t});\n\t}\n\tif (errors.length > 0) return { errors };\n\tconst scope = scopeValidation.scope;\n\tconst fragment = snapshotFragment(record.fragment as MemoryFragment<T>);\n\treturn {\n\t\trecord: Object.freeze({\n\t\t\tid: recordId as FactId,\n\t\t\tkind: record.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: record.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: record.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tfragment,\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordMetadata(record: AgenticMemoryRecord): AgenticMemoryRecordMetadata {\n\treturn Object.freeze({\n\t\trecordId: record.id,\n\t\tkind: record.kind,\n\t\tpersistenceLevel: record.persistenceLevel,\n\t\tartifactKind: record.artifactKind,\n\t\t...(record.scope === undefined ? {} : { scope: record.scope }),\n\t});\n}\n\nfunction validateRecordMetadata(value: unknown): {\n\treadonly ok: boolean;\n\treadonly metadata?: AgenticMemoryRecordMetadata;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (!isPlainRecord(value)) {\n\t\treturn { ok: false, errors: [\"record metadata must be an object when present\"] };\n\t}\n\tconst errors: string[] = [];\n\tfor (const key of Object.keys(value)) {\n\t\tif (\n\t\t\tkey !== \"recordId\" &&\n\t\t\tkey !== \"kind\" &&\n\t\t\tkey !== \"persistenceLevel\" &&\n\t\t\tkey !== \"artifactKind\" &&\n\t\t\tkey !== \"scope\"\n\t\t) {\n\t\t\terrors.push(`record.${key} is not part of AgenticMemoryRecordMetadata`);\n\t\t}\n\t}\n\tif (!isNonEmptyString(value.recordId)) {\n\t\terrors.push(\"record.recordId must be a non-empty string\");\n\t}\n\tif (!isAgenticMemoryKind(value.kind)) {\n\t\terrors.push(\"record.kind is invalid\");\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\terrors.push(\"record.persistenceLevel is invalid\");\n\t}\n\tif (!isAgenticMemoryArtifactKind(value.artifactKind)) {\n\t\terrors.push(\"record.artifactKind is invalid\");\n\t}\n\tconst scopeValidation = validateScope(value.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push(...scopeValidation.errors.map((error) => `record.${error}`));\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tmetadata: Object.freeze({\n\t\t\trecordId: value.recordId as FactId,\n\t\t\tkind: value.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: value.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scopeValidation.scope === undefined ? {} : { scope: scopeValidation.scope }),\n\t\t}),\n\t};\n}\n\nfunction contextState(\n\tprojection: AgenticMemoryStatusState,\n\tretrieval: MemoryRetrievalStatus[\"state\"],\n): AgenticMemoryContextState {\n\tif (projection === \"error\" || retrieval === \"error\") return \"error\";\n\tif (projection === \"partial\" || retrieval === \"partial\") return \"partial\";\n\treturn retrieval;\n}\n\nfunction agenticStatusState(errorCount: number, validRecords: number): AgenticMemoryStatusState {\n\tif (errorCount > 0 && validRecords === 0) return \"error\";\n\tif (errorCount > 0) return \"partial\";\n\treturn validRecords > 0 ? \"ready\" : \"empty\";\n}\n\nfunction isAgenticMemoryKind(value: unknown): value is AgenticMemoryKind {\n\treturn (\n\t\tvalue === \"working\" ||\n\t\tvalue === \"episodic\" ||\n\t\tvalue === \"semantic\" ||\n\t\tvalue === \"procedural\" ||\n\t\tvalue === \"profile\"\n\t);\n}\n\nfunction isAgenticMemoryPersistenceLevel(value: unknown): value is AgenticMemoryPersistenceLevel {\n\treturn (\n\t\tvalue === \"turn\" ||\n\t\tvalue === \"session\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"longTerm\" ||\n\t\tvalue === \"permanent\" ||\n\t\tvalue === \"archived\"\n\t);\n}\n\nfunction isAgenticMemoryArtifactKind(value: unknown): value is AgenticMemoryArtifactKind {\n\treturn value === \"raw\" || value === \"insight\" || value === \"profile\" || value === \"procedure\";\n}\n\nfunction validateScope(value: unknown): {\n\treadonly ok: boolean;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn { ok: false, errors: [\"scope must be an object when present\"] };\n\t}\n\tconst scope = value as Record<string, unknown>;\n\tconst errors: string[] = [];\n\tconst allowed = new Set([\"sessionId\", \"projectId\", \"userId\", \"tenantId\"]);\n\tfor (const key of Object.keys(scope)) {\n\t\tif (!allowed.has(key)) errors.push(`scope.${key} is not part of AgenticMemoryScope`);\n\t}\n\tfor (const key of allowed) {\n\t\tif (scope[key] !== undefined && (typeof scope[key] !== \"string\" || scope[key].length === 0)) {\n\t\t\terrors.push(`scope.${key} must be a non-empty string when present`);\n\t\t}\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tscope: Object.freeze({\n\t\t\t...(scope.sessionId === undefined ? {} : { sessionId: scope.sessionId as string }),\n\t\t\t...(scope.projectId === undefined ? {} : { projectId: scope.projectId as string }),\n\t\t\t...(scope.userId === undefined ? {} : { userId: scope.userId as string }),\n\t\t\t...(scope.tenantId === undefined ? {} : { tenantId: scope.tenantId as string }),\n\t\t}),\n\t};\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nfunction assertExactKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertAgenticMemoryRecordCodecShape(value: unknown): void {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertNoSymbolKeys(value, \"agenticMemoryRecordFrame.record\");\n\tassertExactKeys(\n\t\tvalue,\n\t\tvalue.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst fragment = value.fragment;\n\tif (!isPlainRecord(fragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertNoSymbolKeys(fragment, \"agenticMemoryRecordFrame.record.fragment\");\n\tassertExactKeys(\n\t\tfragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(fragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(fragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(fragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(fragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(fragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tassertStrictJsonValue(fragment.tags, \"record.fragment.tags\");\n\tassertStrictJsonValue(fragment.sources, \"record.fragment.sources\");\n\tif (fragment.embedding !== undefined) {\n\t\tassertStrictJsonValue(fragment.embedding, \"record.fragment.embedding\");\n\t}\n\tif (value.scope !== undefined) assertScopeFrame(value.scope);\n}\n\nfunction assertNoSymbolKeys(value: object, label: string): void {\n\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\tthrow new TypeError(`${label}: unexpected symbol fields`);\n\t}\n}\n\nfunction decimalBigIntString(value: bigint, label: string): string {\n\tconst out = value.toString(10);\n\tif (!/^-?(0|[1-9]\\d*)$/.test(out)) {\n\t\tthrow new TypeError(`${label} must encode as a canonical decimal bigint string`);\n\t}\n\treturn out;\n}\n\nfunction parseDecimalBigInt(value: unknown, label: string): bigint {\n\tif (typeof value !== \"string\" || !/^(0|-?[1-9]\\d*)$/.test(value)) {\n\t\tthrow new TypeError(`${label} must be a canonical decimal bigint string`);\n\t}\n\treturn BigInt(value);\n}\n\nfunction assertStrictJsonValue(value: unknown, label: string): StrictJsonValue {\n\ttry {\n\t\tstrictJsonCodec.encode(value);\n\t\treturn value as StrictJsonValue;\n\t} catch (error) {\n\t\tthrow new TypeError(`${label} must be strict JSON: ${errorMessage(error)}`);\n\t}\n}\n\nfunction assertScopeFrame(value: unknown): AgenticMemoryScope {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: scope must be an object when present\");\n\t}\n\tassertStrictJsonValue(value, \"record.scope\");\n\tconst validation = validateScope(value);\n\tif (!validation.ok || validation.scope === undefined) {\n\t\tthrow new TypeError(`agenticMemoryRecordFrame: invalid scope: ${validation.errors.join(\"; \")}`);\n\t}\n\tassertExactKeys(\n\t\tvalue as Record<string, unknown>,\n\t\t[\n\t\t\t...((value as Record<string, unknown>).sessionId === undefined ? [] : [\"sessionId\"]),\n\t\t\t...((value as Record<string, unknown>).projectId === undefined ? [] : [\"projectId\"]),\n\t\t\t...((value as Record<string, unknown>).userId === undefined ? [] : [\"userId\"]),\n\t\t\t...((value as Record<string, unknown>).tenantId === undefined ? [] : [\"tenantId\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.scope\",\n\t);\n\treturn validation.scope;\n}\n\nfunction assertKindValue(value: unknown): AgenticMemoryKind {\n\tif (!isAgenticMemoryKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid memory kind\");\n\t}\n\treturn value;\n}\n\nfunction assertPersistenceLevelValue(value: unknown): AgenticMemoryPersistenceLevel {\n\tif (!isAgenticMemoryPersistenceLevel(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid persistence level\");\n\t}\n\treturn value;\n}\n\nfunction assertArtifactKindValue(value: unknown): AgenticMemoryArtifactKind {\n\tif (!isAgenticMemoryArtifactKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid artifact kind\");\n\t}\n\treturn value;\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): string {\n\tif (!isNonEmptyString(value)) throw new TypeError(`${label} must be a non-empty string`);\n\treturn value;\n}\n\nfunction assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new TypeError(`${label} must be a string`);\n\treturn value;\n}\n\nfunction assertConfidence(value: unknown, label: string): number {\n\tif (!Number.isFinite(value) || (value as number) < 0 || (value as number) > 1) {\n\t\tthrow new TypeError(`${label} must be a finite number in [0, 1]`);\n\t}\n\treturn value as number;\n}\n\nfunction assertStringArray(value: unknown, label: string): readonly string[] {\n\tif (!isDenseArrayOf(value, (item): item is string => typeof item === \"string\")) {\n\t\tthrow new TypeError(`${label} must be a readonly string array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction assertFiniteNumberArray(value: unknown, label: string): readonly number[] {\n\tif (!isDenseArrayOf(value, (item): item is number => Number.isFinite(item))) {\n\t\tthrow new TypeError(`${label} must be a finite number array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction freezeError<T extends { readonly validationErrors?: readonly string[] }>(error: T): T {\n\treturn Object.freeze({\n\t\t...error,\n\t\t...(error.validationErrors === undefined\n\t\t\t? {}\n\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t}) as T;\n}\n\nfunction safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport { assertGraphLocalNode, type Graph, type StateNode } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport {\n\ttype AgenticMemoryRecord,\n\ttype AgenticMemoryRecordFrame,\n\ttype AgenticMemoryStrictJsonValue,\n\tagenticMemoryRecordCodec,\n\tagenticMemoryRecordFrame,\n\tagenticMemoryRecordFrameCodec,\n\tassertAgenticMemoryRecordFrame,\n} from \"../solutions/index.js\";\nimport type { AppendLogEntry, AppendLogStorageTier, KvStorageTier } from \"../storage/index.js\";\n\nexport const AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT =\n\t\"graphrefly.agenticMemory.records.snapshot\" as const;\nexport const AGENTIC_MEMORY_RECORD_CHANGE_FORMAT =\n\t\"graphrefly.agenticMemory.records.change\" as const;\nexport const AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION = 1 as const;\n\nexport interface AgenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION;\n\treadonly changeCursor: number;\n\treadonly records: readonly AgenticMemoryRecordFrame<TJson>[];\n}\n\nexport interface AgenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_CHANGE_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION;\n\treadonly change: {\n\t\treadonly kind: \"replaceAll\";\n\t\treadonly records: readonly AgenticMemoryRecordFrame<TJson>[];\n\t};\n}\n\nexport interface AgenticMemoryRecordsRestoreState<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly records: readonly AgenticMemoryRecord<TJson>[];\n\treadonly source: \"empty\" | \"changes\" | \"snapshot\" | \"snapshot+changes\";\n\treadonly snapshot: { readonly found: boolean; readonly changeCursor: number };\n\treadonly changes: { readonly applied: number; readonly cursor: number };\n}\n\nexport interface LoadAgenticMemoryRecordsStateOptions {\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n}\n\nexport interface AgenticMemoryRecordsPersistenceCursor {\n\treadonly kind: \"persistence.cursor\";\n\treadonly changeSeq: number;\n\treadonly snapshotWrites: number;\n\treadonly changeWrites: number;\n}\n\nexport interface AgenticMemoryRecordsPersistenceStatus {\n\treadonly state: \"starting\" | \"ready\" | \"flushing\" | \"errored\" | \"disposed\";\n\treadonly pending: number;\n\treadonly writes: number;\n\treadonly errors: number;\n\treadonly cursor: AgenticMemoryRecordsPersistenceCursor;\n}\n\nexport interface AgenticMemoryRecordsPersistenceError {\n\treadonly phase: \"snapshot\" | \"change\";\n\treadonly message: string;\n\treadonly cursor: AgenticMemoryRecordsPersistenceCursor;\n}\n\nexport interface PersistAgenticMemoryRecordsOptions {\n\treadonly name?: string;\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n\treadonly initialChangeCursor?: number;\n\treadonly snapshotOnAttach?: boolean;\n\treadonly snapshotEveryChanges?: number;\n}\n\nexport interface AgenticMemoryRecordsPersistenceHandle {\n\treadonly ready: StateNode<boolean>;\n\treadonly status: StateNode<AgenticMemoryRecordsPersistenceStatus>;\n\treadonly error: StateNode<AgenticMemoryRecordsPersistenceError | null>;\n\treadonly cursor: StateNode<AgenticMemoryRecordsPersistenceCursor>;\n\tflush(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n\tsnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n\tdispose(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n}\n\nexport interface OpenPersistentAgenticMemoryRecordsOptions<\n\tTJson extends AgenticMemoryStrictJsonValue,\n> extends LoadAgenticMemoryRecordsStateOptions,\n\t\tOmit<\n\t\t\tPersistAgenticMemoryRecordsOptions,\n\t\t\t\"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly AgenticMemoryRecord<TJson>[];\n}\n\nexport interface PersistentAgenticMemoryRecords<TJson extends AgenticMemoryStrictJsonValue> {\n\treadonly records: StateNode<readonly AgenticMemoryRecord<TJson>[]>;\n\treadonly persistence: AgenticMemoryRecordsPersistenceHandle;\n\treadonly loaded: AgenticMemoryRecordsRestoreState<TJson>;\n}\n\ninterface QueueItem {\n\treadonly phase: \"snapshot\" | \"change\" | \"flush\" | \"dispose\";\n\treadonly done?: (status: AgenticMemoryRecordsPersistenceStatus) => void;\n\trun(): void | PromiseLike<void>;\n}\n\nexport function agenticMemoryRecordsSnapshotKey(storagePrefix = \"agentic-memory\"): string {\n\tif (storagePrefix.length === 0) throw new TypeError(\"storagePrefix must be non-empty\");\n\treturn `${storagePrefix}/records.snapshot`;\n}\n\nexport function agenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\trecords: readonly AgenticMemoryRecord<TJson>[],\n\topts: { readonly changeCursor?: number } = {},\n): AgenticMemoryRecordSnapshotFrame<TJson> {\n\tconst changeCursor = validateChangeCursor(opts.changeCursor ?? -1);\n\treturn assertAgenticMemoryRecordSnapshotFrame({\n\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchangeCursor,\n\t\trecords: records.map((record) => agenticMemoryRecordFrame(record)),\n\t});\n}\n\nexport function agenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(records: readonly AgenticMemoryRecord<TJson>[]): AgenticMemoryRecordChangeFrame<TJson> {\n\treturn assertAgenticMemoryRecordChangeFrame({\n\t\tformat: AGENTIC_MEMORY_RECORD_CHANGE_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchange: {\n\t\t\tkind: \"replaceAll\",\n\t\t\trecords: records.map((record) => agenticMemoryRecordFrame(record)),\n\t\t},\n\t});\n}\n\nexport function assertAgenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(value: unknown): AgenticMemoryRecordSnapshotFrame<TJson> {\n\tif (!isPlainRecord(value)) throw new TypeError(\"agentic memory snapshot frame must be an object\");\n\tassertKeys(\n\t\tvalue,\n\t\t[\"changeCursor\", \"format\", \"records\", \"version\"],\n\t\t\"agentic memory snapshot frame\",\n\t);\n\tif (value.format !== AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: invalid version\");\n\t}\n\tconst changeCursor = validateChangeCursor(value.changeCursor);\n\tif (!Array.isArray(value.records)) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: records must be an array\");\n\t}\n\tconst records = assertDenseRecordFrames<TJson>(\n\t\tvalue.records,\n\t\t\"agentic memory snapshot frame records\",\n\t);\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchangeCursor,\n\t\trecords: Object.freeze(records),\n\t});\n}\n\nexport function assertAgenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(value: unknown): AgenticMemoryRecordChangeFrame<TJson> {\n\tif (!isPlainRecord(value)) throw new TypeError(\"agentic memory change frame must be an object\");\n\tassertKeys(value, [\"change\", \"format\", \"version\"], \"agentic memory change frame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_CHANGE_FORMAT) {\n\t\tthrow new TypeError(\"agentic memory change frame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agentic memory change frame: invalid version\");\n\t}\n\tif (!isPlainRecord(value.change)) {\n\t\tthrow new TypeError(\"agentic memory change frame: change must be an object\");\n\t}\n\tassertKeys(value.change, [\"kind\", \"records\"], \"agentic memory change frame change\");\n\tif (value.change.kind !== \"replaceAll\") {\n\t\tthrow new TypeError(\"agentic memory change frame: change.kind must be replaceAll\");\n\t}\n\tif (!Array.isArray(value.change.records)) {\n\t\tthrow new TypeError(\"agentic memory change frame: change.records must be an array\");\n\t}\n\tconst records = assertDenseRecordFrames<TJson>(\n\t\tvalue.change.records,\n\t\t\"agentic memory change frame records\",\n\t);\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_CHANGE_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchange: Object.freeze({\n\t\t\tkind: \"replaceAll\",\n\t\t\trecords: Object.freeze(records),\n\t\t}),\n\t});\n}\n\nexport function loadAgenticMemoryRecordsState<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(opts: LoadAgenticMemoryRecordsStateOptions): Promise<AgenticMemoryRecordsRestoreState<TJson>> {\n\tconst storagePrefix = opts.storagePrefix ?? \"agentic-memory\";\n\tconst snapshotKey = opts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(storagePrefix);\n\treturn opts.snapshotStore.get(snapshotKey).then((rawSnapshot) => {\n\t\tlet records: readonly AgenticMemoryRecord<TJson>[] = [];\n\t\tlet source: AgenticMemoryRecordsRestoreState<TJson>[\"source\"] = \"empty\";\n\t\tlet changeCursor = -1;\n\t\tif (rawSnapshot !== undefined) {\n\t\t\tconst snapshot = assertAgenticMemoryRecordSnapshotFrame<TJson>(rawSnapshot);\n\t\t\trecords = snapshot.records.map(recordFromFrame);\n\t\t\tchangeCursor = snapshot.changeCursor;\n\t\t\tsource = \"snapshot\";\n\t\t}\n\t\tif (opts.changeLog === undefined) {\n\t\t\treturn {\n\t\t\t\trecords,\n\t\t\t\tsource,\n\t\t\t\tsnapshot: { found: rawSnapshot !== undefined, changeCursor },\n\t\t\t\tchanges: { applied: 0, cursor: changeCursor },\n\t\t\t};\n\t\t}\n\t\treturn opts.changeLog.read({ after: changeCursor }).then((entries) => {\n\t\t\tlet applied = 0;\n\t\t\tlet cursor = changeCursor;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.seq !== cursor + 1) {\n\t\t\t\t\tthrow new Error(\"agentic memory records change log is non-contiguous\");\n\t\t\t\t}\n\t\t\t\tconst change = assertAgenticMemoryRecordChangeFrame<TJson>(entry.value);\n\t\t\t\trecords = change.change.records.map(recordFromFrame);\n\t\t\t\tcursor = entry.seq;\n\t\t\t\tapplied += 1;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trecords,\n\t\t\t\tsource:\n\t\t\t\t\trawSnapshot !== undefined && applied > 0\n\t\t\t\t\t\t? \"snapshot+changes\"\n\t\t\t\t\t\t: rawSnapshot !== undefined\n\t\t\t\t\t\t\t? \"snapshot\"\n\t\t\t\t\t\t\t: applied > 0\n\t\t\t\t\t\t\t\t? \"changes\"\n\t\t\t\t\t\t\t\t: \"empty\",\n\t\t\t\tsnapshot: { found: rawSnapshot !== undefined, changeCursor },\n\t\t\t\tchanges: { applied, cursor },\n\t\t\t};\n\t\t});\n\t});\n}\n\nexport function persistAgenticMemoryRecords<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<TJson>[]>,\n\topts: PersistAgenticMemoryRecordsOptions,\n): AgenticMemoryRecordsPersistenceHandle {\n\tconst name = opts.name ?? \"agenticMemoryRecords.persistence\";\n\tconst snapshotKey =\n\t\topts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(opts.storagePrefix ?? name);\n\tconst snapshotEveryChanges = validateSnapshotEveryChanges(opts.snapshotEveryChanges);\n\tassertGraphLocalNode(graph, records as Node<unknown>, `${name}.records`);\n\tlet cursorValue: AgenticMemoryRecordsPersistenceCursor = {\n\t\tkind: \"persistence.cursor\",\n\t\tchangeSeq: validateChangeCursor(opts.initialChangeCursor ?? -1),\n\t\tsnapshotWrites: 0,\n\t\tchangeWrites: 0,\n\t};\n\tlet statusValue = statusOf(\"starting\", 0, 0, 0, cursorValue);\n\tlet errorCount = 0;\n\tlet writes = 0;\n\tlet running = false;\n\tlet disposed = false;\n\tlet disposeRequested = false;\n\tlet subscribing = true;\n\tlet observedChangesSinceSnapshot = 0;\n\tlet latestRecords: readonly AgenticMemoryRecord<TJson>[] = records.cache ?? [];\n\tlet stop: (() => void) | undefined;\n\tconst queue: QueueItem[] = [];\n\tconst ready = graph.state(false, { name: `${name}/ready` });\n\tconst status = graph.state<AgenticMemoryRecordsPersistenceStatus>(statusValue, {\n\t\tname: `${name}/status`,\n\t});\n\tconst error = graph.state<AgenticMemoryRecordsPersistenceError | null>(null, {\n\t\tname: `${name}/error`,\n\t});\n\tconst cursor = graph.state<AgenticMemoryRecordsPersistenceCursor>(cursorValue, {\n\t\tname: `${name}/cursor`,\n\t});\n\n\tfunction publish(state: AgenticMemoryRecordsPersistenceStatus[\"state\"]): void {\n\t\tconst nextState = statusValue.state === \"errored\" && state !== \"disposed\" ? \"errored\" : state;\n\t\tstatusValue = statusOf(\n\t\t\tnextState,\n\t\t\tqueue.length + (running ? 1 : 0),\n\t\t\twrites,\n\t\t\terrorCount,\n\t\t\tcursorValue,\n\t\t);\n\t\tcursor.set(cursorValue);\n\t\tstatus.set(statusValue);\n\t\tif (nextState === \"ready\") ready.set(true);\n\t\tif (nextState === \"errored\" || nextState === \"disposed\") ready.set(false);\n\t}\n\n\tfunction report(phase: \"snapshot\" | \"change\", caught: unknown): void {\n\t\terrorCount += 1;\n\t\terror.set({ phase, message: errorMessage(caught), cursor: cursorValue });\n\t}\n\n\tfunction callDone(done: QueueItem[\"done\"]): void {\n\t\ttry {\n\t\t\tdone?.(statusValue);\n\t\t} catch {\n\t\t\t// Done callbacks are advisory controls and must not wedge the adapter queue.\n\t\t}\n\t}\n\n\tfunction finish(item: QueueItem): void {\n\t\tif (item.phase === \"dispose\") {\n\t\t\tdisposed = true;\n\t\t\trunning = false;\n\t\t\tpublish(\"disposed\");\n\t\t} else if (statusValue.state !== \"errored\") {\n\t\t\trunning = false;\n\t\t\tpublish(\"ready\");\n\t\t} else {\n\t\t\trunning = false;\n\t\t\tpublish(\"errored\");\n\t\t}\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction fail(item: QueueItem, caught: unknown): void {\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") report(item.phase, caught);\n\t\trunning = false;\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") publish(\"errored\");\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction chainThenable(item: QueueItem, value: unknown): boolean {\n\t\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return false;\n\t\tconst then = (value as { then?: unknown }).then;\n\t\tif (typeof then !== \"function\") return false;\n\t\tlet settled = false;\n\t\tconst settle = (next: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tnext();\n\t\t};\n\t\ttry {\n\t\t\t(then as (onFulfilled: () => void, onRejected: (error: unknown) => void) => unknown).call(\n\t\t\t\tvalue,\n\t\t\t\t() => settle(() => finish(item)),\n\t\t\t\t(caught) => settle(() => fail(item, caught)),\n\t\t\t);\n\t\t} catch (caught) {\n\t\t\tsettle(() => fail(item, caught));\n\t\t}\n\t\treturn true;\n\t}\n\n\tfunction enqueue(item: QueueItem): void {\n\t\tif (disposed || (disposeRequested && item.phase !== \"dispose\" && item.phase !== \"flush\")) {\n\t\t\tcallDone(item.done);\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(item);\n\t\tdrain();\n\t}\n\n\tfunction drain(): void {\n\t\tif (running) return;\n\t\tconst item = queue.shift();\n\t\tif (item === undefined) return;\n\t\trunning = true;\n\t\tpublish(\n\t\t\titem.phase === \"flush\" ? \"flushing\" : statusValue.state === \"starting\" ? \"starting\" : \"ready\",\n\t\t);\n\t\tlet result: void | PromiseLike<void>;\n\t\ttry {\n\t\t\tresult = item.run();\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn;\n\t\t}\n\t\tif (chainThenable(item, result)) return;\n\t\tfinish(item);\n\t}\n\n\tfunction enqueueSnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\tconst snapshotRecords = latestRecords;\n\t\tobservedChangesSinceSnapshot = 0;\n\t\tenqueue({\n\t\t\tphase: \"snapshot\",\n\t\t\tdone,\n\t\t\trun() {\n\t\t\t\tconst records = Object.freeze(\n\t\t\t\t\tsnapshotRecords.map((record) => agenticMemoryRecordFrame(record)),\n\t\t\t\t);\n\t\t\t\tconst frame = assertAgenticMemoryRecordSnapshotFrame<TJson>({\n\t\t\t\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\t\t\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\t\t\t\tchangeCursor: cursorValue.changeSeq,\n\t\t\t\t\trecords,\n\t\t\t\t});\n\t\t\t\treturn opts.snapshotStore.set(snapshotKey, frame).then(() => {\n\t\t\t\t\tcursorValue = { ...cursorValue, snapshotWrites: cursorValue.snapshotWrites + 1 };\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction enqueueChange(nextRecords: readonly AgenticMemoryRecord<TJson>[]): void {\n\t\tconst changeLog = opts.changeLog;\n\t\tif (changeLog === undefined) return;\n\t\tenqueue({\n\t\t\tphase: \"change\",\n\t\t\trun() {\n\t\t\t\tconst frame = agenticMemoryRecordChangeFrame(nextRecords);\n\t\t\t\treturn changeLog.append(frame).then((written) => {\n\t\t\t\t\tconst entry = written as AppendLogEntry<AgenticMemoryRecordChangeFrame<TJson>>;\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tchangeSeq: entry.seq,\n\t\t\t\t\t\tchangeWrites: cursorValue.changeWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction cancelQueuedForDispose(): void {\n\t\tconst pending = queue.splice(0);\n\t\tfor (const item of pending) callDone(item.done);\n\t}\n\n\tstop = records.subscribe((msg: Message, delivery?: DeliveryMeta) => {\n\t\tif (disposeRequested) return;\n\t\tconst nextRecords = dataOf<readonly AgenticMemoryRecord<TJson>[]>(msg);\n\t\tif (nextRecords === undefined) return;\n\t\tlatestRecords = nextRecords;\n\t\tif (subscribing && delivery === undefined) return;\n\t\tobservedChangesSinceSnapshot += 1;\n\t\tenqueueChange(nextRecords);\n\t\tif (\n\t\t\tsnapshotEveryChanges !== undefined &&\n\t\t\tobservedChangesSinceSnapshot >= snapshotEveryChanges\n\t\t) {\n\t\t\tenqueueSnapshot();\n\t\t}\n\t});\n\tsubscribing = false;\n\tif (opts.snapshotOnAttach !== false) enqueueSnapshot();\n\telse publish(\"ready\");\n\n\treturn {\n\t\tready,\n\t\tstatus,\n\t\terror,\n\t\tcursor,\n\t\tflush(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueue({ phase: \"flush\", done, run: () => undefined });\n\t\t},\n\t\tsnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed || disposeRequested) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueueSnapshot(done);\n\t\t},\n\t\tdispose(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdisposeRequested = true;\n\t\t\tstop?.();\n\t\t\tcancelQueuedForDispose();\n\t\t\tenqueue({ phase: \"dispose\", done, run: () => undefined });\n\t\t},\n\t};\n}\n\nexport function openPersistentAgenticMemoryRecords<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\topts: OpenPersistentAgenticMemoryRecordsOptions<TJson>,\n): Promise<PersistentAgenticMemoryRecords<TJson>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"agentic-memory\";\n\tconst snapshotKey = opts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(storagePrefix);\n\treturn loadAgenticMemoryRecordsState<TJson>({ ...opts, snapshotKey, storagePrefix }).then(\n\t\t(loaded) => {\n\t\t\tconst records =\n\t\t\t\tloaded.source === \"empty\" && opts.initial !== undefined ? opts.initial : loaded.records;\n\t\t\tconst node = opts.graph.state<readonly AgenticMemoryRecord<TJson>[]>(records, {\n\t\t\t\tname: opts.name,\n\t\t\t});\n\t\t\tconst persistence = persistAgenticMemoryRecords(opts.graph, node, {\n\t\t\t\t...opts,\n\t\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\t\tsnapshotKey,\n\t\t\t\tstoragePrefix,\n\t\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t\t});\n\t\t\treturn { records: node, persistence, loaded };\n\t\t},\n\t);\n}\n\nfunction recordFromFrame<TJson extends AgenticMemoryStrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\treturn agenticMemoryRecordCodec<TJson>().decode(\n\t\tagenticMemoryRecordFrameCodec<TJson>().encode(frame),\n\t);\n}\n\nfunction statusOf(\n\tstate: AgenticMemoryRecordsPersistenceStatus[\"state\"],\n\tpending: number,\n\twrites: number,\n\terrors: number,\n\tcursor: AgenticMemoryRecordsPersistenceCursor,\n): AgenticMemoryRecordsPersistenceStatus {\n\treturn { state, pending, writes, errors, cursor };\n}\n\nfunction dataOf<C>(msg: Message): C | undefined {\n\treturn msg[0] === \"DATA\" ? (msg[1] as C) : undefined;\n}\n\nfunction validateChangeCursor(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < -1) {\n\t\tthrow new RangeError(\"changeCursor must be a safe integer >= -1\");\n\t}\n\treturn value;\n}\n\nfunction validateSnapshotEveryChanges(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new RangeError(\"snapshotEveryChanges must be a positive safe integer\");\n\t}\n\treturn value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = Object.keys(value).sort();\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected frame fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertDenseRecordFrames<TJson extends AgenticMemoryStrictJsonValue>(\n\tvalue: readonly unknown[],\n\tlabel: string,\n): readonly AgenticMemoryRecordFrame<TJson>[] {\n\tconst records: AgenticMemoryRecordFrame<TJson>[] = [];\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i)) {\n\t\t\tthrow new TypeError(`${label}: sparse array hole at ${i}`);\n\t\t}\n\t\trecords.push(assertAgenticMemoryRecordFrame<TJson>(value[i]));\n\t}\n\treturn Object.freeze(records);\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Passive resilience policy helpers for graph-visible adapters (D130/D132).\n *\n * These helpers never schedule work and never own graph state. Drivers/adapters\n * consume them, while graph-visible bundles expose attempts/status/errors.\n */\n\nexport type BackoffPolicy =\n\t| { readonly kind: \"none\" }\n\t| { readonly kind: \"constant\"; readonly delayMs: number }\n\t| {\n\t\t\treadonly kind: \"linear\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly stepMs: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| {\n\t\t\treadonly kind: \"exponential\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly factor: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| { readonly kind: \"fibonacci\"; readonly unitMs: number; readonly maxMs?: number };\n\nexport interface RetryPolicy {\n\t/** Total attempts including the first try. */\n\treadonly maxAttempts: number;\n\treadonly backoff: BackoffPolicy;\n}\n\nexport type RetryState = \"idle\" | \"running\" | \"waiting\" | \"succeeded\" | \"failed\" | \"exhausted\";\n\nexport interface RetryStatus {\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly delayMs?: number;\n\treadonly state: RetryState;\n}\n\nexport const noBackoff: BackoffPolicy = Object.freeze({ kind: \"none\" });\n\nexport function retryPolicy(maxAttempts = 1, backoff: BackoffPolicy = noBackoff): RetryPolicy {\n\tif (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n\t\tthrow new RangeError(\"retryPolicy: maxAttempts must be a positive integer\");\n\t}\n\treturn Object.freeze({ maxAttempts, backoff });\n}\n\nexport function shouldRetry(policy: RetryPolicy, failedAttempt: number): boolean {\n\treturn failedAttempt < policy.maxAttempts;\n}\n\nexport function nextRetryDelayMs(policy: RetryPolicy, nextAttempt: number): number | undefined {\n\tif (!Number.isInteger(nextAttempt) || nextAttempt <= 0 || nextAttempt > policy.maxAttempts) {\n\t\treturn undefined;\n\t}\n\treturn backoffDelayMs(policy.backoff, nextAttempt);\n}\n\nexport function backoffDelayMs(policy: BackoffPolicy, attempt: number): number {\n\tconst safeAttempt = Math.max(1, Math.trunc(attempt));\n\tswitch (policy.kind) {\n\t\tcase \"none\":\n\t\t\treturn 0;\n\t\tcase \"constant\":\n\t\t\treturn nonNegative(policy.delayMs);\n\t\tcase \"linear\":\n\t\t\treturn cap(\n\t\t\t\tnonNegative(policy.initialMs) + nonNegative(policy.stepMs) * (safeAttempt - 1),\n\t\t\t\tpolicy.maxMs,\n\t\t\t);\n\t\tcase \"exponential\": {\n\t\t\tconst factor = Math.max(1, Math.trunc(policy.factor));\n\t\t\treturn cap(nonNegative(policy.initialMs) * factor ** (safeAttempt - 1), policy.maxMs);\n\t\t}\n\t\tcase \"fibonacci\":\n\t\t\treturn cap(nonNegative(policy.unitMs) * fibonacci(safeAttempt), policy.maxMs);\n\t}\n}\n\nfunction cap(value: number, max: number | undefined): number {\n\tif (max === undefined) return value;\n\treturn Math.min(value, nonNegative(max));\n}\n\nfunction nonNegative(value: number): number {\n\tif (!Number.isFinite(value)) return 0;\n\treturn Math.max(0, value);\n}\n\nfunction fibonacci(n: number): number {\n\tif (n <= 1) return 1;\n\tlet prev = 1;\n\tlet curr = 1;\n\tfor (let i = 2; i <= n; i += 1) {\n\t\tconst next = prev + curr;\n\t\tprev = curr;\n\t\tcurr = next;\n\t}\n\treturn curr;\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\tnextRetryDelayMs,\n\ttype RetryPolicy,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload, type Wave } from \"../protocol/messages.js\";\n\nexport type WireBridgeEnvelopeType =\n\t| \"start\"\n\t| \"data\"\n\t| \"ack\"\n\t| \"nack\"\n\t| \"status\"\n\t| \"error\"\n\t| \"close\";\n\nexport interface WireBridgeMetadata {\n\t/** Monotonic envelope sequence within the bridge session. */\n\treadonly seq: number;\n\t/** Monotonic accepted inbound cursor observed by the sending side. */\n\treadonly cursor: number;\n\t/** D151: correlation/idempotency metadata, not an authoritative duplicate lookup key. */\n\treadonly idempotencyKey: string;\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly timestampMs?: number;\n\t/** D151 ack/nack correlation target; receipt duplicate recognition still uses seq/cursor. */\n\treadonly ackForSeq?: number;\n\treadonly requestId?: string;\n}\n\nexport type WireBridgePayload<TData = unknown> =\n\t| { readonly kind: \"data\"; readonly value: TData }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"status\"; readonly status: unknown }\n\t| { readonly kind: \"close\"; readonly reason?: unknown };\n\nexport interface WireBridgeEnvelope<TData = unknown> {\n\treadonly sessionId: string;\n\treadonly type: WireBridgeEnvelopeType;\n\treadonly payload?: WireBridgePayload<TData>;\n\treadonly metadata: WireBridgeMetadata;\n}\n\nexport type WireBridgeCommand<TData = unknown> =\n\t| { readonly kind: \"start\"; readonly idempotencyKey?: string; readonly requestId?: string }\n\t| {\n\t\t\treadonly kind: \"send\";\n\t\t\treadonly payload: TData;\n\t\t\treadonly idempotencyKey?: string;\n\t\t\treadonly requestId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"ack\";\n\t\t\treadonly ackForSeq: number;\n\t\t\treadonly idempotencyKey?: string;\n\t\t\treadonly requestId?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"nack\";\n\t\t\treadonly ackForSeq: number;\n\t\t\treadonly error: unknown;\n\t\t\treadonly idempotencyKey?: string;\n\t\t\treadonly requestId?: string;\n\t }\n\t| { readonly kind: \"close\"; readonly reason?: unknown; readonly idempotencyKey?: string };\n\nexport type WireBridgeEvent<TOutbound = unknown, TInbound = unknown> =\n\t| {\n\t\t\treadonly kind: \"outbound\";\n\t\t\treadonly envelope: WireBridgeEnvelope<TOutbound>;\n\t }\n\t| {\n\t\t\treadonly kind: \"inbound\";\n\t\t\treadonly envelope: WireBridgeEnvelope<TInbound>;\n\t }\n\t| {\n\t\t\treadonly kind: \"ack\";\n\t\t\treadonly ackForSeq: number;\n\t\t\treadonly envelope: WireBridgeEnvelope<TInbound>;\n\t\t\treadonly outbound: WireBridgeEnvelope<TOutbound>;\n\t }\n\t| {\n\t\t\treadonly kind: \"nack\";\n\t\t\treadonly ackForSeq: number;\n\t\t\treadonly envelope: WireBridgeEnvelope<TInbound>;\n\t\t\treadonly outbound: WireBridgeEnvelope<TOutbound>;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"timeout\"; readonly seq: number; readonly attempt: number }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly seq: number;\n\t\t\treadonly attempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"exhausted\";\n\t\t\treadonly seq: number;\n\t\t\treadonly attempt: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"cursor\"; readonly cursor: number }\n\t| { readonly kind: \"duplicate\"; readonly seq: number; readonly cursor: number }\n\t| { readonly kind: \"out-of-order\"; readonly seq: number; readonly expected: number }\n\t| { readonly kind: \"session-mismatch\"; readonly expected: string; readonly actual: string }\n\t| { readonly kind: \"late-receipt\"; readonly receipt: \"ack\" | \"nack\"; readonly ackForSeq: number }\n\t| { readonly kind: \"invalid\"; readonly error: string };\n\nexport interface WireBridgeAck {\n\treadonly ackForSeq: number;\n\treadonly envelope: WireBridgeEnvelope;\n}\n\nexport interface WireBridgeNack {\n\treadonly ackForSeq: number;\n\treadonly envelope: WireBridgeEnvelope;\n\treadonly error: unknown;\n}\n\nexport interface WireBridgeAttempt {\n\treadonly seq: number;\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n}\n\nexport interface WireBridgeStatus {\n\treadonly sessionId: string;\n\treadonly state: \"idle\" | \"started\" | \"open\" | \"waiting\" | \"closed\" | \"errored\" | \"exhausted\";\n\treadonly cursor: number;\n\treadonly nextSeq: number;\n\treadonly pending: number;\n\treadonly attempts: number;\n\treadonly acked: number;\n\treadonly nacked: number;\n\treadonly errors: number;\n\treadonly lastSeq?: number;\n\treadonly lastDelayMs?: number;\n}\n\nexport interface WireBridgeOptions {\n\treadonly name?: string;\n\treadonly sessionId: string;\n\treadonly retry?: RetryPolicy;\n\t/** Finite D134 ack timeout. Defaults to 30s so pending ack tracking is bounded. */\n\treadonly ackTimeoutMs?: number;\n\treadonly now?: () => number;\n}\n\nexport interface WireBridgeBundle<TOutbound = unknown, TInbound = unknown> {\n\treadonly sessionId: string;\n\treadonly command: Node<WireBridgeCommand<TOutbound>>;\n\treadonly outbound: Node<WireBridgeEnvelope<TOutbound>>;\n\treadonly inbound: Node<WireBridgeEnvelope<TInbound>>;\n\treadonly events: Node<WireBridgeEvent<TOutbound, TInbound>>;\n\treadonly acks: Node<WireBridgeAck>;\n\treadonly nacks: Node<WireBridgeNack>;\n\treadonly status: Node<WireBridgeStatus>;\n\treadonly errors: Node<unknown>;\n\treadonly cursor: Node<number>;\n\treadonly attempts: Node<WireBridgeAttempt>;\n\tstart(): void;\n\tsend(payload: TOutbound, opts?: { idempotencyKey?: string; requestId?: string }): void;\n\tack(ackForSeq: number, opts?: { idempotencyKey?: string; requestId?: string }): void;\n\tnack(\n\t\tackForSeq: number,\n\t\terror: unknown,\n\t\topts?: { idempotencyKey?: string; requestId?: string },\n\t): void;\n\tclose(reason?: unknown, opts?: { idempotencyKey?: string }): void;\n}\n\nexport interface RemoteCallRequest<T = unknown> {\n\treadonly operation: string;\n\treadonly requestId: string;\n\treadonly payload: T;\n}\n\nexport type RemoteCallResponse<T = unknown> =\n\t| {\n\t\t\treadonly kind: \"result\";\n\t\t\treadonly operation: string;\n\t\t\treadonly requestId: string;\n\t\t\treadonly payload: T;\n\t }\n\t| {\n\t\t\treadonly kind: \"error\";\n\t\t\treadonly operation: string;\n\t\t\treadonly requestId: string;\n\t\t\treadonly error: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"status\";\n\t\t\treadonly operation: string;\n\t\t\treadonly requestId: string;\n\t\t\treadonly status: string;\n\t };\n\nexport interface RemoteCallResult<T = unknown> {\n\treadonly operation: string;\n\treadonly requestId: string;\n\treadonly payload: T;\n}\n\nexport type RemoteCallStatusState =\n\t| \"idle\"\n\t| \"requested\"\n\t| \"responded\"\n\t| \"errored\"\n\t| \"timed-out\"\n\t| \"bridge-errored\";\n\nexport interface RemoteCallStatus {\n\treadonly state: RemoteCallStatusState;\n\treadonly operation?: string;\n\treadonly requestId?: string;\n\treadonly pending: number;\n\treadonly completed: number;\n\treadonly errors: number;\n\treadonly timeouts: number;\n}\n\nexport interface RemoteCallError {\n\treadonly operation?: string;\n\treadonly requestId?: string;\n\treadonly error: string;\n}\n\nexport interface RemoteCallTimeout {\n\treadonly operation?: string;\n\treadonly requestId: string;\n\treadonly error: string;\n}\n\nexport interface RemoteCallOptions {\n\treadonly name?: string;\n}\n\nexport interface RemoteCallBundle<TRequest = unknown, TResponse = unknown> {\n\treadonly responses: Node<RemoteCallResponse<TResponse>>;\n\treadonly results: Node<RemoteCallResult<TResponse>>;\n\treadonly status: Node<RemoteCallStatus>;\n\treadonly errors: Node<RemoteCallError>;\n\treadonly timeouts: Node<RemoteCallTimeout>;\n\tcall(\n\t\toperation: string,\n\t\trequestId: string,\n\t\tpayload: TRequest,\n\t\topts?: { readonly idempotencyKey?: string },\n\t): RemoteCallRequest<TRequest>;\n\ttimeout(requestId: string, operation: string | undefined, error: string): RemoteCallTimeout;\n}\n\nexport type RemoteResponderHandler<TRequest = unknown, TResponse = unknown> = (\n\trequest: RemoteCallRequest<TRequest>,\n) => TResponse;\n\nexport interface RemoteResponderHandlerDefinition<TRequest = unknown, TResponse = unknown> {\n\treadonly operation: string;\n\treadonly handle: RemoteResponderHandler<TRequest, TResponse>;\n}\n\nexport type RemoteResponderEvent<TRequest = unknown, TResponse = unknown> =\n\t| {\n\t\t\treadonly kind: \"request\";\n\t\t\treadonly request: RemoteCallRequest<TRequest>;\n\t\t\treadonly seq: number;\n\t }\n\t| {\n\t\t\treadonly kind: \"response\";\n\t\t\treadonly requestId: string;\n\t\t\treadonly operation: string;\n\t\t\treadonly command: WireBridgeCommand<RemoteCallResponse<TResponse>>;\n\t }\n\t| {\n\t\t\treadonly kind: \"rejected\";\n\t\t\treadonly requestId?: string;\n\t\t\treadonly operation?: string;\n\t\t\treadonly error: string;\n\t\t\treadonly command?: WireBridgeCommand<RemoteCallResponse<TResponse>>;\n\t }\n\t| { readonly kind: \"invalid\"; readonly error: string };\n\nexport type RemoteResponderStatusState = \"idle\" | \"responded\" | \"rejected\" | \"errored\";\n\nexport interface RemoteResponderStatus {\n\treadonly state: RemoteResponderStatusState;\n\treadonly operation?: string;\n\treadonly requestId?: string;\n\treadonly handled: number;\n\treadonly rejected: number;\n\treadonly errors: number;\n}\n\nexport interface RemoteResponderOptions<TRequest = unknown, TResponse = unknown> {\n\treadonly name?: string;\n\treadonly handlers?: readonly RemoteResponderHandlerDefinition<TRequest, TResponse>[];\n\t/** Default false: non-owned operations are ignored so multiple responders may share one bridge. */\n\treadonly rejectUnknown?: boolean;\n}\n\nexport interface RemoteResponderBundle<TRequest = unknown, TResponse = unknown> {\n\treadonly events: Node<RemoteResponderEvent<TRequest, TResponse>>;\n\treadonly responseCommands: Node<WireBridgeCommand<RemoteCallResponse<TResponse>>>;\n\treadonly requests: Node<RemoteCallRequest<TRequest>>;\n\treadonly status: Node<RemoteResponderStatus>;\n\treadonly errors: Node<RemoteCallError>;\n\trelease(): void;\n}\n\ninterface PendingEnvelope<TData> {\n\tenvelope: WireBridgeEnvelope<TData>;\n\ttimer?: ReturnType<typeof setTimeout>;\n}\n\ninterface BridgeState<TData> {\n\tactive: boolean;\n\tcleanupInstalled: boolean;\n\tnextSeq: number;\n\tcursor: number;\n\tremoteCursor: number;\n\tterminalReported: boolean;\n\tpending: Map<number, PendingEnvelope<TData>>;\n}\n\ninterface AttachedCommandSources<TOutbound> {\n\tsources: Node<WireBridgeCommand<TOutbound>>[];\n}\n\ninterface WireBridgeInvalidIngress {\n\treadonly __wireBridgeInvalidIngress: true;\n\treadonly error: string;\n}\n\nconst envelopeTypes = new Set<WireBridgeEnvelopeType>([\n\t\"start\",\n\t\"data\",\n\t\"ack\",\n\t\"nack\",\n\t\"status\",\n\t\"error\",\n\t\"close\",\n]);\n\nconst defaultAckTimeoutMs = 30_000;\nconst bridgeCommandSources = new WeakMap<\n\tWireBridgeBundle<unknown, unknown>,\n\tAttachedCommandSources<unknown>\n>();\nconst bridgeInboundTargets = new WeakMap<\n\tWireBridgeBundle<unknown, unknown>,\n\tNode<WireBridgeEnvelope<unknown> | WireBridgeInvalidIngress>\n>();\n\n/** Stable D134 idempotency key helper scoped to one bridge session and sequence. */\nexport function wireBridgeIdempotencyKey(sessionId: string, seq: number): string {\n\treturn `${sessionId}:${seq}`;\n}\n\n/** Create a D134 wire bridge envelope with ordered metadata. */\nexport function wireBridgeEnvelope<TData = unknown>(input: {\n\treadonly sessionId: string;\n\treadonly type: WireBridgeEnvelopeType;\n\treadonly seq: number;\n\treadonly cursor?: number;\n\treadonly payload?: WireBridgePayload<TData>;\n\treadonly idempotencyKey?: string;\n\treadonly attempt?: number;\n\treadonly maxAttempts?: number;\n\treadonly timestampMs?: number;\n\treadonly ackForSeq?: number;\n\treadonly requestId?: string;\n}): WireBridgeEnvelope<TData> {\n\tif (typeof input.sessionId !== \"string\" || input.sessionId.length === 0) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: sessionId must be a non-empty string\");\n\t}\n\tif (!envelopeTypes.has(input.type)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: type is not recognized\");\n\t}\n\tif (!isSafePositiveInteger(input.seq)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: seq must be a positive integer\");\n\t}\n\tconst cursor = input.cursor ?? 0;\n\tif (!isSafeNonNegativeInteger(cursor)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: cursor must be a non-negative integer\");\n\t}\n\tconst attempt = input.attempt ?? 1;\n\tif (!isSafePositiveInteger(attempt)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: attempt must be a positive integer\");\n\t}\n\tconst maxAttempts = input.maxAttempts ?? attempt;\n\tif (!isSafePositiveInteger(maxAttempts) || maxAttempts < attempt) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: maxAttempts must be >= attempt\");\n\t}\n\tif (input.ackForSeq !== undefined && !isSafePositiveInteger(input.ackForSeq)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: ackForSeq must be a positive integer\");\n\t}\n\tif ((input.type === \"ack\" || input.type === \"nack\") && input.ackForSeq === undefined) {\n\t\tthrow new RangeError(`wireBridgeEnvelope: ${input.type} envelope requires ackForSeq`);\n\t}\n\tif (input.idempotencyKey !== undefined && input.idempotencyKey.length === 0) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: idempotencyKey must be a non-empty string\");\n\t}\n\tconst payloadError = validatePayloadForType(input.type, input.payload, \"wireBridgeEnvelope\");\n\tif (payloadError !== undefined) {\n\t\tthrow new RangeError(payloadError);\n\t}\n\treturn {\n\t\tsessionId: input.sessionId,\n\t\ttype: input.type,\n\t\tpayload: input.payload,\n\t\tmetadata: {\n\t\t\tseq: input.seq,\n\t\t\tcursor,\n\t\t\tidempotencyKey: input.idempotencyKey ?? wireBridgeIdempotencyKey(input.sessionId, input.seq),\n\t\t\tattempt,\n\t\t\tmaxAttempts,\n\t\t\ttimestampMs: input.timestampMs,\n\t\t\tackForSeq: input.ackForSeq,\n\t\t\trequestId: input.requestId,\n\t\t},\n\t};\n}\n\nexport function wireBridge<TOutbound = unknown, TInbound = unknown>(\n\tgraph: Graph,\n\topts: WireBridgeOptions,\n): WireBridgeBundle<TOutbound, TInbound> {\n\tconst name = opts.name ?? \"wireBridge\";\n\tconst policy = opts.retry ?? retryPolicy();\n\tconst command = graph.node<WireBridgeCommand<TOutbound>>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"wireBridgeCommand\",\n\t});\n\tconst inboundCore = graph.node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>(\n\t\t[],\n\t\tnull,\n\t\t{\n\t\t\tname: `${name}/inbound`,\n\t\t\tfactory: \"wireBridgeInbound\",\n\t\t},\n\t);\n\tconst inbound = guardedInboundNode(inboundCore, opts.sessionId);\n\tconst events = wireBridgeEventsNode<TOutbound, TInbound>(\n\t\tgraph,\n\t\tcommand,\n\t\tinboundCore,\n\t\tname,\n\t\topts,\n\t\tpolicy,\n\t);\n\tconst outbound = projectOutbound(graph, events, name);\n\tconst acks = projectAcks(graph, events, name);\n\tconst nacks = projectNacks(graph, events, name);\n\tconst status = projectStatus(graph, events, name, opts.sessionId);\n\tconst errors = projectErrors(graph, events, name);\n\tconst cursor = projectCursor(graph, events, name);\n\tconst attempts = projectAttempts(graph, events, name);\n\tconst bundle: WireBridgeBundle<TOutbound, TInbound> = {\n\t\tsessionId: opts.sessionId,\n\t\tcommand,\n\t\toutbound,\n\t\tinbound,\n\t\tevents,\n\t\tacks,\n\t\tnacks,\n\t\tstatus,\n\t\terrors,\n\t\tcursor,\n\t\tattempts,\n\t\tstart: () => command.down([[\"DATA\", { kind: \"start\" }]]),\n\t\tsend: (payload, sendOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t\tidempotencyKey: sendOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: sendOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tack: (ackForSeq, ackOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\t\tackForSeq,\n\t\t\t\t\t\tidempotencyKey: ackOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: ackOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tnack: (ackForSeq, error, nackOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"nack\",\n\t\t\t\t\t\tackForSeq,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tidempotencyKey: nackOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: nackOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tclose: (reason, closeOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\"DATA\", { kind: \"close\", reason, idempotencyKey: closeOpts?.idempotencyKey }],\n\t\t\t]),\n\t};\n\tbridgeCommandSources.set(bundle as WireBridgeBundle<unknown, unknown>, { sources: [] });\n\tbridgeInboundTargets.set(bundle as WireBridgeBundle<unknown, unknown>, inboundCore);\n\treturn bundle;\n}\n\n/** D147 remote dispatcher call helper over explicit wireBridge request/response facts. */\nexport function remoteCall<TRequest = unknown, TResponse = unknown>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>,\n\topts: RemoteCallOptions = {},\n): RemoteCallBundle<TRequest, TResponse> {\n\tconst name = opts.name ?? \"remoteCall\";\n\tconst timeouts = graph.node<RemoteCallTimeout>([], null, {\n\t\tname: `${name}/timeouts`,\n\t\tfactory: \"remoteCallTimeouts\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst responses = remoteCallResponsesNode(graph, bridge.events, timeouts, name);\n\tconst results = remoteCallResultsNode(graph, responses, name);\n\tconst status = remoteCallStatusNode(graph, bridge.events, responses, timeouts, name);\n\tconst errors = remoteCallErrorsNode(graph, responses, timeouts, bridge.events, name);\n\treturn {\n\t\tresponses,\n\t\tresults,\n\t\tstatus,\n\t\terrors,\n\t\ttimeouts,\n\t\tcall(operation, requestId, payload, callOpts) {\n\t\t\tconst request = remoteCallRequest(operation, requestId, payload);\n\t\t\tbridge.command.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tpayload: request,\n\t\t\t\t\t\tidempotencyKey: callOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn request;\n\t\t},\n\t\ttimeout(requestId, operation, error) {\n\t\t\tconst timeout = remoteCallTimeout(requestId, operation, error);\n\t\t\ttimeouts.down([[\"DATA\", timeout]]);\n\t\t\treturn timeout;\n\t\t},\n\t};\n}\n\nexport function remoteResponderHandler<TRequest = unknown, TResponse = unknown>(\n\toperation: string,\n\thandle: RemoteResponderHandler<TRequest, TResponse>,\n): RemoteResponderHandlerDefinition<TRequest, TResponse> {\n\tif (operation.length === 0) {\n\t\tthrow new RangeError(\"remoteResponderHandler: operation must be non-empty\");\n\t}\n\tif (typeof handle !== \"function\") {\n\t\tthrow new TypeError(\"remoteResponderHandler: handle must be a function\");\n\t}\n\treturn { operation, handle };\n}\n\n/** D147 remote responder over inbound wireBridge request facts and outbound command facts. */\nexport function remoteResponder<TRequest = unknown, TResponse = unknown>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<RemoteCallResponse<TResponse>, RemoteCallRequest<TRequest>>,\n\topts: RemoteResponderOptions<TRequest, TResponse> = {},\n): RemoteResponderBundle<TRequest, TResponse> {\n\tconst name = opts.name ?? \"remoteResponder\";\n\tconst handlers = normalizeRemoteHandlers(opts.handlers ?? []);\n\tconst topology = graph.topologyGroup({ name: `${name}.remoteResponder` });\n\tconst events = topology.add(\n\t\tremoteResponderEventsNode(\n\t\t\tgraph,\n\t\t\twireBridgeInboundTarget(bridge),\n\t\t\tname,\n\t\t\tbridge.sessionId,\n\t\t\thandlers,\n\t\t\topts.rejectUnknown === true,\n\t\t),\n\t);\n\tconst responseCommands = topology.add(remoteResponderResponseCommandsNode(graph, events, name));\n\tconst requests = topology.add(remoteResponderRequestsNode(graph, events, name));\n\tconst status = topology.add(remoteResponderStatusNode(graph, events, name));\n\tconst errors = topology.add(remoteResponderErrorsNode(graph, events, name));\n\ttry {\n\t\tattachWireBridgeCommandSource(bridge, responseCommands);\n\t} catch (error) {\n\t\ttopology.release({ reason: `${name}.remoteResponder.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\tevents,\n\t\tresponseCommands,\n\t\trequests,\n\t\tstatus,\n\t\terrors,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tdetachWireBridgeCommandSource(bridge, responseCommands);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.remoteResponder.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachWireBridgeCommandSource(bridge, responseCommands);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction wireBridgeEventsNode<TOutbound, TInbound>(\n\tgraph: Graph,\n\tcommand: Node<WireBridgeCommand<TOutbound>>,\n\tinbound: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n\tname: string,\n\topts: WireBridgeOptions,\n\tpolicy: RetryPolicy,\n): Node<WireBridgeEvent<TOutbound, TInbound>> {\n\tconst now = opts.now ?? Date.now;\n\treturn graph.node<WireBridgeEvent<TOutbound, TInbound>>(\n\t\t[command, inbound],\n\t\t(ctx) => {\n\t\t\tconst state = initBridgeState<TOutbound>(ctx);\n\n\t\t\tconst emitOutbound = (\n\t\t\t\ttype: WireBridgeEnvelopeType,\n\t\t\t\tpayload: WireBridgePayload<TOutbound> | undefined,\n\t\t\t\tcommandOpts: { idempotencyKey?: string; requestId?: string; ackForSeq?: number } = {},\n\t\t\t\tbeforeEmit?: () => void,\n\t\t\t) => {\n\t\t\t\tif (!isSafePositiveInteger(state.nextSeq)) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\t\t\t\terror: `${opts.sessionId}: next outbound seq exceeded Number.MAX_SAFE_INTEGER`,\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\treturn;\n\t\t\t\t}\n\t\t\t\tconst seq = state.nextSeq;\n\t\t\t\tlet envelope: WireBridgeEnvelope<TOutbound>;\n\t\t\t\ttry {\n\t\t\t\t\tenvelope = wireBridgeEnvelope<TOutbound>({\n\t\t\t\t\t\tsessionId: opts.sessionId,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\tcursor: state.cursor,\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t\tidempotencyKey: commandOpts.idempotencyKey,\n\t\t\t\t\t\tattempt: 1,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\ttimestampMs: now(),\n\t\t\t\t\t\tackForSeq: commandOpts.ackForSeq,\n\t\t\t\t\t\trequestId: commandOpts.requestId,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\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\treturn;\n\t\t\t\t}\n\t\t\t\tstate.nextSeq++;\n\t\t\t\tbeforeEmit?.();\n\t\t\t\tctx.down([[\"DATA\", { kind: \"outbound\", envelope }]]);\n\t\t\t\tif (shouldTrackAck(type)) armAckTimeout(ctx, state, envelope, opts, policy, now);\n\t\t\t};\n\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tprocessInbound(ctx, state, raw, opts.sessionId);\n\t\t\t}\n\t\t\tconst inboundTerminal = ctx.terminal[1];\n\t\t\tif (inboundTerminal !== false && inboundTerminal !== undefined && !state.terminalReported) {\n\t\t\t\tstate.terminalReported = true;\n\t\t\t\tconst error =\n\t\t\t\t\tinboundTerminal === true\n\t\t\t\t\t\t? `${opts.sessionId}: inbound protocol COMPLETE is local misuse; remote completion must arrive as a DATA envelope fact`\n\t\t\t\t\t\t: `${opts.sessionId}: inbound protocol ERROR ${String(\n\t\t\t\t\t\t\t\terrorPayload(inboundTerminal),\n\t\t\t\t\t\t\t)} is local misuse; remote errors must arrive as DATA envelope facts`;\n\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error }]]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst invalid = validateCommand(raw);\n\t\t\t\tif (invalid !== undefined) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: invalid }]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst commandValue = raw as WireBridgeCommand<TOutbound>;\n\t\t\t\tswitch (commandValue.kind) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\temitOutbound(\"start\", undefined, commandValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"send\":\n\t\t\t\t\t\temitOutbound(\"data\", { kind: \"data\", value: commandValue.payload }, commandValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"ack\":\n\t\t\t\t\t\temitOutbound(\"ack\", undefined, {\n\t\t\t\t\t\t\tidempotencyKey: commandValue.idempotencyKey,\n\t\t\t\t\t\t\trequestId: commandValue.requestId,\n\t\t\t\t\t\t\tackForSeq: commandValue.ackForSeq,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"nack\":\n\t\t\t\t\t\temitOutbound(\n\t\t\t\t\t\t\t\"nack\",\n\t\t\t\t\t\t\t{ kind: \"error\", error: errorPayload(commandValue.error) },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tidempotencyKey: commandValue.idempotencyKey,\n\t\t\t\t\t\t\t\trequestId: commandValue.requestId,\n\t\t\t\t\t\t\t\tackForSeq: commandValue.ackForSeq,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"close\":\n\t\t\t\t\t\temitOutbound(\n\t\t\t\t\t\t\t\"close\",\n\t\t\t\t\t\t\t{ kind: \"close\", reason: commandValue.reason },\n\t\t\t\t\t\t\tcommandValue,\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tfor (const pending of state.pending.values()) {\n\t\t\t\t\t\t\t\t\tif (pending.timer !== undefined) clearTimeout(pending.timer);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstate.pending.clear();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"wireBridgeEvents\",\n\t\t\tpartial: true,\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t);\n}\n\nfunction initBridgeState<TPayload>(ctx: Ctx): BridgeState<TPayload> {\n\tlet state = ctx.state.get<BridgeState<TPayload>>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tactive: true,\n\t\t\tcleanupInstalled: false,\n\t\t\tnextSeq: 1,\n\t\t\tcursor: 0,\n\t\t\tremoteCursor: 0,\n\t\t\tterminalReported: false,\n\t\t\tpending: new Map(),\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tstate.active = true;\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tstate.active = false;\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tfor (const pending of state.pending.values()) {\n\t\t\t\tif (pending.timer !== undefined) clearTimeout(pending.timer);\n\t\t\t}\n\t\t\tstate.pending.clear();\n\t\t});\n\t}\n\treturn state;\n}\n\nfunction attachWireBridgeCommandSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeCommand<TOutbound>>,\n): void {\n\tconst attached = bridgeCommandSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<WireBridgeCommand<TOutbound>>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\tbridge.command.replaceDeps([...sources], wireBridgeCommandSourceFn(sources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tbridge.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachWireBridgeCommandSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeCommand<TOutbound>>,\n): void {\n\tconst attached = bridgeCommandSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<WireBridgeCommand<TOutbound>>[];\n\tif (!sources.includes(source)) return;\n\tconst previousSources = [...sources];\n\tconst nextSources = sources.filter((candidate) => candidate !== source);\n\tsources.splice(0, sources.length, ...nextSources);\n\ttry {\n\t\tbridge.command.replaceDeps([...nextSources], wireBridgeCommandSourceFn(nextSources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tbridge.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction wireBridgeInboundTarget<TInbound>(\n\tbridge: WireBridgeBundle<unknown, TInbound>,\n): Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress> {\n\tconst target = bridgeInboundTargets.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (target === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge inbound target registry missing\");\n\t}\n\treturn target as Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>;\n}\n\nfunction wireBridgeCommandSourceFn<TOutbound>(sourceCount: number): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tfor (let i = 0; i < sourceCount; i += 1) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", command as WireBridgeCommand<TOutbound>]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction remoteCallRequest<TRequest>(\n\toperation: string,\n\trequestId: string,\n\tpayload: TRequest,\n): RemoteCallRequest<TRequest> {\n\tif (operation.length === 0) throw new RangeError(\"remoteCall: operation must be non-empty\");\n\tif (requestId.length === 0) throw new RangeError(\"remoteCall: requestId must be non-empty\");\n\treturn { operation, requestId, payload };\n}\n\nfunction remoteCallTimeout(\n\trequestId: string,\n\toperation: string | undefined,\n\terror: string,\n): RemoteCallTimeout {\n\tif (requestId.length === 0)\n\t\tthrow new RangeError(\"remoteCall: timeout requestId must be non-empty\");\n\tif (error.length === 0) throw new RangeError(\"remoteCall: timeout error must be non-empty\");\n\treturn { ...(operation === undefined ? {} : { operation }), requestId, error };\n}\n\ninterface RemotePendingRequest {\n\toperation: string;\n\trequestId: string;\n\tseq: number;\n}\n\ninterface RemotePendingState {\n\trequestIds: Set<string>;\n\tbySeq: Map<number, RemotePendingRequest>;\n}\n\nfunction remotePendingState(): RemotePendingState {\n\treturn { requestIds: new Set(), bySeq: new Map() };\n}\n\nfunction remotePendingContains(state: RemotePendingState, requestId: string): boolean {\n\treturn state.requestIds.has(requestId);\n}\n\nfunction remotePendingDuplicate(state: RemotePendingState, request: RemotePendingRequest): boolean {\n\tconst current = remotePendingTakeBySeqPreview(state, request.seq);\n\treturn current?.requestId !== request.requestId && state.requestIds.has(request.requestId);\n}\n\nfunction remotePendingTakeBySeqPreview(\n\tstate: RemotePendingState,\n\tseq: number,\n): RemotePendingRequest | undefined {\n\treturn state.bySeq.get(seq);\n}\n\nfunction remotePendingInsert(state: RemotePendingState, request: RemotePendingRequest): void {\n\tconst existingBySeq = state.bySeq.get(request.seq);\n\tif (existingBySeq !== undefined) {\n\t\tstate.requestIds.delete(existingBySeq.requestId);\n\t}\n\tfor (const [seq, pending] of state.bySeq) {\n\t\tif (pending.requestId === request.requestId && seq !== request.seq) {\n\t\t\tstate.bySeq.delete(seq);\n\t\t\tbreak;\n\t\t}\n\t}\n\tstate.requestIds.add(request.requestId);\n\tstate.bySeq.set(request.seq, request);\n}\n\nfunction remotePendingTakeByRequestId(\n\tstate: RemotePendingState,\n\trequestId: string,\n): RemotePendingRequest | undefined {\n\tif (!state.requestIds.delete(requestId)) return undefined;\n\tlet seq: number | undefined;\n\tlet found: RemotePendingRequest | undefined;\n\tfor (const [candidateSeq, request] of state.bySeq) {\n\t\tif (request.requestId === requestId) {\n\t\t\tseq = candidateSeq;\n\t\t\tfound = request;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (seq !== undefined) state.bySeq.delete(seq);\n\treturn found;\n}\n\nfunction remotePendingTakeBySeq(\n\tstate: RemotePendingState,\n\tseq: number,\n): RemotePendingRequest | undefined {\n\tconst request = state.bySeq.get(seq);\n\tif (request === undefined) return undefined;\n\tstate.bySeq.delete(seq);\n\tstate.requestIds.delete(request.requestId);\n\treturn request;\n}\n\nfunction remotePendingFromReceipt<T>(\n\tstate: RemotePendingState,\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n): RemotePendingRequest | undefined {\n\tconst bySeq = remotePendingTakeBySeq(state, envelope.metadata.seq);\n\tif (bySeq !== undefined) return bySeq;\n\tconst fallback = pendingRequestFromEnvelope(envelope);\n\tif (fallback === undefined || remotePendingContains(state, fallback.requestId)) {\n\t\treturn undefined;\n\t}\n\treturn fallback;\n}\n\nfunction pendingRequestFromEnvelope<T>(\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n): RemotePendingRequest | undefined {\n\tif (envelope.payload?.kind !== \"data\") return undefined;\n\tconst request = validateRemoteCallRequest(envelope.payload.value);\n\tif (request === undefined) return undefined;\n\treturn {\n\t\toperation: request.operation,\n\t\trequestId: request.requestId,\n\t\tseq: envelope.metadata.seq,\n\t};\n}\n\nfunction validateRemoteCallRequest<T>(value: unknown): RemoteCallRequest<T> | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (typeof value.operation !== \"string\" || value.operation.length === 0) return undefined;\n\tif (typeof value.requestId !== \"string\" || value.requestId.length === 0) return undefined;\n\tif (!(\"payload\" in value)) return undefined;\n\treturn {\n\t\toperation: value.operation,\n\t\trequestId: value.requestId,\n\t\tpayload: value.payload as T,\n\t};\n}\n\nfunction validateRemoteCallResponse<T>(value: unknown): RemoteCallResponse<T> | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (typeof value.operation !== \"string\" || value.operation.length === 0) return undefined;\n\tif (typeof value.requestId !== \"string\" || value.requestId.length === 0) return undefined;\n\tif (value.kind === \"result\" && \"payload\" in value) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\tpayload: value.payload as T,\n\t\t};\n\t}\n\tif (value.kind === \"error\" && typeof value.error === \"string\" && value.error.length > 0) {\n\t\treturn {\n\t\t\tkind: \"error\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\terror: value.error,\n\t\t};\n\t}\n\tif (value.kind === \"status\" && typeof value.status === \"string\" && value.status.length > 0) {\n\t\treturn {\n\t\t\tkind: \"status\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\tstatus: value.status,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction remoteMalformedResponseRequestId(value: unknown): string | undefined {\n\tif (!isRecord(value)) return undefined;\n\treturn typeof value.requestId === \"string\" && value.requestId.length > 0\n\t\t? value.requestId\n\t\t: undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isThenable(value: unknown): boolean {\n\treturn isRecord(value) && typeof value.then === \"function\";\n}\n\nfunction remoteCallResponseRequestId<T>(response: RemoteCallResponse<T>): string {\n\treturn response.requestId;\n}\n\nfunction remoteCallResponseIsTerminal<T>(response: RemoteCallResponse<T>): boolean {\n\treturn response.kind === \"result\" || response.kind === \"error\";\n}\n\nfunction remoteCallResponsesNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tname: string,\n): Node<RemoteCallResponse<TResponse>> {\n\treturn graph.node<RemoteCallResponse<TResponse>>(\n\t\t[events, timeouts],\n\t\t(ctx) => {\n\t\t\ttype State = {\n\t\t\t\tpending: RemotePendingState;\n\t\t\t};\n\t\t\tconst state = ctx.state.get<State>() ?? {\n\t\t\t\tpending: remotePendingState(),\n\t\t\t};\n\t\t\tconst ready: RemoteCallResponse<TResponse>[] = [];\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request === undefined) continue;\n\t\t\t\t\tif (remotePendingDuplicate(state.pending, request)) continue;\n\t\t\t\t\tremotePendingInsert(state.pending, request);\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tif (requestId !== undefined && remotePendingContains(state.pending, requestId)) {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, requestId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst requestId = remoteCallResponseRequestId(response);\n\t\t\t\t\tif (remotePendingContains(state.pending, requestId)) {\n\t\t\t\t\t\tif (remoteCallResponseIsTerminal(response)) {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, requestId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tready.push(response);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tremotePendingFromReceipt(state.pending, event.outbound);\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tremotePendingTakeBySeq(state.pending, event.seq);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(state.pending, timeout.requestId);\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t\tfor (const response of ready) ctx.down([[\"DATA\", response]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/responses`,\n\t\t\tfactory: \"remoteCallResponses\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallResultsNode<TResponse>(\n\tgraph: Graph,\n\tresponses: Node<RemoteCallResponse<TResponse>>,\n\tname: string,\n): Node<RemoteCallResult<TResponse>> {\n\treturn graph.node<RemoteCallResult<TResponse>>(\n\t\t[responses],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst response = raw as RemoteCallResponse<TResponse>;\n\t\t\t\tif (response.kind === \"result\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\t\tpayload: response.payload,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/results`, factory: \"remoteCallResults\", completeWhenDepsComplete: false },\n\t);\n}\n\nfunction remoteCallStatusNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\tresponses: Node<RemoteCallResponse<TResponse>>,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tname: string,\n): Node<RemoteCallStatus> {\n\treturn graph.node<RemoteCallStatus>(\n\t\t[events, responses, timeouts],\n\t\t(ctx) => {\n\t\t\ttype State = { status: RemoteCallStatus; pending: RemotePendingState };\n\t\t\tconst state =\n\t\t\t\tctx.state.get<State>() ??\n\t\t\t\t({\n\t\t\t\t\tstatus: { state: \"idle\", pending: 0, completed: 0, errors: 0, timeouts: 0 },\n\t\t\t\t\tpending: remotePendingState(),\n\t\t\t\t} satisfies State);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request !== undefined) {\n\t\t\t\t\t\tif (remotePendingDuplicate(state.pending, request)) {\n\t\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\terrors: state.status.errors + 1,\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\tremotePendingInsert(state.pending, request);\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"requested\",\n\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else if (\n\t\t\t\t\tevent.kind === \"invalid\" ||\n\t\t\t\t\tevent.kind === \"session-mismatch\" ||\n\t\t\t\t\tevent.kind === \"out-of-order\" ||\n\t\t\t\t\tevent.kind === \"late-receipt\"\n\t\t\t\t) {\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tconst request = remotePendingFromReceipt(state.pending, event.outbound);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\t...(request === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { operation: request.operation, requestId: request.requestId }),\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tconst request = remotePendingTakeBySeq(state.pending, event.seq);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\t...(request === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { operation: request.operation, requestId: request.requestId }),\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tif (requestId !== undefined) {\n\t\t\t\t\t\t\tconst request = remotePendingTakeByRequestId(state.pending, requestId);\n\t\t\t\t\t\t\tif (request !== undefined) {\n\t\t\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\t\trequestId,\n\t\t\t\t\t\t\t\t\terrors: state.status.errors + 1,\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}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst response = raw as RemoteCallResponse<TResponse>;\n\t\t\t\tif (response.kind === \"result\") {\n\t\t\t\t\tremotePendingTakeByRequestId(state.pending, response.requestId);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"responded\",\n\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\tcompleted: state.status.completed + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (response.kind === \"error\") {\n\t\t\t\t\tremotePendingTakeByRequestId(state.pending, response.requestId);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 2) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(state.pending, timeout.requestId);\n\t\t\t\tstate.status = {\n\t\t\t\t\t...state.status,\n\t\t\t\t\tstate: \"timed-out\",\n\t\t\t\t\toperation: timeout.operation,\n\t\t\t\t\trequestId: timeout.requestId,\n\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\ttimeouts: state.status.timeouts + 1,\n\t\t\t\t};\n\t\t\t}\n\t\t\tstate.status = { ...state.status, pending: state.pending.requestIds.size };\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", state.status]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"remoteCallStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallErrorsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tresponses: Node<RemoteCallResponse<TResponse>>,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\tname: string,\n): Node<RemoteCallError> {\n\treturn graph.node<RemoteCallError>(\n\t\t[responses, timeouts, events],\n\t\t(ctx) => {\n\t\t\tconst pending = ctx.state.get<RemotePendingState>() ?? remotePendingState();\n\t\t\tfor (const raw of depBatch(ctx, 2) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request !== undefined) {\n\t\t\t\t\t\tif (remotePendingDuplicate(pending, request)) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\t\t\terror: `remoteCall: duplicate in-flight requestId '${request.requestId}'`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tremotePendingInsert(pending, request);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst response = raw as RemoteCallResponse<TResponse>;\n\t\t\t\tif (response.kind === \"error\") {\n\t\t\t\t\tremotePendingTakeByRequestId(pending, response.requestId);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\t\terror: response.error,\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 if (response.kind === \"result\") {\n\t\t\t\t\tremotePendingTakeByRequestId(pending, response.requestId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(pending, timeout.requestId);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ operation: timeout.operation, requestId: timeout.requestId, error: timeout.error },\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 2) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tconst request =\n\t\t\t\t\t\t\trequestId === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: remotePendingTakeByRequestId(pending, requestId);\n\t\t\t\t\t\tif (request === undefined) continue;\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\t\terror: \"remoteCall: response payload is malformed\",\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\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.kind === \"nack\") {\n\t\t\t\t\tconst request = remotePendingFromReceipt(pending, event.outbound);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: request?.operation,\n\t\t\t\t\t\t\t\trequestId: request?.requestId,\n\t\t\t\t\t\t\t\terror: String(event.error),\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 if (event.kind === \"exhausted\") {\n\t\t\t\t\tconst request = remotePendingTakeBySeq(pending, event.seq);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: request?.operation,\n\t\t\t\t\t\t\t\trequestId: request?.requestId,\n\t\t\t\t\t\t\t\terror: String(event.error),\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 if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { error: event.error }]]);\n\t\t\t\t} else if (\n\t\t\t\t\tevent.kind === \"session-mismatch\" ||\n\t\t\t\t\tevent.kind === \"out-of-order\" ||\n\t\t\t\t\tevent.kind === \"late-receipt\"\n\t\t\t\t) {\n\t\t\t\t\tctx.down([[\"DATA\", { error: remoteCallBridgeErrorMessage(event) }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(pending);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/errors`,\n\t\t\tfactory: \"remoteCallErrors\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallBridgeErrorMessage<TRequest, TResponse>(\n\tevent: WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>,\n): string {\n\tif (event.kind === \"session-mismatch\") {\n\t\treturn `remoteCall: inbound session ${event.actual} did not match expected ${event.expected}`;\n\t}\n\tif (event.kind === \"out-of-order\") {\n\t\treturn `remoteCall: inbound seq ${event.seq} arrived before expected seq ${event.expected}`;\n\t}\n\tif (event.kind === \"late-receipt\") {\n\t\treturn `remoteCall: late ${event.receipt} for unknown or completed ackForSeq ${event.ackForSeq}`;\n\t}\n\treturn \"remoteCall: bridge error\";\n}\n\nfunction normalizeRemoteHandlers<TRequest, TResponse>(\n\thandlers: readonly RemoteResponderHandlerDefinition<TRequest, TResponse>[],\n): Map<string, RemoteResponderHandler<TRequest, TResponse>> {\n\tconst out = new Map<string, RemoteResponderHandler<TRequest, TResponse>>();\n\tfor (const handler of handlers) {\n\t\tif (handler.operation.length === 0) {\n\t\t\tthrow new RangeError(\"remoteResponder: operation must be non-empty\");\n\t\t}\n\t\tif (out.has(handler.operation)) {\n\t\t\tthrow new RangeError(`remoteResponder: duplicate operation '${handler.operation}'`);\n\t\t}\n\t\tout.set(handler.operation, handler.handle);\n\t}\n\treturn out;\n}\n\ninterface RemoteResponderCursor {\n\tcursor: number;\n\tremoteCursor: number;\n}\n\ntype RemoteResponderInbound<T> =\n\t| { readonly kind: \"request\"; readonly request: RemoteCallRequest<T>; readonly seq: number }\n\t| { readonly kind: \"consumed\" }\n\t| { readonly kind: \"invalid\"; readonly error: string };\n\nfunction reduceRemoteResponderInbound<T>(\n\tcursor: RemoteResponderCursor,\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n\texpectedSessionId: string,\n): RemoteResponderInbound<T> {\n\tconst envelopeError = validateInboundEnvelope(envelope);\n\tif (envelopeError !== undefined) {\n\t\treturn { kind: \"invalid\", error: envelopeError };\n\t}\n\tif (envelope.sessionId !== expectedSessionId) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: inbound session ${envelope.sessionId} did not match expected ${expectedSessionId}`,\n\t\t};\n\t}\n\tconst seq = envelope.metadata.seq;\n\tconst expected = cursor.cursor + 1;\n\tif (seq <= cursor.cursor) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: duplicate request seq ${seq} at cursor ${cursor.cursor}`,\n\t\t};\n\t}\n\tif (seq > expected) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: out-of-order request seq ${seq}, expected ${expected}`,\n\t\t};\n\t}\n\tif (envelope.metadata.cursor < cursor.remoteCursor) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `${envelope.sessionId}: remoteResponder inbound cursor ${envelope.metadata.cursor} regressed below ${cursor.remoteCursor}`,\n\t\t};\n\t}\n\tcursor.cursor = seq;\n\tcursor.remoteCursor = envelope.metadata.cursor;\n\tif (envelope.type !== \"data\") return { kind: \"consumed\" };\n\tif (envelope.payload?.kind !== \"data\") {\n\t\treturn { kind: \"invalid\", error: \"remoteResponder: request envelope must carry request DATA\" };\n\t}\n\tconst request = validateRemoteCallRequest<T>(envelope.payload.value);\n\tif (request === undefined) {\n\t\treturn { kind: \"invalid\", error: \"remoteResponder: request payload is malformed\" };\n\t}\n\treturn { kind: \"request\", request, seq };\n}\n\nfunction remoteResponderEventsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tinbound: Node<WireBridgeEnvelope<RemoteCallRequest<TRequest>> | WireBridgeInvalidIngress>,\n\tname: string,\n\texpectedSessionId: string,\n\thandlers: Map<string, RemoteResponderHandler<TRequest, TResponse>>,\n\trejectUnknown: boolean,\n): Node<RemoteResponderEvent<TRequest, TResponse>> {\n\treturn graph.node<RemoteResponderEvent<TRequest, TResponse>>(\n\t\t[inbound],\n\t\t(ctx) => {\n\t\t\tconst cursor = ctx.state.get<RemoteResponderCursor>() ?? { cursor: 0, remoteCursor: 0 };\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst envelope = raw as WireBridgeEnvelope<RemoteCallRequest<TRequest>>;\n\t\t\t\tconst received = reduceRemoteResponderInbound(cursor, envelope, expectedSessionId);\n\t\t\t\tif (received.kind === \"consumed\") continue;\n\t\t\t\tif (received.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: received.error }]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { request, seq } = received;\n\t\t\t\tctx.down([[\"DATA\", { kind: \"request\", request, seq }]]);\n\t\t\t\tconst handler = handlers.get(request.operation);\n\t\t\t\tif (handler === undefined) {\n\t\t\t\t\tif (!rejectUnknown) continue;\n\t\t\t\t\tconst error = `remoteResponder: unknown operation '${request.operation}'`;\n\t\t\t\t\tconst response = remoteCallErrorResponse(request, error);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst payload = handler(request);\n\t\t\t\t\tif (isThenable(payload)) {\n\t\t\t\t\t\tthrow new Error(\"remoteResponder: async handler results require a later adapter shape\");\n\t\t\t\t\t}\n\t\t\t\t\tconst response = {\n\t\t\t\t\t\tkind: \"result\",\n\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t} satisfies RemoteCallResponse<TResponse>;\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"response\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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} catch (error) {\n\t\t\t\t\trethrowGraphRuntimeInvariant(error);\n\t\t\t\t\tconst message = errorMessage(error);\n\t\t\t\t\tconst response = remoteCallErrorResponse(request, message);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\terror: message,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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\tctx.state.set(cursor);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"remoteResponderEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallErrorResponse<TRequest, TResponse>(\n\trequest: RemoteCallRequest<TRequest>,\n\terror: string,\n): RemoteCallResponse<TResponse> {\n\treturn {\n\t\tkind: \"error\",\n\t\toperation: request.operation,\n\t\trequestId: request.requestId,\n\t\terror,\n\t};\n}\n\nfunction remoteResponderResponseCommandsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<WireBridgeCommand<RemoteCallResponse<TResponse>>> {\n\treturn graph.node<WireBridgeCommand<RemoteCallResponse<TResponse>>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (\n\t\t\t\t\t(event.kind === \"response\" || event.kind === \"rejected\") &&\n\t\t\t\t\tevent.command !== undefined\n\t\t\t\t) {\n\t\t\t\t\tctx.down([[\"DATA\", event.command]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/responseCommands`,\n\t\t\tfactory: \"remoteResponderResponseCommands\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteResponderRequestsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteCallRequest<TRequest>> {\n\treturn graph.node<RemoteCallRequest<TRequest>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"request\") ctx.down([[\"DATA\", event.request]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/requests`,\n\t\t\tfactory: \"remoteResponderRequests\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t},\n\t);\n}\n\nfunction remoteResponderStatusNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteResponderStatus> {\n\treturn graph.node<RemoteResponderStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet status =\n\t\t\t\tctx.state.get<RemoteResponderStatus>() ??\n\t\t\t\t({ state: \"idle\", handled: 0, rejected: 0, errors: 0 } satisfies RemoteResponderStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"response\") {\n\t\t\t\t\tstatus = {\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tstate: \"responded\",\n\t\t\t\t\t\toperation: event.operation,\n\t\t\t\t\t\trequestId: event.requestId,\n\t\t\t\t\t\thandled: status.handled + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"rejected\") {\n\t\t\t\t\tstatus = {\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tstate: \"rejected\",\n\t\t\t\t\t\toperation: event.operation,\n\t\t\t\t\t\trequestId: event.requestId,\n\t\t\t\t\t\trejected: status.rejected + 1,\n\t\t\t\t\t\terrors: status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tstatus = { ...status, state: \"errored\", errors: status.errors + 1 };\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(status);\n\t\t\tctx.down([[\"DATA\", status]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"remoteResponderStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteResponderErrorsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteCallError> {\n\treturn graph.node<RemoteCallError>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"rejected\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ operation: event.operation, requestId: event.requestId, error: event.error },\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { error: event.error }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"remoteResponderErrors\", completeWhenDepsComplete: false },\n\t);\n}\n\nfunction armAckTimeout<TPayload>(\n\tctx: Ctx,\n\tstate: BridgeState<TPayload>,\n\tenvelope: WireBridgeEnvelope<TPayload>,\n\topts: WireBridgeOptions,\n\tpolicy: RetryPolicy,\n\tnow: () => number,\n): void {\n\tconst timeoutMs = opts.ackTimeoutMs ?? defaultAckTimeoutMs;\n\tif (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n\t\tthrow new RangeError(\"wireBridge: ackTimeoutMs must be a non-negative finite number\");\n\t}\n\tconst pending: PendingEnvelope<TPayload> = { envelope };\n\tconst schedule = (current: WireBridgeEnvelope<TPayload>) => {\n\t\tpending.timer = setTimeout(() => {\n\t\t\tpending.timer = undefined;\n\t\t\tif (!state.active || !state.pending.has(current.metadata.seq)) return;\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"timeout\",\n\t\t\t\t\t\tseq: current.metadata.seq,\n\t\t\t\t\t\tattempt: current.metadata.attempt,\n\t\t\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t\t\t],\n\t\t\t]);\n\t\t\tif (!shouldRetry(policy, current.metadata.attempt)) {\n\t\t\t\tconst error = `${opts.sessionId}: ack timeout for seq ${current.metadata.seq}`;\n\t\t\t\tstate.pending.delete(current.metadata.seq);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"exhausted\",\n\t\t\t\t\t\t\tseq: current.metadata.seq,\n\t\t\t\t\t\t\tattempt: current.metadata.attempt,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst attempt = current.metadata.attempt + 1;\n\t\t\tconst delayMs = nextRetryDelayMs(policy, attempt) ?? 0;\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"retry\",\n\t\t\t\t\t\tseq: current.metadata.seq,\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\terror: `${opts.sessionId}: ack timeout for seq ${current.metadata.seq}`,\n\t\t\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t\t\t],\n\t\t\t]);\n\t\t\tconst retry = wireBridgeEnvelope<TPayload>({\n\t\t\t\tsessionId: current.sessionId,\n\t\t\t\ttype: current.type,\n\t\t\t\tseq: current.metadata.seq,\n\t\t\t\tcursor: state.cursor,\n\t\t\t\tpayload: current.payload,\n\t\t\t\tidempotencyKey: current.metadata.idempotencyKey,\n\t\t\t\tattempt,\n\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\ttimestampMs: now(),\n\t\t\t\trequestId: current.metadata.requestId,\n\t\t\t});\n\t\t\tpending.timer = setTimeout(() => {\n\t\t\t\tpending.timer = undefined;\n\t\t\t\tif (!state.active || !state.pending.has(current.metadata.seq)) return;\n\t\t\t\tpending.envelope = retry;\n\t\t\t\tctx.down([[\"DATA\", { kind: \"outbound\", envelope: retry }]]);\n\t\t\t\tschedule(retry);\n\t\t\t}, delayMs);\n\t\t}, timeoutMs);\n\t};\n\tstate.pending.set(envelope.metadata.seq, pending);\n\tschedule(envelope);\n}\n\nfunction processInbound<TOutbound, TInbound>(\n\tctx: Ctx,\n\tstate: BridgeState<TOutbound>,\n\tinput: unknown,\n\tsessionId: string,\n): void {\n\tif (isInvalidIngress(input)) {\n\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: input.error }]]);\n\t\treturn;\n\t}\n\tconst invalid = validateInboundEnvelope(input);\n\tif (invalid !== undefined) {\n\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: invalid }]]);\n\t\treturn;\n\t}\n\tconst envelope = input as WireBridgeEnvelope<TInbound>;\n\tif (envelope.sessionId !== sessionId) {\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"session-mismatch\",\n\t\t\t\t\texpected: sessionId,\n\t\t\t\t\tactual: envelope.sessionId,\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tconst seq = envelope.metadata.seq;\n\tconst expected = state.cursor + 1;\n\tif (seq <= state.cursor) {\n\t\tctx.down([[\"DATA\", { kind: \"duplicate\", seq, cursor: state.cursor }]]);\n\t\treturn;\n\t}\n\tif (seq > expected) {\n\t\tctx.down([[\"DATA\", { kind: \"out-of-order\", seq, expected }]]);\n\t\treturn;\n\t}\n\tif (envelope.metadata.cursor < state.remoteCursor) {\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\terror: `${sessionId}: inbound cursor ${envelope.metadata.cursor} regressed below ${state.remoteCursor}`,\n\t\t\t\t},\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tstate.remoteCursor = envelope.metadata.cursor;\n\tstate.cursor = seq;\n\tctx.down([[\"DATA\", { kind: \"cursor\", cursor: state.cursor }]]);\n\tctx.down([[\"DATA\", { kind: \"inbound\", envelope }]]);\n\tif (envelope.type === \"ack\" && envelope.metadata.ackForSeq !== undefined) {\n\t\tconst pending = state.pending.get(envelope.metadata.ackForSeq);\n\t\tif (pending === undefined) {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", { kind: \"late-receipt\", receipt: \"ack\", ackForSeq: envelope.metadata.ackForSeq }],\n\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tif (pending?.timer !== undefined) clearTimeout(pending.timer);\n\t\tstate.pending.delete(envelope.metadata.ackForSeq);\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\tackForSeq: envelope.metadata.ackForSeq,\n\t\t\t\t\tenvelope,\n\t\t\t\t\toutbound: pending.envelope,\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t} else if (envelope.type === \"nack\" && envelope.metadata.ackForSeq !== undefined) {\n\t\tconst pending = state.pending.get(envelope.metadata.ackForSeq);\n\t\tif (pending === undefined) {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", { kind: \"late-receipt\", receipt: \"nack\", ackForSeq: envelope.metadata.ackForSeq }],\n\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tif (pending?.timer !== undefined) clearTimeout(pending.timer);\n\t\tstate.pending.delete(envelope.metadata.ackForSeq);\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"nack\",\n\t\t\t\t\tackForSeq: envelope.metadata.ackForSeq,\n\t\t\t\t\tenvelope,\n\t\t\t\t\toutbound: pending.envelope,\n\t\t\t\t\terror: bridgePayloadError(envelope.payload, \"remote nack\"),\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t}\n}\n\nfunction validateInboundEnvelope(envelope: unknown): string | undefined {\n\tif (typeof envelope !== \"object\" || envelope === null) {\n\t\treturn \"wireBridge: inbound envelope must be an object\";\n\t}\n\tconst candidate = envelope as Partial<WireBridgeEnvelope<unknown>>;\n\tif (typeof candidate.sessionId !== \"string\" || candidate.sessionId.length === 0) {\n\t\treturn \"wireBridge: inbound envelope sessionId must be a non-empty string\";\n\t}\n\tif (\n\t\ttypeof candidate.type !== \"string\" ||\n\t\t!envelopeTypes.has(candidate.type as WireBridgeEnvelopeType)\n\t) {\n\t\treturn \"wireBridge: inbound envelope type is not recognized\";\n\t}\n\tconst metadata = candidate.metadata as Partial<WireBridgeMetadata> | undefined;\n\tif (typeof metadata !== \"object\" || metadata === null) {\n\t\treturn \"wireBridge: inbound envelope metadata must be an object\";\n\t}\n\tif (!isSafePositiveInteger(metadata.seq)) {\n\t\treturn \"wireBridge: inbound envelope seq must be a positive integer\";\n\t}\n\tif (!isSafeNonNegativeInteger(metadata.cursor)) {\n\t\treturn \"wireBridge: inbound envelope cursor must be a non-negative integer\";\n\t}\n\tif (\n\t\ttypeof metadata.idempotencyKey !== \"string\" ||\n\t\t(metadata.idempotencyKey as string).length === 0\n\t) {\n\t\treturn \"wireBridge: inbound envelope idempotencyKey must be a non-empty string\";\n\t}\n\tif (!isSafePositiveInteger(metadata.attempt)) {\n\t\treturn \"wireBridge: inbound envelope attempt must be a positive integer\";\n\t}\n\tif (\n\t\t!isSafePositiveInteger(metadata.maxAttempts) ||\n\t\t(metadata.maxAttempts as number) < (metadata.attempt as number)\n\t) {\n\t\treturn \"wireBridge: inbound envelope maxAttempts must be >= attempt\";\n\t}\n\tif (metadata.ackForSeq !== undefined && !isSafePositiveInteger(metadata.ackForSeq)) {\n\t\treturn \"wireBridge: inbound envelope ackForSeq must be a positive integer\";\n\t}\n\tif ((candidate.type === \"ack\" || candidate.type === \"nack\") && metadata.ackForSeq === undefined) {\n\t\treturn `wireBridge: inbound ${candidate.type} envelope requires ackForSeq`;\n\t}\n\tconst payloadError = validatePayloadForType(\n\t\tcandidate.type as WireBridgeEnvelopeType,\n\t\tcandidate.payload,\n\t\t\"wireBridge: inbound envelope\",\n\t);\n\tif (payloadError !== undefined) return payloadError;\n\treturn undefined;\n}\n\nfunction validateCommand(value: unknown): string | undefined {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn \"wireBridge: command fact must be an object\";\n\t}\n\tconst kind = (value as { readonly kind?: unknown }).kind;\n\tif (\n\t\tkind !== \"start\" &&\n\t\tkind !== \"send\" &&\n\t\tkind !== \"ack\" &&\n\t\tkind !== \"nack\" &&\n\t\tkind !== \"close\"\n\t) {\n\t\treturn \"wireBridge: command kind is not recognized\";\n\t}\n\tif (\n\t\t(kind === \"ack\" || kind === \"nack\") &&\n\t\t!isSafePositiveInteger((value as { readonly ackForSeq?: unknown }).ackForSeq)\n\t) {\n\t\treturn `wireBridge: ${kind} command ackForSeq must be a positive integer`;\n\t}\n\treturn undefined;\n}\n\nfunction projectOutbound<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeEnvelope<TOutbound>> {\n\treturn graph.node<WireBridgeEnvelope<TOutbound>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\") ctx.down([[\"DATA\", event.envelope]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/outbound`, factory: \"wireBridgeOutbound\" },\n\t);\n}\n\nfunction projectAcks<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeAck> {\n\treturn graph.node<WireBridgeAck>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"ack\") {\n\t\t\t\t\tctx.down([[\"DATA\", { ackForSeq: event.ackForSeq, envelope: event.envelope }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/acks`, factory: \"wireBridgeAcks\" },\n\t);\n}\n\nfunction projectNacks<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeNack> {\n\treturn graph.node<WireBridgeNack>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"nack\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { ackForSeq: event.ackForSeq, envelope: event.envelope, error: event.error }],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/nacks`, factory: \"wireBridgeNacks\" },\n\t);\n}\n\nfunction projectStatus<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n\tsessionId: string,\n): Node<WireBridgeStatus> {\n\treturn graph.node<WireBridgeStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<WireBridgeStatus>() ??\n\t\t\t\t({\n\t\t\t\t\tsessionId,\n\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\tcursor: 0,\n\t\t\t\t\tnextSeq: 1,\n\t\t\t\t\tpending: 0,\n\t\t\t\t\tattempts: 0,\n\t\t\t\t\tacked: 0,\n\t\t\t\t\tnacked: 0,\n\t\t\t\t\terrors: 0,\n\t\t\t\t} satisfies WireBridgeStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst { seq, attempt } = event.envelope.metadata;\n\t\t\t\t\tconst trackAck = shouldTrackAck(event.envelope.type);\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate:\n\t\t\t\t\t\t\tevent.envelope.type === \"start\"\n\t\t\t\t\t\t\t\t? \"started\"\n\t\t\t\t\t\t\t\t: event.envelope.type === \"close\"\n\t\t\t\t\t\t\t\t\t? \"closed\"\n\t\t\t\t\t\t\t\t\t: \"open\",\n\t\t\t\t\t\tnextSeq: Math.max(next.nextSeq, seq + 1),\n\t\t\t\t\t\tpending:\n\t\t\t\t\t\t\tevent.envelope.type === \"close\"\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: trackAck && attempt === 1\n\t\t\t\t\t\t\t\t\t? next.pending + 1\n\t\t\t\t\t\t\t\t\t: next.pending,\n\t\t\t\t\t\tattempts: trackAck ? next.attempts + 1 : next.attempts,\n\t\t\t\t\t\tlastSeq: seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"ack\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: event.outbound.type === \"close\" ? \"closed\" : \"open\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\tacked: next.acked + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\tnacked: next.nacked + 1,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tlastSeq: event.seq,\n\t\t\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"cursor\") {\n\t\t\t\t\tnext = { ...next, cursor: event.cursor };\n\t\t\t\t} else if (event.kind === \"out-of-order\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1, lastSeq: event.seq };\n\t\t\t\t} else if (event.kind === \"session-mismatch\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1 };\n\t\t\t\t} else if (event.kind === \"late-receipt\" || event.kind === \"invalid\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1 };\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"error\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"close\") {\n\t\t\t\t\tnext = { ...next, state: \"closed\", lastSeq: event.envelope.metadata.seq };\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"wireBridgeStatus\" },\n\t);\n}\n\nfunction projectErrors<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<unknown> {\n\treturn graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"nack\") ctx.down([[\"DATA\", event.error]]);\n\t\t\t\telse if (event.kind === \"exhausted\") ctx.down([[\"DATA\", event.error]]);\n\t\t\t\telse if (event.kind === \"out-of-order\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: inbound seq ${event.seq} arrived before expected seq ${event.expected}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"error\") {\n\t\t\t\t\tctx.down([[\"DATA\", bridgePayloadError(event.envelope.payload, \"remote error envelope\")]]);\n\t\t\t\t} else if (event.kind === \"session-mismatch\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: inbound session ${event.actual} did not match expected ${event.expected}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"late-receipt\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: late ${event.receipt} for unknown or completed ackForSeq ${event.ackForSeq}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", event.error]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"wireBridgeErrors\" },\n\t);\n}\n\nfunction projectCursor<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<number> {\n\treturn graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"cursor\") ctx.down([[\"DATA\", event.cursor]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/cursor`, factory: \"wireBridgeCursor\" },\n\t);\n}\n\nfunction projectAttempts<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeAttempt> {\n\treturn graph.node<WireBridgeAttempt>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\" && shouldTrackAck(event.envelope.type)) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tseq: event.envelope.metadata.seq,\n\t\t\t\t\t\t\t\tattempt: event.envelope.metadata.attempt,\n\t\t\t\t\t\t\t\tmaxAttempts: event.envelope.metadata.maxAttempts,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"wireBridgeAttempts\" },\n\t);\n}\n\nfunction guardedInboundNode<TInbound>(\n\tnode: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n\tsessionId: string,\n): Node<WireBridgeEnvelope<TInbound>> {\n\treturn new Proxy(node, {\n\t\tget(target, property) {\n\t\t\tif (property === \"down\") {\n\t\t\t\treturn (msgs: Wave) => target.down(guardInboundWave(msgs, sessionId));\n\t\t\t}\n\t\t\tconst value = Reflect.get(target, property, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t}) as Node<WireBridgeEnvelope<TInbound>>;\n}\n\nfunction guardInboundWave(msgs: Wave, sessionId: string): Wave {\n\treturn msgs.map((msg) => {\n\t\tif (msg[0] === \"DATA\") return msg;\n\t\tif (msg[0] === \"ERROR\") {\n\t\t\treturn [\n\t\t\t\t\"DATA\",\n\t\t\t\tinvalidIngress(\n\t\t\t\t\t`${sessionId}: inbound protocol ERROR ${String(\n\t\t\t\t\t\terrorPayload(msg[1]),\n\t\t\t\t\t)} is local misuse; remote errors must arrive as DATA envelope facts`,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t\tif (msg[0] === \"COMPLETE\") {\n\t\t\treturn [\n\t\t\t\t\"DATA\",\n\t\t\t\tinvalidIngress(\n\t\t\t\t\t`${sessionId}: inbound protocol COMPLETE is local misuse; remote completion must arrive as a DATA envelope fact`,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t\treturn [\n\t\t\t\"DATA\",\n\t\t\tinvalidIngress(\n\t\t\t\t`${sessionId}: inbound port accepts DATA envelope facts only; ${msg[0]} is local protocol traffic`,\n\t\t\t),\n\t\t];\n\t});\n}\n\nfunction invalidIngress(error: string): WireBridgeInvalidIngress {\n\treturn { __wireBridgeInvalidIngress: true, error };\n}\n\nfunction isInvalidIngress(value: unknown): value is WireBridgeInvalidIngress {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t(value as WireBridgeInvalidIngress).__wireBridgeInvalidIngress === true &&\n\t\ttypeof (value as WireBridgeInvalidIngress).error === \"string\"\n\t);\n}\n\nfunction shouldTrackAck(type: WireBridgeEnvelopeType): boolean {\n\treturn type === \"start\" || type === \"data\" || type === \"close\";\n}\n\nfunction isSafePositiveInteger(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) > 0;\n}\n\nfunction isSafeNonNegativeInteger(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) >= 0;\n}\n\nfunction validatePayloadForType(\n\ttype: WireBridgeEnvelopeType,\n\tpayload: unknown,\n\tprefix: string,\n): string | undefined {\n\tconst kind =\n\t\ttypeof payload === \"object\" && payload !== null\n\t\t\t? (payload as { readonly kind?: unknown }).kind\n\t\t\t: undefined;\n\tswitch (type) {\n\t\tcase \"data\":\n\t\t\treturn kind === \"data\" && (payload as { readonly value?: unknown }).value !== undefined\n\t\t\t\t? undefined\n\t\t\t\t: `${prefix}: data envelope requires data payload`;\n\t\tcase \"nack\":\n\t\tcase \"error\":\n\t\t\treturn kind === \"error\" && (payload as { readonly error?: unknown }).error !== undefined\n\t\t\t\t? undefined\n\t\t\t\t: `${prefix}: ${type} envelope requires error payload`;\n\t\tcase \"status\":\n\t\t\treturn kind === \"status\" && (payload as { readonly status?: unknown }).status !== undefined\n\t\t\t\t? undefined\n\t\t\t\t: `${prefix}: status envelope requires status payload`;\n\t\tcase \"close\":\n\t\t\treturn kind === \"close\" ? undefined : `${prefix}: close envelope requires close payload`;\n\t\tcase \"start\":\n\t\tcase \"ack\":\n\t\t\treturn payload === undefined\n\t\t\t\t? undefined\n\t\t\t\t: `${prefix}: ${type} envelope must not carry a payload`;\n\t}\n}\n\nfunction bridgePayloadError(payload: unknown, fallback: unknown): unknown {\n\tif (\n\t\ttypeof payload === \"object\" &&\n\t\tpayload !== null &&\n\t\t(payload as { readonly kind?: unknown }).kind === \"error\"\n\t) {\n\t\treturn (payload as { readonly error?: unknown }).error;\n\t}\n\treturn fallback;\n}\n\nfunction rethrowGraphRuntimeInvariant(error: unknown): void {\n\tconst message = errorMessage(error);\n\tif (\n\t\tmessage.includes(\"R-reentrancy\") ||\n\t\tmessage.includes(\"R-rewire\") ||\n\t\tmessage.includes(\"R-graph-domain\") ||\n\t\tmessage.includes(\"D37\") ||\n\t\tmessage.includes(\"D22\") ||\n\t\tmessage.includes(\"different graph\") ||\n\t\tmessage.includes(\"cross-graph\") ||\n\t\tmessage.includes(\"wire bridge\") ||\n\t\tmessage.includes(\"mid-fn topology mutation\") ||\n\t\tmessage.includes(\"reentrant dep mutation\") ||\n\t\tmessage.includes(\"feedback cycle\")\n\t) {\n\t\tthrow error;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Graph-visible outbound environment adapters (D130/D132).\n *\n * Async transport work is confined to graph-local EnvironmentDrivers. Each\n * helper returns declared nodes for events/status/attempts/errors instead of a\n * hidden sink side channel.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type {\n\tDriverCancel,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tWebSocketRequest,\n\tWebSocketSend,\n\tWebSocketSendResult,\n\tWebSocketSessionHandle,\n} from \"../graph/environment.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\tnextRetryDelayMs,\n\ttype RetryPolicy,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\n\nexport type OutboundEvent<TValue, TResult> =\n\t| { readonly kind: \"attempt\"; readonly value: TValue; readonly attempt: number }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly value: TValue;\n\t\t\treadonly attempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"sent\";\n\t\t\treadonly value: TValue;\n\t\t\treadonly attempt: number;\n\t\t\treadonly result: TResult;\n\t }\n\t| {\n\t\t\treadonly kind: \"failed\";\n\t\t\treadonly value: TValue;\n\t\t\treadonly attempt: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"exhausted\";\n\t\t\treadonly value: TValue;\n\t\t\treadonly attempt: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"upstream-complete\" }\n\t| { readonly kind: \"upstream-error\"; readonly error: unknown };\n\nexport interface OutboundStatus {\n\treadonly state:\n\t\t| \"idle\"\n\t\t| \"running\"\n\t\t| \"waiting\"\n\t\t| \"succeeded\"\n\t\t| \"failed\"\n\t\t| \"exhausted\"\n\t\t| \"completed\";\n\treadonly inFlight: number;\n\treadonly attempt: number;\n\treadonly sent: number;\n\treadonly failed: number;\n\treadonly lastDelayMs?: number;\n}\n\nexport interface OutboundBundle<TValue, TResult> {\n\treadonly events: Node<OutboundEvent<TValue, TResult>>;\n\treadonly status: Node<OutboundStatus>;\n\treadonly attempts: Node<number>;\n\treadonly errors: Node<unknown>;\n}\n\nexport interface OutboundAdapterOptions {\n\treadonly name?: string;\n\treadonly retry?: RetryPolicy;\n}\n\nexport type HttpRequestOf<T> = (value: T) => HttpRequest;\nexport type ProcessCommandOf<T> = (value: T) => ProcessCommand;\nexport type WebSocketSendOf<T> = (value: T) => WebSocketSend;\n\n/** D133 command facts for a graph-visible WebSocket SessionBundle. */\nexport type WebSocketSessionCommand =\n\t| { readonly kind: \"start\" }\n\t| { readonly kind: \"send\"; readonly message: WebSocketSend }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\n/** Inbound facts emitted by the live WebSocket session connection. */\nexport type WebSocketSessionInbound =\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array };\n\n/** Observable lifecycle facts for bounded D133 reconnect/session progress. */\nexport type WebSocketSessionLifecycle =\n\t| { readonly kind: \"starting\"; readonly attempt: number; readonly maxAttempts: number }\n\t| { readonly kind: \"open\"; readonly attempt: number }\n\t| { readonly kind: \"sent\"; readonly message: WebSocketSend }\n\t| { readonly kind: \"closing\"; readonly code?: number; readonly reason?: string }\n\t| { readonly kind: \"closed\"; readonly code?: number; readonly reason?: string }\n\t| {\n\t\t\treadonly kind: \"retrying\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly nextAttempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\n/** D175 graph-visible outbound disposition for a WebSocket SessionBundle send. */\nexport type WebSocketSessionOutbound =\n\t| { readonly kind: \"queued\"; readonly seq: number; readonly message: WebSocketSend }\n\t| { readonly kind: \"sending\"; readonly seq: number; readonly message: WebSocketSend }\n\t| { readonly kind: \"sent\"; readonly seq: number; readonly message: WebSocketSend }\n\t| {\n\t\t\treadonly kind: \"rejected\";\n\t\t\treadonly seq: number;\n\t\t\treadonly message: WebSocketSend;\n\t\t\treadonly error: unknown;\n\t }\n\t| {\n\t\t\treadonly kind: \"canceled\";\n\t\t\treadonly seq: number;\n\t\t\treadonly message: WebSocketSend;\n\t\t\treadonly reason: unknown;\n\t };\n\n/** Current graph-visible WebSocket session status projection. */\nexport interface WebSocketSessionStatus {\n\treadonly state:\n\t\t| \"idle\"\n\t\t| \"connecting\"\n\t\t| \"open\"\n\t\t| \"closing\"\n\t\t| \"closed\"\n\t\t| \"waiting\"\n\t\t| \"exhausted\"\n\t\t| \"errored\";\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly sent: number;\n\treadonly received: number;\n\treadonly errors: number;\n\treadonly lastDelayMs?: number;\n}\n\n/** D133 SessionBundle: all session commands, inbound data, attempts, status, and errors are nodes. */\nexport interface WebSocketSessionBundle {\n\treadonly command: Node<WebSocketSessionCommand>;\n\treadonly inbound: Node<WebSocketSessionInbound>;\n\treadonly lifecycle: Node<WebSocketSessionLifecycle>;\n\treadonly outbound: Node<WebSocketSessionOutbound>;\n\treadonly status: Node<WebSocketSessionStatus>;\n\treadonly errors: Node<unknown>;\n\treadonly attempts: Node<number>;\n\tstart(): void;\n\tsend(message: WebSocketSend | string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n}\n\nexport type WebSocketSessionSendPolicy =\n\t| { readonly kind?: \"reject\" }\n\t| { readonly kind: \"buffer\"; readonly maxPending: number };\n\n/** Options for the D133 WebSocket SessionBundle; retry is bounded unless configured otherwise. */\nexport interface WebSocketSessionOptions {\n\treadonly name?: string;\n\treadonly retry?: RetryPolicy;\n\treadonly sendPolicy?: WebSocketSessionSendPolicy;\n}\n\ntype WebSocketSessionEvent =\n\t| { readonly kind: \"attempt\"; readonly attempt: number; readonly maxAttempts: number }\n\t| { readonly kind: \"open\"; readonly attempt: number }\n\t| { readonly kind: \"message\"; readonly message: WebSocketSessionInbound }\n\t| { readonly kind: \"sent\"; readonly message: WebSocketSend }\n\t| { readonly kind: \"closing\"; readonly code?: number; readonly reason?: string }\n\t| { readonly kind: \"closed\"; readonly code?: number; readonly reason?: string }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly nextAttempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"outbound\"; readonly fact: WebSocketSessionOutbound }\n\t| { readonly kind: \"error\"; readonly error: unknown; readonly attempt?: number }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\ninterface SendState {\n\tseq: number;\n\tcancels: Map<number, DriverCancel>;\n\ttimers: Map<number, ReturnType<typeof setTimeout>>;\n\tactive: boolean;\n\tcleanupInstalled: boolean;\n}\n\nfunction assertSourceLocal<T>(source: Node<T>): Node<T> {\n\treturn source;\n}\n\nfunction initSendState(ctx: Ctx): SendState {\n\tlet state = ctx.state.get<SendState>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tseq: 0,\n\t\t\tcancels: new Map(),\n\t\t\ttimers: new Map(),\n\t\t\tactive: true,\n\t\t\tcleanupInstalled: false,\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tstate.active = true;\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tstate.active = false;\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tfor (const cancel of state.cancels.values()) runCancel(cancel);\n\t\t\tfor (const timer of state.timers.values()) clearTimeout(timer);\n\t\t\tstate.cancels.clear();\n\t\t\tstate.timers.clear();\n\t\t});\n\t}\n\treturn state;\n}\n\nfunction runCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cancellation is best-effort and must not hide graph-visible outcomes.\n\t}\n}\n\nfunction outboundNodes<TValue, TResult>(\n\tgraph: Graph,\n\tevents: Node<OutboundEvent<TValue, TResult>>,\n\tname: string,\n): OutboundBundle<TValue, TResult> {\n\tconst status = graph.node<OutboundStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tconst current =\n\t\t\t\tctx.state.get<OutboundStatus>() ??\n\t\t\t\t({ state: \"idle\", inFlight: 0, attempt: 0, sent: 0, failed: 0 } satisfies OutboundStatus);\n\t\t\tlet next = current;\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tnext = reduceStatus(next, event as OutboundEvent<TValue, TResult>);\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"outboundStatus\" },\n\t);\n\tconst attempts = graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as OutboundEvent<TValue, TResult>;\n\t\t\t\tif (\"attempt\" in typed) ctx.down([[\"DATA\", typed.attempt]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"outboundAttempts\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as OutboundEvent<TValue, TResult>;\n\t\t\t\tif (\"error\" in typed) ctx.down([[\"DATA\", typed.error]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"outboundErrors\" },\n\t);\n\treturn { events, status, attempts, errors };\n}\n\nfunction reduceStatus<TValue, TResult>(\n\tcurrent: OutboundStatus,\n\tevent: OutboundEvent<TValue, TResult>,\n): OutboundStatus {\n\tswitch (event.kind) {\n\t\tcase \"attempt\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"running\",\n\t\t\t\tinFlight: current.inFlight + 1,\n\t\t\t\tattempt: event.attempt,\n\t\t\t};\n\t\tcase \"retry\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"waiting\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t};\n\t\tcase \"sent\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"succeeded\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tsent: current.sent + 1,\n\t\t\t\tlastDelayMs: undefined,\n\t\t\t};\n\t\tcase \"failed\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"failed\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tfailed: current.failed + 1,\n\t\t\t};\n\t\tcase \"exhausted\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"exhausted\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tfailed: current.failed + 1,\n\t\t\t};\n\t\tcase \"upstream-complete\":\n\t\t\treturn { ...current, state: \"completed\" };\n\t\tcase \"upstream-error\":\n\t\t\treturn { ...current, state: \"failed\", failed: current.failed + 1 };\n\t}\n}\n\ninterface WebSocketSessionState {\n\tactive: boolean;\n\tconnected: boolean;\n\tcleanupInstalled: boolean;\n\tcurrentAttempt: number;\n\tcurrentSession: WebSocketSessionHandle | undefined;\n\tsendCancels: Map<number, DriverCancel>;\n\tliveSends: Map<number, PendingWebSocketOutbound>;\n\tpendingOutbound: PendingWebSocketOutbound[];\n\ttimers: Map<number, ReturnType<typeof setTimeout>>;\n\tseq: number;\n\toutboundSeq: number;\n}\n\ninterface PendingWebSocketOutbound {\n\treadonly seq: number;\n\treadonly message: WebSocketSend;\n}\n\nfunction initWebSocketSessionState(ctx: Ctx): WebSocketSessionState {\n\tlet state = ctx.state.get<WebSocketSessionState>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tactive: true,\n\t\t\tconnected: false,\n\t\t\tcleanupInstalled: false,\n\t\t\tcurrentAttempt: 0,\n\t\t\tcurrentSession: undefined,\n\t\t\tsendCancels: new Map(),\n\t\t\tliveSends: new Map(),\n\t\t\tpendingOutbound: [],\n\t\t\ttimers: new Map(),\n\t\t\tseq: 0,\n\t\t\toutboundSeq: 0,\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tstate.active = true;\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tconst sendCancels = [...state.sendCancels.values()];\n\t\t\tconst timers = [...state.timers.values()];\n\t\t\tconst session = state.currentSession;\n\t\t\tstate.active = false;\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tstate.connected = false;\n\t\t\tstate.currentAttempt = 0;\n\t\t\tstate.currentSession = undefined;\n\t\t\tstate.sendCancels.clear();\n\t\t\tstate.liveSends.clear();\n\t\t\tstate.pendingOutbound = [];\n\t\t\tstate.timers.clear();\n\t\t\tfor (const cancel of sendCancels) runCancel(cancel);\n\t\t\tfor (const timer of timers) clearTimeout(timer);\n\t\t\tsession?.cancel();\n\t\t});\n\t}\n\treturn state;\n}\n\nfunction closeWebSocketSessionState(\n\tstate: WebSocketSessionState,\n\tdriverAction: \"cancel\" | \"none\" = \"cancel\",\n): {\n\treadonly canceled: PendingWebSocketOutbound[];\n\treadonly session: WebSocketSessionHandle | undefined;\n} {\n\tconst session = state.currentSession;\n\tconst timers = [...state.timers.values()];\n\tconst sendCancels = [...state.sendCancels.values()];\n\tconst canceled = [...state.pendingOutbound, ...state.liveSends.values()];\n\tstate.connected = false;\n\tstate.currentAttempt = 0;\n\tstate.currentSession = undefined;\n\tstate.timers.clear();\n\tstate.sendCancels.clear();\n\tstate.pendingOutbound = [];\n\tstate.liveSends.clear();\n\tfor (const timer of timers) clearTimeout(timer);\n\tfor (const cancelSend of sendCancels) runCancel(cancelSend);\n\tif (driverAction === \"cancel\") session?.cancel();\n\treturn { canceled, session };\n}\n\nfunction cancelRetryTimers(state: WebSocketSessionState): void {\n\tfor (const timer of state.timers.values()) clearTimeout(timer);\n\tstate.timers.clear();\n}\n\nfunction cleanupWebSocketConnection(\n\tstate: WebSocketSessionState,\n\tdriverAction: \"cancel\" | \"none\" = \"cancel\",\n): PendingWebSocketOutbound[] {\n\tconst session = state.currentSession;\n\tconst sendCancels = [...state.sendCancels.values()];\n\tconst canceled = [...state.liveSends.values()];\n\tstate.connected = false;\n\tstate.currentAttempt = 0;\n\tstate.currentSession = undefined;\n\tstate.sendCancels.clear();\n\tstate.liveSends.clear();\n\tfor (const cancelSend of sendCancels) runCancel(cancelSend);\n\tif (driverAction === \"cancel\") session?.cancel();\n\treturn canceled;\n}\n\nfunction normalizeWebSocketSessionSendPolicy(\n\tpolicy: WebSocketSessionSendPolicy | undefined,\n): { readonly kind: \"reject\" } | { readonly kind: \"buffer\"; readonly maxPending: number } {\n\tif (policy?.kind !== \"buffer\") return { kind: \"reject\" };\n\tif (!Number.isFinite(policy.maxPending) || policy.maxPending < 1) {\n\t\tthrow new Error(\"webSocketSession: buffer sendPolicy requires finite maxPending >= 1\");\n\t}\n\treturn { kind: \"buffer\", maxPending: Math.floor(policy.maxPending) };\n}\n\nfunction webSocketSessionEventNode(\n\tgraph: Graph,\n\tcommand: Node<WebSocketSessionCommand>,\n\trequest: WebSocketRequest,\n\tname: string,\n\tpolicy: RetryPolicy,\n\tsendPolicy: ReturnType<typeof normalizeWebSocketSessionSendPolicy>,\n): Node<WebSocketSessionEvent> {\n\treturn graph.node<WebSocketSessionEvent>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tconst state = initWebSocketSessionState(ctx);\n\n\t\t\tconst emitOutbound = (fact: WebSocketSessionOutbound) => {\n\t\t\t\tctx.down([[\"DATA\", { kind: \"outbound\", fact } satisfies WebSocketSessionEvent]]);\n\t\t\t};\n\n\t\t\tconst emitOutboundCanceled = (\n\t\t\t\titems: readonly PendingWebSocketOutbound[],\n\t\t\t\treason: unknown,\n\t\t\t) => {\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"canceled\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\treason,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst emitOutboundRejected = (items: readonly PendingWebSocketOutbound[], error: unknown) => {\n\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: payload,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst retryOrExhaust = (attempt: number, error: unknown) => {\n\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\tconst canceled = cleanupWebSocketConnection(state);\n\t\t\t\temitOutboundCanceled(canceled, `${name}: connection cleanup`);\n\t\t\t\tif (shouldRetry(policy, attempt)) {\n\t\t\t\t\tconst nextAttempt = attempt + 1;\n\t\t\t\t\tconst delayMs = nextRetryDelayMs(policy, nextAttempt) ?? 0;\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"retry\",\n\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\tnextAttempt,\n\t\t\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\tconst timerId = state.seq++;\n\t\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\t\tstate.timers.delete(timerId);\n\t\t\t\t\t\tif (!state.active) return;\n\t\t\t\t\t\tstart(nextAttempt);\n\t\t\t\t\t}, delayMs);\n\t\t\t\t\tstate.timers.set(timerId, timer);\n\t\t\t\t} else {\n\t\t\t\t\temitOutboundRejected(state.pendingOutbound, payload);\n\t\t\t\t\tstate.pendingOutbound = [];\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ kind: \"exhausted\", attempt, error: payload } satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst start = (attempt: number) => {\n\t\t\t\tif (\n\t\t\t\t\t!state.active ||\n\t\t\t\t\tstate.connected ||\n\t\t\t\t\tstate.currentAttempt !== 0 ||\n\t\t\t\t\tstate.timers.size > 0\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst driver = ctx.environment().webSocketDriver();\n\t\t\t\tstate.currentAttempt = attempt;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"attempt\",\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\tconst connectSession = driver?.connectSession;\n\t\t\t\tif (connectSession === undefined) {\n\t\t\t\t\tretryOrExhaust(attempt, `${name}: missing WebSocket session capability`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet session: WebSocketSessionHandle | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = connectSession.call(driver, request, (event) => {\n\t\t\t\t\t\tif (!state.active || state.currentAttempt !== attempt) return;\n\t\t\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\t\t\tconst ws = event.event;\n\t\t\t\t\t\t\tif (ws.kind === \"open\") {\n\t\t\t\t\t\t\t\tstate.connected = true;\n\t\t\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"open\", attempt } satisfies WebSocketSessionEvent]]);\n\t\t\t\t\t\t\t\tflushPending();\n\t\t\t\t\t\t\t} else if (ws.kind === \"text\" || ws.kind === \"binary\") {\n\t\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tkind: \"message\",\n\t\t\t\t\t\t\t\t\t\t\tmessage: ws satisfies WebSocketSessionInbound,\n\t\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} else if (ws.kind === \"close\") {\n\t\t\t\t\t\t\t\tconst normalClose = ws.code === 1000;\n\t\t\t\t\t\t\t\tconst canceled = cleanupWebSocketConnection(state);\n\t\t\t\t\t\t\t\temitOutboundCanceled(canceled, `${name}: session closed`);\n\t\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tkind: \"closed\",\n\t\t\t\t\t\t\t\t\t\t\tcode: ws.code,\n\t\t\t\t\t\t\t\t\t\t\treason: ws.reason,\n\t\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t\tif (!normalClose) {\n\t\t\t\t\t\t\t\t\tretryOrExhaust(attempt, {\n\t\t\t\t\t\t\t\t\t\tkind: \"close\",\n\t\t\t\t\t\t\t\t\t\tcode: ws.code,\n\t\t\t\t\t\t\t\t\t\treason: ws.reason,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\t\t\tretryOrExhaust(attempt, event.error);\n\t\t\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\t\t\tretryOrExhaust(attempt, `${name}: connection completed`);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tretryOrExhaust(attempt, error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (session === undefined) {\n\t\t\t\t\tretryOrExhaust(attempt, `${name}: missing WebSocket session capability`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.active && state.currentAttempt === attempt) {\n\t\t\t\t\tstate.currentSession = session;\n\t\t\t\t} else {\n\t\t\t\t\tsession.cancel();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfunction sendNow(item: PendingWebSocketOutbound): void {\n\t\t\t\tif (!state.connected) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst session = state.currentSession;\n\t\t\t\tif (session === undefined) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: `${name}: missing WebSocket session capability`,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\terror: `${name}: missing WebSocket session capability`,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst sendId = state.seq++;\n\t\t\t\tstate.liveSends.set(sendId, item);\n\t\t\t\temitOutbound({ kind: \"sending\", seq: item.seq, message: item.message });\n\t\t\t\tlet done = false;\n\t\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcancel = session.send(item.message, (result) => {\n\t\t\t\t\t\tif (done || !state.active || !state.liveSends.has(sendId)) return;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.liveSends.delete(sendId);\n\t\t\t\t\t\tstate.sendCancels.delete(sendId);\n\t\t\t\t\t\tif (result.ok) {\n\t\t\t\t\t\t\temitOutbound({ kind: \"sent\", seq: item.seq, message: item.message });\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\"DATA\", { kind: \"sent\", message: item.message } satisfies WebSocketSessionEvent],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst payload = errorPayload(result.error);\n\t\t\t\t\t\t\temitOutbound({\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\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} catch (error) {\n\t\t\t\t\tstate.liveSends.delete(sendId);\n\t\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: payload,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", error: payload } satisfies WebSocketSessionEvent]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cancel !== undefined && !done && state.active && state.liveSends.has(sendId)) {\n\t\t\t\t\tstate.sendCancels.set(sendId, cancel);\n\t\t\t\t} else if (cancel !== undefined && !state.active) runCancel(cancel);\n\t\t\t}\n\n\t\t\tfunction flushPending(): void {\n\t\t\t\tconst pending = state.pendingOutbound;\n\t\t\t\tstate.pendingOutbound = [];\n\t\t\t\tfor (let index = 0; index < pending.length; index++) {\n\t\t\t\t\tconst item = pending[index];\n\t\t\t\t\tif (!state.connected || state.currentSession === undefined) {\n\t\t\t\t\t\temitOutboundCanceled(pending.slice(index), `${name}: session closed`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsendNow(item);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst send = (message: WebSocketSend) => {\n\t\t\t\tconst item = { seq: state.outboundSeq++, message } satisfies PendingWebSocketOutbound;\n\t\t\t\tif (state.connected) {\n\t\t\t\t\tsendNow(item);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (sendPolicy.kind === \"buffer\") {\n\t\t\t\t\tif (state.pendingOutbound.length >= sendPolicy.maxPending) {\n\t\t\t\t\t\temitOutbound({\n\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\terror: `${name}: outbound buffer full`,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t\terror: `${name}: outbound buffer full`,\n\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstate.pendingOutbound.push(item);\n\t\t\t\t\temitOutbound({ kind: \"queued\", seq: item.seq, message });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\temitOutbound({\n\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\tseq: item.seq,\n\t\t\t\t\tmessage,\n\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t});\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t};\n\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst commandValue = raw as WebSocketSessionCommand;\n\t\t\t\tif (commandValue.kind === \"start\") start(1);\n\t\t\t\telse if (commandValue.kind === \"send\") send(commandValue.message);\n\t\t\t\telse {\n\t\t\t\t\tcancelRetryTimers(state);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"closing\",\n\t\t\t\t\t\t\t\tcode: commandValue.code,\n\t\t\t\t\t\t\t\treason: commandValue.reason,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\tconst { canceled, session } = closeWebSocketSessionState(state, \"none\");\n\t\t\t\t\temitOutboundCanceled(canceled, `${name}: session closed`);\n\t\t\t\t\tsession?.close(commandValue.code, commandValue.reason);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"closed\",\n\t\t\t\t\t\t\t\tcode: commandValue.code,\n\t\t\t\t\t\t\t\treason: commandValue.reason,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/events`, factory: \"webSocketSessionEvents\" },\n\t);\n}\n\nfunction webSocketSessionNodes(\n\tgraph: Graph,\n\tcommand: Node<WebSocketSessionCommand>,\n\tevents: Node<WebSocketSessionEvent>,\n\tname: string,\n\tpolicy: RetryPolicy,\n): WebSocketSessionBundle {\n\tconst inbound = graph.node<WebSocketSessionInbound>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"message\") ctx.down([[\"DATA\", event.message]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/inbound`, factory: \"webSocketSessionInbound\" },\n\t);\n\tconst lifecycle = graph.node<WebSocketSessionLifecycle>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"starting\",\n\t\t\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\t\t\tmaxAttempts: event.maxAttempts,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionLifecycle,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"open\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"open\", attempt: event.attempt }]]);\n\t\t\t\t} else if (event.kind === \"sent\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"sent\", message: event.message }]]);\n\t\t\t\t} else if (event.kind === \"closing\" || event.kind === \"closed\") {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"retrying\",\n\t\t\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\t\t\tnextAttempt: event.nextAttempt,\n\t\t\t\t\t\t\t\tdelayMs: event.delayMs,\n\t\t\t\t\t\t\t\terror: event.error,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionLifecycle,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/lifecycle`, factory: \"webSocketSessionLifecycle\" },\n\t);\n\tconst outbound = graph.node<WebSocketSessionOutbound>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"outbound\") ctx.down([[\"DATA\", event.fact]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/outbound`, factory: \"webSocketSessionOutbound\" },\n\t);\n\tconst status = graph.node<WebSocketSessionStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<WebSocketSessionStatus>() ??\n\t\t\t\t({\n\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\tattempt: 0,\n\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\tsent: 0,\n\t\t\t\t\treceived: 0,\n\t\t\t\t\terrors: 0,\n\t\t\t\t} satisfies WebSocketSessionStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: event.maxAttempts,\n\t\t\t\t\t\tlastDelayMs: undefined,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"open\") {\n\t\t\t\t\tnext = { ...next, state: \"open\", attempt: event.attempt, lastDelayMs: undefined };\n\t\t\t\t} else if (event.kind === \"message\") {\n\t\t\t\t\tnext = { ...next, received: next.received + 1 };\n\t\t\t\t} else if (event.kind === \"sent\") {\n\t\t\t\t\tnext = { ...next, sent: next.sent + 1 };\n\t\t\t\t} else if (event.kind === \"closing\") {\n\t\t\t\t\tnext = { ...next, state: \"closing\" };\n\t\t\t\t} else if (event.kind === \"closed\") {\n\t\t\t\t\tnext = { ...next, state: \"closed\" };\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\tattempt: event.attempt ?? next.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"webSocketSessionStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (\"error\" in event) ctx.down([[\"DATA\", event.error]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"webSocketSessionErrors\" },\n\t);\n\tconst attempts = graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") ctx.down([[\"DATA\", event.attempt]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"webSocketSessionAttempts\" },\n\t);\n\treturn {\n\t\tcommand,\n\t\tinbound,\n\t\tlifecycle,\n\t\toutbound,\n\t\tstatus,\n\t\terrors,\n\t\tattempts,\n\t\tstart: () => command.down([[\"DATA\", { kind: \"start\" }]]),\n\t\tsend: (message) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\ttypeof message === \"string\" || message instanceof Uint8Array\n\t\t\t\t\t\t\t\t? { data: message }\n\t\t\t\t\t\t\t\t: message,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tclose: (code, reason) => command.down([[\"DATA\", { kind: \"close\", code, reason }]]),\n\t};\n}\n\n/**\n * Create a graph-visible D133 WebSocket SessionBundle.\n *\n * The convenience start/send/close methods publish command facts only; hidden\n * session state is driven by the command node and graph-local EnvironmentDrivers.\n */\nexport function webSocketSession(\n\tgraph: Graph,\n\trequest: WebSocketRequest,\n\topts: WebSocketSessionOptions = {},\n): WebSocketSessionBundle {\n\tconst name = opts.name ?? \"webSocketSession\";\n\tconst policy = opts.retry ?? retryPolicy();\n\tconst sendPolicy = normalizeWebSocketSessionSendPolicy(opts.sendPolicy);\n\tconst command = graph.node<WebSocketSessionCommand>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"webSocketSessionCommand\",\n\t});\n\tconst events = webSocketSessionEventNode(graph, command, request, name, policy, sendPolicy);\n\treturn webSocketSessionNodes(graph, command, events, name, policy);\n}\n\nfunction outboundNode<TValue, TResult>(\n\tgraph: Graph,\n\tsource: Node<TValue>,\n\tname: string,\n\tsend: (\n\t\tctx: Ctx,\n\t\tvalue: TValue,\n\t\tcallback: (result: { ok: true; value: TResult } | { ok: false; error: unknown }) => void,\n\t) => DriverCancel | undefined,\n\topts: OutboundAdapterOptions,\n): Node<OutboundEvent<TValue, TResult>> {\n\tconst policy = opts.retry ?? retryPolicy();\n\treturn graph.node<OutboundEvent<TValue, TResult>>(\n\t\t[assertSourceLocal(source)],\n\t\t(ctx) => {\n\t\t\tconst state = initSendState(ctx);\n\t\t\tconst start = (value: TValue, attempt: number) => {\n\t\t\t\tif (!state.active) return;\n\t\t\t\tconst id = state.seq++;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"attempt\", value, attempt } satisfies OutboundEvent<TValue, TResult>],\n\t\t\t\t]);\n\t\t\t\tconst failTerminal = (error: unknown) => {\n\t\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ kind: \"exhausted\", value, attempt, error: payload } satisfies OutboundEvent<\n\t\t\t\t\t\t\t\tTValue,\n\t\t\t\t\t\t\t\tTResult\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\tctx.down([[\"ERROR\", payload]]);\n\t\t\t\t};\n\t\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\t\tlet done = false;\n\t\t\t\ttry {\n\t\t\t\t\tcancel = send(ctx, value, (result) => {\n\t\t\t\t\t\tif (done || !state.active) return;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.cancels.delete(id);\n\t\t\t\t\t\tif (result.ok) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{ kind: \"sent\", value, attempt, result: result.value } satisfies OutboundEvent<\n\t\t\t\t\t\t\t\t\t\tTValue,\n\t\t\t\t\t\t\t\t\t\tTResult\n\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (shouldRetry(policy, attempt)) {\n\t\t\t\t\t\t\tconst nextAttempt = attempt + 1;\n\t\t\t\t\t\t\tconst delayMs = nextRetryDelayMs(policy, nextAttempt) ?? 0;\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"retry\",\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\t\t\t\t\terror: errorPayload(result.error),\n\t\t\t\t\t\t\t\t\t} satisfies OutboundEvent<TValue, TResult>,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\t\t\t\tstate.timers.delete(id);\n\t\t\t\t\t\t\t\tif (!state.active) return;\n\t\t\t\t\t\t\t\tstart(value, nextAttempt);\n\t\t\t\t\t\t\t}, delayMs);\n\t\t\t\t\t\t\tstate.timers.set(id, timer);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"exhausted\",\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\t\t\terror: errorPayload(result.error),\n\t\t\t\t\t\t\t\t\t} satisfies OutboundEvent<TValue, TResult>,\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} catch (error) {\n\t\t\t\t\tif (!done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.cancels.delete(id);\n\t\t\t\t\t\tfailTerminal(error);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cancel === undefined) {\n\t\t\t\t\tif (!done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tfailTerminal(`${name}: missing environment driver capability`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!done && state.active) {\n\t\t\t\t\tstate.cancels.set(id, cancel);\n\t\t\t\t} else if (!state.active) {\n\t\t\t\t\trunCancel(cancel);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) start(value as TValue, 1);\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal === true) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"upstream-complete\" } satisfies OutboundEvent<TValue, TResult>],\n\t\t\t\t]);\n\t\t\t} else if (terminal !== false && terminal !== undefined) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ kind: \"upstream-error\", error: terminal } satisfies OutboundEvent<TValue, TResult>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory: name },\n\t);\n}\n\nexport function toHttp<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trequestOf: HttpRequestOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, HttpResponse> {\n\tconst name = opts.name ?? \"toHttp\";\n\tconst events = outboundNode<T, HttpResponse>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst request = requestOf(value);\n\t\t\treturn ctx.environment().httpDriver()?.request(request, callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n\nexport function toProcess<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tcommandOf: ProcessCommandOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, ProcessResult> {\n\tconst name = opts.name ?? \"toProcess\";\n\tconst events = outboundNode<T, ProcessResult>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst command = commandOf(value);\n\t\t\treturn ctx.environment().processDriver()?.run(command, callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n\nexport function toWebSocket<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trequest: WebSocketRequest,\n\tsendOf: WebSocketSendOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, WebSocketSendResult> {\n\tconst name = opts.name ?? \"toWebSocket\";\n\tconst events = outboundNode<T, WebSocketSendResult>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst driver = ctx.environment().webSocketDriver();\n\t\t\treturn driver?.send?.(request, sendOf(value), callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n","/**\n * Dependency-free NestJS adapter tokens and method metadata.\n *\n * The old compat layer imported `@nestjs/common` for DI decorators. Clean-slate keeps the\n * retainable token/metadata vocabulary here and leaves actual `Inject(...)` composition to\n * user-land NestJS code, so @graphrefly/ts keeps zero framework dependencies (D125/B61).\n */\n\n/** Injection token for a root graph singleton. */\nexport const GRAPHREFLY_ROOT_GRAPH = Symbol.for(\"graphrefly:root-graph\");\n\n/** Injection token for adapter module options. */\nexport const GRAPHREFLY_MODULE_OPTIONS = Symbol.for(\"graphrefly:module-options\");\n\n/** Injection token for a request-scoped graph. */\nexport const GRAPHREFLY_REQUEST_GRAPH = Symbol.for(\"graphrefly:request-graph\");\n\nexport type DecoratorHostConstructor = abstract new (...args: unknown[]) => unknown;\nexport type DecoratorBoundMethod = (...args: unknown[]) => unknown;\n\nexport interface OnGraphEventMeta {\n\tnodeName: string;\n\tmethodKey: string | symbol;\n}\n\nexport interface GraphIntervalMeta {\n\tms: number;\n\tmethodKey: string | symbol;\n}\n\nexport interface GraphCronMeta {\n\texpr: string;\n\tmethodKey: string | symbol;\n}\n\nexport const EVENT_HANDLERS = new Map<DecoratorHostConstructor, OnGraphEventMeta[]>();\nexport const INTERVAL_HANDLERS = new Map<DecoratorHostConstructor, GraphIntervalMeta[]>();\nexport const CRON_HANDLERS = new Map<DecoratorHostConstructor, GraphCronMeta[]>();\n\nexport type GraphMethodDecorator = MethodDecorator &\n\t((value: DecoratorBoundMethod, context: ClassMethodDecoratorContext) => void);\n\n/** Get the injection token for a named feature graph. */\nexport function getGraphToken(name: string): symbol {\n\treturn Symbol.for(`graphrefly:graph:${name}`);\n}\n\n/** Get the injection token for a node at a qualified path. */\nexport function getNodeToken(path: string): symbol {\n\treturn Symbol.for(`graphrefly:node:${path}`);\n}\n\nfunction sameMeta<T>(a: T, b: T): boolean {\n\tconst left = a as Record<string | symbol, unknown>;\n\tconst right = b as Record<string | symbol, unknown>;\n\tconst keys = Reflect.ownKeys(left);\n\tif (keys.length !== Reflect.ownKeys(right).length) return false;\n\tfor (const key of keys) {\n\t\tif (!Object.is(left[key], right[key])) return false;\n\t}\n\treturn true;\n}\n\nfunction pushUniqueMeta<T>(\n\tregistry: Map<DecoratorHostConstructor, T[]>,\n\tctor: DecoratorHostConstructor,\n\titem: T,\n): void {\n\tconst existing = registry.get(ctor) ?? [];\n\tif (existing.some((current) => sameMeta(current, item))) return;\n\tregistry.set(ctor, [...existing, item]);\n}\n\nfunction registerMeta<T>(\n\tregistry: Map<DecoratorHostConstructor, T[]>,\n\tmeta: (methodKey: string | symbol) => T,\n): GraphMethodDecorator {\n\treturn ((targetOrValue: object, contextOrKey: ClassMethodDecoratorContext | string | symbol) => {\n\t\tif (typeof contextOrKey === \"object\" && contextOrKey !== null) {\n\t\t\tconst methodKey = contextOrKey.name;\n\t\t\tcontextOrKey.addInitializer(function (this: unknown) {\n\t\t\t\tconst ctor = (this as { constructor: DecoratorHostConstructor }).constructor;\n\t\t\t\tpushUniqueMeta(registry, ctor, meta(methodKey));\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst ctor = (targetOrValue as { constructor: DecoratorHostConstructor }).constructor;\n\t\tpushUniqueMeta(registry, ctor, meta(contextOrKey));\n\t}) as GraphMethodDecorator;\n}\n\n/** Register a method as a DATA-event handler for a graph observe path. */\nexport function OnGraphEvent(nodeName: string): GraphMethodDecorator {\n\treturn registerMeta(EVENT_HANDLERS, (methodKey) => ({ nodeName, methodKey }));\n}\n\n/** Register fixed-interval metadata for a user-land NestJS scheduler bridge. */\nexport function GraphInterval(ms: number): GraphMethodDecorator {\n\treturn registerMeta(INTERVAL_HANDLERS, (methodKey) => ({ ms, methodKey }));\n}\n\n/** Register cron metadata for a user-land NestJS scheduler bridge. */\nexport function GraphCron(expr: string): GraphMethodDecorator {\n\treturn registerMeta(CRON_HANDLERS, (methodKey) => ({ expr, methodKey }));\n}\n","/**\n * The shared reactiveCollection core (CSP-2.8, D60).\n *\n * Every reactive data structure (list/map/index/log) is `collectionCore(backend) + a typed method\n * surface` (D60 #5). The core owns the TWO output ports and nothing else:\n *\n * - BACKEND — the single materialized state (D60 #1): a plain mutable object with a monotonic\n * `version` + a `snapshot()`. It applies deltas and IS the materialized state; there is NO ACC\n * node and NO effect bridge re-deriving it (the misdesign D60 rejected — the backend already\n * integrates, its cost is intrinsic). The backend is a closure object, not a graph node, so its\n * durability is structural (survives last-subscriber disconnect; node ROM/RAM is moot, D60 #1).\n *\n * - DELTA port (D60 #2a) — an always-on bare source ({@link CollectionCore.delta}); each mutation\n * pushes ONE change payload (O(1)/mutation). Downstream watches events anytime. It is the\n * structure's BACKBONE: the snapshot node declares it as its dep (D60 reactiveList topology).\n *\n * - SNAPSHOT port (D60 #2b) — a pull-mode node ({@link CollectionCore.snapshot}, R-pull/D269) that\n * is QUIET by default and, on a cone-routed PULL demand, LAZILY reads `backend.snapshot()`\n * (one O(n) materialization) and pushes it once, then re-quiets. The O(n) build happens ONLY on\n * demand — never eagerly per mutation (D60 #2b: lazy is P·O(n), not M·O(n)). It has NO value of\n * its own — its fn reads the backend on demand, so the backend stays the single source of truth\n * (D60 #3). Coalesce-on-no-change is free: the delta-dep's DIRTY/DATA arms the pull node via\n * R-pull's quiet-absorb accounting; a demand with no intervening delta emits no duplicate DATA.\n *\n * Demand path: a downstream consumer issues `ctx.upNext([[\"PULL\", { pullId: core.pullId }]])`\n * (boundary-deferred self-demand, R-up-routing/D269) — it needs the snapshot node upstream in its\n * declared cone, NOT its reference. Cold-start (a demand before any mutation) emits no DATA; for an\n * initial/imperative read use the structure's synchronous quick-read (the deliberately-non-reactive\n * peek, D60) — the reactive pull serves the watch-delta-then-demand pattern.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch } from \"../../ctx/types.js\";\nimport type { Dispatcher } from \"../../dispatcher/index.js\";\nimport { Node, releaseRuntimeOfNode } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport { type GraphCheckpointJson, registerBackendStateContributor } from \"../checkpoint.js\";\nimport type { Graph } from \"../graph.js\";\nimport type { Operator } from \"../operators.js\";\nimport type { ViewCachePolicy } from \"../policies/types.js\";\n\n/** The materialized-state contract a structure's backend must satisfy (D60 #1). */\nexport interface CollectionBackend<S> {\n\t/** Monotonic mutation counter; advances on every visible state change (idempotency, D49). */\n\treadonly version: number;\n\t/** A fresh defensive materialization of the current state (D60: first-cut defensive copy). */\n\tsnapshot(): S;\n}\n\nexport interface CollectionCoreOptions {\n\t/** Debug/inspection name; the delta/snapshot nodes derive `${name}.delta` / `${name}.snapshot`. */\n\tname?: string;\n\t/** Dispatcher for the core's nodes (default = process-global, D26). */\n\tdispatcher?: Dispatcher;\n\t/** Graph funnel for describe-visible input folds (D61). Required by *From/attach methods. */\n\tgraph?: Graph;\n}\n\nexport interface CollectionCore<S, C> {\n\t/** DELTA backbone (D60 #2a): a bare source; every {@link CollectionCore.emit} pushes one change. */\n\treadonly delta: Node<C>;\n\t/** SNAPSHOT pull node (D60 #2b): demand via `ctx.upNext([[\"PULL\", { pullId }]])`; lazy O(n) on demand. */\n\treadonly snapshot: Node<S>;\n\t/** The snapshot node's pullId — the author writes it verbatim into the demander's fn (D269). */\n\treadonly pullId: symbol;\n\t/** Push one delta event (the imperative path: a method mutates the backend, then calls this). */\n\temit(change: C): void;\n\t/**\n\t * D54 widening: fold an in-graph producer `src` into the backend. `apply` mutates the backend +\n\t * `emit`s the change(s). The folder is a DECLARED-dep node (describe shows `src → folder`, NOT a\n\t * D45 island); its emit is the structure's plumbing (D54-sanctioned). Returns a disposer.\n\t */\n\tbindSource<V>(src: Node<V>, apply: (value: V) => void): () => void;\n}\n\n/**\n * Public D121 collection-view surface. A view is a derived surface: `delta` is the pushed update\n * port, `snapshot` is a lazy pull node, and neither port is writable authority.\n */\nexport interface ReactiveView<C, S> {\n\t/** Derived DELTA/update stream for the view. For light views this is recomputed from the parent backend. */\n\treadonly delta: Node<C>;\n\t/** Derived SNAPSHOT pull node: demand via `pullId` to materialize the current view. */\n\treadonly snapshot: Node<S>;\n\t/** The snapshot node's pullId (R-pull/D269), minted per view instance. */\n\treadonly pullId: symbol;\n\t/** Release memoized/light-view resources owned by the parent collection. */\n\tdispose(): void;\n}\n\ninterface LightReactiveViewOptions<S> extends CollectionCoreOptions {\n\treadonly factory: string;\n\treadonly materializeSnapshot: () => S;\n\treadonly onDispose?: () => void;\n}\n\ninterface CollectionRestoreSpec {\n\treadonly deltaRef: string;\n\treadonly snapshotRef: string;\n\treadonly config?: GraphCheckpointJson;\n\treadonly backendState: () => unknown;\n}\n\nfunction validateViewCacheMaxEntries(policy: ViewCachePolicy | undefined): number | undefined {\n\tconst maxEntries = policy?.maxEntries;\n\tif (maxEntries === undefined) return undefined;\n\tif (!Number.isInteger(maxEntries) || maxEntries < 0) {\n\t\tthrow new RangeError(`viewCache.maxEntries must be a non-negative integer (got ${maxEntries})`);\n\t}\n\treturn maxEntries;\n}\n\n/**\n * Internal D80 memo manager for derived views. Eviction drops only the structure's memo lookup;\n * returned ReactiveView handles remain live until explicitly disposed or their parent releases all\n * live views.\n */\nexport class ViewMemoCache<K, V extends { dispose(): void }> {\n\tprivate readonly maxEntries: number | undefined;\n\tprivate readonly equals: (a: K, b: K) => boolean;\n\tprivate readonly memo: Array<{ key: K; value: V }> = [];\n\tprivate readonly live = new Set<V>();\n\n\tconstructor(policy: ViewCachePolicy | undefined, equals: (a: K, b: K) => boolean = Object.is) {\n\t\tthis.maxEntries = validateViewCacheMaxEntries(policy);\n\t\tthis.equals = equals;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst index = this.memo.findIndex((entry) => this.equals(entry.key, key));\n\t\tif (index < 0) return undefined;\n\t\tconst [entry] = this.memo.splice(index, 1);\n\t\tif (entry === undefined) return undefined;\n\t\tthis.memo.push(entry);\n\t\treturn entry.value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tthis.deleteValue(value);\n\t\tthis.live.add(value);\n\t\tif (this.maxEntries === 0) return;\n\t\tthis.memo.push({ key, value });\n\t\twhile (this.maxEntries !== undefined && this.memo.length > this.maxEntries) {\n\t\t\tthis.memo.shift();\n\t\t}\n\t}\n\n\tdeleteValue(value: V): void {\n\t\tfor (let i = this.memo.length - 1; i >= 0; i -= 1) {\n\t\t\tif (this.memo[i]?.value === value) this.memo.splice(i, 1);\n\t\t}\n\t\tthis.live.delete(value);\n\t}\n\n\tdisposeAll(): void {\n\t\tfor (const view of [...this.live]) view.dispose();\n\t\tthis.memo.length = 0;\n\t\tthis.live.clear();\n\t}\n}\n\n/**\n * Build a D121 first-cut light view. The view declares `parent.delta -> view.delta ->\n * view.snapshot`; the pushed `delta` forwards parent delta events as the view's arm/update stream,\n * while `snapshot` reads the parent collection backend through the supplied materializer on demand.\n * No writable state/cache is exposed (D120).\n */\nexport function lightReactiveView<C, S>(\n\tparentDelta: Node<unknown>,\n\topts: LightReactiveViewOptions<S>,\n): ReactiveView<C, S> {\n\tconst { dispatcher, factory, graph, materializeSnapshot, name, onDispose } = opts;\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst group = graph?.topologyGroup({ name: name ?? factory });\n\tconst deltaBody = (ctx: Ctx): void => {\n\t\tfor (const change of (depBatch(ctx, 0) ?? []) as readonly C[]) {\n\t\t\tctx.down([[\"DATA\", change]]);\n\t\t}\n\t};\n\tconst delta = group\n\t\t? group.node<C>([parentDelta], deltaBody, {\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_view_delta\", factory },\n\t\t\t\tpartial: true,\n\t\t\t})\n\t\t: new Node<C>([parentDelta], deltaBody, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tpartial: true,\n\t\t\t});\n\n\tconst pullId = Symbol(name ? `${name}.snapshot` : `${factory}.snapshot`);\n\tconst snapshotBody = (ctx: Ctx): void => {\n\t\ttry {\n\t\t\tctx.down([[\"DATA\", materializeSnapshot()]]);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, `${factory}.snapshot materializer failed`)]]);\n\t\t}\n\t};\n\tconst snapshot = group\n\t\t? group.node<S>([delta as Node<unknown>], snapshotBody, {\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_view_snapshot\", factory },\n\t\t\t\tpartial: true,\n\t\t\t\tpullId,\n\t\t\t})\n\t\t: new Node<S>([delta as Node<unknown>], snapshotBody, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tpartial: true,\n\t\t\t\tpullId,\n\t\t\t});\n\n\tlet disposed = false;\n\treturn {\n\t\tdelta,\n\t\tsnapshot,\n\t\tpullId,\n\t\tdispose(): void {\n\t\t\tif (disposed) return;\n\t\t\tif (group) {\n\t\t\t\tgroup.release({ reason: factory });\n\t\t\t} else {\n\t\t\t\treleaseRuntimeOfNode(delta as Node<unknown>);\n\t\t\t\treleaseRuntimeOfNode(snapshot as Node<unknown>);\n\t\t\t}\n\t\t\tdisposed = true;\n\t\t\tonDispose?.();\n\t\t},\n\t};\n}\n\n/**\n * Build the shared core for a reactive structure (D60). `factory` names the nodes for describe\n * (D6/D51 auto-discovery). The structure passes its `backend` (any {@link CollectionBackend}) and\n * layers a typed method surface on top.\n */\nexport function collectionCore<S, C>(\n\tbackend: CollectionBackend<S>,\n\tfactory: string,\n\topts: CollectionCoreOptions = {},\n\trestore?: CollectionRestoreSpec,\n): CollectionCore<S, C> {\n\tconst { name, dispatcher, graph } = opts;\n\tconst base: { dispatcher?: Dispatcher } = dispatcher ? { dispatcher } : {};\n\tlet bindSeq = 0;\n\n\t// DELTA backbone: a bare source (D60 #2a / review #2 — node([], null), no `initial`, so a late\n\t// subscriber gets no fake \"initial change\"; state is the snapshot port's job).\n\tconst delta = graph\n\t\t? graph.node<C>([], null, {\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_delta\", collection: factory },\n\t\t\t\t...(restore ? { restore: { ref: restore.deltaRef, config: restore.config } } : {}),\n\t\t\t})\n\t\t: new Node<C>([], null, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t});\n\n\t// SNAPSHOT pull node: dep=[delta] (the backbone arms it via quiet-absorb so coalesce is free,\n\t// D60). The fn IGNORES the delta value — it reads `backend.snapshot()` on demand (D60 #3). The\n\t// pullId is a unique Symbol (R-pull/D269: matched by identity, zero collision with pause locks).\n\t// `partial:true`: the fn does not need the delta's value, so it must not gate on \"all deps\n\t// settled\" — it fires whenever armed (a mutation since the last delivery).\n\tconst pullId = Symbol(name ? `${name}.snapshot` : `${factory}.snapshot`);\n\tlet deliveredVersion = backend.version;\n\tconst snapFn = (ctx: Ctx): void => {\n\t\tif (ctx.pull !== undefined && backend.version === deliveredVersion) return;\n\t\tdeliveredVersion = backend.version;\n\t\tctx.down([[\"DATA\", backend.snapshot()]]);\n\t};\n\tconst snapshot = graph\n\t\t? graph.node<S>([delta as Node<unknown>], snapFn, {\n\t\t\t\tpullId,\n\t\t\t\tpartial: true,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot\", collection: factory },\n\t\t\t\t...(restore ? { restore: { ref: restore.snapshotRef, config: restore.config } } : {}),\n\t\t\t})\n\t\t: new Node<S>([delta as Node<unknown>], snapFn, {\n\t\t\t\t...base,\n\t\t\t\tpullId,\n\t\t\t\tpartial: true,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t});\n\n\tif (restore !== undefined) {\n\t\tregisterBackendStateContributor(delta as Node<unknown>, restore.backendState);\n\t}\n\n\tfunction emit(change: C): void {\n\t\t// External tier-3 emit → the substrate synthesizes the leading DIRTY (R-dirty-before-data),\n\t\t// which the quiet snapshot node absorbs (R-pull) and uses to arm its next demand delivery.\n\t\tdelta.down([[\"DATA\", change]]);\n\t}\n\n\tfunction bindSource<V>(src: Node<V>, apply: (value: V) => void): () => void {\n\t\tif (graph === undefined)\n\t\t\tthrow new Error(\n\t\t\t\t\"collectionCore.bindSource requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t);\n\t\t// A graph-bound declared-dep folder (effect-shaped): reads each src batch value, applies it\n\t\t// to the backend (apply mutates + emits the delta). src → folder is a real edge describe\n\t\t// shows (D54/D61), not an internal subscribe island.\n\t\tconst op: Operator<V, void> = {\n\t\t\tfactory: `${factory}.bindSource`,\n\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\ttry {\n\t\t\t\t\tif (b) for (const v of b) apply(v as V);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"collectionCore.bindSource failed\")]]);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t\tconst folder = graph.initNode(op, [src], {\n\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\tmeta: { kind: \"collection_bind_source\", collection: factory },\n\t\t});\n\t\treturn graph.retain(folder, { reason: `${factory}.bindSource` });\n\t}\n\n\treturn { delta, snapshot, pullId, emit, bindSource };\n}\n","/**\n * Reactive dual-key index (CSP-2.8, D54/D60) — unique primary key, rows sorted by (secondary, primary).\n *\n * Shape = the shared {@link collectionCore} two ports over a sorted-array + parallel-Map BACKEND\n * (D60). The SNAPSHOT port delivers the ordered `IndexRow[]`. Secondary/reverse lookup = \"Z\"\n * (review #4): `has`/`get`/`rangeByPrimary` are SYNCHRONOUS point-reads over the backend's parallel\n * Map (NOT topology, like `.cache`); `byPrimary` is an OPTIONAL reactive derived over the delta\n * backbone (a pushed primary→value map), LAZILY created on first access (no default keepalive,\n * R-rom-ram). The two coexist: the derived is the reactive reverse-lookup port; the sync reads are\n * the point query.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount, depLatest } from \"../../ctx/types.js\";\nimport { Node, node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport type { Operator } from \"../operators.js\";\nimport type { OrderedCapacityPolicy, ReactiveOpt, ViewCachePolicy } from \"../policies/types.js\";\nimport type { IndexChange } from \"./change.js\";\nimport {\n\ttype CollectionCore,\n\ttype CollectionCoreOptions,\n\tcollectionCore,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport type ReactiveIndexOpt<T> = ReactiveOpt<T>;\nexport type ReactiveIndexCapacityOrder = \"secondary\" | \"primary\" | \"lru\";\n\nexport interface ReactiveIndexCapacityPolicy\n\textends OrderedCapacityPolicy<ReactiveIndexCapacityOrder> {}\n\nexport interface ReactiveIndexOptions extends CollectionCoreOptions {\n\t/**\n\t * D73 explicit capacity policy: no implicit eviction default.\n\t * `order` chooses eviction semantics and `maxSize` may be static or node-valued (D68).\n\t */\n\treadonly capacity?: ReactiveIndexCapacityPolicy;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\treadonly viewCache?: ViewCachePolicy;\n}\n\nexport interface IndexRow<K, V = unknown> {\n\treadonly primary: K;\n\treadonly secondary: unknown;\n\treadonly value: V;\n}\n\nexport interface ReactiveIndex<K, V = unknown> {\n\treadonly delta: Node<IndexChange<K, V>>;\n\t/** SNAPSHOT pull node: demand → rows sorted by (secondary, primary) (lazy O(n)). */\n\treadonly snapshot: Node<readonly IndexRow<K, V>[]>;\n\treadonly pullId: symbol;\n\t/** Row count (O(1)). Sync non-reactive read. */\n\treadonly size: number;\n\t/** O(1) primary-key existence. Sync read (Z). */\n\thas(primary: K): boolean;\n\t/** O(1) value lookup by primary key. Sync read (Z). */\n\tget(primary: K): V | undefined;\n\t/** Values whose primary sorts within `[start, end)`, ascending primary order. Sync read (Z). */\n\trangeByPrimary(start: K, end: K): V[];\n\t/**\n\t * D121 light range view over the primary axis. `delta` forwards parent index mutations, and\n\t * `snapshot` is a pull node that materializes the current range on demand.\n\t */\n\trange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]>;\n\t/** Ordered rows (fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly IndexRow<K, V>[];\n\t/** Primary→value map (fresh copy). Sync non-reactive read. */\n\ttoPrimaryMap(): ReadonlyMap<K, V>;\n\t/**\n\t * OPTIONAL reactive reverse-lookup port (Z): a derived primary→value map, pushed on every\n\t * mutation. Lazily created on first access (no keepalive — live only while subscribed). Use the\n\t * synchronous {@link ReactiveIndex.get} for a one-shot point query.\n\t */\n\treadonly byPrimary: Node<ReadonlyMap<K, V>>;\n\t/** Insert/replace a row. Returns `true` if a NEW row was inserted (primary was absent). */\n\tupsert(primary: K, secondary: unknown, value: V): boolean;\n\t/** Bulk upsert; one delta per row. No-op if empty. */\n\tupsertMany(rows: Iterable<{ primary: K; secondary: unknown; value: V }>): void;\n\tdelete(primary: K): void;\n\t/** Bulk delete; one delta event. No-op if nothing removed. */\n\tdeleteMany(primaries: Iterable<K>): void;\n\tclear(): void;\n\t/** D54 widening: every row from `src` is upserted. Returns a disposer. */\n\tupsertFrom(src: Node<{ primary: K; secondary: unknown; value: V }>): () => void;\n\tdispose(): void;\n}\n\n// ── ordering helpers (pure; backend-internal) ──\nfunction cmpOrd(a: unknown, b: unknown): number {\n\tif (a === b) return 0;\n\tconst ta = typeof a;\n\tif (\n\t\tta === typeof b &&\n\t\t(ta === \"number\" || ta === \"string\" || ta === \"boolean\" || ta === \"bigint\")\n\t) {\n\t\tconst ax = a as number | string;\n\t\tconst bx = b as number | string;\n\t\treturn ax < bx ? -1 : ax > bx ? 1 : 0;\n\t}\n\treturn String(a).localeCompare(String(b));\n}\nfunction compareRows<K, V>(a: IndexRow<K, V>, b: IndexRow<K, V>): number {\n\tconst c = cmpOrd(a.secondary, b.secondary);\n\treturn c !== 0 ? c : cmpOrd(a.primary, b.primary);\n}\nfunction bisectLeft<K, V>(rows: readonly IndexRow<K, V>[], row: IndexRow<K, V>): number {\n\tlet lo = 0;\n\tlet hi = rows.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (compareRows(rows[mid] as IndexRow<K, V>, row) < 0) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** Default sorted-array + parallel-Map backend (D60 first-cut; B-tree/persistent backend deferred). */\nclass IndexBackend<K, V> {\n\tprivate _version = 0;\n\tprivate readonly buf: IndexRow<K, V>[] = [];\n\tprivate readonly byKey = new Map<K, IndexRow<K, V>>();\n\tprivate readonly trackLru: boolean;\n\n\tconstructor(trackLru: boolean, initialRows: readonly IndexRow<K, V>[] = []) {\n\t\tthis.trackLru = trackLru;\n\t\tfor (const row of initialRows) {\n\t\t\tthis.upsert(row.primary, row.secondary, row.value);\n\t\t}\n\t\tthis._version = 0;\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\thas(primary: K): boolean {\n\t\tconst row = this.byKey.get(primary);\n\t\tif (row === undefined) return false;\n\t\tthis.touchLru(row);\n\t\treturn true;\n\t}\n\tget(primary: K): V | undefined {\n\t\tconst row = this.byKey.get(primary);\n\t\tif (row === undefined) return undefined;\n\t\tthis.touchLru(row);\n\t\treturn row.value;\n\t}\n\n\tprivate touchLru(row: IndexRow<K, V>): void {\n\t\tif (!this.trackLru) return;\n\t\tthis.byKey.delete(row.primary);\n\t\tthis.byKey.set(row.primary, row);\n\t}\n\n\tprivate removeRow(row: IndexRow<K, V>): void {\n\t\tconst start = bisectLeft(this.buf, row);\n\t\tfor (\n\t\t\tlet i = start;\n\t\t\ti < this.buf.length && compareRows(this.buf[i] as IndexRow<K, V>, row) === 0;\n\t\t\ti++\n\t\t) {\n\t\t\tif (this.buf[i] === row) {\n\t\t\t\tthis.buf.splice(i, 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst fallback = this.buf.indexOf(row);\n\t\tif (fallback >= 0) {\n\t\t\tthis.buf.splice(fallback, 1);\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"reactiveIndex: internal row index desynchronized\");\n\t}\n\n\tupsert(primary: K, secondary: unknown, value: V): boolean {\n\t\tconst existing = this.byKey.get(primary);\n\t\tconst row: IndexRow<K, V> = { primary, secondary, value };\n\t\tif (existing !== undefined) {\n\t\t\tthis.removeRow(existing);\n\t\t\tthis.byKey.delete(primary);\n\t\t}\n\t\tthis.buf.splice(bisectLeft(this.buf, row), 0, row);\n\t\tthis.byKey.set(primary, row);\n\t\tthis._version += 1;\n\t\treturn existing === undefined;\n\t}\n\n\tdelete(primary: K): boolean {\n\t\tconst existing = this.byKey.get(primary);\n\t\tif (existing === undefined) return false;\n\t\tthis.removeRow(existing);\n\t\tthis.byKey.delete(primary);\n\t\tthis._version += 1;\n\t\treturn true;\n\t}\n\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis.byKey.clear();\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\trangeByPrimary(start: K, end: K): V[] {\n\t\tif (cmpOrd(start, end) >= 0) return [];\n\t\tconst rows = [...this.byKey.entries()].filter(\n\t\t\t([p]) => cmpOrd(p, start) >= 0 && cmpOrd(p, end) < 0,\n\t\t);\n\t\trows.sort(([a], [b]) => cmpOrd(a, b));\n\t\treturn rows.map(([, r]) => r.value);\n\t}\n\n\tevictOneForCapacity(order: ReactiveIndexCapacityOrder, maxSize?: number): K | undefined {\n\t\tif (maxSize === undefined) return undefined;\n\t\tif (!Number.isInteger(maxSize) || maxSize < 1)\n\t\t\tthrow new RangeError(`reactiveIndex: maxSize must be a positive integer (got ${maxSize})`);\n\t\tconst overflow = this.buf.length - maxSize;\n\t\tif (overflow <= 0) return undefined;\n\n\t\tswitch (order) {\n\t\t\tcase \"secondary\": {\n\t\t\t\tconst row = this.buf[0] as IndexRow<K, V> | undefined;\n\t\t\t\tif (row === undefined) return undefined;\n\t\t\t\tthis.buf.shift();\n\t\t\t\tthis.byKey.delete(row.primary);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn row.primary;\n\t\t\t}\n\t\t\tcase \"primary\": {\n\t\t\t\tlet victim: K | undefined;\n\t\t\t\tfor (const key of this.byKey.keys()) {\n\t\t\t\t\tif (victim === undefined || cmpOrd(key, victim) < 0) victim = key;\n\t\t\t\t}\n\t\t\t\tif (victim === undefined) return undefined;\n\t\t\t\tconst row = this.byKey.get(victim);\n\t\t\t\tif (row !== undefined) this.removeRow(row);\n\t\t\t\tthis.byKey.delete(victim);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn victim;\n\t\t\t}\n\t\t\tcase \"lru\": {\n\t\t\t\tconst oldest = this.byKey.keys().next().value as K | undefined;\n\t\t\t\tif (oldest === undefined) return undefined;\n\t\t\t\tconst row = this.byKey.get(oldest);\n\t\t\t\tif (row !== undefined) this.removeRow(row);\n\t\t\t\tthis.byKey.delete(oldest);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn oldest;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new Error(`reactiveIndex: unknown capacity order '${String(order)}'`);\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): readonly IndexRow<K, V>[] {\n\t\treturn [...this.buf];\n\t}\n\ttoPrimaryMap(): ReadonlyMap<K, V> {\n\t\tconst m = new Map<K, V>();\n\t\tfor (const r of this.buf) m.set(r.primary, r.value);\n\t\treturn m;\n\t}\n}\n\nfunction assertCheckpointableIndexRows(rows: readonly IndexRow<unknown, unknown>[]): void {\n\tfor (const [i, row] of rows.entries()) {\n\t\tconst primary = row.primary;\n\t\tif (\n\t\t\tprimary === null ||\n\t\t\ttypeof primary === \"string\" ||\n\t\t\ttypeof primary === \"number\" ||\n\t\t\ttypeof primary === \"boolean\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(\n\t\t\t`reactiveIndex checkpoint backendState[${i}].primary must be a JSON primitive primary key for D160 restore`,\n\t\t);\n\t}\n}\n\n/**\n * Create a reactive dual-key index (D54/D60). DELTA + lazy pull SNAPSHOT + pullId via\n * {@link collectionCore}; this layer adds the sorted backend + Z reverse-lookup surface.\n */\nexport function reactiveIndex<K, V = unknown>(\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\treturn createReactiveIndex(options);\n}\n\n/** @internal D160 restore path: seed the backend without replaying public deltas. */\nexport function restoreReactiveIndexFromBackendState<K, V = unknown>(\n\tinitialRows: readonly IndexRow<K, V>[],\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\treturn createReactiveIndex(options, initialRows);\n}\n\nfunction createReactiveIndex<K, V = unknown>(\n\toptions: ReactiveIndexOptions = {},\n\tinitialRows: readonly IndexRow<K, V>[] = [],\n): ReactiveIndex<K, V> {\n\tconst { capacity, graph, dispatcher, name } = options;\n\tconst lruEnabled = capacity?.order === \"lru\";\n\tconst backend = new IndexBackend<K, V>(lruEnabled, initialRows);\n\tconst core: CollectionCore<readonly IndexRow<K, V>[], IndexChange<K, V>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveIndex\",\n\t\toptions,\n\t\tgraph !== undefined && name !== undefined && capacity === undefined\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveIndex.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveIndex.snapshot\",\n\t\t\t\t\tbackendState: () => {\n\t\t\t\t\t\tconst rows = backend.snapshot();\n\t\t\t\t\t\tassertCheckpointableIndexRows(rows);\n\t\t\t\t\t\treturn rows;\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tconst rangeMemo = new ViewMemoCache<\n\t\treadonly [K, K],\n\t\tReactiveView<IndexChange<K, V>, readonly V[]>\n\t>(options.viewCache, ([aStart, aEnd], [bStart, bEnd]) => {\n\t\treturn cmpOrd(aStart, bStart) === 0 && cmpOrd(aEnd, bEnd) === 0;\n\t});\n\tlet bindSeq = 0;\n\tlet rangeSeq = 0;\n\tlet capacityPolicy: Node<number> | undefined;\n\tlet apply: Node<IndexChange<K, V>> | undefined;\n\tlet releaseApply = () => {};\n\n\tfunction isNodeOpt<T>(x: ReactiveIndexOpt<T>): x is Node<T> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveIndex: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction enforceCapacity(): void {\n\t\tif (currentCapacityOrder === undefined) return;\n\t\tfor (;;) {\n\t\t\tconst primary = backend.evictOneForCapacity(currentCapacityOrder, currentMaxSize);\n\t\t\tif (primary === undefined) return;\n\t\t\tcore.emit({ kind: \"delete\", primary });\n\t\t}\n\t}\n\n\tconst applyBody = (ctx: Ctx): void => {\n\t\tconst deps = apply?.deps ?? [];\n\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep === capacityPolicy) {\n\t\t\t\tconst latest = depLatest(ctx, i);\n\t\t\t\tif (latest !== undefined) currentMaxSize = validateMaxSize(latest as number);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const r of (depBatch(ctx, i) ?? []) as readonly {\n\t\t\t\t\tprimary: K;\n\t\t\t\t\tsecondary: unknown;\n\t\t\t\t\tvalue: V;\n\t\t\t\t}[]) {\n\t\t\t\t\tbackend.upsert(r.primary, r.secondary, r.value);\n\t\t\t\t\tcore.emit({ kind: \"upsert\", primary: r.primary, secondary: r.secondary, value: r.value });\n\t\t\t\t\tenforceCapacity();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tenforceCapacity();\n\t};\n\n\tfunction ensureApply(): Node<IndexChange<K, V>> {\n\t\tif (apply !== undefined) return apply;\n\t\tconst op: Operator<unknown, IndexChange<K, V>> = {\n\t\t\tfactory: \"reactiveIndex.capacityPolicy\",\n\t\t\tbody: applyBody,\n\t\t\topts: { partial: true },\n\t\t};\n\t\tconst deps = capacityPolicy ? [capacityPolicy as Node<unknown>] : [];\n\t\tapply = graph\n\t\t\t? graph.initNode(op, deps, {\n\t\t\t\t\tname: name ? `${name}.capacityPolicy` : undefined,\n\t\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveIndex\" },\n\t\t\t\t})\n\t\t\t: new Node<IndexChange<K, V>>(deps, op.body, {\n\t\t\t\t\t...base,\n\t\t\t\t\tfactory: \"reactiveIndex.capacityPolicy\",\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tname: name ? `${name}.capacityPolicy` : undefined,\n\t\t\t\t});\n\t\treleaseApply = graph\n\t\t\t? graph.retain(apply, { reason: \"reactiveIndex.capacityPolicy\" })\n\t\t\t: apply.subscribe(() => {});\n\t\treturn apply;\n\t}\n\n\tlet currentMaxSize: number | undefined;\n\tconst currentCapacityOrder: ReactiveIndexCapacityOrder | undefined = capacity?.order;\n\tif (capacity !== undefined) {\n\t\tif (\n\t\t\tcurrentCapacityOrder !== \"secondary\" &&\n\t\t\tcurrentCapacityOrder !== \"primary\" &&\n\t\t\tcurrentCapacityOrder !== \"lru\"\n\t\t) {\n\t\t\tthrow new Error(\"reactiveIndex: capacity.order must be one of secondary|primary|lru (D73)\");\n\t\t}\n\n\t\tconst maxSize = capacity.maxSize;\n\t\tif (isNodeOpt(maxSize) && graph === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"reactiveIndex capacity.maxSize Node option requires options.graph so the policy edge is describe-visible (D73)\",\n\t\t\t);\n\t\t}\n\n\t\tcapacityPolicy = isNodeOpt(maxSize)\n\t\t\t? maxSize\n\t\t\t: graph\n\t\t\t\t? graph.initNode<number, number>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfactory: \"reactiveIndex.maxSizePolicy\",\n\t\t\t\t\t\t\tbody: () => {},\n\t\t\t\t\t\t\topts: { initial: validateMaxSize(maxSize) },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[],\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: name ? `${name}.maxSizePolicy` : undefined,\n\t\t\t\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveIndex\", policy: \"maxSize\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\n\t\tif (!isNodeOpt(maxSize)) currentMaxSize = validateMaxSize(maxSize);\n\n\t\tif (capacityPolicy instanceof Node) ensureApply();\n\t}\n\n\t// Lazy reactive reverse-lookup port (Z): a delta-driven pushed primary→value map. Created on\n\t// first access so an index that never uses it pays nothing (no keepalive — R-rom-ram).\n\tlet byPrimaryNode: Node<ReadonlyMap<K, V>> | undefined;\n\tfunction getByPrimary(): Node<ReadonlyMap<K, V>> {\n\t\tif (byPrimaryNode === undefined) {\n\t\t\tbyPrimaryNode = node<ReadonlyMap<K, V>>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\t// pushed reverse-lookup: re-read the backend's primary map on each delta (the\n\t\t\t\t\t// structure's own backend, D60 #1 — not a foreign .cache peek).\n\t\t\t\t\tctx.down([[\"DATA\", backend.toPrimaryMap()]]);\n\t\t\t\t},\n\t\t\t\t{ factory: \"reactiveIndex.byPrimary\", partial: true },\n\t\t\t);\n\t\t}\n\t\treturn byPrimaryNode;\n\t}\n\n\tfunction getRange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]> {\n\t\tconst key = [start, end] as const;\n\t\tconst hit = rangeMemo.get(key);\n\t\tif (hit !== undefined) return hit;\n\t\tconst materialize = (): readonly V[] => backend.rangeByPrimary(start, end);\n\t\tlet view: ReactiveView<IndexChange<K, V>, readonly V[]>;\n\t\tview = lightReactiveView<IndexChange<K, V>, readonly V[]>(core.delta as Node<unknown>, {\n\t\t\t...options,\n\t\t\tfactory: \"reactiveIndex.range\",\n\t\t\tname: name ? `${name}.range#${rangeSeq++}` : undefined,\n\t\t\tmaterializeSnapshot: materialize,\n\t\t\tonDispose: () => {\n\t\t\t\trangeMemo.deleteValue(view);\n\t\t\t},\n\t\t});\n\t\trangeMemo.set(key, view);\n\t\treturn view;\n\t}\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\thas(primary: K): boolean {\n\t\t\treturn backend.has(primary);\n\t\t},\n\t\tget(primary: K): V | undefined {\n\t\t\treturn backend.get(primary);\n\t\t},\n\t\trangeByPrimary(start: K, end: K): V[] {\n\t\t\treturn backend.rangeByPrimary(start, end);\n\t\t},\n\t\trange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]> {\n\t\t\treturn getRange(start, end);\n\t\t},\n\t\ttoArray(): readonly IndexRow<K, V>[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\t\ttoPrimaryMap(): ReadonlyMap<K, V> {\n\t\t\treturn backend.toPrimaryMap();\n\t\t},\n\t\tget byPrimary(): Node<ReadonlyMap<K, V>> {\n\t\t\treturn getByPrimary();\n\t\t},\n\n\t\tupsert(primary: K, secondary: unknown, value: V): boolean {\n\t\t\tconst inserted = backend.upsert(primary, secondary, value);\n\t\t\tcore.emit({ kind: \"upsert\", primary, secondary, value });\n\t\t\tenforceCapacity();\n\t\t\treturn inserted;\n\t\t},\n\t\tupsertMany(rows: Iterable<{ primary: K; secondary: unknown; value: V }>): void {\n\t\t\tfor (const r of rows) {\n\t\t\t\tbackend.upsert(r.primary, r.secondary, r.value);\n\t\t\t\tcore.emit({ kind: \"upsert\", primary: r.primary, secondary: r.secondary, value: r.value });\n\t\t\t\tenforceCapacity();\n\t\t\t}\n\t\t},\n\t\tdelete(primary: K): void {\n\t\t\tif (backend.delete(primary)) core.emit({ kind: \"delete\", primary });\n\t\t},\n\t\tdeleteMany(primaries: Iterable<K>): void {\n\t\t\tconst removed: K[] = [];\n\t\t\tfor (const p of primaries) if (backend.delete(p)) removed.push(p);\n\t\t\tif (removed.length > 0) core.emit({ kind: \"deleteMany\", primaries: removed });\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\n\t\tupsertFrom(src: Node<{ primary: K; secondary: unknown; value: V }>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveIndex.upsertFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<\n\t\t\t\t{ primary: K; secondary: unknown; value: V },\n\t\t\t\t{ primary: K; secondary: unknown; value: V }\n\t\t\t> = {\n\t\t\t\tfactory: \"reactiveIndex.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const r of (depBatch(ctx, 0) ?? []) as readonly {\n\t\t\t\t\t\t\tprimary: K;\n\t\t\t\t\t\t\tsecondary: unknown;\n\t\t\t\t\t\t\tvalue: V;\n\t\t\t\t\t\t}[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", r]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveIndex.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveIndex\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tconst applyNode = ensureApply();\n\t\t\tapplyNode.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapplyNode.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t\trangeMemo.disposeAll();\n\t\t},\n\t};\n}\n","/**\n * Internal graph-layer policy helpers (D70).\n *\n * This module is deliberately NOT exported from the package index. It centralizes policy plumbing\n * shared by collection structures while each structure still owns backend mutation + delta emission\n * in its apply/mutation path (D60/D61/D68/D69).\n */\n\nimport { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport type { Node } from \"../../node/node.js\";\n\nexport type PolicyOpt<T> = T | Node<T>;\n\nexport interface PolicyReader<T> {\n\treadonly index: number;\n\tread(ctx: Ctx, current: T | undefined): T | undefined;\n}\n\nexport class PolicyInputs {\n\treadonly deps: Node<unknown>[];\n\n\tconstructor(initial: readonly Node<unknown>[] = []) {\n\t\tthis.deps = [...initial];\n\t}\n\n\tadd<T>(node: Node<T> | undefined): PolicyReader<T> {\n\t\tif (node === undefined) return missingPolicyReader<T>();\n\t\tconst index = this.deps.push(node as Node<unknown>) - 1;\n\t\treturn policyReader<T>(index);\n\t}\n}\n\nfunction missingPolicyReader<T>(): PolicyReader<T> {\n\treturn {\n\t\tindex: -1,\n\t\tread: (_ctx, current) => current,\n\t};\n}\n\nfunction policyReader<T>(index: number): PolicyReader<T> {\n\treturn {\n\t\tindex,\n\t\tread(ctx, current) {\n\t\t\tconst latest = depLatest(ctx, index);\n\t\t\treturn latest === undefined ? current : (latest as T);\n\t\t},\n\t};\n}\n\nexport interface KeyOrderPolicy<K> {\n\tkeys(): Iterable<K>;\n}\n\nexport function lruKeys<K>(keys: Iterable<K>): KeyOrderPolicy<K> {\n\treturn {\n\t\tkeys: () => keys,\n\t};\n}\n\nexport interface CapacityConfig {\n\treadonly maxSize?: number;\n}\n\nexport interface SizedCapacityConfig extends CapacityConfig {\n\treadonly size: number;\n}\n\nexport function trimHeadOverflow<T>(items: T[], config: CapacityConfig): T[];\nexport function trimHeadOverflow<T>(items: Iterable<T>, config: SizedCapacityConfig): T[];\nexport function trimHeadOverflow<T>(\n\titems: T[] | Iterable<T>,\n\tconfig: CapacityConfig | SizedCapacityConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 1)\n\t\tthrow new RangeError(`maxSize must be a positive integer (got ${maxSize})`);\n\n\tconst size = \"size\" in config ? config.size : Array.isArray(items) ? items.length : undefined;\n\tif (size === undefined) throw new Error(\"trimHeadOverflow requires size for non-array iterables\");\n\tconst overflow = size - maxSize;\n\tif (overflow <= 0) return [];\n\n\tif (Array.isArray(items) && !(\"size\" in config)) return items.splice(0, overflow);\n\n\tconst victims: T[] = [];\n\tfor (const item of items) {\n\t\tvictims.push(item);\n\t\tif (victims.length === overflow) break;\n\t}\n\treturn victims;\n}\n\nexport interface DeadlineEntry<K> {\n\treadonly key: K;\n\treadonly expiresAt: number;\n}\n\nexport interface DeadlinePolicy<K> {\n\treadonly size: number;\n\tpush(item: DeadlineEntry<K>): void;\n\tpeek(): DeadlineEntry<K> | undefined;\n\tpop(): DeadlineEntry<K> | undefined;\n}\n\nexport function deadlines<K>(): DeadlinePolicy<K> {\n\treturn new MinDeadlineHeap<K>();\n}\n\nclass MinDeadlineHeap<K> implements DeadlinePolicy<K> {\n\tprivate readonly items: DeadlineEntry<K>[] = [];\n\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\n\tpush(item: DeadlineEntry<K>): void {\n\t\tthis.items.push(item);\n\t\tthis.up(this.items.length - 1);\n\t}\n\n\tpeek(): DeadlineEntry<K> | undefined {\n\t\treturn this.items[0];\n\t}\n\n\tpop(): DeadlineEntry<K> | undefined {\n\t\tconst top = this.items[0];\n\t\tconst last = this.items.pop();\n\t\tif (top !== undefined && last !== undefined && this.items.length > 0) {\n\t\t\tthis.items[0] = last;\n\t\t\tthis.down(0);\n\t\t}\n\t\treturn top;\n\t}\n\n\tprivate up(i: number): void {\n\t\twhile (i > 0) {\n\t\t\tconst p = (i - 1) >> 1;\n\t\t\tif (\n\t\t\t\t(this.items[p] as DeadlineEntry<K>).expiresAt <=\n\t\t\t\t(this.items[i] as DeadlineEntry<K>).expiresAt\n\t\t\t)\n\t\t\t\treturn;\n\t\t\t[this.items[p], this.items[i]] = [\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t\tthis.items[p] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = p;\n\t\t}\n\t}\n\n\tprivate down(i: number): void {\n\t\tfor (;;) {\n\t\t\tconst left = i * 2 + 1;\n\t\t\tconst right = left + 1;\n\t\t\tlet smallest = i;\n\t\t\tif (left < this.items.length && this.expiresAt(left) < this.expiresAt(smallest))\n\t\t\t\tsmallest = left;\n\t\t\tif (right < this.items.length && this.expiresAt(right) < this.expiresAt(smallest))\n\t\t\t\tsmallest = right;\n\t\t\tif (smallest === i) return;\n\t\t\t[this.items[i], this.items[smallest]] = [\n\t\t\t\tthis.items[smallest] as DeadlineEntry<K>,\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = smallest;\n\t\t}\n\t}\n\n\tprivate expiresAt(i: number): number {\n\t\treturn (this.items[i] as DeadlineEntry<K>).expiresAt;\n\t}\n}\n\nexport interface ScoredEntry<T> {\n\treadonly entry: T;\n\treadonly score: number;\n}\n\nexport interface RetentionSelectionConfig {\n\treadonly maxSize?: number;\n}\n\nexport function selectRetentionVictims<T>(\n\tscoredEntries: readonly ScoredEntry<T>[],\n\tconfig: RetentionSelectionConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 0)\n\t\tthrow new RangeError(`retention maxSize must be a non-negative integer (got ${maxSize})`);\n\tconst overflow = scoredEntries.length - maxSize;\n\tif (overflow <= 0) return [];\n\n\treturn scoredEntries\n\t\t.map((item, index) => {\n\t\t\tif (!Number.isFinite(item.score))\n\t\t\t\tthrow new RangeError(`retention score must be finite (got ${item.score})`);\n\t\t\treturn { ...item, index };\n\t\t})\n\t\t.sort((a, b) => a.score - b.score || a.index - b.index)\n\t\t.slice(0, overflow)\n\t\t.map((item) => item.entry);\n}\n","/**\n * Reactive positional list (CSP-2.8, D54/D60) — the two-port collection template.\n *\n * Shape (D60 + review #2): a mutable array BACKEND (the single materialized state) + the shared\n * {@link collectionCore} two ports — a DELTA stream ({@link ReactiveList.delta}, one event per\n * mutation, O(1)) and a lazy pull SNAPSHOT ({@link ReactiveList.snapshot}, materialized only on a\n * cone-routed PULL demand). Mutation input is D54 A3 hybrid: ergonomic imperative methods (the\n * external boundary, state-verb-legitimate, D4) + `appendFrom(src)` widening (an in-graph producer\n * drives the list with zero imperative glue). Synchronous quick-reads (`at`/`size`/`toArray`) are\n * the deliberately-non-reactive peek for cold/imperative reads (D60).\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount, depLatest } from \"../../ctx/types.js\";\nimport { Node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport type { Operator } from \"../operators.js\";\nimport { trimHeadOverflow } from \"../policies/collection.js\";\nimport type { ReactiveOpt } from \"../policies/types.js\";\nimport type { ListChange } from \"./change.js\";\nimport { type CollectionCore, type CollectionCoreOptions, collectionCore } from \"./core.js\";\n\nexport type ReactiveListOpt<T> = ReactiveOpt<T>;\n\nexport interface ReactiveListOptions extends CollectionCoreOptions {\n\t/**\n\t * Head-trim capacity policy (D72). A static number caps the list locally; a Node-valued maxSize\n\t * must be graph-bound and becomes a declared policy dep that trims on policy changes.\n\t */\n\tmaxSize?: ReactiveListOpt<number>;\n}\n\nexport interface ReactiveList<T> {\n\t/** DELTA stream: one {@link ListChange} per mutation (O(1)). Subscribe to observe events. */\n\treadonly delta: Node<ListChange<T>>;\n\t/** SNAPSHOT pull node: demand via `ctx.upNext([[\"PULL\", { pullId }]])` → one `readonly T[]` (lazy O(n)). */\n\treadonly snapshot: Node<readonly T[]>;\n\t/** The snapshot node's pullId — write it verbatim into the demander's fn (D269). */\n\treadonly pullId: symbol;\n\t/** Current entry count (O(1), synchronous non-reactive read). */\n\treadonly size: number;\n\t/** Positional access (O(1)); negative indices Python-style; `undefined` out of range. Sync read. */\n\tat(index: number): T | undefined;\n\t/** Full current contents (O(n), fresh defensive copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly T[];\n\tappend(value: T): void;\n\t/** Append all values; one delta event + one snapshot-arm. No-op if `values` is empty. */\n\tappendMany(values: readonly T[]): void;\n\t/** Insert at `index` (0..size). Throws `RangeError` out of range. */\n\tinsert(index: number, value: T): void;\n\t/** Insert all at `index` as one op. No-op if `values` is empty. Throws out of range. */\n\tinsertMany(index: number, values: readonly T[]): void;\n\t/** Remove and return the value at `index` (default last; negative Python-style). Throws if empty/out of range. */\n\tpop(index?: number): T;\n\tclear(): void;\n\t/** D54 widening: every value from `src` is appended. Returns a disposer. */\n\tappendFrom(src: Node<T>): () => void;\n\t/** Release the widening subscriptions (idempotent). */\n\tdispose(): void;\n}\n\n/** Default mutable-array backend (D60 first-cut; pluggable persistent/immutable backend deferred). */\nclass ListBackend<T> {\n\tprivate _version = 0;\n\tprivate readonly buf: T[];\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tthis.buf = initial ? [...initial] : [];\n\t\ttrimHeadOverflow(this.buf, { maxSize });\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\treturn i < 0 || i >= this.buf.length ? undefined : this.buf[i];\n\t}\n\n\tsnapshot(): readonly T[] {\n\t\treturn [...this.buf];\n\t}\n\n\tappend(value: T): void {\n\t\tthis.buf.push(value);\n\t\tthis._version += 1;\n\t}\n\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\tfor (const v of values) this.buf.push(v);\n\t\tthis._version += 1;\n\t}\n\n\tinsert(index: number, value: T): void {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.buf.length)\n\t\t\tthrow new RangeError(`insert: index ${index} out of range [0, ${this.buf.length}]`);\n\t\tthis.buf.splice(index, 0, value);\n\t\tthis._version += 1;\n\t}\n\n\tinsertMany(index: number, values: readonly T[]): void {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.buf.length)\n\t\t\tthrow new RangeError(`insertMany: index ${index} out of range [0, ${this.buf.length}]`);\n\t\tif (values.length === 0) return;\n\t\tthis.buf.splice(index, 0, ...values);\n\t\tthis._version += 1;\n\t}\n\n\tpop(index: number): T {\n\t\tif (this.buf.length === 0) throw new RangeError(\"pop from empty list\");\n\t\tif (!Number.isInteger(index)) throw new RangeError(`pop: index ${index} must be an integer`);\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\tif (i < 0 || i >= this.buf.length) throw new RangeError(`pop: index ${index} out of range`);\n\t\tconst [v] = this.buf.splice(i, 1);\n\t\tthis._version += 1;\n\t\treturn v as T;\n\t}\n\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\tenforceMaxSize(maxSize?: number): number {\n\t\tconst removed = trimHeadOverflow(this.buf, { maxSize }).length;\n\t\tif (removed > 0) this._version += 1;\n\t\treturn removed;\n\t}\n}\n\n/**\n * Create a reactive list (D54/D60). The DELTA + SNAPSHOT ports + pullId come from the shared\n * {@link collectionCore}; this layer adds the typed list method surface + backend.\n *\n * @example\n * ```ts\n * const list = reactiveList<number>([1]);\n * // observe events:\n * list.delta.subscribe((m) => { if (m[0] === \"DATA\") console.log(\"Δ\", m[1]); });\n * list.append(2); // delta: {kind:\"append\", value:2}\n * // demand the snapshot (a downstream consumer, holding `list.snapshot` upstream, runs):\n * // ctx.upNext([[\"PULL\", { pullId: list.pullId }]]); → SNAPSHOT delivers [1, 2]\n * list.toArray(); // [1, 2] (synchronous non-reactive read)\n * ```\n */\nexport function reactiveList<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveListOptions = {},\n): ReactiveList<T> {\n\tconst { maxSize, graph, dispatcher } = options;\n\tconst base = dispatcher ? { dispatcher } : {};\n\n\tfunction isNodeOpt(x: ReactiveListOpt<number> | undefined): x is Node<number> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveList: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tconst initialMaxSize = isNodeOpt(maxSize) ? undefined : maxSize;\n\tconst backend = new ListBackend<T>(\n\t\tinitial,\n\t\tinitialMaxSize === undefined ? undefined : validateMaxSize(initialMaxSize),\n\t);\n\tconst restorable = graph !== undefined && options.name !== undefined && maxSize === undefined;\n\tconst core: CollectionCore<readonly T[], ListChange<T>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveList\",\n\t\toptions,\n\t\trestorable\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveList.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveList.snapshot\",\n\t\t\t\t\tbackendState: () => backend.snapshot(),\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tlet bindSeq = 0;\n\tlet capacityPolicy: Node<number> | undefined;\n\tlet apply: Node<ListChange<T>> | undefined;\n\tlet releaseApply = () => {};\n\tlet currentMaxSize = initialMaxSize;\n\n\tfunction emitTrimmed(n: number): void {\n\t\tif (n > 0) core.emit({ kind: \"trimHead\", n });\n\t}\n\n\tfunction enforceCapacity(): void {\n\t\temitTrimmed(backend.enforceMaxSize(currentMaxSize));\n\t}\n\n\tconst applyBody = (ctx: Ctx): void => {\n\t\tconst deps = apply?.deps ?? [];\n\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep === capacityPolicy) {\n\t\t\t\tconst latest = depLatest(ctx, i);\n\t\t\t\tif (latest !== undefined) currentMaxSize = validateMaxSize(latest as number);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const value of (depBatch(ctx, i) ?? []) as readonly T[]) {\n\t\t\t\t\tbackend.append(value);\n\t\t\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\t\t\tenforceCapacity();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tenforceCapacity();\n\t};\n\n\tfunction ensureApply(): Node<ListChange<T>> {\n\t\tif (apply !== undefined) return apply;\n\t\tconst op: Operator<unknown, ListChange<T>> = {\n\t\t\tfactory: \"reactiveList.capacityPolicy\",\n\t\t\tbody: applyBody,\n\t\t\topts: { partial: true },\n\t\t};\n\t\tconst deps = capacityPolicy ? [capacityPolicy as Node<unknown>] : [];\n\t\tapply = graph\n\t\t\t? graph.initNode(op, deps, {\n\t\t\t\t\tname: options.name ? `${options.name}.capacityPolicy` : undefined,\n\t\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveList\" },\n\t\t\t\t})\n\t\t\t: new Node<ListChange<T>>(deps, op.body, {\n\t\t\t\t\t...base,\n\t\t\t\t\tfactory: \"reactiveList.capacityPolicy\",\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tname: options.name ? `${options.name}.capacityPolicy` : undefined,\n\t\t\t\t});\n\t\treleaseApply = graph\n\t\t\t? graph.retain(apply, { reason: \"reactiveList.capacityPolicy\" })\n\t\t\t: apply.subscribe(() => {});\n\t\treturn apply;\n\t}\n\n\tfunction constPolicyNode(value: number): Node<number> {\n\t\tconst op: Operator<never, number> = {\n\t\t\tfactory: \"reactiveList.maxSizePolicy\",\n\t\t\tbody: () => {},\n\t\t\topts: { initial: value },\n\t\t};\n\t\tif (graph) {\n\t\t\treturn graph.initNode(op, [], {\n\t\t\t\tname: options.name ? `${options.name}.maxSizePolicy` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveList\", policy: \"maxSize\" },\n\t\t\t});\n\t\t}\n\t\treturn new Node<number>([], null, {\n\t\t\t...base,\n\t\t\tinitial: value,\n\t\t\tfactory: \"reactiveList.maxSizePolicy\",\n\t\t\tname: options.name ? `${options.name}.maxSizePolicy` : undefined,\n\t\t});\n\t}\n\n\tif (maxSize !== undefined) {\n\t\tif (isNodeOpt(maxSize) && graph === undefined)\n\t\t\tthrow new Error(\n\t\t\t\t\"reactiveList maxSize Node option requires options.graph so the policy edge is describe-visible (D72)\",\n\t\t\t);\n\t\tcapacityPolicy = isNodeOpt(maxSize)\n\t\t\t? maxSize\n\t\t\t: graph\n\t\t\t\t? constPolicyNode(validateMaxSize(maxSize))\n\t\t\t\t: undefined;\n\t\tif (capacityPolicy !== undefined) ensureApply();\n\t}\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\t\ttoArray(): readonly T[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\tbackend.append(value);\n\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tconst copy = [...values];\n\t\t\tbackend.appendMany(copy);\n\t\t\tcore.emit({ kind: \"appendMany\", values: copy });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tinsert(index: number, value: T): void {\n\t\t\tbackend.insert(index, value);\n\t\t\tcore.emit({ kind: \"insert\", index, value });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tinsertMany(index: number, values: readonly T[]): void {\n\t\t\tif (values.length === 0) {\n\t\t\t\t// still validate the index (mirror backend) so an out-of-range empty insert throws\n\t\t\t\tbackend.insertMany(index, values);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst copy = [...values];\n\t\t\tbackend.insertMany(index, copy);\n\t\t\tcore.emit({ kind: \"insertMany\", index, values: copy });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tpop(index = -1): T {\n\t\t\tconst resolved = index < 0 ? backend.size + index : index;\n\t\t\tconst value = backend.pop(index);\n\t\t\tcore.emit({ kind: \"pop\", index: resolved, value });\n\t\t\treturn value;\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\n\t\tappendFrom(src: Node<T>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveList.appendFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<T, T> = {\n\t\t\t\tfactory: \"reactiveList.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const value of (depBatch(ctx, 0) ?? []) as readonly T[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", value]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveList.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: options.name ? `${options.name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveList\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tconst applyNode = ensureApply();\n\t\t\tapplyNode.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapplyNode.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t},\n\t};\n}\n","/**\n * Reactive append-only log (CSP-2.8, D54/D60) — two-port collection with incremental views.\n *\n * Shape = the shared {@link collectionCore} two ports over an array (or ring-buffer if `maxSize`)\n * BACKEND (D60). Specializations (D60 #5 / review #5):\n * - SNAPSHOT (the full `readonly T[]`) is the lazy pull port like the others, BUT the log's main\n * consumption is INCREMENTAL: `tail()` / `slice()` / `scan()` re-derive on the DELTA backbone\n * (dep=[delta]), folding each appended value as it arrives — NOT re-scanning a pushed full array.\n * - `append(undefined)` throws: `undefined` is the substrate SENTINEL (R-data-payload / R-sentinel),\n * not a valid value.\n * - empty log: the snapshot is `[]` (a real empty array); a never-appended `scan` seeds its initial.\n * There is NO `[[RESOLVED]]`-for-empty dual role (D49 narrowed RESOLVED to undirty-only, D60 #5b).\n * - `attach(upstream)` = the D54 widening (a declared input-fold dep), NOT an imperative subscribe.\n * - {@link mergeReactiveLogs} is a DECLARED-DEP merge (deps=[...delta streams]), NOT the old\n * internal-subscribe island (D45 must-fix, D60 #5e).\n * - storage persistence = D57 (binding-layer observe-sink), out of scope here.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount } from \"../../ctx/types.js\";\nimport { type Node, node } from \"../../node/node.js\";\nimport type { GraphCheckpointJson } from \"../checkpoint.js\";\nimport { trimHeadOverflow } from \"../policies/collection.js\";\nimport type { ViewCachePolicy } from \"../policies/types.js\";\nimport type { LogChange } from \"./change.js\";\nimport {\n\ttype CollectionCore,\n\ttype CollectionCoreOptions,\n\tcollectionCore,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport interface ReactiveLogOptions extends CollectionCoreOptions {\n\t/** Ring-buffer cap: appends past `maxSize` evict the oldest (head-trim, append-only-safe). */\n\tmaxSize?: number;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\tviewCache?: ViewCachePolicy;\n}\n\nexport interface ReactiveLog<T> {\n\treadonly delta: Node<LogChange<T>>;\n\t/** SNAPSHOT pull node: demand → full `readonly T[]` (lazy O(n)). For incremental use {@link tail}, {@link slice}, or {@link scan}. */\n\treadonly snapshot: Node<readonly T[]>;\n\treadonly pullId: symbol;\n\t/** Entry count (O(1)). Sync non-reactive read. */\n\treadonly size: number;\n\t/** Positional access (O(1)); negative Python-style; `undefined` out of range. Sync read. */\n\tat(index: number): T | undefined;\n\t/** Full contents (O(n) fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly T[];\n\t/** Append one value. Throws on `undefined` (substrate SENTINEL, R-data-payload). */\n\tappend(value: T): void;\n\t/** Append many; one delta event. No-op if empty. Throws if any value is `undefined`. */\n\tappendMany(values: readonly T[]): void;\n\tclear(): void;\n\t/** Remove the first `n` entries (clamped to size). */\n\ttrimHead(n: number): void;\n\t/**\n\t * Incremental tail view: a derived node emitting the last `n` entries, recomputed on each delta\n\t * (dep=[delta], D60 #5a). Memoized per `n` until {@link dispose}; use stable ranges for\n\t * long-lived logs. Subscribe to keep it live.\n\t */\n\ttail(n: number): Node<readonly T[]>;\n\t/**\n\t * Incremental positional view: a derived node emitting `toArray().slice(start, stop)`,\n\t * recomputed on each delta (dep=[delta], D60 #5a). Memoized per `[start, stop]` until\n\t * {@link dispose}; use stable ranges for long-lived logs.\n\t */\n\tslice(start: number, stop?: number): Node<readonly T[]>;\n\t/**\n\t * D121 light page view: `delta` forwards parent log mutations, and `snapshot` is a pull node\n\t * that materializes the current page on demand.\n\t */\n\tpage(offset: number, limit: number): ReactiveView<LogChange<T>, readonly T[]>;\n\t/**\n\t * Incremental running aggregate over appended values (dep=[delta], D60 #5a). O(1) per append —\n\t * folds only the new values each delta; resets on `clear`/`trimHead` (a non-append delta) via a\n\t * full re-fold. Emits the current accumulator on every mutation; seeds `initial` on an empty log.\n\t */\n\tscan<A>(initial: A, step: (acc: A, value: T) => A): Node<A>;\n\t/** D54 widening: every value from `src` is appended. Returns a disposer. */\n\tattach(src: Node<T>): () => void;\n\tdispose(): void;\n}\n\n/** Default array / ring-buffer backend (D60 first-cut; persistent backend deferred). */\nclass LogBackend<T> {\n\tprivate _version = 0;\n\tprivate buf: T[];\n\tprivate readonly maxSize?: number;\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tif (maxSize !== undefined && maxSize < 1)\n\t\t\tthrow new RangeError(\"reactiveLog: maxSize must be >= 1\");\n\t\tthis.maxSize = maxSize;\n\t\tthis.buf = initial ? [...initial] : [];\n\t\ttrimHeadOverflow(this.buf, { maxSize });\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\treturn i < 0 || i >= this.buf.length ? undefined : this.buf[i];\n\t}\n\tsnapshot(): readonly T[] {\n\t\treturn [...this.buf];\n\t}\n\n\tappend(value: T): void {\n\t\tthis.buf.push(value);\n\t\ttrimHeadOverflow(this.buf, { maxSize: this.maxSize });\n\t\tthis._version += 1;\n\t}\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\tfor (const v of values) this.buf.push(v);\n\t\ttrimHeadOverflow(this.buf, { maxSize: this.maxSize });\n\t\tthis._version += 1;\n\t}\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\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\tif (n === 0 || this.buf.length === 0) return 0;\n\t\tconst removed = Math.min(n, this.buf.length);\n\t\tthis.buf.splice(0, removed);\n\t\tthis._version += 1;\n\t\treturn removed;\n\t}\n}\n\nfunction rejectUndefined<T>(value: T, ctx: string): void {\n\t// R-data-payload / R-sentinel (D60 #5): undefined is the substrate SENTINEL, not a valid value.\n\tif (value === undefined)\n\t\tthrow new TypeError(\n\t\t\t`${ctx}: undefined is the substrate SENTINEL, not a valid value — use null`,\n\t\t);\n}\n\n/**\n * Create an append-only reactive log (D54/D60). DELTA + lazy pull SNAPSHOT + pullId via\n * {@link collectionCore}; this layer adds the typed append surface + incremental view/scan.\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLog<T> {\n\tconst { maxSize, viewCache, ...coreOpts } = options;\n\tconst base = coreOpts.dispatcher ? { dispatcher: coreOpts.dispatcher } : {};\n\tconst backend = new LogBackend<T>(initial, maxSize);\n\tconst restoreConfig =\n\t\tcoreOpts.graph !== undefined && coreOpts.name !== undefined\n\t\t\t? ({\n\t\t\t\t\t...(maxSize !== undefined ? { maxSize } : {}),\n\t\t\t\t} as GraphCheckpointJson)\n\t\t\t: undefined;\n\tconst core: CollectionCore<readonly T[], LogChange<T>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveLog\",\n\t\tcoreOpts,\n\t\trestoreConfig !== undefined\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveLog.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveLog.snapshot\",\n\t\t\t\t\tconfig: restoreConfig,\n\t\t\t\t\tbackendState: () => backend.snapshot(),\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst tailMemo = new Map<number, Node<readonly T[]>>();\n\tconst sliceMemo = new Map<string, Node<readonly T[]>>();\n\tconst pageMemo = new ViewMemoCache<string, ReactiveView<LogChange<T>, readonly T[]>>(viewCache);\n\tlet pageSeq = 0;\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\t\ttoArray(): readonly T[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\trejectUndefined(value, \"reactiveLog.append\");\n\t\t\tbackend.append(value);\n\t\t\tcore.emit({ kind: \"append\", value });\n\t\t},\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tfor (const v of values) rejectUndefined(v, \"reactiveLog.appendMany\");\n\t\t\tconst copy = [...values];\n\t\t\tbackend.appendMany(copy);\n\t\t\tcore.emit({ kind: \"appendMany\", values: copy });\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\t\ttrimHead(n: number): void {\n\t\t\tconst removed = backend.trimHead(n);\n\t\t\tif (removed > 0) core.emit({ kind: \"trimHead\", n: removed });\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\tconst hit = tailMemo.get(n);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\t// Incremental on the DELTA backbone (D60 #5a): each delta re-reads the backend's current\n\t\t\t// tail (the backend is this structure's own materialized state, D60 #1 — not a foreign\n\t\t\t// .cache peek). `partial:true` — the tail does not consume the delta value, it fires on arm.\n\t\t\tconst tnode = node<readonly T[]>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tconst all = backend.snapshot();\n\t\t\t\t\tctx.down([[\"DATA\", n === 0 ? [] : all.slice(Math.max(0, all.length - n))]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.tail\", partial: true },\n\t\t\t);\n\t\t\ttailMemo.set(n, tnode);\n\t\t\treturn tnode;\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\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\t\tthrow new RangeError(`slice: stop must be a non-negative integer (got ${stop})`);\n\t\t\t}\n\t\t\tconst key = `${start}:${stop ?? \"\"}`;\n\t\t\tconst hit = sliceMemo.get(key);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\t// Incremental on the DELTA backbone (D60 #5a): each delta re-reads this log's own\n\t\t\t// backend slice. The backend is the single materialized state (D60), not a dep cache.\n\t\t\tconst snode = node<readonly T[]>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tctx.down([[\"DATA\", backend.snapshot().slice(start, stop)]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.slice\", partial: true },\n\t\t\t);\n\t\t\tsliceMemo.set(key, snode);\n\t\t\treturn snode;\n\t\t},\n\n\t\tpage(offset: number, limit: number): ReactiveView<LogChange<T>, readonly T[]> {\n\t\t\tif (!Number.isInteger(offset) || offset < 0) {\n\t\t\t\tthrow new RangeError(`page: offset must be a non-negative integer (got ${offset})`);\n\t\t\t}\n\t\t\tif (!Number.isInteger(limit) || limit < 0) {\n\t\t\t\tthrow new RangeError(`page: limit must be a non-negative integer (got ${limit})`);\n\t\t\t}\n\t\t\tconst key = `${offset}:${limit}`;\n\t\t\tconst hit = pageMemo.get(key);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\tconst materialize = (): readonly T[] => backend.snapshot().slice(offset, offset + limit);\n\t\t\tlet view: ReactiveView<LogChange<T>, readonly T[]>;\n\t\t\tview = lightReactiveView<LogChange<T>, readonly T[]>(core.delta as Node<unknown>, {\n\t\t\t\t...coreOpts,\n\t\t\t\tfactory: \"reactiveLog.page\",\n\t\t\t\tname: coreOpts.name ? `${coreOpts.name}.page#${pageSeq++}` : undefined,\n\t\t\t\tmaterializeSnapshot: materialize,\n\t\t\t\tonDispose: () => {\n\t\t\t\t\tpageMemo.deleteValue(view);\n\t\t\t\t},\n\t\t\t});\n\t\t\tpageMemo.set(key, view);\n\t\t\treturn view;\n\t\t},\n\n\t\tscan<A>(initial: A, step: (acc: A, value: T) => A): Node<A> {\n\t\t\t// Incremental fold on the delta backbone: keep the accumulator + processed-count in\n\t\t\t// ctx.state; fold only the new tail each append; full re-fold on a shrink (clear/trimHead).\n\t\t\treturn node<A>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tconst st = ctx.state.get<{ acc: A; processed: number }>() ?? {\n\t\t\t\t\t\tacc: initial,\n\t\t\t\t\t\tprocessed: 0,\n\t\t\t\t\t};\n\t\t\t\t\tconst all = backend.snapshot();\n\t\t\t\t\tif (all.length < st.processed || (maxSize !== undefined && all.length <= st.processed)) {\n\t\t\t\t\t\t// Shrink or ring-buffer overwrite: re-fold from the current backend snapshot.\n\t\t\t\t\t\tlet acc = initial;\n\t\t\t\t\t\tfor (const v of all) acc = step(acc, v);\n\t\t\t\t\t\tst.acc = acc;\n\t\t\t\t\t\tst.processed = all.length;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = st.processed; i < all.length; i++) st.acc = step(st.acc, all[i] as T);\n\t\t\t\t\t\tst.processed = all.length;\n\t\t\t\t\t}\n\t\t\t\t\tctx.state.set(st);\n\t\t\t\t\tctx.down([[\"DATA\", st.acc]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.scan\", partial: true },\n\t\t\t);\n\t\t},\n\n\t\tattach(src: Node<T>): () => void {\n\t\t\tconst dispose = core.bindSource(src, (value: T) => {\n\t\t\t\trejectUndefined(value, \"reactiveLog.attach\");\n\t\t\t\tbackend.append(value);\n\t\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\t});\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\ttailMemo.clear();\n\t\t\tsliceMemo.clear();\n\t\t\tpageMemo.disposeAll();\n\t\t},\n\t};\n}\n\n/**\n * Fan-in N reactive logs into one merged DELTA stream (D60 #5e — a DECLARED-DEP merge, NOT the old\n * internal-subscribe island). The returned node declares each log's `delta` as a dep (`partial`)\n * and re-emits every change it sees — describe shows `log[i].delta → merged` truthfully (D45).\n * For the merged SNAPSHOT, fold the merged delta with {@link ReactiveLog.scan}-style logic, or\n * demand each source's snapshot independently.\n */\nexport function mergeReactiveLogs<T>(logs: readonly ReactiveLog<T>[]): Node<LogChange<T>> {\n\tconst deps = logs.map((l) => l.delta as Node<unknown>);\n\treturn node<LogChange<T>>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b) for (const c of b) ctx.down([[\"DATA\", c as LogChange<T>]]);\n\t\t\t}\n\t\t},\n\t\t{ factory: \"mergeReactiveLogs\", partial: true },\n\t);\n}\n\n/**\n * Standalone incremental scan over a reactive log. Equivalent to `log.scan(initial, step)`;\n * provided for pipe-builder and helper-composition call sites.\n */\nexport function scanLog<T, A>(\n\tlog: ReactiveLog<T>,\n\tinitial: A,\n\tstep: (acc: A, value: T) => A,\n): Node<A> {\n\treturn log.scan(initial, step);\n}\n","/**\n * Async + sync sources (binding-layer sugar, D43 / D40 / feedback_async_sources_binding_layer).\n *\n * Sources are depless {@link Operator}`<never, T>` specs built on the `producer`/`node` path:\n * the body runs ONCE on activation (node `_activate`), schedules its work, and emits later via\n * the captured `ctx.down` (an external tier-3 emit → the leading DIRTY is synthesized for it,\n * R-dirty-before-data). Async lives ONLY here (R-no-raw-async / F-SYNC-CORE): `setTimeout` /\n * `Promise` / `for await` are confined to source bodies; the wave core stays sync. Cleanup is\n * `ctx.onDeactivation` (D28), NOT a returned object. Per-language (D6/D24), never in parity.\n *\n * Instantiate via `g.initNode(timer(1000), [])` (graph-bound, inspectable) or\n * {@link initNode}(timer(1000), []) (bare). Pool/pause defaults (D43): timer/interval =\n * sync + pausable:false (keep producing through PAUSE); fromPromise/fromAsyncIter = async\n * (default pausable, so a paused source buffers its late emits — R-async-paused).\n */\n\nimport type { Ctx } from \"../ctx/types.js\";\nimport type { Node, NodeOptions } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { toCheckpointJson } from \"./checkpoint.js\";\nimport type {\n\tDriverCancel,\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"./environment.js\";\nimport { initNode, type Operator } from \"./operators.js\";\n\n/**\n * Values accepted by {@link fromAny}: an existing Node, a Promise, an (a)sync iterable, or a\n * bare scalar. The universal coercion target for higher-order operators (CSP-2.7).\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Host-boundary options for {@link singleFromAny}. */\nexport interface SingleFromAnyOptions<K> {\n\t/**\n\t * Map a caller key to the in-flight dedupe key. Defaults to key identity; object keys dedupe only\n\t * when the same object reference is reused. Return a stable string/canonical value for structural\n\t * object-key dedupe.\n\t */\n\tkeyOf?: (key: K) => unknown;\n\t/** Treat a sync iterable result as a stream and take its first item. Defaults to scalar value. */\n\titer?: boolean;\n}\n\n/**\n * Internal: build a depless source spec. `setup` runs once on activation; its returned fn (if\n * any) is registered as the deactivation cleanup (clear timers / abort). `setup` schedules the\n * async work and emits via `ctx.down` — synchronously (sync sources) or later (async sources).\n */\nfunction source<T>(\n\tfactory: string,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: setup returns a cleanup fn OR nothing — the void arm keeps no-return source bodies (e.g. `of`/`fromIter`) ergonomic, same idiom as EffectFn.\n\tsetup: (ctx: Ctx) => void | (() => void),\n\topts?: Partial<NodeOptions<T>>,\n): Operator<never, T> {\n\treturn {\n\t\tfactory,\n\t\topts,\n\t\tbody: (ctx) => {\n\t\t\tlet cleanup: undefined | (() => void);\n\t\t\tlet deactivated = false;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tdeactivated = true;\n\t\t\t\tif (typeof cleanup === \"function\") cleanup();\n\t\t\t});\n\t\t\tconst maybeCleanup = setup(ctx);\n\t\t\tcleanup = typeof maybeCleanup === \"function\" ? maybeCleanup : undefined;\n\t\t\tif (deactivated && typeof cleanup === \"function\") cleanup();\n\t\t},\n\t};\n}\n\nfunction assertNonEmptyString(value: string, label: string): void {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new TypeError(`${label} must be a non-empty string`);\n\t}\n}\n\nfunction cleanupDriverWork(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n): void {\n\tactive.value = false;\n\tconst cancel = cancelSlot.value;\n\tcancelSlot.value = undefined;\n\tif (cancel !== undefined) runDriverCancel(cancel);\n}\n\nfunction installDriverCancel(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n\tcancel: DriverCancel,\n): void {\n\tif (active.value) cancelSlot.value = cancel;\n\telse runDriverCancel(cancel);\n}\n\nfunction runDriverCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cleanup is best-effort: it must not suppress graph-visible terminal delivery.\n\t}\n}\n\nfunction driverOneShotSource<T>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (result: DriverResult<T>) => void) => DriverCancel | undefined,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (result: DriverResult<T>) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\tif (result.ok) ctx.down([[\"DATA\", result.value], [\"COMPLETE\"]]);\n\t\t\t\telse ctx.down([[\"ERROR\", errorPayload(result.error)]]);\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction driverStreamSource<T, E extends { readonly kind: string }>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (event: E) => void) => DriverCancel | undefined,\n\tdataOf: (event: E) => T | undefined,\n\terrorOf: (event: E) => unknown,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (event: E) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\tconst value = dataOf(event);\n\t\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(errorOf(event))]]);\n\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\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\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isAsyncIterable<T>(x: unknown): x is AsyncIterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nfunction isIterable<T>(x: unknown): x is Iterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\t);\n}\n\n/** Options shared by async/timer sources: an optional AbortSignal → ERROR on abort. */\nexport interface AsyncSourceOpts {\n\tsignal?: AbortSignal;\n}\n\nexport interface TimerSourceOpts extends AsyncSourceOpts {\n\tperiod?: number;\n}\n\n/** Options for {@link fromCron}. */\nexport interface FromCronOptions extends AsyncSourceOpts {\n\t/** Cron matcher polling interval in milliseconds. Default: 60_000. */\n\ttickMs?: number;\n\t/**\n\t * Emitted value shape. `timestamp_ns` is a decimal string so it cannot lose precision as a\n\t * JavaScript number; use `timestamp_ms` when numeric millisecond precision is enough.\n\t */\n\toutput?: \"date\" | \"timestamp_ms\" | \"timestamp_ns\";\n}\n\n/** Minimal five-field cron schedule: minute hour day-of-month month day-of-week. */\nexport interface CronSchedule {\n\treadonly minutes: ReadonlySet<number>;\n\treadonly hours: ReadonlySet<number>;\n\treadonly daysOfMonth: ReadonlySet<number>;\n\treadonly months: ReadonlySet<number>;\n\treadonly daysOfWeek: ReadonlySet<number>;\n}\n\n/** DOM/EventEmitter-style target accepted by {@link fromEvent}. */\nexport interface EventTargetLike {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n}\n\nexport interface EventListenerOptionsLike {\n\tcapture?: boolean;\n\tpassive?: boolean;\n\tonce?: boolean;\n}\n\nexport type FromEventOptions = EventListenerOptionsLike;\n\n/** Host push registration callback accepted by {@link fromPushNotification}. */\nexport type PushUnsubscribe = () => void;\nexport type PushRegister<T> = (deliver: (payload: T) => void) => PushUnsubscribe | undefined;\n\nfunction parseCronField(field: string, min: number, max: number): Set<number> {\n\tif (field.length === 0) throw new Error(\"Invalid cron field: empty\");\n\tconst out = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tif (part.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tconst stepParts = part.split(\"/\");\n\t\tif (stepParts.length > 2) throw new Error(`Invalid cron step: ${part}`);\n\t\tconst [range, stepText] = stepParts;\n\t\tif (range == null || range.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (stepText === \"\") throw new Error(`Invalid cron step: ${part}`);\n\t\tconst step = stepText == null ? 1 : parseCronInt(stepText, `Invalid cron step: ${part}`);\n\t\tif (step < 1) throw new Error(`Invalid cron step: ${part}`);\n\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b, extra] = range.split(\"-\");\n\t\t\tif (extra !== undefined || a === \"\" || b === \"\")\n\t\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t\tstart = parseCronInt(a, `Invalid cron field: ${field}`);\n\t\t\tend = parseCronInt(b, `Invalid cron field: ${field}`);\n\t\t} else {\n\t\t\tstart = parseCronInt(range, `Invalid cron field: ${field}`);\n\t\t\tend = start;\n\t\t}\n\n\t\tif (!Number.isInteger(start) || !Number.isInteger(end)) {\n\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t}\n\t\tif (start < min || end > max) {\n\t\t\tthrow new RangeError(`Cron field out of range: ${field} (${min}-${max})`);\n\t\t}\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) out.add(i);\n\t}\n\treturn out;\n}\n\nfunction parseCronInt(text: string, message: string): number {\n\tif (!/^\\d+$/.test(text)) throw new Error(message);\n\tconst value = Number.parseInt(text, 10);\n\tif (!Number.isSafeInteger(value)) throw new Error(message);\n\treturn value;\n}\n\n/** Parse a standard five-field cron expression. */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5 || parts.some((part) => part.length === 0)) {\n\t\tthrow new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\t}\n\treturn {\n\t\tminutes: parseCronField(parts[0], 0, 59),\n\t\thours: parseCronField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseCronField(parts[2], 1, 31),\n\t\tmonths: parseCronField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseCronField(parts[4], 0, 6),\n\t};\n}\n\n/** Test whether a local Date matches a parsed cron schedule. */\nexport function matchesCron(schedule: CronSchedule, date: Date): boolean {\n\treturn (\n\t\tschedule.minutes.has(date.getMinutes()) &&\n\t\tschedule.hours.has(date.getHours()) &&\n\t\tschedule.daysOfMonth.has(date.getDate()) &&\n\t\tschedule.months.has(date.getMonth() + 1) &&\n\t\tschedule.daysOfWeek.has(date.getDay())\n\t);\n}\n\nfunction cronMinuteKey(date: Date): string {\n\treturn `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}`;\n}\n\nfunction dateToTimestampNs(date: Date): string {\n\treturn (BigInt(date.getTime()) * 1_000_000n).toString();\n}\n\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"date\" },\n): Operator<never, Date>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"timestamp_ms\" },\n): Operator<never, number>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions & { output?: \"timestamp_ns\" },\n): Operator<never, string>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions,\n): Operator<never, Date | number | string>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions = {},\n): Operator<never, Date | number | string> {\n\tconst schedule = parseCron(expr);\n\tconst { tickMs = 60_000, output = \"timestamp_ns\", signal } = opts;\n\tif (!Number.isFinite(tickMs) || tickMs <= 0) {\n\t\tthrow new RangeError(\"fromCron: tickMs must be a positive finite number\");\n\t}\n\treturn source<Date | number | string>(\n\t\t\"fromCron\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet lastFiredKey: string | undefined;\n\t\t\tlet intervalId: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (intervalId !== undefined) clearInterval(intervalId);\n\t\t\t\tintervalId = undefined;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst emitNow = (now: Date) => {\n\t\t\t\tif (output === \"date\") ctx.down([[\"DATA\", now]]);\n\t\t\t\telse if (output === \"timestamp_ms\") ctx.down([[\"DATA\", now.getTime()]]);\n\t\t\t\telse ctx.down([[\"DATA\", dateToTimestampNs(now)]]);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key = cronMinuteKey(now);\n\t\t\t\tif (key !== lastFiredKey && matchesCron(schedule, now)) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\temitNow(now);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn cleanup;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tcheck();\n\t\t\tintervalId = setInterval(check, tickMs);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n}\n\nexport function runProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn runProcessWithOptions({ program, args });\n}\n\nexport function fromProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn processSource(\"fromProcess\", { program, args });\n}\n\nexport function runProcessWithOptions(command: ProcessCommand): Operator<never, ProcessResult> {\n\treturn processSource(\"runProcess\", command);\n}\n\nfunction processSource(factory: string, command: ProcessCommand): Operator<never, ProcessResult> {\n\tassertNonEmptyString(command.program, `${factory}: program`);\n\treturn driverOneShotSource<ProcessResult>(\n\t\tfactory,\n\t\t`${factory}: missing process driver`,\n\t\t(ctx, callback) => ctx.environment().processDriver()?.run(command, callback),\n\t);\n}\n\nexport function fromHttp(url: string): Operator<never, HttpResponse> {\n\treturn fromHttpWithOptions({ method: \"GET\", url });\n}\n\nexport function fromHttpWithOptions(request: HttpRequest): Operator<never, HttpResponse> {\n\tassertNonEmptyString(request.url, \"fromHttp: url\");\n\tassertNonEmptyString(request.method, \"fromHttp: method\");\n\treturn driverOneShotSource<HttpResponse>(\n\t\t\"fromHttp\",\n\t\t\"fromHttp: missing http driver\",\n\t\t(ctx, callback) => ctx.environment().httpDriver()?.request(request, callback),\n\t);\n}\n\nexport function fromSSE(url: string): Operator<never, SseEvent> {\n\treturn fromSSEWithOptions({ url });\n}\n\nexport function fromSSEWithOptions(request: SseRequest): Operator<never, SseEvent> {\n\tassertNonEmptyString(request.url, \"fromSSE: url\");\n\treturn driverStreamSource<SseEvent, SseDriverEvent>(\n\t\t\"fromSSE\",\n\t\t\"fromSSE: missing sse driver\",\n\t\t(ctx, callback) => ctx.environment().sseDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebSocket(url: string): Operator<never, WebSocketEvent> {\n\treturn fromWebSocketWithOptions({ url });\n}\n\nexport function fromWebSocketWithOptions(\n\trequest: WebSocketRequest,\n): Operator<never, WebSocketEvent> {\n\tassertNonEmptyString(request.url, \"fromWebSocket: url\");\n\treturn driverStreamSource<WebSocketEvent, WebSocketDriverEvent>(\n\t\t\"fromWebSocket\",\n\t\t\"fromWebSocket: missing websocket driver\",\n\t\t(ctx, callback) => ctx.environment().webSocketDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebhook(id: string): Operator<never, WebhookEvent> {\n\treturn fromWebhookWithOptions({ id });\n}\n\nexport function fromWebhookWithOptions(\n\tregistration: WebhookRegistration,\n): Operator<never, WebhookEvent> {\n\tassertNonEmptyString(registration.id, \"fromWebhook: id\");\n\treturn driverStreamSource<WebhookEvent, WebhookDriverEvent>(\n\t\t\"fromWebhook\",\n\t\t\"fromWebhook: missing webhook driver\",\n\t\t(ctx, callback) => ctx.environment().webhookDriver()?.register(registration, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nfunction timerSource(factory: string, ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\tconst { period, signal } = opts ?? {};\n\tconst op = source<number>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet count = 0;\n\t\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst finish = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tif (period != null) {\n\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\t\tif (done) return;\n\t\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\t}, period);\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot: DATA then COMPLETE in one wave (terminal-is-forever).\n\t\t\t\t\tdone = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", count++], [\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tt = setTimeout(finish, ms);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n\tif (factory === \"timer\" && period === undefined && signal === undefined) {\n\t\treturn { ...op, restore: { ref: \"timer\", config: { ms: toCheckpointJson(ms, \"timer.ms\") } } };\n\t}\n\treturn op;\n}\n\n/**\n * Timer source: one-shot (first tick then COMPLETE) or periodic (`{period}` → 0, 1, 2, …).\n * sync pool + pausable:false (a timer keeps producing through PAUSE, R-pause-modes). Emits the\n * tick counter from 0; deactivation clears the timers.\n */\nexport function timer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"timer\", ms, opts);\n}\n\n/** Frozen pure-ts name for {@link timer}; preserves the real factory name in describe(). */\nexport function fromTimer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"fromTimer\", ms, opts);\n}\n\n/** interval: periodic ticks (0, 1, 2, …), first at `ms`, then every `ms` (RxJS semantics). */\nexport function interval(ms: number): Operator<never, number> {\n\treturn timerSource(\"interval\", ms, { period: ms });\n}\n\n/**\n * Lift a Promise (or thenable) to a single-value stream: one DATA then COMPLETE, or ERROR on\n * rejection. async pool (default pausable → a paused source buffers its late emit). Optional\n * `signal` aborts to ERROR.\n */\nexport function fromPromise<T>(\n\tp: Promise<T> | PromiseLike<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst signal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromPromise\",\n\t\t(ctx) => {\n\t\t\tlet settled = false;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\t// onAbort only runs from a `signal` listener / the `signal.aborted` guard → signal is defined.\n\t\t\t\tctx.down([[\"ERROR\", errorPayload((signal as AbortSignal).reason)]]);\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid Promise.resolve(p).then(\n\t\t\t\t(v) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * Read an async iterable: each value → DATA; COMPLETE when done; ERROR on failure. async pool.\n * Optional `signal` aborts the pump.\n */\nexport function fromAsyncIter<T>(\n\titerable: AsyncIterable<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst outerSignal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromAsyncIter\",\n\t\t(ctx) => {\n\t\t\tconst ac = new AbortController();\n\t\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet done = false;\n\t\t\tconst pump = async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const v of iterable) {\n\t\t\t\t\t\tif (ac.signal.aborted) break;\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"COMPLETE\"]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t} finally {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tvoid pump();\n\t\t\treturn () => {\n\t\t\t\tif (!done) ac.abort();\n\t\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * of: synchronous values — each argument as DATA, then COMPLETE. `of()` is the EMPTY source.\n */\nexport function of<T = never>(...values: T[]): Operator<never, T> {\n\treturn source<T>(\n\t\t\"of\",\n\t\t(ctx) => {\n\t\t\tfor (const value of values) ctx.down([[\"DATA\", value]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** fromIter: a sync iterable — each value → DATA (in order), then COMPLETE, on activation. */\nexport function fromIter<T>(iterable: Iterable<T>): Operator<never, T> {\n\treturn source<T>(\n\t\t\"fromIter\",\n\t\t(ctx) => {\n\t\t\tfor (const v of iterable) ctx.down([[\"DATA\", v]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** EMPTY analogue: complete immediately with no DATA. */\nexport function empty<T = never>(): Operator<never, T> {\n\treturn source<T>(\n\t\t\"empty\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** NEVER analogue: activate and remain silent until deactivation. */\nexport function never<T = never>(): Operator<never, T> {\n\treturn source<T>(\"never\", () => undefined, { pool: \"sync\" });\n}\n\n/** Error source: terminate with ERROR on activation, coercing invalid host-language payloads. */\nexport function throwError(err: unknown): Operator<never, never> {\n\treturn source<never>(\n\t\t\"throwError\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"ERROR\", errorPayload(err)]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a DOM-style event target. Each event becomes DATA; deactivation removes the listener.\n * External callbacks are source boundaries (D43), so no polling or operator-level async leaks in.\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts: FromEventOptions = {},\n): Operator<never, T> {\n\tif (target == null || typeof target.addEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement addEventListener\");\n\t}\n\tif (typeof target.removeEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement removeEventListener\");\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new TypeError(\"fromEvent: event type must be a non-empty string\");\n\t}\n\treturn source<T>(\n\t\t\"fromEvent\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst handler = (event: unknown) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", event as T]]);\n\t\t\t};\n\t\t\ttarget.addEventListener(type, handler, opts);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\ttarget.removeEventListener(type, handler, opts);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a host push transport. The host owns network/native setup; this factory owns reactive\n * delivery and teardown only, preserving async-at-source-boundary discipline.\n */\nexport function fromPushNotification<T = unknown>(register: PushRegister<T>): Operator<never, T> {\n\tif (typeof register !== \"function\") {\n\t\tthrow new TypeError(\"fromPushNotification: register must be a function\");\n\t}\n\treturn source<T>(\n\t\t\"fromPushNotification\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst deliver = (payload: T) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", payload]]);\n\t\t\t};\n\t\t\tconst unsubscribe = register(deliver);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (typeof unsubscribe === \"function\") unsubscribe();\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Coerce a {@link NodeInput}`<T>` to a `Node<T>` (D43 — coercion prerequisite for the CSP-2.7\n * higher-order operators). An existing Node passes through; a thenable → {@link fromPromise};\n * an async iterable → {@link fromAsyncIter}; with `{iter:true}` a sync iterable →\n * {@link fromIter}; everything else → {@link of}. Coerced nodes are bare (use\n * `opts.dispatcher` to bind one, default = process-global D26).\n */\nexport function fromAny<T>(\n\tinput: NodeInput<T>,\n\topts: NodeOptions<T> & { iter?: boolean } = {},\n): Node<T> {\n\tif (isNode(input)) return input as Node<T>;\n\tconst { iter, ...nodeOpts } = opts;\n\tif (isThenable(input)) {\n\t\treturn initNode(fromPromise(input as PromiseLike<T>), [], nodeOpts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as {\n\t\t\t[Symbol.asyncIterator]?: unknown;\n\t\t\t[Symbol.iterator]?: unknown;\n\t\t};\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn initNode(fromAsyncIter(input as AsyncIterable<T>), [], nodeOpts);\n\t\t}\n\t\tif (iter === true && typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn initNode(fromIter(input as Iterable<T>), [], nodeOpts);\n\t\t}\n\t}\n\treturn initNode(of(input as T), [], nodeOpts);\n}\n\n/**\n * Resolve the first DATA from a Node as a Promise. This is a host-boundary escape hatch, not a\n * graph operator; do not call it from reactive node bodies. ERROR rejects, and COMPLETE before DATA\n * rejects because no value exists.\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\tconst finish = (f: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tf();\n\t\t\tif (unsub) {\n\t\t\t\tunsub();\n\t\t\t\tunsub = undefined;\n\t\t\t} else {\n\t\t\t\tshouldUnsub = true;\n\t\t\t}\n\t\t};\n\t\tunsub = source.subscribe((msg) => {\n\t\t\tif (msg[0] === \"DATA\") {\n\t\t\t\tfinish(() => resolve(msg[1] as T));\n\t\t\t} else if (msg[0] === \"ERROR\") {\n\t\t\t\tfinish(() => reject(msg[1]));\n\t\t\t} else if (msg[0] === \"COMPLETE\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: completed without DATA\")));\n\t\t\t} else if (msg[0] === \"TEARDOWN\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: torn down without DATA\")));\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\nfunction singleFromAnyValue<T>(value: T): T {\n\tif (value === undefined) {\n\t\tthrow new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\");\n\t}\n\treturn value;\n}\n\nasync function firstFromAsyncIterable<T>(input: AsyncIterable<T>): Promise<T> {\n\tconst iter = input[Symbol.asyncIterator]();\n\tconst { value, done } = await iter.next();\n\tif (done) {\n\t\tawait iter.return?.();\n\t\tthrow new Error(\"singleFromAny: factory returned empty async iterable\");\n\t}\n\ttry {\n\t\tawait iter.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn value as T;\n}\n\nfunction firstFromIterable<T>(input: Iterable<T>): Promise<T> {\n\tconst iter = input[Symbol.iterator]();\n\tconst { value, done } = iter.next();\n\tif (done) {\n\t\titer.return?.();\n\t\treturn Promise.reject(new Error(\"singleFromAny: factory returned empty iterable\"));\n\t}\n\ttry {\n\t\titer.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn Promise.resolve(value as T);\n}\n\nfunction nodeInputToPromise<T>(input: NodeInput<T>, opts: { iter?: boolean }): Promise<T> {\n\tif (isThenable(input)) return Promise.resolve(input as PromiseLike<T>).then(singleFromAnyValue);\n\tif (isNode(input)) return firstValueFrom(input as Node<T>).then(singleFromAnyValue);\n\tif (isAsyncIterable<T>(input)) return firstFromAsyncIterable(input).then(singleFromAnyValue);\n\tif (opts.iter === true && isIterable<T>(input)) {\n\t\treturn firstFromIterable(input).then(singleFromAnyValue);\n\t}\n\tif (input === undefined) {\n\t\treturn Promise.reject(new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\"));\n\t}\n\treturn Promise.resolve(singleFromAnyValue(input as T));\n}\n\n/**\n * Keyed singleflight over {@link NodeInput}. Concurrent calls with the same key share one Promise;\n * once that input resolves/rejects, the in-flight entry is cleared and a later call re-runs the\n * factory. Host-boundary helper only; it does not create graph topology.\n */\nexport function singleFromAny<K, T>(\n\tfactory: (key: K) => NodeInput<T>,\n\topts: SingleFromAnyOptions<K> = {},\n): (key: K) => Promise<T> {\n\tconst keyOf = opts.keyOf ?? ((key: K): unknown => key);\n\tconst inFlight = new Map<unknown, Promise<T>>();\n\n\treturn (key: K): Promise<T> => {\n\t\tconst dedupeKey = keyOf(key);\n\t\tconst existing = inFlight.get(dedupeKey);\n\t\tif (existing) return existing;\n\n\t\tlet resolvePending!: (value: T) => void;\n\t\tlet rejectPending!: (reason: unknown) => void;\n\t\tlet tracked!: Promise<T>;\n\t\tconst cleanup = (): void => {\n\t\t\tif (inFlight.get(dedupeKey) === tracked) inFlight.delete(dedupeKey);\n\t\t};\n\t\tconst pending = new Promise<T>((resolve, reject) => {\n\t\t\tresolvePending = resolve;\n\t\t\trejectPending = reject;\n\t\t});\n\t\ttracked = pending.then(\n\t\t\t(value) => {\n\t\t\t\tcleanup();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tcleanup();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tinFlight.set(dedupeKey, tracked);\n\t\ttry {\n\t\t\tnodeInputToPromise(factory(key), opts).then(resolvePending, rejectPending);\n\t\t} catch (e) {\n\t\t\trejectPending(e);\n\t\t}\n\t\treturn tracked;\n\t};\n}\n","/**\n * Reactive key–value map (CSP-2.8, D54/D60/D68) — two-port collection with policy opts.\n *\n * Shape = the shared {@link collectionCore} two ports over a `Map` BACKEND (D60). Specializations\n * (D60 #3 / review #3):\n * - TTL/LRU are node-as-opt policies (D68). Static `maxSize` / `defaultTtl` values become constant\n * policy deps; Node-valued opts are declared deps. The graph-visible `reactiveMap.apply` node is\n * the normal backend mutation path and emits the public delta payloads it materializes.\n * - LAZY TTL (no background timer): expiry is checked at read (`get`/`has`) + at synchronous\n * snapshot materialization (`toMap`/`pruneExpired`). A read/prune that deletes an expired key\n * emits the normal delta `delete{reason:\"expired\"}` (D61). Snapshot demand uses an internal pull\n * `snapshotPrep` node: it prunes expired entries and reads the backend once, then public\n * `snapshot` and `delta` derive from that declared prep payload. No snapshot fn drives its own\n * dep (D37).\n * - delete-reason enum {expired|lru-evict|archived|explicit} on the delta (D60 #3c).\n * - LRU `maxSize`: an over-cap `set` evicts the oldest, emitting a `delete{reason:\"lru-evict\"}`.\n * A live-key `get`/`has` touches LRU order WITHOUT a version bump (internal, D60 #3d).\n * - retention (score-archive, D72): `retention.maxSize` is a value-or-Node numeric policy and\n * the static scorer selects archive victims through the normal `reactiveMap.apply` path.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepTerminal,\n\tisTerminalComplete,\n\ttype NodeFn,\n} from \"../../ctx/types.js\";\nimport { strictCanonicalJsonBytes } from \"../../json/codec.js\";\nimport { Node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport { registerBackendStateContributor } from \"../checkpoint.js\";\nimport { initNode, type Operator } from \"../operators.js\";\nimport {\n\tdeadlines,\n\tlruKeys,\n\tPolicyInputs,\n\ttype PolicyOpt,\n\ttype ScoredEntry,\n\tselectRetentionVictims,\n\ttrimHeadOverflow,\n} from \"../policies/collection.js\";\nimport type { ReactiveOpt, RetentionPolicy, ViewCachePolicy } from \"../policies/types.js\";\nimport { timer } from \"../sources.js\";\nimport type { MapChange } from \"./change.js\";\nimport {\n\ttype CollectionCoreOptions,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport type ReactiveMapOpt<T> = ReactiveOpt<T>;\n\nexport interface ReactiveMapRetentionEntry<K, V> {\n\treadonly key: K;\n\treadonly value: V;\n}\n\nexport interface ReactiveMapRetentionPolicy<K, V>\n\textends RetentionPolicy<ReactiveMapRetentionEntry<K, V>> {\n\t/** Archive capacity. Unlike LRU, zero is allowed and archives every live entry. */\n\treadonly maxSize?: ReactiveMapOpt<number>;\n\t/** Higher scores are retained; lowest finite scores are archived first. */\n\tscore(entry: ReactiveMapRetentionEntry<K, V>): number;\n}\n\ninterface ResolvedRetentionPolicy<K, V> {\n\treadonly maxSize?: number;\n\tscore(entry: ReactiveMapRetentionEntry<K, V>): number;\n}\n\nexport interface ReactiveMapOptions<K = unknown, V = unknown> extends CollectionCoreOptions {\n\t/**\n\t * LRU cap as a node-as-opt policy (D68). A static number is a constant policy config; a Node must\n\t * be graph-bound and becomes a declared dep of `reactiveMap.apply`.\n\t */\n\tmaxSize?: ReactiveMapOpt<number>;\n\t/**\n\t * Default TTL in milliseconds as a node-as-opt policy (D68). Per-call `set(...,{ttl})` overrides.\n\t * Lazy expiry only; no active timer in this cut.\n\t */\n\tdefaultTtl?: ReactiveMapOpt<number>;\n\t/**\n\t * Score-based retention/archive policy (D72). The scorer is static local code; only maxSize can be\n\t * a Node-valued policy, keeping graph describe data serializable while apply owns the mutation.\n\t */\n\tretention?: ReactiveMapRetentionPolicy<K, V>;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\tviewCache?: ViewCachePolicy;\n\t/** Injectable monotonic-ish clock for TTL (default `Date.now`). Graph-local clock = follow-up (D26). */\n\tnow?: () => number;\n}\n\nexport interface ReactiveMap<K, V> {\n\treadonly delta: Node<MapChange<K, V>>;\n\treadonly snapshot: Node<ReadonlyMap<K, V>>;\n\treadonly pullId: symbol;\n\t/** Raw entry count (O(1)); may include not-yet-pruned expired entries. Sync non-reactive read. */\n\treadonly size: number;\n\t/** Get a live value (prunes the key if expired). Sync read. */\n\tget(key: K): V | undefined;\n\t/** Live-key existence (prunes if expired). Sync read. */\n\thas(key: K): boolean;\n\t/** Current live (non-expired) entries (fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoMap(): ReadonlyMap<K, V>;\n\t/**\n\t * D121 light selected-map view. `delta` forwards parent map mutations, and `snapshot` is a pull\n\t * node that materializes the currently matching live entries on demand.\n\t */\n\tselect(\n\t\tpredicate: (value: V, key: K) => boolean,\n\t): ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>;\n\tset(key: K, value: V, opts?: { ttl?: number }): void;\n\t/** Bulk set; one delta event per entry, one snapshot-arm. No-op if empty. */\n\tsetMany(entries: Iterable<readonly [K, V]>, opts?: { ttl?: number }): void;\n\tdelete(key: K): void;\n\t/** Bulk delete; one delta per removed key. No-op if none present. */\n\tdeleteMany(keys: Iterable<K>): void;\n\tclear(): void;\n\t/** Explicitly prune expired entries; every removed key emits `delete{reason:\"expired\"}` (D61). */\n\tpruneExpired(): void;\n\t/** D54 widening: every `[key, value]` from `src` is set. Returns a disposer. */\n\tsetFrom(src: Node<readonly [K, V]>): () => void;\n\tdispose(): void;\n}\n\ninterface Entry<V> {\n\tvalue: V;\n\texpiresAt?: number;\n}\n\nfunction strictJsonIdentity(value: unknown): string {\n\treturn Array.from(strictCanonicalJsonBytes(value)).join(\",\");\n}\n\ntype Lookup<V> =\n\t| { found: true; value: V }\n\t| { found: false; expired?: false }\n\t| { found: false; expired: true; previous: V };\n\ninterface SnapshotPrep<K, V> {\n\treadonly snapshot: ReadonlyMap<K, V>;\n\treadonly expired: readonly MapChange<K, V>[];\n}\n\ntype MapIntent<K, V> =\n\t| { kind: \"set\"; key: K; value: V; ttl?: number }\n\t| { kind: \"delete\"; key: K }\n\t| { kind: \"clear\" }\n\t| { kind: \"pruneExpired\" }\n\t| { kind: \"pruneKey\"; key: K };\n\n/** Default `Map`-backed store. TTL/LRU policy lives in graph-visible policy/apply nodes (D68). */\nclass MapBackend<K, V> {\n\tprivate _version = 0;\n\tprivate readonly store = new Map<K, Entry<V>>();\n\tprivate readonly now: () => number;\n\n\tconstructor(opts: { now?: () => number }) {\n\t\tthis.now = opts.now ?? Date.now;\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this.store.size;\n\t}\n\n\tnowMs(): number {\n\t\treturn this.now();\n\t}\n\n\texpiresAtOf(key: K): number | undefined {\n\t\treturn this.store.get(key)?.expiresAt;\n\t}\n\n\tprivate isExpired(e: Entry<V>): boolean {\n\t\treturn e.expiresAt !== undefined && this.now() >= e.expiresAt;\n\t}\n\n\tresolveExpiresAt(ttl?: number): number | undefined {\n\t\tif (ttl === undefined) return undefined;\n\t\tif (!Number.isFinite(ttl) || ttl <= 0)\n\t\t\tthrow new RangeError(`reactiveMap: ttl must be a positive finite number (got ${ttl})`);\n\t\treturn this.now() + ttl;\n\t}\n\n\tprivate deleteExpired(key: K, e: Entry<V>): Array<[K, V]> {\n\t\tthis.store.delete(key);\n\t\tthis._version += 1;\n\t\treturn [[key, e.value]];\n\t}\n\n\t/** Read without materializing expiry. Caller routes expired deletes through the apply node (D68). */\n\tlookup(key: K): Lookup<V> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined) return { found: false };\n\t\tif (this.isExpired(e)) return { found: false, expired: true, previous: e.value };\n\t\t// LRU touch (no version bump — internal, D60 #3d).\n\t\tthis.store.delete(key);\n\t\tthis.store.set(key, e);\n\t\treturn { found: true, value: e.value };\n\t}\n\n\t/** Set; returns the entries evicted by LRU overflow (the caller emits their delete deltas). */\n\tset(key: K, value: V, expiresAt?: number): void {\n\t\tif (this.store.has(key)) this.store.delete(key); // re-insert at LRU end\n\t\tthis.store.set(key, { value, expiresAt });\n\t\tthis._version += 1;\n\t}\n\n\tenforceLru(maxSize?: number): Array<[K, V]> {\n\t\tconst evicted: Array<[K, V]> = [];\n\t\tfor (const oldest of trimHeadOverflow(lruKeys(this.store.keys()).keys(), {\n\t\t\tmaxSize,\n\t\t\tsize: this.store.size,\n\t\t})) {\n\t\t\tconst e = this.store.get(oldest);\n\t\t\tif (e !== undefined) evicted.push([oldest, e.value]);\n\t\t\tthis.store.delete(oldest);\n\t\t}\n\t\tif (evicted.length > 0) this._version += 1;\n\t\treturn evicted;\n\t}\n\n\tenforceRetention(policy?: ResolvedRetentionPolicy<K, V>): Array<[K, V]> {\n\t\tif (policy === undefined || policy.maxSize === undefined) return [];\n\t\tconst scored: ScoredEntry<readonly [K, V]>[] = [];\n\t\tfor (const [key, entry] of this.store) {\n\t\t\tif (!this.isExpired(entry)) {\n\t\t\t\tscored.push({\n\t\t\t\t\tentry: [key, entry.value] as const,\n\t\t\t\t\tscore: policy.score({ key, value: entry.value }),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst archived = selectRetentionVictims(scored, { maxSize: policy.maxSize });\n\t\tfor (const [key] of archived) this.store.delete(key);\n\t\tif (archived.length > 0) this._version += 1;\n\t\treturn archived.map(([key, value]) => [key, value]);\n\t}\n\n\tdelete(key: K): Lookup<V> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined) return { found: false };\n\t\tthis.store.delete(key);\n\t\tthis._version += 1;\n\t\treturn { found: true, value: e.value };\n\t}\n\n\tclear(): number {\n\t\tconst n = this.store.size;\n\t\tif (n === 0) return 0;\n\t\tthis.store.clear();\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\tpruneExpired(): Array<[K, V]> {\n\t\tconst removed: Array<[K, V]> = [];\n\t\tfor (const [k, e] of this.store) {\n\t\t\tif (this.isExpired(e)) {\n\t\t\t\tthis.store.delete(k);\n\t\t\t\tremoved.push([k, e.value]);\n\t\t\t}\n\t\t}\n\t\tif (removed.length > 0) this._version += 1;\n\t\treturn removed;\n\t}\n\n\tpruneKeyIfExpired(key: K): Array<[K, V]> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined || !this.isExpired(e)) return [];\n\t\treturn this.deleteExpired(key, e);\n\t}\n\n\t/** Fresh snapshot of live entries. Does not prune; callers choose whether to materialize expiry. */\n\tsnapshot(): ReadonlyMap<K, V> {\n\t\tconst out = new Map<K, V>();\n\t\tfor (const [k, e] of this.store) if (!this.isExpired(e)) out.set(k, e.value);\n\t\treturn out;\n\t}\n\n\t/** D160 checkpoint payload: exact restorable map entries, excluding TTL-bearing state. */\n\tcheckpointEntries(): readonly (readonly [K, V])[] {\n\t\tconst out: Array<readonly [K, V]> = [];\n\t\tconst seen = new Set<string>();\n\t\tfor (const [key, entry] of this.store) {\n\t\t\tif (entry.expiresAt !== undefined) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"reactiveMap checkpoint backendState cannot preserve per-entry TTL; persist the map externally or clear TTL state before graph checkpoint (D160)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stableKey = strictJsonIdentity(key);\n\t\t\tif (seen.has(stableKey)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"reactiveMap checkpoint backendState contains duplicate strict-JSON keys (D160)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tseen.add(stableKey);\n\t\t\tout.push([key, entry.value] as const);\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/**\n * Create a reactive map (D54/D60). DELTA stream of {@link MapChange} + lazy pull SNAPSHOT (a\n * `ReadonlyMap`) + pullId via {@link collectionCore}; this layer adds the typed map surface.\n */\nexport function reactiveMap<K, V>(options: ReactiveMapOptions<K, V> = {}): ReactiveMap<K, V> {\n\treturn createReactiveMap(options);\n}\n\n/** @internal D161 restore path: seed the backend without replaying public deltas. */\nexport function restoreReactiveMapFromBackendState<K, V>(\n\tinitialEntries: readonly (readonly [K, V])[],\n\toptions: ReactiveMapOptions<K, V> = {},\n): ReactiveMap<K, V> {\n\treturn createReactiveMap(options, initialEntries);\n}\n\nfunction createReactiveMap<K, V>(\n\toptions: ReactiveMapOptions<K, V> = {},\n\tinitialEntries: readonly (readonly [K, V])[] = [],\n): ReactiveMap<K, V> {\n\tconst { maxSize, defaultTtl, retention, viewCache, now, name, dispatcher, graph } = options;\n\tconst backend = new MapBackend<K, V>({ now });\n\tfor (const [key, value] of initialEntries) backend.set(key, value);\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst restorable =\n\t\tgraph !== undefined &&\n\t\tname !== undefined &&\n\t\tmaxSize === undefined &&\n\t\tdefaultTtl === undefined &&\n\t\tretention === undefined;\n\n\tfunction isNodeOpt<T>(x: PolicyOpt<T> | undefined): x is Node<T> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveMap: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction validateTtl(v: number): number {\n\t\tif (!Number.isFinite(v) || v <= 0)\n\t\t\tthrow new RangeError(`reactiveMap: defaultTtl must be a positive finite number (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction validateRetentionMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 0)\n\t\t\tthrow new RangeError(\n\t\t\t\t`reactiveMap: retention.maxSize must be a non-negative integer (got ${v})`,\n\t\t\t);\n\t\treturn v;\n\t}\n\n\tif (retention !== undefined && typeof retention.score !== \"function\")\n\t\tthrow new TypeError(\"reactiveMap: retention.score must be a function\");\n\n\ttype PolicyLabel = \"lruPolicy\" | \"ttlPolicy\" | \"retentionPolicy\";\n\n\tfunction constPolicyNode(label: PolicyLabel, value: number): Node<number> {\n\t\tconst op: Operator<never, number> = {\n\t\t\tfactory: `reactiveMap.${label}`,\n\t\t\tbody: () => {},\n\t\t\topts: { initial: value },\n\t\t};\n\t\tif (graph) {\n\t\t\treturn graph.initNode(op, [], {\n\t\t\t\tname: name ? `${name}.${label}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveMap\", policy: label },\n\t\t\t});\n\t\t}\n\t\treturn new Node<number>([], null, {\n\t\t\t...base,\n\t\t\tinitial: value,\n\t\t\tfactory: `reactiveMap.${label}`,\n\t\t\tname: name ? `${name}.${label}` : undefined,\n\t\t});\n\t}\n\n\tfunction policyNode(\n\t\tlabel: PolicyLabel,\n\t\topt: PolicyOpt<number> | undefined,\n\t\tvalidate: (v: number) => number,\n\t): Node<number> | undefined {\n\t\tif (opt === undefined) return undefined;\n\t\tif (isNodeOpt(opt)) {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`reactiveMap ${label} Node option requires options.graph so the policy edge is describe-visible (${label === \"retentionPolicy\" ? \"D72\" : \"D68\"})`,\n\t\t\t\t);\n\t\t\treturn opt;\n\t\t}\n\t\treturn constPolicyNode(label, validate(opt));\n\t}\n\n\tconst intentOp: Operator<never, MapIntent<K, V>> = {\n\t\tfactory: \"reactiveMap.intent\",\n\t\tbody: () => {},\n\t};\n\tconst intent = graph\n\t\t? graph.initNode(intentOp, [], {\n\t\t\t\tname: name ? `${name}.intent` : undefined,\n\t\t\t\tmeta: { kind: \"collection_intent\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.intent\" } } : {}),\n\t\t\t})\n\t\t: new Node<MapIntent<K, V>>([], null, {\n\t\t\t\t...base,\n\t\t\t\tfactory: \"reactiveMap.intent\",\n\t\t\t\tname: name ? `${name}.intent` : undefined,\n\t\t\t});\n\tconst lruPolicy = policyNode(\"lruPolicy\", maxSize, validateMaxSize);\n\tconst ttlPolicy = policyNode(\"ttlPolicy\", defaultTtl, validateTtl);\n\tconst retentionPolicy = policyNode(\n\t\t\"retentionPolicy\",\n\t\tretention?.maxSize,\n\t\tvalidateRetentionMaxSize,\n\t);\n\n\tlet currentMaxSize = isNodeOpt(maxSize) ? undefined : maxSize;\n\tlet currentDefaultTtl = isNodeOpt(defaultTtl) ? undefined : defaultTtl;\n\tlet currentRetentionMaxSize = isNodeOpt(retention?.maxSize)\n\t\t? undefined\n\t\t: retention?.maxSize === undefined\n\t\t\t? undefined\n\t\t\t: validateRetentionMaxSize(retention.maxSize);\n\tconst ttlHeap = deadlines<K>();\n\tlet ttlTimer: Node<unknown> | null = null;\n\tlet ttlTimerDue: number | undefined;\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tlet bindSeq = 0;\n\tlet apply: Node<MapChange<K, V>>;\n\tconst selectMemo = new ViewMemoCache<\n\t\t(value: V, key: K) => boolean,\n\t\tReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>\n\t>(viewCache);\n\tlet selectSeq = 0;\n\n\tconst policyInputs = new PolicyInputs([intent as Node<unknown>]);\n\tconst lruReader = policyInputs.add(lruPolicy);\n\tconst ttlReader = policyInputs.add(ttlPolicy);\n\tconst retentionReader = policyInputs.add(retentionPolicy);\n\n\tfunction emitExpired(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"expired\" }]]);\n\t}\n\n\tfunction emitLruEvicted(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"lru-evict\" }]]);\n\t}\n\n\tfunction emitArchived(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"archived\" }]]);\n\t}\n\n\tfunction nextValidExpiry(): { readonly key: K; readonly expiresAt: number } | undefined {\n\t\tfor (;;) {\n\t\t\tconst top = ttlHeap.peek();\n\t\t\tif (top === undefined) return undefined;\n\t\t\tif (backend.expiresAtOf(top.key) === top.expiresAt) return top;\n\t\t\tttlHeap.pop();\n\t\t}\n\t}\n\n\tfunction scheduleTtl(ctx: Ctx, body: NodeFn): void {\n\t\tfor (;;) {\n\t\t\tconst next = nextValidExpiry();\n\t\t\tif (next === undefined) {\n\t\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, body);\n\t\t\t\tttlTimer = null;\n\t\t\t\tttlTimerDue = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (next.expiresAt <= backend.nowMs()) {\n\t\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ttlTimerDue === next.expiresAt) return;\n\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, body);\n\t\t\tttlTimerDue = next.expiresAt;\n\t\t\tttlTimer = initNode(timer(Math.max(0, next.expiresAt - backend.nowMs())), [], base);\n\t\t\tctx.rewireNext.subscribeDep(ttlTimer, body);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfunction applyIntent(ctx: Ctx, intentValue: MapIntent<K, V>): void {\n\t\tif (intentValue.kind === \"set\") {\n\t\t\tconst ttl = intentValue.ttl ?? currentDefaultTtl;\n\t\t\tconst expiresAt = backend.resolveExpiresAt(ttl);\n\t\t\tbackend.set(intentValue.key, intentValue.value, expiresAt);\n\t\t\tif (expiresAt !== undefined) ttlHeap.push({ key: intentValue.key, expiresAt });\n\t\t\tctx.down([[\"DATA\", { kind: \"set\", key: intentValue.key, value: intentValue.value }]]);\n\t\t\temitLruEvicted(ctx, backend.enforceLru(currentMaxSize));\n\t\t\temitArchived(\n\t\t\t\tctx,\n\t\t\t\tbackend.enforceRetention(\n\t\t\t\t\tretention ? { maxSize: currentRetentionMaxSize, score: retention.score } : undefined,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"delete\") {\n\t\t\tconst previous = backend.delete(intentValue.key);\n\t\t\tif (previous.found)\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ kind: \"delete\", key: intentValue.key, previous: previous.value, reason: \"explicit\" },\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"clear\") {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) ctx.down([[\"DATA\", { kind: \"clear\", count }]]);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"pruneExpired\") {\n\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\treturn;\n\t\t}\n\t\temitExpired(ctx, backend.pruneKeyIfExpired(intentValue.key));\n\t}\n\n\tconst applyBody: NodeFn = (ctx: Ctx) => {\n\t\tconst nextMaxSize = lruReader.read(ctx, currentMaxSize);\n\t\tcurrentMaxSize = nextMaxSize === undefined ? undefined : validateMaxSize(nextMaxSize);\n\t\tconst nextTtl = ttlReader.read(ctx, currentDefaultTtl);\n\t\tcurrentDefaultTtl = nextTtl === undefined ? undefined : validateTtl(nextTtl);\n\t\tconst nextRetentionMaxSize = retentionReader.read(ctx, currentRetentionMaxSize);\n\t\tcurrentRetentionMaxSize =\n\t\t\tnextRetentionMaxSize === undefined\n\t\t\t\t? undefined\n\t\t\t\t: validateRetentionMaxSize(nextRetentionMaxSize);\n\n\t\tfor (const item of (depBatch(ctx, 0) ?? []) as readonly MapIntent<K, V>[]) {\n\t\t\tapplyIntent(ctx, item);\n\t\t}\n\t\tconst deps = apply.deps;\n\t\tfor (let i = 1; i < depCount(ctx); i++) {\n\t\t\tif (i === lruReader.index || i === ttlReader.index || i === retentionReader.index) continue;\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const item of (depBatch(ctx, i) ?? []) as readonly MapIntent<K, V>[]) {\n\t\t\t\t\tapplyIntent(ctx, item);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdep === ttlTimer &&\n\t\t\t\t((depBatch(ctx, i)?.length ?? 0) > 0 || isTerminalComplete(depTerminal(ctx, i)))\n\t\t\t) {\n\t\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, applyBody);\n\t\t\t\tttlTimer = null;\n\t\t\t\tttlTimerDue = undefined;\n\t\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\t}\n\t\t}\n\t\t// Lowering a reactive maxSize is itself a policy-driven backend mutation (D68).\n\t\temitLruEvicted(ctx, backend.enforceLru(currentMaxSize));\n\t\temitArchived(\n\t\t\tctx,\n\t\t\tbackend.enforceRetention(\n\t\t\t\tretention ? { maxSize: currentRetentionMaxSize, score: retention.score } : undefined,\n\t\t\t),\n\t\t);\n\t\tscheduleTtl(ctx, applyBody);\n\t};\n\n\tconst applyOp: Operator<unknown, MapChange<K, V>> = {\n\t\tfactory: \"reactiveMap.apply\",\n\t\tbody: applyBody,\n\t\topts: { partial: true },\n\t};\n\tapply = graph\n\t\t? graph.initNode(applyOp, policyInputs.deps as readonly Node<unknown>[], {\n\t\t\t\tname: name ? `${name}.apply` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.apply\" } } : {}),\n\t\t\t})\n\t\t: initNode(applyOp, policyInputs.deps, {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.apply` : undefined,\n\t\t\t});\n\n\tconst pullId = Symbol(name ? `${name}.snapshot` : \"reactiveMap.snapshot\");\n\tconst snapshotPrepOp: Operator<unknown, SnapshotPrep<K, V>> = {\n\t\tfactory: \"reactiveMap.snapshotPrep\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tconst expired = backend.pruneExpired().map(\n\t\t\t\t([key, previous]): MapChange<K, V> => ({\n\t\t\t\t\tkind: \"delete\",\n\t\t\t\t\tkey,\n\t\t\t\t\tprevious,\n\t\t\t\t\treason: \"expired\",\n\t\t\t\t}),\n\t\t\t);\n\t\t\tctx.down([[\"DATA\", { snapshot: backend.snapshot(), expired }]]);\n\t\t},\n\t\topts: {\n\t\t\t...base,\n\t\t\tpullId,\n\t\t\tpartial: true,\n\t\t},\n\t};\n\tconst snapshotPrep = graph\n\t\t? graph.initNode(snapshotPrepOp, [apply as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.snapshotPrep` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot_prep\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.snapshotPrep\" } } : {}),\n\t\t\t})\n\t\t: initNode(snapshotPrepOp, [apply as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.snapshotPrep` : undefined,\n\t\t\t});\n\tconst deltaOp: Operator<unknown, MapChange<K, V>> = {\n\t\tfactory: \"reactiveMap.delta\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tfor (const change of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", change as MapChange<K, V>]]);\n\t\t\t}\n\t\t\tfor (const prep of depBatch(ctx, 1) ?? []) {\n\t\t\t\tfor (const change of (prep as SnapshotPrep<K, V>).expired) ctx.down([[\"DATA\", change]]);\n\t\t\t}\n\t\t},\n\t\topts: { partial: true },\n\t};\n\tconst delta = graph\n\t\t? graph.initNode(deltaOp, [apply as Node<unknown>, snapshotPrep as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_delta\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.delta\" } } : {}),\n\t\t\t})\n\t\t: initNode(deltaOp, [apply as Node<unknown>, snapshotPrep as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t});\n\tconst snapshotOp: Operator<unknown, ReadonlyMap<K, V>> = {\n\t\tfactory: \"reactiveMap.snapshot\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tfor (const prep of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", (prep as SnapshotPrep<K, V>).snapshot]]);\n\t\t\t}\n\t\t},\n\t\topts: { partial: true },\n\t};\n\tconst snapshot = graph\n\t\t? graph.initNode(snapshotOp, [snapshotPrep as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.snapshot\" } } : {}),\n\t\t\t})\n\t\t: initNode(snapshotOp, [snapshotPrep as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t});\n\tif (restorable) {\n\t\tregisterBackendStateContributor(intent as Node<unknown>, () => backend.checkpointEntries());\n\t}\n\tconst releaseApply = graph\n\t\t? graph.retain(apply, { reason: \"reactiveMap.apply\" })\n\t\t: apply.subscribe(() => {});\n\tconst binds: Array<() => void> = [];\n\n\tfunction doSet(key: K, value: V, ttl?: number): void {\n\t\tif (ttl !== undefined) validateTtl(ttl);\n\t\tintent.down([\n\t\t\t[\"DATA\", ttl === undefined ? { kind: \"set\", key, value } : { kind: \"set\", key, value, ttl }],\n\t\t]);\n\t}\n\n\tfunction read(key: K): Lookup<V> {\n\t\tconst r = backend.lookup(key);\n\t\tif (!r.found && r.expired) intent.down([[\"DATA\", { kind: \"pruneKey\", key }]]);\n\t\treturn r;\n\t}\n\n\tfunction selectedSnapshot(predicate: (value: V, key: K) => boolean): ReadonlyMap<K, V> {\n\t\tconst out = new Map<K, V>();\n\t\tfor (const [key, value] of backend.snapshot()) {\n\t\t\tif (predicate(value, key)) out.set(key, value);\n\t\t}\n\t\treturn out;\n\t}\n\n\tfunction select(\n\t\tpredicate: (value: V, key: K) => boolean,\n\t): ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>> {\n\t\tif (typeof predicate !== \"function\")\n\t\t\tthrow new TypeError(\"reactiveMap.select: predicate must be a function\");\n\t\tconst cached = selectMemo.get(predicate);\n\t\tif (cached !== undefined) return cached;\n\t\tlet view: ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>;\n\t\tview = lightReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>(delta as Node<unknown>, {\n\t\t\tdispatcher,\n\t\t\tgraph,\n\t\t\tfactory: \"reactiveMap.select\",\n\t\t\tname: name ? `${name}.select#${selectSeq++}` : undefined,\n\t\t\tmaterializeSnapshot: () => selectedSnapshot(predicate),\n\t\t\tonDispose: () => {\n\t\t\t\tselectMemo.deleteValue(view);\n\t\t\t},\n\t\t});\n\t\tselectMemo.set(predicate, view);\n\t\treturn view;\n\t}\n\n\treturn {\n\t\tdelta,\n\t\tsnapshot,\n\t\tpullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tget(key: K): V | undefined {\n\t\t\tconst r = read(key);\n\t\t\treturn r.found ? r.value : undefined;\n\t\t},\n\t\thas(key: K): boolean {\n\t\t\treturn read(key).found;\n\t\t},\n\t\ttoMap(): ReadonlyMap<K, V> {\n\t\t\tintent.down([[\"DATA\", { kind: \"pruneExpired\" }]]);\n\t\t\treturn backend.snapshot();\n\t\t},\n\t\tselect,\n\n\t\tset(key: K, value: V, opts?: { ttl?: number }): void {\n\t\t\tdoSet(key, value, opts?.ttl);\n\t\t},\n\t\tsetMany(entries: Iterable<readonly [K, V]>, opts?: { ttl?: number }): void {\n\t\t\tfor (const [k, v] of entries) doSet(k, v, opts?.ttl);\n\t\t},\n\t\tdelete(key: K): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"delete\", key }]]);\n\t\t},\n\t\tdeleteMany(keys: Iterable<K>): void {\n\t\t\tfor (const k of keys) {\n\t\t\t\tintent.down([[\"DATA\", { kind: \"delete\", key: k }]]);\n\t\t\t}\n\t\t},\n\t\tclear(): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"clear\" }]]);\n\t\t},\n\t\tpruneExpired(): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"pruneExpired\" }]]);\n\t\t},\n\n\t\tsetFrom(src: Node<readonly [K, V]>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveMap.setFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<readonly [K, V], MapIntent<K, V>> = {\n\t\t\t\tfactory: \"reactiveMap.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const [k, v] of (depBatch(ctx, 0) ?? []) as readonly (readonly [K, V])[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"set\", key: k, value: v }]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveMap.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveMap\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tapply.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapply.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tselectMemo.disposeAll();\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t},\n\t};\n}\n","import type {\n\tIndexRow,\n\tReactiveIndex,\n\tReactiveIndexOptions,\n} from \"../graph/data-structures/reactive-index.js\";\nimport { restoreReactiveIndexFromBackendState } from \"../graph/data-structures/reactive-index.js\";\nimport type { ReactiveListOptions } from \"../graph/data-structures/reactive-list.js\";\nimport { type ReactiveList, reactiveList } from \"../graph/data-structures/reactive-list.js\";\nimport type { ReactiveLogOptions } from \"../graph/data-structures/reactive-log.js\";\nimport { type ReactiveLog, reactiveLog } from \"../graph/data-structures/reactive-log.js\";\nimport type { ReactiveMap, ReactiveMapOptions } from \"../graph/data-structures/reactive-map.js\";\nimport { restoreReactiveMapFromBackendState } from \"../graph/data-structures/reactive-map.js\";\nimport type {\n\tReactiveIndexRestoreState,\n\tReactiveListRestoreState,\n\tReactiveLogRestoreState,\n\tReactiveMapRestoreState,\n} from \"../storage/index.js\";\n\nfunction isListRestoreState<T>(\n\tstate: ReactiveListRestoreState<T> | readonly T[],\n): state is ReactiveListRestoreState<T> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreListValues<T>(state: ReactiveListRestoreState<T> | readonly T[]): readonly T[] {\n\tif (!isListRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveList\") throw new TypeError(\"restore state kind must be reactiveList\");\n\treturn state.state;\n}\n\nfunction isLogRestoreState<T>(\n\tstate: ReactiveLogRestoreState<T> | readonly T[],\n): state is ReactiveLogRestoreState<T> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreLogValues<T>(state: ReactiveLogRestoreState<T> | readonly T[]): readonly T[] {\n\tif (!isLogRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveLog\") throw new TypeError(\"restore state kind must be reactiveLog\");\n\treturn state.state;\n}\n\nfunction isMapRestoreState<K, V>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n): state is ReactiveMapRestoreState<K, V> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreMapEntries<K, V>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n): readonly (readonly [K, V])[] {\n\tif (!isMapRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveMap\") throw new TypeError(\"restore state kind must be reactiveMap\");\n\treturn state.state;\n}\n\nfunction isIndexRestoreState<K, V>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n): state is ReactiveIndexRestoreState<K, V> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreIndexRows<K, V>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n): readonly IndexRow<K, V>[] {\n\tif (!isIndexRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveIndex\") {\n\t\tthrow new TypeError(\"restore state kind must be reactiveIndex\");\n\t}\n\treturn state.state;\n}\n\n/** D161 synchronous collection-owned restore. This helper never reads storage. */\nexport function restoreReactiveList<T = unknown>(\n\tstate: ReactiveListRestoreState<T> | readonly T[],\n\toptions: ReactiveListOptions = {},\n): ReactiveList<T> {\n\tconst values = restoreListValues(state);\n\treturn reactiveList<T>(values, options);\n}\n\n/** D161 synchronous collection-owned restore. This helper never reads storage. */\nexport function restoreReactiveLog<T = unknown>(\n\tstate: ReactiveLogRestoreState<T> | readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLog<T> {\n\tconst values = restoreLogValues(state);\n\treturn reactiveLog<T>(values, options);\n}\n\n/** D161 synchronous collection-owned restore for map entries; policy config still comes from options. */\nexport function restoreReactiveMap<K = unknown, V = unknown>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n\toptions: ReactiveMapOptions<K, V> = {},\n): ReactiveMap<K, V> {\n\tconst entries = restoreMapEntries(state);\n\treturn restoreReactiveMapFromBackendState<K, V>(entries, options);\n}\n\n/** D161 synchronous collection-owned restore for sorted index rows; key-codec I/O stays outside. */\nexport function restoreReactiveIndex<K = unknown, V = unknown>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\tconst rows = restoreIndexRows(state);\n\treturn restoreReactiveIndexFromBackendState<K, V>(rows, options);\n}\n","import type {\n\tIndexChange,\n\tListChange,\n\tLogChange,\n\tMapChange,\n} from \"../graph/data-structures/change.js\";\nimport type { IndexRow } from \"../graph/data-structures/reactive-index.js\";\nimport { strictCanonicalJsonBytes, strictJsonCodecFor } from \"../json/codec.js\";\nimport type { AppendLogStorageTier } from \"./append-log.js\";\nimport type { Codec } from \"./codec.js\";\nimport type { KvStorageTier } from \"./kv.js\";\n\n/** D161 strict-JSON snapshot frame format tag for reactive collection persistence. */\nexport const REACTIVE_COLLECTION_SNAPSHOT_FORMAT =\n\t\"graphrefly.reactive-collection.snapshot.v1\" as const;\n/** D161 strict-JSON change frame format tag for reactive collection persistence. */\nexport const REACTIVE_COLLECTION_CHANGE_FORMAT =\n\t\"graphrefly.reactive-collection.change.v1\" as const;\n/** D161 v1 frame version for reactive collection snapshot/change storage. */\nexport const REACTIVE_COLLECTION_FRAME_VERSION = 1 as const;\n\n/** D161 collection kinds recognized by the unified persistence frame envelope. */\nexport type ReactiveCollectionStorageKind =\n\t| \"reactiveList\"\n\t| \"reactiveLog\"\n\t| \"reactiveMap\"\n\t| \"reactiveIndex\";\n\n/** D161 durable baseline frame; storage is passive and does not own graph restore. */\nexport interface ReactiveCollectionSnapshotFrame<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tS = unknown,\n> {\n\treadonly format: typeof REACTIVE_COLLECTION_SNAPSHOT_FORMAT;\n\treadonly version: typeof REACTIVE_COLLECTION_FRAME_VERSION;\n\treadonly kind: K;\n\t/** Last append-log seq reflected by this snapshot; -1 means no change-log entry. */\n\treadonly changeCursor: number;\n\treadonly snapshot: S;\n}\n\n/** D161 append-log change frame; change-log replay is collection-state folding, not graph restore. */\nexport interface ReactiveCollectionChangeFrame<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tC = unknown,\n> {\n\treadonly format: typeof REACTIVE_COLLECTION_CHANGE_FORMAT;\n\treadonly version: typeof REACTIVE_COLLECTION_FRAME_VERSION;\n\treadonly kind: K;\n\treadonly change: C;\n}\n\n/** D161 passive load/fold result consumed by synchronous restoreReactive* helpers. */\nexport interface ReactiveCollectionRestoreState<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tS = unknown,\n> {\n\treadonly kind: K;\n\treadonly state: S;\n\treadonly source: \"empty\" | \"changes\" | \"snapshot\" | \"snapshot+changes\";\n\treadonly snapshot: { readonly found: boolean; readonly changeCursor: number };\n\treadonly changes: { readonly applied: number; readonly cursor: number };\n}\n\n/** D161 restore state for a reactiveList materialized as a strict-JSON array snapshot. */\nexport type ReactiveListRestoreState<T = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveList\",\n\treadonly T[]\n>;\n\n/** D161 restore state for a reactiveLog materialized as a strict-JSON array snapshot. */\nexport type ReactiveLogRestoreState<T = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveLog\",\n\treadonly T[]\n>;\n\n/** D161 passive restore-state shape for reactiveMap; policy-aware restore remains deferred. */\nexport type ReactiveMapRestoreState<K = unknown, V = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveMap\",\n\treadonly (readonly [K, V])[]\n>;\n\n/** D161 passive restore-state shape for reactiveIndex; key-codec restore remains deferred. */\nexport type ReactiveIndexRestoreState<K = unknown, V = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveIndex\",\n\treadonly IndexRow<K, V>[]\n>;\n\n/** D161 passive storage inputs for collection load/fold helpers. */\nexport interface LoadReactiveCollectionStateOptions {\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nfunction assertKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected frame fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertSafeInteger(value: unknown, label: string, min = 0): number {\n\tif (!Number.isSafeInteger(value) || (value as number) < min) {\n\t\tthrow new TypeError(`${label} must be a safe integer >= ${min}`);\n\t}\n\treturn value as number;\n}\n\nfunction assertKind<K extends ReactiveCollectionStorageKind>(\n\tvalue: unknown,\n\texpected: K,\n\tlabel: string,\n): K {\n\tif (value !== expected) throw new TypeError(`${label}: kind must be ${expected}`);\n\treturn expected;\n}\n\nfunction assertArray<T = unknown>(value: unknown, label: string): readonly T[] {\n\tif (!Array.isArray(value)) throw new TypeError(`${label}: snapshot must be an array`);\n\treturn value as readonly T[];\n}\n\nfunction strictJsonIdentity(value: unknown): string {\n\treturn Array.from(strictCanonicalJsonBytes(value)).join(\",\");\n}\n\nfunction assertEntryArray<K = unknown, V = unknown>(\n\tvalue: unknown,\n\tlabel: string,\n): readonly (readonly [K, V])[] {\n\tconst entries = assertArray<unknown>(value, label);\n\tconst seen = new Set<string>();\n\tfor (const [i, entry] of entries.entries()) {\n\t\tif (!Array.isArray(entry) || entry.length !== 2) {\n\t\t\tthrow new TypeError(`${label}: entry ${i} must be [key,value]`);\n\t\t}\n\t\tconst key = strictJsonIdentity(entry[0]);\n\t\tif (seen.has(key)) throw new TypeError(`${label}: entry ${i} duplicates an earlier key`);\n\t\tseen.add(key);\n\t}\n\treturn entries as readonly (readonly [K, V])[];\n}\n\nfunction assertIndexRows<K = unknown, V = unknown>(\n\tvalue: unknown,\n\tlabel: string,\n): readonly IndexRow<K, V>[] {\n\tconst rows = assertArray<unknown>(value, label);\n\tconst seen = new Set<string>();\n\tfor (const [i, row] of rows.entries()) {\n\t\tif (!isRecord(row)) throw new TypeError(`${label}: row ${i} must be an object`);\n\t\tassertKeys(row, [\"primary\", \"secondary\", \"value\"], `${label} row`);\n\t\tconst primary = strictJsonIdentity(row.primary);\n\t\tif (seen.has(primary)) {\n\t\t\tthrow new TypeError(`${label}: row ${i} duplicates an earlier primary`);\n\t\t}\n\t\tseen.add(primary);\n\t}\n\treturn rows as readonly IndexRow<K, V>[];\n}\n\n/** Build the default D161 snapshot key for a storage prefix. */\nexport function collectionSnapshotKey(storagePrefix = \"reactive-collection\"): string {\n\tif (storagePrefix.length === 0) throw new TypeError(\"storagePrefix must be non-empty\");\n\treturn `${storagePrefix}/snapshot`;\n}\n\n/** Build a D161 strict-JSON snapshot frame before validation/encoding. */\nexport function reactiveCollectionSnapshotFrame<K extends ReactiveCollectionStorageKind, S>(\n\tkind: K,\n\tsnapshot: S,\n\topts: { readonly changeCursor?: number } = {},\n): ReactiveCollectionSnapshotFrame<K, S> {\n\tconst changeCursor = opts.changeCursor ?? -1;\n\tif (!Number.isSafeInteger(changeCursor) || changeCursor < -1) {\n\t\tthrow new RangeError(\"reactive collection snapshot changeCursor must be a safe integer >= -1\");\n\t}\n\treturn {\n\t\tformat: REACTIVE_COLLECTION_SNAPSHOT_FORMAT,\n\t\tversion: REACTIVE_COLLECTION_FRAME_VERSION,\n\t\tkind,\n\t\tchangeCursor,\n\t\tsnapshot,\n\t};\n}\n\n/** Build a D161 strict-JSON change frame before validation/encoding. */\nexport function reactiveCollectionChangeFrame<K extends ReactiveCollectionStorageKind, C>(\n\tkind: K,\n\tchange: C,\n): ReactiveCollectionChangeFrame<K, C> {\n\treturn {\n\t\tformat: REACTIVE_COLLECTION_CHANGE_FORMAT,\n\t\tversion: REACTIVE_COLLECTION_FRAME_VERSION,\n\t\tkind,\n\t\tchange,\n\t};\n}\n\n/** Validate a D161 snapshot frame and reject non-strict-JSON payloads honestly. */\nexport function assertReactiveCollectionSnapshotFrame<\n\tK extends ReactiveCollectionStorageKind,\n\tS = unknown,\n>(value: unknown, expectedKind: K): ReactiveCollectionSnapshotFrame<K, S> {\n\tif (!isRecord(value)) throw new TypeError(\"reactive collection snapshot frame must be an object\");\n\tassertKeys(value, [\"changeCursor\", \"format\", \"kind\", \"snapshot\", \"version\"], \"snapshot frame\");\n\tif (value.format !== REACTIVE_COLLECTION_SNAPSHOT_FORMAT) {\n\t\tthrow new TypeError(\"snapshot frame: invalid format\");\n\t}\n\tif (value.version !== REACTIVE_COLLECTION_FRAME_VERSION) {\n\t\tthrow new TypeError(\"snapshot frame: invalid version\");\n\t}\n\tassertKind(value.kind, expectedKind, \"snapshot frame\");\n\tassertSafeInteger(value.changeCursor, \"snapshot frame changeCursor\", -1);\n\tstrictJsonCodecFor<unknown>().encode(value);\n\treturn value as unknown as ReactiveCollectionSnapshotFrame<K, S>;\n}\n\n/** Validate a D161 change frame and reject non-strict-JSON payloads honestly. */\nexport function assertReactiveCollectionChangeFrame<\n\tK extends ReactiveCollectionStorageKind,\n\tC = unknown,\n>(value: unknown, expectedKind: K): ReactiveCollectionChangeFrame<K, C> {\n\tif (!isRecord(value)) throw new TypeError(\"reactive collection change frame must be an object\");\n\tassertKeys(value, [\"change\", \"format\", \"kind\", \"version\"], \"change frame\");\n\tif (value.format !== REACTIVE_COLLECTION_CHANGE_FORMAT) {\n\t\tthrow new TypeError(\"change frame: invalid format\");\n\t}\n\tif (value.version !== REACTIVE_COLLECTION_FRAME_VERSION) {\n\t\tthrow new TypeError(\"change frame: invalid version\");\n\t}\n\tassertKind(value.kind, expectedKind, \"change frame\");\n\tif (!Object.hasOwn(value, \"change\")) throw new TypeError(\"change frame: change is required\");\n\tstrictJsonCodecFor<unknown>().encode(value);\n\treturn value as unknown as ReactiveCollectionChangeFrame<K, C>;\n}\n\n/** Codec for D161 snapshot frames with strict JSON validation on both encode and decode. */\nexport function reactiveCollectionSnapshotFrameCodec<\n\tK extends ReactiveCollectionStorageKind,\n\tS = unknown,\n>(kind: K): Codec<ReactiveCollectionSnapshotFrame<K, S>> {\n\tconst codec = strictJsonCodecFor<unknown>();\n\treturn {\n\t\tencode(value) {\n\t\t\treturn codec.encode(assertReactiveCollectionSnapshotFrame<K, S>(value, kind));\n\t\t},\n\t\tdecode(bytes) {\n\t\t\treturn assertReactiveCollectionSnapshotFrame<K, S>(codec.decode(bytes), kind);\n\t\t},\n\t};\n}\n\n/** Codec for D161 change frames with strict JSON validation on both encode and decode. */\nexport function reactiveCollectionChangeFrameCodec<\n\tK extends ReactiveCollectionStorageKind,\n\tC = unknown,\n>(kind: K): Codec<ReactiveCollectionChangeFrame<K, C>> {\n\tconst codec = strictJsonCodecFor<unknown>();\n\treturn {\n\t\tencode(value) {\n\t\t\treturn codec.encode(assertReactiveCollectionChangeFrame<K, C>(value, kind));\n\t\t},\n\t\tdecode(bytes) {\n\t\t\treturn assertReactiveCollectionChangeFrame<K, C>(codec.decode(bytes), kind);\n\t\t},\n\t};\n}\n\nfunction assertListChange<T>(value: unknown): ListChange<T> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveList change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"append\":\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveList append.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"value\"], \"reactiveList append\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"appendMany\":\n\t\t\tassertKeys(value, [\"kind\", \"values\"], \"reactiveList appendMany\");\n\t\t\tassertArray<T>(value.values, \"reactiveList appendMany.values\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"insert\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"value\"], \"reactiveList insert\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList insert.index\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"insertMany\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"values\"], \"reactiveList insertMany\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList insertMany.index\", 0);\n\t\t\tassertArray<T>(value.values, \"reactiveList insertMany.values\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"pop\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"value\"], \"reactiveList pop\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList pop.index\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"trimHead\":\n\t\t\tassertKeys(value, [\"kind\", \"n\"], \"reactiveList trimHead\");\n\t\t\tassertSafeInteger(value.n, \"reactiveList trimHead.n\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveList clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveList clear.count\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveList change kind ${value.kind}`);\n\t}\n}\n\nfunction assertLogChange<T>(value: unknown): LogChange<T> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveLog change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"append\":\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveLog append.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"value\"], \"reactiveLog append\");\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"appendMany\":\n\t\t\tassertKeys(value, [\"kind\", \"values\"], \"reactiveLog appendMany\");\n\t\t\tassertArray<T>(value.values, \"reactiveLog appendMany.values\");\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"trimHead\":\n\t\t\tassertKeys(value, [\"kind\", \"n\"], \"reactiveLog trimHead\");\n\t\t\tassertSafeInteger(value.n, \"reactiveLog trimHead.n\", 0);\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveLog clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveLog clear.count\", 0);\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveLog change kind ${value.kind}`);\n\t}\n}\n\nfunction assertMapChange<K, V>(value: unknown): MapChange<K, V> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveMap change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"set\":\n\t\t\tif (!Object.hasOwn(value, \"key\")) throw new TypeError(\"reactiveMap set.key required\");\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveMap set.value required\");\n\t\t\tassertKeys(value, [\"key\", \"kind\", \"value\"], \"reactiveMap set\");\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tcase \"delete\":\n\t\t\tif (!Object.hasOwn(value, \"key\")) throw new TypeError(\"reactiveMap delete.key required\");\n\t\t\tif (!Object.hasOwn(value, \"previous\")) {\n\t\t\t\tthrow new TypeError(\"reactiveMap delete.previous required\");\n\t\t\t}\n\t\t\tassertKeys(value, [\"key\", \"kind\", \"previous\", \"reason\"], \"reactiveMap delete\");\n\t\t\tif (\n\t\t\t\tvalue.reason !== \"expired\" &&\n\t\t\t\tvalue.reason !== \"lru-evict\" &&\n\t\t\t\tvalue.reason !== \"archived\" &&\n\t\t\t\tvalue.reason !== \"explicit\"\n\t\t\t) {\n\t\t\t\tthrow new TypeError(\"reactiveMap delete.reason is invalid\");\n\t\t\t}\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveMap clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveMap clear.count\", 0);\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveMap change kind ${value.kind}`);\n\t}\n}\n\nfunction assertIndexChange<K, V>(value: unknown): IndexChange<K, V> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveIndex change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"upsert\":\n\t\t\tif (!Object.hasOwn(value, \"primary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.primary required\");\n\t\t\t}\n\t\t\tif (!Object.hasOwn(value, \"secondary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.secondary required\");\n\t\t\t}\n\t\t\tif (!Object.hasOwn(value, \"value\"))\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"primary\", \"secondary\", \"value\"], \"reactiveIndex upsert\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"delete\":\n\t\t\tif (!Object.hasOwn(value, \"primary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex delete.primary required\");\n\t\t\t}\n\t\t\tassertKeys(value, [\"kind\", \"primary\"], \"reactiveIndex delete\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"deleteMany\":\n\t\t\tassertKeys(value, [\"kind\", \"primaries\"], \"reactiveIndex deleteMany\");\n\t\t\tassertArray<K>(value.primaries, \"reactiveIndex deleteMany.primaries\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveIndex clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveIndex clear.count\", 0);\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveIndex change kind ${value.kind}`);\n\t}\n}\n\nfunction applyListChange<T>(state: T[], change: ListChange<T>): void {\n\tswitch (change.kind) {\n\t\tcase \"append\":\n\t\t\tstate.push(change.value);\n\t\t\treturn;\n\t\tcase \"appendMany\":\n\t\t\tstate.push(...change.values);\n\t\t\treturn;\n\t\tcase \"insert\":\n\t\t\tif (change.index > state.length)\n\t\t\t\tthrow new Error(\"reactiveList insert change is out of range\");\n\t\t\tstate.splice(change.index, 0, change.value);\n\t\t\treturn;\n\t\tcase \"insertMany\":\n\t\t\tif (change.index > state.length) {\n\t\t\t\tthrow new Error(\"reactiveList insertMany change is out of range\");\n\t\t\t}\n\t\t\tstate.splice(change.index, 0, ...change.values);\n\t\t\treturn;\n\t\tcase \"pop\":\n\t\t\tif (change.index >= state.length) throw new Error(\"reactiveList pop change is out of range\");\n\t\t\tif (!strictJsonEquals(state[change.index], change.value)) {\n\t\t\t\tthrow new Error(\"reactiveList pop change value does not match current state\");\n\t\t\t}\n\t\t\tstate.splice(change.index, 1);\n\t\t\treturn;\n\t\tcase \"trimHead\":\n\t\t\tif (change.n > state.length) throw new Error(\"reactiveList trimHead change is out of range\");\n\t\t\tstate.splice(0, change.n);\n\t\t\treturn;\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveList clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction strictJsonEquals(a: unknown, b: unknown): boolean {\n\tconst left = strictCanonicalJsonBytes(a);\n\tconst right = strictCanonicalJsonBytes(b);\n\tif (left.byteLength !== right.byteLength) return false;\n\tfor (let i = 0; i < left.byteLength; i += 1) if (left[i] !== right[i]) return false;\n\treturn true;\n}\n\nfunction findJsonIndex<T>(\n\tvalues: readonly T[],\n\tmatch: (value: T) => unknown,\n\tkey: unknown,\n\tlabel: string,\n): number {\n\tlet found = -1;\n\tfor (let i = 0; i < values.length; i += 1) {\n\t\tif (strictJsonEquals(match(values[i] as T), key)) {\n\t\t\tif (found !== -1) throw new Error(`${label} duplicate JSON key in restore state`);\n\t\t\tfound = i;\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction cmpOrd(a: unknown, b: unknown): number {\n\tif (a === b) return 0;\n\tconst ta = typeof a;\n\tif (\n\t\tta === typeof b &&\n\t\t(ta === \"number\" || ta === \"string\" || ta === \"boolean\" || ta === \"bigint\")\n\t) {\n\t\tconst ax = a as number | string | bigint | boolean;\n\t\tconst bx = b as number | string | bigint | boolean;\n\t\treturn ax < bx ? -1 : ax > bx ? 1 : 0;\n\t}\n\treturn String(a).localeCompare(String(b));\n}\n\nfunction applyLogChange<T>(state: T[], change: LogChange<T>): void {\n\tswitch (change.kind) {\n\t\tcase \"append\":\n\t\t\tstate.push(change.value);\n\t\t\treturn;\n\t\tcase \"appendMany\":\n\t\t\tstate.push(...change.values);\n\t\t\treturn;\n\t\tcase \"trimHead\":\n\t\t\tif (change.n > state.length) throw new Error(\"reactiveLog trimHead change is out of range\");\n\t\t\tstate.splice(0, change.n);\n\t\t\treturn;\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveLog clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction applyMapChange<K, V>(state: Array<readonly [K, V]>, change: MapChange<K, V>): void {\n\tswitch (change.kind) {\n\t\tcase \"set\": {\n\t\t\tconst index = findJsonIndex(state, ([key]) => key, change.key, \"reactiveMap\");\n\t\t\tif (index === -1) state.push([change.key, change.value] as const);\n\t\t\telse state[index] = [change.key, change.value] as const;\n\t\t\treturn;\n\t\t}\n\t\tcase \"delete\": {\n\t\t\tconst index = findJsonIndex(state, ([key]) => key, change.key, \"reactiveMap\");\n\t\t\tif (index === -1) throw new Error(\"reactiveMap delete change key is missing\");\n\t\t\tif (!strictJsonEquals(state[index]?.[1], change.previous)) {\n\t\t\t\tthrow new Error(\"reactiveMap delete change previous value does not match current state\");\n\t\t\t}\n\t\t\tstate.splice(index, 1);\n\t\t\treturn;\n\t\t}\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveMap clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction sortIndexRows<K, V>(state: Array<IndexRow<K, V>>): void {\n\tstate.sort((a, b) => {\n\t\tconst bySecondary = cmpOrd(a.secondary, b.secondary);\n\t\treturn bySecondary === 0 ? cmpOrd(a.primary, b.primary) : bySecondary;\n\t});\n}\n\nfunction applyIndexChange<K, V>(state: Array<IndexRow<K, V>>, change: IndexChange<K, V>): void {\n\tswitch (change.kind) {\n\t\tcase \"upsert\": {\n\t\t\tconst index = findJsonIndex(state, (row) => row.primary, change.primary, \"reactiveIndex\");\n\t\t\tconst row: IndexRow<K, V> = {\n\t\t\t\tprimary: change.primary,\n\t\t\t\tsecondary: change.secondary,\n\t\t\t\tvalue: change.value,\n\t\t\t};\n\t\t\tif (index === -1) state.push(row);\n\t\t\telse state[index] = row;\n\t\t\tsortIndexRows(state);\n\t\t\treturn;\n\t\t}\n\t\tcase \"delete\": {\n\t\t\tconst index = findJsonIndex(state, (row) => row.primary, change.primary, \"reactiveIndex\");\n\t\t\tif (index === -1) throw new Error(\"reactiveIndex delete change primary is missing\");\n\t\t\tstate.splice(index, 1);\n\t\t\treturn;\n\t\t}\n\t\tcase \"deleteMany\": {\n\t\t\tfor (const primary of change.primaries) {\n\t\t\t\tconst index = findJsonIndex(state, (row) => row.primary, primary, \"reactiveIndex\");\n\t\t\t\tif (index === -1) {\n\t\t\t\t\tthrow new Error(\"reactiveIndex deleteMany change primary is missing\");\n\t\t\t\t}\n\t\t\t\tstate.splice(index, 1);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveIndex clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction finishState<K extends ReactiveCollectionStorageKind, T>(\n\tkind: K,\n\tstate: T[],\n\tsnapshotFound: boolean,\n\tsnapshotCursor: number,\n\tapplied: number,\n\tcursor: number,\n): ReactiveCollectionRestoreState<K, readonly T[]> {\n\treturn {\n\t\tkind,\n\t\tstate,\n\t\tsource: snapshotFound\n\t\t\t? applied > 0\n\t\t\t\t? \"snapshot+changes\"\n\t\t\t\t: \"snapshot\"\n\t\t\t: applied > 0\n\t\t\t\t? \"changes\"\n\t\t\t\t: \"empty\",\n\t\tsnapshot: { found: snapshotFound, changeCursor: snapshotCursor },\n\t\tchanges: { applied, cursor },\n\t};\n}\n\nfunction loadState<K extends ReactiveCollectionStorageKind, T, C>(\n\tkind: K,\n\topts: LoadReactiveCollectionStateOptions,\n\tassertSnapshot: (value: unknown) => readonly T[],\n\tassertChange: (value: unknown) => C,\n\tapplyChange: (state: T[], change: C) => void,\n): Promise<ReactiveCollectionRestoreState<K, readonly T[]>> {\n\tconst key = opts.snapshotKey ?? collectionSnapshotKey(opts.storagePrefix);\n\treturn opts.snapshotStore.get(key).then((snapshotValue) => {\n\t\tlet snapshotFound = false;\n\t\tlet snapshotCursor = -1;\n\t\tlet state: T[] = [];\n\n\t\tif (snapshotValue !== undefined) {\n\t\t\tconst frame = assertReactiveCollectionSnapshotFrame<K, readonly T[]>(snapshotValue, kind);\n\t\t\tstate = [...assertSnapshot(frame.snapshot)];\n\t\t\tsnapshotFound = true;\n\t\t\tsnapshotCursor = frame.changeCursor;\n\t\t}\n\n\t\tif (opts.changeLog === undefined) {\n\t\t\treturn finishState(kind, state, snapshotFound, snapshotCursor, 0, snapshotCursor);\n\t\t}\n\n\t\treturn opts.changeLog.read({ after: snapshotCursor }).then((entries) => {\n\t\t\tlet applied = 0;\n\t\t\tlet cursor = snapshotCursor;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst expectedSeq = cursor + 1;\n\t\t\t\tif (!Number.isSafeInteger(entry.seq) || entry.seq !== expectedSeq) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`reactive collection change log is non-contiguous: expected seq ${expectedSeq}, got ${entry.seq}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst frame = assertReactiveCollectionChangeFrame<K, C>(entry.value, kind);\n\t\t\t\tconst change = assertChange(frame.change);\n\t\t\t\tapplyChange(state, change);\n\t\t\t\tapplied += 1;\n\t\t\t\tcursor = entry.seq;\n\t\t\t}\n\t\t\treturn finishState(kind, state, snapshotFound, snapshotCursor, applied, cursor);\n\t\t});\n\t});\n}\n\n/** D161 passive load/fold for reactiveList; reads storage but never mutates graph topology. */\nexport function loadReactiveListState<T = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveListRestoreState<T>> {\n\treturn loadState<\"reactiveList\", T, ListChange<T>>(\n\t\t\"reactiveList\",\n\t\topts,\n\t\t(value) => assertArray<T>(value, \"reactiveList snapshot\"),\n\t\tassertListChange,\n\t\tapplyListChange,\n\t);\n}\n\n/** D161 passive load/fold for reactiveLog; reads storage but never mutates graph topology. */\nexport function loadReactiveLogState<T = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveLogRestoreState<T>> {\n\treturn loadState<\"reactiveLog\", T, LogChange<T>>(\n\t\t\"reactiveLog\",\n\t\topts,\n\t\t(value) => assertArray<T>(value, \"reactiveLog snapshot\"),\n\t\tassertLogChange,\n\t\tapplyLogChange,\n\t);\n}\n\n/** D161 passive load/fold scaffold for reactiveMap; synchronous policy restore is deferred. */\nexport function loadReactiveMapState<K = unknown, V = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveMapRestoreState<K, V>> {\n\treturn loadState<\"reactiveMap\", readonly [K, V], MapChange<K, V>>(\n\t\t\"reactiveMap\",\n\t\topts,\n\t\t(value) => assertEntryArray<K, V>(value, \"reactiveMap snapshot\"),\n\t\tassertMapChange,\n\t\tapplyMapChange,\n\t);\n}\n\n/** D161 passive load/fold scaffold for reactiveIndex; key-codec restore is deferred. */\nexport function loadReactiveIndexState<K = unknown, V = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveIndexRestoreState<K, V>> {\n\treturn loadState<\"reactiveIndex\", IndexRow<K, V>, IndexChange<K, V>>(\n\t\t\"reactiveIndex\",\n\t\topts,\n\t\t(value) => assertIndexRows<K, V>(value, \"reactiveIndex snapshot\"),\n\t\tassertIndexChange,\n\t\tapplyIndexChange,\n\t);\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport {\n\ttype ReactiveIndex,\n\ttype ReactiveIndexOptions,\n\ttype ReactiveList,\n\ttype ReactiveListOptions,\n\ttype ReactiveLog,\n\ttype ReactiveLogOptions,\n\ttype ReactiveMap,\n\ttype ReactiveMapOptions,\n\trestoreReactiveIndex,\n\trestoreReactiveList,\n\trestoreReactiveLog,\n\trestoreReactiveMap,\n} from \"../data-structures/index.js\";\nimport type {\n\tIndexChange,\n\tListChange,\n\tLogChange,\n\tMapChange,\n} from \"../graph/data-structures/change.js\";\nimport type { IndexRow } from \"../graph/data-structures/reactive-index.js\";\nimport { assertGraphLocalNode, type Graph, type StateNode } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport type {\n\tAppendLogEntry,\n\tAppendLogStorageTier,\n\tKvStorageTier,\n\tLoadReactiveCollectionStateOptions,\n\tReactiveCollectionChangeFrame,\n\tReactiveCollectionSnapshotFrame,\n\tReactiveIndexRestoreState,\n\tReactiveListRestoreState,\n\tReactiveLogRestoreState,\n\tReactiveMapRestoreState,\n} from \"../storage/index.js\";\nimport {\n\tassertReactiveCollectionChangeFrame,\n\tassertReactiveCollectionSnapshotFrame,\n\tcollectionSnapshotKey,\n\tloadReactiveIndexState,\n\tloadReactiveListState,\n\tloadReactiveLogState,\n\tloadReactiveMapState,\n\treactiveCollectionChangeFrame,\n\treactiveCollectionSnapshotFrame,\n} from \"../storage/index.js\";\n\ntype PersistableKind = \"reactiveList\" | \"reactiveLog\" | \"reactiveMap\" | \"reactiveIndex\";\ntype PersistableChange<T, K extends PersistableKind> = K extends \"reactiveList\"\n\t? ListChange<T>\n\t: K extends \"reactiveLog\"\n\t\t? LogChange<T>\n\t\t: K extends \"reactiveMap\"\n\t\t\t? MapChange<unknown, T>\n\t\t\t: IndexChange<unknown, T>;\ntype PersistableCollection<T, K extends PersistableKind> = K extends \"reactiveList\"\n\t? ReactiveList<T>\n\t: K extends \"reactiveLog\"\n\t\t? ReactiveLog<T>\n\t\t: K extends \"reactiveMap\"\n\t\t\t? ReactiveMap<unknown, T>\n\t\t\t: ReactiveIndex<unknown, T>;\n\n/** D161 adapter write-progress cursor; this is not a domain replay or wire-bridge cursor. */\nexport interface ReactiveCollectionPersistenceCursor {\n\treadonly kind: \"persistence.cursor\";\n\treadonly collection: PersistableKind;\n\treadonly changeSeq: number;\n\treadonly snapshotWrites: number;\n\treadonly changeWrites: number;\n}\n\n/** D161 graph-visible persistence sidecar status fact. */\nexport interface ReactiveCollectionPersistenceStatus {\n\treadonly state: \"starting\" | \"ready\" | \"flushing\" | \"errored\" | \"disposed\";\n\treadonly pending: number;\n\treadonly writes: number;\n\treadonly errors: number;\n\treadonly cursor: ReactiveCollectionPersistenceCursor;\n}\n\n/** D161 graph-visible persistence sidecar error fact. */\nexport interface ReactiveCollectionPersistenceError {\n\treadonly phase: \"snapshot\" | \"change\";\n\treadonly message: string;\n\treadonly cursor: ReactiveCollectionPersistenceCursor;\n}\n\n/** Options for the D161 graph-bound persistence sidecar over a reactive collection. */\nexport interface PersistReactiveCollectionOptions<K extends PersistableKind = PersistableKind> {\n\treadonly kind: K;\n\treadonly name?: string;\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n\t/** Adapter write cursor seed for wrappers that already folded a change log. */\n\treadonly initialChangeCursor?: number;\n\t/** Default true: write one durable baseline when the adapter attaches. */\n\treadonly snapshotOnAttach?: boolean;\n\t/** Optional snapshot cadence. Manual snapshots remain available via handle.snapshot(). */\n\treadonly snapshotEveryChanges?: number;\n}\n\n/** D161 sidecar controls; flush waits for queued storage promises to settle, not fsync. */\nexport interface ReactiveCollectionPersistenceHandle {\n\treadonly ready: StateNode<boolean>;\n\treadonly status: StateNode<ReactiveCollectionPersistenceStatus>;\n\treadonly error: StateNode<ReactiveCollectionPersistenceError | null>;\n\treadonly cursor: StateNode<ReactiveCollectionPersistenceCursor>;\n\tflush(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n\tsnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n\tdispose(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n}\n\ninterface QueueItem {\n\treadonly phase: \"snapshot\" | \"change\" | \"flush\" | \"dispose\";\n\treadonly done?: (status: ReactiveCollectionPersistenceStatus) => void;\n\trun(): void | PromiseLike<void>;\n}\n\nfunction emptyCursor(collection: PersistableKind): ReactiveCollectionPersistenceCursor {\n\treturn {\n\t\tkind: \"persistence.cursor\",\n\t\tcollection,\n\t\tchangeSeq: -1,\n\t\tsnapshotWrites: 0,\n\t\tchangeWrites: 0,\n\t};\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction validateSnapshotEveryChanges(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new RangeError(\"snapshotEveryChanges must be a positive safe integer\");\n\t}\n\treturn value;\n}\n\nfunction validateInitialChangeCursor(value: number | undefined): number {\n\tif (value === undefined) return -1;\n\tif (!Number.isSafeInteger(value) || value < -1) {\n\t\tthrow new RangeError(\"initialChangeCursor must be a safe integer >= -1\");\n\t}\n\treturn value;\n}\n\nfunction statusOf(\n\tstate: ReactiveCollectionPersistenceStatus[\"state\"],\n\tpending: number,\n\twrites: number,\n\terrors: number,\n\tcursor: ReactiveCollectionPersistenceCursor,\n): ReactiveCollectionPersistenceStatus {\n\treturn { state, pending, writes, errors, cursor };\n}\n\nfunction dataOf<C>(msg: Message): C | undefined {\n\treturn msg[0] === \"DATA\" ? (msg[1] as C) : undefined;\n}\n\n/**\n * D161 graph-bound sidecar over an existing collection. It writes passive storage frames and\n * exposes adapter progress as graph-visible DATA facts; it never restores or mutates the collection.\n */\nexport function persistReactiveCollection<T, K extends PersistableKind>(\n\tgraph: Graph,\n\tcollection: PersistableCollection<T, K>,\n\topts: PersistReactiveCollectionOptions<K>,\n): ReactiveCollectionPersistenceHandle {\n\tconst kind = opts.kind;\n\tconst name = opts.name ?? `${kind}.persistence`;\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(opts.storagePrefix ?? name);\n\tconst snapshotEveryChanges = validateSnapshotEveryChanges(opts.snapshotEveryChanges);\n\tassertGraphLocalNode(graph, collection.delta as Node<unknown>, `${name}.collection.delta`);\n\tassertGraphLocalNode(graph, collection.snapshot as Node<unknown>, `${name}.collection.snapshot`);\n\n\tlet cursorValue = {\n\t\t...emptyCursor(kind),\n\t\tchangeSeq: validateInitialChangeCursor(opts.initialChangeCursor),\n\t};\n\tlet statusValue = statusOf(\"starting\", 0, 0, 0, cursorValue);\n\tlet errorCount = 0;\n\tlet writes = 0;\n\tlet observedChangesSinceSnapshot = 0;\n\tlet running = false;\n\tlet disposed = false;\n\tlet disposeRequested = false;\n\tlet subscribing = true;\n\tlet stop: (() => void) | undefined;\n\tconst queue: QueueItem[] = [];\n\n\tconst ready = graph.state(false, { name: `${name}/ready` });\n\tconst status = graph.state<ReactiveCollectionPersistenceStatus>(statusValue, {\n\t\tname: `${name}/status`,\n\t});\n\tconst error = graph.state<ReactiveCollectionPersistenceError | null>(null, {\n\t\tname: `${name}/error`,\n\t});\n\tconst cursor = graph.state<ReactiveCollectionPersistenceCursor>(cursorValue, {\n\t\tname: `${name}/cursor`,\n\t});\n\n\tfunction publish(state: ReactiveCollectionPersistenceStatus[\"state\"]): void {\n\t\tconst nextState = statusValue.state === \"errored\" && state !== \"disposed\" ? \"errored\" : state;\n\t\tstatusValue = statusOf(\n\t\t\tnextState,\n\t\t\tqueue.length + (running ? 1 : 0),\n\t\t\twrites,\n\t\t\terrorCount,\n\t\t\tcursorValue,\n\t\t);\n\t\tcursor.set(cursorValue);\n\t\tstatus.set(statusValue);\n\t\tif (nextState === \"ready\") ready.set(true);\n\t\tif (nextState === \"errored\" || nextState === \"disposed\") ready.set(false);\n\t}\n\n\tfunction report(phase: \"snapshot\" | \"change\", caught: unknown): void {\n\t\terrorCount += 1;\n\t\tconst fact = { phase, message: errorMessage(caught), cursor: cursorValue };\n\t\terror.set(fact);\n\t}\n\n\tfunction callDone(done: QueueItem[\"done\"]): void {\n\t\ttry {\n\t\t\tdone?.(statusValue);\n\t\t} catch {\n\t\t\t// Done callbacks are advisory barriers; user code must not wedge the adapter queue.\n\t\t}\n\t}\n\n\tfunction finish(item: QueueItem): void {\n\t\tif (item.phase === \"dispose\") {\n\t\t\tdisposed = true;\n\t\t\trunning = false;\n\t\t\tpublish(\"disposed\");\n\t\t} else if (statusValue.state !== \"errored\") {\n\t\t\trunning = false;\n\t\t\tpublish(\"ready\");\n\t\t} else {\n\t\t\trunning = false;\n\t\t\tpublish(\"errored\");\n\t\t}\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction fail(item: QueueItem, caught: unknown): void {\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") report(item.phase, caught);\n\t\trunning = false;\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") publish(\"errored\");\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction chainThenable(item: QueueItem, value: unknown): boolean {\n\t\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return false;\n\t\tlet then: unknown;\n\t\ttry {\n\t\t\tthen = (value as { then?: unknown }).then;\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn true;\n\t\t}\n\t\tif (typeof then !== \"function\") return false;\n\t\tlet settled = false;\n\t\tconst settle = (next: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tnext();\n\t\t};\n\t\ttry {\n\t\t\t(then as (onFulfilled: () => void, onRejected: (error: unknown) => void) => unknown).call(\n\t\t\t\tvalue,\n\t\t\t\t() => settle(() => finish(item)),\n\t\t\t\t(caught) => settle(() => fail(item, caught)),\n\t\t\t);\n\t\t} catch (caught) {\n\t\t\tsettle(() => fail(item, caught));\n\t\t}\n\t\treturn true;\n\t}\n\n\tfunction enqueue(item: QueueItem): void {\n\t\tif (disposed || (disposeRequested && item.phase !== \"dispose\" && item.phase !== \"flush\")) {\n\t\t\tcallDone(item.done);\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(item);\n\t\tdrain();\n\t}\n\n\tfunction drain(): void {\n\t\tif (running) return;\n\t\tconst item = queue.shift();\n\t\tif (item === undefined) return;\n\t\trunning = true;\n\t\tpublish(\n\t\t\titem.phase === \"flush\" ? \"flushing\" : statusValue.state === \"starting\" ? \"starting\" : \"ready\",\n\t\t);\n\t\tlet result: void | PromiseLike<void>;\n\t\ttry {\n\t\t\tresult = item.run();\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn;\n\t\t}\n\t\tif (chainThenable(item, result)) return;\n\t\tfinish(item);\n\t}\n\n\tfunction enqueueSnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\tconst snapshot = collectionSnapshot(collection, kind);\n\t\tobservedChangesSinceSnapshot = 0;\n\t\tenqueue({\n\t\t\tphase: \"snapshot\",\n\t\t\tdone,\n\t\t\trun() {\n\t\t\t\tconst frame: ReactiveCollectionSnapshotFrame<K, readonly unknown[]> =\n\t\t\t\t\treactiveCollectionSnapshotFrame(kind, snapshot, {\n\t\t\t\t\t\tchangeCursor: cursorValue.changeSeq,\n\t\t\t\t\t});\n\t\t\t\tassertReactiveCollectionSnapshotFrame(frame, kind);\n\t\t\t\treturn opts.snapshotStore.set(snapshotKey, frame).then(() => {\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tsnapshotWrites: cursorValue.snapshotWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction enqueueChange(change: PersistableChange<T, K>): void {\n\t\tconst changeLog = opts.changeLog;\n\t\tif (changeLog === undefined) return;\n\t\tenqueue({\n\t\t\tphase: \"change\",\n\t\t\trun() {\n\t\t\t\tconst frame: ReactiveCollectionChangeFrame<\n\t\t\t\t\tPersistableKind,\n\t\t\t\t\tPersistableChange<T, K>\n\t\t\t\t> = reactiveCollectionChangeFrame(kind, change);\n\t\t\t\tassertReactiveCollectionChangeFrame(frame, kind);\n\t\t\t\treturn changeLog.append(frame).then((written) => {\n\t\t\t\t\tconst entry = written as AppendLogEntry<\n\t\t\t\t\t\tReactiveCollectionChangeFrame<PersistableKind, PersistableChange<T, K>>\n\t\t\t\t\t>;\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tchangeSeq: entry.seq,\n\t\t\t\t\t\tchangeWrites: cursorValue.changeWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction cancelQueuedForDispose(): void {\n\t\tconst pending = queue.splice(0);\n\t\tfor (const item of pending) callDone(item.done);\n\t}\n\n\tstop = (collection.delta as Node<PersistableChange<T, K>>).subscribe(\n\t\t(msg: Message, delivery?: DeliveryMeta) => {\n\t\t\tif (disposeRequested) return;\n\t\t\tconst change = dataOf<PersistableChange<T, K>>(msg);\n\t\t\tif (change === undefined) return;\n\t\t\tif (subscribing && delivery === undefined) return;\n\t\t\tobservedChangesSinceSnapshot += 1;\n\t\t\tenqueueChange(change);\n\t\t\tif (\n\t\t\t\tsnapshotEveryChanges !== undefined &&\n\t\t\t\tobservedChangesSinceSnapshot >= snapshotEveryChanges\n\t\t\t) {\n\t\t\t\tenqueueSnapshot();\n\t\t\t}\n\t\t},\n\t);\n\tsubscribing = false;\n\n\tif (opts.snapshotOnAttach !== false) enqueueSnapshot();\n\telse publish(\"ready\");\n\n\treturn {\n\t\tready,\n\t\tstatus,\n\t\terror,\n\t\tcursor,\n\t\tflush(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueue({ phase: \"flush\", done, run: () => undefined });\n\t\t},\n\t\tsnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed || disposeRequested) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueueSnapshot(done);\n\t\t},\n\t\tdispose(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdisposeRequested = true;\n\t\t\tstop?.();\n\t\t\tcancelQueuedForDispose();\n\t\t\tenqueue({ phase: \"dispose\", done, run: () => undefined });\n\t\t},\n\t};\n}\n\nfunction collectionSnapshot<T, K extends PersistableKind>(\n\tcollection: PersistableCollection<T, K>,\n\tkind: K,\n): readonly unknown[] {\n\tif (kind === \"reactiveMap\") {\n\t\treturn [...(collection as ReactiveMap<unknown, unknown>).toMap()];\n\t}\n\tif (kind === \"reactiveIndex\") {\n\t\treturn (collection as ReactiveIndex<unknown, unknown>).toArray();\n\t}\n\treturn (collection as ReactiveList<T> | ReactiveLog<T>).toArray();\n}\n\ntype CollectionOptionsWithoutGraphName<T> = Omit<T, \"graph\" | \"name\">;\n\n/** Options for D161 load -> restore -> persist composition for reactiveList. */\nexport interface OpenPersistentReactiveListOptions<T>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveList\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly T[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveListOptions>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveLog. */\nexport interface OpenPersistentReactiveLogOptions<T>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveLog\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly T[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveLogOptions>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveMap. */\nexport interface OpenPersistentReactiveMapOptions<K, V>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveMap\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly (readonly [K, V])[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveMapOptions<K, V>>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveIndex. */\nexport interface OpenPersistentReactiveIndexOptions<K, V>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveIndex\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly IndexRow<K, V>[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveIndexOptions>;\n}\n\n/** Return value for D161 persistent reactiveList composition. */\nexport interface PersistentReactiveList<T> {\n\treadonly collection: ReactiveList<T>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveListRestoreState<T>;\n}\n\n/** Return value for D161 persistent reactiveLog composition. */\nexport interface PersistentReactiveLog<T> {\n\treadonly collection: ReactiveLog<T>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveLogRestoreState<T>;\n}\n\n/** Return value for D161 persistent reactiveMap composition. */\nexport interface PersistentReactiveMap<K, V> {\n\treadonly collection: ReactiveMap<K, V>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveMapRestoreState<K, V>;\n}\n\n/** Return value for D161 persistent reactiveIndex composition. */\nexport interface PersistentReactiveIndex<K, V> {\n\treadonly collection: ReactiveIndex<K, V>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveIndexRestoreState<K, V>;\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveList, then sidecar persist. */\nexport function openPersistentReactiveList<T = unknown>(\n\topts: OpenPersistentReactiveListOptions<T>,\n): Promise<PersistentReactiveList<T>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveListState<T>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveList<T>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<T, \"reactiveList\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveList\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveLog, then sidecar persist. */\nexport function openPersistentReactiveLog<T = unknown>(\n\topts: OpenPersistentReactiveLogOptions<T>,\n): Promise<PersistentReactiveLog<T>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveLogState<T>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveLog<T>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<T, \"reactiveLog\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveLog\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveMap, then sidecar persist. */\nexport function openPersistentReactiveMap<K = unknown, V = unknown>(\n\topts: OpenPersistentReactiveMapOptions<K, V>,\n): Promise<PersistentReactiveMap<K, V>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveMapState<K, V>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveMap<K, V>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<V, \"reactiveMap\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveMap\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveIndex, then sidecar persist. */\nexport function openPersistentReactiveIndex<K = unknown, V = unknown>(\n\topts: OpenPersistentReactiveIndexOptions<K, V>,\n): Promise<PersistentReactiveIndex<K, V>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveIndexState<K, V>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveIndex<K, V>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<V, \"reactiveIndex\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveIndex\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n","/**\n * Framework-neutral store adapters.\n *\n * Focused framework bindings build on this tiny Node-facing layer without\n * importing framework packages into the dependency-free adapters barrel\n * (D125/D238).\n */\n\nimport type { DeliveryMeta, Sink } from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\n\n/** A minimal readable store contract shared by Svelte/Nanostores-style adapters. */\nexport interface ReadableStore<T> {\n\tget(): T | undefined;\n\tsubscribe(run: (value: T | undefined) => void): () => void;\n}\n\n/** A minimal writable store contract over a clean-slate writable node. */\nexport interface WritableStore<T> extends ReadableStore<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** React `useSyncExternalStore`-compatible shape, without importing React. */\nexport interface ExternalStore<T> {\n\tgetSnapshot(): T | undefined;\n\tgetServerSnapshot(): T | undefined;\n\tsubscribe(onStoreChange: () => void): () => void;\n}\n\n/** Object-of-nodes factory used by record subscription adapters. */\nexport type NodeRecordFactory<K extends string, R extends Record<string, unknown>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/** Zustand-compatible store API over a caller-owned clean-slate state node. */\nexport interface ZustandStoreApi<T extends object> {\n\tgetState(): T;\n\tsetState(partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean): void;\n\tgetInitialState(): T;\n\tsubscribe(listener: (state: T, prevState: T) => void): () => void;\n\tdestroy(): void;\n}\n\n/** Jotai-style atom facade over a caller-owned node. */\nexport interface JotaiAtom<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable Jotai-style atom facade over a caller-owned writable node. */\nexport interface WritableJotaiAtom<T> extends JotaiAtom<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** Nanostores-style atom facade over a caller-owned node. */\nexport interface NanoAtom<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\tlisten(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable Nanostores-style atom facade over a caller-owned writable node. */\nexport interface WritableNanoAtom<T> extends NanoAtom<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** TC39-Signals-style facade over a caller-owned node. */\nexport interface SignalLike<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable TC39-Signals-style facade over a caller-owned writable node. */\nexport interface WritableSignalLike<T> extends SignalLike<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\nexport interface SubscribeValuesOptions<T> {\n\t/** Emit the current cache snapshot immediately. `undefined` means SENTINEL/no DATA. */\n\timmediate?: boolean;\n\t/** Suppress synchronous push-on-subscribe/replay DATA. Useful for change-only store listeners. */\n\tchangesOnly?: boolean;\n\tonError?: (error: unknown) => void;\n\tonComplete?: () => void;\n\t/** Custom cache reader for wrappers that keep their own snapshot object. */\n\tgetSnapshot?: () => T | undefined;\n}\n\nexport interface WritableNode<T> extends Node<T> {\n\tset(value: T): void;\n}\n\nexport interface WritableStoreOptions<T> extends SubscribeValuesOptions<T> {\n\t/** Override writes for adapters that need a framework-owned reducer. */\n\twrite?: (node: WritableNode<T>, value: T) => void;\n}\n\n/** Read a node cache without activating it. */\nexport function nodeSnapshot<T>(node: Node<T>): T | undefined {\n\treturn node.cache as T | undefined;\n}\n\n/**\n * Subscribe to DATA values from a Node. Protocol internals stay below the adapter boundary:\n * DATA drives value listeners, ERROR/COMPLETE route to optional lifecycle callbacks.\n */\nexport function subscribeNodeValues<T>(\n\tnode: Node<T>,\n\trun: (value: T | undefined) => void,\n\topts: SubscribeValuesOptions<T> = {},\n): () => void {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tif (opts.immediate) run(read());\n\n\tlet subscribing = true;\n\tconst skipSynchronousHandshakeData = opts.changesOnly || opts.immediate;\n\tconst sink: Sink = (msg, delivery?: DeliveryMeta) => {\n\t\tswitch (msg[0]) {\n\t\t\tcase \"DATA\":\n\t\t\t\tif (skipSynchronousHandshakeData && subscribing && delivery === undefined) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\trun(msg[1] as T);\n\t\t\t\treturn;\n\t\t\tcase \"ERROR\":\n\t\t\t\topts.onError?.(msg[1]);\n\t\t\t\treturn;\n\t\t\tcase \"COMPLETE\":\n\t\t\t\topts.onComplete?.();\n\t\t\t\treturn;\n\t\t}\n\t};\n\tconst unsubscribe = node.subscribe(sink);\n\tsubscribing = false;\n\treturn unsubscribe;\n}\n\n/** Build a Svelte/Nanostores-style readable store from a clean-slate Node. */\nexport function readableStore<T>(\n\tnode: Node<T>,\n\topts: SubscribeValuesOptions<T> = {},\n): ReadableStore<T> {\n\treturn {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (run) => subscribeNodeValues(node, run, { immediate: true, ...opts }),\n\t};\n}\n\nfunction hasWritableSet<T>(node: Node<T>): node is WritableNode<T> {\n\treturn typeof (node as { set?: unknown }).set === \"function\";\n}\n\nfunction defaultWrite<T>(node: WritableNode<T>, value: T): void {\n\tnode.set(value);\n}\n\n/** Build a writable store over a StateNode or compatible clean-slate writable Node. */\nexport function writableStore<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableStore<T>;\nexport function writableStore<T>(\n\tnode: Node<T>,\n\topts: WritableStoreOptions<T> & { write: (node: WritableNode<T>, value: T) => void },\n): WritableStore<T>;\nexport function writableStore<T>(\n\tnode: Node<T>,\n\topts: WritableStoreOptions<T> = {},\n): WritableStore<T> {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tconst write = opts.write ?? (hasWritableSet(node) ? defaultWrite : undefined);\n\tif (!write) {\n\t\tthrow new TypeError(\"writableStore: node must expose set(value) or opts.write\");\n\t}\n\tconst writable = node as WritableNode<T>;\n\treturn {\n\t\tget: read,\n\t\tsubscribe: (run) => subscribeNodeValues(node, run, { immediate: true, ...opts }),\n\t\tset: (value) => write(writable, value),\n\t\tupdate: (fn) => write(writable, fn(read())),\n\t};\n}\n\n/** Build the tiny shape React's `useSyncExternalStore` expects, without importing React. */\nexport function externalStore<T>(\n\tnode: Node<T>,\n\topts: Pick<SubscribeValuesOptions<T>, \"getSnapshot\" | \"onError\" | \"onComplete\"> = {},\n): ExternalStore<T> {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\treturn {\n\t\tgetSnapshot: read,\n\t\tgetServerSnapshot: read,\n\t\tsubscribe: (onStoreChange) =>\n\t\t\tsubscribeNodeValues(node, () => onStoreChange(), {\n\t\t\t\tchangesOnly: true,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tonComplete: opts.onComplete,\n\t\t\t}),\n\t};\n}\n\n/** Build a framework-neutral keyed record store for focused framework record bindings. */\nexport function recordReadableStore<K extends string, R extends Record<string, unknown>>(\n\tkeysNode: Node<readonly K[]>,\n\tfactory: NodeRecordFactory<K, R>,\n\topts: SubscribeValuesOptions<Record<K, R>> = {},\n): ReadableStore<Record<K, R>> {\n\tconst read = () => {\n\t\tconst keys = keysNode.cache ?? [];\n\t\tconst out = {} as Record<K, R>;\n\t\tfor (const key of keys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst values = {} as R;\n\t\t\tfor (const field of Object.keys(nodes) as Array<keyof R>) {\n\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t}\n\t\t\tout[key] = values;\n\t\t}\n\t\treturn out;\n\t};\n\n\treturn {\n\t\tget: read,\n\t\tsubscribe(run) {\n\t\t\tconst entryUnsubs: Array<() => void> = [];\n\t\t\tconst cleanupEntries = () => {\n\t\t\t\tfor (const unsub of entryUnsubs.splice(0)) unsub();\n\t\t\t};\n\t\t\tconst sync = () => {\n\t\t\t\tcleanupEntries();\n\t\t\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tfor (const field of Object.keys(nodes) as Array<keyof R>) {\n\t\t\t\t\t\tentryUnsubs.push(\n\t\t\t\t\t\t\tsubscribeNodeValues(nodes[field], () => run(read()), {\n\t\t\t\t\t\t\t\tchangesOnly: true,\n\t\t\t\t\t\t\t\tonError: opts.onError,\n\t\t\t\t\t\t\t\tonComplete: opts.onComplete,\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\trun(read());\n\t\t\t};\n\t\t\tconst keysUnsub = subscribeNodeValues(keysNode, sync, {\n\t\t\t\tchangesOnly: true,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tonComplete: opts.onComplete,\n\t\t\t});\n\t\t\tsync();\n\t\t\treturn () => {\n\t\t\t\tkeysUnsub();\n\t\t\t\tcleanupEntries();\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** Build a Zustand-compatible StoreApi over a caller-owned clean-slate state node. */\nexport function zustandStore<T extends object>(\n\tnode: WritableNode<T>,\n\tinitialState?: T,\n\topts?: WritableStoreOptions<T>,\n): ZustandStoreApi<T>;\nexport function zustandStore<T extends object>(\n\tnode: Node<T>,\n\tinitialState: T | undefined,\n\topts: WritableStoreOptions<T> & { write: (node: WritableNode<T>, value: T) => void },\n): ZustandStoreApi<T>;\nexport function zustandStore<T extends object>(\n\tnode: Node<T>,\n\tinitialState: T = nodeSnapshot(node) as T,\n\topts: WritableStoreOptions<T> = {},\n): ZustandStoreApi<T> {\n\tconst listeners = new Set<() => void>();\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tconst write = opts.write ?? (hasWritableSet(node) ? defaultWrite : undefined);\n\tif (!write) {\n\t\tthrow new TypeError(\"zustandStore: node must expose set(value) or opts.write\");\n\t}\n\tconst writable = node as WritableNode<T>;\n\tconst api: ZustandStoreApi<T> = {\n\t\tgetState: () => read() as T,\n\t\tsetState(partial, replace) {\n\t\t\tconst prev = api.getState();\n\t\t\tconst next = typeof partial === \"function\" ? partial(prev) : partial;\n\t\t\twrite(writable, replace ? (next as T) : ({ ...prev, ...next } as T));\n\t\t},\n\t\tgetInitialState: () => initialState,\n\t\tsubscribe(listener) {\n\t\t\tlet prev = api.getState();\n\t\t\tconst unsub = subscribeNodeValues(\n\t\t\t\tnode,\n\t\t\t\t(value) => {\n\t\t\t\t\tconst next = value as T;\n\t\t\t\t\tlistener(next, prev);\n\t\t\t\t\tprev = next;\n\t\t\t\t},\n\t\t\t\t{ changesOnly: true, onError: opts.onError, onComplete: opts.onComplete },\n\t\t\t);\n\t\t\tlisteners.add(unsub);\n\t\t\treturn () => {\n\t\t\t\tif (!listeners.delete(unsub)) return;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\tdestroy() {\n\t\t\tfor (const unsub of [...listeners]) {\n\t\t\t\tlisteners.delete(unsub);\n\t\t\t\tunsub();\n\t\t\t}\n\t\t},\n\t};\n\treturn api;\n}\n\n/** Build a Jotai-style atom facade over a caller-owned node. */\nexport function jotaiAtom<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableJotaiAtom<T>;\nexport function jotaiAtom<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): JotaiAtom<T>;\nexport function jotaiAtom<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): JotaiAtom<T> | WritableJotaiAtom<T> {\n\tconst base: JotaiAtom<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n\n/** Build a Nanostores-style atom facade over a caller-owned node. */\nexport function nanoAtom<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableNanoAtom<T>;\nexport function nanoAtom<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): NanoAtom<T>;\nexport function nanoAtom<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): NanoAtom<T> | WritableNanoAtom<T> {\n\tconst base: NanoAtom<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { immediate: true, ...opts }),\n\t\tlisten: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n\n/** Build a TC39-Signals-style facade over a caller-owned node. */\nexport function signalFromNode<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableSignalLike<T>;\nexport function signalFromNode<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): SignalLike<T>;\nexport function signalFromNode<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): SignalLike<T> | WritableSignalLike<T> {\n\tconst base: SignalLike<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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,KAAK,OAAO,KAAK,gBAAgB,MAAM,aAAaA,KAAI,IAAI;AAAA,IAC5D,WAAW,CAAC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,WAAW,MAAM,GAAG,KAAK,CAAC;AAAA,IACzF,QAAQ,CAAC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,aAAa,MAAM,GAAG,KAAK,CAAC;AAAA,IACxF,OAAOA;AAAA,EACR;AACA,MAAI,eAAeA,KAAI,KAAK,OAAQ,KAAiC,UAAU,YAAY;AAC1F,UAAM,WAAW;AAAA,MAChBA;AAAA,MACA;AAAA,IAGD;AACA,WAAO,EAAE,GAAG,MAAM,KAAK,SAAS,KAAK,QAAQ,SAAS,OAAO;AAAA,EAC9D;AACA,SAAO;AACR;AAQO,SAAS,eACfA,OACA,OAA4D,CAAC,GACrB;AACxC,QAAM,OAAsB;AAAA,IAC3B,KAAK,OAAO,KAAK,gBAAgB,MAAM,aAAaA,KAAI,IAAI;AAAA,IAC5D,WAAW,CAAC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,aAAa,MAAM,GAAG,KAAK,CAAC;AAAA,IAC3F,OAAOA;AAAA,EACR;AACA,MAAI,eAAeA,KAAI,KAAK,OAAQ,KAAiC,UAAU,YAAY;AAC1F,UAAM,WAAW;AAAA,MAChBA;AAAA,MACA;AAAA,IAGD;AACA,WAAO,EAAE,GAAG,MAAM,KAAK,SAAS,KAAK,QAAQ,SAAS,OAAO;AAAA,EAC9D;AACA,SAAO;AACR;","names":["depCount","out","node","node","source","isDenseArrayOf","isPlainRecord","source","recordFromFrame","errorMessage","drain","records","node","source","requestId","errorMessage","node","source","timer","ctor","entry","active","node","active","initial","active","isRecord","ownKeys","assertKeys","strictJsonIdentity","isRecord","assertKeys","cmpOrd","row","errorMessage","validateSnapshotEveryChanges","statusOf","dataOf","drain","node"]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/index.ts","../../src/batch/boundary.ts","../../src/batch/batch.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/dispatcher/index.ts","../../src/node/core.ts","../../src/graph/environment.ts","../../src/node/protocol-guards.ts","../../src/node/runtime-accessors.ts","../../src/node/node-context-runtime.ts","../../src/node/node-input-runtime.ts","../../src/node/node-runtime-host.ts","../../src/node/node-lifecycle-runtime.ts","../../src/json/codec.ts","../../src/node/versioning.ts","../../src/node/node-output-runtime.ts","../../src/node/node-rewire-runtime.ts","../../src/node/node.ts","../../src/graph/checkpoint.ts","../../src/graph/operators.ts","../../src/graph/graph.ts","../../src/patterns/semantic-memory.ts","../../src/solutions/agentic-memory-shared.ts","../../src/solutions/agentic-memory-frame.ts","../../src/adapters/agentic-memory-storage.ts","../../src/graph/resilience.ts","../../src/adapters/bridge-protobuf.ts","../../src/adapters/bridge-validation.ts","../../src/adapters/bridge-remote-call.ts","../../src/adapters/bridge-projections.ts","../../src/adapters/bridge-remote-responder.ts","../../src/adapters/bridge.ts","../../src/adapters/bridge-wire-edge-group.ts","../../src/adapters/environment-outbound.ts","../../src/adapters/environment-websocket-session.ts","../../src/graph/data-structures/core.ts","../../src/graph/data-structures/reactive-index.ts","../../src/graph/policies/collection.ts","../../src/graph/data-structures/reactive-list.ts","../../src/graph/data-structures/reactive-log.ts","../../src/graph/sources.ts","../../src/graph/data-structures/reactive-map.ts","../../src/data-structures/persistence.ts","../../src/storage/reactive-collection.ts","../../src/adapters/reactive-collection-storage.ts","../../src/adapters/store.ts"],"sourcesContent":["/**\n * Graph/framework/environment adapter namespace.\n *\n * Use focused adapter subpaths for graph-bound bridges such as\n * `@graphrefly/ts/adapters/observe-storage`.\n */\n\nexport * from \"./agentic-memory-storage.js\";\nexport * from \"./bridge.js\";\nexport * from \"./bridge-wire-edge-group.js\";\nexport * from \"./environment.js\";\nexport * from \"./reactive-collection-storage.js\";\nexport * from \"./store.js\";\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Declarative batch (R-batch-coalesce / D12).\n *\n * Inside a batch, DIRTY propagates immediately but the tier-3 settle slice\n * (DATA/RESOLVED/INVALIDATE) is deferred to commit, so a shared downstream\n * recomputes ONCE after all batched sources settle. Success -> commit; a thrown\n * error -> rollback; `bctx.rollback()` is the explicit escape hatch.\n *\n * Coalescing note: this kernel coalesces multiple emits to the SAME node within\n * one batch to the latest tier-3 wave (last-value-wins). Full per-item batch-array\n * delivery (downstream fn receiving [v1..vK]) is a documented refinement — the\n * dominant use (coalescing a diamond join to one recompute) is exact here.\n */\n\nimport type { Wave } from \"../protocol/messages.js\";\nimport { dropBoundaryTasksForBatch, enterWave, exitWave } from \"./boundary.js\";\n\n/** A node target the batch can commit/rollback against (structural, avoids an import cycle). */\nexport interface BatchTarget {\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport interface BatchCtx {\n\t/** Discard all deferred emissions in this batch instead of committing. */\n\trollback(): void;\n}\n\ninterface ActiveBatch {\n\torder: BatchTarget[];\n\tdeferred: Map<BatchTarget, Wave>;\n\tcommitted: boolean;\n\trolledBack: boolean;\n}\n\nlet active: ActiveBatch | null = null;\nlet boundaryOwner: ActiveBatch | null = null;\n\nexport function currentBatch(): boolean {\n\treturn active !== null;\n}\n\nexport function currentBoundaryBatchToken(): object | undefined {\n\treturn active ?? boundaryOwner ?? undefined;\n}\n\n/**\n * Defer a node's tier-3 settle slice into the active batch. Returns true if a batch\n * captured it; false if there is no active batch (caller emits normally).\n */\nexport function deferToBatch(target: BatchTarget, tier3Wave: Wave): boolean {\n\tif (active === null) return false;\n\tif (!active.deferred.has(target)) active.order.push(target);\n\tactive.deferred.set(target, tier3Wave); // last-value coalescing\n\treturn true;\n}\n\n/**\n * Defer a topology mutation until after the active batch has committed/rolled back,\n * but only when this target has an uncommitted settle slice in the current batch.\n */\nexport function deferAfterBatchForTarget(target: BatchTarget, fn: () => void): boolean {\n\tif (active === null || !active.deferred.has(target)) return false;\n\tconst owner = active;\n\ttarget.__deferBoundary(() => {\n\t\tif (owner.committed) fn();\n\t}, owner);\n\treturn true;\n}\n\nfunction commit(b: ActiveBatch): void {\n\tconst prev = boundaryOwner;\n\tboundaryOwner = b;\n\ttry {\n\t\tfor (const target of b.order) {\n\t\t\tconst wave = b.deferred.get(target);\n\t\t\tif (wave) target.__commitBatchedWave(wave);\n\t\t}\n\t\tb.committed = true;\n\t} catch (e) {\n\t\tdropBoundaryTasksForBatch(b);\n\t\tthrow e;\n\t} finally {\n\t\tboundaryOwner = prev;\n\t}\n}\n\nfunction rollback(b: ActiveBatch): void {\n\tdropBoundaryTasksForBatch(b);\n\tfor (const target of b.order) target.__rollbackBatched();\n}\n\n/**\n * Run updates as one coalesced batch.\n *\n * @param fn - Synchronous callback that performs node updates and may call `rollback()`.\n * @returns The callback return value when the batch commits.\n * @example\n * ```ts\n * import { batch, graph } from \"@graphrefly/ts\";\n *\n * const g = graph();\n * const left = g.state(0);\n * const right = g.state(0);\n *\n * batch(() => {\n * left.set(1);\n * right.set(2);\n * });\n * ```\n * @remarks **Coalescing:** DATA/RESOLVED/INVALIDATE settle slices are deferred until commit so\n * shared downstream nodes recompute once for the batch.\n * @category core\n */\nexport function batch<R>(fn: (bctx: BatchCtx) => R): R {\n\t// Wave-owner boundary (R-rewire-deferred / D47): bracket the whole batch (fn + commit) so a\n\t// ctx.rewireNext issued by a fn that runs during COMMIT drains AFTER the commit, never on the\n\t// un-committed view. Inner waves (state.set, commit cascade) nest under this owner.\n\tenterWave();\n\ttry {\n\t\tif (active !== null) {\n\t\t\t// Nested batch joins the outer frame (one commit at the outermost exit).\n\t\t\tconst outer = active;\n\t\t\treturn fn({\n\t\t\t\trollback: () => {\n\t\t\t\t\touter.rolledBack = true;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst b: ActiveBatch = { order: [], deferred: new Map(), committed: false, rolledBack: false };\n\t\tactive = b;\n\t\tconst bctx: BatchCtx = {\n\t\t\trollback: () => {\n\t\t\t\tb.rolledBack = true;\n\t\t\t},\n\t\t};\n\t\tlet result: R;\n\t\ttry {\n\t\t\tresult = fn(bctx);\n\t\t} catch (e) {\n\t\t\tactive = null;\n\t\t\trollback(b);\n\t\t\tthrow e;\n\t\t}\n\t\tactive = null;\n\t\tif (b.rolledBack) rollback(b);\n\t\telse {\n\t\t\tcommit(b);\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\texitWave();\n\t}\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated retired handle-dispatch PoC (R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/**\n * First-class dispatcher (D21). Owns pools; graph binds to one (default = process-global,\n * D26 — the only global singleton). Pool trait is pluggable for WorkerPool/RemotePool (D20).\n */\n/** Per-handle profiling counters (D39 / R-profile). Lives on the dispatcher — the invoke\n * funnel (F-DISPATCH-ALL) — NEVER on the thin node (R-node-thin). */\nexport interface HandleStat {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n}\n\nconst statKey = (h: Handle): string => `${h.poolId}:${h.handleId}`;\n\nexport class Dispatcher {\n\tprivate pools: Pool[] = [];\n\treadonly syncPoolId: number;\n\treadonly asyncPoolId: number;\n\n\t// opt-in profile recorder (default OFF → zero overhead, F-PERF).\n\tprivate _recording = false;\n\tprivate _stats = new Map<string, HandleStat>();\n\tprivate _totalInvokes = 0;\n\n\tconstructor() {\n\t\tthis.syncPoolId = this.addPool(new PoolTable(\"sync\"));\n\t\tthis.asyncPoolId = this.addPool(new PoolTable(\"async\"));\n\t}\n\n\t/** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */\n\tsetRecording(on: boolean): void {\n\t\tthis._recording = on;\n\t}\n\t/** Reset accumulated profiling counters. */\n\tclearStats(): void {\n\t\tthis._stats.clear();\n\t\tthis._totalInvokes = 0;\n\t}\n\t/** Read a handle's accumulated counters (undefined if it never ran while recording). */\n\tstatFor(handle: Handle): HandleStat | undefined {\n\t\treturn this._stats.get(statKey(handle));\n\t}\n\t/** Total fn invocations recorded across the dispatcher. */\n\tget totalInvokes(): number {\n\t\treturn this._totalInvokes;\n\t}\n\n\taddPool(pool: Pool): number {\n\t\tconst id = this.pools.length;\n\t\tthis.pools.push(pool);\n\t\treturn id;\n\t}\n\n\t/** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */\n\tregister(fn: NodeFn, pool: PoolKind | number = \"sync\"): Handle {\n\t\tconst poolId = pool === \"sync\" ? this.syncPoolId : pool === \"async\" ? this.asyncPoolId : pool;\n\t\tconst handleId = this.pools[poolId].register(fn);\n\t\treturn { poolId, handleId };\n\t}\n\n\t/**\n\t * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any\n\t * accumulated profile stat so a reused id never inherits the previous tenant's counters.\n\t * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node\n\t * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives\n\t * activate↔deactivate and is reused on reactivation; only a rewire swaps it).\n\t */\n\tunregister(handle: Handle): void {\n\t\tthis.pools[handle.poolId].unregister(handle.handleId);\n\t\t// Drop the stat UNCONDITIONALLY (QA F2.1), not only while recording: if recording was\n\t\t// OFF at unregister time the key would linger, and a later register reusing this id (the\n\t\t// free-list) would inherit the prior tenant's counters once recording resumes. delete of\n\t\t// an absent key is a cheap no-op; unregister is off the hot invoke path (F-PERF intact).\n\t\tthis._stats.delete(statKey(handle));\n\t}\n\n\t/** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */\n\tinvoke(handle: Handle, ctx: Ctx): void {\n\t\tif (!this._recording) {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t\treturn;\n\t\t}\n\t\tthis._totalInvokes++;\n\t\tconst t0 = performance.now();\n\t\ttry {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t} finally {\n\t\t\tconst dur = (performance.now() - t0) * 1e6; // ms → ns\n\t\t\tconst key = statKey(handle);\n\t\t\tconst s = this._stats.get(key) ?? {\n\t\t\t\tinvokes: 0,\n\t\t\t\ttotalDurationNs: 0,\n\t\t\t\tlastDurationNs: 0,\n\t\t\t};\n\t\t\ts.invokes++;\n\t\t\ts.lastDurationNs = dur;\n\t\t\ts.totalDurationNs += dur;\n\t\t\tthis._stats.set(key, s);\n\t\t}\n\t}\n\n\tpoolKind(poolId: number): PoolKind {\n\t\treturn this.pools[poolId].kind;\n\t}\n}\n\n/** The only global singleton (D26). Overridable by passing an explicit dispatcher. */\nexport const defaultDispatcher = new Dispatcher();\n","import type { Ctx, Sink } from \"../ctx/types.js\";\nimport type { Dispatcher, Handle } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport { type LockId, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\nimport type { Node, Status } from \"./node.js\";\nimport type { NodeVersion, ResolvedNodeVersioningPolicy } from \"./versioning.js\";\n\nexport type NodeId = number & { readonly __nodeId: unique symbol };\n\nexport interface DepBookkeeping {\n\tbatch: Array<unknown[] | null>;\n\twaveData: unknown[][][];\n\twaveTokens: Array<object | undefined>;\n\tprev: unknown[];\n\thasData: boolean[];\n\tdirty: boolean[];\n\ttier: number[];\n\tterminal: Array<true | unknown | undefined>;\n\tterminalInput: Array<true | unknown | undefined>;\n\tunsubs: Array<() => void>;\n\tidxBoxes: Array<{ v: number }>;\n}\n\nexport interface ValueState<T> {\n\tcache: T | undefined;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasTorndown: boolean;\n\treplayRing: T[];\n}\n\nexport interface VersionState {\n\tpolicy: ResolvedNodeVersioningPolicy;\n\tvalue: NodeVersion | undefined;\n}\n\nexport interface WaveState {\n\tpending: number;\n\thasCalledFnOnce: boolean;\n\temittedDirtyThisWave: boolean;\n\temittedSettleThisWave: boolean;\n\tinsideRunWave: boolean;\n\tinDepMutation: boolean;\n\trewireRunPending: boolean;\n\tbatchDirtyOwed: boolean;\n}\n\nexport interface ControlState {\n\tpauseLockset: Set<unknown>;\n\tpausedDepWaveOccurred: boolean;\n\tpauseBuffer: Wave[];\n\tdemandOwed: PullDemand | undefined;\n\tactivePull: PullDemand | undefined;\n\tpullDirtyOwed: boolean;\n\tinDeliverDemand: boolean;\n}\n\nexport interface PrivateState {\n\tvalue: unknown;\n\tpersist: boolean;\n}\n\nexport interface CleanupHooks {\n\tonDeactivation: Array<() => void>;\n\tonInvalidate: Array<() => void>;\n}\n\nexport interface SyncCtxState {\n\tvalue: Ctx | null;\n}\n\nexport interface LifecycleState {\n\tsubscribers: Set<Sink>;\n\tactivated: boolean;\n}\n\nexport interface BoundaryTask {\n\tapply: () => void;\n\tbatchToken?: object;\n\tisReady?: () => boolean;\n}\n\nexport interface BoundaryState {\n\tqueue: BoundaryTask[];\n\thead: number;\n}\n\nexport interface NodeSlot<_T> {\n\tid: NodeId;\n\tdeps: Node<unknown>[];\n\thandle: Handle | null;\n\tpool: \"sync\" | \"async\";\n\tdispatcher: Dispatcher;\n\tenvironment: EnvironmentDrivers;\n\tpartial: boolean;\n\tterminalAsRealInput: boolean;\n\tcompleteWhenDepsComplete: boolean;\n\terrorWhenDepsError: boolean;\n\tresubscribable: boolean;\n\tresetOnTeardown: boolean;\n\tpausable: boolean | \"resumeAll\";\n\tpull: boolean;\n\tpullLock: LockId | undefined;\n\treplayN: number;\n\tdynamic: boolean;\n\tname?: string;\n\tfactory?: string;\n}\n\nexport interface NodeState<T> {\n\tdep: DepBookkeeping;\n\tlifecycle: LifecycleState;\n\tvalue: ValueState<T>;\n\tversion: VersionState;\n\twave: WaveState;\n\tcontrol: ControlState;\n\tprivateState: PrivateState;\n\thooks: CleanupHooks;\n\tsyncCtx: SyncCtxState;\n}\n\nexport class NodeCore {\n\tprivate nextId = 0;\n\tprivate readonly slots: Array<NodeSlot<unknown> | undefined> = [];\n\tprivate readonly values: Array<ValueState<unknown> | undefined> = [];\n\tprivate readonly waves: Array<WaveState | undefined> = [];\n\tprivate readonly controls: Array<ControlState | undefined> = [];\n\tprivate readonly lifecycles: Array<LifecycleState | undefined> = [];\n\tprivate readonly depStates: Array<DepBookkeeping | undefined> = [];\n\tprivate readonly privateStates: Array<PrivateState | undefined> = [];\n\tprivate readonly hooks: Array<CleanupHooks | undefined> = [];\n\tprivate readonly syncCtxs: Array<SyncCtxState | undefined> = [];\n\tprivate readonly versionStates: Array<VersionState | undefined> = [];\n\tprivate readonly boundary: BoundaryState = { queue: [], head: 0 };\n\n\tcreateSlot<T>(\n\t\tslot: Omit<NodeSlot<T>, \"id\">,\n\t\tstate: NodeState<T>,\n\t): { id: NodeId; slot: NodeSlot<T> } {\n\t\tconst id = this.nextId++ as NodeId;\n\t\tconst full = { ...slot, id };\n\t\tthis.slots[id] = full as NodeSlot<unknown>;\n\t\tthis.depStates[id] = state.dep;\n\t\tthis.lifecycles[id] = state.lifecycle;\n\t\tthis.values[id] = state.value as ValueState<unknown>;\n\t\tthis.waves[id] = state.wave;\n\t\tthis.controls[id] = state.control;\n\t\tthis.privateStates[id] = state.privateState;\n\t\tthis.hooks[id] = state.hooks;\n\t\tthis.syncCtxs[id] = state.syncCtx;\n\t\tthis.versionStates[id] = state.version;\n\t\treturn { id, slot: full };\n\t}\n\n\tget<T>(id: NodeId): NodeSlot<T> {\n\t\tconst slot = this.slots[id];\n\t\tif (slot === undefined) throw new Error(\"NodeCore: unknown node slot\");\n\t\treturn slot as NodeSlot<T>;\n\t}\n\n\tgetValue<T>(id: NodeId): ValueState<T> {\n\t\tconst value = this.values[id];\n\t\tif (value === undefined) throw new Error(\"NodeCore: unknown node value state\");\n\t\treturn value as ValueState<T>;\n\t}\n\n\tgetWave(id: NodeId): WaveState {\n\t\tconst wave = this.waves[id];\n\t\tif (wave === undefined) throw new Error(\"NodeCore: unknown node wave state\");\n\t\treturn wave;\n\t}\n\n\tgetControl(id: NodeId): ControlState {\n\t\tconst control = this.controls[id];\n\t\tif (control === undefined) throw new Error(\"NodeCore: unknown node control state\");\n\t\treturn control;\n\t}\n\n\tgetLifecycle(id: NodeId): LifecycleState {\n\t\tconst lifecycle = this.lifecycles[id];\n\t\tif (lifecycle === undefined) throw new Error(\"NodeCore: unknown node lifecycle state\");\n\t\treturn lifecycle;\n\t}\n\n\tgetDep(id: NodeId): DepBookkeeping {\n\t\tconst dep = this.depStates[id];\n\t\tif (dep === undefined) throw new Error(\"NodeCore: unknown node dep state\");\n\t\treturn dep;\n\t}\n\n\tgetPrivateState(id: NodeId): PrivateState {\n\t\tconst state = this.privateStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node private state\");\n\t\treturn state;\n\t}\n\n\tgetHooks(id: NodeId): CleanupHooks {\n\t\tconst hooks = this.hooks[id];\n\t\tif (hooks === undefined) throw new Error(\"NodeCore: unknown node cleanup hooks\");\n\t\treturn hooks;\n\t}\n\n\tgetSyncCtx(id: NodeId): SyncCtxState {\n\t\tconst state = this.syncCtxs[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node ctx state\");\n\t\treturn state;\n\t}\n\n\tgetVersion(id: NodeId): VersionState {\n\t\tconst state = this.versionStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node version state\");\n\t\treturn state;\n\t}\n\n\t/** @internal D122: release graph-owned ephemeral node runtime state from core retention. */\n\treleaseSlot(id: NodeId): void {\n\t\tthis.slots[id] = undefined;\n\t\tthis.depStates[id] = undefined;\n\t\tthis.lifecycles[id] = undefined;\n\t\tthis.values[id] = undefined;\n\t\tthis.waves[id] = undefined;\n\t\tthis.controls[id] = undefined;\n\t\tthis.privateStates[id] = undefined;\n\t\tthis.hooks[id] = undefined;\n\t\tthis.syncCtxs[id] = undefined;\n\t\tthis.versionStates[id] = undefined;\n\t}\n\n\t/** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */\n\tenqueueBoundaryTask(task: BoundaryTask): void {\n\t\tthis.boundary.queue.push(task);\n\t}\n\n\t/** @internal */\n\thasBoundaryTasks(): boolean {\n\t\treturn this.boundary.head < this.boundary.queue.length;\n\t}\n\n\t/** @internal */\n\tboundaryTaskCount(): number {\n\t\treturn this.boundary.queue.length - this.boundary.head;\n\t}\n\n\t/** @internal */\n\tshiftBoundaryTask(): BoundaryTask | undefined {\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst task = this.boundary.queue[this.boundary.head++];\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** @internal Put a not-yet-ready task back at this core's FIFO head. */\n\tunshiftBoundaryTask(task: BoundaryTask): void {\n\t\tconst remaining = this.boundary.queue.slice(this.boundary.head);\n\t\tthis.boundary.queue = [task, ...remaining];\n\t\tthis.boundary.head = 0;\n\t}\n\n\t/** @internal D110: discard all pending tasks caused by an uncommitted batch. */\n\tdropBoundaryTasksForBatch(batchToken: object): void {\n\t\tconst remaining = this.boundary.queue\n\t\t\t.slice(this.boundary.head)\n\t\t\t.filter((task) => task.batchToken !== batchToken);\n\t\tthis.boundary.queue = remaining;\n\t\tthis.boundary.head = 0;\n\t}\n}\n\nexport function makeDepBookkeeping(depCount: number): DepBookkeeping {\n\treturn {\n\t\tbatch: new Array(depCount).fill(null),\n\t\twaveData: Array.from({ length: depCount }, () => []),\n\t\twaveTokens: new Array(depCount).fill(undefined),\n\t\tprev: new Array(depCount).fill(SENTINEL),\n\t\thasData: new Array(depCount).fill(false),\n\t\tdirty: new Array(depCount).fill(false),\n\t\ttier: new Array(depCount).fill(0),\n\t\tterminal: new Array(depCount).fill(undefined),\n\t\tterminalInput: new Array(depCount).fill(undefined),\n\t\tunsubs: [],\n\t\tidxBoxes: [],\n\t};\n}\n","/**\n * Graph-owned environment driver bag (D130/D131).\n *\n * Drivers host process/network/messaging/runtime boundary work outside the synchronous wave core.\n * The bag is graph-local and is read from ctx by source/adapter bodies.\n */\n\nexport type DriverCancel = () => void;\n\nexport type DriverResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport interface ProcessCommand {\n\treadonly program: string;\n\treadonly args: readonly string[];\n\treadonly cwd?: string;\n\treadonly env?: readonly (readonly [string, string])[];\n}\n\nexport interface ProcessResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number | null;\n\treadonly signal: string | null;\n}\n\nexport interface HttpRequest {\n\treadonly method: string;\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n\treadonly body?: Uint8Array | string;\n}\n\nexport interface HttpResponse {\n\treadonly status: number;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport interface SseRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport interface SseEvent {\n\treadonly event?: string;\n\treadonly data: string;\n\treadonly id?: string;\n\treadonly retryMs?: number;\n}\n\nexport type SseDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: SseEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebSocketRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport type WebSocketEvent =\n\t| { readonly kind: \"open\" }\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\nexport interface WebSocketSend {\n\treadonly data: string | Uint8Array;\n}\n\nexport interface WebSocketSendResult {\n\treadonly sent: true;\n}\n\n/** Live WebSocket session handle for D133 SessionBundle adapters. */\nexport interface WebSocketSessionHandle {\n\tsend(\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\tclose(code?: number, reason?: string): void;\n\tcancel(): void;\n}\n\nexport type WebSocketDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebSocketEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebhookRegistration {\n\treadonly id: string;\n\treadonly method?: string;\n\treadonly path?: string;\n}\n\nexport interface WebhookEvent {\n\treadonly registrationId: string;\n\treadonly method: string;\n\treadonly path: string;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly query: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport type WebhookDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebhookEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface LocalProcessDriver {\n\trun(\n\t\tcommand: ProcessCommand,\n\t\tcallback: (result: DriverResult<ProcessResult>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalHttpDriver {\n\trequest(\n\t\trequest: HttpRequest,\n\t\tcallback: (result: DriverResult<HttpResponse>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalSseDriver {\n\tconnect(request: SseRequest, callback: (event: SseDriverEvent) => void): DriverCancel;\n}\n\nexport interface LocalWebSocketDriver {\n\tconnect(request: WebSocketRequest, callback: (event: WebSocketDriverEvent) => void): DriverCancel;\n\tsend?(\n\t\trequest: WebSocketRequest,\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\t/** Open a live bidirectional session; unlike send(), outbound messages use this same connection. */\n\tconnectSession?(\n\t\trequest: WebSocketRequest,\n\t\tcallback: (event: WebSocketDriverEvent) => void,\n\t): WebSocketSessionHandle;\n}\n\nexport interface LocalWebhookDriver {\n\tregister(\n\t\tregistration: WebhookRegistration,\n\t\tcallback: (event: WebhookDriverEvent) => void,\n\t): DriverCancel;\n}\n\nexport interface FetchResponseLike {\n\treadonly status: number;\n\treadonly headers?: { forEach?(fn: (value: string, key: string) => void): void };\n\tarrayBuffer(): PromiseLike<ArrayBuffer>;\n}\n\nexport type FetchLike = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: readonly (readonly [string, string])[];\n\t\treadonly body?: Uint8Array | string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => PromiseLike<FetchResponseLike>;\n\nexport interface WebSocketLike {\n\tsend(data: string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n\tremoveEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n}\n\nexport type WebSocketConstructorLike = new (url: string) => WebSocketLike;\n\nexport interface EnvironmentDriversInit {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n}\n\nexport class EnvironmentDrivers {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n\n\tconstructor(init: EnvironmentDriversInit = {}) {\n\t\tthis.process = init.process;\n\t\tthis.http = init.http;\n\t\tthis.sse = init.sse;\n\t\tthis.websocket = init.websocket;\n\t\tthis.webhook = init.webhook;\n\t\tObject.freeze(this);\n\t}\n\n\tstatic empty(): EnvironmentDrivers {\n\t\treturn EMPTY_ENVIRONMENT;\n\t}\n\n\twithProcess(driver: LocalProcessDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, process: driver });\n\t}\n\n\twithHttp(driver: LocalHttpDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, http: driver });\n\t}\n\n\twithSse(driver: LocalSseDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, sse: driver });\n\t}\n\n\twithWebSocket(driver: LocalWebSocketDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, websocket: driver });\n\t}\n\n\twithWebhook(driver: LocalWebhookDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, webhook: driver });\n\t}\n\n\tprocessDriver(): LocalProcessDriver | undefined {\n\t\treturn this.process;\n\t}\n\n\thttpDriver(): LocalHttpDriver | undefined {\n\t\treturn this.http;\n\t}\n\n\tsseDriver(): LocalSseDriver | undefined {\n\t\treturn this.sse;\n\t}\n\n\twebSocketDriver(): LocalWebSocketDriver | undefined {\n\t\treturn this.websocket;\n\t}\n\n\twebhookDriver(): LocalWebhookDriver | undefined {\n\t\treturn this.webhook;\n\t}\n}\n\nconst EMPTY_ENVIRONMENT = new EnvironmentDrivers();\n\nexport function fetchHttpDriver(fetchFn: FetchLike = requireGlobalFetch()): LocalHttpDriver {\n\treturn {\n\t\trequest(request, callback) {\n\t\t\tconst controller = new AbortController();\n\t\t\tvoid Promise.resolve(\n\t\t\t\tfetchFn(request.url, {\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\theaders: request.headers,\n\t\t\t\t\tbody: request.body,\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t}),\n\t\t\t).then(\n\t\t\t\tasync (response) => {\n\t\t\t\t\tconst headers: Array<readonly [string, string]> = [];\n\t\t\t\t\tresponse.headers?.forEach?.((value, key) => {\n\t\t\t\t\t\theaders.push([key, value]);\n\t\t\t\t\t});\n\t\t\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\tcallback({ ok: true, value: { status: response.status, headers, body } });\n\t\t\t\t},\n\t\t\t\t(error) => callback({ ok: false, error }),\n\t\t\t);\n\t\t\treturn () => controller.abort();\n\t\t},\n\t};\n}\n\nexport function domWebSocketDriver(\n\tWebSocketCtor: WebSocketConstructorLike = requireGlobalWebSocket(),\n): LocalWebSocketDriver {\n\treturn {\n\t\tconnect(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tsend(request, message, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet settled = false;\n\t\t\tconst finish = (result: DriverResult<WebSocketSendResult>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcallback(result);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t\tconst onOpen = () => {\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\tfinish({ ok: true, value: { sent: true } });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinish({ ok: false, error });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => finish({ ok: false, error: event });\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tconnectSession(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet active = true;\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tconst removeListeners = () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn {\n\t\t\t\tsend(message, sendCallback) {\n\t\t\t\t\tlet canceled = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: true, value: { sent: true } });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: false, error });\n\t\t\t\t\t}\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tclose(code, reason) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t},\n\t\t\t\tcancel() {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tactive = false;\n\t\t\t\t\tremoveListeners();\n\t\t\t\t\tsocket.close();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction requireGlobalFetch(): FetchLike {\n\tconst fetchFn = (globalThis as { fetch?: FetchLike }).fetch;\n\tif (fetchFn === undefined) throw new Error(\"fetchHttpDriver: global fetch is not available\");\n\treturn fetchFn;\n}\n\nfunction requireGlobalWebSocket(): WebSocketConstructorLike {\n\tconst ctor = (globalThis as { WebSocket?: WebSocketConstructorLike }).WebSocket;\n\tif (ctor === undefined) throw new Error(\"domWebSocketDriver: global WebSocket is not available\");\n\treturn ctor;\n}\n","import { isInvalidErrorPayload, type PullDemand, type Wave } from \"../protocol/messages.js\";\n\nexport function terminalView(t: unknown): unknown {\n\treturn t === undefined ? false : t;\n}\n\nexport function normalizePullDemand(demand: PullDemand): PullDemand {\n\tif (typeof demand !== \"object\" || demand === null || Array.isArray(demand)) {\n\t\tthrow new Error(\"ctx.up: PULL requires { pullId, params? } demand payload (D269)\");\n\t}\n\tconst pullId = (demand as { pullId?: unknown }).pullId;\n\tif (typeof pullId !== \"string\" && typeof pullId !== \"symbol\") {\n\t\tthrow new Error(\"ctx.up: PULL demand requires a string or symbol pullId (D269)\");\n\t}\n\tconst params = (demand as { params?: unknown }).params;\n\treturn params === undefined ? { pullId } : { pullId, params };\n}\n\nexport function validateDownPayloads(msgs: Wave): void {\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"DATA\" && m[1] === undefined) {\n\t\t\tthrow new Error(\"down: DATA requires a non-SENTINEL payload (R-data-payload)\");\n\t\t}\n\t\tif (m[0] === \"ERROR\" && isInvalidErrorPayload(m[1])) {\n\t\t\tthrow new Error(\"down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)\");\n\t\t}\n\t}\n}\n","import type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { NodeCore } from \"./core.js\";\nimport type { Node } from \"./node.js\";\nimport type { NodeCheckpointState, NodeRestoreState } from \"./types.js\";\n\ntype TopologyDepsChangedObserver = (\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n) => void;\n\nlet constructingCore: NodeCore | undefined;\nlet constructingEnvironment: EnvironmentDrivers | undefined;\nexport const ownerTokens = new WeakMap<Node<unknown>, unknown>();\nexport const topologyDepsChangedObservers = new WeakMap<\n\tNode<unknown>,\n\tTopologyDepsChangedObserver\n>();\nexport const checkpointReaders = new WeakMap<Node<unknown>, () => NodeCheckpointState>();\nexport const restoreWriters = new WeakMap<Node<unknown>, (state: NodeRestoreState) => void>();\nexport const runtimeReleasers = new WeakMap<Node<unknown>, () => void>();\nexport const runtimeQuiescenceReaders = new WeakMap<Node<unknown>, () => boolean>();\nexport const subscriberCountReaders = new WeakMap<Node<unknown>, () => number>();\nexport const activationReaders = new WeakMap<Node<unknown>, () => boolean>();\nexport const releasedNodes = new WeakSet<Node<unknown>>();\n\n/** @internal Run a Node/StateNode constructor against a graph-local core without widening the public constructor. */\nexport function withNodeCore<TNode extends Node<unknown>>(\n\tcore: NodeCore,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingCore;\n\tconstructingCore = core;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingCore = prev;\n\t}\n}\n\n/** @internal Consume the graph-local NodeCore staged by withNodeCore. */\nexport function takeConstructingNodeCore(): NodeCore | undefined {\n\tconst core = constructingCore;\n\tconstructingCore = undefined;\n\treturn core;\n}\n\n/** @internal Run a Node/StateNode constructor with graph-owned environment drivers (D130/D131). */\nexport function withEnvironmentDrivers<TNode extends Node<unknown>>(\n\tenvironment: EnvironmentDrivers,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingEnvironment;\n\tconstructingEnvironment = environment;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingEnvironment = prev;\n\t}\n}\n\n/** @internal Consume graph-owned environment drivers staged by withEnvironmentDrivers. */\nexport function takeConstructingEnvironmentDrivers(): EnvironmentDrivers | undefined {\n\tconst environment = constructingEnvironment;\n\tconstructingEnvironment = undefined;\n\treturn environment;\n}\n\n/** @internal Graph-domain ownership token for D22 intra-graph guards. */\nexport function getNodeOwner(n: Node<unknown>): unknown {\n\treturn ownerTokens.get(n);\n}\n\n/** @internal Assign graph-domain ownership after graph registration. */\nexport function setNodeOwner(n: Node<unknown>, owner: unknown): void {\n\townerTokens.set(n, owner);\n}\n\n/** @internal Graph-layer D145 topology egress hook. */\nexport function setNodeTopologyDepsChangedObserver(\n\tn: Node<unknown>,\n\tobserver: TopologyDepsChangedObserver,\n): void {\n\ttopologyDepsChangedObservers.set(n, observer);\n}\n\nexport function notifyTopologyDepsChanged(\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n): void {\n\ttopologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);\n}\n\n/** @internal Graph checkpoint inspection, kept as a module helper so Node stays method-thin. */\nexport function checkpointStateOfNode(n: Node<unknown>): NodeCheckpointState {\n\tconst read = checkpointReaders.get(n);\n\tif (read === undefined) throw new Error(\"checkpoint: unknown node state\");\n\treturn read();\n}\n\n/** @internal D94 restore commit: install runtime state without a protocol wave or subscription. */\nexport function restoreStateOfNode(n: Node<unknown>, state: NodeRestoreState): void {\n\tconst write = restoreWriters.get(n);\n\tif (write === undefined) throw new Error(\"restoreGraph: unknown node state\");\n\twrite(state);\n}\n\n/** @internal D122 graph-owned ephemeral lifecycle release. */\nexport function releaseRuntimeOfNode(n: Node<unknown>): void {\n\truntimeReleasers.get(n)?.();\n}\n\n/** @internal D124 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeQuiescentForRelease(n: Node<unknown>): boolean {\n\treturn runtimeQuiescenceReaders.get(n)?.() ?? false;\n}\n\n/** @internal D124 graph-owned release subscriber accounting. */\nexport function subscriberCountOfNode(n: Node<unknown>): number {\n\treturn subscriberCountReaders.get(n)?.() ?? 0;\n}\n\n/** @internal D124 graph-owned release internal-subscriber accounting. */\nexport function isNodeActiveForRelease(n: Node<unknown>): boolean {\n\treturn activationReaders.get(n)?.() ?? false;\n}\n\n/** @internal D122 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeReleased(n: Node<unknown>): boolean {\n\treturn releasedNodes.has(n);\n}\n","import { enterWave, exitWave } from \"../batch/boundary.js\";\nimport {\n\tCTX_DEP_CACHE,\n\tCTX_NODE_BINDING,\n\ttype Ctx,\n\ttype CtxState,\n\ttype TerminalData,\n\ttype WaveData,\n} from \"../ctx/types.js\";\nimport type { PullDemand } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport type { NodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { terminalView } from \"./protocol-guards.js\";\nimport { withEnvironmentDrivers, withNodeCore } from \"./runtime-accessors.js\";\n\nexport function nodeBuildCtx<T>(self: NodeRuntimeHost<T>): Ctx {\n\tconst kind = self._slot.handle\n\t\t? self._slot.dispatcher.poolKind(self._slot.handle.poolId)\n\t\t: \"sync\";\n\tif (kind === \"sync\") {\n\t\tif (self._syncCtx === null) self._syncCtx = self._makeCtx();\n\t\tself._refreshCtx(self._syncCtx);\n\t\treturn self._syncCtx;\n\t}\n\t// async: snapshot dep inputs so a deferred late-emit reads this wave's view.\n\treturn self._makeCtx({\n\t\twaveData: self._dep.waveData.map((waves) => waves.map((w) => [...w])),\n\t\tterminal: self._dep.terminalInput.map(terminalView),\n\t\tlatest: [...self._dep.prev],\n\t});\n}\n\nexport function nodeMakeCtx<T>(\n\tself: NodeRuntimeHost<T>,\n\tsnapshot?: { waveData: unknown[][][]; terminal: unknown[]; latest: unknown[] },\n): Ctx {\n\tconst ctx: Ctx = {\n\t\t// Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove\n\t\t// it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed\n\t\t// ctx at depth 0, so this is the boundary that drains any rewireNext it issued.\n\t\tup: (msgs, towardDep) => {\n\t\t\tif (self._released) return;\n\t\t\tenterWave();\n\t\t\ttry {\n\t\t\t\tself._up(msgs, towardDep);\n\t\t\t} finally {\n\t\t\t\texitWave();\n\t\t\t}\n\t\t},\n\t\tdown: (msgs) => {\n\t\t\tif (self._released) return;\n\t\t\tenterWave();\n\t\t\ttry {\n\t\t\t\tself._down(msgs);\n\t\t\t} finally {\n\t\t\t\texitWave();\n\t\t\t}\n\t\t},\n\t\twaveData: snapshot?.waveData ?? self._dep.waveData,\n\t\tterminal: snapshot?.terminal ?? self._dep.terminalInput.map(terminalView),\n\t\tstate: self._makeState(),\n\t\tonDeactivation: (fn) => {\n\t\t\tif (self._released) return;\n\t\t\tself._hooks.onDeactivation.push(fn);\n\t\t},\n\t\tonInvalidate: (fn) => {\n\t\t\tif (self._released) return;\n\t\t\tself._hooks.onInvalidate.push(fn);\n\t\t},\n\t\tenvironment: () => self._slot.environment,\n\t\t// R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.\n\t\trewireNext: {\n\t\t\tsubscribeDep: (dep, fn) => self._requestRewireNext({ kind: \"add\", dep, fn }),\n\t\t\tunsubscribeDep: (dep, fn) => self._requestRewireNext({ kind: \"remove\", dep, fn }),\n\t\t\treplaceDeps: (deps, fn) => self._requestRewireNext({ kind: \"set\", deps, fn }),\n\t\t},\n\t\t// R-up-routing / R-pull (D269): deferred up — route a control/demand wave (e.g. PULL)\n\t\t// up the declared cone at the committed boundary. The SELF-demand path: an\n\t\t// immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).\n\t\tupNext: (msgs, towardDep) => self._requestUpNext(msgs, towardDep),\n\t\t...(self._control.activePull === undefined ? {} : { pull: self._control.activePull }),\n\t\t[CTX_DEP_CACHE]: { latest: snapshot?.latest ?? self._dep.prev },\n\t\t[CTX_NODE_BINDING]: {\n\t\t\tdispatcher: self._slot.dispatcher,\n\t\t\tcreate: <U>(factory: () => Node<U>) =>\n\t\t\t\twithEnvironmentDrivers(self._slot.environment, () => withNodeCore(self._core, factory)),\n\t\t},\n\t};\n\tif (self._slot.dynamic) {\n\t\t// R-dynamic-node: read a dep's latest by index. Untracked deps still drive waves and\n\t\t// re-run the fn; under D49 (no equals-substitution) the fn re-emits its current value\n\t\t// as DATA — to suppress redundant downstream propagation, pair with distinctUntilChanged.\n\t\tctx.track = (i: number) => ctx[CTX_DEP_CACHE]?.latest[i];\n\t}\n\treturn ctx;\n}\n\nexport function nodeRefreshCtx<T>(self: NodeRuntimeHost<T>, ctx: Ctx): void {\n\t(ctx as { waveData: WaveData }).waveData = self._dep.waveData;\n\t(ctx as { terminal: TerminalData }).terminal = self._dep.terminalInput.map(terminalView);\n\tif (self._control.activePull === undefined) {\n\t\tdelete (ctx as { pull?: PullDemand }).pull;\n\t} else {\n\t\t(ctx as { pull?: PullDemand }).pull = self._control.activePull;\n\t}\n\tctx[CTX_DEP_CACHE] = { latest: self._dep.prev };\n}\n\nexport function nodeMakeState<T>(self: NodeRuntimeHost<T>): CtxState {\n\treturn {\n\t\tget: <S>() => self._privateState.value as S | undefined,\n\t\tset: <S>(v: S) => {\n\t\t\tself._privateState.value = v;\n\t\t},\n\t\tpersist: (on = true) => {\n\t\t\tself._privateState.persist = on;\n\t\t},\n\t};\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport type { Handle } from \"../dispatcher/index.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport { isTerminal, SENTINEL } from \"../protocol/messages.js\";\nimport type { NodeRuntimeHost } from \"./node-runtime-host.js\";\n\nexport function nodeRecordDepProjection<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tdelivery: DeliveryMeta | undefined,\n): unknown[] {\n\tconst token = delivery?.wave ?? {};\n\tif (self._dep.waveTokens[idx] !== token) {\n\t\tself._dep.waveData[idx].push([]);\n\t\tself._dep.waveTokens[idx] = token;\n\t}\n\treturn self._dep.waveData[idx][self._dep.waveData[idx].length - 1];\n}\n\nexport function nodeDepProjectionHasData<T>(self: NodeRuntimeHost<T>, idx: number): boolean {\n\tconst projection = self._dep.waveData[idx][self._dep.waveData[idx].length - 1];\n\treturn projection?.some((v) => v !== SENTINEL) ?? false;\n}\n\nexport function nodeReceiveFromDep<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tmsg: Message,\n\tdelivery?: DeliveryMeta,\n): void {\n\tif (self._released) return;\n\tconst t = msg[0];\n\tif (t === \"START\") return;\n\tconst isLastInDeliveredWave = delivery?.last ?? true;\n\t// Terminal-is-forever, except terminal intermediates still relay upstream TEARDOWN\n\t// downstream for lifecycle unwire (R-teardown-terminal-relay / D65).\n\tif (self._value.terminal !== undefined) {\n\t\tif (t === \"TEARDOWN\") self._down([[\"TEARDOWN\"]]);\n\t\treturn;\n\t}\n\n\tif (t === \"INVALIDATE\") {\n\t\tconst projection = self._recordDepProjection(idx, delivery);\n\t\tprojection.push(SENTINEL);\n\t\tif (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) self._maybeRun();\n\t\t// The dep's value is gone — drop our cached latest view to SENTINEL so the\n\t\t// never-emitted detector reads correctly, C-3) and cascade (idempotent).\n\t\tself._dep.prev[idx] = SENTINEL;\n\t\tself._dep.hasData[idx] = false;\n\t\tself._dep.batch[idx] = null;\n\t\t// EC3: un-wedge the dirty bookkeeping if this dep had gone DIRTY first, so an\n\t\t// INVALIDATE-before-DATA doesn't strand _pending / downstream forever\n\t\t// (R-invalidate-idempotent — exists to prevent the wedged-DIRTY deadlock).\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\t// D50 / R-paused-invalidate: this INVALIDATE SUPERSEDES the dep's buffered\n\t\t// paused dep-wave (_depBatch[idx] just cleared). Re-derive the paused-recompute\n\t\t// flag — if no dep still carries a buffered DATA, CANCEL the paused recompute\n\t\t// (attributed cancellation; the node has settled to SENTINEL via its own\n\t\t// INVALIDATE, so a RESUME must not recompute against a now-SENTINEL dep). A\n\t\t// surviving dep keeps it set; a later DATA re-arms it ([DATA,INVALIDATE,DATA2]).\n\t\tif (self._control.pausedDepWaveOccurred && self._dep.batch.every((b) => b === null)) {\n\t\t\tself._control.pausedDepWaveOccurred = false;\n\t\t}\n\t\tconst hadData = self._value.hasData;\n\t\tself._invalidate(); // cascades INVALIDATE iff populated; no-op otherwise\n\t\t// If we broadcast DIRTY this wave but _invalidate produced no settle (the node\n\t\t// was never populated, so the cascade is suppressed per the rule), un-dirty\n\t\t// downstream with a RESOLVED once all deps have settled.\n\t\tif (self._wave.pending === 0 && self._wave.emittedDirtyThisWave) {\n\t\t\tif (!hadData) self._down([[\"RESOLVED\"]]);\n\t\t\telse self._wave.emittedDirtyThisWave = false;\n\t\t}\n\t\tself._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): an INVALIDATE settle can drain _pending → fire a deferred demand\n\t\treturn;\n\t}\n\n\tif (isTerminal(t)) {\n\t\t// Tier 5 (R-tier / D34): COMPLETE | ERROR — ONE branch routed by the CENTRAL tier table,\n\t\t// not a per-variant string check (feedback_use_tier_for_signal_routing). The shared terminal\n\t\t// bookkeeping (record the terminal + release the in-wave DIRTY) runs for ANY tier-5 message;\n\t\t// only the COMPLETE-vs-ERROR cascade differs, so discriminate by the type within the tier.\n\t\tconst isError = t === \"ERROR\";\n\t\tconst errPayload = isError ? (msg as readonly [\"ERROR\", unknown])[1] : undefined;\n\t\tself._dep.terminal[idx] = isError ? errPayload : true;\n\t\tself._dep.terminalInput[idx] = isError ? errPayload : true;\n\t\t// R-terminal-settles-dirty (B35): a terminal RELEASES this dep's outstanding in-wave DIRTY\n\t\t// contribution (the exactly-one-settle invariant) — exactly as DATA/RESOLVED/INVALIDATE do\n\t\t// (a dirty-then-terminal-without-DATA dep would otherwise strand _pending and wedge the node,\n\t\t// the deadlock R-invalidate-idempotent prevents for INVALIDATE).\n\t\tself._releaseDepDirty(idx);\n\t\tconst ranValueBeforeTerminal = self._depProjectionHasData(idx) && isLastInDeliveredWave;\n\t\tif (ranValueBeforeTerminal) self._maybeRun();\n\t\tif (isError && self._slot.errorWhenDepsError) {\n\t\t\tself._down([[\"ERROR\", errPayload]]); // auto-cascade ERROR → node itself terminal\n\t\t} else if (self._slot.terminalAsRealInput) {\n\t\t\tif (ranValueBeforeTerminal) {\n\t\t\t\tself._fireOwedDemandIfReady();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tself._maybeRun(); // rescue/reduce/catch/*Map: the fn reads depTerminal(ctx, idx)\n\t\t} else if (self._slot.completeWhenDepsComplete && self._allDepsTerminal()) {\n\t\t\t// R-deps-terminal auto-COMPLETE + B42: COMPLETE once ALL deps are TERMINAL (each COMPLETE\n\t\t\t// or an absorbed ERROR) — so an absorbed-error dep terminating LAST still fires the\n\t\t\t// cascade. terminalAsRealInput is checked FIRST so a rescue recovers via _maybeRun rather\n\t\t\t// than being preempted (no operator sets both completeWhenDepsComplete:true + tari:true).\n\t\t\tself._down([[\"COMPLETE\"]]);\n\t\t} else {\n\t\t\t// absorbed terminal, NOT an input + not auto-completing: the dep's signalled change did\n\t\t\t// not materialise (no DATA) → un-dirty downstream, keep cache (R-resolved-undirty balance).\n\t\t\tself._settleAfterAbsorbedTerminal();\n\t\t}\n\t\tself._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): a dep terminal can drain _pending → fire a deferred demand (no-op if this node went terminal)\n\t\treturn;\n\t}\n\n\tif (t === \"TEARDOWN\") {\n\t\tself._down([[\"TEARDOWN\"]]);\n\t\treturn;\n\t}\n\n\tif (t === \"DIRTY\") {\n\t\tif (!self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = true;\n\t\t\tself._wave.pending++;\n\t\t\tself._dep.tier[idx] = 2;\n\t\t\tself._markDirty();\n\t\t}\n\t\treturn;\n\t}\n\n\tif (t === \"DATA\") {\n\t\tconst v = msg[1];\n\t\tself._recordDepProjection(idx, delivery).push(v);\n\t\tconst b = self._dep.batch[idx];\n\t\tif (b === null) self._dep.batch[idx] = [v];\n\t\telse b.push(v);\n\t\tself._dep.prev[idx] = v;\n\t\tself._dep.hasData[idx] = true;\n\t\tself._dep.tier[idx] = 3;\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\tif (isLastInDeliveredWave) self._maybeRun();\n\t\tself._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\treturn;\n\t}\n\n\tif (t === \"RESOLVED\") {\n\t\tself._recordDepProjection(idx, delivery);\n\t\tself._dep.tier[idx] = 3;\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\tif (isLastInDeliveredWave) self._maybeRun();\n\t\tself._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\treturn;\n\t}\n\t// PAUSE / RESUME are not delivered downstream to a dep-subscriber; a node is\n\t// paused via its own up() (lockset), not by an upstream dep.\n}\n\nexport function nodeReleaseDepDirty<T>(self: NodeRuntimeHost<T>, idx: number): void {\n\tif (self._dep.dirty[idx]) {\n\t\tself._dep.dirty[idx] = false;\n\t\tself._wave.pending--;\n\t}\n}\n\nexport function nodeSettleAfterAbsorbedTerminal<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._wave.pending !== 0 || !self._wave.emittedDirtyThisWave) return;\n\t// A real value occurred this wave (some OTHER dep delivered DATA) → recompute. _maybeRun\n\t// runs the fn ONLY if it's not gated (first-run gate open, not paused); it may emit DATA, a\n\t// fn-synthesized undirty RESOLVED, or nothing (gated / gate still holds).\n\tconst sawData = self._dep.batch.some((b) => b !== null && b.length > 0);\n\tif (sawData) self._maybeRun();\n\t// If after that the node STILL owes a downstream settle (no DATA occurred, OR the recompute\n\t// was gated — e.g. the first-run gate holds because the terminated dep never delivered and\n\t// terminalAsRealInput is false), balance the broadcast DIRTY with one undirty RESOLVED\n\t// (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t// Without this fallback a DIRTY-then-terminal-without-DATA dep on a pre-first-run multi-dep\n\t// node would strand the DIRTY → downstream wedged (the B35 class, in the gate-holds corner).\n\tif (self._wave.emittedDirtyThisWave) self._down([[\"RESOLVED\"]]);\n}\n\nexport function nodeMarkDirty<T>(self: NodeRuntimeHost<T>): void {\n\tself._value.status = \"dirty\";\n\t// SPIKE (protocol-pull): while quiet, ABSORB the upstream DIRTY — do NOT relay it downstream.\n\t// This is the P0b wedge fix: a quiet pull node that relayed DIRTY but withheld the settle\n\t// (coalesced by pause) wedged every downstream's two-phase _pending. The downstream learns of\n\t// changes via the push STREAM port, not the silent snapshot port; on demand the pull node\n\t// emits a fresh wave. Internal dep dirty-accounting (the DIRTY-branch _pending++) is untouched.\n\tif (self._isPullQuiet()) return;\n\tif (!self._wave.emittedDirtyThisWave) {\n\t\tself._wave.emittedDirtyThisWave = true;\n\t\tself._emitToSubs([\"DIRTY\"]);\n\t}\n}\n\nexport function nodeMaybeRun<T>(self: NodeRuntimeHost<T>): void {\n\t// R-rewire: an added cached dep's push-on-subscribe lands here mid-mutation. Defer\n\t// the fn-run to ONE atomic two-phase settle after every added dep is wired, so the\n\t// fn never fires on a partially-populated added-dep view (multi-add) — _settleRewire\n\t// drains this flag.\n\tif (self._wave.inDepMutation) {\n\t\tself._wave.rewireRunPending = true;\n\t\treturn;\n\t}\n\t// R-pause-modes + R-pull: while externally paused or pull-quiet, default pull mode\n\t// coalesces. `resumeAll` still runs so its outgoing settle slice can enter pauseBuffer.\n\tif (self._slot.pausable === true && (self._isPaused() || self._isPullQuiet())) {\n\t\tself._control.pausedDepWaveOccurred = true;\n\t\treturn;\n\t}\n\tself._tryRun();\n}\n\nexport function nodeSettleRewire<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._slot.pausable === true && self._isPaused()) {\n\t\tself._control.pausedDepWaveOccurred = true;\n\t\treturn;\n\t}\n\tif (self._wave.pending > 0) return;\n\tif (self._slot.handle === null) {\n\t\tself._passthroughEmit();\n\t\treturn;\n\t}\n\tif (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;\n\tself._markDirty(); // phase 1 (no-op if already dirty, e.g. unsubscribeDep auto-settle)\n\tself._runWave(); // phase 2: fn → DATA/RESOLVED\n}\n\nexport function nodeTryRun<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._wave.pending > 0) return;\n\tif (self._slot.handle === null) {\n\t\t// Passthrough wire (deps, no fn): forward the latest dep DATA downstream.\n\t\tself._passthroughEmit();\n\t\treturn;\n\t}\n\tif (!self._wave.hasCalledFnOnce) {\n\t\tif (self._slot.partial || self._allDepsSettled()) self._runWave();\n\t\t// else: first-run gate holds fn until every dep has settled (R-first-run-gate).\n\t\treturn;\n\t}\n\tself._runWave();\n}\n\nexport function nodeAllDepsSettled<T>(self: NodeRuntimeHost<T>): boolean {\n\tfor (let i = 0; i < self._slot.deps.length; i++) {\n\t\tif (self._dep.hasData[i]) continue;\n\t\tif (self._slot.terminalAsRealInput && self._dep.terminal[i] !== undefined) continue;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function nodePassthroughEmit<T>(self: NodeRuntimeHost<T>): void {\n\t// Single-dep wire: relay dep 0's latest batch value as DATA.\n\tconst b = self._dep.batch[0];\n\tif (b !== null && b.length > 0) {\n\t\tself._down([[\"DATA\", b[b.length - 1]]]);\n\t} else if (self._wave.emittedDirtyThisWave) {\n\t\t// R-resolved-undirty (D49): the dep settled via an undirty RESOLVED (no DATA in the\n\t\t// batch), but this wire already broadcast DIRTY downstream this wave — balance it with\n\t\t// a RESOLVED so downstream un-dirties instead of wedging. Routed through _down (NOT a\n\t\t// bare _emitToSubs) so the balance respects batch-defer (D12) + pause-buffer, matching\n\t\t// the zero-dep un-dirty path. Without this, a passthrough over a filter-reject /\n\t\t// distinctUntilChanged-dup leaves a dangling DIRTY (the wedge D49 made common).\n\t\tself._down([[\"RESOLVED\"]]);\n\t}\n\tself._dep.batch[0] = null;\n\tself._wave.emittedDirtyThisWave = false;\n}\n\nexport function nodeRunWave<T>(self: NodeRuntimeHost<T>): void {\n\t// R-reentrancy (D37): a fn that re-drives its own dep mid-wave re-enters here while\n\t// _insideRunWave is still set — a synchronous feedback cycle. Reject (throw); the graph\n\t// layer catches it and converts to [[ERROR, e]] (D30). The try/finally resets the flag\n\t// on every frame as the throw unwinds, leaving the graph clean for the catch. Detection\n\t// is node-local and free — it reuses the existing _insideRunWave flag (no new structure,\n\t// dispatcher stays a pure funnel).\n\tif (self._wave.insideRunWave)\n\t\tthrow new Error(\n\t\t\t\"synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)\",\n\t\t);\n\tself._wave.hasCalledFnOnce = true;\n\t// R-cleanup-hooks per-run lifecycle (D28 clarification): clear BOTH hook lists\n\t// before the fn runs; the fn body re-registers the current run's hooks. Only the\n\t// latest run's registrations are live — a re-run supersedes the prior run's hooks,\n\t// discarded WITHOUT firing (no fire-on-rerun; onRerun stays cut). Fixes the push-only\n\t// accumulation (K stale hooks fired after K runs). C-14.\n\tself._hooks.onInvalidate = [];\n\tself._hooks.onDeactivation = [];\n\tconst ctx = self._buildCtx();\n\tconst wasDirty = self._wave.emittedDirtyThisWave;\n\tself._wave.emittedSettleThisWave = false;\n\tself._wave.insideRunWave = true;\n\ttry {\n\t\tself._slot.dispatcher.invoke(self._slot.handle as Handle, ctx);\n\t} finally {\n\t\tself._wave.insideRunWave = false;\n\t}\n\n\t// R-resolved-undirty (D49): a SYNC fn DIRTY'd in phase 1 that produced NO tier-3 value\n\t// this wave (filter-reject / distinctUntilChanged-dup / any no-emit fn) gets a substrate-\n\t// SYNTHESIZED undirty RESOLVED to clear the downstream dirty — operator bodies stay\n\t// protocol-clean (R-primary-api-clean). Status reflects cache freshness: a carried value\n\t// -> resolved, never-valued -> sentinel. EXEMPT: terminal/INVALIDATE waves (they set\n\t// _emittedSettleThisWave and balance their own dirty), and ASYNC-pool nodes — an async fn\n\t// that returns without emitting has DEFERRED its result (it emits later via the stashed\n\t// ctx), NOT rejected; synthesizing here would prematurely settle a still-pending diamond\n\t// leg (R-async-paused / C-4). The eventual async ctx.down carries its own DIRTY balance.\n\tif (\n\t\twasDirty &&\n\t\t!self._wave.emittedSettleThisWave &&\n\t\tself._value.terminal === undefined &&\n\t\t!self._isAsyncPool()\n\t) {\n\t\tself._down([[\"RESOLVED\"]]);\n\t}\n\n\t// roll wave-local state forward\n\tfor (let i = 0; i < self._dep.batch.length; i++) {\n\t\tself._dep.batch[i] = null;\n\t\tself._dep.waveData[i] = [];\n\t\tself._dep.waveTokens[i] = undefined;\n\t\tself._dep.terminalInput[i] = undefined;\n\t}\n\tself._wave.emittedDirtyThisWave = false;\n}\n","import type { Ctx, CtxState, DeliveryMeta, NodeFn } from \"../ctx/types.js\";\nimport type { LockId, Message, PullDemand, Wave } from \"../protocol/messages.js\";\nimport type {\n\tCleanupHooks,\n\tControlState,\n\tDepBookkeeping,\n\tLifecycleState,\n\tNodeCore,\n\tNodeId,\n\tNodeSlot,\n\tPrivateState,\n\tSyncCtxState,\n\tValueState,\n\tVersionState,\n\tWaveState,\n} from \"./core.js\";\nimport type { Node } from \"./node.js\";\nimport type { RewireOp, UpRouteState } from \"./types.js\";\n\nexport interface NodeRuntimeHost<T = unknown> {\n\t_core: NodeCore;\n\t_id: NodeId;\n\t_slot: NodeSlot<T>;\n\t_dep: DepBookkeeping;\n\t_value: ValueState<T>;\n\t_wave: WaveState;\n\t_control: ControlState;\n\t_lifecycle: LifecycleState;\n\t_privateState: PrivateState;\n\t_hooks: CleanupHooks;\n\t_syncCtxState: SyncCtxState;\n\t_version: VersionState;\n\t_syncCtx: Ctx | null;\n\t_restoredActivationPending: boolean;\n\t_released: boolean;\n\t_assertNotReleased(op: string): void;\n\t_isPullQuiet(): boolean;\n\t_requestRewireNext(op: RewireOp): void;\n\t_requestUpNext(msgs: Wave, towardDep?: number): void;\n\t_applyRewireNext(op: RewireOp): void;\n\t_dedupDeps(deps: Node<unknown>[]): Node<unknown>[];\n\t_reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean;\n\t_assertRewireDepOwner(dep: Node<unknown>): void;\n\t_rewire(newDeps: Node<unknown>[], fn: NodeFn, opts?: { allowTerminalOwner?: boolean }): boolean;\n\t_activate(): void;\n\t_subscribeDepAt(depNode: Node<unknown>, opts?: { seedRestored?: boolean }): void;\n\t_seedRestoredDepAt(idx: number, depNode: Node<unknown>): void;\n\t_deactivate(): void;\n\t_subscriberCount(): number;\n\t_isRuntimeQuiescentForRelease(): boolean;\n\t_releaseRuntime(): void;\n\t_resetDepState(): void;\n\t_recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[];\n\t_depProjectionHasData(idx: number): boolean;\n\t_receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void;\n\t_releaseDepDirty(idx: number): void;\n\t_settleAfterAbsorbedTerminal(): void;\n\t_markDirty(): void;\n\t_maybeRun(): void;\n\t_settleRewire(): void;\n\t_tryRun(): void;\n\t_allDepsSettled(): boolean;\n\t_passthroughEmit(): void;\n\t_runWave(): void;\n\t_buildCtx(): Ctx;\n\t_makeCtx(snapshot?: { waveData: unknown[][][]; terminal: unknown[]; latest: unknown[] }): Ctx;\n\t_refreshCtx(ctx: Ctx): void;\n\t_makeState(): CtxState;\n\t_down(msgs: Wave): void;\n\t_up(msgs: Wave, towardDep?: number, route?: UpRouteState): void;\n\t_markDemandRouted(lockId: LockId, route: UpRouteState): boolean;\n\t_forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void;\n\t_isPaused(): boolean;\n\t_hasBoundaryPauseLock(): boolean;\n\t_isAsyncPool(): boolean;\n\t_pauseAcquire(lockId: unknown): void;\n\t_pauseRelease(lockId: unknown): void;\n\t_onResume(): void;\n\t_canFireDemand(): boolean;\n\t_deliverPullDemand(demand: PullDemand): void;\n\t_onDemand(demand: PullDemand): void;\n\t_firePullDemand(): void;\n\t_fireOwedDemandIfReady(): void;\n\t_shouldBufferOnPause(): boolean;\n\t_invalidate(delivery?: DeliveryMeta): void;\n\t_allDepsTerminal(): boolean;\n\t_resetLifecycle(): void;\n\t_emitToSubs(msg: Message, delivery?: DeliveryMeta): void;\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport function nodeRuntimeHost<T>(node: Node<T>): NodeRuntimeHost<T> {\n\treturn node as unknown as NodeRuntimeHost<T>;\n}\n","import { SENTINEL } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport {\n\tactivationReaders,\n\tcheckpointReaders,\n\townerTokens,\n\treleasedNodes,\n\trestoreWriters,\n\truntimeQuiescenceReaders,\n\truntimeReleasers,\n\tsubscriberCountReaders,\n\ttopologyDepsChangedObservers,\n} from \"./runtime-accessors.js\";\n\nexport function nodeActivate<T>(self: NodeRuntimeHost<T>): void {\n\tself._lifecycle.activated = true;\n\tconst seedRestoredDeps = self._restoredActivationPending;\n\tself._restoredActivationPending = false;\n\t// R-pull (D55/D272): activePull is undefined before wiring deps, so each dep's\n\t// push-on-subscribe DIRTY/DATA is absorbed quietly, not relayed downstream.\n\tself._dep.unsubs = new Array(self._slot.deps.length);\n\tself._dep.idxBoxes = new Array(self._slot.deps.length);\n\tfor (const dep of self._slot.deps) self._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });\n\t// Depless producer (fn, no deps): run once on activation.\n\tif (self._slot.deps.length === 0 && self._slot.handle !== null && !self._wave.hasCalledFnOnce) {\n\t\tself._runWave();\n\t}\n}\n\nexport function nodeSubscribeDepAt<T>(\n\tself: NodeRuntimeHost<T>,\n\tdepNode: Node<unknown>,\n\topts: { seedRestored?: boolean } = {},\n): void {\n\tconst idx0 = self._slot.deps.indexOf(depNode);\n\tconst box = { v: idx0 };\n\tlet ignoreInitialPush = opts.seedRestored === true;\n\tif (ignoreInitialPush && idx0 !== -1) {\n\t\tself._seedRestoredDepAt(idx0, depNode);\n\t\tconst dep = nodeRuntimeHost(depNode);\n\t\tif (dep._value.terminal !== undefined && !dep._slot.resubscribable) {\n\t\t\tself._dep.unsubs[idx0] = () => {};\n\t\t\tself._dep.idxBoxes[idx0] = box;\n\t\t\treturn;\n\t\t}\n\t}\n\tconst unsub = depNode.subscribe((msg, delivery) => {\n\t\tif (ignoreInitialPush && delivery === undefined) return;\n\t\tif (ignoreInitialPush) ignoreInitialPush = false;\n\t\tif (box.v === -1) return; // dep removed — stale callback, drop (drain)\n\t\tself._receiveFromDep(box.v, msg, delivery);\n\t});\n\tif (ignoreInitialPush && idx0 !== -1 && box.v !== -1) self._seedRestoredDepAt(idx0, depNode);\n\tignoreInitialPush = false;\n\tif (idx0 !== -1) {\n\t\tself._dep.unsubs[idx0] = unsub;\n\t\tself._dep.idxBoxes[idx0] = box;\n\t}\n}\n\nexport function nodeSeedRestoredDepAt<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tdepNode: Node<unknown>,\n): void {\n\tconst dep = nodeRuntimeHost(depNode);\n\tconst seedData = dep._value.hasData && !dep._slot.pull;\n\tself._dep.batch[idx] = null;\n\tself._dep.waveData[idx] = [];\n\tself._dep.waveTokens[idx] = undefined;\n\tself._dep.prev[idx] = seedData ? dep._value.cache : SENTINEL;\n\tself._dep.hasData[idx] = seedData;\n\tself._dep.dirty[idx] = false;\n\tself._dep.tier[idx] = seedData ? 3 : 0;\n\tself._dep.terminal[idx] = dep._value.terminal;\n\tself._dep.terminalInput[idx] = undefined;\n}\n\nexport function nodeDeactivate<T>(self: NodeRuntimeHost<T>): void {\n\tself._lifecycle.activated = false;\n\tfor (const u of self._dep.unsubs) if (u) u();\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tfor (const fn of self._hooks.onDeactivation) fn();\n\tself._hooks.onDeactivation = [];\n\tself._hooks.onInvalidate = [];\n\n\tconst isCompute = self._slot.handle !== null || self._slot.deps.length > 0;\n\tif (isCompute) {\n\t\t// RAM: compute nodes clear cache; reconnect re-runs fn fresh.\n\t\tself._value.cache = SENTINEL;\n\t\tself._value.hasData = false;\n\t\tself._value.status = \"sentinel\";\n\t}\n\tself._resetDepState();\n\tself._wave.hasCalledFnOnce = false;\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._value.replayRing = []; // BH6: don't replay stale values to a post-reactivation subscriber\n\tif (!self._privateState.persist) self._privateState.value = SENTINEL;\n}\n\nexport function nodeSubscriberCount<T>(self: NodeRuntimeHost<T>): number {\n\treturn self._lifecycle.subscribers.size;\n}\n\nexport function nodeIsRuntimeQuiescentForRelease<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn (\n\t\t!self._released &&\n\t\tself._value.status !== \"dirty\" &&\n\t\tself._value.status !== \"pending\" &&\n\t\tself._wave.pending === 0 &&\n\t\t!self._wave.insideRunWave &&\n\t\t!self._wave.inDepMutation &&\n\t\t!self._wave.rewireRunPending &&\n\t\t!self._wave.batchDirtyOwed &&\n\t\tself._dep.dirty.every((dirty) => !dirty) &&\n\t\tself._control.pauseBuffer.length === 0 &&\n\t\t!self._control.pausedDepWaveOccurred &&\n\t\tself._control.demandOwed === undefined &&\n\t\tself._control.activePull === undefined &&\n\t\t!self._control.inDeliverDemand &&\n\t\tself._control.pauseLockset.size === 0\n\t);\n}\n\nexport function nodeReleaseRuntime<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._released) return;\n\tself._released = true;\n\tconst node = self as unknown as Node<unknown>;\n\treleasedNodes.add(node);\n\tlet releaseError: unknown;\n\tconst recordReleaseError = (error: unknown): void => {\n\t\tif (releaseError === undefined) releaseError = error;\n\t};\n\tself._lifecycle.activated = false;\n\tfor (const u of self._dep.unsubs) {\n\t\ttry {\n\t\t\tu();\n\t\t} catch (error) {\n\t\t\trecordReleaseError(error);\n\t\t\t// D124 release is graph-owned and atomic; user cleanup must not split commit.\n\t\t}\n\t}\n\tfor (const fn of self._hooks.onDeactivation) {\n\t\ttry {\n\t\t\tfn();\n\t\t} catch (error) {\n\t\t\trecordReleaseError(error);\n\t\t\t// D124 release cleans runtime without synthesizing protocol ERROR/COMPLETE.\n\t\t}\n\t}\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tself._lifecycle.subscribers.clear();\n\tif (self._slot.handle !== null) {\n\t\tself._slot.dispatcher.unregister(self._slot.handle);\n\t\tself._slot.handle = null;\n\t}\n\tself._slot.deps = [];\n\tself._dep.batch = [];\n\tself._dep.waveData = [];\n\tself._dep.waveTokens = [];\n\tself._dep.prev = [];\n\tself._dep.hasData = [];\n\tself._dep.dirty = [];\n\tself._dep.tier = [];\n\tself._dep.terminal = [];\n\tself._dep.terminalInput = [];\n\tself._value.cache = SENTINEL;\n\tself._value.hasData = false;\n\tself._value.status = \"sentinel\";\n\tself._value.terminal = undefined;\n\tself._value.replayRing = [];\n\tself._privateState.value = SENTINEL;\n\tself._privateState.persist = false;\n\tself._syncCtx = null;\n\tself._resetDepState();\n\tself._hooks.onDeactivation = [];\n\tself._hooks.onInvalidate = [];\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined;\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._restoredActivationPending = false;\n\tcheckpointReaders.delete(node);\n\trestoreWriters.delete(node);\n\truntimeReleasers.delete(node);\n\truntimeQuiescenceReaders.delete(node);\n\tsubscriberCountReaders.delete(node);\n\tactivationReaders.delete(node);\n\townerTokens.delete(node);\n\ttopologyDepsChangedObservers.delete(node);\n\tself._core.releaseSlot(self._id);\n\tif (releaseError !== undefined) throw releaseError;\n}\n\nexport function nodeResetDepState<T>(self: NodeRuntimeHost<T>): void {\n\tconst n = self._slot.deps.length;\n\tfor (let i = 0; i < n; i++) {\n\t\tself._dep.batch[i] = null;\n\t\tself._dep.waveData[i] = [];\n\t\tself._dep.waveTokens[i] = undefined;\n\t\tself._dep.prev[i] = SENTINEL;\n\t\tself._dep.hasData[i] = false;\n\t\tself._dep.dirty[i] = false;\n\t\tself._dep.tier[i] = 0;\n\t\tself._dep.terminal[i] = undefined;\n\t\tself._dep.terminalInput[i] = undefined;\n\t}\n\tself._wave.pending = 0;\n\tself._wave.emittedDirtyThisWave = false;\n}\n","/**\n * Neutral JSON/encoding utilities (D96).\n *\n * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON\n * scanner/canonicalization contract.\n */\n\n/** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */\nexport interface Codec<T> {\n\tencode(value: T): Uint8Array;\n\tdecode(bytes: Uint8Array): T;\n}\n\nexport type StrictJsonScalar = null | boolean | number | string;\nexport type StrictJsonValue =\n\t| StrictJsonScalar\n\t| readonly StrictJsonValue[]\n\t| { readonly [key: string]: StrictJsonValue };\nexport type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;\n\ntype JsonValue = StrictJsonValue;\n\nconst JS_MIN_NORMAL_NUMBER = 2 ** -1022;\n\nfunction assertStableJsonNumber(value: number, path: string): void {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new TypeError(`stableJsonString: non-finite number at ${path}`);\n\t}\n}\n\nfunction assertStrictJsonNumber(value: number, path: string): void {\n\tassertStableJsonNumber(value, path);\n\tif (Object.is(value, -0)) {\n\t\tthrow new TypeError(`stableJsonString: non-canonical number at ${path}`);\n\t}\n\tconst abs = Math.abs(value);\n\tif (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {\n\t\tthrow new TypeError(`stableJsonString: subnormal number at ${path}`);\n\t}\n\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`stableJsonString: integer outside safe range at ${path}`);\n\t}\n}\n\nfunction sortedJsonValue(\n\tvalue: unknown,\n\tseen = new Set<object>(),\n\tpath = \"$\",\n\tstrictNumbers = false,\n): JsonValue {\n\tif (value === null) return null;\n\tif (typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (strictNumbers) assertStrictJsonNumber(value, path);\n\t\telse assertStableJsonNumber(value, path);\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);\n\t}\n\tif (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\tthrow new TypeError(`stableJsonString: non-plain object at ${path}`);\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst isIndex =\n\t\t\t\t\t/^(0|[1-9]\\d*)$/.test(key) &&\n\t\t\t\t\tNumber.isSafeInteger(Number(key)) &&\n\t\t\t\t\tNumber(key) < value.length;\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\t\tif (descriptor !== undefined && (\"get\" in descriptor || \"set\" in descriptor)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: accessor property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && descriptor !== undefined && !descriptor.enumerable) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-enumerable array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: JsonValue[] = [];\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tif (!(i in value)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);\n\t\t\t\t}\n\t\t\t\tout.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t}\n\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor !== undefined && (\"get\" in descriptor || \"set\" in descriptor)) {\n\t\t\t\tthrow new TypeError(`stableJsonString: accessor property at ${path}.${key}`);\n\t\t\t}\n\t\t\tif (descriptor !== undefined && !descriptor.enumerable) {\n\t\t\t\tthrow new TypeError(`stableJsonString: non-enumerable property at ${path}.${key}`);\n\t\t\t}\n\t\t}\n\t\tconst out: Record<string, JsonValue> = Object.create(null);\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tout[key] = sortedJsonValue(\n\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\tseen,\n\t\t\t\t`${path}.${key}`,\n\t\t\t\tstrictNumbers,\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value, new Set<object>(), \"$\", true));\n}\n\n/** Build a JSON codec using stable object-key ordering. */\nexport function jsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder();\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\treturn encoder.encode(stableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\treturn JSON.parse(decoder.decode(bytes)) as T;\n\t\t},\n\t};\n}\n\n/** Default stable JSON codec for unknown values. */\nexport const jsonCodec: Codec<unknown> = jsonCodecFor<unknown>();\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.byteLength !== b.byteLength) return false;\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction hasUnpairedSurrogate(value: string): boolean {\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tconst code = value.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (code >= 0xdc00 && code <= 0xdfff) return true;\n\t}\n\treturn false;\n}\n\nfunction assertNoUnpairedSurrogates(value: unknown, seen = new Set<object>(), path = \"$\"): void {\n\tif (typeof value === \"string\") {\n\t\tif (hasUnpairedSurrogate(value)) {\n\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (value === null || typeof value !== \"object\") return;\n\tif (seen.has(value)) return;\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tassertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value as Record<string, unknown>)) {\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertNoUnpairedSurrogates((value as Record<string, unknown>)[key], seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction assertNoDuplicateJsonObjectKeys(text: string): void {\n\tlet index = 0;\n\n\tfunction fail(message: string): never {\n\t\tthrow new TypeError(`strictJsonCodec: ${message}`);\n\t}\n\n\tfunction skipWhitespace(): void {\n\t\twhile (/\\s/.test(text[index] ?? \"\")) index += 1;\n\t}\n\n\tfunction readJsonString(): string {\n\t\tconst start = index;\n\t\tindex += 1;\n\t\twhile (index < text.length) {\n\t\t\tconst ch = text[index];\n\t\t\tif (ch === '\"') {\n\t\t\t\tindex += 1;\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.parse(text.slice(start, index)) as string;\n\t\t\t\t} catch {\n\t\t\t\t\tfail(\"malformed JSON string\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ch === \"\\\\\") {\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t\tfail(\"unterminated JSON string\");\n\t}\n\n\tfunction consumeLiteral(literal: string): void {\n\t\tif (text.slice(index, index + literal.length) !== literal) {\n\t\t\tfail(`malformed JSON near byte ${index}`);\n\t\t}\n\t\tindex += literal.length;\n\t}\n\n\tfunction consumeNumber(): void {\n\t\tconst match = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/.exec(text.slice(index));\n\t\tif (!match) fail(`malformed JSON number near byte ${index}`);\n\t\tindex += match[0].length;\n\t}\n\n\tfunction parseValue(path: string): void {\n\t\tskipWhitespace();\n\t\tconst ch = text[index];\n\t\tif (ch === \"{\") {\n\t\t\tparseObject(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tparseArray(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\treadJsonString();\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"t\") {\n\t\t\tconsumeLiteral(\"true\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"f\") {\n\t\t\tconsumeLiteral(\"false\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"n\") {\n\t\t\tconsumeLiteral(\"null\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"-\" || (ch !== undefined && ch >= \"0\" && ch <= \"9\")) {\n\t\t\tconsumeNumber();\n\t\t\treturn;\n\t\t}\n\t\tfail(`malformed JSON near byte ${index}`);\n\t}\n\n\tfunction parseObject(path: string): void {\n\t\tconst keys = new Set<string>();\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"}\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\twhile (index < text.length) {\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== '\"') fail(`expected object key near byte ${index}`);\n\t\t\tconst key = readJsonString();\n\t\t\tif (keys.has(key)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tkeys.add(key);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== \":\") fail(`expected ':' after object key near byte ${index}`);\n\t\t\tindex += 1;\n\t\t\tparseValue(`${path}.${key}`);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"}\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or '}' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON object\");\n\t}\n\n\tfunction parseArray(path: string): void {\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"]\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\tlet item = 0;\n\t\twhile (index < text.length) {\n\t\t\tparseValue(`${path}[${item}]`);\n\t\t\titem += 1;\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"]\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or ']' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON array\");\n\t}\n\n\tparseValue(\"$\");\n\tskipWhitespace();\n\tif (index !== text.length) fail(`trailing JSON token near byte ${index}`);\n}\n\n/**\n * Build a strict canonical JSON codec (D84/D87/D96).\n * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,\n * unpaired surrogates, and values that cannot round-trip through stable JSON.\n */\nexport function strictJsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\tassertNoUnpairedSurrogates(value);\n\t\t\treturn encoder.encode(strictStableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\tconst text = decoder.decode(bytes);\n\t\t\tassertNoDuplicateJsonObjectKeys(text);\n\t\t\tconst decoded = JSON.parse(text) as unknown;\n\t\t\tassertNoUnpairedSurrogates(decoded);\n\t\t\tconst canonical = encoder.encode(strictStableJsonString(decoded));\n\t\t\tif (!bytesEqual(bytes, canonical)) {\n\t\t\t\tthrow new TypeError(\"strictJsonCodec: bytes are not canonical stable JSON\");\n\t\t\t}\n\t\t\treturn decoded as T;\n\t\t},\n\t};\n}\n\n/** Default strict canonical JSON codec for unknown values. */\nexport const strictJsonCodec: Codec<unknown> = strictJsonCodecFor<unknown>();\n\n/** D113 neutral helper for strict canonical JSON UTF-8 bytes. */\nexport function strictCanonicalJsonBytes(value: unknown): Uint8Array {\n\treturn strictJsonCodec.encode(value);\n}\n\n/** Validate and normalize a host value into strict canonical JSON data. */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as StrictJsonValue;\n\t} catch (cause) {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tthrow new TypeError(`${label}: value is not strict JSON compatible: ${message}`, { cause });\n\t}\n}\n\n/** Validate and normalize a host value into a strict canonical JSON object. */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst normalized = assertStrictJsonValue(value, label);\n\tif (normalized === null || typeof normalized !== \"object\" || Array.isArray(normalized)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn normalized as StrictJsonObject;\n}\n","import { strictCanonicalJsonBytes, strictJsonCodec } from \"../json/codec.js\";\n\nexport type NodeVersioningLevel = 0 | 1;\n\n/**\n * D112 V1 node-version hash callback.\n *\n * The callback receives strict canonical JSON UTF-8 DATA bytes, not the raw host value.\n * Runtime V1 versioning encodes DATA with `strictCanonicalJsonBytes(value)` before calling hash.\n */\nexport type NodeVersionHashFn = (bytes: Uint8Array) => string;\n\nexport type NodeVersioningPolicy =\n\t| false\n\t| 0\n\t| 1\n\t| {\n\t\t\tlevel: NodeVersioningLevel;\n\t\t\thash?: NodeVersionHashFn;\n\t };\n\nexport type ResolvedNodeVersioningPolicy =\n\t| { readonly enabled: false }\n\t| { readonly enabled: true; readonly level: 0 }\n\t| { readonly enabled: true; readonly level: 1; readonly hash: NodeVersionHashFn };\n\nexport type NodeVersionV0 = {\n\treadonly level: 0;\n\treadonly counter: number;\n};\n\nexport type NodeVersionV1 = {\n\treadonly level: 1;\n\treadonly counter: number;\n\treadonly cid: string;\n\treadonly prev: string | null;\n};\n\nexport type NodeVersion = NodeVersionV0 | NodeVersionV1;\n\nexport type NodeVersionJson = NodeVersion;\n\nconst ABSENT_V1_SEED = Object.freeze({\n\t\"@graphrefly/node-version\": \"v1-absent\",\n});\n\nfunction fnv1a64(input: Uint8Array): string {\n\tlet hash = 0xcbf29ce484222325n;\n\tconst prime = 0x100000001b3n;\n\tfor (const byte of input) {\n\t\thash ^= BigInt(byte);\n\t\thash = BigInt.asUintN(64, hash * prime);\n\t}\n\treturn hash.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Default synchronous D112 V1 node-version hash over strict canonical JSON UTF-8 bytes.\n *\n * When hashing a host value directly, encode first:\n * `defaultNodeVersionHash(strictCanonicalJsonBytes(value))`.\n */\nexport function defaultNodeVersionHash(bytes: Uint8Array): string {\n\treturn `fnv1a64:${fnv1a64(bytes)}`;\n}\n\nfunction computeV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\tvalue: unknown,\n): string {\n\treturn policy.hash(strictCanonicalJsonBytes(value));\n}\n\nexport function assertNodeVersionDataCompatible(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): void {\n\tif (!policy.enabled || policy.level === 0) return;\n\tstrictCanonicalJsonBytes(value);\n}\n\nexport function snapshotNodeVersionData(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): unknown {\n\tif (!policy.enabled || policy.level === 0) return value;\n\tconst bytes = strictCanonicalJsonBytes(value);\n\treturn strictJsonCodec.decode(bytes);\n}\n\nexport function resolveNodeVersioningPolicy(\n\tpolicy: NodeVersioningPolicy | undefined,\n): ResolvedNodeVersioningPolicy {\n\tif (policy === false) return { enabled: false };\n\tif (policy === undefined || policy === 0) return { enabled: true, level: 0 };\n\tif (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };\n\tif (typeof policy === \"object\" && policy !== null) {\n\t\tif (policy.level === 0) return { enabled: true, level: 0 };\n\t\tif (policy.level === 1) {\n\t\t\treturn { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };\n\t\t}\n\t}\n\tthrow new Error(\"node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)\");\n}\n\nexport function createNodeVersion(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tinitialValue: unknown = ABSENT_V1_SEED,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: 0,\n\t\tcid: computeV1Cid(policy, initialValue),\n\t\tprev: null,\n\t});\n}\n\nexport function advanceNodeVersion(\n\tcurrent: NodeVersion | undefined,\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (current === undefined) return createNodeVersion(policy, value);\n\tif (policy.level === 0) {\n\t\treturn Object.freeze({ level: 0, counter: current.counter + 1 });\n\t}\n\tconst previous = current.level === 1 ? current.cid : null;\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: current.counter + 1,\n\t\tcid: computeV1Cid(policy, value),\n\t\tprev: previous,\n\t});\n}\n\nexport function cloneNodeVersion(version: NodeVersion | undefined): NodeVersion | undefined {\n\tif (version === undefined) return undefined;\n\tif (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: version.counter,\n\t\tcid: version.cid,\n\t\tprev: version.prev,\n\t});\n}\n\nexport function restoredV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\thasData: boolean,\n\tcache: unknown,\n): string {\n\treturn computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);\n}\n\nexport function validateNodeVersionJson(value: unknown, path: string): NodeVersionJson {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new Error(`restoreGraph: ${path} must be an object`);\n\t}\n\tconst record = value as Record<string, unknown>;\n\tif (record.level === 0) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\treturn Object.freeze({ level: 0, counter: record.counter as number });\n\t}\n\tif (record.level === 1) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\tif (typeof record.cid !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.cid must be a string`);\n\t\t}\n\t\tif (record.prev !== null && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string or null`);\n\t\t}\n\t\tif ((record.counter as number) === 0 && record.prev !== null) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be null when counter is 0`);\n\t\t}\n\t\tif ((record.counter as number) > 0 && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string when counter is > 0`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tlevel: 1,\n\t\t\tcounter: record.counter as number,\n\t\t\tcid: record.cid,\n\t\t\tprev: record.prev,\n\t\t});\n\t}\n\tthrow new Error(`restoreGraph: ${path}.level must be 0 or 1`);\n}\n","import { currentBatch, deferToBatch } from \"../batch/batch.js\";\nimport { deferRewire, scheduleBoundaryDrain } from \"../batch/boundary.js\";\nimport type { DeliveryMeta } from \"../ctx/types.js\";\nimport type { LockId, Message, PullDemand, Wave } from \"../protocol/messages.js\";\nimport {\n\tisDeferredTier,\n\tisPauseBufferedTier,\n\tisUpAllowed,\n\tisValueTier,\n\tmessageTier,\n\tSENTINEL,\n} from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { normalizePullDemand, validateDownPayloads } from \"./protocol-guards.js\";\nimport type { UpRouteState } from \"./types.js\";\nimport {\n\tadvanceNodeVersion,\n\tassertNodeVersionDataCompatible,\n\tsnapshotNodeVersionData,\n} from \"./versioning.js\";\n\nexport function nodeDown<T>(self: NodeRuntimeHost<T>, msgs: Wave): void {\n\tif (self._released) return;\n\tvalidateDownPayloads(msgs);\n\tconst deliveryWave = {};\n\tconst assertVersionDataCompatible = (wave: readonly Message[]) => {\n\t\tfor (const m of wave) {\n\t\t\tif (m[0] === \"DATA\") assertNodeVersionDataCompatible(self._version.policy, m[1]);\n\t\t}\n\t};\n\tconst snapshotVersionData = (wave: readonly Message[]): Message[] =>\n\t\twave.map((m) =>\n\t\t\tm[0] === \"DATA\"\n\t\t\t\t? ([\"DATA\", snapshotNodeVersionData(self._version.policy, m[1])] as Message)\n\t\t\t\t: m,\n\t\t);\n\tassertVersionDataCompatible(msgs);\n\t// Terminal-is-forever (R-terminal / D17 / B30): once COMPLETE/ERROR has been emitted the\n\t// node is final — a self-emit (state.set / ctx.down) in a LATER wave is a no-op, never\n\t// resurrecting the cache or re-emitting. The COMPLETE/ERROR arms below also self-guard\n\t// against a double terminal, but DATA/RESOLVED/INVALIDATE had no entry guard, so a\n\t// post-terminal set() would overwrite cache + emit DATA. R-teardown-terminal-relay / D65\n\t// carves out the only post-terminal exception: TEARDOWN still relays downstream for unwire\n\t// without reopening value output. A single wave that goes terminal mid-loop (e.g.\n\t// [COMPLETE, TEARDOWN]) is unaffected: _terminal is still undefined at entry.\n\t// Resubscribable reset clears _terminal before any re-emit.\n\tif (self._value.terminal !== undefined) {\n\t\tif (!msgs.some((m) => m[0] === \"TEARDOWN\")) return;\n\t\tself._value.hasTorndown = true;\n\t\tif (self._slot.resetOnTeardown) {\n\t\t\tself._value.cache = SENTINEL;\n\t\t\tself._value.hasData = false;\n\t\t}\n\t\tself._emitToSubs([\"TEARDOWN\"], { wave: deliveryWave, last: true });\n\t\treturn;\n\t}\n\tlet sorted: Message[] = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));\n\t// R-same-wave-merge: collapse repeated INVALIDATE in one wave (Q9) so the\n\t// cleanup hook + downstream broadcast fire at most once.\n\tconst firstInvalidate = sorted.findIndex((m) => m[0] === \"INVALIDATE\");\n\tif (firstInvalidate !== -1) {\n\t\tsorted = sorted.filter((m, i) => m[0] !== \"INVALIDATE\" || i === firstInvalidate);\n\t}\n\t// R-teardown-complete: a TEARDOWN reaching a non-terminal node synthesizes a\n\t// COMPLETE prefix (so firstValueFrom-style bridges resolve), unless the wave\n\t// already carries a terminal or the node already tore down.\n\tconst hasTeardown = sorted.some((m) => m[0] === \"TEARDOWN\");\n\tconst hasTerminal = sorted.some((m) => m[0] === \"COMPLETE\" || m[0] === \"ERROR\");\n\tif (\n\t\thasTeardown &&\n\t\t!hasTerminal &&\n\t\tself._value.terminal === undefined &&\n\t\t!self._value.hasTorndown\n\t) {\n\t\tsorted = [[\"COMPLETE\"], ...sorted];\n\t}\n\t// R-batch-coalesce (D12): inside a batch, emit DIRTY immediately but defer the\n\t// tier-3 settle slice to commit so a shared downstream recomputes once. Only\n\t// external emits defer (fn emits during commit run normally).\n\tif (!self._wave.insideRunWave && currentBatch()) {\n\t\tconst deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));\n\t\tif (deferred.length > 0) {\n\t\t\tif (!self._wave.emittedDirtyThisWave) {\n\t\t\t\tself._wave.emittedDirtyThisWave = true;\n\t\t\t\tself._value.status = \"dirty\";\n\t\t\t\tself._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t\t}\n\t\t\tself._wave.batchDirtyOwed = true; // BH1: owe a balancing RESOLVED on rollback\n\t\t\tdeferToBatch(self as unknown as Node<unknown>, deferred);\n\t\t\treturn;\n\t\t}\n\t}\n\t// R-pause-modes / R-async-paused: defer the settle slice (tier 3/4) into the\n\t// pause buffer while paused; tier 0-2 (DIRTY/PAUSE/RESUME), tier 5 (terminal),\n\t// tier 6 (TEARDOWN) bypass so end-of-stream + control always reach observers.\n\tif (self._shouldBufferOnPause()) {\n\t\tconst buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));\n\t\tif (buffered.length > 0) {\n\t\t\t// B36 / R-resolved-undirty: buffering a settle slice still means this fn wave\n\t\t\t// produced a settle. Without this, _runWave sees \"dirty + no settle\" and\n\t\t\t// synthesizes a RESOLVED that pierces the pause while the DATA waits in the buffer.\n\t\t\tself._wave.emittedSettleThisWave = true;\n\t\t\tself._control.pauseBuffer.push(buffered);\n\t\t}\n\t\tsorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));\n\t\tif (sorted.length === 0) return;\n\t}\n\tlet dataCount = 0;\n\tlet hasTier3 = false;\n\tlet hasResolved = false;\n\tfor (const m of sorted) {\n\t\tif (m[0] === \"DATA\") dataCount++;\n\t\tif (m[0] === \"RESOLVED\") hasResolved = true;\n\t\tif (isValueTier(m[0])) hasTier3 = true;\n\t}\n\t// EC2 / R-resolved-undirty tier-3 exclusivity: a wave's tier-3 slot is >=1 DATA\n\t// (occurrence) XOR exactly 1 RESOLVED (undirty) — never mixed. Reject fail-fast.\n\tif (dataCount >= 1 && hasResolved) {\n\t\tthrow new Error(\n\t\t\t\"down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)\",\n\t\t);\n\t}\n\tconst plannedVersions: Array<NodeVersion | undefined> = new Array(sorted.length);\n\tif (dataCount > 0) {\n\t\tlet plannedVersion = self._version.value;\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst m = sorted[i];\n\t\t\tif (m[0] !== \"DATA\") continue;\n\t\t\tplannedVersion = advanceNodeVersion(plannedVersion, self._version.policy, m[1]);\n\t\t\tplannedVersions[i] = plannedVersion;\n\t\t}\n\t}\n\n\t// Synthesize a leading DIRTY for an EXTERNAL tier-3 emit (R-dirty-before-data), and for\n\t// PULL demand fns only when they actually emit tier-3. A no-op pull helper must stay silent.\n\tif (\n\t\thasTier3 &&\n\t\t(!self._wave.insideRunWave || self._control.pullDirtyOwed) &&\n\t\t!self._wave.emittedDirtyThisWave\n\t) {\n\t\tself._wave.emittedDirtyThisWave = true;\n\t\tself._value.status = \"dirty\";\n\t\tself._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t}\n\n\tfor (let i = 0; i < sorted.length; i++) {\n\t\tconst m = sorted[i];\n\t\tconst delivery = { wave: deliveryWave, last: i === sorted.length - 1 };\n\t\t// R-resolved-undirty (D49): a tier-3+ emit this wave means the fn produced a settle,\n\t\t// so no synthesized undirty RESOLVED is owed (see _runWave).\n\t\tif (isDeferredTier(m[0])) self._wave.emittedSettleThisWave = true;\n\t\tif (m[0] === \"DIRTY\") {\n\t\t\tif (!self._wave.emittedDirtyThisWave) {\n\t\t\t\tself._wave.emittedDirtyThisWave = true;\n\t\t\t\tself._value.status = \"dirty\";\n\t\t\t\tself._emitToSubs([\"DIRTY\"], delivery);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"DATA\") {\n\t\t\tconst v = m[1] as T;\n\t\t\t// R-resolved-undirty (D49): every value-occurrence is emitted as DATA — the\n\t\t\t// substrate never substitutes DATA->RESOLVED on value-equality. Dedup is opt-in\n\t\t\t// at the operator layer (distinctUntilChanged), never a substrate behavior.\n\t\t\tself._value.cache = v;\n\t\t\tself._value.hasData = true;\n\t\t\tself._value.status = \"settled\";\n\t\t\tself._version.value = plannedVersions[i];\n\t\t\tif (self._slot.replayN > 0) {\n\t\t\t\tself._value.replayRing.push(v);\n\t\t\t\tif (self._value.replayRing.length > self._slot.replayN) self._value.replayRing.shift();\n\t\t\t}\n\t\t\tself._emitToSubs([\"DATA\", v], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"RESOLVED\") {\n\t\t\tself._value.status = self._value.hasData ? \"resolved\" : \"sentinel\";\n\t\t\tself._emitToSubs([\"RESOLVED\"], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"INVALIDATE\") {\n\t\t\tself._invalidate(delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"COMPLETE\") {\n\t\t\tif (self._value.terminal !== undefined) continue;\n\t\t\tself._value.terminal = true;\n\t\t\tself._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\tself._value.status = \"completed\";\n\t\t\tself._emitToSubs([\"COMPLETE\"], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"ERROR\") {\n\t\t\tif (self._value.terminal !== undefined) continue;\n\t\t\tself._value.terminal = m[1];\n\t\t\tself._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\tself._value.status = \"errored\";\n\t\t\tself._emitToSubs([\"ERROR\", m[1]], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"TEARDOWN\") {\n\t\t\tself._value.hasTorndown = true;\n\t\t\tif (self._slot.resetOnTeardown) {\n\t\t\t\tself._value.cache = SENTINEL;\n\t\t\t\tself._value.hasData = false;\n\t\t\t}\n\t\t\tself._emitToSubs([\"TEARDOWN\"], delivery);\n\t\t}\n\t\t// PAUSE / RESUME — control slice.\n\t}\n\n\tif (!self._wave.insideRunWave) self._wave.emittedDirtyThisWave = false;\n}\n\nexport function nodeUp<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsgs: Wave,\n\ttowardDep?: number,\n\troute?: UpRouteState,\n): void {\n\tif (self._released) return;\n\tconst routeState = route ?? { demandFired: new Map() };\n\tfor (const m of msgs) {\n\t\tif (!isUpAllowed(m[0])) {\n\t\t\tthrow new Error(\n\t\t\t\t`ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"PAUSE\") {\n\t\t\t// PAUSE is NODE-TARGETED (R-up-routing): it ACQUIRES a lock, so there is no\n\t\t\t// pre-existing holder to route to — a controller targets the node directly.\n\t\t\tself._pauseAcquire(m[1]);\n\t\t} else if (m[0] === \"RESUME\") {\n\t\t\t// R-up-routing (D269): RESUME is pause-lock release only.\n\t\t\tif (self._control.pauseLockset.has(m[1])) {\n\t\t\t\t// a pause lock held HERE → release LOCALLY (normal pause/resume, R-pause-lockset).\n\t\t\t\tself._pauseRelease(m[1]);\n\t\t\t} else {\n\t\t\t\t// not held here → forward UP the declared cone to find the holder.\n\t\t\t\tself._forwardUp(m, towardDep, routeState);\n\t\t\t}\n\t\t} else if (m[0] === \"PULL\") {\n\t\t\t// R-up-routing / R-pull (D269/D272): DEMAND-IF-PULL-HOLDER-ELSE-FORWARD-UP.\n\t\t\tconst demand = normalizePullDemand(m[1]);\n\t\t\tif (self._slot.pull && demand.pullId === self._slot.pullLock) {\n\t\t\t\tif (!self._markDemandRouted(demand.pullId, routeState)) self._onDemand(demand);\n\t\t\t} else {\n\t\t\t\tself._forwardUp([\"PULL\", demand], towardDep, routeState);\n\t\t\t}\n\t\t} else if (self._slot.deps.length === 0) {\n\t\t\t// R-up-at-source (D38): a depless source is the terminus of upstream control.\n\t\t\t// INVALIDATE → HONOR the invalidate-request. Routed through _down (NOT a direct\n\t\t\t// _invalidate call, QA A-2) so the invalidate-request respects batch-defer (D12)\n\t\t\t// and pause-buffer exactly like a downstream-originated INVALIDATE; _down's\n\t\t\t// INVALIDATE branch calls _invalidate() (clear cache → SENTINEL, fire onInvalidate,\n\t\t\t// broadcast downstream). Outside batch/pause it is identical to a direct call.\n\t\t\t// DIRTY / TEARDOWN → DROP (no coherent terminus action; self-dirty would wedge\n\t\t\t// downstream awaiting a settle that never comes; source lifecycle is source-owned).\n\t\t\tif (m[0] === \"INVALIDATE\") self._down([[\"INVALIDATE\"]]);\n\t\t} else {\n\t\t\t// dep-bearing intermediate: forward DIRTY/INVALIDATE/TEARDOWN up toward deps.\n\t\t\tself._forwardUp(m, towardDep, routeState);\n\t\t}\n\t}\n}\n\nexport function nodeMarkDemandRouted<T>(\n\tself: NodeRuntimeHost<T>,\n\tlockId: LockId,\n\troute: UpRouteState,\n): boolean {\n\tlet holders = route.demandFired.get(lockId);\n\tif (holders === undefined) {\n\t\tholders = new Set();\n\t\troute.demandFired.set(lockId, holders);\n\t}\n\tconst node = self as unknown as Node<unknown>;\n\tif (holders.has(node)) return true;\n\tholders.add(node);\n\treturn false;\n}\n\nexport function nodeForwardUp<T>(\n\tself: NodeRuntimeHost<T>,\n\tm: Message,\n\ttowardDep: number | undefined,\n\troute: UpRouteState,\n): void {\n\tif (self._slot.deps.length === 0) return; // depless source terminus → drop\n\tif (towardDep !== undefined) {\n\t\tconst d = self._slot.deps[towardDep];\n\t\tif (d !== undefined) nodeRuntimeHost(d)._up([m], undefined, route);\n\t} else {\n\t\tfor (const dep of self._slot.deps) nodeRuntimeHost(dep)._up([m], undefined, route);\n\t}\n}\n\nexport function nodeIsPaused<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn self._control.pauseLockset.size > 0;\n}\n\nexport function nodeHasBoundaryPauseLock<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._slot.pausable === false) return false;\n\treturn self._control.pauseLockset.size > 0;\n}\n\nexport function nodeIsAsyncPool<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn (\n\t\tself._slot.handle !== null &&\n\t\tself._slot.dispatcher.poolKind(self._slot.handle.poolId) === \"async\"\n\t);\n}\n\nexport function nodePauseAcquire<T>(self: NodeRuntimeHost<T>, lockId: unknown): void {\n\tself._control.pauseLockset.add(lockId); // Set => same-id repeat PAUSE is idempotent\n}\n\nexport function nodePauseRelease<T>(self: NodeRuntimeHost<T>, lockId: unknown): void {\n\tif (!self._control.pauseLockset.has(lockId)) return; // unknown id => no-op\n\tself._control.pauseLockset.delete(lockId);\n\t// R-pull (D59 / D272): releasing an EXTERNAL pause lock can unblock an owed demand.\n\t// Pull quiet is activePull-derived and never stored in pauseLockset.\n\tif (self._slot.pull && self._control.demandOwed !== undefined) self._fireOwedDemandIfReady();\n\tif (self._hasBoundaryPauseLock()) return; // another external lock still held => stay paused\n\tscheduleBoundaryDrain(self._core);\n\tif (self._slot.pull) return; // pull nodes stay quiet until PULL, even after external resume\n\tself._onResume();\n}\n\nexport function nodeOnResume<T>(self: NodeRuntimeHost<T>): void {\n\t// BH3: a node that terminated while paused discards its buffer and never\n\t// replays/recomputes (terminal-is-forever).\n\tif (self._value.terminal !== undefined) {\n\t\tself._control.pauseBuffer = [];\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._control.demandOwed = undefined;\n\t\tself._control.activePull = undefined;\n\t\tself._control.pullDirtyOwed = false;\n\t\treturn;\n\t}\n\t// Non-pull pause/resume (R-pause-modes): drain buffered settle slices (resumeAll /\n\t// async-at-paused, R-async-paused), then fire a coalesced dep-wave once (default mode).\n\t// A PULL node does not resume by draining here; its demand fires through _onDemand.\n\tif (self._control.pauseBuffer.length > 0) {\n\t\tconst buf = self._control.pauseBuffer;\n\t\tself._control.pauseBuffer = [];\n\t\tfor (const wave of buf) self._down(wave);\n\t}\n\tif (self._control.pausedDepWaveOccurred) {\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._tryRun();\n\t}\n}\n\nexport function nodeCanFireDemand<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._value.terminal !== undefined || self._wave.pending > 0) return false;\n\treturn self._control.pauseLockset.size === 0;\n}\n\nexport function nodeDeliverPullDemand<T>(self: NodeRuntimeHost<T>, demand: PullDemand): void {\n\tself._control.demandOwed = undefined;\n\tself._control.activePull = demand;\n\tself._control.inDeliverDemand = true;\n\ttry {\n\t\tself._firePullDemand();\n\t} finally {\n\t\tself._control.activePull = undefined;\n\t\tself._control.inDeliverDemand = false;\n\t}\n}\n\nexport function nodeOnDemand<T>(self: NodeRuntimeHost<T>, demand: PullDemand): void {\n\tif (self._control.inDeliverDemand) return; // re-entrant demand during an active delivery → drop (1:1)\n\tif (self._canFireDemand()) self._deliverPullDemand(demand);\n\telse self._control.demandOwed = demand; // latest owed params wins (D269/D272)\n}\n\nexport function nodeFirePullDemand<T>(self: NodeRuntimeHost<T>): void {\n\tlet drainedBuffer = false;\n\tif (self._control.pauseBuffer.length > 0) {\n\t\tconst buf = self._control.pauseBuffer;\n\t\tself._control.pauseBuffer = [];\n\t\tfor (const wave of buf) self._down(wave);\n\t\tdrainedBuffer = true;\n\t}\n\tif (drainedBuffer) return;\n\tif (self._control.pausedDepWaveOccurred) {\n\t\t// QA-B2: only deliver if the fn can actually run this wave (settle-ready + first-run gate\n\t\t// open). A gated run emits no DATA, so emitting the leading DIRTY would STRAND downstream\n\t\t// — the exact wedge this feature exists to prevent (NoWedgeWhileQuiet). When gated, stay\n\t\t// SILENT and KEEP _pausedDepWaveOccurred so a later demand (once every dep has settled)\n\t\t// delivers. Mirrors _settleRewire's pre-_markDirty gate.\n\t\tconst gated =\n\t\t\tself._slot.handle !== null &&\n\t\t\t!self._wave.hasCalledFnOnce &&\n\t\t\t!(self._slot.partial || self._allDepsSettled());\n\t\tif (self._wave.pending > 0 || gated) return;\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._control.pullDirtyOwed = true;\n\t\ttry {\n\t\t\tself._tryRun(); // fn DATA triggers DIRTY-before-DATA; no DATA means no output.\n\t\t} finally {\n\t\t\tself._control.pullDirtyOwed = false;\n\t\t}\n\t\treturn;\n\t}\n\tif (self._slot.handle !== null) {\n\t\tif (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._control.pullDirtyOwed = true;\n\t\ttry {\n\t\t\tself._runWave();\n\t\t} finally {\n\t\t\tself._control.pullDirtyOwed = false;\n\t\t}\n\t}\n}\n\nexport function nodeFireOwedDemandIfReady<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._control.inDeliverDemand) return; // don't re-enter during an active delivery (1:1, QA guard)\n\tif (self._slot.pull && self._control.demandOwed !== undefined && self._canFireDemand()) {\n\t\tself._deliverPullDemand(self._control.demandOwed);\n\t}\n}\n\nexport function nodeShouldBufferOnPause<T>(self: NodeRuntimeHost<T>): boolean {\n\t// D44: pausable mode is the OUTER gate over R-async-paused buffering.\n\t// false: ignore PAUSE/RESUME ENTIRELY — never buffer, keep producing (R-pause-modes; resolves B20).\n\tif (self._slot.pausable === false) return false;\n\tif (!self._isPaused() && !self._isPullQuiet()) return false;\n\t// resumeAll: production-gating — buffer the node's own (sync/async) settle slice too.\n\tif (self._slot.pausable === \"resumeAll\") return true;\n\t// true (default): PAUSE gates recomputation/propagation, NOT a leaf source's own production.\n\t// An async COMPUTE node's (deps>0) in-flight result buffers (R-async-paused / C-2); a depless\n\t// async leaf source's own production delivers immediately (R-pause-modes / C-10).\n\tif (!self._wave.insideRunWave && self._isAsyncPool() && self._slot.deps.length > 0) return true;\n\treturn false;\n}\n\nexport function nodeInvalidate<T>(self: NodeRuntimeHost<T>, delivery?: DeliveryMeta): void {\n\tif (!self._value.hasData) return; // never-populated or already-reset → no-op\n\tself._value.cache = SENTINEL;\n\tself._value.hasData = false;\n\tself._value.status = \"sentinel\";\n\tself._value.replayRing = []; // BH6: invalidated values are stale — don't replay them\n\tfor (const fn of self._hooks.onInvalidate) fn();\n\tself._emitToSubs([\"INVALIDATE\"], delivery);\n}\n\nexport function nodeAllDepsTerminal<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._slot.deps.length === 0) return false;\n\tfor (const tm of self._dep.terminal) if (tm === undefined) return false;\n\treturn true;\n}\n\nexport function nodeResetLifecycle<T>(self: NodeRuntimeHost<T>): void {\n\tfor (const u of self._dep.unsubs) if (u) u();\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tself._lifecycle.subscribers.clear();\n\tself._lifecycle.activated = false;\n\tself._value.terminal = undefined;\n\tself._value.hasTorndown = false;\n\tself._wave.hasCalledFnOnce = false;\n\tself._resetDepState();\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._value.replayRing = []; // BH6\n\tconst isCompute = self._slot.handle !== null || self._slot.deps.length > 0;\n\tif (isCompute) {\n\t\tself._value.cache = SENTINEL;\n\t\tself._value.hasData = false;\n\t\tself._value.status = \"sentinel\";\n\t} else {\n\t\tself._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t}\n\tif (!self._privateState.persist) self._privateState.value = SENTINEL;\n}\n\nexport function nodeEmitToSubs<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsg: Message,\n\tdelivery?: DeliveryMeta,\n): void {\n\tif (self._released) return;\n\t// Copy guards against subscribe/unsubscribe during iteration.\n\tconst subs = [...self._lifecycle.subscribers];\n\tfor (const sink of subs) sink(msg, delivery);\n}\n\nexport function nodeCommitBatchedWave<T>(self: NodeRuntimeHost<T>, wave: Wave): void {\n\tself._wave.batchDirtyOwed = false; // commit delivers the real settle (BH1)\n\tself._down(wave); // batch is inactive at commit -> processes normally\n}\n\nexport function nodeRollbackBatched<T>(self: NodeRuntimeHost<T>): void {\n\t// BH1: keyed on _batchDirtyOwed (not _emittedDirtyThisWave, which a fn wave between\n\t// defer and rollback would have reset) so the balancing RESOLVED is never skipped.\n\tif (self._wave.batchDirtyOwed) {\n\t\tself._wave.batchDirtyOwed = false;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t\tself._emitToSubs([\"RESOLVED\"]);\n\t}\n}\n\nexport function nodeDeferBoundary<T>(\n\tself: NodeRuntimeHost<T>,\n\tfn: () => void,\n\tbatchToken?: object,\n): void {\n\tdeferRewire(self._core, fn, {\n\t\tbatchToken,\n\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t});\n}\n","import { currentBoundaryBatchToken, deferAfterBatchForTarget } from \"../batch/batch.js\";\nimport { deferRewire } from \"../batch/boundary.js\";\nimport type { NodeFn } from \"../ctx/types.js\";\nimport type { Wave } from \"../protocol/messages.js\";\nimport { errorPayload, SENTINEL } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { notifyTopologyDepsChanged } from \"./runtime-accessors.js\";\nimport type { RewireOp } from \"./types.js\";\n\nexport function nodeRequestRewireNext<T>(self: NodeRuntimeHost<T>, op: RewireOp): void {\n\tdeferRewire(self._core, () => self._applyRewireNext(op), {\n\t\tbatchToken: currentBoundaryBatchToken(),\n\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t});\n}\n\nexport function nodeRequestUpNext<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsgs: Wave,\n\ttowardDep?: number,\n): void {\n\tdeferRewire(\n\t\tself._core,\n\t\t() => {\n\t\t\tif (!self._released) self._up(msgs, towardDep);\n\t\t},\n\t\t{\n\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t\t},\n\t);\n}\n\nexport function nodeApplyRewireNext<T>(self: NodeRuntimeHost<T>, op: RewireOp): void {\n\tif (self._released) return;\n\ttry {\n\t\t// D62 / R-rewire-deferred: terminal seals output but does NOT cancel queued topology.\n\t\t// Public/immediate rewire of a terminal node still rejects; the exception is only for\n\t\t// self-triggered ops already issued before terminal and now draining at the boundary.\n\t\tif (op.kind === \"add\") {\n\t\t\tconst next = self._slot.deps.includes(op.dep)\n\t\t\t\t? [...self._slot.deps]\n\t\t\t\t: [...self._slot.deps, op.dep];\n\t\t\tself._rewire(next, op.fn, { allowTerminalOwner: true });\n\t\t} else if (op.kind === \"remove\") {\n\t\t\tself._rewire(\n\t\t\t\tself._slot.deps.filter((d) => d !== op.dep),\n\t\t\t\top.fn,\n\t\t\t\t{ allowTerminalOwner: true },\n\t\t\t);\n\t\t} else {\n\t\t\tself._rewire(self._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });\n\t\t}\n\t} catch (e) {\n\t\t// An invalid deferred op (cycle / self / non-resubscribable terminal dep) surfaces as\n\t\t// an ERROR on this node (D30-consistent) rather than stranding the rest of the drain\n\t\t// queue. Reachable only on misuse — higher-order operator inners are fresh, acyclic\n\t\t// leaf sources. Coerce a SENTINEL reason (a rewire fn that `throw undefined`s) to a real\n\t\t// Error so _down's R-data-payload guard does not itself throw out of the drain.\n\t\tself._down([[\"ERROR\", errorPayload(e, \"rewireNext op failed\")]]);\n\t}\n}\n\nexport function nodeRewire<T>(\n\tself: NodeRuntimeHost<T>,\n\tnewDeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: { allowTerminalOwner?: boolean } = {},\n): boolean {\n\tconst node = self as unknown as Node<unknown>;\n\t// ── rejects (R-rewire / D42) ──\n\tif (self._value.terminal !== undefined && !opts.allowTerminalOwner)\n\t\tthrow new Error(\n\t\t\t\"rewire: node is terminal (completed/errored) — cannot rewire (R-rewire / D42)\",\n\t\t);\n\tif (self._wave.insideRunWave)\n\t\tthrow new Error(\n\t\t\t\"rewire: mid-fn topology mutation — a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)\",\n\t\t);\n\tif (self._wave.inDepMutation)\n\t\tthrow new Error(\n\t\t\t\"rewire: reentrant dep mutation — another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)\",\n\t\t);\n\tif (newDeps.includes(node)) throw new Error(\"rewire: self-dependency rejected (R-rewire / D42)\");\n\tconst oldDeps = self._slot.deps;\n\tconst added = newDeps.filter((d) => !oldDeps.includes(d));\n\tfor (const d of added) {\n\t\tif (self._reachableUpstream(d, node))\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: would create a cycle — dep already transitively depends on this node (R-rewire / D42)\",\n\t\t\t);\n\t\tconst dep = nodeRuntimeHost(d);\n\t\tif (dep._value.terminal !== undefined && !dep._slot.resubscribable)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: cannot add a non-resubscribable terminal dep — would wedge (R-rewire / D42)\",\n\t\t\t);\n\t\tself._assertRewireDepOwner(d);\n\t}\n\n\tif (\n\t\tdeferAfterBatchForTarget(node, () => {\n\t\t\tself._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });\n\t\t})\n\t) {\n\t\treturn true;\n\t}\n\tif (!self._lifecycle.activated) self._restoredActivationPending = false;\n\n\tself._wave.inDepMutation = true;\n\tself._wave.rewireRunPending = false;\n\tlet zeroDepUnDirty = false;\n\ttry {\n\t\t// fn swap (SD-1): re-register against the same pool, then release the old handle\n\t\t// (B15) so the rewired-away fn closure is GC'd and its dispatcher slot is reused —\n\t\t// a rewire-heavy graph (CSP-2.7 *Map) no longer leaks a handle per swap. Register\n\t\t// first, then unregister the old: self._slot.handle never points at a freed slot, and a\n\t\t// null old handle (a passthrough/state node gaining a fn) has nothing to free.\n\t\tconst oldHandle = self._slot.handle;\n\t\tself._slot.handle = self._slot.dispatcher.register(fn, self._slot.pool);\n\t\tif (oldHandle !== null) self._slot.dispatcher.unregister(oldHandle);\n\n\t\tconst removed = oldDeps.filter((d) => !newDeps.includes(d));\n\t\tlet removedDirtyContributor = false;\n\t\tfor (const d of removed) {\n\t\t\tconst oldIdx = oldDeps.indexOf(d);\n\t\t\tif (self._dep.dirty[oldIdx]) {\n\t\t\t\tremovedDirtyContributor = true;\n\t\t\t\tself._wave.pending--;\n\t\t\t}\n\t\t\tif (self._lifecycle.activated) {\n\t\t\t\tconst box = self._dep.idxBoxes[oldIdx];\n\t\t\t\tif (box) box.v = -1; // drain: any stale in-flight callback drops\n\t\t\t\tconst unsub = self._dep.unsubs[oldIdx];\n\t\t\t\tif (unsub) unsub(); // stops the removed dep's edge — no further delivery\n\t\t\t}\n\t\t}\n\n\t\t// Rebuild per-dep parallel arrays in newDeps order; kept deps carry their state\n\t\t// + subscription, added deps start fresh (R-rewire Q1/Q4).\n\t\tconst n = newDeps.length;\n\t\tconst newBatch: Array<unknown[] | null> = new Array(n).fill(null);\n\t\tconst newPrev: unknown[] = new Array(n).fill(SENTINEL);\n\t\tconst newHasData: boolean[] = new Array(n).fill(false);\n\t\tconst newDirty: boolean[] = new Array(n).fill(false);\n\t\tconst newTier: number[] = new Array(n).fill(0);\n\t\tconst newTerminal: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\tconst newTerminalInput: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\tconst newUnsubs: Array<() => void> = new Array(n);\n\t\tconst newBoxes: Array<{ v: number }> = new Array(n);\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tconst oldIdx = oldDeps.indexOf(newDeps[j]);\n\t\t\tif (oldIdx !== -1) {\n\t\t\t\tnewBatch[j] = self._dep.batch[oldIdx];\n\t\t\t\tnewPrev[j] = self._dep.prev[oldIdx];\n\t\t\t\tnewHasData[j] = self._dep.hasData[oldIdx];\n\t\t\t\tnewDirty[j] = self._dep.dirty[oldIdx];\n\t\t\t\tnewTier[j] = self._dep.tier[oldIdx];\n\t\t\t\tnewTerminal[j] = self._dep.terminal[oldIdx];\n\t\t\t\tnewUnsubs[j] = self._dep.unsubs[oldIdx];\n\t\t\t\t// carry the kept dep's subscription box and point it at the new index (O(1) reroute)\n\t\t\t\tconst box = self._dep.idxBoxes[oldIdx];\n\t\t\t\tif (box) box.v = j;\n\t\t\t\tnewBoxes[j] = box;\n\t\t\t}\n\t\t}\n\t\tself._slot.deps = newDeps;\n\t\tself._dep.batch = newBatch;\n\t\tself._dep.prev = newPrev;\n\t\tself._dep.hasData = newHasData;\n\t\tself._dep.dirty = newDirty;\n\t\tself._dep.tier = newTier;\n\t\tself._dep.terminal = newTerminal;\n\t\tself._dep.terminalInput = newTerminalInput;\n\t\tself._dep.unsubs = newUnsubs;\n\t\tself._dep.idxBoxes = newBoxes;\n\t\tself._dep.waveData = newDeps.map(() => []);\n\t\tself._dep.waveTokens = new Array(newDeps.length).fill(undefined);\n\t\tself._syncCtx = null;\n\n\t\t// Subscribe added deps — push-on-subscribe (R-push-subscribe) delivers a cached\n\t\t// dep's DATA here, which drives _maybeRun; a SENTINEL dep delivers START only.\n\t\tif (self._lifecycle.activated) {\n\t\t\tfor (const d of added) self._subscribeDepAt(d);\n\t\t}\n\t\tnotifyTopologyDepsChanged(node, oldDeps, newDeps);\n\n\t\t// Q6 auto-settle: removing the sole dirty contributor closes the wave. With deps\n\t\t// remaining, request the atomic settle (recompute → DATA for a value; a no-emit fn\n\t\t// gets a substrate-synthesized undirty RESOLVED per R-resolved-undirty/D49 — NOT\n\t\t// equals-absorption, which is gone). With zero deps the node is inert (degenerate\n\t\t// fn-no-deps) — just un-dirty downstream. Cache is preserved either way (Q7).\n\t\tif (removedDirtyContributor && self._wave.pending === 0 && self._value.status === \"dirty\") {\n\t\t\tif (newDeps.length > 0) self._wave.rewireRunPending = true;\n\t\t\telse zeroDepUnDirty = true;\n\t\t}\n\t} finally {\n\t\tself._wave.inDepMutation = false;\n\t}\n\n\t// Atomic post-mutation settle (outside the reentrancy guard so a fresh wave runs\n\t// normally): ONE two-phase DIRTY→DATA recompute if any added dep delivered data or a\n\t// sole-dirty dep was removed; else the zero-dep un-dirty via _down (pause/batch-safe).\n\tif (self._wave.rewireRunPending) {\n\t\tself._wave.rewireRunPending = false;\n\t\tself._settleRewire();\n\t} else if (zeroDepUnDirty) {\n\t\tif (self._wave.emittedDirtyThisWave) self._down([[\"RESOLVED\"]]);\n\t\telse self._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t}\n\treturn false;\n}\n","/**\n * The node primitive — the thinnest substrate object (R-node-thin / D5).\n *\n * Holds a fn handle + deps + the wave state machine; ZERO inspection cruft\n * (naming/find/describe are the graph layer, CSP-2). Canonical authority:\n * ~/src/graphrefly/spec/rules.jsonl (R-node-*, R-two-phase, R-diamond, R-resolved-undirty,\n * R-first-run-gate, R-push-subscribe, R-rom-ram, R-fn-contract, R-initial, R-ctx-up).\n *\n * Slice 1 = core wave: state node, compute node, two-phase DIRTY->DATA, diamond\n * pending-counter join, first-run gate, substrate-synthesized undirty RESOLVED\n * (R-resolved-undirty / D49 — no equals-substitution; every occurrence is DATA),\n * push-on-subscribe, lazy activation, ROM/RAM. Lifecycle (terminal/INVALIDATE/cleanup),\n * control (PAUSE/async), batch, and dynamicNode land in later slices.\n */\n\nimport { enterWave, exitWave } from \"../batch/boundary.js\";\nimport type { Ctx, CtxState, DeliveryMeta, NodeFn, Sink } from \"../ctx/types.js\";\nimport { defaultDispatcher, type Handle } from \"../dispatcher/index.js\";\nimport { EnvironmentDrivers } from \"../graph/environment.js\";\nimport {\n\ttype LockId,\n\ttype Message,\n\ttype PullDemand,\n\tSENTINEL,\n\ttype Wave,\n} from \"../protocol/messages.js\";\nimport {\n\ttype CleanupHooks,\n\ttype ControlState,\n\ttype DepBookkeeping,\n\ttype LifecycleState,\n\tmakeDepBookkeeping,\n\tNodeCore,\n\ttype NodeId,\n\ttype NodeSlot,\n\ttype PrivateState,\n\ttype SyncCtxState,\n\ttype ValueState,\n\ttype VersionState,\n\ttype WaveState,\n} from \"./core.js\";\nimport {\n\tnodeBuildCtx,\n\tnodeMakeCtx,\n\tnodeMakeState,\n\tnodeRefreshCtx,\n} from \"./node-context-runtime.js\";\nimport {\n\tnodeAllDepsSettled,\n\tnodeDepProjectionHasData,\n\tnodeMarkDirty,\n\tnodeMaybeRun,\n\tnodePassthroughEmit,\n\tnodeReceiveFromDep,\n\tnodeRecordDepProjection,\n\tnodeReleaseDepDirty,\n\tnodeRunWave,\n\tnodeSettleAfterAbsorbedTerminal,\n\tnodeSettleRewire,\n\tnodeTryRun,\n} from \"./node-input-runtime.js\";\nimport {\n\tnodeActivate,\n\tnodeDeactivate,\n\tnodeIsRuntimeQuiescentForRelease,\n\tnodeReleaseRuntime,\n\tnodeResetDepState,\n\tnodeSeedRestoredDepAt,\n\tnodeSubscribeDepAt,\n\tnodeSubscriberCount,\n} from \"./node-lifecycle-runtime.js\";\nimport {\n\tnodeAllDepsTerminal,\n\tnodeCanFireDemand,\n\tnodeCommitBatchedWave,\n\tnodeDeferBoundary,\n\tnodeDeliverPullDemand,\n\tnodeDown,\n\tnodeEmitToSubs,\n\tnodeFireOwedDemandIfReady,\n\tnodeFirePullDemand,\n\tnodeForwardUp,\n\tnodeHasBoundaryPauseLock,\n\tnodeInvalidate,\n\tnodeIsAsyncPool,\n\tnodeIsPaused,\n\tnodeMarkDemandRouted,\n\tnodeOnDemand,\n\tnodeOnResume,\n\tnodePauseAcquire,\n\tnodePauseRelease,\n\tnodeResetLifecycle,\n\tnodeRollbackBatched,\n\tnodeShouldBufferOnPause,\n\tnodeUp,\n} from \"./node-output-runtime.js\";\nimport {\n\tnodeApplyRewireNext,\n\tnodeRequestRewireNext,\n\tnodeRequestUpNext,\n\tnodeRewire,\n} from \"./node-rewire-runtime.js\";\nimport { nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport {\n\tactivationReaders,\n\tcheckpointReaders,\n\tgetNodeOwner,\n\trestoreWriters,\n\truntimeQuiescenceReaders,\n\truntimeReleasers,\n\tsubscriberCountReaders,\n\ttakeConstructingEnvironmentDrivers,\n\ttakeConstructingNodeCore,\n} from \"./runtime-accessors.js\";\nimport type { NodeOptions, RewireOp, Status, UpRouteState } from \"./types.js\";\nimport {\n\tcloneNodeVersion,\n\tcreateNodeVersion,\n\ttype NodeVersion,\n\tresolveNodeVersioningPolicy,\n\trestoredV1Cid,\n} from \"./versioning.js\";\n\nexport {\n\tcheckpointStateOfNode,\n\tgetNodeOwner,\n\tisNodeActiveForRelease,\n\tisNodeRuntimeQuiescentForRelease,\n\tisNodeRuntimeReleased,\n\treleaseRuntimeOfNode,\n\trestoreStateOfNode,\n\tsetNodeOwner,\n\tsetNodeTopologyDepsChangedObserver,\n\tsubscriberCountOfNode,\n\twithEnvironmentDrivers,\n\twithNodeCore,\n} from \"./runtime-accessors.js\";\nexport type { NodeCheckpointState, NodeOptions, NodeRestoreState, Status } from \"./types.js\";\n\n/**\n * Reactive substrate node that owns dependencies, wave handling, lifecycle, and subscribers.\n *\n * @example\n * ```ts\n * import { node } from \"@graphrefly/ts\";\n *\n * const source = node<number>([], null);\n * source.subscribe((value) => console.log(value));\n * source.down([[\"DATA\", 1]]);\n * ```\n * @remarks **Substrate primitive:** `Node` is graph-agnostic; use `graph().node`,\n * `graph().state`, or `graph().derived` when you want inspection and lifecycle ownership.\n * @category core\n */\nexport class Node<T = unknown> {\n\tprivate readonly _core: NodeCore;\n\tprivate readonly _id: NodeId;\n\tprivate readonly _slot: NodeSlot<T>;\n\tprivate readonly _dep: DepBookkeeping;\n\tprivate readonly _value: ValueState<T>;\n\tprivate readonly _wave: WaveState;\n\tprivate readonly _control: ControlState;\n\tprivate readonly _lifecycle: LifecycleState;\n\tprivate readonly _privateState: PrivateState;\n\tprivate readonly _hooks: CleanupHooks;\n\tprivate readonly _syncCtxState: SyncCtxState;\n\tprivate readonly _version: VersionState;\n\tprivate _restoredActivationPending = false;\n\tprivate _released = false;\n\n\tprivate get _syncCtx(): Ctx | null {\n\t\treturn this._syncCtxState.value;\n\t}\n\n\tprivate set _syncCtx(ctx: Ctx | null) {\n\t\tthis._syncCtxState.value = ctx;\n\t}\n\n\tprivate static _retainIndirectRuntimeMethods(node: Node<unknown>): void {\n\t\tvoid node._dep;\n\t\tvoid node._hooks;\n\t\tvoid node._restoredActivationPending;\n\t\tvoid node._requestRewireNext;\n\t\tvoid node._requestUpNext;\n\t\tvoid node._applyRewireNext;\n\t\tvoid node._reachableUpstream;\n\t\tvoid node._assertRewireDepOwner;\n\t\tvoid node._subscribeDepAt;\n\t\tvoid node._seedRestoredDepAt;\n\t\tvoid node._recordDepProjection;\n\t\tvoid node._depProjectionHasData;\n\t\tvoid node._receiveFromDep;\n\t\tvoid node._releaseDepDirty;\n\t\tvoid node._settleAfterAbsorbedTerminal;\n\t\tvoid node._markDirty;\n\t\tvoid node._maybeRun;\n\t\tvoid node._settleRewire;\n\t\tvoid node._tryRun;\n\t\tvoid node._allDepsSettled;\n\t\tvoid node._passthroughEmit;\n\t\tvoid node._runWave;\n\t\tvoid node._buildCtx;\n\t\tvoid node._makeCtx;\n\t\tvoid node._refreshCtx;\n\t\tvoid node._makeState;\n\t\tvoid node._markDemandRouted;\n\t\tvoid node._forwardUp;\n\t\tvoid node._isPullQuiet;\n\t\tvoid node._isPaused;\n\t\tvoid node._hasBoundaryPauseLock;\n\t\tvoid node._isAsyncPool;\n\t\tvoid node._pauseAcquire;\n\t\tvoid node._pauseRelease;\n\t\tvoid node._onResume;\n\t\tvoid node._canFireDemand;\n\t\tvoid node._deliverPullDemand;\n\t\tvoid node._onDemand;\n\t\tvoid node._firePullDemand;\n\t\tvoid node._fireOwedDemandIfReady;\n\t\tvoid node._shouldBufferOnPause;\n\t\tvoid node._invalidate;\n\t\tvoid node._allDepsTerminal;\n\t\tvoid node._emitToSubs;\n\t}\n\n\tconstructor(\n\t\tdeps: Node<unknown>[],\n\t\thandleOrFn: Handle | NodeFn | null,\n\t\topts: NodeOptions<T> = {},\n\t) {\n\t\tconst core = takeConstructingNodeCore();\n\t\tconst dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tconst environment = takeConstructingEnvironmentDrivers() ?? EnvironmentDrivers.empty();\n\t\tconst pool = opts.pool ?? \"sync\";\n\t\tconst pausable = opts.pausable ?? true;\n\t\tconst pullLock = opts.pullId;\n\t\tconst pull = opts.pullId !== undefined;\n\t\t// R-pull (D269): pull-mode is keyed by an author-supplied pullId (its quiet latch).\n\t\t// R-pull (D55, pin 3): pull still uses the pausable delivery-content axis; pausable:false\n\t\t// ignores PAUSE/RESUME buffering and contradicts quiet pull delivery. Reject at construction.\n\t\tif (pull && pausable === false)\n\t\t\tthrow new Error(\n\t\t\t\t\"node: pullId is incompatible with pausable:false — a pull node uses the pausable delivery-content axis (R-pull / R-pause-modes / D55,D269)\",\n\t\t\t);\n\n\t\tlet handle: Handle | null;\n\t\tif (handleOrFn === null) handle = null;\n\t\telse if (typeof handleOrFn === \"function\") handle = dispatcher.register(handleOrFn, pool);\n\t\telse handle = handleOrFn;\n\n\t\tconst n = deps.length;\n\t\tconst dep = makeDepBookkeeping(n);\n\t\tconst versioning = resolveNodeVersioningPolicy(opts.versioning);\n\t\tconst value = {\n\t\t\tcache: SENTINEL as T | undefined,\n\t\t\thasData: false,\n\t\t\tstatus: \"sentinel\" as Status,\n\t\t\tterminal: undefined,\n\t\t\thasTorndown: false,\n\t\t\treplayRing: [] as T[],\n\t\t};\n\t\tif (opts.initial !== undefined) {\n\t\t\tvalue.cache = opts.initial as T;\n\t\t\tvalue.hasData = true;\n\t\t\tvalue.status = \"settled\";\n\t\t}\n\t\tconst pauseLockset = new Set<unknown>();\n\t\tthis._core = core ?? new NodeCore();\n\t\tconst created = this._core.createSlot<T>(\n\t\t\t{\n\t\t\t\tdeps,\n\t\t\t\thandle,\n\t\t\t\tpool,\n\t\t\t\tdispatcher,\n\t\t\t\tenvironment,\n\t\t\t\tpartial: opts.partial ?? false,\n\t\t\t\tterminalAsRealInput: opts.terminalAsRealInput ?? false,\n\t\t\t\tcompleteWhenDepsComplete: opts.completeWhenDepsComplete ?? true,\n\t\t\t\terrorWhenDepsError: opts.errorWhenDepsError ?? true,\n\t\t\t\tresubscribable: opts.resubscribable ?? false,\n\t\t\t\tresetOnTeardown: opts.resetOnTeardown ?? false,\n\t\t\t\tpausable,\n\t\t\t\tpull,\n\t\t\t\tpullLock,\n\t\t\t\treplayN: opts.replayBuffer ?? 0,\n\t\t\t\tdynamic: opts.dynamic ?? false,\n\t\t\t\tname: opts.name,\n\t\t\t\tfactory: opts.factory,\n\t\t\t},\n\t\t\t{\n\t\t\t\tdep,\n\t\t\t\tlifecycle: { subscribers: new Set<Sink>(), activated: false },\n\t\t\t\tvalue,\n\t\t\t\twave: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\thasCalledFnOnce: false,\n\t\t\t\t\temittedDirtyThisWave: false,\n\t\t\t\t\temittedSettleThisWave: false,\n\t\t\t\t\tinsideRunWave: false,\n\t\t\t\t\tinDepMutation: false,\n\t\t\t\t\trewireRunPending: false,\n\t\t\t\t\tbatchDirtyOwed: false,\n\t\t\t\t},\n\t\t\t\tcontrol: {\n\t\t\t\t\tpauseLockset,\n\t\t\t\t\tpausedDepWaveOccurred: false,\n\t\t\t\t\tpauseBuffer: [],\n\t\t\t\t\tdemandOwed: undefined,\n\t\t\t\t\tactivePull: undefined,\n\t\t\t\t\tpullDirtyOwed: false,\n\t\t\t\t\tinDeliverDemand: false,\n\t\t\t\t},\n\t\t\t\tprivateState: { value: SENTINEL, persist: false },\n\t\t\t\thooks: { onDeactivation: [], onInvalidate: [] },\n\t\t\t\tsyncCtx: { value: null },\n\t\t\t\tversion: {\n\t\t\t\t\tpolicy: versioning,\n\t\t\t\t\tvalue: createNodeVersion(\n\t\t\t\t\t\tversioning,\n\t\t\t\t\t\topts.initial !== undefined ? opts.initial : undefined,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tthis._id = created.id;\n\t\tthis._slot = this._core.get<T>(this._id);\n\t\tthis._dep = this._core.getDep(this._id);\n\t\tthis._value = this._core.getValue<T>(this._id);\n\t\tthis._wave = this._core.getWave(this._id);\n\t\tthis._control = this._core.getControl(this._id);\n\t\tthis._lifecycle = this._core.getLifecycle(this._id);\n\t\tthis._privateState = this._core.getPrivateState(this._id);\n\t\tthis._hooks = this._core.getHooks(this._id);\n\t\tthis._syncCtxState = this._core.getSyncCtx(this._id);\n\t\tthis._version = this._core.getVersion(this._id);\n\t\tcheckpointReaders.set(this as Node<unknown>, () => ({\n\t\t\tcache: this._value.cache,\n\t\t\thasData: this._value.hasData,\n\t\t\tterminal: this._value.terminal,\n\t\t\tactivated: this._lifecycle.activated,\n\t\t\thasCalledFnOnce: this._wave.hasCalledFnOnce,\n\t\t\tctxState: {\n\t\t\t\tvalue: this._privateState.value,\n\t\t\t\tpersist: this._privateState.persist,\n\t\t\t},\n\t\t\tversion: cloneNodeVersion(this._version.value),\n\t\t\thandle: this._slot.handle,\n\t\t}));\n\t\trestoreWriters.set(this as Node<unknown>, (state) => {\n\t\t\tthis._assertNotReleased(\"restoreGraph\");\n\t\t\tthis._value.cache = state.cache as T;\n\t\t\tthis._value.hasData = state.hasData;\n\t\t\tthis._value.status = state.status;\n\t\t\tthis._value.terminal = state.terminal;\n\t\t\tthis._value.hasTorndown = false;\n\t\t\tthis._value.replayRing = [];\n\t\t\tthis._wave.hasCalledFnOnce = state.hasCalledFnOnce;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._wave.emittedSettleThisWave = false;\n\t\t\tthis._wave.pending = 0;\n\t\t\tthis._wave.insideRunWave = false;\n\t\t\tthis._wave.inDepMutation = false;\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t\tthis._control.pauseLockset.clear();\n\t\t\tthis._privateState.value = state.ctxState.value;\n\t\t\tthis._privateState.persist = state.ctxState.persist;\n\t\t\tif (state.version === false) {\n\t\t\t\tthis._version.policy = { enabled: false };\n\t\t\t\tthis._version.value = undefined;\n\t\t\t} else if (state.version.level === 0) {\n\t\t\t\tthis._version.policy = { enabled: true, level: 0 };\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t} else {\n\t\t\t\tif (!this._version.policy.enabled || this._version.policy.level !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// D109: V1 restore must match the selected hash lane. After DATA then\n\t\t\t\t// INVALIDATE/resetOnTeardown, cache is absent while cid remains the last DATA cid;\n\t\t\t\t// without the DATA value, restore cannot verify the lane, so fail honestly.\n\t\t\t\tif (!state.hasData && state.version.counter > 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);\n\t\t\t\tif (expectedCid !== state.version.cid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t}\n\t\t\tthis._syncCtx = null;\n\t\t\tthis._resetDepState();\n\t\t\t// A fresh restored graph has no subscribers before return. Keep activation closed so the\n\t\t\t// first real subscriber wires deps normally; D94's preserved lifecycle bit is the first-run\n\t\t\t// gate (`hasCalledFnOnce`), not a hidden subscription graph.\n\t\t\tthis._lifecycle.activated = false;\n\t\t\tthis._lifecycle.subscribers.clear();\n\t\t\tthis._restoredActivationPending = true;\n\t\t});\n\t\truntimeReleasers.set(this as Node<unknown>, () => this._releaseRuntime());\n\t\truntimeQuiescenceReaders.set(this as Node<unknown>, () => this._isRuntimeQuiescentForRelease());\n\t\tsubscriberCountReaders.set(this as Node<unknown>, () => this._subscriberCount());\n\t\tactivationReaders.set(this as Node<unknown>, () => this._lifecycle.activated);\n\t\tNode._retainIndirectRuntimeMethods(this as Node<unknown>);\n\t}\n\n\t/** R-pull (D55/D272): true while a pull node is not serving a PULL demand pulse. */\n\tprivate _isPullQuiet(): boolean {\n\t\treturn this._slot.pull && this._control.activePull === undefined;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): this pull node's pullId (pure data, like {@link cache}/{@link handle} —\n\t * never triggers computation). A consumer demands one delivery by cone-routing PULL of it (no\n\t * node reference): `ctx.up([[\"PULL\", { pullId }]])` (immediate; loops back → D37 for a self-read\n\t * dep) or `ctx.upNext([[\"PULL\", { pullId }]])` (boundary-deferred self-demand). Undefined for a\n\t * non-pull node. The author writes the pullId verbatim; routing matches by identity.\n\t */\n\tget pullId(): LockId | undefined {\n\t\treturn this._slot.pullLock;\n\t}\n\n\tget cache(): T | undefined {\n\t\treturn this._value.cache;\n\t}\n\n\tget status(): Status {\n\t\treturn this._value.status;\n\t}\n\n\tget version(): NodeVersion | undefined {\n\t\treturn cloneNodeVersion(this._version.value);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._slot.name;\n\t}\n\n\t/** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */\n\tget factory(): string | undefined {\n\t\treturn this._slot.factory;\n\t}\n\n\t/**\n\t * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the\n\t * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a\n\t * construction-time snapshot) so every edge corresponds to a real current subscription (D3).\n\t * Inspection-only, like cache/status; never triggers computation.\n\t */\n\tget deps(): readonly Node<unknown>[] {\n\t\treturn this._slot.deps;\n\t}\n\n\t/**\n\t * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough\n\t * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph\n\t * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node\n\t * (R-node-thin / D39).\n\t */\n\tget handle(): Handle | null {\n\t\treturn this._slot.handle;\n\t}\n\n\t/** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */\n\tsubscribe(sink: Sink): () => void {\n\t\tthis._assertNotReleased(\"subscribe\");\n\t\t// Wave-owner boundary (R-rewire-deferred / D47): the activation cascade can run fns that\n\t\t// issue ctx.rewireNext; the OUTERMOST exit drains them. Nested subscribes (dep wiring)\n\t\t// just inc/dec the depth.\n\t\tenterWave();\n\t\ttry {\n\t\t\t// R-terminal: late subscribe to a terminal node either resets (resubscribable)\n\t\t\t// or is rejected (non-resubscribable, R2.2.7.b).\n\t\t\tif (this._value.terminal !== undefined) {\n\t\t\t\tif (this._slot.resubscribable) {\n\t\t\t\t\tthis._restoredActivationPending = false;\n\t\t\t\t\tthis._resetLifecycle();\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)\",\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis._lifecycle.subscribers.add(sink);\n\t\t\tsink([\"START\"]);\n\t\t\tif (this._slot.replayN > 0 && this._value.replayRing.length > 0) {\n\t\t\t\t// R-replay-buffer: late subscriber gets the last N DATA after START.\n\t\t\t\tfor (const v of this._value.replayRing) sink([\"DATA\", v]);\n\t\t\t} else if (this._value.hasData && !this._slot.pull) {\n\t\t\t\t// R-pull (D55): a pull node NEVER push-on-subscribes its cached value — quiet by\n\t\t\t\t// default, it stays silent until demanded (START only). QA-B4: gated on `_pull`, not\n\t\t\t\t// activePull, so a REACTIVATED pull node still does not leak its cache.\n\t\t\t\tsink([\"DATA\", this._value.cache]);\n\t\t\t} else if (this._value.status === \"dirty\" && !this._slot.pull) {\n\t\t\t\tsink([\"DIRTY\"]);\n\t\t\t}\n\n\t\t\tif (!this._lifecycle.activated) this._activate();\n\n\t\t\treturn () => {\n\t\t\t\tif (!this._lifecycle.subscribers.delete(sink)) return;\n\t\t\t\tif (this._lifecycle.subscribers.size === 0) this._deactivate();\n\t\t\t};\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */\n\tdown(msgs: Wave): void {\n\t\tthis._assertNotReleased(\"down\");\n\t\t// Wave-owner boundary (D47): a state.set / external push that drives a fn issuing\n\t\t// ctx.rewireNext drains at this outermost exit.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._down(msgs);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up\n\t * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t */\n\tup(msgs: Wave, towardDep?: number): void {\n\t\tthis._assertNotReleased(\"up\");\n\t\t// Wave-owner boundary (D47). Internal dep-forwarding calls dep.up() nest under this.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._up(msgs, towardDep);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t// ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──\n\n\t/**\n\t * Replace this node's deps atomically (surgical, Option-C). Requires an explicit\n\t * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps\n\t * keep their subscription + per-dep state; only removed deps unsubscribe and only\n\t * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The\n\t * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).\n\t */\n\treplaceDeps(newDeps: Node<unknown>[], fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"replaceDeps\");\n\t\tthis._rewire(this._dedupDeps(newDeps), fn);\n\t}\n\n\t/** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */\n\tsubscribeDep(depNode: Node<unknown>, fn: NodeFn): number {\n\t\tthis._assertNotReleased(\"subscribeDep\");\n\t\tconst next = this._slot.deps.includes(depNode)\n\t\t\t? [...this._slot.deps]\n\t\t\t: [...this._slot.deps, depNode];\n\t\tconst deferred = this._rewire(next, fn);\n\t\treturn deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);\n\t}\n\n\t/** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */\n\tunsubscribeDep(depNode: Node<unknown>, fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"unsubscribeDep\");\n\t\tthis._rewire(\n\t\t\tthis._slot.deps.filter((d) => d !== depNode),\n\t\t\tfn,\n\t\t);\n\t}\n\n\tprivate _requestRewireNext(op: RewireOp): void {\n\t\tnodeRequestRewireNext(nodeRuntimeHost(this), op);\n\t}\n\n\tprivate _requestUpNext(msgs: Wave, towardDep?: number): void {\n\t\tnodeRequestUpNext(nodeRuntimeHost(this), msgs, towardDep);\n\t}\n\n\tprivate _applyRewireNext(op: RewireOp): void {\n\t\tnodeApplyRewireNext(nodeRuntimeHost(this), op);\n\t}\n\n\tprivate _dedupDeps(deps: Node<unknown>[]): Node<unknown>[] {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst out: Node<unknown>[] = [];\n\t\tfor (const d of deps)\n\t\t\tif (!seen.has(d)) {\n\t\t\t\tseen.add(d);\n\t\t\t\tout.push(d);\n\t\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst stack: Node<unknown>[] = [from];\n\t\twhile (stack.length > 0) {\n\t\t\tconst n = stack.pop();\n\t\t\tif (n === undefined) continue;\n\t\t\tif (n === target) return true;\n\t\t\tif (seen.has(n)) continue;\n\t\t\tseen.add(n);\n\t\t\tfor (const d of nodeRuntimeHost(n)._slot.deps) stack.push(d);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _assertRewireDepOwner(dep: Node<unknown>): void {\n\t\tconst selfOwner = getNodeOwner(this as unknown as Node<unknown>);\n\t\tconst depOwner = getNodeOwner(dep);\n\t\tif (selfOwner !== undefined && depOwner !== undefined && selfOwner !== depOwner)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)\",\n\t\t\t);\n\t}\n\n\tprivate _rewire(\n\t\tnewDeps: Node<unknown>[],\n\t\tfn: NodeFn,\n\t\topts: { allowTerminalOwner?: boolean } = {},\n\t): boolean {\n\t\treturn nodeRewire(nodeRuntimeHost(this), newDeps, fn, opts);\n\t}\n\n\t// ── activation / deactivation (lazy; R-rom-ram) ──\n\n\tprivate _activate(): void {\n\t\tnodeActivate(nodeRuntimeHost(this));\n\t}\n\n\tprivate _deactivate(): void {\n\t\tnodeDeactivate(nodeRuntimeHost(this));\n\t}\n\n\tprivate _assertNotReleased(op: string): void {\n\t\tif (this._released)\n\t\t\tthrow new Error(`${op}: node has been released from its graph lifecycle (D122)`);\n\t}\n\n\tprivate _subscriberCount(): number {\n\t\treturn nodeSubscriberCount(nodeRuntimeHost(this));\n\t}\n\n\tprivate _isRuntimeQuiescentForRelease(): boolean {\n\t\treturn nodeIsRuntimeQuiescentForRelease(nodeRuntimeHost(this));\n\t}\n\n\tprivate _releaseRuntime(): void {\n\t\tnodeReleaseRuntime(nodeRuntimeHost(this));\n\t}\n\n\tprivate _resetDepState(): void {\n\t\tnodeResetDepState(nodeRuntimeHost(this));\n\t}\n\n\tprivate _subscribeDepAt(depNode: Node<unknown>, opts: { seedRestored?: boolean } = {}): void {\n\t\tnodeSubscribeDepAt(nodeRuntimeHost(this), depNode, opts);\n\t}\n\n\tprivate _seedRestoredDepAt(idx: number, depNode: Node<unknown>): void {\n\t\tnodeSeedRestoredDepAt(nodeRuntimeHost(this), idx, depNode);\n\t}\n\n\tprivate _recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[] {\n\t\treturn nodeRecordDepProjection(nodeRuntimeHost(this), idx, delivery);\n\t}\n\n\tprivate _depProjectionHasData(idx: number): boolean {\n\t\treturn nodeDepProjectionHasData(nodeRuntimeHost(this), idx);\n\t}\n\n\tprivate _receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void {\n\t\tnodeReceiveFromDep(nodeRuntimeHost(this), idx, msg, delivery);\n\t}\n\n\tprivate _releaseDepDirty(idx: number): void {\n\t\tnodeReleaseDepDirty(nodeRuntimeHost(this), idx);\n\t}\n\n\tprivate _settleAfterAbsorbedTerminal(): void {\n\t\tnodeSettleAfterAbsorbedTerminal(nodeRuntimeHost(this));\n\t}\n\n\tprivate _markDirty(): void {\n\t\tnodeMarkDirty(nodeRuntimeHost(this));\n\t}\n\n\tprivate _maybeRun(): void {\n\t\tnodeMaybeRun(nodeRuntimeHost(this));\n\t}\n\n\tprivate _settleRewire(): void {\n\t\tnodeSettleRewire(nodeRuntimeHost(this));\n\t}\n\n\tprivate _tryRun(): void {\n\t\tnodeTryRun(nodeRuntimeHost(this));\n\t}\n\n\tprivate _allDepsSettled(): boolean {\n\t\treturn nodeAllDepsSettled(nodeRuntimeHost(this));\n\t}\n\n\tprivate _passthroughEmit(): void {\n\t\tnodePassthroughEmit(nodeRuntimeHost(this));\n\t}\n\n\tprivate _runWave(): void {\n\t\tnodeRunWave(nodeRuntimeHost(this));\n\t}\n\n\tprivate _buildCtx(): Ctx {\n\t\treturn nodeBuildCtx(nodeRuntimeHost(this));\n\t}\n\n\tprivate _makeCtx(snapshot?: {\n\t\twaveData: unknown[][][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): Ctx {\n\t\treturn nodeMakeCtx(nodeRuntimeHost(this), snapshot);\n\t}\n\n\tprivate _refreshCtx(ctx: Ctx): void {\n\t\tnodeRefreshCtx(nodeRuntimeHost(this), ctx);\n\t}\n\n\tprivate _makeState(): CtxState {\n\t\treturn nodeMakeState(nodeRuntimeHost(this));\n\t}\n\n\t// ── downstream emission pipeline (the unified waist) ──\n\n\tprivate _down(msgs: Wave): void {\n\t\tnodeDown(nodeRuntimeHost(this), msgs);\n\t}\n\n\tprivate _up(msgs: Wave, towardDep?: number, route?: UpRouteState): void {\n\t\tnodeUp(nodeRuntimeHost(this), msgs, towardDep, route);\n\t}\n\n\tprivate _markDemandRouted(lockId: LockId, route: UpRouteState): boolean {\n\t\treturn nodeMarkDemandRouted(nodeRuntimeHost(this), lockId, route);\n\t}\n\n\tprivate _forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void {\n\t\tnodeForwardUp(nodeRuntimeHost(this), m, towardDep, route);\n\t}\n\n\tprivate _isPaused(): boolean {\n\t\treturn nodeIsPaused(nodeRuntimeHost(this));\n\t}\n\n\tprivate _hasBoundaryPauseLock(): boolean {\n\t\treturn nodeHasBoundaryPauseLock(nodeRuntimeHost(this));\n\t}\n\n\tprivate _isAsyncPool(): boolean {\n\t\treturn nodeIsAsyncPool(nodeRuntimeHost(this));\n\t}\n\n\tprivate _pauseAcquire(lockId: unknown): void {\n\t\tnodePauseAcquire(nodeRuntimeHost(this), lockId);\n\t}\n\n\tprivate _pauseRelease(lockId: unknown): void {\n\t\tnodePauseRelease(nodeRuntimeHost(this), lockId);\n\t}\n\n\tprivate _onResume(): void {\n\t\tnodeOnResume(nodeRuntimeHost(this));\n\t}\n\n\tprivate _canFireDemand(): boolean {\n\t\treturn nodeCanFireDemand(nodeRuntimeHost(this));\n\t}\n\n\tprivate _deliverPullDemand(demand: PullDemand): void {\n\t\tnodeDeliverPullDemand(nodeRuntimeHost(this), demand);\n\t}\n\n\tprivate _onDemand(demand: PullDemand): void {\n\t\tnodeOnDemand(nodeRuntimeHost(this), demand);\n\t}\n\n\tprivate _firePullDemand(): void {\n\t\tnodeFirePullDemand(nodeRuntimeHost(this));\n\t}\n\n\tprivate _fireOwedDemandIfReady(): void {\n\t\tnodeFireOwedDemandIfReady(nodeRuntimeHost(this));\n\t}\n\n\tprivate _shouldBufferOnPause(): boolean {\n\t\treturn nodeShouldBufferOnPause(nodeRuntimeHost(this));\n\t}\n\n\tprivate _invalidate(delivery?: DeliveryMeta): void {\n\t\tnodeInvalidate(nodeRuntimeHost(this), delivery);\n\t}\n\n\tprivate _allDepsTerminal(): boolean {\n\t\treturn nodeAllDepsTerminal(nodeRuntimeHost(this));\n\t}\n\n\tprivate _emitToSubs(msg: Message, delivery?: DeliveryMeta): void {\n\t\tnodeEmitToSubs(nodeRuntimeHost(this), msg, delivery);\n\t}\n\n\t/** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */\n\tprivate _resetLifecycle(): void {\n\t\tnodeResetLifecycle(nodeRuntimeHost(this));\n\t}\n\n\t/** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */\n\t__commitBatchedWave(wave: Wave): void {\n\t\tnodeCommitBatchedWave(nodeRuntimeHost(this), wave);\n\t}\n\n\t/** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */\n\t__rollbackBatched(): void {\n\t\tnodeRollbackBatched(nodeRuntimeHost(this));\n\t}\n\n\t/** B49: enqueue a committed-boundary task on this node's graph-local core. */\n\t__deferBoundary(fn: () => void, batchToken?: object): void {\n\t\tnodeDeferBoundary(nodeRuntimeHost(this), fn, batchToken);\n\t}\n}\n\n/**\n * Construct a node (R-node-iface / D5 / L1.9 deps-first).\n * node([], null, { initial }) — state node (manual source; emit via .down)\n * node([], fn) — producer (runs on activation)\n * node([a, b], fn) — compute / derived\n * node([dep]) — passthrough wire\n *\n * @param deps - Upstream nodes this node reads positionally from `ctx`.\n * @param handleOrFn - Dispatcher handle, node function, or `null` for a manual source/state node.\n * @param opts - Node runtime options such as `initial`, `name`, pool, dispatcher, and restore data.\n * @returns A graph-agnostic `Node`.\n * @example\n * ```ts\n * import { depLatest, node } from \"@graphrefly/ts\";\n *\n * const source = node<number>([], null, { initial: 1 });\n * const doubled = node<number>([source], (ctx) => {\n * ctx.down([[\"DATA\", Number(depLatest(ctx, 0)) * 2]]);\n * });\n * ```\n * @category core\n */\nexport function node<T = unknown>(\n\tdeps: Node<unknown>[] = [],\n\thandleOrFn: Handle | NodeFn | null = null,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, handleOrFn, opts);\n}\n\n/**\n * Construct a dynamicNode (R-dynamic-node / D35) — a node variant whose fn reads a\n * subset of a fixed superset of deps per invocation via `ctx.track(i)`. All declared\n * deps participate in wave tracking; an unread dep's change re-runs the fn, which re-emits\n * its current value as DATA (D49 removed equals-absorption — dedup is opt-in via\n * distinctUntilChanged). Intra-graph only (D22).\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","/**\n * Graph checkpoint public data shape (D83/D86/D90/D116).\n *\n * Checkpoint is a graph lifecycle snapshot: strict-JSON-compatible data, no storage I/O,\n * no observe-log replay, and no restore runtime in this first TS slice.\n */\n\nimport { type StrictJsonValue, strictJsonCodec } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { NodeVersionJson } from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\n\nexport const GRAPH_CHECKPOINT_VERSION = \"graphrefly.checkpoint.v1\" as const;\n\nexport type GraphCheckpointVersion = typeof GRAPH_CHECKPOINT_VERSION;\n\nexport type GraphCheckpointJson = StrictJsonValue;\n\nexport type GraphCheckpointValue =\n\t| { kind: \"SENTINEL\" }\n\t| { kind: \"DATA\"; data: GraphCheckpointJson };\n\nexport type GraphCheckpointTerminal =\n\t| { kind: \"none\" }\n\t| { kind: \"COMPLETE\" }\n\t| { kind: \"ERROR\"; error: GraphCheckpointJson };\n\nexport type GraphCheckpointFactory =\n\t| {\n\t\t\tkind: \"registry-ref\";\n\t\t\tref: string;\n\t\t\tconfig?: GraphCheckpointJson;\n\t\t\tconfigVersion?: GraphCheckpointJson;\n\t }\n\t| { kind: \"local-only\"; name: string; reason: string };\n\nexport interface GraphCheckpointNode {\n\tid: string;\n\tname?: string;\n\tfactory: GraphCheckpointFactory;\n\tstatus: string;\n\tdeps: string[];\n\tvalue: GraphCheckpointValue;\n\tbackendState?: GraphCheckpointJson;\n\tversion?: NodeVersionJson;\n\tterminal: GraphCheckpointTerminal;\n\tlifecycle: { activated: boolean; hasCalledFnOnce: boolean };\n\tctxState: { persist: boolean; value: GraphCheckpointValue };\n\tmeta?: { [key: string]: GraphCheckpointJson };\n}\n\nexport interface GraphCheckpointEdge {\n\tfrom: string;\n\tto: string;\n}\n\nexport interface GraphCheckpointMount {\n\tat: string;\n\tcheckpoint: GraphCheckpoint;\n}\n\nexport interface GraphCheckpoint {\n\tversion: GraphCheckpointVersion;\n\tname?: string;\n\tnodes: GraphCheckpointNode[];\n\tedges: GraphCheckpointEdge[];\n\tmounts?: GraphCheckpointMount[];\n}\n\nexport function toCheckpointJson(value: unknown, path = \"$\"): GraphCheckpointJson {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as GraphCheckpointJson;\n\t} catch (cause) {\n\t\tthrow new TypeError(`checkpoint: value at ${path} is not strict JSON compatible`, {\n\t\t\tcause,\n\t\t});\n\t}\n}\n\nexport function checkpointValue(\n\tvalue: unknown,\n\thasData: boolean,\n\tpath: string,\n): GraphCheckpointValue {\n\tif (!hasData || value === SENTINEL) return { kind: \"SENTINEL\" };\n\treturn { kind: \"DATA\", data: toCheckpointJson(value, path) };\n}\n\nexport function checkpointTerminal(value: unknown, path: string): GraphCheckpointTerminal {\n\tif (value === undefined) return { kind: \"none\" };\n\tif (value === true) return { kind: \"COMPLETE\" };\n\treturn { kind: \"ERROR\", error: toCheckpointJson(value, path) };\n}\n\ntype BackendStateContributor = () => unknown;\n\nconst backendStateContributors = new WeakMap<Node<unknown>, BackendStateContributor>();\n\n/** @internal D160: collection-owned backend checkpoint contributor for graph checkpoint. */\nexport function registerBackendStateContributor(\n\tnode: Node<unknown>,\n\tcontributor: BackendStateContributor,\n): void {\n\tbackendStateContributors.set(node, contributor);\n}\n\n/** @internal D160: capture a node's collection backend state when it has a contributor. */\nexport function checkpointBackendStateOfNode(\n\tnode: Node<unknown>,\n\tpath: string,\n): GraphCheckpointJson | undefined {\n\tconst contributor = backendStateContributors.get(node);\n\tif (contributor === undefined) return undefined;\n\treturn toCheckpointJson(contributor(), path);\n}\n","/**\n * Operators as free-standing factory definitions (D43 / D6 / D40 Catalog-first).\n *\n * Operators are `node` sugar (D6), NOT verbs (D4) and NEVER in parity (D24). Each is a\n * pure {@link Operator} spec — `{factory, body, opts}` — built on the bare `node` primitive\n * (NOT the `derived` verb): `body` reads ctx dep slots positionally and emits via\n * `ctx.down`. Two ways to instantiate:\n *\n * - {@link initNode}(op, deps, opts?) — bare, no Graph; returns a working `Node<T>`.\n * - `g.initNode(op, deps, opts?)` — graph-bound; the SAME call, plus inspection registration\n * (the real factory name lands in the graph's `_entries`, so describe/observe/profile\n * show it — D6/R-describe — while the node stays thin, R-node-thin).\n *\n * The D30 throw→ERROR boundary lives once, in the free {@link initNode} (which `g.initNode`\n * funnels through). The pure-ts `operatorOpts/partialOperatorOpts/gatedOperatorOpts` trio is\n * NOT ported: its sole job (`describeKind:\"derived\"`) is dead under D6/D39 (factory = the\n * REAL operator name); only the `partial`/`terminalAsRealInput` flags survive, carried\n * per-operator in `op.opts`.\n *\n * Config is folded into the factory (`map(fn)`, `scan(reducer, seed)`, `take(n)`, `merge()`),\n * so fn params are annotated where the source type can't be inferred (RxJS-pipe cost);\n * dep-type safety is recovered by the typed `g.initNode` overloads.\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepLatest,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { NodeCore } from \"../node/core.js\";\nimport { Node, type NodeOptions, withNodeCore } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { type GraphCheckpointJson, toCheckpointJson } from \"./checkpoint.js\";\nimport type { GraphRestoreDefinition, GraphRestoreEntry, GraphRestoreRegistry } from \"./restore.js\";\n\n/**\n * A free-standing operator definition (D43). `TIn` = the element type each dep delivers\n * (the operator reads `depLatest(ctx, i) as TIn`); `TOut` = the emitted value type.\n * `__in`/`__out` are phantom-only (never assigned) — they let `g.initNode` infer + check the\n * dep tuple against the operator without an explicit type argument.\n */\nexport interface Operator<TIn = unknown, TOut = unknown> {\n\t/** Real operator name shown in describe (D6/L1.5) — recorded at `_add` by `g.initNode`. */\n\treadonly factory: string;\n\t/** The ctx-body: reads ctx dep slots positionally, emits via `ctx.down`. */\n\treadonly body: (ctx: Ctx) => void;\n\t/** Behavioral node options the operator needs (e.g. `partial:true` for combine-family). */\n\treadonly opts?: Partial<NodeOptions<TOut>>;\n\t/**\n\t * D97/D100 restore metadata derived from a named definition or static built-in config.\n\t * This is semantic metadata only; dispatcher handles stay graph-local runtime state.\n\t */\n\treadonly restore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t};\n\t/** @internal phantom — never set; carries the dep element type for `g.initNode` inference. */\n\treadonly __in?: TIn;\n\t/** @internal phantom — never set; carries the output value type. */\n\treadonly __out?: TOut;\n}\n\ntype MutableRestoreRegistry = Map<string, GraphRestoreEntry> | Record<string, GraphRestoreEntry>;\n\nexport type RestoreRegistryEntry = GraphRestoreEntry;\n\nexport interface Definition<S = unknown, T = unknown> extends GraphRestoreDefinition<S, T> {\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport interface DefineOpts {\n\tregistry?: MutableRestoreRegistry;\n}\n\nfunction registryHas(registry: MutableRestoreRegistry, ref: string): boolean {\n\treturn registry instanceof Map ? registry.has(ref) : Object.hasOwn(registry, ref);\n}\n\nfunction registrySet(\n\tregistry: MutableRestoreRegistry,\n\tref: string,\n\tentry: GraphRestoreEntry,\n): void {\n\tif (registryHas(registry, ref)) {\n\t\tthrow new Error(`restoreRegistry: duplicate ref '${ref}'`);\n\t}\n\tif (registry instanceof Map) registry.set(ref, entry);\n\telse registry[ref] = entry;\n}\n\nexport function addToRestoreRegistry(\n\tregistry: MutableRestoreRegistry,\n\tentry: GraphRestoreEntry,\n): void {\n\tregistrySet(registry, entry.ref, entry);\n}\n\nexport function restoreRegistry(\n\tentries: readonly GraphRestoreEntry[] = [],\n\tbase?: GraphRestoreRegistry,\n): Map<string, GraphRestoreEntry> {\n\tconst out = new Map<string, GraphRestoreEntry>();\n\tif (base instanceof Map) {\n\t\tfor (const [ref, entry] of base) registrySet(out, ref, entry);\n\t} else if (base !== undefined) {\n\t\tfor (const [ref, entry] of Object.entries(base)) registrySet(out, ref, entry);\n\t}\n\tfor (const entry of entries) addToRestoreRegistry(out, entry);\n\treturn out;\n}\n\nfunction isDefinition<S, T>(fn: ((v: S) => T) | Definition<S, T>): fn is Definition<S, T> {\n\treturn typeof fn === \"object\" && fn !== null && (fn as Definition<S, T>).kind === \"definition\";\n}\n\nexport function define<S, T>(\n\tref: string,\n\tfn: (v: S) => T,\n\topts: DefineOpts = {},\n): Definition<S, T> {\n\tconst jsonRef = toCheckpointJson(ref, \"define.ref\");\n\tif (typeof jsonRef !== \"string\") throw new TypeError(\"define: ref must be a string\");\n\tconst definition: Definition<S, T> = {\n\t\tkind: \"definition\",\n\t\tref: jsonRef,\n\t\tfn,\n\t};\n\tif (opts.registry !== undefined) addToRestoreRegistry(opts.registry, definition);\n\treturn definition;\n}\n\n/**\n * Instantiate an operator as a bare `Node<T>` — NO Graph required (D43 bare-node path).\n * Wraps `op.body` in the D30 value-throw→ERROR boundary; merges `op.opts` with caller `opts`\n * (caller wins, so `partial`/`pool`/`dispatcher` overrides take effect). The\n * dispatcher defaults to the process-global (D26) unless `opts.dispatcher` is passed.\n *\n * `g.initNode` is the same call PLUS graph registration; graph inspection\n * (describe/observe/profile) requires that path — a node built bare here is not registered in\n * any graph's index.\n */\nexport function initNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn makeInitNode(op, deps, opts);\n}\n\n/** @internal Graph-bound operator instantiation into a graph-local B49 core. */\nexport function initNodeWithCore<TIn, TOut>(\n\tcore: NodeCore,\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn withNodeCore(core, () => makeInitNode(op, deps, opts));\n}\n\nfunction makeInitNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut>,\n): Node<TOut> {\n\tconst body = operatorNodeFn(op);\n\t// D43-reserved / D51: stamp the operator's real factory onto the bare node so a runtime *Map\n\t// inner (created here via fromAny, NOT registered in any graph) is named in describe's\n\t// auto-discovery. A graph-bound g.initNode also records it in `_entries` (entry.factory wins\n\t// there); this field is only read for a node absent from the graph index. Caller opts win.\n\treturn new Node<TOut>([...deps], body, { factory: op.factory, ...op.opts, ...opts });\n}\n\n/** @internal Build the dispatcher body for an Operator spec. */\nexport function operatorNodeFn<TIn, TOut>(op: Operator<TIn, TOut>): NodeFn {\n\treturn (ctx) => {\n\t\ttry {\n\t\t\top.body(ctx);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"operator threw without a valid error payload\")]]); // D30: value-level throw → ERROR\n\t\t}\n\t};\n}\n\n// ── Slice 1 — single-dep map / take / control (CSP-2.7 catalog re-derive, D40) ──\n// All read dep 0 positionally + emit via ctx.down. Under D49 every occurrence is DATA (no\n// equals-absorption); a body that returns WITHOUT emitting gets a substrate-synthesized undirty\n// RESOLVED (R-resolved-undirty) — so a \"skip this wave\" is a bare `return`. Terminal-emitting\n// operators (reduce/last/find/elementAt) read `depTerminal(ctx, 0)` via the\n// `completeWhenDepsComplete:false + terminalAsRealInput:true` flags (R-deps-terminal): the fn fires\n// on the source's COMPLETE and emits its final value. NOT 1:1 pure-ts ports — the frozen reference\n// (D41) uses a producer + internal `subscribeOr`, the D45-banned describe island; these are\n// declared-dep nodes whose single edge `describe` shows truthfully.\n\n/**\n * Transform each upstream DATA value with a synchronous mapping function.\n *\n * @param fn - Mapping function, or a named `define()` definition for checkpoint restoration.\n * @returns An operator that emits `fn(value)` for each upstream value.\n * @example\n * ```ts\n * import { graph, map } from \"@graphrefly/ts\";\n *\n * const g = graph();\n * const count = g.state(1);\n * const doubled = g.initNode(map((value: number) => value * 2), [count]);\n * ```\n * @remarks **Restorable maps:** Passing a named `define()` registers semantic restore metadata.\n * @category operators\n */\nexport function map<S, T>(fn: ((v: S) => T) | Definition<S, T>): Operator<S, T> {\n\tif (isDefinition(fn)) {\n\t\treturn mapFromFunction(fn.fn, {\n\t\t\tref: \"map\",\n\t\t\tconfig: { fn: toCheckpointJson(fn.ref, `map.fn`) },\n\t\t});\n\t}\n\treturn mapFromFunction(fn);\n}\n\nfunction mapFromFunction<S, T>(\n\tfn: (v: S) => T,\n\trestore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t},\n): Operator<S, T> {\n\treturn {\n\t\tfactory: \"map\",\n\t\t...(restore ? { restore } : {}),\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) ctx.down([[\"DATA\", fn(v as S)]]);\n\t\t},\n\t};\n}\n\n/**\n * Pass through upstream values that satisfy a predicate.\n *\n * @param pred - Predicate evaluated for each upstream DATA value.\n * @returns An operator that emits matching values and stays quiet for non-matches.\n * @example\n * ```ts\n * import { filter, graph } from \"@graphrefly/ts\";\n *\n * const g = graph();\n * const count = g.state(0);\n * const even = g.initNode(filter((value: number) => value % 2 === 0), [count]);\n * ```\n * @category operators\n */\nexport function filter<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"filter\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) if (pred(v as S)) ctx.down([[\"DATA\", v]]);\n\t\t},\n\t};\n}\n\n/**\n * Accumulate upstream values and emit each intermediate accumulator.\n *\n * @param reducer - Reducer called with the previous accumulator and each upstream value.\n * @param seed - Initial accumulator value.\n * @returns An operator that emits the accumulator after every input value.\n * @example\n * ```ts\n * import { graph, scan } from \"@graphrefly/ts\";\n *\n * const g = graph();\n * const values = g.state(1);\n * const total = g.initNode(scan((sum: number, value: number) => sum + value, 0), [values]);\n * ```\n * @category operators\n */\nexport function scan<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"scan\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tfor (const v of b) {\n\t\t\t\tacc = reducer(acc, v as S);\n\t\t\t\tctx.down([[\"DATA\", acc]]);\n\t\t\t}\n\t\t\tctx.state.set(acc);\n\t\t},\n\t};\n}\n\n/**\n * Emit the first `n` upstream values, then complete.\n *\n * @param n - Number of DATA values to pass before completion.\n * @returns An operator that forwards at most `n` values and then emits COMPLETE.\n * @example\n * ```ts\n * import { graph, take } from \"@graphrefly/ts\";\n *\n * const firstThree = graph().initNode(take<number>(3), [source]);\n * ```\n * @category operators\n */\nexport function take<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"take\",\n\t\trestore: { ref: \"take\", config: { n: toCheckpointJson(n, \"take.n\") } },\n\t\tbody: (ctx) => {\n\t\t\tif (n <= 0) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (count >= n) return; // already satisfied\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count >= n) break;\n\t\t\t\tcount += 1;\n\t\t\t\tctx.down(count >= n ? [[\"DATA\", v], [\"COMPLETE\"]] : [[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * Suppress consecutive duplicate values.\n *\n * @param eq - Equality predicate; defaults to `Object.is`.\n * @returns An operator that emits only when the next value differs from the previous emitted value.\n * @example\n * ```ts\n * import { distinctUntilChanged, graph } from \"@graphrefly/ts\";\n *\n * const stable = graph().initNode(distinctUntilChanged<number>(), [source]);\n * ```\n * @category operators\n */\nexport function distinctUntilChanged<S>(eq: (a: S, b: S) => boolean = Object.is): Operator<S, S> {\n\treturn {\n\t\tfactory: \"distinctUntilChanged\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst prev = ctx.state.get<{ v: S }>();\n\t\t\tlet last = prev?.v;\n\t\t\tlet hasLast = prev !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasLast && eq(last as S, v)) continue;\n\t\t\t\tlast = v;\n\t\t\t\thasLast = true;\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tif (hasLast) ctx.state.set({ v: last as S });\n\t\t},\n\t};\n}\n\n/**\n * merge: interleave several sources — emit each DATA from whichever dep fired. `partial:true`\n * (combine-family): fires on any single dep, not gated on all deps settling.\n *\n * @returns An operator that forwards DATA from any dependency.\n * @example\n * ```ts\n * import { graph, merge } from \"@graphrefly/ts\";\n *\n * const merged = graph().initNode(merge<number>(), [left, right]);\n * ```\n * @category operators\n */\nexport function merge<T>(): Operator<T, T> {\n\treturn {\n\t\tfactory: \"merge\",\n\t\topts: { partial: true },\n\t\tbody: (ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b && b.length > 0) {\n\t\t\t\t\tfor (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * reduce: accumulate over the whole source, emit ONE final value on the source's COMPLETE\n * (RxJS `reduce`). Unlike {@link scan} (which emits every step), reduce stays quiet until the\n * source terminates. `completeWhenDepsComplete:false + terminalAsRealInput:true`: the fn fires on\n * the source COMPLETE (reading `terminal===true`) and emits the accumulator + COMPLETE. An empty\n * source emits the seed (RxJS parity). A source ERROR auto-forwards (errorWhenDepsError default).\n *\n * @param reducer - Reducer called with the accumulator and each upstream DATA value.\n * @param seed - Initial accumulator value emitted if the source completes empty.\n * @returns An operator that emits one accumulated value when the source completes.\n * @example\n * ```ts\n * import { graph, reduce } from \"@graphrefly/ts\";\n *\n * const total = graph().initNode(reduce((sum: number, value: number) => sum + value, 0), [source]);\n * ```\n * @category operators\n */\nexport function reduce<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"reduce\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tif (b) for (const v of b) acc = reducer(acc, v as S);\n\t\t\tctx.state.set(acc);\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"DATA\", acc], [\"COMPLETE\"]]);\n\t\t\t// else (live DATA wave): no emit → substrate-synthesized undirty RESOLVED (D49).\n\t\t},\n\t};\n}\n\n/**\n * pairwise: emit `[previous, current]` for each consecutive pair; the very first value produces no\n * pair (quiet → undirty RESOLVED). Previous value is kept in `ctx.state`.\n */\nexport function pairwise<S>(): Operator<S, readonly [S, S]> {\n\treturn {\n\t\tfactory: \"pairwise\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst st = ctx.state.get<{ prev: S }>();\n\t\t\tlet prev = st?.prev;\n\t\t\tlet hasPrev = st !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasPrev) ctx.down([[\"DATA\", [prev as S, v] as const]]);\n\t\t\t\tprev = v;\n\t\t\t\thasPrev = true;\n\t\t\t}\n\t\t\tif (hasPrev) ctx.state.set({ prev: prev as S });\n\t\t},\n\t};\n}\n\n/** skip: drop the first `n` DATA values, then pass the rest through. */\nexport function skip<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"skip\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count < n) {\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * takeWhile: emit values while `pred` holds; on the first value that fails `pred`, COMPLETE\n * WITHOUT emitting it (RxJS default, non-inclusive). Terminal-is-forever once it completes.\n */\nexport function takeWhile<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"takeWhile\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (pred(v)) ctx.down([[\"DATA\", v]]);\n\t\t\t\telse {\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * first: emit the first value matching `pred` (or simply the first value), then COMPLETE. EDGE\n * (RxJS divergence, flagged — same class as last/find/elementAt): if the source COMPLETEs with no\n * matching value, the substrate auto-cascades a bare COMPLETE (no value); RxJS `first()` throws\n * EmptyError. Could align to `[[ERROR, EmptyError]]` (expressible) if strict RxJS parity is wanted.\n */\nexport function first<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"first\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (!pred || pred(v)) {\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no match in this wave → undirty RESOLVED (await next match)\n\t\t},\n\t};\n}\n\n/**\n * last: emit the last value matching `pred` (or the last value) on the source's COMPLETE.\n * `completeWhenDepsComplete:false + terminalAsRealInput:true`. EDGE (RxJS divergence, flagged):\n * RxJS `last()` throws EmptyError when no value matched; we COMPLETE without a value (no throw) —\n * the clean-slate substrate has no \"complete-or-throw\" terminal and SENTINEL forbids emitting a\n * placeholder.\n */\nexport function last<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"last\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) for (const v of b) if (!pred || pred(v as S)) ctx.state.set({ v });\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) {\n\t\t\t\tconst st = ctx.state.get<{ v: S }>();\n\t\t\t\tctx.down(st ? [[\"DATA\", st.v], [\"COMPLETE\"]] : [[\"COMPLETE\"]]);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * find: emit the first value matching `pred`, then COMPLETE. EDGE (RxJS divergence, flagged): RxJS\n * `find` emits `undefined` then COMPLETE when nothing matched — but `undefined` IS the SENTINEL\n * (R-sentinel), so a not-found source COMPLETE here emits a bare COMPLETE (no value).\n */\nexport function find<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"find\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (pred(v as S)) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // not found → bare COMPLETE\n\t\t},\n\t};\n}\n\n/**\n * elementAt: emit the value at zero-based `index`, then COMPLETE. EDGE (RxJS divergence, flagged):\n * RxJS throws ArgumentOutOfRangeError if the source completes before `index`; we COMPLETE without\n * a value (no throw), consistent with last/find.\n */\nexport function elementAt<S>(index: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"elementAt\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (count === index) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\tctx.state.set(count);\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // index out of range → bare COMPLETE\n\t\t},\n\t};\n}\n\n/** Observer object for {@link tap} — lifecycle-aware side effects (RxJS tap observer form). */\nexport interface TapObserver<T> {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n}\n\n/**\n * tap: invoke a side effect on each DATA (function form) or on data/error/complete (observer form);\n * values pass through unchanged. The observer form reads source terminals\n * (`completeWhenDepsComplete:false + errorWhenDepsError:false + terminalAsRealInput:true`) so it can\n * call `error`/`complete` then forward the terminal; the function form lets the substrate\n * auto-cascade terminals.\n */\nexport function tap<S>(fnOrObserver: ((v: S) => void) | TapObserver<S>): Operator<S, S> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\tconst fn = fnOrObserver;\n\t\treturn {\n\t\t\tfactory: \"tap\",\n\t\t\tbody: (ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\tif (b)\n\t\t\t\t\tfor (const v of b) {\n\t\t\t\t\t\tfn(v as S);\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\tconst obs = fnOrObserver;\n\treturn {\n\t\tfactory: \"tap\",\n\t\topts: {\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tobs.complete?.();\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(terminal)) {\n\t\t\t\tconst err = terminalErrorValue(terminal);\n\t\t\t\tobs.error?.(err);\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b)\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tobs.data?.(v as S);\n\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * onFirstData (alias `tapFirst`): invoke `fn` exactly once on the first qualifying value (default\n * `where: v => v != null` — null/undefined pass through without counting as \"first\"), then pass all\n * values through unchanged. The one-shot guard is per-node `ctx.state` (NOT a factory closure, so a\n * second instantiation of the same factory re-arms — R-ctx-state).\n */\nexport function onFirstData<S>(\n\tfn: (v: S) => void,\n\topts?: { where?: (v: S) => boolean },\n): Operator<S, S> {\n\tconst where = opts?.where ?? ((v: S) => v != null);\n\treturn {\n\t\tfactory: \"onFirstData\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet fired = ctx.state.get<boolean>() ?? false;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (!fired && where(v as S)) {\n\t\t\t\t\tfired = true;\n\t\t\t\t\tfn(v as S);\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(fired);\n\t\t},\n\t};\n}\n\n/** tapFirst: alias of {@link onFirstData} (the one-shot companion to {@link tap}). */\nexport const tapFirst = onFirstData;\n\n/** Options for {@link settle}. */\nexport interface SettleOpts<S> {\n\t/** Consecutive no-change waves before declaring convergence + COMPLETE. */\n\tquietWaves: number;\n\t/** Optional hard cap on total waves before forced COMPLETE. */\n\tmaxWaves?: number;\n\t/** Optional comparator; a DATA equal to the previous one does NOT reset the quiet counter. */\n\tequals?: (a: S, b: S) => boolean;\n}\n\n/** Internal settle accumulator state (per-node, R-ctx-state). */\ninterface SettleState<S> {\n\tlast: S | undefined;\n\thasValue: boolean;\n\tquiet: number;\n\twaves: number;\n\tdone: boolean;\n}\n\n/**\n * settle: forward each DATA unchanged, watch for convergence, COMPLETE once the source has been\n * quiet for `quietWaves` consecutive waves (or `maxWaves` elapsed). \"Wave\" = one fn invocation\n * (a DATA batch OR a bare undirty RESOLVED end-of-wave). No polling (R-no-polling) — the counter\n * advances only on real upstream waves. `settle`'s own `equals` is a body comparator, NOT the\n * removed substrate `equals` (D49).\n */\nexport function settle<S>(opts: SettleOpts<S>): Operator<S, S> {\n\tconst { quietWaves, maxWaves, equals } = opts;\n\tif (!Number.isInteger(quietWaves) || quietWaves < 1) {\n\t\tthrow new RangeError(`settle: quietWaves must be a positive integer (got ${quietWaves})`);\n\t}\n\tif (maxWaves != null && (!Number.isInteger(maxWaves) || maxWaves < 1)) {\n\t\tthrow new RangeError(`settle: maxWaves must be a positive integer when set (got ${maxWaves})`);\n\t}\n\treturn {\n\t\tfactory: \"settle\",\n\t\tbody: (ctx) => {\n\t\t\tconst st: SettleState<S> = ctx.state.get<SettleState<S>>() ?? {\n\t\t\t\tlast: undefined,\n\t\t\t\thasValue: false,\n\t\t\t\tquiet: 0,\n\t\t\t\twaves: 0,\n\t\t\t\tdone: false,\n\t\t\t};\n\t\t\tif (st.done) return;\n\t\t\tst.waves++;\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet sawChange = false;\n\t\t\tif (b && b.length > 0) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tconst next = v as S;\n\t\t\t\t\tconst isChange = !st.hasValue || equals == null || !equals(st.last as S, next);\n\t\t\t\t\tif (isChange) sawChange = true;\n\t\t\t\t\tst.last = next;\n\t\t\t\t\tst.hasValue = true;\n\t\t\t\t\tctx.down([[\"DATA\", next]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.quiet = sawChange ? 0 : st.quiet + 1;\n\t\t\tconst settled = st.hasValue && st.quiet >= quietWaves;\n\t\t\tconst exhausted = maxWaves != null && st.waves >= maxWaves;\n\t\t\tif (settled || exhausted) {\n\t\t\t\tst.done = true;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t\t// A no-DATA wave that didn't converge → bare undirty RESOLVED is synthesized by the\n\t\t\t// substrate (D49); nothing to emit here.\n\t\t},\n\t};\n}\n\n// ── Slice 3 — error-handling control (CSP-2.7, D40) ──\n// rescue/catchError ABSORB the source ERROR (errorWhenDepsError:false) and read the error payload\n// from `depTerminal(ctx, 0)` (R-deps-terminal). They set completeWhenDepsComplete:false so a\n// normal source COMPLETE is forwarded explicitly — which ALSO sidesteps B40 (the\n// completeWhenDepsComplete:true × absorbed-errored-dep auto-complete gap): there is no auto-complete\n// to block. valve is a [source, control] gate (state-verb-legitimate control input).\n\n/**\n * rescue (alias `catchError`): replace an upstream ERROR with a recovered value. On source DATA →\n * forward; on source ERROR → emit `recover(err)` as DATA (if `recover` throws, forward THAT as\n * ERROR); on source COMPLETE → COMPLETE. After recovery the source is terminal-errored (dead) so no\n * further values flow — the recovered value is the final cached value (matches the frozen pure-ts\n * reference; it does NOT auto-COMPLETE, RxJS-`catchError(()=>of(x))` divergence, flagged).\n */\nexport function rescue<S>(recover: (err: unknown) => S): Operator<S, S> {\n\treturn {\n\t\tfactory: \"rescue\",\n\t\topts: {\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (b) for (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t} else if (isTerminalError(terminal)) {\n\t\t\t\t// ERROR payload absorbed → recover.\n\t\t\t\ttry {\n\t\t\t\t\tctx.down([[\"DATA\", recover(terminalErrorValue(terminal))]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"rescue threw without a valid error payload\")]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** catchError: RxJS-named alias of {@link rescue}. */\nexport const catchError = rescue;\n\n/** Options for {@link valve}. */\nexport interface ValveOpts {\n\t/**\n\t * Optional AbortController (or a `() => AbortController | undefined` factory): on the control's\n\t * truthy→falsy edge, `valve` calls `controller.abort()` — cancel an in-flight async boundary\n\t * (LLM/fetch) the caller threaded `controller.signal` into. An external-resource cleanup (like\n\t * `ctx.onDeactivation`), NOT an imperative reactive trigger (R-no-imperative).\n\t */\n\tabortInFlight?: AbortController | (() => AbortController | undefined);\n}\n\n/**\n * valve: forward the source's DATA only while `control` (dep 1) is truthy; when closed, stay quiet\n * (undirty RESOLVED). `[source, control]` declared deps + `partial:true` (the control wave can fire\n * before the source ever delivers). `completeWhenDepsComplete:false` — closing the gate (control\n * terminating) does NOT complete the valve; only the SOURCE's terminal (read via\n * `terminalAsRealInput`) is forwarded. The `state`-verb control input is a legitimate external\n * boundary (D4 / D54), not a forbidden imperative trigger.\n */\nexport function valve<S>(opts?: ValveOpts): Operator<S, S> {\n\tconst abortInFlight = opts?.abortInFlight;\n\treturn {\n\t\tfactory: \"valve\",\n\t\topts: { partial: true, completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst ctlBatch = depBatch(ctx, 1);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\t\tconst controlValue = depLatest(ctx, 1) as boolean | undefined;\n\n\t\t\tif (abortInFlight != null) {\n\t\t\t\t// Fire abort on the truthy→falsy edge only (never on activation / no prior state).\n\t\t\t\tconst prev = ctx.state.get<{ ctl: boolean | undefined }>();\n\t\t\t\tif (prev?.ctl === true && !controlValue) {\n\t\t\t\t\tconst c = typeof abortInFlight === \"function\" ? abortInFlight() : abortInFlight;\n\t\t\t\t\tc?.abort();\n\t\t\t\t}\n\t\t\t\tctx.state.set({\n\t\t\t\t\tctl: controlValue === true ? true : controlValue == null ? undefined : false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Source terminal forwarding (control terminal is absorbed by completeWhenDepsComplete:false).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!controlValue) return; // gate closed → quiet (undirty RESOLVED)\n\n\t\t\tif (srcBatch && srcBatch.length > 0) {\n\t\t\t\tfor (const v of srcBatch) ctx.down([[\"DATA\", v]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Gate just opened this wave (control fired, source didn't): re-emit the last source value.\n\t\t\tconst srcLatest = depLatest(ctx, 0);\n\t\t\tif (ctlBatch && ctlBatch.length > 0 && srcLatest !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", srcLatest as S]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * The Graph layer (CSP-2): convenience + inspection entry (D5 / R-graph-role).\n *\n * g.* sugar desugars to dispatcher.register + Node and auto-registers into the graph\n * inspection index (D27: sugar→ctx-fn conversion lives strictly here; the substrate node\n * only ever sees `(ctx)=>void`). The Graph owns naming, describe, mount, and the D30\n * value-level throw→ERROR boundary. The bare node()/dispatcher stay inspection-free\n * (R-node-thin).\n *\n * Canonical authority: ~/src/graphrefly — D3/D5/D27/D30/D36/D37/D39, R-graph-role,\n * R-describe, R-fn-contract, R-edges-derived, R-meta-presentation.\n */\n\nimport { type BatchCtx, batch as batchRun } from \"../batch/batch.js\";\nimport { type Ctx, depCount, depLatest, type NodeFn } from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher } from \"../dispatcher/index.js\";\nimport { NodeCore } from \"../node/core.js\";\nimport {\n\tcheckpointStateOfNode,\n\tgetNodeOwner,\n\tisNodeActiveForRelease,\n\tisNodeRuntimeQuiescentForRelease,\n\tisNodeRuntimeReleased,\n\tNode,\n\ttype NodeOptions,\n\treleaseRuntimeOfNode,\n\tsetNodeOwner,\n\tsetNodeTopologyDepsChangedObserver,\n\tsubscriberCountOfNode,\n\twithEnvironmentDrivers,\n\twithNodeCore,\n} from \"../node/node.js\";\nimport type { NodeVersioningPolicy } from \"../node/versioning.js\";\nimport { errorPayload, messageTier, SENTINEL } from \"../protocol/messages.js\";\nimport {\n\tGRAPH_BLUEPRINT_VERSION,\n\ttype GraphBlueprint,\n\ttype GraphBlueprintOptions,\n\tgraphBlueprintDiagnostics,\n\tnormalizeTopology,\n\tnormalizeTopologyMeta,\n} from \"./blueprint.js\";\nimport {\n\tcheckpointBackendStateOfNode,\n\tcheckpointTerminal,\n\tcheckpointValue,\n\tGRAPH_CHECKPOINT_VERSION,\n\ttype GraphCheckpoint,\n\ttype GraphCheckpointFactory,\n\ttype GraphCheckpointJson,\n\ttype GraphCheckpointNode,\n\ttoCheckpointJson,\n} from \"./checkpoint.js\";\nimport {\n\ttype DescribeEdge,\n\ttype DescribeNode,\n\ttype DescribeOpts,\n\ttype DescribeSnapshot,\n\ttype GraphTopologySnapshot,\n\ttopologyFromDescribe,\n} from \"./describe.js\";\nimport { EnvironmentDrivers } from \"./environment.js\";\nimport { lifecycleRegistrars, restoreRegistrars } from \"./graph-lifecycle.js\";\nimport {\n\tassertCheckpointQuiescentStatus,\n\tcheckpointFactory,\n\tcloneTopologyEvent,\n\texplainSubset,\n\tisNonAuthoritativeCollectionHelperMeta,\n\tprefixTopologyPath,\n\ttopologyPathMatches,\n} from \"./graph-support.js\";\nimport {\n\tGraphTopologyGroup,\n\ttype TopologyGroup,\n\ttype TopologyGroupOptions,\n} from \"./graph-topology-group.js\";\nimport type { DepValues, DerivedFn, EffectFn, GraphOptions, SugarOpts } from \"./graph-types.js\";\nimport type {\n\tNodeProfile,\n\tObserveStream,\n\tProfile,\n\tTopologyEvent,\n\tTopologyStream,\n} from \"./inspect.js\";\nimport { initNodeWithCore, type Operator } from \"./operators.js\";\n\nexport type {\n\tTopologyGroup,\n\tTopologyGroupOptions,\n\tTopologyGroupReleaseOptions,\n} from \"./graph-topology-group.js\";\nexport type { DerivedFn, EffectFn, GraphOptions, SugarOpts } from \"./graph-types.js\";\n\ninterface Entry {\n\tnode: Node<unknown>;\n\tid: string;\n\tname?: string;\n\tfactory: string;\n\tdeps: readonly Node<unknown>[];\n\tmeta?: Record<string, unknown>;\n\trestore?: { ref: string; config?: unknown; configVersion?: unknown };\n}\n\ninterface TopologyObserver {\n\tpath?: string;\n\tsink(event: TopologyEvent): void;\n}\n\ninterface MountedGraph {\n\tat: string;\n\tgraph: Graph;\n\ttopologyUnsub?: () => void;\n}\n\nfunction nodeOwner(n: Node<unknown>): Graph | undefined {\n\treturn getNodeOwner(n) as Graph | undefined;\n}\n\nexport function assertGraphLocalNode(owner: Graph, n: Node<unknown>, label: string): void {\n\tif (isNodeRuntimeReleased(n)) {\n\t\tthrow new Error(`${label} has been released from its graph lifecycle (D122)`);\n\t}\n\tconst existing = nodeOwner(n);\n\tif (existing !== undefined && existing !== owner) {\n\t\tthrow new Error(\n\t\t\t`${label} belongs to a different graph; cross-graph deps require a wire bridge`,\n\t\t);\n\t}\n}\n\n/**\n * A state node (L4-Q1): a manual source whose `.set(v)` is `node.down([[DATA, v]])` sugar.\n * Extends the substrate Node so it is usable as a dep AND carries the graph-layer `.set`.\n *\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts\";\n *\n * const count = graph().state(0);\n * count.set(1);\n * ```\n * @category graph\n */\nexport class StateNode<T> extends Node<T> {\n\tset(v: T): void {\n\t\tthis.down([[\"DATA\", v]]);\n\t}\n}\n\n/**\n * Own a single graph-local topology, lifecycle, inspection index, and dispatcher boundary.\n *\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts\";\n *\n * const g = graph({ name: \"counter\" });\n * const count = g.state(0, { name: \"count\" });\n * const doubled = g.derived([count], ([value]) => value * 2, { name: \"doubled\" });\n * ```\n * @remarks **Graph-local:** Cross-graph dependencies require a wire bridge; direct deps stay inside\n * one graph ownership domain.\n * @category graph\n */\nexport class Graph {\n\treadonly name?: string;\n\tprivate readonly _dispatcher: Dispatcher;\n\tprivate readonly _versioning: NodeVersioningPolicy | undefined;\n\tprivate readonly _environment: EnvironmentDrivers;\n\tprivate readonly _core = new NodeCore();\n\tprivate readonly _entries = new Map<Node<unknown>, Entry>();\n\tprivate readonly _byId = new Map<string, Node<unknown>>();\n\tprivate readonly _retiredIds = new Set<string>();\n\tprivate readonly _mounts: MountedGraph[] = [];\n\tprivate _seq = 0;\n\tprivate _clock = 0; // graph-local monotonic clock for observe seq (D26)\n\tprivate _topologyObserverSeq = 0;\n\tprivate readonly _topologyObservers = new Map<number, TopologyObserver>();\n\tprivate _topologyDelivering = false;\n\tprivate readonly _topologyQueue: TopologyEvent[] = [];\n\t// D51: stable synthetic ids for unregistered live deps (runtime *Map inners) auto-discovered by\n\t// describe(). WeakMap-cached so successive describes agree + the inner's id is freed when it is.\n\t// A dedicated counter (NOT _seq) so a describe() call never perturbs registered-node id numbering.\n\tprivate _synthSeq = 0;\n\tprivate readonly _synthIds = new WeakMap<Node<unknown>, string>();\n\n\tconstructor(opts: GraphOptions = {}) {\n\t\tthis.name = opts.name;\n\t\tthis._dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tthis._versioning = opts.versioning;\n\t\tthis._environment = opts.environment ?? EnvironmentDrivers.empty();\n\t\tif (opts.profile) this._dispatcher.setRecording(true);\n\t\trestoreRegistrars.set(this, {\n\t\t\tstateNode: <T = unknown>(id: string, stateOpts: SugarOpts<T> = {}) => {\n\t\t\t\tconst n = this._construct(() => new StateNode<T>([], null, this._nodeOpts(stateOpts)));\n\t\t\t\tthis._addWithId(n, \"state\", [], stateOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t\tnode: <T = unknown>(\n\t\t\t\tid: string,\n\t\t\t\tfactory: string,\n\t\t\t\tdeps: readonly Node<unknown>[],\n\t\t\t\tfn: NodeFn | null,\n\t\t\t\tnodeOpts: SugarOpts<T> = {},\n\t\t\t) => {\n\t\t\t\tthis._assertDepsLocal(deps, `dep of restored '${id}'`);\n\t\t\t\tconst n = this._construct(() => new Node<T>([...deps], fn, this._nodeOpts(nodeOpts)));\n\t\t\t\tthis._addWithId(n, factory, deps, nodeOpts, id);\n\t\t\t\treturn n;\n\t\t\t},\n\t\t});\n\t\tlifecycleRegistrars.set(this, {\n\t\t\tassertRegisteredNode: (node, label) => this._assertRegisteredNode(node, label),\n\t\t\treleaseNodes: (nodes, releaseOpts) => this._releaseNodes(nodes, releaseOpts),\n\t\t});\n\t}\n\n\t// ── registration / inspection index ──\n\n\tprivate _add<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t): Node<T> {\n\t\tconst id = opts.name ?? `${factory}#${this._seq++}`;\n\t\treturn this._addWithId(n, factory, deps, opts, id);\n\t}\n\n\tprivate _addWithId<T>(\n\t\tn: Node<T>,\n\t\tfactory: string,\n\t\tdeps: readonly Node<unknown>[],\n\t\topts: SugarOpts<T>,\n\t\tid: string,\n\t): Node<T> {\n\t\tassertGraphLocalNode(this, n as Node<unknown>, `graph node '${opts.name ?? factory}'`);\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, `dep of '${opts.name ?? factory}'`);\n\t\tif (this._byId.has(id)) {\n\t\t\tthrow new Error(`graph: duplicate node id '${id}' (checkpoint/describe ids must be unique)`);\n\t\t}\n\t\tif (this._retiredIds.has(id)) {\n\t\t\tthrow new Error(`graph: node id '${id}' was released and cannot be reused (D152/D153)`);\n\t\t}\n\t\tconst meta =\n\t\t\topts.meta === undefined\n\t\t\t\t? undefined\n\t\t\t\t: (normalizeTopologyMeta(opts.meta, `graph node '${id}' meta`) as Record<string, unknown>);\n\t\tthis._entries.set(n as Node<unknown>, {\n\t\t\tnode: n as Node<unknown>,\n\t\t\tid,\n\t\t\tname: opts.name,\n\t\t\tfactory,\n\t\t\tdeps,\n\t\t\tmeta,\n\t\t\trestore: opts.restore,\n\t\t});\n\t\tsetNodeOwner(n as Node<unknown>, this);\n\t\tthis._byId.set(id, n as Node<unknown>);\n\t\tsetNodeTopologyDepsChangedObserver(n as Node<unknown>, (_node, prevDeps, nextDeps) => {\n\t\t\tthis._emitTopologyDepsChanged(n as Node<unknown>, prevDeps, nextDeps);\n\t\t});\n\t\tconst seqMatch = /#(\\d+)$/.exec(id);\n\t\tif (seqMatch) this._seq = Math.max(this._seq, Number(seqMatch[1]) + 1);\n\t\tthis._emitTopologyNodeRegistered(n as Node<unknown>);\n\t\treturn n;\n\t}\n\n\tprivate _assertDepsLocal(deps: readonly Node<unknown>[], label: string): void {\n\t\tfor (const dep of deps) assertGraphLocalNode(this, dep, label);\n\t}\n\n\tprivate _assertRegisteredNode(node: Node<unknown>, label: string): void {\n\t\tassertGraphLocalNode(this, node, label);\n\t\tif (!this._entries.has(node)) {\n\t\t\tthrow new Error(`${label} is not a registered graph node (D152)`);\n\t\t}\n\t}\n\n\tprivate _nodeOpts<T>(opts: SugarOpts<T>): NodeOptions<T> {\n\t\tif (opts.meta !== undefined) {\n\t\t\tnormalizeTopologyMeta(opts.meta, `graph node '${opts.name ?? opts.factory ?? \"node\"}' meta`);\n\t\t}\n\t\t// strip graph-only fields; inject the bound dispatcher\n\t\tconst { name: _n, meta: _m, restore: _r, ...rest } = opts;\n\t\treturn {\n\t\t\t...rest,\n\t\t\tversioning: rest.versioning ?? this._versioning,\n\t\t\tdispatcher: this._dispatcher,\n\t\t};\n\t}\n\n\tprivate _construct<TNode extends Node<unknown>>(create: () => TNode): TNode {\n\t\treturn withEnvironmentDrivers(this._environment, () => withNodeCore(this._core, create));\n\t}\n\n\t/** Look up a registered node by its id. */\n\tfind(id: string): Node<unknown> | undefined {\n\t\tconst local = this._byId.get(id);\n\t\tif (local !== undefined) return local;\n\t\tconst separator = id.indexOf(\"::\");\n\t\tif (separator < 0) return undefined;\n\t\tconst mountPath = id.slice(0, separator);\n\t\tconst childPath = id.slice(separator + 2);\n\t\treturn this._mounts.find((mount) => mount.at === mountPath)?.graph.find(childPath);\n\t}\n\n\tprivate _releaseNodes(nodes: readonly Node<unknown>[], _opts: { reason?: string } = {}): void {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst entries: Array<{ node: Node<unknown>; entry: Entry }> = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (seen.has(node)) continue;\n\t\t\tseen.add(node);\n\t\t\tconst entry = this._entries.get(node);\n\t\t\tif (entry === undefined) continue;\n\t\t\tentries.push({ node, entry });\n\t\t}\n\t\tconst releaseSet = new Set(entries.map(({ node }) => node));\n\t\tconst releaseIds = new Map(entries.map(({ node, entry }) => [node, entry.id] as const));\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tif (releaseSet.has(entry.node)) continue;\n\t\t\tfor (const dep of entry.node.deps) {\n\t\t\t\tif (!releaseSet.has(dep)) continue;\n\t\t\t\tconst depId = releaseIds.get(dep) ?? dep.name ?? dep.factory ?? \"released node\";\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still depends on '${depId}' (D122)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const { node, entry } of entries) {\n\t\t\tif (!isNodeRuntimeQuiescentForRelease(node)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' is not runtime-quiescent (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet internalSubscribers = 0;\n\t\t\tfor (const { node: dependent } of entries) {\n\t\t\t\tif (dependent === node || !isNodeActiveForRelease(dependent)) continue;\n\t\t\t\tfor (const dep of dependent.deps) {\n\t\t\t\t\tif (dep === node) internalSubscribers += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (subscriberCountOfNode(node) > internalSubscribers) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`graph: cannot release node group; '${entry.id}' still has live subscribers (D124)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst releasedEvents =\n\t\t\tthis._topologyObservers.size === 0\n\t\t\t\t? []\n\t\t\t\t: entries.map(({ node, entry }) => ({\n\t\t\t\t\t\tpath: entry.id,\n\t\t\t\t\t\tfactory: entry.factory,\n\t\t\t\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\t\t\t}));\n\t\tfor (const { node, entry } of entries) {\n\t\t\tthis._entries.delete(node);\n\t\t\tthis._byId.delete(entry.id);\n\t\t\tthis._retiredIds.add(entry.id);\n\t\t}\n\t\tlet releaseError: unknown;\n\t\tfor (const { node } of entries) {\n\t\t\ttry {\n\t\t\t\treleaseRuntimeOfNode(node);\n\t\t\t} catch (error) {\n\t\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t\t}\n\t\t}\n\t\tfor (const event of releasedEvents) this._emitTopologyNodeReleased(event);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\t// ── 8 verbs (core: node/state/batch + sugar: producer/derived/effect/mount) ──\n\n\t/** ctx-level power surface: a raw `(ctx)=>void` fn (or a passthrough/state when null). */\n\tnode<T = unknown>(\n\t\tdeps: readonly Node<unknown>[] = [],\n\t\tfn: NodeFn | null = null,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"node\"}'`);\n\t\tconst n = this._construct(() => new Node<T>(deps as Node<unknown>[], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, opts.factory ?? \"node\", deps, opts);\n\t}\n\n\t/** A manual source with `.set(v)` (L4-Q1). */\n\tstate<T>(initial: T, opts: SugarOpts<T> = {}): StateNode<T> {\n\t\tconst n = this._construct(\n\t\t\t() => new StateNode<T>([], null, { ...this._nodeOpts(opts), initial }),\n\t\t);\n\t\tthis._add(n, \"state\", [], opts);\n\t\treturn n;\n\t}\n\n\t/** ctx-level depless source; its fn runs on activation (R-rom-ram). */\n\tproducer<T = unknown>(fn: NodeFn, opts: SugarOpts<T> = {}): Node<T> {\n\t\tconst n = this._construct(() => new Node<T>([], fn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"producer\", [], opts);\n\t}\n\n\t/** value-level pure transform: deps → value (D27 wrapped; D30 throw→ERROR). */\n\tderived<const D extends readonly Node<unknown>[], T>(\n\t\tdeps: D,\n\t\tfn: DerivedFn<D, T>,\n\t\topts: SugarOpts<T> = {},\n\t): Node<T> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"derived\"}'`);\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst result = fn(...args);\n\t\t\t\tif (result !== undefined) ctx.down([[\"DATA\", result]]);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"derived threw without a valid error payload\")]]); // D30: value-level throw → graph-layer ERROR\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<T>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"derived\", deps, opts);\n\t}\n\n\t/** value-level sink: deps → effect; return value (a fn) becomes onDeactivation (D28). */\n\teffect<const D extends readonly Node<unknown>[]>(\n\t\tdeps: D,\n\t\tfn: EffectFn<D>,\n\t\topts: SugarOpts<void> = {},\n\t): Node<void> {\n\t\tthis._assertDepsLocal(deps, `dep of '${opts.name ?? \"effect\"}'`);\n\t\t// effect cleanup = deactivation-only (D28 / Flag 3): the LATEST returned cleanup\n\t\t// fires ONCE when the effect deactivates (not between re-runs — onRerun was cut).\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification / C-14): the substrate clears\n\t\t// the hook list before EACH fn run, so the effect re-registers its returned cleanup\n\t\t// every run — only the latest run's registration is live (or none, if the latest run\n\t\t// returned void). No st.registered/ctx.state bookkeeping; re-registering every run is\n\t\t// safe (the per-run clear prevents accumulation).\n\t\tconst ctxFn: NodeFn = (ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst args = Array.from({ length: depCount(ctx) }, (_, i) =>\n\t\t\t\t\tdepLatest(ctx, i),\n\t\t\t\t) as DepValues<D>;\n\t\t\t\tconst cleanup = fn(...args);\n\t\t\t\tif (typeof cleanup === \"function\") ctx.onDeactivation(cleanup);\n\t\t\t} catch (e) {\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"effect threw without a valid error payload\")]]);\n\t\t\t}\n\t\t};\n\t\tconst n = this._construct(() => new Node<void>([...deps], ctxFn, this._nodeOpts(opts)));\n\t\treturn this._add(n, \"effect\", deps, opts);\n\t}\n\n\t/** Declarative batch (D12): one wave, success→commit / throw→rollback. */\n\tbatch<T>(fn: (bctx: BatchCtx) => T): T {\n\t\treturn batchRun(fn);\n\t}\n\n\t/** Embed a child graph addressable under `at` (R-mount; mount has no deps). */\n\tmount(child: Graph, opts: { at: string }): void {\n\t\tconst mount = { at: opts.at, graph: child };\n\t\tthis._mounts.push(mount);\n\t\tif (this._topologyObservers.size > 0) this._ensureMountedTopologyForwarders();\n\t\tthis._emitTopologyMountChanged(opts.at);\n\t}\n\n\t// ── operator funnel (D43): instantiate any free-standing Operator (node sugar, D6/L1.5) ──\n\t// g.initNode is the single graph-bound entry for the whole operator/source catalog (D40):\n\t// it delegates to the FREE initNode (graph/operators.ts — the D30 throw→ERROR boundary +\n\t// dispatcher binding live there) and records the operator's REAL factory name in the\n\t// inspection index (_add) so describe shows it (D6/R-describe) while the node stays thin\n\t// (R-node-thin). Operators are free-standing factory definitions (graph/operators.ts,\n\t// graph/sources.ts) usable bare via the free initNode(); this funnel is the inspectable\n\t// path. Replaces the per-operator methods.\n\n\t/**\n\t * Instantiate an operator (or source) factory as a registered graph node. `deps` are\n\t * type-checked against the operator's input element type; the output type flows from the\n\t * operator. A source is a depless operator — pass `[]`. Caller `opts` (name/meta/behavioral\n\t * overrides) win over the operator's baked-in `opts`.\n\t */\n\tinitNode<TIn, TOut>(\n\t\top: Operator<TIn, TOut>,\n\t\tdeps: readonly Node<TIn>[],\n\t\topts: SugarOpts<TOut> = {},\n\t): Node<TOut> {\n\t\tconst entryOpts =\n\t\t\top.restore !== undefined && !(\"restore\" in opts) ? { ...opts, restore: op.restore } : opts;\n\t\tfor (const dep of deps as readonly Node<unknown>[])\n\t\t\tassertGraphLocalNode(this, dep, `dep of '${entryOpts.name ?? op.factory}'`);\n\t\t// Node<T> is invariant (T appears in NodeOptions.initial); widen the typed deps to the\n\t\t// erased Node surface the free initNode / _add accept (same cast the old methods used).\n\t\tconst erased = deps as readonly Node<unknown>[];\n\t\tconst n = withEnvironmentDrivers(this._environment, () =>\n\t\t\tinitNodeWithCore(this._core, op, erased, this._nodeOpts(entryOpts)),\n\t\t);\n\t\treturn this._add(n, op.factory, erased, entryOpts);\n\t}\n\n\t/**\n\t * Graph-owned activation root for internal helper nodes. This is the sanctioned keepalive shape:\n\t * a graph, not a helper closure, owns the subscription and returns the release handle.\n\t */\n\tretain<T>(node: Node<T>, opts: { reason?: string } = {}): () => void {\n\t\tassertGraphLocalNode(this, node as Node<unknown>, opts.reason ?? \"retained node\");\n\t\treturn node.subscribe(() => {});\n\t}\n\n\t/**\n\t * D152 graph-owned topology/release group. Members are ordinary registered graph nodes;\n\t * release is quiescent-only and removes ids atomically without synthesizing protocol messages.\n\t */\n\ttopologyGroup(opts: TopologyGroupOptions = {}): TopologyGroup {\n\t\treturn new GraphTopologyGroup(this, opts);\n\t}\n\n\t// ── inspection: describe / observe / profile (D39) ──\n\n\t/** Live point-in-time structure snapshot (R-describe / D39 / D51). `_prefix` carries the mount path. */\n\tdescribe(opts: DescribeOpts = {}, _prefix = \"\"): DescribeSnapshot {\n\t\t// D51: edges derive from each node's CURRENT/LIVE deps (entry.node.deps, NOT the\n\t\t// construction-time entry.deps), so a rewire (C-8 immediate / C-11 *Map deferred) is\n\t\t// reflected and every edge is a real current subscription (D3). A live dep absent from this\n\t\t// graph's index (a runtime *Map inner / bare fromAny node) is AUTO-DISCOVERED as a snapshot\n\t\t// node with a synthesized stable id (B2). B38 extends this to transitive live-reachability:\n\t\t// discovered unregistered nodes are recursively expanded through their own live deps.\n\t\tconst discovered = new Map<Node<unknown>, string>(); // unregistered live dep → synth local id\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\t// unregistered: a stable synthetic id, cached so successive describes + both call sites\n\t\t\t// agree; the `~` prefix can't collide with a registered name or `factory#seq`.\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\t// the `~` prefix avoids the registered `name`/`factory#seq` space; guard the\n\t\t\t\t// pathological case of a user node literally named `~factory#n` (bump until free).\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: DescribeNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\t// pass 1: registered nodes, reading LIVE deps (localId records any unregistered inner).\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid,\n\t\t\t\tfactory: entry.factory,\n\t\t\t\tstatus: entry.node.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (entry.name !== undefined) dnode.name = entry.name;\n\t\t\tif (entry.node.cache !== undefined) dnode.value = entry.node.cache; // absent = SENTINEL\n\t\t\tif (entry.node.version !== undefined) dnode.version = entry.node.version;\n\t\t\tif (entry.meta !== undefined) dnode.meta = entry.meta;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\t// pass 2: recursively emit auto-discovered unregistered nodes (D51+B38). localId() may add\n\t\t// further unregistered deps to `discovered` while this loop runs; a visited set keeps each\n\t\t// discovered node emitted once (stable ids via _synthIds).\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst dnode: DescribeNode = {\n\t\t\t\tid: `${_prefix}${sid}`,\n\t\t\t\tfactory: inner.factory ?? \"?\",\n\t\t\t\tstatus: inner.status,\n\t\t\t\tdeps: liveIds,\n\t\t\t};\n\t\t\tif (inner.cache !== undefined) dnode.value = inner.cache;\n\t\t\tif (inner.version !== undefined) dnode.version = inner.version;\n\t\t\tnodes.push(dnode);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: dnode.id });\n\t\t}\n\t\tconst snap: DescribeSnapshot = { nodes, edges };\n\t\tif (this.name !== undefined) snap.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tsnap.subgraphs = this._mounts.map((m) => m.graph.describe({}, `${_prefix}${m.at}::`));\n\t\t}\n\t\treturn opts.explain ? explainSubset(snap, opts.explain) : snap;\n\t}\n\n\t/**\n\t * D173 pure-structure topology snapshot over the same live truth source as describe().\n\t * Runtime status/value/version remain on describe(); blueprint metadata is a later envelope.\n\t */\n\ttopology(): GraphTopologySnapshot {\n\t\treturn topologyFromDescribe(this.describe());\n\t}\n\n\t/**\n\t * D177 synchronous audit/collaboration envelope over the pure topology snapshot.\n\t * Hashing and environment provenance enrichment stay in pure helpers outside Graph core.\n\t */\n\tblueprint(opts: GraphBlueprintOptions = {}): GraphBlueprint {\n\t\tconst topology = normalizeTopology(this.topology());\n\t\tconst out: GraphBlueprint = {\n\t\t\tversion: GRAPH_BLUEPRINT_VERSION,\n\t\t\ttopology,\n\t\t};\n\t\tif (opts.diagnostics) {\n\t\t\t(out as { diagnostics?: ReturnType<typeof graphBlueprintDiagnostics> }).diagnostics =\n\t\t\t\tgraphBlueprintDiagnostics(topology);\n\t\t}\n\t\tif (opts.provenance !== undefined) {\n\t\t\t(out as { provenance?: GraphBlueprint[\"provenance\"] }).provenance = normalizeTopologyMeta(\n\t\t\t\topts.provenance,\n\t\t\t\t\"graph blueprint provenance\",\n\t\t\t\t\"provenance\",\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _observeTargets(path?: string): Array<[string, Node<unknown>]> {\n\t\tconst all: Array<[string, Node<unknown>]> = [...this._entries.values()].map((e) => [\n\t\t\te.id,\n\t\t\te.node,\n\t\t]);\n\t\tif (path === undefined) return all; // whole graph\n\t\tconst exact = this._byId.get(path);\n\t\tif (exact) return [[path, exact]]; // single node\n\t\treturn all.filter(([id]) => id.startsWith(`${path}::`)); // subtree (mount-aware :: boundary, QA A-1)\n\t}\n\n\t/**\n\t * observe(path?) = read-only enveloped EGRESS (R-observe / D39). NOT a graph node — it\n\t * taps the target node(s) via subscribe and forwards each Message as an ObserveEvent.\n\t * No path = whole graph; an exact id = a single node; otherwise a `::`-prefix subtree.\n\t */\n\t// NOTE (R-observe/D19): observe is a real, lazily-ACTIVATING subscriber — observing a\n\t// cold node runs its fn (and activates upstream); whole-graph observe() activates the\n\t// graph. \"Read-only\" means it never emits/mutates node state, NOT that it avoids\n\t// activation. Use it knowing inspection of a cold graph wakes it.\n\tobserve(path?: string): ObserveStream {\n\t\tconst targets = this._observeTargets(path);\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst unsubs = targets.map(([id, n]) =>\n\t\t\t\t\tn.subscribe((msg) => {\n\t\t\t\t\t\tsink({ path: id, msg, tier: messageTier(msg[0]), seq: this._clock++ });\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};\n\t}\n\n\t/**\n\t * D145 observeTopology(path?) = read-only graph lifecycle egress over the existing\n\t * graph registry. It is not a graph node, does not subscribe to nodes, and emits no DATA.\n\t */\n\tobserveTopology(path?: string): TopologyStream {\n\t\treturn {\n\t\t\tsubscribe: (sink) => {\n\t\t\t\tconst id = this._topologyObserverSeq++;\n\t\t\t\tthis._topologyObservers.set(id, { path, sink });\n\t\t\t\tthis._ensureMountedTopologyForwarders();\n\t\t\t\treturn () => {\n\t\t\t\t\tthis._topologyObservers.delete(id);\n\t\t\t\t\tif (this._topologyObservers.size === 0) this._releaseMountedTopologyForwarders();\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate _idForTopologyNode(n: Node<unknown>): string {\n\t\tconst e = this._entries.get(n);\n\t\tif (e) return e.id;\n\t\tlet sid = this._synthIds.get(n);\n\t\tif (sid === undefined) {\n\t\t\tdo {\n\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t} while (this._byId.has(sid));\n\t\t\tthis._synthIds.set(n, sid);\n\t\t}\n\t\treturn sid;\n\t}\n\n\tprivate _topologyDeps(deps: readonly Node<unknown>[]): string[] {\n\t\treturn deps.map((dep) => this._idForTopologyNode(dep));\n\t}\n\n\tprivate _emitTopologyNodeRegistered(node: Node<unknown>): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-registered\",\n\t\t\tpath: entry.id,\n\t\t\tfactory: entry.factory,\n\t\t\tdeps: this._topologyDeps(node.deps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyDepsChanged(\n\t\tnode: Node<unknown>,\n\t\tprevDeps: readonly Node<unknown>[],\n\t\tnextDeps: readonly Node<unknown>[],\n\t): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tconst entry = this._entries.get(node);\n\t\tif (entry === undefined) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"deps-changed\",\n\t\t\tpath: entry.id,\n\t\t\tprevDeps: this._topologyDeps(prevDeps),\n\t\t\tdeps: this._topologyDeps(nextDeps),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyNodeReleased(event: {\n\t\tpath: string;\n\t\tfactory: string;\n\t\tdeps: readonly string[];\n\t}): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"node-released\",\n\t\t\tpath: event.path,\n\t\t\tfactory: event.factory,\n\t\t\tdeps: [...event.deps],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyMountChanged(path: string): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: \"mount-changed\",\n\t\t\tpath,\n\t\t\tfactory: \"mount\",\n\t\t\tdeps: [],\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _ensureMountedTopologyForwarders(): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tfor (const mount of this._mounts) {\n\t\t\tif (mount.topologyUnsub !== undefined) continue;\n\t\t\tconst mountPath = mount.at;\n\t\t\tmount.topologyUnsub = mount.graph.observeTopology().subscribe((event) => {\n\t\t\t\tthis._emitMountedTopologyEvent(mountPath, event);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate _releaseMountedTopologyForwarders(): void {\n\t\tfor (const mount of this._mounts) {\n\t\t\tmount.topologyUnsub?.();\n\t\t\tmount.topologyUnsub = undefined;\n\t\t}\n\t}\n\n\tprivate _emitMountedTopologyEvent(mountPath: string, event: TopologyEvent): void {\n\t\tif (this._topologyObservers.size === 0) return;\n\t\tthis._emitTopologyEvent({\n\t\t\tkind: event.kind,\n\t\t\tpath: prefixTopologyPath(mountPath, event.path),\n\t\t\tdeps: event.deps.map((dep) => prefixTopologyPath(mountPath, dep)),\n\t\t\t...(event.prevDeps !== undefined\n\t\t\t\t? { prevDeps: event.prevDeps.map((dep) => prefixTopologyPath(mountPath, dep)) }\n\t\t\t\t: {}),\n\t\t\t...(event.factory !== undefined ? { factory: event.factory } : {}),\n\t\t\tseq: this._clock++,\n\t\t});\n\t}\n\n\tprivate _emitTopologyEvent(event: TopologyEvent): void {\n\t\tif (this._topologyDelivering) {\n\t\t\tthis._topologyQueue.push(event);\n\t\t\treturn;\n\t\t}\n\t\tthis._topologyDelivering = true;\n\t\ttry {\n\t\t\tlet current: TopologyEvent | undefined = event;\n\t\t\twhile (current !== undefined) {\n\t\t\t\tconst observers = [...this._topologyObservers.entries()];\n\t\t\t\tfor (const [id, observer] of observers) {\n\t\t\t\t\tif (this._topologyObservers.get(id) !== observer) continue;\n\t\t\t\t\tif (observer.path !== undefined && !topologyPathMatches(current.path, observer.path))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tobserver.sink(cloneTopologyEvent(current));\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// D145 egress is read-only inspection; observer failure must not veto a\n\t\t\t\t\t\t// graph registry/rewire mutation that already committed.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = this._topologyQueue.shift();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._topologyDelivering = false;\n\t\t}\n\t}\n\n\t/**\n\t * profile() = accumulated-counter snapshot (R-profile / D39). invokes + duration are\n\t * dispatcher-backed (the invoke funnel, F-DISPATCH-ALL) — counters never live on the\n\t * thin node (R-node-thin). Requires `graph({ profile: true })` (opt-in, F-PERF).\n\t */\n\tprofile(): Profile {\n\t\tconst nodes: Record<string, NodeProfile> = {};\n\t\tlet totalInvokes = 0;\n\t\tfor (const e of this._entries.values()) {\n\t\t\tconst h = e.node.handle;\n\t\t\tconst stat = h ? this._dispatcher.statFor(h) : undefined;\n\t\t\tconst invokes = stat?.invokes ?? 0;\n\t\t\tnodes[e.id] = {\n\t\t\t\tinvokes,\n\t\t\t\ttotalDurationNs: stat?.totalDurationNs ?? 0,\n\t\t\t\tlastDurationNs: stat?.lastDurationNs ?? 0,\n\t\t\t\tstatus: e.node.status,\n\t\t\t};\n\t\t\t// graph-scoped (QA D-2): sum THIS graph's nodes, NOT the dispatcher-global\n\t\t\t// counter (which would leak invokes from other graphs sharing the dispatcher).\n\t\t\ttotalInvokes += invokes;\n\t\t}\n\t\treturn { totalInvokes, nodes };\n\t}\n\n\t/** Versioned graph lifecycle checkpoint (R-snapshot / D83 / D90). Pure capture, no storage I/O. */\n\tcheckpoint(): GraphCheckpoint {\n\t\treturn this._checkpoint(\"\", new WeakSet());\n\t}\n\n\tprivate _checkpoint(_prefix: string, stack: WeakSet<Graph>): GraphCheckpoint {\n\t\tif (stack.has(this)) {\n\t\t\tthrow new Error(\"checkpoint: cyclic graph mount detected\");\n\t\t}\n\t\tstack.add(this);\n\t\tconst discovered = new Map<Node<unknown>, string>();\n\t\tconst localId = (n: Node<unknown>): string => {\n\t\t\tconst e = this._entries.get(n);\n\t\t\tif (e) return `${_prefix}${e.id}`;\n\t\t\tlet sid = this._synthIds.get(n);\n\t\t\tif (sid === undefined) {\n\t\t\t\tdo {\n\t\t\t\t\tsid = `~${n.factory ?? \"?\"}#${this._synthSeq++}`;\n\t\t\t\t} while (this._byId.has(sid));\n\t\t\t\tthis._synthIds.set(n, sid);\n\t\t\t}\n\t\t\tdiscovered.set(n, sid);\n\t\t\treturn `${_prefix}${sid}`;\n\t\t};\n\t\tconst nodes: GraphCheckpointNode[] = [];\n\t\tconst edges: DescribeEdge[] = [];\n\t\tfor (const entry of this._entries.values()) {\n\t\t\tconst id = `${_prefix}${entry.id}`;\n\t\t\tconst liveIds = entry.node.deps.map(localId);\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(entry.node, id, {\n\t\t\t\t\tname: entry.name,\n\t\t\t\t\tfactory: checkpointFactory(entry.factory, entry.node, false, entry.restore, entry.meta),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst visited = new Set<Node<unknown>>();\n\t\tconst queue: Node<unknown>[] = [...discovered.keys()];\n\t\tfor (let i = 0; i < queue.length; i += 1) {\n\t\t\tconst inner = queue[i];\n\t\t\tif (visited.has(inner)) continue;\n\t\t\tvisited.add(inner);\n\t\t\tconst sid = discovered.get(inner);\n\t\t\tif (sid === undefined) continue;\n\t\t\tconst liveIds = inner.deps.map(localId);\n\t\t\tfor (const dep of inner.deps) {\n\t\t\t\tif (!this._entries.has(dep) && !visited.has(dep)) queue.push(dep);\n\t\t\t}\n\t\t\tconst id = `${_prefix}${sid}`;\n\t\t\tnodes.push(\n\t\t\t\tthis._checkpointNode(inner, id, {\n\t\t\t\t\tfactory: checkpointFactory(inner.factory ?? \"?\", inner, true),\n\t\t\t\t\tdeps: liveIds,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tfor (const from of liveIds) edges.push({ from, to: id });\n\t\t}\n\t\tconst checkpoint: GraphCheckpoint = {\n\t\t\tversion: GRAPH_CHECKPOINT_VERSION,\n\t\t\tnodes,\n\t\t\tedges,\n\t\t};\n\t\tif (this.name !== undefined) checkpoint.name = this.name;\n\t\tif (this._mounts.length > 0) {\n\t\t\tcheckpoint.mounts = this._mounts.map((m) => ({\n\t\t\t\tat: m.at,\n\t\t\t\tcheckpoint: m.graph._checkpoint(\"\", stack),\n\t\t\t}));\n\t\t}\n\t\tstack.delete(this);\n\t\treturn toCheckpointJson(checkpoint, \"checkpoint\") as unknown as GraphCheckpoint;\n\t}\n\n\tprivate _checkpointNode(\n\t\tnode: Node<unknown>,\n\t\tid: string,\n\t\topts: {\n\t\t\tname?: string;\n\t\t\tfactory: GraphCheckpointFactory;\n\t\t\tdeps: string[];\n\t\t\tmeta?: Record<string, unknown>;\n\t\t},\n\t): GraphCheckpointNode {\n\t\tconst state = checkpointStateOfNode(node);\n\t\tassertCheckpointQuiescentStatus(node.status, id, \"checkpoint\");\n\t\tconst nonAuthoritativeCollectionHelper = isNonAuthoritativeCollectionHelperMeta(opts.meta);\n\t\tconst out: GraphCheckpointNode = {\n\t\t\tid,\n\t\t\tfactory: opts.factory,\n\t\t\tstatus: node.status,\n\t\t\tdeps: opts.deps,\n\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t: checkpointValue(state.cache, state.hasData, `${id}.value`),\n\t\t\tterminal: checkpointTerminal(state.terminal, `${id}.terminal`),\n\t\t\tlifecycle: { activated: state.activated, hasCalledFnOnce: state.hasCalledFnOnce },\n\t\t\tctxState: {\n\t\t\t\tpersist: state.ctxState.persist,\n\t\t\t\tvalue: nonAuthoritativeCollectionHelper\n\t\t\t\t\t? { kind: \"SENTINEL\" }\n\t\t\t\t\t: checkpointValue(\n\t\t\t\t\t\t\tstate.ctxState.value,\n\t\t\t\t\t\t\tstate.ctxState.value !== SENTINEL,\n\t\t\t\t\t\t\t`${id}.ctxState`,\n\t\t\t\t\t\t),\n\t\t\t},\n\t\t};\n\t\tif (opts.name !== undefined) out.name = opts.name;\n\t\tconst backendState = checkpointBackendStateOfNode(node, `${id}.backendState`);\n\t\tif (backendState !== undefined) out.backendState = backendState;\n\t\tif (state.version !== undefined) out.version = state.version;\n\t\tif (opts.meta !== undefined)\n\t\t\tout.meta = toCheckpointJson(opts.meta, `${id}.meta`) as {\n\t\t\t\t[key: string]: GraphCheckpointJson;\n\t\t\t};\n\t\treturn out;\n\t}\n}\n\n/**\n * Construct a graph with graph-local topology, lifecycle, and inspection ownership.\n *\n * @param opts - Optional graph name, dispatcher, versioning policy, environment drivers, and\n * profiling switch.\n * @returns A `Graph` instance whose sugar methods create graph-registered nodes.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts\";\n *\n * const g = graph({ name: \"counter\" });\n * const count = g.state(0, { name: \"count\" });\n * const doubled = g.derived([count], ([value]) => value * 2);\n * ```\n * @category graph\n */\nexport function graph(opts: GraphOptions = {}): Graph {\n\treturn new Graph(opts);\n}\n\n/** @internal D122 graph-owned ephemeral node-group release. */\nexport function releaseGraphNodes(\n\tgraph: Graph,\n\tnodes: readonly Node<unknown>[],\n\topts: { reason?: string } = {},\n): void {\n\tconst registrar = lifecycleRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"graph: unknown lifecycle registrar\");\n\tregistrar.releaseNodes(nodes, opts);\n}\n\n/** @internal D94 descriptor path: register a restored state node without widening Graph. */\nexport function restoreStateNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\topts: SugarOpts<T> = {},\n): StateNode<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.stateNode(id, opts);\n}\n\n/** @internal D94 descriptor path: register a restored ctx-level node without widening Graph. */\nexport function restoreNodeInGraph<T = unknown>(\n\tgraph: Graph,\n\tid: string,\n\tfactory: string,\n\tdeps: readonly Node<unknown>[],\n\tfn: NodeFn | null,\n\topts: SugarOpts<T> = {},\n): Node<T> {\n\tconst registrar = restoreRegistrars.get(graph);\n\tif (registrar === undefined) throw new Error(\"restoreGraph: unknown graph restore registrar\");\n\treturn registrar.node(id, factory, deps, fn, opts);\n}\n","/**\n * Passive semantic-memory vocabulary and deterministic helpers.\n *\n * D158 splits semantic memory into horizontal patterns and vertical solutions.\n * This module intentionally owns no graph nodes, storage restore, timers,\n * subscriptions, vector indexes, knowledge graphs, or agentic runtime.\n */\n\nimport type { StrictJsonValue } from \"../json/codec.js\";\n\n/** Stable identity for a semantic-memory fact. */\nexport type FactId = string;\n\n/** Shard partition key used by passive sharding helpers. */\nexport type ShardKey = string | number;\n\n/**\n * A single semantic-memory fact. Pattern convention only: this is not a\n * protocol message, storage record owner, restore contract, or graph runtime.\n */\nexport interface MemoryFragment<T = unknown> {\n\treadonly id: FactId;\n\treadonly payload: T;\n\t/** Transaction time, typically monotonic nanoseconds. */\n\treadonly tNs: bigint;\n\t/** Valid-time start. Undefined means unbounded past. */\n\treadonly validFrom?: bigint;\n\t/** Valid-time end. Undefined means currently valid. */\n\treadonly validTo?: bigint;\n\t/** Confidence score in the closed interval [0, 1]. */\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\t/** Fact ids this fragment derives from or depends on. */\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** Columnar passive store vocabulary for callers that keep memory facts outside GraphReFly. */\nexport interface FactStore<T = unknown> {\n\treadonly byId: ReadonlyMap<FactId, MemoryFragment<T>>;\n}\n\n/** Read-only projection passed to scoring policies; it exposes no mutation surface. */\nexport interface StoreReadHandle<T = unknown> {\n\tget(id: FactId): MemoryFragment<T> | undefined;\n\thas(id: FactId): boolean;\n\treadonly size: number;\n\tvalues(): IterableIterator<MemoryFragment<T>>;\n}\n\nexport type ScoringPolicy<T = unknown> = (\n\tfragment: MemoryFragment<T>,\n\tstore: StoreReadHandle<T>,\n) => number;\nexport type DecayPolicy = (confidence: number, ageNs: bigint) => number;\nexport type AdmissionFilter<T = unknown> = (fragment: MemoryFragment<T>) => boolean;\n\n/** Outcome signal for policy learning. This is an application fact, not a protocol event. */\nexport interface OutcomeSignal {\n\treadonly factId: FactId;\n\treadonly reward: number;\n}\n\n/** Passive structured query over semantic-memory facts. */\nexport interface MemoryQuery {\n\treadonly tags?: readonly string[];\n\treadonly asOf?: bigint;\n\treadonly minConfidence?: number;\n\treadonly limit?: number;\n}\n\nexport interface MemoryAnswer<T = unknown> {\n\treadonly query: MemoryQuery;\n\treadonly results: readonly MemoryFragment<T>[];\n}\n\nexport type KnowledgeAssertionStrictJsonValue = StrictJsonValue;\n\n/** Passive KG endpoint vocabulary. Entity ids are DATA keys, not graph node ids. */\nexport interface KnowledgeAssertionSubject {\n\treadonly id: FactId;\n\treadonly type?: string;\n}\n\n/** Passive KG object/value vocabulary. */\nexport type KnowledgeAssertionObject =\n\t| {\n\t\t\treadonly kind: \"entity\";\n\t\t\treadonly id: FactId;\n\t\t\treadonly type?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"value\";\n\t\t\treadonly value: KnowledgeAssertionStrictJsonValue;\n\t\t\treadonly valueType?: string;\n\t };\n\n/** Passive KG assertion fact consumed by lower semantic-memory graph patterns. */\nexport interface KnowledgeAssertion {\n\treadonly id: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\n/** Entry vocabulary for ranked collection-like memory views. */\nexport interface CollectionEntry<T = unknown> {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: bigint;\n\treadonly lastAccessNs: bigint;\n\treadonly baseScore: number;\n}\n\nexport type RankedCollectionEntry<T = unknown> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionScoreFn<T = unknown> = (value: T) => number;\n\n/** Query shape shared by passive retrieval/ranking helpers. */\nexport interface RetrievalQuery {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n\treadonly context?: readonly string[];\n}\n\nexport interface VectorSearchResult<TMeta = unknown> {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n}\n\nexport interface RetrievalEntry<TMem = unknown> {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n\treadonly context?: readonly string[];\n}\n\nexport interface RetrievalTrace<TMem = unknown> {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n}\n\n/** Generic per-dimension thresholds. Any configured dimension below threshold is rejected. */\nexport type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;\n\nexport interface AdmissionScoredOptions<Dims extends string, TRaw = unknown> {\n\treadonly scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;\n\treadonly thresholds?: AdmissionThresholds<Dims>;\n}\n\nexport interface AdmissionScores {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n}\n\nexport interface AdmissionScore3DOptions {\n\treadonly scoreFn: (raw: unknown) => AdmissionScores;\n\treadonly persistenceThreshold?: number;\n\treadonly personalValueThreshold?: number;\n\treadonly requireStructured?: boolean;\n}\n\nexport interface ShardByTenantOptions {\n\treadonly tenants?: readonly string[];\n\treadonly shardCount?: number;\n}\n\nexport interface ShardByTenantConfig<T = unknown> {\n\treadonly shardBy: (fragment: MemoryFragment<T>) => ShardKey;\n\treadonly shardCount: number;\n}\n\nexport interface MemoryFragmentValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n}\n\n/** Cosine similarity over zero-padded vectors. Non-finite results normalize to 0. */\nexport function cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\tconst score = dot / Math.sqrt(na * nb);\n\treturn Number.isFinite(score) ? score : 0;\n}\n\n/**\n * Returns true when a fragment is valid at `asOf`.\n *\n * Omitted `asOf` has no clock to compare against, so it admits only fragments\n * that are live and not valid-time delayed.\n */\nexport function memoryFragmentValidAt(fragment: MemoryFragment, asOf?: bigint): boolean {\n\tif (asOf === undefined) return fragment.validTo === undefined && fragment.validFrom === undefined;\n\tif (fragment.validFrom !== undefined && fragment.validFrom > asOf) return false;\n\tif (fragment.validTo !== undefined && fragment.validTo <= asOf) return false;\n\treturn true;\n}\n\n/** Pure structured-query predicate over a single fragment. */\nexport function memoryFragmentMatchesQuery(\n\tfragment: MemoryFragment,\n\tquery: MemoryQuery = {},\n): boolean {\n\tif (!memoryFragmentValidAt(fragment, query.asOf)) return false;\n\tif (query.minConfidence !== undefined && fragment.confidence < query.minConfidence) return false;\n\tif (\n\t\tquery.tags &&\n\t\tquery.tags.length > 0 &&\n\t\t!query.tags.some((tag) => fragment.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filter and rank fragments by confidence desc, then transaction time desc. */\nexport function filterMemoryFragments<T>(\n\tfragments: Iterable<MemoryFragment<T>>,\n\tquery: MemoryQuery = {},\n): readonly MemoryFragment<T>[] {\n\tconst results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tresults.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));\n\treturn query.limit === undefined ? results : results.slice(0, Math.max(0, query.limit));\n}\n\n/** Validate the passive MemoryFragment shape without throwing. */\nexport function validateMemoryFragment(value: unknown): MemoryFragmentValidation {\n\tconst errors: string[] = [];\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn { ok: false, errors: [\"fragment must be an object\"] };\n\t}\n\tconst fragment = value as Partial<MemoryFragment>;\n\tif (typeof fragment.id !== \"string\" || fragment.id.length === 0) {\n\t\terrors.push(\"id must be a non-empty string\");\n\t}\n\tif (!Object.hasOwn(fragment, \"payload\")) {\n\t\terrors.push(\"payload must be present\");\n\t}\n\tif (typeof fragment.tNs !== \"bigint\") {\n\t\terrors.push(\"tNs must be a bigint\");\n\t}\n\tconst confidence = fragment.confidence;\n\tif (\n\t\t!Number.isFinite(confidence) ||\n\t\tconfidence === undefined ||\n\t\tconfidence < 0 ||\n\t\tconfidence > 1\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1]\");\n\t}\n\tif (!isDenseArrayOf(fragment.tags, (tag): tag is string => typeof tag === \"string\")) {\n\t\terrors.push(\"tags must be a readonly string array\");\n\t}\n\tif (!isDenseArrayOf(fragment.sources, (source): source is string => typeof source === \"string\")) {\n\t\terrors.push(\"sources must be a readonly string array\");\n\t}\n\tif (fragment.validFrom !== undefined && typeof fragment.validFrom !== \"bigint\") {\n\t\terrors.push(\"validFrom must be a bigint when present\");\n\t}\n\tif (fragment.validTo !== undefined && typeof fragment.validTo !== \"bigint\") {\n\t\terrors.push(\"validTo must be a bigint when present\");\n\t}\n\tif (\n\t\ttypeof fragment.validFrom === \"bigint\" &&\n\t\ttypeof fragment.validTo === \"bigint\" &&\n\t\tfragment.validFrom >= fragment.validTo\n\t) {\n\t\terrors.push(\"validFrom must be earlier than validTo\");\n\t}\n\tif (\n\t\tfragment.embedding !== undefined &&\n\t\t!isDenseArrayOf(fragment.embedding, (component): component is number =>\n\t\t\tNumber.isFinite(component),\n\t\t)\n\t) {\n\t\terrors.push(\"embedding must be a finite number array when present\");\n\t}\n\tif (fragment.parentFragmentId !== undefined && typeof fragment.parentFragmentId !== \"string\") {\n\t\terrors.push(\"parentFragmentId must be a string when present\");\n\t}\n\tif (fragment.provenance !== undefined && typeof fragment.provenance !== \"string\") {\n\t\terrors.push(\"provenance must be a string when present\");\n\t}\n\treturn { ok: errors.length === 0, errors };\n}\n\nexport function isMemoryFragment(value: unknown): value is MemoryFragment {\n\treturn validateMemoryFragment(value).ok;\n}\n\n/**\n * Generic N-dimension admission filter. Missing or non-finite thresholded scores reject.\n */\nexport function admissionScored<Dims extends string, TRaw = unknown>(\n\topts: AdmissionScoredOptions<Dims, TRaw>,\n): (raw: TRaw) => boolean {\n\tconst thresholds = opts.thresholds ?? ({} as AdmissionThresholds<Dims>);\n\treturn (raw: TRaw): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tfor (const dim of Object.keys(thresholds) as Dims[]) {\n\t\t\tconst min = thresholds[dim];\n\t\t\tif (min === undefined) continue;\n\t\t\tconst score = scores[dim];\n\t\t\tconst safe = Number.isFinite(score) ? (score as number) : Number.NEGATIVE_INFINITY;\n\t\t\tif (safe < min) return false;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/** Three-axis admission sugar for persistence / structure / personal-value scoring. */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean {\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tif (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;\n\t\tif (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;\n\t\tif (!opts.requireStructured) return true;\n\t\treturn scoreAtLeast(scores.structure, Number.MIN_VALUE);\n\t};\n}\n\n/** Build a passive `{ shardBy, shardCount }` pair for tenant-isolated sharding. */\nexport function shardByTenant<T>(\n\ttenantOf: (fragment: MemoryFragment<T>) => string,\n\topts: ShardByTenantOptions = {},\n): ShardByTenantConfig<T> {\n\tif (opts.tenants && opts.tenants.length > 0) {\n\t\tconst tenants = [...new Set(opts.tenants)];\n\t\tconst index = new Map(tenants.map((tenant, i) => [tenant, i] as const));\n\t\tconst overflow = tenants.length;\n\t\treturn {\n\t\t\tshardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,\n\t\t\tshardCount: tenants.length + 1,\n\t\t};\n\t}\n\tconst configuredShardCount = opts.shardCount ?? 4;\n\tconst shardCount = Number.isSafeInteger(configuredShardCount)\n\t\t? Math.max(1, configuredShardCount)\n\t\t: 4;\n\treturn { shardBy: (fragment) => tenantOf(fragment), shardCount };\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction scoreAtLeast(score: number, min: number): boolean {\n\treturn Number.isFinite(score) && score >= min;\n}\n","import { strictJsonCodec } from \"../json/codec.js\";\nimport type { MemoryFragment } from \"../patterns/semantic-memory.js\";\nimport { validateMemoryFragment } from \"../patterns/semantic-memory.js\";\nimport type {\n\tAgenticMemoryArtifactKind,\n\tAgenticMemoryError,\n\tAgenticMemoryKind,\n\tAgenticMemoryPersistenceLevel,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRecordMetadata,\n\tAgenticMemoryScope,\n\tAgenticMemoryStatusState,\n\tStrictJsonValue,\n} from \"./agentic-memory-types.js\";\n\nexport function validateAndProjectRecords<T>(value: unknown): {\n\treadonly records: AgenticMemoryRecord<T>[];\n\treadonly fragments: MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Record<FactId, AgenticMemoryRecordMetadata>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\treadonly invalidRecordIndexes: Set<number>;\n} {\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tconst fragments: MemoryFragment<T>[] = [];\n\tconst metadataByFragmentId = Object.create(null) as Record<FactId, AgenticMemoryRecordMetadata>;\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tconst invalidRecordIndexes = new Set<number>();\n\tconst seenRecordIds = new Set<FactId>();\n\tconst seenFragmentIds = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input must be an array\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input length could not be read\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-record\",\n\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = validateAndSnapshotRecord<T>(raw, i);\n\t\tif (result.errors.length > 0) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push(...result.errors);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.record === undefined) continue;\n\t\tif (seenRecordIds.has(result.record.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-record-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate record id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate record id '${result.record.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (seenFragmentIds.has(result.record.fragment.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate fragment id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\tfragmentId: result.record.fragment.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate fragment id '${result.record.fragment.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenRecordIds.add(result.record.id);\n\t\tseenFragmentIds.add(result.record.fragment.id);\n\t\trecords.push(result.record);\n\t\tfragments.push(result.record.fragment);\n\t\tmetadataByFragmentId[result.record.fragment.id] = recordMetadata(result.record);\n\t}\n\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n}\n\nexport function validateAndSnapshotRecord<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\ttry {\n\t\treturn validateAndSnapshotRecordInner<T>(value, index);\n\t} catch (error) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nexport function validateAndSnapshotRecordInner<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: \"agenticMemoryBundle: record must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst record = value as Partial<AgenticMemoryRecord<T>> & Record<string, unknown>;\n\tconst recordId = typeof record.id === \"string\" ? record.id : undefined;\n\tif (recordId === undefined || recordId.length === 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record.id must be a non-empty string\",\n\t\t\tindex,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"record.id must be a non-empty string\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryKind(record.kind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.kind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"kind must be one of working, episodic, semantic, procedural, profile\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(record.persistenceLevel)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-persistence-level\",\n\t\t\tmessage: \"agenticMemoryBundle: record.persistenceLevel is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\n\t\t\t\t\"persistenceLevel must be one of turn, session, project, longTerm, permanent, archived\",\n\t\t\t],\n\t\t});\n\t}\n\tif (!isAgenticMemoryArtifactKind(record.artifactKind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-artifact-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.artifactKind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"artifactKind must be one of raw, insight, profile, procedure\"],\n\t\t});\n\t}\n\tconst scopeValidation = validateScope(record.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-scope\",\n\t\t\tmessage: \"agenticMemoryBundle: record.scope is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(scopeValidation.errors),\n\t\t});\n\t}\n\tconst fragmentValidation = validateMemoryFragment(record.fragment);\n\tif (!fragmentValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-fragment\",\n\t\t\tmessage: \"agenticMemoryBundle: record.fragment is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\tfragmentId:\n\t\t\t\ttypeof record.fragment === \"object\" &&\n\t\t\t\trecord.fragment !== null &&\n\t\t\t\ttypeof (record.fragment as Partial<MemoryFragment>).id === \"string\"\n\t\t\t\t\t? (record.fragment as Partial<MemoryFragment>).id\n\t\t\t\t\t: undefined,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze([...fragmentValidation.errors]),\n\t\t});\n\t}\n\tconst forbiddenFields = [\n\t\t\"storageTier\",\n\t\t\"storageKey\",\n\t\t\"adapter\",\n\t\t\"collection\",\n\t\t\"collections\",\n\t\t\"ttl\",\n\t\t\"ttlMs\",\n\t\t\"ttlNs\",\n\t\t\"expiresAt\",\n\t\t\"timer\",\n\t\t\"scheduler\",\n\t\t\"schedule\",\n\t\t\"retentionTimer\",\n\t\t\"consolidationSchedule\",\n\t\t\"reflectionSchedule\",\n\t\t\"llm\",\n\t\t\"llmHandle\",\n\t\t\"tool\",\n\t\t\"toolHandle\",\n\t\t\"runner\",\n\t\t\"runnerHandle\",\n\t\t\"restore\",\n\t\t\"hydrate\",\n\t\t\"hydration\",\n\t\t\"graphMutation\",\n\t\t\"protocol\",\n\t] as const;\n\tconst presentForbidden = forbiddenFields.filter((field) => Object.hasOwn(record, field));\n\tif (presentForbidden.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record contains forbidden runtime/persistence fields\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\tpresentForbidden.map((field) => `${field} is not part of AgenticMemoryRecord`),\n\t\t\t),\n\t\t});\n\t}\n\tif (errors.length > 0) return { errors };\n\tconst scope = scopeValidation.scope;\n\tconst fragment = snapshotFragment(record.fragment as MemoryFragment<T>);\n\treturn {\n\t\trecord: Object.freeze({\n\t\t\tid: recordId as FactId,\n\t\t\tkind: record.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: record.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: record.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tfragment,\n\t\t}),\n\t\terrors,\n\t};\n}\n\nexport function snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nexport function recordMetadata(record: AgenticMemoryRecord): AgenticMemoryRecordMetadata {\n\treturn Object.freeze({\n\t\trecordId: record.id,\n\t\tkind: record.kind,\n\t\tpersistenceLevel: record.persistenceLevel,\n\t\tartifactKind: record.artifactKind,\n\t\t...(record.scope === undefined ? {} : { scope: record.scope }),\n\t});\n}\n\nexport function validateRecordMetadata(value: unknown): {\n\treadonly ok: boolean;\n\treadonly metadata?: AgenticMemoryRecordMetadata;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (!isPlainRecord(value)) {\n\t\treturn { ok: false, errors: [\"record metadata must be an object when present\"] };\n\t}\n\tconst errors: string[] = [];\n\tfor (const key of Object.keys(value)) {\n\t\tif (\n\t\t\tkey !== \"recordId\" &&\n\t\t\tkey !== \"kind\" &&\n\t\t\tkey !== \"persistenceLevel\" &&\n\t\t\tkey !== \"artifactKind\" &&\n\t\t\tkey !== \"scope\"\n\t\t) {\n\t\t\terrors.push(`record.${key} is not part of AgenticMemoryRecordMetadata`);\n\t\t}\n\t}\n\tif (!isNonEmptyString(value.recordId)) {\n\t\terrors.push(\"record.recordId must be a non-empty string\");\n\t}\n\tif (!isAgenticMemoryKind(value.kind)) {\n\t\terrors.push(\"record.kind is invalid\");\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\terrors.push(\"record.persistenceLevel is invalid\");\n\t}\n\tif (!isAgenticMemoryArtifactKind(value.artifactKind)) {\n\t\terrors.push(\"record.artifactKind is invalid\");\n\t}\n\tconst scopeValidation = validateScope(value.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push(...scopeValidation.errors.map((error) => `record.${error}`));\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tmetadata: Object.freeze({\n\t\t\trecordId: value.recordId as FactId,\n\t\t\tkind: value.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: value.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scopeValidation.scope === undefined ? {} : { scope: scopeValidation.scope }),\n\t\t}),\n\t};\n}\n\nexport function contextState(\n\tprojection: AgenticMemoryStatusState,\n\tretrieval: MemoryRetrievalStatus[\"state\"],\n): AgenticMemoryContextState {\n\tif (projection === \"error\" || retrieval === \"error\") return \"error\";\n\tif (projection === \"partial\" || retrieval === \"partial\") return \"partial\";\n\treturn retrieval;\n}\n\nexport function agenticStatusState(\n\terrorCount: number,\n\tvalidRecords: number,\n): AgenticMemoryStatusState {\n\tif (errorCount > 0 && validRecords === 0) return \"error\";\n\tif (errorCount > 0) return \"partial\";\n\treturn validRecords > 0 ? \"ready\" : \"empty\";\n}\n\nexport function isAgenticMemoryKind(value: unknown): value is AgenticMemoryKind {\n\treturn (\n\t\tvalue === \"working\" ||\n\t\tvalue === \"episodic\" ||\n\t\tvalue === \"semantic\" ||\n\t\tvalue === \"procedural\" ||\n\t\tvalue === \"profile\"\n\t);\n}\n\nexport function isAgenticMemoryPersistenceLevel(\n\tvalue: unknown,\n): value is AgenticMemoryPersistenceLevel {\n\treturn (\n\t\tvalue === \"turn\" ||\n\t\tvalue === \"session\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"longTerm\" ||\n\t\tvalue === \"permanent\" ||\n\t\tvalue === \"archived\"\n\t);\n}\n\nexport function isAgenticMemoryArtifactKind(value: unknown): value is AgenticMemoryArtifactKind {\n\treturn value === \"raw\" || value === \"insight\" || value === \"profile\" || value === \"procedure\";\n}\n\nexport function validateScope(value: unknown): {\n\treadonly ok: boolean;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn { ok: false, errors: [\"scope must be an object when present\"] };\n\t}\n\tconst scope = value as Record<string, unknown>;\n\tconst errors: string[] = [];\n\tconst allowed = new Set([\"sessionId\", \"projectId\", \"userId\", \"tenantId\"]);\n\tfor (const key of Object.keys(scope)) {\n\t\tif (!allowed.has(key)) errors.push(`scope.${key} is not part of AgenticMemoryScope`);\n\t}\n\tfor (const key of allowed) {\n\t\tif (scope[key] !== undefined && (typeof scope[key] !== \"string\" || scope[key].length === 0)) {\n\t\t\terrors.push(`scope.${key} must be a non-empty string when present`);\n\t\t}\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tscope: Object.freeze({\n\t\t\t...(scope.sessionId === undefined ? {} : { sessionId: scope.sessionId as string }),\n\t\t\t...(scope.projectId === undefined ? {} : { projectId: scope.projectId as string }),\n\t\t\t...(scope.userId === undefined ? {} : { userId: scope.userId as string }),\n\t\t\t...(scope.tenantId === undefined ? {} : { tenantId: scope.tenantId as string }),\n\t\t}),\n\t};\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nexport function assertExactKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected fields ${actual.join(\",\")}`);\n\t}\n}\n\nexport function assertAgenticMemoryRecordCodecShape(value: unknown): void {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertNoSymbolKeys(value, \"agenticMemoryRecordFrame.record\");\n\tassertExactKeys(\n\t\tvalue,\n\t\tvalue.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst fragment = value.fragment;\n\tif (!isPlainRecord(fragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertNoSymbolKeys(fragment, \"agenticMemoryRecordFrame.record.fragment\");\n\tassertExactKeys(\n\t\tfragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(fragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(fragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(fragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(fragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(fragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tassertStrictJsonValue(fragment.tags, \"record.fragment.tags\");\n\tassertStrictJsonValue(fragment.sources, \"record.fragment.sources\");\n\tif (fragment.embedding !== undefined) {\n\t\tassertStrictJsonValue(fragment.embedding, \"record.fragment.embedding\");\n\t}\n\tif (value.scope !== undefined) assertScopeFrame(value.scope);\n}\n\nexport function assertNoSymbolKeys(value: object, label: string): void {\n\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\tthrow new TypeError(`${label}: unexpected symbol fields`);\n\t}\n}\n\nexport function decimalBigIntString(value: bigint, label: string): string {\n\tconst out = value.toString(10);\n\tif (!/^-?(0|[1-9]\\d*)$/.test(out)) {\n\t\tthrow new TypeError(`${label} must encode as a canonical decimal bigint string`);\n\t}\n\treturn out;\n}\n\nexport function parseDecimalBigInt(value: unknown, label: string): bigint {\n\tif (typeof value !== \"string\" || !/^(0|-?[1-9]\\d*)$/.test(value)) {\n\t\tthrow new TypeError(`${label} must be a canonical decimal bigint string`);\n\t}\n\treturn BigInt(value);\n}\n\nexport function assertStrictJsonValue(value: unknown, label: string): StrictJsonValue {\n\ttry {\n\t\tstrictJsonCodec.encode(value);\n\t\treturn value as StrictJsonValue;\n\t} catch (error) {\n\t\tthrow new TypeError(`${label} must be strict JSON: ${errorMessage(error)}`);\n\t}\n}\n\nexport function assertScopeFrame(value: unknown): AgenticMemoryScope {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: scope must be an object when present\");\n\t}\n\tassertStrictJsonValue(value, \"record.scope\");\n\tconst validation = validateScope(value);\n\tif (!validation.ok || validation.scope === undefined) {\n\t\tthrow new TypeError(`agenticMemoryRecordFrame: invalid scope: ${validation.errors.join(\"; \")}`);\n\t}\n\tassertExactKeys(\n\t\tvalue as Record<string, unknown>,\n\t\t[\n\t\t\t...((value as Record<string, unknown>).sessionId === undefined ? [] : [\"sessionId\"]),\n\t\t\t...((value as Record<string, unknown>).projectId === undefined ? [] : [\"projectId\"]),\n\t\t\t...((value as Record<string, unknown>).userId === undefined ? [] : [\"userId\"]),\n\t\t\t...((value as Record<string, unknown>).tenantId === undefined ? [] : [\"tenantId\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.scope\",\n\t);\n\treturn validation.scope;\n}\n\nexport function assertKindValue(value: unknown): AgenticMemoryKind {\n\tif (!isAgenticMemoryKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid memory kind\");\n\t}\n\treturn value;\n}\n\nexport function assertPersistenceLevelValue(value: unknown): AgenticMemoryPersistenceLevel {\n\tif (!isAgenticMemoryPersistenceLevel(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid persistence level\");\n\t}\n\treturn value;\n}\n\nexport function assertArtifactKindValue(value: unknown): AgenticMemoryArtifactKind {\n\tif (!isAgenticMemoryArtifactKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid artifact kind\");\n\t}\n\treturn value;\n}\n\nexport function assertNonEmptyString(value: unknown, label: string): string {\n\tif (!isNonEmptyString(value)) throw new TypeError(`${label} must be a non-empty string`);\n\treturn value;\n}\n\nexport function assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new TypeError(`${label} must be a string`);\n\treturn value;\n}\n\nexport function assertConfidence(value: unknown, label: string): number {\n\tif (!Number.isFinite(value) || (value as number) < 0 || (value as number) > 1) {\n\t\tthrow new TypeError(`${label} must be a finite number in [0, 1]`);\n\t}\n\treturn value as number;\n}\n\nexport function assertStringArray(value: unknown, label: string): readonly string[] {\n\tif (!isDenseArrayOf(value, (item): item is string => typeof item === \"string\")) {\n\t\tthrow new TypeError(`${label} must be a readonly string array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nexport function assertFiniteNumberArray(value: unknown, label: string): readonly number[] {\n\tif (!isDenseArrayOf(value, (item): item is number => Number.isFinite(item))) {\n\t\tthrow new TypeError(`${label} must be a finite number array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nexport function isDenseArrayOf<T>(\n\tvalue: unknown,\n\tpredicate: (item: unknown) => item is T,\n): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nexport function freezeError<T extends { readonly validationErrors?: readonly string[] }>(\n\terror: T,\n): T {\n\treturn Object.freeze({\n\t\t...error,\n\t\t...(error.validationErrors === undefined\n\t\t\t? {}\n\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t}) as T;\n}\n\nexport function safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","import { type Codec, strictJsonCodec } from \"../json/codec.js\";\nimport type { MemoryFragment } from \"../patterns/semantic-memory.js\";\nimport {\n\tassertAgenticMemoryRecordCodecShape,\n\tassertArtifactKindValue,\n\tassertConfidence,\n\tassertExactKeys,\n\tassertFiniteNumberArray,\n\tassertKindValue,\n\tassertNonEmptyString,\n\tassertPersistenceLevelValue,\n\tassertScopeFrame,\n\tassertStrictJsonValue,\n\tassertString,\n\tassertStringArray,\n\tdecimalBigIntString,\n\tisPlainRecord,\n\tparseDecimalBigInt,\n\tvalidateAndSnapshotRecord,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryFragmentFrame,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRecordFrame,\n\tStrictJsonValue,\n} from \"./agentic-memory-types.js\";\n\nexport const AGENTIC_MEMORY_RECORD_FRAME_FORMAT = \"graphrefly.agenticMemoryRecord\";\nexport const AGENTIC_MEMORY_RECORD_FRAME_VERSION = 1;\n\nexport function agenticMemoryRecordFrame<TJson extends StrictJsonValue>(\n\trecord: AgenticMemoryRecord<TJson>,\n): AgenticMemoryRecordFrame<TJson> {\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: invalid record: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\tassertAgenticMemoryRecordCodecShape(record);\n\tassertStrictJsonValue(result.record.fragment.payload, \"record.fragment.payload\");\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\t\trecord: Object.freeze({\n\t\t\tid: result.record.id,\n\t\t\tkind: result.record.kind,\n\t\t\tpersistenceLevel: result.record.persistenceLevel,\n\t\t\tartifactKind: result.record.artifactKind,\n\t\t\t...(result.record.scope === undefined ? {} : { scope: result.record.scope }),\n\t\t\tfragment: fragmentFrame(result.record.fragment as MemoryFragment<TJson>),\n\t\t}),\n\t});\n}\n\n/** Assert and snapshot a decoded D166 record frame. Unknown fields fail honestly. */\nexport function assertAgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue>(\n\tvalue: unknown,\n): AgenticMemoryRecordFrame<TJson> {\n\tif (!isPlainRecord(value))\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: frame must be an object\");\n\tassertStrictJsonValue(value, \"agenticMemoryRecordFrame\");\n\tassertExactKeys(value, [\"format\", \"record\", \"version\"], \"agenticMemoryRecordFrame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_FRAME_FORMAT) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid version\");\n\t}\n\tconst rawRecord = value.record;\n\tif (!isPlainRecord(rawRecord)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawRecord,\n\t\trawRecord.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst rawFragment = rawRecord.fragment;\n\tif (!isPlainRecord(rawFragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawFragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(rawFragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(rawFragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(rawFragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(rawFragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(rawFragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tif (rawRecord.scope !== undefined) assertScopeFrame(rawRecord.scope);\n\tconst frame = value as unknown as AgenticMemoryRecordFrame<TJson>;\n\tconst decoded = recordFromFrame(frame);\n\tconst roundtrip = agenticMemoryRecordFrame(decoded);\n\treturn roundtrip as AgenticMemoryRecordFrame<TJson>;\n}\n\n/** Strict canonical JSON codec for D166 AgenticMemoryRecordFrame values. */\nexport function agenticMemoryRecordFrameCodec<\n\tTJson extends StrictJsonValue = StrictJsonValue,\n>(): Codec<AgenticMemoryRecordFrame<TJson>> {\n\treturn {\n\t\tencode(value: AgenticMemoryRecordFrame<TJson>): Uint8Array {\n\t\t\treturn strictJsonCodec.encode(assertAgenticMemoryRecordFrame<TJson>(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecordFrame<TJson> {\n\t\t\treturn assertAgenticMemoryRecordFrame<TJson>(strictJsonCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/** Strict canonical JSON codec that persists records and decodes bigint fields back to bigint. */\nexport function agenticMemoryRecordCodec<TJson extends StrictJsonValue = StrictJsonValue>(): Codec<\n\tAgenticMemoryRecord<TJson>\n> {\n\tconst frameCodec = agenticMemoryRecordFrameCodec<TJson>();\n\treturn {\n\t\tencode(value: AgenticMemoryRecord<TJson>): Uint8Array {\n\t\t\treturn frameCodec.encode(agenticMemoryRecordFrame(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecord<TJson> {\n\t\t\treturn recordFromFrame(frameCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/**\n * D167 solution-level retention command projection.\n *\n * Archive/restore/setPersistenceLevel are derived views over current records;\n * requestConsolidation emits request facts only.\n */\n\nfunction fragmentFrame<TJson extends StrictJsonValue>(\n\tfragment: MemoryFragment<TJson>,\n): AgenticMemoryFragmentFrame<TJson> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: decimalBigIntString(fragment.tNs, \"fragment.tNs\"),\n\t\t...(fragment.validFrom === undefined\n\t\t\t? {}\n\t\t\t: { validFrom: decimalBigIntString(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t...(fragment.validTo === undefined\n\t\t\t? {}\n\t\t\t: { validTo: decimalBigIntString(fragment.validTo, \"fragment.validTo\") }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordFromFrame<TJson extends StrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\tconst fragment = frame.record.fragment;\n\tconst record: AgenticMemoryRecord<TJson> = {\n\t\tid: assertNonEmptyString(frame.record.id, \"record.id\"),\n\t\tkind: assertKindValue(frame.record.kind),\n\t\tpersistenceLevel: assertPersistenceLevelValue(frame.record.persistenceLevel),\n\t\tartifactKind: assertArtifactKindValue(frame.record.artifactKind),\n\t\t...(frame.record.scope === undefined ? {} : { scope: assertScopeFrame(frame.record.scope) }),\n\t\tfragment: {\n\t\t\tid: assertNonEmptyString(fragment.id, \"fragment.id\"),\n\t\t\tpayload: assertStrictJsonValue(fragment.payload, \"fragment.payload\") as TJson,\n\t\t\ttNs: parseDecimalBigInt(fragment.tNs, \"fragment.tNs\"),\n\t\t\t...(fragment.validFrom === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validFrom: parseDecimalBigInt(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t\t...(fragment.validTo === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validTo: parseDecimalBigInt(fragment.validTo, \"fragment.validTo\") }),\n\t\t\tconfidence: assertConfidence(fragment.confidence, \"fragment.confidence\"),\n\t\t\ttags: assertStringArray(fragment.tags, \"fragment.tags\"),\n\t\t\tsources: assertStringArray(fragment.sources, \"fragment.sources\"),\n\t\t\t...(fragment.embedding === undefined\n\t\t\t\t? {}\n\t\t\t\t: { embedding: assertFiniteNumberArray(fragment.embedding, \"fragment.embedding\") }),\n\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparentFragmentId: assertNonEmptyString(fragment.parentFragmentId, \"parentFragmentId\"),\n\t\t\t\t\t}),\n\t\t\t...(fragment.provenance === undefined\n\t\t\t\t? {}\n\t\t\t\t: { provenance: assertString(fragment.provenance, \"provenance\") }),\n\t\t},\n\t};\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: decoded record is invalid: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn result.record;\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport { assertGraphLocalNode, type Graph, type StateNode } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport {\n\ttype AgenticMemoryRecord,\n\ttype AgenticMemoryRecordFrame,\n\ttype AgenticMemoryStrictJsonValue,\n\tagenticMemoryRecordCodec,\n\tagenticMemoryRecordFrame,\n\tagenticMemoryRecordFrameCodec,\n\tassertAgenticMemoryRecordFrame,\n} from \"../solutions/index.js\";\nimport type { AppendLogEntry, AppendLogStorageTier, KvStorageTier } from \"../storage/index.js\";\n\nexport const AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT =\n\t\"graphrefly.agenticMemory.records.snapshot\" as const;\nexport const AGENTIC_MEMORY_RECORD_CHANGE_FORMAT =\n\t\"graphrefly.agenticMemory.records.change\" as const;\nexport const AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION = 1 as const;\n\nexport interface AgenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION;\n\treadonly changeCursor: number;\n\treadonly records: readonly AgenticMemoryRecordFrame<TJson>[];\n}\n\nexport interface AgenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_CHANGE_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION;\n\treadonly change: {\n\t\treadonly kind: \"replaceAll\";\n\t\treadonly records: readonly AgenticMemoryRecordFrame<TJson>[];\n\t};\n}\n\nexport interface AgenticMemoryRecordsRestoreState<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n> {\n\treadonly records: readonly AgenticMemoryRecord<TJson>[];\n\treadonly source: \"empty\" | \"changes\" | \"snapshot\" | \"snapshot+changes\";\n\treadonly snapshot: { readonly found: boolean; readonly changeCursor: number };\n\treadonly changes: { readonly applied: number; readonly cursor: number };\n}\n\nexport interface LoadAgenticMemoryRecordsStateOptions {\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n}\n\nexport interface AgenticMemoryRecordsPersistenceCursor {\n\treadonly kind: \"persistence.cursor\";\n\treadonly changeSeq: number;\n\treadonly snapshotWrites: number;\n\treadonly changeWrites: number;\n}\n\nexport interface AgenticMemoryRecordsPersistenceStatus {\n\treadonly state: \"starting\" | \"ready\" | \"flushing\" | \"errored\" | \"disposed\";\n\treadonly pending: number;\n\treadonly writes: number;\n\treadonly errors: number;\n\treadonly cursor: AgenticMemoryRecordsPersistenceCursor;\n}\n\nexport interface AgenticMemoryRecordsPersistenceError {\n\treadonly phase: \"snapshot\" | \"change\";\n\treadonly message: string;\n\treadonly cursor: AgenticMemoryRecordsPersistenceCursor;\n}\n\nexport interface PersistAgenticMemoryRecordsOptions {\n\treadonly name?: string;\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n\treadonly initialChangeCursor?: number;\n\treadonly snapshotOnAttach?: boolean;\n\treadonly snapshotEveryChanges?: number;\n}\n\nexport interface AgenticMemoryRecordsPersistenceHandle {\n\treadonly ready: StateNode<boolean>;\n\treadonly status: StateNode<AgenticMemoryRecordsPersistenceStatus>;\n\treadonly error: StateNode<AgenticMemoryRecordsPersistenceError | null>;\n\treadonly cursor: StateNode<AgenticMemoryRecordsPersistenceCursor>;\n\tflush(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n\tsnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n\tdispose(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void;\n}\n\nexport interface OpenPersistentAgenticMemoryRecordsOptions<\n\tTJson extends AgenticMemoryStrictJsonValue,\n> extends LoadAgenticMemoryRecordsStateOptions,\n\t\tOmit<\n\t\t\tPersistAgenticMemoryRecordsOptions,\n\t\t\t\"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly AgenticMemoryRecord<TJson>[];\n}\n\nexport interface PersistentAgenticMemoryRecords<TJson extends AgenticMemoryStrictJsonValue> {\n\treadonly records: StateNode<readonly AgenticMemoryRecord<TJson>[]>;\n\treadonly persistence: AgenticMemoryRecordsPersistenceHandle;\n\treadonly loaded: AgenticMemoryRecordsRestoreState<TJson>;\n}\n\ninterface QueueItem {\n\treadonly phase: \"snapshot\" | \"change\" | \"flush\" | \"dispose\";\n\treadonly done?: (status: AgenticMemoryRecordsPersistenceStatus) => void;\n\trun(): void | PromiseLike<void>;\n}\n\nexport function agenticMemoryRecordsSnapshotKey(storagePrefix = \"agentic-memory\"): string {\n\tif (storagePrefix.length === 0) throw new TypeError(\"storagePrefix must be non-empty\");\n\treturn `${storagePrefix}/records.snapshot`;\n}\n\nexport function agenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\trecords: readonly AgenticMemoryRecord<TJson>[],\n\topts: { readonly changeCursor?: number } = {},\n): AgenticMemoryRecordSnapshotFrame<TJson> {\n\tconst changeCursor = validateChangeCursor(opts.changeCursor ?? -1);\n\treturn assertAgenticMemoryRecordSnapshotFrame({\n\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchangeCursor,\n\t\trecords: records.map((record) => agenticMemoryRecordFrame(record)),\n\t});\n}\n\nexport function agenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(records: readonly AgenticMemoryRecord<TJson>[]): AgenticMemoryRecordChangeFrame<TJson> {\n\treturn assertAgenticMemoryRecordChangeFrame({\n\t\tformat: AGENTIC_MEMORY_RECORD_CHANGE_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchange: {\n\t\t\tkind: \"replaceAll\",\n\t\t\trecords: records.map((record) => agenticMemoryRecordFrame(record)),\n\t\t},\n\t});\n}\n\nexport function assertAgenticMemoryRecordSnapshotFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(value: unknown): AgenticMemoryRecordSnapshotFrame<TJson> {\n\tif (!isPlainRecord(value)) throw new TypeError(\"agentic memory snapshot frame must be an object\");\n\tassertKeys(\n\t\tvalue,\n\t\t[\"changeCursor\", \"format\", \"records\", \"version\"],\n\t\t\"agentic memory snapshot frame\",\n\t);\n\tif (value.format !== AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: invalid version\");\n\t}\n\tconst changeCursor = validateChangeCursor(value.changeCursor);\n\tif (!Array.isArray(value.records)) {\n\t\tthrow new TypeError(\"agentic memory snapshot frame: records must be an array\");\n\t}\n\tconst records = assertDenseRecordFrames<TJson>(\n\t\tvalue.records,\n\t\t\"agentic memory snapshot frame records\",\n\t);\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchangeCursor,\n\t\trecords: Object.freeze(records),\n\t});\n}\n\nexport function assertAgenticMemoryRecordChangeFrame<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(value: unknown): AgenticMemoryRecordChangeFrame<TJson> {\n\tif (!isPlainRecord(value)) throw new TypeError(\"agentic memory change frame must be an object\");\n\tassertKeys(value, [\"change\", \"format\", \"version\"], \"agentic memory change frame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_CHANGE_FORMAT) {\n\t\tthrow new TypeError(\"agentic memory change frame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agentic memory change frame: invalid version\");\n\t}\n\tif (!isPlainRecord(value.change)) {\n\t\tthrow new TypeError(\"agentic memory change frame: change must be an object\");\n\t}\n\tassertKeys(value.change, [\"kind\", \"records\"], \"agentic memory change frame change\");\n\tif (value.change.kind !== \"replaceAll\") {\n\t\tthrow new TypeError(\"agentic memory change frame: change.kind must be replaceAll\");\n\t}\n\tif (!Array.isArray(value.change.records)) {\n\t\tthrow new TypeError(\"agentic memory change frame: change.records must be an array\");\n\t}\n\tconst records = assertDenseRecordFrames<TJson>(\n\t\tvalue.change.records,\n\t\t\"agentic memory change frame records\",\n\t);\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_CHANGE_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\tchange: Object.freeze({\n\t\t\tkind: \"replaceAll\",\n\t\t\trecords: Object.freeze(records),\n\t\t}),\n\t});\n}\n\nexport function loadAgenticMemoryRecordsState<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(opts: LoadAgenticMemoryRecordsStateOptions): Promise<AgenticMemoryRecordsRestoreState<TJson>> {\n\tconst storagePrefix = opts.storagePrefix ?? \"agentic-memory\";\n\tconst snapshotKey = opts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(storagePrefix);\n\treturn opts.snapshotStore.get(snapshotKey).then((rawSnapshot) => {\n\t\tlet records: readonly AgenticMemoryRecord<TJson>[] = [];\n\t\tlet source: AgenticMemoryRecordsRestoreState<TJson>[\"source\"] = \"empty\";\n\t\tlet changeCursor = -1;\n\t\tif (rawSnapshot !== undefined) {\n\t\t\tconst snapshot = assertAgenticMemoryRecordSnapshotFrame<TJson>(rawSnapshot);\n\t\t\trecords = snapshot.records.map(recordFromFrame);\n\t\t\tchangeCursor = snapshot.changeCursor;\n\t\t\tsource = \"snapshot\";\n\t\t}\n\t\tif (opts.changeLog === undefined) {\n\t\t\treturn {\n\t\t\t\trecords,\n\t\t\t\tsource,\n\t\t\t\tsnapshot: { found: rawSnapshot !== undefined, changeCursor },\n\t\t\t\tchanges: { applied: 0, cursor: changeCursor },\n\t\t\t};\n\t\t}\n\t\treturn opts.changeLog.read({ after: changeCursor }).then((entries) => {\n\t\t\tlet applied = 0;\n\t\t\tlet cursor = changeCursor;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.seq !== cursor + 1) {\n\t\t\t\t\tthrow new Error(\"agentic memory records change log is non-contiguous\");\n\t\t\t\t}\n\t\t\t\tconst change = assertAgenticMemoryRecordChangeFrame<TJson>(entry.value);\n\t\t\t\trecords = change.change.records.map(recordFromFrame);\n\t\t\t\tcursor = entry.seq;\n\t\t\t\tapplied += 1;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trecords,\n\t\t\t\tsource:\n\t\t\t\t\trawSnapshot !== undefined && applied > 0\n\t\t\t\t\t\t? \"snapshot+changes\"\n\t\t\t\t\t\t: rawSnapshot !== undefined\n\t\t\t\t\t\t\t? \"snapshot\"\n\t\t\t\t\t\t\t: applied > 0\n\t\t\t\t\t\t\t\t? \"changes\"\n\t\t\t\t\t\t\t\t: \"empty\",\n\t\t\t\tsnapshot: { found: rawSnapshot !== undefined, changeCursor },\n\t\t\t\tchanges: { applied, cursor },\n\t\t\t};\n\t\t});\n\t});\n}\n\nexport function persistAgenticMemoryRecords<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<TJson>[]>,\n\topts: PersistAgenticMemoryRecordsOptions,\n): AgenticMemoryRecordsPersistenceHandle {\n\tconst name = opts.name ?? \"agenticMemoryRecords.persistence\";\n\tconst snapshotKey =\n\t\topts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(opts.storagePrefix ?? name);\n\tconst snapshotEveryChanges = validateSnapshotEveryChanges(opts.snapshotEveryChanges);\n\tassertGraphLocalNode(graph, records as Node<unknown>, `${name}.records`);\n\tlet cursorValue: AgenticMemoryRecordsPersistenceCursor = {\n\t\tkind: \"persistence.cursor\",\n\t\tchangeSeq: validateChangeCursor(opts.initialChangeCursor ?? -1),\n\t\tsnapshotWrites: 0,\n\t\tchangeWrites: 0,\n\t};\n\tlet statusValue = statusOf(\"starting\", 0, 0, 0, cursorValue);\n\tlet errorCount = 0;\n\tlet writes = 0;\n\tlet running = false;\n\tlet disposed = false;\n\tlet disposeRequested = false;\n\tlet subscribing = true;\n\tlet observedChangesSinceSnapshot = 0;\n\tlet latestRecords: readonly AgenticMemoryRecord<TJson>[] = records.cache ?? [];\n\tlet stop: (() => void) | undefined;\n\tconst queue: QueueItem[] = [];\n\tconst ready = graph.state(false, { name: `${name}/ready` });\n\tconst status = graph.state<AgenticMemoryRecordsPersistenceStatus>(statusValue, {\n\t\tname: `${name}/status`,\n\t});\n\tconst error = graph.state<AgenticMemoryRecordsPersistenceError | null>(null, {\n\t\tname: `${name}/error`,\n\t});\n\tconst cursor = graph.state<AgenticMemoryRecordsPersistenceCursor>(cursorValue, {\n\t\tname: `${name}/cursor`,\n\t});\n\n\tfunction publish(state: AgenticMemoryRecordsPersistenceStatus[\"state\"]): void {\n\t\tconst nextState = statusValue.state === \"errored\" && state !== \"disposed\" ? \"errored\" : state;\n\t\tstatusValue = statusOf(\n\t\t\tnextState,\n\t\t\tqueue.length + (running ? 1 : 0),\n\t\t\twrites,\n\t\t\terrorCount,\n\t\t\tcursorValue,\n\t\t);\n\t\tcursor.set(cursorValue);\n\t\tstatus.set(statusValue);\n\t\tif (nextState === \"ready\") ready.set(true);\n\t\tif (nextState === \"errored\" || nextState === \"disposed\") ready.set(false);\n\t}\n\n\tfunction report(phase: \"snapshot\" | \"change\", caught: unknown): void {\n\t\terrorCount += 1;\n\t\terror.set({ phase, message: errorMessage(caught), cursor: cursorValue });\n\t}\n\n\tfunction callDone(done: QueueItem[\"done\"]): void {\n\t\ttry {\n\t\t\tdone?.(statusValue);\n\t\t} catch {\n\t\t\t// Done callbacks are advisory controls and must not wedge the adapter queue.\n\t\t}\n\t}\n\n\tfunction finish(item: QueueItem): void {\n\t\tif (item.phase === \"dispose\") {\n\t\t\tdisposed = true;\n\t\t\trunning = false;\n\t\t\tpublish(\"disposed\");\n\t\t} else if (statusValue.state !== \"errored\") {\n\t\t\trunning = false;\n\t\t\tpublish(\"ready\");\n\t\t} else {\n\t\t\trunning = false;\n\t\t\tpublish(\"errored\");\n\t\t}\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction fail(item: QueueItem, caught: unknown): void {\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") report(item.phase, caught);\n\t\trunning = false;\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") publish(\"errored\");\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction chainThenable(item: QueueItem, value: unknown): boolean {\n\t\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return false;\n\t\tconst then = (value as { then?: unknown }).then;\n\t\tif (typeof then !== \"function\") return false;\n\t\tlet settled = false;\n\t\tconst settle = (next: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tnext();\n\t\t};\n\t\ttry {\n\t\t\t(then as (onFulfilled: () => void, onRejected: (error: unknown) => void) => unknown).call(\n\t\t\t\tvalue,\n\t\t\t\t() => settle(() => finish(item)),\n\t\t\t\t(caught) => settle(() => fail(item, caught)),\n\t\t\t);\n\t\t} catch (caught) {\n\t\t\tsettle(() => fail(item, caught));\n\t\t}\n\t\treturn true;\n\t}\n\n\tfunction enqueue(item: QueueItem): void {\n\t\tif (disposed || (disposeRequested && item.phase !== \"dispose\" && item.phase !== \"flush\")) {\n\t\t\tcallDone(item.done);\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(item);\n\t\tdrain();\n\t}\n\n\tfunction drain(): void {\n\t\tif (running) return;\n\t\tconst item = queue.shift();\n\t\tif (item === undefined) return;\n\t\trunning = true;\n\t\tpublish(\n\t\t\titem.phase === \"flush\" ? \"flushing\" : statusValue.state === \"starting\" ? \"starting\" : \"ready\",\n\t\t);\n\t\tlet result: void | PromiseLike<void>;\n\t\ttry {\n\t\t\tresult = item.run();\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn;\n\t\t}\n\t\tif (chainThenable(item, result)) return;\n\t\tfinish(item);\n\t}\n\n\tfunction enqueueSnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\tconst snapshotRecords = latestRecords;\n\t\tobservedChangesSinceSnapshot = 0;\n\t\tenqueue({\n\t\t\tphase: \"snapshot\",\n\t\t\tdone,\n\t\t\trun() {\n\t\t\t\tconst records = Object.freeze(\n\t\t\t\t\tsnapshotRecords.map((record) => agenticMemoryRecordFrame(record)),\n\t\t\t\t);\n\t\t\t\tconst frame = assertAgenticMemoryRecordSnapshotFrame<TJson>({\n\t\t\t\t\tformat: AGENTIC_MEMORY_RECORD_SNAPSHOT_FORMAT,\n\t\t\t\t\tversion: AGENTIC_MEMORY_RECORD_STORAGE_FRAME_VERSION,\n\t\t\t\t\tchangeCursor: cursorValue.changeSeq,\n\t\t\t\t\trecords,\n\t\t\t\t});\n\t\t\t\treturn opts.snapshotStore.set(snapshotKey, frame).then(() => {\n\t\t\t\t\tcursorValue = { ...cursorValue, snapshotWrites: cursorValue.snapshotWrites + 1 };\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction enqueueChange(nextRecords: readonly AgenticMemoryRecord<TJson>[]): void {\n\t\tconst changeLog = opts.changeLog;\n\t\tif (changeLog === undefined) return;\n\t\tenqueue({\n\t\t\tphase: \"change\",\n\t\t\trun() {\n\t\t\t\tconst frame = agenticMemoryRecordChangeFrame(nextRecords);\n\t\t\t\treturn changeLog.append(frame).then((written) => {\n\t\t\t\t\tconst entry = written as AppendLogEntry<AgenticMemoryRecordChangeFrame<TJson>>;\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tchangeSeq: entry.seq,\n\t\t\t\t\t\tchangeWrites: cursorValue.changeWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction cancelQueuedForDispose(): void {\n\t\tconst pending = queue.splice(0);\n\t\tfor (const item of pending) callDone(item.done);\n\t}\n\n\tstop = records.subscribe((msg: Message, delivery?: DeliveryMeta) => {\n\t\tif (disposeRequested) return;\n\t\tconst nextRecords = dataOf<readonly AgenticMemoryRecord<TJson>[]>(msg);\n\t\tif (nextRecords === undefined) return;\n\t\tlatestRecords = nextRecords;\n\t\tif (subscribing && delivery === undefined) return;\n\t\tobservedChangesSinceSnapshot += 1;\n\t\tenqueueChange(nextRecords);\n\t\tif (\n\t\t\tsnapshotEveryChanges !== undefined &&\n\t\t\tobservedChangesSinceSnapshot >= snapshotEveryChanges\n\t\t) {\n\t\t\tenqueueSnapshot();\n\t\t}\n\t});\n\tsubscribing = false;\n\tif (opts.snapshotOnAttach !== false) enqueueSnapshot();\n\telse publish(\"ready\");\n\n\treturn {\n\t\tready,\n\t\tstatus,\n\t\terror,\n\t\tcursor,\n\t\tflush(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueue({ phase: \"flush\", done, run: () => undefined });\n\t\t},\n\t\tsnapshot(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed || disposeRequested) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueueSnapshot(done);\n\t\t},\n\t\tdispose(done?: (status: AgenticMemoryRecordsPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdisposeRequested = true;\n\t\t\tstop?.();\n\t\t\tcancelQueuedForDispose();\n\t\t\tenqueue({ phase: \"dispose\", done, run: () => undefined });\n\t\t},\n\t};\n}\n\nexport function openPersistentAgenticMemoryRecords<\n\tTJson extends AgenticMemoryStrictJsonValue = AgenticMemoryStrictJsonValue,\n>(\n\topts: OpenPersistentAgenticMemoryRecordsOptions<TJson>,\n): Promise<PersistentAgenticMemoryRecords<TJson>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"agentic-memory\";\n\tconst snapshotKey = opts.snapshotKey ?? agenticMemoryRecordsSnapshotKey(storagePrefix);\n\treturn loadAgenticMemoryRecordsState<TJson>({ ...opts, snapshotKey, storagePrefix }).then(\n\t\t(loaded) => {\n\t\t\tconst records =\n\t\t\t\tloaded.source === \"empty\" && opts.initial !== undefined ? opts.initial : loaded.records;\n\t\t\tconst node = opts.graph.state<readonly AgenticMemoryRecord<TJson>[]>(records, {\n\t\t\t\tname: opts.name,\n\t\t\t});\n\t\t\tconst persistence = persistAgenticMemoryRecords(opts.graph, node, {\n\t\t\t\t...opts,\n\t\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\t\tsnapshotKey,\n\t\t\t\tstoragePrefix,\n\t\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t\t});\n\t\t\treturn { records: node, persistence, loaded };\n\t\t},\n\t);\n}\n\nfunction recordFromFrame<TJson extends AgenticMemoryStrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\treturn agenticMemoryRecordCodec<TJson>().decode(\n\t\tagenticMemoryRecordFrameCodec<TJson>().encode(frame),\n\t);\n}\n\nfunction statusOf(\n\tstate: AgenticMemoryRecordsPersistenceStatus[\"state\"],\n\tpending: number,\n\twrites: number,\n\terrors: number,\n\tcursor: AgenticMemoryRecordsPersistenceCursor,\n): AgenticMemoryRecordsPersistenceStatus {\n\treturn { state, pending, writes, errors, cursor };\n}\n\nfunction dataOf<C>(msg: Message): C | undefined {\n\treturn msg[0] === \"DATA\" ? (msg[1] as C) : undefined;\n}\n\nfunction validateChangeCursor(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < -1) {\n\t\tthrow new RangeError(\"changeCursor must be a safe integer >= -1\");\n\t}\n\treturn value;\n}\n\nfunction validateSnapshotEveryChanges(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new RangeError(\"snapshotEveryChanges must be a positive safe integer\");\n\t}\n\treturn value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = Object.keys(value).sort();\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected frame fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertDenseRecordFrames<TJson extends AgenticMemoryStrictJsonValue>(\n\tvalue: readonly unknown[],\n\tlabel: string,\n): readonly AgenticMemoryRecordFrame<TJson>[] {\n\tconst records: AgenticMemoryRecordFrame<TJson>[] = [];\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i)) {\n\t\t\tthrow new TypeError(`${label}: sparse array hole at ${i}`);\n\t\t}\n\t\trecords.push(assertAgenticMemoryRecordFrame<TJson>(value[i]));\n\t}\n\treturn Object.freeze(records);\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Passive resilience policy helpers for graph-visible adapters (D130/D132).\n *\n * These helpers never schedule work and never own graph state. Drivers/adapters\n * consume them, while graph-visible bundles expose attempts/status/errors.\n */\n\nexport type BackoffPolicy =\n\t| { readonly kind: \"none\" }\n\t| { readonly kind: \"constant\"; readonly delayMs: number }\n\t| {\n\t\t\treadonly kind: \"linear\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly stepMs: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| {\n\t\t\treadonly kind: \"exponential\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly factor: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| { readonly kind: \"fibonacci\"; readonly unitMs: number; readonly maxMs?: number };\n\nexport interface RetryPolicy {\n\t/** Total attempts including the first try. */\n\treadonly maxAttempts: number;\n\treadonly backoff: BackoffPolicy;\n}\n\nexport type RetryState = \"idle\" | \"running\" | \"waiting\" | \"succeeded\" | \"failed\" | \"exhausted\";\n\nexport interface RetryStatus {\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly delayMs?: number;\n\treadonly state: RetryState;\n}\n\nexport const noBackoff: BackoffPolicy = Object.freeze({ kind: \"none\" });\n\nexport function retryPolicy(maxAttempts = 1, backoff: BackoffPolicy = noBackoff): RetryPolicy {\n\tif (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n\t\tthrow new RangeError(\"retryPolicy: maxAttempts must be a positive integer\");\n\t}\n\treturn Object.freeze({ maxAttempts, backoff });\n}\n\nexport function shouldRetry(policy: RetryPolicy, failedAttempt: number): boolean {\n\treturn failedAttempt < policy.maxAttempts;\n}\n\nexport function nextRetryDelayMs(policy: RetryPolicy, nextAttempt: number): number | undefined {\n\tif (!Number.isInteger(nextAttempt) || nextAttempt <= 0 || nextAttempt > policy.maxAttempts) {\n\t\treturn undefined;\n\t}\n\treturn backoffDelayMs(policy.backoff, nextAttempt);\n}\n\nexport function backoffDelayMs(policy: BackoffPolicy, attempt: number): number {\n\tconst safeAttempt = Math.max(1, Math.trunc(attempt));\n\tswitch (policy.kind) {\n\t\tcase \"none\":\n\t\t\treturn 0;\n\t\tcase \"constant\":\n\t\t\treturn nonNegative(policy.delayMs);\n\t\tcase \"linear\":\n\t\t\treturn cap(\n\t\t\t\tnonNegative(policy.initialMs) + nonNegative(policy.stepMs) * (safeAttempt - 1),\n\t\t\t\tpolicy.maxMs,\n\t\t\t);\n\t\tcase \"exponential\": {\n\t\t\tconst factor = Math.max(1, Math.trunc(policy.factor));\n\t\t\treturn cap(nonNegative(policy.initialMs) * factor ** (safeAttempt - 1), policy.maxMs);\n\t\t}\n\t\tcase \"fibonacci\":\n\t\t\treturn cap(nonNegative(policy.unitMs) * fibonacci(safeAttempt), policy.maxMs);\n\t}\n}\n\nfunction cap(value: number, max: number | undefined): number {\n\tif (max === undefined) return value;\n\treturn Math.min(value, nonNegative(max));\n}\n\nfunction nonNegative(value: number): number {\n\tif (!Number.isFinite(value)) return 0;\n\treturn Math.max(0, value);\n}\n\nfunction fibonacci(n: number): number {\n\tif (n <= 1) return 1;\n\tlet prev = 1;\n\tlet curr = 1;\n\tfor (let i = 2; i <= n; i += 1) {\n\t\tconst next = prev + curr;\n\t\tprev = curr;\n\t\tcurr = next;\n\t}\n\treturn curr;\n}\n","// D497 canonical protobuf profile for the D134/D496 wire bridge envelope subset.\n\nexport type CanonicalProtobufErrorCategory =\n\t| \"unknown_field\"\n\t| \"duplicate_singular\"\n\t| \"noncanonical_bytes\"\n\t| \"invalid_oneof\"\n\t| \"missing_required\"\n\t| \"invalid_wire_edge\"\n\t| \"default_emission\"\n\t| \"malformed\";\n\nexport class CanonicalProtobufError extends Error {\n\treadonly category: CanonicalProtobufErrorCategory;\n\n\tconstructor(category: CanonicalProtobufErrorCategory, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CanonicalProtobufError\";\n\t\tthis.category = category;\n\t}\n}\n\nexport interface CanonicalWireBridgeMetadata {\n\treadonly seq: bigint;\n\treadonly cursor: bigint;\n\treadonly idempotencyKey: string;\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly timestampMs?: bigint;\n\treadonly ackForSeq?: bigint;\n\treadonly requestId?: string;\n}\n\nexport type CanonicalWireBridgeDataBody =\n\t| { readonly kind: \"value\"; readonly value: Uint8Array }\n\t| { readonly kind: \"wire_edge\"; readonly frame: CanonicalWireEdgeFrame };\n\nexport interface CanonicalWireEdgeFrame {\n\treadonly kind: \"dirty\" | \"data\";\n\treadonly edgeId: string;\n\treadonly causeId: string;\n\treadonly value?: Uint8Array;\n}\n\nexport type CanonicalWireBridgePayload =\n\t| { readonly kind: \"start\" }\n\t| { readonly kind: \"data\"; readonly body: CanonicalWireBridgeDataBody }\n\t| { readonly kind: \"ack\" }\n\t| { readonly kind: \"nack\"; readonly error?: Uint8Array }\n\t| { readonly kind: \"status\"; readonly status: Uint8Array }\n\t| { readonly kind: \"error\"; readonly error: Uint8Array }\n\t| { readonly kind: \"close\"; readonly reason?: Uint8Array };\n\nexport interface CanonicalWireBridgeEnvelope {\n\treadonly sessionId: string;\n\treadonly metadata: CanonicalWireBridgeMetadata;\n\treadonly payload: CanonicalWireBridgePayload;\n}\n\ninterface Field {\n\treadonly no: number;\n\treadonly wireType: number;\n\treadonly value: bigint | Uint8Array;\n}\n\nconst maxUint64 = (1n << 64n) - 1n;\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\nconst textEncoder = new TextEncoder();\n\nexport function decodeCanonicalWireBridgeEnvelope(bytes: Uint8Array): CanonicalWireBridgeEnvelope {\n\tconst input = Uint8Array.from(bytes);\n\tconst envelope = parseWireBridgeEnvelope(input);\n\tvalidateWireBridgeEnvelope(envelope);\n\tconst canonical = encodeCanonicalWireBridgeEnvelope(envelope);\n\tif (!bytesEqual(input, canonical)) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"noncanonical_bytes\",\n\t\t\t\"WireBridgeEnvelope bytes are not canonical deterministic protobuf\",\n\t\t);\n\t}\n\treturn envelope;\n}\n\nexport function decodeCanonicalWireEdgeFrame(bytes: Uint8Array): CanonicalWireEdgeFrame {\n\tconst input = Uint8Array.from(bytes);\n\tconst frame = parseWireEdgeFrame(input);\n\tvalidateWireEdgeFrame(frame);\n\tconst canonical = encodeWireEdgeFrame(frame);\n\tif (!bytesEqual(input, canonical)) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"noncanonical_bytes\",\n\t\t\t\"WireEdgeFrame bytes are not canonical deterministic protobuf\",\n\t\t);\n\t}\n\treturn frame;\n}\n\nexport function encodeCanonicalWireEdgeFrame(frame: CanonicalWireEdgeFrame): Uint8Array {\n\tvalidateWireEdgeFrame(frame);\n\treturn encodeWireEdgeFrame(frame);\n}\n\nexport function encodeCanonicalWireBridgeEnvelope(\n\tenvelope: CanonicalWireBridgeEnvelope,\n): Uint8Array {\n\tvalidateWireBridgeEnvelope(envelope);\n\tconst out = new ByteWriter();\n\tout.stringField(1, envelope.sessionId);\n\tout.messageField(2, encodeMetadata(envelope.metadata));\n\tswitch (envelope.payload.kind) {\n\t\tcase \"start\":\n\t\t\tout.messageField(3, new Uint8Array());\n\t\t\tbreak;\n\t\tcase \"data\":\n\t\t\tout.messageField(4, encodeDataPayload(envelope.payload.body));\n\t\t\tbreak;\n\t\tcase \"ack\":\n\t\t\tout.messageField(5, new Uint8Array());\n\t\t\tbreak;\n\t\tcase \"nack\":\n\t\t\tout.messageField(6, encodeOptionalBytesMessage(1, envelope.payload.error));\n\t\t\tbreak;\n\t\tcase \"status\":\n\t\t\tout.messageField(7, encodeRequiredBytesMessage(1, envelope.payload.status));\n\t\t\tbreak;\n\t\tcase \"error\":\n\t\t\tout.messageField(8, encodeRequiredBytesMessage(1, envelope.payload.error));\n\t\t\tbreak;\n\t\tcase \"close\":\n\t\t\tout.messageField(9, encodeOptionalBytesMessage(1, envelope.payload.reason));\n\t\t\tbreak;\n\t}\n\treturn out.finish();\n}\n\nfunction parseWireBridgeEnvelope(bytes: Uint8Array): CanonicalWireBridgeEnvelope {\n\tconst fields = readFields(\n\t\tbytes,\n\t\tnew Map([\n\t\t\t[1, 2],\n\t\t\t[2, 2],\n\t\t\t[3, 2],\n\t\t\t[4, 2],\n\t\t\t[5, 2],\n\t\t\t[6, 2],\n\t\t\t[7, 2],\n\t\t\t[8, 2],\n\t\t\t[9, 2],\n\t\t]),\n\t\t\"WireBridgeEnvelope\",\n\t);\n\tconst session = bytesField(fields, 1);\n\tconst metadataBytes = bytesField(fields, 2);\n\tconst payloadFields = fields.filter((field) => field.no >= 3 && field.no <= 9);\n\tif (session === undefined || metadataBytes === undefined || payloadFields.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireBridgeEnvelope missing required fields\",\n\t\t);\n\t}\n\tif (payloadFields.length !== 1) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"invalid_oneof\",\n\t\t\t\"WireBridgeEnvelope payload oneof has multiple cases\",\n\t\t);\n\t}\n\tconst payloadField = payloadFields[0];\n\tif (!(payloadField.value instanceof Uint8Array)) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"WireBridgeEnvelope payload is malformed\");\n\t}\n\treturn {\n\t\tsessionId: utf8String(session, \"session_id\"),\n\t\tmetadata: parseMetadata(metadataBytes),\n\t\tpayload: parseEnvelopePayload(payloadField.no, payloadField.value),\n\t};\n}\n\nfunction parseEnvelopePayload(fieldNo: number, bytes: Uint8Array): CanonicalWireBridgePayload {\n\tswitch (fieldNo) {\n\t\tcase 3:\n\t\t\trequireEmptyMessage(bytes, \"start\");\n\t\t\treturn { kind: \"start\" };\n\t\tcase 4:\n\t\t\treturn { kind: \"data\", body: parseDataPayload(bytes) };\n\t\tcase 5:\n\t\t\trequireEmptyMessage(bytes, \"ack\");\n\t\t\treturn { kind: \"ack\" };\n\t\tcase 6:\n\t\t\treturn { kind: \"nack\", error: parseOptionalBytesPayload(bytes, \"nack\") };\n\t\tcase 7:\n\t\t\treturn { kind: \"status\", status: parseRequiredBytesPayload(bytes, \"status\") };\n\t\tcase 8:\n\t\t\treturn { kind: \"error\", error: parseRequiredBytesPayload(bytes, \"error\") };\n\t\tcase 9:\n\t\t\treturn { kind: \"close\", reason: parseOptionalBytesPayload(bytes, \"close\") };\n\t\tdefault:\n\t\t\tthrow new CanonicalProtobufError(\"unknown_field\", \"unknown envelope payload field\");\n\t}\n}\n\nfunction parseMetadata(bytes: Uint8Array): CanonicalWireBridgeMetadata {\n\tconst fields = readFields(\n\t\tbytes,\n\t\tnew Map([\n\t\t\t[1, 0],\n\t\t\t[2, 0],\n\t\t\t[3, 2],\n\t\t\t[4, 0],\n\t\t\t[5, 0],\n\t\t\t[6, 0],\n\t\t\t[7, 0],\n\t\t\t[8, 2],\n\t\t]),\n\t\t\"WireBridgeMetadata\",\n\t);\n\tconst seq = uintField(fields, 1);\n\tconst cursor = uintField(fields, 2);\n\tconst key = bytesField(fields, 3);\n\tconst attempt = uintField(fields, 4);\n\tconst maxAttempts = uintField(fields, 5);\n\tif (\n\t\tseq === undefined ||\n\t\tcursor === undefined ||\n\t\tkey === undefined ||\n\t\tattempt === undefined ||\n\t\tmaxAttempts === undefined\n\t) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireBridgeMetadata missing required fields\",\n\t\t);\n\t}\n\tconst timestampMs = uintField(fields, 6);\n\tconst ackForSeq = uintField(fields, 7);\n\tconst requestId = bytesField(fields, 8);\n\tif (timestampMs === 0n || ackForSeq === 0n || requestId?.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"default_emission\",\n\t\t\t\"optional metadata default value was emitted\",\n\t\t);\n\t}\n\treturn {\n\t\tseq,\n\t\tcursor,\n\t\tidempotencyKey: utf8String(key, \"idempotency_key\"),\n\t\tattempt: uint32(attempt, \"attempt\"),\n\t\tmaxAttempts: uint32(maxAttempts, \"max_attempts\"),\n\t\ttimestampMs,\n\t\tackForSeq,\n\t\trequestId: requestId === undefined ? undefined : utf8String(requestId, \"request_id\"),\n\t};\n}\n\nfunction parseDataPayload(bytes: Uint8Array): CanonicalWireBridgeDataBody {\n\tconst fields = readFields(\n\t\tbytes,\n\t\tnew Map([\n\t\t\t[1, 2],\n\t\t\t[2, 2],\n\t\t]),\n\t\t\"WireBridgeDataPayload\",\n\t);\n\tconst value = bytesField(fields, 1);\n\tconst wireEdge = bytesField(fields, 2);\n\tif (value !== undefined && wireEdge !== undefined) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"invalid_oneof\",\n\t\t\t\"WireBridgeDataPayload body has multiple cases\",\n\t\t);\n\t}\n\tif (value !== undefined) return { kind: \"value\", value };\n\tif (wireEdge !== undefined) return { kind: \"wire_edge\", frame: parseWireEdgeFrame(wireEdge) };\n\tthrow new CanonicalProtobufError(\"missing_required\", \"WireBridgeDataPayload missing body\");\n}\n\nfunction parseWireEdgeFrame(bytes: Uint8Array): CanonicalWireEdgeFrame {\n\tconst fields = readFields(\n\t\tbytes,\n\t\tnew Map([\n\t\t\t[1, 0],\n\t\t\t[2, 2],\n\t\t\t[3, 2],\n\t\t\t[4, 2],\n\t\t]),\n\t\t\"WireEdgeFrame\",\n\t);\n\tconst kind = uintField(fields, 1);\n\tconst edge = bytesField(fields, 2);\n\tconst cause = bytesField(fields, 3);\n\tconst value = bytesField(fields, 4);\n\tif (kind === undefined || edge === undefined || cause === undefined) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", \"WireEdgeFrame missing required fields\");\n\t}\n\tif (edge.length === 0 || cause.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireEdgeFrame edge_id/cause_id must be non-empty\",\n\t\t);\n\t}\n\tif (kind === 1n) {\n\t\tif (value !== undefined) {\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"invalid_wire_edge\",\n\t\t\t\t\"DIRTY WireEdgeFrame must not carry value\",\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"dirty\",\n\t\t\tedgeId: utf8String(edge, \"edge_id\"),\n\t\t\tcauseId: utf8String(cause, \"cause_id\"),\n\t\t};\n\t}\n\tif (kind === 2n) {\n\t\tif (value === undefined) {\n\t\t\tthrow new CanonicalProtobufError(\"invalid_wire_edge\", \"DATA WireEdgeFrame requires value\");\n\t\t}\n\t\treturn {\n\t\t\tkind: \"data\",\n\t\t\tedgeId: utf8String(edge, \"edge_id\"),\n\t\t\tcauseId: utf8String(cause, \"cause_id\"),\n\t\t\tvalue,\n\t\t};\n\t}\n\tthrow new CanonicalProtobufError(\"invalid_wire_edge\", \"WireEdgeFrame kind is invalid\");\n}\n\nfunction validateWireBridgeEnvelope(envelope: CanonicalWireBridgeEnvelope): void {\n\tif (!isRecord(envelope)) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"WireBridgeEnvelope DTO must be an object\");\n\t}\n\tif (typeof envelope.sessionId !== \"string\" || envelope.sessionId.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireBridgeEnvelope session_id must be non-empty\",\n\t\t);\n\t}\n\tconst metadata = envelope.metadata;\n\tif (!isRecord(metadata)) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"WireBridgeMetadata DTO must be an object\");\n\t}\n\tassertUint64(metadata.seq, \"seq\");\n\tassertUint64(metadata.cursor, \"cursor\");\n\tassertUint32Number(metadata.attempt, \"attempt\");\n\tassertUint32Number(metadata.maxAttempts, \"max_attempts\");\n\tif (metadata.timestampMs !== undefined) assertUint64(metadata.timestampMs, \"timestamp_ms\");\n\tif (metadata.ackForSeq !== undefined) assertUint64(metadata.ackForSeq, \"ack_for_seq\");\n\tif (metadata.seq === 0n || metadata.attempt === 0 || metadata.maxAttempts < metadata.attempt) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireBridgeMetadata positive fields are invalid\",\n\t\t);\n\t}\n\tif (typeof metadata.idempotencyKey !== \"string\" || metadata.idempotencyKey.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireBridgeMetadata idempotency_key is required\",\n\t\t);\n\t}\n\tif (metadata.requestId !== undefined && typeof metadata.requestId !== \"string\") {\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"WireBridgeMetadata request_id must be a string\");\n\t}\n\tif (!isRecord(envelope.payload)) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", \"WireBridgeEnvelope payload is required\");\n\t}\n\tvalidatePayloadDto(envelope.payload);\n\tif (\n\t\t(envelope.payload.kind === \"ack\" || envelope.payload.kind === \"nack\") &&\n\t\tmetadata.ackForSeq === undefined\n\t) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", \"ACK/NACK requires metadata.ack_for_seq\");\n\t}\n\tif (metadata.timestampMs === 0n || metadata.ackForSeq === 0n || metadata.requestId === \"\") {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"default_emission\",\n\t\t\t\"optional metadata default value was emitted\",\n\t\t);\n\t}\n}\n\nfunction validatePayloadDto(payload: CanonicalWireBridgePayload): void {\n\tswitch (payload.kind) {\n\t\tcase \"start\":\n\t\tcase \"ack\":\n\t\t\treturn;\n\t\tcase \"data\":\n\t\t\tif (!isRecord(payload.body)) {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"WireBridgeDataPayload body is required\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (payload.body.kind === \"value\") {\n\t\t\t\tassertUint8Array(payload.body.value, \"WireBridgeDataPayload value\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (payload.body.kind === \"wire_edge\") {\n\t\t\t\tvalidateWireEdgeFrame(payload.body.frame);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"invalid_oneof\",\n\t\t\t\t\"WireBridgeDataPayload body kind is invalid\",\n\t\t\t);\n\t\tcase \"nack\":\n\t\t\tif (payload.error !== undefined)\n\t\t\t\tassertNonEmptyOptionalBytes(payload.error, \"WireBridgeNackPayload error\");\n\t\t\treturn;\n\t\tcase \"status\":\n\t\t\tassertNonEmptyRequiredBytes(payload.status, \"WireBridgeStatusPayload status\");\n\t\t\treturn;\n\t\tcase \"error\":\n\t\t\tassertNonEmptyRequiredBytes(payload.error, \"WireBridgeErrorPayload error\");\n\t\t\treturn;\n\t\tcase \"close\":\n\t\t\tif (payload.reason !== undefined)\n\t\t\t\tassertNonEmptyOptionalBytes(payload.reason, \"WireBridgeClosePayload reason\");\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"invalid_oneof\",\n\t\t\t\t\"WireBridgeEnvelope payload kind is invalid\",\n\t\t\t);\n\t}\n}\n\nfunction validateWireEdgeFrame(frame: CanonicalWireEdgeFrame): void {\n\tif (!isRecord(frame)) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"WireEdgeFrame DTO must be an object\");\n\t}\n\tif (typeof frame.edgeId !== \"string\" || typeof frame.causeId !== \"string\") {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireEdgeFrame edge_id/cause_id are required\",\n\t\t);\n\t}\n\tif (frame.edgeId.length === 0 || frame.causeId.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"missing_required\",\n\t\t\t\"WireEdgeFrame edge_id/cause_id must be non-empty\",\n\t\t);\n\t}\n\tswitch (frame.kind) {\n\t\tcase \"dirty\":\n\t\t\tif (frame.value !== undefined) {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"invalid_wire_edge\",\n\t\t\t\t\t\"DIRTY WireEdgeFrame must not carry value\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\tcase \"data\":\n\t\t\tif (frame.value === undefined) {\n\t\t\t\tthrow new CanonicalProtobufError(\"invalid_wire_edge\", \"DATA WireEdgeFrame requires value\");\n\t\t\t}\n\t\t\tassertUint8Array(frame.value, \"WireEdgeFrame value\");\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new CanonicalProtobufError(\"invalid_wire_edge\", \"WireEdgeFrame kind is invalid\");\n\t}\n}\n\nfunction encodeMetadata(metadata: CanonicalWireBridgeMetadata): Uint8Array {\n\tconst out = new ByteWriter();\n\tout.varintField(1, metadata.seq);\n\tout.varintField(2, metadata.cursor);\n\tout.stringField(3, metadata.idempotencyKey);\n\tout.varintField(4, BigInt(metadata.attempt));\n\tout.varintField(5, BigInt(metadata.maxAttempts));\n\tif (metadata.timestampMs !== undefined) out.varintField(6, metadata.timestampMs);\n\tif (metadata.ackForSeq !== undefined) out.varintField(7, metadata.ackForSeq);\n\tif (metadata.requestId !== undefined) out.stringField(8, metadata.requestId);\n\treturn out.finish();\n}\n\nfunction encodeDataPayload(body: CanonicalWireBridgeDataBody): Uint8Array {\n\tconst out = new ByteWriter();\n\tif (body.kind === \"value\") {\n\t\tout.bytesField(1, body.value);\n\t} else {\n\t\tout.messageField(2, encodeWireEdgeFrame(body.frame));\n\t}\n\treturn out.finish();\n}\n\nfunction encodeWireEdgeFrame(frame: CanonicalWireEdgeFrame): Uint8Array {\n\tconst out = new ByteWriter();\n\tout.varintField(1, frame.kind === \"dirty\" ? 1n : 2n);\n\tout.stringField(2, frame.edgeId);\n\tout.stringField(3, frame.causeId);\n\tif (frame.value !== undefined) out.bytesField(4, frame.value);\n\treturn out.finish();\n}\n\nfunction encodeRequiredBytesMessage(fieldNo: number, value: Uint8Array): Uint8Array {\n\tconst out = new ByteWriter();\n\tout.bytesField(fieldNo, value);\n\treturn out.finish();\n}\n\nfunction encodeOptionalBytesMessage(fieldNo: number, value: Uint8Array | undefined): Uint8Array {\n\tconst out = new ByteWriter();\n\tif (value !== undefined) {\n\t\tassertNonEmptyOptionalBytes(value, \"optional bytes payload\");\n\t\tout.bytesField(fieldNo, value);\n\t}\n\treturn out.finish();\n}\n\nfunction parseRequiredBytesPayload(bytes: Uint8Array, name: string): Uint8Array {\n\tconst fields = readFields(bytes, new Map([[1, 2]]), `WireBridge${name}Payload`);\n\tconst value = bytesField(fields, 1);\n\tif (value === undefined) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", `${name} payload missing required bytes`);\n\t}\n\tif (value.length === 0) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", `${name} payload bytes must be non-empty`);\n\t}\n\treturn value;\n}\n\nfunction parseOptionalBytesPayload(bytes: Uint8Array, name: string): Uint8Array | undefined {\n\tconst fields = readFields(bytes, new Map([[1, 2]]), `WireBridge${name}Payload`);\n\tconst value = bytesField(fields, 1);\n\tif (value?.length === 0) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"default_emission\",\n\t\t\t`${name} optional bytes default value was emitted`,\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction requireEmptyMessage(bytes: Uint8Array, name: string): void {\n\tif (bytes.length !== 0) {\n\t\tthrow new CanonicalProtobufError(\"unknown_field\", `${name} payload must be empty`);\n\t}\n}\n\nfunction readFields(bytes: Uint8Array, allowed: Map<number, number>, messageName: string): Field[] {\n\tconst reader = new ByteReader(bytes);\n\tconst fields: Field[] = [];\n\tconst seen = new Set<number>();\n\twhile (!reader.done()) {\n\t\tconst key = reader.varint();\n\t\tconst fieldNo = Number(key >> 3n);\n\t\tconst wireType = Number(key & 7n);\n\t\tconst expectedWireType = allowed.get(fieldNo);\n\t\tif (fieldNo <= 0 || expectedWireType === undefined) {\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"unknown_field\",\n\t\t\t\t`${messageName} contains unknown field ${fieldNo}`,\n\t\t\t);\n\t\t}\n\t\tif (wireType !== expectedWireType) {\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"malformed\",\n\t\t\t\t`${messageName} field ${fieldNo} has wrong wire type`,\n\t\t\t);\n\t\t}\n\t\tif (seen.has(fieldNo)) {\n\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\"duplicate_singular\",\n\t\t\t\t`${messageName} field ${fieldNo} is duplicated`,\n\t\t\t);\n\t\t}\n\t\tseen.add(fieldNo);\n\t\tif (wireType === 0) {\n\t\t\tfields.push({ no: fieldNo, wireType, value: reader.varint() });\n\t\t} else if (wireType === 2) {\n\t\t\tfields.push({ no: fieldNo, wireType, value: reader.readBytes() });\n\t\t} else {\n\t\t\tthrow new CanonicalProtobufError(\"malformed\", `${messageName} unsupported wire type`);\n\t\t}\n\t}\n\treturn fields;\n}\n\nfunction uintField(fields: readonly Field[], no: number): bigint | undefined {\n\tconst field = fields.find((candidate) => candidate.no === no);\n\treturn typeof field?.value === \"bigint\" ? field.value : undefined;\n}\n\nfunction bytesField(fields: readonly Field[], no: number): Uint8Array | undefined {\n\tconst field = fields.find((candidate) => candidate.no === no);\n\treturn field?.value instanceof Uint8Array ? field.value : undefined;\n}\n\nfunction utf8String(bytes: Uint8Array, field: string): string {\n\tlet text: string;\n\ttry {\n\t\ttext = textDecoder.decode(bytes);\n\t} catch (error) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"malformed\",\n\t\t\t`${field} is not valid utf-8: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\tif (text.length === 0) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", `${field} must be non-empty`);\n\t}\n\treturn text;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction assertUint64(value: unknown, field: string): asserts value is bigint {\n\tif (typeof value !== \"bigint\" || value < 0n || value > maxUint64) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", `${field} must be a uint64 bigint`);\n\t}\n}\n\nfunction assertUint32Number(value: unknown, field: string): asserts value is number {\n\tif (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 0xffff_ffff) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", `${field} must be a uint32 number`);\n\t}\n}\n\nfunction assertUint8Array(value: unknown, field: string): asserts value is Uint8Array {\n\tif (!(value instanceof Uint8Array)) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", `${field} must be Uint8Array bytes`);\n\t}\n}\n\nfunction assertNonEmptyOptionalBytes(value: unknown, field: string): asserts value is Uint8Array {\n\tassertUint8Array(value, field);\n\tif (value.length === 0) {\n\t\tthrow new CanonicalProtobufError(\"default_emission\", `${field} default value must be omitted`);\n\t}\n}\n\nfunction assertNonEmptyRequiredBytes(value: unknown, field: string): asserts value is Uint8Array {\n\tassertUint8Array(value, field);\n\tif (value.length === 0) {\n\t\tthrow new CanonicalProtobufError(\"missing_required\", `${field} must be non-empty`);\n\t}\n}\n\nfunction uint32(value: bigint, field: string): number {\n\tif (value > 0xffff_ffffn) {\n\t\tthrow new CanonicalProtobufError(\"malformed\", `${field} exceeds uint32`);\n\t}\n\treturn Number(value);\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) return false;\n\tfor (let i = 0; i < left.length; i++) {\n\t\tif (left[i] !== right[i]) return false;\n\t}\n\treturn true;\n}\n\nclass ByteReader {\n\tprivate offset = 0;\n\n\tconstructor(private readonly buf: Uint8Array) {}\n\n\tdone(): boolean {\n\t\treturn this.offset === this.buf.length;\n\t}\n\n\tvarint(): bigint {\n\t\tlet shift = 0n;\n\t\tlet result = 0n;\n\t\tfor (let i = 0; i < 10; i++) {\n\t\t\tif (this.offset >= this.buf.length) {\n\t\t\t\tthrow new CanonicalProtobufError(\"malformed\", \"truncated varint\");\n\t\t\t}\n\t\t\tconst byte = this.buf[this.offset++];\n\t\t\tif (i === 9 && (byte & 0xfe) !== 0) {\n\t\t\t\tthrow new CanonicalProtobufError(\"malformed\", \"varint exceeds 64 bits\");\n\t\t\t}\n\t\t\tresult |= BigInt(byte & 0x7f) << shift;\n\t\t\tif ((byte & 0x80) === 0) return result;\n\t\t\tshift += 7n;\n\t\t}\n\t\tthrow new CanonicalProtobufError(\"malformed\", \"varint exceeds 64 bits\");\n\t}\n\n\treadBytes(): Uint8Array {\n\t\tconst len = this.varint();\n\t\tif (len > BigInt(this.buf.length - this.offset)) {\n\t\t\tthrow new CanonicalProtobufError(\"malformed\", \"length-delimited field is truncated\");\n\t\t}\n\t\tconst start = this.offset;\n\t\tthis.offset += Number(len);\n\t\treturn this.buf.slice(start, this.offset);\n\t}\n}\n\nclass ByteWriter {\n\tprivate readonly chunks: number[] = [];\n\n\tvarintField(fieldNo: number, value: bigint): void {\n\t\tthis.tag(fieldNo, 0);\n\t\tthis.varint(value);\n\t}\n\n\tbytesField(fieldNo: number, value: Uint8Array): void {\n\t\tthis.tag(fieldNo, 2);\n\t\tthis.varint(BigInt(value.length));\n\t\tthis.bytes(value);\n\t}\n\n\tstringField(fieldNo: number, value: string): void {\n\t\tthis.bytesField(fieldNo, textEncoder.encode(value));\n\t}\n\n\tmessageField(fieldNo: number, value: Uint8Array): void {\n\t\tthis.bytesField(fieldNo, value);\n\t}\n\n\tfinish(): Uint8Array {\n\t\treturn new Uint8Array(this.chunks);\n\t}\n\n\tprivate tag(fieldNo: number, wireType: number): void {\n\t\tthis.varint(BigInt((fieldNo << 3) | wireType));\n\t}\n\n\tprivate varint(value: bigint): void {\n\t\tif (value < 0n || value > maxUint64) {\n\t\t\tthrow new CanonicalProtobufError(\"malformed\", \"varint value must fit uint64\");\n\t\t}\n\t\tlet next = value;\n\t\tdo {\n\t\t\tlet byte = Number(next & 0x7fn);\n\t\t\tnext >>= 7n;\n\t\t\tif (next !== 0n) byte |= 0x80;\n\t\t\tthis.chunks.push(byte);\n\t\t} while (next !== 0n);\n\t}\n\n\tprivate bytes(value: Uint8Array): void {\n\t\tfor (const byte of value) this.chunks.push(byte);\n\t}\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { assertStrictJsonValue } from \"../json/codec.js\";\nimport type { CanonicalWireBridgeDataBody, CanonicalWireEdgeFrame } from \"./bridge-protobuf.js\";\nimport type {\n\tRemoteCallRequest,\n\tRemoteCallResponse,\n\tWireBridgeEnvelope,\n\tWireBridgeEnvelopeType,\n\tWireBridgeMetadata,\n} from \"./bridge-types.js\";\n\nexport const envelopeTypes = new Set<WireBridgeEnvelopeType>([\n\t\"start\",\n\t\"data\",\n\t\"ack\",\n\t\"nack\",\n\t\"status\",\n\t\"error\",\n\t\"close\",\n]);\n\nexport function validateRemoteCallRequest<T>(value: unknown): RemoteCallRequest<T> | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (typeof value.operation !== \"string\" || value.operation.length === 0) return undefined;\n\tif (typeof value.requestId !== \"string\" || value.requestId.length === 0) return undefined;\n\tif (!(\"payload\" in value)) return undefined;\n\treturn {\n\t\toperation: value.operation,\n\t\trequestId: value.requestId,\n\t\tpayload: value.payload as T,\n\t};\n}\n\nexport function validateRemoteCallResponse<T>(value: unknown): RemoteCallResponse<T> | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (typeof value.operation !== \"string\" || value.operation.length === 0) return undefined;\n\tif (typeof value.requestId !== \"string\" || value.requestId.length === 0) return undefined;\n\tif (value.kind === \"result\" && \"payload\" in value) {\n\t\treturn {\n\t\t\tkind: \"result\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\tpayload: value.payload as T,\n\t\t};\n\t}\n\tif (value.kind === \"error\" && typeof value.error === \"string\" && value.error.length > 0) {\n\t\treturn {\n\t\t\tkind: \"error\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\terror: value.error,\n\t\t};\n\t}\n\tif (value.kind === \"status\" && typeof value.status === \"string\" && value.status.length > 0) {\n\t\treturn {\n\t\t\tkind: \"status\",\n\t\t\toperation: value.operation,\n\t\t\trequestId: value.requestId,\n\t\t\tstatus: value.status,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nexport function remoteMalformedResponseRequestId(value: unknown): string | undefined {\n\tif (!isRecord(value)) return undefined;\n\treturn typeof value.requestId === \"string\" && value.requestId.length > 0\n\t\t? value.requestId\n\t\t: undefined;\n}\n\nexport function remoteMalformedResponseOperation(value: unknown): string | undefined {\n\tif (!isRecord(value)) return undefined;\n\treturn typeof value.operation === \"string\" && value.operation.length > 0\n\t\t? value.operation\n\t\t: undefined;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nexport function isThenable(value: unknown): boolean {\n\treturn isRecord(value) && typeof value.then === \"function\";\n}\n\nexport function validateInboundEnvelope(envelope: unknown): string | undefined {\n\tif (typeof envelope !== \"object\" || envelope === null) {\n\t\treturn \"wireBridge: inbound envelope must be an object\";\n\t}\n\tconst candidate = envelope as Partial<WireBridgeEnvelope<unknown>>;\n\tif (typeof candidate.sessionId !== \"string\" || candidate.sessionId.length === 0) {\n\t\treturn \"wireBridge: inbound envelope sessionId must be a non-empty string\";\n\t}\n\tif (\n\t\ttypeof candidate.type !== \"string\" ||\n\t\t!envelopeTypes.has(candidate.type as WireBridgeEnvelopeType)\n\t) {\n\t\treturn \"wireBridge: inbound envelope type is not recognized\";\n\t}\n\tconst metadata = candidate.metadata as Partial<WireBridgeMetadata> | undefined;\n\tif (typeof metadata !== \"object\" || metadata === null) {\n\t\treturn \"wireBridge: inbound envelope metadata must be an object\";\n\t}\n\tif (!isSafePositiveInteger(metadata.seq)) {\n\t\treturn \"wireBridge: inbound envelope seq must be a positive integer\";\n\t}\n\tif (!isSafeNonNegativeInteger(metadata.cursor)) {\n\t\treturn \"wireBridge: inbound envelope cursor must be a non-negative integer\";\n\t}\n\tif (\n\t\ttypeof metadata.idempotencyKey !== \"string\" ||\n\t\t(metadata.idempotencyKey as string).length === 0\n\t) {\n\t\treturn \"wireBridge: inbound envelope idempotencyKey must be a non-empty string\";\n\t}\n\tif (!isSafePositiveInteger(metadata.attempt)) {\n\t\treturn \"wireBridge: inbound envelope attempt must be a positive integer\";\n\t}\n\tif (\n\t\t!isSafePositiveInteger(metadata.maxAttempts) ||\n\t\t(metadata.maxAttempts as number) < (metadata.attempt as number)\n\t) {\n\t\treturn \"wireBridge: inbound envelope maxAttempts must be >= attempt\";\n\t}\n\tif (metadata.ackForSeq !== undefined && !isSafePositiveInteger(metadata.ackForSeq)) {\n\t\treturn \"wireBridge: inbound envelope ackForSeq must be a positive integer\";\n\t}\n\tif ((candidate.type === \"ack\" || candidate.type === \"nack\") && metadata.ackForSeq === undefined) {\n\t\treturn `wireBridge: inbound ${candidate.type} envelope requires ackForSeq`;\n\t}\n\tconst payloadError = validatePayloadForType(\n\t\tcandidate.type as WireBridgeEnvelopeType,\n\t\tcandidate.payload,\n\t\t\"wireBridge: inbound envelope\",\n\t);\n\tif (payloadError !== undefined) return payloadError;\n\treturn undefined;\n}\n\nexport function validateCommand(value: unknown): string | undefined {\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn \"wireBridge: command fact must be an object\";\n\t}\n\tconst kind = (value as { readonly kind?: unknown }).kind;\n\tif (\n\t\tkind !== \"start\" &&\n\t\tkind !== \"send\" &&\n\t\tkind !== \"ack\" &&\n\t\tkind !== \"nack\" &&\n\t\tkind !== \"ack-timeout\" &&\n\t\tkind !== \"close\"\n\t) {\n\t\treturn \"wireBridge: command kind is not recognized\";\n\t}\n\tif (\n\t\t(kind === \"ack\" || kind === \"nack\") &&\n\t\t!isSafePositiveInteger((value as { readonly ackForSeq?: unknown }).ackForSeq)\n\t) {\n\t\treturn `wireBridge: ${kind} command ackForSeq must be a positive integer`;\n\t}\n\tif (kind === \"ack-timeout\") {\n\t\tconst timeout = value as {\n\t\t\treadonly seq?: unknown;\n\t\t\treadonly attempt?: unknown;\n\t\t\treadonly observedAtMs?: unknown;\n\t\t};\n\t\tif (!isSafePositiveInteger(timeout.seq)) {\n\t\t\treturn \"wireBridge: ack-timeout command seq must be a positive integer\";\n\t\t}\n\t\tif (!isSafePositiveInteger(timeout.attempt)) {\n\t\t\treturn \"wireBridge: ack-timeout command attempt must be a positive integer\";\n\t\t}\n\t\tconst observedAtMs = timeout.observedAtMs;\n\t\tif (\n\t\t\tobservedAtMs !== undefined &&\n\t\t\t(typeof observedAtMs !== \"number\" || !Number.isFinite(observedAtMs) || observedAtMs < 0)\n\t\t) {\n\t\t\treturn \"wireBridge: ack-timeout command observedAtMs must be a non-negative finite number\";\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function shouldTrackAck(type: WireBridgeEnvelopeType): boolean {\n\treturn type === \"start\" || type === \"data\" || type === \"close\";\n}\n\nexport function isSafePositiveInteger(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) > 0;\n}\n\nexport function isSafeNonNegativeInteger(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) >= 0;\n}\n\nexport function validatePayloadForType(\n\ttype: WireBridgeEnvelopeType,\n\tpayload: unknown,\n\tprefix: string,\n): string | undefined {\n\tconst record =\n\t\ttypeof payload === \"object\" && payload !== null\n\t\t\t? (payload as Record<string, unknown>)\n\t\t\t: undefined;\n\tconst kind = record === undefined ? undefined : ownData(record, \"kind\");\n\tswitch (type) {\n\t\tcase \"data\":\n\t\t\tif (kind !== \"data\" || record === undefined || !hasOwnData(record, \"value\")) {\n\t\t\t\treturn `${prefix}: data envelope requires data payload`;\n\t\t\t}\n\t\t\treturn wireAdmissiblePayloadError(ownData(record, \"value\"), `${prefix}: data payload`);\n\t\tcase \"nack\":\n\t\tcase \"error\":\n\t\t\tif (kind !== \"error\" || record === undefined || !hasOwnData(record, \"error\")) {\n\t\t\t\treturn `${prefix}: ${type} envelope requires error payload`;\n\t\t\t}\n\t\t\treturn wireAdmissiblePayloadError(ownData(record, \"error\"), `${prefix}: ${type} payload`);\n\t\tcase \"status\":\n\t\t\tif (kind !== \"status\" || record === undefined || !hasOwnData(record, \"status\")) {\n\t\t\t\treturn `${prefix}: status envelope requires status payload`;\n\t\t\t}\n\t\t\treturn wireAdmissiblePayloadError(ownData(record, \"status\"), `${prefix}: status payload`);\n\t\tcase \"close\":\n\t\t\tif (kind !== \"close\") return `${prefix}: close envelope requires close payload`;\n\t\t\tif (record === undefined || !(\"reason\" in record)) return undefined;\n\t\t\tif (!hasOwnData(record, \"reason\")) {\n\t\t\t\treturn `${prefix}: close reason must be a data property`;\n\t\t\t}\n\t\t\treturn wireAdmissiblePayloadError(ownData(record, \"reason\"), `${prefix}: close reason`);\n\t\tcase \"start\":\n\t\tcase \"ack\":\n\t\t\treturn payload === undefined\n\t\t\t\t? undefined\n\t\t\t\t: `${prefix}: ${type} envelope must not carry a payload`;\n\t}\n}\n\nexport function normalizeWireAdmissiblePayload(value: unknown, label: string): unknown {\n\tif (value instanceof Uint8Array) return Uint8Array.from(value);\n\tif (isCanonicalWireBridgeDataBody(value)) return cloneCanonicalWireBridgeDataBody(value);\n\tif (isCanonicalWireEdgeFrame(value)) return cloneCanonicalWireEdgeFrame(value);\n\tif (isCanonicalWireBridgeDataBodyLike(value) || isCanonicalWireEdgeFrameLike(value)) {\n\t\tthrow new TypeError(`${label}: invalid canonical wire DTO`);\n\t}\n\ttry {\n\t\treturn assertStrictJsonValue(value, label);\n\t} catch (error) {\n\t\tthrow new TypeError(\n\t\t\t`${label}: wire-admissible payload must be copied bytes, canonical WireEdgeFrame material, or strict JSON-like material`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nexport function wireAdmissiblePayloadError(value: unknown, label: string): string | undefined {\n\ttry {\n\t\tnormalizeWireAdmissiblePayload(value, label);\n\t\treturn undefined;\n\t} catch (error) {\n\t\treturn errorMessage(error);\n\t}\n}\n\nexport function normalizeWireBridgePayload<T>(\n\tpayload:\n\t\t| { readonly kind: \"data\"; readonly value: T }\n\t\t| { readonly kind: \"error\"; readonly error: unknown }\n\t\t| { readonly kind: \"status\"; readonly status: unknown }\n\t\t| { readonly kind: \"close\"; readonly reason?: unknown }\n\t\t| undefined,\n\tprefix: string,\n): typeof payload {\n\tif (payload === undefined) return undefined;\n\tif (payload.kind === \"data\") {\n\t\treturn {\n\t\t\t...payload,\n\t\t\tvalue: normalizeWireAdmissiblePayload(payload.value, `${prefix}: data payload`) as T,\n\t\t};\n\t}\n\tif (payload.kind === \"error\") {\n\t\treturn {\n\t\t\t...payload,\n\t\t\terror: normalizeWireAdmissiblePayload(payload.error, `${prefix}: error payload`),\n\t\t};\n\t}\n\tif (payload.kind === \"status\") {\n\t\treturn {\n\t\t\t...payload,\n\t\t\tstatus: normalizeWireAdmissiblePayload(payload.status, `${prefix}: status payload`),\n\t\t};\n\t}\n\tif (\"reason\" in payload) {\n\t\tif (payload.reason === undefined) return { kind: \"close\" };\n\t\treturn {\n\t\t\t...payload,\n\t\t\treason: normalizeWireAdmissiblePayload(payload.reason, `${prefix}: close reason`),\n\t\t};\n\t}\n\treturn payload;\n}\n\nfunction isCanonicalWireBridgeDataBody(value: unknown): value is CanonicalWireBridgeDataBody {\n\tif (!isPlainDataRecord(value)) return false;\n\tconst kind = ownData(value, \"kind\");\n\tif (kind === \"value\") {\n\t\treturn hasOnlyKeys(value, [\"kind\", \"value\"]) && ownData(value, \"value\") instanceof Uint8Array;\n\t}\n\tif (kind === \"wire_edge\") {\n\t\treturn (\n\t\t\thasOnlyKeys(value, [\"frame\", \"kind\"]) && isCanonicalWireEdgeFrame(ownData(value, \"frame\"))\n\t\t);\n\t}\n\treturn false;\n}\n\nfunction isCanonicalWireBridgeDataBodyLike(value: unknown): boolean {\n\tif (!isPlainDataRecord(value)) return false;\n\tconst kind = ownData(value, \"kind\");\n\tif (kind === \"wire_edge\") return \"frame\" in value;\n\tif (kind !== \"value\") return false;\n\treturn \"value\" in value && ownData(value, \"value\") instanceof Uint8Array;\n}\n\nfunction isCanonicalWireEdgeFrame(value: unknown): value is CanonicalWireEdgeFrame {\n\tif (!isPlainDataRecord(value)) return false;\n\tconst kind = ownData(value, \"kind\");\n\tconst edgeId = ownData(value, \"edgeId\");\n\tconst causeId = ownData(value, \"causeId\");\n\tif (typeof edgeId !== \"string\" || edgeId.length === 0) return false;\n\tif (typeof causeId !== \"string\" || causeId.length === 0) return false;\n\tif (kind === \"dirty\") return hasOnlyKeys(value, [\"causeId\", \"edgeId\", \"kind\"]);\n\tif (kind === \"data\") {\n\t\treturn (\n\t\t\thasOnlyKeys(value, [\"causeId\", \"edgeId\", \"kind\", \"value\"]) &&\n\t\t\townData(value, \"value\") instanceof Uint8Array\n\t\t);\n\t}\n\treturn false;\n}\n\nfunction isCanonicalWireEdgeFrameLike(value: unknown): boolean {\n\tif (!isPlainDataRecord(value)) return false;\n\tconst kind = ownData(value, \"kind\");\n\tif (kind !== \"dirty\" && kind !== \"data\") return false;\n\treturn \"edgeId\" in value || \"causeId\" in value || \"value\" in value;\n}\n\nfunction isPlainDataRecord(value: unknown): value is Record<string, unknown> {\n\tif (!isRecord(value)) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\tif (proto !== Object.prototype && proto !== null) return false;\n\tif (Object.getOwnPropertySymbols(value).length > 0) return false;\n\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor) || !descriptor.enumerable) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction ownData(value: Record<string, unknown>, key: string): unknown {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\treturn descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nfunction hasOwnData(value: Record<string, unknown>, key: string): boolean {\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\treturn descriptor !== undefined && \"value\" in descriptor;\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n\tconst allowed = new Set(keys);\n\tconst actual = Object.getOwnPropertyNames(value);\n\treturn actual.length === keys.length && actual.every((key) => allowed.has(key));\n}\n\nfunction cloneCanonicalWireBridgeDataBody(\n\tvalue: CanonicalWireBridgeDataBody,\n): CanonicalWireBridgeDataBody {\n\tif (value.kind === \"value\") return { kind: \"value\", value: Uint8Array.from(value.value) };\n\treturn { kind: \"wire_edge\", frame: cloneCanonicalWireEdgeFrame(value.frame) };\n}\n\nfunction cloneCanonicalWireEdgeFrame(value: CanonicalWireEdgeFrame): CanonicalWireEdgeFrame {\n\treturn {\n\t\tkind: value.kind,\n\t\tedgeId: value.edgeId,\n\t\tcauseId: value.causeId,\n\t\t...(value.value === undefined ? {} : { value: Uint8Array.from(value.value) }),\n\t};\n}\n\nexport function bridgePayloadError(payload: unknown, fallback: unknown): unknown {\n\tif (\n\t\ttypeof payload === \"object\" &&\n\t\tpayload !== null &&\n\t\t(payload as { readonly kind?: unknown }).kind === \"error\"\n\t) {\n\t\treturn (payload as { readonly error?: unknown }).error;\n\t}\n\treturn fallback;\n}\n\nexport function rethrowGraphRuntimeInvariant(error: unknown): void {\n\tconst message = errorMessage(error);\n\tif (\n\t\tmessage.includes(\"R-reentrancy\") ||\n\t\tmessage.includes(\"R-rewire\") ||\n\t\tmessage.includes(\"R-graph-domain\") ||\n\t\tmessage.includes(\"D37\") ||\n\t\tmessage.includes(\"D22\") ||\n\t\tmessage.includes(\"different graph\") ||\n\t\tmessage.includes(\"cross-graph\") ||\n\t\tmessage.includes(\"wire bridge\") ||\n\t\tmessage.includes(\"mid-fn topology mutation\") ||\n\t\tmessage.includes(\"reentrant dep mutation\") ||\n\t\tmessage.includes(\"feedback cycle\")\n\t) {\n\t\tthrow error;\n\t}\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type {\n\tRemoteCallBundle,\n\tRemoteCallError,\n\tRemoteCallOptions,\n\tRemoteCallRequest,\n\tRemoteCallResponse,\n\tRemoteCallResult,\n\tRemoteCallStatus,\n\tRemoteCallTimeout,\n\tWireBridgeBundle,\n\tWireBridgeEnvelope,\n\tWireBridgeEvent,\n} from \"./bridge-types.js\";\nimport {\n\tremoteMalformedResponseOperation,\n\tremoteMalformedResponseRequestId,\n\tvalidateRemoteCallRequest,\n\tvalidateRemoteCallResponse,\n} from \"./bridge-validation.js\";\n\n/** D147 remote dispatcher call helper over explicit wireBridge request/response facts. */\nexport function remoteCall<TRequest = unknown, TResponse = unknown>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>,\n\topts: RemoteCallOptions = {},\n): RemoteCallBundle<TRequest, TResponse> {\n\tconst name = opts.name ?? \"remoteCall\";\n\tconst timeouts = graph.node<RemoteCallTimeout>([], null, {\n\t\tname: `${name}/timeouts`,\n\t\tfactory: \"remoteCallTimeouts\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst responses = remoteCallResponsesNode(graph, bridge.events, timeouts, name);\n\tconst results = remoteCallResultsNode(graph, responses, name);\n\tconst status = remoteCallStatusNode(graph, bridge.events, timeouts, name);\n\tconst errors = remoteCallErrorsNode(graph, timeouts, bridge.events, name);\n\treturn {\n\t\tresponses,\n\t\tresults,\n\t\tstatus,\n\t\terrors,\n\t\ttimeouts,\n\t\tcall(operation, requestId, payload, callOpts) {\n\t\t\tconst request = remoteCallRequest(operation, requestId, payload);\n\t\t\tbridge.command.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tpayload: request,\n\t\t\t\t\t\tidempotencyKey: callOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn request;\n\t\t},\n\t\ttimeout(requestId, operation, error) {\n\t\t\tconst timeout = remoteCallTimeout(requestId, operation, error);\n\t\t\ttimeouts.down([[\"DATA\", timeout]]);\n\t\t\treturn timeout;\n\t\t},\n\t};\n}\n\nfunction remoteCallRequest<TRequest>(\n\toperation: string,\n\trequestId: string,\n\tpayload: TRequest,\n): RemoteCallRequest<TRequest> {\n\tif (operation.length === 0) throw new RangeError(\"remoteCall: operation must be non-empty\");\n\tif (requestId.length === 0) throw new RangeError(\"remoteCall: requestId must be non-empty\");\n\treturn { operation, requestId, payload };\n}\n\nfunction remoteCallTimeout(\n\trequestId: string,\n\toperation: string | undefined,\n\terror: string,\n): RemoteCallTimeout {\n\tif (requestId.length === 0)\n\t\tthrow new RangeError(\"remoteCall: timeout requestId must be non-empty\");\n\tif (error.length === 0) throw new RangeError(\"remoteCall: timeout error must be non-empty\");\n\treturn { ...(operation === undefined ? {} : { operation }), requestId, error };\n}\n\ninterface RemotePendingRequest {\n\toperation: string;\n\trequestId: string;\n\tseq: number;\n}\n\ninterface RemotePendingState {\n\trequestIds: Set<string>;\n\tbySeq: Map<number, RemotePendingRequest>;\n}\n\nfunction remotePendingState(): RemotePendingState {\n\treturn { requestIds: new Set(), bySeq: new Map() };\n}\n\nfunction remotePendingContains(state: RemotePendingState, requestId: string): boolean {\n\treturn state.requestIds.has(requestId);\n}\n\nfunction remotePendingDuplicate(state: RemotePendingState, request: RemotePendingRequest): boolean {\n\tconst current = remotePendingTakeBySeqPreview(state, request.seq);\n\treturn current?.requestId !== request.requestId && state.requestIds.has(request.requestId);\n}\n\nfunction remotePendingTakeBySeqPreview(\n\tstate: RemotePendingState,\n\tseq: number,\n): RemotePendingRequest | undefined {\n\treturn state.bySeq.get(seq);\n}\n\nfunction remotePendingPeekByRequestId(\n\tstate: RemotePendingState,\n\trequestId: string,\n): RemotePendingRequest | undefined {\n\tfor (const request of state.bySeq.values()) {\n\t\tif (request.requestId === requestId) return request;\n\t}\n\treturn undefined;\n}\n\nfunction remotePendingInsert(state: RemotePendingState, request: RemotePendingRequest): void {\n\tconst existingBySeq = state.bySeq.get(request.seq);\n\tif (existingBySeq !== undefined) {\n\t\tstate.requestIds.delete(existingBySeq.requestId);\n\t}\n\tfor (const [seq, pending] of state.bySeq) {\n\t\tif (pending.requestId === request.requestId && seq !== request.seq) {\n\t\t\tstate.bySeq.delete(seq);\n\t\t\tbreak;\n\t\t}\n\t}\n\tstate.requestIds.add(request.requestId);\n\tstate.bySeq.set(request.seq, request);\n}\n\nfunction remotePendingTakeByRequestId(\n\tstate: RemotePendingState,\n\trequestId: string,\n): RemotePendingRequest | undefined {\n\tif (!state.requestIds.delete(requestId)) return undefined;\n\tlet seq: number | undefined;\n\tlet found: RemotePendingRequest | undefined;\n\tfor (const [candidateSeq, request] of state.bySeq) {\n\t\tif (request.requestId === requestId) {\n\t\t\tseq = candidateSeq;\n\t\t\tfound = request;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (seq !== undefined) state.bySeq.delete(seq);\n\treturn found;\n}\n\nfunction remotePendingTakeBySeq(\n\tstate: RemotePendingState,\n\tseq: number,\n): RemotePendingRequest | undefined {\n\tconst request = state.bySeq.get(seq);\n\tif (request === undefined) return undefined;\n\tstate.bySeq.delete(seq);\n\tstate.requestIds.delete(request.requestId);\n\treturn request;\n}\n\nfunction remotePendingFromReceipt<T>(\n\tstate: RemotePendingState,\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n): RemotePendingRequest | undefined {\n\tconst bySeq = remotePendingTakeBySeq(state, envelope.metadata.seq);\n\tif (bySeq !== undefined) return bySeq;\n\tconst fallback = pendingRequestFromEnvelope(envelope);\n\tif (fallback === undefined || remotePendingContains(state, fallback.requestId)) {\n\t\treturn undefined;\n\t}\n\treturn fallback;\n}\n\nfunction pendingRequestFromEnvelope<T>(\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n): RemotePendingRequest | undefined {\n\tif (envelope.payload?.kind !== \"data\") return undefined;\n\tconst request = validateRemoteCallRequest(envelope.payload.value);\n\tif (request === undefined) return undefined;\n\treturn {\n\t\toperation: request.operation,\n\t\trequestId: request.requestId,\n\t\tseq: envelope.metadata.seq,\n\t};\n}\n\nfunction remoteCallResponseRequestId<T>(response: RemoteCallResponse<T>): string {\n\treturn response.requestId;\n}\n\nfunction remoteCallResponseIsTerminal<T>(response: RemoteCallResponse<T>): boolean {\n\treturn response.kind === \"result\" || response.kind === \"error\";\n}\n\nfunction remoteCallResponseOperation<T>(response: RemoteCallResponse<T>): string {\n\treturn response.operation;\n}\n\nfunction remoteCallResponseMatchesPending<T>(\n\tresponse: RemoteCallResponse<T>,\n\trequest: RemotePendingRequest,\n): boolean {\n\treturn remoteCallResponseOperation(response) === request.operation;\n}\n\nfunction remoteCallResponsesNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tname: string,\n): Node<RemoteCallResponse<TResponse>> {\n\treturn graph.node<RemoteCallResponse<TResponse>>(\n\t\t[events, timeouts],\n\t\t(ctx) => {\n\t\t\ttype State = {\n\t\t\t\tpending: RemotePendingState;\n\t\t\t};\n\t\t\tconst state = ctx.state.get<State>() ?? {\n\t\t\t\tpending: remotePendingState(),\n\t\t\t};\n\t\t\tconst ready: RemoteCallResponse<TResponse>[] = [];\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request === undefined) continue;\n\t\t\t\t\tif (remotePendingDuplicate(state.pending, request)) continue;\n\t\t\t\t\tremotePendingInsert(state.pending, request);\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tconst operation = remoteMalformedResponseOperation(event.envelope.payload.value);\n\t\t\t\t\t\tconst request =\n\t\t\t\t\t\t\trequestId === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: remotePendingPeekByRequestId(state.pending, requestId);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trequest !== undefined &&\n\t\t\t\t\t\t\toperation !== undefined &&\n\t\t\t\t\t\t\toperation === request.operation\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, request.requestId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst requestId = remoteCallResponseRequestId(response);\n\t\t\t\t\tconst request = remotePendingPeekByRequestId(state.pending, requestId);\n\t\t\t\t\tif (request !== undefined && remoteCallResponseMatchesPending(response, request)) {\n\t\t\t\t\t\tif (remoteCallResponseIsTerminal(response)) {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, requestId);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tready.push(response);\n\t\t\t\t\t}\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tremotePendingFromReceipt(state.pending, event.outbound);\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tremotePendingTakeBySeq(state.pending, event.seq);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(state.pending, timeout.requestId);\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t\tfor (const response of ready) ctx.down([[\"DATA\", response]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/responses`,\n\t\t\tfactory: \"remoteCallResponses\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallResultsNode<TResponse>(\n\tgraph: Graph,\n\tresponses: Node<RemoteCallResponse<TResponse>>,\n\tname: string,\n): Node<RemoteCallResult<TResponse>> {\n\treturn graph.node<RemoteCallResult<TResponse>>(\n\t\t[responses],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst response = raw as RemoteCallResponse<TResponse>;\n\t\t\t\tif (response.kind === \"result\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\t\tpayload: response.payload,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/results`, factory: \"remoteCallResults\", completeWhenDepsComplete: false },\n\t);\n}\n\nfunction remoteCallStatusNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tname: string,\n): Node<RemoteCallStatus> {\n\treturn graph.node<RemoteCallStatus>(\n\t\t[events, timeouts],\n\t\t(ctx) => {\n\t\t\ttype State = { status: RemoteCallStatus; pending: RemotePendingState };\n\t\t\tconst state =\n\t\t\t\tctx.state.get<State>() ??\n\t\t\t\t({\n\t\t\t\t\tstatus: { state: \"idle\", pending: 0, completed: 0, errors: 0, timeouts: 0 },\n\t\t\t\t\tpending: remotePendingState(),\n\t\t\t\t} satisfies State);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request !== undefined) {\n\t\t\t\t\t\tif (remotePendingDuplicate(state.pending, request)) {\n\t\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\terrors: state.status.errors + 1,\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\tremotePendingInsert(state.pending, request);\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"requested\",\n\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} else if (\n\t\t\t\t\tevent.kind === \"invalid\" ||\n\t\t\t\t\tevent.kind === \"session-mismatch\" ||\n\t\t\t\t\tevent.kind === \"out-of-order\" ||\n\t\t\t\t\tevent.kind === \"late-receipt\"\n\t\t\t\t) {\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tconst request = remotePendingFromReceipt(state.pending, event.outbound);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\t...(request === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { operation: request.operation, requestId: request.requestId }),\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tconst request = remotePendingTakeBySeq(state.pending, event.seq);\n\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\tstate: \"bridge-errored\",\n\t\t\t\t\t\t...(request === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { operation: request.operation, requestId: request.requestId }),\n\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tconst operation = remoteMalformedResponseOperation(event.envelope.payload.value);\n\t\t\t\t\t\tconst request =\n\t\t\t\t\t\t\trequestId === undefined || operation === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: remotePendingPeekByRequestId(state.pending, requestId);\n\t\t\t\t\t\tconst matchedRequest =\n\t\t\t\t\t\t\trequest !== undefined && request.operation === operation ? request : undefined;\n\t\t\t\t\t\tif (matchedRequest === undefined) continue;\n\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, matchedRequest.requestId);\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\toperation: matchedRequest.operation,\n\t\t\t\t\t\t\trequestId: matchedRequest.requestId,\n\t\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst request = remotePendingPeekByRequestId(state.pending, response.requestId);\n\t\t\t\t\tif (request === undefined) {\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (!remoteCallResponseMatchesPending(response, request)) {\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (response.kind === \"result\") {\n\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, request.requestId);\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"responded\",\n\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\tcompleted: state.status.completed + 1,\n\t\t\t\t\t\t};\n\t\t\t\t\t} else if (response.kind === \"error\") {\n\t\t\t\t\t\tremotePendingTakeByRequestId(state.pending, request.requestId);\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstate.status = {\n\t\t\t\t\t\t\t...state.status,\n\t\t\t\t\t\t\tstate: \"requested\",\n\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\trequestId: response.requestId,\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\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(state.pending, timeout.requestId);\n\t\t\t\tstate.status = {\n\t\t\t\t\t...state.status,\n\t\t\t\t\tstate: \"timed-out\",\n\t\t\t\t\toperation: timeout.operation,\n\t\t\t\t\trequestId: timeout.requestId,\n\t\t\t\t\terrors: state.status.errors + 1,\n\t\t\t\t\ttimeouts: state.status.timeouts + 1,\n\t\t\t\t};\n\t\t\t}\n\t\t\tstate.status = { ...state.status, pending: state.pending.requestIds.size };\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", state.status]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"remoteCallStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallErrorsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\ttimeouts: Node<RemoteCallTimeout>,\n\tevents: Node<WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>>,\n\tname: string,\n): Node<RemoteCallError> {\n\treturn graph.node<RemoteCallError>(\n\t\t[timeouts, events],\n\t\t(ctx) => {\n\t\t\tconst pending = ctx.state.get<RemotePendingState>() ?? remotePendingState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst timeout = raw as RemoteCallTimeout;\n\t\t\t\tremotePendingTakeByRequestId(pending, timeout.requestId);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ operation: timeout.operation, requestId: timeout.requestId, error: timeout.error },\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<\n\t\t\t\t\tRemoteCallRequest<TRequest>,\n\t\t\t\t\tRemoteCallResponse<TResponse>\n\t\t\t\t>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst request = pendingRequestFromEnvelope(event.envelope);\n\t\t\t\t\tif (request !== undefined) {\n\t\t\t\t\t\tif (remotePendingDuplicate(pending, request)) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\t\t\terror: `remoteCall: duplicate in-flight requestId '${request.requestId}'`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tremotePendingInsert(pending, request);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.kind === \"inbound\" && event.envelope.payload?.kind === \"data\") {\n\t\t\t\t\tconst response = validateRemoteCallResponse<TResponse>(event.envelope.payload.value);\n\t\t\t\t\tif (response === undefined) {\n\t\t\t\t\t\tconst requestId = remoteMalformedResponseRequestId(event.envelope.payload.value);\n\t\t\t\t\t\tconst operation = remoteMalformedResponseOperation(event.envelope.payload.value);\n\t\t\t\t\t\tconst request =\n\t\t\t\t\t\t\trequestId === undefined || operation === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: remotePendingPeekByRequestId(pending, requestId);\n\t\t\t\t\t\tif (request === undefined || request.operation !== operation) continue;\n\t\t\t\t\t\tremotePendingTakeByRequestId(pending, request.requestId);\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t...(operation === undefined ? {} : { operation }),\n\t\t\t\t\t\t\t\t\t...(requestId === undefined ? {} : { requestId }),\n\t\t\t\t\t\t\t\t\terror: \"remoteCall: response payload is malformed\",\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 {\n\t\t\t\t\t\tconst request = remotePendingPeekByRequestId(pending, response.requestId);\n\t\t\t\t\t\tif (request === undefined) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\t\t\t\terror: \"remoteCall: orphan response for unknown or completed request\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} else if (!remoteCallResponseMatchesPending(response, request)) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\t\t\terror: `remoteCall: response operation '${response.operation}' did not match pending operation '${request.operation}'`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} else if (response.kind === \"error\") {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(pending, request.requestId);\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\toperation: response.operation,\n\t\t\t\t\t\t\t\t\t\trequestId: response.requestId,\n\t\t\t\t\t\t\t\t\t\terror: response.error,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} else if (response.kind === \"result\") {\n\t\t\t\t\t\t\tremotePendingTakeByRequestId(pending, request.requestId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (event.kind === \"nack\") {\n\t\t\t\t\tconst request = remotePendingFromReceipt(pending, event.outbound);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: request?.operation,\n\t\t\t\t\t\t\t\trequestId: request?.requestId,\n\t\t\t\t\t\t\t\terror: String(event.error),\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 if (event.kind === \"exhausted\") {\n\t\t\t\t\tconst request = remotePendingTakeBySeq(pending, event.seq);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperation: request?.operation,\n\t\t\t\t\t\t\t\trequestId: request?.requestId,\n\t\t\t\t\t\t\t\terror: String(event.error),\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 if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { error: event.error }]]);\n\t\t\t\t} else if (\n\t\t\t\t\tevent.kind === \"session-mismatch\" ||\n\t\t\t\t\tevent.kind === \"out-of-order\" ||\n\t\t\t\t\tevent.kind === \"late-receipt\"\n\t\t\t\t) {\n\t\t\t\t\tctx.down([[\"DATA\", { error: remoteCallBridgeErrorMessage(event) }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(pending);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/errors`,\n\t\t\tfactory: \"remoteCallErrors\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallBridgeErrorMessage<TRequest, TResponse>(\n\tevent: WireBridgeEvent<RemoteCallRequest<TRequest>, RemoteCallResponse<TResponse>>,\n): string {\n\tif (event.kind === \"session-mismatch\") {\n\t\treturn `remoteCall: inbound session ${event.actual} did not match expected ${event.expected}`;\n\t}\n\tif (event.kind === \"out-of-order\") {\n\t\treturn `remoteCall: inbound seq ${event.seq} arrived before expected seq ${event.expected}`;\n\t}\n\tif (event.kind === \"late-receipt\") {\n\t\treturn `remoteCall: late ${event.receipt} for unknown or completed ackForSeq ${event.ackForSeq}`;\n\t}\n\treturn \"remoteCall: bridge error\";\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload, type Wave } from \"../protocol/messages.js\";\nimport type {\n\tWireBridgeAck,\n\tWireBridgeAttempt,\n\tWireBridgeEnvelope,\n\tWireBridgeEvent,\n\tWireBridgeInvalidIngress,\n\tWireBridgeNack,\n\tWireBridgeStatus,\n} from \"./bridge-types.js\";\nimport { bridgePayloadError, shouldTrackAck } from \"./bridge-validation.js\";\n\nexport function projectOutbound<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeEnvelope<TOutbound>> {\n\treturn graph.node<WireBridgeEnvelope<TOutbound>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\") ctx.down([[\"DATA\", event.envelope]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/outbound`, factory: \"wireBridgeOutbound\" },\n\t);\n}\n\nexport function projectAcks<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeAck> {\n\treturn graph.node<WireBridgeAck>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"ack\") {\n\t\t\t\t\tctx.down([[\"DATA\", { ackForSeq: event.ackForSeq, envelope: event.envelope }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/acks`, factory: \"wireBridgeAcks\" },\n\t);\n}\n\nexport function projectNacks<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeNack> {\n\treturn graph.node<WireBridgeNack>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"nack\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { ackForSeq: event.ackForSeq, envelope: event.envelope, error: event.error }],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/nacks`, factory: \"wireBridgeNacks\" },\n\t);\n}\n\nexport function projectStatus<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n\tsessionId: string,\n): Node<WireBridgeStatus> {\n\treturn graph.node<WireBridgeStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<WireBridgeStatus>() ??\n\t\t\t\t({\n\t\t\t\t\tsessionId,\n\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\tcursor: 0,\n\t\t\t\t\tnextSeq: 1,\n\t\t\t\t\tpending: 0,\n\t\t\t\t\tattempts: 0,\n\t\t\t\t\tacked: 0,\n\t\t\t\t\tnacked: 0,\n\t\t\t\t\terrors: 0,\n\t\t\t\t} satisfies WireBridgeStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\") {\n\t\t\t\t\tconst { seq, attempt } = event.envelope.metadata;\n\t\t\t\t\tconst trackAck = shouldTrackAck(event.envelope.type);\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate:\n\t\t\t\t\t\t\tevent.envelope.type === \"start\"\n\t\t\t\t\t\t\t\t? \"started\"\n\t\t\t\t\t\t\t\t: event.envelope.type === \"close\"\n\t\t\t\t\t\t\t\t\t? \"closed\"\n\t\t\t\t\t\t\t\t\t: \"open\",\n\t\t\t\t\t\tnextSeq: Math.max(next.nextSeq, seq + 1),\n\t\t\t\t\t\tpending:\n\t\t\t\t\t\t\tevent.envelope.type === \"close\"\n\t\t\t\t\t\t\t\t? 1\n\t\t\t\t\t\t\t\t: trackAck && attempt === 1\n\t\t\t\t\t\t\t\t\t? next.pending + 1\n\t\t\t\t\t\t\t\t\t: next.pending,\n\t\t\t\t\t\tattempts: trackAck ? next.attempts + 1 : next.attempts,\n\t\t\t\t\t\tlastSeq: seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"ack\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: event.outbound.type === \"close\" ? \"closed\" : \"open\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\tacked: next.acked + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"nack\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\tnacked: next.nacked + 1,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tlastSeq: event.seq,\n\t\t\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tpending: Math.max(0, next.pending - 1),\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"cursor\") {\n\t\t\t\t\tnext = { ...next, cursor: event.cursor };\n\t\t\t\t} else if (event.kind === \"out-of-order\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1, lastSeq: event.seq };\n\t\t\t\t} else if (event.kind === \"session-mismatch\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1 };\n\t\t\t\t} else if (event.kind === \"late-receipt\" || event.kind === \"invalid\") {\n\t\t\t\t\tnext = { ...next, state: \"errored\", errors: next.errors + 1 };\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"error\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastSeq: event.envelope.metadata.seq,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"close\") {\n\t\t\t\t\tnext = { ...next, state: \"closed\", lastSeq: event.envelope.metadata.seq };\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"wireBridgeStatus\" },\n\t);\n}\n\nexport function projectErrors<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<unknown> {\n\treturn graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"nack\") ctx.down([[\"DATA\", event.error]]);\n\t\t\t\telse if (event.kind === \"exhausted\") ctx.down([[\"DATA\", event.error]]);\n\t\t\t\telse if (event.kind === \"out-of-order\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: inbound seq ${event.seq} arrived before expected seq ${event.expected}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"inbound\" && event.envelope.type === \"error\") {\n\t\t\t\t\tctx.down([[\"DATA\", bridgePayloadError(event.envelope.payload, \"remote error envelope\")]]);\n\t\t\t\t} else if (event.kind === \"session-mismatch\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: inbound session ${event.actual} did not match expected ${event.expected}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"late-receipt\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t`${name}: late ${event.receipt} for unknown or completed ackForSeq ${event.ackForSeq}`,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", event.error]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"wireBridgeErrors\" },\n\t);\n}\n\nexport function projectCursor<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<number> {\n\treturn graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"cursor\") ctx.down([[\"DATA\", event.cursor]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/cursor`, factory: \"wireBridgeCursor\" },\n\t);\n}\n\nexport function projectAttempts<TOutbound, TInbound>(\n\tgraph: Graph,\n\tevents: Node<WireBridgeEvent<TOutbound, TInbound>>,\n\tname: string,\n): Node<WireBridgeAttempt> {\n\treturn graph.node<WireBridgeAttempt>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeEvent<TOutbound, TInbound>;\n\t\t\t\tif (event.kind === \"outbound\" && shouldTrackAck(event.envelope.type)) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tseq: event.envelope.metadata.seq,\n\t\t\t\t\t\t\t\tattempt: event.envelope.metadata.attempt,\n\t\t\t\t\t\t\t\tmaxAttempts: event.envelope.metadata.maxAttempts,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"wireBridgeAttempts\" },\n\t);\n}\n\nexport function guardedInboundNode<TInbound>(\n\tnode: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n\tsessionId: string,\n): Node<WireBridgeEnvelope<TInbound>> {\n\treturn new Proxy(node, {\n\t\tget(target, property) {\n\t\t\tif (property === \"down\") {\n\t\t\t\treturn (msgs: Wave) => target.down(guardInboundWave(msgs, sessionId));\n\t\t\t}\n\t\t\tconst value = Reflect.get(target, property, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t}) as Node<WireBridgeEnvelope<TInbound>>;\n}\n\nexport function guardInboundWave(msgs: Wave, sessionId: string): Wave {\n\treturn msgs.map((msg) => {\n\t\tif (msg[0] === \"DATA\") return msg;\n\t\tif (msg[0] === \"ERROR\") {\n\t\t\treturn [\n\t\t\t\t\"DATA\",\n\t\t\t\tinvalidIngress(\n\t\t\t\t\t`${sessionId}: inbound protocol ERROR ${String(\n\t\t\t\t\t\terrorPayload(msg[1]),\n\t\t\t\t\t)} is local misuse; remote errors must arrive as DATA envelope facts`,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t\tif (msg[0] === \"COMPLETE\") {\n\t\t\treturn [\n\t\t\t\t\"DATA\",\n\t\t\t\tinvalidIngress(\n\t\t\t\t\t`${sessionId}: inbound protocol COMPLETE is local misuse; remote completion must arrive as a DATA envelope fact`,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t\treturn [\n\t\t\t\"DATA\",\n\t\t\tinvalidIngress(\n\t\t\t\t`${sessionId}: inbound port accepts DATA envelope facts only; ${msg[0]} is local protocol traffic`,\n\t\t\t),\n\t\t];\n\t});\n}\n\nexport function invalidIngress(error: string): WireBridgeInvalidIngress {\n\treturn { __wireBridgeInvalidIngress: true, error };\n}\n\nexport function isInvalidIngress(value: unknown): value is WireBridgeInvalidIngress {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t(value as WireBridgeInvalidIngress).__wireBridgeInvalidIngress === true &&\n\t\ttypeof (value as WireBridgeInvalidIngress).error === \"string\"\n\t);\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type {\n\tRemoteCallError,\n\tRemoteCallRequest,\n\tRemoteCallResponse,\n\tRemoteResponderEvent,\n\tRemoteResponderHandler,\n\tRemoteResponderHandlerDefinition,\n\tRemoteResponderStatus,\n\tWireBridgeCommand,\n\tWireBridgeEnvelope,\n\tWireBridgeInvalidIngress,\n} from \"./bridge-types.js\";\nimport {\n\terrorMessage,\n\tisThenable,\n\trethrowGraphRuntimeInvariant,\n\tvalidateInboundEnvelope,\n\tvalidateRemoteCallRequest,\n} from \"./bridge-validation.js\";\n\nexport function normalizeRemoteHandlers<TRequest, TResponse>(\n\thandlers: readonly RemoteResponderHandlerDefinition<TRequest, TResponse>[],\n): Map<string, RemoteResponderHandler<TRequest, TResponse>> {\n\tconst out = new Map<string, RemoteResponderHandler<TRequest, TResponse>>();\n\tfor (const handler of handlers) {\n\t\tif (handler.operation.length === 0) {\n\t\t\tthrow new RangeError(\"remoteResponder: operation must be non-empty\");\n\t\t}\n\t\tif (out.has(handler.operation)) {\n\t\t\tthrow new RangeError(`remoteResponder: duplicate operation '${handler.operation}'`);\n\t\t}\n\t\tout.set(handler.operation, handler.handle);\n\t}\n\treturn out;\n}\n\ninterface RemoteResponderCursor {\n\tcursor: number;\n\tremoteCursor: number;\n}\n\ntype RemoteResponderInbound<T> =\n\t| { readonly kind: \"request\"; readonly request: RemoteCallRequest<T>; readonly seq: number }\n\t| { readonly kind: \"consumed\" }\n\t| { readonly kind: \"invalid\"; readonly error: string };\n\nfunction reduceRemoteResponderInbound<T>(\n\tcursor: RemoteResponderCursor,\n\tenvelope: WireBridgeEnvelope<RemoteCallRequest<T>>,\n\texpectedSessionId: string,\n): RemoteResponderInbound<T> {\n\tconst envelopeError = validateInboundEnvelope(envelope);\n\tif (envelopeError !== undefined) {\n\t\treturn { kind: \"invalid\", error: envelopeError };\n\t}\n\tif (envelope.sessionId !== expectedSessionId) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: inbound session ${envelope.sessionId} did not match expected ${expectedSessionId}`,\n\t\t};\n\t}\n\tconst seq = envelope.metadata.seq;\n\tconst expected = cursor.cursor + 1;\n\tif (seq <= cursor.cursor) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: duplicate request seq ${seq} at cursor ${cursor.cursor}`,\n\t\t};\n\t}\n\tif (seq > expected) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `remoteResponder: out-of-order request seq ${seq}, expected ${expected}`,\n\t\t};\n\t}\n\tif (envelope.metadata.cursor < cursor.remoteCursor) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\terror: `${envelope.sessionId}: remoteResponder inbound cursor ${envelope.metadata.cursor} regressed below ${cursor.remoteCursor}`,\n\t\t};\n\t}\n\tcursor.cursor = seq;\n\tcursor.remoteCursor = envelope.metadata.cursor;\n\tif (envelope.type !== \"data\") return { kind: \"consumed\" };\n\tif (envelope.payload?.kind !== \"data\") {\n\t\treturn { kind: \"invalid\", error: \"remoteResponder: request envelope must carry request DATA\" };\n\t}\n\tconst request = validateRemoteCallRequest<T>(envelope.payload.value);\n\tif (request === undefined) {\n\t\treturn { kind: \"invalid\", error: \"remoteResponder: request payload is malformed\" };\n\t}\n\treturn { kind: \"request\", request, seq };\n}\n\nexport function remoteResponderEventsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tinbound: Node<WireBridgeEnvelope<RemoteCallRequest<TRequest>> | WireBridgeInvalidIngress>,\n\tname: string,\n\texpectedSessionId: string,\n\thandlers: Map<string, RemoteResponderHandler<TRequest, TResponse>>,\n\trejectUnknown: boolean,\n): Node<RemoteResponderEvent<TRequest, TResponse>> {\n\treturn graph.node<RemoteResponderEvent<TRequest, TResponse>>(\n\t\t[inbound],\n\t\t(ctx) => {\n\t\t\tconst cursor = ctx.state.get<RemoteResponderCursor>() ?? { cursor: 0, remoteCursor: 0 };\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst envelope = raw as WireBridgeEnvelope<RemoteCallRequest<TRequest>>;\n\t\t\t\tconst received = reduceRemoteResponderInbound(cursor, envelope, expectedSessionId);\n\t\t\t\tif (received.kind === \"consumed\") continue;\n\t\t\t\tif (received.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: received.error }]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { request, seq } = received;\n\t\t\t\tctx.down([[\"DATA\", { kind: \"request\", request, seq }]]);\n\t\t\t\tconst handler = handlers.get(request.operation);\n\t\t\t\tif (handler === undefined) {\n\t\t\t\t\tif (!rejectUnknown) continue;\n\t\t\t\t\tconst error = `remoteResponder: unknown operation '${request.operation}'`;\n\t\t\t\t\tconst response = remoteCallErrorResponse(request, error);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst payload = handler(request);\n\t\t\t\t\tif (isThenable(payload)) {\n\t\t\t\t\t\tthrow new Error(\"remoteResponder: async handler results require a later adapter shape\");\n\t\t\t\t\t}\n\t\t\t\t\tconst response = {\n\t\t\t\t\t\tkind: \"result\",\n\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t} satisfies RemoteCallResponse<TResponse>;\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"response\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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} catch (error) {\n\t\t\t\t\trethrowGraphRuntimeInvariant(error);\n\t\t\t\t\tconst message = errorMessage(error);\n\t\t\t\t\tconst response = remoteCallErrorResponse(request, message);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\toperation: request.operation,\n\t\t\t\t\t\t\t\terror: message,\n\t\t\t\t\t\t\t\tcommand: { kind: \"send\", payload: response, requestId: request.requestId },\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\tctx.state.set(cursor);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"remoteResponderEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction remoteCallErrorResponse<TRequest, TResponse>(\n\trequest: RemoteCallRequest<TRequest>,\n\terror: string,\n): RemoteCallResponse<TResponse> {\n\treturn {\n\t\tkind: \"error\",\n\t\toperation: request.operation,\n\t\trequestId: request.requestId,\n\t\terror,\n\t};\n}\n\nexport function remoteResponderResponseCommandsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<WireBridgeCommand<RemoteCallResponse<TResponse>>> {\n\treturn graph.node<WireBridgeCommand<RemoteCallResponse<TResponse>>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (\n\t\t\t\t\t(event.kind === \"response\" || event.kind === \"rejected\") &&\n\t\t\t\t\tevent.command !== undefined\n\t\t\t\t) {\n\t\t\t\t\tctx.down([[\"DATA\", event.command]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/responseCommands`,\n\t\t\tfactory: \"remoteResponderResponseCommands\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nexport function remoteResponderRequestsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteCallRequest<TRequest>> {\n\treturn graph.node<RemoteCallRequest<TRequest>>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"request\") ctx.down([[\"DATA\", event.request]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/requests`,\n\t\t\tfactory: \"remoteResponderRequests\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t},\n\t);\n}\n\nexport function remoteResponderStatusNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteResponderStatus> {\n\treturn graph.node<RemoteResponderStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet status =\n\t\t\t\tctx.state.get<RemoteResponderStatus>() ??\n\t\t\t\t({ state: \"idle\", handled: 0, rejected: 0, errors: 0 } satisfies RemoteResponderStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"response\") {\n\t\t\t\t\tstatus = {\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tstate: \"responded\",\n\t\t\t\t\t\toperation: event.operation,\n\t\t\t\t\t\trequestId: event.requestId,\n\t\t\t\t\t\thandled: status.handled + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"rejected\") {\n\t\t\t\t\tstatus = {\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tstate: \"rejected\",\n\t\t\t\t\t\toperation: event.operation,\n\t\t\t\t\t\trequestId: event.requestId,\n\t\t\t\t\t\trejected: status.rejected + 1,\n\t\t\t\t\t\terrors: status.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tstatus = { ...status, state: \"errored\", errors: status.errors + 1 };\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(status);\n\t\t\tctx.down([[\"DATA\", status]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"remoteResponderStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nexport function remoteResponderErrorsNode<TRequest, TResponse>(\n\tgraph: Graph,\n\tevents: Node<RemoteResponderEvent<TRequest, TResponse>>,\n\tname: string,\n): Node<RemoteCallError> {\n\treturn graph.node<RemoteCallError>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as RemoteResponderEvent<TRequest, TResponse>;\n\t\t\t\tif (event.kind === \"rejected\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ operation: event.operation, requestId: event.requestId, error: event.error },\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"invalid\") {\n\t\t\t\t\tctx.down([[\"DATA\", { error: event.error }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"remoteResponderErrors\", completeWhenDepsComplete: false },\n\t);\n}\n","/**\n * Graph-visible wire bridge envelope helpers (D134).\n *\n * This first slice is transport-free: commands become outbound envelope facts,\n * remote receipts enter only through the inbound fact node, and retry/ack timeout\n * state is surfaced through graph-visible attempts/status/errors nodes.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\tnextRetryDelayMs,\n\ttype RetryPolicy,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport type {\n\tCanonicalWireBridgeDataBody,\n\tCanonicalWireBridgeEnvelope,\n\tCanonicalWireBridgeMetadata,\n\tCanonicalWireBridgePayload,\n\tCanonicalWireEdgeFrame,\n} from \"./bridge-protobuf.js\";\nimport {\n\tCanonicalProtobufError,\n\tdecodeCanonicalWireBridgeEnvelope,\n\tencodeCanonicalWireBridgeEnvelope,\n} from \"./bridge-protobuf.js\";\nimport type {\n\tAttachedCommandSources,\n\tBridgeState,\n\tRemoteCallRequest,\n\tRemoteCallResponse,\n\tRemoteResponderBundle,\n\tRemoteResponderHandler,\n\tRemoteResponderHandlerDefinition,\n\tRemoteResponderOptions,\n\tWireBridgeAckDriverBundle,\n\tWireBridgeAckDriverIssue,\n\tWireBridgeAckDriverOptions,\n\tWireBridgeAckDriverStatus,\n\tWireBridgeBundle,\n\tWireBridgeCommand,\n\tWireBridgeEnvelope,\n\tWireBridgeEnvelopeType,\n\tWireBridgeEvent,\n\tWireBridgeInvalidIngress,\n\tWireBridgeMetadata,\n\tWireBridgeOptions,\n\tWireBridgePayload,\n\tWireBridgeProtobufBundle,\n\tWireBridgeProtobufData,\n\tWireBridgeProtobufIssue,\n\tWireBridgeProtobufOptions,\n\tWireBridgeProtobufStatus,\n} from \"./bridge-types.js\";\n\nexport type {\n\tCanonicalProtobufErrorCategory,\n\tCanonicalWireBridgeDataBody,\n\tCanonicalWireBridgeEnvelope,\n\tCanonicalWireBridgeMetadata,\n\tCanonicalWireBridgePayload,\n\tCanonicalWireEdgeFrame,\n} from \"./bridge-protobuf.js\";\nexport {\n\tCanonicalProtobufError,\n\tdecodeCanonicalWireBridgeEnvelope,\n\tdecodeCanonicalWireEdgeFrame,\n\tencodeCanonicalWireBridgeEnvelope,\n\tencodeCanonicalWireEdgeFrame,\n} from \"./bridge-protobuf.js\";\nexport { remoteCall } from \"./bridge-remote-call.js\";\nexport type {\n\tRemoteCallBundle,\n\tRemoteCallError,\n\tRemoteCallOptions,\n\tRemoteCallRequest,\n\tRemoteCallResponse,\n\tRemoteCallResult,\n\tRemoteCallStatus,\n\tRemoteCallStatusState,\n\tRemoteCallTimeout,\n\tRemoteResponderBundle,\n\tRemoteResponderEvent,\n\tRemoteResponderHandler,\n\tRemoteResponderHandlerDefinition,\n\tRemoteResponderOptions,\n\tRemoteResponderStatus,\n\tRemoteResponderStatusState,\n\tWireBridgeAck,\n\tWireBridgeAckDriverBundle,\n\tWireBridgeAckDriverIssue,\n\tWireBridgeAckDriverOptions,\n\tWireBridgeAckDriverStatus,\n\tWireBridgeAttempt,\n\tWireBridgeBundle,\n\tWireBridgeCommand,\n\tWireBridgeEnvelope,\n\tWireBridgeEnvelopeType,\n\tWireBridgeEvent,\n\tWireBridgeMetadata,\n\tWireBridgeNack,\n\tWireBridgeOptions,\n\tWireBridgePayload,\n\tWireBridgeProtobufBundle,\n\tWireBridgeProtobufData,\n\tWireBridgeProtobufIssue,\n\tWireBridgeProtobufOptions,\n\tWireBridgeProtobufStatus,\n\tWireBridgeStatus,\n} from \"./bridge-types.js\";\n\nimport {\n\tguardedInboundNode,\n\tinvalidIngress,\n\tisInvalidIngress,\n\tprojectAcks,\n\tprojectAttempts,\n\tprojectCursor,\n\tprojectErrors,\n\tprojectNacks,\n\tprojectOutbound,\n\tprojectStatus,\n} from \"./bridge-projections.js\";\nimport {\n\tnormalizeRemoteHandlers,\n\tremoteResponderErrorsNode,\n\tremoteResponderEventsNode,\n\tremoteResponderRequestsNode,\n\tremoteResponderResponseCommandsNode,\n\tremoteResponderStatusNode,\n} from \"./bridge-remote-responder.js\";\nimport {\n\tbridgePayloadError,\n\tenvelopeTypes,\n\tisSafeNonNegativeInteger,\n\tisSafePositiveInteger,\n\tnormalizeWireBridgePayload,\n\tshouldTrackAck,\n\tvalidateCommand,\n\tvalidateInboundEnvelope,\n\tvalidatePayloadForType,\n} from \"./bridge-validation.js\";\n\nconst bridgeCommandSources = new WeakMap<\n\tWireBridgeBundle<unknown, unknown>,\n\tAttachedCommandSources<unknown>\n>();\nconst bridgeInboundTargets = new WeakMap<\n\tWireBridgeBundle<unknown, unknown>,\n\tNode<WireBridgeEnvelope<unknown> | WireBridgeInvalidIngress>\n>();\nconst bridgeInboundSources = new WeakMap<\n\tWireBridgeBundle<unknown, unknown>,\n\t{ sources: Node<WireBridgeEnvelope<unknown> | WireBridgeInvalidIngress>[] }\n>();\n\n/** Stable D134 idempotency key helper scoped to one bridge session and sequence. */\nexport function wireBridgeIdempotencyKey(sessionId: string, seq: number): string {\n\treturn `${sessionId}:${seq}`;\n}\n\n/** Create a D134 wire bridge envelope with ordered metadata. */\nexport function wireBridgeEnvelope<TData = unknown>(input: {\n\treadonly sessionId: string;\n\treadonly type: WireBridgeEnvelopeType;\n\treadonly seq: number;\n\treadonly cursor?: number;\n\treadonly payload?: WireBridgePayload<TData>;\n\treadonly idempotencyKey?: string;\n\treadonly attempt?: number;\n\treadonly maxAttempts?: number;\n\treadonly timestampMs?: number;\n\treadonly ackForSeq?: number;\n\treadonly requestId?: string;\n}): WireBridgeEnvelope<TData> {\n\tif (typeof input.sessionId !== \"string\" || input.sessionId.length === 0) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: sessionId must be a non-empty string\");\n\t}\n\tif (!envelopeTypes.has(input.type)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: type is not recognized\");\n\t}\n\tif (!isSafePositiveInteger(input.seq)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: seq must be a positive integer\");\n\t}\n\tconst cursor = input.cursor ?? 0;\n\tif (!isSafeNonNegativeInteger(cursor)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: cursor must be a non-negative integer\");\n\t}\n\tconst attempt = input.attempt ?? 1;\n\tif (!isSafePositiveInteger(attempt)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: attempt must be a positive integer\");\n\t}\n\tconst maxAttempts = input.maxAttempts ?? attempt;\n\tif (!isSafePositiveInteger(maxAttempts) || maxAttempts < attempt) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: maxAttempts must be >= attempt\");\n\t}\n\tif (input.ackForSeq !== undefined && !isSafePositiveInteger(input.ackForSeq)) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: ackForSeq must be a positive integer\");\n\t}\n\tif ((input.type === \"ack\" || input.type === \"nack\") && input.ackForSeq === undefined) {\n\t\tthrow new RangeError(`wireBridgeEnvelope: ${input.type} envelope requires ackForSeq`);\n\t}\n\tif (input.idempotencyKey !== undefined && input.idempotencyKey.length === 0) {\n\t\tthrow new RangeError(\"wireBridgeEnvelope: idempotencyKey must be a non-empty string\");\n\t}\n\tconst payloadError = validatePayloadForType(input.type, input.payload, \"wireBridgeEnvelope\");\n\tif (payloadError !== undefined) {\n\t\tthrow new RangeError(payloadError);\n\t}\n\tconst payload = normalizeWireBridgePayload(\n\t\tinput.payload,\n\t\t`wireBridgeEnvelope ${input.type} envelope`,\n\t) as WireBridgePayload<TData> | undefined;\n\treturn {\n\t\tsessionId: input.sessionId,\n\t\ttype: input.type,\n\t\tpayload,\n\t\tmetadata: {\n\t\t\tseq: input.seq,\n\t\t\tcursor,\n\t\t\tidempotencyKey: input.idempotencyKey ?? wireBridgeIdempotencyKey(input.sessionId, input.seq),\n\t\t\tattempt,\n\t\t\tmaxAttempts,\n\t\t\ttimestampMs: input.timestampMs,\n\t\t\tackForSeq: input.ackForSeq,\n\t\t\trequestId: input.requestId,\n\t\t},\n\t};\n}\n\nexport function wireBridge<TOutbound = unknown, TInbound = unknown>(\n\tgraph: Graph,\n\topts: WireBridgeOptions,\n): WireBridgeBundle<TOutbound, TInbound> {\n\tconst name = opts.name ?? \"wireBridge\";\n\tconst policy = opts.retry ?? retryPolicy();\n\tconst command = graph.node<WireBridgeCommand<TOutbound>>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"wireBridgeCommand\",\n\t});\n\tconst inboundCore = graph.node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>(\n\t\t[],\n\t\tnull,\n\t\t{\n\t\t\tname: `${name}/inbound`,\n\t\t\tfactory: \"wireBridgeInbound\",\n\t\t},\n\t);\n\tconst inbound = guardedInboundNode(inboundCore, opts.sessionId);\n\tconst events = wireBridgeEventsNode<TOutbound, TInbound>(\n\t\tgraph,\n\t\tcommand,\n\t\tinboundCore,\n\t\tname,\n\t\topts,\n\t\tpolicy,\n\t);\n\tconst outbound = projectOutbound(graph, events, name);\n\tconst acks = projectAcks(graph, events, name);\n\tconst nacks = projectNacks(graph, events, name);\n\tconst status = projectStatus(graph, events, name, opts.sessionId);\n\tconst errors = projectErrors(graph, events, name);\n\tconst cursor = projectCursor(graph, events, name);\n\tconst attempts = projectAttempts(graph, events, name);\n\tconst bundle: WireBridgeBundle<TOutbound, TInbound> = {\n\t\tsessionId: opts.sessionId,\n\t\tcommand,\n\t\toutbound,\n\t\tinbound,\n\t\tevents,\n\t\tacks,\n\t\tnacks,\n\t\tstatus,\n\t\terrors,\n\t\tcursor,\n\t\tattempts,\n\t\tstart: () => command.down([[\"DATA\", { kind: \"start\" }]]),\n\t\tsend: (payload, sendOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t\tidempotencyKey: sendOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: sendOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tack: (ackForSeq, ackOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\t\tackForSeq,\n\t\t\t\t\t\tidempotencyKey: ackOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: ackOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tnack: (ackForSeq, error, nackOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"nack\",\n\t\t\t\t\t\tackForSeq,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tidempotencyKey: nackOpts?.idempotencyKey,\n\t\t\t\t\t\trequestId: nackOpts?.requestId,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tclose: (reason, closeOpts) =>\n\t\t\tcommand.down([\n\t\t\t\t[\"DATA\", { kind: \"close\", reason, idempotencyKey: closeOpts?.idempotencyKey }],\n\t\t\t]),\n\t};\n\tbridgeCommandSources.set(bundle as WireBridgeBundle<unknown, unknown>, { sources: [] });\n\tbridgeInboundTargets.set(bundle as WireBridgeBundle<unknown, unknown>, inboundCore);\n\tbridgeInboundSources.set(bundle as WireBridgeBundle<unknown, unknown>, { sources: [] });\n\treturn bundle;\n}\n\ntype WireBridgeAckTimeoutCommand = Extract<\n\tWireBridgeCommand<never>,\n\t{ readonly kind: \"ack-timeout\" }\n>;\n\ntype WireBridgeAckDriverEvent =\n\t| {\n\t\t\treadonly kind: \"command\";\n\t\t\treadonly command: WireBridgeAckTimeoutCommand;\n\t\t\treadonly pending: number;\n\t\t\treadonly nowMs: number;\n\t }\n\t| {\n\t\t\treadonly kind: \"issue\";\n\t\t\treadonly issue: WireBridgeAckDriverIssue;\n\t\t\treadonly pending: number;\n\t\t\treadonly nowMs?: number;\n\t }\n\t| { readonly kind: \"state\"; readonly pending: number; readonly nowMs?: number };\n\ninterface AckDriverPendingAttempt {\n\treadonly seq: number;\n\tattempt: number;\n\tobservedAtMs?: number;\n\ttimedOutAttempt?: number;\n\ttimedOutAtMs?: number;\n\tretryDueAtMs?: number;\n\tretryReleasedAttempt?: number;\n}\n\ninterface AckDriverState {\n\tnowMs?: number;\n\tpending: Map<number, AckDriverPendingAttempt>;\n}\n\n/** D502 explicit graph-visible ack-timeout command driver for a wireBridge. */\nexport function wireBridgeAckDriver<TOutbound = unknown, TInbound = unknown>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\topts: WireBridgeAckDriverOptions,\n): WireBridgeAckDriverBundle {\n\tconst name = opts.name ?? `${bridge.sessionId}/wireBridgeAckDriver`;\n\tif (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs < 0) {\n\t\tthrow new RangeError(\"wireBridgeAckDriver: timeoutMs must be a non-negative finite number\");\n\t}\n\tconst topology = graph.topologyGroup({ name: `${name}.wireBridgeAckDriver` });\n\tconst active = { current: true };\n\tconst events = topology.add(wireBridgeAckDriverEventsNode(graph, bridge, opts, name, active));\n\tconst commands = topology.add(\n\t\tgraph.node<WireBridgeCommand<never>>([events], wireBridgeAckDriverCommandsFn(), {\n\t\t\tname: `${name}/commands`,\n\t\t\tfactory: \"wireBridgeAckDriverCommands\",\n\t\t}),\n\t);\n\tconst issues = topology.add(wireBridgeAckDriverIssuesNode(graph, events, name));\n\tconst status = topology.add(wireBridgeAckDriverStatusNode(graph, events, name));\n\tlet released = false;\n\treturn {\n\t\tcommands,\n\t\tstatus,\n\t\tissues,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tactive.current = false;\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.wireBridgeAckDriver.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tactive.current = true;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction wireBridgeAckDriverEventsNode<TOutbound, TInbound>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\topts: WireBridgeAckDriverOptions,\n\tname: string,\n\tactive: { current: boolean },\n): Node<WireBridgeAckDriverEvent> {\n\treturn graph.node<WireBridgeAckDriverEvent>(\n\t\t[opts.clock, bridge.attempts, bridge.acks, bridge.nacks, bridge.status],\n\t\t(ctx) => {\n\t\t\tlet state = ctx.state.get<AckDriverState>();\n\t\t\tif (state === undefined) {\n\t\t\t\tstate = { pending: new Map() };\n\t\t\t\tctx.state.set(state);\n\t\t\t}\n\t\t\tlet touched = false;\n\t\t\tfor (const rawClock of depBatch(ctx, 0) ?? []) {\n\t\t\t\tif (!Number.isFinite(rawClock) || (rawClock as number) < 0) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"issue\",\n\t\t\t\t\t\t\t\tissue: {\n\t\t\t\t\t\t\t\t\tcode: \"wire-bridge-ack-driver-clock-invalid\",\n\t\t\t\t\t\t\t\t\tmessage: \"wireBridgeAckDriver: clock facts must be non-negative finite numbers\",\n\t\t\t\t\t\t\t\t\tnowMs: rawClock as number,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tpending: state.pending.size,\n\t\t\t\t\t\t\t\tnowMs: state.nowMs,\n\t\t\t\t\t\t\t} satisfies WireBridgeAckDriverEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\ttouched = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst nowMs = rawClock as number;\n\t\t\t\tif (state.nowMs !== undefined && nowMs < state.nowMs) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"issue\",\n\t\t\t\t\t\t\t\tissue: {\n\t\t\t\t\t\t\t\t\tcode: \"wire-bridge-ack-driver-clock-regressed\",\n\t\t\t\t\t\t\t\t\tmessage: \"wireBridgeAckDriver: clock facts must be monotonic\",\n\t\t\t\t\t\t\t\t\tnowMs,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tpending: state.pending.size,\n\t\t\t\t\t\t\t\tnowMs: state.nowMs,\n\t\t\t\t\t\t\t} satisfies WireBridgeAckDriverEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\ttouched = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.nowMs = nowMs;\n\t\t\t\ttouched = true;\n\t\t\t}\n\t\t\tfor (const rawAttempt of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst attempt = rawAttempt as { readonly seq: number; readonly attempt: number };\n\t\t\t\tstate.pending.set(attempt.seq, {\n\t\t\t\t\tseq: attempt.seq,\n\t\t\t\t\tattempt: attempt.attempt,\n\t\t\t\t\tobservedAtMs: state.nowMs,\n\t\t\t\t});\n\t\t\t\ttouched = true;\n\t\t\t}\n\t\t\tfor (const rawAck of depBatch(ctx, 2) ?? []) {\n\t\t\t\tstate.pending.delete((rawAck as { readonly ackForSeq: number }).ackForSeq);\n\t\t\t\ttouched = true;\n\t\t\t}\n\t\t\tfor (const rawNack of depBatch(ctx, 3) ?? []) {\n\t\t\t\tstate.pending.delete((rawNack as { readonly ackForSeq: number }).ackForSeq);\n\t\t\t\ttouched = true;\n\t\t\t}\n\t\t\tfor (const rawStatus of depBatch(ctx, 4) ?? []) {\n\t\t\t\tconst status = rawStatus as {\n\t\t\t\t\treadonly state?: string;\n\t\t\t\t\treadonly pending?: number;\n\t\t\t\t\treadonly lastSeq?: number;\n\t\t\t\t\treadonly lastDelayMs?: number;\n\t\t\t\t};\n\t\t\t\tif (status.pending === 0) state.pending.clear();\n\t\t\t\telse if (status.state === \"exhausted\" && status.lastSeq !== undefined) {\n\t\t\t\t\tstate.pending.delete(status.lastSeq);\n\t\t\t\t} else if (\n\t\t\t\t\tstatus.state === \"waiting\" &&\n\t\t\t\t\tstatus.lastSeq !== undefined &&\n\t\t\t\t\tstatus.lastDelayMs !== undefined\n\t\t\t\t) {\n\t\t\t\t\tconst pending = state.pending.get(status.lastSeq);\n\t\t\t\t\tif (\n\t\t\t\t\t\tpending?.timedOutAtMs !== undefined &&\n\t\t\t\t\t\tpending.retryReleasedAttempt !== pending.attempt\n\t\t\t\t\t) {\n\t\t\t\t\t\tpending.retryDueAtMs = pending.timedOutAtMs + status.lastDelayMs;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttouched = true;\n\t\t\t}\n\t\t\tconst nowMs = state.nowMs;\n\t\t\tlet emittedCommand = false;\n\t\t\tif (active.current && nowMs !== undefined) {\n\t\t\t\tfor (const pending of state.pending.values()) {\n\t\t\t\t\tif (pending.observedAtMs === undefined) {\n\t\t\t\t\t\tpending.observedAtMs = nowMs;\n\t\t\t\t\t\ttouched = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tpending.observedAtMs !== undefined &&\n\t\t\t\t\t\tnowMs - pending.observedAtMs >= opts.timeoutMs &&\n\t\t\t\t\t\tpending.timedOutAttempt !== pending.attempt\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst command: WireBridgeAckTimeoutCommand = {\n\t\t\t\t\t\t\tkind: \"ack-timeout\",\n\t\t\t\t\t\t\tseq: pending.seq,\n\t\t\t\t\t\t\tattempt: pending.attempt,\n\t\t\t\t\t\t\tobservedAtMs: nowMs,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tpending.timedOutAttempt = pending.attempt;\n\t\t\t\t\t\tpending.timedOutAtMs = nowMs;\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"command\", command, pending: state.pending.size, nowMs }]]);\n\t\t\t\t\t\temittedCommand = true;\n\t\t\t\t\t\ttouched = true;\n\t\t\t\t\t} else if (\n\t\t\t\t\t\tpending.retryDueAtMs !== undefined &&\n\t\t\t\t\t\tnowMs >= pending.retryDueAtMs &&\n\t\t\t\t\t\tpending.retryReleasedAttempt !== pending.attempt\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst command: WireBridgeAckTimeoutCommand = {\n\t\t\t\t\t\t\tkind: \"ack-timeout\",\n\t\t\t\t\t\t\tseq: pending.seq,\n\t\t\t\t\t\t\tattempt: pending.attempt,\n\t\t\t\t\t\t\tobservedAtMs: nowMs,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tpending.retryReleasedAttempt = pending.attempt;\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"command\", command, pending: state.pending.size, nowMs }]]);\n\t\t\t\t\t\temittedCommand = true;\n\t\t\t\t\t\ttouched = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (touched && !emittedCommand) {\n\t\t\t\tctx.down([[\"DATA\", { kind: \"state\", pending: state.pending.size, nowMs }]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"wireBridgeAckDriverEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction wireBridgeAckDriverCommandsFn(): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\tconst event = raw as WireBridgeAckDriverEvent;\n\t\t\tif (event.kind === \"command\") ctx.down([[\"DATA\", event.command]]);\n\t\t}\n\t};\n}\n\nfunction wireBridgeAckDriverIssuesNode(\n\tgraph: Graph,\n\tevents: Node<WireBridgeAckDriverEvent>,\n\tname: string,\n): Node<WireBridgeAckDriverIssue> {\n\treturn graph.node<WireBridgeAckDriverIssue>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeAckDriverEvent;\n\t\t\t\tif (event.kind === \"issue\") ctx.down([[\"DATA\", event.issue]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/issues`, factory: \"wireBridgeAckDriverIssues\" },\n\t);\n}\n\nfunction wireBridgeAckDriverStatusNode(\n\tgraph: Graph,\n\tevents: Node<WireBridgeAckDriverEvent>,\n\tname: string,\n): Node<WireBridgeAckDriverStatus> {\n\treturn graph.node<WireBridgeAckDriverStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<WireBridgeAckDriverStatus>() ??\n\t\t\t\t({\n\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\tpending: 0,\n\t\t\t\t\tcommands: 0,\n\t\t\t\t\tissues: 0,\n\t\t\t\t} satisfies WireBridgeAckDriverStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeAckDriverEvent;\n\t\t\t\tif (event.kind === \"command\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"timed-out\",\n\t\t\t\t\t\tpending: event.pending,\n\t\t\t\t\t\tcommands: next.commands + 1,\n\t\t\t\t\t\tnowMs: event.nowMs,\n\t\t\t\t\t\tlastCommand: event.command,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"issue\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"issues\",\n\t\t\t\t\t\tpending: event.pending,\n\t\t\t\t\t\tissues: next.issues + 1,\n\t\t\t\t\t\tnowMs: event.nowMs,\n\t\t\t\t\t\tlastIssue: event.issue,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: event.pending > 0 ? \"active\" : \"idle\",\n\t\t\t\t\t\tpending: event.pending,\n\t\t\t\t\t\tnowMs: event.nowMs,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"wireBridgeAckDriverStatus\" },\n\t);\n}\n\ntype WireBridgeProtobufInboundResult =\n\t| { readonly kind: \"decoded\"; readonly envelope: WireBridgeEnvelope<WireBridgeProtobufData> }\n\t| {\n\t\t\treadonly kind: \"issue\";\n\t\t\treadonly issue: WireBridgeProtobufIssue;\n\t\t\treadonly invalid: WireBridgeInvalidIngress;\n\t };\n\ntype WireBridgeProtobufOutboundResult =\n\t| { readonly kind: \"encoded\"; readonly bytes: Uint8Array }\n\t| { readonly kind: \"issue\"; readonly issue: WireBridgeProtobufIssue };\n\ntype WireBridgeProtobufEvent =\n\t| {\n\t\t\treadonly kind: \"inbound\";\n\t\t\treadonly result: WireBridgeProtobufInboundResult;\n\t }\n\t| {\n\t\t\treadonly kind: \"outbound\";\n\t\t\treadonly result: WireBridgeProtobufOutboundResult;\n\t };\n\ntype WireBridgeProtobufInboundEvent = Extract<\n\tWireBridgeProtobufEvent,\n\t{ readonly kind: \"inbound\" }\n>;\ntype WireBridgeProtobufOutboundEvent = Extract<\n\tWireBridgeProtobufEvent,\n\t{ readonly kind: \"outbound\" }\n>;\n\n/**\n * D498 focused canonical protobuf byte adapter over an existing semantic wireBridge bundle.\n *\n * This helper owns no transport/session/retry policy and does not add wireBridge core options.\n * Malformed bytes become graph-visible issue/invalid facts, never local protocol terminals.\n */\nexport function wireBridgeProtobuf(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<WireBridgeProtobufData, WireBridgeProtobufData>,\n\topts: WireBridgeProtobufOptions = {},\n): WireBridgeProtobufBundle {\n\tconst name = opts.name ?? \"wireBridgeProtobuf\";\n\tconst topology = graph.topologyGroup({ name: `${name}.wireBridgeProtobuf` });\n\tconst inboundBytes = topology.node<Uint8Array>([], null, {\n\t\tname: `${name}/inboundBytes`,\n\t\tfactory: \"wireBridgeProtobufInboundBytes\",\n\t});\n\tconst inboundResults = topology.node<WireBridgeProtobufInboundResult>(\n\t\t[inboundBytes],\n\t\t(ctx) => {\n\t\t\tfor (const bytes of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst result = wireBridgeProtobufInboundResult(bytes as Uint8Array, bridge.sessionId);\n\t\t\t\tctx.down([[\"DATA\", result]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/inboundResults`,\n\t\t\tfactory: \"wireBridgeProtobufInboundResults\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outboundResults = topology.node<WireBridgeProtobufOutboundResult>(\n\t\t[bridge.outbound],\n\t\t(ctx) => {\n\t\t\tfor (const envelope of depBatch(ctx, 0) ?? []) {\n\t\t\t\tlet result: WireBridgeProtobufOutboundResult;\n\t\t\t\ttry {\n\t\t\t\t\tconst canonical = canonicalEnvelopeFromSemantic(\n\t\t\t\t\t\tenvelope as WireBridgeEnvelope<WireBridgeProtobufData>,\n\t\t\t\t\t);\n\t\t\t\t\tresult = { kind: \"encoded\", bytes: encodeCanonicalWireBridgeEnvelope(canonical) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst issue = protobufIssue(\"outbound\", \"encode\", error);\n\t\t\t\t\tresult = { kind: \"issue\", issue };\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", result]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/outboundResults`,\n\t\t\tfactory: \"wireBridgeProtobufOutboundResults\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst inboundEvents = topology.node<WireBridgeProtobufInboundEvent>(\n\t\t[inboundResults],\n\t\t(ctx) => {\n\t\t\tfor (const result of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"inbound\", result: result as WireBridgeProtobufInboundResult }],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/inboundEvents`,\n\t\t\tfactory: \"wireBridgeProtobufInboundEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outboundEvents = topology.node<WireBridgeProtobufOutboundEvent>(\n\t\t[outboundResults],\n\t\t(ctx) => {\n\t\t\tfor (const result of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"outbound\", result: result as WireBridgeProtobufOutboundResult }],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/outboundEvents`,\n\t\t\tfactory: \"wireBridgeProtobufOutboundEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst inboundDecoded = topology.node<\n\t\tWireBridgeEnvelope<WireBridgeProtobufData> | WireBridgeInvalidIngress\n\t>(\n\t\t[inboundEvents],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufInboundEvent;\n\t\t\t\tconst result = event.result;\n\t\t\t\tctx.down([[\"DATA\", result.kind === \"decoded\" ? result.envelope : result.invalid]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/inboundDecoded`,\n\t\t\tfactory: \"wireBridgeProtobufInboundDecoded\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outboundBytes = topology.node<Uint8Array>(\n\t\t[outboundEvents],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufOutboundEvent;\n\t\t\t\tif (event.result.kind === \"encoded\") {\n\t\t\t\t\tctx.down([[\"DATA\", event.result.bytes]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/outboundBytes`,\n\t\t\tfactory: \"wireBridgeProtobufOutboundBytes\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst issues = topology.node<WireBridgeProtobufIssue>(\n\t\t[inboundEvents, outboundEvents],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufInboundEvent;\n\t\t\t\tconst result = event.result;\n\t\t\t\tif (result.kind === \"issue\") ctx.down([[\"DATA\", result.issue]]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufOutboundEvent;\n\t\t\t\tconst result = event.result;\n\t\t\t\tif (result.kind === \"issue\") ctx.down([[\"DATA\", result.issue]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/issues`,\n\t\t\tfactory: \"wireBridgeProtobufIssues\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst status = topology.node<WireBridgeProtobufStatus>(\n\t\t[inboundEvents, outboundEvents],\n\t\t(ctx) => {\n\t\t\tlet status =\n\t\t\t\tctx.state.get<WireBridgeProtobufStatus>() ??\n\t\t\t\t({ decoded: 0, encoded: 0, issues: 0, state: \"idle\" } satisfies WireBridgeProtobufStatus);\n\t\t\tconst emitStatus = (next: WireBridgeProtobufStatus) => {\n\t\t\t\tstatus = next;\n\t\t\t\tctx.state.set(status);\n\t\t\t\tctx.down([[\"DATA\", status]]);\n\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufInboundEvent;\n\t\t\t\tconst result = event.result;\n\t\t\t\tif (result.kind === \"decoded\") {\n\t\t\t\t\temitStatus({\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tdecoded: status.decoded + 1,\n\t\t\t\t\t\tstate: status.issues > 0 ? \"issues\" : \"active\",\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\temitStatus({\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tissues: status.issues + 1,\n\t\t\t\t\t\tstate: \"issues\",\n\t\t\t\t\t\tlastIssue: result.issue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst event = raw as WireBridgeProtobufOutboundEvent;\n\t\t\t\tconst result = event.result;\n\t\t\t\tif (result.kind === \"encoded\") {\n\t\t\t\t\temitStatus({\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tencoded: status.encoded + 1,\n\t\t\t\t\t\tstate: status.issues > 0 ? \"issues\" : \"active\",\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\temitStatus({\n\t\t\t\t\t\t...status,\n\t\t\t\t\t\tissues: status.issues + 1,\n\t\t\t\t\t\tstate: \"issues\",\n\t\t\t\t\t\tlastIssue: result.issue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"wireBridgeProtobufStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\ttry {\n\t\tattachWireBridgeInboundSource(bridge, inboundDecoded);\n\t} catch (error) {\n\t\ttopology.release({ reason: `${name}.wireBridgeProtobuf.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\tinboundBytes,\n\t\toutboundBytes,\n\t\tissues,\n\t\tstatus,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tdetachWireBridgeInboundSource(bridge, inboundDecoded);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.wireBridgeProtobuf.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachWireBridgeInboundSource(bridge, inboundDecoded);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function remoteResponderHandler<TRequest = unknown, TResponse = unknown>(\n\toperation: string,\n\thandle: RemoteResponderHandler<TRequest, TResponse>,\n): RemoteResponderHandlerDefinition<TRequest, TResponse> {\n\tif (operation.length === 0) {\n\t\tthrow new RangeError(\"remoteResponderHandler: operation must be non-empty\");\n\t}\n\tif (typeof handle !== \"function\") {\n\t\tthrow new TypeError(\"remoteResponderHandler: handle must be a function\");\n\t}\n\treturn { operation, handle };\n}\n\n/** D147 remote responder over inbound wireBridge request facts and outbound command facts. */\nexport function remoteResponder<TRequest = unknown, TResponse = unknown>(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<RemoteCallResponse<TResponse>, RemoteCallRequest<TRequest>>,\n\topts: RemoteResponderOptions<TRequest, TResponse> = {},\n): RemoteResponderBundle<TRequest, TResponse> {\n\tconst name = opts.name ?? \"remoteResponder\";\n\tconst handlers = normalizeRemoteHandlers(opts.handlers ?? []);\n\tconst topology = graph.topologyGroup({ name: `${name}.remoteResponder` });\n\tconst events = topology.add(\n\t\tremoteResponderEventsNode(\n\t\t\tgraph,\n\t\t\twireBridgeInboundTarget(bridge),\n\t\t\tname,\n\t\t\tbridge.sessionId,\n\t\t\thandlers,\n\t\t\topts.rejectUnknown === true,\n\t\t),\n\t);\n\tconst responseCommands = topology.add(remoteResponderResponseCommandsNode(graph, events, name));\n\tconst requests = topology.add(remoteResponderRequestsNode(graph, events, name));\n\tconst status = topology.add(remoteResponderStatusNode(graph, events, name));\n\tconst errors = topology.add(remoteResponderErrorsNode(graph, events, name));\n\ttry {\n\t\tattachWireBridgeCommandSource(bridge, responseCommands);\n\t} catch (error) {\n\t\ttopology.release({ reason: `${name}.remoteResponder.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\tevents,\n\t\tresponseCommands,\n\t\trequests,\n\t\tstatus,\n\t\terrors,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tdetachWireBridgeCommandSource(bridge, responseCommands);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.remoteResponder.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachWireBridgeCommandSource(bridge, responseCommands);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction wireBridgeEventsNode<TOutbound, TInbound>(\n\tgraph: Graph,\n\tcommand: Node<WireBridgeCommand<TOutbound>>,\n\tinbound: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n\tname: string,\n\topts: WireBridgeOptions,\n\tpolicy: RetryPolicy,\n): Node<WireBridgeEvent<TOutbound, TInbound>> {\n\tconst now = opts.now ?? Date.now;\n\treturn graph.node<WireBridgeEvent<TOutbound, TInbound>>(\n\t\t[command, inbound],\n\t\t(ctx) => {\n\t\t\tconst state = initBridgeState<TOutbound>(ctx);\n\n\t\t\tconst emitOutbound = (\n\t\t\t\ttype: WireBridgeEnvelopeType,\n\t\t\t\tpayload: WireBridgePayload<TOutbound> | undefined,\n\t\t\t\tcommandOpts: { idempotencyKey?: string; requestId?: string; ackForSeq?: number } = {},\n\t\t\t\tbeforeEmit?: () => void,\n\t\t\t) => {\n\t\t\t\tif (!isSafePositiveInteger(state.nextSeq)) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\t\t\t\terror: `${opts.sessionId}: next outbound seq exceeded Number.MAX_SAFE_INTEGER`,\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\treturn;\n\t\t\t\t}\n\t\t\t\tconst seq = state.nextSeq;\n\t\t\t\tlet envelope: WireBridgeEnvelope<TOutbound>;\n\t\t\t\ttry {\n\t\t\t\t\tconst normalizedPayload = normalizeWireBridgePayload(\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t\t`wireBridge: outbound ${type} envelope`,\n\t\t\t\t\t) as WireBridgePayload<TOutbound> | undefined;\n\t\t\t\t\tenvelope = wireBridgeEnvelope<TOutbound>({\n\t\t\t\t\t\tsessionId: opts.sessionId,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\tcursor: state.cursor,\n\t\t\t\t\t\tpayload: normalizedPayload,\n\t\t\t\t\t\tidempotencyKey: commandOpts.idempotencyKey,\n\t\t\t\t\t\tattempt: 1,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\ttimestampMs: now(),\n\t\t\t\t\t\tackForSeq: commandOpts.ackForSeq,\n\t\t\t\t\t\trequestId: commandOpts.requestId,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\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\treturn;\n\t\t\t\t}\n\t\t\t\tstate.nextSeq++;\n\t\t\t\tbeforeEmit?.();\n\t\t\t\tctx.down([[\"DATA\", { kind: \"outbound\", envelope }]]);\n\t\t\t\tif (shouldTrackAck(type)) state.pending.set(envelope.metadata.seq, { envelope });\n\t\t\t};\n\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tprocessInbound(ctx, state, raw, opts.sessionId);\n\t\t\t}\n\t\t\tconst inboundTerminal = ctx.terminal[1];\n\t\t\tif (inboundTerminal !== false && inboundTerminal !== undefined && !state.terminalReported) {\n\t\t\t\tstate.terminalReported = true;\n\t\t\t\tconst error =\n\t\t\t\t\tinboundTerminal === true\n\t\t\t\t\t\t? `${opts.sessionId}: inbound protocol COMPLETE is local misuse; remote completion must arrive as a DATA envelope fact`\n\t\t\t\t\t\t: `${opts.sessionId}: inbound protocol ERROR ${String(\n\t\t\t\t\t\t\t\terrorPayload(inboundTerminal),\n\t\t\t\t\t\t\t)} is local misuse; remote errors must arrive as DATA envelope facts`;\n\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error }]]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst invalid = validateCommand(raw);\n\t\t\t\tif (invalid !== undefined) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: invalid }]]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst commandValue = raw as WireBridgeCommand<TOutbound>;\n\t\t\t\tswitch (commandValue.kind) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\temitOutbound(\"start\", undefined, commandValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"send\":\n\t\t\t\t\t\temitOutbound(\"data\", { kind: \"data\", value: commandValue.payload }, commandValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"ack\":\n\t\t\t\t\t\temitOutbound(\"ack\", undefined, {\n\t\t\t\t\t\t\tidempotencyKey: commandValue.idempotencyKey,\n\t\t\t\t\t\t\trequestId: commandValue.requestId,\n\t\t\t\t\t\t\tackForSeq: commandValue.ackForSeq,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"nack\":\n\t\t\t\t\t\temitOutbound(\n\t\t\t\t\t\t\t\"nack\",\n\t\t\t\t\t\t\t{ kind: \"error\", error: errorPayload(commandValue.error) },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tidempotencyKey: commandValue.idempotencyKey,\n\t\t\t\t\t\t\t\trequestId: commandValue.requestId,\n\t\t\t\t\t\t\t\tackForSeq: commandValue.ackForSeq,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"ack-timeout\":\n\t\t\t\t\t\tprocessAckTimeoutCommand(ctx, state, commandValue, opts, policy, now);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"close\":\n\t\t\t\t\t\temitOutbound(\n\t\t\t\t\t\t\t\"close\",\n\t\t\t\t\t\t\tcommandValue.reason === undefined\n\t\t\t\t\t\t\t\t? { kind: \"close\" }\n\t\t\t\t\t\t\t\t: { kind: \"close\", reason: commandValue.reason },\n\t\t\t\t\t\t\tcommandValue,\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tstate.pending.clear();\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"wireBridgeEvents\",\n\t\t\tpartial: true,\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t);\n}\n\nfunction initBridgeState<TPayload>(ctx: Ctx): BridgeState<TPayload> {\n\tlet state = ctx.state.get<BridgeState<TPayload>>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tcleanupInstalled: false,\n\t\t\tnextSeq: 1,\n\t\t\tcursor: 0,\n\t\t\tremoteCursor: 0,\n\t\t\tterminalReported: false,\n\t\t\tpending: new Map(),\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tstate.pending.clear();\n\t\t});\n\t}\n\treturn state;\n}\n\nfunction attachWireBridgeCommandSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeCommand<TOutbound>>,\n): void {\n\tconst attached = bridgeCommandSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<WireBridgeCommand<TOutbound>>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\tbridge.command.replaceDeps([...sources], wireBridgeCommandSourceFn(sources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tbridge.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachWireBridgeCommandSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeCommand<TOutbound>>,\n): void {\n\tconst attached = bridgeCommandSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<WireBridgeCommand<TOutbound>>[];\n\tif (!sources.includes(source)) return;\n\tconst previousSources = [...sources];\n\tconst nextSources = sources.filter((candidate) => candidate !== source);\n\tsources.splice(0, sources.length, ...nextSources);\n\ttry {\n\t\tbridge.command.replaceDeps([...nextSources], wireBridgeCommandSourceFn(nextSources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tbridge.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction attachWireBridgeInboundSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n): void {\n\tconst attached = bridgeInboundSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"wireBridgeProtobuf: bridge inbound source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<\n\t\tWireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress\n\t>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\twireBridgeInboundTarget(bridge).replaceDeps(\n\t\t\t[...sources],\n\t\t\twireBridgeInboundSourceFn(sources.length),\n\t\t);\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\twireBridgeInboundTarget(bridge).replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeInboundSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachWireBridgeInboundSource<TOutbound, TInbound>(\n\tbridge: WireBridgeBundle<TOutbound, TInbound>,\n\tsource: Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>,\n): void {\n\tconst attached = bridgeInboundSources.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"wireBridgeProtobuf: bridge inbound source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<\n\t\tWireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress\n\t>[];\n\tif (!sources.includes(source)) return;\n\tconst previousSources = [...sources];\n\tconst nextSources = sources.filter((candidate) => candidate !== source);\n\tsources.splice(0, sources.length, ...nextSources);\n\ttry {\n\t\twireBridgeInboundTarget(bridge).replaceDeps(\n\t\t\t[...nextSources],\n\t\t\twireBridgeInboundSourceFn(nextSources.length),\n\t\t);\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\twireBridgeInboundTarget(bridge).replaceDeps(\n\t\t\t[...previousSources],\n\t\t\twireBridgeInboundSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction wireBridgeInboundTarget<TInbound>(\n\tbridge: WireBridgeBundle<unknown, TInbound>,\n): Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress> {\n\tconst target = bridgeInboundTargets.get(bridge as WireBridgeBundle<unknown, unknown>);\n\tif (target === undefined) {\n\t\tthrow new Error(\"remoteResponder: bridge inbound target registry missing\");\n\t}\n\treturn target as Node<WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress>;\n}\n\nfunction wireBridgeCommandSourceFn<TOutbound>(sourceCount: number): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tfor (let i = 0; i < sourceCount; i += 1) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", command as WireBridgeCommand<TOutbound>]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction wireBridgeInboundSourceFn<TInbound>(sourceCount: number): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tfor (let i = 0; i < sourceCount; i += 1) {\n\t\t\tfor (const envelope of depBatch(ctx, i) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", envelope as WireBridgeEnvelope<TInbound> | WireBridgeInvalidIngress]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction wireBridgeProtobufInboundResult(\n\tbytes: Uint8Array,\n\tsessionId: string,\n): WireBridgeProtobufInboundResult {\n\ttry {\n\t\tconst envelope = semanticEnvelopeFromCanonical(decodeCanonicalWireBridgeEnvelope(bytes));\n\t\treturn { kind: \"decoded\", envelope };\n\t} catch (error) {\n\t\tconst issue = protobufIssue(\"inbound\", \"decode\", error);\n\t\treturn {\n\t\t\tkind: \"issue\",\n\t\t\tissue,\n\t\t\tinvalid: invalidIngress(`${sessionId}: ${issue.message}`),\n\t\t};\n\t}\n}\n\nfunction semanticEnvelopeFromCanonical(\n\tenvelope: CanonicalWireBridgeEnvelope,\n): WireBridgeEnvelope<WireBridgeProtobufData> {\n\tconst metadata = semanticMetadataFromCanonical(envelope.metadata);\n\tswitch (envelope.payload.kind) {\n\t\tcase \"start\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"start\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"ack\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"ack\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\tackForSeq: metadata.ackForSeq,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"data\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"data\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tpayload: { kind: \"data\", value: envelope.payload.body },\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"nack\":\n\t\t\tif (envelope.payload.error === undefined) {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"semantic wireBridge nack requires error bytes\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"nack\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tpayload: { kind: \"error\", error: envelope.payload.error },\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\tackForSeq: metadata.ackForSeq,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"status\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"status\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tpayload: { kind: \"status\", status: envelope.payload.status },\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"error\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"error\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tpayload: { kind: \"error\", error: envelope.payload.error },\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t\tcase \"close\":\n\t\t\treturn wireBridgeEnvelope({\n\t\t\t\tsessionId: envelope.sessionId,\n\t\t\t\ttype: \"close\",\n\t\t\t\tseq: metadata.seq,\n\t\t\t\tcursor: metadata.cursor,\n\t\t\t\tpayload:\n\t\t\t\t\tenvelope.payload.reason === undefined\n\t\t\t\t\t\t? { kind: \"close\" }\n\t\t\t\t\t\t: { kind: \"close\", reason: envelope.payload.reason },\n\t\t\t\tidempotencyKey: metadata.idempotencyKey,\n\t\t\t\tattempt: metadata.attempt,\n\t\t\t\tmaxAttempts: metadata.maxAttempts,\n\t\t\t\ttimestampMs: metadata.timestampMs,\n\t\t\t\trequestId: metadata.requestId,\n\t\t\t});\n\t}\n}\n\nfunction canonicalEnvelopeFromSemantic(\n\tenvelope: WireBridgeEnvelope<WireBridgeProtobufData>,\n): CanonicalWireBridgeEnvelope {\n\treturn {\n\t\tsessionId: envelope.sessionId,\n\t\tmetadata: {\n\t\t\tseq: BigInt(envelope.metadata.seq),\n\t\t\tcursor: BigInt(envelope.metadata.cursor),\n\t\t\tidempotencyKey: envelope.metadata.idempotencyKey,\n\t\t\tattempt: envelope.metadata.attempt,\n\t\t\tmaxAttempts: envelope.metadata.maxAttempts,\n\t\t\ttimestampMs:\n\t\t\t\tenvelope.metadata.timestampMs === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: BigInt(envelope.metadata.timestampMs),\n\t\t\tackForSeq:\n\t\t\t\tenvelope.metadata.ackForSeq === undefined ? undefined : BigInt(envelope.metadata.ackForSeq),\n\t\t\trequestId: envelope.metadata.requestId,\n\t\t},\n\t\tpayload: canonicalPayloadFromSemantic(envelope),\n\t};\n}\n\nfunction canonicalPayloadFromSemantic(\n\tenvelope: WireBridgeEnvelope<WireBridgeProtobufData>,\n): CanonicalWireBridgePayload {\n\tconst payload = envelope.payload;\n\tswitch (envelope.type) {\n\t\tcase \"start\":\n\t\t\treturn { kind: \"start\" };\n\t\tcase \"ack\":\n\t\t\treturn { kind: \"ack\" };\n\t\tcase \"data\":\n\t\t\tif (payload?.kind !== \"data\") {\n\t\t\t\tthrow new CanonicalProtobufError(\"missing_required\", \"data envelope requires data payload\");\n\t\t\t}\n\t\t\treturn { kind: \"data\", body: canonicalDataBody(payload.value) };\n\t\tcase \"nack\":\n\t\t\tif (payload?.kind !== \"error\") {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"nack envelope requires error payload\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"nack\", error: requiredBytes(payload.error, \"nack error\") };\n\t\tcase \"status\":\n\t\t\tif (payload?.kind !== \"status\") {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"status envelope requires status payload\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"status\", status: requiredBytes(payload.status, \"status\") };\n\t\tcase \"error\":\n\t\t\tif (payload?.kind !== \"error\") {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"error envelope requires error payload\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"error\", error: requiredBytes(payload.error, \"error\") };\n\t\tcase \"close\":\n\t\t\tif (payload?.kind !== \"close\") {\n\t\t\t\tthrow new CanonicalProtobufError(\n\t\t\t\t\t\"missing_required\",\n\t\t\t\t\t\"close envelope requires close payload\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"close\", reason: optionalBytes(payload.reason, \"close reason\") };\n\t}\n}\n\nfunction canonicalDataBody(value: unknown): CanonicalWireBridgeDataBody {\n\tif (value instanceof Uint8Array) return { kind: \"value\", value };\n\tif (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t(value as { readonly kind?: unknown }).kind === \"value\"\n\t) {\n\t\tconst bytes = (value as { readonly value?: unknown }).value;\n\t\tif (bytes instanceof Uint8Array) return { kind: \"value\", value: bytes };\n\t}\n\tif (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t(value as { readonly kind?: unknown }).kind === \"wire_edge\"\n\t) {\n\t\tconst frame = (value as { readonly frame?: unknown }).frame;\n\t\treturn { kind: \"wire_edge\", frame: frame as CanonicalWireEdgeFrame };\n\t}\n\tthrow new CanonicalProtobufError(\n\t\t\"malformed\",\n\t\t\"wireBridgeProtobuf data payload must be Uint8Array or CanonicalWireBridgeDataBody\",\n\t);\n}\n\nfunction semanticMetadataFromCanonical(metadata: CanonicalWireBridgeMetadata): WireBridgeMetadata {\n\treturn {\n\t\tseq: safeSemanticNumber(metadata.seq, \"seq\"),\n\t\tcursor: safeSemanticNumber(metadata.cursor, \"cursor\"),\n\t\tidempotencyKey: metadata.idempotencyKey,\n\t\tattempt: metadata.attempt,\n\t\tmaxAttempts: metadata.maxAttempts,\n\t\ttimestampMs:\n\t\t\tmetadata.timestampMs === undefined\n\t\t\t\t? undefined\n\t\t\t\t: safeSemanticNumber(metadata.timestampMs, \"timestamp_ms\"),\n\t\tackForSeq:\n\t\t\tmetadata.ackForSeq === undefined\n\t\t\t\t? undefined\n\t\t\t\t: safeSemanticNumber(metadata.ackForSeq, \"ack_for_seq\"),\n\t\trequestId: metadata.requestId,\n\t};\n}\n\nfunction safeSemanticNumber(value: bigint, field: string): number {\n\tif (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n\t\tthrow new CanonicalProtobufError(\n\t\t\t\"malformed\",\n\t\t\t`${field} exceeds semantic wireBridge Number.MAX_SAFE_INTEGER range`,\n\t\t);\n\t}\n\treturn Number(value);\n}\n\nfunction requiredBytes(value: unknown, field: string): Uint8Array {\n\tif (value instanceof Uint8Array) return value;\n\tthrow new CanonicalProtobufError(\"malformed\", `wireBridgeProtobuf ${field} must be Uint8Array`);\n}\n\nfunction optionalBytes(value: unknown, field: string): Uint8Array | undefined {\n\tif (value === undefined) return undefined;\n\tif (value instanceof Uint8Array) return value;\n\tthrow new CanonicalProtobufError(\"malformed\", `wireBridgeProtobuf ${field} must be Uint8Array`);\n}\n\nfunction protobufIssue(\n\tdirection: WireBridgeProtobufIssue[\"direction\"],\n\toperation: WireBridgeProtobufIssue[\"operation\"],\n\terror: unknown,\n): WireBridgeProtobufIssue {\n\treturn {\n\t\tdirection,\n\t\toperation,\n\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\tcategory: error instanceof CanonicalProtobufError ? error.category : undefined,\n\t};\n}\n\nfunction processAckTimeoutCommand<TPayload>(\n\tctx: Ctx,\n\tstate: BridgeState<TPayload>,\n\tcommand: Extract<WireBridgeCommand<TPayload>, { readonly kind: \"ack-timeout\" }>,\n\topts: WireBridgeOptions,\n\tpolicy: RetryPolicy,\n\tnow: () => number,\n): void {\n\tconst pending = state.pending.get(command.seq);\n\tif (pending === undefined || pending.envelope.metadata.attempt !== command.attempt) return;\n\tconst current = pending.envelope;\n\tconst emitRetryOutbound = () => {\n\t\tconst attempt = current.metadata.attempt + 1;\n\t\tconst retry = wireBridgeEnvelope<TPayload>({\n\t\t\tsessionId: current.sessionId,\n\t\t\ttype: current.type,\n\t\t\tseq: current.metadata.seq,\n\t\t\tcursor: state.cursor,\n\t\t\tpayload: current.payload,\n\t\t\tidempotencyKey: current.metadata.idempotencyKey,\n\t\t\tattempt,\n\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\ttimestampMs: now(),\n\t\t\trequestId: current.metadata.requestId,\n\t\t});\n\t\tpending.envelope = retry;\n\t\tpending.timeoutReportedAttempt = undefined;\n\t\tpending.retryDueAtMs = undefined;\n\t\tctx.down([[\"DATA\", { kind: \"outbound\", envelope: retry }]]);\n\t};\n\tif (pending.timeoutReportedAttempt === current.metadata.attempt) {\n\t\tif (\n\t\t\tpending.retryDueAtMs !== undefined &&\n\t\t\tcommand.observedAtMs !== undefined &&\n\t\t\tcommand.observedAtMs < pending.retryDueAtMs\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\temitRetryOutbound();\n\t\treturn;\n\t}\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"timeout\",\n\t\t\t\tseq: current.metadata.seq,\n\t\t\t\tattempt: current.metadata.attempt,\n\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t],\n\t]);\n\tif (!shouldRetry(policy, current.metadata.attempt)) {\n\t\tconst error = `${opts.sessionId}: ack timeout for seq ${current.metadata.seq}`;\n\t\tstate.pending.delete(current.metadata.seq);\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"exhausted\",\n\t\t\t\t\tseq: current.metadata.seq,\n\t\t\t\t\tattempt: current.metadata.attempt,\n\t\t\t\t\terror,\n\t\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tconst attempt = current.metadata.attempt + 1;\n\tconst delayMs = nextRetryDelayMs(policy, attempt) ?? 0;\n\tconst error = `${opts.sessionId}: ack timeout for seq ${current.metadata.seq}`;\n\tpending.timeoutReportedAttempt = current.metadata.attempt;\n\tif (delayMs > 0 && command.observedAtMs !== undefined) {\n\t\tpending.retryDueAtMs = command.observedAtMs + delayMs;\n\t}\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"retry\",\n\t\t\t\tseq: current.metadata.seq,\n\t\t\t\tattempt,\n\t\t\t\tdelayMs,\n\t\t\t\terror,\n\t\t\t} satisfies WireBridgeEvent<TPayload, unknown>,\n\t\t],\n\t]);\n\tif (pending.retryDueAtMs !== undefined) return;\n\temitRetryOutbound();\n}\n\nfunction processInbound<TOutbound, TInbound>(\n\tctx: Ctx,\n\tstate: BridgeState<TOutbound>,\n\tinput: unknown,\n\tsessionId: string,\n): void {\n\tif (isInvalidIngress(input)) {\n\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: input.error }]]);\n\t\treturn;\n\t}\n\tconst invalid = validateInboundEnvelope(input);\n\tif (invalid !== undefined) {\n\t\tctx.down([[\"DATA\", { kind: \"invalid\", error: invalid }]]);\n\t\treturn;\n\t}\n\tconst envelope = input as WireBridgeEnvelope<TInbound>;\n\tif (envelope.sessionId !== sessionId) {\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"session-mismatch\",\n\t\t\t\t\texpected: sessionId,\n\t\t\t\t\tactual: envelope.sessionId,\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tconst seq = envelope.metadata.seq;\n\tconst expected = state.cursor + 1;\n\tif (seq <= state.cursor) {\n\t\tctx.down([[\"DATA\", { kind: \"duplicate\", seq, cursor: state.cursor }]]);\n\t\treturn;\n\t}\n\tif (seq > expected) {\n\t\tctx.down([[\"DATA\", { kind: \"out-of-order\", seq, expected }]]);\n\t\treturn;\n\t}\n\tif (envelope.metadata.cursor < state.remoteCursor) {\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"invalid\",\n\t\t\t\t\terror: `${sessionId}: inbound cursor ${envelope.metadata.cursor} regressed below ${state.remoteCursor}`,\n\t\t\t\t},\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tstate.remoteCursor = envelope.metadata.cursor;\n\tstate.cursor = seq;\n\tctx.down([[\"DATA\", { kind: \"cursor\", cursor: state.cursor }]]);\n\tctx.down([[\"DATA\", { kind: \"inbound\", envelope }]]);\n\tif (envelope.type === \"ack\" && envelope.metadata.ackForSeq !== undefined) {\n\t\tconst pending = state.pending.get(envelope.metadata.ackForSeq);\n\t\tif (pending === undefined) {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", { kind: \"late-receipt\", receipt: \"ack\", ackForSeq: envelope.metadata.ackForSeq }],\n\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tstate.pending.delete(envelope.metadata.ackForSeq);\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"ack\",\n\t\t\t\t\tackForSeq: envelope.metadata.ackForSeq,\n\t\t\t\t\tenvelope,\n\t\t\t\t\toutbound: pending.envelope,\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t} else if (envelope.type === \"nack\" && envelope.metadata.ackForSeq !== undefined) {\n\t\tconst pending = state.pending.get(envelope.metadata.ackForSeq);\n\t\tif (pending === undefined) {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", { kind: \"late-receipt\", receipt: \"nack\", ackForSeq: envelope.metadata.ackForSeq }],\n\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tstate.pending.delete(envelope.metadata.ackForSeq);\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"nack\",\n\t\t\t\t\tackForSeq: envelope.metadata.ackForSeq,\n\t\t\t\t\tenvelope,\n\t\t\t\t\toutbound: pending.envelope,\n\t\t\t\t\terror: bridgePayloadError(envelope.payload, \"remote nack\"),\n\t\t\t\t} satisfies WireBridgeEvent<TOutbound, TInbound>,\n\t\t\t],\n\t\t]);\n\t}\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { CanonicalWireEdgeFrame } from \"./bridge-protobuf.js\";\nimport type {\n\tWireBridgeBundle,\n\tWireBridgeCommand,\n\tWireBridgeEnvelope,\n\tWireBridgeProtobufData,\n} from \"./bridge-types.js\";\n\nexport interface WireEdgeGroupEdge {\n\treadonly edgeId: string;\n\treadonly outbound?: Node<Uint8Array>;\n}\nexport type WireEdgeGroupIssueCode =\n\t| \"wire-edge-group-missing-snapshot\"\n\t| \"wire-edge-group-unknown-edge\"\n\t| \"wire-edge-group-duplicate-dirty\"\n\t| \"wire-edge-group-duplicate-data\"\n\t| \"wire-edge-group-data-before-dirty\"\n\t| \"wire-edge-group-competing-cause\"\n\t| \"wire-edge-group-malformed-frame\"\n\t| \"wire-edge-group-incomplete-cause\";\nexport interface WireEdgeGroupIssue {\n\treadonly code: WireEdgeGroupIssueCode;\n\treadonly message: string;\n\treadonly edgeId?: string;\n\treadonly causeId?: string;\n\treadonly activeCauseId?: string;\n}\nexport interface WireEdgeGroupStatus {\n\treadonly state: \"idle\" | \"collecting\" | \"released\" | \"issues\";\n\treadonly expectedEdges: readonly string[];\n\treadonly dirty: number;\n\treadonly data: number;\n\treadonly released: number;\n\treadonly issues: number;\n\treadonly activeCauseId?: string;\n\treadonly lastIssue?: WireEdgeGroupIssue;\n}\nexport interface WireEdgeGroupOptions {\n\treadonly name?: string;\n\treadonly edges: readonly WireEdgeGroupEdge[];\n}\nexport interface WireEdgeGroupBundle {\n\treadonly inbound: ReadonlyMap<string, Node<Uint8Array>>;\n\treadonly status: Node<WireEdgeGroupStatus>;\n\treadonly issues: Node<WireEdgeGroupIssue>;\n\trelease(): void;\n}\n\ntype Command = WireBridgeCommand<WireBridgeProtobufData>;\ntype Event =\n\t| { kind: \"outbound\"; command: Command }\n\t| { kind: \"frame\"; frame: CanonicalWireEdgeFrame }\n\t| { kind: \"bridge-end\" }\n\t| { kind: \"issue\"; issue: WireEdgeGroupIssue };\ntype Gate =\n\t| { kind: \"release\"; causeId: string; edgeId: string; value: Uint8Array }\n\t| { kind: \"progress\"; causeId: string; dirty: number; data: number }\n\t| { kind: \"issue\"; issue: WireEdgeGroupIssue };\ninterface OutState {\n\tnextCause: number;\n\tsnapshots: Map<string, Uint8Array>;\n}\ninterface GateState {\n\tactiveCauseId?: string;\n\tdirty: Set<string>;\n\tdata: Map<string, Uint8Array>;\n\tfailed: CauseTombstones;\n\treleased: CauseTombstones;\n}\n\nconst WIRE_EDGE_GROUP_CAUSE_TOMBSTONE_LIMIT = 1024;\n\nclass CauseTombstones {\n\tprivate readonly seen = new Set<string>();\n\tprivate readonly order: string[] = [];\n\n\thas(causeId: string): boolean {\n\t\treturn this.seen.has(causeId);\n\t}\n\n\tadd(causeId: string): void {\n\t\tif (this.seen.has(causeId)) return;\n\t\tthis.seen.add(causeId);\n\t\tthis.order.push(causeId);\n\t\twhile (this.order.length > WIRE_EDGE_GROUP_CAUSE_TOMBSTONE_LIMIT) {\n\t\t\tconst evicted = this.order.shift();\n\t\t\tif (evicted !== undefined) this.seen.delete(evicted);\n\t\t}\n\t}\n}\n\nexport function wireEdgeGroup(\n\tgraph: Graph,\n\tbridge: WireBridgeBundle<WireBridgeProtobufData, WireBridgeProtobufData>,\n\topts: WireEdgeGroupOptions,\n): WireEdgeGroupBundle {\n\tconst name = opts.name ?? \"wireEdgeGroup\";\n\tconst edges = normalize(opts.edges);\n\tconst expected = edges.map((edge) => edge.edgeId);\n\tconst outbound = edges\n\t\t.map((edge, index) => ({ edge, index }))\n\t\t.filter(\n\t\t\t(entry): entry is { edge: { edgeId: string; outbound: Node<Uint8Array> }; index: number } =>\n\t\t\t\tentry.edge.outbound !== undefined,\n\t\t);\n\tconst topology = graph.topologyGroup({ name: `${name}.wireEdgeGroup` });\n\tconst events = topology.node<Event>(\n\t\t[...outbound.map((entry) => entry.edge.outbound), bridge.inbound],\n\t\teventsFn(\n\t\t\tname,\n\t\t\tedges,\n\t\t\toutbound.map((entry) => entry.index),\n\t\t),\n\t\t{\n\t\t\tname: `${name}/events`,\n\t\t\tfactory: \"wireEdgeGroupEvents\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t);\n\tconst gate = topology.node<Gate>([events], gateFn(name, expected), {\n\t\tname: `${name}/gate`,\n\t\tfactory: \"wireEdgeGroupGate\",\n\t\tpartial: true,\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst commands = topology.node<Command>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as Event;\n\t\t\t\tif (event.kind === \"outbound\") ctx.down([[\"DATA\", event.command]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/commands`,\n\t\t\tfactory: \"wireEdgeGroupCommands\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst issues = topology.node<WireEdgeGroupIssue>(\n\t\t[events, gate],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as Event;\n\t\t\t\tif (event.kind === \"issue\") ctx.down([[\"DATA\", event.issue]]);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst event = raw as Gate;\n\t\t\t\tif (event.kind === \"issue\") ctx.down([[\"DATA\", event.issue]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/issues`,\n\t\t\tfactory: \"wireEdgeGroupIssues\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst status = topology.node<WireEdgeGroupStatus>([events, gate], statusFn(expected), {\n\t\tname: `${name}/status`,\n\t\tfactory: \"wireEdgeGroupStatus\",\n\t\tpartial: true,\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst inbound = new Map(\n\t\tedges.map(\n\t\t\t(edge) =>\n\t\t\t\t[\n\t\t\t\t\tedge.edgeId,\n\t\t\t\t\ttopology.node<Uint8Array>(\n\t\t\t\t\t\t[gate],\n\t\t\t\t\t\t(ctx) => {\n\t\t\t\t\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\t\t\t\tconst event = raw as Gate;\n\t\t\t\t\t\t\t\tif (event.kind === \"release\" && event.edgeId === edge.edgeId)\n\t\t\t\t\t\t\t\t\tctx.down([[\"DATA\", Uint8Array.from(event.value)]]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: `${name}/inbound/${edge.edgeId}`,\n\t\t\t\t\t\t\tfactory: \"wireEdgeGroupInboundEdge\",\n\t\t\t\t\t\t\tpartial: true,\n\t\t\t\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\t\t\t\terrorWhenDepsError: false,\n\t\t\t\t\t\t\tmeta: { edgeId: edge.edgeId },\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t] as const,\n\t\t),\n\t);\n\tbridge.command.replaceDeps([commands], commandSourceFn());\n\tlet released = false;\n\treturn {\n\t\tinbound,\n\t\tstatus,\n\t\tissues,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tbridge.command.replaceDeps([], commandSourceFn());\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.wireEdgeGroup.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tbridge.command.replaceDeps([commands], commandSourceFn());\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction commandSourceFn(): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tfor (const command of depBatch(ctx, 0) ?? []) ctx.down([[\"DATA\", command as Command]]);\n\t};\n}\nfunction normalize(edges: readonly WireEdgeGroupEdge[]) {\n\tconst seen = new Set<string>();\n\tif (edges.length === 0) throw new RangeError(\"wireEdgeGroup: edges must be non-empty\");\n\treturn edges.map((edge) => {\n\t\tif (!edge.edgeId) throw new RangeError(\"wireEdgeGroup: edgeId must be a non-empty string\");\n\t\tif (seen.has(edge.edgeId))\n\t\t\tthrow new RangeError(`wireEdgeGroup: duplicate edgeId ${edge.edgeId}`);\n\t\tseen.add(edge.edgeId);\n\t\treturn edge;\n\t});\n}\nfunction issue(\n\tcode: WireEdgeGroupIssueCode,\n\tmessage: string,\n\textra: Omit<WireEdgeGroupIssue, \"code\" | \"message\"> = {},\n): WireEdgeGroupIssue {\n\treturn { code, message, ...extra };\n}\nfunction send(frame: CanonicalWireEdgeFrame): Command {\n\treturn { kind: \"send\", payload: { kind: \"wire_edge\", frame: clone(frame) } };\n}\nfunction clone(frame: CanonicalWireEdgeFrame): CanonicalWireEdgeFrame {\n\treturn frame.kind === \"data\"\n\t\t? {\n\t\t\t\tkind: \"data\",\n\t\t\t\tedgeId: frame.edgeId,\n\t\t\t\tcauseId: frame.causeId,\n\t\t\t\tvalue: Uint8Array.from(frame.value ?? new Uint8Array()),\n\t\t\t}\n\t\t: { kind: \"dirty\", edgeId: frame.edgeId, causeId: frame.causeId };\n}\nfunction eventsFn(\n\tname: string,\n\tedges: readonly WireEdgeGroupEdge[],\n\toutboundIndexes: readonly number[],\n): (ctx: Ctx) => void {\n\tconst byDep = new Map<number, WireEdgeGroupEdge>();\n\toutboundIndexes.forEach((edgeIndex, depIndex) => {\n\t\tbyDep.set(depIndex, edges[edgeIndex]);\n\t});\n\tconst inboundIndex = outboundIndexes.length;\n\treturn (ctx) => {\n\t\tlet st = ctx.state.get<OutState>();\n\t\tif (!st) {\n\t\t\tst = { nextCause: 1, snapshots: new Map() };\n\t\t\tctx.state.set(st);\n\t\t}\n\t\tlet trigger = false;\n\t\tfor (let i = 0; i < outboundIndexes.length; i++) {\n\t\t\tconst edge = byDep.get(i);\n\t\t\tif (!edge) continue;\n\t\t\tfor (const raw of depBatch(ctx, i) ?? []) {\n\t\t\t\tif (!(raw instanceof Uint8Array))\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"issue\",\n\t\t\t\t\t\t\t\tissue: issue(\n\t\t\t\t\t\t\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t\t\t\t\t\t\t`${name}: outbound edge ${edge.edgeId} must emit Uint8Array bytes`,\n\t\t\t\t\t\t\t\t\t{ edgeId: edge.edgeId },\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t} satisfies Event,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\telse {\n\t\t\t\t\tst.snapshots.set(edge.edgeId, Uint8Array.from(raw));\n\t\t\t\t\ttrigger = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (trigger) emitOutbound(ctx, name, edges, st);\n\t\tfor (const rawEnvelope of depBatch(ctx, inboundIndex) ?? []) {\n\t\t\tconst ev = frameEvent(name, rawEnvelope as WireBridgeEnvelope<unknown>);\n\t\t\tif (ev) ctx.down([[\"DATA\", ev]]);\n\t\t}\n\t};\n}\nfunction emitOutbound(\n\tctx: Ctx,\n\tname: string,\n\tedges: readonly WireEdgeGroupEdge[],\n\tst: OutState,\n): void {\n\tconst missing = edges.filter((edge) => !st.snapshots.has(edge.edgeId));\n\tif (missing.length) {\n\t\tfor (const edge of missing)\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"issue\",\n\t\t\t\t\t\tissue: issue(\n\t\t\t\t\t\t\t\"wire-edge-group-missing-snapshot\",\n\t\t\t\t\t\t\t`${name}: missing outbound snapshot for edge ${edge.edgeId}`,\n\t\t\t\t\t\t\t{ edgeId: edge.edgeId },\n\t\t\t\t\t\t),\n\t\t\t\t\t} satisfies Event,\n\t\t\t\t],\n\t\t\t]);\n\t\treturn;\n\t}\n\tconst causeId = `${name}:cause:${st.nextCause++}`;\n\tfor (const edge of edges)\n\t\tctx.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"outbound\",\n\t\t\t\t\tcommand: send({ kind: \"dirty\", edgeId: edge.edgeId, causeId }),\n\t\t\t\t} satisfies Event,\n\t\t\t],\n\t\t]);\n\tfor (const edge of edges) {\n\t\tconst value = st.snapshots.get(edge.edgeId);\n\t\tif (value)\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"outbound\",\n\t\t\t\t\t\tcommand: send({ kind: \"data\", edgeId: edge.edgeId, causeId, value }),\n\t\t\t\t\t} satisfies Event,\n\t\t\t\t],\n\t\t\t]);\n\t}\n}\nfunction frameEvent(name: string, envelope: WireBridgeEnvelope<unknown>): Event | undefined {\n\tif (envelope.type === \"close\" || envelope.type === \"error\") return { kind: \"bridge-end\" };\n\tif (envelope.type !== \"data\") return undefined;\n\tconst value = envelope.payload?.kind === \"data\" ? envelope.payload.value : undefined;\n\tif (\n\t\tvalue instanceof Uint8Array ||\n\t\t(typeof value === \"object\" && value !== null && (value as { kind?: unknown }).kind === \"value\")\n\t)\n\t\treturn undefined;\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\t(value as { kind?: unknown }).kind !== \"wire_edge\"\n\t)\n\t\treturn {\n\t\t\tkind: \"issue\",\n\t\t\tissue: issue(\n\t\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t\t`${name}: wire-edge payload must be a wire_edge frame`,\n\t\t\t),\n\t\t};\n\tconst frame = (value as { frame?: unknown }).frame;\n\tconst bad = validate(name, frame);\n\treturn bad\n\t\t? { kind: \"issue\", issue: bad }\n\t\t: { kind: \"frame\", frame: clone(frame as CanonicalWireEdgeFrame) };\n}\nfunction validate(name: string, frame: unknown): WireEdgeGroupIssue | undefined {\n\tif (typeof frame !== \"object\" || frame === null)\n\t\treturn issue(\"wire-edge-group-malformed-frame\", `${name}: wire-edge frame must be an object`);\n\tconst f = frame as Partial<CanonicalWireEdgeFrame>;\n\tif (f.kind !== \"dirty\" && f.kind !== \"data\")\n\t\treturn issue(\n\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t`${name}: wire-edge frame kind must be dirty or data`,\n\t\t);\n\tif (!f.edgeId)\n\t\treturn issue(\n\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t`${name}: wire-edge frame edgeId must be non-empty`,\n\t\t\t{ causeId: f.causeId },\n\t\t);\n\tif (!f.causeId)\n\t\treturn issue(\n\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t`${name}: wire-edge frame causeId must be non-empty`,\n\t\t\t{ edgeId: f.edgeId },\n\t\t);\n\tif (f.kind === \"dirty\" && f.value !== undefined)\n\t\treturn issue(\n\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t`${name}: DIRTY wire-edge frame must not carry value bytes`,\n\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t);\n\tif (f.kind === \"data\" && !(f.value instanceof Uint8Array))\n\t\treturn issue(\n\t\t\t\"wire-edge-group-malformed-frame\",\n\t\t\t`${name}: DATA wire-edge frame requires Uint8Array value bytes`,\n\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t);\n\treturn undefined;\n}\nfunction gateFn(name: string, expectedIds: readonly string[]): (ctx: Ctx) => void {\n\tconst expected = new Set(expectedIds);\n\treturn (ctx) => {\n\t\tlet st = ctx.state.get<GateState>();\n\t\tif (!st) {\n\t\t\tst = {\n\t\t\t\tdirty: new Set(),\n\t\t\t\tdata: new Map(),\n\t\t\t\tfailed: new CauseTombstones(),\n\t\t\t\treleased: new CauseTombstones(),\n\t\t\t};\n\t\t\tctx.state.set(st);\n\t\t}\n\t\tconst emitIssue = (i: WireEdgeGroupIssue) =>\n\t\t\tctx.down([[\"DATA\", { kind: \"issue\", issue: i } satisfies Gate]]);\n\t\tconst reset = () => {\n\t\t\tst.activeCauseId = undefined;\n\t\t\tst.dirty.clear();\n\t\t\tst.data.clear();\n\t\t};\n\t\tconst fail = (causeId?: string) => {\n\t\t\tif (causeId) st.failed.add(causeId);\n\t\t\treset();\n\t\t};\n\t\tconst progress = (causeId: string) =>\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{ kind: \"progress\", causeId, dirty: st.dirty.size, data: st.data.size } satisfies Gate,\n\t\t\t\t],\n\t\t\t]);\n\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\tconst ev = raw as Event;\n\t\t\tif (ev.kind === \"issue\") {\n\t\t\t\temitIssue(ev.issue);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ev.kind === \"outbound\") continue;\n\t\t\tif (ev.kind === \"bridge-end\") {\n\t\t\t\tif (st.activeCauseId) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tissue(\n\t\t\t\t\t\t\t\"wire-edge-group-incomplete-cause\",\n\t\t\t\t\t\t\t`${name}: cause ${st.activeCauseId} ended before all expected edge frames arrived`,\n\t\t\t\t\t\t\t{ causeId: st.activeCauseId },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tfail(st.activeCauseId);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst f = ev.frame;\n\t\t\tif (st.failed.has(f.causeId)) {\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\n\t\t\t\t\t\t\"wire-edge-group-incomplete-cause\",\n\t\t\t\t\t\t`${name}: cause ${f.causeId} was already failed closed`,\n\t\t\t\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (st.released.has(f.causeId)) {\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\n\t\t\t\t\t\tf.kind === \"dirty\"\n\t\t\t\t\t\t\t? \"wire-edge-group-duplicate-dirty\"\n\t\t\t\t\t\t\t: \"wire-edge-group-duplicate-data\",\n\t\t\t\t\t\t`${name}: cause ${f.causeId} was already released`,\n\t\t\t\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!expected.has(f.edgeId)) {\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\"wire-edge-group-unknown-edge\", `${name}: unknown edge ${f.edgeId}`, {\n\t\t\t\t\t\tedgeId: f.edgeId,\n\t\t\t\t\t\tcauseId: f.causeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tfail(f.causeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!st.activeCauseId) st.activeCauseId = f.causeId;\n\t\t\tif (st.activeCauseId !== f.causeId) {\n\t\t\t\tconst activeCauseId = st.activeCauseId;\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\n\t\t\t\t\t\t\"wire-edge-group-competing-cause\",\n\t\t\t\t\t\t`${name}: competing cause ${f.causeId} arrived while ${activeCauseId} is active`,\n\t\t\t\t\t\t{ edgeId: f.edgeId, causeId: f.causeId, activeCauseId },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\n\t\t\t\t\t\t\"wire-edge-group-incomplete-cause\",\n\t\t\t\t\t\t`${name}: active cause ${activeCauseId} is incomplete`,\n\t\t\t\t\t\t{ causeId: activeCauseId },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tfail(activeCauseId);\n\t\t\t\tst.failed.add(f.causeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (f.kind === \"dirty\") {\n\t\t\t\tif (st.dirty.has(f.edgeId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tissue(\n\t\t\t\t\t\t\t\"wire-edge-group-duplicate-dirty\",\n\t\t\t\t\t\t\t`${name}: duplicate DIRTY for edge ${f.edgeId}`,\n\t\t\t\t\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tfail(f.causeId);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tst.dirty.add(f.edgeId);\n\t\t\t\tprogress(f.causeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!st.dirty.has(f.edgeId)) {\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\n\t\t\t\t\t\t\"wire-edge-group-data-before-dirty\",\n\t\t\t\t\t\t`${name}: DATA for edge ${f.edgeId} arrived before DIRTY`,\n\t\t\t\t\t\t{ edgeId: f.edgeId, causeId: f.causeId },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tfail(f.causeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (st.data.has(f.edgeId)) {\n\t\t\t\temitIssue(\n\t\t\t\t\tissue(\"wire-edge-group-duplicate-data\", `${name}: duplicate DATA for edge ${f.edgeId}`, {\n\t\t\t\t\t\tedgeId: f.edgeId,\n\t\t\t\t\t\tcauseId: f.causeId,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tfail(f.causeId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tst.data.set(f.edgeId, Uint8Array.from(f.value ?? new Uint8Array()));\n\t\t\tif (st.dirty.size === expectedIds.length && st.data.size === expectedIds.length) {\n\t\t\t\tfor (const edgeId of expectedIds) {\n\t\t\t\t\tconst value = st.data.get(edgeId);\n\t\t\t\t\tif (value)\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"release\",\n\t\t\t\t\t\t\t\t\tcauseId: f.causeId,\n\t\t\t\t\t\t\t\t\tedgeId,\n\t\t\t\t\t\t\t\t\tvalue: Uint8Array.from(value),\n\t\t\t\t\t\t\t\t} satisfies Gate,\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tst.released.add(f.causeId);\n\t\t\t\treset();\n\t\t\t} else progress(f.causeId);\n\t\t}\n\t};\n}\nfunction statusFn(expectedIds: readonly string[]): (ctx: Ctx) => void {\n\treturn (ctx) => {\n\t\tlet next =\n\t\t\tctx.state.get<WireEdgeGroupStatus>() ??\n\t\t\t({\n\t\t\t\tstate: \"idle\",\n\t\t\t\texpectedEdges: [...expectedIds],\n\t\t\t\tdirty: 0,\n\t\t\t\tdata: 0,\n\t\t\t\treleased: 0,\n\t\t\t\tissues: 0,\n\t\t\t} satisfies WireEdgeGroupStatus);\n\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\tconst ev = raw as Event;\n\t\t\tif (ev.kind === \"issue\")\n\t\t\t\tnext = { ...next, state: \"issues\", issues: next.issues + 1, lastIssue: ev.issue };\n\t\t}\n\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\tconst ev = raw as Gate;\n\t\t\tif (ev.kind === \"issue\")\n\t\t\t\tnext = { ...next, state: \"issues\", issues: next.issues + 1, lastIssue: ev.issue };\n\t\t\telse if (ev.kind === \"progress\")\n\t\t\t\tnext = {\n\t\t\t\t\t...next,\n\t\t\t\t\tstate: \"collecting\",\n\t\t\t\t\tactiveCauseId: ev.causeId,\n\t\t\t\t\tdirty: ev.dirty,\n\t\t\t\t\tdata: ev.data,\n\t\t\t\t};\n\t\t\telse\n\t\t\t\tnext = {\n\t\t\t\t\t...next,\n\t\t\t\t\tstate: \"released\",\n\t\t\t\t\tactiveCauseId: ev.causeId,\n\t\t\t\t\tdirty: expectedIds.length,\n\t\t\t\t\tdata: expectedIds.length,\n\t\t\t\t\treleased: next.released + 1,\n\t\t\t\t};\n\t\t}\n\t\tctx.state.set(next);\n\t\tctx.down([[\"DATA\", next]]);\n\t};\n}\n","/**\n * Graph-visible outbound environment adapters (D130/D132).\n *\n * Async transport work is confined to graph-local EnvironmentDrivers. Each\n * helper returns declared nodes for events/status/attempts/errors instead of a\n * hidden sink side channel.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type {\n\tDriverCancel,\n\tHttpResponse,\n\tProcessResult,\n\tWebSocketRequest,\n\tWebSocketSendResult,\n} from \"../graph/environment.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport { nextRetryDelayMs, retryPolicy, shouldRetry } from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport type {\n\tHttpRequestOf,\n\tOutboundAdapterOptions,\n\tOutboundBundle,\n\tOutboundEvent,\n\tOutboundStatus,\n\tProcessCommandOf,\n\tWebSocketSendOf,\n} from \"./environment-types.js\";\n\ninterface SendState {\n\tseq: number;\n\tcancels: Map<number, DriverCancel>;\n\ttimers: Map<number, ReturnType<typeof setTimeout>>;\n\tactive: boolean;\n\tcleanupInstalled: boolean;\n}\n\nfunction assertSourceLocal<T>(source: Node<T>): Node<T> {\n\treturn source;\n}\n\nfunction initSendState(ctx: Ctx): SendState {\n\tlet state = ctx.state.get<SendState>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tseq: 0,\n\t\t\tcancels: new Map(),\n\t\t\ttimers: new Map(),\n\t\t\tactive: true,\n\t\t\tcleanupInstalled: false,\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tstate.active = true;\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tstate.active = false;\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tfor (const cancel of state.cancels.values()) runCancel(cancel);\n\t\t\tfor (const timer of state.timers.values()) clearTimeout(timer);\n\t\t\tstate.cancels.clear();\n\t\t\tstate.timers.clear();\n\t\t});\n\t}\n\treturn state;\n}\n\nexport function runCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cancellation is best-effort and must not hide graph-visible outcomes.\n\t}\n}\n\nfunction outboundNodes<TValue, TResult>(\n\tgraph: Graph,\n\tevents: Node<OutboundEvent<TValue, TResult>>,\n\tname: string,\n): OutboundBundle<TValue, TResult> {\n\tconst status = graph.node<OutboundStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tconst current =\n\t\t\t\tctx.state.get<OutboundStatus>() ??\n\t\t\t\t({ state: \"idle\", inFlight: 0, attempt: 0, sent: 0, failed: 0 } satisfies OutboundStatus);\n\t\t\tlet next = current;\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tnext = reduceStatus(next, event as OutboundEvent<TValue, TResult>);\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"outboundStatus\" },\n\t);\n\tconst attempts = graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as OutboundEvent<TValue, TResult>;\n\t\t\t\tif (\"attempt\" in typed) ctx.down([[\"DATA\", typed.attempt]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"outboundAttempts\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as OutboundEvent<TValue, TResult>;\n\t\t\t\tif (\"error\" in typed) ctx.down([[\"DATA\", typed.error]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"outboundErrors\" },\n\t);\n\treturn { events, status, attempts, errors };\n}\n\nfunction reduceStatus<TValue, TResult>(\n\tcurrent: OutboundStatus,\n\tevent: OutboundEvent<TValue, TResult>,\n): OutboundStatus {\n\tswitch (event.kind) {\n\t\tcase \"attempt\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"running\",\n\t\t\t\tinFlight: current.inFlight + 1,\n\t\t\t\tattempt: event.attempt,\n\t\t\t};\n\t\tcase \"retry\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"waiting\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t};\n\t\tcase \"sent\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"succeeded\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tsent: current.sent + 1,\n\t\t\t\tlastDelayMs: undefined,\n\t\t\t};\n\t\tcase \"failed\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"failed\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tfailed: current.failed + 1,\n\t\t\t};\n\t\tcase \"exhausted\":\n\t\t\treturn {\n\t\t\t\t...current,\n\t\t\t\tstate: \"exhausted\",\n\t\t\t\tinFlight: Math.max(0, current.inFlight - 1),\n\t\t\t\tattempt: event.attempt,\n\t\t\t\tfailed: current.failed + 1,\n\t\t\t};\n\t\tcase \"upstream-complete\":\n\t\t\treturn { ...current, state: \"completed\" };\n\t\tcase \"upstream-error\":\n\t\t\treturn { ...current, state: \"failed\", failed: current.failed + 1 };\n\t}\n}\n\nfunction outboundNode<TValue, TResult>(\n\tgraph: Graph,\n\tsource: Node<TValue>,\n\tname: string,\n\tsend: (\n\t\tctx: Ctx,\n\t\tvalue: TValue,\n\t\tcallback: (result: { ok: true; value: TResult } | { ok: false; error: unknown }) => void,\n\t) => DriverCancel | undefined,\n\topts: OutboundAdapterOptions,\n): Node<OutboundEvent<TValue, TResult>> {\n\tconst policy = opts.retry ?? retryPolicy();\n\treturn graph.node<OutboundEvent<TValue, TResult>>(\n\t\t[assertSourceLocal(source)],\n\t\t(ctx) => {\n\t\t\tconst state = initSendState(ctx);\n\t\t\tconst start = (value: TValue, attempt: number) => {\n\t\t\t\tif (!state.active) return;\n\t\t\t\tconst id = state.seq++;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"attempt\", value, attempt } satisfies OutboundEvent<TValue, TResult>],\n\t\t\t\t]);\n\t\t\t\tconst failTerminal = (error: unknown) => {\n\t\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ kind: \"exhausted\", value, attempt, error: payload } satisfies OutboundEvent<\n\t\t\t\t\t\t\t\tTValue,\n\t\t\t\t\t\t\t\tTResult\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\tctx.down([[\"ERROR\", payload]]);\n\t\t\t\t};\n\t\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\t\tlet done = false;\n\t\t\t\ttry {\n\t\t\t\t\tcancel = send(ctx, value, (result) => {\n\t\t\t\t\t\tif (done || !state.active) return;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.cancels.delete(id);\n\t\t\t\t\t\tif (result.ok) {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{ kind: \"sent\", value, attempt, result: result.value } satisfies OutboundEvent<\n\t\t\t\t\t\t\t\t\t\tTValue,\n\t\t\t\t\t\t\t\t\t\tTResult\n\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (shouldRetry(policy, attempt)) {\n\t\t\t\t\t\t\tconst nextAttempt = attempt + 1;\n\t\t\t\t\t\t\tconst delayMs = nextRetryDelayMs(policy, nextAttempt) ?? 0;\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"retry\",\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\t\t\t\t\terror: errorPayload(result.error),\n\t\t\t\t\t\t\t\t\t} satisfies OutboundEvent<TValue, TResult>,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\t\t\t\tstate.timers.delete(id);\n\t\t\t\t\t\t\t\tif (!state.active) return;\n\t\t\t\t\t\t\t\tstart(value, nextAttempt);\n\t\t\t\t\t\t\t}, delayMs);\n\t\t\t\t\t\t\tstate.timers.set(id, timer);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"exhausted\",\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\t\t\terror: errorPayload(result.error),\n\t\t\t\t\t\t\t\t\t} satisfies OutboundEvent<TValue, TResult>,\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} catch (error) {\n\t\t\t\t\tif (!done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.cancels.delete(id);\n\t\t\t\t\t\tfailTerminal(error);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cancel === undefined) {\n\t\t\t\t\tif (!done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tfailTerminal(`${name}: missing environment driver capability`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!done && state.active) {\n\t\t\t\t\tstate.cancels.set(id, cancel);\n\t\t\t\t} else if (!state.active) {\n\t\t\t\t\trunCancel(cancel);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) start(value as TValue, 1);\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal === true) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"upstream-complete\" } satisfies OutboundEvent<TValue, TResult>],\n\t\t\t\t]);\n\t\t\t} else if (terminal !== false && terminal !== undefined) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ kind: \"upstream-error\", error: terminal } satisfies OutboundEvent<TValue, TResult>,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory: name },\n\t);\n}\n\nexport function toHttp<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trequestOf: HttpRequestOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, HttpResponse> {\n\tconst name = opts.name ?? \"toHttp\";\n\tconst events = outboundNode<T, HttpResponse>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst request = requestOf(value);\n\t\t\treturn ctx.environment().httpDriver()?.request(request, callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n\nexport function toProcess<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tcommandOf: ProcessCommandOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, ProcessResult> {\n\tconst name = opts.name ?? \"toProcess\";\n\tconst events = outboundNode<T, ProcessResult>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst command = commandOf(value);\n\t\t\treturn ctx.environment().processDriver()?.run(command, callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n\nexport function toWebSocket<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\trequest: WebSocketRequest,\n\tsendOf: WebSocketSendOf<T>,\n\topts: OutboundAdapterOptions = {},\n): OutboundBundle<T, WebSocketSendResult> {\n\tconst name = opts.name ?? \"toWebSocket\";\n\tconst events = outboundNode<T, WebSocketSendResult>(\n\t\tgraph,\n\t\tsource,\n\t\tname,\n\t\t(ctx, value, callback) => {\n\t\t\tconst driver = ctx.environment().webSocketDriver();\n\t\t\treturn driver?.send?.(request, sendOf(value), callback);\n\t\t},\n\t\topts,\n\t);\n\treturn outboundNodes(graph, events, name);\n}\n","/**\n * Graph-visible outbound environment adapters (D130/D132).\n *\n * Async transport work is confined to graph-local EnvironmentDrivers. Each\n * helper returns declared nodes for events/status/attempts/errors instead of a\n * hidden sink side channel.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type {\n\tDriverCancel,\n\tWebSocketRequest,\n\tWebSocketSend,\n\tWebSocketSessionHandle,\n} from \"../graph/environment.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\tnextRetryDelayMs,\n\ttype RetryPolicy,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { runCancel } from \"./environment-outbound.js\";\nimport type {\n\tWebSocketSessionBundle,\n\tWebSocketSessionCommand,\n\tWebSocketSessionInbound,\n\tWebSocketSessionLifecycle,\n\tWebSocketSessionOptions,\n\tWebSocketSessionOutbound,\n\tWebSocketSessionSendPolicy,\n\tWebSocketSessionStatus,\n} from \"./environment-types.js\";\n\ntype WebSocketSessionEvent =\n\t| { readonly kind: \"attempt\"; readonly attempt: number; readonly maxAttempts: number }\n\t| { readonly kind: \"open\"; readonly attempt: number }\n\t| { readonly kind: \"message\"; readonly message: WebSocketSessionInbound }\n\t| { readonly kind: \"sent\"; readonly message: WebSocketSend }\n\t| { readonly kind: \"closing\"; readonly code?: number; readonly reason?: string }\n\t| { readonly kind: \"closed\"; readonly code?: number; readonly reason?: string }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly nextAttempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"outbound\"; readonly fact: WebSocketSessionOutbound }\n\t| { readonly kind: \"error\"; readonly error: unknown; readonly attempt?: number }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\ninterface WebSocketSessionState {\n\tactive: boolean;\n\tconnected: boolean;\n\tcleanupInstalled: boolean;\n\tcurrentAttempt: number;\n\tcurrentSession: WebSocketSessionHandle | undefined;\n\tsendCancels: Map<number, DriverCancel>;\n\tliveSends: Map<number, PendingWebSocketOutbound>;\n\tpendingOutbound: PendingWebSocketOutbound[];\n\ttimers: Map<number, ReturnType<typeof setTimeout>>;\n\tseq: number;\n\toutboundSeq: number;\n}\n\ninterface PendingWebSocketOutbound {\n\treadonly seq: number;\n\treadonly message: WebSocketSend;\n}\n\nfunction initWebSocketSessionState(ctx: Ctx): WebSocketSessionState {\n\tlet state = ctx.state.get<WebSocketSessionState>();\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tactive: true,\n\t\t\tconnected: false,\n\t\t\tcleanupInstalled: false,\n\t\t\tcurrentAttempt: 0,\n\t\t\tcurrentSession: undefined,\n\t\t\tsendCancels: new Map(),\n\t\t\tliveSends: new Map(),\n\t\t\tpendingOutbound: [],\n\t\t\ttimers: new Map(),\n\t\t\tseq: 0,\n\t\t\toutboundSeq: 0,\n\t\t};\n\t\tctx.state.set(state);\n\t}\n\tstate.active = true;\n\tif (!state.cleanupInstalled) {\n\t\tstate.cleanupInstalled = true;\n\t\tctx.onDeactivation(() => {\n\t\t\tconst sendCancels = [...state.sendCancels.values()];\n\t\t\tconst timers = [...state.timers.values()];\n\t\t\tconst session = state.currentSession;\n\t\t\tstate.active = false;\n\t\t\tstate.cleanupInstalled = false;\n\t\t\tstate.connected = false;\n\t\t\tstate.currentAttempt = 0;\n\t\t\tstate.currentSession = undefined;\n\t\t\tstate.sendCancels.clear();\n\t\t\tstate.liveSends.clear();\n\t\t\tstate.pendingOutbound = [];\n\t\t\tstate.timers.clear();\n\t\t\tfor (const cancel of sendCancels) runCancel(cancel);\n\t\t\tfor (const timer of timers) clearTimeout(timer);\n\t\t\tsession?.cancel();\n\t\t});\n\t}\n\treturn state;\n}\n\nfunction closeWebSocketSessionState(\n\tstate: WebSocketSessionState,\n\tdriverAction: \"cancel\" | \"none\" = \"cancel\",\n): {\n\treadonly canceled: PendingWebSocketOutbound[];\n\treadonly session: WebSocketSessionHandle | undefined;\n} {\n\tconst session = state.currentSession;\n\tconst timers = [...state.timers.values()];\n\tconst sendCancels = [...state.sendCancels.values()];\n\tconst canceled = [...state.pendingOutbound, ...state.liveSends.values()];\n\tstate.connected = false;\n\tstate.currentAttempt = 0;\n\tstate.currentSession = undefined;\n\tstate.timers.clear();\n\tstate.sendCancels.clear();\n\tstate.pendingOutbound = [];\n\tstate.liveSends.clear();\n\tfor (const timer of timers) clearTimeout(timer);\n\tfor (const cancelSend of sendCancels) runCancel(cancelSend);\n\tif (driverAction === \"cancel\") session?.cancel();\n\treturn { canceled, session };\n}\n\nfunction cancelRetryTimers(state: WebSocketSessionState): void {\n\tfor (const timer of state.timers.values()) clearTimeout(timer);\n\tstate.timers.clear();\n}\n\nfunction cleanupWebSocketConnection(\n\tstate: WebSocketSessionState,\n\tdriverAction: \"cancel\" | \"none\" = \"cancel\",\n): PendingWebSocketOutbound[] {\n\tconst session = state.currentSession;\n\tconst sendCancels = [...state.sendCancels.values()];\n\tconst canceled = [...state.liveSends.values()];\n\tstate.connected = false;\n\tstate.currentAttempt = 0;\n\tstate.currentSession = undefined;\n\tstate.sendCancels.clear();\n\tstate.liveSends.clear();\n\tfor (const cancelSend of sendCancels) runCancel(cancelSend);\n\tif (driverAction === \"cancel\") session?.cancel();\n\treturn canceled;\n}\n\nfunction normalizeWebSocketSessionSendPolicy(\n\tpolicy: WebSocketSessionSendPolicy | undefined,\n): { readonly kind: \"reject\" } | { readonly kind: \"buffer\"; readonly maxPending: number } {\n\tif (policy?.kind !== \"buffer\") return { kind: \"reject\" };\n\tif (!Number.isFinite(policy.maxPending) || policy.maxPending < 1) {\n\t\tthrow new Error(\"webSocketSession: buffer sendPolicy requires finite maxPending >= 1\");\n\t}\n\treturn { kind: \"buffer\", maxPending: Math.floor(policy.maxPending) };\n}\n\nfunction webSocketSessionEventNode(\n\tgraph: Graph,\n\tcommand: Node<WebSocketSessionCommand>,\n\trequest: WebSocketRequest,\n\tname: string,\n\tpolicy: RetryPolicy,\n\tsendPolicy: ReturnType<typeof normalizeWebSocketSessionSendPolicy>,\n): Node<WebSocketSessionEvent> {\n\treturn graph.node<WebSocketSessionEvent>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tconst state = initWebSocketSessionState(ctx);\n\n\t\t\tconst emitOutbound = (fact: WebSocketSessionOutbound) => {\n\t\t\t\tctx.down([[\"DATA\", { kind: \"outbound\", fact } satisfies WebSocketSessionEvent]]);\n\t\t\t};\n\n\t\t\tconst emitOutboundCanceled = (\n\t\t\t\titems: readonly PendingWebSocketOutbound[],\n\t\t\t\treason: unknown,\n\t\t\t) => {\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"canceled\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\treason,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst emitOutboundRejected = (items: readonly PendingWebSocketOutbound[], error: unknown) => {\n\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: payload,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst retryOrExhaust = (attempt: number, error: unknown) => {\n\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\tconst canceled = cleanupWebSocketConnection(state);\n\t\t\t\temitOutboundCanceled(canceled, `${name}: connection cleanup`);\n\t\t\t\tif (shouldRetry(policy, attempt)) {\n\t\t\t\t\tconst nextAttempt = attempt + 1;\n\t\t\t\t\tconst delayMs = nextRetryDelayMs(policy, nextAttempt) ?? 0;\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"retry\",\n\t\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\t\tnextAttempt,\n\t\t\t\t\t\t\t\tdelayMs,\n\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\tconst timerId = state.seq++;\n\t\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\t\tstate.timers.delete(timerId);\n\t\t\t\t\t\tif (!state.active) return;\n\t\t\t\t\t\tstart(nextAttempt);\n\t\t\t\t\t}, delayMs);\n\t\t\t\t\tstate.timers.set(timerId, timer);\n\t\t\t\t} else {\n\t\t\t\t\temitOutboundRejected(state.pendingOutbound, payload);\n\t\t\t\t\tstate.pendingOutbound = [];\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{ kind: \"exhausted\", attempt, error: payload } satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst start = (attempt: number) => {\n\t\t\t\tif (\n\t\t\t\t\t!state.active ||\n\t\t\t\t\tstate.connected ||\n\t\t\t\t\tstate.currentAttempt !== 0 ||\n\t\t\t\t\tstate.timers.size > 0\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst driver = ctx.environment().webSocketDriver();\n\t\t\t\tstate.currentAttempt = attempt;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"attempt\",\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\tconst connectSession = driver?.connectSession;\n\t\t\t\tif (connectSession === undefined) {\n\t\t\t\t\tretryOrExhaust(attempt, `${name}: missing WebSocket session capability`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet session: WebSocketSessionHandle | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = connectSession.call(driver, request, (event) => {\n\t\t\t\t\t\tif (!state.active || state.currentAttempt !== attempt) return;\n\t\t\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\t\t\tconst ws = event.event;\n\t\t\t\t\t\t\tif (ws.kind === \"open\") {\n\t\t\t\t\t\t\t\tstate.connected = true;\n\t\t\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"open\", attempt } satisfies WebSocketSessionEvent]]);\n\t\t\t\t\t\t\t\tflushPending();\n\t\t\t\t\t\t\t} else if (ws.kind === \"text\" || ws.kind === \"binary\") {\n\t\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tkind: \"message\",\n\t\t\t\t\t\t\t\t\t\t\tmessage: ws satisfies WebSocketSessionInbound,\n\t\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t} else if (ws.kind === \"close\") {\n\t\t\t\t\t\t\t\tconst normalClose = ws.code === 1000;\n\t\t\t\t\t\t\t\tconst canceled = cleanupWebSocketConnection(state);\n\t\t\t\t\t\t\t\temitOutboundCanceled(canceled, `${name}: session closed`);\n\t\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tkind: \"closed\",\n\t\t\t\t\t\t\t\t\t\t\tcode: ws.code,\n\t\t\t\t\t\t\t\t\t\t\treason: ws.reason,\n\t\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t\tif (!normalClose) {\n\t\t\t\t\t\t\t\t\tretryOrExhaust(attempt, {\n\t\t\t\t\t\t\t\t\t\tkind: \"close\",\n\t\t\t\t\t\t\t\t\t\tcode: ws.code,\n\t\t\t\t\t\t\t\t\t\treason: ws.reason,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\t\t\tretryOrExhaust(attempt, event.error);\n\t\t\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\t\t\tretryOrExhaust(attempt, `${name}: connection completed`);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tretryOrExhaust(attempt, error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (session === undefined) {\n\t\t\t\t\tretryOrExhaust(attempt, `${name}: missing WebSocket session capability`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.active && state.currentAttempt === attempt) {\n\t\t\t\t\tstate.currentSession = session;\n\t\t\t\t} else {\n\t\t\t\t\tsession.cancel();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfunction sendNow(item: PendingWebSocketOutbound): void {\n\t\t\t\tif (!state.connected) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst session = state.currentSession;\n\t\t\t\tif (session === undefined) {\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: `${name}: missing WebSocket session capability`,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\terror: `${name}: missing WebSocket session capability`,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst sendId = state.seq++;\n\t\t\t\tstate.liveSends.set(sendId, item);\n\t\t\t\temitOutbound({ kind: \"sending\", seq: item.seq, message: item.message });\n\t\t\t\tlet done = false;\n\t\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tcancel = session.send(item.message, (result) => {\n\t\t\t\t\t\tif (done || !state.active || !state.liveSends.has(sendId)) return;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tstate.liveSends.delete(sendId);\n\t\t\t\t\t\tstate.sendCancels.delete(sendId);\n\t\t\t\t\t\tif (result.ok) {\n\t\t\t\t\t\t\temitOutbound({ kind: \"sent\", seq: item.seq, message: item.message });\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\"DATA\", { kind: \"sent\", message: item.message } satisfies WebSocketSessionEvent],\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst payload = errorPayload(result.error);\n\t\t\t\t\t\t\temitOutbound({\n\t\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t\t\terror: payload,\n\t\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\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} catch (error) {\n\t\t\t\t\tstate.liveSends.delete(sendId);\n\t\t\t\t\tconst payload = errorPayload(error);\n\t\t\t\t\temitOutbound({\n\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\tmessage: item.message,\n\t\t\t\t\t\terror: payload,\n\t\t\t\t\t});\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", error: payload } satisfies WebSocketSessionEvent]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (cancel !== undefined && !done && state.active && state.liveSends.has(sendId)) {\n\t\t\t\t\tstate.sendCancels.set(sendId, cancel);\n\t\t\t\t} else if (cancel !== undefined && !state.active) runCancel(cancel);\n\t\t\t}\n\n\t\t\tfunction flushPending(): void {\n\t\t\t\tconst pending = state.pendingOutbound;\n\t\t\t\tstate.pendingOutbound = [];\n\t\t\t\tfor (let index = 0; index < pending.length; index++) {\n\t\t\t\t\tconst item = pending[index];\n\t\t\t\t\tif (!state.connected || state.currentSession === undefined) {\n\t\t\t\t\t\temitOutboundCanceled(pending.slice(index), `${name}: session closed`);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsendNow(item);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst send = (message: WebSocketSend) => {\n\t\t\t\tconst item = { seq: state.outboundSeq++, message } satisfies PendingWebSocketOutbound;\n\t\t\t\tif (state.connected) {\n\t\t\t\t\tsendNow(item);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (sendPolicy.kind === \"buffer\") {\n\t\t\t\t\tif (state.pendingOutbound.length >= sendPolicy.maxPending) {\n\t\t\t\t\t\temitOutbound({\n\t\t\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\t\t\tseq: item.seq,\n\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\terror: `${name}: outbound buffer full`,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\t\t\terror: `${name}: outbound buffer full`,\n\t\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstate.pendingOutbound.push(item);\n\t\t\t\t\temitOutbound({ kind: \"queued\", seq: item.seq, message });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\temitOutbound({\n\t\t\t\t\tkind: \"rejected\",\n\t\t\t\t\tseq: item.seq,\n\t\t\t\t\tmessage,\n\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t});\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"error\",\n\t\t\t\t\t\t\terror: `${name}: session is not open`,\n\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t};\n\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst commandValue = raw as WebSocketSessionCommand;\n\t\t\t\tif (commandValue.kind === \"start\") start(1);\n\t\t\t\telse if (commandValue.kind === \"send\") send(commandValue.message);\n\t\t\t\telse {\n\t\t\t\t\tcancelRetryTimers(state);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"closing\",\n\t\t\t\t\t\t\t\tcode: commandValue.code,\n\t\t\t\t\t\t\t\treason: commandValue.reason,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t\tconst { canceled, session } = closeWebSocketSessionState(state, \"none\");\n\t\t\t\t\temitOutboundCanceled(canceled, `${name}: session closed`);\n\t\t\t\t\tsession?.close(commandValue.code, commandValue.reason);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"closed\",\n\t\t\t\t\t\t\t\tcode: commandValue.code,\n\t\t\t\t\t\t\t\treason: commandValue.reason,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionEvent,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/events`, factory: \"webSocketSessionEvents\" },\n\t);\n}\n\nfunction webSocketSessionNodes(\n\tgraph: Graph,\n\tcommand: Node<WebSocketSessionCommand>,\n\tevents: Node<WebSocketSessionEvent>,\n\tname: string,\n\tpolicy: RetryPolicy,\n): WebSocketSessionBundle {\n\tconst inbound = graph.node<WebSocketSessionInbound>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"message\") ctx.down([[\"DATA\", event.message]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/inbound`, factory: \"webSocketSessionInbound\" },\n\t);\n\tconst lifecycle = graph.node<WebSocketSessionLifecycle>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"starting\",\n\t\t\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\t\t\tmaxAttempts: event.maxAttempts,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionLifecycle,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"open\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"open\", attempt: event.attempt }]]);\n\t\t\t\t} else if (event.kind === \"sent\") {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"sent\", message: event.message }]]);\n\t\t\t\t} else if (event.kind === \"closing\" || event.kind === \"closed\") {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkind: \"retrying\",\n\t\t\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\t\t\tnextAttempt: event.nextAttempt,\n\t\t\t\t\t\t\t\tdelayMs: event.delayMs,\n\t\t\t\t\t\t\t\terror: event.error,\n\t\t\t\t\t\t\t} satisfies WebSocketSessionLifecycle,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tctx.down([[\"DATA\", event]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/lifecycle`, factory: \"webSocketSessionLifecycle\" },\n\t);\n\tconst outbound = graph.node<WebSocketSessionOutbound>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"outbound\") ctx.down([[\"DATA\", event.fact]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/outbound`, factory: \"webSocketSessionOutbound\" },\n\t);\n\tconst status = graph.node<WebSocketSessionStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<WebSocketSessionStatus>() ??\n\t\t\t\t({\n\t\t\t\t\tstate: \"idle\",\n\t\t\t\t\tattempt: 0,\n\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\tsent: 0,\n\t\t\t\t\treceived: 0,\n\t\t\t\t\terrors: 0,\n\t\t\t\t} satisfies WebSocketSessionStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"connecting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: event.maxAttempts,\n\t\t\t\t\t\tlastDelayMs: undefined,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"open\") {\n\t\t\t\t\tnext = { ...next, state: \"open\", attempt: event.attempt, lastDelayMs: undefined };\n\t\t\t\t} else if (event.kind === \"message\") {\n\t\t\t\t\tnext = { ...next, received: next.received + 1 };\n\t\t\t\t} else if (event.kind === \"sent\") {\n\t\t\t\t\tnext = { ...next, sent: next.sent + 1 };\n\t\t\t\t} else if (event.kind === \"closing\") {\n\t\t\t\t\tnext = { ...next, state: \"closing\" };\n\t\t\t\t} else if (event.kind === \"closed\") {\n\t\t\t\t\tnext = { ...next, state: \"closed\" };\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t\tlastDelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"errored\",\n\t\t\t\t\t\tattempt: event.attempt ?? next.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"exhausted\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\t...next,\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\terrors: next.errors + 1,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"webSocketSessionStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (\"error\" in event) ctx.down([[\"DATA\", event.error]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"webSocketSessionErrors\" },\n\t);\n\tconst attempts = graph.node<number>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as WebSocketSessionEvent;\n\t\t\t\tif (event.kind === \"attempt\") ctx.down([[\"DATA\", event.attempt]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/attempts`, factory: \"webSocketSessionAttempts\" },\n\t);\n\treturn {\n\t\tcommand,\n\t\tinbound,\n\t\tlifecycle,\n\t\toutbound,\n\t\tstatus,\n\t\terrors,\n\t\tattempts,\n\t\tstart: () => command.down([[\"DATA\", { kind: \"start\" }]]),\n\t\tsend: (message) =>\n\t\t\tcommand.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"send\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\ttypeof message === \"string\" || message instanceof Uint8Array\n\t\t\t\t\t\t\t\t? { data: message }\n\t\t\t\t\t\t\t\t: message,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t]),\n\t\tclose: (code, reason) => command.down([[\"DATA\", { kind: \"close\", code, reason }]]),\n\t};\n}\n\n/**\n * Create a graph-visible D133 WebSocket SessionBundle.\n *\n * The convenience start/send/close methods publish command facts only; hidden\n * session state is driven by the command node and graph-local EnvironmentDrivers.\n */\nexport function webSocketSession(\n\tgraph: Graph,\n\trequest: WebSocketRequest,\n\topts: WebSocketSessionOptions = {},\n): WebSocketSessionBundle {\n\tconst name = opts.name ?? \"webSocketSession\";\n\tconst policy = opts.retry ?? retryPolicy();\n\tconst sendPolicy = normalizeWebSocketSessionSendPolicy(opts.sendPolicy);\n\tconst command = graph.node<WebSocketSessionCommand>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"webSocketSessionCommand\",\n\t});\n\tconst events = webSocketSessionEventNode(graph, command, request, name, policy, sendPolicy);\n\treturn webSocketSessionNodes(graph, command, events, name, policy);\n}\n","/**\n * The shared reactiveCollection core (CSP-2.8, D60).\n *\n * Every reactive data structure (list/map/index/log) is `collectionCore(backend) + a typed method\n * surface` (D60 #5). The core owns the TWO output ports and nothing else:\n *\n * - BACKEND — the single materialized state (D60 #1): a plain mutable object with a monotonic\n * `version` + a `snapshot()`. It applies deltas and IS the materialized state; there is NO ACC\n * node and NO effect bridge re-deriving it (the misdesign D60 rejected — the backend already\n * integrates, its cost is intrinsic). The backend is a closure object, not a graph node, so its\n * durability is structural (survives last-subscriber disconnect; node ROM/RAM is moot, D60 #1).\n *\n * - DELTA port (D60 #2a) — an always-on bare source ({@link CollectionCore.delta}); each mutation\n * pushes ONE change payload (O(1)/mutation). Downstream watches events anytime. It is the\n * structure's BACKBONE: the snapshot node declares it as its dep (D60 reactiveList topology).\n *\n * - SNAPSHOT port (D60 #2b) — a pull-mode node ({@link CollectionCore.snapshot}, R-pull/D269) that\n * is QUIET by default and, on a cone-routed PULL demand, LAZILY reads `backend.snapshot()`\n * (one O(n) materialization) and pushes it once, then re-quiets. The O(n) build happens ONLY on\n * demand — never eagerly per mutation (D60 #2b: lazy is P·O(n), not M·O(n)). It has NO value of\n * its own — its fn reads the backend on demand, so the backend stays the single source of truth\n * (D60 #3). Coalesce-on-no-change is free: the delta-dep's DIRTY/DATA arms the pull node via\n * R-pull's quiet-absorb accounting; a demand with no intervening delta emits no duplicate DATA.\n *\n * Demand path: a downstream consumer issues `ctx.upNext([[\"PULL\", { pullId: core.pullId }]])`\n * (boundary-deferred self-demand, R-up-routing/D269) — it needs the snapshot node upstream in its\n * declared cone, NOT its reference. Cold-start (a demand before any mutation) emits no DATA; for an\n * initial/imperative read use the structure's synchronous quick-read (the deliberately-non-reactive\n * peek, D60) — the reactive pull serves the watch-delta-then-demand pattern.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch } from \"../../ctx/types.js\";\nimport type { Dispatcher } from \"../../dispatcher/index.js\";\nimport { Node, releaseRuntimeOfNode } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport { type GraphCheckpointJson, registerBackendStateContributor } from \"../checkpoint.js\";\nimport type { Graph } from \"../graph.js\";\nimport type { Operator } from \"../operators.js\";\nimport type { ViewCachePolicy } from \"../policies/types.js\";\n\n/** The materialized-state contract a structure's backend must satisfy (D60 #1). */\nexport interface CollectionBackend<S> {\n\t/** Monotonic mutation counter; advances on every visible state change (idempotency, D49). */\n\treadonly version: number;\n\t/** A fresh defensive materialization of the current state (D60: first-cut defensive copy). */\n\tsnapshot(): S;\n}\n\nexport interface CollectionCoreOptions {\n\t/** Debug/inspection name; the delta/snapshot nodes derive `${name}.delta` / `${name}.snapshot`. */\n\tname?: string;\n\t/** Dispatcher for the core's nodes (default = process-global, D26). */\n\tdispatcher?: Dispatcher;\n\t/** Graph funnel for describe-visible input folds (D61). Required by *From/attach methods. */\n\tgraph?: Graph;\n}\n\nexport interface CollectionCore<S, C> {\n\t/** DELTA backbone (D60 #2a): a bare source; every {@link CollectionCore.emit} pushes one change. */\n\treadonly delta: Node<C>;\n\t/** SNAPSHOT pull node (D60 #2b): demand via `ctx.upNext([[\"PULL\", { pullId }]])`; lazy O(n) on demand. */\n\treadonly snapshot: Node<S>;\n\t/** The snapshot node's pullId — the author writes it verbatim into the demander's fn (D269). */\n\treadonly pullId: symbol;\n\t/** Push one delta event (the imperative path: a method mutates the backend, then calls this). */\n\temit(change: C): void;\n\t/**\n\t * D54 widening: fold an in-graph producer `src` into the backend. `apply` mutates the backend +\n\t * `emit`s the change(s). The folder is a DECLARED-dep node (describe shows `src → folder`, NOT a\n\t * D45 island); its emit is the structure's plumbing (D54-sanctioned). Returns a disposer.\n\t */\n\tbindSource<V>(src: Node<V>, apply: (value: V) => void): () => void;\n}\n\n/**\n * Public D121 collection-view surface. A view is a derived surface: `delta` is the pushed update\n * port, `snapshot` is a lazy pull node, and neither port is writable authority.\n */\nexport interface ReactiveView<C, S> {\n\t/** Derived DELTA/update stream for the view. For light views this is recomputed from the parent backend. */\n\treadonly delta: Node<C>;\n\t/** Derived SNAPSHOT pull node: demand via `pullId` to materialize the current view. */\n\treadonly snapshot: Node<S>;\n\t/** The snapshot node's pullId (R-pull/D269), minted per view instance. */\n\treadonly pullId: symbol;\n\t/** Release memoized/light-view resources owned by the parent collection. */\n\tdispose(): void;\n}\n\ninterface LightReactiveViewOptions<S> extends CollectionCoreOptions {\n\treadonly factory: string;\n\treadonly materializeSnapshot: () => S;\n\treadonly onDispose?: () => void;\n}\n\ninterface CollectionRestoreSpec {\n\treadonly deltaRef: string;\n\treadonly snapshotRef: string;\n\treadonly config?: GraphCheckpointJson;\n\treadonly backendState: () => unknown;\n}\n\nfunction validateViewCacheMaxEntries(policy: ViewCachePolicy | undefined): number | undefined {\n\tconst maxEntries = policy?.maxEntries;\n\tif (maxEntries === undefined) return undefined;\n\tif (!Number.isInteger(maxEntries) || maxEntries < 0) {\n\t\tthrow new RangeError(`viewCache.maxEntries must be a non-negative integer (got ${maxEntries})`);\n\t}\n\treturn maxEntries;\n}\n\n/**\n * Internal D80 memo manager for derived views. Eviction drops only the structure's memo lookup;\n * returned ReactiveView handles remain live until explicitly disposed or their parent releases all\n * live views.\n */\nexport class ViewMemoCache<K, V extends { dispose(): void }> {\n\tprivate readonly maxEntries: number | undefined;\n\tprivate readonly equals: (a: K, b: K) => boolean;\n\tprivate readonly memo: Array<{ key: K; value: V }> = [];\n\tprivate readonly live = new Set<V>();\n\n\tconstructor(policy: ViewCachePolicy | undefined, equals: (a: K, b: K) => boolean = Object.is) {\n\t\tthis.maxEntries = validateViewCacheMaxEntries(policy);\n\t\tthis.equals = equals;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst index = this.memo.findIndex((entry) => this.equals(entry.key, key));\n\t\tif (index < 0) return undefined;\n\t\tconst [entry] = this.memo.splice(index, 1);\n\t\tif (entry === undefined) return undefined;\n\t\tthis.memo.push(entry);\n\t\treturn entry.value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tthis.deleteValue(value);\n\t\tthis.live.add(value);\n\t\tif (this.maxEntries === 0) return;\n\t\tthis.memo.push({ key, value });\n\t\twhile (this.maxEntries !== undefined && this.memo.length > this.maxEntries) {\n\t\t\tthis.memo.shift();\n\t\t}\n\t}\n\n\tdeleteValue(value: V): void {\n\t\tfor (let i = this.memo.length - 1; i >= 0; i -= 1) {\n\t\t\tif (this.memo[i]?.value === value) this.memo.splice(i, 1);\n\t\t}\n\t\tthis.live.delete(value);\n\t}\n\n\tdisposeAll(): void {\n\t\tfor (const view of [...this.live]) view.dispose();\n\t\tthis.memo.length = 0;\n\t\tthis.live.clear();\n\t}\n}\n\n/**\n * Build a D121 first-cut light view. The view declares `parent.delta -> view.delta ->\n * view.snapshot`; the pushed `delta` forwards parent delta events as the view's arm/update stream,\n * while `snapshot` reads the parent collection backend through the supplied materializer on demand.\n * No writable state/cache is exposed (D120).\n */\nexport function lightReactiveView<C, S>(\n\tparentDelta: Node<unknown>,\n\topts: LightReactiveViewOptions<S>,\n): ReactiveView<C, S> {\n\tconst { dispatcher, factory, graph, materializeSnapshot, name, onDispose } = opts;\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst group = graph?.topologyGroup({ name: name ?? factory });\n\tconst deltaBody = (ctx: Ctx): void => {\n\t\tfor (const change of (depBatch(ctx, 0) ?? []) as readonly C[]) {\n\t\t\tctx.down([[\"DATA\", change]]);\n\t\t}\n\t};\n\tconst delta = group\n\t\t? group.node<C>([parentDelta], deltaBody, {\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_view_delta\", factory },\n\t\t\t\tpartial: true,\n\t\t\t})\n\t\t: new Node<C>([parentDelta], deltaBody, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tpartial: true,\n\t\t\t});\n\n\tconst pullId = Symbol(name ? `${name}.snapshot` : `${factory}.snapshot`);\n\tconst snapshotBody = (ctx: Ctx): void => {\n\t\ttry {\n\t\t\tctx.down([[\"DATA\", materializeSnapshot()]]);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, `${factory}.snapshot materializer failed`)]]);\n\t\t}\n\t};\n\tconst snapshot = group\n\t\t? group.node<S>([delta as Node<unknown>], snapshotBody, {\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_view_snapshot\", factory },\n\t\t\t\tpartial: true,\n\t\t\t\tpullId,\n\t\t\t})\n\t\t: new Node<S>([delta as Node<unknown>], snapshotBody, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tpartial: true,\n\t\t\t\tpullId,\n\t\t\t});\n\n\tlet disposed = false;\n\treturn {\n\t\tdelta,\n\t\tsnapshot,\n\t\tpullId,\n\t\tdispose(): void {\n\t\t\tif (disposed) return;\n\t\t\tif (group) {\n\t\t\t\tgroup.release({ reason: factory });\n\t\t\t} else {\n\t\t\t\treleaseRuntimeOfNode(delta as Node<unknown>);\n\t\t\t\treleaseRuntimeOfNode(snapshot as Node<unknown>);\n\t\t\t}\n\t\t\tdisposed = true;\n\t\t\tonDispose?.();\n\t\t},\n\t};\n}\n\n/**\n * Build the shared core for a reactive structure (D60). `factory` names the nodes for describe\n * (D6/D51 auto-discovery). The structure passes its `backend` (any {@link CollectionBackend}) and\n * layers a typed method surface on top.\n */\nexport function collectionCore<S, C>(\n\tbackend: CollectionBackend<S>,\n\tfactory: string,\n\topts: CollectionCoreOptions = {},\n\trestore?: CollectionRestoreSpec,\n): CollectionCore<S, C> {\n\tconst { name, dispatcher, graph } = opts;\n\tconst base: { dispatcher?: Dispatcher } = dispatcher ? { dispatcher } : {};\n\tlet bindSeq = 0;\n\n\t// DELTA backbone: a bare source (D60 #2a / review #2 — node([], null), no `initial`, so a late\n\t// subscriber gets no fake \"initial change\"; state is the snapshot port's job).\n\tconst delta = graph\n\t\t? graph.node<C>([], null, {\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_delta\", collection: factory },\n\t\t\t\t...(restore ? { restore: { ref: restore.deltaRef, config: restore.config } } : {}),\n\t\t\t})\n\t\t: new Node<C>([], null, {\n\t\t\t\t...base,\n\t\t\t\tfactory: `${factory}.delta`,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t});\n\n\t// SNAPSHOT pull node: dep=[delta] (the backbone arms it via quiet-absorb so coalesce is free,\n\t// D60). The fn IGNORES the delta value — it reads `backend.snapshot()` on demand (D60 #3). The\n\t// pullId is a unique Symbol (R-pull/D269: matched by identity, zero collision with pause locks).\n\t// `partial:true`: the fn does not need the delta's value, so it must not gate on \"all deps\n\t// settled\" — it fires whenever armed (a mutation since the last delivery).\n\tconst pullId = Symbol(name ? `${name}.snapshot` : `${factory}.snapshot`);\n\tlet deliveredVersion = backend.version;\n\tconst snapFn = (ctx: Ctx): void => {\n\t\tif (ctx.pull !== undefined && backend.version === deliveredVersion) return;\n\t\tdeliveredVersion = backend.version;\n\t\tctx.down([[\"DATA\", backend.snapshot()]]);\n\t};\n\tconst snapshot = graph\n\t\t? graph.node<S>([delta as Node<unknown>], snapFn, {\n\t\t\t\tpullId,\n\t\t\t\tpartial: true,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot\", collection: factory },\n\t\t\t\t...(restore ? { restore: { ref: restore.snapshotRef, config: restore.config } } : {}),\n\t\t\t})\n\t\t: new Node<S>([delta as Node<unknown>], snapFn, {\n\t\t\t\t...base,\n\t\t\t\tpullId,\n\t\t\t\tpartial: true,\n\t\t\t\tfactory: `${factory}.snapshot`,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t});\n\n\tif (restore !== undefined) {\n\t\tregisterBackendStateContributor(delta as Node<unknown>, restore.backendState);\n\t}\n\n\tfunction emit(change: C): void {\n\t\t// External tier-3 emit → the substrate synthesizes the leading DIRTY (R-dirty-before-data),\n\t\t// which the quiet snapshot node absorbs (R-pull) and uses to arm its next demand delivery.\n\t\tdelta.down([[\"DATA\", change]]);\n\t}\n\n\tfunction bindSource<V>(src: Node<V>, apply: (value: V) => void): () => void {\n\t\tif (graph === undefined)\n\t\t\tthrow new Error(\n\t\t\t\t\"collectionCore.bindSource requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t);\n\t\t// A graph-bound declared-dep folder (effect-shaped): reads each src batch value, applies it\n\t\t// to the backend (apply mutates + emits the delta). src → folder is a real edge describe\n\t\t// shows (D54/D61), not an internal subscribe island.\n\t\tconst op: Operator<V, void> = {\n\t\t\tfactory: `${factory}.bindSource`,\n\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\ttry {\n\t\t\t\t\tif (b) for (const v of b) apply(v as V);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"collectionCore.bindSource failed\")]]);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t\tconst folder = graph.initNode(op, [src], {\n\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\tmeta: { kind: \"collection_bind_source\", collection: factory },\n\t\t});\n\t\treturn graph.retain(folder, { reason: `${factory}.bindSource` });\n\t}\n\n\treturn { delta, snapshot, pullId, emit, bindSource };\n}\n","/**\n * Reactive dual-key index (CSP-2.8, D54/D60) — unique primary key, rows sorted by (secondary, primary).\n *\n * Shape = the shared {@link collectionCore} two ports over a sorted-array + parallel-Map BACKEND\n * (D60). The SNAPSHOT port delivers the ordered `IndexRow[]`. Secondary/reverse lookup = \"Z\"\n * (review #4): `has`/`get`/`rangeByPrimary` are SYNCHRONOUS point-reads over the backend's parallel\n * Map (NOT topology, like `.cache`); `byPrimary` is an OPTIONAL reactive derived over the delta\n * backbone (a pushed primary→value map), LAZILY created on first access (no default keepalive,\n * R-rom-ram). The two coexist: the derived is the reactive reverse-lookup port; the sync reads are\n * the point query.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount, depLatest } from \"../../ctx/types.js\";\nimport { Node, node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport type { Operator } from \"../operators.js\";\nimport type { OrderedCapacityPolicy, ReactiveOpt, ViewCachePolicy } from \"../policies/types.js\";\nimport type { IndexChange } from \"./change.js\";\nimport {\n\ttype CollectionCore,\n\ttype CollectionCoreOptions,\n\tcollectionCore,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport type ReactiveIndexOpt<T> = ReactiveOpt<T>;\nexport type ReactiveIndexCapacityOrder = \"secondary\" | \"primary\" | \"lru\";\n\nexport interface ReactiveIndexCapacityPolicy\n\textends OrderedCapacityPolicy<ReactiveIndexCapacityOrder> {}\n\nexport interface ReactiveIndexOptions extends CollectionCoreOptions {\n\t/**\n\t * D73 explicit capacity policy: no implicit eviction default.\n\t * `order` chooses eviction semantics and `maxSize` may be static or node-valued (D68).\n\t */\n\treadonly capacity?: ReactiveIndexCapacityPolicy;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\treadonly viewCache?: ViewCachePolicy;\n}\n\nexport interface IndexRow<K, V = unknown> {\n\treadonly primary: K;\n\treadonly secondary: unknown;\n\treadonly value: V;\n}\n\nexport interface ReactiveIndex<K, V = unknown> {\n\treadonly delta: Node<IndexChange<K, V>>;\n\t/** SNAPSHOT pull node: demand → rows sorted by (secondary, primary) (lazy O(n)). */\n\treadonly snapshot: Node<readonly IndexRow<K, V>[]>;\n\treadonly pullId: symbol;\n\t/** Row count (O(1)). Sync non-reactive read. */\n\treadonly size: number;\n\t/** O(1) primary-key existence. Sync read (Z). */\n\thas(primary: K): boolean;\n\t/** O(1) value lookup by primary key. Sync read (Z). */\n\tget(primary: K): V | undefined;\n\t/** Values whose primary sorts within `[start, end)`, ascending primary order. Sync read (Z). */\n\trangeByPrimary(start: K, end: K): V[];\n\t/**\n\t * D121 light range view over the primary axis. `delta` forwards parent index mutations, and\n\t * `snapshot` is a pull node that materializes the current range on demand.\n\t */\n\trange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]>;\n\t/** Ordered rows (fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly IndexRow<K, V>[];\n\t/** Primary→value map (fresh copy). Sync non-reactive read. */\n\ttoPrimaryMap(): ReadonlyMap<K, V>;\n\t/**\n\t * OPTIONAL reactive reverse-lookup port (Z): a derived primary→value map, pushed on every\n\t * mutation. Lazily created on first access (no keepalive — live only while subscribed). Use the\n\t * synchronous {@link ReactiveIndex.get} for a one-shot point query.\n\t */\n\treadonly byPrimary: Node<ReadonlyMap<K, V>>;\n\t/** Insert/replace a row. Returns `true` if a NEW row was inserted (primary was absent). */\n\tupsert(primary: K, secondary: unknown, value: V): boolean;\n\t/** Bulk upsert; one delta per row. No-op if empty. */\n\tupsertMany(rows: Iterable<{ primary: K; secondary: unknown; value: V }>): void;\n\tdelete(primary: K): void;\n\t/** Bulk delete; one delta event. No-op if nothing removed. */\n\tdeleteMany(primaries: Iterable<K>): void;\n\tclear(): void;\n\t/** D54 widening: every row from `src` is upserted. Returns a disposer. */\n\tupsertFrom(src: Node<{ primary: K; secondary: unknown; value: V }>): () => void;\n\tdispose(): void;\n}\n\n// ── ordering helpers (pure; backend-internal) ──\nfunction cmpOrd(a: unknown, b: unknown): number {\n\tif (a === b) return 0;\n\tconst ta = typeof a;\n\tif (\n\t\tta === typeof b &&\n\t\t(ta === \"number\" || ta === \"string\" || ta === \"boolean\" || ta === \"bigint\")\n\t) {\n\t\tconst ax = a as number | string;\n\t\tconst bx = b as number | string;\n\t\treturn ax < bx ? -1 : ax > bx ? 1 : 0;\n\t}\n\treturn String(a).localeCompare(String(b));\n}\nfunction compareRows<K, V>(a: IndexRow<K, V>, b: IndexRow<K, V>): number {\n\tconst c = cmpOrd(a.secondary, b.secondary);\n\treturn c !== 0 ? c : cmpOrd(a.primary, b.primary);\n}\nfunction bisectLeft<K, V>(rows: readonly IndexRow<K, V>[], row: IndexRow<K, V>): number {\n\tlet lo = 0;\n\tlet hi = rows.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >> 1;\n\t\tif (compareRows(rows[mid] as IndexRow<K, V>, row) < 0) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** Default sorted-array + parallel-Map backend (D60 first-cut; B-tree/persistent backend deferred). */\nclass IndexBackend<K, V> {\n\tprivate _version = 0;\n\tprivate readonly buf: IndexRow<K, V>[] = [];\n\tprivate readonly byKey = new Map<K, IndexRow<K, V>>();\n\tprivate readonly trackLru: boolean;\n\n\tconstructor(trackLru: boolean, initialRows: readonly IndexRow<K, V>[] = []) {\n\t\tthis.trackLru = trackLru;\n\t\tfor (const row of initialRows) {\n\t\t\tthis.upsert(row.primary, row.secondary, row.value);\n\t\t}\n\t\tthis._version = 0;\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\thas(primary: K): boolean {\n\t\tconst row = this.byKey.get(primary);\n\t\tif (row === undefined) return false;\n\t\tthis.touchLru(row);\n\t\treturn true;\n\t}\n\tget(primary: K): V | undefined {\n\t\tconst row = this.byKey.get(primary);\n\t\tif (row === undefined) return undefined;\n\t\tthis.touchLru(row);\n\t\treturn row.value;\n\t}\n\n\tprivate touchLru(row: IndexRow<K, V>): void {\n\t\tif (!this.trackLru) return;\n\t\tthis.byKey.delete(row.primary);\n\t\tthis.byKey.set(row.primary, row);\n\t}\n\n\tprivate removeRow(row: IndexRow<K, V>): void {\n\t\tconst start = bisectLeft(this.buf, row);\n\t\tfor (\n\t\t\tlet i = start;\n\t\t\ti < this.buf.length && compareRows(this.buf[i] as IndexRow<K, V>, row) === 0;\n\t\t\ti++\n\t\t) {\n\t\t\tif (this.buf[i] === row) {\n\t\t\t\tthis.buf.splice(i, 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst fallback = this.buf.indexOf(row);\n\t\tif (fallback >= 0) {\n\t\t\tthis.buf.splice(fallback, 1);\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"reactiveIndex: internal row index desynchronized\");\n\t}\n\n\tupsert(primary: K, secondary: unknown, value: V): boolean {\n\t\tconst existing = this.byKey.get(primary);\n\t\tconst row: IndexRow<K, V> = { primary, secondary, value };\n\t\tif (existing !== undefined) {\n\t\t\tthis.removeRow(existing);\n\t\t\tthis.byKey.delete(primary);\n\t\t}\n\t\tthis.buf.splice(bisectLeft(this.buf, row), 0, row);\n\t\tthis.byKey.set(primary, row);\n\t\tthis._version += 1;\n\t\treturn existing === undefined;\n\t}\n\n\tdelete(primary: K): boolean {\n\t\tconst existing = this.byKey.get(primary);\n\t\tif (existing === undefined) return false;\n\t\tthis.removeRow(existing);\n\t\tthis.byKey.delete(primary);\n\t\tthis._version += 1;\n\t\treturn true;\n\t}\n\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis.byKey.clear();\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\trangeByPrimary(start: K, end: K): V[] {\n\t\tif (cmpOrd(start, end) >= 0) return [];\n\t\tconst rows = [...this.byKey.entries()].filter(\n\t\t\t([p]) => cmpOrd(p, start) >= 0 && cmpOrd(p, end) < 0,\n\t\t);\n\t\trows.sort(([a], [b]) => cmpOrd(a, b));\n\t\treturn rows.map(([, r]) => r.value);\n\t}\n\n\tevictOneForCapacity(order: ReactiveIndexCapacityOrder, maxSize?: number): K | undefined {\n\t\tif (maxSize === undefined) return undefined;\n\t\tif (!Number.isInteger(maxSize) || maxSize < 1)\n\t\t\tthrow new RangeError(`reactiveIndex: maxSize must be a positive integer (got ${maxSize})`);\n\t\tconst overflow = this.buf.length - maxSize;\n\t\tif (overflow <= 0) return undefined;\n\n\t\tswitch (order) {\n\t\t\tcase \"secondary\": {\n\t\t\t\tconst row = this.buf[0] as IndexRow<K, V> | undefined;\n\t\t\t\tif (row === undefined) return undefined;\n\t\t\t\tthis.buf.shift();\n\t\t\t\tthis.byKey.delete(row.primary);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn row.primary;\n\t\t\t}\n\t\t\tcase \"primary\": {\n\t\t\t\tlet victim: K | undefined;\n\t\t\t\tfor (const key of this.byKey.keys()) {\n\t\t\t\t\tif (victim === undefined || cmpOrd(key, victim) < 0) victim = key;\n\t\t\t\t}\n\t\t\t\tif (victim === undefined) return undefined;\n\t\t\t\tconst row = this.byKey.get(victim);\n\t\t\t\tif (row !== undefined) this.removeRow(row);\n\t\t\t\tthis.byKey.delete(victim);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn victim;\n\t\t\t}\n\t\t\tcase \"lru\": {\n\t\t\t\tconst oldest = this.byKey.keys().next().value as K | undefined;\n\t\t\t\tif (oldest === undefined) return undefined;\n\t\t\t\tconst row = this.byKey.get(oldest);\n\t\t\t\tif (row !== undefined) this.removeRow(row);\n\t\t\t\tthis.byKey.delete(oldest);\n\t\t\t\tthis._version += 1;\n\t\t\t\treturn oldest;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tthrow new Error(`reactiveIndex: unknown capacity order '${String(order)}'`);\n\t\t\t}\n\t\t}\n\t}\n\n\tsnapshot(): readonly IndexRow<K, V>[] {\n\t\treturn [...this.buf];\n\t}\n\ttoPrimaryMap(): ReadonlyMap<K, V> {\n\t\tconst m = new Map<K, V>();\n\t\tfor (const r of this.buf) m.set(r.primary, r.value);\n\t\treturn m;\n\t}\n}\n\nfunction assertCheckpointableIndexRows(rows: readonly IndexRow<unknown, unknown>[]): void {\n\tfor (const [i, row] of rows.entries()) {\n\t\tconst primary = row.primary;\n\t\tif (\n\t\t\tprimary === null ||\n\t\t\ttypeof primary === \"string\" ||\n\t\t\ttypeof primary === \"number\" ||\n\t\t\ttypeof primary === \"boolean\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(\n\t\t\t`reactiveIndex checkpoint backendState[${i}].primary must be a JSON primitive primary key for D160 restore`,\n\t\t);\n\t}\n}\n\n/**\n * Create a reactive dual-key index (D54/D60). DELTA + lazy pull SNAPSHOT + pullId via\n * {@link collectionCore}; this layer adds the sorted backend + Z reverse-lookup surface.\n */\nexport function reactiveIndex<K, V = unknown>(\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\treturn createReactiveIndex(options);\n}\n\n/** @internal D160 restore path: seed the backend without replaying public deltas. */\nexport function restoreReactiveIndexFromBackendState<K, V = unknown>(\n\tinitialRows: readonly IndexRow<K, V>[],\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\treturn createReactiveIndex(options, initialRows);\n}\n\nfunction createReactiveIndex<K, V = unknown>(\n\toptions: ReactiveIndexOptions = {},\n\tinitialRows: readonly IndexRow<K, V>[] = [],\n): ReactiveIndex<K, V> {\n\tconst { capacity, graph, dispatcher, name } = options;\n\tconst lruEnabled = capacity?.order === \"lru\";\n\tconst backend = new IndexBackend<K, V>(lruEnabled, initialRows);\n\tconst core: CollectionCore<readonly IndexRow<K, V>[], IndexChange<K, V>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveIndex\",\n\t\toptions,\n\t\tgraph !== undefined && name !== undefined && capacity === undefined\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveIndex.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveIndex.snapshot\",\n\t\t\t\t\tbackendState: () => {\n\t\t\t\t\t\tconst rows = backend.snapshot();\n\t\t\t\t\t\tassertCheckpointableIndexRows(rows);\n\t\t\t\t\t\treturn rows;\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tconst rangeMemo = new ViewMemoCache<\n\t\treadonly [K, K],\n\t\tReactiveView<IndexChange<K, V>, readonly V[]>\n\t>(options.viewCache, ([aStart, aEnd], [bStart, bEnd]) => {\n\t\treturn cmpOrd(aStart, bStart) === 0 && cmpOrd(aEnd, bEnd) === 0;\n\t});\n\tlet bindSeq = 0;\n\tlet rangeSeq = 0;\n\tlet capacityPolicy: Node<number> | undefined;\n\tlet apply: Node<IndexChange<K, V>> | undefined;\n\tlet releaseApply = () => {};\n\n\tfunction isNodeOpt<T>(x: ReactiveIndexOpt<T>): x is Node<T> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveIndex: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction enforceCapacity(): void {\n\t\tif (currentCapacityOrder === undefined) return;\n\t\tfor (;;) {\n\t\t\tconst primary = backend.evictOneForCapacity(currentCapacityOrder, currentMaxSize);\n\t\t\tif (primary === undefined) return;\n\t\t\tcore.emit({ kind: \"delete\", primary });\n\t\t}\n\t}\n\n\tconst applyBody = (ctx: Ctx): void => {\n\t\tconst deps = apply?.deps ?? [];\n\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep === capacityPolicy) {\n\t\t\t\tconst latest = depLatest(ctx, i);\n\t\t\t\tif (latest !== undefined) currentMaxSize = validateMaxSize(latest as number);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const r of (depBatch(ctx, i) ?? []) as readonly {\n\t\t\t\t\tprimary: K;\n\t\t\t\t\tsecondary: unknown;\n\t\t\t\t\tvalue: V;\n\t\t\t\t}[]) {\n\t\t\t\t\tbackend.upsert(r.primary, r.secondary, r.value);\n\t\t\t\t\tcore.emit({ kind: \"upsert\", primary: r.primary, secondary: r.secondary, value: r.value });\n\t\t\t\t\tenforceCapacity();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tenforceCapacity();\n\t};\n\n\tfunction ensureApply(): Node<IndexChange<K, V>> {\n\t\tif (apply !== undefined) return apply;\n\t\tconst op: Operator<unknown, IndexChange<K, V>> = {\n\t\t\tfactory: \"reactiveIndex.capacityPolicy\",\n\t\t\tbody: applyBody,\n\t\t\topts: { partial: true },\n\t\t};\n\t\tconst deps = capacityPolicy ? [capacityPolicy as Node<unknown>] : [];\n\t\tapply = graph\n\t\t\t? graph.initNode(op, deps, {\n\t\t\t\t\tname: name ? `${name}.capacityPolicy` : undefined,\n\t\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveIndex\" },\n\t\t\t\t})\n\t\t\t: new Node<IndexChange<K, V>>(deps, op.body, {\n\t\t\t\t\t...base,\n\t\t\t\t\tfactory: \"reactiveIndex.capacityPolicy\",\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tname: name ? `${name}.capacityPolicy` : undefined,\n\t\t\t\t});\n\t\treleaseApply = graph\n\t\t\t? graph.retain(apply, { reason: \"reactiveIndex.capacityPolicy\" })\n\t\t\t: apply.subscribe(() => {});\n\t\treturn apply;\n\t}\n\n\tlet currentMaxSize: number | undefined;\n\tconst currentCapacityOrder: ReactiveIndexCapacityOrder | undefined = capacity?.order;\n\tif (capacity !== undefined) {\n\t\tif (\n\t\t\tcurrentCapacityOrder !== \"secondary\" &&\n\t\t\tcurrentCapacityOrder !== \"primary\" &&\n\t\t\tcurrentCapacityOrder !== \"lru\"\n\t\t) {\n\t\t\tthrow new Error(\"reactiveIndex: capacity.order must be one of secondary|primary|lru (D73)\");\n\t\t}\n\n\t\tconst maxSize = capacity.maxSize;\n\t\tif (isNodeOpt(maxSize) && graph === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"reactiveIndex capacity.maxSize Node option requires options.graph so the policy edge is describe-visible (D73)\",\n\t\t\t);\n\t\t}\n\n\t\tcapacityPolicy = isNodeOpt(maxSize)\n\t\t\t? maxSize\n\t\t\t: graph\n\t\t\t\t? graph.initNode<number, number>(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfactory: \"reactiveIndex.maxSizePolicy\",\n\t\t\t\t\t\t\tbody: () => {},\n\t\t\t\t\t\t\topts: { initial: validateMaxSize(maxSize) },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[],\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: name ? `${name}.maxSizePolicy` : undefined,\n\t\t\t\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveIndex\", policy: \"maxSize\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\n\t\tif (!isNodeOpt(maxSize)) currentMaxSize = validateMaxSize(maxSize);\n\n\t\tif (capacityPolicy instanceof Node) ensureApply();\n\t}\n\n\t// Lazy reactive reverse-lookup port (Z): a delta-driven pushed primary→value map. Created on\n\t// first access so an index that never uses it pays nothing (no keepalive — R-rom-ram).\n\tlet byPrimaryNode: Node<ReadonlyMap<K, V>> | undefined;\n\tfunction getByPrimary(): Node<ReadonlyMap<K, V>> {\n\t\tif (byPrimaryNode === undefined) {\n\t\t\tbyPrimaryNode = node<ReadonlyMap<K, V>>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\t// pushed reverse-lookup: re-read the backend's primary map on each delta (the\n\t\t\t\t\t// structure's own backend, D60 #1 — not a foreign .cache peek).\n\t\t\t\t\tctx.down([[\"DATA\", backend.toPrimaryMap()]]);\n\t\t\t\t},\n\t\t\t\t{ factory: \"reactiveIndex.byPrimary\", partial: true },\n\t\t\t);\n\t\t}\n\t\treturn byPrimaryNode;\n\t}\n\n\tfunction getRange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]> {\n\t\tconst key = [start, end] as const;\n\t\tconst hit = rangeMemo.get(key);\n\t\tif (hit !== undefined) return hit;\n\t\tconst materialize = (): readonly V[] => backend.rangeByPrimary(start, end);\n\t\tlet view: ReactiveView<IndexChange<K, V>, readonly V[]>;\n\t\tview = lightReactiveView<IndexChange<K, V>, readonly V[]>(core.delta as Node<unknown>, {\n\t\t\t...options,\n\t\t\tfactory: \"reactiveIndex.range\",\n\t\t\tname: name ? `${name}.range#${rangeSeq++}` : undefined,\n\t\t\tmaterializeSnapshot: materialize,\n\t\t\tonDispose: () => {\n\t\t\t\trangeMemo.deleteValue(view);\n\t\t\t},\n\t\t});\n\t\trangeMemo.set(key, view);\n\t\treturn view;\n\t}\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\thas(primary: K): boolean {\n\t\t\treturn backend.has(primary);\n\t\t},\n\t\tget(primary: K): V | undefined {\n\t\t\treturn backend.get(primary);\n\t\t},\n\t\trangeByPrimary(start: K, end: K): V[] {\n\t\t\treturn backend.rangeByPrimary(start, end);\n\t\t},\n\t\trange(start: K, end: K): ReactiveView<IndexChange<K, V>, readonly V[]> {\n\t\t\treturn getRange(start, end);\n\t\t},\n\t\ttoArray(): readonly IndexRow<K, V>[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\t\ttoPrimaryMap(): ReadonlyMap<K, V> {\n\t\t\treturn backend.toPrimaryMap();\n\t\t},\n\t\tget byPrimary(): Node<ReadonlyMap<K, V>> {\n\t\t\treturn getByPrimary();\n\t\t},\n\n\t\tupsert(primary: K, secondary: unknown, value: V): boolean {\n\t\t\tconst inserted = backend.upsert(primary, secondary, value);\n\t\t\tcore.emit({ kind: \"upsert\", primary, secondary, value });\n\t\t\tenforceCapacity();\n\t\t\treturn inserted;\n\t\t},\n\t\tupsertMany(rows: Iterable<{ primary: K; secondary: unknown; value: V }>): void {\n\t\t\tfor (const r of rows) {\n\t\t\t\tbackend.upsert(r.primary, r.secondary, r.value);\n\t\t\t\tcore.emit({ kind: \"upsert\", primary: r.primary, secondary: r.secondary, value: r.value });\n\t\t\t\tenforceCapacity();\n\t\t\t}\n\t\t},\n\t\tdelete(primary: K): void {\n\t\t\tif (backend.delete(primary)) core.emit({ kind: \"delete\", primary });\n\t\t},\n\t\tdeleteMany(primaries: Iterable<K>): void {\n\t\t\tconst removed: K[] = [];\n\t\t\tfor (const p of primaries) if (backend.delete(p)) removed.push(p);\n\t\t\tif (removed.length > 0) core.emit({ kind: \"deleteMany\", primaries: removed });\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\n\t\tupsertFrom(src: Node<{ primary: K; secondary: unknown; value: V }>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveIndex.upsertFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<\n\t\t\t\t{ primary: K; secondary: unknown; value: V },\n\t\t\t\t{ primary: K; secondary: unknown; value: V }\n\t\t\t> = {\n\t\t\t\tfactory: \"reactiveIndex.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const r of (depBatch(ctx, 0) ?? []) as readonly {\n\t\t\t\t\t\t\tprimary: K;\n\t\t\t\t\t\t\tsecondary: unknown;\n\t\t\t\t\t\t\tvalue: V;\n\t\t\t\t\t\t}[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", r]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveIndex.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveIndex\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tconst applyNode = ensureApply();\n\t\t\tapplyNode.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapplyNode.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t\trangeMemo.disposeAll();\n\t\t},\n\t};\n}\n","/**\n * Internal graph-layer policy helpers (D70).\n *\n * This module is deliberately NOT exported from the package index. It centralizes policy plumbing\n * shared by collection structures while each structure still owns backend mutation + delta emission\n * in its apply/mutation path (D60/D61/D68/D69).\n */\n\nimport { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport type { Node } from \"../../node/node.js\";\n\nexport type PolicyOpt<T> = T | Node<T>;\n\nexport interface PolicyReader<T> {\n\treadonly index: number;\n\tread(ctx: Ctx, current: T | undefined): T | undefined;\n}\n\nexport class PolicyInputs {\n\treadonly deps: Node<unknown>[];\n\n\tconstructor(initial: readonly Node<unknown>[] = []) {\n\t\tthis.deps = [...initial];\n\t}\n\n\tadd<T>(node: Node<T> | undefined): PolicyReader<T> {\n\t\tif (node === undefined) return missingPolicyReader<T>();\n\t\tconst index = this.deps.push(node as Node<unknown>) - 1;\n\t\treturn policyReader<T>(index);\n\t}\n}\n\nfunction missingPolicyReader<T>(): PolicyReader<T> {\n\treturn {\n\t\tindex: -1,\n\t\tread: (_ctx, current) => current,\n\t};\n}\n\nfunction policyReader<T>(index: number): PolicyReader<T> {\n\treturn {\n\t\tindex,\n\t\tread(ctx, current) {\n\t\t\tconst latest = depLatest(ctx, index);\n\t\t\treturn latest === undefined ? current : (latest as T);\n\t\t},\n\t};\n}\n\nexport interface KeyOrderPolicy<K> {\n\tkeys(): Iterable<K>;\n}\n\nexport function lruKeys<K>(keys: Iterable<K>): KeyOrderPolicy<K> {\n\treturn {\n\t\tkeys: () => keys,\n\t};\n}\n\nexport interface CapacityConfig {\n\treadonly maxSize?: number;\n}\n\nexport interface SizedCapacityConfig extends CapacityConfig {\n\treadonly size: number;\n}\n\nexport function trimHeadOverflow<T>(items: T[], config: CapacityConfig): T[];\nexport function trimHeadOverflow<T>(items: Iterable<T>, config: SizedCapacityConfig): T[];\nexport function trimHeadOverflow<T>(\n\titems: T[] | Iterable<T>,\n\tconfig: CapacityConfig | SizedCapacityConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 1)\n\t\tthrow new RangeError(`maxSize must be a positive integer (got ${maxSize})`);\n\n\tconst size = \"size\" in config ? config.size : Array.isArray(items) ? items.length : undefined;\n\tif (size === undefined) throw new Error(\"trimHeadOverflow requires size for non-array iterables\");\n\tconst overflow = size - maxSize;\n\tif (overflow <= 0) return [];\n\n\tif (Array.isArray(items) && !(\"size\" in config)) return items.splice(0, overflow);\n\n\tconst victims: T[] = [];\n\tfor (const item of items) {\n\t\tvictims.push(item);\n\t\tif (victims.length === overflow) break;\n\t}\n\treturn victims;\n}\n\nexport interface DeadlineEntry<K> {\n\treadonly key: K;\n\treadonly expiresAt: number;\n}\n\nexport interface DeadlinePolicy<K> {\n\treadonly size: number;\n\tpush(item: DeadlineEntry<K>): void;\n\tpeek(): DeadlineEntry<K> | undefined;\n\tpop(): DeadlineEntry<K> | undefined;\n}\n\nexport function deadlines<K>(): DeadlinePolicy<K> {\n\treturn new MinDeadlineHeap<K>();\n}\n\nclass MinDeadlineHeap<K> implements DeadlinePolicy<K> {\n\tprivate readonly items: DeadlineEntry<K>[] = [];\n\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\n\tpush(item: DeadlineEntry<K>): void {\n\t\tthis.items.push(item);\n\t\tthis.up(this.items.length - 1);\n\t}\n\n\tpeek(): DeadlineEntry<K> | undefined {\n\t\treturn this.items[0];\n\t}\n\n\tpop(): DeadlineEntry<K> | undefined {\n\t\tconst top = this.items[0];\n\t\tconst last = this.items.pop();\n\t\tif (top !== undefined && last !== undefined && this.items.length > 0) {\n\t\t\tthis.items[0] = last;\n\t\t\tthis.down(0);\n\t\t}\n\t\treturn top;\n\t}\n\n\tprivate up(i: number): void {\n\t\twhile (i > 0) {\n\t\t\tconst p = (i - 1) >> 1;\n\t\t\tif (\n\t\t\t\t(this.items[p] as DeadlineEntry<K>).expiresAt <=\n\t\t\t\t(this.items[i] as DeadlineEntry<K>).expiresAt\n\t\t\t)\n\t\t\t\treturn;\n\t\t\t[this.items[p], this.items[i]] = [\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t\tthis.items[p] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = p;\n\t\t}\n\t}\n\n\tprivate down(i: number): void {\n\t\tfor (;;) {\n\t\t\tconst left = i * 2 + 1;\n\t\t\tconst right = left + 1;\n\t\t\tlet smallest = i;\n\t\t\tif (left < this.items.length && this.expiresAt(left) < this.expiresAt(smallest))\n\t\t\t\tsmallest = left;\n\t\t\tif (right < this.items.length && this.expiresAt(right) < this.expiresAt(smallest))\n\t\t\t\tsmallest = right;\n\t\t\tif (smallest === i) return;\n\t\t\t[this.items[i], this.items[smallest]] = [\n\t\t\t\tthis.items[smallest] as DeadlineEntry<K>,\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = smallest;\n\t\t}\n\t}\n\n\tprivate expiresAt(i: number): number {\n\t\treturn (this.items[i] as DeadlineEntry<K>).expiresAt;\n\t}\n}\n\nexport interface ScoredEntry<T> {\n\treadonly entry: T;\n\treadonly score: number;\n}\n\nexport interface RetentionSelectionConfig {\n\treadonly maxSize?: number;\n}\n\nexport function selectRetentionVictims<T>(\n\tscoredEntries: readonly ScoredEntry<T>[],\n\tconfig: RetentionSelectionConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 0)\n\t\tthrow new RangeError(`retention maxSize must be a non-negative integer (got ${maxSize})`);\n\tconst overflow = scoredEntries.length - maxSize;\n\tif (overflow <= 0) return [];\n\n\treturn scoredEntries\n\t\t.map((item, index) => {\n\t\t\tif (!Number.isFinite(item.score))\n\t\t\t\tthrow new RangeError(`retention score must be finite (got ${item.score})`);\n\t\t\treturn { ...item, index };\n\t\t})\n\t\t.sort((a, b) => a.score - b.score || a.index - b.index)\n\t\t.slice(0, overflow)\n\t\t.map((item) => item.entry);\n}\n","/**\n * Reactive positional list (CSP-2.8, D54/D60) — the two-port collection template.\n *\n * Shape (D60 + review #2): a mutable array BACKEND (the single materialized state) + the shared\n * {@link collectionCore} two ports — a DELTA stream ({@link ReactiveList.delta}, one event per\n * mutation, O(1)) and a lazy pull SNAPSHOT ({@link ReactiveList.snapshot}, materialized only on a\n * cone-routed PULL demand). Mutation input is D54 A3 hybrid: ergonomic imperative methods (the\n * external boundary, state-verb-legitimate, D4) + `appendFrom(src)` widening (an in-graph producer\n * drives the list with zero imperative glue). Synchronous quick-reads (`at`/`size`/`toArray`) are\n * the deliberately-non-reactive peek for cold/imperative reads (D60).\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount, depLatest } from \"../../ctx/types.js\";\nimport { Node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport type { Operator } from \"../operators.js\";\nimport { trimHeadOverflow } from \"../policies/collection.js\";\nimport type { ReactiveOpt } from \"../policies/types.js\";\nimport type { ListChange } from \"./change.js\";\nimport { type CollectionCore, type CollectionCoreOptions, collectionCore } from \"./core.js\";\n\nexport type ReactiveListOpt<T> = ReactiveOpt<T>;\n\nexport interface ReactiveListOptions extends CollectionCoreOptions {\n\t/**\n\t * Head-trim capacity policy (D72). A static number caps the list locally; a Node-valued maxSize\n\t * must be graph-bound and becomes a declared policy dep that trims on policy changes.\n\t */\n\tmaxSize?: ReactiveListOpt<number>;\n}\n\nexport interface ReactiveList<T> {\n\t/** DELTA stream: one {@link ListChange} per mutation (O(1)). Subscribe to observe events. */\n\treadonly delta: Node<ListChange<T>>;\n\t/** SNAPSHOT pull node: demand via `ctx.upNext([[\"PULL\", { pullId }]])` → one `readonly T[]` (lazy O(n)). */\n\treadonly snapshot: Node<readonly T[]>;\n\t/** The snapshot node's pullId — write it verbatim into the demander's fn (D269). */\n\treadonly pullId: symbol;\n\t/** Current entry count (O(1), synchronous non-reactive read). */\n\treadonly size: number;\n\t/** Positional access (O(1)); negative indices Python-style; `undefined` out of range. Sync read. */\n\tat(index: number): T | undefined;\n\t/** Full current contents (O(n), fresh defensive copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly T[];\n\tappend(value: T): void;\n\t/** Append all values; one delta event + one snapshot-arm. No-op if `values` is empty. */\n\tappendMany(values: readonly T[]): void;\n\t/** Insert at `index` (0..size). Throws `RangeError` out of range. */\n\tinsert(index: number, value: T): void;\n\t/** Insert all at `index` as one op. No-op if `values` is empty. Throws out of range. */\n\tinsertMany(index: number, values: readonly T[]): void;\n\t/** Remove and return the value at `index` (default last; negative Python-style). Throws if empty/out of range. */\n\tpop(index?: number): T;\n\tclear(): void;\n\t/** D54 widening: every value from `src` is appended. Returns a disposer. */\n\tappendFrom(src: Node<T>): () => void;\n\t/** Release the widening subscriptions (idempotent). */\n\tdispose(): void;\n}\n\n/** Default mutable-array backend (D60 first-cut; pluggable persistent/immutable backend deferred). */\nclass ListBackend<T> {\n\tprivate _version = 0;\n\tprivate readonly buf: T[];\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tthis.buf = initial ? [...initial] : [];\n\t\ttrimHeadOverflow(this.buf, { maxSize });\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\treturn i < 0 || i >= this.buf.length ? undefined : this.buf[i];\n\t}\n\n\tsnapshot(): readonly T[] {\n\t\treturn [...this.buf];\n\t}\n\n\tappend(value: T): void {\n\t\tthis.buf.push(value);\n\t\tthis._version += 1;\n\t}\n\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\tfor (const v of values) this.buf.push(v);\n\t\tthis._version += 1;\n\t}\n\n\tinsert(index: number, value: T): void {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.buf.length)\n\t\t\tthrow new RangeError(`insert: index ${index} out of range [0, ${this.buf.length}]`);\n\t\tthis.buf.splice(index, 0, value);\n\t\tthis._version += 1;\n\t}\n\n\tinsertMany(index: number, values: readonly T[]): void {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.buf.length)\n\t\t\tthrow new RangeError(`insertMany: index ${index} out of range [0, ${this.buf.length}]`);\n\t\tif (values.length === 0) return;\n\t\tthis.buf.splice(index, 0, ...values);\n\t\tthis._version += 1;\n\t}\n\n\tpop(index: number): T {\n\t\tif (this.buf.length === 0) throw new RangeError(\"pop from empty list\");\n\t\tif (!Number.isInteger(index)) throw new RangeError(`pop: index ${index} must be an integer`);\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\tif (i < 0 || i >= this.buf.length) throw new RangeError(`pop: index ${index} out of range`);\n\t\tconst [v] = this.buf.splice(i, 1);\n\t\tthis._version += 1;\n\t\treturn v as T;\n\t}\n\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\tenforceMaxSize(maxSize?: number): number {\n\t\tconst removed = trimHeadOverflow(this.buf, { maxSize }).length;\n\t\tif (removed > 0) this._version += 1;\n\t\treturn removed;\n\t}\n}\n\n/**\n * Create a reactive list (D54/D60). The DELTA + SNAPSHOT ports + pullId come from the shared\n * {@link collectionCore}; this layer adds the typed list method surface + backend.\n *\n * @example\n * ```ts\n * const list = reactiveList<number>([1]);\n * // observe events:\n * list.delta.subscribe((m) => { if (m[0] === \"DATA\") console.log(\"Δ\", m[1]); });\n * list.append(2); // delta: {kind:\"append\", value:2}\n * // demand the snapshot (a downstream consumer, holding `list.snapshot` upstream, runs):\n * // ctx.upNext([[\"PULL\", { pullId: list.pullId }]]); → SNAPSHOT delivers [1, 2]\n * list.toArray(); // [1, 2] (synchronous non-reactive read)\n * ```\n * @param initial - Optional initial list contents.\n * @param options - Optional graph binding, dispatcher, name, and capacity policy.\n * @returns A reactive list with DELTA and lazy SNAPSHOT ports plus imperative mutation helpers.\n * @category data-structures\n */\nexport function reactiveList<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveListOptions = {},\n): ReactiveList<T> {\n\tconst { maxSize, graph, dispatcher } = options;\n\tconst base = dispatcher ? { dispatcher } : {};\n\n\tfunction isNodeOpt(x: ReactiveListOpt<number> | undefined): x is Node<number> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveList: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tconst initialMaxSize = isNodeOpt(maxSize) ? undefined : maxSize;\n\tconst backend = new ListBackend<T>(\n\t\tinitial,\n\t\tinitialMaxSize === undefined ? undefined : validateMaxSize(initialMaxSize),\n\t);\n\tconst restorable = graph !== undefined && options.name !== undefined && maxSize === undefined;\n\tconst core: CollectionCore<readonly T[], ListChange<T>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveList\",\n\t\toptions,\n\t\trestorable\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveList.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveList.snapshot\",\n\t\t\t\t\tbackendState: () => backend.snapshot(),\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tlet bindSeq = 0;\n\tlet capacityPolicy: Node<number> | undefined;\n\tlet apply: Node<ListChange<T>> | undefined;\n\tlet releaseApply = () => {};\n\tlet currentMaxSize = initialMaxSize;\n\n\tfunction emitTrimmed(n: number): void {\n\t\tif (n > 0) core.emit({ kind: \"trimHead\", n });\n\t}\n\n\tfunction enforceCapacity(): void {\n\t\temitTrimmed(backend.enforceMaxSize(currentMaxSize));\n\t}\n\n\tconst applyBody = (ctx: Ctx): void => {\n\t\tconst deps = apply?.deps ?? [];\n\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep === capacityPolicy) {\n\t\t\t\tconst latest = depLatest(ctx, i);\n\t\t\t\tif (latest !== undefined) currentMaxSize = validateMaxSize(latest as number);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const value of (depBatch(ctx, i) ?? []) as readonly T[]) {\n\t\t\t\t\tbackend.append(value);\n\t\t\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\t\t\tenforceCapacity();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tenforceCapacity();\n\t};\n\n\tfunction ensureApply(): Node<ListChange<T>> {\n\t\tif (apply !== undefined) return apply;\n\t\tconst op: Operator<unknown, ListChange<T>> = {\n\t\t\tfactory: \"reactiveList.capacityPolicy\",\n\t\t\tbody: applyBody,\n\t\t\topts: { partial: true },\n\t\t};\n\t\tconst deps = capacityPolicy ? [capacityPolicy as Node<unknown>] : [];\n\t\tapply = graph\n\t\t\t? graph.initNode(op, deps, {\n\t\t\t\t\tname: options.name ? `${options.name}.capacityPolicy` : undefined,\n\t\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveList\" },\n\t\t\t\t})\n\t\t\t: new Node<ListChange<T>>(deps, op.body, {\n\t\t\t\t\t...base,\n\t\t\t\t\tfactory: \"reactiveList.capacityPolicy\",\n\t\t\t\t\tpartial: true,\n\t\t\t\t\tname: options.name ? `${options.name}.capacityPolicy` : undefined,\n\t\t\t\t});\n\t\treleaseApply = graph\n\t\t\t? graph.retain(apply, { reason: \"reactiveList.capacityPolicy\" })\n\t\t\t: apply.subscribe(() => {});\n\t\treturn apply;\n\t}\n\n\tfunction constPolicyNode(value: number): Node<number> {\n\t\tconst op: Operator<never, number> = {\n\t\t\tfactory: \"reactiveList.maxSizePolicy\",\n\t\t\tbody: () => {},\n\t\t\topts: { initial: value },\n\t\t};\n\t\tif (graph) {\n\t\t\treturn graph.initNode(op, [], {\n\t\t\t\tname: options.name ? `${options.name}.maxSizePolicy` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveList\", policy: \"maxSize\" },\n\t\t\t});\n\t\t}\n\t\treturn new Node<number>([], null, {\n\t\t\t...base,\n\t\t\tinitial: value,\n\t\t\tfactory: \"reactiveList.maxSizePolicy\",\n\t\t\tname: options.name ? `${options.name}.maxSizePolicy` : undefined,\n\t\t});\n\t}\n\n\tif (maxSize !== undefined) {\n\t\tif (isNodeOpt(maxSize) && graph === undefined)\n\t\t\tthrow new Error(\n\t\t\t\t\"reactiveList maxSize Node option requires options.graph so the policy edge is describe-visible (D72)\",\n\t\t\t);\n\t\tcapacityPolicy = isNodeOpt(maxSize)\n\t\t\t? maxSize\n\t\t\t: graph\n\t\t\t\t? constPolicyNode(validateMaxSize(maxSize))\n\t\t\t\t: undefined;\n\t\tif (capacityPolicy !== undefined) ensureApply();\n\t}\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\t\ttoArray(): readonly T[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\tbackend.append(value);\n\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tconst copy = [...values];\n\t\t\tbackend.appendMany(copy);\n\t\t\tcore.emit({ kind: \"appendMany\", values: copy });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tinsert(index: number, value: T): void {\n\t\t\tbackend.insert(index, value);\n\t\t\tcore.emit({ kind: \"insert\", index, value });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tinsertMany(index: number, values: readonly T[]): void {\n\t\t\tif (values.length === 0) {\n\t\t\t\t// still validate the index (mirror backend) so an out-of-range empty insert throws\n\t\t\t\tbackend.insertMany(index, values);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst copy = [...values];\n\t\t\tbackend.insertMany(index, copy);\n\t\t\tcore.emit({ kind: \"insertMany\", index, values: copy });\n\t\t\tenforceCapacity();\n\t\t},\n\t\tpop(index = -1): T {\n\t\t\tconst resolved = index < 0 ? backend.size + index : index;\n\t\t\tconst value = backend.pop(index);\n\t\t\tcore.emit({ kind: \"pop\", index: resolved, value });\n\t\t\treturn value;\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\n\t\tappendFrom(src: Node<T>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveList.appendFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<T, T> = {\n\t\t\t\tfactory: \"reactiveList.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const value of (depBatch(ctx, 0) ?? []) as readonly T[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", value]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveList.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: options.name ? `${options.name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveList\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tconst applyNode = ensureApply();\n\t\t\tapplyNode.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapplyNode.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t},\n\t};\n}\n","/**\n * Reactive append-only log (CSP-2.8, D54/D60) — two-port collection with incremental views.\n *\n * Shape = the shared {@link collectionCore} two ports over an array (or ring-buffer if `maxSize`)\n * BACKEND (D60). Specializations (D60 #5 / review #5):\n * - SNAPSHOT (the full `readonly T[]`) is the lazy pull port like the others, BUT the log's main\n * consumption is INCREMENTAL: `tail()` / `slice()` / `scan()` re-derive on the DELTA backbone\n * (dep=[delta]), folding each appended value as it arrives — NOT re-scanning a pushed full array.\n * - `append(undefined)` throws: `undefined` is the substrate SENTINEL (R-data-payload / R-sentinel),\n * not a valid value.\n * - empty log: the snapshot is `[]` (a real empty array); a never-appended `scan` seeds its initial.\n * There is NO `[[RESOLVED]]`-for-empty dual role (D49 narrowed RESOLVED to undirty-only, D60 #5b).\n * - `attach(upstream)` = the D54 widening (a declared input-fold dep), NOT an imperative subscribe.\n * - {@link mergeReactiveLogs} is a DECLARED-DEP merge (deps=[...delta streams]), NOT the old\n * internal-subscribe island (D45 must-fix, D60 #5e).\n * - storage persistence = D57 (binding-layer observe-sink), out of scope here.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport { type Ctx, depBatch, depCount } from \"../../ctx/types.js\";\nimport { type Node, node } from \"../../node/node.js\";\nimport type { GraphCheckpointJson } from \"../checkpoint.js\";\nimport { trimHeadOverflow } from \"../policies/collection.js\";\nimport type { ViewCachePolicy } from \"../policies/types.js\";\nimport type { LogChange } from \"./change.js\";\nimport {\n\ttype CollectionCore,\n\ttype CollectionCoreOptions,\n\tcollectionCore,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport interface ReactiveLogOptions extends CollectionCoreOptions {\n\t/** Ring-buffer cap: appends past `maxSize` evict the oldest (head-trim, append-only-safe). */\n\tmaxSize?: number;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\tviewCache?: ViewCachePolicy;\n}\n\nexport interface ReactiveLog<T> {\n\treadonly delta: Node<LogChange<T>>;\n\t/** SNAPSHOT pull node: demand → full `readonly T[]` (lazy O(n)). For incremental use {@link tail}, {@link slice}, or {@link scan}. */\n\treadonly snapshot: Node<readonly T[]>;\n\treadonly pullId: symbol;\n\t/** Entry count (O(1)). Sync non-reactive read. */\n\treadonly size: number;\n\t/** Positional access (O(1)); negative Python-style; `undefined` out of range. Sync read. */\n\tat(index: number): T | undefined;\n\t/** Full contents (O(n) fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoArray(): readonly T[];\n\t/** Append one value. Throws on `undefined` (substrate SENTINEL, R-data-payload). */\n\tappend(value: T): void;\n\t/** Append many; one delta event. No-op if empty. Throws if any value is `undefined`. */\n\tappendMany(values: readonly T[]): void;\n\tclear(): void;\n\t/** Remove the first `n` entries (clamped to size). */\n\ttrimHead(n: number): void;\n\t/**\n\t * Incremental tail view: a derived node emitting the last `n` entries, recomputed on each delta\n\t * (dep=[delta], D60 #5a). Memoized per `n` until {@link dispose}; use stable ranges for\n\t * long-lived logs. Subscribe to keep it live.\n\t */\n\ttail(n: number): Node<readonly T[]>;\n\t/**\n\t * Incremental positional view: a derived node emitting `toArray().slice(start, stop)`,\n\t * recomputed on each delta (dep=[delta], D60 #5a). Memoized per `[start, stop]` until\n\t * {@link dispose}; use stable ranges for long-lived logs.\n\t */\n\tslice(start: number, stop?: number): Node<readonly T[]>;\n\t/**\n\t * D121 light page view: `delta` forwards parent log mutations, and `snapshot` is a pull node\n\t * that materializes the current page on demand.\n\t */\n\tpage(offset: number, limit: number): ReactiveView<LogChange<T>, readonly T[]>;\n\t/**\n\t * Incremental running aggregate over appended values (dep=[delta], D60 #5a). O(1) per append —\n\t * folds only the new values each delta; resets on `clear`/`trimHead` (a non-append delta) via a\n\t * full re-fold. Emits the current accumulator on every mutation; seeds `initial` on an empty log.\n\t */\n\tscan<A>(initial: A, step: (acc: A, value: T) => A): Node<A>;\n\t/** D54 widening: every value from `src` is appended. Returns a disposer. */\n\tattach(src: Node<T>): () => void;\n\tdispose(): void;\n}\n\n/** Default array / ring-buffer backend (D60 first-cut; persistent backend deferred). */\nclass LogBackend<T> {\n\tprivate _version = 0;\n\tprivate buf: T[];\n\tprivate readonly maxSize?: number;\n\n\tconstructor(initial?: readonly T[], maxSize?: number) {\n\t\tif (maxSize !== undefined && maxSize < 1)\n\t\t\tthrow new RangeError(\"reactiveLog: maxSize must be >= 1\");\n\t\tthis.maxSize = maxSize;\n\t\tthis.buf = initial ? [...initial] : [];\n\t\ttrimHeadOverflow(this.buf, { maxSize });\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\tget size(): number {\n\t\treturn this.buf.length;\n\t}\n\tat(index: number): T | undefined {\n\t\tif (!Number.isInteger(index)) return undefined;\n\t\tconst i = index >= 0 ? index : this.buf.length + index;\n\t\treturn i < 0 || i >= this.buf.length ? undefined : this.buf[i];\n\t}\n\tsnapshot(): readonly T[] {\n\t\treturn [...this.buf];\n\t}\n\n\tappend(value: T): void {\n\t\tthis.buf.push(value);\n\t\ttrimHeadOverflow(this.buf, { maxSize: this.maxSize });\n\t\tthis._version += 1;\n\t}\n\tappendMany(values: readonly T[]): void {\n\t\tif (values.length === 0) return;\n\t\tfor (const v of values) this.buf.push(v);\n\t\ttrimHeadOverflow(this.buf, { maxSize: this.maxSize });\n\t\tthis._version += 1;\n\t}\n\tclear(): number {\n\t\tconst n = this.buf.length;\n\t\tif (n === 0) return 0;\n\t\tthis.buf.length = 0;\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\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\tif (n === 0 || this.buf.length === 0) return 0;\n\t\tconst removed = Math.min(n, this.buf.length);\n\t\tthis.buf.splice(0, removed);\n\t\tthis._version += 1;\n\t\treturn removed;\n\t}\n}\n\nfunction rejectUndefined<T>(value: T, ctx: string): void {\n\t// R-data-payload / R-sentinel (D60 #5): undefined is the substrate SENTINEL, not a valid value.\n\tif (value === undefined)\n\t\tthrow new TypeError(\n\t\t\t`${ctx}: undefined is the substrate SENTINEL, not a valid value — use null`,\n\t\t);\n}\n\n/**\n * Create an append-only reactive log (D54/D60). DELTA + lazy pull SNAPSHOT + pullId via\n * {@link collectionCore}; this layer adds the typed append surface + incremental view/scan.\n */\nexport function reactiveLog<T>(\n\tinitial?: readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLog<T> {\n\tconst { maxSize, viewCache, ...coreOpts } = options;\n\tconst base = coreOpts.dispatcher ? { dispatcher: coreOpts.dispatcher } : {};\n\tconst backend = new LogBackend<T>(initial, maxSize);\n\tconst restoreConfig =\n\t\tcoreOpts.graph !== undefined && coreOpts.name !== undefined\n\t\t\t? ({\n\t\t\t\t\t...(maxSize !== undefined ? { maxSize } : {}),\n\t\t\t\t} as GraphCheckpointJson)\n\t\t\t: undefined;\n\tconst core: CollectionCore<readonly T[], LogChange<T>> = collectionCore(\n\t\tbackend,\n\t\t\"reactiveLog\",\n\t\tcoreOpts,\n\t\trestoreConfig !== undefined\n\t\t\t? {\n\t\t\t\t\tdeltaRef: \"reactiveLog.delta\",\n\t\t\t\t\tsnapshotRef: \"reactiveLog.snapshot\",\n\t\t\t\t\tconfig: restoreConfig,\n\t\t\t\t\tbackendState: () => backend.snapshot(),\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n\tconst binds: Array<() => void> = [];\n\tconst tailMemo = new Map<number, Node<readonly T[]>>();\n\tconst sliceMemo = new Map<string, Node<readonly T[]>>();\n\tconst pageMemo = new ViewMemoCache<string, ReactiveView<LogChange<T>, readonly T[]>>(viewCache);\n\tlet pageSeq = 0;\n\n\treturn {\n\t\tdelta: core.delta,\n\t\tsnapshot: core.snapshot,\n\t\tpullId: core.pullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tat(index: number): T | undefined {\n\t\t\treturn backend.at(index);\n\t\t},\n\t\ttoArray(): readonly T[] {\n\t\t\treturn backend.snapshot();\n\t\t},\n\n\t\tappend(value: T): void {\n\t\t\trejectUndefined(value, \"reactiveLog.append\");\n\t\t\tbackend.append(value);\n\t\t\tcore.emit({ kind: \"append\", value });\n\t\t},\n\t\tappendMany(values: readonly T[]): void {\n\t\t\tif (values.length === 0) return;\n\t\t\tfor (const v of values) rejectUndefined(v, \"reactiveLog.appendMany\");\n\t\t\tconst copy = [...values];\n\t\t\tbackend.appendMany(copy);\n\t\t\tcore.emit({ kind: \"appendMany\", values: copy });\n\t\t},\n\t\tclear(): void {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) core.emit({ kind: \"clear\", count });\n\t\t},\n\t\ttrimHead(n: number): void {\n\t\t\tconst removed = backend.trimHead(n);\n\t\t\tif (removed > 0) core.emit({ kind: \"trimHead\", n: removed });\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\tconst hit = tailMemo.get(n);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\t// Incremental on the DELTA backbone (D60 #5a): each delta re-reads the backend's current\n\t\t\t// tail (the backend is this structure's own materialized state, D60 #1 — not a foreign\n\t\t\t// .cache peek). `partial:true` — the tail does not consume the delta value, it fires on arm.\n\t\t\tconst tnode = node<readonly T[]>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tconst all = backend.snapshot();\n\t\t\t\t\tctx.down([[\"DATA\", n === 0 ? [] : all.slice(Math.max(0, all.length - n))]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.tail\", partial: true },\n\t\t\t);\n\t\t\ttailMemo.set(n, tnode);\n\t\t\treturn tnode;\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\tif (stop !== undefined && (!Number.isInteger(stop) || stop < 0)) {\n\t\t\t\tthrow new RangeError(`slice: stop must be a non-negative integer (got ${stop})`);\n\t\t\t}\n\t\t\tconst key = `${start}:${stop ?? \"\"}`;\n\t\t\tconst hit = sliceMemo.get(key);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\t// Incremental on the DELTA backbone (D60 #5a): each delta re-reads this log's own\n\t\t\t// backend slice. The backend is the single materialized state (D60), not a dep cache.\n\t\t\tconst snode = node<readonly T[]>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tctx.down([[\"DATA\", backend.snapshot().slice(start, stop)]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.slice\", partial: true },\n\t\t\t);\n\t\t\tsliceMemo.set(key, snode);\n\t\t\treturn snode;\n\t\t},\n\n\t\tpage(offset: number, limit: number): ReactiveView<LogChange<T>, readonly T[]> {\n\t\t\tif (!Number.isInteger(offset) || offset < 0) {\n\t\t\t\tthrow new RangeError(`page: offset must be a non-negative integer (got ${offset})`);\n\t\t\t}\n\t\t\tif (!Number.isInteger(limit) || limit < 0) {\n\t\t\t\tthrow new RangeError(`page: limit must be a non-negative integer (got ${limit})`);\n\t\t\t}\n\t\t\tconst key = `${offset}:${limit}`;\n\t\t\tconst hit = pageMemo.get(key);\n\t\t\tif (hit !== undefined) return hit;\n\t\t\tconst materialize = (): readonly T[] => backend.snapshot().slice(offset, offset + limit);\n\t\t\tlet view: ReactiveView<LogChange<T>, readonly T[]>;\n\t\t\tview = lightReactiveView<LogChange<T>, readonly T[]>(core.delta as Node<unknown>, {\n\t\t\t\t...coreOpts,\n\t\t\t\tfactory: \"reactiveLog.page\",\n\t\t\t\tname: coreOpts.name ? `${coreOpts.name}.page#${pageSeq++}` : undefined,\n\t\t\t\tmaterializeSnapshot: materialize,\n\t\t\t\tonDispose: () => {\n\t\t\t\t\tpageMemo.deleteValue(view);\n\t\t\t\t},\n\t\t\t});\n\t\t\tpageMemo.set(key, view);\n\t\t\treturn view;\n\t\t},\n\n\t\tscan<A>(initial: A, step: (acc: A, value: T) => A): Node<A> {\n\t\t\t// Incremental fold on the delta backbone: keep the accumulator + processed-count in\n\t\t\t// ctx.state; fold only the new tail each append; full re-fold on a shrink (clear/trimHead).\n\t\t\treturn node<A>(\n\t\t\t\t[core.delta as Node<unknown>],\n\t\t\t\t(ctx: Ctx) => {\n\t\t\t\t\tconst st = ctx.state.get<{ acc: A; processed: number }>() ?? {\n\t\t\t\t\t\tacc: initial,\n\t\t\t\t\t\tprocessed: 0,\n\t\t\t\t\t};\n\t\t\t\t\tconst all = backend.snapshot();\n\t\t\t\t\tif (all.length < st.processed || (maxSize !== undefined && all.length <= st.processed)) {\n\t\t\t\t\t\t// Shrink or ring-buffer overwrite: re-fold from the current backend snapshot.\n\t\t\t\t\t\tlet acc = initial;\n\t\t\t\t\t\tfor (const v of all) acc = step(acc, v);\n\t\t\t\t\t\tst.acc = acc;\n\t\t\t\t\t\tst.processed = all.length;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = st.processed; i < all.length; i++) st.acc = step(st.acc, all[i] as T);\n\t\t\t\t\t\tst.processed = all.length;\n\t\t\t\t\t}\n\t\t\t\t\tctx.state.set(st);\n\t\t\t\t\tctx.down([[\"DATA\", st.acc]]);\n\t\t\t\t},\n\t\t\t\t{ ...base, factory: \"reactiveLog.scan\", partial: true },\n\t\t\t);\n\t\t},\n\n\t\tattach(src: Node<T>): () => void {\n\t\t\tconst dispose = core.bindSource(src, (value: T) => {\n\t\t\t\trejectUndefined(value, \"reactiveLog.attach\");\n\t\t\t\tbackend.append(value);\n\t\t\t\tcore.emit({ kind: \"append\", value });\n\t\t\t});\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\ttailMemo.clear();\n\t\t\tsliceMemo.clear();\n\t\t\tpageMemo.disposeAll();\n\t\t},\n\t};\n}\n\n/**\n * Fan-in N reactive logs into one merged DELTA stream (D60 #5e — a DECLARED-DEP merge, NOT the old\n * internal-subscribe island). The returned node declares each log's `delta` as a dep (`partial`)\n * and re-emits every change it sees — describe shows `log[i].delta → merged` truthfully (D45).\n * For the merged SNAPSHOT, fold the merged delta with {@link ReactiveLog.scan}-style logic, or\n * demand each source's snapshot independently.\n */\nexport function mergeReactiveLogs<T>(logs: readonly ReactiveLog<T>[]): Node<LogChange<T>> {\n\tconst deps = logs.map((l) => l.delta as Node<unknown>);\n\treturn node<LogChange<T>>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b) for (const c of b) ctx.down([[\"DATA\", c as LogChange<T>]]);\n\t\t\t}\n\t\t},\n\t\t{ factory: \"mergeReactiveLogs\", partial: true },\n\t);\n}\n\n/**\n * Standalone incremental scan over a reactive log. Equivalent to `log.scan(initial, step)`;\n * provided for pipe-builder and helper-composition call sites.\n */\nexport function scanLog<T, A>(\n\tlog: ReactiveLog<T>,\n\tinitial: A,\n\tstep: (acc: A, value: T) => A,\n): Node<A> {\n\treturn log.scan(initial, step);\n}\n","/**\n * Async + sync sources (binding-layer sugar, D43 / D40 / feedback_async_sources_binding_layer).\n *\n * Sources are depless {@link Operator}`<never, T>` specs built on the `producer`/`node` path:\n * the body runs ONCE on activation (node `_activate`), schedules its work, and emits later via\n * the captured `ctx.down` (an external tier-3 emit → the leading DIRTY is synthesized for it,\n * R-dirty-before-data). Async lives ONLY here (R-no-raw-async / F-SYNC-CORE): `setTimeout` /\n * `Promise` / `for await` are confined to source bodies; the wave core stays sync. Cleanup is\n * `ctx.onDeactivation` (D28), NOT a returned object. Per-language (D6/D24), never in parity.\n *\n * Instantiate via `g.initNode(timer(1000), [])` (graph-bound, inspectable) or\n * {@link initNode}(timer(1000), []) (bare). Pool/pause defaults (D43): timer/interval =\n * sync + pausable:false (keep producing through PAUSE); fromPromise/fromAsyncIter = async\n * (default pausable, so a paused source buffers its late emits — R-async-paused).\n */\n\nimport type { Ctx } from \"../ctx/types.js\";\nimport type { Node, NodeOptions } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { toCheckpointJson } from \"./checkpoint.js\";\nimport type {\n\tDriverCancel,\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"./environment.js\";\nimport { initNode, type Operator } from \"./operators.js\";\n\n/**\n * Values accepted by {@link fromAny}: an existing Node, a Promise, an (a)sync iterable, or a\n * bare scalar. The universal coercion target for higher-order operators (CSP-2.7).\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Host-boundary options for {@link singleFromAny}. */\nexport interface SingleFromAnyOptions<K> {\n\t/**\n\t * Map a caller key to the in-flight dedupe key. Defaults to key identity; object keys dedupe only\n\t * when the same object reference is reused. Return a stable string/canonical value for structural\n\t * object-key dedupe.\n\t */\n\tkeyOf?: (key: K) => unknown;\n\t/** Treat a sync iterable result as a stream and take its first item. Defaults to scalar value. */\n\titer?: boolean;\n}\n\n/**\n * Internal: build a depless source spec. `setup` runs once on activation; its returned fn (if\n * any) is registered as the deactivation cleanup (clear timers / abort). `setup` schedules the\n * async work and emits via `ctx.down` — synchronously (sync sources) or later (async sources).\n */\nfunction source<T>(\n\tfactory: string,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: setup returns a cleanup fn OR nothing — the void arm keeps no-return source bodies (e.g. `of`/`fromIter`) ergonomic, same idiom as EffectFn.\n\tsetup: (ctx: Ctx) => void | (() => void),\n\topts?: Partial<NodeOptions<T>>,\n): Operator<never, T> {\n\treturn {\n\t\tfactory,\n\t\topts,\n\t\tbody: (ctx) => {\n\t\t\tlet cleanup: undefined | (() => void);\n\t\t\tlet deactivated = false;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tdeactivated = true;\n\t\t\t\tif (typeof cleanup === \"function\") cleanup();\n\t\t\t});\n\t\t\tconst maybeCleanup = setup(ctx);\n\t\t\tcleanup = typeof maybeCleanup === \"function\" ? maybeCleanup : undefined;\n\t\t\tif (deactivated && typeof cleanup === \"function\") cleanup();\n\t\t},\n\t};\n}\n\nfunction assertNonEmptyString(value: string, label: string): void {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new TypeError(`${label} must be a non-empty string`);\n\t}\n}\n\nfunction cleanupDriverWork(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n): void {\n\tactive.value = false;\n\tconst cancel = cancelSlot.value;\n\tcancelSlot.value = undefined;\n\tif (cancel !== undefined) runDriverCancel(cancel);\n}\n\nfunction installDriverCancel(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n\tcancel: DriverCancel,\n): void {\n\tif (active.value) cancelSlot.value = cancel;\n\telse runDriverCancel(cancel);\n}\n\nfunction runDriverCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cleanup is best-effort: it must not suppress graph-visible terminal delivery.\n\t}\n}\n\nfunction driverOneShotSource<T>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (result: DriverResult<T>) => void) => DriverCancel | undefined,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (result: DriverResult<T>) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\tif (result.ok) ctx.down([[\"DATA\", result.value], [\"COMPLETE\"]]);\n\t\t\t\telse ctx.down([[\"ERROR\", errorPayload(result.error)]]);\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction driverStreamSource<T, E extends { readonly kind: string }>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (event: E) => void) => DriverCancel | undefined,\n\tdataOf: (event: E) => T | undefined,\n\terrorOf: (event: E) => unknown,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (event: E) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\tconst value = dataOf(event);\n\t\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(errorOf(event))]]);\n\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\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\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isAsyncIterable<T>(x: unknown): x is AsyncIterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nfunction isIterable<T>(x: unknown): x is Iterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\t);\n}\n\n/** Options shared by async/timer sources: an optional AbortSignal → ERROR on abort. */\nexport interface AsyncSourceOpts {\n\tsignal?: AbortSignal;\n}\n\nexport interface TimerSourceOpts extends AsyncSourceOpts {\n\tperiod?: number;\n}\n\n/** Options for {@link fromCron}. */\nexport interface FromCronOptions extends AsyncSourceOpts {\n\t/** Cron matcher polling interval in milliseconds. Default: 60_000. */\n\ttickMs?: number;\n\t/** IANA timezone used for wall-clock cron matching. Defaults to the host-local timezone. */\n\ttimezone?: string;\n\t/**\n\t * DST policy for timezone-aware matching. Current D484 defaults are explicit: nonexistent\n\t * wall-clock minutes are skipped, and repeated wall-clock minutes fire at most once.\n\t */\n\tdst?: {\n\t\treadonly nonexistent?: \"skip\";\n\t\treadonly repeated?: \"once\";\n\t};\n\t/**\n\t * Emitted value shape. `timestamp_ns` is a decimal string so it cannot lose precision as a\n\t * JavaScript number; use `timestamp_ms` when numeric millisecond precision is enough.\n\t */\n\toutput?: \"date\" | \"timestamp_ms\" | \"timestamp_ns\";\n}\n\n/** Minimal five-field cron schedule: minute hour day-of-month month day-of-week. */\nexport interface CronSchedule {\n\treadonly minutes: ReadonlySet<number>;\n\treadonly hours: ReadonlySet<number>;\n\treadonly daysOfMonth: ReadonlySet<number>;\n\treadonly months: ReadonlySet<number>;\n\treadonly daysOfWeek: ReadonlySet<number>;\n}\n\n/** DOM/EventEmitter-style target accepted by {@link fromEvent}. */\nexport interface EventTargetLike {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n}\n\nexport interface EventListenerOptionsLike {\n\tcapture?: boolean;\n\tpassive?: boolean;\n\tonce?: boolean;\n}\n\nexport type FromEventOptions = EventListenerOptionsLike;\n\n/** Host push registration callback accepted by {@link fromPushNotification}. */\nexport type PushUnsubscribe = () => void;\nexport type PushRegister<T> = (deliver: (payload: T) => void) => PushUnsubscribe | undefined;\n\nfunction parseCronField(field: string, min: number, max: number): Set<number> {\n\tif (field.length === 0) throw new Error(\"Invalid cron field: empty\");\n\tconst out = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tif (part.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tconst stepParts = part.split(\"/\");\n\t\tif (stepParts.length > 2) throw new Error(`Invalid cron step: ${part}`);\n\t\tconst [range, stepText] = stepParts;\n\t\tif (range == null || range.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (stepText === \"\") throw new Error(`Invalid cron step: ${part}`);\n\t\tconst step = stepText == null ? 1 : parseCronInt(stepText, `Invalid cron step: ${part}`);\n\t\tif (step < 1) throw new Error(`Invalid cron step: ${part}`);\n\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b, extra] = range.split(\"-\");\n\t\t\tif (extra !== undefined || a === \"\" || b === \"\")\n\t\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t\tstart = parseCronInt(a, `Invalid cron field: ${field}`);\n\t\t\tend = parseCronInt(b, `Invalid cron field: ${field}`);\n\t\t} else {\n\t\t\tstart = parseCronInt(range, `Invalid cron field: ${field}`);\n\t\t\tend = start;\n\t\t}\n\n\t\tif (!Number.isInteger(start) || !Number.isInteger(end)) {\n\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t}\n\t\tif (start < min || end > max) {\n\t\t\tthrow new RangeError(`Cron field out of range: ${field} (${min}-${max})`);\n\t\t}\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) out.add(i);\n\t}\n\treturn out;\n}\n\nfunction parseCronInt(text: string, message: string): number {\n\tif (!/^\\d+$/.test(text)) throw new Error(message);\n\tconst value = Number.parseInt(text, 10);\n\tif (!Number.isSafeInteger(value)) throw new Error(message);\n\treturn value;\n}\n\n/** Parse a standard five-field cron expression. */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5 || parts.some((part) => part.length === 0)) {\n\t\tthrow new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\t}\n\treturn {\n\t\tminutes: parseCronField(parts[0], 0, 59),\n\t\thours: parseCronField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseCronField(parts[2], 1, 31),\n\t\tmonths: parseCronField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseCronField(parts[4], 0, 6),\n\t};\n}\n\nexport interface CronMatchOptions {\n\t/** IANA timezone used for wall-clock projection. Defaults to the host-local timezone. */\n\ttimezone?: string;\n}\n\ninterface CronWallClockFields {\n\treadonly year: number;\n\treadonly month: number;\n\treadonly day: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly dayOfWeek: number;\n}\n\n/** Test whether a Date matches a parsed cron schedule in host-local time or an IANA timezone. */\nexport function matchesCron(\n\tschedule: CronSchedule,\n\tdate: Date,\n\topts: CronMatchOptions = {},\n): boolean {\n\tconst fields = cronWallClockFields(date, opts.timezone);\n\treturn (\n\t\tschedule.minutes.has(fields.minute) &&\n\t\tschedule.hours.has(fields.hour) &&\n\t\tschedule.daysOfMonth.has(fields.day) &&\n\t\tschedule.months.has(fields.month) &&\n\t\tschedule.daysOfWeek.has(fields.dayOfWeek)\n\t);\n}\n\nfunction cronMinuteKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}-${fields.hour}-${fields.minute}`;\n}\n\nfunction cronDayKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}`;\n}\n\nfunction cronWallClockFields(date: Date, timezone?: string): CronWallClockFields {\n\tif (timezone === undefined) {\n\t\treturn {\n\t\t\tyear: date.getFullYear(),\n\t\t\tmonth: date.getMonth() + 1,\n\t\t\tday: date.getDate(),\n\t\t\thour: date.getHours(),\n\t\t\tminute: date.getMinutes(),\n\t\t\tdayOfWeek: date.getDay(),\n\t\t};\n\t}\n\tconst parts = timezoneFormatter(timezone).formatToParts(date);\n\tconst values: Record<string, number> = {};\n\tfor (const part of parts) {\n\t\tif (\n\t\t\tpart.type === \"year\" ||\n\t\t\tpart.type === \"month\" ||\n\t\t\tpart.type === \"day\" ||\n\t\t\tpart.type === \"hour\" ||\n\t\t\tpart.type === \"minute\"\n\t\t) {\n\t\t\tvalues[part.type] = Number.parseInt(part.value, 10);\n\t\t}\n\t}\n\tconst year = values.year;\n\tconst month = values.month;\n\tconst day = values.day;\n\tconst hour = values.hour;\n\tconst minute = values.minute;\n\tif (\n\t\tyear === undefined ||\n\t\tmonth === undefined ||\n\t\tday === undefined ||\n\t\thour === undefined ||\n\t\tminute === undefined\n\t) {\n\t\tthrow new Error(`fromCron: timezone projection failed for ${timezone}`);\n\t}\n\treturn {\n\t\tyear,\n\t\tmonth,\n\t\tday,\n\t\thour,\n\t\tminute,\n\t\tdayOfWeek: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),\n\t};\n}\n\nconst TIMEZONE_FORMATTERS = new Map<string, Intl.DateTimeFormat>();\n\nfunction timezoneFormatter(timezone: string): Intl.DateTimeFormat {\n\tconst existing = TIMEZONE_FORMATTERS.get(timezone);\n\tif (existing !== undefined) return existing;\n\tassertNonEmptyString(timezone, \"fromCron: timezone\");\n\ttry {\n\t\tconst formatter = new Intl.DateTimeFormat(\"en-US-u-ca-gregory-nu-latn\", {\n\t\t\ttimeZone: timezone,\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\thourCycle: \"h23\",\n\t\t});\n\t\tformatter.format(new Date(0));\n\t\tTIMEZONE_FORMATTERS.set(timezone, formatter);\n\t\treturn formatter;\n\t} catch (error) {\n\t\tthrow new RangeError(\n\t\t\t`fromCron: unsupported IANA timezone '${timezone}' (${error instanceof Error ? error.message : String(error)})`,\n\t\t);\n\t}\n}\n\nfunction dateToTimestampNs(date: Date): string {\n\treturn (BigInt(date.getTime()) * 1_000_000n).toString();\n}\n\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"date\" },\n): Operator<never, Date>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"timestamp_ms\" },\n): Operator<never, number>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions & { output?: \"timestamp_ns\" },\n): Operator<never, string>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions,\n): Operator<never, Date | number | string>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions = {},\n): Operator<never, Date | number | string> {\n\tconst schedule = parseCron(expr);\n\tconst { tickMs = 60_000, output = \"timestamp_ns\", signal, timezone } = opts;\n\tif (opts.dst?.nonexistent !== undefined && opts.dst.nonexistent !== \"skip\") {\n\t\tthrow new RangeError(\"fromCron: dst.nonexistent currently supports only 'skip'\");\n\t}\n\tif (opts.dst?.repeated !== undefined && opts.dst.repeated !== \"once\") {\n\t\tthrow new RangeError(\"fromCron: dst.repeated currently supports only 'once'\");\n\t}\n\tif (timezone !== undefined) timezoneFormatter(timezone);\n\tif (!Number.isFinite(tickMs) || tickMs <= 0) {\n\t\tthrow new RangeError(\"fromCron: tickMs must be a positive finite number\");\n\t}\n\treturn source<Date | number | string>(\n\t\t\"fromCron\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet lastFiredKey: string | undefined;\n\t\t\tlet firedTimezoneDay: string | undefined;\n\t\t\tconst firedTimezoneMinutes = new Set<string>();\n\t\t\tlet intervalId: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (intervalId !== undefined) clearInterval(intervalId);\n\t\t\t\tintervalId = undefined;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst emitNow = (now: Date) => {\n\t\t\t\tif (output === \"date\") ctx.down([[\"DATA\", now]]);\n\t\t\t\telse if (output === \"timestamp_ms\") ctx.down([[\"DATA\", now.getTime()]]);\n\t\t\t\telse ctx.down([[\"DATA\", dateToTimestampNs(now)]]);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key = cronMinuteKey(now, timezone);\n\t\t\t\tconst alreadyFired =\n\t\t\t\t\ttimezone === undefined ? key === lastFiredKey : firedTimezoneMinutes.has(key);\n\t\t\t\tif (!alreadyFired && matchesCron(schedule, now, { timezone })) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\tif (timezone !== undefined) {\n\t\t\t\t\t\tconst dayKey = cronDayKey(now, timezone);\n\t\t\t\t\t\tif (dayKey !== firedTimezoneDay) {\n\t\t\t\t\t\t\tfiredTimezoneDay = dayKey;\n\t\t\t\t\t\t\tfiredTimezoneMinutes.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfiredTimezoneMinutes.add(key);\n\t\t\t\t\t}\n\t\t\t\t\temitNow(now);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn cleanup;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tcheck();\n\t\t\tintervalId = setInterval(check, tickMs);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n}\n\nexport function runProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn runProcessWithOptions({ program, args });\n}\n\nexport function fromProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn processSource(\"fromProcess\", { program, args });\n}\n\nexport function runProcessWithOptions(command: ProcessCommand): Operator<never, ProcessResult> {\n\treturn processSource(\"runProcess\", command);\n}\n\nfunction processSource(factory: string, command: ProcessCommand): Operator<never, ProcessResult> {\n\tassertNonEmptyString(command.program, `${factory}: program`);\n\treturn driverOneShotSource<ProcessResult>(\n\t\tfactory,\n\t\t`${factory}: missing process driver`,\n\t\t(ctx, callback) => ctx.environment().processDriver()?.run(command, callback),\n\t);\n}\n\nexport function fromHttp(url: string): Operator<never, HttpResponse> {\n\treturn fromHttpWithOptions({ method: \"GET\", url });\n}\n\nexport function fromHttpWithOptions(request: HttpRequest): Operator<never, HttpResponse> {\n\tassertNonEmptyString(request.url, \"fromHttp: url\");\n\tassertNonEmptyString(request.method, \"fromHttp: method\");\n\treturn driverOneShotSource<HttpResponse>(\n\t\t\"fromHttp\",\n\t\t\"fromHttp: missing http driver\",\n\t\t(ctx, callback) => ctx.environment().httpDriver()?.request(request, callback),\n\t);\n}\n\nexport function fromSSE(url: string): Operator<never, SseEvent> {\n\treturn fromSSEWithOptions({ url });\n}\n\nexport function fromSSEWithOptions(request: SseRequest): Operator<never, SseEvent> {\n\tassertNonEmptyString(request.url, \"fromSSE: url\");\n\treturn driverStreamSource<SseEvent, SseDriverEvent>(\n\t\t\"fromSSE\",\n\t\t\"fromSSE: missing sse driver\",\n\t\t(ctx, callback) => ctx.environment().sseDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebSocket(url: string): Operator<never, WebSocketEvent> {\n\treturn fromWebSocketWithOptions({ url });\n}\n\nexport function fromWebSocketWithOptions(\n\trequest: WebSocketRequest,\n): Operator<never, WebSocketEvent> {\n\tassertNonEmptyString(request.url, \"fromWebSocket: url\");\n\treturn driverStreamSource<WebSocketEvent, WebSocketDriverEvent>(\n\t\t\"fromWebSocket\",\n\t\t\"fromWebSocket: missing websocket driver\",\n\t\t(ctx, callback) => ctx.environment().webSocketDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebhook(id: string): Operator<never, WebhookEvent> {\n\treturn fromWebhookWithOptions({ id });\n}\n\nexport function fromWebhookWithOptions(\n\tregistration: WebhookRegistration,\n): Operator<never, WebhookEvent> {\n\tassertNonEmptyString(registration.id, \"fromWebhook: id\");\n\treturn driverStreamSource<WebhookEvent, WebhookDriverEvent>(\n\t\t\"fromWebhook\",\n\t\t\"fromWebhook: missing webhook driver\",\n\t\t(ctx, callback) => ctx.environment().webhookDriver()?.register(registration, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nfunction timerSource(factory: string, ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\tconst { period, signal } = opts ?? {};\n\tconst op = source<number>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet count = 0;\n\t\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst finish = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tif (period != null) {\n\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\t\tif (done) return;\n\t\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\t}, period);\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot: DATA then COMPLETE in one wave (terminal-is-forever).\n\t\t\t\t\tdone = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", count++], [\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tt = setTimeout(finish, ms);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n\tif (factory === \"timer\" && period === undefined && signal === undefined) {\n\t\treturn { ...op, restore: { ref: \"timer\", config: { ms: toCheckpointJson(ms, \"timer.ms\") } } };\n\t}\n\treturn op;\n}\n\n/**\n * Timer source: one-shot (first tick then COMPLETE) or periodic (`{period}` → 0, 1, 2, …).\n * sync pool + pausable:false (a timer keeps producing through PAUSE, R-pause-modes). Emits the\n * tick counter from 0; deactivation clears the timers.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { graph, timer } from \"@graphrefly/ts\";\n *\n * const tick = graph().initNode(timer(100), []);\n * ```\n * @category sources\n */\nexport function timer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"timer\", ms, opts);\n}\n\n/**\n * Create a timer source with the legacy `fromTimer` factory name.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { fromTimer, graph } from \"@graphrefly/ts\";\n *\n * const tick = graph().initNode(fromTimer(100), []);\n * ```\n * @remarks **Factory name:** This preserves the real `fromTimer` factory name in `describe()`.\n * @category sources\n */\nexport function fromTimer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"fromTimer\", ms, opts);\n}\n\n/**\n * Emit periodic tick counters.\n *\n * @param ms - Delay before the first tick and between later ticks in milliseconds.\n * @returns A source operator that emits `0`, `1`, `2`, and so on.\n * @example\n * ```ts\n * import { graph, interval } from \"@graphrefly/ts\";\n *\n * const ticks = graph().initNode(interval(1000), []);\n * ```\n * @category sources\n */\nexport function interval(ms: number): Operator<never, number> {\n\treturn timerSource(\"interval\", ms, { period: ms });\n}\n\n/**\n * Lift a Promise (or thenable) to a single-value stream: one DATA then COMPLETE, or ERROR on\n * rejection. async pool (default pausable → a paused source buffers its late emit). Optional\n * `signal` aborts to ERROR.\n *\n * @param p - Promise or thenable to lift into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits one DATA value and COMPLETE, or ERROR on rejection/abort.\n * @example\n * ```ts\n * import { fromPromise, graph } from \"@graphrefly/ts\";\n *\n * const user = graph().initNode(fromPromise(fetch(\"/user\").then((res) => res.json())), []);\n * ```\n * @category sources\n */\nexport function fromPromise<T>(\n\tp: Promise<T> | PromiseLike<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst signal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromPromise\",\n\t\t(ctx) => {\n\t\t\tlet settled = false;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\t// onAbort only runs from a `signal` listener / the `signal.aborted` guard → signal is defined.\n\t\t\t\tctx.down([[\"ERROR\", errorPayload((signal as AbortSignal).reason)]]);\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid Promise.resolve(p).then(\n\t\t\t\t(v) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * Read an async iterable: each value → DATA; COMPLETE when done; ERROR on failure. async pool.\n * Optional `signal` aborts the pump.\n *\n * @param iterable - Async iterable to pump into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { fromAsyncIter, graph } from \"@graphrefly/ts\";\n *\n * const stream = graph().initNode(fromAsyncIter(events()), []);\n * ```\n * @category sources\n */\nexport function fromAsyncIter<T>(\n\titerable: AsyncIterable<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst outerSignal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromAsyncIter\",\n\t\t(ctx) => {\n\t\t\tconst ac = new AbortController();\n\t\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet done = false;\n\t\t\tconst pump = async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const v of iterable) {\n\t\t\t\t\t\tif (ac.signal.aborted) break;\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"COMPLETE\"]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t} finally {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tvoid pump();\n\t\t\treturn () => {\n\t\t\t\tif (!done) ac.abort();\n\t\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * of: synchronous values — each argument as DATA, then COMPLETE. `of()` is the EMPTY source.\n *\n * @param values - Values to emit synchronously on activation.\n * @returns A source operator that emits each value and then COMPLETE.\n * @example\n * ```ts\n * import { graph, of } from \"@graphrefly/ts\";\n *\n * const values = graph().initNode(of(1, 2, 3), []);\n * ```\n * @category sources\n */\nexport function of<T = never>(...values: T[]): Operator<never, T> {\n\treturn source<T>(\n\t\t\"of\",\n\t\t(ctx) => {\n\t\t\tfor (const value of values) ctx.down([[\"DATA\", value]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Emit every value from a synchronous iterable.\n *\n * @param iterable - Iterable whose values are emitted in order.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { fromIter, graph } from \"@graphrefly/ts\";\n *\n * const values = graph().initNode(fromIter([1, 2, 3]), []);\n * ```\n * @category sources\n */\nexport function fromIter<T>(iterable: Iterable<T>): Operator<never, T> {\n\treturn source<T>(\n\t\t\"fromIter\",\n\t\t(ctx) => {\n\t\t\tfor (const v of iterable) ctx.down([[\"DATA\", v]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Complete immediately without emitting DATA.\n *\n * @returns A source operator that emits COMPLETE on activation.\n * @example\n * ```ts\n * import { empty, graph } from \"@graphrefly/ts\";\n *\n * const done = graph().initNode(empty(), []);\n * ```\n * @category sources\n */\nexport function empty<T = never>(): Operator<never, T> {\n\treturn source<T>(\n\t\t\"empty\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Activate and remain silent until deactivation.\n *\n * @returns A source operator that never emits DATA or terminal messages by itself.\n * @example\n * ```ts\n * import { graph, never } from \"@graphrefly/ts\";\n *\n * const quiet = graph().initNode(never(), []);\n * ```\n * @category sources\n */\nexport function never<T = never>(): Operator<never, T> {\n\treturn source<T>(\"never\", () => undefined, { pool: \"sync\" });\n}\n\n/**\n * Terminate with ERROR on activation.\n *\n * @param err - Host-language error payload to normalize into a protocol ERROR payload.\n * @returns A source operator that emits ERROR.\n * @example\n * ```ts\n * import { graph, throwError } from \"@graphrefly/ts\";\n *\n * const failed = graph().initNode(throwError(new Error(\"boom\")), []);\n * ```\n * @category sources\n */\nexport function throwError(err: unknown): Operator<never, never> {\n\treturn source<never>(\n\t\t\"throwError\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"ERROR\", errorPayload(err)]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a DOM-style event target. Each event becomes DATA; deactivation removes the listener.\n * External callbacks are source boundaries (D43), so no polling or operator-level async leaks in.\n *\n * @param target - Event target implementing `addEventListener` and `removeEventListener`.\n * @param type - Event type to subscribe to.\n * @param opts - Optional listener options and source options.\n * @returns A source operator that emits each event as DATA.\n * @example\n * ```ts\n * import { fromEvent, graph } from \"@graphrefly/ts\";\n *\n * const clicks = graph().initNode(fromEvent<MouseEvent>(button, \"click\"), []);\n * ```\n * @category sources\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts: FromEventOptions = {},\n): Operator<never, T> {\n\tif (target == null || typeof target.addEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement addEventListener\");\n\t}\n\tif (typeof target.removeEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement removeEventListener\");\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new TypeError(\"fromEvent: event type must be a non-empty string\");\n\t}\n\treturn source<T>(\n\t\t\"fromEvent\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst handler = (event: unknown) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", event as T]]);\n\t\t\t};\n\t\t\ttarget.addEventListener(type, handler, opts);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\ttarget.removeEventListener(type, handler, opts);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a host push transport. The host owns network/native setup; this factory owns reactive\n * delivery and teardown only, preserving async-at-source-boundary discipline.\n */\nexport function fromPushNotification<T = unknown>(register: PushRegister<T>): Operator<never, T> {\n\tif (typeof register !== \"function\") {\n\t\tthrow new TypeError(\"fromPushNotification: register must be a function\");\n\t}\n\treturn source<T>(\n\t\t\"fromPushNotification\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst deliver = (payload: T) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", payload]]);\n\t\t\t};\n\t\t\tconst unsubscribe = register(deliver);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (typeof unsubscribe === \"function\") unsubscribe();\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Coerce a {@link NodeInput}`<T>` to a `Node<T>` (D43 — coercion prerequisite for the CSP-2.7\n * higher-order operators). An existing Node passes through; a thenable → {@link fromPromise};\n * an async iterable → {@link fromAsyncIter}; with `{iter:true}` a sync iterable →\n * {@link fromIter}; everything else → {@link of}. Coerced nodes are bare (use\n * `opts.dispatcher` to bind one, default = process-global D26).\n */\nexport function fromAny<T>(\n\tinput: NodeInput<T>,\n\topts: NodeOptions<T> & { iter?: boolean } = {},\n): Node<T> {\n\tif (isNode(input)) return input as Node<T>;\n\tconst { iter, ...nodeOpts } = opts;\n\tif (isThenable(input)) {\n\t\treturn initNode(fromPromise(input as PromiseLike<T>), [], nodeOpts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as {\n\t\t\t[Symbol.asyncIterator]?: unknown;\n\t\t\t[Symbol.iterator]?: unknown;\n\t\t};\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn initNode(fromAsyncIter(input as AsyncIterable<T>), [], nodeOpts);\n\t\t}\n\t\tif (iter === true && typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn initNode(fromIter(input as Iterable<T>), [], nodeOpts);\n\t\t}\n\t}\n\treturn initNode(of(input as T), [], nodeOpts);\n}\n\n/**\n * Resolve the first DATA from a Node as a Promise. This is a host-boundary escape hatch, not a\n * graph operator; do not call it from reactive node bodies. ERROR rejects, and COMPLETE before DATA\n * rejects because no value exists.\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\tconst finish = (f: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tf();\n\t\t\tif (unsub) {\n\t\t\t\tunsub();\n\t\t\t\tunsub = undefined;\n\t\t\t} else {\n\t\t\t\tshouldUnsub = true;\n\t\t\t}\n\t\t};\n\t\tunsub = source.subscribe((msg) => {\n\t\t\tif (msg[0] === \"DATA\") {\n\t\t\t\tfinish(() => resolve(msg[1] as T));\n\t\t\t} else if (msg[0] === \"ERROR\") {\n\t\t\t\tfinish(() => reject(msg[1]));\n\t\t\t} else if (msg[0] === \"COMPLETE\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: completed without DATA\")));\n\t\t\t} else if (msg[0] === \"TEARDOWN\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: torn down without DATA\")));\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\nfunction singleFromAnyValue<T>(value: T): T {\n\tif (value === undefined) {\n\t\tthrow new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\");\n\t}\n\treturn value;\n}\n\nasync function firstFromAsyncIterable<T>(input: AsyncIterable<T>): Promise<T> {\n\tconst iter = input[Symbol.asyncIterator]();\n\tconst { value, done } = await iter.next();\n\tif (done) {\n\t\tawait iter.return?.();\n\t\tthrow new Error(\"singleFromAny: factory returned empty async iterable\");\n\t}\n\ttry {\n\t\tawait iter.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn value as T;\n}\n\nfunction firstFromIterable<T>(input: Iterable<T>): Promise<T> {\n\tconst iter = input[Symbol.iterator]();\n\tconst { value, done } = iter.next();\n\tif (done) {\n\t\titer.return?.();\n\t\treturn Promise.reject(new Error(\"singleFromAny: factory returned empty iterable\"));\n\t}\n\ttry {\n\t\titer.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn Promise.resolve(value as T);\n}\n\nfunction nodeInputToPromise<T>(input: NodeInput<T>, opts: { iter?: boolean }): Promise<T> {\n\tif (isThenable(input)) return Promise.resolve(input as PromiseLike<T>).then(singleFromAnyValue);\n\tif (isNode(input)) return firstValueFrom(input as Node<T>).then(singleFromAnyValue);\n\tif (isAsyncIterable<T>(input)) return firstFromAsyncIterable(input).then(singleFromAnyValue);\n\tif (opts.iter === true && isIterable<T>(input)) {\n\t\treturn firstFromIterable(input).then(singleFromAnyValue);\n\t}\n\tif (input === undefined) {\n\t\treturn Promise.reject(new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\"));\n\t}\n\treturn Promise.resolve(singleFromAnyValue(input as T));\n}\n\n/**\n * Keyed singleflight over {@link NodeInput}. Concurrent calls with the same key share one Promise;\n * once that input resolves/rejects, the in-flight entry is cleared and a later call re-runs the\n * factory. Host-boundary helper only; it does not create graph topology.\n */\nexport function singleFromAny<K, T>(\n\tfactory: (key: K) => NodeInput<T>,\n\topts: SingleFromAnyOptions<K> = {},\n): (key: K) => Promise<T> {\n\tconst keyOf = opts.keyOf ?? ((key: K): unknown => key);\n\tconst inFlight = new Map<unknown, Promise<T>>();\n\n\treturn (key: K): Promise<T> => {\n\t\tconst dedupeKey = keyOf(key);\n\t\tconst existing = inFlight.get(dedupeKey);\n\t\tif (existing) return existing;\n\n\t\tlet resolvePending!: (value: T) => void;\n\t\tlet rejectPending!: (reason: unknown) => void;\n\t\tlet tracked!: Promise<T>;\n\t\tconst cleanup = (): void => {\n\t\t\tif (inFlight.get(dedupeKey) === tracked) inFlight.delete(dedupeKey);\n\t\t};\n\t\tconst pending = new Promise<T>((resolve, reject) => {\n\t\t\tresolvePending = resolve;\n\t\t\trejectPending = reject;\n\t\t});\n\t\ttracked = pending.then(\n\t\t\t(value) => {\n\t\t\t\tcleanup();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tcleanup();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tinFlight.set(dedupeKey, tracked);\n\t\ttry {\n\t\t\tnodeInputToPromise(factory(key), opts).then(resolvePending, rejectPending);\n\t\t} catch (e) {\n\t\t\trejectPending(e);\n\t\t}\n\t\treturn tracked;\n\t};\n}\n","/**\n * Reactive key–value map (CSP-2.8, D54/D60/D68) — two-port collection with policy opts.\n *\n * Shape = the shared {@link collectionCore} two ports over a `Map` BACKEND (D60). Specializations\n * (D60 #3 / review #3):\n * - TTL/LRU are node-as-opt policies (D68). Static `maxSize` / `defaultTtl` values become constant\n * policy deps; Node-valued opts are declared deps. The graph-visible `reactiveMap.apply` node is\n * the normal backend mutation path and emits the public delta payloads it materializes.\n * - LAZY TTL (no background timer): expiry is checked at read (`get`/`has`) + at synchronous\n * snapshot materialization (`toMap`/`pruneExpired`). A read/prune that deletes an expired key\n * emits the normal delta `delete{reason:\"expired\"}` (D61). Snapshot demand uses an internal pull\n * `snapshotPrep` node: it prunes expired entries and reads the backend once, then public\n * `snapshot` and `delta` derive from that declared prep payload. No snapshot fn drives its own\n * dep (D37).\n * - delete-reason enum {expired|lru-evict|archived|explicit} on the delta (D60 #3c).\n * - LRU `maxSize`: an over-cap `set` evicts the oldest, emitting a `delete{reason:\"lru-evict\"}`.\n * A live-key `get`/`has` touches LRU order WITHOUT a version bump (internal, D60 #3d).\n * - retention (score-archive, D72): `retention.maxSize` is a value-or-Node numeric policy and\n * the static scorer selects archive victims through the normal `reactiveMap.apply` path.\n *\n * Per-language (D6/D24, never in parity, no conformance — the substrate pull is already C-16).\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepTerminal,\n\tisTerminalComplete,\n\ttype NodeFn,\n} from \"../../ctx/types.js\";\nimport { strictCanonicalJsonBytes } from \"../../json/codec.js\";\nimport { Node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport { registerBackendStateContributor } from \"../checkpoint.js\";\nimport { initNode, type Operator } from \"../operators.js\";\nimport {\n\tdeadlines,\n\tlruKeys,\n\tPolicyInputs,\n\ttype PolicyOpt,\n\ttype ScoredEntry,\n\tselectRetentionVictims,\n\ttrimHeadOverflow,\n} from \"../policies/collection.js\";\nimport type { ReactiveOpt, RetentionPolicy, ViewCachePolicy } from \"../policies/types.js\";\nimport { timer } from \"../sources.js\";\nimport type { MapChange } from \"./change.js\";\nimport {\n\ttype CollectionCoreOptions,\n\tlightReactiveView,\n\ttype ReactiveView,\n\tViewMemoCache,\n} from \"./core.js\";\n\nexport type ReactiveMapOpt<T> = ReactiveOpt<T>;\n\nexport interface ReactiveMapRetentionEntry<K, V> {\n\treadonly key: K;\n\treadonly value: V;\n}\n\nexport interface ReactiveMapRetentionPolicy<K, V>\n\textends RetentionPolicy<ReactiveMapRetentionEntry<K, V>> {\n\t/** Archive capacity. Unlike LRU, zero is allowed and archives every live entry. */\n\treadonly maxSize?: ReactiveMapOpt<number>;\n\t/** Higher scores are retained; lowest finite scores are archived first. */\n\tscore(entry: ReactiveMapRetentionEntry<K, V>): number;\n}\n\ninterface ResolvedRetentionPolicy<K, V> {\n\treadonly maxSize?: number;\n\tscore(entry: ReactiveMapRetentionEntry<K, V>): number;\n}\n\nexport interface ReactiveMapOptions<K = unknown, V = unknown> extends CollectionCoreOptions {\n\t/**\n\t * LRU cap as a node-as-opt policy (D68). A static number is a constant policy config; a Node must\n\t * be graph-bound and becomes a declared dep of `reactiveMap.apply`.\n\t */\n\tmaxSize?: ReactiveMapOpt<number>;\n\t/**\n\t * Default TTL in milliseconds as a node-as-opt policy (D68). Per-call `set(...,{ttl})` overrides.\n\t * Lazy expiry only; no active timer in this cut.\n\t */\n\tdefaultTtl?: ReactiveMapOpt<number>;\n\t/**\n\t * Score-based retention/archive policy (D72). The scorer is static local code; only maxSize can be\n\t * a Node-valued policy, keeping graph describe data serializable while apply owns the mutation.\n\t */\n\tretention?: ReactiveMapRetentionPolicy<K, V>;\n\t/** Static D80 memo policy for D121 light views. Eviction does not dispose returned views. */\n\tviewCache?: ViewCachePolicy;\n\t/** Injectable monotonic-ish clock for TTL (default `Date.now`). Graph-local clock = follow-up (D26). */\n\tnow?: () => number;\n}\n\nexport interface ReactiveMap<K, V> {\n\treadonly delta: Node<MapChange<K, V>>;\n\treadonly snapshot: Node<ReadonlyMap<K, V>>;\n\treadonly pullId: symbol;\n\t/** Raw entry count (O(1)); may include not-yet-pruned expired entries. Sync non-reactive read. */\n\treadonly size: number;\n\t/** Get a live value (prunes the key if expired). Sync read. */\n\tget(key: K): V | undefined;\n\t/** Live-key existence (prunes if expired). Sync read. */\n\thas(key: K): boolean;\n\t/** Current live (non-expired) entries (fresh copy). Sync non-reactive read (cold-start peek). */\n\ttoMap(): ReadonlyMap<K, V>;\n\t/**\n\t * D121 light selected-map view. `delta` forwards parent map mutations, and `snapshot` is a pull\n\t * node that materializes the currently matching live entries on demand.\n\t */\n\tselect(\n\t\tpredicate: (value: V, key: K) => boolean,\n\t): ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>;\n\tset(key: K, value: V, opts?: { ttl?: number }): void;\n\t/** Bulk set; one delta event per entry, one snapshot-arm. No-op if empty. */\n\tsetMany(entries: Iterable<readonly [K, V]>, opts?: { ttl?: number }): void;\n\tdelete(key: K): void;\n\t/** Bulk delete; one delta per removed key. No-op if none present. */\n\tdeleteMany(keys: Iterable<K>): void;\n\tclear(): void;\n\t/** Explicitly prune expired entries; every removed key emits `delete{reason:\"expired\"}` (D61). */\n\tpruneExpired(): void;\n\t/** D54 widening: every `[key, value]` from `src` is set. Returns a disposer. */\n\tsetFrom(src: Node<readonly [K, V]>): () => void;\n\tdispose(): void;\n}\n\ninterface Entry<V> {\n\tvalue: V;\n\texpiresAt?: number;\n}\n\nfunction strictJsonIdentity(value: unknown): string {\n\treturn Array.from(strictCanonicalJsonBytes(value)).join(\",\");\n}\n\ntype Lookup<V> =\n\t| { found: true; value: V }\n\t| { found: false; expired?: false }\n\t| { found: false; expired: true; previous: V };\n\ninterface SnapshotPrep<K, V> {\n\treadonly snapshot: ReadonlyMap<K, V>;\n\treadonly expired: readonly MapChange<K, V>[];\n}\n\ntype MapIntent<K, V> =\n\t| { kind: \"set\"; key: K; value: V; ttl?: number }\n\t| { kind: \"delete\"; key: K }\n\t| { kind: \"clear\" }\n\t| { kind: \"pruneExpired\" }\n\t| { kind: \"pruneKey\"; key: K };\n\n/** Default `Map`-backed store. TTL/LRU policy lives in graph-visible policy/apply nodes (D68). */\nclass MapBackend<K, V> {\n\tprivate _version = 0;\n\tprivate readonly store = new Map<K, Entry<V>>();\n\tprivate readonly now: () => number;\n\n\tconstructor(opts: { now?: () => number }) {\n\t\tthis.now = opts.now ?? Date.now;\n\t}\n\n\tget version(): number {\n\t\treturn this._version;\n\t}\n\n\tget size(): number {\n\t\treturn this.store.size;\n\t}\n\n\tnowMs(): number {\n\t\treturn this.now();\n\t}\n\n\texpiresAtOf(key: K): number | undefined {\n\t\treturn this.store.get(key)?.expiresAt;\n\t}\n\n\tprivate isExpired(e: Entry<V>): boolean {\n\t\treturn e.expiresAt !== undefined && this.now() >= e.expiresAt;\n\t}\n\n\tresolveExpiresAt(ttl?: number): number | undefined {\n\t\tif (ttl === undefined) return undefined;\n\t\tif (!Number.isFinite(ttl) || ttl <= 0)\n\t\t\tthrow new RangeError(`reactiveMap: ttl must be a positive finite number (got ${ttl})`);\n\t\treturn this.now() + ttl;\n\t}\n\n\tprivate deleteExpired(key: K, e: Entry<V>): Array<[K, V]> {\n\t\tthis.store.delete(key);\n\t\tthis._version += 1;\n\t\treturn [[key, e.value]];\n\t}\n\n\t/** Read without materializing expiry. Caller routes expired deletes through the apply node (D68). */\n\tlookup(key: K): Lookup<V> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined) return { found: false };\n\t\tif (this.isExpired(e)) return { found: false, expired: true, previous: e.value };\n\t\t// LRU touch (no version bump — internal, D60 #3d).\n\t\tthis.store.delete(key);\n\t\tthis.store.set(key, e);\n\t\treturn { found: true, value: e.value };\n\t}\n\n\t/** Set; returns the entries evicted by LRU overflow (the caller emits their delete deltas). */\n\tset(key: K, value: V, expiresAt?: number): void {\n\t\tif (this.store.has(key)) this.store.delete(key); // re-insert at LRU end\n\t\tthis.store.set(key, { value, expiresAt });\n\t\tthis._version += 1;\n\t}\n\n\tenforceLru(maxSize?: number): Array<[K, V]> {\n\t\tconst evicted: Array<[K, V]> = [];\n\t\tfor (const oldest of trimHeadOverflow(lruKeys(this.store.keys()).keys(), {\n\t\t\tmaxSize,\n\t\t\tsize: this.store.size,\n\t\t})) {\n\t\t\tconst e = this.store.get(oldest);\n\t\t\tif (e !== undefined) evicted.push([oldest, e.value]);\n\t\t\tthis.store.delete(oldest);\n\t\t}\n\t\tif (evicted.length > 0) this._version += 1;\n\t\treturn evicted;\n\t}\n\n\tenforceRetention(policy?: ResolvedRetentionPolicy<K, V>): Array<[K, V]> {\n\t\tif (policy === undefined || policy.maxSize === undefined) return [];\n\t\tconst scored: ScoredEntry<readonly [K, V]>[] = [];\n\t\tfor (const [key, entry] of this.store) {\n\t\t\tif (!this.isExpired(entry)) {\n\t\t\t\tscored.push({\n\t\t\t\t\tentry: [key, entry.value] as const,\n\t\t\t\t\tscore: policy.score({ key, value: entry.value }),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst archived = selectRetentionVictims(scored, { maxSize: policy.maxSize });\n\t\tfor (const [key] of archived) this.store.delete(key);\n\t\tif (archived.length > 0) this._version += 1;\n\t\treturn archived.map(([key, value]) => [key, value]);\n\t}\n\n\tdelete(key: K): Lookup<V> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined) return { found: false };\n\t\tthis.store.delete(key);\n\t\tthis._version += 1;\n\t\treturn { found: true, value: e.value };\n\t}\n\n\tclear(): number {\n\t\tconst n = this.store.size;\n\t\tif (n === 0) return 0;\n\t\tthis.store.clear();\n\t\tthis._version += 1;\n\t\treturn n;\n\t}\n\n\tpruneExpired(): Array<[K, V]> {\n\t\tconst removed: Array<[K, V]> = [];\n\t\tfor (const [k, e] of this.store) {\n\t\t\tif (this.isExpired(e)) {\n\t\t\t\tthis.store.delete(k);\n\t\t\t\tremoved.push([k, e.value]);\n\t\t\t}\n\t\t}\n\t\tif (removed.length > 0) this._version += 1;\n\t\treturn removed;\n\t}\n\n\tpruneKeyIfExpired(key: K): Array<[K, V]> {\n\t\tconst e = this.store.get(key);\n\t\tif (e === undefined || !this.isExpired(e)) return [];\n\t\treturn this.deleteExpired(key, e);\n\t}\n\n\t/** Fresh snapshot of live entries. Does not prune; callers choose whether to materialize expiry. */\n\tsnapshot(): ReadonlyMap<K, V> {\n\t\tconst out = new Map<K, V>();\n\t\tfor (const [k, e] of this.store) if (!this.isExpired(e)) out.set(k, e.value);\n\t\treturn out;\n\t}\n\n\t/** D160 checkpoint payload: exact restorable map entries, excluding TTL-bearing state. */\n\tcheckpointEntries(): readonly (readonly [K, V])[] {\n\t\tconst out: Array<readonly [K, V]> = [];\n\t\tconst seen = new Set<string>();\n\t\tfor (const [key, entry] of this.store) {\n\t\t\tif (entry.expiresAt !== undefined) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"reactiveMap checkpoint backendState cannot preserve per-entry TTL; persist the map externally or clear TTL state before graph checkpoint (D160)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stableKey = strictJsonIdentity(key);\n\t\t\tif (seen.has(stableKey)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"reactiveMap checkpoint backendState contains duplicate strict-JSON keys (D160)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tseen.add(stableKey);\n\t\t\tout.push([key, entry.value] as const);\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/**\n * Create a reactive map (D54/D60). DELTA stream of {@link MapChange} + lazy pull SNAPSHOT (a\n * `ReadonlyMap`) + pullId via {@link collectionCore}; this layer adds the typed map surface.\n */\nexport function reactiveMap<K, V>(options: ReactiveMapOptions<K, V> = {}): ReactiveMap<K, V> {\n\treturn createReactiveMap(options);\n}\n\n/** @internal D161 restore path: seed the backend without replaying public deltas. */\nexport function restoreReactiveMapFromBackendState<K, V>(\n\tinitialEntries: readonly (readonly [K, V])[],\n\toptions: ReactiveMapOptions<K, V> = {},\n): ReactiveMap<K, V> {\n\treturn createReactiveMap(options, initialEntries);\n}\n\nfunction createReactiveMap<K, V>(\n\toptions: ReactiveMapOptions<K, V> = {},\n\tinitialEntries: readonly (readonly [K, V])[] = [],\n): ReactiveMap<K, V> {\n\tconst { maxSize, defaultTtl, retention, viewCache, now, name, dispatcher, graph } = options;\n\tconst backend = new MapBackend<K, V>({ now });\n\tfor (const [key, value] of initialEntries) backend.set(key, value);\n\tconst base = dispatcher ? { dispatcher } : {};\n\tconst restorable =\n\t\tgraph !== undefined &&\n\t\tname !== undefined &&\n\t\tmaxSize === undefined &&\n\t\tdefaultTtl === undefined &&\n\t\tretention === undefined;\n\n\tfunction isNodeOpt<T>(x: PolicyOpt<T> | undefined): x is Node<T> {\n\t\treturn x instanceof Node;\n\t}\n\n\tfunction validateMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 1)\n\t\t\tthrow new RangeError(`reactiveMap: maxSize must be a positive integer (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction validateTtl(v: number): number {\n\t\tif (!Number.isFinite(v) || v <= 0)\n\t\t\tthrow new RangeError(`reactiveMap: defaultTtl must be a positive finite number (got ${v})`);\n\t\treturn v;\n\t}\n\n\tfunction validateRetentionMaxSize(v: number): number {\n\t\tif (!Number.isFinite(v) || !Number.isInteger(v) || v < 0)\n\t\t\tthrow new RangeError(\n\t\t\t\t`reactiveMap: retention.maxSize must be a non-negative integer (got ${v})`,\n\t\t\t);\n\t\treturn v;\n\t}\n\n\tif (retention !== undefined && typeof retention.score !== \"function\")\n\t\tthrow new TypeError(\"reactiveMap: retention.score must be a function\");\n\n\ttype PolicyLabel = \"lruPolicy\" | \"ttlPolicy\" | \"retentionPolicy\";\n\n\tfunction constPolicyNode(label: PolicyLabel, value: number): Node<number> {\n\t\tconst op: Operator<never, number> = {\n\t\t\tfactory: `reactiveMap.${label}`,\n\t\t\tbody: () => {},\n\t\t\topts: { initial: value },\n\t\t};\n\t\tif (graph) {\n\t\t\treturn graph.initNode(op, [], {\n\t\t\t\tname: name ? `${name}.${label}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy\", collection: \"reactiveMap\", policy: label },\n\t\t\t});\n\t\t}\n\t\treturn new Node<number>([], null, {\n\t\t\t...base,\n\t\t\tinitial: value,\n\t\t\tfactory: `reactiveMap.${label}`,\n\t\t\tname: name ? `${name}.${label}` : undefined,\n\t\t});\n\t}\n\n\tfunction policyNode(\n\t\tlabel: PolicyLabel,\n\t\topt: PolicyOpt<number> | undefined,\n\t\tvalidate: (v: number) => number,\n\t): Node<number> | undefined {\n\t\tif (opt === undefined) return undefined;\n\t\tif (isNodeOpt(opt)) {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`reactiveMap ${label} Node option requires options.graph so the policy edge is describe-visible (${label === \"retentionPolicy\" ? \"D72\" : \"D68\"})`,\n\t\t\t\t);\n\t\t\treturn opt;\n\t\t}\n\t\treturn constPolicyNode(label, validate(opt));\n\t}\n\n\tconst intentOp: Operator<never, MapIntent<K, V>> = {\n\t\tfactory: \"reactiveMap.intent\",\n\t\tbody: () => {},\n\t};\n\tconst intent = graph\n\t\t? graph.initNode(intentOp, [], {\n\t\t\t\tname: name ? `${name}.intent` : undefined,\n\t\t\t\tmeta: { kind: \"collection_intent\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.intent\" } } : {}),\n\t\t\t})\n\t\t: new Node<MapIntent<K, V>>([], null, {\n\t\t\t\t...base,\n\t\t\t\tfactory: \"reactiveMap.intent\",\n\t\t\t\tname: name ? `${name}.intent` : undefined,\n\t\t\t});\n\tconst lruPolicy = policyNode(\"lruPolicy\", maxSize, validateMaxSize);\n\tconst ttlPolicy = policyNode(\"ttlPolicy\", defaultTtl, validateTtl);\n\tconst retentionPolicy = policyNode(\n\t\t\"retentionPolicy\",\n\t\tretention?.maxSize,\n\t\tvalidateRetentionMaxSize,\n\t);\n\n\tlet currentMaxSize = isNodeOpt(maxSize) ? undefined : maxSize;\n\tlet currentDefaultTtl = isNodeOpt(defaultTtl) ? undefined : defaultTtl;\n\tlet currentRetentionMaxSize = isNodeOpt(retention?.maxSize)\n\t\t? undefined\n\t\t: retention?.maxSize === undefined\n\t\t\t? undefined\n\t\t\t: validateRetentionMaxSize(retention.maxSize);\n\tconst ttlHeap = deadlines<K>();\n\tlet ttlTimer: Node<unknown> | null = null;\n\tlet ttlTimerDue: number | undefined;\n\tconst bindDeps = new WeakSet<Node<unknown>>();\n\tlet bindSeq = 0;\n\tlet apply: Node<MapChange<K, V>>;\n\tconst selectMemo = new ViewMemoCache<\n\t\t(value: V, key: K) => boolean,\n\t\tReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>\n\t>(viewCache);\n\tlet selectSeq = 0;\n\n\tconst policyInputs = new PolicyInputs([intent as Node<unknown>]);\n\tconst lruReader = policyInputs.add(lruPolicy);\n\tconst ttlReader = policyInputs.add(ttlPolicy);\n\tconst retentionReader = policyInputs.add(retentionPolicy);\n\n\tfunction emitExpired(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"expired\" }]]);\n\t}\n\n\tfunction emitLruEvicted(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"lru-evict\" }]]);\n\t}\n\n\tfunction emitArchived(ctx: Ctx, entries: Array<[K, V]>): void {\n\t\tfor (const [key, previous] of entries)\n\t\t\tctx.down([[\"DATA\", { kind: \"delete\", key, previous, reason: \"archived\" }]]);\n\t}\n\n\tfunction nextValidExpiry(): { readonly key: K; readonly expiresAt: number } | undefined {\n\t\tfor (;;) {\n\t\t\tconst top = ttlHeap.peek();\n\t\t\tif (top === undefined) return undefined;\n\t\t\tif (backend.expiresAtOf(top.key) === top.expiresAt) return top;\n\t\t\tttlHeap.pop();\n\t\t}\n\t}\n\n\tfunction scheduleTtl(ctx: Ctx, body: NodeFn): void {\n\t\tfor (;;) {\n\t\t\tconst next = nextValidExpiry();\n\t\t\tif (next === undefined) {\n\t\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, body);\n\t\t\t\tttlTimer = null;\n\t\t\t\tttlTimerDue = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (next.expiresAt <= backend.nowMs()) {\n\t\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ttlTimerDue === next.expiresAt) return;\n\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, body);\n\t\t\tttlTimerDue = next.expiresAt;\n\t\t\tttlTimer = initNode(timer(Math.max(0, next.expiresAt - backend.nowMs())), [], base);\n\t\t\tctx.rewireNext.subscribeDep(ttlTimer, body);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tfunction applyIntent(ctx: Ctx, intentValue: MapIntent<K, V>): void {\n\t\tif (intentValue.kind === \"set\") {\n\t\t\tconst ttl = intentValue.ttl ?? currentDefaultTtl;\n\t\t\tconst expiresAt = backend.resolveExpiresAt(ttl);\n\t\t\tbackend.set(intentValue.key, intentValue.value, expiresAt);\n\t\t\tif (expiresAt !== undefined) ttlHeap.push({ key: intentValue.key, expiresAt });\n\t\t\tctx.down([[\"DATA\", { kind: \"set\", key: intentValue.key, value: intentValue.value }]]);\n\t\t\temitLruEvicted(ctx, backend.enforceLru(currentMaxSize));\n\t\t\temitArchived(\n\t\t\t\tctx,\n\t\t\t\tbackend.enforceRetention(\n\t\t\t\t\tretention ? { maxSize: currentRetentionMaxSize, score: retention.score } : undefined,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"delete\") {\n\t\t\tconst previous = backend.delete(intentValue.key);\n\t\t\tif (previous.found)\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{ kind: \"delete\", key: intentValue.key, previous: previous.value, reason: \"explicit\" },\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"clear\") {\n\t\t\tconst count = backend.clear();\n\t\t\tif (count > 0) ctx.down([[\"DATA\", { kind: \"clear\", count }]]);\n\t\t\treturn;\n\t\t}\n\t\tif (intentValue.kind === \"pruneExpired\") {\n\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\treturn;\n\t\t}\n\t\temitExpired(ctx, backend.pruneKeyIfExpired(intentValue.key));\n\t}\n\n\tconst applyBody: NodeFn = (ctx: Ctx) => {\n\t\tconst nextMaxSize = lruReader.read(ctx, currentMaxSize);\n\t\tcurrentMaxSize = nextMaxSize === undefined ? undefined : validateMaxSize(nextMaxSize);\n\t\tconst nextTtl = ttlReader.read(ctx, currentDefaultTtl);\n\t\tcurrentDefaultTtl = nextTtl === undefined ? undefined : validateTtl(nextTtl);\n\t\tconst nextRetentionMaxSize = retentionReader.read(ctx, currentRetentionMaxSize);\n\t\tcurrentRetentionMaxSize =\n\t\t\tnextRetentionMaxSize === undefined\n\t\t\t\t? undefined\n\t\t\t\t: validateRetentionMaxSize(nextRetentionMaxSize);\n\n\t\tfor (const item of (depBatch(ctx, 0) ?? []) as readonly MapIntent<K, V>[]) {\n\t\t\tapplyIntent(ctx, item);\n\t\t}\n\t\tconst deps = apply.deps;\n\t\tfor (let i = 1; i < depCount(ctx); i++) {\n\t\t\tif (i === lruReader.index || i === ttlReader.index || i === retentionReader.index) continue;\n\t\t\tconst dep = deps[i];\n\t\t\tif (dep && bindDeps.has(dep)) {\n\t\t\t\tfor (const item of (depBatch(ctx, i) ?? []) as readonly MapIntent<K, V>[]) {\n\t\t\t\t\tapplyIntent(ctx, item);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdep === ttlTimer &&\n\t\t\t\t((depBatch(ctx, i)?.length ?? 0) > 0 || isTerminalComplete(depTerminal(ctx, i)))\n\t\t\t) {\n\t\t\t\tif (ttlTimer) ctx.rewireNext.unsubscribeDep(ttlTimer, applyBody);\n\t\t\t\tttlTimer = null;\n\t\t\t\tttlTimerDue = undefined;\n\t\t\t\temitExpired(ctx, backend.pruneExpired());\n\t\t\t}\n\t\t}\n\t\t// Lowering a reactive maxSize is itself a policy-driven backend mutation (D68).\n\t\temitLruEvicted(ctx, backend.enforceLru(currentMaxSize));\n\t\temitArchived(\n\t\t\tctx,\n\t\t\tbackend.enforceRetention(\n\t\t\t\tretention ? { maxSize: currentRetentionMaxSize, score: retention.score } : undefined,\n\t\t\t),\n\t\t);\n\t\tscheduleTtl(ctx, applyBody);\n\t};\n\n\tconst applyOp: Operator<unknown, MapChange<K, V>> = {\n\t\tfactory: \"reactiveMap.apply\",\n\t\tbody: applyBody,\n\t\topts: { partial: true },\n\t};\n\tapply = graph\n\t\t? graph.initNode(applyOp, policyInputs.deps as readonly Node<unknown>[], {\n\t\t\t\tname: name ? `${name}.apply` : undefined,\n\t\t\t\tmeta: { kind: \"collection_policy_apply\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.apply\" } } : {}),\n\t\t\t})\n\t\t: initNode(applyOp, policyInputs.deps, {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.apply` : undefined,\n\t\t\t});\n\n\tconst pullId = Symbol(name ? `${name}.snapshot` : \"reactiveMap.snapshot\");\n\tconst snapshotPrepOp: Operator<unknown, SnapshotPrep<K, V>> = {\n\t\tfactory: \"reactiveMap.snapshotPrep\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tconst expired = backend.pruneExpired().map(\n\t\t\t\t([key, previous]): MapChange<K, V> => ({\n\t\t\t\t\tkind: \"delete\",\n\t\t\t\t\tkey,\n\t\t\t\t\tprevious,\n\t\t\t\t\treason: \"expired\",\n\t\t\t\t}),\n\t\t\t);\n\t\t\tctx.down([[\"DATA\", { snapshot: backend.snapshot(), expired }]]);\n\t\t},\n\t\topts: {\n\t\t\t...base,\n\t\t\tpullId,\n\t\t\tpartial: true,\n\t\t},\n\t};\n\tconst snapshotPrep = graph\n\t\t? graph.initNode(snapshotPrepOp, [apply as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.snapshotPrep` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot_prep\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.snapshotPrep\" } } : {}),\n\t\t\t})\n\t\t: initNode(snapshotPrepOp, [apply as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.snapshotPrep` : undefined,\n\t\t\t});\n\tconst deltaOp: Operator<unknown, MapChange<K, V>> = {\n\t\tfactory: \"reactiveMap.delta\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tfor (const change of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", change as MapChange<K, V>]]);\n\t\t\t}\n\t\t\tfor (const prep of depBatch(ctx, 1) ?? []) {\n\t\t\t\tfor (const change of (prep as SnapshotPrep<K, V>).expired) ctx.down([[\"DATA\", change]]);\n\t\t\t}\n\t\t},\n\t\topts: { partial: true },\n\t};\n\tconst delta = graph\n\t\t? graph.initNode(deltaOp, [apply as Node<unknown>, snapshotPrep as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t\tmeta: { kind: \"collection_delta\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.delta\" } } : {}),\n\t\t\t})\n\t\t: initNode(deltaOp, [apply as Node<unknown>, snapshotPrep as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.delta` : undefined,\n\t\t\t});\n\tconst snapshotOp: Operator<unknown, ReadonlyMap<K, V>> = {\n\t\tfactory: \"reactiveMap.snapshot\",\n\t\tbody: (ctx: Ctx) => {\n\t\t\tfor (const prep of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", (prep as SnapshotPrep<K, V>).snapshot]]);\n\t\t\t}\n\t\t},\n\t\topts: { partial: true },\n\t};\n\tconst snapshot = graph\n\t\t? graph.initNode(snapshotOp, [snapshotPrep as Node<unknown>], {\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t\tmeta: { kind: \"collection_snapshot\", collection: \"reactiveMap\" },\n\t\t\t\t...(restorable ? { restore: { ref: \"reactiveMap.snapshot\" } } : {}),\n\t\t\t})\n\t\t: initNode(snapshotOp, [snapshotPrep as Node<unknown>], {\n\t\t\t\t...base,\n\t\t\t\tname: name ? `${name}.snapshot` : undefined,\n\t\t\t});\n\tif (restorable) {\n\t\tregisterBackendStateContributor(intent as Node<unknown>, () => backend.checkpointEntries());\n\t}\n\tconst releaseApply = graph\n\t\t? graph.retain(apply, { reason: \"reactiveMap.apply\" })\n\t\t: apply.subscribe(() => {});\n\tconst binds: Array<() => void> = [];\n\n\tfunction doSet(key: K, value: V, ttl?: number): void {\n\t\tif (ttl !== undefined) validateTtl(ttl);\n\t\tintent.down([\n\t\t\t[\"DATA\", ttl === undefined ? { kind: \"set\", key, value } : { kind: \"set\", key, value, ttl }],\n\t\t]);\n\t}\n\n\tfunction read(key: K): Lookup<V> {\n\t\tconst r = backend.lookup(key);\n\t\tif (!r.found && r.expired) intent.down([[\"DATA\", { kind: \"pruneKey\", key }]]);\n\t\treturn r;\n\t}\n\n\tfunction selectedSnapshot(predicate: (value: V, key: K) => boolean): ReadonlyMap<K, V> {\n\t\tconst out = new Map<K, V>();\n\t\tfor (const [key, value] of backend.snapshot()) {\n\t\t\tif (predicate(value, key)) out.set(key, value);\n\t\t}\n\t\treturn out;\n\t}\n\n\tfunction select(\n\t\tpredicate: (value: V, key: K) => boolean,\n\t): ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>> {\n\t\tif (typeof predicate !== \"function\")\n\t\t\tthrow new TypeError(\"reactiveMap.select: predicate must be a function\");\n\t\tconst cached = selectMemo.get(predicate);\n\t\tif (cached !== undefined) return cached;\n\t\tlet view: ReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>;\n\t\tview = lightReactiveView<MapChange<K, V>, ReadonlyMap<K, V>>(delta as Node<unknown>, {\n\t\t\tdispatcher,\n\t\t\tgraph,\n\t\t\tfactory: \"reactiveMap.select\",\n\t\t\tname: name ? `${name}.select#${selectSeq++}` : undefined,\n\t\t\tmaterializeSnapshot: () => selectedSnapshot(predicate),\n\t\t\tonDispose: () => {\n\t\t\t\tselectMemo.deleteValue(view);\n\t\t\t},\n\t\t});\n\t\tselectMemo.set(predicate, view);\n\t\treturn view;\n\t}\n\n\treturn {\n\t\tdelta,\n\t\tsnapshot,\n\t\tpullId,\n\n\t\tget size(): number {\n\t\t\treturn backend.size;\n\t\t},\n\t\tget(key: K): V | undefined {\n\t\t\tconst r = read(key);\n\t\t\treturn r.found ? r.value : undefined;\n\t\t},\n\t\thas(key: K): boolean {\n\t\t\treturn read(key).found;\n\t\t},\n\t\ttoMap(): ReadonlyMap<K, V> {\n\t\t\tintent.down([[\"DATA\", { kind: \"pruneExpired\" }]]);\n\t\t\treturn backend.snapshot();\n\t\t},\n\t\tselect,\n\n\t\tset(key: K, value: V, opts?: { ttl?: number }): void {\n\t\t\tdoSet(key, value, opts?.ttl);\n\t\t},\n\t\tsetMany(entries: Iterable<readonly [K, V]>, opts?: { ttl?: number }): void {\n\t\t\tfor (const [k, v] of entries) doSet(k, v, opts?.ttl);\n\t\t},\n\t\tdelete(key: K): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"delete\", key }]]);\n\t\t},\n\t\tdeleteMany(keys: Iterable<K>): void {\n\t\t\tfor (const k of keys) {\n\t\t\t\tintent.down([[\"DATA\", { kind: \"delete\", key: k }]]);\n\t\t\t}\n\t\t},\n\t\tclear(): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"clear\" }]]);\n\t\t},\n\t\tpruneExpired(): void {\n\t\t\tintent.down([[\"DATA\", { kind: \"pruneExpired\" }]]);\n\t\t},\n\n\t\tsetFrom(src: Node<readonly [K, V]>): () => void {\n\t\t\tif (graph === undefined)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"reactiveMap.setFrom requires options.graph so the input fold is describe-visible (D61)\",\n\t\t\t\t);\n\t\t\tconst op: Operator<readonly [K, V], MapIntent<K, V>> = {\n\t\t\t\tfactory: \"reactiveMap.bindSource\",\n\t\t\t\tbody: (ctx: Ctx) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const [k, v] of (depBatch(ctx, 0) ?? []) as readonly (readonly [K, V])[]) {\n\t\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"set\", key: k, value: v }]]);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"reactiveMap.bindSource failed\")]]);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst folder = graph.initNode(op, [src], {\n\t\t\t\tname: name ? `${name}.bind#${bindSeq++}` : undefined,\n\t\t\t\tmeta: { kind: \"collection_bind_source\", collection: \"reactiveMap\" },\n\t\t\t});\n\t\t\tbindDeps.add(folder as Node<unknown>);\n\t\t\tapply.subscribeDep(folder as Node<unknown>, applyBody);\n\t\t\tlet active = true;\n\t\t\tconst dispose = () => {\n\t\t\t\tif (!active) return;\n\t\t\t\tactive = false;\n\t\t\t\tapply.unsubscribeDep(folder as Node<unknown>, applyBody);\n\t\t\t};\n\t\t\tbinds.push(dispose);\n\t\t\treturn dispose;\n\t\t},\n\t\tdispose(): void {\n\t\t\tselectMemo.disposeAll();\n\t\t\tfor (const d of binds) d();\n\t\t\tbinds.length = 0;\n\t\t\treleaseApply();\n\t\t},\n\t};\n}\n","import type {\n\tIndexRow,\n\tReactiveIndex,\n\tReactiveIndexOptions,\n} from \"../graph/data-structures/reactive-index.js\";\nimport { restoreReactiveIndexFromBackendState } from \"../graph/data-structures/reactive-index.js\";\nimport type { ReactiveListOptions } from \"../graph/data-structures/reactive-list.js\";\nimport { type ReactiveList, reactiveList } from \"../graph/data-structures/reactive-list.js\";\nimport type { ReactiveLogOptions } from \"../graph/data-structures/reactive-log.js\";\nimport { type ReactiveLog, reactiveLog } from \"../graph/data-structures/reactive-log.js\";\nimport type { ReactiveMap, ReactiveMapOptions } from \"../graph/data-structures/reactive-map.js\";\nimport { restoreReactiveMapFromBackendState } from \"../graph/data-structures/reactive-map.js\";\nimport type {\n\tReactiveIndexRestoreState,\n\tReactiveListRestoreState,\n\tReactiveLogRestoreState,\n\tReactiveMapRestoreState,\n} from \"../storage/index.js\";\n\nfunction isListRestoreState<T>(\n\tstate: ReactiveListRestoreState<T> | readonly T[],\n): state is ReactiveListRestoreState<T> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreListValues<T>(state: ReactiveListRestoreState<T> | readonly T[]): readonly T[] {\n\tif (!isListRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveList\") throw new TypeError(\"restore state kind must be reactiveList\");\n\treturn state.state;\n}\n\nfunction isLogRestoreState<T>(\n\tstate: ReactiveLogRestoreState<T> | readonly T[],\n): state is ReactiveLogRestoreState<T> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreLogValues<T>(state: ReactiveLogRestoreState<T> | readonly T[]): readonly T[] {\n\tif (!isLogRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveLog\") throw new TypeError(\"restore state kind must be reactiveLog\");\n\treturn state.state;\n}\n\nfunction isMapRestoreState<K, V>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n): state is ReactiveMapRestoreState<K, V> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreMapEntries<K, V>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n): readonly (readonly [K, V])[] {\n\tif (!isMapRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveMap\") throw new TypeError(\"restore state kind must be reactiveMap\");\n\treturn state.state;\n}\n\nfunction isIndexRestoreState<K, V>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n): state is ReactiveIndexRestoreState<K, V> {\n\treturn !Array.isArray(state);\n}\n\nfunction restoreIndexRows<K, V>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n): readonly IndexRow<K, V>[] {\n\tif (!isIndexRestoreState(state)) return state;\n\tif (state.kind !== \"reactiveIndex\") {\n\t\tthrow new TypeError(\"restore state kind must be reactiveIndex\");\n\t}\n\treturn state.state;\n}\n\n/** D161 synchronous collection-owned restore. This helper never reads storage. */\nexport function restoreReactiveList<T = unknown>(\n\tstate: ReactiveListRestoreState<T> | readonly T[],\n\toptions: ReactiveListOptions = {},\n): ReactiveList<T> {\n\tconst values = restoreListValues(state);\n\treturn reactiveList<T>(values, options);\n}\n\n/** D161 synchronous collection-owned restore. This helper never reads storage. */\nexport function restoreReactiveLog<T = unknown>(\n\tstate: ReactiveLogRestoreState<T> | readonly T[],\n\toptions: ReactiveLogOptions = {},\n): ReactiveLog<T> {\n\tconst values = restoreLogValues(state);\n\treturn reactiveLog<T>(values, options);\n}\n\n/** D161 synchronous collection-owned restore for map entries; policy config still comes from options. */\nexport function restoreReactiveMap<K = unknown, V = unknown>(\n\tstate: ReactiveMapRestoreState<K, V> | readonly (readonly [K, V])[],\n\toptions: ReactiveMapOptions<K, V> = {},\n): ReactiveMap<K, V> {\n\tconst entries = restoreMapEntries(state);\n\treturn restoreReactiveMapFromBackendState<K, V>(entries, options);\n}\n\n/** D161 synchronous collection-owned restore for sorted index rows; key-codec I/O stays outside. */\nexport function restoreReactiveIndex<K = unknown, V = unknown>(\n\tstate: ReactiveIndexRestoreState<K, V> | readonly IndexRow<K, V>[],\n\toptions: ReactiveIndexOptions = {},\n): ReactiveIndex<K, V> {\n\tconst rows = restoreIndexRows(state);\n\treturn restoreReactiveIndexFromBackendState<K, V>(rows, options);\n}\n","import type {\n\tIndexChange,\n\tListChange,\n\tLogChange,\n\tMapChange,\n} from \"../graph/data-structures/change.js\";\nimport type { IndexRow } from \"../graph/data-structures/reactive-index.js\";\nimport { strictCanonicalJsonBytes, strictJsonCodecFor } from \"../json/codec.js\";\nimport type { AppendLogStorageTier } from \"./append-log.js\";\nimport type { Codec } from \"./codec.js\";\nimport type { KvStorageTier } from \"./kv.js\";\n\n/** D161 strict-JSON snapshot frame format tag for reactive collection persistence. */\nexport const REACTIVE_COLLECTION_SNAPSHOT_FORMAT =\n\t\"graphrefly.reactive-collection.snapshot.v1\" as const;\n/** D161 strict-JSON change frame format tag for reactive collection persistence. */\nexport const REACTIVE_COLLECTION_CHANGE_FORMAT =\n\t\"graphrefly.reactive-collection.change.v1\" as const;\n/** D161 v1 frame version for reactive collection snapshot/change storage. */\nexport const REACTIVE_COLLECTION_FRAME_VERSION = 1 as const;\n\n/** D161 collection kinds recognized by the unified persistence frame envelope. */\nexport type ReactiveCollectionStorageKind =\n\t| \"reactiveList\"\n\t| \"reactiveLog\"\n\t| \"reactiveMap\"\n\t| \"reactiveIndex\";\n\n/** D161 durable baseline frame; storage is passive and does not own graph restore. */\nexport interface ReactiveCollectionSnapshotFrame<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tS = unknown,\n> {\n\treadonly format: typeof REACTIVE_COLLECTION_SNAPSHOT_FORMAT;\n\treadonly version: typeof REACTIVE_COLLECTION_FRAME_VERSION;\n\treadonly kind: K;\n\t/** Last append-log seq reflected by this snapshot; -1 means no change-log entry. */\n\treadonly changeCursor: number;\n\treadonly snapshot: S;\n}\n\n/** D161 append-log change frame; change-log replay is collection-state folding, not graph restore. */\nexport interface ReactiveCollectionChangeFrame<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tC = unknown,\n> {\n\treadonly format: typeof REACTIVE_COLLECTION_CHANGE_FORMAT;\n\treadonly version: typeof REACTIVE_COLLECTION_FRAME_VERSION;\n\treadonly kind: K;\n\treadonly change: C;\n}\n\n/** D161 passive load/fold result consumed by synchronous restoreReactive* helpers. */\nexport interface ReactiveCollectionRestoreState<\n\tK extends ReactiveCollectionStorageKind = ReactiveCollectionStorageKind,\n\tS = unknown,\n> {\n\treadonly kind: K;\n\treadonly state: S;\n\treadonly source: \"empty\" | \"changes\" | \"snapshot\" | \"snapshot+changes\";\n\treadonly snapshot: { readonly found: boolean; readonly changeCursor: number };\n\treadonly changes: { readonly applied: number; readonly cursor: number };\n}\n\n/** D161 restore state for a reactiveList materialized as a strict-JSON array snapshot. */\nexport type ReactiveListRestoreState<T = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveList\",\n\treadonly T[]\n>;\n\n/** D161 restore state for a reactiveLog materialized as a strict-JSON array snapshot. */\nexport type ReactiveLogRestoreState<T = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveLog\",\n\treadonly T[]\n>;\n\n/** D161 passive restore-state shape for reactiveMap; policy-aware restore remains deferred. */\nexport type ReactiveMapRestoreState<K = unknown, V = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveMap\",\n\treadonly (readonly [K, V])[]\n>;\n\n/** D161 passive restore-state shape for reactiveIndex; key-codec restore remains deferred. */\nexport type ReactiveIndexRestoreState<K = unknown, V = unknown> = ReactiveCollectionRestoreState<\n\t\"reactiveIndex\",\n\treadonly IndexRow<K, V>[]\n>;\n\n/** D161 passive storage inputs for collection load/fold helpers. */\nexport interface LoadReactiveCollectionStateOptions {\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nfunction assertKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected frame fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertSafeInteger(value: unknown, label: string, min = 0): number {\n\tif (!Number.isSafeInteger(value) || (value as number) < min) {\n\t\tthrow new TypeError(`${label} must be a safe integer >= ${min}`);\n\t}\n\treturn value as number;\n}\n\nfunction assertKind<K extends ReactiveCollectionStorageKind>(\n\tvalue: unknown,\n\texpected: K,\n\tlabel: string,\n): K {\n\tif (value !== expected) throw new TypeError(`${label}: kind must be ${expected}`);\n\treturn expected;\n}\n\nfunction assertArray<T = unknown>(value: unknown, label: string): readonly T[] {\n\tif (!Array.isArray(value)) throw new TypeError(`${label}: snapshot must be an array`);\n\treturn value as readonly T[];\n}\n\nfunction strictJsonIdentity(value: unknown): string {\n\treturn Array.from(strictCanonicalJsonBytes(value)).join(\",\");\n}\n\nfunction assertEntryArray<K = unknown, V = unknown>(\n\tvalue: unknown,\n\tlabel: string,\n): readonly (readonly [K, V])[] {\n\tconst entries = assertArray<unknown>(value, label);\n\tconst seen = new Set<string>();\n\tfor (const [i, entry] of entries.entries()) {\n\t\tif (!Array.isArray(entry) || entry.length !== 2) {\n\t\t\tthrow new TypeError(`${label}: entry ${i} must be [key,value]`);\n\t\t}\n\t\tconst key = strictJsonIdentity(entry[0]);\n\t\tif (seen.has(key)) throw new TypeError(`${label}: entry ${i} duplicates an earlier key`);\n\t\tseen.add(key);\n\t}\n\treturn entries as readonly (readonly [K, V])[];\n}\n\nfunction assertIndexRows<K = unknown, V = unknown>(\n\tvalue: unknown,\n\tlabel: string,\n): readonly IndexRow<K, V>[] {\n\tconst rows = assertArray<unknown>(value, label);\n\tconst seen = new Set<string>();\n\tfor (const [i, row] of rows.entries()) {\n\t\tif (!isRecord(row)) throw new TypeError(`${label}: row ${i} must be an object`);\n\t\tassertKeys(row, [\"primary\", \"secondary\", \"value\"], `${label} row`);\n\t\tconst primary = strictJsonIdentity(row.primary);\n\t\tif (seen.has(primary)) {\n\t\t\tthrow new TypeError(`${label}: row ${i} duplicates an earlier primary`);\n\t\t}\n\t\tseen.add(primary);\n\t}\n\treturn rows as readonly IndexRow<K, V>[];\n}\n\n/** Build the default D161 snapshot key for a storage prefix. */\nexport function collectionSnapshotKey(storagePrefix = \"reactive-collection\"): string {\n\tif (storagePrefix.length === 0) throw new TypeError(\"storagePrefix must be non-empty\");\n\treturn `${storagePrefix}/snapshot`;\n}\n\n/** Build a D161 strict-JSON snapshot frame before validation/encoding. */\nexport function reactiveCollectionSnapshotFrame<K extends ReactiveCollectionStorageKind, S>(\n\tkind: K,\n\tsnapshot: S,\n\topts: { readonly changeCursor?: number } = {},\n): ReactiveCollectionSnapshotFrame<K, S> {\n\tconst changeCursor = opts.changeCursor ?? -1;\n\tif (!Number.isSafeInteger(changeCursor) || changeCursor < -1) {\n\t\tthrow new RangeError(\"reactive collection snapshot changeCursor must be a safe integer >= -1\");\n\t}\n\treturn {\n\t\tformat: REACTIVE_COLLECTION_SNAPSHOT_FORMAT,\n\t\tversion: REACTIVE_COLLECTION_FRAME_VERSION,\n\t\tkind,\n\t\tchangeCursor,\n\t\tsnapshot,\n\t};\n}\n\n/** Build a D161 strict-JSON change frame before validation/encoding. */\nexport function reactiveCollectionChangeFrame<K extends ReactiveCollectionStorageKind, C>(\n\tkind: K,\n\tchange: C,\n): ReactiveCollectionChangeFrame<K, C> {\n\treturn {\n\t\tformat: REACTIVE_COLLECTION_CHANGE_FORMAT,\n\t\tversion: REACTIVE_COLLECTION_FRAME_VERSION,\n\t\tkind,\n\t\tchange,\n\t};\n}\n\n/** Validate a D161 snapshot frame and reject non-strict-JSON payloads honestly. */\nexport function assertReactiveCollectionSnapshotFrame<\n\tK extends ReactiveCollectionStorageKind,\n\tS = unknown,\n>(value: unknown, expectedKind: K): ReactiveCollectionSnapshotFrame<K, S> {\n\tif (!isRecord(value)) throw new TypeError(\"reactive collection snapshot frame must be an object\");\n\tassertKeys(value, [\"changeCursor\", \"format\", \"kind\", \"snapshot\", \"version\"], \"snapshot frame\");\n\tif (value.format !== REACTIVE_COLLECTION_SNAPSHOT_FORMAT) {\n\t\tthrow new TypeError(\"snapshot frame: invalid format\");\n\t}\n\tif (value.version !== REACTIVE_COLLECTION_FRAME_VERSION) {\n\t\tthrow new TypeError(\"snapshot frame: invalid version\");\n\t}\n\tassertKind(value.kind, expectedKind, \"snapshot frame\");\n\tassertSafeInteger(value.changeCursor, \"snapshot frame changeCursor\", -1);\n\tstrictJsonCodecFor<unknown>().encode(value);\n\treturn value as unknown as ReactiveCollectionSnapshotFrame<K, S>;\n}\n\n/** Validate a D161 change frame and reject non-strict-JSON payloads honestly. */\nexport function assertReactiveCollectionChangeFrame<\n\tK extends ReactiveCollectionStorageKind,\n\tC = unknown,\n>(value: unknown, expectedKind: K): ReactiveCollectionChangeFrame<K, C> {\n\tif (!isRecord(value)) throw new TypeError(\"reactive collection change frame must be an object\");\n\tassertKeys(value, [\"change\", \"format\", \"kind\", \"version\"], \"change frame\");\n\tif (value.format !== REACTIVE_COLLECTION_CHANGE_FORMAT) {\n\t\tthrow new TypeError(\"change frame: invalid format\");\n\t}\n\tif (value.version !== REACTIVE_COLLECTION_FRAME_VERSION) {\n\t\tthrow new TypeError(\"change frame: invalid version\");\n\t}\n\tassertKind(value.kind, expectedKind, \"change frame\");\n\tif (!Object.hasOwn(value, \"change\")) throw new TypeError(\"change frame: change is required\");\n\tstrictJsonCodecFor<unknown>().encode(value);\n\treturn value as unknown as ReactiveCollectionChangeFrame<K, C>;\n}\n\n/** Codec for D161 snapshot frames with strict JSON validation on both encode and decode. */\nexport function reactiveCollectionSnapshotFrameCodec<\n\tK extends ReactiveCollectionStorageKind,\n\tS = unknown,\n>(kind: K): Codec<ReactiveCollectionSnapshotFrame<K, S>> {\n\tconst codec = strictJsonCodecFor<unknown>();\n\treturn {\n\t\tencode(value) {\n\t\t\treturn codec.encode(assertReactiveCollectionSnapshotFrame<K, S>(value, kind));\n\t\t},\n\t\tdecode(bytes) {\n\t\t\treturn assertReactiveCollectionSnapshotFrame<K, S>(codec.decode(bytes), kind);\n\t\t},\n\t};\n}\n\n/** Codec for D161 change frames with strict JSON validation on both encode and decode. */\nexport function reactiveCollectionChangeFrameCodec<\n\tK extends ReactiveCollectionStorageKind,\n\tC = unknown,\n>(kind: K): Codec<ReactiveCollectionChangeFrame<K, C>> {\n\tconst codec = strictJsonCodecFor<unknown>();\n\treturn {\n\t\tencode(value) {\n\t\t\treturn codec.encode(assertReactiveCollectionChangeFrame<K, C>(value, kind));\n\t\t},\n\t\tdecode(bytes) {\n\t\t\treturn assertReactiveCollectionChangeFrame<K, C>(codec.decode(bytes), kind);\n\t\t},\n\t};\n}\n\nfunction assertListChange<T>(value: unknown): ListChange<T> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveList change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"append\":\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveList append.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"value\"], \"reactiveList append\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"appendMany\":\n\t\t\tassertKeys(value, [\"kind\", \"values\"], \"reactiveList appendMany\");\n\t\t\tassertArray<T>(value.values, \"reactiveList appendMany.values\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"insert\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"value\"], \"reactiveList insert\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList insert.index\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"insertMany\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"values\"], \"reactiveList insertMany\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList insertMany.index\", 0);\n\t\t\tassertArray<T>(value.values, \"reactiveList insertMany.values\");\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"pop\":\n\t\t\tassertKeys(value, [\"index\", \"kind\", \"value\"], \"reactiveList pop\");\n\t\t\tassertSafeInteger(value.index, \"reactiveList pop.index\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"trimHead\":\n\t\t\tassertKeys(value, [\"kind\", \"n\"], \"reactiveList trimHead\");\n\t\t\tassertSafeInteger(value.n, \"reactiveList trimHead.n\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveList clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveList clear.count\", 0);\n\t\t\treturn value as unknown as ListChange<T>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveList change kind ${value.kind}`);\n\t}\n}\n\nfunction assertLogChange<T>(value: unknown): LogChange<T> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveLog change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"append\":\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveLog append.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"value\"], \"reactiveLog append\");\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"appendMany\":\n\t\t\tassertKeys(value, [\"kind\", \"values\"], \"reactiveLog appendMany\");\n\t\t\tassertArray<T>(value.values, \"reactiveLog appendMany.values\");\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"trimHead\":\n\t\t\tassertKeys(value, [\"kind\", \"n\"], \"reactiveLog trimHead\");\n\t\t\tassertSafeInteger(value.n, \"reactiveLog trimHead.n\", 0);\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveLog clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveLog clear.count\", 0);\n\t\t\treturn value as unknown as LogChange<T>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveLog change kind ${value.kind}`);\n\t}\n}\n\nfunction assertMapChange<K, V>(value: unknown): MapChange<K, V> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveMap change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"set\":\n\t\t\tif (!Object.hasOwn(value, \"key\")) throw new TypeError(\"reactiveMap set.key required\");\n\t\t\tif (!Object.hasOwn(value, \"value\")) throw new TypeError(\"reactiveMap set.value required\");\n\t\t\tassertKeys(value, [\"key\", \"kind\", \"value\"], \"reactiveMap set\");\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tcase \"delete\":\n\t\t\tif (!Object.hasOwn(value, \"key\")) throw new TypeError(\"reactiveMap delete.key required\");\n\t\t\tif (!Object.hasOwn(value, \"previous\")) {\n\t\t\t\tthrow new TypeError(\"reactiveMap delete.previous required\");\n\t\t\t}\n\t\t\tassertKeys(value, [\"key\", \"kind\", \"previous\", \"reason\"], \"reactiveMap delete\");\n\t\t\tif (\n\t\t\t\tvalue.reason !== \"expired\" &&\n\t\t\t\tvalue.reason !== \"lru-evict\" &&\n\t\t\t\tvalue.reason !== \"archived\" &&\n\t\t\t\tvalue.reason !== \"explicit\"\n\t\t\t) {\n\t\t\t\tthrow new TypeError(\"reactiveMap delete.reason is invalid\");\n\t\t\t}\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveMap clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveMap clear.count\", 0);\n\t\t\treturn value as unknown as MapChange<K, V>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveMap change kind ${value.kind}`);\n\t}\n}\n\nfunction assertIndexChange<K, V>(value: unknown): IndexChange<K, V> {\n\tif (!isRecord(value) || typeof value.kind !== \"string\") {\n\t\tthrow new TypeError(\"reactiveIndex change must be an object with kind\");\n\t}\n\tswitch (value.kind) {\n\t\tcase \"upsert\":\n\t\t\tif (!Object.hasOwn(value, \"primary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.primary required\");\n\t\t\t}\n\t\t\tif (!Object.hasOwn(value, \"secondary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.secondary required\");\n\t\t\t}\n\t\t\tif (!Object.hasOwn(value, \"value\"))\n\t\t\t\tthrow new TypeError(\"reactiveIndex upsert.value required\");\n\t\t\tassertKeys(value, [\"kind\", \"primary\", \"secondary\", \"value\"], \"reactiveIndex upsert\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"delete\":\n\t\t\tif (!Object.hasOwn(value, \"primary\")) {\n\t\t\t\tthrow new TypeError(\"reactiveIndex delete.primary required\");\n\t\t\t}\n\t\t\tassertKeys(value, [\"kind\", \"primary\"], \"reactiveIndex delete\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"deleteMany\":\n\t\t\tassertKeys(value, [\"kind\", \"primaries\"], \"reactiveIndex deleteMany\");\n\t\t\tassertArray<K>(value.primaries, \"reactiveIndex deleteMany.primaries\");\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tcase \"clear\":\n\t\t\tassertKeys(value, [\"count\", \"kind\"], \"reactiveIndex clear\");\n\t\t\tassertSafeInteger(value.count, \"reactiveIndex clear.count\", 0);\n\t\t\treturn value as unknown as IndexChange<K, V>;\n\t\tdefault:\n\t\t\tthrow new TypeError(`unsupported reactiveIndex change kind ${value.kind}`);\n\t}\n}\n\nfunction applyListChange<T>(state: T[], change: ListChange<T>): void {\n\tswitch (change.kind) {\n\t\tcase \"append\":\n\t\t\tstate.push(change.value);\n\t\t\treturn;\n\t\tcase \"appendMany\":\n\t\t\tstate.push(...change.values);\n\t\t\treturn;\n\t\tcase \"insert\":\n\t\t\tif (change.index > state.length)\n\t\t\t\tthrow new Error(\"reactiveList insert change is out of range\");\n\t\t\tstate.splice(change.index, 0, change.value);\n\t\t\treturn;\n\t\tcase \"insertMany\":\n\t\t\tif (change.index > state.length) {\n\t\t\t\tthrow new Error(\"reactiveList insertMany change is out of range\");\n\t\t\t}\n\t\t\tstate.splice(change.index, 0, ...change.values);\n\t\t\treturn;\n\t\tcase \"pop\":\n\t\t\tif (change.index >= state.length) throw new Error(\"reactiveList pop change is out of range\");\n\t\t\tif (!strictJsonEquals(state[change.index], change.value)) {\n\t\t\t\tthrow new Error(\"reactiveList pop change value does not match current state\");\n\t\t\t}\n\t\t\tstate.splice(change.index, 1);\n\t\t\treturn;\n\t\tcase \"trimHead\":\n\t\t\tif (change.n > state.length) throw new Error(\"reactiveList trimHead change is out of range\");\n\t\t\tstate.splice(0, change.n);\n\t\t\treturn;\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveList clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction strictJsonEquals(a: unknown, b: unknown): boolean {\n\tconst left = strictCanonicalJsonBytes(a);\n\tconst right = strictCanonicalJsonBytes(b);\n\tif (left.byteLength !== right.byteLength) return false;\n\tfor (let i = 0; i < left.byteLength; i += 1) if (left[i] !== right[i]) return false;\n\treturn true;\n}\n\nfunction findJsonIndex<T>(\n\tvalues: readonly T[],\n\tmatch: (value: T) => unknown,\n\tkey: unknown,\n\tlabel: string,\n): number {\n\tlet found = -1;\n\tfor (let i = 0; i < values.length; i += 1) {\n\t\tif (strictJsonEquals(match(values[i] as T), key)) {\n\t\t\tif (found !== -1) throw new Error(`${label} duplicate JSON key in restore state`);\n\t\t\tfound = i;\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction cmpOrd(a: unknown, b: unknown): number {\n\tif (a === b) return 0;\n\tconst ta = typeof a;\n\tif (\n\t\tta === typeof b &&\n\t\t(ta === \"number\" || ta === \"string\" || ta === \"boolean\" || ta === \"bigint\")\n\t) {\n\t\tconst ax = a as number | string | bigint | boolean;\n\t\tconst bx = b as number | string | bigint | boolean;\n\t\treturn ax < bx ? -1 : ax > bx ? 1 : 0;\n\t}\n\treturn String(a).localeCompare(String(b));\n}\n\nfunction applyLogChange<T>(state: T[], change: LogChange<T>): void {\n\tswitch (change.kind) {\n\t\tcase \"append\":\n\t\t\tstate.push(change.value);\n\t\t\treturn;\n\t\tcase \"appendMany\":\n\t\t\tstate.push(...change.values);\n\t\t\treturn;\n\t\tcase \"trimHead\":\n\t\t\tif (change.n > state.length) throw new Error(\"reactiveLog trimHead change is out of range\");\n\t\t\tstate.splice(0, change.n);\n\t\t\treturn;\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveLog clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction applyMapChange<K, V>(state: Array<readonly [K, V]>, change: MapChange<K, V>): void {\n\tswitch (change.kind) {\n\t\tcase \"set\": {\n\t\t\tconst index = findJsonIndex(state, ([key]) => key, change.key, \"reactiveMap\");\n\t\t\tif (index === -1) state.push([change.key, change.value] as const);\n\t\t\telse state[index] = [change.key, change.value] as const;\n\t\t\treturn;\n\t\t}\n\t\tcase \"delete\": {\n\t\t\tconst index = findJsonIndex(state, ([key]) => key, change.key, \"reactiveMap\");\n\t\t\tif (index === -1) throw new Error(\"reactiveMap delete change key is missing\");\n\t\t\tif (!strictJsonEquals(state[index]?.[1], change.previous)) {\n\t\t\t\tthrow new Error(\"reactiveMap delete change previous value does not match current state\");\n\t\t\t}\n\t\t\tstate.splice(index, 1);\n\t\t\treturn;\n\t\t}\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveMap clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction sortIndexRows<K, V>(state: Array<IndexRow<K, V>>): void {\n\tstate.sort((a, b) => {\n\t\tconst bySecondary = cmpOrd(a.secondary, b.secondary);\n\t\treturn bySecondary === 0 ? cmpOrd(a.primary, b.primary) : bySecondary;\n\t});\n}\n\nfunction applyIndexChange<K, V>(state: Array<IndexRow<K, V>>, change: IndexChange<K, V>): void {\n\tswitch (change.kind) {\n\t\tcase \"upsert\": {\n\t\t\tconst index = findJsonIndex(state, (row) => row.primary, change.primary, \"reactiveIndex\");\n\t\t\tconst row: IndexRow<K, V> = {\n\t\t\t\tprimary: change.primary,\n\t\t\t\tsecondary: change.secondary,\n\t\t\t\tvalue: change.value,\n\t\t\t};\n\t\t\tif (index === -1) state.push(row);\n\t\t\telse state[index] = row;\n\t\t\tsortIndexRows(state);\n\t\t\treturn;\n\t\t}\n\t\tcase \"delete\": {\n\t\t\tconst index = findJsonIndex(state, (row) => row.primary, change.primary, \"reactiveIndex\");\n\t\t\tif (index === -1) throw new Error(\"reactiveIndex delete change primary is missing\");\n\t\t\tstate.splice(index, 1);\n\t\t\treturn;\n\t\t}\n\t\tcase \"deleteMany\": {\n\t\t\tfor (const primary of change.primaries) {\n\t\t\t\tconst index = findJsonIndex(state, (row) => row.primary, primary, \"reactiveIndex\");\n\t\t\t\tif (index === -1) {\n\t\t\t\t\tthrow new Error(\"reactiveIndex deleteMany change primary is missing\");\n\t\t\t\t}\n\t\t\t\tstate.splice(index, 1);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tcase \"clear\":\n\t\t\tif (change.count !== state.length) {\n\t\t\t\tthrow new Error(\"reactiveIndex clear change count does not match current state\");\n\t\t\t}\n\t\t\tstate.length = 0;\n\t\t\treturn;\n\t}\n}\n\nfunction finishState<K extends ReactiveCollectionStorageKind, T>(\n\tkind: K,\n\tstate: T[],\n\tsnapshotFound: boolean,\n\tsnapshotCursor: number,\n\tapplied: number,\n\tcursor: number,\n): ReactiveCollectionRestoreState<K, readonly T[]> {\n\treturn {\n\t\tkind,\n\t\tstate,\n\t\tsource: snapshotFound\n\t\t\t? applied > 0\n\t\t\t\t? \"snapshot+changes\"\n\t\t\t\t: \"snapshot\"\n\t\t\t: applied > 0\n\t\t\t\t? \"changes\"\n\t\t\t\t: \"empty\",\n\t\tsnapshot: { found: snapshotFound, changeCursor: snapshotCursor },\n\t\tchanges: { applied, cursor },\n\t};\n}\n\nfunction loadState<K extends ReactiveCollectionStorageKind, T, C>(\n\tkind: K,\n\topts: LoadReactiveCollectionStateOptions,\n\tassertSnapshot: (value: unknown) => readonly T[],\n\tassertChange: (value: unknown) => C,\n\tapplyChange: (state: T[], change: C) => void,\n): Promise<ReactiveCollectionRestoreState<K, readonly T[]>> {\n\tconst key = opts.snapshotKey ?? collectionSnapshotKey(opts.storagePrefix);\n\treturn opts.snapshotStore.get(key).then((snapshotValue) => {\n\t\tlet snapshotFound = false;\n\t\tlet snapshotCursor = -1;\n\t\tlet state: T[] = [];\n\n\t\tif (snapshotValue !== undefined) {\n\t\t\tconst frame = assertReactiveCollectionSnapshotFrame<K, readonly T[]>(snapshotValue, kind);\n\t\t\tstate = [...assertSnapshot(frame.snapshot)];\n\t\t\tsnapshotFound = true;\n\t\t\tsnapshotCursor = frame.changeCursor;\n\t\t}\n\n\t\tif (opts.changeLog === undefined) {\n\t\t\treturn finishState(kind, state, snapshotFound, snapshotCursor, 0, snapshotCursor);\n\t\t}\n\n\t\treturn opts.changeLog.read({ after: snapshotCursor }).then((entries) => {\n\t\t\tlet applied = 0;\n\t\t\tlet cursor = snapshotCursor;\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst expectedSeq = cursor + 1;\n\t\t\t\tif (!Number.isSafeInteger(entry.seq) || entry.seq !== expectedSeq) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`reactive collection change log is non-contiguous: expected seq ${expectedSeq}, got ${entry.seq}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst frame = assertReactiveCollectionChangeFrame<K, C>(entry.value, kind);\n\t\t\t\tconst change = assertChange(frame.change);\n\t\t\t\tapplyChange(state, change);\n\t\t\t\tapplied += 1;\n\t\t\t\tcursor = entry.seq;\n\t\t\t}\n\t\t\treturn finishState(kind, state, snapshotFound, snapshotCursor, applied, cursor);\n\t\t});\n\t});\n}\n\n/** D161 passive load/fold for reactiveList; reads storage but never mutates graph topology. */\nexport function loadReactiveListState<T = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveListRestoreState<T>> {\n\treturn loadState<\"reactiveList\", T, ListChange<T>>(\n\t\t\"reactiveList\",\n\t\topts,\n\t\t(value) => assertArray<T>(value, \"reactiveList snapshot\"),\n\t\tassertListChange,\n\t\tapplyListChange,\n\t);\n}\n\n/** D161 passive load/fold for reactiveLog; reads storage but never mutates graph topology. */\nexport function loadReactiveLogState<T = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveLogRestoreState<T>> {\n\treturn loadState<\"reactiveLog\", T, LogChange<T>>(\n\t\t\"reactiveLog\",\n\t\topts,\n\t\t(value) => assertArray<T>(value, \"reactiveLog snapshot\"),\n\t\tassertLogChange,\n\t\tapplyLogChange,\n\t);\n}\n\n/** D161 passive load/fold scaffold for reactiveMap; synchronous policy restore is deferred. */\nexport function loadReactiveMapState<K = unknown, V = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveMapRestoreState<K, V>> {\n\treturn loadState<\"reactiveMap\", readonly [K, V], MapChange<K, V>>(\n\t\t\"reactiveMap\",\n\t\topts,\n\t\t(value) => assertEntryArray<K, V>(value, \"reactiveMap snapshot\"),\n\t\tassertMapChange,\n\t\tapplyMapChange,\n\t);\n}\n\n/** D161 passive load/fold scaffold for reactiveIndex; key-codec restore is deferred. */\nexport function loadReactiveIndexState<K = unknown, V = unknown>(\n\topts: LoadReactiveCollectionStateOptions,\n): Promise<ReactiveIndexRestoreState<K, V>> {\n\treturn loadState<\"reactiveIndex\", IndexRow<K, V>, IndexChange<K, V>>(\n\t\t\"reactiveIndex\",\n\t\topts,\n\t\t(value) => assertIndexRows<K, V>(value, \"reactiveIndex snapshot\"),\n\t\tassertIndexChange,\n\t\tapplyIndexChange,\n\t);\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport {\n\ttype ReactiveIndex,\n\ttype ReactiveIndexOptions,\n\ttype ReactiveList,\n\ttype ReactiveListOptions,\n\ttype ReactiveLog,\n\ttype ReactiveLogOptions,\n\ttype ReactiveMap,\n\ttype ReactiveMapOptions,\n\trestoreReactiveIndex,\n\trestoreReactiveList,\n\trestoreReactiveLog,\n\trestoreReactiveMap,\n} from \"../data-structures/index.js\";\nimport type {\n\tIndexChange,\n\tListChange,\n\tLogChange,\n\tMapChange,\n} from \"../graph/data-structures/change.js\";\nimport type { IndexRow } from \"../graph/data-structures/reactive-index.js\";\nimport { assertGraphLocalNode, type Graph, type StateNode } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport type {\n\tAppendLogEntry,\n\tAppendLogStorageTier,\n\tKvStorageTier,\n\tLoadReactiveCollectionStateOptions,\n\tReactiveCollectionChangeFrame,\n\tReactiveCollectionSnapshotFrame,\n\tReactiveIndexRestoreState,\n\tReactiveListRestoreState,\n\tReactiveLogRestoreState,\n\tReactiveMapRestoreState,\n} from \"../storage/index.js\";\nimport {\n\tassertReactiveCollectionChangeFrame,\n\tassertReactiveCollectionSnapshotFrame,\n\tcollectionSnapshotKey,\n\tloadReactiveIndexState,\n\tloadReactiveListState,\n\tloadReactiveLogState,\n\tloadReactiveMapState,\n\treactiveCollectionChangeFrame,\n\treactiveCollectionSnapshotFrame,\n} from \"../storage/index.js\";\n\ntype PersistableKind = \"reactiveList\" | \"reactiveLog\" | \"reactiveMap\" | \"reactiveIndex\";\ntype PersistableChange<T, K extends PersistableKind> = K extends \"reactiveList\"\n\t? ListChange<T>\n\t: K extends \"reactiveLog\"\n\t\t? LogChange<T>\n\t\t: K extends \"reactiveMap\"\n\t\t\t? MapChange<unknown, T>\n\t\t\t: IndexChange<unknown, T>;\ntype PersistableCollection<T, K extends PersistableKind> = K extends \"reactiveList\"\n\t? ReactiveList<T>\n\t: K extends \"reactiveLog\"\n\t\t? ReactiveLog<T>\n\t\t: K extends \"reactiveMap\"\n\t\t\t? ReactiveMap<unknown, T>\n\t\t\t: ReactiveIndex<unknown, T>;\n\n/** D161 adapter write-progress cursor; this is not a domain replay or wire-bridge cursor. */\nexport interface ReactiveCollectionPersistenceCursor {\n\treadonly kind: \"persistence.cursor\";\n\treadonly collection: PersistableKind;\n\treadonly changeSeq: number;\n\treadonly snapshotWrites: number;\n\treadonly changeWrites: number;\n}\n\n/** D161 graph-visible persistence sidecar status fact. */\nexport interface ReactiveCollectionPersistenceStatus {\n\treadonly state: \"starting\" | \"ready\" | \"flushing\" | \"errored\" | \"disposed\";\n\treadonly pending: number;\n\treadonly writes: number;\n\treadonly errors: number;\n\treadonly cursor: ReactiveCollectionPersistenceCursor;\n}\n\n/** D161 graph-visible persistence sidecar error fact. */\nexport interface ReactiveCollectionPersistenceError {\n\treadonly phase: \"snapshot\" | \"change\";\n\treadonly message: string;\n\treadonly cursor: ReactiveCollectionPersistenceCursor;\n}\n\n/** Options for the D161 graph-bound persistence sidecar over a reactive collection. */\nexport interface PersistReactiveCollectionOptions<K extends PersistableKind = PersistableKind> {\n\treadonly kind: K;\n\treadonly name?: string;\n\treadonly snapshotStore: KvStorageTier<unknown>;\n\treadonly snapshotKey?: string;\n\treadonly storagePrefix?: string;\n\treadonly changeLog?: AppendLogStorageTier<unknown>;\n\t/** Adapter write cursor seed for wrappers that already folded a change log. */\n\treadonly initialChangeCursor?: number;\n\t/** Default true: write one durable baseline when the adapter attaches. */\n\treadonly snapshotOnAttach?: boolean;\n\t/** Optional snapshot cadence. Manual snapshots remain available via handle.snapshot(). */\n\treadonly snapshotEveryChanges?: number;\n}\n\n/** D161 sidecar controls; flush waits for queued storage promises to settle, not fsync. */\nexport interface ReactiveCollectionPersistenceHandle {\n\treadonly ready: StateNode<boolean>;\n\treadonly status: StateNode<ReactiveCollectionPersistenceStatus>;\n\treadonly error: StateNode<ReactiveCollectionPersistenceError | null>;\n\treadonly cursor: StateNode<ReactiveCollectionPersistenceCursor>;\n\tflush(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n\tsnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n\tdispose(done?: (status: ReactiveCollectionPersistenceStatus) => void): void;\n}\n\ninterface QueueItem {\n\treadonly phase: \"snapshot\" | \"change\" | \"flush\" | \"dispose\";\n\treadonly done?: (status: ReactiveCollectionPersistenceStatus) => void;\n\trun(): void | PromiseLike<void>;\n}\n\nfunction emptyCursor(collection: PersistableKind): ReactiveCollectionPersistenceCursor {\n\treturn {\n\t\tkind: \"persistence.cursor\",\n\t\tcollection,\n\t\tchangeSeq: -1,\n\t\tsnapshotWrites: 0,\n\t\tchangeWrites: 0,\n\t};\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction validateSnapshotEveryChanges(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isSafeInteger(value) || value < 1) {\n\t\tthrow new RangeError(\"snapshotEveryChanges must be a positive safe integer\");\n\t}\n\treturn value;\n}\n\nfunction validateInitialChangeCursor(value: number | undefined): number {\n\tif (value === undefined) return -1;\n\tif (!Number.isSafeInteger(value) || value < -1) {\n\t\tthrow new RangeError(\"initialChangeCursor must be a safe integer >= -1\");\n\t}\n\treturn value;\n}\n\nfunction statusOf(\n\tstate: ReactiveCollectionPersistenceStatus[\"state\"],\n\tpending: number,\n\twrites: number,\n\terrors: number,\n\tcursor: ReactiveCollectionPersistenceCursor,\n): ReactiveCollectionPersistenceStatus {\n\treturn { state, pending, writes, errors, cursor };\n}\n\nfunction dataOf<C>(msg: Message): C | undefined {\n\treturn msg[0] === \"DATA\" ? (msg[1] as C) : undefined;\n}\n\n/**\n * D161 graph-bound sidecar over an existing collection. It writes passive storage frames and\n * exposes adapter progress as graph-visible DATA facts; it never restores or mutates the collection.\n */\nexport function persistReactiveCollection<T, K extends PersistableKind>(\n\tgraph: Graph,\n\tcollection: PersistableCollection<T, K>,\n\topts: PersistReactiveCollectionOptions<K>,\n): ReactiveCollectionPersistenceHandle {\n\tconst kind = opts.kind;\n\tconst name = opts.name ?? `${kind}.persistence`;\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(opts.storagePrefix ?? name);\n\tconst snapshotEveryChanges = validateSnapshotEveryChanges(opts.snapshotEveryChanges);\n\tassertGraphLocalNode(graph, collection.delta as Node<unknown>, `${name}.collection.delta`);\n\tassertGraphLocalNode(graph, collection.snapshot as Node<unknown>, `${name}.collection.snapshot`);\n\n\tlet cursorValue = {\n\t\t...emptyCursor(kind),\n\t\tchangeSeq: validateInitialChangeCursor(opts.initialChangeCursor),\n\t};\n\tlet statusValue = statusOf(\"starting\", 0, 0, 0, cursorValue);\n\tlet errorCount = 0;\n\tlet writes = 0;\n\tlet observedChangesSinceSnapshot = 0;\n\tlet running = false;\n\tlet disposed = false;\n\tlet disposeRequested = false;\n\tlet subscribing = true;\n\tlet stop: (() => void) | undefined;\n\tconst queue: QueueItem[] = [];\n\n\tconst ready = graph.state(false, { name: `${name}/ready` });\n\tconst status = graph.state<ReactiveCollectionPersistenceStatus>(statusValue, {\n\t\tname: `${name}/status`,\n\t});\n\tconst error = graph.state<ReactiveCollectionPersistenceError | null>(null, {\n\t\tname: `${name}/error`,\n\t});\n\tconst cursor = graph.state<ReactiveCollectionPersistenceCursor>(cursorValue, {\n\t\tname: `${name}/cursor`,\n\t});\n\n\tfunction publish(state: ReactiveCollectionPersistenceStatus[\"state\"]): void {\n\t\tconst nextState = statusValue.state === \"errored\" && state !== \"disposed\" ? \"errored\" : state;\n\t\tstatusValue = statusOf(\n\t\t\tnextState,\n\t\t\tqueue.length + (running ? 1 : 0),\n\t\t\twrites,\n\t\t\terrorCount,\n\t\t\tcursorValue,\n\t\t);\n\t\tcursor.set(cursorValue);\n\t\tstatus.set(statusValue);\n\t\tif (nextState === \"ready\") ready.set(true);\n\t\tif (nextState === \"errored\" || nextState === \"disposed\") ready.set(false);\n\t}\n\n\tfunction report(phase: \"snapshot\" | \"change\", caught: unknown): void {\n\t\terrorCount += 1;\n\t\tconst fact = { phase, message: errorMessage(caught), cursor: cursorValue };\n\t\terror.set(fact);\n\t}\n\n\tfunction callDone(done: QueueItem[\"done\"]): void {\n\t\ttry {\n\t\t\tdone?.(statusValue);\n\t\t} catch {\n\t\t\t// Done callbacks are advisory barriers; user code must not wedge the adapter queue.\n\t\t}\n\t}\n\n\tfunction finish(item: QueueItem): void {\n\t\tif (item.phase === \"dispose\") {\n\t\t\tdisposed = true;\n\t\t\trunning = false;\n\t\t\tpublish(\"disposed\");\n\t\t} else if (statusValue.state !== \"errored\") {\n\t\t\trunning = false;\n\t\t\tpublish(\"ready\");\n\t\t} else {\n\t\t\trunning = false;\n\t\t\tpublish(\"errored\");\n\t\t}\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction fail(item: QueueItem, caught: unknown): void {\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") report(item.phase, caught);\n\t\trunning = false;\n\t\tif (item.phase === \"snapshot\" || item.phase === \"change\") publish(\"errored\");\n\t\tcallDone(item.done);\n\t\tdrain();\n\t}\n\n\tfunction chainThenable(item: QueueItem, value: unknown): boolean {\n\t\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return false;\n\t\tlet then: unknown;\n\t\ttry {\n\t\t\tthen = (value as { then?: unknown }).then;\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn true;\n\t\t}\n\t\tif (typeof then !== \"function\") return false;\n\t\tlet settled = false;\n\t\tconst settle = (next: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tnext();\n\t\t};\n\t\ttry {\n\t\t\t(then as (onFulfilled: () => void, onRejected: (error: unknown) => void) => unknown).call(\n\t\t\t\tvalue,\n\t\t\t\t() => settle(() => finish(item)),\n\t\t\t\t(caught) => settle(() => fail(item, caught)),\n\t\t\t);\n\t\t} catch (caught) {\n\t\t\tsettle(() => fail(item, caught));\n\t\t}\n\t\treturn true;\n\t}\n\n\tfunction enqueue(item: QueueItem): void {\n\t\tif (disposed || (disposeRequested && item.phase !== \"dispose\" && item.phase !== \"flush\")) {\n\t\t\tcallDone(item.done);\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(item);\n\t\tdrain();\n\t}\n\n\tfunction drain(): void {\n\t\tif (running) return;\n\t\tconst item = queue.shift();\n\t\tif (item === undefined) return;\n\t\trunning = true;\n\t\tpublish(\n\t\t\titem.phase === \"flush\" ? \"flushing\" : statusValue.state === \"starting\" ? \"starting\" : \"ready\",\n\t\t);\n\t\tlet result: void | PromiseLike<void>;\n\t\ttry {\n\t\t\tresult = item.run();\n\t\t} catch (caught) {\n\t\t\tfail(item, caught);\n\t\t\treturn;\n\t\t}\n\t\tif (chainThenable(item, result)) return;\n\t\tfinish(item);\n\t}\n\n\tfunction enqueueSnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\tconst snapshot = collectionSnapshot(collection, kind);\n\t\tobservedChangesSinceSnapshot = 0;\n\t\tenqueue({\n\t\t\tphase: \"snapshot\",\n\t\t\tdone,\n\t\t\trun() {\n\t\t\t\tconst frame: ReactiveCollectionSnapshotFrame<K, readonly unknown[]> =\n\t\t\t\t\treactiveCollectionSnapshotFrame(kind, snapshot, {\n\t\t\t\t\t\tchangeCursor: cursorValue.changeSeq,\n\t\t\t\t\t});\n\t\t\t\tassertReactiveCollectionSnapshotFrame(frame, kind);\n\t\t\t\treturn opts.snapshotStore.set(snapshotKey, frame).then(() => {\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tsnapshotWrites: cursorValue.snapshotWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction enqueueChange(change: PersistableChange<T, K>): void {\n\t\tconst changeLog = opts.changeLog;\n\t\tif (changeLog === undefined) return;\n\t\tenqueue({\n\t\t\tphase: \"change\",\n\t\t\trun() {\n\t\t\t\tconst frame: ReactiveCollectionChangeFrame<\n\t\t\t\t\tPersistableKind,\n\t\t\t\t\tPersistableChange<T, K>\n\t\t\t\t> = reactiveCollectionChangeFrame(kind, change);\n\t\t\t\tassertReactiveCollectionChangeFrame(frame, kind);\n\t\t\t\treturn changeLog.append(frame).then((written) => {\n\t\t\t\t\tconst entry = written as AppendLogEntry<\n\t\t\t\t\t\tReactiveCollectionChangeFrame<PersistableKind, PersistableChange<T, K>>\n\t\t\t\t\t>;\n\t\t\t\t\tcursorValue = {\n\t\t\t\t\t\t...cursorValue,\n\t\t\t\t\t\tchangeSeq: entry.seq,\n\t\t\t\t\t\tchangeWrites: cursorValue.changeWrites + 1,\n\t\t\t\t\t};\n\t\t\t\t\twrites += 1;\n\t\t\t\t\tpublish(\"ready\");\n\t\t\t\t});\n\t\t\t},\n\t\t});\n\t}\n\n\tfunction cancelQueuedForDispose(): void {\n\t\tconst pending = queue.splice(0);\n\t\tfor (const item of pending) callDone(item.done);\n\t}\n\n\tstop = (collection.delta as Node<PersistableChange<T, K>>).subscribe(\n\t\t(msg: Message, delivery?: DeliveryMeta) => {\n\t\t\tif (disposeRequested) return;\n\t\t\tconst change = dataOf<PersistableChange<T, K>>(msg);\n\t\t\tif (change === undefined) return;\n\t\t\tif (subscribing && delivery === undefined) return;\n\t\t\tobservedChangesSinceSnapshot += 1;\n\t\t\tenqueueChange(change);\n\t\t\tif (\n\t\t\t\tsnapshotEveryChanges !== undefined &&\n\t\t\t\tobservedChangesSinceSnapshot >= snapshotEveryChanges\n\t\t\t) {\n\t\t\t\tenqueueSnapshot();\n\t\t\t}\n\t\t},\n\t);\n\tsubscribing = false;\n\n\tif (opts.snapshotOnAttach !== false) enqueueSnapshot();\n\telse publish(\"ready\");\n\n\treturn {\n\t\tready,\n\t\tstatus,\n\t\terror,\n\t\tcursor,\n\t\tflush(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueue({ phase: \"flush\", done, run: () => undefined });\n\t\t},\n\t\tsnapshot(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed || disposeRequested) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenqueueSnapshot(done);\n\t\t},\n\t\tdispose(done?: (status: ReactiveCollectionPersistenceStatus) => void): void {\n\t\t\tif (disposed) {\n\t\t\t\tcallDone(done);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdisposeRequested = true;\n\t\t\tstop?.();\n\t\t\tcancelQueuedForDispose();\n\t\t\tenqueue({ phase: \"dispose\", done, run: () => undefined });\n\t\t},\n\t};\n}\n\nfunction collectionSnapshot<T, K extends PersistableKind>(\n\tcollection: PersistableCollection<T, K>,\n\tkind: K,\n): readonly unknown[] {\n\tif (kind === \"reactiveMap\") {\n\t\treturn [...(collection as ReactiveMap<unknown, unknown>).toMap()];\n\t}\n\tif (kind === \"reactiveIndex\") {\n\t\treturn (collection as ReactiveIndex<unknown, unknown>).toArray();\n\t}\n\treturn (collection as ReactiveList<T> | ReactiveLog<T>).toArray();\n}\n\ntype CollectionOptionsWithoutGraphName<T> = Omit<T, \"graph\" | \"name\">;\n\n/** Options for D161 load -> restore -> persist composition for reactiveList. */\nexport interface OpenPersistentReactiveListOptions<T>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveList\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly T[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveListOptions>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveLog. */\nexport interface OpenPersistentReactiveLogOptions<T>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveLog\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly T[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveLogOptions>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveMap. */\nexport interface OpenPersistentReactiveMapOptions<K, V>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveMap\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly (readonly [K, V])[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveMapOptions<K, V>>;\n}\n\n/** Options for D161 load -> restore -> persist composition for reactiveIndex. */\nexport interface OpenPersistentReactiveIndexOptions<K, V>\n\textends LoadReactiveCollectionStateOptions,\n\t\tOmit<\n\t\t\tPersistReactiveCollectionOptions<\"reactiveIndex\">,\n\t\t\t\"kind\" | \"snapshotStore\" | \"changeLog\" | \"initialChangeCursor\"\n\t\t> {\n\treadonly graph: Graph;\n\treadonly name?: string;\n\treadonly initial?: readonly IndexRow<K, V>[];\n\treadonly collection?: CollectionOptionsWithoutGraphName<ReactiveIndexOptions>;\n}\n\n/** Return value for D161 persistent reactiveList composition. */\nexport interface PersistentReactiveList<T> {\n\treadonly collection: ReactiveList<T>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveListRestoreState<T>;\n}\n\n/** Return value for D161 persistent reactiveLog composition. */\nexport interface PersistentReactiveLog<T> {\n\treadonly collection: ReactiveLog<T>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveLogRestoreState<T>;\n}\n\n/** Return value for D161 persistent reactiveMap composition. */\nexport interface PersistentReactiveMap<K, V> {\n\treadonly collection: ReactiveMap<K, V>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveMapRestoreState<K, V>;\n}\n\n/** Return value for D161 persistent reactiveIndex composition. */\nexport interface PersistentReactiveIndex<K, V> {\n\treadonly collection: ReactiveIndex<K, V>;\n\treadonly persistence: ReactiveCollectionPersistenceHandle;\n\treadonly loaded: ReactiveIndexRestoreState<K, V>;\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveList, then sidecar persist. */\nexport function openPersistentReactiveList<T = unknown>(\n\topts: OpenPersistentReactiveListOptions<T>,\n): Promise<PersistentReactiveList<T>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveListState<T>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveList<T>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<T, \"reactiveList\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveList\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveLog, then sidecar persist. */\nexport function openPersistentReactiveLog<T = unknown>(\n\topts: OpenPersistentReactiveLogOptions<T>,\n): Promise<PersistentReactiveLog<T>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveLogState<T>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveLog<T>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<T, \"reactiveLog\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveLog\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveMap, then sidecar persist. */\nexport function openPersistentReactiveMap<K = unknown, V = unknown>(\n\topts: OpenPersistentReactiveMapOptions<K, V>,\n): Promise<PersistentReactiveMap<K, V>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveMapState<K, V>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveMap<K, V>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<V, \"reactiveMap\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveMap\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n\n/** D161 convenience wrapper: passive load, sync restoreReactiveIndex, then sidecar persist. */\nexport function openPersistentReactiveIndex<K = unknown, V = unknown>(\n\topts: OpenPersistentReactiveIndexOptions<K, V>,\n): Promise<PersistentReactiveIndex<K, V>> {\n\tconst storagePrefix = opts.storagePrefix ?? opts.name ?? \"reactive-collection\";\n\tconst snapshotKey = opts.snapshotKey ?? collectionSnapshotKey(storagePrefix);\n\tconst loadOpts = { ...opts, snapshotKey, storagePrefix };\n\treturn loadReactiveIndexState<K, V>(loadOpts).then((loaded) => {\n\t\tconst state =\n\t\t\tloaded.source === \"empty\" && opts.initial !== undefined\n\t\t\t\t? { ...loaded, state: opts.initial }\n\t\t\t\t: loaded;\n\t\tconst collection = restoreReactiveIndex<K, V>(state, {\n\t\t\t...(opts.collection ?? {}),\n\t\t\tgraph: opts.graph,\n\t\t\tname: opts.name,\n\t\t});\n\t\tconst persistence = persistReactiveCollection<V, \"reactiveIndex\">(opts.graph, collection, {\n\t\t\t...opts,\n\t\t\tkind: \"reactiveIndex\",\n\t\t\tname: opts.name ? `${opts.name}/persistence` : undefined,\n\t\t\tsnapshotKey,\n\t\t\tstoragePrefix,\n\t\t\tinitialChangeCursor: loaded.changes.cursor,\n\t\t});\n\t\treturn { collection, persistence, loaded };\n\t});\n}\n","/**\n * Framework-neutral store adapters.\n *\n * Focused framework bindings build on this tiny Node-facing layer without\n * importing framework packages into the dependency-free adapters barrel\n * (D125/D238).\n */\n\nimport type { DeliveryMeta, Sink } from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\n\n/** A minimal readable store contract shared by Svelte/Nanostores-style adapters. */\nexport interface ReadableStore<T> {\n\tget(): T | undefined;\n\tsubscribe(run: (value: T | undefined) => void): () => void;\n}\n\n/** A minimal writable store contract over a clean-slate writable node. */\nexport interface WritableStore<T> extends ReadableStore<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** React `useSyncExternalStore`-compatible shape, without importing React. */\nexport interface ExternalStore<T> {\n\tgetSnapshot(): T | undefined;\n\tgetServerSnapshot(): T | undefined;\n\tsubscribe(onStoreChange: () => void): () => void;\n}\n\n/** Object-of-nodes factory used by record subscription adapters. */\nexport type NodeRecordFactory<K extends string, R extends Record<string, unknown>> = (key: K) => {\n\t[P in keyof R]: Node<R[P]>;\n};\n\n/** Zustand-compatible store API over a caller-owned clean-slate state node. */\nexport interface ZustandStoreApi<T extends object> {\n\tgetState(): T;\n\tsetState(partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean): void;\n\tgetInitialState(): T;\n\tsubscribe(listener: (state: T, prevState: T) => void): () => void;\n\tdestroy(): void;\n}\n\n/** Jotai-style atom facade over a caller-owned node. */\nexport interface JotaiAtom<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable Jotai-style atom facade over a caller-owned writable node. */\nexport interface WritableJotaiAtom<T> extends JotaiAtom<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** Nanostores-style atom facade over a caller-owned node. */\nexport interface NanoAtom<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\tlisten(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable Nanostores-style atom facade over a caller-owned writable node. */\nexport interface WritableNanoAtom<T> extends NanoAtom<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\n/** TC39-Signals-style facade over a caller-owned node. */\nexport interface SignalLike<T> {\n\tget(): T | undefined;\n\tsubscribe(callback: (value: T | undefined) => void): () => void;\n\treadonly _node: Node<T>;\n}\n\n/** Writable TC39-Signals-style facade over a caller-owned writable node. */\nexport interface WritableSignalLike<T> extends SignalLike<T> {\n\tset(value: T): void;\n\tupdate(fn: (value: T | undefined) => T): void;\n}\n\nexport interface SubscribeValuesOptions<T> {\n\t/** Emit the current cache snapshot immediately. `undefined` means SENTINEL/no DATA. */\n\timmediate?: boolean;\n\t/** Suppress synchronous push-on-subscribe/replay DATA. Useful for change-only store listeners. */\n\tchangesOnly?: boolean;\n\tonError?: (error: unknown) => void;\n\tonComplete?: () => void;\n\t/** Custom cache reader for wrappers that keep their own snapshot object. */\n\tgetSnapshot?: () => T | undefined;\n}\n\nexport interface WritableNode<T> extends Node<T> {\n\tset(value: T): void;\n}\n\nexport interface WritableStoreOptions<T> extends SubscribeValuesOptions<T> {\n\t/** Override writes for adapters that need a framework-owned reducer. */\n\twrite?: (node: WritableNode<T>, value: T) => void;\n}\n\n/** Read a node cache without activating it. */\nexport function nodeSnapshot<T>(node: Node<T>): T | undefined {\n\treturn node.cache as T | undefined;\n}\n\n/**\n * Subscribe to DATA values from a Node. Protocol internals stay below the adapter boundary:\n * DATA drives value listeners, ERROR/COMPLETE route to optional lifecycle callbacks.\n */\nexport function subscribeNodeValues<T>(\n\tnode: Node<T>,\n\trun: (value: T | undefined) => void,\n\topts: SubscribeValuesOptions<T> = {},\n): () => void {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tif (opts.immediate) run(read());\n\n\tlet subscribing = true;\n\tconst skipSynchronousHandshakeData = opts.changesOnly || opts.immediate;\n\tconst sink: Sink = (msg, delivery?: DeliveryMeta) => {\n\t\tswitch (msg[0]) {\n\t\t\tcase \"DATA\":\n\t\t\t\tif (skipSynchronousHandshakeData && subscribing && delivery === undefined) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\trun(msg[1] as T);\n\t\t\t\treturn;\n\t\t\tcase \"ERROR\":\n\t\t\t\topts.onError?.(msg[1]);\n\t\t\t\treturn;\n\t\t\tcase \"COMPLETE\":\n\t\t\t\topts.onComplete?.();\n\t\t\t\treturn;\n\t\t}\n\t};\n\tconst unsubscribe = node.subscribe(sink);\n\tsubscribing = false;\n\treturn unsubscribe;\n}\n\n/** Build a Svelte/Nanostores-style readable store from a clean-slate Node. */\nexport function readableStore<T>(\n\tnode: Node<T>,\n\topts: SubscribeValuesOptions<T> = {},\n): ReadableStore<T> {\n\treturn {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (run) => subscribeNodeValues(node, run, { immediate: true, ...opts }),\n\t};\n}\n\nfunction hasWritableSet<T>(node: Node<T>): node is WritableNode<T> {\n\treturn typeof (node as { set?: unknown }).set === \"function\";\n}\n\nfunction defaultWrite<T>(node: WritableNode<T>, value: T): void {\n\tnode.set(value);\n}\n\n/** Build a writable store over a StateNode or compatible clean-slate writable Node. */\nexport function writableStore<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableStore<T>;\nexport function writableStore<T>(\n\tnode: Node<T>,\n\topts: WritableStoreOptions<T> & { write: (node: WritableNode<T>, value: T) => void },\n): WritableStore<T>;\nexport function writableStore<T>(\n\tnode: Node<T>,\n\topts: WritableStoreOptions<T> = {},\n): WritableStore<T> {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tconst write = opts.write ?? (hasWritableSet(node) ? defaultWrite : undefined);\n\tif (!write) {\n\t\tthrow new TypeError(\"writableStore: node must expose set(value) or opts.write\");\n\t}\n\tconst writable = node as WritableNode<T>;\n\treturn {\n\t\tget: read,\n\t\tsubscribe: (run) => subscribeNodeValues(node, run, { immediate: true, ...opts }),\n\t\tset: (value) => write(writable, value),\n\t\tupdate: (fn) => write(writable, fn(read())),\n\t};\n}\n\n/** Build the tiny shape React's `useSyncExternalStore` expects, without importing React. */\nexport function externalStore<T>(\n\tnode: Node<T>,\n\topts: Pick<SubscribeValuesOptions<T>, \"getSnapshot\" | \"onError\" | \"onComplete\"> = {},\n): ExternalStore<T> {\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\treturn {\n\t\tgetSnapshot: read,\n\t\tgetServerSnapshot: read,\n\t\tsubscribe: (onStoreChange) =>\n\t\t\tsubscribeNodeValues(node, () => onStoreChange(), {\n\t\t\t\tchangesOnly: true,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tonComplete: opts.onComplete,\n\t\t\t}),\n\t};\n}\n\n/** Build a framework-neutral keyed record store for focused framework record bindings. */\nexport function recordReadableStore<K extends string, R extends Record<string, unknown>>(\n\tkeysNode: Node<readonly K[]>,\n\tfactory: NodeRecordFactory<K, R>,\n\topts: SubscribeValuesOptions<Record<K, R>> = {},\n): ReadableStore<Record<K, R>> {\n\tconst read = () => {\n\t\tconst keys = keysNode.cache ?? [];\n\t\tconst out = {} as Record<K, R>;\n\t\tfor (const key of keys) {\n\t\t\tconst nodes = factory(key);\n\t\t\tconst values = {} as R;\n\t\t\tfor (const field of Object.keys(nodes) as Array<keyof R>) {\n\t\t\t\tvalues[field] = nodes[field].cache as R[keyof R];\n\t\t\t}\n\t\t\tout[key] = values;\n\t\t}\n\t\treturn out;\n\t};\n\n\treturn {\n\t\tget: read,\n\t\tsubscribe(run) {\n\t\t\tconst entryUnsubs: Array<() => void> = [];\n\t\t\tconst cleanupEntries = () => {\n\t\t\t\tfor (const unsub of entryUnsubs.splice(0)) unsub();\n\t\t\t};\n\t\t\tconst sync = () => {\n\t\t\t\tcleanupEntries();\n\t\t\t\tfor (const key of keysNode.cache ?? []) {\n\t\t\t\t\tconst nodes = factory(key);\n\t\t\t\t\tfor (const field of Object.keys(nodes) as Array<keyof R>) {\n\t\t\t\t\t\tentryUnsubs.push(\n\t\t\t\t\t\t\tsubscribeNodeValues(nodes[field], () => run(read()), {\n\t\t\t\t\t\t\t\tchangesOnly: true,\n\t\t\t\t\t\t\t\tonError: opts.onError,\n\t\t\t\t\t\t\t\tonComplete: opts.onComplete,\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\trun(read());\n\t\t\t};\n\t\t\tconst keysUnsub = subscribeNodeValues(keysNode, sync, {\n\t\t\t\tchangesOnly: true,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tonComplete: opts.onComplete,\n\t\t\t});\n\t\t\tsync();\n\t\t\treturn () => {\n\t\t\t\tkeysUnsub();\n\t\t\t\tcleanupEntries();\n\t\t\t};\n\t\t},\n\t};\n}\n\n/** Build a Zustand-compatible StoreApi over a caller-owned clean-slate state node. */\nexport function zustandStore<T extends object>(\n\tnode: WritableNode<T>,\n\tinitialState?: T,\n\topts?: WritableStoreOptions<T>,\n): ZustandStoreApi<T>;\nexport function zustandStore<T extends object>(\n\tnode: Node<T>,\n\tinitialState: T | undefined,\n\topts: WritableStoreOptions<T> & { write: (node: WritableNode<T>, value: T) => void },\n): ZustandStoreApi<T>;\nexport function zustandStore<T extends object>(\n\tnode: Node<T>,\n\tinitialState: T = nodeSnapshot(node) as T,\n\topts: WritableStoreOptions<T> = {},\n): ZustandStoreApi<T> {\n\tconst listeners = new Set<() => void>();\n\tconst read = opts.getSnapshot ?? (() => nodeSnapshot(node));\n\tconst write = opts.write ?? (hasWritableSet(node) ? defaultWrite : undefined);\n\tif (!write) {\n\t\tthrow new TypeError(\"zustandStore: node must expose set(value) or opts.write\");\n\t}\n\tconst writable = node as WritableNode<T>;\n\tconst api: ZustandStoreApi<T> = {\n\t\tgetState: () => read() as T,\n\t\tsetState(partial, replace) {\n\t\t\tconst prev = api.getState();\n\t\t\tconst next = typeof partial === \"function\" ? partial(prev) : partial;\n\t\t\twrite(writable, replace ? (next as T) : ({ ...prev, ...next } as T));\n\t\t},\n\t\tgetInitialState: () => initialState,\n\t\tsubscribe(listener) {\n\t\t\tlet prev = api.getState();\n\t\t\tconst unsub = subscribeNodeValues(\n\t\t\t\tnode,\n\t\t\t\t() => {\n\t\t\t\t\tconst next = api.getState();\n\t\t\t\t\tlistener(next, prev);\n\t\t\t\t\tprev = next;\n\t\t\t\t},\n\t\t\t\t{ changesOnly: true, onError: opts.onError, onComplete: opts.onComplete },\n\t\t\t);\n\t\t\tlisteners.add(unsub);\n\t\t\treturn () => {\n\t\t\t\tif (!listeners.delete(unsub)) return;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t},\n\t\tdestroy() {\n\t\t\tfor (const unsub of [...listeners]) {\n\t\t\t\tlisteners.delete(unsub);\n\t\t\t\tunsub();\n\t\t\t}\n\t\t},\n\t};\n\treturn api;\n}\n\n/** Build a Jotai-style atom facade over a caller-owned node. */\nexport function jotaiAtom<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableJotaiAtom<T>;\nexport function jotaiAtom<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): JotaiAtom<T>;\nexport function jotaiAtom<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): JotaiAtom<T> | WritableJotaiAtom<T> {\n\tconst base: JotaiAtom<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n\n/** Build a Nanostores-style atom facade over a caller-owned node. */\nexport function nanoAtom<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableNanoAtom<T>;\nexport function nanoAtom<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): NanoAtom<T>;\nexport function nanoAtom<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): NanoAtom<T> | WritableNanoAtom<T> {\n\tconst base: NanoAtom<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { immediate: true, ...opts }),\n\t\tlisten: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n\n/** Build a TC39-Signals-style facade over a caller-owned node. */\nexport function signalFromNode<T>(\n\tnode: WritableNode<T>,\n\topts?: WritableStoreOptions<T>,\n): WritableSignalLike<T>;\nexport function signalFromNode<T>(node: Node<T>, opts?: SubscribeValuesOptions<T>): SignalLike<T>;\nexport function signalFromNode<T>(\n\tnode: Node<T> | WritableNode<T>,\n\topts: SubscribeValuesOptions<T> | WritableStoreOptions<T> = {},\n): SignalLike<T> | WritableSignalLike<T> {\n\tconst base: SignalLike<T> = {\n\t\tget: () => (opts.getSnapshot ?? (() => nodeSnapshot(node)))(),\n\t\tsubscribe: (callback) => subscribeNodeValues(node, callback, { changesOnly: true, ...opts }),\n\t\t_node: node,\n\t};\n\tif (hasWritableSet(node) || typeof (opts as WritableStoreOptions<T>).write === \"function\") {\n\t\tconst writable = writableStore(\n\t\t\tnode,\n\t\t\topts as WritableStoreOptions<T> & {\n\t\t\t\twrite: (node: WritableNode<T>, value: T) => void;\n\t\t\t},\n\t\t);\n\t\treturn { ...base, set: writable.set, update: writable.update };\n\t}\n\treturn base;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkCA,IAAI,QAAQ;AACZ,IAAM,eAA2B,CAAC;AAClC,IAAI,cAAc;AAGX,SAAS,YAAkB;AACjC;AACD;AAGO,SAAS,WAAiB;AAChC;AACA,MAAI,UAAU,KAAK,cAAc,aAAa,OAAQ,OAAM;AAC7D;AAWO,SAAS,YACf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AC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,WAAW,MAAM,GAAG,KAAK,CAAC;AAAA,IACzF,QAAQ,CAAC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,aAAa,MAAM,GAAG,KAAK,CAAC;AAAA,IACxF,OAAOA;AAAA,EACR;AACA,MAAI,eAAeA,KAAI,KAAK,OAAQ,KAAiC,UAAU,YAAY;AAC1F,UAAM,WAAW;AAAA,MAChBA;AAAA,MACA;AAAA,IAGD;AACA,WAAO,EAAE,GAAG,MAAM,KAAK,SAAS,KAAK,QAAQ,SAAS,OAAO;AAAA,EAC9D;AACA,SAAO;AACR;AAQO,SAAS,eACfA,OACA,OAA4D,CAAC,GACrB;AACxC,QAAM,OAAsB;AAAA,IAC3B,KAAK,OAAO,KAAK,gBAAgB,MAAM,aAAaA,KAAI,IAAI;AAAA,IAC5D,WAAW,CAAC,aAAa,oBAAoBA,OAAM,UAAU,EAAE,aAAa,MAAM,GAAG,KAAK,CAAC;AAAA,IAC3F,OAAOA;AAAA,EACR;AACA,MAAI,eAAeA,KAAI,KAAK,OAAQ,KAAiC,UAAU,YAAY;AAC1F,UAAM,WAAW;AAAA,MAChBA;AAAA,MACA;AAAA,IAGD;AACA,WAAO,EAAE,GAAG,MAAM,KAAK,SAAS,KAAK,QAAQ,SAAS,OAAO;AAAA,EAC9D;AACA,SAAO;AACR;","names":["depCount","node","node","node","out","node","node","node","node","source","assertStrictJsonValue","isDenseArrayOf","assertStrictJsonValue","isPlainRecord","source","recordFromFrame","errorMessage","drain","records","node","bytesEqual","isRecord","errorMessage","requestId","request","node","errorMessage","active","nowMs","issue","status","emitOutbound","source","attempt","error","source","timer","send","timer","emitOutbound","send","entry","active","node","active","initial","validate","active","isRecord","ownKeys","assertKeys","strictJsonIdentity","isRecord","assertKeys","cmpOrd","row","errorMessage","validateSnapshotEveryChanges","statusOf","dataOf","drain","node"]}
|