@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/orchestration/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/graph/resilience.ts","../../src/batch/boundary.ts","../../src/batch/batch.ts","../../src/dispatcher/index.ts","../../src/graph/environment.ts","../../src/node/core.ts","../../src/json/codec.ts","../../src/node/versioning.ts","../../src/node/node.ts","../../src/graph/checkpoint.ts","../../src/graph/operators.ts","../../src/graph/sources.ts","../../src/graph/time.ts","../../src/orchestration/agent-runtime.ts","../../src/orchestration/work-item-runtime.ts"],"sourcesContent":["/**\n * Reusable application-infrastructure orchestration namespace.\n *\n * Retained root orchestration helpers land here only after B63 re-derives them\n * onto clean-slate graph surfaces.\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport type { Graph, TopologyGroup } from \"../graph/graph.js\";\nimport {\n\ttype BackoffPolicy,\n\tbackoffDelayMs,\n\tnextRetryDelayMs,\n\tnoBackoff,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport { timeout as timeoutOperator } from \"../graph/time.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport * from \"./agent-runtime.js\";\nexport * from \"./work-item-runtime.js\";\n\nexport {\n\ttype BackoffPolicy,\n\tbackoffDelayMs,\n\tnoBackoff,\n\tnextRetryDelayMs,\n\tretryPolicy,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tshouldRetry,\n};\n\nexport type ResilienceEvent =\n\t| { readonly kind: \"attempt\"; readonly attempt: number }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"success\"; readonly attempt?: number }\n\t| { readonly kind: \"failure\"; readonly attempt?: number; readonly error: unknown }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\nexport interface RetryStatusBundle {\n\treadonly status: Node<RetryStatus>;\n\treadonly errors: Node<unknown>;\n}\n\nexport interface BreakerOptions {\n\treadonly failureThreshold: number;\n\treadonly resetAfterMs?: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface BreakerStatus {\n\treadonly state: \"closed\" | \"open\" | \"half-open\";\n\treadonly failures: number;\n\treadonly openedAtMs?: number;\n}\n\nexport interface BreakerBundle {\n\treadonly status: Node<BreakerStatus>;\n\treadonly allowed: Node<boolean>;\n}\n\nexport interface RateLimitOptions {\n\treadonly max: number;\n\treadonly windowMs: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface RateLimitStatus {\n\treadonly allowed: number;\n\treadonly dropped: number;\n\treadonly remaining: number;\n\treadonly resetAtMs: number;\n}\n\nexport interface RateLimitBundle<T> {\n\treadonly allowed: Node<T>;\n\treadonly dropped: Node<T>;\n\treadonly status: Node<RateLimitStatus>;\n}\n\ntype RateLimitEvent<T> =\n\t| { readonly kind: \"allowed\"; readonly value: T; readonly status: RateLimitStatus }\n\t| { readonly kind: \"dropped\"; readonly value: T; readonly status: RateLimitStatus };\n\nexport interface TimeoutBundle<T> {\n\treadonly node: Node<T>;\n\treadonly status: Node<\"running\" | \"completed\" | \"errored\">;\n\treadonly errors: Node<unknown>;\n}\n\n/** D136 graph-visible process command fact. */\nexport interface ProcessCommand<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Event draft returned by a ProcessBundle reducer before runtime ordering. */\nexport interface ProcessEventDraft<T = unknown> {\n\treadonly id?: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Ordered process event fact. These are DATA facts, not protocol messages. */\nexport interface ProcessEvent<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly commandId: string;\n\treadonly commandType: string;\n\treadonly payload: T;\n\treadonly timestampMs: number;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Effect-request draft emitted by a ProcessBundle reducer for visible effect runners. */\nexport interface ProcessEffectRequestDraft<T = unknown> {\n\treadonly id?: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Ordered effect-request fact. Effect runners consume this node in later slices. */\nexport interface ProcessEffectRequest<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly commandId: string;\n\treadonly commandType: string;\n\treadonly payload: T;\n\treadonly timestampMs: number;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ProcessEffectCommandType =\n\t| \"effect.result\"\n\t| \"effect.failure\"\n\t| \"effect.cancel\"\n\t| \"effect.timeout\";\n\ninterface ProcessEffectOutcomeBase {\n\treadonly effectId: string;\n\treadonly effectType: string;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly commandId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ProcessEffectOutcome<TResult = unknown> =\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"result\"; readonly value: TResult })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"failure\"; readonly error: unknown })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"cancel\"; readonly reason?: string })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"timeout\"; readonly error: unknown });\n\nexport type ProcessEffectCommandPayload<TResult = unknown> =\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"result\";\n\t\t\treadonly value: TResult;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"failure\";\n\t\t\treadonly error: unknown;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"cancel\";\n\t\t\treadonly reason?: string;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"timeout\";\n\t\t\treadonly error: unknown;\n\t });\n\nexport type ProcessErrorCode =\n\t| \"malformed-command\"\n\t| \"reducer-threw\"\n\t| \"clock-threw\"\n\t| \"malformed-state\"\n\t| \"malformed-event\"\n\t| \"malformed-effect\";\n\n/** Graph-visible ProcessBundle error fact. These are DATA facts, not protocol ERROR. */\nexport interface ProcessError {\n\treadonly code: ProcessErrorCode;\n\treadonly message: string;\n\treadonly command?: unknown;\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly cursor: ProcessCursor;\n}\n\n/** Accepted/rejected command outcome projected from the ProcessBundle runtime. */\nexport interface ProcessStatus {\n\treadonly state: \"accepted\" | \"rejected\";\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly eventCount: number;\n\treadonly effectCount: number;\n\treadonly errorCode?: ProcessErrorCode;\n\treadonly cursor: ProcessCursor;\n}\n\nexport interface ProcessEffectRunnerStatus {\n\treadonly state: \"requested\" | \"commanded\" | \"rejected\";\n\treadonly effectId?: string;\n\treadonly effectType?: string;\n\treadonly commandId?: string;\n\treadonly commandType?: ProcessEffectCommandType;\n\treadonly requested: number;\n\treadonly commanded: number;\n\treadonly rejected: number;\n}\n\nexport interface ProcessEffectRunnerError {\n\treadonly code: \"malformed-outcome\";\n\treadonly message: string;\n\treadonly outcome?: unknown;\n\treadonly effectId?: string;\n\treadonly effectType?: string;\n}\n\n/** Ordered audit fact for one attempted command reduction. */\nexport interface ProcessAuditRecord {\n\treadonly seq: number;\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly outcome: \"success\" | \"failure\";\n\treadonly eventIds: readonly string[];\n\treadonly eventTypes: readonly string[];\n\treadonly effectIds: readonly string[];\n\treadonly effectTypes: readonly string[];\n\treadonly errorCode?: ProcessErrorCode;\n\treadonly errorMessage?: string;\n\treadonly cursor: ProcessCursor;\n}\n\n/** Monotonic graph-visible ProcessBundle cursor counters. */\nexport interface ProcessCursor {\n\treadonly eventSeq: number;\n\treadonly effectSeq: number;\n\treadonly commandCount: number;\n\treadonly errorCount: number;\n\treadonly auditSeq: number;\n}\n\n/** Internal runtime stream fact exposed through ProcessBundle projection nodes. */\ntype ProcessRuntimeFact<TState = unknown, TEvent = unknown, TEffect = unknown> =\n\t| { readonly kind: \"state\"; readonly state: TState; readonly cursor: ProcessCursor }\n\t| { readonly kind: \"event\"; readonly event: ProcessEvent<TEvent> }\n\t| { readonly kind: \"effect-request\"; readonly effect: ProcessEffectRequest<TEffect> }\n\t| { readonly kind: \"status\"; readonly status: ProcessStatus }\n\t| { readonly kind: \"error\"; readonly error: ProcessError }\n\t| { readonly kind: \"audit\"; readonly audit: ProcessAuditRecord }\n\t| { readonly kind: \"cursor\"; readonly cursor: ProcessCursor };\n\ntype ProcessEffectRunnerFact<TResult = unknown> =\n\t| { readonly kind: \"outcome\"; readonly outcome: ProcessEffectOutcome<TResult> }\n\t| {\n\t\t\treadonly kind: \"command\";\n\t\t\treadonly command: ProcessCommand<ProcessEffectCommandPayload<TResult>>;\n\t }\n\t| { readonly kind: \"error\"; readonly error: ProcessEffectRunnerError };\n\n/** Reducer result: next process state plus optional event/effect-request drafts. */\nexport interface ProcessReduction<TState = unknown, TEvent = unknown, TEffect = unknown> {\n\treadonly state: TState;\n\treadonly events?: readonly ProcessEventDraft<TEvent>[];\n\treadonly effects?: readonly ProcessEffectRequestDraft<TEffect>[];\n}\n\n/** Sync ProcessBundle reducer. Async effects belong in graph-visible adapters, not here. */\nexport type ProcessReducer<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> = (command: ProcessCommand<TCommand>, state: TState) => ProcessReduction<TState, TEvent, TEffect>;\n\n/** Options for a D136 facts-plus-reducer ProcessBundle. */\nexport interface ProcessBundleOptions<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> {\n\treadonly name?: string;\n\treadonly initialState: TState;\n\treadonly reduce: ProcessReducer<TCommand, TState, TEvent, TEffect>;\n\treadonly now?: () => number;\n}\n\n/** D136 facts-plus-reducer process bundle. It is not a workflow engine or hidden runtime owner. */\nexport interface ProcessBundle<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> {\n\treadonly command: Node<ProcessCommand<TCommand>>;\n\treadonly events: Node<ProcessEvent<TEvent>>;\n\treadonly state: Node<TState>;\n\treadonly audit: Node<ProcessAuditRecord>;\n\treadonly effectRequests: Node<ProcessEffectRequest<TEffect>>;\n\treadonly status: Node<ProcessStatus>;\n\treadonly errors: Node<ProcessError>;\n\treadonly cursor: Node<ProcessCursor>;\n\tdispatch(command: ProcessCommand<TCommand>): ProcessCommand<TCommand>;\n\t/** Release only graph-owned retain roots; process facts/topology/cache/state remain ordinary graph data. */\n\trelease(): void;\n}\n\nexport interface ProcessEffectRunnerOptions<TResult = unknown> {\n\treadonly name?: string;\n\treadonly outcomes: readonly Node<ProcessEffectOutcome<TResult>>[];\n}\n\nexport interface ProcessEffectRunnerBundle<TEffect = unknown, TResult = unknown> {\n\treadonly requests: Node<ProcessEffectRequest<TEffect>>;\n\treadonly outcomes: Node<ProcessEffectOutcome<TResult>>;\n\treadonly commands: Node<ProcessCommand<ProcessEffectCommandPayload<TResult>>>;\n\treadonly status: Node<ProcessEffectRunnerStatus>;\n\treadonly errors: Node<ProcessEffectRunnerError>;\n\trelease(): void;\n}\n\ninterface AttachedProcessCommandSources<TCommand> {\n\tsources: Node<ProcessCommand<TCommand>>[];\n}\n\nconst processCommandSources = new WeakMap<\n\tProcessBundle<unknown, unknown, unknown, unknown>,\n\tAttachedProcessCommandSources<unknown>\n>();\n\nexport function retryStatusBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: { name?: string; policy?: RetryPolicy } = {},\n): RetryStatusBundle {\n\tconst policy = opts.policy ?? retryPolicy();\n\tconst name = opts.name ?? \"retry\";\n\tconst status = graph.node<RetryStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<RetryStatus>() ??\n\t\t\t\t({ state: \"idle\", attempt: 0, maxAttempts: policy.maxAttempts } satisfies RetryStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tnext = { state: \"running\", attempt: event.attempt, maxAttempts: policy.maxAttempts };\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"success\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"succeeded\",\n\t\t\t\t\t\tattempt: event.attempt ?? next.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"failure\") {\n\t\t\t\t\tconst attempt = event.attempt ?? next.attempt;\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: shouldRetry(policy, attempt) ? \"failed\" : \"exhausted\",\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: shouldRetry(policy, attempt)\n\t\t\t\t\t\t\t? nextRetryDelayMs(policy, attempt + 1)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\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: \"retryStatus\" },\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 ResilienceEvent;\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: \"retryErrors\" },\n\t);\n\treturn { status, errors };\n}\n\nexport function breakerBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: BreakerOptions,\n): BreakerBundle {\n\tif (!Number.isInteger(opts.failureThreshold) || opts.failureThreshold <= 0) {\n\t\tthrow new RangeError(\"breakerBundle: failureThreshold must be a positive integer\");\n\t}\n\tconst name = opts.name ?? \"breaker\";\n\tconst now = opts.now ?? Date.now;\n\tconst status = graph.node<BreakerStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<BreakerStatus>() ??\n\t\t\t\t({ state: \"closed\", failures: 0 } satisfies BreakerStatus);\n\t\t\tif (\n\t\t\t\tnext.state === \"open\" &&\n\t\t\t\topts.resetAfterMs !== undefined &&\n\t\t\t\tnext.openedAtMs !== undefined &&\n\t\t\t\tnow() - next.openedAtMs >= opts.resetAfterMs\n\t\t\t) {\n\t\t\t\tnext = { ...next, state: \"half-open\" };\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"success\") {\n\t\t\t\t\tnext = { state: \"closed\", failures: 0 };\n\t\t\t\t} else if (event.kind === \"failure\" || event.kind === \"exhausted\") {\n\t\t\t\t\tconst failures = next.failures + 1;\n\t\t\t\t\tnext =\n\t\t\t\t\t\tfailures >= opts.failureThreshold\n\t\t\t\t\t\t\t? { state: \"open\", failures, openedAtMs: now() }\n\t\t\t\t\t\t\t: { ...next, failures };\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: \"breakerStatus\" },\n\t);\n\tconst allowed = graph.node<boolean>(\n\t\t[status],\n\t\t(ctx) => {\n\t\t\tconst statusBatch = depBatch(ctx, 0) ?? [];\n\t\t\tfor (const value of statusBatch) {\n\t\t\t\tctx.down([[\"DATA\", (value as BreakerStatus).state !== \"open\"]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"breakerAllowed\" },\n\t);\n\treturn { status, allowed };\n}\n\nexport function rateLimitBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\topts: RateLimitOptions,\n): RateLimitBundle<T> {\n\tif (!Number.isInteger(opts.max) || opts.max <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: max must be a positive integer\");\n\t}\n\tif (!Number.isFinite(opts.windowMs) || opts.windowMs <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: windowMs must be positive\");\n\t}\n\tconst now = opts.now ?? Date.now;\n\tconst name = opts.name ?? \"rateLimit\";\n\tconst events = graph.node<RateLimitEvent<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\ttype State = { count: number; resetAtMs: number; allowed: number; dropped: number };\n\t\t\tconst current = now();\n\t\t\tlet state =\n\t\t\t\tctx.state.get<State>() ??\n\t\t\t\t({ count: 0, resetAtMs: current + opts.windowMs, allowed: 0, dropped: 0 } satisfies State);\n\t\t\tif (current >= state.resetAtMs) {\n\t\t\t\tstate = { ...state, count: 0, resetAtMs: current + opts.windowMs };\n\t\t\t}\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst allowed = state.count < opts.max;\n\t\t\t\tstate = allowed\n\t\t\t\t\t? { ...state, count: state.count + 1, allowed: state.allowed + 1 }\n\t\t\t\t\t: { ...state, dropped: state.dropped + 1 };\n\t\t\t\tconst status = {\n\t\t\t\t\tallowed: state.allowed,\n\t\t\t\t\tdropped: state.dropped,\n\t\t\t\t\tremaining: Math.max(0, opts.max - state.count),\n\t\t\t\t\tresetAtMs: state.resetAtMs,\n\t\t\t\t} satisfies RateLimitStatus;\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\tallowed\n\t\t\t\t\t\t\t? ({ kind: \"allowed\", value: value as T, status } satisfies RateLimitEvent<T>)\n\t\t\t\t\t\t\t: ({ kind: \"dropped\", value: value as T, status } satisfies RateLimitEvent<T>),\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},\n\t\t{ name: `${name}/events`, factory: \"rateLimitEvents\" },\n\t);\n\tconst allowed = graph.node<T>(\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 RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"allowed\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"rateLimitAllowed\" },\n\t);\n\tconst dropped = graph.node<T>(\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 RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"dropped\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/dropped`, factory: \"rateLimitDropped\" },\n\t);\n\tconst status = graph.node<RateLimitStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", (event as RateLimitEvent<T>).status]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"rateLimitStatus\" },\n\t);\n\treturn { allowed, dropped, status };\n}\n\nexport function timeoutBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tms: number,\n\topts: { name?: string } = {},\n): TimeoutBundle<T> {\n\tconst name = opts.name ?? \"timeout\";\n\tconst node = timeoutOperator(source, ms);\n\tconst status = graph.node<\"running\" | \"completed\" | \"errored\">(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal === true) ctx.down([[\"DATA\", \"completed\"]]);\n\t\t\telse if (terminal !== false && terminal !== undefined) ctx.down([[\"DATA\", \"errored\"]]);\n\t\t\telse if ((depBatch(ctx, 0) ?? []).length > 0) ctx.down([[\"DATA\", \"running\"]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"timeoutStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal !== true && terminal !== false && terminal !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", terminal]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"timeoutErrors\" },\n\t);\n\treturn { node, status, errors };\n}\n\n/**\n * Build a D136 ProcessBundle from graph-visible command facts and a reducer.\n *\n * The bundle retains its runtime/projection nodes until `release()` is called.\n * Reducer and validation failures are emitted as DATA error/status/audit facts;\n * they do not mint protocol ERROR messages or own restore/hydration behavior.\n */\nexport function processBundle<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n>(\n\tgraph: Graph,\n\topts: ProcessBundleOptions<TCommand, TState, TEvent, TEffect>,\n): ProcessBundle<TCommand, TState, TEvent, TEffect> {\n\tif (typeof opts.reduce !== \"function\") {\n\t\tthrow new TypeError(\"processBundle: reduce must be a function\");\n\t}\n\tif (opts.initialState === undefined) {\n\t\tthrow new TypeError(\"processBundle: initialState must not be undefined\");\n\t}\n\tconst name = opts.name ?? \"process\";\n\tconst now = opts.now ?? Date.now;\n\tconst topology = graph.topologyGroup({ name: `${name}.process` });\n\tconst command = topology.node<ProcessCommand<TCommand>>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"processCommand\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst runtime = topology.node<ProcessRuntimeFact<TState, TEvent, TEffect>>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessRuntimeState<TState>>() ??\n\t\t\t\t({\n\t\t\t\t\teventSeq: 0,\n\t\t\t\t\teffectSeq: 0,\n\t\t\t\t\tcommandCount: 0,\n\t\t\t\t\terrorCount: 0,\n\t\t\t\t\tauditSeq: 0,\n\t\t\t\t\tseenEventIds: [],\n\t\t\t\t\tseenEffectIds: [],\n\t\t\t\t\tstate: opts.initialState,\n\t\t\t\t} satisfies ProcessRuntimeState<TState>);\n\t\t\tctx.state.persist(true);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = reduceProcessCommandFact(\n\t\t\t\t\traw,\n\t\t\t\t\tstate,\n\t\t\t\t\topts.reduce as ProcessReducer<unknown, TState, unknown, unknown>,\n\t\t\t\t\tnow,\n\t\t\t\t\t(fact) => ctx.down([[\"DATA\", fact as ProcessRuntimeFact<TState, TEvent, TEffect>]]),\n\t\t\t\t);\n\t\t\t\tctx.state.set(state);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processRuntime\",\n\t\t\tmeta: { process: \"facts-plus-reducer\", d: \"D136\" },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst events = processProjection<ProcessEvent<TEvent>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/events`,\n\t\t\"processEvents\",\n\t\t(fact) => (fact.kind === \"event\" ? fact.event : undefined),\n\t);\n\tconst state = processProjection<TState, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/state`,\n\t\t\"processState\",\n\t\t(fact) => (fact.kind === \"state\" ? fact.state : undefined),\n\t);\n\tconst audit = processProjection<ProcessAuditRecord, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/audit`,\n\t\t\"processAudit\",\n\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t);\n\tconst effectRequests = processProjection<ProcessEffectRequest<TEffect>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/effectRequests`,\n\t\t\"processEffectRequests\",\n\t\t(fact) => (fact.kind === \"effect-request\" ? fact.effect : undefined),\n\t);\n\tconst status = processProjection<ProcessStatus, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/status`,\n\t\t\"processStatus\",\n\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t);\n\tconst errors = processProjection<ProcessError, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst cursor = processProjection<ProcessCursor, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/cursor`,\n\t\t\"processCursor\",\n\t\t(fact) => (fact.kind === \"cursor\" ? fact.cursor : undefined),\n\t);\n\tconst retainProcessNodes = () => [\n\t\tgraph.retain(runtime, { reason: `${name}.process.runtime` }),\n\t\tgraph.retain(events, { reason: `${name}.process.events` }),\n\t\tgraph.retain(state, { reason: `${name}.process.state` }),\n\t\tgraph.retain(audit, { reason: `${name}.process.audit` }),\n\t\tgraph.retain(effectRequests, { reason: `${name}.process.effectRequests` }),\n\t\tgraph.retain(status, { reason: `${name}.process.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.process.errors` }),\n\t\tgraph.retain(cursor, { reason: `${name}.process.cursor` }),\n\t];\n\tlet releaseRetains = retainProcessNodes();\n\tlet released = false;\n\tconst bundle: ProcessBundle<TCommand, TState, TEvent, TEffect> = {\n\t\tcommand,\n\t\tevents,\n\t\tstate,\n\t\taudit,\n\t\teffectRequests,\n\t\tstatus,\n\t\terrors,\n\t\tcursor,\n\t\tdispatch(next) {\n\t\t\tcommand.down([[\"DATA\", next]]);\n\t\t\treturn next;\n\t\t},\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.process.release` });\n\t\t\t\treleased = true;\n\t\t\t\tprocessCommandSources.delete(\n\t\t\t\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treleaseRetains = retainProcessNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n\tprocessCommandSources.set(\n\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t{ sources: [] },\n\t);\n\treturn bundle;\n}\n\n/**\n * Build a D156 graph-visible effect runner adapter over a ProcessBundle.\n *\n * The runner consumes visible effect-request and outcome facts, then publishes\n * ordinary ProcessCommand DATA facts back through process.command via a declared\n * graph edge. Async handlers, timers, and process state ownership stay outside\n * this helper.\n */\nexport function processEffectRunner<TEffect = unknown, TResult = unknown>(\n\tgraph: Graph,\n\tprocess: ProcessBundle<unknown, unknown, unknown, TEffect>,\n\topts: ProcessEffectRunnerOptions<TResult>,\n): ProcessEffectRunnerBundle<TEffect, TResult> {\n\tif (opts.outcomes.length === 0) {\n\t\tthrow new RangeError(\"processEffectRunner: outcomes must contain at least one node\");\n\t}\n\tconst name = opts.name ?? \"processEffectRunner\";\n\tconst topology = graph.topologyGroup({ name: `${name}.effectRunner` });\n\tconst requests = topology.node<ProcessEffectRequest<TEffect>>(\n\t\t[process.effectRequests],\n\t\t(ctx) => {\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", request as ProcessEffectRequest<TEffect>]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/requests`,\n\t\t\tfactory: \"processEffectRunnerRequests\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst runtime = topology.node<ProcessEffectRunnerFact<TResult>>(\n\t\t[...opts.outcomes],\n\t\t(ctx) => {\n\t\t\tfor (let i = 0; i < opts.outcomes.length; i += 1) {\n\t\t\t\tfor (const raw of depBatch(ctx, i) ?? []) {\n\t\t\t\t\tconst parsed = parseProcessEffectOutcome<TResult>(raw);\n\t\t\t\t\tif (typeof parsed === \"string\") {\n\t\t\t\t\t\tconst error = {\n\t\t\t\t\t\t\tcode: \"malformed-outcome\",\n\t\t\t\t\t\t\tmessage: parsed,\n\t\t\t\t\t\t\toutcome: raw,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerError;\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", error }]]);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst outcome = parsed as ProcessEffectOutcome<TResult>;\n\t\t\t\t\tconst command = processEffectOutcomeCommand(outcome);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"outcome\", outcome }]]);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"command\", command }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processEffectRunner\",\n\t\t\tmeta: { process: \"effect-runner\", d: \"D156\" },\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outcomes = processEffectRunnerProjection<ProcessEffectOutcome<TResult>, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/outcomes`,\n\t\t\"processEffectRunnerOutcomes\",\n\t\t(fact) => (fact.kind === \"outcome\" ? fact.outcome : undefined),\n\t);\n\tconst commands = processEffectRunnerProjection<\n\t\tProcessCommand<ProcessEffectCommandPayload<TResult>>,\n\t\tTResult\n\t>(topology, runtime, `${name}/commands`, \"processEffectRunnerCommands\", (fact) =>\n\t\tfact.kind === \"command\" ? fact.command : undefined,\n\t);\n\tconst errors = processEffectRunnerProjection<ProcessEffectRunnerError, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processEffectRunnerErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst status = topology.node<ProcessEffectRunnerStatus>(\n\t\t[requests, runtime],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessEffectRunnerState>() ??\n\t\t\t\t({ requested: 0, commanded: 0, rejected: 0 } satisfies ProcessEffectRunnerState);\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = { ...state, requested: state.requested + 1 };\n\t\t\t\tconst typedRequest = request as ProcessEffectRequest<TEffect>;\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\tstate: \"requested\",\n\t\t\t\t\t\t\teffectId: typedRequest.id,\n\t\t\t\t\t\t\teffectType: typedRequest.type,\n\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tfor (const fact of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst typedFact = fact as ProcessEffectRunnerFact<TResult>;\n\t\t\t\tif (typedFact.kind === \"command\") {\n\t\t\t\t\tstate = { ...state, commanded: state.commanded + 1 };\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\tstate: \"commanded\",\n\t\t\t\t\t\t\t\teffectId: typedFact.command.payload.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.command.payload.effectType,\n\t\t\t\t\t\t\t\tcommandId: typedFact.command.id,\n\t\t\t\t\t\t\t\tcommandType: typedFact.command.type as ProcessEffectCommandType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tif (typedFact.kind === \"error\") {\n\t\t\t\t\tstate = { ...state, rejected: state.rejected + 1 };\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\tstate: \"rejected\",\n\t\t\t\t\t\t\t\teffectId: typedFact.error.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.error.effectType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\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(state);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"processEffectRunnerStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst retainRunnerNodes = () => [\n\t\tgraph.retain(requests, { reason: `${name}.effectRunner.requests` }),\n\t\tgraph.retain(outcomes, { reason: `${name}.effectRunner.outcomes` }),\n\t\tgraph.retain(commands, { reason: `${name}.effectRunner.commands` }),\n\t\tgraph.retain(status, { reason: `${name}.effectRunner.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.effectRunner.errors` }),\n\t];\n\tlet releaseRetains = retainRunnerNodes();\n\ttry {\n\t\tattachProcessCommandSource(process, commands);\n\t} catch (error) {\n\t\tfor (const releaseRetain of releaseRetains) releaseRetain();\n\t\treleaseRetains = [];\n\t\ttopology.release({ reason: `${name}.effectRunner.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\trequests,\n\t\toutcomes,\n\t\tcommands,\n\t\tstatus,\n\t\terrors,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\tdetachProcessCommandSource(process, commands);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.effectRunner.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachProcessCommandSource(process, commands);\n\t\t\t\treleaseRetains = retainRunnerNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function constantBackoff(delayMs: number): BackoffPolicy {\n\treturn { kind: \"constant\", delayMs };\n}\n\ninterface ProcessEffectRunnerState {\n\trequested: number;\n\tcommanded: number;\n\trejected: number;\n}\n\ninterface ProcessRuntimeState<TState> {\n\teventSeq: number;\n\teffectSeq: number;\n\tcommandCount: number;\n\terrorCount: number;\n\tauditSeq: number;\n\tseenEventIds: string[];\n\tseenEffectIds: string[];\n\tstate: TState;\n}\n\nfunction processEffectRunnerProjection<T, TResult>(\n\ttopology: TopologyGroup,\n\truntime: Node<ProcessEffectRunnerFact<TResult>>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: ProcessEffectRunnerFact<TResult>) => T | undefined,\n): Node<T> {\n\treturn topology.node<T>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst value = pick(fact as ProcessEffectRunnerFact<TResult>);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction parseProcessEffectOutcome<TResult>(raw: unknown): ProcessEffectOutcome<TResult> | string {\n\tif (!isObjectRecord(raw)) return \"processEffectRunner: outcome must be an object\";\n\tif (typeof raw.kind !== \"string\") {\n\t\treturn \"processEffectRunner: outcome kind must be a string\";\n\t}\n\tif (\n\t\traw.kind !== \"result\" &&\n\t\traw.kind !== \"failure\" &&\n\t\traw.kind !== \"cancel\" &&\n\t\traw.kind !== \"timeout\"\n\t) {\n\t\treturn \"processEffectRunner: outcome kind must be result, failure, cancel, or timeout\";\n\t}\n\tif (typeof raw.effectId !== \"string\" || raw.effectId.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectId must be a non-empty string\";\n\t}\n\tif (typeof raw.effectType !== \"string\" || raw.effectType.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectType must be a non-empty string\";\n\t}\n\tif (\"commandId\" in raw && raw.commandId !== undefined) {\n\t\tif (typeof raw.commandId !== \"string\" || raw.commandId.length === 0) {\n\t\t\treturn \"processEffectRunner: outcome commandId must be a non-empty string\";\n\t\t}\n\t}\n\tfor (const key of [\"processId\", \"correlationId\", \"causationId\"] as const) {\n\t\tif (key in raw && raw[key] !== undefined && typeof raw[key] !== \"string\") {\n\t\t\treturn `processEffectRunner: outcome ${key} must be a string`;\n\t\t}\n\t}\n\tif (\"metadata\" in raw && raw.metadata !== undefined && !isObjectRecord(raw.metadata)) {\n\t\treturn \"processEffectRunner: outcome metadata must be a plain object\";\n\t}\n\tif (raw.kind === \"result\" && !(\"value\" in raw)) {\n\t\treturn \"processEffectRunner: result outcome must carry value\";\n\t}\n\tif ((raw.kind === \"failure\" || raw.kind === \"timeout\") && !(\"error\" in raw)) {\n\t\treturn `processEffectRunner: ${raw.kind} outcome must carry error`;\n\t}\n\tif (\n\t\traw.kind === \"cancel\" &&\n\t\t\"reason\" in raw &&\n\t\traw.reason !== undefined &&\n\t\ttypeof raw.reason !== \"string\"\n\t) {\n\t\treturn \"processEffectRunner: cancel outcome reason must be a string\";\n\t}\n\treturn raw as unknown as ProcessEffectOutcome<TResult>;\n}\n\nfunction processEffectOutcomeCommand<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessCommand<ProcessEffectCommandPayload<TResult>> {\n\tconst commandType = processEffectCommandType(outcome.kind);\n\treturn {\n\t\tid: outcome.commandId ?? `${outcome.effectId}:${commandType}`,\n\t\ttype: commandType,\n\t\tpayload: processEffectCommandPayload(outcome),\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n}\n\nfunction processEffectCommandType(kind: ProcessEffectOutcome[\"kind\"]): ProcessEffectCommandType {\n\tswitch (kind) {\n\t\tcase \"result\":\n\t\t\treturn \"effect.result\";\n\t\tcase \"failure\":\n\t\t\treturn \"effect.failure\";\n\t\tcase \"cancel\":\n\t\t\treturn \"effect.cancel\";\n\t\tcase \"timeout\":\n\t\t\treturn \"effect.timeout\";\n\t}\n}\n\nfunction processEffectCommandPayload<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessEffectCommandPayload<TResult> {\n\tconst base = {\n\t\teffectId: outcome.effectId,\n\t\teffectType: outcome.effectType,\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n\tswitch (outcome.kind) {\n\t\tcase \"result\":\n\t\t\treturn { ...base, kind: \"result\", value: outcome.value };\n\t\tcase \"failure\":\n\t\t\treturn { ...base, kind: \"failure\", error: outcome.error };\n\t\tcase \"cancel\":\n\t\t\treturn { ...base, kind: \"cancel\", reason: outcome.reason };\n\t\tcase \"timeout\":\n\t\t\treturn { ...base, kind: \"timeout\", error: outcome.error };\n\t}\n}\n\nfunction attachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\tprocess.command.replaceDeps([...sources], processCommandSourceFn(sources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\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\tprocess.command.replaceDeps([...nextSources], processCommandSourceFn(nextSources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction processCommandSourceFn(sourceCount: number) {\n\treturn (ctx: Parameters<NodeFn>[0]) => {\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 ProcessCommand<unknown>]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction processRuntimeDraft<TState>(\n\tstate: ProcessRuntimeState<TState>,\n): ProcessRuntimeState<TState> {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t\tseenEventIds: [...state.seenEventIds],\n\t\tseenEffectIds: [...state.seenEffectIds],\n\t\tstate: state.state,\n\t};\n}\n\nfunction reduceProcessCommandFact<TState>(\n\traw: unknown,\n\tstate: ProcessRuntimeState<TState>,\n\treduce: ProcessReducer<unknown, TState, unknown, unknown>,\n\tnow: () => number,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n): ProcessRuntimeState<TState> {\n\tconst draft = processRuntimeDraft(state);\n\tdraft.commandCount += 1;\n\tconst parsed = parseProcessCommand(raw);\n\tif (typeof parsed === \"string\") {\n\t\temitProcessFailure(draft, emit, raw, undefined, \"malformed-command\", parsed);\n\t\treturn draft;\n\t}\n\tconst command = parsed as ProcessCommand<unknown>;\n\tlet reduction: ProcessReduction<TState, unknown, unknown>;\n\tconst reducerState = cloneProcessState(state.state);\n\tif (!reducerState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", reducerState.message);\n\t\treturn draft;\n\t}\n\ttry {\n\t\treduction = reduce(command, reducerState.value);\n\t} catch (error) {\n\t\trethrowGraphRuntimeInvariant(error);\n\t\temitProcessFailure(draft, emit, command, command, \"reducer-threw\", errorMessage(error));\n\t\treturn draft;\n\t}\n\tif (!isObjectRecord(reduction) || !(\"state\" in reduction)) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer must return { state, events?, effects? }\",\n\t\t);\n\t\treturn draft;\n\t}\n\tif (reduction.state === undefined) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer state must not be undefined\",\n\t\t);\n\t\treturn draft;\n\t}\n\tconst privateState = cloneProcessState(reduction.state);\n\tif (!privateState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", privateState.message);\n\t\treturn draft;\n\t}\n\tconst visibleState = cloneProcessState(privateState.value);\n\tif (!visibleState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", visibleState.message);\n\t\treturn draft;\n\t}\n\tconst preparedEvents = prepareProcessEvents(command, draft, reduction.events ?? []);\n\tif (typeof preparedEvents === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-event\", preparedEvents);\n\t\treturn draft;\n\t}\n\tconst preparedEffects = prepareProcessEffects(command, draft, reduction.effects ?? []);\n\tif (typeof preparedEffects === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-effect\", preparedEffects);\n\t\treturn draft;\n\t}\n\tconst timestampMs = readTimestampMs(now);\n\tif (typeof timestampMs === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"clock-threw\", timestampMs);\n\t\treturn draft;\n\t}\n\tdraft.state = privateState.value;\n\temit({ kind: \"state\", state: visibleState.value, cursor: processCursorOf(draft) });\n\tconst events: ProcessEvent<unknown>[] = [];\n\tfor (const eventDraft of preparedEvents) {\n\t\tdraft.eventSeq += 1;\n\t\tdraft.seenEventIds.push(eventDraft.id);\n\t\tconst event: ProcessEvent<unknown> = {\n\t\t\tid: eventDraft.id,\n\t\t\ttype: eventDraft.type,\n\t\t\tseq: draft.eventSeq,\n\t\t\tcursor: draft.eventSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: eventDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(eventDraft.processId === undefined ? {} : { processId: eventDraft.processId }),\n\t\t\t...(eventDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: eventDraft.correlationId }),\n\t\t\t...(eventDraft.causationId === undefined ? {} : { causationId: eventDraft.causationId }),\n\t\t\t...(eventDraft.metadata === undefined ? {} : { metadata: eventDraft.metadata }),\n\t\t};\n\t\tevents.push(event);\n\t\temit({ kind: \"event\", event });\n\t}\n\tconst effects: ProcessEffectRequest<unknown>[] = [];\n\tfor (const effectDraft of preparedEffects) {\n\t\tdraft.effectSeq += 1;\n\t\tdraft.seenEffectIds.push(effectDraft.id);\n\t\tconst effect: ProcessEffectRequest<unknown> = {\n\t\t\tid: effectDraft.id,\n\t\t\ttype: effectDraft.type,\n\t\t\tseq: draft.effectSeq,\n\t\t\tcursor: draft.effectSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: effectDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(effectDraft.processId === undefined ? {} : { processId: effectDraft.processId }),\n\t\t\t...(effectDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: effectDraft.correlationId }),\n\t\t\t...(effectDraft.causationId === undefined ? {} : { causationId: effectDraft.causationId }),\n\t\t\t...(effectDraft.metadata === undefined ? {} : { metadata: effectDraft.metadata }),\n\t\t};\n\t\teffects.push(effect);\n\t\temit({ kind: \"effect-request\", effect });\n\t}\n\temitProcessStatus(draft, emit, command, \"accepted\", events.length, effects.length);\n\temitProcessAudit(draft, emit, command, \"success\", events, effects, undefined, undefined);\n\temit({ kind: \"cursor\", cursor: processCursorOf(draft) });\n\treturn draft;\n}\n\nfunction processProjection<TOut, TState, TEvent, TEffect>(\n\tgraph: Graph | TopologyGroup,\n\truntime: Node<ProcessRuntimeFact<TState, TEvent, TEffect>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: ProcessRuntimeFact<TState, TEvent, TEffect>) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst selected = select(raw as ProcessRuntimeFact<TState, TEvent, TEffect>);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false },\n\t);\n}\n\nfunction parseProcessCommand(value: unknown): ProcessCommand<unknown> | string {\n\tif (!isObjectRecord(value)) return \"processBundle: command fact must be an object\";\n\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\treturn \"processBundle: command id must be a non-empty string\";\n\t}\n\tif (typeof value.type !== \"string\" || value.type.length === 0) {\n\t\treturn \"processBundle: command type must be a non-empty string\";\n\t}\n\treturn {\n\t\tid: value.id,\n\t\ttype: value.type,\n\t\tpayload: value.payload,\n\t\t...(typeof value.processId === \"string\" ? { processId: value.processId } : {}),\n\t\t...(typeof value.correlationId === \"string\" ? { correlationId: value.correlationId } : {}),\n\t\t...(typeof value.causationId === \"string\" ? { causationId: value.causationId } : {}),\n\t\t...(isObjectRecord(value.metadata) ? { metadata: value.metadata } : {}),\n\t};\n}\n\nfunction prepareProcessEvents(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEventDraft<unknown>[],\n): Array<ProcessEventDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: events must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEventDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: event draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:event:${state.eventSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate event '${id}'`;\n\t\tif (state.seenEventIds.includes(id)) return `processBundle: duplicate event '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction prepareProcessEffects(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEffectRequestDraft<unknown>[],\n): Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: effects must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: effect draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:effect:${state.effectSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tif (state.seenEffectIds.includes(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction emitProcessFailure<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\traw: unknown,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tcode: ProcessErrorCode,\n\tmessage: string,\n): void {\n\tstate.errorCount += 1;\n\tconst cursor = processCursorOf(state);\n\tconst error: ProcessError = {\n\t\tcode,\n\t\tmessage,\n\t\tcommand: raw,\n\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\tcursor,\n\t};\n\temit({ kind: \"error\", error });\n\temitProcessStatus(state, emit, command, \"rejected\", 0, 0, code);\n\temitProcessAudit(state, emit, command, \"failure\", [], [], code, message);\n\temit({ kind: \"cursor\", cursor: processCursorOf(state) });\n}\n\nfunction emitProcessStatus<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tstatusState: ProcessStatus[\"state\"],\n\teventCount: number,\n\teffectCount: number,\n\terrorCode?: ProcessErrorCode,\n): void {\n\temit({\n\t\tkind: \"status\",\n\t\tstatus: {\n\t\t\tstate: statusState,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\teventCount,\n\t\t\teffectCount,\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction emitProcessAudit<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\toutcome: ProcessAuditRecord[\"outcome\"],\n\tevents: readonly ProcessEvent<unknown>[],\n\teffects: readonly ProcessEffectRequest<unknown>[],\n\terrorCode: ProcessErrorCode | undefined,\n\terrorMessage: string | undefined,\n): void {\n\tstate.auditSeq += 1;\n\temit({\n\t\tkind: \"audit\",\n\t\taudit: {\n\t\t\tseq: state.auditSeq,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\toutcome,\n\t\t\teventIds: events.map((event) => event.id),\n\t\t\teventTypes: events.map((event) => event.type),\n\t\t\teffectIds: effects.map((effect) => effect.id),\n\t\t\teffectTypes: effects.map((effect) => effect.type),\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\t...(errorMessage === undefined ? {} : { errorMessage }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction processCursorOf(state: ProcessRuntimeState<unknown>): ProcessCursor {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t};\n}\n\ntype CloneProcessStateResult<TState> =\n\t| { readonly ok: true; readonly value: TState }\n\t| { readonly ok: false; readonly message: string };\n\nfunction cloneProcessState<TState>(state: TState): CloneProcessStateResult<TState> {\n\tif (typeof state !== \"object\" || state === null) return { ok: true, value: state };\n\ttry {\n\t\tif (typeof globalThis.structuredClone === \"function\") {\n\t\t\treturn { ok: true, value: globalThis.structuredClone(state) as TState };\n\t\t}\n\t\treturn { ok: true, value: JSON.parse(JSON.stringify(state)) as TState };\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: `processBundle: state must be cloneable before reducer execution (${errorMessage(error)})`,\n\t\t};\n\t}\n}\n\nfunction readTimestampMs(now: () => number): number | string {\n\ttry {\n\t\tconst timestampMs = now();\n\t\tif (!Number.isFinite(timestampMs)) return \"processBundle: now() must return a finite number\";\n\t\treturn timestampMs;\n\t} catch (error) {\n\t\treturn errorMessage(error);\n\t}\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 isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\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 * 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 * 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 * 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","/**\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 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 * 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 * 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 * Wall-clock time operators (CSP-2.7 / D52 / B23). Authored as COMPOSITIONS over the already-active\n * higher-order *Map machinery (D47) + the `timer` source — NO raw `setTimeout` in any operator body\n * (R-no-raw-async / check-no-raw-async; `setTimeout` stays confined to `sources.ts`'s `timer`). The\n * timer source's `onDeactivation` clearTimeout IS the reset/cancel: switchMap's unsubscribeDep on a new\n * source value tears the in-flight timer down (the declarative equivalent of the frozen reference's\n * imperative clearTimeout-then-setTimeout). Per-language (D6/D24), never in parity.\n *\n * Shipped this cut (clean *Map+timer):\n * - delay = mergeMap(v → timer(ms)→v) (every value delayed ms, ALL kept, order preserved)\n * - debounce(Time) = switchMap(v → timer(ms)→v) (cancel-and-restart; emit the latest after quiet ms)\n * - throttle(Time) = exhaustMap(v → [v now, alive ms]) (leading edge: emit v, ignore for ms)\n *\n * Behavior on source COMPLETE (per-operator, NOT a uniform DROP): debounce/debounceTime EMIT their\n * pending trailing value — switchMap does not cancel the in-flight inner on source COMPLETE (only a\n * superseding source value cancels it via unsubscribeDep→onDeactivation→clearTimeout), so the timer still\n * fires at `ms`, emits the debounced value, and only THEN does the operator COMPLETE (RxJS\n * debounceTime parity). delay emits every still-pending delayed value then COMPLETEs (mergeMap keeps\n * all inners). throttle/throttleTime have NO trailing value (leading-edge only, RxJS default\n * trailing:false) — an open window inner is dropped when the operator completes.\n *\n * B41 tail (landed 2026-05-31, the two shapes reflect WHEN the clock arms):\n * - audit / auditTime — VALUE-TRIGGERED trailing edge: a source value opens a duration window\n * (`audit(durationSelector)` = the general/notifier form, mirroring the *Map\n * `Project` idiom + D46; `auditTime(ms)` = `audit(() => timer(ms))`), emits the\n * window's LATEST value at the window's close. Self-wires the notifier via\n * ctx.rewireNext — a normal `g.initNode(audit(sel), [source])` operator.\n * - timeout / bufferTime — SUBSCRIBE-ARMED (RxJS-cold): the clock must run from activation, before\n * any source value, so the timer/interval is a CONSTRUCTION-time dep (a depless\n * source arms lazily on subscribe per node `_activate`). A dep-bearing operator\n * body never runs at activation (only depless nodes do, node.ts), so these ship\n * as graph composition HELPERS `timeout(source, ms)` / `bufferTime(source, ms)`\n * returning a Node — NOT `g.initNode(op, [deps])` operators. timeout resets its\n * idle timer per source value via ctx.rewireNext (ERROR on the gap); bufferTime\n * is buffer-over-interval with terminal cleanup via ctx.rewireNext.\n *\n * NOT ported (D58): window/windowCount/windowTime — the Node<Node<T>> higher-order forms are a D45\n * describe island; the array forms (buffer/bufferCount/bufferTime) are the graph-first equivalent.\n *\n * Inspection caveat (timeout/bufferTime): the helper returns a BARE node (free initNode) self-carrying\n * its factory for describe auto-discovery (D51), but it is NOT in a graph's _entries — so g.describe()\n * lists it only when it is a live dep of a registered node (a first-cut limit, like the *Map inners).\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { exhaustMap, mergeMap, switchMap } from \"./higher-order.js\";\nimport { filter, initNode, map, merge, type Operator } from \"./operators.js\";\nimport { fromAny, interval, type NodeInput, of, timer } from \"./sources.js\";\n\n/** A bare inner that emits `v` once after `ms`, then COMPLETEs (timer(ms)→map(v); auto-completes). */\nfunction delayedValue<S>(v: S, ms: number): Node<S> {\n\treturn initNode(\n\t\tmap(() => v),\n\t\t[initNode(timer(ms), [])],\n\t);\n}\n\n/**\n * An inner that emits `v` IMMEDIATELY (on activation) and stays alive for `ms` (then COMPLETEs),\n * emitting nothing more — the leading-edge throttle window. `merge(of(v), silentTimer)`: `of(v)`\n * emits v + COMPLETE at t=0; `filter(()=>false)` over `timer(ms)` emits no DATA and COMPLETEs at\n * t=ms; merge forwards v at t=0 and COMPLETEs (all deps complete) at t=ms.\n */\nfunction throttleWindow<S>(v: S, ms: number): Node<S> {\n\tconst silentTimer = initNode(\n\t\tfilter<number>(() => false),\n\t\t[initNode(timer(ms), [])],\n\t) as Node<S>;\n\treturn initNode(merge<S>(), [initNode(of(v), []), silentTimer]);\n}\n\n/**\n * delay: shift every value by `ms`, preserving all values + order. `mergeMap` keeps every inner\n * timer live (equal `ms`, so they fire in arrival order).\n */\nexport function delay<S>(ms: number): Operator<S, S> {\n\treturn { ...mergeMap<S, S>((v) => delayedValue(v, ms)), factory: \"delay\" };\n}\n\n/**\n * debounce (alias `debounceTime`): emit the latest value only after `ms` of quiet. `switchMap`\n * cancels the prior timer (its onDeactivation clearTimeout) on each new source value and restarts —\n * the declarative debounce.\n *\n * RxJS-7 divergence (reference rxjs@7.8, B44): RxJS `debounceTime` FLUSHES the pending value\n * IMMEDIATELY when the source COMPLETEs (its `_complete` calls `debouncedNext()` before\n * `complete()`). This composition instead emits the pending value when the in-flight `timer(ms)`\n * fires — i.e. at `(last-value-time + ms)` — so if the source completes mid-window the trailing\n * value arrives up to `ms` later than RxJS. Inherent to the `*Map`+`timer` form (the composition\n * cannot flush early without detecting COMPLETE inside the switchMap inner); accepted, not a bug.\n */\nexport function debounce<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounce\" };\n}\n\n/** debounceTime: RxJS-named alias of {@link debounce}. */\nexport function debounceTime<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounceTime\" };\n}\n\n/**\n * throttle (alias `throttleTime`): leading-edge — emit a value immediately, then ignore the source\n * for `ms`. `exhaustMap` drops new source values while the current window inner is alive; the\n * window emits v at its leading edge and stays alive `ms`.\n *\n * Matches the RxJS-7 `throttleTime` DEFAULT (leading:true, trailing:false). The leading/trailing\n * OPTIONS RxJS exposes are NOT provided (a capability gap, not a behavior divergence; B44) — add a\n * trailing-window form if a consumer needs it.\n */\nexport function throttle<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttle\" };\n}\n\n/** throttleTime: RxJS-named alias of {@link throttle}. */\nexport function throttleTime<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttleTime\" };\n}\n\n// ── B41 tail: value-triggered (audit) + subscribe-armed (timeout/bufferTime) ──\n\n/** Per-node bookkeeping for {@link audit}: the open window's notifier + the latest value seen. */\ninterface AuditState<S> {\n\twindowOpen: boolean;\n\tlatest: { v: S } | undefined;\n\tnotifier: Node<unknown> | null;\n}\n\n/**\n * audit: VALUE-TRIGGERED trailing throttle. A source value (when no window is open) opens a duration\n * window via `durationSelector(value)` → a notifier `NodeInput` wired as dep 1 with `ctx.rewireNext`\n * (D47 — the *Map self-rewire idiom, NOT an internal subscribe, D45); during the window new source\n * values only UPDATE the tracked latest (no emit); when the notifier fires (its first DATA / COMPLETE)\n * the window closes and the LATEST value is emitted. This is throttle's trailing-edge twin\n * (throttle emits the window's FIRST value at the leading edge; audit emits the LAST at the close).\n *\n * `durationSelector` is the general/notifier form (mirrors the *Map `Project` idiom + D46); the source\n * is dep 0, the live notifier (if any) is dep 1. On source COMPLETE the pending latest is FLUSHED then\n * COMPLETE (RxJS-7 audit flush-on-complete, B44). A source/notifier ERROR is read as a real terminal\n * input so the live notifier can be removed before ERROR. Self-catching (D30); re-supplies its body on\n * every rewire.\n */\nexport function audit<S>(durationSelector: (v: S) => NodeInput<unknown>): Operator<S, S> {\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: AuditState<S> = ctx.state.get<AuditState<S>>() ?? {\n\t\t\t\twindowOpen: false,\n\t\t\t\tlatest: undefined,\n\t\t\t\tnotifier: null,\n\t\t\t};\n\t\t\tconst sourceBatch = depBatch(ctx, 0);\n\t\t\tconst notifierBatch = depBatch(ctx, 1); // live duration notifier while a window is open\n\t\t\tconst sourceTerminal = depTerminal(ctx, 0);\n\t\t\tconst notifierTerminal = depTerminal(ctx, 1);\n\n\t\t\t// every source value updates the window's latest (the value emitted at the window's close).\n\t\t\tconst sb = sourceBatch as readonly S[] | null;\n\t\t\tif (sb) for (const v of sb) st.latest = { v };\n\n\t\t\t// the window closes when its duration notifier fires (DATA or COMPLETE) → emit the latest.\n\t\t\tconst notifierFired =\n\t\t\t\tst.windowOpen &&\n\t\t\t\t((notifierBatch != null && notifierBatch.length > 0) ||\n\t\t\t\t\tisTerminalComplete(notifierTerminal));\n\t\t\tif (notifierFired) {\n\t\t\t\tif (st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tconst old = st.notifier;\n\t\t\t\tst.windowOpen = false;\n\t\t\t\tst.notifier = null;\n\t\t\t\tst.latest = undefined;\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body);\n\t\t\t}\n\n\t\t\t// source/notifier ERROR → forward ERROR, but first remove the helper-owned notifier.\n\t\t\tconst sourceError = isTerminalError(sourceTerminal);\n\t\t\tconst notifierError = isTerminalError(notifierTerminal);\n\t\t\tif (sourceError || notifierError) {\n\t\t\t\tconst err = terminalErrorValue(sourceError ? sourceTerminal : notifierTerminal);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// source COMPLETE → flush the pending latest (B44 audit flush-on-complete) then COMPLETE.\n\t\t\tif (isTerminalComplete(sourceTerminal)) {\n\t\t\t\tif (st.windowOpen && st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// a fresh source value with no open window → open one (value-triggered, trailing edge).\n\t\t\tif (!st.windowOpen && sb != null && sb.length > 0 && st.latest !== undefined) {\n\t\t\t\tconst n = fromAny<unknown>(durationSelector(st.latest.v), { iter: true });\n\t\t\t\tst.windowOpen = true;\n\t\t\t\tst.notifier = n;\n\t\t\t\tctx.rewireNext.subscribeDep(n, body); // (a same-wave close+reopen issues remove-before-add)\n\t\t\t}\n\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"audit threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn {\n\t\tfactory: \"audit\",\n\t\tbody,\n\t\topts: {\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}\n\n/** auditTime: the `ms`-specialization of {@link audit} — the window is a `timer(ms)`. */\nexport function auditTime<S>(ms: number): Operator<S, S> {\n\treturn { ...audit<S>(() => initNode(timer(ms), [])), factory: \"auditTime\" };\n}\n\n/** Per-node bookkeeping for {@link timeout}: the live idle timer (reset on each source value). */\ninterface TimeoutState {\n\ttimer: Node<unknown> | null;\n}\n\n/**\n * timeout: idle watchdog — forward every source value, but ERROR if more than `ms` elapses with no\n * value (RxJS `timeout(ms)`, `first === each === ms`). SUBSCRIBE-ARMED: the first `timer(ms)` is a\n * CONSTRUCTION-time dep, so it arms when `timeout`'s node is subscribed/activated (a depless source\n * runs lazily on `_activate`) — i.e. a source that never emits its FIRST value within `ms` still\n * errors. A dep-bearing operator body never runs at activation (only depless nodes do, node.ts), which\n * is why this is a HELPER returning a Node, not a `g.initNode(op, [source])` operator.\n *\n * Each source value forwards as-is and RESETS the idle timer (unsubscribeDep the current `timer(ms)`,\n * subscribeDep a fresh one — its `onDeactivation` clearTimeout cancels the prior countdown). The timer\n * firing (its DATA/COMPLETE) is the timeout → `[[ERROR]]`. Source COMPLETE forwards COMPLETE (no\n * error) and removes the idle timer during the terminal wave (D62 terminal-drains-queued-rewire);\n * a source ERROR forwards likewise. The idle timer is also torn down when the consumer unsubscribes\n * (timeout deactivates → dep unsub → timer onDeactivation). Self-catching (D30).\n */\nexport function timeout<S>(source: Node<S>, ms: number): Node<S> {\n\tconst makeTimer = (): Node<unknown> => initNode(timer(ms), []);\n\tconst initial = makeTimer();\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: TimeoutState = ctx.state.get<TimeoutState>() ?? { timer: initial };\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\n\t\t\t// a source value forwards as-is and resets the idle window.\n\t\t\tconst sb = srcBatch as readonly S[] | null;\n\t\t\tif (sb != null && sb.length > 0) {\n\t\t\t\tfor (const v of sb) ctx.down([[\"DATA\", v]]);\n\t\t\t\tconst old = st.timer;\n\t\t\t\tconst next = makeTimer();\n\t\t\t\tst.timer = next;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body); // remove-before-add (alignment)\n\t\t\t\tctx.rewireNext.subscribeDep(next, body);\n\t\t\t\treturn; // a value-bearing wave is never also a timeout-fire wave\n\t\t\t}\n\n\t\t\t// source COMPLETE → forward COMPLETE (no timeout fires).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// source ERROR (absorbed via errorWhenDepsError:false) → forward it.\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise this wave is the idle timer firing → timeout ERROR.\n\t\t\tconst timerBatch = depBatch(ctx, 1);\n\t\t\tif (\n\t\t\t\t(timerBatch != null && timerBatch.length > 0) ||\n\t\t\t\tisTerminalComplete(depTerminal(ctx, 1))\n\t\t\t) {\n\t\t\t\tctx.down([[\"ERROR\", new Error(`timeout: no value within ${ms}ms`)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"timeout threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn initNode<S, S>(\n\t\t{\n\t\t\tfactory: \"timeout\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, initial],\n\t);\n}\n\n/**\n * bufferTime: buffer source values and flush them as an array every `ms` (RxJS `bufferTime(ms)`).\n * SUBSCRIBE-ARMED: the `interval(ms)` notifier is a CONSTRUCTION-time dep (arms on subscribe), so an\n * empty window flushes `[]` even before the first source value — matching the landed {@link buffer}\n * (which flushes on every notifier signal). On source COMPLETE the remainder flushes then COMPLETE\n * (B44), and D62 lets the terminal wave still drain `unsubscribeDep(interval)` so the helper-owned\n * interval source deactivates instead of ticking forever.\n */\nexport function bufferTime<S>(source: Node<S>, ms: number): Node<S[]> {\n\tconst iv: Node<unknown> = initNode(interval(ms), []);\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\tconst srcBatch = depBatch(ctx, 0);\n\t\tconst tickBatch = depBatch(ctx, 1);\n\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\tconst buf = ctx.state.get<S[]>() ?? [];\n\t\tif (srcBatch) for (const v of srcBatch) buf.push(v as S);\n\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\tif (buf.length > 0) ctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\treturn;\n\t\t}\n\t\tif (isTerminalError(srcTerminal)) {\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\treturn;\n\t\t}\n\t\tif (tickBatch && tickBatch.length > 0) {\n\t\t\tctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\treturn;\n\t\t}\n\t\tctx.state.set(buf);\n\t};\n\treturn initNode<unknown, S[]>(\n\t\t{\n\t\t\tfactory: \"bufferTime\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, iv],\n\t);\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport interface SourceRef {\n\treadonly kind: string;\n\treadonly id: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestInput<T = unknown> {\n\treadonly inputId: string;\n\treadonly inputKind: string;\n\treadonly dataMode?: \"ref\" | \"summary\" | \"inline\";\n\treadonly ref?: string;\n\treadonly summary?: string;\n\treadonly value?: T;\n\treadonly schemaRef?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunGoal<TInput = unknown> {\n\treadonly kind: string;\n\treadonly summary?: string;\n\treadonly detailRef?: string;\n\treadonly input?: AgentRequestInput<TInput>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunLimits {\n\treadonly maxSteps?: number;\n\treadonly maxRequests?: number;\n\treadonly maxAttemptsPerOperation?: number;\n\treadonly maxPendingRequests?: number;\n\treadonly maxCostUsd?: number;\n\treadonly timeoutMs?: number;\n}\n\nexport interface EffectRun<TInput = unknown> {\n\treadonly kind: \"effect-run\";\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly goal: EffectRunGoal<TInput>;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly limits?: EffectRunLimits;\n\treadonly createdBy?: string;\n\treadonly createdAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunOptions<TInput = unknown> {\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly goal: EffectRunGoal<TInput>;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly limits?: EffectRunLimits;\n\treadonly createdBy?: string;\n\treadonly createdAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport function effectRun<TInput = unknown>(opts: EffectRunOptions<TInput>): EffectRun<TInput> {\n\treturn {\n\t\tkind: \"effect-run\",\n\t\teffectRunId: opts.effectRunId,\n\t\tagentRunId: opts.agentRunId,\n\t\tsubjectRefs: opts.subjectRefs,\n\t\tgoal: opts.goal,\n\t\tsourceRefs: opts.sourceRefs,\n\t\tpolicyRefs: opts.policyRefs,\n\t\tlimits: opts.limits,\n\t\tcreatedBy: opts.createdBy,\n\t\tcreatedAtMs: opts.createdAtMs,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nexport type AgentRequestKind = \"context\" | \"prompt\" | \"executor\";\n\nexport interface AgentRequestProposal<TPayload = unknown> {\n\treadonly kind: \"proposal\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly parentRequestId?: string;\n\treadonly sourceDecisionId?: string;\n\treadonly requestKind: AgentRequestKind;\n\treadonly required?: boolean;\n\treadonly subjectId?: string;\n\treadonly input?: AgentRequestInput<TPayload>;\n\treadonly payload?: TPayload;\n\treadonly reason?: string;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestAdmitted {\n\treadonly kind: \"admitted\";\n\treadonly proposalId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly admittedAtMs?: number;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestRejected {\n\treadonly kind: \"rejected\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly issue: DataIssue;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestDeferred {\n\treadonly kind: \"deferred\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly reason?: string;\n\treadonly untilRef?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestMerged {\n\treadonly kind: \"merged\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly targetRequestId: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestIssued<TPayload = unknown> {\n\treadonly kind: \"issued\";\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly proposalId?: string;\n\treadonly parentRequestId?: string;\n\treadonly requestKind: AgentRequestKind;\n\treadonly required: boolean;\n\treadonly input?: AgentRequestInput<TPayload>;\n\treadonly payload?: TPayload;\n\treadonly issuedAtMs?: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type AgentRequestStatus =\n\t| \"proposed\"\n\t| \"admitted\"\n\t| \"rejected\"\n\t| \"deferred\"\n\t| \"merged\"\n\t| \"issued\"\n\t| \"awaiting-context\"\n\t| \"awaiting-prompt\"\n\t| \"awaiting-route\"\n\t| \"awaiting-provider\"\n\t| \"in-flight\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"blocked\"\n\t| \"canceled\"\n\t| \"timeout\"\n\t| \"waived\"\n\t| \"retry-exhausted\";\n\nexport interface AgentRequestStatusChanged {\n\treadonly kind: \"status\";\n\treadonly requestId: string;\n\treadonly operationId?: string;\n\treadonly effectRunId: string;\n\treadonly status: AgentRequestStatus;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type AgentRequestFact<TPayload = unknown> =\n\t| AgentRequestProposal<TPayload>\n\t| AgentRequestAdmitted\n\t| AgentRequestRejected\n\t| AgentRequestDeferred\n\t| AgentRequestMerged\n\t| AgentRequestIssued<TPayload>\n\t| AgentRequestStatusChanged;\n\nexport interface AgentRequestViews {\n\treadonly requestsById: ReadonlyMap<string, AgentRequestIssued>;\n\treadonly requestsByEffectRun: ReadonlyMap<string, readonly string[]>;\n\treadonly statusByRequest: ReadonlyMap<string, AgentRequestStatusChanged>;\n\treadonly pending: readonly AgentRequestIssued[];\n\treadonly awaitingProvider: readonly AgentRequestIssued[];\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface AgentRequestLedgerBundle {\n\treadonly views: Node<AgentRequestViews>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport interface ExecutorProfile {\n\treadonly profileId: string;\n\treadonly executorId: string;\n\treadonly kind: \"llm\" | \"tool\" | \"human\" | \"agent\";\n\treadonly acceptedInputKinds?: readonly string[];\n\treadonly acceptedSchemaRefs?: readonly string[];\n\treadonly acceptedResultKinds?: readonly string[];\n\treadonly capabilities?: Record<string, unknown>;\n\treadonly limits?: Record<string, number>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutorRoute {\n\treadonly kind: \"executor-route\";\n\treadonly routeId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly inputId?: string;\n\treadonly inputKind?: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n\treadonly allowedParams?: Record<string, unknown>;\n\treadonly reason?: string;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ExecutorOutcomeStatus = \"result\" | \"failure\" | \"canceled\" | \"timeout\" | \"blocked\";\n\nexport interface ExecutorUsage {\n\treadonly inputTokens?: number;\n\treadonly outputTokens?: number;\n\treadonly cacheHitTokens?: number;\n\treadonly cacheMissTokens?: number;\n\treadonly cacheWriteTokens?: number;\n\treadonly cacheMode?: string;\n\treadonly costUsd?: number;\n\treadonly latencyMs?: number;\n}\n\nexport interface ExecutorOutcomeBase {\n\treadonly kind: ExecutorOutcomeStatus;\n\treadonly outcomeId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly routeId: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n\treadonly attempt: number;\n\treadonly inputId?: string;\n\treadonly inputKind?: string;\n\treadonly occurredAtMs?: number;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly usage?: ExecutorUsage;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentOutputEnvelope<T = unknown> {\n\treadonly kind: string;\n\treadonly value?: T;\n\treadonly refs?: readonly SourceRef[];\n\treadonly summary?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ExecutorOutcome<T = unknown> =\n\t| (ExecutorOutcomeBase & { readonly kind: \"result\"; readonly result: AgentOutputEnvelope<T> })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"failure\";\n\t\t\treadonly error: DataIssue;\n\t\t\treadonly retryable?: boolean;\n\t })\n\t| (ExecutorOutcomeBase & { readonly kind: \"canceled\"; readonly reason?: string })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"timeout\";\n\t\t\treadonly timeoutMs?: number;\n\t\t\treadonly retryable?: boolean;\n\t })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"blocked\";\n\t\t\treadonly needs: readonly AgentNeed[];\n\t });\n\n/**\n * Provider-neutral tool-call request input (D359). Concrete clients, secrets,\n * transports, and SDK handles stay in executor adapter bindings, not this fact.\n */\nexport interface ToolCallInput<TArguments = unknown> {\n\treadonly kind: \"tool-call\";\n\treadonly toolName: string;\n\treadonly operation?: string;\n\treadonly arguments?: TArguments;\n\treadonly argumentsRef?: string;\n\treadonly expectedOutput?: {\n\t\treadonly resultKind?: string;\n\t\treadonly schemaRef?: string;\n\t};\n\treadonly idempotency?: {\n\t\treadonly key?: string;\n\t\treadonly safeToRetry?: boolean;\n\t};\n\treadonly timeoutMs?: number;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Tool provider family label for optional Layer C adapters (D359). Builtin,\n * MCP, CLI, and Composio providers stay executor/tool recipes, not WorkItem\n * core or protocol semantics.\n */\nexport type ToolProviderKind = \"local-builtin\" | \"mcp\" | \"cli\" | \"composio\" | (string & {});\n\n/**\n * Graph-visible catalog entry for a tool exposed by an executor provider\n * (D359). Runtime clients and credentials remain private adapter state.\n */\nexport interface ToolProviderCatalogEntry {\n\treadonly kind: \"tool-catalog-entry\";\n\treadonly providerId: string;\n\treadonly toolName: string;\n\treadonly operation?: string;\n\treadonly inputKind: \"tool-call\";\n\treadonly profileId: string;\n\treadonly executorId: string;\n\treadonly resultKinds?: readonly string[];\n\treadonly schemaRefs?: readonly string[];\n\treadonly capabilities?: Record<string, unknown>;\n\treadonly limits?: Record<string, number>;\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Graph-visible tool provider catalog/status surface (D359). This is passive\n * DATA for routing/profile selection and UI inspection, not a provider runtime.\n */\nexport interface ToolProviderCatalog {\n\treadonly kind: \"tool-provider-catalog\";\n\treadonly providerId: string;\n\treadonly providerKind: ToolProviderKind;\n\treadonly profiles: readonly ExecutorProfile[];\n\treadonly tools: readonly ToolProviderCatalogEntry[];\n\treadonly status?: \"ready\" | \"unavailable\" | \"misconfigured\";\n\treadonly issues?: readonly DataIssue[];\n\treadonly audit?: readonly AgentRuntimeAuditRecord[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Options for producing a local builtin tool-provider catalog (D359). Limits and\n * capabilities are declarative policy hints; execution remains adapter-owned.\n */\nexport interface LocalBuiltinToolProviderCatalogOptions {\n\treadonly providerId?: string;\n\treadonly executorId?: string;\n\treadonly profileId?: string;\n\treadonly tools?: readonly Omit<\n\t\tToolProviderCatalogEntry,\n\t\t\"kind\" | \"providerId\" | \"inputKind\" | \"profileId\" | \"executorId\"\n\t>[];\n\treadonly limits?: Record<string, number>;\n\treadonly capabilities?: Record<string, unknown>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Audience selector for bounded ExecutorOutcome projections (D359).\n */\nexport type ExecutorOutcomeViewAudience = \"agent-observation\" | \"ui\" | \"diagnostic\" | \"audit\";\n\n/**\n * View policy for deriving bounded, audience-specific ExecutorOutcome summaries\n * (D359/D270/D293) without inlining large/raw provider material.\n */\nexport interface ExecutorOutcomeViewPolicy {\n\treadonly audience?: ExecutorOutcomeViewAudience;\n\treadonly maxSummaryChars?: number;\n\treadonly includeIssues?: boolean;\n\treadonly includeUsage?: boolean;\n\treadonly includeMetadata?: boolean;\n}\n\n/**\n * Bounded projection of ExecutorOutcome for agent, UI, diagnostic, or audit\n * consumers (D359). Large/raw material stays behind refs.\n */\nexport interface ExecutorOutcomeView {\n\treadonly kind: \"executor-outcome-view\";\n\treadonly viewId: string;\n\treadonly audience: ExecutorOutcomeViewAudience;\n\treadonly outcomeId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly routeId: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n\treadonly status: ExecutorOutcomeStatus;\n\treadonly summary: string;\n\treadonly summaryTruncated?: boolean;\n\treadonly summaryChars?: number;\n\treadonly summaryLimitChars?: number;\n\treadonly errorKind?: string;\n\treadonly retryable?: boolean;\n\treadonly nextActions?: readonly string[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly materialRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly usage?: ExecutorUsage;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Output bundle for ExecutorOutcome view projectors (D359).\n */\nexport interface ExecutorOutcomeViewBundle {\n\treadonly views: Node<ExecutorOutcomeView>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport interface ContextContribution {\n\treadonly kind: \"context-contribution\";\n\treadonly contributionId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly status: \"ready\" | \"pending\" | \"issue\";\n\treadonly frameId?: string;\n\treadonly issues?: readonly DataIssue[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface PromptBundle {\n\treadonly kind: \"prompt-bundle\";\n\treadonly promptId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly status: \"ready\" | \"partial\" | \"issue\";\n\treadonly sourceFrameIds?: readonly string[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestSatisfactionBundle {\n\treadonly status: Node<AgentRequestStatusChanged>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport type AgentDecisionKind = \"continue\" | \"final\" | \"blocked\";\n\nexport interface AgentNeed {\n\treadonly kind: string;\n\treadonly message?: string;\n\treadonly refs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentDecisionBase {\n\treadonly kind: AgentDecisionKind;\n\treadonly decisionId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId: string;\n\treadonly source: {\n\t\treadonly requestId: string;\n\t\treadonly operationId: string;\n\t\treadonly outcomeId: string;\n\t};\n\treadonly reason?: string;\n\treadonly confidence?: number;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentDecisionContinue extends AgentDecisionBase {\n\treadonly kind: \"continue\";\n\treadonly next: readonly AgentRequestProposal[];\n}\n\nexport interface AgentDecisionFinal extends AgentDecisionBase {\n\treadonly kind: \"final\";\n\treadonly output: AgentOutputEnvelope;\n\treadonly summary?: string;\n}\n\nexport interface AgentDecisionBlocked extends AgentDecisionBase {\n\treadonly kind: \"blocked\";\n\treadonly needs: readonly AgentNeed[];\n}\n\nexport type AgentDecision = AgentDecisionContinue | AgentDecisionFinal | AgentDecisionBlocked;\n\nexport interface StructuredAgentDecisionEnvelope {\n\treadonly kind: \"agent-decision\";\n\treadonly decision: AgentDecision;\n\treadonly schemaRef: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n}\n\nexport interface StructuredAgentDecisionInterpreterBundle {\n\treadonly decisions: Node<AgentDecision>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport type EffectRunResultStatus =\n\t| \"completed\"\n\t| \"failed\"\n\t| \"blocked\"\n\t| \"canceled\"\n\t| \"timeout\"\n\t| \"waived\";\n\nexport interface EffectRunResultBase {\n\treadonly kind: \"effect-run-result\";\n\treadonly resultId: string;\n\treadonly status: EffectRunResultStatus;\n\treadonly effectRunId: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly operationId?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly auditRefs?: readonly string[];\n\treadonly completedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type EffectRunResult =\n\t| (EffectRunResultBase & { readonly status: \"completed\"; readonly output: AgentOutputEnvelope })\n\t| (EffectRunResultBase & { readonly status: \"failed\"; readonly error: DataIssue })\n\t| (EffectRunResultBase & { readonly status: \"blocked\"; readonly needs: readonly AgentNeed[] })\n\t| (EffectRunResultBase & { readonly status: \"canceled\"; readonly reason?: string })\n\t| (EffectRunResultBase & { readonly status: \"timeout\"; readonly timeoutMs?: number })\n\t| (EffectRunResultBase & { readonly status: \"waived\"; readonly reason?: string });\n\nexport interface EffectRunCompletionBundle {\n\treadonly results: Node<EffectRunResult>;\n\treadonly status: Node<EffectRunCompletionStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport interface EffectRunCompletionStatus {\n\treadonly effectRunId: string;\n\treadonly state:\n\t\t| \"pending\"\n\t\t| \"completed\"\n\t\t| \"failed\"\n\t\t| \"blocked\"\n\t\t| \"canceled\"\n\t\t| \"timeout\"\n\t\t| \"waived\";\n\treadonly requiredPending: readonly string[];\n\treadonly requiredTerminal: readonly string[];\n\treadonly sourceRefs?: readonly SourceRef[];\n}\n\nexport interface AgentRuntimeAuditRecord {\n\treadonly id: string;\n\treadonly kind: string;\n\treadonly subjectId?: string;\n\treadonly message?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly issueCode?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\ninterface RequestSatisfactionState {\n\trequests: Map<string, AgentRequestIssued>;\n\tprofiles: Map<string, ExecutorProfile>;\n\troutes: Map<string, ExecutorRoute>;\n\toutcomes: Map<string, ExecutorOutcome>;\n\tcontexts: Map<string, ContextContribution>;\n\tprompts: Map<string, PromptBundle>;\n\tcompatibleRoutesByRouteId: Map<string, ExecutorRoute>;\n\tterminalRequests: Set<string>;\n\tacceptedTerminalFactIds: Set<string>;\n\tissueKeys: Set<string>;\n\tstatusKeys: Set<string>;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\nexport function agentRequestProposalFromDecision(\n\tdecision: AgentDecisionContinue,\n\tproposal: Omit<AgentRequestProposal, \"kind\" | \"effectRunId\" | \"agentRunId\" | \"sourceDecisionId\">,\n): AgentRequestProposal {\n\treturn {\n\t\tkind: \"proposal\",\n\t\t...proposal,\n\t\teffectRunId: decision.effectRunId,\n\t\tagentRunId: decision.agentRunId,\n\t\tsourceDecisionId: decision.decisionId,\n\t\tevidenceRefs: proposal.evidenceRefs ?? decision.evidenceRefs,\n\t};\n}\n\nexport function admitAgentRequestProposal(\n\tproposal: AgentRequestProposal,\n\topts: {\n\t\treadonly requestId: string;\n\t\treadonly operationId: string;\n\t\treadonly admittedAtMs?: number;\n\t\treadonly reason?: string;\n\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\treadonly metadata?: Record<string, unknown>;\n\t},\n): AgentRequestAdmitted {\n\treturn {\n\t\tkind: \"admitted\",\n\t\tproposalId: proposal.proposalId,\n\t\trequestId: opts.requestId,\n\t\toperationId: opts.operationId,\n\t\teffectRunId: proposal.effectRunId,\n\t\tagentRunId: proposal.agentRunId,\n\t\tadmittedAtMs: opts.admittedAtMs,\n\t\treason: opts.reason,\n\t\tsourceRefs: opts.sourceRefs,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nexport function issueAgentRequest(\n\tproposal: AgentRequestProposal,\n\tadmission: AgentRequestAdmitted,\n\topts: { readonly issuedAtMs?: number; readonly sourceRefs?: readonly SourceRef[] } = {},\n): AgentRequestIssued {\n\treturn {\n\t\tkind: \"issued\",\n\t\trequestId: admission.requestId,\n\t\toperationId: admission.operationId,\n\t\teffectRunId: admission.effectRunId,\n\t\tagentRunId: admission.agentRunId,\n\t\tproposalId: proposal.proposalId,\n\t\tparentRequestId: proposal.parentRequestId,\n\t\trequestKind: proposal.requestKind,\n\t\trequired: proposal.required ?? true,\n\t\tinput: proposal.input,\n\t\tpayload: proposal.payload,\n\t\tissuedAtMs: opts.issuedAtMs,\n\t\tsourceRefs: opts.sourceRefs ?? admission.sourceRefs,\n\t\tmetadata: proposal.metadata,\n\t};\n}\n\nexport function agentRequestLedgerViews(\n\tgraph: Graph,\n\tfacts: Node<AgentRequestFact>,\n\topts: { readonly name?: string } = {},\n): AgentRequestLedgerBundle {\n\tconst name = opts.name ?? \"agentRequests\";\n\tconst views = graph.node<AgentRequestViews>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tconst prev = ctx.state.get<AgentRequestViewsState>() ?? emptyAgentRequestViewsState();\n\t\t\tconst next = cloneAgentRequestViewsState(prev);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\treduceAgentRequestViews(next, fact);\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", freezeAgentRequestViews(next)]]);\n\t\t},\n\t\t{ name: `${name}/views`, factory: \"agentRequestLedgerViews\" },\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"rejected\") ctx.down([[\"DATA\", fact.issue]]);\n\t\t\t\tif (fact.kind === \"status\") {\n\t\t\t\t\tfor (const issue of fact.issues ?? []) ctx.down([[\"DATA\", issue]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/issues`, factory: \"agentRequestLedgerIssues\" },\n\t);\n\tconst audit = graph.node<AgentRuntimeAuditRecord>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tlet seq = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tseq += 1;\n\t\t\t\tconst fact = raw as AgentRequestFact;\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\tid: `${name}:ledger:${seq}`,\n\t\t\t\t\t\t\tkind: `agent-request-${fact.kind}`,\n\t\t\t\t\t\t\tsubjectId: \"requestId\" in fact ? fact.requestId : fact.proposalId,\n\t\t\t\t\t\t} satisfies AgentRuntimeAuditRecord,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tctx.state.set(seq);\n\t\t},\n\t\t{ name: `${name}/audit`, factory: \"agentRequestLedgerAudit\" },\n\t);\n\treturn { views, issues, audit };\n}\n\nexport function requestSatisfactionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly requestFacts: Node<AgentRequestFact>;\n\t\treadonly executorProfiles?: readonly Node<ExecutorProfile>[];\n\t\treadonly executorRoutes?: readonly Node<ExecutorRoute>[];\n\t\treadonly executorOutcomes?: readonly Node<ExecutorOutcome>[];\n\t\treadonly contextContributions?: readonly Node<ContextContribution>[];\n\t\treadonly promptBundles?: readonly Node<PromptBundle>[];\n\t},\n): AgentRequestSatisfactionBundle {\n\tconst name = opts.name ?? \"requestSatisfaction\";\n\tconst profileDeps = opts.executorProfiles ?? [];\n\tconst routeDeps = opts.executorRoutes ?? [];\n\tconst outcomeDeps = opts.executorOutcomes ?? [];\n\tconst contextDeps = opts.contextContributions ?? [];\n\tconst promptDeps = opts.promptBundles ?? [];\n\tconst deps = [\n\t\topts.requestFacts,\n\t\t...profileDeps,\n\t\t...routeDeps,\n\t\t...outcomeDeps,\n\t\t...contextDeps,\n\t\t...promptDeps,\n\t];\n\tconst profileStart = 1;\n\tconst routeStart = profileStart + profileDeps.length;\n\tconst outcomeStart = routeStart + routeDeps.length;\n\tconst contextStart = outcomeStart + outcomeDeps.length;\n\tconst promptStart = contextStart + contextDeps.length;\n\tconst runtime = graph.node<AgentRequestSatisfactionFact>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<RequestSatisfactionState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\tprofiles: new Map<string, ExecutorProfile>(),\n\t\t\t\troutes: new Map<string, ExecutorRoute>(),\n\t\t\t\toutcomes: new Map<string, ExecutorOutcome>(),\n\t\t\t\tcontexts: new Map<string, ContextContribution>(),\n\t\t\t\tprompts: new Map<string, PromptBundle>(),\n\t\t\t\tcompatibleRoutesByRouteId: new Map<string, ExecutorRoute>(),\n\t\t\t\tterminalRequests: new Set<string>(),\n\t\t\t\tacceptedTerminalFactIds: new Set<string>(),\n\t\t\t\tissueKeys: new Set<string>(),\n\t\t\t\tstatusKeys: new Set<string>(),\n\t\t\t\tissueSeq: 0,\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tif ((fact as AgentRequestFact).kind === \"issued\") {\n\t\t\t\t\tconst request = fact as AgentRequestIssued;\n\t\t\t\t\tstate.requests.set(request.requestId, request);\n\t\t\t\t\temitStatus(ctx, state, request, initialRequestStatus(request), [\n\t\t\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, profileStart, profileDeps.length, (raw) => {\n\t\t\t\tconst profile = raw as ExecutorProfile;\n\t\t\t\tstate.profiles.set(profile.profileId, profile);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, routeStart, routeDeps.length, (raw) => {\n\t\t\t\tconst route = raw as ExecutorRoute;\n\t\t\t\tstate.routes.set(route.routeId, route);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, outcomeStart, outcomeDeps.length, (raw) => {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tstate.outcomes.set(outcome.outcomeId, outcome);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, contextStart, contextDeps.length, (raw) => {\n\t\t\t\tconst contribution = raw as ContextContribution;\n\t\t\t\tstate.contexts.set(contribution.contributionId, contribution);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, promptStart, promptDeps.length, (raw) => {\n\t\t\t\tconst prompt = raw as PromptBundle;\n\t\t\t\tstate.prompts.set(prompt.promptId, prompt);\n\t\t\t});\n\t\t\tevaluateRequestSatisfaction(ctx, state);\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"requestSatisfactionProjector\" },\n\t);\n\tconst status = graph.node<AgentRequestStatusChanged>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"status\") ctx.down([[\"DATA\", typed.status]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"requestSatisfactionStatus\" },\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"issue\") ctx.down([[\"DATA\", typed.issue]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/issues`, factory: \"requestSatisfactionIssues\" },\n\t);\n\tconst audit = graph.node<AgentRuntimeAuditRecord>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"audit\") ctx.down([[\"DATA\", typed.audit]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/audit`, factory: \"requestSatisfactionAudit\" },\n\t);\n\treturn { status, issues, audit };\n}\n\nexport function localBuiltinToolProviderCatalog(\n\topts: LocalBuiltinToolProviderCatalogOptions = {},\n): ToolProviderCatalog {\n\tconst providerId = opts.providerId ?? \"local-builtin\";\n\tconst executorId = opts.executorId ?? `${providerId}:tool-executor`;\n\tconst profileId = opts.profileId ?? `${providerId}:tool-profile`;\n\tconst tools =\n\t\topts.tools ??\n\t\t([\n\t\t\t{ toolName: \"document/read-doc\", operation: \"read\" },\n\t\t\t{ toolName: \"file.read\", operation: \"read\" },\n\t\t\t{ toolName: \"file.edit/apply-patch\", operation: \"edit\" },\n\t\t\t{ toolName: \"bash.run\", operation: \"run\" },\n\t\t\t{ toolName: \"url.fetch\", operation: \"fetch\" },\n\t\t\t{ toolName: \"date.now\", operation: \"read\" },\n\t\t\t{ toolName: \"weather.fetch\", operation: \"fetch\" },\n\t\t\t{ toolName: \"calculator/eval\", operation: \"eval\" },\n\t\t] satisfies readonly Omit<\n\t\t\tToolProviderCatalogEntry,\n\t\t\t\"kind\" | \"providerId\" | \"inputKind\" | \"profileId\" | \"executorId\"\n\t\t>[]);\n\tconst toolEntries = tools.map((tool) =>\n\t\tObject.freeze({\n\t\t\tkind: \"tool-catalog-entry\",\n\t\t\tproviderId,\n\t\t\tinputKind: \"tool-call\",\n\t\t\tprofileId,\n\t\t\texecutorId,\n\t\t\t...tool,\n\t\t} satisfies ToolProviderCatalogEntry),\n\t);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-catalog\",\n\t\tproviderId,\n\t\tproviderKind: \"local-builtin\",\n\t\tstatus: \"ready\",\n\t\tprofiles: Object.freeze([\n\t\t\tObject.freeze({\n\t\t\t\tprofileId,\n\t\t\t\texecutorId,\n\t\t\t\tkind: \"tool\",\n\t\t\t\tacceptedInputKinds: Object.freeze([\"tool-call\"]),\n\t\t\t\tacceptedResultKinds: Object.freeze(\n\t\t\t\t\tArray.from(new Set(toolEntries.flatMap((tool) => tool.resultKinds ?? []))),\n\t\t\t\t),\n\t\t\t\tcapabilities: Object.freeze({\n\t\t\t\t\ttoolNames: Object.freeze(toolEntries.map((tool) => tool.toolName)),\n\t\t\t\t\t...(opts.capabilities ?? {}),\n\t\t\t\t}),\n\t\t\t\tlimits: opts.limits,\n\t\t\t\tmetadata: opts.metadata,\n\t\t\t} satisfies ExecutorProfile),\n\t\t]),\n\t\ttools: Object.freeze(toolEntries),\n\t\tmetadata: opts.metadata,\n\t});\n}\n\nexport function executorOutcomeViewProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly outcomes: Node<ExecutorOutcome>;\n\t\treadonly policy?: ExecutorOutcomeViewPolicy;\n\t},\n): ExecutorOutcomeViewBundle {\n\tconst name = opts.name ?? \"executorOutcomeViews\";\n\tconst policy = {\n\t\taudience: opts.policy?.audience ?? \"agent-observation\",\n\t\tmaxSummaryChars: opts.policy?.maxSummaryChars ?? 512,\n\t\tincludeIssues: opts.policy?.includeIssues ?? true,\n\t\tincludeUsage: opts.policy?.includeUsage ?? false,\n\t\tincludeMetadata: opts.policy?.includeMetadata ?? false,\n\t} satisfies Required<ExecutorOutcomeViewPolicy>;\n\tconst runtime = graph.node<ExecutorOutcomeViewFact>(\n\t\t[opts.outcomes],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tconst projection = executorOutcomeViewProjectionFromOutcome(outcome, policy);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"view\", view: projection.view } satisfies ExecutorOutcomeViewFact],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${outcome.outcomeId}:outcome-view:${policy.audience}`,\n\t\t\t\t\t\t\t\tkind: \"executor-outcome-view-projected\",\n\t\t\t\t\t\t\t\tsubjectId: outcome.requestId,\n\t\t\t\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t\t\t\t\tmetadata: { audience: policy.audience, status: outcome.kind },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ExecutorOutcomeViewFact,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\tfor (const issue of projection.issues) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"issue\", issue } satisfies ExecutorOutcomeViewFact]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"executorOutcomeViewProjector\" },\n\t);\n\treturn {\n\t\tviews: projectRuntimeFact(graph, runtime, `${name}/views`, \"executorOutcomeViews\", (fact) =>\n\t\t\tfact.kind === \"view\" ? fact.view : undefined,\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"executorOutcomeViewIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"executorOutcomeViewAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport function structuredAgentDecisionInterpreter(\n\tgraph: Graph,\n\toutcomes: Node<ExecutorOutcome>,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly schemaRef?: string;\n\t\treadonly requestFacts?: readonly Node<AgentRequestFact>[];\n\t} = {},\n): StructuredAgentDecisionInterpreterBundle {\n\tconst name = opts.name ?? \"structuredAgentDecisionInterpreter\";\n\tconst requestFacts = opts.requestFacts ?? [];\n\tconst runtime = graph.node<StructuredAgentDecisionInterpreterFact>(\n\t\t[outcomes, ...requestFacts],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<StructuredInterpreterState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\tissueSeq: 0,\n\t\t\t};\n\t\t\tforEachDepBatch(ctx, 1, requestFacts.length, (raw) => {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\") state.requests.set(fact.requestId, fact);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tif (outcome.kind !== \"result\") {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"non-result-outcome\",\n\t\t\t\t\t\t\"Only result outcomes can carry AgentDecision envelopes\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst value = outcome.result.value;\n\t\t\t\tif (!isRecord(value)) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"malformed-agent-decision\",\n\t\t\t\t\t\t\"ExecutorOutcome result must carry a structured agent-decision envelope\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst envelope = value as Partial<StructuredAgentDecisionEnvelope>;\n\t\t\t\tif (envelope.kind !== \"agent-decision\" || !isRecord(envelope.decision)) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"malformed-agent-decision\",\n\t\t\t\t\t\t\"Structured agent-decision envelope is missing kind or decision\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (typeof envelope.schemaRef !== \"string\" || envelope.schemaRef.length === 0) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"missing-agent-decision-schema\",\n\t\t\t\t\t\t\"Structured agent-decision envelope must carry schemaRef evidence\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (opts.schemaRef !== undefined && envelope.schemaRef !== opts.schemaRef) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"agent-decision-schema-mismatch\",\n\t\t\t\t\t\t\"Structured agent-decision envelope schemaRef did not match\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst decision = validateAgentDecision(envelope.decision, outcome);\n\t\t\t\tif (typeof decision === \"string\") {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(ctx, state.issueSeq, outcome, \"malformed-agent-decision\", decision);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst request = state.requests.get(decision.source.requestId);\n\t\t\t\tif (request === undefined) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"missing-agent-decision-request\",\n\t\t\t\t\t\t\"AgentDecision source request must be present in the request ledger\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\trequest.effectRunId !== decision.effectRunId ||\n\t\t\t\t\trequest.operationId !== decision.source.operationId\n\t\t\t\t) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"stale-agent-decision-source\",\n\t\t\t\t\t\t\"AgentDecision source request/effectRun/operation identity did not match the request ledger\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"decision\", decision } satisfies StructuredAgentDecisionInterpreterFact],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${outcome.outcomeId}:agent-decision-interpreted`,\n\t\t\t\t\t\t\t\tkind: \"agent-decision-interpreted\",\n\t\t\t\t\t\t\t\tsubjectId: decision.effectRunId,\n\t\t\t\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies StructuredAgentDecisionInterpreterFact,\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},\n\t\t{ name: `${name}/runtime`, factory: \"structuredAgentDecisionInterpreter\" },\n\t);\n\treturn {\n\t\tdecisions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/decisions`,\n\t\t\t\"structuredAgentDecisions\",\n\t\t\t(fact) => (fact.kind === \"decision\" ? fact.decision : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"structuredAgentDecisionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"structuredAgentDecisionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport function effectRunCompletionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly effectRuns: Node<EffectRun>;\n\t\treadonly decisions?: readonly Node<AgentDecision>[];\n\t\treadonly requestStatuses?: readonly Node<AgentRequestStatusChanged>[];\n\t\treadonly requestFacts?: readonly Node<AgentRequestFact>[];\n\t\treadonly resultCandidates?: readonly Node<EffectRunResult>[];\n\t\treadonly now?: () => number;\n\t},\n): EffectRunCompletionBundle {\n\tconst name = opts.name ?? \"effectRunCompletion\";\n\tconst decisions = opts.decisions ?? [];\n\tconst requestStatuses = opts.requestStatuses ?? [];\n\tconst requestFacts = opts.requestFacts ?? [];\n\tconst resultCandidates = opts.resultCandidates ?? [];\n\tconst deps = [\n\t\topts.effectRuns,\n\t\t...decisions,\n\t\t...requestStatuses,\n\t\t...requestFacts,\n\t\t...resultCandidates,\n\t];\n\tconst decisionStart = 1;\n\tconst requestStatusStart = decisionStart + decisions.length;\n\tconst requestFactStart = requestStatusStart + requestStatuses.length;\n\tconst resultCandidateStart = requestFactStart + requestFacts.length;\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<EffectRunCompletionFact>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<EffectRunCompletionState>() ?? emptyEffectRunCompletionState();\n\t\t\tconst touchedEffectRunIds = new Set<string>();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst run = raw as EffectRun;\n\t\t\t\tstate.runs.set(run.effectRunId, run);\n\t\t\t\ttouchedEffectRunIds.add(run.effectRunId);\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, requestFactStart, requestFacts.length, (raw) => {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\") {\n\t\t\t\t\tstate.requests.set(fact.requestId, fact);\n\t\t\t\t\ttouchedEffectRunIds.add(fact.effectRunId);\n\t\t\t\t\tconst existingStatus = state.statusByRequest.get(fact.requestId);\n\t\t\t\t\tif (existingStatus !== undefined && !statusMatchesRequest(existingStatus, fact)) {\n\t\t\t\t\t\temitEffectRunIssue(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t\"stale-request-status\",\n\t\t\t\t\t\t\t`AgentRequest status for '${fact.requestId}' did not match its issued effectRun/operation identity`,\n\t\t\t\t\t\t\tfact.effectRunId,\n\t\t\t\t\t\t\t[ref(\"agent-request\", fact.requestId)],\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst result = state.resultsByEffectRun.get(fact.effectRunId);\n\t\t\t\t\tif (result !== undefined && fact.required) {\n\t\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\t\t\"late-required-request-after-effect-run-result\",\n\t\t\t\t\t\t\t`Required request '${fact.requestId}' arrived after EffectRun '${fact.effectRunId}' already had a terminal result`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsubjectId: fact.effectRunId,\n\t\t\t\t\t\t\t\trefs: [\n\t\t\t\t\t\t\t\t\tref(\"agent-request\", fact.requestId),\n\t\t\t\t\t\t\t\t\tref(\"effect-run-result\", result.resultId),\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\tctx.down([\n\t\t\t\t\t\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\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: \"audit\",\n\t\t\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\t\t\tid: `${fact.effectRunId}:late-required-request:${state.issueSeq}`,\n\t\t\t\t\t\t\t\t\t\tkind: \"late-required-request-after-effect-run-result\",\n\t\t\t\t\t\t\t\t\t\tsubjectId: fact.effectRunId,\n\t\t\t\t\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t\t\t\t\t\tsourceRefs: [\n\t\t\t\t\t\t\t\t\t\t\tref(\"agent-request\", fact.requestId),\n\t\t\t\t\t\t\t\t\t\t\tref(\"effect-run-result\", result.resultId),\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t} satisfies EffectRunCompletionFact,\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 (fact.kind === \"status\") {\n\t\t\t\t\tacceptRequestStatus(ctx, state, fact);\n\t\t\t\t\ttouchedEffectRunIds.add(fact.effectRunId);\n\t\t\t\t}\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, requestStatusStart, requestStatuses.length, (raw) => {\n\t\t\t\tconst status = raw as AgentRequestStatusChanged;\n\t\t\t\tacceptRequestStatus(ctx, state, status);\n\t\t\t\ttouchedEffectRunIds.add(status.effectRunId);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, resultCandidateStart, resultCandidates.length, (raw) => {\n\t\t\t\tacceptEffectRunResultCandidate(ctx, state, raw as EffectRunResult);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, decisionStart, decisions.length, (raw) => {\n\t\t\t\tconst decision = raw as AgentDecision;\n\t\t\t\tstate.decisions.set(decision.decisionId, decision);\n\t\t\t\ttouchedEffectRunIds.add(decision.effectRunId);\n\t\t\t});\n\t\t\tfor (const decision of state.decisions.values()) {\n\t\t\t\tif (state.resultsByEffectRun.has(decision.effectRunId)) continue;\n\t\t\t\tconst candidate = candidateFromDecision(decision, state, now());\n\t\t\t\tif (candidate === undefined) continue;\n\t\t\t\tacceptEffectRunResultCandidate(ctx, state, candidate);\n\t\t\t}\n\t\t\tfor (const effectRunId of touchedEffectRunIds) {\n\t\t\t\tif (!state.resultsByEffectRun.has(effectRunId)) {\n\t\t\t\t\temitEffectRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\teffectRunId,\n\t\t\t\t\t\t\"pending\",\n\t\t\t\t\t\trequiredPendingRequests(effectRunId, state),\n\t\t\t\t\t\trequiredTerminalRequests(effectRunId, state),\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},\n\t\t{ name: `${name}/runtime`, factory: \"effectRunCompletionProjector\" },\n\t);\n\treturn {\n\t\tresults: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/results`,\n\t\t\t\"effectRunCompletionResults\",\n\t\t\t(fact) => (fact.kind === \"result\" ? fact.result : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"effectRunCompletionStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"effectRunCompletionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"effectRunCompletionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport function fakeExecutorResult<T>(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly result: AgentOutputEnvelope<T> },\n): ExecutorOutcome<T> {\n\treturn { kind: \"result\", ...opts };\n}\n\nexport function fakeExecutorFailure(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & {\n\t\treadonly error: DataIssue;\n\t\treadonly retryable?: boolean;\n\t},\n): ExecutorOutcome {\n\treturn { kind: \"failure\", ...opts };\n}\n\nexport function fakeExecutorBlocked(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly needs: readonly AgentNeed[] },\n): ExecutorOutcome {\n\treturn { kind: \"blocked\", ...opts };\n}\n\nexport function fakeExecutorTimeout(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & {\n\t\treadonly timeoutMs?: number;\n\t\treadonly retryable?: boolean;\n\t},\n): ExecutorOutcome {\n\treturn { kind: \"timeout\", ...opts };\n}\n\nexport function fakeExecutorCanceled(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly reason?: string },\n): ExecutorOutcome {\n\treturn { kind: \"canceled\", ...opts };\n}\n\ntype AgentRequestSatisfactionFact =\n\t| { readonly kind: \"status\"; readonly status: AgentRequestStatusChanged }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ntype ExecutorOutcomeViewFact =\n\t| { readonly kind: \"view\"; readonly view: ExecutorOutcomeView }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ninterface ExecutorOutcomeViewProjection {\n\treadonly view: ExecutorOutcomeView;\n\treadonly issues: readonly DataIssue[];\n}\n\ninterface ExecutorOutcomeSummaryProjection {\n\treadonly summary: string;\n\treadonly truncated: boolean;\n\treadonly originalChars: number;\n\treadonly limitChars: number;\n}\n\ntype StructuredAgentDecisionInterpreterFact =\n\t| { readonly kind: \"decision\"; readonly decision: AgentDecision }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ntype EffectRunCompletionFact =\n\t| { readonly kind: \"result\"; readonly result: EffectRunResult }\n\t| { readonly kind: \"status\"; readonly status: EffectRunCompletionStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ninterface AgentRequestViewsState {\n\trequestsById: Map<string, AgentRequestIssued>;\n\trequestsByEffectRun: Map<string, string[]>;\n\tstatusByRequest: Map<string, AgentRequestStatusChanged>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n\tauditSeq: number;\n}\n\ninterface EffectRunCompletionState {\n\truns: Map<string, EffectRun>;\n\trequests: Map<string, AgentRequestIssued>;\n\tstatusByRequest: Map<string, AgentRequestStatusChanged>;\n\tdecisions: Map<string, AgentDecision>;\n\tresultsByEffectRun: Map<string, EffectRunResult>;\n\tissueSeq: number;\n}\n\ninterface StructuredInterpreterState {\n\trequests: Map<string, AgentRequestIssued>;\n\tissueSeq: number;\n}\n\nfunction initialRequestStatus(request: AgentRequestIssued): AgentRequestStatus {\n\tif (request.requestKind === \"context\") return \"awaiting-context\";\n\tif (request.requestKind === \"prompt\") return \"awaiting-prompt\";\n\treturn \"awaiting-route\";\n}\n\nfunction evaluateRequestSatisfaction(ctx: Ctx, state: RequestSatisfactionState): void {\n\tfor (const route of state.routes.values()) handleRoute(ctx, state, route);\n\tfor (const contribution of state.contexts.values())\n\t\thandleContextContribution(ctx, state, contribution);\n\tfor (const prompt of state.prompts.values()) handlePromptBundle(ctx, state, prompt);\n\tfor (const outcome of state.outcomes.values()) handleExecutorOutcome(ctx, state, outcome);\n}\n\nfunction handleRoute(ctx: Ctx, state: RequestSatisfactionState, route: ExecutorRoute): void {\n\tconst request = state.requests.get(route.requestId);\n\tif (request === undefined) {\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (state.compatibleRoutesByRouteId.get(route.routeId)?.requestId !== request.requestId) {\n\t\t\temitIssueOnce(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`late-route:${route.routeId}`,\n\t\t\t\t\"late-route-after-terminal\",\n\t\t\t\t`ExecutorRoute '${route.routeId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\t\trequest.requestId,\n\t\t\t\t[ref(\"executor-route\", route.routeId), ref(\"agent-request\", request.requestId)],\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\tif (request.operationId !== route.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-route:${route.routeId}`,\n\t\t\t\"stale-route-operation\",\n\t\t\t`ExecutorRoute '${route.routeId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-route\", route.routeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst profile = state.profiles.get(route.profileId);\n\tif (profile === undefined) {\n\t\treturn;\n\t}\n\tconst compatibilityIssue = routeCompatibilityIssue(request, route, profile);\n\tif (compatibilityIssue !== undefined) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`route-incompatible:${route.routeId}:${compatibilityIssue}`,\n\t\t\tcompatibilityIssue,\n\t\t\t`ExecutorRoute '${route.routeId}' is incompatible with request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\tref(\"executor-profile\", profile.profileId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tstate.compatibleRoutesByRouteId.set(route.routeId, route);\n\temitStatusOnce(\n\t\tctx,\n\t\tstate,\n\t\t`route:${route.routeId}:awaiting-provider`,\n\t\trequest,\n\t\t\"awaiting-provider\",\n\t\t[\n\t\t\tref(\"executor-route\", route.routeId),\n\t\t\tref(\"executor-profile\", profile.profileId),\n\t\t\tref(\"agent-request\", request.requestId),\n\t\t],\n\t);\n}\n\nfunction handleExecutorOutcome(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\toutcome: ExecutorOutcome,\n): void {\n\tconst request = state.requests.get(outcome.requestId);\n\tif (request === undefined) {\n\t\treturn;\n\t}\n\tif (request.operationId !== outcome.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-outcome:${outcome.outcomeId}`,\n\t\t\t\"stale-outcome-operation\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst route = state.compatibleRoutesByRouteId.get(outcome.routeId);\n\tif (route === undefined || route.requestId !== request.requestId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-route:${outcome.outcomeId}`,\n\t\t\t\"missing-compatible-route\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' has no compatible route for request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst outcomeIssue = outcomeCompatibilityIssue(request, route, outcome);\n\tif (outcomeIssue !== undefined) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`outcome-incompatible:${outcome.outcomeId}:${outcomeIssue}`,\n\t\t\toutcomeIssue,\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' is incompatible with route '${route.routeId}' for request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (state.acceptedTerminalFactIds.has(`outcome:${outcome.outcomeId}`)) return;\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-outcome:${outcome.outcomeId}`,\n\t\t\t\"duplicate-terminal-outcome\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tstate.terminalRequests.add(request.requestId);\n\tstate.acceptedTerminalFactIds.add(`outcome:${outcome.outcomeId}`);\n\tconst status = outcomeStatus(outcome);\n\temitStatus(ctx, state, request, status, [\n\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\tref(\"executor-route\", route.routeId),\n\t\tref(\"agent-request\", request.requestId),\n\t]);\n}\n\nfunction handleContextContribution(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tcontribution: ContextContribution,\n): void {\n\tconst request = state.requests.get(contribution.requestId);\n\tif (request === undefined) return;\n\tif (request.operationId !== contribution.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-context:${contribution.contributionId}`,\n\t\t\t\"stale-context-operation\",\n\t\t\t`ContextContribution '${contribution.contributionId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (request.requestKind !== \"context\") {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`wrong-context-kind:${contribution.contributionId}`,\n\t\t\t\"wrong-kind-context-satisfaction\",\n\t\t\t`ContextContribution '${contribution.contributionId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (\n\t\t\tstate.acceptedTerminalFactIds.has(`context:${contribution.contributionId}`) ||\n\t\t\tstate.statusKeys.has(`context:${contribution.contributionId}:awaiting-context`)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-context:${contribution.contributionId}`,\n\t\t\t\"duplicate-terminal-context\",\n\t\t\t`ContextContribution '${contribution.contributionId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"context-contribution\", contribution.contributionId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tif (contribution.status === \"pending\")\n\t\temitStatusOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`context:${contribution.contributionId}:awaiting-context`,\n\t\t\trequest,\n\t\t\t\"awaiting-context\",\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\telse {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`context:${contribution.contributionId}`);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\trequest,\n\t\t\tcontribution.status === \"ready\" ? \"completed\" : \"failed\",\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t\tcontribution.issues,\n\t\t);\n\t}\n}\n\nfunction handlePromptBundle(ctx: Ctx, state: RequestSatisfactionState, prompt: PromptBundle): void {\n\tconst request = state.requests.get(prompt.requestId);\n\tif (request === undefined) return;\n\tif (request.operationId !== prompt.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-prompt:${prompt.promptId}`,\n\t\t\t\"stale-prompt-operation\",\n\t\t\t`PromptBundle '${prompt.promptId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (request.requestKind !== \"prompt\") {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`wrong-prompt-kind:${prompt.promptId}`,\n\t\t\t\"wrong-kind-prompt-satisfaction\",\n\t\t\t`PromptBundle '${prompt.promptId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (\n\t\t\tstate.acceptedTerminalFactIds.has(`prompt:${prompt.promptId}`) ||\n\t\t\tstate.statusKeys.has(`prompt:${prompt.promptId}:awaiting-prompt`)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-prompt:${prompt.promptId}`,\n\t\t\t\"duplicate-terminal-prompt\",\n\t\t\t`PromptBundle '${prompt.promptId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (prompt.status === \"ready\") {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);\n\t\temitStatus(ctx, state, request, \"completed\", [ref(\"prompt-bundle\", prompt.promptId)]);\n\t} else if (prompt.status === \"issue\") {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\trequest,\n\t\t\t\"failed\",\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t\tprompt.issues,\n\t\t);\n\t} else {\n\t\temitStatusOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`prompt:${prompt.promptId}:awaiting-prompt`,\n\t\t\trequest,\n\t\t\t\"awaiting-prompt\",\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t\tprompt.issues,\n\t\t);\n\t}\n}\n\nfunction routeCompatibilityIssue(\n\trequest: AgentRequestIssued,\n\troute: ExecutorRoute,\n\tprofile: ExecutorProfile,\n): string | undefined {\n\tif (request.requestKind !== \"executor\") return \"route-for-non-executor-request\";\n\tif (route.executorId !== profile.executorId) return \"route-profile-executor-mismatch\";\n\tif (\n\t\trequest.input?.inputId !== undefined &&\n\t\troute.inputId !== undefined &&\n\t\trequest.input.inputId !== route.inputId\n\t) {\n\t\treturn \"route-input-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputKind !== undefined &&\n\t\troute.inputKind !== undefined &&\n\t\trequest.input.inputKind !== route.inputKind\n\t) {\n\t\treturn \"route-input-kind-mismatch\";\n\t}\n\tconst inputKind = request.input?.inputKind ?? route.inputKind;\n\tif (inputKind !== undefined && !profileKindAcceptsInput(profile.kind, inputKind))\n\t\treturn \"profile-kind-input-incompatible\";\n\tif (\n\t\tinputKind !== undefined &&\n\t\tprofile.acceptedInputKinds !== undefined &&\n\t\t!profile.acceptedInputKinds.includes(inputKind)\n\t) {\n\t\treturn \"profile-rejects-input-kind\";\n\t}\n\tif (\n\t\trequest.input?.schemaRef !== undefined &&\n\t\tprofile.acceptedSchemaRefs !== undefined &&\n\t\t!profile.acceptedSchemaRefs.includes(request.input.schemaRef)\n\t) {\n\t\treturn \"profile-rejects-schema\";\n\t}\n\treturn undefined;\n}\n\nfunction outcomeCompatibilityIssue(\n\trequest: AgentRequestIssued,\n\troute: ExecutorRoute,\n\toutcome: ExecutorOutcome,\n): string | undefined {\n\tif (outcome.executorId !== route.executorId) return \"outcome-route-executor-mismatch\";\n\tif (outcome.profileId !== route.profileId) return \"outcome-route-profile-mismatch\";\n\tif (\n\t\troute.inputId !== undefined &&\n\t\t(outcome.inputId === undefined || outcome.inputId !== route.inputId)\n\t) {\n\t\treturn \"outcome-route-input-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputId !== undefined &&\n\t\toutcome.inputId !== undefined &&\n\t\toutcome.inputId !== request.input.inputId\n\t) {\n\t\treturn \"outcome-request-input-mismatch\";\n\t}\n\tif (\n\t\troute.inputKind !== undefined &&\n\t\t(outcome.inputKind === undefined || outcome.inputKind !== route.inputKind)\n\t) {\n\t\treturn \"outcome-route-input-kind-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputKind !== undefined &&\n\t\toutcome.inputKind !== undefined &&\n\t\toutcome.inputKind !== request.input.inputKind\n\t) {\n\t\treturn \"outcome-request-input-kind-mismatch\";\n\t}\n\treturn undefined;\n}\n\nfunction profileKindAcceptsInput(kind: ExecutorProfile[\"kind\"], inputKind: string): boolean {\n\tif (kind === \"llm\") return inputKind === \"llm-call\";\n\tif (kind === \"tool\") return inputKind === \"tool-call\";\n\tif (kind === \"human\") return inputKind === \"human-task\";\n\treturn inputKind === \"agent-task\";\n}\n\nfunction outcomeStatus(outcome: ExecutorOutcome): AgentRequestStatus {\n\tif (outcome.kind === \"result\") return \"completed\";\n\tif (outcome.kind === \"failure\") return \"failed\";\n\tif (outcome.kind === \"timeout\") return \"timeout\";\n\tif (outcome.kind === \"canceled\") return \"canceled\";\n\treturn \"blocked\";\n}\n\nfunction executorOutcomeViewProjectionFromOutcome(\n\toutcome: ExecutorOutcome,\n\tpolicy: Required<ExecutorOutcomeViewPolicy>,\n): ExecutorOutcomeViewProjection {\n\tconst sourceRefs = uniqueSourceRefs([\n\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t...(outcome.evidenceRefs ?? []),\n\t]);\n\tconst summary = projectOutcomeSummary(outcome, policy.maxSummaryChars);\n\tconst issues = Object.freeze([\n\t\t...outcomeIssues(outcome),\n\t\t...(summary.truncated ? [outcomeSummaryTruncationIssue(outcome, summary, policy)] : []),\n\t]);\n\tconst view = Object.freeze({\n\t\tkind: \"executor-outcome-view\",\n\t\tviewId: `${outcome.outcomeId}:${policy.audience}`,\n\t\taudience: policy.audience,\n\t\toutcomeId: outcome.outcomeId,\n\t\trequestId: outcome.requestId,\n\t\toperationId: outcome.operationId,\n\t\trouteId: outcome.routeId,\n\t\texecutorId: outcome.executorId,\n\t\tprofileId: outcome.profileId,\n\t\tstatus: outcome.kind,\n\t\tsummary: summary.summary,\n\t\tsummaryTruncated: summary.truncated,\n\t\tsummaryChars: summary.originalChars,\n\t\tsummaryLimitChars: summary.limitChars,\n\t\terrorKind: outcomeErrorKind(outcome),\n\t\tretryable: outcomeRetryable(outcome),\n\t\tnextActions: outcomeNextActions(outcome),\n\t\tsourceRefs,\n\t\tmaterialRefs: outcomeMaterialRefs(outcome),\n\t\tissues: policy.includeIssues && issues.length > 0 ? issues : undefined,\n\t\tusage: policy.includeUsage ? outcome.usage : undefined,\n\t\tmetadata: policy.includeMetadata ? outcome.metadata : undefined,\n\t} satisfies ExecutorOutcomeView);\n\treturn Object.freeze({ view, issues });\n}\n\nfunction projectOutcomeSummary(\n\toutcome: ExecutorOutcome,\n\tmaxChars: number,\n): ExecutorOutcomeSummaryProjection {\n\tconst summary = outcomeSummary(outcome);\n\tconst limitChars = Math.max(0, maxChars);\n\tif (summary.length <= limitChars) {\n\t\treturn Object.freeze({\n\t\t\tsummary,\n\t\t\ttruncated: false,\n\t\t\toriginalChars: summary.length,\n\t\t\tlimitChars,\n\t\t});\n\t}\n\tconst bounded =\n\t\tlimitChars <= 1\n\t\t\t? summary.slice(0, limitChars)\n\t\t\t: limitChars <= 3\n\t\t\t\t? summary.slice(0, limitChars)\n\t\t\t\t: `${summary.slice(0, limitChars - 3)}...`;\n\treturn Object.freeze({\n\t\tsummary: bounded,\n\t\ttruncated: true,\n\t\toriginalChars: summary.length,\n\t\tlimitChars,\n\t});\n}\n\nfunction outcomeSummaryTruncationIssue(\n\toutcome: ExecutorOutcome,\n\tsummary: ExecutorOutcomeSummaryProjection,\n\tpolicy: Required<ExecutorOutcomeViewPolicy>,\n): DataIssue {\n\treturn dataIssue(\n\t\t\"executor-outcome-view-summary-truncated\",\n\t\t\"ExecutorOutcome view summary was truncated; inspect material refs or the source outcome for full detail\",\n\t\t{\n\t\t\tsubjectId: outcome.requestId,\n\t\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\tseverity: \"warning\",\n\t\t\tdetails: {\n\t\t\t\taudience: policy.audience,\n\t\t\t\toutcomeId: outcome.outcomeId,\n\t\t\t\toriginalChars: summary.originalChars,\n\t\t\t\tlimitChars: summary.limitChars,\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction outcomeSummary(outcome: ExecutorOutcome): string {\n\tif (outcome.kind === \"result\") {\n\t\tif (outcome.result.summary !== undefined && outcome.result.summary.length > 0)\n\t\t\treturn outcome.result.summary;\n\t\treturn `Executor result '${outcome.result.kind}' is available via source refs`;\n\t}\n\tif (outcome.kind === \"failure\") return outcome.error.message;\n\tif (outcome.kind === \"blocked\") {\n\t\tconst needKinds = outcome.needs.map((need) => need.kind).join(\", \");\n\t\treturn needKinds.length > 0 ? `Executor blocked: ${needKinds}` : \"Executor blocked\";\n\t}\n\tif (outcome.kind === \"timeout\") {\n\t\treturn outcome.timeoutMs === undefined\n\t\t\t? \"Executor timed out\"\n\t\t\t: `Executor timed out after ${outcome.timeoutMs}ms`;\n\t}\n\treturn outcome.reason ?? \"Executor canceled\";\n}\n\nfunction outcomeErrorKind(outcome: ExecutorOutcome): string | undefined {\n\tif (outcome.kind === \"failure\") return outcome.error.code;\n\tif (outcome.kind === \"timeout\") return \"timeout\";\n\tif (outcome.kind === \"blocked\") return outcome.needs[0]?.kind ?? \"blocked\";\n\tif (outcome.kind === \"canceled\") return \"canceled\";\n\treturn undefined;\n}\n\nfunction outcomeRetryable(outcome: ExecutorOutcome): boolean | undefined {\n\tif (outcome.kind === \"failure\" || outcome.kind === \"timeout\") return outcome.retryable;\n\treturn undefined;\n}\n\nfunction outcomeIssues(outcome: ExecutorOutcome): readonly DataIssue[] {\n\tif (outcome.kind === \"failure\") return Object.freeze([outcome.error, ...(outcome.issues ?? [])]);\n\treturn outcome.issues ?? [];\n}\n\nfunction outcomeNextActions(outcome: ExecutorOutcome): readonly string[] | undefined {\n\tif (outcome.kind === \"blocked\") return Object.freeze(outcome.needs.map((need) => need.kind));\n\tif ((outcome.kind === \"failure\" || outcome.kind === \"timeout\") && outcome.retryable === true) {\n\t\treturn Object.freeze([\"retry-or-route\"]);\n\t}\n\treturn undefined;\n}\n\nfunction outcomeMaterialRefs(outcome: ExecutorOutcome): readonly SourceRef[] | undefined {\n\tconst refs =\n\t\toutcome.kind === \"result\"\n\t\t\t? [...(outcome.result.refs ?? [])]\n\t\t\t: outcome.kind === \"blocked\"\n\t\t\t\t? outcome.needs.flatMap((need) => [...(need.refs ?? [])])\n\t\t\t\t: [];\n\treturn refs.length === 0 ? undefined : uniqueSourceRefs(refs);\n}\n\nfunction uniqueSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\tconst seen = new Set<string>();\n\tconst unique: SourceRef[] = [];\n\tfor (const sourceRef of sourceRefs) {\n\t\tconst key = `${sourceRef.kind}:${sourceRef.id}:${JSON.stringify(sourceRef.metadata ?? {})}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(sourceRef);\n\t}\n\treturn Object.freeze(unique);\n}\n\nfunction emitStatus(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\trequest: AgentRequestIssued,\n\tstatus: AgentRequestStatus,\n\tsourceRefs?: readonly SourceRef[],\n\tissues?: readonly DataIssue[],\n): void {\n\tconst fact: AgentRequestStatusChanged = {\n\t\tkind: \"status\",\n\t\trequestId: request.requestId,\n\t\toperationId: request.operationId,\n\t\teffectRunId: request.effectRunId,\n\t\tstatus,\n\t\tsourceRefs,\n\t\tissues,\n\t};\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\"DATA\", { kind: \"status\", status: fact } satisfies AgentRequestSatisfactionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${request.requestId}:status:${state.auditSeq}`,\n\t\t\t\t\tkind: \"agent-request-status\",\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\tsourceRefs,\n\t\t\t\t\tmetadata: { status },\n\t\t\t\t},\n\t\t\t} satisfies AgentRequestSatisfactionFact,\n\t\t],\n\t]);\n}\n\nfunction emitStatusOnce(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tkey: string,\n\trequest: AgentRequestIssued,\n\tstatus: AgentRequestStatus,\n\tsourceRefs?: readonly SourceRef[],\n\tissues?: readonly DataIssue[],\n): void {\n\tif (state.statusKeys.has(key)) return;\n\tstate.statusKeys.add(key);\n\temitStatus(ctx, state, request, status, sourceRefs, issues);\n}\n\nfunction emitIssue(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\trefs?: readonly SourceRef[],\n): void {\n\tstate.issueSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs });\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies AgentRequestSatisfactionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${subjectId ?? \"request\"}:issue:${state.auditSeq}`,\n\t\t\t\t\tkind: \"agent-request-issue\",\n\t\t\t\t\tsubjectId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs: refs,\n\t\t\t\t},\n\t\t\t} satisfies AgentRequestSatisfactionFact,\n\t\t],\n\t]);\n}\n\nfunction emitIssueOnce(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\trefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\temitIssue(ctx, state, code, message, subjectId, refs);\n}\n\nfunction emitInterpreterIssue(\n\tctx: Ctx,\n\tseq: number,\n\toutcome: ExecutorOutcome,\n\tcode: string,\n\tmessage: string,\n): void {\n\tconst issue = dataIssue(code, message, {\n\t\tsubjectId: outcome.requestId,\n\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t});\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies StructuredAgentDecisionInterpreterFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${outcome.outcomeId}:agent-decision-issue:${seq}`,\n\t\t\t\t\tkind: \"agent-decision-issue\",\n\t\t\t\t\tsubjectId: outcome.requestId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t},\n\t\t\t} satisfies StructuredAgentDecisionInterpreterFact,\n\t\t],\n\t]);\n}\n\nfunction validateAgentDecision(raw: unknown, outcome: ExecutorOutcome): AgentDecision | string {\n\tif (!isRecord(raw)) return \"AgentDecision must be an object\";\n\tconst kind = raw.kind;\n\tif (kind !== \"continue\" && kind !== \"final\" && kind !== \"blocked\") {\n\t\treturn \"AgentDecision kind must be continue, final, or blocked\";\n\t}\n\tif (typeof raw.decisionId !== \"string\" || raw.decisionId.length === 0)\n\t\treturn \"AgentDecision decisionId must be a non-empty string\";\n\tif (\n\t\traw.effectRunId === undefined ||\n\t\ttypeof raw.effectRunId !== \"string\" ||\n\t\traw.effectRunId.length === 0\n\t)\n\t\treturn \"AgentDecision effectRunId must be a non-empty string\";\n\tif (typeof raw.agentRunId !== \"string\" || raw.agentRunId.length === 0)\n\t\treturn \"AgentDecision agentRunId must be a non-empty string\";\n\tconst source = raw.source;\n\tif (\n\t\t!isRecord(source) ||\n\t\tsource.requestId !== outcome.requestId ||\n\t\tsource.operationId !== outcome.operationId ||\n\t\tsource.outcomeId !== outcome.outcomeId\n\t) {\n\t\treturn \"AgentDecision source must match the ExecutorOutcome requestId, operationId, and outcomeId\";\n\t}\n\tif (kind === \"continue\") {\n\t\tif (!Array.isArray(raw.next)) return \"AgentDecision.continue next must be an array\";\n\t\tfor (const proposal of raw.next) {\n\t\t\tif (!isAgentRequestProposalLike(proposal, raw.effectRunId)) {\n\t\t\t\treturn \"AgentDecision.continue next entries must be AgentRequestProposal-like objects\";\n\t\t\t}\n\t\t}\n\t\treturn raw as unknown as AgentDecisionContinue;\n\t}\n\tif (kind === \"final\") {\n\t\tif (!isRecord(raw.output) || typeof raw.output.kind !== \"string\")\n\t\t\treturn \"AgentDecision.final output must be an envelope with kind\";\n\t\treturn raw as unknown as AgentDecisionFinal;\n\t}\n\tif (!Array.isArray(raw.needs)) return \"AgentDecision.blocked needs must be an array\";\n\tfor (const need of raw.needs) {\n\t\tif (!isAgentNeedLike(need))\n\t\t\treturn \"AgentDecision.blocked needs entries must be AgentNeed-like objects\";\n\t}\n\treturn raw as unknown as AgentDecisionBlocked;\n}\n\nfunction isAgentRequestProposalLike(value: unknown, effectRunId: string): boolean {\n\tif (!isRecord(value)) return false;\n\tif (value.kind !== \"proposal\") return false;\n\tif (typeof value.proposalId !== \"string\" || value.proposalId.length === 0) return false;\n\tif (value.effectRunId !== effectRunId) return false;\n\treturn (\n\t\tvalue.requestKind === \"context\" ||\n\t\tvalue.requestKind === \"prompt\" ||\n\t\tvalue.requestKind === \"executor\"\n\t);\n}\n\nfunction isAgentNeedLike(value: unknown): boolean {\n\treturn isRecord(value) && typeof value.kind === \"string\" && value.kind.length > 0;\n}\n\nfunction candidateFromDecision(\n\tdecision: AgentDecision,\n\tstate: EffectRunCompletionState,\n\tcompletedAtMs: number,\n): EffectRunResult | undefined {\n\tconst run = state.runs.get(decision.effectRunId);\n\tif (run === undefined) return undefined;\n\tif (!decisionSourceRequestTerminal(decision, state)) return undefined;\n\tconst requiredPending = requiredPendingRequests(decision.effectRunId, state);\n\tif (decision.kind === \"final\") {\n\t\tif (requiredPending.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tkind: \"effect-run-result\",\n\t\t\tresultId: `${decision.effectRunId}:result`,\n\t\t\tstatus: \"completed\",\n\t\t\teffectRunId: decision.effectRunId,\n\t\t\tsubjectRefs: run.subjectRefs,\n\t\t\toperationId: decision.source.operationId,\n\t\t\tsourceRefs: [\n\t\t\t\tref(\"agent-decision\", decision.decisionId),\n\t\t\t\tref(\"executor-outcome\", decision.source.outcomeId),\n\t\t\t],\n\t\t\tcompletedAtMs,\n\t\t\toutput: decision.output,\n\t\t};\n\t}\n\tif (decision.kind === \"blocked\" && requiredPending.length === 0) {\n\t\treturn {\n\t\t\tkind: \"effect-run-result\",\n\t\t\tresultId: `${decision.effectRunId}:result`,\n\t\t\tstatus: \"blocked\",\n\t\t\teffectRunId: decision.effectRunId,\n\t\t\tsubjectRefs: run.subjectRefs,\n\t\t\toperationId: decision.source.operationId,\n\t\t\tsourceRefs: [\n\t\t\t\tref(\"agent-decision\", decision.decisionId),\n\t\t\t\tref(\"executor-outcome\", decision.source.outcomeId),\n\t\t\t],\n\t\t\tcompletedAtMs,\n\t\t\tneeds: decision.needs,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction acceptEffectRunResultCandidate(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tcandidate: EffectRunResult,\n): void {\n\tif (!state.runs.has(candidate.effectRunId)) {\n\t\temitEffectRunIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t\"unknown-effect-run-result-candidate\",\n\t\t\t`EffectRunResult candidate '${candidate.resultId}' references unknown EffectRun '${candidate.effectRunId}'`,\n\t\t\tcandidate.effectRunId,\n\t\t\tcandidate.sourceRefs,\n\t\t);\n\t\treturn;\n\t}\n\tconst existing = state.resultsByEffectRun.get(candidate.effectRunId);\n\tif (existing !== undefined) {\n\t\tstate.issueSeq += 1;\n\t\tconst duplicate = sameTerminalResult(existing, candidate);\n\t\tconst code = duplicate ? \"duplicate-effect-run-result\" : \"conflicting-effect-run-result\";\n\t\tconst issue = dataIssue(\n\t\t\tcode,\n\t\t\t`EffectRun '${candidate.effectRunId}' already has a terminal result`,\n\t\t\t{\n\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\trefs: candidate.sourceRefs,\n\t\t\t},\n\t\t);\n\t\tctx.down([\n\t\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"audit\",\n\t\t\t\t\taudit: {\n\t\t\t\t\t\tid: `${candidate.effectRunId}:${code}:${state.issueSeq}`,\n\t\t\t\t\t\tkind: duplicate ? \"effect-run-result-duplicate\" : \"effect-run-result-conflict\",\n\t\t\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t\t},\n\t\t\t\t} satisfies EffectRunCompletionFact,\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tstate.resultsByEffectRun.set(candidate.effectRunId, candidate);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"result\", result: candidate } satisfies EffectRunCompletionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"status\",\n\t\t\t\tstatus: {\n\t\t\t\t\teffectRunId: candidate.effectRunId,\n\t\t\t\t\tstate: candidate.status,\n\t\t\t\t\trequiredPending: [],\n\t\t\t\t\trequiredTerminal: requiredTerminalRequests(candidate.effectRunId, state),\n\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${candidate.effectRunId}:terminal-result`,\n\t\t\t\t\tkind: \"effect-run-terminal-result\",\n\t\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t\tmetadata: { status: candidate.status },\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nfunction emitEffectRunStatus(\n\tctx: Ctx,\n\teffectRunId: string,\n\tstate: EffectRunCompletionStatus[\"state\"],\n\trequiredPending: readonly string[],\n\trequiredTerminal: readonly string[],\n): void {\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"status\",\n\t\t\t\tstatus: { effectRunId, state, requiredPending, requiredTerminal },\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nfunction requiredPendingRequests(\n\teffectRunId: string,\n\tstate: EffectRunCompletionState,\n): readonly string[] {\n\tconst pending: string[] = [];\n\tfor (const request of state.requests.values()) {\n\t\tif (request.effectRunId !== effectRunId || !request.required) continue;\n\t\tconst statusFact = matchingStatusForRequest(state, request);\n\t\tconst status = statusFact?.status;\n\t\tif (status === undefined || !isTerminalRequestStatus(status)) pending.push(request.requestId);\n\t}\n\treturn pending;\n}\n\nfunction requiredTerminalRequests(\n\teffectRunId: string,\n\tstate: EffectRunCompletionState,\n): readonly string[] {\n\tconst terminal: string[] = [];\n\tfor (const request of state.requests.values()) {\n\t\tif (request.effectRunId !== effectRunId || !request.required) continue;\n\t\tconst statusFact = matchingStatusForRequest(state, request);\n\t\tconst status = statusFact?.status;\n\t\tif (status !== undefined && isTerminalRequestStatus(status)) terminal.push(request.requestId);\n\t}\n\treturn terminal;\n}\n\nfunction isTerminalRequestStatus(status: AgentRequestStatus): boolean {\n\treturn (\n\t\tstatus === \"completed\" ||\n\t\tstatus === \"failed\" ||\n\t\tstatus === \"blocked\" ||\n\t\tstatus === \"canceled\" ||\n\t\tstatus === \"timeout\" ||\n\t\tstatus === \"waived\" ||\n\t\tstatus === \"retry-exhausted\"\n\t);\n}\n\nfunction decisionSourceRequestTerminal(\n\tdecision: AgentDecision,\n\tstate: EffectRunCompletionState,\n): boolean {\n\tconst request = state.requests.get(decision.source.requestId);\n\tif (request === undefined) return false;\n\tif (\n\t\trequest.effectRunId !== decision.effectRunId ||\n\t\trequest.operationId !== decision.source.operationId\n\t) {\n\t\treturn false;\n\t}\n\tconst status = matchingStatusForRequest(state, request)?.status;\n\treturn status !== undefined && isTerminalRequestStatus(status);\n}\n\nfunction acceptRequestStatus(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tstatus: AgentRequestStatusChanged,\n): void {\n\tconst request = state.requests.get(status.requestId);\n\tif (request !== undefined && !statusMatchesRequest(status, request)) {\n\t\temitEffectRunIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t\"stale-request-status\",\n\t\t\t`AgentRequest status for '${status.requestId}' did not match its issued effectRun/operation identity`,\n\t\t\trequest.effectRunId,\n\t\t\t[ref(\"agent-request\", status.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tstate.statusByRequest.set(status.requestId, status);\n}\n\nfunction matchingStatusForRequest(\n\tstate: EffectRunCompletionState,\n\trequest: AgentRequestIssued,\n): AgentRequestStatusChanged | undefined {\n\tconst status = state.statusByRequest.get(request.requestId);\n\tif (status === undefined) return undefined;\n\treturn statusMatchesRequest(status, request) ? status : undefined;\n}\n\nfunction statusMatchesRequest(\n\tstatus: AgentRequestStatusChanged,\n\trequest: AgentRequestIssued,\n): boolean {\n\treturn (\n\t\tstatus.effectRunId === request.effectRunId &&\n\t\t(status.operationId === undefined || status.operationId === request.operationId)\n\t);\n}\n\nfunction emitEffectRunIssue(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tstate.issueSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${subjectId ?? \"effect-run\"}:${code}:${state.issueSeq}`,\n\t\t\t\t\tkind: \"effect-run-issue\",\n\t\t\t\t\tsubjectId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs,\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nfunction sameTerminalResult(a: EffectRunResult, b: EffectRunResult): boolean {\n\treturn (\n\t\ta.status === b.status && a.resultId === b.resultId && JSON.stringify(a) === JSON.stringify(b)\n\t);\n}\n\nfunction emptyEffectRunCompletionState(): EffectRunCompletionState {\n\treturn {\n\t\truns: new Map<string, EffectRun>(),\n\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\tstatusByRequest: new Map<string, AgentRequestStatusChanged>(),\n\t\tdecisions: new Map<string, AgentDecision>(),\n\t\tresultsByEffectRun: new Map<string, EffectRunResult>(),\n\t\tissueSeq: 0,\n\t};\n}\n\nfunction emptyAgentRequestViewsState(): AgentRequestViewsState {\n\treturn {\n\t\trequestsById: new Map<string, AgentRequestIssued>(),\n\t\trequestsByEffectRun: new Map<string, string[]>(),\n\t\tstatusByRequest: new Map<string, AgentRequestStatusChanged>(),\n\t\tissues: [],\n\t\taudit: [],\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction cloneAgentRequestViewsState(state: AgentRequestViewsState): AgentRequestViewsState {\n\treturn {\n\t\trequestsById: new Map(state.requestsById),\n\t\trequestsByEffectRun: new Map(Array.from(state.requestsByEffectRun, ([k, v]) => [k, [...v]])),\n\t\tstatusByRequest: new Map(state.statusByRequest),\n\t\tissues: [...state.issues],\n\t\taudit: [...state.audit],\n\t\tauditSeq: state.auditSeq,\n\t};\n}\n\nfunction reduceAgentRequestViews(state: AgentRequestViewsState, fact: AgentRequestFact): void {\n\tstate.auditSeq += 1;\n\tif (fact.kind === \"issued\") {\n\t\tstate.requestsById.set(fact.requestId, fact);\n\t\tconst requestIds = state.requestsByEffectRun.get(fact.effectRunId) ?? [];\n\t\tif (!requestIds.includes(fact.requestId)) requestIds.push(fact.requestId);\n\t\tstate.requestsByEffectRun.set(fact.effectRunId, requestIds);\n\t\tstate.statusByRequest.set(fact.requestId, {\n\t\t\tkind: \"status\",\n\t\t\trequestId: fact.requestId,\n\t\t\toperationId: fact.operationId,\n\t\t\teffectRunId: fact.effectRunId,\n\t\t\tstatus: \"issued\",\n\t\t\tsourceRefs: [ref(\"agent-request\", fact.requestId)],\n\t\t});\n\t} else if (fact.kind === \"status\") {\n\t\tstate.statusByRequest.set(fact.requestId, fact);\n\t\tif (fact.issues !== undefined) state.issues.push(...fact.issues);\n\t} else if (fact.kind === \"rejected\") {\n\t\tstate.issues.push(fact.issue);\n\t}\n\tstate.audit.push({\n\t\tid: `agent-request-ledger:${state.auditSeq}`,\n\t\tkind: `agent-request-${fact.kind}`,\n\t\tsubjectId: \"requestId\" in fact ? fact.requestId : fact.proposalId,\n\t});\n}\n\nfunction freezeAgentRequestViews(state: AgentRequestViewsState): AgentRequestViews {\n\tconst pending = Array.from(state.requestsById.values()).filter((request) => {\n\t\tconst status = state.statusByRequest.get(request.requestId)?.status;\n\t\treturn status === undefined || !isTerminalRequestStatus(status);\n\t});\n\tconst awaitingProvider = pending.filter(\n\t\t(request) => state.statusByRequest.get(request.requestId)?.status === \"awaiting-provider\",\n\t);\n\treturn {\n\t\trequestsById: new Map(state.requestsById),\n\t\trequestsByEffectRun: new Map(\n\t\t\tArray.from(state.requestsByEffectRun, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tstatusByRequest: new Map(state.statusByRequest),\n\t\tpending: Object.freeze(pending),\n\t\tawaitingProvider: Object.freeze(awaitingProvider),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction projectRuntimeFact<T, TOut>(\n\tgraph: Graph,\n\truntime: Node<T>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: T) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as T;\n\t\t\t\tconst value = pick(typed);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory },\n\t);\n}\n\nfunction forEachDepBatch(\n\tctx: Ctx,\n\tstart: number,\n\tcount: number,\n\tfn: (value: unknown) => void,\n): void {\n\tfor (let i = 0; i < count; i += 1) {\n\t\tfor (const value of depBatch(ctx, start + i) ?? []) fn(value);\n\t}\n}\n\nfunction dataIssue(\n\tcode: string,\n\tmessage: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly refs?: readonly SourceRef[];\n\t\treadonly severity?: DataIssue[\"severity\"];\n\t\treadonly details?: unknown;\n\t} = {},\n): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: opts.severity ?? \"error\",\n\t\tsubjectId: opts.subjectId,\n\t\trefs: opts.refs?.map((r) => `${r.kind}:${r.id}`),\n\t\tdetails: opts.details,\n\t};\n}\n\nfunction ref(kind: string, id: string): SourceRef {\n\treturn { kind, id };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\ttype AgentNeed,\n\ttype AgentOutputEnvelope,\n\ttype AgentRuntimeAuditRecord,\n\ttype EffectRun,\n\ttype EffectRunGoal,\n\ttype EffectRunLimits,\n\ttype EffectRunResult,\n\ttype EffectRunResultStatus,\n\teffectRun,\n\ttype SourceRef,\n} from \"./agent-runtime.js\";\n\nexport interface WorkItemSeed {\n\treadonly kind: \"work-item\";\n\treadonly workItemId: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly workItemKind?: string;\n\treadonly summary?: string;\n\treadonly detailRef?: string;\n\treadonly lifecycleStatus?: string;\n\treadonly issues?: readonly DataIssue[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemEffectRequested<TInput = unknown> {\n\treadonly kind: \"work-item-effect-requested\";\n\treadonly requestId: string;\n\treadonly workItemId: string;\n\treadonly effectRunId: string;\n\treadonly effectKind: string;\n\treadonly executionInputRevision?: number;\n\treadonly planId?: string;\n\treadonly planMemberId?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly goal: EffectRunGoal<TInput>;\n\treadonly agentRunId?: string;\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly limits?: EffectRunLimits;\n\treadonly createdBy?: string;\n\treadonly createdAtMs?: number;\n\treadonly idempotencyKey?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemEvidenceRecorded {\n\treadonly kind: \"work-item-evidence-recorded\";\n\treadonly evidenceId: string;\n\treadonly workItemId: string;\n\treadonly requestId?: string;\n\treadonly effectRunId: string;\n\treadonly effectRunResultId: string;\n\treadonly executionInputRevision?: number;\n\treadonly planId?: string;\n\treadonly planMemberId?: string;\n\treadonly status: EffectRunResultStatus;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly output?: AgentOutputEnvelope;\n\treadonly error?: DataIssue;\n\treadonly needs?: readonly AgentNeed[];\n\treadonly reason?: string;\n\treadonly timeoutMs?: number;\n\treadonly issues?: readonly DataIssue[];\n\treadonly auditRefs?: readonly string[];\n\treadonly recordedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type WorkItemDomainActionProposalPayloadFrom = \"evidence\" | \"effect-run-result\" | \"output\";\n\nexport interface WorkItemDomainActionProposalSpec<TPayload = unknown> {\n\treadonly actionKind: string;\n\treadonly behavior?: \"propose\";\n\treadonly statuses?: readonly EffectRunResultStatus[];\n\treadonly outputKinds?: readonly string[];\n\treadonly payloadFrom?: WorkItemDomainActionProposalPayloadFrom;\n\treadonly payload?: TPayload;\n\treadonly reason?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemDomainActionProposal<TPayload = unknown> {\n\treadonly kind: \"work-item-domain-action-proposal\";\n\treadonly proposalId: string;\n\treadonly workItemId: string;\n\treadonly actionKind: string;\n\treadonly effectRunId: string;\n\treadonly effectRunResultId: string;\n\treadonly evidenceId: string;\n\treadonly policyId: string;\n\treadonly payload?: TPayload;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly proposedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type WorkItemDomainActionAdmissionOutcome = \"admit\" | \"reject\" | \"defer\" | \"merge\";\nexport type WorkItemDomainActionAdmissionState = \"admitted\" | \"rejected\" | \"deferred\" | \"merged\";\n\nexport interface WorkItemDomainActionAdmissionPolicy {\n\treadonly kind: \"work-item-domain-action-admission-policy\";\n\treadonly policyId: string;\n\treadonly actionKinds?: readonly string[];\n\treadonly allowedOutcomes?: readonly WorkItemDomainActionAdmissionOutcome[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemDomainActionAdmissionDecision {\n\treadonly kind: \"work-item-domain-action-admission-decision\";\n\treadonly decisionId: string;\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly outcome: WorkItemDomainActionAdmissionOutcome;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly targetProposalId?: string;\n\treadonly targetAdmissionId?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly decidedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemDomainActionAdmission {\n\treadonly kind: \"work-item-domain-action-admission\";\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly workItemId: string;\n\treadonly actionKind: string;\n\treadonly state: WorkItemDomainActionAdmissionState;\n\treadonly decisionId: string;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly targetProposalId?: string;\n\treadonly targetAdmissionId?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly admittedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemEffectMappingPolicy {\n\treadonly kind: \"work-item-effect-mapping-policy\";\n\treadonly policyId: string;\n\treadonly effectKinds?: readonly string[];\n\treadonly evidence?: {\n\t\treadonly behavior?: \"record\";\n\t};\n\treadonly actionProposals?: readonly WorkItemDomainActionProposalSpec[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemStatusRecord {\n\treadonly kind: \"work-item-status\";\n\treadonly statusId: string;\n\treadonly workItemId: string;\n\treadonly state:\n\t\t| \"effect-request-pending\"\n\t\t| \"effect-run-seeded\"\n\t\t| \"evidence-recorded\"\n\t\t| \"domain-action-proposed\"\n\t\t| \"domain-action-admitted\"\n\t\t| \"domain-action-rejected\"\n\t\t| \"domain-action-deferred\"\n\t\t| \"domain-action-merged\"\n\t\t| \"mapping-issue\";\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly effectRunId?: string;\n\treadonly requestId?: string;\n\treadonly evidenceId?: string;\n\treadonly proposalId?: string;\n\treadonly issues?: readonly DataIssue[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface WorkItemEffectRequestViews {\n\treadonly pendingEffectRequests: readonly WorkItemEffectRequested[];\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface WorkItemEvidenceViews {\n\treadonly evidenceByWorkItem: ReadonlyMap<string, readonly WorkItemEvidenceRecorded[]>;\n\treadonly latestEvidenceByEffectRun: ReadonlyMap<string, WorkItemEvidenceRecorded>;\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n\treadonly pendingEffectRequests: readonly WorkItemEffectRequested[];\n}\n\nexport interface WorkItemDomainActionProposalViews {\n\treadonly proposalsByWorkItem: ReadonlyMap<string, readonly WorkItemDomainActionProposal[]>;\n\treadonly proposalsByEvidence: ReadonlyMap<string, readonly WorkItemDomainActionProposal[]>;\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface WorkItemDomainActionAdmissionViews {\n\treadonly admissionsByProposal: ReadonlyMap<string, WorkItemDomainActionAdmission>;\n\treadonly admissionsByWorkItem: ReadonlyMap<string, readonly WorkItemDomainActionAdmission[]>;\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface WorkItemEffectRunBundle {\n\treadonly effectRuns: Node<EffectRun>;\n\treadonly status: Node<WorkItemStatusRecord>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<WorkItemEffectRequestViews>;\n}\n\nexport interface WorkItemEvidenceMapperBundle {\n\treadonly evidence: Node<WorkItemEvidenceRecorded>;\n\treadonly status: Node<WorkItemStatusRecord>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<WorkItemEvidenceViews>;\n}\n\nexport interface WorkItemDomainActionProposalBundle {\n\treadonly proposals: Node<WorkItemDomainActionProposal>;\n\treadonly status: Node<WorkItemStatusRecord>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<WorkItemDomainActionProposalViews>;\n}\n\nexport interface WorkItemDomainActionAdmissionBundle {\n\treadonly admissions: Node<WorkItemDomainActionAdmission>;\n\treadonly status: Node<WorkItemStatusRecord>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<WorkItemDomainActionAdmissionViews>;\n}\n\nexport function workItemEffectRunProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly workItems: Node<WorkItemSeed>;\n\t\treadonly effectRequests: Node<WorkItemEffectRequested>;\n\t},\n): WorkItemEffectRunBundle {\n\tconst name = opts.name ?? \"workItemEffectRuns\";\n\tconst runtime = graph.node<WorkItemEffectRunFact>(\n\t\t[opts.workItems, opts.effectRequests],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<WorkItemEffectRunState>() ?? emptyWorkItemEffectRunState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst workItem = raw as WorkItemSeed;\n\t\t\t\tstate.workItems.set(workItem.workItemId, workItem);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst request = raw as WorkItemEffectRequested;\n\t\t\t\tstate.requests.set(request.requestId, request);\n\t\t\t\tconst requestRefs = workItemEffectRequestRefs(request);\n\t\t\t\tstate.statusSeq += 1;\n\t\t\t\tstate.auditSeq += 1;\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: \"status\",\n\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\tkind: \"work-item-status\",\n\t\t\t\t\t\t\t\tstatusId: `${request.workItemId}:effect-request-pending:${state.statusSeq}`,\n\t\t\t\t\t\t\t\tworkItemId: request.workItemId,\n\t\t\t\t\t\t\t\teffectRunId: request.effectRunId,\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\tstate: \"effect-request-pending\",\n\t\t\t\t\t\t\t\tsourceRefs: requestRefs,\n\t\t\t\t\t\t\t\tmetadata: { effectKind: request.effectKind },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies WorkItemEffectRunFact,\n\t\t\t\t\t],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${request.workItemId}:effect-request-pending:${state.auditSeq}`,\n\t\t\t\t\t\t\t\tkind: \"work-item-effect-request-pending\",\n\t\t\t\t\t\t\t\tsubjectId: request.workItemId,\n\t\t\t\t\t\t\t\tsourceRefs: requestRefs,\n\t\t\t\t\t\t\t\tmetadata: { effectRunId: request.effectRunId, effectKind: request.effectKind },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies WorkItemEffectRunFact,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\tconst workItem = state.workItems.get(request.workItemId);\n\t\t\t\tif (workItem === undefined) {\n\t\t\t\t\temitWorkItemEffectRunIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`unknown-work-item:${request.requestId}`,\n\t\t\t\t\t\t\"unknown-work-item-effect-request\",\n\t\t\t\t\t\t`WorkItemEffectRequested '${request.requestId}' references unknown WorkItem '${request.workItemId}'`,\n\t\t\t\t\t\trequest.workItemId,\n\t\t\t\t\t\trequestRefs,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst existingEffectRunId = state.effectRunsByRequest.get(request.requestId);\n\t\t\t\tif (existingEffectRunId !== undefined) {\n\t\t\t\t\temitWorkItemEffectRunIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-effect-request:${request.requestId}`,\n\t\t\t\t\t\t\"duplicate-work-item-effect-request\",\n\t\t\t\t\t\t`WorkItemEffectRequested '${request.requestId}' was already mapped to EffectRun '${existingEffectRunId}'`,\n\t\t\t\t\t\trequest.workItemId,\n\t\t\t\t\t\trequestRefs,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (state.seededEffectRunIds.has(request.effectRunId)) {\n\t\t\t\t\temitWorkItemEffectRunIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-effect-run:${request.effectRunId}:${request.requestId}`,\n\t\t\t\t\t\t\"duplicate-work-item-effect-run\",\n\t\t\t\t\t\t`EffectRun '${request.effectRunId}' was already seeded from another WorkItemEffectRequested fact`,\n\t\t\t\t\t\trequest.workItemId,\n\t\t\t\t\t\trequestRefs,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.effectRunsByRequest.set(request.requestId, request.effectRunId);\n\t\t\t\tstate.seededEffectRunIds.add(request.effectRunId);\n\t\t\t\tconst run = effectRun({\n\t\t\t\t\teffectRunId: request.effectRunId,\n\t\t\t\t\tagentRunId: request.agentRunId,\n\t\t\t\t\tsubjectRefs: [ref(\"work-item\", request.workItemId)],\n\t\t\t\t\tgoal: request.goal,\n\t\t\t\t\tsourceRefs: [\n\t\t\t\t\t\tref(\"work-item\", request.workItemId),\n\t\t\t\t\t\tref(\"work-item-effect-request\", request.requestId),\n\t\t\t\t\t\t...(request.sourceRefs ?? []),\n\t\t\t\t\t],\n\t\t\t\t\tpolicyRefs: request.policyRefs,\n\t\t\t\t\tlimits: request.limits,\n\t\t\t\t\tcreatedBy: request.createdBy,\n\t\t\t\t\tcreatedAtMs: request.createdAtMs,\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t...(request.metadata ?? {}),\n\t\t\t\t\t\teffectKind: request.effectKind,\n\t\t\t\t\t\tidempotencyKey: request.idempotencyKey,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tstate.statusSeq += 1;\n\t\t\t\tstate.auditSeq += 1;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"effect-run\", effectRun: run } satisfies WorkItemEffectRunFact],\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: \"status\",\n\t\t\t\t\t\t\tstatus: {\n\t\t\t\t\t\t\t\tkind: \"work-item-status\",\n\t\t\t\t\t\t\t\tstatusId: `${request.workItemId}:effect-run-seeded:${state.statusSeq}`,\n\t\t\t\t\t\t\t\tworkItemId: request.workItemId,\n\t\t\t\t\t\t\t\teffectRunId: request.effectRunId,\n\t\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\t\tstate: \"effect-run-seeded\",\n\t\t\t\t\t\t\t\tsourceRefs: run.sourceRefs,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies WorkItemEffectRunFact,\n\t\t\t\t\t],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${request.workItemId}:effect-run-seeded:${state.auditSeq}`,\n\t\t\t\t\t\t\t\tkind: \"work-item-effect-run-seeded\",\n\t\t\t\t\t\t\t\tsubjectId: request.workItemId,\n\t\t\t\t\t\t\t\tsourceRefs: run.sourceRefs,\n\t\t\t\t\t\t\t\tmetadata: { effectRunId: request.effectRunId, effectKind: request.effectKind },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies WorkItemEffectRunFact,\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},\n\t\t{ name: `${name}/runtime`, factory: \"workItemEffectRunProjector\" },\n\t);\n\treturn {\n\t\teffectRuns: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/effectRuns`,\n\t\t\t\"workItemEffectRuns\",\n\t\t\t(fact) => (fact.kind === \"effect-run\" ? fact.effectRun : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"workItemEffectRunStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"workItemEffectRunIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(graph, runtime, `${name}/audit`, \"workItemEffectRunAudit\", (fact) =>\n\t\t\tfact.kind === \"audit\" ? fact.audit : undefined,\n\t\t),\n\t\tviews: graph.node<WorkItemEffectRequestViews>(\n\t\t\t[opts.effectRequests, runtime],\n\t\t\t(ctx) => {\n\t\t\t\tconst state = ctx.state.get<WorkItemEffectRunViewsState>() ?? {\n\t\t\t\t\tpendingEffectRequests: new Map<string, WorkItemEffectRequested>(),\n\t\t\t\t\tsettledRequestIds: new Set<string>(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\tconst request = raw as WorkItemEffectRequested;\n\t\t\t\t\tif (!state.settledRequestIds.has(request.requestId))\n\t\t\t\t\t\tstate.pendingEffectRequests.set(request.requestId, request);\n\t\t\t\t}\n\t\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\t\tconst fact = raw as WorkItemEffectRunFact;\n\t\t\t\t\tif (fact.kind === \"effect-run\") {\n\t\t\t\t\t\tfor (const request of state.pendingEffectRequests.values()) {\n\t\t\t\t\t\t\tif (request.effectRunId === fact.effectRun.effectRunId) {\n\t\t\t\t\t\t\t\tstate.pendingEffectRequests.delete(request.requestId);\n\t\t\t\t\t\t\t\tstate.settledRequestIds.add(request.requestId);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (fact.kind === \"issue\") {\n\t\t\t\t\t\tdeletePendingWorkItemEffectRequest(state, fact.issue.refs);\n\t\t\t\t\t\tstate.issues.push(fact.issue);\n\t\t\t\t\t} else if (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t\t}\n\t\t\t\tctx.state.set(state);\n\t\t\t\tctx.down([[\"DATA\", freezeWorkItemEffectRequestViews(state)]]);\n\t\t\t},\n\t\t\t{ name: `${name}/views`, factory: \"workItemEffectRequestViews\" },\n\t\t),\n\t};\n}\n\nexport function workItemEffectResultMapper(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly workItems: Node<WorkItemSeed>;\n\t\treadonly effectRuns: Node<EffectRun>;\n\t\treadonly effectRunResults: Node<EffectRunResult>;\n\t\treadonly effectRequests?: Node<WorkItemEffectRequested>;\n\t\treadonly mappingPolicies?: readonly Node<WorkItemEffectMappingPolicy>[];\n\t\treadonly now?: () => number;\n\t},\n): WorkItemEvidenceMapperBundle {\n\tconst name = opts.name ?? \"workItemEffectResultMapper\";\n\tconst policyDeps = opts.mappingPolicies ?? [];\n\tconst deps = [\n\t\topts.workItems,\n\t\topts.effectRuns,\n\t\topts.effectRunResults,\n\t\t...(opts.effectRequests === undefined ? [] : [opts.effectRequests]),\n\t\t...policyDeps,\n\t];\n\tconst effectRequestIndex = 3;\n\tconst policyStart = effectRequestIndex + (opts.effectRequests === undefined ? 0 : 1);\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<WorkItemEvidenceMapperFact>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<WorkItemEvidenceState>() ?? emptyWorkItemEvidenceState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst workItem = raw as WorkItemSeed;\n\t\t\t\tstate.workItems.set(workItem.workItemId, workItem);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst run = raw as EffectRun;\n\t\t\t\tstate.effectRuns.set(run.effectRunId, run);\n\t\t\t\tconst workItemRef = singleWorkItemRef([\n\t\t\t\t\t...(run.subjectRefs ?? []),\n\t\t\t\t\t...(run.sourceRefs ?? []),\n\t\t\t\t]);\n\t\t\t\tif (workItemRef !== undefined)\n\t\t\t\t\tstate.effectRunWorkItems.set(run.effectRunId, workItemRef.id);\n\t\t\t}\n\t\t\tif (opts.effectRequests !== undefined) {\n\t\t\t\tfor (const raw of depBatch(ctx, effectRequestIndex) ?? []) {\n\t\t\t\t\tconst request = raw as WorkItemEffectRequested;\n\t\t\t\t\tstate.pendingEffectRequests.set(request.requestId, request);\n\t\t\t\t\tconst existing = state.requestsByEffectRun.get(request.effectRunId);\n\t\t\t\t\tif (existing !== undefined && existing.requestId !== request.requestId) {\n\t\t\t\t\t\tconst ambiguous = state.ambiguousRequestsByEffectRun.get(request.effectRunId) ?? [\n\t\t\t\t\t\t\texisting,\n\t\t\t\t\t\t];\n\t\t\t\t\t\tif (!ambiguous.some((item) => item.requestId === request.requestId))\n\t\t\t\t\t\t\tambiguous.push(request);\n\t\t\t\t\t\tstate.ambiguousRequestsByEffectRun.set(request.effectRunId, ambiguous);\n\t\t\t\t\t\temitWorkItemEvidenceIssue(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t`duplicate-effect-request:${request.effectRunId}:${request.requestId}`,\n\t\t\t\t\t\t\t\"duplicate-work-item-effect-request\",\n\t\t\t\t\t\t\t`EffectRun '${request.effectRunId}' has multiple WorkItemEffectRequested facts`,\n\t\t\t\t\t\t\trequest.workItemId,\n\t\t\t\t\t\t\tuniqueSourceRefs(ambiguous.flatMap(workItemEffectRequestRefs)),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstate.requestsByEffectRun.set(request.effectRunId, request);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachPolicyDepBatch(ctx, policyStart, policyDeps.length, (raw) => {\n\t\t\t\tconst policy = raw as WorkItemEffectMappingPolicy;\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 2) ?? []) {\n\t\t\t\tconst result = raw as EffectRunResult;\n\t\t\t\tmapEffectRunResultToWorkItemEvidence(ctx, state, result, now());\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"workItemEffectResultMapper\" },\n\t);\n\treturn {\n\t\tevidence: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/evidence`,\n\t\t\t\"workItemEvidenceRecorded\",\n\t\t\t(fact) => (fact.kind === \"evidence\" ? fact.evidence : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"workItemEvidenceStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"workItemEvidenceIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(graph, runtime, `${name}/audit`, \"workItemEvidenceAudit\", (fact) =>\n\t\t\tfact.kind === \"audit\" ? fact.audit : undefined,\n\t\t),\n\t\tviews: graph.node<WorkItemEvidenceViews>(\n\t\t\t[...(opts.effectRequests === undefined ? [] : [opts.effectRequests]), runtime],\n\t\t\t(ctx) => {\n\t\t\t\tconst state = ctx.state.get<WorkItemEvidenceViewsState>() ?? {\n\t\t\t\t\tevidenceByWorkItem: new Map<string, WorkItemEvidenceRecorded[]>(),\n\t\t\t\t\tlatestEvidenceByEffectRun: new Map<string, WorkItemEvidenceRecorded>(),\n\t\t\t\t\tpendingEffectRequests: new Map<string, WorkItemEffectRequested>(),\n\t\t\t\t\tsettledEffectRunIds: new Set<string>(),\n\t\t\t\t\tsettledRequestIds: new Set<string>(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\t\tif (opts.effectRequests !== undefined) {\n\t\t\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\t\tconst request = raw as WorkItemEffectRequested;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!state.settledRequestIds.has(request.requestId) &&\n\t\t\t\t\t\t\t!state.settledEffectRunIds.has(request.effectRunId)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tstate.pendingEffectRequests.set(request.requestId, request);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst runtimeIndex = opts.effectRequests === undefined ? 0 : 1;\n\t\t\t\tfor (const raw of depBatch(ctx, runtimeIndex) ?? []) {\n\t\t\t\t\tconst fact = raw as WorkItemEvidenceMapperFact;\n\t\t\t\t\tif (fact.kind === \"evidence\") {\n\t\t\t\t\t\tconst evidence = fact.evidence;\n\t\t\t\t\t\tconst byWorkItem = state.evidenceByWorkItem.get(evidence.workItemId) ?? [];\n\t\t\t\t\t\tbyWorkItem.push(evidence);\n\t\t\t\t\t\tstate.evidenceByWorkItem.set(evidence.workItemId, byWorkItem);\n\t\t\t\t\t\tstate.latestEvidenceByEffectRun.set(evidence.effectRunId, evidence);\n\t\t\t\t\t\tfor (const request of state.pendingEffectRequests.values()) {\n\t\t\t\t\t\t\tif (request.effectRunId === evidence.effectRunId) {\n\t\t\t\t\t\t\t\tstate.pendingEffectRequests.delete(request.requestId);\n\t\t\t\t\t\t\t\tstate.settledRequestIds.add(request.requestId);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.settledEffectRunIds.add(evidence.effectRunId);\n\t\t\t\t\t} else if (fact.kind === \"issue\") {\n\t\t\t\t\t\tdeletePendingWorkItemEffectRequest(state, fact.issue.refs);\n\t\t\t\t\t\tstate.issues.push(fact.issue);\n\t\t\t\t\t} else if (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t\t}\n\t\t\t\tctx.state.set(state);\n\t\t\t\tctx.down([[\"DATA\", freezeWorkItemEvidenceViews(state)]]);\n\t\t\t},\n\t\t\t{ name: `${name}/views`, factory: \"workItemEvidenceViews\" },\n\t\t),\n\t};\n}\n\nexport function workItemDomainActionProposalProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly workItems: Node<WorkItemSeed>;\n\t\treadonly evidence: Node<WorkItemEvidenceRecorded>;\n\t\treadonly effectRunResults: Node<EffectRunResult>;\n\t\treadonly mappingPolicies: readonly Node<WorkItemEffectMappingPolicy>[];\n\t\treadonly now?: () => number;\n\t},\n): WorkItemDomainActionProposalBundle {\n\tconst name = opts.name ?? \"workItemDomainActionProposals\";\n\tconst now = opts.now ?? Date.now;\n\tconst policyStart = 3;\n\tconst runtime = graph.node<WorkItemDomainActionProposalFact>(\n\t\t[opts.workItems, opts.evidence, opts.effectRunResults, ...opts.mappingPolicies],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<WorkItemDomainActionProposalState>() ??\n\t\t\t\temptyWorkItemDomainActionProposalState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst workItem = raw as WorkItemSeed;\n\t\t\t\tstate.workItems.set(workItem.workItemId, workItem);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst evidence = raw as WorkItemEvidenceRecorded;\n\t\t\t\tif (state.evidence.has(evidence.evidenceId)) {\n\t\t\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-action-proposal-evidence:${evidence.evidenceId}`,\n\t\t\t\t\t\t\"duplicate-work-item-action-proposal-evidence\",\n\t\t\t\t\t\t`WorkItemEvidenceRecorded '${evidence.evidenceId}' was already seen by the action proposal projector`,\n\t\t\t\t\t\tevidence.workItemId,\n\t\t\t\t\t\tworkItemEvidenceOnlyRefs(evidence),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.evidence.set(evidence.evidenceId, evidence);\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 2) ?? []) {\n\t\t\t\tconst result = raw as EffectRunResult;\n\t\t\t\tif (state.results.has(result.resultId)) {\n\t\t\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-action-proposal-result:${result.resultId}`,\n\t\t\t\t\t\t\"duplicate-work-item-action-proposal-result\",\n\t\t\t\t\t\t`EffectRunResult '${result.resultId}' was already seen by the action proposal projector`,\n\t\t\t\t\t\tworkItemIdForEffectRunResult(state, result),\n\t\t\t\t\t\tworkItemResultRefs(result),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.results.set(result.resultId, result);\n\t\t\t}\n\t\t\tforEachPolicyDepBatch(ctx, policyStart, opts.mappingPolicies.length, (raw) => {\n\t\t\t\tconst policy = raw as WorkItemEffectMappingPolicy;\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tevaluateWorkItemDomainActionProposals(ctx, state, now());\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"workItemDomainActionProposalProjector\", partial: true },\n\t);\n\treturn {\n\t\tproposals: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/proposals`,\n\t\t\t\"workItemDomainActionProposals\",\n\t\t\t(fact) => (fact.kind === \"proposal\" ? fact.proposal : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"workItemDomainActionProposalStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"workItemDomainActionProposalIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"workItemDomainActionProposalAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: graph.node<WorkItemDomainActionProposalViews>(\n\t\t\t[runtime],\n\t\t\t(ctx) => {\n\t\t\t\tconst state = ctx.state.get<WorkItemDomainActionProposalViewsState>() ?? {\n\t\t\t\t\tproposalsByWorkItem: new Map<string, WorkItemDomainActionProposal[]>(),\n\t\t\t\t\tproposalsByEvidence: new Map<string, WorkItemDomainActionProposal[]>(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\tconst fact = raw as WorkItemDomainActionProposalFact;\n\t\t\t\t\tif (fact.kind === \"proposal\") {\n\t\t\t\t\t\tconst proposal = fact.proposal;\n\t\t\t\t\t\tconst byWorkItem = state.proposalsByWorkItem.get(proposal.workItemId) ?? [];\n\t\t\t\t\t\tbyWorkItem.push(proposal);\n\t\t\t\t\t\tstate.proposalsByWorkItem.set(proposal.workItemId, byWorkItem);\n\t\t\t\t\t\tconst byEvidence = state.proposalsByEvidence.get(proposal.evidenceId) ?? [];\n\t\t\t\t\t\tbyEvidence.push(proposal);\n\t\t\t\t\t\tstate.proposalsByEvidence.set(proposal.evidenceId, byEvidence);\n\t\t\t\t\t} else if (fact.kind === \"issue\") state.issues.push(fact.issue);\n\t\t\t\t\telse if (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t\t}\n\t\t\t\tctx.state.set(state);\n\t\t\t\tctx.down([[\"DATA\", freezeWorkItemDomainActionProposalViews(state)]]);\n\t\t\t},\n\t\t\t{ name: `${name}/views`, factory: \"workItemDomainActionProposalViews\" },\n\t\t),\n\t};\n}\n\nexport function workItemDomainActionAdmissionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly proposals: Node<WorkItemDomainActionProposal>;\n\t\treadonly decisions: Node<WorkItemDomainActionAdmissionDecision>;\n\t\treadonly admissionPolicies?: readonly Node<WorkItemDomainActionAdmissionPolicy>[];\n\t\treadonly now?: () => number;\n\t},\n): WorkItemDomainActionAdmissionBundle {\n\tconst name = opts.name ?? \"workItemDomainActionAdmissions\";\n\tconst policyDeps = opts.admissionPolicies ?? [];\n\tconst policyStart = 2;\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<WorkItemDomainActionAdmissionFact>(\n\t\t[opts.proposals, opts.decisions, ...policyDeps],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<WorkItemDomainActionAdmissionStateInternal>() ??\n\t\t\t\temptyWorkItemDomainActionAdmissionState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst proposal = raw as WorkItemDomainActionProposal;\n\t\t\t\tif (state.proposals.has(proposal.proposalId)) {\n\t\t\t\t\temitWorkItemAdmissionIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-admission-proposal:${proposal.proposalId}`,\n\t\t\t\t\t\t\"duplicate-work-item-domain-action-proposal\",\n\t\t\t\t\t\t`WorkItemDomainActionProposal '${proposal.proposalId}' was already seen by the admission projector`,\n\t\t\t\t\t\tproposal.workItemId,\n\t\t\t\t\t\tworkItemAdmissionProposalRefs(proposal),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.proposals.set(proposal.proposalId, proposal);\n\t\t\t}\n\t\t\tforEachPolicyDepBatch(ctx, policyStart, policyDeps.length, (raw) => {\n\t\t\t\tconst policy = raw as WorkItemDomainActionAdmissionPolicy;\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst decision = raw as WorkItemDomainActionAdmissionDecision;\n\t\t\t\tif (state.decisions.has(decision.decisionId)) {\n\t\t\t\t\temitWorkItemAdmissionIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-admission-decision:${decision.decisionId}`,\n\t\t\t\t\t\t\"duplicate-work-item-domain-action-admission-decision\",\n\t\t\t\t\t\t`WorkItemDomainActionAdmissionDecision '${decision.decisionId}' was already seen by the admission projector`,\n\t\t\t\t\t\tdecision.proposalId,\n\t\t\t\t\t\tworkItemAdmissionDecisionRefs(decision),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.decisions.set(decision.decisionId, decision);\n\t\t\t}\n\t\t\tevaluateWorkItemDomainActionAdmissions(ctx, state, now());\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"workItemDomainActionAdmissionProjector\", partial: true },\n\t);\n\treturn {\n\t\tadmissions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/admissions`,\n\t\t\t\"workItemDomainActionAdmissions\",\n\t\t\t(fact) => (fact.kind === \"admission\" ? fact.admission : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"workItemDomainActionAdmissionStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"workItemDomainActionAdmissionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"workItemDomainActionAdmissionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: graph.node<WorkItemDomainActionAdmissionViews>(\n\t\t\t[runtime],\n\t\t\t(ctx) => {\n\t\t\t\tconst state = ctx.state.get<WorkItemDomainActionAdmissionViewsState>() ?? {\n\t\t\t\t\tadmissionsByProposal: new Map<string, WorkItemDomainActionAdmission>(),\n\t\t\t\t\tadmissionsByWorkItem: new Map<string, WorkItemDomainActionAdmission[]>(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\t\tconst fact = raw as WorkItemDomainActionAdmissionFact;\n\t\t\t\t\tif (fact.kind === \"admission\") {\n\t\t\t\t\t\tconst admission = fact.admission;\n\t\t\t\t\t\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\t\t\t\t\t\tconst byWorkItem = state.admissionsByWorkItem.get(admission.workItemId) ?? [];\n\t\t\t\t\t\tbyWorkItem.push(admission);\n\t\t\t\t\t\tstate.admissionsByWorkItem.set(admission.workItemId, byWorkItem);\n\t\t\t\t\t} else if (fact.kind === \"issue\") state.issues.push(fact.issue);\n\t\t\t\t\telse if (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t\t}\n\t\t\t\tctx.state.set(state);\n\t\t\t\tctx.down([[\"DATA\", freezeWorkItemDomainActionAdmissionViews(state)]]);\n\t\t\t},\n\t\t\t{ name: `${name}/views`, factory: \"workItemDomainActionAdmissionViews\" },\n\t\t),\n\t};\n}\n\ntype WorkItemEffectRunFact =\n\t| { readonly kind: \"effect-run\"; readonly effectRun: EffectRun }\n\t| { readonly kind: \"status\"; readonly status: WorkItemStatusRecord }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ntype WorkItemEvidenceMapperFact =\n\t| { readonly kind: \"evidence\"; readonly evidence: WorkItemEvidenceRecorded }\n\t| { readonly kind: \"status\"; readonly status: WorkItemStatusRecord }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ntype WorkItemDomainActionProposalFact =\n\t| { readonly kind: \"proposal\"; readonly proposal: WorkItemDomainActionProposal }\n\t| { readonly kind: \"status\"; readonly status: WorkItemStatusRecord }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ntype WorkItemDomainActionAdmissionFact =\n\t| { readonly kind: \"admission\"; readonly admission: WorkItemDomainActionAdmission }\n\t| { readonly kind: \"status\"; readonly status: WorkItemStatusRecord }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ninterface WorkItemEffectRunState {\n\tworkItems: Map<string, WorkItemSeed>;\n\trequests: Map<string, WorkItemEffectRequested>;\n\teffectRunsByRequest: Map<string, string>;\n\tseededEffectRunIds: Set<string>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n\tissueKeys: Set<string>;\n\tstatusSeq: number;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\ninterface WorkItemEvidenceState {\n\tworkItems: Map<string, WorkItemSeed>;\n\teffectRuns: Map<string, EffectRun>;\n\teffectRunWorkItems: Map<string, string>;\n\tevidenceByWorkItem: Map<string, WorkItemEvidenceRecorded[]>;\n\tlatestEvidenceByEffectRun: Map<string, WorkItemEvidenceRecorded>;\n\tpendingEffectRequests: Map<string, WorkItemEffectRequested>;\n\trequestsByEffectRun: Map<string, WorkItemEffectRequested>;\n\tambiguousRequestsByEffectRun: Map<string, WorkItemEffectRequested[]>;\n\tpolicies: Map<string, WorkItemEffectMappingPolicy>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n\tissueKeys: Set<string>;\n\tstatusSeq: number;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\ninterface WorkItemDomainActionProposalState {\n\tworkItems: Map<string, WorkItemSeed>;\n\tevidence: Map<string, WorkItemEvidenceRecorded>;\n\tresults: Map<string, EffectRunResult>;\n\tpolicies: Map<string, WorkItemEffectMappingPolicy>;\n\tproposedKeys: Set<string>;\n\tissueKeys: Set<string>;\n\tstatusSeq: number;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\ninterface WorkItemDomainActionAdmissionStateInternal {\n\tproposals: Map<string, WorkItemDomainActionProposal>;\n\tpolicies: Map<string, WorkItemDomainActionAdmissionPolicy>;\n\tdecisions: Map<string, WorkItemDomainActionAdmissionDecision>;\n\tadmissionsById: Map<string, WorkItemDomainActionAdmission>;\n\tadmissionsByProposal: Map<string, WorkItemDomainActionAdmission>;\n\tterminalDecisionIds: Set<string>;\n\tissueKeys: Set<string>;\n\tstatusSeq: number;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\ninterface WorkItemEffectRunViewsState {\n\tpendingEffectRequests: Map<string, WorkItemEffectRequested>;\n\tsettledRequestIds: Set<string>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\ninterface WorkItemEvidenceViewsState {\n\tevidenceByWorkItem: Map<string, WorkItemEvidenceRecorded[]>;\n\tlatestEvidenceByEffectRun: Map<string, WorkItemEvidenceRecorded>;\n\tpendingEffectRequests: Map<string, WorkItemEffectRequested>;\n\tsettledEffectRunIds: Set<string>;\n\tsettledRequestIds: Set<string>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\ninterface WorkItemDomainActionProposalViewsState {\n\tproposalsByWorkItem: Map<string, WorkItemDomainActionProposal[]>;\n\tproposalsByEvidence: Map<string, WorkItemDomainActionProposal[]>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\ninterface WorkItemDomainActionAdmissionViewsState {\n\tadmissionsByProposal: Map<string, WorkItemDomainActionAdmission>;\n\tadmissionsByWorkItem: Map<string, WorkItemDomainActionAdmission[]>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\ninterface WorkItemMappingPolicyContext {\n\treadonly policyRefs: readonly SourceRef[];\n\treadonly effectKind?: string;\n}\n\nfunction mapEffectRunResultToWorkItemEvidence(\n\tctx: Ctx,\n\tstate: WorkItemEvidenceState,\n\tresult: EffectRunResult,\n\trecordedAtMs: number,\n): void {\n\tconst run = state.effectRuns.get(result.effectRunId);\n\tif (run === undefined) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unknown-effect-run:${result.resultId}`,\n\t\t\t\"unknown-effect-run-result\",\n\t\t\t`EffectRunResult '${result.resultId}' references unknown EffectRun '${result.effectRunId}'`,\n\t\t\tresult.effectRunId,\n\t\t\tresult.sourceRefs,\n\t\t);\n\t\treturn;\n\t}\n\tconst staleEffectRunRef = (result.sourceRefs ?? []).find(\n\t\t(sourceRef) => sourceRef.kind === \"effect-run\" && sourceRef.id !== result.effectRunId,\n\t);\n\tif (staleEffectRunRef !== undefined) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-effect-run-ref:${result.resultId}`,\n\t\t\t\"stale-effect-run-source-ref\",\n\t\t\t`EffectRunResult '${result.resultId}' carries a stale EffectRun source ref '${staleEffectRunRef.id}'`,\n\t\t\tresult.effectRunId,\n\t\t\tresult.sourceRefs,\n\t\t);\n\t\treturn;\n\t}\n\tconst runWorkItemRef = singleWorkItemRef([...(run.subjectRefs ?? []), ...(run.sourceRefs ?? [])]);\n\tconst resultWorkItemRefs = distinctWorkItemRefs([\n\t\t...(result.subjectRefs ?? []),\n\t\t...(result.sourceRefs ?? []),\n\t]);\n\tif (resultWorkItemRefs.length > 1) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`ambiguous-work-item-ref:${result.resultId}`,\n\t\t\t\"stale-work-item-source-ref\",\n\t\t\t`EffectRunResult '${result.resultId}' carries multiple WorkItem refs`,\n\t\t\tresultWorkItemRefs[0]?.id,\n\t\t\tworkItemResultRefs(result),\n\t\t);\n\t\treturn;\n\t}\n\tconst resultWorkItemRef = resultWorkItemRefs[0];\n\tif (\n\t\trunWorkItemRef !== undefined &&\n\t\tresultWorkItemRef !== undefined &&\n\t\trunWorkItemRef.id !== resultWorkItemRef.id\n\t) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-work-item-ref:${result.resultId}`,\n\t\t\t\"stale-work-item-source-ref\",\n\t\t\t`EffectRunResult '${result.resultId}' WorkItem ref '${resultWorkItemRef.id}' does not match EffectRun '${result.effectRunId}'`,\n\t\t\tresultWorkItemRef.id,\n\t\t\tworkItemResultRefs(result),\n\t\t);\n\t\treturn;\n\t}\n\tconst workItemId =\n\t\tresultWorkItemRef?.id ?? runWorkItemRef?.id ?? state.effectRunWorkItems.get(result.effectRunId);\n\tif (workItemId === undefined) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-work-item-ref:${result.resultId}`,\n\t\t\t\"missing-work-item-source-ref\",\n\t\t\t`EffectRunResult '${result.resultId}' cannot be mapped without a WorkItem source ref`,\n\t\t\tresult.effectRunId,\n\t\t\tworkItemResultRefs(result),\n\t\t);\n\t\treturn;\n\t}\n\tif (!state.workItems.has(workItemId)) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unknown-work-item:${result.resultId}`,\n\t\t\t\"unknown-work-item-evidence-target\",\n\t\t\t`EffectRunResult '${result.resultId}' references unseeded WorkItem '${workItemId}'`,\n\t\t\tworkItemId,\n\t\t\tworkItemResultRefs(result),\n\t\t);\n\t\treturn;\n\t}\n\tconst request = state.requestsByEffectRun.get(result.effectRunId);\n\tconst ambiguousRequests = state.ambiguousRequestsByEffectRun.get(result.effectRunId);\n\tif (ambiguousRequests !== undefined) {\n\t\tconst refs = uniqueSourceRefs([\n\t\t\t...workItemResultRefs(result),\n\t\t\t...ambiguousRequests.flatMap(workItemEffectRequestRefs),\n\t\t]);\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`ambiguous-effect-request:${result.effectRunId}:${result.resultId}`,\n\t\t\t\"duplicate-work-item-effect-request\",\n\t\t\t`EffectRun '${result.effectRunId}' has ambiguous WorkItemEffectRequested facts`,\n\t\t\tworkItemId,\n\t\t\trefs,\n\t\t);\n\t\tclearPendingWorkItemEffectRequestsForRun(state, result.effectRunId);\n\t\treturn;\n\t}\n\tconst policyIssue = workItemMappingPolicyIssue(state, request, run);\n\tif (policyIssue !== undefined) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`${policyIssue.code}:${result.resultId}`,\n\t\t\tpolicyIssue.code,\n\t\t\tpolicyIssue.message,\n\t\t\tworkItemId,\n\t\t\tworkItemMappingPolicyIssueRefs(result, run, request),\n\t\t);\n\t\tclearPendingWorkItemEffectRequestsForRun(state, result.effectRunId);\n\t\treturn;\n\t}\n\tif (state.latestEvidenceByEffectRun.has(result.effectRunId)) {\n\t\temitWorkItemEvidenceIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-evidence:${result.effectRunId}:${result.resultId}`,\n\t\t\t\"duplicate-work-item-evidence\",\n\t\t\t`EffectRun '${result.effectRunId}' already recorded WorkItem evidence`,\n\t\t\tworkItemId,\n\t\t\tworkItemResultRefs(result),\n\t\t);\n\t\treturn;\n\t}\n\tconst evidence = workItemEvidenceFromResult(result, run, workItemId, request, recordedAtMs);\n\tconst byWorkItem = state.evidenceByWorkItem.get(workItemId) ?? [];\n\tbyWorkItem.push(evidence);\n\tstate.evidenceByWorkItem.set(workItemId, byWorkItem);\n\tstate.latestEvidenceByEffectRun.set(result.effectRunId, evidence);\n\tclearPendingWorkItemEffectRequestsForRun(state, result.effectRunId);\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst refs = evidence.sourceRefs;\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${workItemId}:evidence-recorded:${state.statusSeq}`,\n\t\tworkItemId,\n\t\tstate: \"evidence-recorded\",\n\t\tsourceRefs: refs,\n\t\teffectRunId: result.effectRunId,\n\t\tevidenceId: evidence.evidenceId,\n\t\tissues: result.issues,\n\t\tmetadata: { resultStatus: result.status },\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${workItemId}:evidence-recorded:${state.auditSeq}`,\n\t\tkind: \"work-item-evidence-recorded\",\n\t\tsubjectId: workItemId,\n\t\tsourceRefs: refs,\n\t\tmetadata: {\n\t\t\teffectRunId: result.effectRunId,\n\t\t\teffectRunResultId: result.resultId,\n\t\t\tresultStatus: result.status,\n\t\t},\n\t};\n\tstate.audit.push(audit);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"evidence\", evidence } satisfies WorkItemEvidenceMapperFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemEvidenceMapperFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemEvidenceMapperFact],\n\t]);\n}\n\nfunction evaluateWorkItemDomainActionProposals(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionProposalState,\n\tproposedAtMs: number,\n): void {\n\tfor (const evidence of state.evidence.values()) {\n\t\tconst result = state.results.get(evidence.effectRunResultId);\n\t\tif (result === undefined) {\n\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`missing-action-proposal-result:${evidence.evidenceId}:${evidence.effectRunResultId}`,\n\t\t\t\t\"missing-work-item-action-proposal-result\",\n\t\t\t\t`WorkItemEvidenceRecorded '${evidence.evidenceId}' references missing EffectRunResult '${evidence.effectRunResultId}'`,\n\t\t\t\tevidence.workItemId,\n\t\t\t\tworkItemEvidenceOnlyRefs(evidence),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.effectRunId !== evidence.effectRunId || result.status !== evidence.status) {\n\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`stale-action-proposal-result:${evidence.evidenceId}:${result.resultId}`,\n\t\t\t\t\"stale-work-item-action-proposal-result\",\n\t\t\t\t`WorkItemEvidenceRecorded '${evidence.evidenceId}' does not match EffectRunResult '${result.resultId}'`,\n\t\t\t\tevidence.workItemId,\n\t\t\t\tworkItemActionProposalRefs(evidence, result),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!state.workItems.has(evidence.workItemId)) {\n\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`unknown-action-proposal-work-item:${evidence.evidenceId}`,\n\t\t\t\t\"unknown-work-item-action-proposal-target\",\n\t\t\t\t`WorkItemEvidenceRecorded '${evidence.evidenceId}' references unseeded WorkItem '${evidence.workItemId}'`,\n\t\t\t\tevidence.workItemId,\n\t\t\t\tworkItemActionProposalRefs(evidence, result),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst policyIds = referencedWorkItemMappingPolicyIds(evidence);\n\t\tfor (const policyId of policyIds) {\n\t\t\tconst policy = state.policies.get(policyId);\n\t\t\tif (policy === undefined) {\n\t\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\t\tctx,\n\t\t\t\t\tstate,\n\t\t\t\t\t`missing-action-proposal-policy:${evidence.evidenceId}:${policyId}`,\n\t\t\t\t\t\"missing-work-item-action-proposal-policy\",\n\t\t\t\t\t`WorkItemEffectMappingPolicy '${policyId}' was referenced for WorkItem action proposals but not present`,\n\t\t\t\t\tevidence.workItemId,\n\t\t\t\t\tworkItemActionProposalRefs(evidence, result),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst effectKind =\n\t\t\t\teffectKindFromMetadata(evidence.metadata) ?? effectKindFromMetadata(result.metadata);\n\t\t\tif (!policyAppliesToRequest(policy, effectKind)) {\n\t\t\t\temitWorkItemActionProposalIssue(\n\t\t\t\t\tctx,\n\t\t\t\t\tstate,\n\t\t\t\t\t`action-proposal-policy-mismatch:${evidence.evidenceId}:${policy.policyId}`,\n\t\t\t\t\t\"work-item-action-proposal-policy-mismatch\",\n\t\t\t\t\t`WorkItemEffectMappingPolicy '${policy.policyId}' does not apply to effectKind '${effectKind ?? \"unknown\"}'`,\n\t\t\t\t\tevidence.workItemId,\n\t\t\t\t\tworkItemActionProposalRefs(evidence, result, policy),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const [index, spec] of (policy.actionProposals ?? []).entries()) {\n\t\t\t\temitWorkItemDomainActionProposal(\n\t\t\t\t\tctx,\n\t\t\t\t\tstate,\n\t\t\t\t\tevidence,\n\t\t\t\t\tresult,\n\t\t\t\t\tpolicy,\n\t\t\t\t\tspec,\n\t\t\t\t\tindex,\n\t\t\t\t\tproposedAtMs,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction emitWorkItemDomainActionProposal(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionProposalState,\n\tevidence: WorkItemEvidenceRecorded,\n\tresult: EffectRunResult,\n\tpolicy: WorkItemEffectMappingPolicy,\n\tspec: WorkItemDomainActionProposalSpec,\n\tindex: number,\n\tproposedAtMs: number,\n): void {\n\tconst key = `${evidence.evidenceId}:${policy.policyId}:${index}:${spec.actionKind}`;\n\tif (state.proposedKeys.has(key)) return;\n\tif (spec.behavior !== undefined && spec.behavior !== \"propose\") {\n\t\temitWorkItemActionProposalIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unsupported-action-proposal-behavior:${key}`,\n\t\t\t\"unsupported-work-item-action-proposal-behavior\",\n\t\t\t`WorkItemEffectMappingPolicy '${policy.policyId}' uses unsupported action proposal behavior '${spec.behavior}'`,\n\t\t\tevidence.workItemId,\n\t\t\tworkItemActionProposalRefs(evidence, result, policy),\n\t\t);\n\t\treturn;\n\t}\n\tif (spec.actionKind.length === 0) {\n\t\temitWorkItemActionProposalIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`malformed-action-proposal:${key}`,\n\t\t\t\"malformed-work-item-action-proposal\",\n\t\t\t`WorkItemEffectMappingPolicy '${policy.policyId}' has an empty actionKind`,\n\t\t\tevidence.workItemId,\n\t\t\tworkItemActionProposalRefs(evidence, result, policy),\n\t\t);\n\t\treturn;\n\t}\n\tif (spec.statuses !== undefined && !spec.statuses.includes(evidence.status)) return;\n\tconst outputKind = evidence.output?.kind;\n\tif (\n\t\tspec.outputKinds !== undefined &&\n\t\t(outputKind === undefined || !spec.outputKinds.includes(outputKind))\n\t)\n\t\treturn;\n\tstate.proposedKeys.add(key);\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst proposal: WorkItemDomainActionProposal = {\n\t\tkind: \"work-item-domain-action-proposal\",\n\t\tproposalId: `${evidence.workItemId}:${evidence.effectRunId}:${evidence.effectRunResultId}:${policy.policyId}:${index}:${spec.actionKind}`,\n\t\tworkItemId: evidence.workItemId,\n\t\tactionKind: spec.actionKind,\n\t\teffectRunId: evidence.effectRunId,\n\t\teffectRunResultId: evidence.effectRunResultId,\n\t\tevidenceId: evidence.evidenceId,\n\t\tpolicyId: policy.policyId,\n\t\tpayload: workItemActionProposalPayload(spec, evidence, result),\n\t\treason: spec.reason ?? evidence.reason ?? resultReason(result),\n\t\tsourceRefs: workItemActionProposalRefs(evidence, result, policy),\n\t\tproposedAtMs,\n\t\tmetadata: {\n\t\t\t...(policy.metadata ?? {}),\n\t\t\t...(spec.metadata ?? {}),\n\t\t\tresultStatus: evidence.status,\n\t\t},\n\t};\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${evidence.workItemId}:domain-action-proposed:${state.statusSeq}`,\n\t\tworkItemId: evidence.workItemId,\n\t\tstate: \"domain-action-proposed\",\n\t\tsourceRefs: proposal.sourceRefs,\n\t\teffectRunId: evidence.effectRunId,\n\t\tevidenceId: evidence.evidenceId,\n\t\tproposalId: proposal.proposalId,\n\t\tmetadata: { actionKind: spec.actionKind, policyId: policy.policyId },\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${evidence.workItemId}:domain-action-proposed:${state.auditSeq}`,\n\t\tkind: \"work-item-domain-action-proposed\",\n\t\tsubjectId: evidence.workItemId,\n\t\tsourceRefs: proposal.sourceRefs,\n\t\tmetadata: {\n\t\t\tactionKind: spec.actionKind,\n\t\t\teffectRunId: evidence.effectRunId,\n\t\t\teffectRunResultId: evidence.effectRunResultId,\n\t\t\tevidenceId: evidence.evidenceId,\n\t\t\tpolicyId: policy.policyId,\n\t\t\tproposalId: proposal.proposalId,\n\t\t},\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"proposal\", proposal } satisfies WorkItemDomainActionProposalFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemDomainActionProposalFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemDomainActionProposalFact],\n\t]);\n}\n\nfunction evaluateWorkItemDomainActionAdmissions(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionAdmissionStateInternal,\n\tadmittedAtMs: number,\n): void {\n\tlet emitted = true;\n\tlet passes = 0;\n\twhile (emitted && passes <= state.decisions.size) {\n\t\temitted = false;\n\t\tpasses += 1;\n\t\tfor (const decision of state.decisions.values()) {\n\t\t\tif (state.terminalDecisionIds.has(decision.decisionId)) continue;\n\t\t\temitted =\n\t\t\t\tevaluateWorkItemDomainActionAdmission(ctx, state, decision, admittedAtMs) || emitted;\n\t\t}\n\t}\n}\n\nfunction evaluateWorkItemDomainActionAdmission(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionAdmissionStateInternal,\n\tdecision: WorkItemDomainActionAdmissionDecision,\n\tadmittedAtMs: number,\n): boolean {\n\tconst proposal = state.proposals.get(decision.proposalId);\n\tconst proposalRefs = workItemAdmissionDecisionRefs(decision, proposal);\n\tconst subjectId = proposal?.workItemId ?? decision.proposalId;\n\tif (proposal === undefined) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-admission-proposal:${decision.decisionId}:${decision.proposalId}`,\n\t\t\t\"missing-work-item-domain-action-admission-proposal\",\n\t\t\t`WorkItemDomainActionAdmissionDecision '${decision.decisionId}' references missing proposal '${decision.proposalId}'`,\n\t\t\tsubjectId,\n\t\t\tproposalRefs,\n\t\t);\n\t\treturn false;\n\t}\n\tconst staleProposalRef = (decision.sourceRefs ?? []).find(\n\t\t(sourceRef) =>\n\t\t\tsourceRef.kind === \"work-item-domain-action-proposal\" &&\n\t\t\tsourceRef.id !== decision.proposalId &&\n\t\t\tsourceRef.id !== decision.targetProposalId,\n\t);\n\tif (staleProposalRef !== undefined) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-admission-proposal-ref:${decision.decisionId}:${staleProposalRef.id}`,\n\t\t\t\"stale-work-item-domain-action-admission-proposal-ref\",\n\t\t\t`WorkItemDomainActionAdmissionDecision '${decision.decisionId}' carries stale proposal ref '${staleProposalRef.id}'`,\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tconst policy = admissionPolicyForDecision(state, decision);\n\tif (typeof policy === \"string\") {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`${policy}:${decision.decisionId}:${decision.policyId ?? \"missing\"}`,\n\t\t\tpolicy,\n\t\t\tadmissionPolicyIssueMessage(policy, decision),\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tif (policy === \"stale-work-item-domain-action-admission-policy-ref\")\n\t\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tif (policy !== undefined) {\n\t\tconst policyIssue = validateWorkItemAdmissionPolicy(policy, decision, proposal);\n\t\tif (policyIssue !== undefined) {\n\t\t\temitWorkItemAdmissionIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`${policyIssue.code}:${decision.decisionId}:${policy.policyId}`,\n\t\t\t\tpolicyIssue.code,\n\t\t\t\tpolicyIssue.message,\n\t\t\t\tproposal.workItemId,\n\t\t\t\tworkItemAdmissionDecisionRefs(decision, proposal, policy),\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t}\n\tconst mergeIssue = validateWorkItemAdmissionMergeTarget(state, decision);\n\tif (mergeIssue !== undefined) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`${mergeIssue.code}:${decision.decisionId}:${decision.targetProposalId ?? \"\"}:${decision.targetAdmissionId ?? \"\"}`,\n\t\t\tmergeIssue.code,\n\t\t\tmergeIssue.message,\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tif (mergeIssue.code !== \"unknown-work-item-domain-action-admission-merge-target\")\n\t\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tif (state.admissionsById.has(decision.admissionId)) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-id:${decision.admissionId}`,\n\t\t\t\"duplicate-work-item-domain-action-admission\",\n\t\t\t`WorkItemDomainActionAdmission '${decision.admissionId}' was already emitted`,\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tif (state.admissionsByProposal.has(decision.proposalId)) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-proposal-decision:${decision.proposalId}:${decision.decisionId}`,\n\t\t\t\"duplicate-work-item-domain-action-admission-proposal\",\n\t\t\t`WorkItemDomainActionProposal '${decision.proposalId}' already has an admission decision`,\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tconst admissionState = admissionStateForOutcome(decision.outcome);\n\tif (admissionState === undefined) {\n\t\temitWorkItemAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unsupported-admission-outcome:${decision.decisionId}:${String(decision.outcome)}`,\n\t\t\t\"unsupported-work-item-domain-action-admission-outcome\",\n\t\t\t`WorkItemDomainActionAdmissionDecision '${decision.decisionId}' uses unsupported outcome '${String(decision.outcome)}'`,\n\t\t\tproposal.workItemId,\n\t\t\tproposalRefs,\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn false;\n\t}\n\tconst admission: WorkItemDomainActionAdmission = {\n\t\tkind: \"work-item-domain-action-admission\",\n\t\tadmissionId: decision.admissionId,\n\t\tproposalId: proposal.proposalId,\n\t\tworkItemId: proposal.workItemId,\n\t\tactionKind: proposal.actionKind,\n\t\tstate: admissionState,\n\t\tdecisionId: decision.decisionId,\n\t\tpolicyId: decision.policyId,\n\t\treason: decision.reason,\n\t\ttargetProposalId: decision.targetProposalId,\n\t\ttargetAdmissionId: decision.targetAdmissionId,\n\t\tsourceRefs: workItemAdmissionDecisionRefs(decision, proposal, policy),\n\t\tadmittedAtMs: decision.decidedAtMs ?? admittedAtMs,\n\t\tmetadata: {\n\t\t\t...(proposal.metadata ?? {}),\n\t\t\t...(policy?.metadata ?? {}),\n\t\t\t...(decision.metadata ?? {}),\n\t\t},\n\t};\n\tstate.admissionsById.set(admission.admissionId, admission);\n\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\tstate.terminalDecisionIds.add(decision.decisionId);\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst statusState = workItemAdmissionStatusState(admission.state);\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${proposal.workItemId}:${statusState}:${state.statusSeq}`,\n\t\tworkItemId: proposal.workItemId,\n\t\tstate: statusState,\n\t\tsourceRefs: admission.sourceRefs,\n\t\teffectRunId: proposal.effectRunId,\n\t\tevidenceId: proposal.evidenceId,\n\t\tproposalId: proposal.proposalId,\n\t\tmetadata: {\n\t\t\tactionKind: proposal.actionKind,\n\t\t\tadmissionId: admission.admissionId,\n\t\t\tdecisionId: decision.decisionId,\n\t\t\tpolicyId: decision.policyId,\n\t\t},\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${proposal.workItemId}:${statusState}:${state.auditSeq}`,\n\t\tkind: `work-item-domain-action-${admission.state}`,\n\t\tsubjectId: proposal.workItemId,\n\t\tsourceRefs: admission.sourceRefs,\n\t\tmetadata: {\n\t\t\tactionKind: proposal.actionKind,\n\t\t\tadmissionId: admission.admissionId,\n\t\t\tdecisionId: decision.decisionId,\n\t\t\tpolicyId: decision.policyId,\n\t\t\tproposalId: proposal.proposalId,\n\t\t},\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"admission\", admission } satisfies WorkItemDomainActionAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemDomainActionAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemDomainActionAdmissionFact],\n\t]);\n\treturn true;\n}\n\nfunction workItemEvidenceFromResult(\n\tresult: EffectRunResult,\n\trun: EffectRun,\n\tworkItemId: string,\n\trequest: WorkItemEffectRequested | undefined,\n\trecordedAtMs: number,\n): WorkItemEvidenceRecorded {\n\tconst base = {\n\t\tkind: \"work-item-evidence-recorded\",\n\t\tevidenceId: `${workItemId}:${result.effectRunId}:${result.resultId}`,\n\t\tworkItemId,\n\t\trequestId: request?.requestId,\n\t\teffectRunId: result.effectRunId,\n\t\teffectRunResultId: result.resultId,\n\t\texecutionInputRevision: request?.executionInputRevision,\n\t\tplanId: request?.planId,\n\t\tplanMemberId: request?.planMemberId,\n\t\tstatus: result.status,\n\t\tsourceRefs: uniqueSourceRefs([\n\t\t\tref(\"work-item\", workItemId),\n\t\t\tref(\"effect-run\", result.effectRunId),\n\t\t\tref(\"effect-run-result\", result.resultId),\n\t\t\t...(run.sourceRefs ?? []),\n\t\t\t...(run.subjectRefs ?? []),\n\t\t\t...(run.policyRefs ?? []),\n\t\t\t...(result.sourceRefs ?? []),\n\t\t\t...(result.subjectRefs ?? []),\n\t\t]),\n\t\tissues: result.issues,\n\t\tauditRefs: result.auditRefs,\n\t\trecordedAtMs,\n\t\tmetadata: {\n\t\t\t...(result.metadata ?? {}),\n\t\t\t...(request?.requestId === undefined ? {} : { requestId: request.requestId }),\n\t\t\t...(request?.executionInputRevision === undefined\n\t\t\t\t? {}\n\t\t\t\t: { executionInputRevision: request.executionInputRevision }),\n\t\t\t...(request?.planId === undefined ? {} : { planId: request.planId }),\n\t\t\t...(request?.planMemberId === undefined ? {} : { planMemberId: request.planMemberId }),\n\t\t},\n\t} satisfies Omit<WorkItemEvidenceRecorded, \"output\" | \"error\" | \"needs\" | \"reason\" | \"timeoutMs\">;\n\tif (result.status === \"completed\") return { ...base, output: result.output };\n\tif (result.status === \"failed\") return { ...base, error: result.error };\n\tif (result.status === \"blocked\") return { ...base, needs: result.needs };\n\tif (result.status === \"timeout\") return { ...base, timeoutMs: result.timeoutMs };\n\tif (result.status === \"canceled\" || result.status === \"waived\")\n\t\treturn { ...base, reason: result.reason };\n\treturn base;\n}\n\nfunction workItemMappingPolicyIssue(\n\tstate: WorkItemEvidenceState,\n\trequest: WorkItemEffectRequested | undefined,\n\trun: EffectRun,\n): { readonly code: string; readonly message: string } | undefined {\n\tconst context = workItemMappingPolicyContext(request, run);\n\tconst referencedPolicyIds = context.policyRefs\n\t\t.filter((sourceRef) => sourceRef.kind === \"work-item-effect-mapping-policy\")\n\t\t.map((sourceRef) => sourceRef.id);\n\tfor (const policyId of referencedPolicyIds) {\n\t\tconst policy = state.policies.get(policyId);\n\t\tif (policy === undefined) {\n\t\t\treturn {\n\t\t\t\tcode: \"missing-work-item-effect-mapping-policy\",\n\t\t\t\tmessage: `WorkItemEffectMappingPolicy '${policyId}' was required but not present`,\n\t\t\t};\n\t\t}\n\t\tconst issue = validateWorkItemMappingPolicy(policy, context.effectKind);\n\t\tif (issue !== undefined) return issue;\n\t}\n\treturn undefined;\n}\n\nfunction validateWorkItemMappingPolicy(\n\tpolicy: WorkItemEffectMappingPolicy,\n\teffectKind: string | undefined,\n): { readonly code: string; readonly message: string } | undefined {\n\tif (!policyAppliesToRequest(policy, effectKind)) {\n\t\treturn {\n\t\t\tcode: \"work-item-effect-mapping-policy-mismatch\",\n\t\t\tmessage: `WorkItemEffectMappingPolicy '${policy.policyId}' does not apply to effectKind '${effectKind ?? \"unknown\"}'`,\n\t\t};\n\t}\n\tconst behavior = policy.evidence?.behavior ?? \"record\";\n\tif (behavior !== \"record\") {\n\t\treturn {\n\t\t\tcode: \"unsupported-work-item-evidence-behavior\",\n\t\t\tmessage: `WorkItemEffectMappingPolicy '${policy.policyId}' uses unsupported evidence behavior '${behavior}'`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction admissionPolicyForDecision(\n\tstate: WorkItemDomainActionAdmissionStateInternal,\n\tdecision: WorkItemDomainActionAdmissionDecision,\n):\n\t| WorkItemDomainActionAdmissionPolicy\n\t| \"missing-work-item-domain-action-admission-policy\"\n\t| \"stale-work-item-domain-action-admission-policy-ref\"\n\t| undefined {\n\tif (decision.policyId === undefined) return undefined;\n\tconst stalePolicyRef = (decision.sourceRefs ?? []).find(\n\t\t(sourceRef) =>\n\t\t\tsourceRef.kind === \"work-item-domain-action-admission-policy\" &&\n\t\t\tsourceRef.id !== decision.policyId,\n\t);\n\tif (stalePolicyRef !== undefined) return \"stale-work-item-domain-action-admission-policy-ref\";\n\treturn (\n\t\tstate.policies.get(decision.policyId) ?? \"missing-work-item-domain-action-admission-policy\"\n\t);\n}\n\nfunction admissionPolicyIssueMessage(\n\tcode:\n\t\t| \"missing-work-item-domain-action-admission-policy\"\n\t\t| \"stale-work-item-domain-action-admission-policy-ref\",\n\tdecision: WorkItemDomainActionAdmissionDecision,\n): string {\n\tif (code === \"missing-work-item-domain-action-admission-policy\") {\n\t\treturn `WorkItemDomainActionAdmissionPolicy '${decision.policyId}' was referenced for WorkItem action admission but not present`;\n\t}\n\treturn `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' carries a stale admission policy source ref`;\n}\n\nfunction validateWorkItemAdmissionPolicy(\n\tpolicy: WorkItemDomainActionAdmissionPolicy,\n\tdecision: WorkItemDomainActionAdmissionDecision,\n\tproposal: WorkItemDomainActionProposal,\n): { readonly code: string; readonly message: string } | undefined {\n\tif (policy.actionKinds !== undefined && !policy.actionKinds.includes(proposal.actionKind)) {\n\t\treturn {\n\t\t\tcode: \"work-item-domain-action-admission-policy-mismatch\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionPolicy '${policy.policyId}' does not apply to actionKind '${proposal.actionKind}'`,\n\t\t};\n\t}\n\tif (policy.allowedOutcomes !== undefined && !policy.allowedOutcomes.includes(decision.outcome)) {\n\t\treturn {\n\t\t\tcode: \"unsupported-work-item-domain-action-admission-outcome\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionPolicy '${policy.policyId}' does not allow outcome '${decision.outcome}'`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction validateWorkItemAdmissionMergeTarget(\n\tstate: WorkItemDomainActionAdmissionStateInternal,\n\tdecision: WorkItemDomainActionAdmissionDecision,\n): { readonly code: string; readonly message: string } | undefined {\n\tconst hasTargetProposal = decision.targetProposalId !== undefined;\n\tconst hasTargetAdmission = decision.targetAdmissionId !== undefined;\n\tif (decision.outcome !== \"merge\") {\n\t\tif (hasTargetProposal || hasTargetAdmission) {\n\t\t\treturn {\n\t\t\t\tcode: \"ambiguous-work-item-domain-action-admission-merge-target\",\n\t\t\t\tmessage: `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' carries a merge target for non-merge outcome '${decision.outcome}'`,\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (hasTargetProposal === hasTargetAdmission) {\n\t\treturn {\n\t\t\tcode: \"ambiguous-work-item-domain-action-admission-merge-target\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' must reference exactly one merge target`,\n\t\t};\n\t}\n\tif (decision.targetProposalId === decision.proposalId) {\n\t\treturn {\n\t\t\tcode: \"ambiguous-work-item-domain-action-admission-merge-target\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' cannot merge a proposal into itself`,\n\t\t};\n\t}\n\tif (decision.targetProposalId !== undefined && !state.proposals.has(decision.targetProposalId)) {\n\t\treturn {\n\t\t\tcode: \"unknown-work-item-domain-action-admission-merge-target\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' references unknown target proposal '${decision.targetProposalId}'`,\n\t\t};\n\t}\n\tif (\n\t\tdecision.targetAdmissionId !== undefined &&\n\t\t!state.admissionsById.has(decision.targetAdmissionId)\n\t) {\n\t\treturn {\n\t\t\tcode: \"unknown-work-item-domain-action-admission-merge-target\",\n\t\t\tmessage: `WorkItemDomainActionAdmissionDecision '${decision.decisionId}' references unknown target admission '${decision.targetAdmissionId}'`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction admissionStateForOutcome(\n\toutcome: WorkItemDomainActionAdmissionOutcome,\n): WorkItemDomainActionAdmissionState | undefined {\n\tif (outcome === \"admit\") return \"admitted\";\n\tif (outcome === \"reject\") return \"rejected\";\n\tif (outcome === \"defer\") return \"deferred\";\n\tif (outcome === \"merge\") return \"merged\";\n\treturn undefined;\n}\n\nfunction workItemAdmissionStatusState(\n\tstate: WorkItemDomainActionAdmissionState,\n): WorkItemStatusRecord[\"state\"] {\n\tif (state === \"admitted\") return \"domain-action-admitted\";\n\tif (state === \"rejected\") return \"domain-action-rejected\";\n\tif (state === \"deferred\") return \"domain-action-deferred\";\n\treturn \"domain-action-merged\";\n}\n\nfunction policyAppliesToRequest(\n\tpolicy: WorkItemEffectMappingPolicy,\n\teffectKind: string | undefined,\n): boolean {\n\treturn (\n\t\tpolicy.effectKinds === undefined ||\n\t\t(effectKind !== undefined && policy.effectKinds.includes(effectKind))\n\t);\n}\n\nfunction workItemMappingPolicyContext(\n\trequest: WorkItemEffectRequested | undefined,\n\trun: EffectRun,\n): WorkItemMappingPolicyContext {\n\treturn {\n\t\tpolicyRefs: request?.policyRefs ?? run.policyRefs ?? [],\n\t\teffectKind: request?.effectKind ?? effectKindFromRun(run),\n\t};\n}\n\nfunction effectKindFromRun(run: EffectRun): string | undefined {\n\tconst effectKind = run.metadata?.effectKind;\n\treturn typeof effectKind === \"string\" ? effectKind : undefined;\n}\n\nfunction workItemMappingPolicyIssueRefs(\n\tresult: EffectRunResult,\n\trun: EffectRun,\n\trequest: WorkItemEffectRequested | undefined,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\t...workItemResultRefs(result),\n\t\t...(request === undefined\n\t\t\t? [...(run.sourceRefs ?? []), ...(run.subjectRefs ?? []), ...(run.policyRefs ?? [])]\n\t\t\t: workItemEffectRequestRefs(request)),\n\t]);\n}\n\nfunction clearPendingWorkItemEffectRequestsForRun(\n\tstate: Pick<WorkItemEvidenceState, \"pendingEffectRequests\">,\n\teffectRunId: string,\n): void {\n\tfor (const pendingRequest of state.pendingEffectRequests.values()) {\n\t\tif (pendingRequest.effectRunId === effectRunId)\n\t\t\tstate.pendingEffectRequests.delete(pendingRequest.requestId);\n\t}\n}\n\nfunction emitWorkItemEffectRunIssue(\n\tctx: Ctx,\n\tstate: WorkItemEffectRunState,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.issueSeq += 1;\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${subjectId ?? \"work-item\"}:mapping-issue:${state.statusSeq}`,\n\t\tworkItemId: subjectId ?? \"unknown\",\n\t\tstate: \"mapping-issue\",\n\t\tsourceRefs,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${subjectId ?? \"work-item\"}:${code}:${state.auditSeq}`,\n\t\tkind: \"work-item-effect-run-issue\",\n\t\tsubjectId,\n\t\tissueCode: code,\n\t\tmessage,\n\t\tsourceRefs,\n\t};\n\tstate.issues.push(issue);\n\tstate.audit.push(audit);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies WorkItemEffectRunFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemEffectRunFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemEffectRunFact],\n\t]);\n}\n\nfunction emitWorkItemEvidenceIssue(\n\tctx: Ctx,\n\tstate: WorkItemEvidenceState,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.issueSeq += 1;\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${subjectId ?? \"work-item\"}:mapping-issue:${state.statusSeq}`,\n\t\tworkItemId: subjectId ?? \"unknown\",\n\t\tstate: \"mapping-issue\",\n\t\tsourceRefs,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${subjectId ?? \"work-item\"}:${code}:${state.auditSeq}`,\n\t\tkind: \"work-item-evidence-mapping-issue\",\n\t\tsubjectId,\n\t\tissueCode: code,\n\t\tmessage,\n\t\tsourceRefs,\n\t};\n\tstate.issues.push(issue);\n\tstate.audit.push(audit);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies WorkItemEvidenceMapperFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemEvidenceMapperFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemEvidenceMapperFact],\n\t]);\n}\n\nfunction emitWorkItemActionProposalIssue(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionProposalState,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.issueSeq += 1;\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${subjectId ?? \"work-item\"}:mapping-issue:${state.statusSeq}`,\n\t\tworkItemId: subjectId ?? \"unknown\",\n\t\tstate: \"mapping-issue\",\n\t\tsourceRefs,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${subjectId ?? \"work-item\"}:${code}:${state.auditSeq}`,\n\t\tkind: \"work-item-action-proposal-issue\",\n\t\tsubjectId,\n\t\tissueCode: code,\n\t\tmessage,\n\t\tsourceRefs,\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies WorkItemDomainActionProposalFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemDomainActionProposalFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemDomainActionProposalFact],\n\t]);\n}\n\nfunction emitWorkItemAdmissionIssue(\n\tctx: Ctx,\n\tstate: WorkItemDomainActionAdmissionStateInternal,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.issueSeq += 1;\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tconst status: WorkItemStatusRecord = {\n\t\tkind: \"work-item-status\",\n\t\tstatusId: `${subjectId ?? \"work-item\"}:mapping-issue:${state.statusSeq}`,\n\t\tworkItemId: subjectId ?? \"unknown\",\n\t\tstate: \"mapping-issue\",\n\t\tsourceRefs,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${subjectId ?? \"work-item\"}:${code}:${state.auditSeq}`,\n\t\tkind: \"work-item-domain-action-admission-issue\",\n\t\tsubjectId,\n\t\tissueCode: code,\n\t\tmessage,\n\t\tsourceRefs,\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies WorkItemDomainActionAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies WorkItemDomainActionAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies WorkItemDomainActionAdmissionFact],\n\t]);\n}\n\nfunction emptyWorkItemEffectRunState(): WorkItemEffectRunState {\n\treturn {\n\t\tworkItems: new Map<string, WorkItemSeed>(),\n\t\trequests: new Map<string, WorkItemEffectRequested>(),\n\t\teffectRunsByRequest: new Map<string, string>(),\n\t\tseededEffectRunIds: new Set<string>(),\n\t\tissues: [],\n\t\taudit: [],\n\t\tissueKeys: new Set<string>(),\n\t\tstatusSeq: 0,\n\t\tissueSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction emptyWorkItemEvidenceState(): WorkItemEvidenceState {\n\treturn {\n\t\tworkItems: new Map<string, WorkItemSeed>(),\n\t\teffectRuns: new Map<string, EffectRun>(),\n\t\teffectRunWorkItems: new Map<string, string>(),\n\t\tevidenceByWorkItem: new Map<string, WorkItemEvidenceRecorded[]>(),\n\t\tlatestEvidenceByEffectRun: new Map<string, WorkItemEvidenceRecorded>(),\n\t\tpendingEffectRequests: new Map<string, WorkItemEffectRequested>(),\n\t\trequestsByEffectRun: new Map<string, WorkItemEffectRequested>(),\n\t\tambiguousRequestsByEffectRun: new Map<string, WorkItemEffectRequested[]>(),\n\t\tpolicies: new Map<string, WorkItemEffectMappingPolicy>(),\n\t\tissues: [],\n\t\taudit: [],\n\t\tissueKeys: new Set<string>(),\n\t\tstatusSeq: 0,\n\t\tissueSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction emptyWorkItemDomainActionProposalState(): WorkItemDomainActionProposalState {\n\treturn {\n\t\tworkItems: new Map<string, WorkItemSeed>(),\n\t\tevidence: new Map<string, WorkItemEvidenceRecorded>(),\n\t\tresults: new Map<string, EffectRunResult>(),\n\t\tpolicies: new Map<string, WorkItemEffectMappingPolicy>(),\n\t\tproposedKeys: new Set<string>(),\n\t\tissueKeys: new Set<string>(),\n\t\tstatusSeq: 0,\n\t\tissueSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction emptyWorkItemDomainActionAdmissionState(): WorkItemDomainActionAdmissionStateInternal {\n\treturn {\n\t\tproposals: new Map<string, WorkItemDomainActionProposal>(),\n\t\tpolicies: new Map<string, WorkItemDomainActionAdmissionPolicy>(),\n\t\tdecisions: new Map<string, WorkItemDomainActionAdmissionDecision>(),\n\t\tadmissionsById: new Map<string, WorkItemDomainActionAdmission>(),\n\t\tadmissionsByProposal: new Map<string, WorkItemDomainActionAdmission>(),\n\t\tterminalDecisionIds: new Set<string>(),\n\t\tissueKeys: new Set<string>(),\n\t\tstatusSeq: 0,\n\t\tissueSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction freezeWorkItemEffectRequestViews(\n\tstate: WorkItemEffectRunViewsState,\n): WorkItemEffectRequestViews {\n\treturn {\n\t\tpendingEffectRequests: Object.freeze(Array.from(state.pendingEffectRequests.values())),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction freezeWorkItemEvidenceViews(state: WorkItemEvidenceViewsState): WorkItemEvidenceViews {\n\treturn {\n\t\tevidenceByWorkItem: new Map(\n\t\t\tArray.from(state.evidenceByWorkItem, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tlatestEvidenceByEffectRun: new Map(state.latestEvidenceByEffectRun),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t\tpendingEffectRequests: Object.freeze(Array.from(state.pendingEffectRequests.values())),\n\t};\n}\n\nfunction freezeWorkItemDomainActionProposalViews(\n\tstate: WorkItemDomainActionProposalViewsState,\n): WorkItemDomainActionProposalViews {\n\treturn {\n\t\tproposalsByWorkItem: new Map(\n\t\t\tArray.from(state.proposalsByWorkItem, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tproposalsByEvidence: new Map(\n\t\t\tArray.from(state.proposalsByEvidence, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction freezeWorkItemDomainActionAdmissionViews(\n\tstate: WorkItemDomainActionAdmissionViewsState,\n): WorkItemDomainActionAdmissionViews {\n\treturn {\n\t\tadmissionsByProposal: new Map(state.admissionsByProposal),\n\t\tadmissionsByWorkItem: new Map(\n\t\t\tArray.from(state.admissionsByWorkItem, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction deletePendingWorkItemEffectRequest(\n\tstate: Pick<\n\t\tWorkItemEffectRunViewsState | WorkItemEvidenceViewsState,\n\t\t\"pendingEffectRequests\" | \"settledRequestIds\"\n\t>,\n\trefs: readonly string[] | undefined,\n): void {\n\tfor (const requestRef of refs?.filter((value) => value.startsWith(\"work-item-effect-request:\")) ??\n\t\t[]) {\n\t\tconst requestId = requestRef.slice(\"work-item-effect-request:\".length);\n\t\tstate.pendingEffectRequests.delete(requestId);\n\t\tstate.settledRequestIds.add(requestId);\n\t}\n}\n\nfunction workItemEffectRequestRefs(request: WorkItemEffectRequested): readonly SourceRef[] {\n\treturn [\n\t\tref(\"work-item\", request.workItemId),\n\t\tref(\"work-item-effect-request\", request.requestId),\n\t\t...(request.sourceRefs ?? []),\n\t];\n}\n\nfunction workItemResultRefs(result: EffectRunResult): readonly SourceRef[] {\n\treturn [\n\t\tref(\"effect-run\", result.effectRunId),\n\t\tref(\"effect-run-result\", result.resultId),\n\t\t...(result.sourceRefs ?? []),\n\t\t...(result.subjectRefs ?? []),\n\t];\n}\n\nfunction workItemActionProposalRefs(\n\tevidence: WorkItemEvidenceRecorded,\n\tresult: EffectRunResult,\n\tpolicy?: WorkItemEffectMappingPolicy,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"work-item\", evidence.workItemId),\n\t\tref(\"effect-run\", evidence.effectRunId),\n\t\tref(\"effect-run-result\", evidence.effectRunResultId),\n\t\tref(\"work-item-evidence\", evidence.evidenceId),\n\t\t...(policy === undefined ? [] : [ref(\"work-item-effect-mapping-policy\", policy.policyId)]),\n\t\t...(evidence.sourceRefs ?? []),\n\t\t...(result.sourceRefs ?? []),\n\t\t...(result.subjectRefs ?? []),\n\t]);\n}\n\nfunction workItemAdmissionProposalRefs(\n\tproposal: WorkItemDomainActionProposal,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"work-item\", proposal.workItemId),\n\t\tref(\"work-item-domain-action-proposal\", proposal.proposalId),\n\t\tref(\"effect-run\", proposal.effectRunId),\n\t\tref(\"effect-run-result\", proposal.effectRunResultId),\n\t\tref(\"work-item-evidence\", proposal.evidenceId),\n\t\tref(\"work-item-effect-mapping-policy\", proposal.policyId),\n\t\t...(proposal.sourceRefs ?? []),\n\t]);\n}\n\nfunction workItemAdmissionDecisionRefs(\n\tdecision: WorkItemDomainActionAdmissionDecision,\n\tproposal?: WorkItemDomainActionProposal,\n\tpolicy?: WorkItemDomainActionAdmissionPolicy,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\t...(proposal === undefined ? [] : workItemAdmissionProposalRefs(proposal)),\n\t\tref(\"work-item-domain-action-admission-decision\", decision.decisionId),\n\t\tref(\"work-item-domain-action-admission\", decision.admissionId),\n\t\tref(\"work-item-domain-action-proposal\", decision.proposalId),\n\t\t...(decision.policyId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"work-item-domain-action-admission-policy\", decision.policyId)]),\n\t\t...(policy === undefined\n\t\t\t? []\n\t\t\t: [ref(\"work-item-domain-action-admission-policy\", policy.policyId)]),\n\t\t...(decision.targetProposalId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"work-item-domain-action-proposal\", decision.targetProposalId)]),\n\t\t...(decision.targetAdmissionId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"work-item-domain-action-admission\", decision.targetAdmissionId)]),\n\t\t...(decision.sourceRefs ?? []),\n\t]);\n}\n\nfunction workItemEvidenceOnlyRefs(evidence: WorkItemEvidenceRecorded): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"work-item\", evidence.workItemId),\n\t\tref(\"effect-run\", evidence.effectRunId),\n\t\tref(\"effect-run-result\", evidence.effectRunResultId),\n\t\tref(\"work-item-evidence\", evidence.evidenceId),\n\t\t...(evidence.sourceRefs ?? []),\n\t]);\n}\n\nfunction referencedWorkItemMappingPolicyIds(evidence: WorkItemEvidenceRecorded): readonly string[] {\n\tconst refs = uniqueSourceRefs([...(evidence.sourceRefs ?? [])]);\n\treturn refs\n\t\t.filter((sourceRef) => sourceRef.kind === \"work-item-effect-mapping-policy\")\n\t\t.map((sourceRef) => sourceRef.id);\n}\n\nfunction effectKindFromMetadata(metadata: Record<string, unknown> | undefined): string | undefined {\n\tconst effectKind = metadata?.effectKind;\n\treturn typeof effectKind === \"string\" ? effectKind : undefined;\n}\n\nfunction workItemActionProposalPayload(\n\tspec: WorkItemDomainActionProposalSpec,\n\tevidence: WorkItemEvidenceRecorded,\n\tresult: EffectRunResult,\n): unknown {\n\tif (spec.payload !== undefined) return spec.payload;\n\tconst payloadFrom = spec.payloadFrom;\n\tif (payloadFrom === undefined) return undefined;\n\tif (payloadFrom === \"effect-run-result\")\n\t\treturn { kind: \"effect-run-result-ref\", resultId: result.resultId };\n\tif (payloadFrom === \"output\") return evidence.output;\n\treturn { kind: \"work-item-evidence-ref\", evidenceId: evidence.evidenceId };\n}\n\nfunction resultReason(result: EffectRunResult): string | undefined {\n\tif (result.status === \"canceled\" || result.status === \"waived\") return result.reason;\n\treturn undefined;\n}\n\nfunction workItemIdForEffectRunResult(\n\tstate: Pick<WorkItemDomainActionProposalState, \"evidence\">,\n\tresult: EffectRunResult,\n): string | undefined {\n\tfor (const evidence of state.evidence.values()) {\n\t\tif (\n\t\t\tevidence.effectRunResultId === result.resultId &&\n\t\t\tevidence.effectRunId === result.effectRunId\n\t\t)\n\t\t\treturn evidence.workItemId;\n\t}\n\treturn undefined;\n}\n\nfunction uniqueSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\tconst seen = new Set<string>();\n\tconst unique: SourceRef[] = [];\n\tfor (const sourceRef of sourceRefs) {\n\t\tconst key = sourceRefKey(sourceRef);\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(sourceRef);\n\t}\n\treturn unique;\n}\n\nfunction sourceRefKey(sourceRef: SourceRef): string {\n\treturn `${sourceRef.kind}:${sourceRef.id}:${JSON.stringify(sourceRef.metadata ?? {})}`;\n}\n\nfunction distinctWorkItemRefs(sourceRefs: readonly SourceRef[] | undefined): readonly SourceRef[] {\n\tconst refs = new Map<string, SourceRef>();\n\tfor (const sourceRef of sourceRefs ?? []) {\n\t\tif (sourceRef.kind === \"work-item\") refs.set(sourceRef.id, sourceRef);\n\t}\n\treturn Array.from(refs.values());\n}\n\nfunction singleWorkItemRef(sourceRefs: readonly SourceRef[] | undefined): SourceRef | undefined {\n\tconst matches = distinctWorkItemRefs(sourceRefs);\n\treturn matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction projectRuntimeFact<T, TOut>(\n\tgraph: Graph,\n\truntime: Node<T>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: T) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as T;\n\t\t\t\tconst value = pick(typed);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory },\n\t);\n}\n\nfunction forEachPolicyDepBatch(\n\tctx: Ctx,\n\tstart: number,\n\tcount: number,\n\tfn: (value: unknown) => void,\n): void {\n\tfor (let i = 0; i < count; i += 1) {\n\t\tfor (const value of depBatch(ctx, start + i) ?? []) fn(value);\n\t}\n}\n\nfunction dataIssue(\n\tcode: string,\n\tmessage: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly refs?: readonly SourceRef[];\n\t\treadonly severity?: DataIssue[\"severity\"];\n\t\treadonly details?: unknown;\n\t} = {},\n): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: opts.severity ?? \"error\",\n\t\tsubjectId: opts.subjectId,\n\t\trefs: opts.refs?.map((r) => `${r.kind}:${r.id}`),\n\t\tdetails: opts.details,\n\t};\n}\n\nfunction ref(kind: string, id: string): SourceRef {\n\treturn { kind, id };\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;;;AC2CO,IAAM,WAAW;AAGjB,SAAS,sBAAsB,GAAqB;AAC1D,SAAO,MAAM,YAAY,OAAO,MAAM;AACvC;AAGO,SAAS,aAAa,QAAiB,WAAW,iCAA0C;AAClG,SAAO,sBAAsB,MAAM,IAAI,IAAI,MAAM,QAAQ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AAS,6BAA6B,OAAsB;AAC3D,QAAM,UAAU,aAAa,KAAK;AAClC,MACC,QAAQ,SAAS,cAAc,KAC/B,QAAQ,SAAS,UAAU,KAC3B,QAAQ,SAAS,gBAAgB,KACjC,QAAQ,SAAS,KAAK,KACtB,QAAQ,SAAS,KAAK,KACtB,QAAQ,SAAS,iBAAiB,KAClC,QAAQ,SAAS,aAAa,KAC9B,QAAQ,SAAS,aAAa,KAC9B,QAAQ,SAAS,0BAA0B,KAC3C,QAAQ,SAAS,wBAAwB,KACzC,QAAQ,SAAS,gBAAgB,GAChC;AACD,UAAM;AAAA,EACP;AACD;AAEA,SAAS,eAAe,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC3E;AAEA,SAAS,aAAa,OAAwB;AAC7C,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC7D;","names":["out","source","source","ref","projectRuntimeFact","uniqueSourceRefs","refs","dataIssue","source","allowed","status","state","errorMessage"]}
|
|
1
|
+
{"version":3,"sources":["../../src/orchestration/index.ts","../../src/graph/resilience.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/orchestration/agent-runtime-common.ts","../../src/orchestration/agent-runtime-adapter-run.ts","../../src/orchestration/agent-runtime-effect-completion.ts","../../src/orchestration/agent-runtime-decision-interpreter.ts","../../src/orchestration/agent-runtime-executor-outcome.ts","../../src/orchestration/agent-runtime-fakes.ts","../../src/orchestration/agent-runtime-outcome-view.ts","../../src/orchestration/agent-runtime-request-ledger.ts","../../src/orchestration/agent-runtime-request-satisfaction.ts","../../src/orchestration/agent-runtime-tool-provider-policy.ts","../../src/orchestration/agent-runtime-tool-provider-input.ts","../../src/orchestration/agent-runtime-tool-provider-run-admission.ts","../../src/orchestration/agent-runtime-tool-provider-run-retry.ts","../../src/orchestration/agent-runtime-types-core.ts","../../src/orchestration/process-utils.ts","../../src/orchestration/process.ts","../../src/batch/boundary.ts","../../src/dispatcher/index.ts","../../src/graph/environment.ts","../../src/node/core.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/batch/batch.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/sources.ts","../../src/graph/time.ts","../../src/orchestration/resilience-bundles.ts","../../src/orchestration/scheduled-readiness.ts"],"sourcesContent":["/**\n * Reusable application-infrastructure orchestration namespace.\n *\n * Retained root orchestration helpers land here only after B63 re-derives them\n * onto clean-slate graph surfaces.\n */\n\nexport {\n\ttype BackoffPolicy,\n\tbackoffDelayMs,\n\tnextRetryDelayMs,\n\tnoBackoff,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nexport * from \"./agent-runtime.js\";\nexport * from \"./process.js\";\nexport * from \"./resilience-bundles.js\";\nexport type {\n\tScheduledReadinessBundle,\n\tScheduledReadinessClock,\n\tScheduledReadinessOverdue,\n\tScheduledReadinessPending,\n\tScheduledReadinessReady,\n\tScheduledReadinessRequested,\n\tScheduledReadinessStatus,\n\tScheduledReadinessStatusState,\n\tScheduledReadinessViews,\n} from \"./scheduled-readiness.js\";\nexport { scheduledReadinessProjector } from \"./scheduled-readiness.js\";\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 * 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","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { AgentNeed } from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentOutputEnvelope,\n\tExecutorArtifactMaterial,\n\tSizeCapacityEvidence,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterInput,\n\tToolProviderExecutionPolicy,\n\tToolProviderPublicTextPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function uniqueSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\tconst seen = new Set<string>();\n\tconst unique: SourceRef[] = [];\n\tfor (const sourceRef of sourceRefs) {\n\t\tconst key = `${sourceRef.kind}:${sourceRef.id}:${JSON.stringify(sourceRef.metadata ?? {})}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(sourceRef);\n\t}\n\treturn Object.freeze(unique);\n}\n\nexport function stableJsonStringify(value: unknown): string {\n\tconst seen = new WeakSet<object>();\n\treturn JSON.stringify(value, (_key, child) => {\n\t\tif (typeof child === \"bigint\") return child.toString();\n\t\tif (typeof child === \"function\") return \"[Function]\";\n\t\tif (!isRecord(child) && !Array.isArray(child)) return child;\n\t\tif (seen.has(child)) return \"[Circular]\";\n\t\tseen.add(child);\n\t\tif (Array.isArray(child)) return child;\n\t\treturn Object.keys(child)\n\t\t\t.sort()\n\t\t\t.reduce<Record<string, unknown>>((out, key) => {\n\t\t\t\tout[key] = child[key];\n\t\t\t\treturn out;\n\t\t\t}, {});\n\t});\n}\n\nexport function stableStringHash(value: string): string {\n\tlet hash = 0x811c9dc5;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\thash ^= value.charCodeAt(i);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(36);\n}\n\nexport function cloneGraphVisibleMaterial(value: unknown): unknown {\n\tif (!isRecord(value) && !Array.isArray(value)) return value;\n\tif (Array.isArray(value))\n\t\treturn Object.freeze(value.map((item) => cloneGraphVisibleMaterial(item)));\n\treturn Object.freeze(\n\t\tObject.entries(value).reduce<Record<string, unknown>>((record, [key, child]) => {\n\t\t\trecord[key] = cloneGraphVisibleMaterial(child);\n\t\t\treturn record;\n\t\t}, {}),\n\t);\n}\n\nexport function projectRuntimeFact<T, TOut>(\n\tgraph: Graph,\n\truntime: Node<T>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: T) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as T;\n\t\t\t\tconst value = pick(typed);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory },\n\t);\n}\n\nexport function forEachDepBatch(\n\tctx: Ctx,\n\tstart: number,\n\tcount: number,\n\tfn: (value: unknown) => void,\n): void {\n\tfor (let i = 0; i < count; i += 1) {\n\t\tfor (const value of depBatch(ctx, start + i) ?? []) fn(value);\n\t}\n}\n\nexport function forbiddenDataKeys(\n\tvalue: unknown,\n\tpath: readonly (string | number)[] = [],\n\tseen: WeakSet<object> = new WeakSet(),\n): readonly { readonly path: readonly (string | number)[]; readonly reason: string }[] {\n\tif (typeof value === \"function\") return [{ path, reason: \"function-value\" }];\n\tif (typeof value === \"symbol\" || typeof value === \"bigint\") {\n\t\treturn [{ path, reason: \"non-graph-visible-primitive\" }];\n\t}\n\tif (!isRecord(value) && !Array.isArray(value)) return [];\n\tif (typeof value === \"object\" && value !== null) {\n\t\tif (seen.has(value)) return [];\n\t\tseen.add(value);\n\t}\n\tconst issues: { readonly path: readonly (string | number)[]; readonly reason: string }[] = [];\n\tif (Array.isArray(value)) {\n\t\tvalue.forEach((item, index) => {\n\t\t\tissues.push(...forbiddenDataKeys(item, [...path, index], seen));\n\t\t});\n\t\treturn issues;\n\t}\n\tif (!isPlainRecord(value)) return [{ path, reason: \"non-plain-runtime-object\" }];\n\tconst symbolKeys = Object.getOwnPropertySymbols(value);\n\tif (symbolKeys.length > 0) {\n\t\tissues.push({ path, reason: \"symbol-key\" });\n\t}\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tconst nextPath = [...path, key];\n\t\tif (\n\t\t\t/^(apiKey|api_key|secret|client|transport|subprocess|sdk|oauth|credential|credentials|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|token|password|passphrase|authorization|authHeader|auth_header|bearer|privateKey|private_key|sessionCookie|session_cookie|cookie)$/i.test(\n\t\t\t\tkey,\n\t\t\t)\n\t\t) {\n\t\t\tissues.push({ path: nextPath, reason: \"forbidden-runtime-key\" });\n\t\t}\n\t\tissues.push(...forbiddenDataKeys(child, nextPath, seen));\n\t}\n\treturn issues;\n}\n\nexport function forbiddenGraphVisibleMaterialIssues(\n\tvalue: unknown,\n\tsubjectRef: SourceRef,\n\tarea: string,\n): readonly DataIssue[] {\n\tif (value === undefined) return [];\n\tconst forbidden = publicMaterialForbiddenKeys(value, \"provider\");\n\tif (forbidden.length === 0) return [];\n\treturn Object.freeze(\n\t\tforbidden.map((entry) =>\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-catalog-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider catalog material must not contain runtime-private adapter material.\",\n\t\t\t\t{ subjectId: subjectRef.id, refs: [subjectRef], details: { area, reason: entry.reason } },\n\t\t\t),\n\t\t),\n\t);\n}\n\nexport function forbiddenAdapterInputMaterialIssues(\n\tvalue: unknown,\n\tsubjectRef: SourceRef,\n\tarea: string,\n): readonly DataIssue[] {\n\tif (value === undefined) return [];\n\tconst forbidden = publicMaterialForbiddenKeys(value, \"provider\");\n\tif (forbidden.length === 0) return [];\n\treturn Object.freeze(\n\t\tforbidden.map((entry) =>\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider adapter input material must not contain runtime-private adapter material.\",\n\t\t\t\t{ subjectId: subjectRef.id, refs: [subjectRef], details: { area, reason: entry.reason } },\n\t\t\t),\n\t\t),\n\t);\n}\n\nexport type PublicMaterialMode = \"graph\" | \"provider\";\n\nexport function sanitizeAdapterInputSourceRefs(\n\tsourceRefs: readonly SourceRef[],\n): readonly SourceRef[] {\n\treturn canonicalPublicSourceRefs(sourceRefs);\n}\n\nexport function sanitizeGraphVisibleRecord<T extends Record<string, unknown> | undefined>(\n\tvalue: T,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): T | undefined {\n\treturn sanitizePublicRecord(value, { mode: \"graph\", policy });\n}\n\nexport function sanitizeProviderGraphVisibleRecord<T extends Record<string, unknown> | undefined>(\n\tvalue: T,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): T | undefined {\n\treturn sanitizePublicRecord(value, { mode: \"provider\", policy });\n}\n\nexport function canonicalPublicSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\treturn uniqueSourceRefs(\n\t\tsourceRefs.map((sourceRef) => {\n\t\t\tconst metadata = sanitizePublicRecord(sourceRef.metadata, { mode: \"provider\" });\n\t\t\treturn metadata === undefined\n\t\t\t\t? { kind: sourceRef.kind, id: sourceRef.id }\n\t\t\t\t: { kind: sourceRef.kind, id: sourceRef.id, metadata };\n\t\t}),\n\t);\n}\n\nexport function sanitizePublicRecord<T extends Record<string, unknown> | undefined>(\n\tvalue: T,\n\topts: {\n\t\treadonly mode: PublicMaterialMode;\n\t\treadonly policy?: ToolProviderPublicTextPolicy;\n\t},\n): T | undefined {\n\tif (value === undefined || publicMaterialForbiddenKeys(value, opts.mode).length > 0) {\n\t\treturn undefined;\n\t}\n\treturn Object.freeze(boundRecordStrings(value, maxPublicMetadataStringChars(opts.policy))) as T;\n}\n\nexport function publicMaterialForbiddenKeys(\n\tvalue: unknown,\n\tmode: PublicMaterialMode,\n): readonly { readonly path: readonly (string | number)[]; readonly reason: string }[] {\n\tconst forbidden = [...forbiddenDataKeys(value)];\n\tif (mode === \"provider\") forbidden.push(...forbiddenProviderRawMaterialKeys(value));\n\treturn forbidden;\n}\n\nexport function unlockedToolProviderPolicyOverrides(\n\toverrides:\n\t\t| Partial<Omit<ToolProviderExecutionPolicy, \"kind\" | \"policyId\" | \"providerId\">>\n\t\t| undefined,\n): Partial<Omit<ToolProviderExecutionPolicy, \"kind\" | \"policyId\" | \"providerId\">> | undefined {\n\tif (overrides === undefined) return undefined;\n\tconst rest = { ...(overrides as Record<string, unknown>) };\n\tdelete rest.kind;\n\tdelete rest.policyId;\n\tdelete rest.providerId;\n\treturn rest as Partial<Omit<ToolProviderExecutionPolicy, \"kind\" | \"policyId\" | \"providerId\">>;\n}\n\nexport function sanitizeAgentOutputEnvelope<T>(\n\tenvelope: AgentOutputEnvelope<T>,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): AgentOutputEnvelope<T> {\n\tconst summary =\n\t\tenvelope.summary === undefined\n\t\t\t? undefined\n\t\t\t: boundedPublicText(envelope.summary, \"summary\", input, policy, issues);\n\tconst metadata = sanitizeRuntimeMetadata(envelope.metadata, input, policy, issues);\n\tif (metadata === undefined && envelope.metadata !== undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-metadata-redacted\",\n\t\t\t\t\"Tool provider adapter runtime metadata was omitted because it contained runtime-private material.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\tconst value = sanitizeInlineOutputValue(envelope.value, input, policy, issues);\n\treturn Object.freeze({\n\t\tkind: envelope.kind,\n\t\tvalue: value as T | undefined,\n\t\trefs: envelope.refs === undefined ? undefined : sanitizeAdapterInputSourceRefs(envelope.refs),\n\t\tsummary,\n\t\tartifacts:\n\t\t\tenvelope.artifacts === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Object.freeze(\n\t\t\t\t\t\tenvelope.artifacts.map((artifact) =>\n\t\t\t\t\t\t\tsanitizeExecutorArtifactMaterial(artifact, input, policy, issues),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\tmetadata,\n\t} satisfies AgentOutputEnvelope<T>);\n}\n\nexport function sanitizeExecutorArtifactMaterial(\n\tartifact: ExecutorArtifactMaterial,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): ExecutorArtifactMaterial {\n\tconst metadata = sanitizeRuntimeMetadata(artifact.metadata, input, policy, issues);\n\tconst redaction = sanitizeRuntimeMetadata(artifact.redaction, input, policy, issues);\n\treturn Object.freeze({\n\t\tkind: artifact.kind,\n\t\t...(artifact.format === undefined ? {} : { format: artifact.format }),\n\t\t...(artifact.schemaRef === undefined ? {} : { schemaRef: artifact.schemaRef }),\n\t\t...(artifact.schemaKind === undefined ? {} : { schemaKind: artifact.schemaKind }),\n\t\t...(artifact.mimeType === undefined ? {} : { mimeType: artifact.mimeType }),\n\t\t...(artifact.mediaType === undefined ? {} : { mediaType: artifact.mediaType }),\n\t\t...(artifact.filename === undefined ? {} : { filename: artifact.filename }),\n\t\t...(artifact.byteLength === undefined ? {} : { byteLength: artifact.byteLength }),\n\t\t...(artifact.digest === undefined ? {} : { digest: artifact.digest }),\n\t\t...(artifact.encoding === undefined ? {} : { encoding: artifact.encoding }),\n\t\tdataMode: artifact.dataMode,\n\t\t...(artifact.summary === undefined\n\t\t\t? {}\n\t\t\t: { summary: boundedPublicText(artifact.summary, \"summary\", input, policy, issues) }),\n\t\t...(artifact.value === undefined\n\t\t\t? {}\n\t\t\t: { value: sanitizeInlineOutputValue(artifact.value, input, policy, issues) }),\n\t\t...(artifact.ref === undefined\n\t\t\t? {}\n\t\t\t: { ref: sanitizeAdapterInputSourceRefs([artifact.ref])[0] }),\n\t\t...(artifact.refs === undefined ? {} : { refs: sanitizeAdapterInputSourceRefs(artifact.refs) }),\n\t\t...(artifact.sourceRefs === undefined\n\t\t\t? {}\n\t\t\t: { sourceRefs: sanitizeAdapterInputSourceRefs(artifact.sourceRefs) }),\n\t\t...(artifact.sizeEvidence === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tsizeEvidence: Object.freeze(\n\t\t\t\t\t\tartifact.sizeEvidence.map((evidence) =>\n\t\t\t\t\t\t\tsanitizeSizeCapacityEvidence(evidence, input, policy, issues),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t...(artifact.sensitivity === undefined\n\t\t\t? {}\n\t\t\t: { sensitivity: Object.freeze([...artifact.sensitivity]) }),\n\t\t...(redaction === undefined ? {} : { redaction }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies ExecutorArtifactMaterial);\n}\n\nfunction sanitizeSizeCapacityEvidence(\n\tevidence: SizeCapacityEvidence,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): SizeCapacityEvidence {\n\tconst metadata = sanitizeRuntimeMetadata(evidence.metadata, input, policy, issues);\n\tconst redaction = sanitizeRuntimeMetadata(evidence.redaction, input, policy, issues);\n\treturn Object.freeze({\n\t\tkind: \"size-capacity-evidence\",\n\t\tunit: evidence.unit,\n\t\tquantity: evidence.quantity,\n\t\tmeasurementSource: evidence.measurementSource,\n\t\t...(evidence.estimated === undefined ? {} : { estimated: evidence.estimated }),\n\t\t...(evidence.encoding === undefined ? {} : { encoding: evidence.encoding }),\n\t\t...(evidence.mediaType === undefined ? {} : { mediaType: evidence.mediaType }),\n\t\t...(evidence.sourceRefs === undefined\n\t\t\t? {}\n\t\t\t: { sourceRefs: sanitizeAdapterInputSourceRefs(evidence.sourceRefs) }),\n\t\t...(evidence.refs === undefined ? {} : { refs: sanitizeAdapterInputSourceRefs(evidence.refs) }),\n\t\t...(evidence.issues === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tissues: Object.freeze(evidence.issues.map((issue) => sanitizeAdapterInputIssue(issue))),\n\t\t\t\t}),\n\t\t...(evidence.sensitivity === undefined\n\t\t\t? {}\n\t\t\t: { sensitivity: Object.freeze([...evidence.sensitivity]) }),\n\t\t...(redaction === undefined ? {} : { redaction }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies SizeCapacityEvidence);\n}\n\nexport function sanitizeAgentNeed(\n\tneed: AgentNeed,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): AgentNeed {\n\tconst metadata = sanitizeRuntimeMetadata(need.metadata, input, policy, issues);\n\tif (metadata === undefined && need.metadata !== undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-metadata-redacted\",\n\t\t\t\t\"Tool provider adapter runtime metadata was omitted because it contained runtime-private material.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\treturn Object.freeze({\n\t\tkind: need.kind,\n\t\tmessage:\n\t\t\tneed.message === undefined\n\t\t\t\t? undefined\n\t\t\t\t: boundedPublicText(need.message, \"message\", input, policy, issues),\n\t\trefs: need.refs === undefined ? undefined : sanitizeAdapterInputSourceRefs(need.refs),\n\t\tmetadata,\n\t} satisfies AgentNeed);\n}\n\nexport function sanitizeRuntimeMetadata<T extends Record<string, unknown> | undefined>(\n\tvalue: T,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): T | undefined {\n\tif (value === undefined) return undefined;\n\tconst bounded = sanitizePublicRecordWithEvidence(value, { mode: \"provider\", policy });\n\tif (bounded === undefined) return undefined;\n\tfor (const entry of bounded.truncated) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-public-text-truncated\",\n\t\t\t\t\"Tool provider adapter runtime public text was truncated; large/raw material must use artifact summary/ref envelopes.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tfield: \"metadata\",\n\t\t\t\t\t\tpath: entry.path.join(\".\"),\n\t\t\t\t\t\toriginalChars: entry.originalChars,\n\t\t\t\t\t\tlimitChars: entry.limitChars,\n\t\t\t\t\t\tunit: \"chars\",\n\t\t\t\t\t\tmeasurementSource: \"js-string-length\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\treturn Object.freeze(bounded.value) as T;\n}\n\nexport function sanitizePublicRecordWithEvidence(\n\tvalue: Record<string, unknown>,\n\topts: {\n\t\treadonly mode: PublicMaterialMode;\n\t\treadonly policy?: ToolProviderPublicTextPolicy;\n\t},\n):\n\t| {\n\t\t\treadonly value: Record<string, unknown>;\n\t\t\treadonly truncated: readonly {\n\t\t\t\treadonly path: readonly (string | number)[];\n\t\t\t\treadonly originalChars: number;\n\t\t\t\treadonly limitChars: number;\n\t\t\t}[];\n\t }\n\t| undefined {\n\tif (publicMaterialForbiddenKeys(value, opts.mode).length > 0) return undefined;\n\treturn boundRecordStringsWithEvidence(value, maxPublicMetadataStringChars(opts.policy));\n}\n\nexport function sanitizeInlineOutputValue(\n\tvalue: unknown,\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): unknown {\n\tif (value === undefined) return undefined;\n\tconst forbidden = [\n\t\t...publicMaterialForbiddenKeys(value, \"provider\"),\n\t\t...oversizedInlineTextKeys(value, maxPublicSummaryChars(policy)),\n\t];\n\tif (forbidden.length === 0) return cloneGraphVisibleMaterial(value);\n\tfor (const entry of forbidden) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider adapter runtime output value must not inline runtime-private, raw, or oversized provider material.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tdetails: { reason: entry.reason },\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\treturn undefined;\n}\n\nexport function boundedPublicText(\n\ttext: string,\n\tfield: \"message\" | \"reason\" | \"summary\",\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderPublicTextPolicy | undefined,\n\tissues: DataIssue[],\n): string {\n\tconst limit =\n\t\tfield === \"summary\"\n\t\t\t? maxPublicSummaryChars(policy)\n\t\t\t: field === \"reason\"\n\t\t\t\t? maxPublicReasonChars(policy)\n\t\t\t\t: maxPublicMessageChars(policy);\n\tconst bounded = boundPublicText(text, limit);\n\tif (!bounded.truncated) return bounded.text;\n\tissues.push(\n\t\tdataIssue(\n\t\t\t\"tool-provider-adapter-runtime-public-text-truncated\",\n\t\t\t\"Tool provider adapter runtime public text was truncated; large/raw material must use artifact summary/ref envelopes.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.requestId,\n\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tdetails: {\n\t\t\t\t\tfield,\n\t\t\t\t\toriginalChars: bounded.originalChars,\n\t\t\t\t\tlimitChars: bounded.limitChars,\n\t\t\t\t\tunit: \"chars\",\n\t\t\t\t\tmeasurementSource: \"js-string-length\",\n\t\t\t\t},\n\t\t\t},\n\t\t),\n\t);\n\treturn bounded.text;\n}\n\nexport function boundPublicText(\n\ttext: string,\n\tlimitChars: number,\n): {\n\treadonly text: string;\n\treadonly truncated: boolean;\n\treadonly originalChars: number;\n\treadonly limitChars: number;\n} {\n\tconst limit = Math.max(0, limitChars);\n\tif (text.length <= limit) {\n\t\treturn { text, truncated: false, originalChars: text.length, limitChars: limit };\n\t}\n\tconst bounded =\n\t\tlimit <= 1\n\t\t\t? text.slice(0, limit)\n\t\t\t: limit <= 3\n\t\t\t\t? text.slice(0, limit)\n\t\t\t\t: `${text.slice(0, limit - 3)}...`;\n\treturn { text: bounded, truncated: true, originalChars: text.length, limitChars: limit };\n}\n\nexport function boundRecordStrings(\n\tvalue: Record<string, unknown>,\n\tlimitChars: number,\n\tseen: WeakSet<object> = new WeakSet(),\n): Record<string, unknown> {\n\tif (seen.has(value)) return {};\n\tseen.add(value);\n\treturn Object.entries(value).reduce<Record<string, unknown>>((out, [key, child]) => {\n\t\tif (typeof child === \"string\") {\n\t\t\tout[key] = boundPublicText(child, limitChars).text;\n\t\t} else if (Array.isArray(child)) {\n\t\t\tout[key] = child.map((item) =>\n\t\t\t\ttypeof item === \"string\"\n\t\t\t\t\t? boundPublicText(item, limitChars).text\n\t\t\t\t\t: isPlainRecord(item)\n\t\t\t\t\t\t? boundRecordStrings(item, limitChars, seen)\n\t\t\t\t\t\t: item,\n\t\t\t);\n\t\t} else if (isPlainRecord(child)) {\n\t\t\tout[key] = boundRecordStrings(child, limitChars, seen);\n\t\t} else {\n\t\t\tout[key] = child;\n\t\t}\n\t\treturn out;\n\t}, {});\n}\n\nexport function boundRecordStringsWithEvidence(\n\tvalue: Record<string, unknown>,\n\tlimitChars: number,\n\tpath: readonly (string | number)[] = [],\n\tseen: WeakSet<object> = new WeakSet(),\n): {\n\treadonly value: Record<string, unknown>;\n\treadonly truncated: readonly {\n\t\treadonly path: readonly (string | number)[];\n\t\treadonly originalChars: number;\n\t\treadonly limitChars: number;\n\t}[];\n} {\n\tif (seen.has(value)) return { value: {}, truncated: [] };\n\tseen.add(value);\n\tconst truncated: {\n\t\treadonly path: readonly (string | number)[];\n\t\treadonly originalChars: number;\n\t\treadonly limitChars: number;\n\t}[] = [];\n\tconst out = Object.entries(value).reduce<Record<string, unknown>>((record, [key, child]) => {\n\t\tconst childPath = [...path, key];\n\t\tif (typeof child === \"string\") {\n\t\t\tconst bounded = boundPublicText(child, limitChars);\n\t\t\trecord[key] = bounded.text;\n\t\t\tif (bounded.truncated) {\n\t\t\t\ttruncated.push({\n\t\t\t\t\tpath: childPath,\n\t\t\t\t\toriginalChars: bounded.originalChars,\n\t\t\t\t\tlimitChars: bounded.limitChars,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (Array.isArray(child)) {\n\t\t\trecord[key] = child.map((item, index) => {\n\t\t\t\tconst itemPath = [...childPath, index];\n\t\t\t\tif (typeof item === \"string\") {\n\t\t\t\t\tconst bounded = boundPublicText(item, limitChars);\n\t\t\t\t\tif (bounded.truncated) {\n\t\t\t\t\t\ttruncated.push({\n\t\t\t\t\t\t\tpath: itemPath,\n\t\t\t\t\t\t\toriginalChars: bounded.originalChars,\n\t\t\t\t\t\t\tlimitChars: bounded.limitChars,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn bounded.text;\n\t\t\t\t}\n\t\t\t\tif (isPlainRecord(item)) {\n\t\t\t\t\tconst nested = boundRecordStringsWithEvidence(item, limitChars, itemPath, seen);\n\t\t\t\t\ttruncated.push(...nested.truncated);\n\t\t\t\t\treturn nested.value;\n\t\t\t\t}\n\t\t\t\treturn item;\n\t\t\t});\n\t\t} else if (isPlainRecord(child)) {\n\t\t\tconst nested = boundRecordStringsWithEvidence(child, limitChars, childPath, seen);\n\t\t\trecord[key] = nested.value;\n\t\t\ttruncated.push(...nested.truncated);\n\t\t} else {\n\t\t\trecord[key] = child;\n\t\t}\n\t\treturn record;\n\t}, {});\n\treturn { value: out, truncated };\n}\n\nexport function sanitizeIssueDetails(\n\tdetails: unknown,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): unknown {\n\tif (details === undefined) return undefined;\n\tif (publicMaterialForbiddenKeys(details, \"provider\").length > 0) {\n\t\treturn { redacted: true, reason: \"forbidden-runtime-material\" };\n\t}\n\tconst bounded = boundUnknownStringsWithEvidence(details, maxPublicMetadataStringChars(policy));\n\tif (bounded.truncated.length === 0) return bounded.value;\n\tconst detailsTruncated = {\n\t\tdetailsTruncated: true,\n\t\tdetailsTruncatedPaths: bounded.truncated.map((entry) => entry.path.join(\".\")),\n\t\tmeasurementSource: \"js-string-length\",\n\t};\n\tif (isPlainRecord(bounded.value)) {\n\t\treturn Object.freeze({ ...bounded.value, ...detailsTruncated });\n\t}\n\treturn Object.freeze({ value: bounded.value, ...detailsTruncated });\n}\n\nexport function boundUnknownStringsWithEvidence(\n\tvalue: unknown,\n\tlimitChars: number,\n\tpath: readonly (string | number)[] = [],\n\tseen: WeakSet<object> = new WeakSet(),\n): {\n\treadonly value: unknown;\n\treadonly truncated: readonly {\n\t\treadonly path: readonly (string | number)[];\n\t\treadonly originalChars: number;\n\t\treadonly limitChars: number;\n\t}[];\n} {\n\tif (typeof value === \"string\") {\n\t\tconst bounded = boundPublicText(value, limitChars);\n\t\treturn {\n\t\t\tvalue: bounded.text,\n\t\t\ttruncated: bounded.truncated\n\t\t\t\t? [{ path, originalChars: bounded.originalChars, limitChars: bounded.limitChars }]\n\t\t\t\t: [],\n\t\t};\n\t}\n\tif (!isRecord(value) && !Array.isArray(value)) return { value, truncated: [] };\n\tif (typeof value === \"object\" && value !== null) {\n\t\tif (seen.has(value)) return { value: Array.isArray(value) ? [] : {}, truncated: [] };\n\t\tseen.add(value);\n\t}\n\tconst truncated: {\n\t\treadonly path: readonly (string | number)[];\n\t\treadonly originalChars: number;\n\t\treadonly limitChars: number;\n\t}[] = [];\n\tif (Array.isArray(value)) {\n\t\tconst out = value.map((item, index) => {\n\t\t\tconst bounded = boundUnknownStringsWithEvidence(item, limitChars, [...path, index], seen);\n\t\t\ttruncated.push(...bounded.truncated);\n\t\t\treturn bounded.value;\n\t\t});\n\t\treturn { value: out, truncated };\n\t}\n\tconst out = Object.entries(value).reduce<Record<string, unknown>>((record, [key, child]) => {\n\t\tconst bounded = boundUnknownStringsWithEvidence(child, limitChars, [...path, key], seen);\n\t\trecord[key] = bounded.value;\n\t\ttruncated.push(...bounded.truncated);\n\t\treturn record;\n\t}, {});\n\treturn { value: out, truncated };\n}\n\nexport function oversizedInlineTextKeys(\n\tvalue: unknown,\n\tlimitChars: number,\n\tpath: readonly (string | number)[] = [],\n\tseen: WeakSet<object> = new WeakSet(),\n): readonly { readonly path: readonly (string | number)[]; readonly reason: string }[] {\n\tif (typeof value === \"string\") {\n\t\treturn value.length > Math.max(0, limitChars)\n\t\t\t? [{ path, reason: \"oversized-inline-text\" }]\n\t\t\t: [];\n\t}\n\tif (!isRecord(value) && !Array.isArray(value)) return [];\n\tif (typeof value === \"object\" && value !== null) {\n\t\tif (seen.has(value)) return [];\n\t\tseen.add(value);\n\t}\n\tconst issues: { readonly path: readonly (string | number)[]; readonly reason: string }[] = [];\n\tif (Array.isArray(value)) {\n\t\tvalue.forEach((item, index) => {\n\t\t\tissues.push(...oversizedInlineTextKeys(item, limitChars, [...path, index], seen));\n\t\t});\n\t\treturn issues;\n\t}\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tissues.push(...oversizedInlineTextKeys(child, limitChars, [...path, key], seen));\n\t}\n\treturn issues;\n}\n\nexport function maxPublicMessageChars(policy?: ToolProviderPublicTextPolicy): number {\n\treturn normalizedPublicTextLimit(policy?.maxMessageChars, 512);\n}\n\nexport function maxPublicSummaryChars(policy?: ToolProviderPublicTextPolicy): number {\n\treturn normalizedPublicTextLimit(policy?.maxSummaryChars, 512);\n}\n\nexport function maxPublicReasonChars(policy?: ToolProviderPublicTextPolicy): number {\n\treturn normalizedPublicTextLimit(policy?.maxReasonChars, 512);\n}\n\nexport function maxPublicMetadataStringChars(policy?: ToolProviderPublicTextPolicy): number {\n\treturn normalizedPublicTextLimit(policy?.maxMetadataStringChars, 256);\n}\n\nexport function normalizedPublicTextLimit(value: number | undefined, fallback: number): number {\n\tif (value === undefined || !Number.isFinite(value)) return fallback;\n\treturn Math.max(0, Math.floor(value));\n}\n\nexport function sanitizeAdapterInputIssue(\n\tissue: DataIssue,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): DataIssue {\n\tconst boundedMessage = boundPublicText(issue.message, maxPublicMessageChars(policy));\n\tconst details = sanitizeIssueDetails(issue.details, policy);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(issue.metadata, policy);\n\tconst refs =\n\t\tissue.refs === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze(issue.refs.filter((entry): entry is string => typeof entry === \"string\"));\n\treturn Object.freeze({\n\t\tkind: issue.kind,\n\t\tcode: issue.code,\n\t\t...(issue.source === undefined ? {} : { source: issue.source }),\n\t\tmessage: boundedMessage.text,\n\t\tseverity: issue.severity,\n\t\tsubjectId: issue.subjectId,\n\t\t...(issue.correlationId === undefined ? {} : { correlationId: issue.correlationId }),\n\t\t...(issue.causationId === undefined ? {} : { causationId: issue.causationId }),\n\t\t...(issue.path === undefined ? {} : { path: Object.freeze([...issue.path]) }),\n\t\t...(refs === undefined || refs.length === 0 ? {} : { refs }),\n\t\t...(issue.retryable === undefined ? {} : { retryable: issue.retryable }),\n\t\tdetails:\n\t\t\tboundedMessage.truncated || details !== issue.details\n\t\t\t\t? {\n\t\t\t\t\t\t...(isRecord(details) ? details : {}),\n\t\t\t\t\t\t...(boundedMessage.truncated\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\ttruncated: true,\n\t\t\t\t\t\t\t\t\toriginalChars: boundedMessage.originalChars,\n\t\t\t\t\t\t\t\t\tlimitChars: boundedMessage.limitChars,\n\t\t\t\t\t\t\t\t\tmeasurementSource: \"js-string-length\",\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t}\n\t\t\t\t: details,\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies DataIssue);\n}\n\nexport function forbiddenProviderRawMaterialKeys(\n\tvalue: unknown,\n\tpath: readonly (string | number)[] = [],\n\tseen: WeakSet<object> = new WeakSet(),\n): readonly { readonly path: readonly (string | number)[]; readonly reason: string }[] {\n\tif (!isRecord(value) && !Array.isArray(value)) return [];\n\tif (typeof value === \"object\" && value !== null) {\n\t\tif (seen.has(value)) return [];\n\t\tseen.add(value);\n\t}\n\tconst issues: { readonly path: readonly (string | number)[]; readonly reason: string }[] = [];\n\tif (Array.isArray(value)) {\n\t\tvalue.forEach((item, index) => {\n\t\t\tissues.push(...forbiddenProviderRawMaterialKeys(item, [...path, index], seen));\n\t\t});\n\t\treturn issues;\n\t}\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tconst nextPath = [...path, key];\n\t\tif (\n\t\t\t/^(stdout|stderr|stack|stackTrace|stack_trace|providerRaw|provider_raw|rawResponse|raw_response|diff|patch|fileContents|file_contents|binary|media)$/i.test(\n\t\t\t\tkey,\n\t\t\t)\n\t\t) {\n\t\t\tissues.push({ path: nextPath, reason: \"raw-provider-material\" });\n\t\t}\n\t\tissues.push(...forbiddenProviderRawMaterialKeys(child, nextPath, seen));\n\t}\n\treturn issues;\n}\n\nexport function dataIssue(\n\tcode: string,\n\tmessage: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly refs?: readonly SourceRef[];\n\t\treadonly severity?: DataIssue[\"severity\"];\n\t\treadonly details?: unknown;\n\t} = {},\n): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: opts.severity ?? \"error\",\n\t\tsubjectId: opts.subjectId,\n\t\trefs: opts.refs?.map((r) => `${r.kind}:${r.id}`),\n\t\tdetails: opts.details,\n\t};\n}\n\nexport function ref(kind: string, id: string): SourceRef {\n\treturn { kind, id };\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!isRecord(value)) return false;\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === Object.prototype || proto === null;\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { ToolProviderAdapterRunProjectorPrivateRetentionHooks } from \"./agent-runtime-adapter-retention.js\";\nimport {\n\tboundPublicText,\n\tdataIssue,\n\tforbiddenDataKeys,\n\tforbiddenProviderRawMaterialKeys,\n\tforEachDepBatch,\n\tisRecord,\n\tmaxPublicReasonChars,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeProviderGraphVisibleRecord,\n\tstableJsonStringify,\n\tstableStringHash,\n} from \"./agent-runtime-common.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterBinding,\n\tToolProviderAdapterInput,\n\tToolProviderAdapterRunBundle,\n\tToolProviderAdapterRunReason,\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunStatus,\n\tToolProviderPublicTextPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function normalizeToolProviderAdapterBindings<TArguments, TResult>(\n\tbindings:\n\t\t| readonly ToolProviderAdapterBinding<TArguments, TResult>[]\n\t\t| ReadonlyMap<string, ToolProviderAdapterBinding<TArguments, TResult>>,\n): ReadonlyMap<string, ToolProviderAdapterBinding<TArguments, TResult>> {\n\tconst result = new Map<string, ToolProviderAdapterBinding<TArguments, TResult>>();\n\tconst bindingList = Array.isArray(bindings)\n\t\t? (bindings as readonly ToolProviderAdapterBinding<TArguments, TResult>[])\n\t\t: undefined;\n\tif (bindingList === undefined) {\n\t\tconst bindingMap = bindings as ReadonlyMap<\n\t\t\tstring,\n\t\t\tToolProviderAdapterBinding<TArguments, TResult>\n\t\t>;\n\t\tfor (const [providerId, binding] of bindingMap.entries()) {\n\t\t\tif (providerId !== binding.providerId) {\n\t\t\t\tthrow new RangeError(\n\t\t\t\t\t`attachToolProviderAdapterRuntime: binding key '${providerId}' must match provider '${binding.providerId}'`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tresult.set(providerId, binding);\n\t\t}\n\t\treturn result;\n\t}\n\tfor (const binding of bindingList) {\n\t\tif (result.has(binding.providerId)) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`attachToolProviderAdapterRuntime: duplicate binding for provider '${binding.providerId}'`,\n\t\t\t);\n\t\t}\n\t\tresult.set(binding.providerId, binding);\n\t}\n\treturn result;\n}\n\nexport function requestToolProviderAdapterRun(\n\tinput: ToolProviderAdapterInput,\n\topts: {\n\t\treadonly runId?: string;\n\t\treadonly attempt?: number;\n\t\treadonly reason?: ToolProviderAdapterRunReason;\n\t\treadonly retryOfOutcomeId?: string;\n\t\treadonly policyRefs?: readonly SourceRef[];\n\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\treadonly metadata?: Record<string, unknown>;\n\t\treadonly requestedAtMs?: number;\n\t} = {},\n): ToolProviderAdapterRunRequested {\n\tconst attempt = opts.attempt ?? 1;\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-adapter-run-requested\",\n\t\trunId: opts.runId ?? defaultToolProviderAdapterRunId(input.adapterInputId, attempt, input),\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\trouteId: input.routeId,\n\t\tproviderId: input.providerId,\n\t\texecutorId: input.executorId,\n\t\tprofileId: input.profileId,\n\t\tattempt,\n\t\treason: sanitizeToolProviderAdapterRunReason(opts.reason, attempt),\n\t\tretryOfOutcomeId: opts.retryOfOutcomeId,\n\t\tpolicyRefs: sanitizeAdapterInputSourceRefs(opts.policyRefs ?? input.policyRefs ?? []),\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t\t...(input.sourceRefs ?? []),\n\t\t\t...(opts.sourceRefs ?? []),\n\t\t]),\n\t\tmetadata: sanitizeProviderGraphVisibleRecord(opts.metadata),\n\t\trequestedAtMs: opts.requestedAtMs,\n\t} satisfies ToolProviderAdapterRunRequested);\n}\n\nexport function toolProviderAdapterRunProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly inputs: Node<ToolProviderAdapterInput>;\n\t\treadonly runRequests?: readonly Node<ToolProviderAdapterRunRequested>[];\n\t\treadonly autoRunReadyInputs?: boolean;\n\t\treadonly now?: () => number;\n\t},\n): ToolProviderAdapterRunBundle {\n\treturn toolProviderAdapterRunProjectorInternal(graph, opts);\n}\n\nexport function toolProviderAdapterRunProjectorInternal(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly inputs: Node<ToolProviderAdapterInput>;\n\t\treadonly runRequests?: readonly Node<ToolProviderAdapterRunRequested>[];\n\t\treadonly autoRunReadyInputs?: boolean;\n\t\treadonly now?: () => number;\n\t\treadonly publicText?: ToolProviderPublicTextPolicy;\n\t\treadonly privateRetentionHooks?: ToolProviderAdapterRunProjectorPrivateRetentionHooks;\n\t},\n): ToolProviderAdapterRunBundle {\n\tconst name = opts.name ?? \"toolProviderAdapterRun\";\n\tconst explicitRunDeps = opts.runRequests ?? [];\n\tconst autoRunReadyInputs = opts.autoRunReadyInputs ?? true;\n\tconst runtime = graph.node<ToolProviderAdapterRunFact>(\n\t\t[opts.inputs, ...explicitRunDeps],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ToolProviderAdapterRunProjectorState>() ?? {\n\t\t\t\tinputs: new Map<string, ToolProviderAdapterInput>(),\n\t\t\t\temittedKeys: new Set<string>(),\n\t\t\t\tstatusKeys: new Set<string>(),\n\t\t\t\tissueKeys: new Set<string>(),\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst input = raw as ToolProviderAdapterInput;\n\t\t\t\tstate.inputs.set(input.adapterInputId, input);\n\t\t\t\topts.privateRetentionHooks?.onAdapterInputKey?.({\n\t\t\t\t\tadapterInputId: input.adapterInputId,\n\t\t\t\t\tdropInput: () => {\n\t\t\t\t\t\tstate.inputs.delete(input.adapterInputId);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (input.status !== \"ready\") continue;\n\t\t\t\tif (autoRunReadyInputs) {\n\t\t\t\t\temitRunRequested(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\trequestToolProviderAdapterRun(input, {\n\t\t\t\t\t\t\trequestedAtMs: opts.now?.(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t} else if (explicitRunDeps.length === 0) {\n\t\t\t\t\temitRunIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\"tool-provider-adapter-run-request-missing\",\n\t\t\t\t\t\t\"Ready tool provider adapter input has no visible run request.\",\n\t\t\t\t\t\tinput.adapterInputId,\n\t\t\t\t\t\t[ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t\temitRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"tool-provider-adapter-run-status\",\n\t\t\t\t\t\t\trunId: defaultToolProviderAdapterRunId(input.adapterInputId, 1, input),\n\t\t\t\t\t\t\tadapterInputId: input.adapterInputId,\n\t\t\t\t\t\t\trequestId: input.requestId,\n\t\t\t\t\t\t\toperationId: input.operationId,\n\t\t\t\t\t\t\tstatus: \"missing-request\",\n\t\t\t\t\t\t\tattempt: 1,\n\t\t\t\t\t\t\tsourceRefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\t\t},\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, 1, explicitRunDeps.length, (raw) => {\n\t\t\t\tif (!isToolProviderAdapterRunRequestedLike(raw)) {\n\t\t\t\t\tconst request = fallbackToolProviderAdapterRunRequest(raw, opts.publicText);\n\t\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\t\"tool-provider-adapter-run-request-invalid-shape\",\n\t\t\t\t\t\t\"Tool provider adapter run request must be a data object with runId, adapterInputId, requestId, operationId, and attempt.\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\t\t\trefs: [ref(\"tool-provider-adapter-run\", request.runId)],\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\temitRunIssueFact(ctx, state, issue, opts.privateRetentionHooks);\n\t\t\t\t\temitRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"tool-provider-adapter-run-status\",\n\t\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\toperationId: request.operationId,\n\t\t\t\t\t\t\tstatus: \"mismatched-request\",\n\t\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\t\tissues: [issue],\n\t\t\t\t\t\t\tsourceRefs: request.sourceRefs,\n\t\t\t\t\t\t},\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t\temitRunAudit(ctx, state, \"tool-provider-adapter-run-request-invalid-shape\", request, {\n\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst request = raw;\n\t\t\t\tconst input = state.inputs.get(request.adapterInputId);\n\t\t\t\tif (input === undefined) {\n\t\t\t\t\tconst replayClassification =\n\t\t\t\t\t\topts.privateRetentionHooks?.classifyRetainedRunRequestReplayEvidence?.(request);\n\t\t\t\t\tif (replayClassification?.kind === \"retention-gap\") {\n\t\t\t\t\t\temitRunRequested(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tsanitizeRetainedToolProviderAdapterRunRequest(request, opts.publicText),\n\t\t\t\t\t\t\topts.privateRetentionHooks,\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\tconst issue = dataIssue(\n\t\t\t\t\t\t\"tool-provider-adapter-run-request-missing-input\",\n\t\t\t\t\t\t\"Tool provider adapter run request references an unknown adapter input.\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\t\t\trefs: sanitizeAdapterInputSourceRefs([\n\t\t\t\t\t\t\t\tref(\"tool-provider-adapter-run\", request.runId),\n\t\t\t\t\t\t\t\t...(request.sourceRefs ?? []),\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\temitRunIssueFact(ctx, state, issue, opts.privateRetentionHooks);\n\t\t\t\t\temitRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"tool-provider-adapter-run-status\",\n\t\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\toperationId: request.operationId,\n\t\t\t\t\t\t\tstatus: \"missing-input\",\n\t\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\t\tissues: [issue],\n\t\t\t\t\t\t\tsourceRefs: sanitizeAdapterInputSourceRefs(request.sourceRefs ?? []),\n\t\t\t\t\t\t},\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst issues = runRequestIdentityIssues(request, input);\n\t\t\t\tif (input.status !== \"ready\") {\n\t\t\t\t\tissues.push(\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"tool-provider-adapter-run-request-input-not-ready\",\n\t\t\t\t\t\t\t\"Tool provider adapter run request requires a ready adapter input.\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\t\t\t\tdetails: { status: input.status },\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\tif (issues.length > 0) {\n\t\t\t\t\tfor (const issue of issues)\n\t\t\t\t\t\temitRunIssueFact(ctx, state, issue, opts.privateRetentionHooks);\n\t\t\t\t\temitRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind: \"tool-provider-adapter-run-status\",\n\t\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\t\toperationId: request.operationId,\n\t\t\t\t\t\t\tstatus: \"mismatched-request\",\n\t\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\t\tissues: Object.freeze(issues),\n\t\t\t\t\t\t\tsourceRefs: sanitizeAdapterInputSourceRefs(request.sourceRefs ?? []),\n\t\t\t\t\t\t},\n\t\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t\t);\n\t\t\t\t\temitRunAudit(ctx, state, \"tool-provider-adapter-run-request-rejected\", request, {\n\t\t\t\t\t\tissueCodes: issues.map((issue) => issue.code),\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\temitRunRequested(\n\t\t\t\t\tctx,\n\t\t\t\t\tstate,\n\t\t\t\t\tsanitizeToolProviderAdapterRunRequest(request, input, opts.publicText),\n\t\t\t\t\topts.privateRetentionHooks,\n\t\t\t\t);\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"toolProviderAdapterRunProjector\", partial: true },\n\t);\n\treturn {\n\t\trequests: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/requests`,\n\t\t\t\"toolProviderAdapterRunRequests\",\n\t\t\t(fact) => (fact.kind === \"request\" ? fact.request : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"toolProviderAdapterRunStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"toolProviderAdapterRunIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"toolProviderAdapterRunAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport type ToolProviderAdapterRunFact =\n\t| { readonly kind: \"request\"; readonly request: ToolProviderAdapterRunRequested }\n\t| { readonly kind: \"status\"; readonly status: ToolProviderAdapterRunStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface ToolProviderAdapterRunProjectorState {\n\tinputs: Map<string, ToolProviderAdapterInput>;\n\temittedKeys: Set<string>;\n\tstatusKeys: Set<string>;\n\tissueKeys: Set<string>;\n\tauditSeq: number;\n}\n\nexport function defaultToolProviderAdapterRunId(\n\tadapterInputId: string,\n\tattempt: number,\n\tinput?: ToolProviderAdapterInput,\n): string {\n\tconst suffix = input === undefined ? \"\" : `:${stableStringHash(stableJsonStringify(input))}`;\n\treturn `${adapterInputId}:run-${attempt}${suffix}`;\n}\n\nexport function sanitizeToolProviderAdapterRunReason(\n\treason: ToolProviderAdapterRunReason | undefined,\n\tattempt: number,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): ToolProviderAdapterRunReason {\n\tconst value = reason ?? (attempt === 1 ? \"initial\" : \"retry\");\n\treturn boundPublicText(value, maxPublicReasonChars(policy)).text as ToolProviderAdapterRunReason;\n}\n\nexport function sanitizeToolProviderAdapterRunRequest(\n\trequest: ToolProviderAdapterRunRequested,\n\tinput: ToolProviderAdapterInput,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): ToolProviderAdapterRunRequested {\n\treturn Object.freeze({\n\t\t...request,\n\t\treason: sanitizeToolProviderAdapterRunReason(request.reason, request.attempt, policy),\n\t\tpolicyRefs: sanitizeAdapterInputSourceRefs(request.policyRefs ?? input.policyRefs ?? []),\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t\t...(input.sourceRefs ?? []),\n\t\t\t...(request.sourceRefs ?? []),\n\t\t]),\n\t\tmetadata: sanitizeProviderGraphVisibleRecord(request.metadata),\n\t} satisfies ToolProviderAdapterRunRequested);\n}\n\nexport function sanitizeRetainedToolProviderAdapterRunRequest(\n\trequest: ToolProviderAdapterRunRequested,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): ToolProviderAdapterRunRequested {\n\tconst policyRefs = sanitizeAdapterInputSourceRefs(request.policyRefs ?? []);\n\tconst sourceRefs = sanitizeAdapterInputSourceRefs(request.sourceRefs ?? []);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(request.metadata);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-adapter-run-requested\",\n\t\trunId: request.runId,\n\t\tadapterInputId: request.adapterInputId,\n\t\trequestId: request.requestId,\n\t\toperationId: request.operationId,\n\t\t...(request.routeId === undefined ? {} : { routeId: request.routeId }),\n\t\t...(request.providerId === undefined ? {} : { providerId: request.providerId }),\n\t\t...(request.executorId === undefined ? {} : { executorId: request.executorId }),\n\t\t...(request.profileId === undefined ? {} : { profileId: request.profileId }),\n\t\tattempt: request.attempt,\n\t\treason: sanitizeToolProviderAdapterRunReason(request.reason, request.attempt, policy),\n\t\t...(request.retryOfOutcomeId === undefined\n\t\t\t? {}\n\t\t\t: { retryOfOutcomeId: request.retryOfOutcomeId }),\n\t\t...(policyRefs.length === 0 ? {} : { policyRefs }),\n\t\t...(sourceRefs.length === 0 ? {} : { sourceRefs }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t...(request.requestedAtMs === undefined ? {} : { requestedAtMs: request.requestedAtMs }),\n\t} satisfies ToolProviderAdapterRunRequested);\n}\n\nexport function isToolProviderAdapterRunRequestedLike(\n\tvalue: unknown,\n): value is ToolProviderAdapterRunRequested {\n\tconst attempt = isRecord(value) ? value.attempt : undefined;\n\treturn (\n\t\tisRecord(value) &&\n\t\tvalue.kind === \"tool-provider-adapter-run-requested\" &&\n\t\ttypeof value.runId === \"string\" &&\n\t\tvalue.runId.length > 0 &&\n\t\ttypeof value.adapterInputId === \"string\" &&\n\t\tvalue.adapterInputId.length > 0 &&\n\t\ttypeof value.requestId === \"string\" &&\n\t\tvalue.requestId.length > 0 &&\n\t\ttypeof value.operationId === \"string\" &&\n\t\tvalue.operationId.length > 0 &&\n\t\ttypeof attempt === \"number\" &&\n\t\tNumber.isInteger(attempt) &&\n\t\tattempt > 0 &&\n\t\ttypeof value.reason === \"string\" &&\n\t\tvalue.reason.length > 0\n\t);\n}\n\nexport function fallbackToolProviderAdapterRunRequest(\n\traw: unknown,\n\tpolicy?: ToolProviderPublicTextPolicy,\n): ToolProviderAdapterRunRequested {\n\tconst record = isRecord(raw) ? raw : {};\n\tconst adapterInputId =\n\t\ttypeof record.adapterInputId === \"string\" && record.adapterInputId.length > 0\n\t\t\t? record.adapterInputId\n\t\t\t: \"<invalid-adapter-input>\";\n\tconst runId =\n\t\ttypeof record.runId === \"string\" && record.runId.length > 0\n\t\t\t? record.runId\n\t\t\t: `${adapterInputId}:invalid-run`;\n\tconst attempt =\n\t\ttypeof record.attempt === \"number\" && Number.isInteger(record.attempt) && record.attempt > 0\n\t\t\t? record.attempt\n\t\t\t: 1;\n\tconst metadata = isRecord(record.metadata)\n\t\t? sanitizeProviderGraphVisibleRecord(record.metadata, policy)\n\t\t: undefined;\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-adapter-run-requested\",\n\t\trunId,\n\t\tadapterInputId,\n\t\trequestId:\n\t\t\ttypeof record.requestId === \"string\" && record.requestId.length > 0\n\t\t\t\t? record.requestId\n\t\t\t\t: \"<invalid-request>\",\n\t\toperationId:\n\t\t\ttypeof record.operationId === \"string\" && record.operationId.length > 0\n\t\t\t\t? record.operationId\n\t\t\t\t: \"<invalid-operation>\",\n\t\tattempt,\n\t\treason: sanitizeToolProviderAdapterRunReason(\n\t\t\ttypeof record.reason === \"string\" && record.reason.length > 0 ? record.reason : \"manual\",\n\t\t\tattempt,\n\t\t\tpolicy,\n\t\t),\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"tool-provider-adapter-run\", runId),\n\t\t\t...sanitizeUntrustedSourceRefs(record.sourceRefs),\n\t\t]),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies ToolProviderAdapterRunRequested);\n}\n\nexport function sanitizeUntrustedSourceRefs(value: unknown): readonly SourceRef[] {\n\tif (!Array.isArray(value)) return [];\n\treturn Object.freeze(\n\t\tvalue\n\t\t\t.filter(\n\t\t\t\t(sourceRef): sourceRef is SourceRef =>\n\t\t\t\t\tisRecord(sourceRef) &&\n\t\t\t\t\ttypeof sourceRef.kind === \"string\" &&\n\t\t\t\t\tsourceRef.kind.length > 0 &&\n\t\t\t\t\ttypeof sourceRef.id === \"string\" &&\n\t\t\t\t\tsourceRef.id.length > 0,\n\t\t\t)\n\t\t\t.map((sourceRef) => ({\n\t\t\t\tkind: sourceRef.kind,\n\t\t\t\tid: sourceRef.id,\n\t\t\t\t...(isRecord(sourceRef.metadata) ? { metadata: sourceRef.metadata } : {}),\n\t\t\t})),\n\t);\n}\n\nexport function runRequestIdentityIssues(\n\trequest: ToolProviderAdapterRunRequested,\n\tinput: ToolProviderAdapterInput,\n): DataIssue[] {\n\tconst refs = sanitizeAdapterInputSourceRefs([\n\t\tref(\"tool-provider-adapter-run\", request.runId),\n\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t...(request.sourceRefs ?? []),\n\t]);\n\tconst issues: DataIssue[] = [];\n\tif (request.kind !== \"tool-provider-adapter-run-requested\") {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-invalid-kind\",\n\t\t\t\t\"Tool provider adapter run request kind must be tool-provider-adapter-run-requested.\",\n\t\t\t\t{ subjectId: request.adapterInputId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.runId.length === 0) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-missing-run-id\",\n\t\t\t\t\"Tool provider adapter run request requires runId.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\trefs,\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\tif (!Number.isInteger(request.attempt) || request.attempt < 1) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-invalid-attempt\",\n\t\t\t\t\"Tool provider adapter run request attempt must be a positive integer.\",\n\t\t\t\t{ subjectId: request.adapterInputId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.requestId !== input.requestId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-request\",\n\t\t\t\t\"Tool provider adapter run request requestId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.operationId !== input.operationId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-operation\",\n\t\t\t\t\"Tool provider adapter run request operationId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.routeId !== undefined && request.routeId !== input.routeId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-route\",\n\t\t\t\t\"Tool provider adapter run request routeId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.providerId !== undefined && request.providerId !== input.providerId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-provider\",\n\t\t\t\t\"Tool provider adapter run request providerId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.executorId !== undefined && request.executorId !== input.executorId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-executor\",\n\t\t\t\t\"Tool provider adapter run request executorId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request.profileId !== undefined && request.profileId !== input.profileId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-stale-profile\",\n\t\t\t\t\"Tool provider adapter run request profileId does not match the adapter input.\",\n\t\t\t\t{ subjectId: input.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tfor (const forbidden of [\n\t\t...forbiddenDataKeys(request),\n\t\t...forbiddenProviderRawMaterialKeys(request),\n\t]) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-run-request-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider adapter run request must not contain runtime-private adapter material.\",\n\t\t\t\t{ subjectId: input.requestId, refs, details: { reason: forbidden.reason } },\n\t\t\t),\n\t\t);\n\t}\n\treturn issues;\n}\n\nexport function emitRunRequested(\n\tctx: Ctx,\n\tstate: ToolProviderAdapterRunProjectorState,\n\trequest: ToolProviderAdapterRunRequested,\n\tprivateRetentionHooks?: ToolProviderAdapterRunProjectorPrivateRetentionHooks,\n): void {\n\tconst key = `${request.runId}:${request.adapterInputId}:${request.attempt}`;\n\tif (state.emittedKeys.has(key)) return;\n\tstate.emittedKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"request\", request } satisfies ToolProviderAdapterRunFact]]);\n\tprivateRetentionHooks?.onRunRequestKey?.({\n\t\tkey,\n\t\trequest,\n\t\tdropKey: () => state.emittedKeys.delete(key),\n\t});\n\temitRunStatus(\n\t\tctx,\n\t\tstate,\n\t\t{\n\t\t\tkind: \"tool-provider-adapter-run-status\",\n\t\t\trunId: request.runId,\n\t\t\tadapterInputId: request.adapterInputId,\n\t\t\trequestId: request.requestId,\n\t\t\toperationId: request.operationId,\n\t\t\tstatus: \"requested\",\n\t\t\tattempt: request.attempt,\n\t\t\tsourceRefs: request.sourceRefs,\n\t\t},\n\t\tprivateRetentionHooks,\n\t);\n\temitRunAudit(ctx, state, \"tool-provider-adapter-run-requested\", request, {\n\t\treason: request.reason,\n\t\tattempt: request.attempt,\n\t});\n}\n\nexport function emitRunStatus(\n\tctx: Ctx,\n\tstate: ToolProviderAdapterRunProjectorState,\n\tstatus: ToolProviderAdapterRunStatus,\n\tprivateRetentionHooks?: ToolProviderAdapterRunProjectorPrivateRetentionHooks,\n): void {\n\tconst cleanSourceRefs =\n\t\tstatus.sourceRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(status.sourceRefs);\n\tconst cleanIssues =\n\t\tstatus.issues === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze(status.issues.map((issue) => sanitizeAdapterInputIssue(issue)));\n\tconst cleanMetadata = sanitizeProviderGraphVisibleRecord(status.metadata);\n\tconst cleanStatus = Object.freeze({\n\t\tkind: status.kind,\n\t\trunId: status.runId,\n\t\tadapterInputId: status.adapterInputId,\n\t\t...(status.requestId === undefined ? {} : { requestId: status.requestId }),\n\t\t...(status.operationId === undefined ? {} : { operationId: status.operationId }),\n\t\tstatus: status.status,\n\t\t...(status.attempt === undefined ? {} : { attempt: status.attempt }),\n\t\t...(status.outcomeId === undefined ? {} : { outcomeId: status.outcomeId }),\n\t\t...(cleanIssues === undefined || cleanIssues.length === 0 ? {} : { issues: cleanIssues }),\n\t\t...(cleanSourceRefs === undefined || cleanSourceRefs.length === 0\n\t\t\t? {}\n\t\t\t: { sourceRefs: cleanSourceRefs }),\n\t\t...(cleanMetadata === undefined ? {} : { metadata: cleanMetadata }),\n\t} satisfies ToolProviderAdapterRunStatus);\n\tconst key = stableJsonStringify({\n\t\trunId: cleanStatus.runId,\n\t\tadapterInputId: cleanStatus.adapterInputId,\n\t\trequestId: cleanStatus.requestId,\n\t\tattempt: cleanStatus.attempt,\n\t\tstatus: cleanStatus.status,\n\t\toutcomeId: cleanStatus.outcomeId,\n\t});\n\tif (state.statusKeys.has(key)) return;\n\tstate.statusKeys.add(key);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"status\", status: cleanStatus } satisfies ToolProviderAdapterRunFact],\n\t]);\n\tprivateRetentionHooks?.onRunStatusKey?.({\n\t\tkey,\n\t\tstatus: cleanStatus,\n\t\tdropKey: () => state.statusKeys.delete(key),\n\t});\n}\n\nexport function emitRunIssue(\n\tctx: Ctx,\n\tstate: ToolProviderAdapterRunProjectorState,\n\tcode: string,\n\tmessage: string,\n\tsubjectId: string,\n\trefs?: readonly SourceRef[],\n\tprivateRetentionHooks?: ToolProviderAdapterRunProjectorPrivateRetentionHooks,\n): void {\n\temitRunIssueFact(\n\t\tctx,\n\t\tstate,\n\t\tdataIssue(code, message, { subjectId, refs }),\n\t\tprivateRetentionHooks,\n\t);\n}\n\nexport function emitRunIssueFact(\n\tctx: Ctx,\n\tstate: ToolProviderAdapterRunProjectorState,\n\tissue: DataIssue,\n\tprivateRetentionHooks?: ToolProviderAdapterRunProjectorPrivateRetentionHooks,\n): void {\n\tconst key = stableJsonStringify({\n\t\tcode: issue.code,\n\t\tsubjectId: issue.subjectId,\n\t\trefs: issue.refs ?? [],\n\t\tdetails: issue.details,\n\t});\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"issue\", issue } satisfies ToolProviderAdapterRunFact]]);\n\tprivateRetentionHooks?.onRunIssueKey?.({\n\t\tkey,\n\t\tissue,\n\t\tdropKey: () => state.issueKeys.delete(key),\n\t});\n}\n\nexport function emitRunAudit(\n\tctx: Ctx,\n\tstate: ToolProviderAdapterRunProjectorState,\n\tkind: string,\n\trequest: ToolProviderAdapterRunRequested,\n\tmetadata?: Record<string, unknown>,\n): void {\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${request.runId}:audit:${state.auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\tsourceRefs: sanitizeAdapterInputSourceRefs(request.sourceRefs ?? []),\n\t\t\t\t\tmetadata: sanitizeProviderGraphVisibleRecord({\n\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t} satisfies ToolProviderAdapterRunFact,\n\t\t],\n\t]);\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport { dataIssue, forEachDepBatch, projectRuntimeFact, ref } from \"./agent-runtime-common.js\";\nimport { candidateFromDecision } from \"./agent-runtime-decision-interpreter.js\";\nimport type {\n\tAgentDecision,\n\tAgentRuntimeAuditRecord,\n\tEffectRunCompletionBundle,\n\tEffectRunCompletionStatus,\n\tEffectRunResult,\n} from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestIssued,\n\tAgentRequestStatus,\n\tAgentRequestStatusChanged,\n\tEffectRun,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\n\nexport function effectRunCompletionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly effectRuns: Node<EffectRun>;\n\t\treadonly decisions?: readonly Node<AgentDecision>[];\n\t\treadonly requestStatuses?: readonly Node<AgentRequestStatusChanged>[];\n\t\treadonly requestFacts?: readonly Node<AgentRequestFact>[];\n\t\treadonly resultCandidates?: readonly Node<EffectRunResult>[];\n\t\treadonly now?: () => number;\n\t},\n): EffectRunCompletionBundle {\n\tconst name = opts.name ?? \"effectRunCompletion\";\n\tconst decisions = opts.decisions ?? [];\n\tconst requestStatuses = opts.requestStatuses ?? [];\n\tconst requestFacts = opts.requestFacts ?? [];\n\tconst resultCandidates = opts.resultCandidates ?? [];\n\tconst deps = [\n\t\topts.effectRuns,\n\t\t...decisions,\n\t\t...requestStatuses,\n\t\t...requestFacts,\n\t\t...resultCandidates,\n\t];\n\tconst decisionStart = 1;\n\tconst requestStatusStart = decisionStart + decisions.length;\n\tconst requestFactStart = requestStatusStart + requestStatuses.length;\n\tconst resultCandidateStart = requestFactStart + requestFacts.length;\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<EffectRunCompletionFact>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<EffectRunCompletionState>() ?? emptyEffectRunCompletionState();\n\t\t\tconst touchedEffectRunIds = new Set<string>();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst run = raw as EffectRun;\n\t\t\t\tstate.runs.set(run.effectRunId, run);\n\t\t\t\ttouchedEffectRunIds.add(run.effectRunId);\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, requestFactStart, requestFacts.length, (raw) => {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\") {\n\t\t\t\t\tstate.requests.set(fact.requestId, fact);\n\t\t\t\t\ttouchedEffectRunIds.add(fact.effectRunId);\n\t\t\t\t\tconst existingStatus = state.statusByRequest.get(fact.requestId);\n\t\t\t\t\tif (existingStatus !== undefined && !statusMatchesRequest(existingStatus, fact)) {\n\t\t\t\t\t\temitEffectRunIssue(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t\"stale-request-status\",\n\t\t\t\t\t\t\t`AgentRequest status for '${fact.requestId}' did not match its issued effectRun/operation identity`,\n\t\t\t\t\t\t\tfact.effectRunId,\n\t\t\t\t\t\t\t[ref(\"agent-request\", fact.requestId)],\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst result = state.resultsByEffectRun.get(fact.effectRunId);\n\t\t\t\t\tif (result !== undefined && fact.required) {\n\t\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\t\t\"late-required-request-after-effect-run-result\",\n\t\t\t\t\t\t\t`Required request '${fact.requestId}' arrived after EffectRun '${fact.effectRunId}' already had a terminal result`,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsubjectId: fact.effectRunId,\n\t\t\t\t\t\t\t\trefs: [\n\t\t\t\t\t\t\t\t\tref(\"agent-request\", fact.requestId),\n\t\t\t\t\t\t\t\t\tref(\"effect-run-result\", result.resultId),\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\tctx.down([\n\t\t\t\t\t\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\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: \"audit\",\n\t\t\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\t\t\tid: `${fact.effectRunId}:late-required-request:${state.issueSeq}`,\n\t\t\t\t\t\t\t\t\t\tkind: \"late-required-request-after-effect-run-result\",\n\t\t\t\t\t\t\t\t\t\tsubjectId: fact.effectRunId,\n\t\t\t\t\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t\t\t\t\t\tsourceRefs: [\n\t\t\t\t\t\t\t\t\t\t\tref(\"agent-request\", fact.requestId),\n\t\t\t\t\t\t\t\t\t\t\tref(\"effect-run-result\", result.resultId),\n\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t} satisfies EffectRunCompletionFact,\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 (fact.kind === \"status\") {\n\t\t\t\t\tacceptRequestStatus(ctx, state, fact);\n\t\t\t\t\ttouchedEffectRunIds.add(fact.effectRunId);\n\t\t\t\t}\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, requestStatusStart, requestStatuses.length, (raw) => {\n\t\t\t\tconst status = raw as AgentRequestStatusChanged;\n\t\t\t\tacceptRequestStatus(ctx, state, status);\n\t\t\t\ttouchedEffectRunIds.add(status.effectRunId);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, resultCandidateStart, resultCandidates.length, (raw) => {\n\t\t\t\tacceptEffectRunResultCandidate(ctx, state, raw as EffectRunResult);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, decisionStart, decisions.length, (raw) => {\n\t\t\t\tconst decision = raw as AgentDecision;\n\t\t\t\tstate.decisions.set(decision.decisionId, decision);\n\t\t\t\ttouchedEffectRunIds.add(decision.effectRunId);\n\t\t\t});\n\t\t\tfor (const decision of state.decisions.values()) {\n\t\t\t\tif (state.resultsByEffectRun.has(decision.effectRunId)) continue;\n\t\t\t\tconst candidate = candidateFromDecision(decision, state, now());\n\t\t\t\tif (candidate === undefined) continue;\n\t\t\t\tacceptEffectRunResultCandidate(ctx, state, candidate);\n\t\t\t}\n\t\t\tfor (const effectRunId of touchedEffectRunIds) {\n\t\t\t\tif (!state.resultsByEffectRun.has(effectRunId)) {\n\t\t\t\t\temitEffectRunStatus(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\teffectRunId,\n\t\t\t\t\t\t\"pending\",\n\t\t\t\t\t\trequiredPendingRequests(effectRunId, state),\n\t\t\t\t\t\trequiredTerminalRequests(effectRunId, state),\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},\n\t\t{ name: `${name}/runtime`, factory: \"effectRunCompletionProjector\" },\n\t);\n\treturn {\n\t\tresults: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/results`,\n\t\t\t\"effectRunCompletionResults\",\n\t\t\t(fact) => (fact.kind === \"result\" ? fact.result : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"effectRunCompletionStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"effectRunCompletionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"effectRunCompletionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport type EffectRunCompletionFact =\n\t| { readonly kind: \"result\"; readonly result: EffectRunResult }\n\t| { readonly kind: \"status\"; readonly status: EffectRunCompletionStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface EffectRunCompletionState {\n\truns: Map<string, EffectRun>;\n\trequests: Map<string, AgentRequestIssued>;\n\tstatusByRequest: Map<string, AgentRequestStatusChanged>;\n\tdecisions: Map<string, AgentDecision>;\n\tresultsByEffectRun: Map<string, EffectRunResult>;\n\tissueSeq: number;\n}\n\nexport function acceptEffectRunResultCandidate(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tcandidate: EffectRunResult,\n): void {\n\tif (!state.runs.has(candidate.effectRunId)) {\n\t\temitEffectRunIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t\"unknown-effect-run-result-candidate\",\n\t\t\t`EffectRunResult candidate '${candidate.resultId}' references unknown EffectRun '${candidate.effectRunId}'`,\n\t\t\tcandidate.effectRunId,\n\t\t\tcandidate.sourceRefs,\n\t\t);\n\t\treturn;\n\t}\n\tconst existing = state.resultsByEffectRun.get(candidate.effectRunId);\n\tif (existing !== undefined) {\n\t\tstate.issueSeq += 1;\n\t\tconst duplicate = sameTerminalResult(existing, candidate);\n\t\tconst code = duplicate ? \"duplicate-effect-run-result\" : \"conflicting-effect-run-result\";\n\t\tconst issue = dataIssue(\n\t\t\tcode,\n\t\t\t`EffectRun '${candidate.effectRunId}' already has a terminal result`,\n\t\t\t{\n\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\trefs: candidate.sourceRefs,\n\t\t\t},\n\t\t);\n\t\tctx.down([\n\t\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"audit\",\n\t\t\t\t\taudit: {\n\t\t\t\t\t\tid: `${candidate.effectRunId}:${code}:${state.issueSeq}`,\n\t\t\t\t\t\tkind: duplicate ? \"effect-run-result-duplicate\" : \"effect-run-result-conflict\",\n\t\t\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t\t},\n\t\t\t\t} satisfies EffectRunCompletionFact,\n\t\t\t],\n\t\t]);\n\t\treturn;\n\t}\n\tstate.resultsByEffectRun.set(candidate.effectRunId, candidate);\n\tctx.down([\n\t\t[\"DATA\", { kind: \"result\", result: candidate } satisfies EffectRunCompletionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"status\",\n\t\t\t\tstatus: {\n\t\t\t\t\teffectRunId: candidate.effectRunId,\n\t\t\t\t\tstate: candidate.status,\n\t\t\t\t\trequiredPending: [],\n\t\t\t\t\trequiredTerminal: requiredTerminalRequests(candidate.effectRunId, state),\n\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${candidate.effectRunId}:terminal-result`,\n\t\t\t\t\tkind: \"effect-run-terminal-result\",\n\t\t\t\t\tsubjectId: candidate.effectRunId,\n\t\t\t\t\tsourceRefs: candidate.sourceRefs,\n\t\t\t\t\tmetadata: { status: candidate.status },\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nexport function emitEffectRunStatus(\n\tctx: Ctx,\n\teffectRunId: string,\n\tstate: EffectRunCompletionStatus[\"state\"],\n\trequiredPending: readonly string[],\n\trequiredTerminal: readonly string[],\n): void {\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"status\",\n\t\t\t\tstatus: { effectRunId, state, requiredPending, requiredTerminal },\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nexport function requiredPendingRequests(\n\teffectRunId: string,\n\tstate: EffectRunCompletionState,\n): readonly string[] {\n\tconst pending: string[] = [];\n\tfor (const request of state.requests.values()) {\n\t\tif (request.effectRunId !== effectRunId || !request.required) continue;\n\t\tconst statusFact = matchingStatusForRequest(state, request);\n\t\tconst status = statusFact?.status;\n\t\tif (status === undefined || !isTerminalRequestStatus(status)) pending.push(request.requestId);\n\t}\n\treturn pending;\n}\n\nexport function requiredTerminalRequests(\n\teffectRunId: string,\n\tstate: EffectRunCompletionState,\n): readonly string[] {\n\tconst terminal: string[] = [];\n\tfor (const request of state.requests.values()) {\n\t\tif (request.effectRunId !== effectRunId || !request.required) continue;\n\t\tconst statusFact = matchingStatusForRequest(state, request);\n\t\tconst status = statusFact?.status;\n\t\tif (status !== undefined && isTerminalRequestStatus(status)) terminal.push(request.requestId);\n\t}\n\treturn terminal;\n}\n\nexport function isTerminalRequestStatus(status: AgentRequestStatus): boolean {\n\treturn (\n\t\tstatus === \"completed\" ||\n\t\tstatus === \"failed\" ||\n\t\tstatus === \"blocked\" ||\n\t\tstatus === \"canceled\" ||\n\t\tstatus === \"timeout\" ||\n\t\tstatus === \"waived\" ||\n\t\tstatus === \"retry-exhausted\"\n\t);\n}\n\nexport function decisionSourceRequestTerminal(\n\tdecision: AgentDecision,\n\tstate: EffectRunCompletionState,\n): boolean {\n\tconst request = state.requests.get(decision.source.requestId);\n\tif (request === undefined) return false;\n\tif (\n\t\trequest.effectRunId !== decision.effectRunId ||\n\t\trequest.operationId !== decision.source.operationId\n\t) {\n\t\treturn false;\n\t}\n\tconst status = matchingStatusForRequest(state, request)?.status;\n\treturn status !== undefined && isTerminalRequestStatus(status);\n}\n\nexport function acceptRequestStatus(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tstatus: AgentRequestStatusChanged,\n): void {\n\tconst request = state.requests.get(status.requestId);\n\tif (request !== undefined && !statusMatchesRequest(status, request)) {\n\t\temitEffectRunIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t\"stale-request-status\",\n\t\t\t`AgentRequest status for '${status.requestId}' did not match its issued effectRun/operation identity`,\n\t\t\trequest.effectRunId,\n\t\t\t[ref(\"agent-request\", status.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tstate.statusByRequest.set(status.requestId, status);\n}\n\nexport function matchingStatusForRequest(\n\tstate: EffectRunCompletionState,\n\trequest: AgentRequestIssued,\n): AgentRequestStatusChanged | undefined {\n\tconst status = state.statusByRequest.get(request.requestId);\n\tif (status === undefined) return undefined;\n\treturn statusMatchesRequest(status, request) ? status : undefined;\n}\n\nexport function statusMatchesRequest(\n\tstatus: AgentRequestStatusChanged,\n\trequest: AgentRequestIssued,\n): boolean {\n\treturn (\n\t\tstatus.effectRunId === request.effectRunId &&\n\t\t(status.operationId === undefined || status.operationId === request.operationId)\n\t);\n}\n\nexport function emitEffectRunIssue(\n\tctx: Ctx,\n\tstate: EffectRunCompletionState,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\tsourceRefs?: readonly SourceRef[],\n): void {\n\tstate.issueSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs: sourceRefs });\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies EffectRunCompletionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${subjectId ?? \"effect-run\"}:${code}:${state.issueSeq}`,\n\t\t\t\t\tkind: \"effect-run-issue\",\n\t\t\t\t\tsubjectId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs,\n\t\t\t\t},\n\t\t\t} satisfies EffectRunCompletionFact,\n\t\t],\n\t]);\n}\n\nexport function sameTerminalResult(a: EffectRunResult, b: EffectRunResult): boolean {\n\treturn (\n\t\ta.status === b.status && a.resultId === b.resultId && JSON.stringify(a) === JSON.stringify(b)\n\t);\n}\n\nexport function emptyEffectRunCompletionState(): EffectRunCompletionState {\n\treturn {\n\t\truns: new Map<string, EffectRun>(),\n\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\tstatusByRequest: new Map<string, AgentRequestStatusChanged>(),\n\t\tdecisions: new Map<string, AgentDecision>(),\n\t\tresultsByEffectRun: new Map<string, EffectRunResult>(),\n\t\tissueSeq: 0,\n\t};\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tdataIssue,\n\tforEachDepBatch,\n\tisRecord,\n\tprojectRuntimeFact,\n\tref,\n} from \"./agent-runtime-common.js\";\nimport type { EffectRunCompletionState } from \"./agent-runtime-effect-completion.js\";\nimport {\n\tdecisionSourceRequestTerminal,\n\trequiredPendingRequests,\n} from \"./agent-runtime-effect-completion.js\";\nimport type {\n\tAgentDecision,\n\tAgentDecisionBlocked,\n\tAgentDecisionContinue,\n\tAgentDecisionFinal,\n\tAgentRuntimeAuditRecord,\n\tEffectRunResult,\n\tStructuredAgentDecisionEnvelope,\n\tStructuredAgentDecisionInterpreterBundle,\n} from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestIssued,\n\tExecutorOutcome,\n} from \"./agent-runtime-types-core.js\";\n\nexport function structuredAgentDecisionInterpreter(\n\tgraph: Graph,\n\toutcomes: Node<ExecutorOutcome>,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly schemaRef?: string;\n\t\treadonly requestFacts?: readonly Node<AgentRequestFact>[];\n\t} = {},\n): StructuredAgentDecisionInterpreterBundle {\n\tconst name = opts.name ?? \"structuredAgentDecisionInterpreter\";\n\tconst requestFacts = opts.requestFacts ?? [];\n\tconst runtime = graph.node<StructuredAgentDecisionInterpreterFact>(\n\t\t[outcomes, ...requestFacts],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<StructuredInterpreterState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\tissueSeq: 0,\n\t\t\t};\n\t\t\tforEachDepBatch(ctx, 1, requestFacts.length, (raw) => {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\") state.requests.set(fact.requestId, fact);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tif (outcome.kind !== \"result\") {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"non-result-outcome\",\n\t\t\t\t\t\t\"Only result outcomes can carry AgentDecision envelopes\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst value = outcome.result.value;\n\t\t\t\tif (!isRecord(value)) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"malformed-agent-decision\",\n\t\t\t\t\t\t\"ExecutorOutcome result must carry a structured agent-decision envelope\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst envelope = value as Partial<StructuredAgentDecisionEnvelope>;\n\t\t\t\tif (envelope.kind !== \"agent-decision\" || !isRecord(envelope.decision)) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"malformed-agent-decision\",\n\t\t\t\t\t\t\"Structured agent-decision envelope is missing kind or decision\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (typeof envelope.schemaRef !== \"string\" || envelope.schemaRef.length === 0) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"missing-agent-decision-schema\",\n\t\t\t\t\t\t\"Structured agent-decision envelope must carry schemaRef evidence\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (opts.schemaRef !== undefined && envelope.schemaRef !== opts.schemaRef) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"agent-decision-schema-mismatch\",\n\t\t\t\t\t\t\"Structured agent-decision envelope schemaRef did not match\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst decision = validateAgentDecision(envelope.decision, outcome);\n\t\t\t\tif (typeof decision === \"string\") {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(ctx, state.issueSeq, outcome, \"malformed-agent-decision\", decision);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst request = state.requests.get(decision.source.requestId);\n\t\t\t\tif (request === undefined) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"missing-agent-decision-request\",\n\t\t\t\t\t\t\"AgentDecision source request must be present in the request ledger\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\trequest.effectRunId !== decision.effectRunId ||\n\t\t\t\t\trequest.operationId !== decision.source.operationId\n\t\t\t\t) {\n\t\t\t\t\tstate.issueSeq += 1;\n\t\t\t\t\temitInterpreterIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate.issueSeq,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\t\"stale-agent-decision-source\",\n\t\t\t\t\t\t\"AgentDecision source request/effectRun/operation identity did not match the request ledger\",\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"decision\", decision } satisfies StructuredAgentDecisionInterpreterFact],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${outcome.outcomeId}:agent-decision-interpreted`,\n\t\t\t\t\t\t\t\tkind: \"agent-decision-interpreted\",\n\t\t\t\t\t\t\t\tsubjectId: decision.effectRunId,\n\t\t\t\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies StructuredAgentDecisionInterpreterFact,\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},\n\t\t{ name: `${name}/runtime`, factory: \"structuredAgentDecisionInterpreter\" },\n\t);\n\treturn {\n\t\tdecisions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/decisions`,\n\t\t\t\"structuredAgentDecisions\",\n\t\t\t(fact) => (fact.kind === \"decision\" ? fact.decision : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"structuredAgentDecisionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"structuredAgentDecisionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport type StructuredAgentDecisionInterpreterFact =\n\t| { readonly kind: \"decision\"; readonly decision: AgentDecision }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface StructuredInterpreterState {\n\trequests: Map<string, AgentRequestIssued>;\n\tissueSeq: number;\n}\n\nexport function emitInterpreterIssue(\n\tctx: Ctx,\n\tseq: number,\n\toutcome: ExecutorOutcome,\n\tcode: string,\n\tmessage: string,\n): void {\n\tconst issue = dataIssue(code, message, {\n\t\tsubjectId: outcome.requestId,\n\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t});\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies StructuredAgentDecisionInterpreterFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${outcome.outcomeId}:agent-decision-issue:${seq}`,\n\t\t\t\t\tkind: \"agent-decision-issue\",\n\t\t\t\t\tsubjectId: outcome.requestId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t},\n\t\t\t} satisfies StructuredAgentDecisionInterpreterFact,\n\t\t],\n\t]);\n}\n\nexport function validateAgentDecision(\n\traw: unknown,\n\toutcome: ExecutorOutcome,\n): AgentDecision | string {\n\tif (!isRecord(raw)) return \"AgentDecision must be an object\";\n\tconst kind = raw.kind;\n\tif (kind !== \"continue\" && kind !== \"final\" && kind !== \"blocked\") {\n\t\treturn \"AgentDecision kind must be continue, final, or blocked\";\n\t}\n\tif (typeof raw.decisionId !== \"string\" || raw.decisionId.length === 0)\n\t\treturn \"AgentDecision decisionId must be a non-empty string\";\n\tif (\n\t\traw.effectRunId === undefined ||\n\t\ttypeof raw.effectRunId !== \"string\" ||\n\t\traw.effectRunId.length === 0\n\t)\n\t\treturn \"AgentDecision effectRunId must be a non-empty string\";\n\tif (typeof raw.agentRunId !== \"string\" || raw.agentRunId.length === 0)\n\t\treturn \"AgentDecision agentRunId must be a non-empty string\";\n\tconst source = raw.source;\n\tif (\n\t\t!isRecord(source) ||\n\t\tsource.requestId !== outcome.requestId ||\n\t\tsource.operationId !== outcome.operationId ||\n\t\tsource.outcomeId !== outcome.outcomeId\n\t) {\n\t\treturn \"AgentDecision source must match the ExecutorOutcome requestId, operationId, and outcomeId\";\n\t}\n\tif (kind === \"continue\") {\n\t\tif (!Array.isArray(raw.next)) return \"AgentDecision.continue next must be an array\";\n\t\tfor (const proposal of raw.next) {\n\t\t\tif (!isAgentRequestProposalLike(proposal, raw.effectRunId)) {\n\t\t\t\treturn \"AgentDecision.continue next entries must be AgentRequestProposal-like objects\";\n\t\t\t}\n\t\t}\n\t\treturn raw as unknown as AgentDecisionContinue;\n\t}\n\tif (kind === \"final\") {\n\t\tif (!isRecord(raw.output) || typeof raw.output.kind !== \"string\")\n\t\t\treturn \"AgentDecision.final output must be an envelope with kind\";\n\t\treturn raw as unknown as AgentDecisionFinal;\n\t}\n\tif (!Array.isArray(raw.needs)) return \"AgentDecision.blocked needs must be an array\";\n\tfor (const need of raw.needs) {\n\t\tif (!isAgentNeedLike(need))\n\t\t\treturn \"AgentDecision.blocked needs entries must be AgentNeed-like objects\";\n\t}\n\treturn raw as unknown as AgentDecisionBlocked;\n}\n\nexport function isAgentRequestProposalLike(value: unknown, effectRunId: string): boolean {\n\tif (!isRecord(value)) return false;\n\tif (value.kind !== \"proposal\") return false;\n\tif (typeof value.proposalId !== \"string\" || value.proposalId.length === 0) return false;\n\tif (value.effectRunId !== effectRunId) return false;\n\treturn (\n\t\tvalue.requestKind === \"context\" ||\n\t\tvalue.requestKind === \"prompt\" ||\n\t\tvalue.requestKind === \"executor\"\n\t);\n}\n\nexport function isAgentNeedLike(value: unknown): boolean {\n\treturn isRecord(value) && typeof value.kind === \"string\" && value.kind.length > 0;\n}\n\nexport function candidateFromDecision(\n\tdecision: AgentDecision,\n\tstate: EffectRunCompletionState,\n\tcompletedAtMs: number,\n): EffectRunResult | undefined {\n\tconst run = state.runs.get(decision.effectRunId);\n\tif (run === undefined) return undefined;\n\tif (!decisionSourceRequestTerminal(decision, state)) return undefined;\n\tconst requiredPending = requiredPendingRequests(decision.effectRunId, state);\n\tif (decision.kind === \"final\") {\n\t\tif (requiredPending.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tkind: \"effect-run-result\",\n\t\t\tresultId: `${decision.effectRunId}:result`,\n\t\t\tstatus: \"completed\",\n\t\t\teffectRunId: decision.effectRunId,\n\t\t\tsubjectRefs: run.subjectRefs,\n\t\t\toperationId: decision.source.operationId,\n\t\t\tsourceRefs: [\n\t\t\t\tref(\"agent-decision\", decision.decisionId),\n\t\t\t\tref(\"executor-outcome\", decision.source.outcomeId),\n\t\t\t],\n\t\t\tcompletedAtMs,\n\t\t\toutput: decision.output,\n\t\t};\n\t}\n\tif (decision.kind === \"blocked\" && requiredPending.length === 0) {\n\t\treturn {\n\t\t\tkind: \"effect-run-result\",\n\t\t\tresultId: `${decision.effectRunId}:result`,\n\t\t\tstatus: \"blocked\",\n\t\t\teffectRunId: decision.effectRunId,\n\t\t\tsubjectRefs: run.subjectRefs,\n\t\t\toperationId: decision.source.operationId,\n\t\t\tsourceRefs: [\n\t\t\t\tref(\"agent-decision\", decision.decisionId),\n\t\t\t\tref(\"executor-outcome\", decision.source.outcomeId),\n\t\t\t],\n\t\t\tcompletedAtMs,\n\t\t\tneeds: decision.needs,\n\t\t};\n\t}\n\treturn undefined;\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport {\n\tboundedPublicText,\n\tdataIssue,\n\tpublicMaterialForbiddenKeys,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeAgentNeed,\n\tsanitizeAgentOutputEnvelope,\n\tsanitizeGraphVisibleRecord,\n\tsanitizeRuntimeMetadata,\n} from \"./agent-runtime-common.js\";\nimport type { AgentRequestStatus, ExecutorOutcome, SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterInput,\n\tToolProviderAdapterRunResult,\n\tToolProviderPublicTextPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function adapterRuntimeIdentity(input: ToolProviderAdapterInput): {\n\treadonly routeId: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n} {\n\tif (input.status !== \"ready\") {\n\t\tthrow new RangeError(\"buildToolProviderExecutorOutcome: adapter input must be ready\");\n\t}\n\tif (\n\t\tinput.routeId === undefined ||\n\t\tinput.executorId === undefined ||\n\t\tinput.profileId === undefined\n\t) {\n\t\tthrow new RangeError(\n\t\t\t\"buildToolProviderExecutorOutcome: ready adapter input is missing route/executor/profile identity\",\n\t\t);\n\t}\n\treturn {\n\t\trouteId: input.routeId,\n\t\texecutorId: input.executorId,\n\t\tprofileId: input.profileId,\n\t};\n}\n\nexport function defaultToolProviderAdapterEvidenceRefs(\n\tinput: ToolProviderAdapterInput,\n): readonly SourceRef[] {\n\treturn sanitizeAdapterInputSourceRefs([\n\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t...(input.sourceRefs ?? []),\n\t]);\n}\n\nexport function buildToolProviderExecutorOutcome<T = unknown>(\n\tinput: ToolProviderAdapterInput,\n\tresult: ToolProviderAdapterRunResult<T>,\n\topts: {\n\t\treadonly attempt?: number;\n\t\treadonly outcomeId?: string;\n\t\treadonly occurredAtMs?: number;\n\t\treadonly runId?: string;\n\t\treadonly publicText?: ToolProviderPublicTextPolicy;\n\t} = {},\n): ExecutorOutcome<T> {\n\tconst ids = adapterRuntimeIdentity(input);\n\tconst attempt = opts.attempt ?? 1;\n\tconst occurredAtMs = result.occurredAtMs ?? opts.occurredAtMs;\n\tconst evidenceRefs =\n\t\tresult.evidenceRefs === undefined\n\t\t\t? defaultToolProviderAdapterEvidenceRefs(input)\n\t\t\t: sanitizeAdapterInputSourceRefs(result.evidenceRefs);\n\tconst issues =\n\t\tresult.issues === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze(\n\t\t\t\t\tresult.issues.map((issue) => sanitizeAdapterInputIssue(issue, opts.publicText)),\n\t\t\t\t);\n\tconst textIssues: DataIssue[] = [];\n\tconst metadata = sanitizeRuntimeMetadata(\n\t\t{\n\t\t\t...(result.metadata ?? {}),\n\t\t\tadapterInputId: input.adapterInputId,\n\t\t\t...(opts.runId === undefined ? {} : { runId: opts.runId }),\n\t\t\tproviderId: input.providerId,\n\t\t\ttoolName: input.toolName,\n\t\t\toperation: input.operation,\n\t\t},\n\t\tinput,\n\t\topts.publicText,\n\t\ttextIssues,\n\t);\n\tif (metadata === undefined && result.metadata !== undefined) {\n\t\ttextIssues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-metadata-redacted\",\n\t\t\t\t\"Tool provider adapter runtime metadata was omitted because it contained runtime-private material.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\tconst base = {\n\t\toutcomeId:\n\t\t\topts.outcomeId ??\n\t\t\t`${input.adapterInputId}:${toolProviderOutcomeRunSegment(opts.runId, attempt)}:${\n\t\t\t\tresult.kind\n\t\t\t}`,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\trouteId: ids.routeId,\n\t\texecutorId: ids.executorId,\n\t\tprofileId: ids.profileId,\n\t\tattempt,\n\t\tevidenceRefs,\n\t\t...(input.input?.inputId === undefined ? {} : { inputId: input.input.inputId }),\n\t\t...(input.input?.inputKind === undefined ? {} : { inputKind: input.input.inputKind }),\n\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\t...(issues === undefined ? {} : { issues }),\n\t\t...(result.usage === undefined ? {} : { usage: result.usage }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t};\n\tconst candidate = (() => {\n\t\tswitch (result.kind) {\n\t\t\tcase \"result\":\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tkind: \"result\",\n\t\t\t\t\tresult: sanitizeAgentOutputEnvelope(result.result, input, opts.publicText, textIssues),\n\t\t\t\t} satisfies ExecutorOutcome<T>;\n\t\t\tcase \"failure\":\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tkind: \"failure\",\n\t\t\t\t\terror: sanitizeAdapterInputIssue(result.error, opts.publicText),\n\t\t\t\t\t...(result.retryable === undefined ? {} : { retryable: result.retryable }),\n\t\t\t\t} satisfies ExecutorOutcome<T>;\n\t\t\tcase \"canceled\":\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tkind: \"canceled\",\n\t\t\t\t\t...(result.reason === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\treason: boundedPublicText(\n\t\t\t\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t\t\t\t\t\"reason\",\n\t\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\t\topts.publicText,\n\t\t\t\t\t\t\t\t\ttextIssues,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}),\n\t\t\t\t} satisfies ExecutorOutcome<T>;\n\t\t\tcase \"timeout\":\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tkind: \"timeout\",\n\t\t\t\t\t...(result.timeoutMs === undefined ? {} : { timeoutMs: result.timeoutMs }),\n\t\t\t\t\t...(result.retryable === undefined ? {} : { retryable: result.retryable }),\n\t\t\t\t} satisfies ExecutorOutcome<T>;\n\t\t\tcase \"blocked\":\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tkind: \"blocked\",\n\t\t\t\t\tneeds: Object.freeze(\n\t\t\t\t\t\tresult.needs.map((need) => sanitizeAgentNeed(need, input, opts.publicText, textIssues)),\n\t\t\t\t\t),\n\t\t\t\t} satisfies ExecutorOutcome<T>;\n\t\t}\n\t})();\n\tconst boundedCandidate =\n\t\ttextIssues.length === 0\n\t\t\t? candidate\n\t\t\t: ({\n\t\t\t\t\t...candidate,\n\t\t\t\t\tissues: Object.freeze([...(candidate.issues ?? []), ...textIssues]),\n\t\t\t\t} satisfies ExecutorOutcome<T>);\n\tconst materialIssues = (boundedCandidate.issues ?? []).filter(\n\t\t(issue) => issue.code === \"tool-provider-adapter-runtime-forbidden-runtime-material\",\n\t);\n\tconst leakIssues = forbiddenAdapterRuntimeMaterialIssues(\n\t\tboundedCandidate,\n\t\tref(\"executor-outcome\", boundedCandidate.outcomeId),\n\t\t\"executor-outcome\",\n\t);\n\tif (leakIssues.length === 0 && materialIssues.length === 0)\n\t\treturn Object.freeze(boundedCandidate);\n\tconst allLeakIssues = Object.freeze([...materialIssues, ...leakIssues]);\n\tconst issue = allLeakIssues[0] ?? dataIssue(\"tool-provider-adapter-runtime-invalid\", \"invalid\");\n\tconst failureMetadata = sanitizeGraphVisibleRecord({\n\t\tadapterInputId: input.adapterInputId,\n\t\t...(opts.runId === undefined ? {} : { runId: opts.runId }),\n\t\tproviderId: input.providerId,\n\t\ttoolName: input.toolName,\n\t\toperation: input.operation,\n\t});\n\treturn Object.freeze({\n\t\tkind: \"failure\",\n\t\toutcomeId: `${input.adapterInputId}:${toolProviderOutcomeRunSegment(\n\t\t\topts.runId,\n\t\t\tattempt,\n\t\t)}:failure`,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\trouteId: ids.routeId,\n\t\texecutorId: ids.executorId,\n\t\tprofileId: ids.profileId,\n\t\tattempt,\n\t\tevidenceRefs,\n\t\t...(input.input?.inputId === undefined ? {} : { inputId: input.input.inputId }),\n\t\t...(input.input?.inputKind === undefined ? {} : { inputKind: input.input.inputKind }),\n\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\t...(failureMetadata === undefined ? {} : { metadata: failureMetadata }),\n\t\terror: issue,\n\t\tretryable: false,\n\t\tissues: allLeakIssues,\n\t} as ExecutorOutcome<T>);\n}\n\nexport function agentRequestStatusForExecutorOutcome(outcome: ExecutorOutcome): AgentRequestStatus {\n\tswitch (outcome.kind) {\n\t\tcase \"result\":\n\t\t\treturn \"completed\";\n\t\tcase \"failure\":\n\t\t\treturn \"failed\";\n\t\tcase \"canceled\":\n\t\t\treturn \"canceled\";\n\t\tcase \"timeout\":\n\t\t\treturn \"timeout\";\n\t\tcase \"blocked\":\n\t\t\treturn \"blocked\";\n\t}\n}\n\nexport function toolProviderOutcomeRunSegment(runId: string | undefined, attempt: number): string {\n\treturn runId === undefined ? `attempt-${attempt}` : `${runId}:attempt-${attempt}`;\n}\n\nexport function adapterRuntimeIssue(\n\tinput: ToolProviderAdapterInput,\n\tcode: string,\n\terror: unknown,\n): DataIssue {\n\treturn dataIssue(code, \"Tool provider adapter runtime failed.\", {\n\t\tsubjectId: input.requestId,\n\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\tdetails: { errorType: error instanceof Error ? error.name : typeof error },\n\t});\n}\n\nexport function forbiddenAdapterRuntimeMaterialIssues(\n\tvalue: unknown,\n\tsubjectRef: SourceRef,\n\tarea: string,\n): readonly DataIssue[] {\n\tif (value === undefined) return [];\n\tconst forbidden = publicMaterialForbiddenKeys(value, \"provider\");\n\tif (forbidden.length === 0) return [];\n\treturn Object.freeze(\n\t\tforbidden.map((entry) =>\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-runtime-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider adapter runtime output must not contain runtime-private adapter material.\",\n\t\t\t\t{ subjectId: subjectRef.id, refs: [subjectRef], details: { area, reason: entry.reason } },\n\t\t\t),\n\t\t),\n\t);\n}\n\nexport function readThenable<T>(value: T | PromiseLike<T>): {\n\treadonly subscribe?: PromiseLike<T>[\"then\"];\n\treadonly error?: unknown;\n} {\n\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return {};\n\ttry {\n\t\tconst then = (value as { then?: unknown }).then;\n\t\tif (typeof then !== \"function\") return {};\n\t\treturn { subscribe: then.bind(value) as PromiseLike<T>[\"then\"] };\n\t} catch (error) {\n\t\treturn { error };\n\t}\n}\n\nexport function outcomeIssues(outcome: ExecutorOutcome): readonly DataIssue[] {\n\tif (outcome.kind === \"failure\") return Object.freeze([outcome.error, ...(outcome.issues ?? [])]);\n\treturn outcome.issues ?? [];\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport type { AgentNeed } from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentOutputEnvelope,\n\tExecutorOutcome,\n\tExecutorOutcomeBase,\n} from \"./agent-runtime-types-core.js\";\n\nexport function fakeExecutorResult<T>(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly result: AgentOutputEnvelope<T> },\n): ExecutorOutcome<T> {\n\treturn { kind: \"result\", ...opts };\n}\n\nexport function fakeExecutorFailure(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & {\n\t\treadonly error: DataIssue;\n\t\treadonly retryable?: boolean;\n\t},\n): ExecutorOutcome {\n\treturn { kind: \"failure\", ...opts };\n}\n\nexport function fakeExecutorBlocked(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly needs: readonly AgentNeed[] },\n): ExecutorOutcome {\n\treturn { kind: \"blocked\", ...opts };\n}\n\nexport function fakeExecutorTimeout(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & {\n\t\treadonly timeoutMs?: number;\n\t\treadonly retryable?: boolean;\n\t},\n): ExecutorOutcome {\n\treturn { kind: \"timeout\", ...opts };\n}\n\nexport function fakeExecutorCanceled(\n\topts: Omit<ExecutorOutcomeBase, \"kind\"> & { readonly reason?: string },\n): ExecutorOutcome {\n\treturn { kind: \"canceled\", ...opts };\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tdataIssue,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeProviderGraphVisibleRecord,\n\tuniqueSourceRefs,\n} from \"./agent-runtime-common.js\";\nimport { outcomeIssues } from \"./agent-runtime-executor-outcome.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { ExecutorOutcome, SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tExecutorOutcomeView,\n\tExecutorOutcomeViewBundle,\n\tExecutorOutcomeViewPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function executorOutcomeViewProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly outcomes: Node<ExecutorOutcome>;\n\t\treadonly policy?: ExecutorOutcomeViewPolicy;\n\t},\n): ExecutorOutcomeViewBundle {\n\tconst name = opts.name ?? \"executorOutcomeViews\";\n\tconst policy = {\n\t\taudience: opts.policy?.audience ?? \"agent-observation\",\n\t\tmaxSummaryChars: opts.policy?.maxSummaryChars ?? 512,\n\t\tincludeIssues: opts.policy?.includeIssues ?? true,\n\t\tincludeUsage: opts.policy?.includeUsage ?? false,\n\t\tincludeMetadata: opts.policy?.includeMetadata ?? false,\n\t} satisfies Required<ExecutorOutcomeViewPolicy>;\n\tconst runtime = graph.node<ExecutorOutcomeViewFact>(\n\t\t[opts.outcomes],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tconst projection = executorOutcomeViewProjectionFromOutcome(outcome, policy);\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", { kind: \"view\", view: projection.view } satisfies ExecutorOutcomeViewFact],\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${outcome.outcomeId}:outcome-view:${policy.audience}`,\n\t\t\t\t\t\t\t\tkind: \"executor-outcome-view-projected\",\n\t\t\t\t\t\t\t\tsubjectId: outcome.requestId,\n\t\t\t\t\t\t\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t\t\t\t\tmetadata: { audience: policy.audience, status: outcome.kind },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ExecutorOutcomeViewFact,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\tfor (const issue of projection.issues) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"issue\", issue } satisfies ExecutorOutcomeViewFact]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"executorOutcomeViewProjector\" },\n\t);\n\treturn {\n\t\tviews: projectRuntimeFact(graph, runtime, `${name}/views`, \"executorOutcomeViews\", (fact) =>\n\t\t\tfact.kind === \"view\" ? fact.view : undefined,\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"executorOutcomeViewIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"executorOutcomeViewAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t};\n}\n\nexport type ExecutorOutcomeViewFact =\n\t| { readonly kind: \"view\"; readonly view: ExecutorOutcomeView }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface ExecutorOutcomeViewProjection {\n\treadonly view: ExecutorOutcomeView;\n\treadonly issues: readonly DataIssue[];\n}\n\nexport interface ExecutorOutcomeSummaryProjection {\n\treadonly summary: string;\n\treadonly truncated: boolean;\n\treadonly originalChars: number;\n\treadonly limitChars: number;\n}\n\nexport function executorOutcomeViewProjectionFromOutcome(\n\toutcome: ExecutorOutcome,\n\tpolicy: Required<ExecutorOutcomeViewPolicy>,\n): ExecutorOutcomeViewProjection {\n\tconst sourceRefs = uniqueSourceRefs([\n\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t...(outcome.evidenceRefs ?? []),\n\t]);\n\tconst summary = projectOutcomeSummary(outcome, policy.maxSummaryChars);\n\tconst issues = Object.freeze([\n\t\t...outcomeIssues(outcome),\n\t\t...(summary.truncated ? [outcomeSummaryTruncationIssue(outcome, summary, policy)] : []),\n\t]);\n\tconst metadata = policy.includeMetadata\n\t\t? sanitizeProviderGraphVisibleRecord(outcome.metadata)\n\t\t: undefined;\n\tconst view = Object.freeze({\n\t\tkind: \"executor-outcome-view\",\n\t\tviewId: `${outcome.outcomeId}:${policy.audience}`,\n\t\taudience: policy.audience,\n\t\toutcomeId: outcome.outcomeId,\n\t\trequestId: outcome.requestId,\n\t\toperationId: outcome.operationId,\n\t\trouteId: outcome.routeId,\n\t\texecutorId: outcome.executorId,\n\t\tprofileId: outcome.profileId,\n\t\tstatus: outcome.kind,\n\t\tsummary: summary.summary,\n\t\tsummaryTruncated: summary.truncated,\n\t\tsummaryChars: summary.originalChars,\n\t\tsummaryLimitChars: summary.limitChars,\n\t\terrorKind: outcomeErrorKind(outcome),\n\t\tretryable: outcomeRetryable(outcome),\n\t\tnextActions: outcomeNextActions(outcome),\n\t\tsourceRefs,\n\t\tmaterialRefs: outcomeMaterialRefs(outcome),\n\t\tissues: policy.includeIssues && issues.length > 0 ? issues : undefined,\n\t\tusage: policy.includeUsage ? outcome.usage : undefined,\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies ExecutorOutcomeView);\n\treturn Object.freeze({ view, issues });\n}\n\nexport function projectOutcomeSummary(\n\toutcome: ExecutorOutcome,\n\tmaxChars: number,\n): ExecutorOutcomeSummaryProjection {\n\tconst summary = outcomeSummary(outcome);\n\tconst limitChars = Math.max(0, maxChars);\n\tif (summary.length <= limitChars) {\n\t\treturn Object.freeze({\n\t\t\tsummary,\n\t\t\ttruncated: false,\n\t\t\toriginalChars: summary.length,\n\t\t\tlimitChars,\n\t\t});\n\t}\n\tconst bounded =\n\t\tlimitChars <= 1\n\t\t\t? summary.slice(0, limitChars)\n\t\t\t: limitChars <= 3\n\t\t\t\t? summary.slice(0, limitChars)\n\t\t\t\t: `${summary.slice(0, limitChars - 3)}...`;\n\treturn Object.freeze({\n\t\tsummary: bounded,\n\t\ttruncated: true,\n\t\toriginalChars: summary.length,\n\t\tlimitChars,\n\t});\n}\n\nexport function outcomeSummaryTruncationIssue(\n\toutcome: ExecutorOutcome,\n\tsummary: ExecutorOutcomeSummaryProjection,\n\tpolicy: Required<ExecutorOutcomeViewPolicy>,\n): DataIssue {\n\treturn dataIssue(\n\t\t\"executor-outcome-view-summary-truncated\",\n\t\t\"ExecutorOutcome view summary was truncated; inspect material refs or the source outcome for full detail\",\n\t\t{\n\t\t\tsubjectId: outcome.requestId,\n\t\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\tseverity: \"warning\",\n\t\t\tdetails: {\n\t\t\t\taudience: policy.audience,\n\t\t\t\toutcomeId: outcome.outcomeId,\n\t\t\t\toriginalChars: summary.originalChars,\n\t\t\t\tlimitChars: summary.limitChars,\n\t\t\t},\n\t\t},\n\t);\n}\n\nexport function outcomeSummary(outcome: ExecutorOutcome): string {\n\tif (outcome.kind === \"result\") {\n\t\tif (outcome.result.summary !== undefined && outcome.result.summary.length > 0)\n\t\t\treturn outcome.result.summary;\n\t\treturn `Executor result '${outcome.result.kind}' is available via source refs`;\n\t}\n\tif (outcome.kind === \"failure\") return outcome.error.message;\n\tif (outcome.kind === \"blocked\") {\n\t\tconst needKinds = outcome.needs.map((need) => need.kind).join(\", \");\n\t\treturn needKinds.length > 0 ? `Executor blocked: ${needKinds}` : \"Executor blocked\";\n\t}\n\tif (outcome.kind === \"timeout\") {\n\t\treturn outcome.timeoutMs === undefined\n\t\t\t? \"Executor timed out\"\n\t\t\t: `Executor timed out after ${outcome.timeoutMs}ms`;\n\t}\n\treturn outcome.reason ?? \"Executor canceled\";\n}\n\nexport function outcomeErrorKind(outcome: ExecutorOutcome): string | undefined {\n\tif (outcome.kind === \"failure\") return outcome.error.code;\n\tif (outcome.kind === \"timeout\") return \"timeout\";\n\tif (outcome.kind === \"blocked\") return outcome.needs[0]?.kind ?? \"blocked\";\n\tif (outcome.kind === \"canceled\") return \"canceled\";\n\treturn undefined;\n}\n\nexport function outcomeRetryable(outcome: ExecutorOutcome): boolean | undefined {\n\tif (outcome.kind === \"failure\" || outcome.kind === \"timeout\") return outcome.retryable;\n\treturn undefined;\n}\n\nexport function outcomeNextActions(outcome: ExecutorOutcome): readonly string[] | undefined {\n\tif (outcome.kind === \"blocked\") return Object.freeze(outcome.needs.map((need) => need.kind));\n\tif ((outcome.kind === \"failure\" || outcome.kind === \"timeout\") && outcome.retryable === true) {\n\t\treturn Object.freeze([\"retry-or-route\"]);\n\t}\n\treturn undefined;\n}\n\nexport function outcomeMaterialRefs(outcome: ExecutorOutcome): readonly SourceRef[] | undefined {\n\tconst refs =\n\t\toutcome.kind === \"result\"\n\t\t\t? [...(outcome.result.refs ?? [])]\n\t\t\t: outcome.kind === \"blocked\"\n\t\t\t\t? outcome.needs.flatMap((need) => [...(need.refs ?? [])])\n\t\t\t\t: [];\n\treturn refs.length === 0 ? undefined : uniqueSourceRefs(refs);\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tboundPublicText,\n\tcloneGraphVisibleMaterial,\n\tmaxPublicReasonChars,\n\tpublicMaterialForbiddenKeys,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeProviderGraphVisibleRecord,\n} from \"./agent-runtime-common.js\";\nimport { isTerminalRequestStatus } from \"./agent-runtime-effect-completion.js\";\nimport type {\n\tAgentDecisionContinue,\n\tAgentRuntimeAuditRecord,\n} from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestAdmitted,\n\tAgentRequestFact,\n\tAgentRequestInput,\n\tAgentRequestIssued,\n\tAgentRequestLedgerBundle,\n\tAgentRequestProposal,\n\tAgentRequestStatusChanged,\n\tAgentRequestViews,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\n\nexport function agentRequestProposalFromDecision(\n\tdecision: AgentDecisionContinue,\n\tproposal: Omit<AgentRequestProposal, \"kind\" | \"effectRunId\" | \"agentRunId\" | \"sourceDecisionId\">,\n): AgentRequestProposal {\n\treturn {\n\t\tkind: \"proposal\",\n\t\t...proposal,\n\t\teffectRunId: decision.effectRunId,\n\t\tagentRunId: decision.agentRunId,\n\t\tsourceDecisionId: decision.decisionId,\n\t\tevidenceRefs: proposal.evidenceRefs ?? decision.evidenceRefs,\n\t};\n}\n\nexport function admitAgentRequestProposal(\n\tproposal: AgentRequestProposal,\n\topts: {\n\t\treadonly requestId: string;\n\t\treadonly operationId: string;\n\t\treadonly admittedAtMs?: number;\n\t\treadonly reason?: string;\n\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\treadonly metadata?: Record<string, unknown>;\n\t},\n): AgentRequestAdmitted {\n\tconst sourceRefs =\n\t\topts.sourceRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(opts.sourceRefs);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(opts.metadata);\n\treturn {\n\t\tkind: \"admitted\",\n\t\tproposalId: proposal.proposalId,\n\t\trequestId: opts.requestId,\n\t\toperationId: opts.operationId,\n\t\teffectRunId: proposal.effectRunId,\n\t\tagentRunId: proposal.agentRunId,\n\t\tadmittedAtMs: opts.admittedAtMs,\n\t\t...(opts.reason === undefined\n\t\t\t? {}\n\t\t\t: { reason: boundPublicText(opts.reason, maxPublicReasonChars()).text }),\n\t\t...(sourceRefs === undefined || sourceRefs.length === 0 ? {} : { sourceRefs }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t};\n}\n\nexport function issueAgentRequest(\n\tproposal: AgentRequestProposal,\n\tadmission: AgentRequestAdmitted,\n\topts: { readonly issuedAtMs?: number; readonly sourceRefs?: readonly SourceRef[] } = {},\n): AgentRequestIssued {\n\tconst input = sanitizeAgentRequestInput(proposal.input);\n\tconst payload = sanitizeAgentRequestMaterial(proposal.payload);\n\tconst sourceRefs = sanitizeAdapterInputSourceRefs(opts.sourceRefs ?? admission.sourceRefs ?? []);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(proposal.metadata);\n\treturn {\n\t\tkind: \"issued\",\n\t\trequestId: admission.requestId,\n\t\toperationId: admission.operationId,\n\t\teffectRunId: admission.effectRunId,\n\t\tagentRunId: admission.agentRunId,\n\t\tproposalId: proposal.proposalId,\n\t\tparentRequestId: proposal.parentRequestId,\n\t\trequestKind: proposal.requestKind,\n\t\trequired: proposal.required ?? true,\n\t\t...(input === undefined ? {} : { input }),\n\t\t...(payload === undefined ? {} : { payload }),\n\t\tissuedAtMs: opts.issuedAtMs,\n\t\t...(sourceRefs.length === 0 ? {} : { sourceRefs }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t};\n}\n\nexport function sanitizeAgentRequestInput<T>(\n\tinput: AgentRequestInput<T> | undefined,\n): AgentRequestInput<T> | undefined {\n\tif (input === undefined) return undefined;\n\tconst {\n\t\tvalue: rawValue,\n\t\tsubjectRefs: rawSubjectRefs,\n\t\tmetadata: rawMetadata,\n\t\t...inputFields\n\t} = input;\n\tconst value = sanitizeAgentRequestMaterial(rawValue);\n\tconst subjectRefs =\n\t\trawSubjectRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(rawSubjectRefs);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(rawMetadata);\n\treturn Object.freeze({\n\t\t...inputFields,\n\t\t...(value === undefined ? {} : { value }),\n\t\t...(subjectRefs === undefined || subjectRefs.length === 0 ? {} : { subjectRefs }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies AgentRequestInput<T>) as AgentRequestInput<T>;\n}\n\nexport function sanitizeAgentRequestMaterial<T>(value: T | undefined): T | undefined {\n\tif (value === undefined) return undefined;\n\tif (publicMaterialForbiddenKeys(value, \"provider\").length > 0) return undefined;\n\treturn cloneGraphVisibleMaterial(value) as T;\n}\n\nexport function sanitizeAgentRequestIssued(request: AgentRequestIssued): AgentRequestIssued {\n\tconst input = sanitizeAgentRequestInput(request.input);\n\tconst payload = sanitizeAgentRequestMaterial(request.payload);\n\tconst sourceRefs =\n\t\trequest.sourceRefs === undefined\n\t\t\t? undefined\n\t\t\t: sanitizeAdapterInputSourceRefs(request.sourceRefs);\n\tconst metadata = sanitizeProviderGraphVisibleRecord(request.metadata);\n\treturn Object.freeze({\n\t\tkind: \"issued\",\n\t\trequestId: request.requestId,\n\t\toperationId: request.operationId,\n\t\teffectRunId: request.effectRunId,\n\t\t...(request.agentRunId === undefined ? {} : { agentRunId: request.agentRunId }),\n\t\t...(request.proposalId === undefined ? {} : { proposalId: request.proposalId }),\n\t\t...(request.parentRequestId === undefined ? {} : { parentRequestId: request.parentRequestId }),\n\t\trequestKind: request.requestKind,\n\t\trequired: request.required,\n\t\t...(input === undefined ? {} : { input }),\n\t\t...(payload === undefined ? {} : { payload }),\n\t\t...(request.issuedAtMs === undefined ? {} : { issuedAtMs: request.issuedAtMs }),\n\t\t...(sourceRefs === undefined || sourceRefs.length === 0 ? {} : { sourceRefs }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies AgentRequestIssued);\n}\n\nexport function agentRequestLedgerViews(\n\tgraph: Graph,\n\tfacts: Node<AgentRequestFact>,\n\topts: { readonly name?: string } = {},\n): AgentRequestLedgerBundle {\n\tconst name = opts.name ?? \"agentRequests\";\n\tconst views = graph.node<AgentRequestViews>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tconst prev = ctx.state.get<AgentRequestViewsState>() ?? emptyAgentRequestViewsState();\n\t\t\tconst next = cloneAgentRequestViewsState(prev);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\treduceAgentRequestViews(next, fact);\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", freezeAgentRequestViews(next)]]);\n\t\t},\n\t\t{ name: `${name}/views`, factory: \"agentRequestLedgerViews\" },\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"rejected\") ctx.down([[\"DATA\", sanitizeAdapterInputIssue(fact.issue)]]);\n\t\t\t\tif (fact.kind === \"status\") {\n\t\t\t\t\tfor (const issue of fact.issues ?? []) {\n\t\t\t\t\t\tctx.down([[\"DATA\", sanitizeAdapterInputIssue(issue)]]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/issues`, factory: \"agentRequestLedgerIssues\" },\n\t);\n\tconst audit = graph.node<AgentRuntimeAuditRecord>(\n\t\t[facts],\n\t\t(ctx) => {\n\t\t\tlet seq = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tseq += 1;\n\t\t\t\tconst fact = raw as AgentRequestFact;\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\tid: `${name}:ledger:${seq}`,\n\t\t\t\t\t\t\tkind: `agent-request-${fact.kind}`,\n\t\t\t\t\t\t\tsubjectId: \"requestId\" in fact ? fact.requestId : fact.proposalId,\n\t\t\t\t\t\t} satisfies AgentRuntimeAuditRecord,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tctx.state.set(seq);\n\t\t},\n\t\t{ name: `${name}/audit`, factory: \"agentRequestLedgerAudit\" },\n\t);\n\treturn { views, issues, audit };\n}\n\nexport interface AgentRequestViewsState {\n\trequestsById: Map<string, AgentRequestIssued>;\n\trequestsByEffectRun: Map<string, string[]>;\n\tstatusByRequest: Map<string, AgentRequestStatusChanged>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n\tauditSeq: number;\n}\n\nexport function emptyAgentRequestViewsState(): AgentRequestViewsState {\n\treturn {\n\t\trequestsById: new Map<string, AgentRequestIssued>(),\n\t\trequestsByEffectRun: new Map<string, string[]>(),\n\t\tstatusByRequest: new Map<string, AgentRequestStatusChanged>(),\n\t\tissues: [],\n\t\taudit: [],\n\t\tauditSeq: 0,\n\t};\n}\n\nexport function cloneAgentRequestViewsState(state: AgentRequestViewsState): AgentRequestViewsState {\n\treturn {\n\t\trequestsById: new Map(state.requestsById),\n\t\trequestsByEffectRun: new Map(Array.from(state.requestsByEffectRun, ([k, v]) => [k, [...v]])),\n\t\tstatusByRequest: new Map(state.statusByRequest),\n\t\tissues: [...state.issues],\n\t\taudit: [...state.audit],\n\t\tauditSeq: state.auditSeq,\n\t};\n}\n\nexport function reduceAgentRequestViews(\n\tstate: AgentRequestViewsState,\n\tfact: AgentRequestFact,\n): void {\n\tstate.auditSeq += 1;\n\tif (fact.kind === \"issued\") {\n\t\tconst request = sanitizeAgentRequestIssued(fact);\n\t\tstate.requestsById.set(request.requestId, request);\n\t\tconst requestIds = state.requestsByEffectRun.get(request.effectRunId) ?? [];\n\t\tif (!requestIds.includes(request.requestId)) requestIds.push(request.requestId);\n\t\tstate.requestsByEffectRun.set(request.effectRunId, requestIds);\n\t\tstate.statusByRequest.set(request.requestId, {\n\t\t\tkind: \"status\",\n\t\t\trequestId: request.requestId,\n\t\t\toperationId: request.operationId,\n\t\t\teffectRunId: request.effectRunId,\n\t\t\tstatus: \"issued\",\n\t\t\tsourceRefs: [ref(\"agent-request\", request.requestId)],\n\t\t});\n\t} else if (fact.kind === \"status\") {\n\t\tconst status = sanitizeAgentRequestStatusChanged(fact);\n\t\tstate.statusByRequest.set(status.requestId, status);\n\t\tif (status.issues !== undefined) state.issues.push(...status.issues);\n\t} else if (fact.kind === \"rejected\") {\n\t\tstate.issues.push(sanitizeAdapterInputIssue(fact.issue));\n\t}\n\tstate.audit.push({\n\t\tid: `agent-request-ledger:${state.auditSeq}`,\n\t\tkind: `agent-request-${fact.kind}`,\n\t\tsubjectId: \"requestId\" in fact ? fact.requestId : fact.proposalId,\n\t});\n}\n\nexport function sanitizeAgentRequestStatusChanged(\n\tstatus: AgentRequestStatusChanged,\n): AgentRequestStatusChanged {\n\tconst sourceRefs =\n\t\tstatus.sourceRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(status.sourceRefs);\n\tconst issues =\n\t\tstatus.issues === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze(status.issues.map((issue) => sanitizeAdapterInputIssue(issue)));\n\tconst metadata = sanitizeProviderGraphVisibleRecord(status.metadata);\n\treturn Object.freeze({\n\t\tkind: \"status\",\n\t\trequestId: status.requestId,\n\t\t...(status.operationId === undefined ? {} : { operationId: status.operationId }),\n\t\teffectRunId: status.effectRunId,\n\t\tstatus: status.status,\n\t\t...(sourceRefs === undefined || sourceRefs.length === 0 ? {} : { sourceRefs }),\n\t\t...(issues === undefined || issues.length === 0 ? {} : { issues }),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies AgentRequestStatusChanged);\n}\n\nexport function freezeAgentRequestViews(state: AgentRequestViewsState): AgentRequestViews {\n\tconst pending = Array.from(state.requestsById.values()).filter((request) => {\n\t\tconst status = state.statusByRequest.get(request.requestId)?.status;\n\t\treturn status === undefined || !isTerminalRequestStatus(status);\n\t});\n\tconst awaitingProvider = pending.filter(\n\t\t(request) => state.statusByRequest.get(request.requestId)?.status === \"awaiting-provider\",\n\t);\n\treturn {\n\t\trequestsById: new Map(state.requestsById),\n\t\trequestsByEffectRun: new Map(\n\t\t\tArray.from(state.requestsByEffectRun, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tstatusByRequest: new Map(state.statusByRequest),\n\t\tpending: Object.freeze(pending),\n\t\tawaitingProvider: Object.freeze(awaitingProvider),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n","import { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tdataIssue,\n\tforEachDepBatch,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n} from \"./agent-runtime-common.js\";\nimport type {\n\tAgentRequestSatisfactionBundle,\n\tAgentRuntimeAuditRecord,\n\tContextContribution,\n\tPromptBundle,\n} from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestIssued,\n\tAgentRequestStatus,\n\tAgentRequestStatusChanged,\n\tExecutorOutcome,\n\tExecutorProfile,\n\tExecutorRoute,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\n\nexport interface RequestSatisfactionState {\n\trequests: Map<string, AgentRequestIssued>;\n\tprofiles: Map<string, ExecutorProfile>;\n\troutes: Map<string, ExecutorRoute>;\n\toutcomes: Map<string, ExecutorOutcome>;\n\tcontexts: Map<string, ContextContribution>;\n\tprompts: Map<string, PromptBundle>;\n\tcompatibleRoutesByRouteId: Map<string, ExecutorRoute>;\n\tterminalRequests: Set<string>;\n\tacceptedTerminalFactIds: Set<string>;\n\tissueKeys: Set<string>;\n\tstatusKeys: Set<string>;\n\tissueSeq: number;\n\tauditSeq: number;\n}\n\nexport function requestSatisfactionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly requestFacts: Node<AgentRequestFact>;\n\t\treadonly executorProfiles?: readonly Node<ExecutorProfile>[];\n\t\treadonly executorRoutes?: readonly Node<ExecutorRoute>[];\n\t\treadonly executorOutcomes?: readonly Node<ExecutorOutcome>[];\n\t\treadonly contextContributions?: readonly Node<ContextContribution>[];\n\t\treadonly promptBundles?: readonly Node<PromptBundle>[];\n\t},\n): AgentRequestSatisfactionBundle {\n\tconst name = opts.name ?? \"requestSatisfaction\";\n\tconst profileDeps = opts.executorProfiles ?? [];\n\tconst routeDeps = opts.executorRoutes ?? [];\n\tconst outcomeDeps = opts.executorOutcomes ?? [];\n\tconst contextDeps = opts.contextContributions ?? [];\n\tconst promptDeps = opts.promptBundles ?? [];\n\tconst deps = [\n\t\topts.requestFacts,\n\t\t...profileDeps,\n\t\t...routeDeps,\n\t\t...outcomeDeps,\n\t\t...contextDeps,\n\t\t...promptDeps,\n\t];\n\tconst profileStart = 1;\n\tconst routeStart = profileStart + profileDeps.length;\n\tconst outcomeStart = routeStart + routeDeps.length;\n\tconst contextStart = outcomeStart + outcomeDeps.length;\n\tconst promptStart = contextStart + contextDeps.length;\n\tconst runtime = graph.node<AgentRequestSatisfactionFact>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<RequestSatisfactionState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\tprofiles: new Map<string, ExecutorProfile>(),\n\t\t\t\troutes: new Map<string, ExecutorRoute>(),\n\t\t\t\toutcomes: new Map<string, ExecutorOutcome>(),\n\t\t\t\tcontexts: new Map<string, ContextContribution>(),\n\t\t\t\tprompts: new Map<string, PromptBundle>(),\n\t\t\t\tcompatibleRoutesByRouteId: new Map<string, ExecutorRoute>(),\n\t\t\t\tterminalRequests: new Set<string>(),\n\t\t\t\tacceptedTerminalFactIds: new Set<string>(),\n\t\t\t\tissueKeys: new Set<string>(),\n\t\t\t\tstatusKeys: new Set<string>(),\n\t\t\t\tissueSeq: 0,\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tif ((fact as AgentRequestFact).kind === \"issued\") {\n\t\t\t\t\tconst request = fact as AgentRequestIssued;\n\t\t\t\t\tstate.requests.set(request.requestId, request);\n\t\t\t\t\temitStatus(ctx, state, request, initialRequestStatus(request), [\n\t\t\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, profileStart, profileDeps.length, (raw) => {\n\t\t\t\tconst profile = raw as ExecutorProfile;\n\t\t\t\tstate.profiles.set(profile.profileId, profile);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, routeStart, routeDeps.length, (raw) => {\n\t\t\t\tconst route = raw as ExecutorRoute;\n\t\t\t\tstate.routes.set(route.routeId, route);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, outcomeStart, outcomeDeps.length, (raw) => {\n\t\t\t\tconst outcome = raw as ExecutorOutcome;\n\t\t\t\tstate.outcomes.set(outcome.outcomeId, outcome);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, contextStart, contextDeps.length, (raw) => {\n\t\t\t\tconst contribution = raw as ContextContribution;\n\t\t\t\tstate.contexts.set(contribution.contributionId, contribution);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, promptStart, promptDeps.length, (raw) => {\n\t\t\t\tconst prompt = raw as PromptBundle;\n\t\t\t\tstate.prompts.set(prompt.promptId, prompt);\n\t\t\t});\n\t\t\tevaluateRequestSatisfaction(ctx, state);\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"requestSatisfactionProjector\" },\n\t);\n\tconst status = graph.node<AgentRequestStatusChanged>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"status\") ctx.down([[\"DATA\", typed.status]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"requestSatisfactionStatus\" },\n\t);\n\tconst issues = graph.node<DataIssue>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"issue\") ctx.down([[\"DATA\", typed.issue]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/issues`, factory: \"requestSatisfactionIssues\" },\n\t);\n\tconst audit = graph.node<AgentRuntimeAuditRecord>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as AgentRequestSatisfactionFact;\n\t\t\t\tif (typed.kind === \"audit\") ctx.down([[\"DATA\", typed.audit]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/audit`, factory: \"requestSatisfactionAudit\" },\n\t);\n\treturn { status, issues, audit };\n}\n\nexport type AgentRequestSatisfactionFact =\n\t| { readonly kind: \"status\"; readonly status: AgentRequestStatusChanged }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport function initialRequestStatus(request: AgentRequestIssued): AgentRequestStatus {\n\tif (request.requestKind === \"context\") return \"awaiting-context\";\n\tif (request.requestKind === \"prompt\") return \"awaiting-prompt\";\n\treturn \"awaiting-route\";\n}\n\nexport function evaluateRequestSatisfaction(ctx: Ctx, state: RequestSatisfactionState): void {\n\tfor (const route of state.routes.values()) handleRoute(ctx, state, route);\n\tfor (const contribution of state.contexts.values())\n\t\thandleContextContribution(ctx, state, contribution);\n\tfor (const prompt of state.prompts.values()) handlePromptBundle(ctx, state, prompt);\n\tfor (const outcome of state.outcomes.values()) handleExecutorOutcome(ctx, state, outcome);\n}\n\nexport function handleRoute(ctx: Ctx, state: RequestSatisfactionState, route: ExecutorRoute): void {\n\tconst request = state.requests.get(route.requestId);\n\tif (request === undefined) {\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (state.compatibleRoutesByRouteId.get(route.routeId)?.requestId !== request.requestId) {\n\t\t\temitIssueOnce(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`late-route:${route.routeId}`,\n\t\t\t\t\"late-route-after-terminal\",\n\t\t\t\t`ExecutorRoute '${route.routeId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\t\trequest.requestId,\n\t\t\t\t[ref(\"executor-route\", route.routeId), ref(\"agent-request\", request.requestId)],\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\tif (request.operationId !== route.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-route:${route.routeId}`,\n\t\t\t\"stale-route-operation\",\n\t\t\t`ExecutorRoute '${route.routeId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-route\", route.routeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst profile = state.profiles.get(route.profileId);\n\tif (profile === undefined) {\n\t\treturn;\n\t}\n\tconst compatibilityIssue = routeCompatibilityIssue(request, route, profile);\n\tif (compatibilityIssue !== undefined) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`route-incompatible:${route.routeId}:${compatibilityIssue}`,\n\t\t\tcompatibilityIssue,\n\t\t\t`ExecutorRoute '${route.routeId}' is incompatible with request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\tref(\"executor-profile\", profile.profileId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tstate.compatibleRoutesByRouteId.set(route.routeId, route);\n\temitStatusOnce(\n\t\tctx,\n\t\tstate,\n\t\t`route:${route.routeId}:awaiting-provider`,\n\t\trequest,\n\t\t\"awaiting-provider\",\n\t\t[\n\t\t\tref(\"executor-route\", route.routeId),\n\t\t\tref(\"executor-profile\", profile.profileId),\n\t\t\tref(\"agent-request\", request.requestId),\n\t\t],\n\t);\n}\n\nexport function handleExecutorOutcome(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\toutcome: ExecutorOutcome,\n): void {\n\tconst request = state.requests.get(outcome.requestId);\n\tif (request === undefined) {\n\t\treturn;\n\t}\n\tif (request.operationId !== outcome.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-outcome:${outcome.outcomeId}`,\n\t\t\t\"stale-outcome-operation\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst route = state.compatibleRoutesByRouteId.get(outcome.routeId);\n\tif (route === undefined || route.requestId !== request.requestId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-route:${outcome.outcomeId}`,\n\t\t\t\"missing-compatible-route\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' has no compatible route for request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tconst outcomeIssue = outcomeCompatibilityIssue(request, route, outcome);\n\tif (outcomeIssue !== undefined) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`outcome-incompatible:${outcome.outcomeId}:${outcomeIssue}`,\n\t\t\toutcomeIssue,\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' is incompatible with route '${route.routeId}' for request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (state.acceptedTerminalFactIds.has(`outcome:${outcome.outcomeId}`)) return;\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-outcome:${outcome.outcomeId}`,\n\t\t\t\"duplicate-terminal-outcome\",\n\t\t\t`ExecutorOutcome '${outcome.outcomeId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"executor-outcome\", outcome.outcomeId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tstate.terminalRequests.add(request.requestId);\n\tstate.acceptedTerminalFactIds.add(`outcome:${outcome.outcomeId}`);\n\tconst status = outcomeStatus(outcome);\n\temitStatus(ctx, state, request, status, [\n\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\tref(\"executor-route\", route.routeId),\n\t\tref(\"agent-request\", request.requestId),\n\t]);\n}\n\nexport function handleContextContribution(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tcontribution: ContextContribution,\n): void {\n\tconst request = state.requests.get(contribution.requestId);\n\tif (request === undefined) return;\n\tif (request.operationId !== contribution.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-context:${contribution.contributionId}`,\n\t\t\t\"stale-context-operation\",\n\t\t\t`ContextContribution '${contribution.contributionId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (request.requestKind !== \"context\") {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`wrong-context-kind:${contribution.contributionId}`,\n\t\t\t\"wrong-kind-context-satisfaction\",\n\t\t\t`ContextContribution '${contribution.contributionId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (\n\t\t\tstate.acceptedTerminalFactIds.has(`context:${contribution.contributionId}`) ||\n\t\t\tstate.statusKeys.has(`context:${contribution.contributionId}:awaiting-context`)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-context:${contribution.contributionId}`,\n\t\t\t\"duplicate-terminal-context\",\n\t\t\t`ContextContribution '${contribution.contributionId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[\n\t\t\t\tref(\"context-contribution\", contribution.contributionId),\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t],\n\t\t);\n\t\treturn;\n\t}\n\tif (contribution.status === \"pending\")\n\t\temitStatusOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`context:${contribution.contributionId}:awaiting-context`,\n\t\t\trequest,\n\t\t\t\"awaiting-context\",\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t);\n\telse {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`context:${contribution.contributionId}`);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\trequest,\n\t\t\tcontribution.status === \"ready\" ? \"completed\" : \"failed\",\n\t\t\t[ref(\"context-contribution\", contribution.contributionId)],\n\t\t\tcontribution.issues,\n\t\t);\n\t}\n}\n\nexport function handlePromptBundle(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tprompt: PromptBundle,\n): void {\n\tconst request = state.requests.get(prompt.requestId);\n\tif (request === undefined) return;\n\tif (request.operationId !== prompt.operationId) {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`stale-prompt:${prompt.promptId}`,\n\t\t\t\"stale-prompt-operation\",\n\t\t\t`PromptBundle '${prompt.promptId}' operationId does not match request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (request.requestKind !== \"prompt\") {\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`wrong-prompt-kind:${prompt.promptId}`,\n\t\t\t\"wrong-kind-prompt-satisfaction\",\n\t\t\t`PromptBundle '${prompt.promptId}' cannot satisfy ${request.requestKind} request '${request.requestId}'`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (state.terminalRequests.has(request.requestId)) {\n\t\tif (\n\t\t\tstate.acceptedTerminalFactIds.has(`prompt:${prompt.promptId}`) ||\n\t\t\tstate.statusKeys.has(`prompt:${prompt.promptId}:awaiting-prompt`)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\temitIssueOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-prompt:${prompt.promptId}`,\n\t\t\t\"duplicate-terminal-prompt\",\n\t\t\t`PromptBundle '${prompt.promptId}' arrived after request '${request.requestId}' was already terminal`,\n\t\t\trequest.requestId,\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId), ref(\"agent-request\", request.requestId)],\n\t\t);\n\t\treturn;\n\t}\n\tif (prompt.status === \"ready\") {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);\n\t\temitStatus(ctx, state, request, \"completed\", [ref(\"prompt-bundle\", prompt.promptId)]);\n\t} else if (prompt.status === \"issue\") {\n\t\tstate.terminalRequests.add(request.requestId);\n\t\tstate.acceptedTerminalFactIds.add(`prompt:${prompt.promptId}`);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\trequest,\n\t\t\t\"failed\",\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t\tprompt.issues,\n\t\t);\n\t} else {\n\t\temitStatusOnce(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`prompt:${prompt.promptId}:awaiting-prompt`,\n\t\t\trequest,\n\t\t\t\"awaiting-prompt\",\n\t\t\t[ref(\"prompt-bundle\", prompt.promptId)],\n\t\t\tprompt.issues,\n\t\t);\n\t}\n}\n\nexport function routeCompatibilityIssue(\n\trequest: AgentRequestIssued,\n\troute: ExecutorRoute,\n\tprofile: ExecutorProfile,\n): string | undefined {\n\tif (request.requestKind !== \"executor\") return \"route-for-non-executor-request\";\n\tif (route.executorId !== profile.executorId) return \"route-profile-executor-mismatch\";\n\tif (\n\t\trequest.input?.inputId !== undefined &&\n\t\troute.inputId !== undefined &&\n\t\trequest.input.inputId !== route.inputId\n\t) {\n\t\treturn \"route-input-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputKind !== undefined &&\n\t\troute.inputKind !== undefined &&\n\t\trequest.input.inputKind !== route.inputKind\n\t) {\n\t\treturn \"route-input-kind-mismatch\";\n\t}\n\tconst inputKind = request.input?.inputKind ?? route.inputKind;\n\tif (inputKind !== undefined && !profileKindAcceptsInput(profile.kind, inputKind))\n\t\treturn \"profile-kind-input-incompatible\";\n\tif (\n\t\tinputKind !== undefined &&\n\t\tprofile.acceptedInputKinds !== undefined &&\n\t\t!profile.acceptedInputKinds.includes(inputKind)\n\t) {\n\t\treturn \"profile-rejects-input-kind\";\n\t}\n\tif (\n\t\trequest.input?.schemaRef !== undefined &&\n\t\tprofile.acceptedSchemaRefs !== undefined &&\n\t\t!profile.acceptedSchemaRefs.includes(request.input.schemaRef)\n\t) {\n\t\treturn \"profile-rejects-schema\";\n\t}\n\treturn undefined;\n}\n\nexport function outcomeCompatibilityIssue(\n\trequest: AgentRequestIssued,\n\troute: ExecutorRoute,\n\toutcome: ExecutorOutcome,\n): string | undefined {\n\tif (outcome.executorId !== route.executorId) return \"outcome-route-executor-mismatch\";\n\tif (outcome.profileId !== route.profileId) return \"outcome-route-profile-mismatch\";\n\tif (\n\t\troute.inputId !== undefined &&\n\t\t(outcome.inputId === undefined || outcome.inputId !== route.inputId)\n\t) {\n\t\treturn \"outcome-route-input-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputId !== undefined &&\n\t\toutcome.inputId !== undefined &&\n\t\toutcome.inputId !== request.input.inputId\n\t) {\n\t\treturn \"outcome-request-input-mismatch\";\n\t}\n\tif (\n\t\troute.inputKind !== undefined &&\n\t\t(outcome.inputKind === undefined || outcome.inputKind !== route.inputKind)\n\t) {\n\t\treturn \"outcome-route-input-kind-mismatch\";\n\t}\n\tif (\n\t\trequest.input?.inputKind !== undefined &&\n\t\toutcome.inputKind !== undefined &&\n\t\toutcome.inputKind !== request.input.inputKind\n\t) {\n\t\treturn \"outcome-request-input-kind-mismatch\";\n\t}\n\treturn undefined;\n}\n\nexport function profileKindAcceptsInput(kind: ExecutorProfile[\"kind\"], inputKind: string): boolean {\n\tif (kind === \"llm\") return inputKind === \"llm-call\";\n\tif (kind === \"tool\") return inputKind === \"tool-call\";\n\tif (kind === \"human\") return inputKind === \"human-task\";\n\treturn inputKind === \"agent-task\";\n}\n\nexport function outcomeStatus(outcome: ExecutorOutcome): AgentRequestStatus {\n\tif (outcome.kind === \"result\") return \"completed\";\n\tif (outcome.kind === \"failure\") return \"failed\";\n\tif (outcome.kind === \"timeout\") return \"timeout\";\n\tif (outcome.kind === \"canceled\") return \"canceled\";\n\treturn \"blocked\";\n}\n\nexport function emitStatus(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\trequest: AgentRequestIssued,\n\tstatus: AgentRequestStatus,\n\tsourceRefs?: readonly SourceRef[],\n\tissues?: readonly DataIssue[],\n): void {\n\tconst cleanSourceRefs =\n\t\tsourceRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(sourceRefs);\n\tconst cleanIssues =\n\t\tissues === undefined\n\t\t\t? undefined\n\t\t\t: Object.freeze(issues.map((issue) => sanitizeAdapterInputIssue(issue)));\n\tconst fact: AgentRequestStatusChanged = {\n\t\tkind: \"status\",\n\t\trequestId: request.requestId,\n\t\toperationId: request.operationId,\n\t\teffectRunId: request.effectRunId,\n\t\tstatus,\n\t\tsourceRefs: cleanSourceRefs,\n\t\tissues: cleanIssues,\n\t};\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\"DATA\", { kind: \"status\", status: fact } satisfies AgentRequestSatisfactionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${request.requestId}:status:${state.auditSeq}`,\n\t\t\t\t\tkind: \"agent-request-status\",\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\tsourceRefs: cleanSourceRefs,\n\t\t\t\t\tmetadata: { status },\n\t\t\t\t},\n\t\t\t} satisfies AgentRequestSatisfactionFact,\n\t\t],\n\t]);\n}\n\nexport function emitStatusOnce(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tkey: string,\n\trequest: AgentRequestIssued,\n\tstatus: AgentRequestStatus,\n\tsourceRefs?: readonly SourceRef[],\n\tissues?: readonly DataIssue[],\n): void {\n\tif (state.statusKeys.has(key)) return;\n\tstate.statusKeys.add(key);\n\temitStatus(ctx, state, request, status, sourceRefs, issues);\n}\n\nexport function emitIssue(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\trefs?: readonly SourceRef[],\n): void {\n\tstate.issueSeq += 1;\n\tconst issue = dataIssue(code, message, { subjectId, refs });\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies AgentRequestSatisfactionFact],\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: {\n\t\t\t\t\tid: `${subjectId ?? \"request\"}:issue:${state.auditSeq}`,\n\t\t\t\t\tkind: \"agent-request-issue\",\n\t\t\t\t\tsubjectId,\n\t\t\t\t\tissueCode: code,\n\t\t\t\t\tmessage,\n\t\t\t\t\tsourceRefs: refs,\n\t\t\t\t},\n\t\t\t} satisfies AgentRequestSatisfactionFact,\n\t\t],\n\t]);\n}\n\nexport function emitIssueOnce(\n\tctx: Ctx,\n\tstate: RequestSatisfactionState,\n\tkey: string,\n\tcode: string,\n\tmessage: string,\n\tsubjectId?: string,\n\trefs?: readonly SourceRef[],\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\temitIssue(ctx, state, code, message, subjectId, refs);\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tdataIssue,\n\tforbiddenDataKeys,\n\tforbiddenGraphVisibleMaterialIssues,\n\tforbiddenProviderRawMaterialKeys,\n\tforEachDepBatch,\n\tisRecord,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeProviderGraphVisibleRecord,\n\tunlockedToolProviderPolicyOverrides,\n} from \"./agent-runtime-common.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestIssued,\n\tExecutorProfile,\n\tExecutorRoute,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\nimport type {\n\tLocalBuiltinToolProviderCatalogOptions,\n\tToolCallInput,\n\tToolProviderApprovalPolicy,\n\tToolProviderArtifactPolicy,\n\tToolProviderCatalog,\n\tToolProviderCatalogEntry,\n\tToolProviderExecutionPolicy,\n\tToolProviderFilesystemPolicy,\n\tToolProviderNetworkPolicy,\n\tToolProviderPathRule,\n\tToolProviderPolicyResolution,\n\tToolProviderPolicyResolutionBundle,\n\tToolProviderPolicyResolutionStatus,\n\tToolProviderRedactionPolicy,\n\tToolProviderSizeCapacityPolicy,\n\tToolProviderSizeLimit,\n\tToolProviderTimeoutPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function localBuiltinToolProviderCatalog(\n\topts: LocalBuiltinToolProviderCatalogOptions = {},\n): ToolProviderCatalog {\n\tconst providerId = opts.providerId ?? \"local-builtin\";\n\tconst executorId = opts.executorId ?? `${providerId}:tool-executor`;\n\tconst profileId = opts.profileId ?? `${providerId}:tool-profile`;\n\tconst tools =\n\t\topts.tools ??\n\t\t([\n\t\t\t{ toolName: \"document/read-doc\", operation: \"read\" },\n\t\t\t{ toolName: \"file.read\", operation: \"read\" },\n\t\t\t{ toolName: \"file.edit/apply-patch\", operation: \"edit\" },\n\t\t\t{ toolName: \"bash.run\", operation: \"run\" },\n\t\t\t{ toolName: \"url.fetch\", operation: \"fetch\" },\n\t\t\t{ toolName: \"date.now\", operation: \"read\" },\n\t\t\t{ toolName: \"weather.fetch\", operation: \"fetch\" },\n\t\t\t{ toolName: \"calculator/eval\", operation: \"eval\" },\n\t\t] satisfies readonly Omit<\n\t\t\tToolProviderCatalogEntry,\n\t\t\t\"kind\" | \"providerId\" | \"inputKind\" | \"profileId\" | \"executorId\"\n\t\t>[]);\n\tconst candidatePolicies: readonly unknown[] = opts.policies?.map((policy) =>\n\t\tObject.freeze(policy),\n\t) ?? [\n\t\tdefaultLocalBuiltinToolProviderExecutionPolicy({\n\t\t\tproviderId,\n\t\t\tprofileId,\n\t\t\ttools,\n\t\t\toverrides: opts.policyOverrides,\n\t\t}),\n\t];\n\tconst policyIssues = Object.freeze(\n\t\tcandidatePolicies.flatMap((policy) => [\n\t\t\t...validateToolProviderExecutionPolicy(policy),\n\t\t\t...validateToolProviderPolicyProviderScope(policy, providerId),\n\t\t]),\n\t);\n\tconst policies = Object.freeze(\n\t\tcandidatePolicies\n\t\t\t.filter((policy) => isPublishableToolProviderExecutionPolicy(policy, providerId))\n\t\t\t.map((policy) => Object.freeze(policy)),\n\t);\n\tconst policyRefs = Object.freeze(\n\t\tpolicies.map((policy) => ref(\"tool-provider-execution-policy\", policy.policyId)),\n\t);\n\tconst catalogInputIssues = Object.freeze([\n\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\topts.metadata,\n\t\t\tref(\"tool-provider-catalog\", providerId),\n\t\t\t\"catalog-metadata\",\n\t\t),\n\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\topts.capabilities,\n\t\t\tref(\"executor-profile\", profileId),\n\t\t\t\"profile-capabilities\",\n\t\t),\n\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\topts.limits,\n\t\t\tref(\"executor-profile\", profileId),\n\t\t\t\"profile-limits\",\n\t\t),\n\t\t...tools.flatMap((tool) => [\n\t\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\t\ttool.metadata,\n\t\t\t\tref(\"tool\", tool.toolName),\n\t\t\t\t\"tool-metadata\",\n\t\t\t),\n\t\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\t\ttool.capabilities,\n\t\t\t\tref(\"tool\", tool.toolName),\n\t\t\t\t\"tool-capabilities\",\n\t\t\t),\n\t\t\t...forbiddenGraphVisibleMaterialIssues(\n\t\t\t\ttool.limits,\n\t\t\t\tref(\"tool\", tool.toolName),\n\t\t\t\t\"tool-limits\",\n\t\t\t),\n\t\t]),\n\t]);\n\tconst toolEntries = tools.map((tool) => {\n\t\tconst toolPolicyRefs = policyRefsForTool(policies, profileId, tool);\n\t\treturn Object.freeze({\n\t\t\t...tool,\n\t\t\tkind: \"tool-catalog-entry\",\n\t\t\tproviderId,\n\t\t\tinputKind: \"tool-call\",\n\t\t\tprofileId,\n\t\t\texecutorId,\n\t\t\tcapabilities: sanitizeProviderGraphVisibleRecord(tool.capabilities),\n\t\t\tlimits: sanitizeProviderGraphVisibleRecord(tool.limits),\n\t\t\tpolicyRefs: toolPolicyRefs,\n\t\t\tmetadata: sanitizeProviderGraphVisibleRecord(tool.metadata),\n\t\t} satisfies ToolProviderCatalogEntry);\n\t});\n\tconst profilePolicyRefs = policyRefsForProfile(policies, profileId);\n\tconst issues = Object.freeze([...policyIssues, ...catalogInputIssues]);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-catalog\",\n\t\tproviderId,\n\t\tproviderKind: \"local-builtin\",\n\t\tstatus: issues.length === 0 ? \"ready\" : \"misconfigured\",\n\t\tprofiles: Object.freeze([\n\t\t\tObject.freeze({\n\t\t\t\tprofileId,\n\t\t\t\texecutorId,\n\t\t\t\tkind: \"tool\",\n\t\t\t\tacceptedInputKinds: Object.freeze([\"tool-call\"]),\n\t\t\t\tacceptedResultKinds: Object.freeze(\n\t\t\t\t\tArray.from(new Set(toolEntries.flatMap((tool) => tool.resultKinds ?? []))),\n\t\t\t\t),\n\t\t\t\tcapabilities: Object.freeze({\n\t\t\t\t\ttoolNames: Object.freeze(toolEntries.map((tool) => tool.toolName)),\n\t\t\t\t\t...(sanitizeProviderGraphVisibleRecord(opts.capabilities) ?? {}),\n\t\t\t\t}),\n\t\t\t\tlimits: sanitizeProviderGraphVisibleRecord(opts.limits),\n\t\t\t\tpolicyRefs: profilePolicyRefs,\n\t\t\t\tmetadata: sanitizeProviderGraphVisibleRecord(opts.metadata),\n\t\t\t} satisfies ExecutorProfile),\n\t\t]),\n\t\ttools: Object.freeze(toolEntries),\n\t\tpolicies,\n\t\tpolicyRefs,\n\t\tissues: issues.length === 0 ? undefined : issues,\n\t\tmetadata: sanitizeProviderGraphVisibleRecord(opts.metadata),\n\t});\n}\n\nexport function validateToolProviderExecutionPolicy(policy: unknown): readonly DataIssue[] {\n\tconst issues: DataIssue[] = [];\n\tif (!isRecord(policy)) {\n\t\treturn Object.freeze([\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-invalid-shape\",\n\t\t\t\t\"Tool provider policy must be a data object.\",\n\t\t\t\t{ refs: [ref(\"tool-provider-execution-policy\", \"<invalid>\")] },\n\t\t\t),\n\t\t]);\n\t}\n\tconst policyId = typeof policy.policyId === \"string\" ? policy.policyId : \"\";\n\tconst providerId = typeof policy.providerId === \"string\" ? policy.providerId : \"\";\n\tconst policyRef = ref(\"tool-provider-execution-policy\", policyId || \"<missing>\");\n\tif (policy.kind !== \"tool-provider-execution-policy\") {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-invalid-kind\",\n\t\t\t\t\"ToolProviderExecutionPolicy.kind must be tool-provider-execution-policy.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tif (!policyId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-missing-policy-id\",\n\t\t\t\t\"Tool provider policy is missing policyId.\",\n\t\t\t\t{\n\t\t\t\t\trefs: [policyRef],\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\tif (!providerId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-missing-provider-id\",\n\t\t\t\t\"Tool provider policy is missing providerId.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tif (\n\t\tpolicy.sizeCapacity === undefined &&\n\t\tpolicy.timeout === undefined &&\n\t\tpolicy.redaction === undefined &&\n\t\tpolicy.filesystem === undefined &&\n\t\tpolicy.approval === undefined &&\n\t\tpolicy.artifacts === undefined &&\n\t\tpolicy.network === undefined\n\t) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-missing-material\",\n\t\t\t\t\"Tool provider policy has no D360 policy material sections.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tif (policy.sizeCapacity !== undefined && !isRecord(policy.sizeCapacity)) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-invalid-size-capacity\",\n\t\t\t\t\"Tool provider size-capacity policy must be a data object.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tconst limits = isRecord(policy.sizeCapacity) ? policy.sizeCapacity.limits : undefined;\n\tif (isRecord(policy.sizeCapacity) && !Array.isArray(limits)) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-invalid-size-capacity\",\n\t\t\t\t\"Tool provider size-capacity limits must be an array.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tfor (const [index, rawLimit] of (Array.isArray(limits) ? limits : []).entries()) {\n\t\tif (!isRecord(rawLimit)) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-size-limit\",\n\t\t\t\t\t\"Tool provider size-capacity limit must be a data object.\",\n\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { index } },\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst limit = rawLimit as Partial<ToolProviderSizeLimit>;\n\t\tif (typeof limit.unit !== \"string\" || limit.unit.length === 0) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-size-limit\",\n\t\t\t\t\t\"Tool provider size-capacity limit unit must be a non-empty string.\",\n\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { index } },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tlimit.softLimit !== undefined &&\n\t\t\t(typeof limit.softLimit !== \"number\" ||\n\t\t\t\t!Number.isFinite(limit.softLimit) ||\n\t\t\t\tlimit.softLimit < 0)\n\t\t) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-size-limit\",\n\t\t\t\t\t\"Tool provider size-capacity softLimit must be a finite non-negative number.\",\n\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { index, unit: limit.unit } },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tlimit.hardLimit !== undefined &&\n\t\t\t(typeof limit.hardLimit !== \"number\" ||\n\t\t\t\t!Number.isFinite(limit.hardLimit) ||\n\t\t\t\tlimit.hardLimit < 0)\n\t\t) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-size-limit\",\n\t\t\t\t\t\"Tool provider size-capacity hardLimit must be a finite non-negative number.\",\n\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { index, unit: limit.unit } },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\ttypeof limit.softLimit === \"number\" &&\n\t\t\tNumber.isFinite(limit.softLimit) &&\n\t\t\ttypeof limit.hardLimit === \"number\" &&\n\t\t\tNumber.isFinite(limit.hardLimit) &&\n\t\t\tlimit.softLimit > limit.hardLimit\n\t\t) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-size-limit\",\n\t\t\t\t\t\"Tool provider size-capacity softLimit must not exceed hardLimit.\",\n\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { index, unit: limit.unit } },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\tif (policy.timeout !== undefined && !isRecord(policy.timeout)) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-invalid-timeout\",\n\t\t\t\t\"Tool provider timeout policy must be a data object.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef] },\n\t\t\t),\n\t\t);\n\t}\n\tfor (const [field, value] of Object.entries(isRecord(policy.timeout) ? policy.timeout : {})) {\n\t\tif (field.endsWith(\"TimeoutMs\") || field === \"timeoutMs\") {\n\t\t\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n\t\t\t\tissues.push(\n\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\"tool-provider-policy-invalid-timeout\",\n\t\t\t\t\t\t\"Tool provider timeout values must be finite non-negative numbers.\",\n\t\t\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { field } },\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const forbidden of [\n\t\t...forbiddenDataKeys(policy),\n\t\t...forbiddenProviderRawMaterialKeys(policy),\n\t]) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-policy-forbidden-runtime-material\",\n\t\t\t\t\"Tool provider policy must not contain runtime-private adapter material.\",\n\t\t\t\t{ subjectId: policyId, refs: [policyRef], details: { reason: forbidden.reason } },\n\t\t\t),\n\t\t);\n\t}\n\treturn Object.freeze(issues);\n}\n\nexport function resolveToolProviderExecutionPolicies(opts: {\n\treadonly request: AgentRequestIssued;\n\treadonly routes?: readonly ExecutorRoute[];\n\treadonly catalogs?: readonly ToolProviderCatalog[];\n}): readonly ToolProviderPolicyResolution[] {\n\tconst request = opts.request;\n\tconst toolCall = toolCallFromRequest(request);\n\tconst baseSourceRefs = Object.freeze([ref(\"agent-request\", request.requestId)]);\n\tif (toolCall === undefined) {\n\t\treturn Object.freeze([\n\t\t\tObject.freeze({\n\t\t\t\tkind: \"tool-provider-policy-resolution\",\n\t\t\t\tresolutionId: `${request.requestId}:${request.operationId}:tool-policy:missing-tool-call`,\n\t\t\t\tstatus: \"missing-tool-call\",\n\t\t\t\trequestId: request.requestId,\n\t\t\t\toperationId: request.operationId,\n\t\t\t\tissues: Object.freeze([\n\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\"tool-provider-policy-missing-tool-call\",\n\t\t\t\t\t\t\"Tool provider policy resolution requires AgentRequest input.value to be a ToolCallInput.\",\n\t\t\t\t\t\t{ subjectId: request.requestId, refs: baseSourceRefs },\n\t\t\t\t\t),\n\t\t\t\t]),\n\t\t\t\tsourceRefs: baseSourceRefs,\n\t\t\t} satisfies ToolProviderPolicyResolution),\n\t\t]);\n\t}\n\tconst routes = (opts.routes ?? []).filter(\n\t\t(route) => route.requestId === request.requestId && route.operationId === request.operationId,\n\t);\n\tif (routes.length === 0) {\n\t\treturn Object.freeze([\n\t\t\tObject.freeze({\n\t\t\t\tkind: \"tool-provider-policy-resolution\",\n\t\t\t\tresolutionId: `${request.requestId}:${request.operationId}:tool-policy:pending-route`,\n\t\t\t\tstatus: \"pending-route\",\n\t\t\t\trequestId: request.requestId,\n\t\t\t\toperationId: request.operationId,\n\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\toperation: toolCall.operation,\n\t\t\t\tsourceRefs: baseSourceRefs,\n\t\t\t} satisfies ToolProviderPolicyResolution),\n\t\t]);\n\t}\n\treturn Object.freeze(\n\t\troutes.map((route) =>\n\t\t\tObject.freeze(\n\t\t\t\tresolveToolProviderPolicyForRoute(request, route, toolCall, opts.catalogs ?? []),\n\t\t\t),\n\t\t),\n\t);\n}\n\nexport function toolProviderPolicyResolutionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly requestFacts: Node<AgentRequestFact>;\n\t\treadonly executorRoutes?: readonly Node<ExecutorRoute>[];\n\t\treadonly toolProviderCatalogs?: readonly Node<ToolProviderCatalog>[];\n\t},\n): ToolProviderPolicyResolutionBundle {\n\tconst name = opts.name ?? \"toolProviderPolicyResolution\";\n\tconst routeDeps = opts.executorRoutes ?? [];\n\tconst catalogDeps = opts.toolProviderCatalogs ?? [];\n\tconst routeStart = 1;\n\tconst catalogStart = routeStart + routeDeps.length;\n\tconst runtime = graph.node<ToolProviderPolicyResolutionFact>(\n\t\t[opts.requestFacts, ...routeDeps, ...catalogDeps],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ToolProviderPolicyResolutionState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\troutes: new Map<string, ExecutorRoute>(),\n\t\t\t\tcatalogs: new Map<string, ToolProviderCatalog>(),\n\t\t\t\temittedKeys: new Set<string>(),\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\" && fact.input?.inputKind === \"tool-call\") {\n\t\t\t\t\tstate.requests.set(fact.requestId, fact);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, routeStart, routeDeps.length, (raw) => {\n\t\t\t\tconst route = raw as ExecutorRoute;\n\t\t\t\tstate.routes.set(route.routeId, route);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, catalogStart, catalogDeps.length, (raw) => {\n\t\t\t\tconst catalog = raw as ToolProviderCatalog;\n\t\t\t\tstate.catalogs.set(catalog.providerId, catalog);\n\t\t\t});\n\t\t\tfor (const request of state.requests.values()) {\n\t\t\t\tconst resolutions = resolveToolProviderExecutionPolicies({\n\t\t\t\t\trequest,\n\t\t\t\t\troutes: Array.from(state.routes.values()),\n\t\t\t\t\tcatalogs: Array.from(state.catalogs.values()),\n\t\t\t\t});\n\t\t\t\tfor (const resolution of resolutions) {\n\t\t\t\t\tconst key = stableToolProviderPolicyResolutionKey(resolution);\n\t\t\t\t\tif (state.emittedKeys.has(key)) continue;\n\t\t\t\t\tstate.emittedKeys.add(key);\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\"DATA\", { kind: \"resolution\", resolution } satisfies ToolProviderPolicyResolutionFact],\n\t\t\t\t\t]);\n\t\t\t\t\tfor (const issue of resolution.issues ?? []) {\n\t\t\t\t\t\tctx.down([\n\t\t\t\t\t\t\t[\"DATA\", { kind: \"issue\", issue } satisfies ToolProviderPolicyResolutionFact],\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tstate.auditSeq += 1;\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: \"audit\",\n\t\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\t\tid: `${name}:audit:${state.auditSeq}`,\n\t\t\t\t\t\t\t\t\tkind: \"tool-provider-policy-resolution\",\n\t\t\t\t\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\t\t\t\t\tsourceRefs: resolution.sourceRefs,\n\t\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\t\tstatus: resolution.status,\n\t\t\t\t\t\t\t\t\t\trouteId: resolution.routeId,\n\t\t\t\t\t\t\t\t\t\tproviderId: resolution.providerId,\n\t\t\t\t\t\t\t\t\t\tprofileId: resolution.profileId,\n\t\t\t\t\t\t\t\t\t\ttoolName: resolution.toolName,\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} satisfies ToolProviderPolicyResolutionFact,\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(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"toolProviderPolicyResolutionProjector\", partial: true },\n\t);\n\tconst resolutions = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/resolutions`,\n\t\t\"toolProviderPolicyResolutions\",\n\t\t(fact) => (fact.kind === \"resolution\" ? fact.resolution : undefined),\n\t);\n\tconst issues = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/issues`,\n\t\t\"toolProviderPolicyResolutionIssues\",\n\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t);\n\tconst audit = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/audit`,\n\t\t\"toolProviderPolicyResolutionAudit\",\n\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t);\n\treturn { resolutions, issues, audit };\n}\n\nexport type ToolProviderPolicyResolutionFact =\n\t| { readonly kind: \"resolution\"; readonly resolution: ToolProviderPolicyResolution }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface ToolProviderPolicyResolutionState {\n\trequests: Map<string, AgentRequestIssued>;\n\troutes: Map<string, ExecutorRoute>;\n\tcatalogs: Map<string, ToolProviderCatalog>;\n\temittedKeys: Set<string>;\n\tauditSeq: number;\n}\n\nexport function isPublishableToolProviderExecutionPolicy(\n\tpolicy: unknown,\n\tproviderId?: string,\n): policy is ToolProviderExecutionPolicy {\n\treturn (\n\t\tisRecord(policy) &&\n\t\tpolicy.kind === \"tool-provider-execution-policy\" &&\n\t\ttypeof policy.policyId === \"string\" &&\n\t\tpolicy.policyId.length > 0 &&\n\t\ttypeof policy.providerId === \"string\" &&\n\t\tpolicy.providerId.length > 0 &&\n\t\t(providerId === undefined || policy.providerId === providerId) &&\n\t\tvalidateToolProviderExecutionPolicy(policy).length === 0\n\t);\n}\n\nexport function validateToolProviderPolicyProviderScope(\n\tpolicy: unknown,\n\tproviderId: string,\n): readonly DataIssue[] {\n\tif (!isRecord(policy)) return [];\n\tif (policy.providerId === undefined || policy.providerId === providerId) return [];\n\treturn Object.freeze([\n\t\tdataIssue(\n\t\t\t\"tool-provider-policy-provider-mismatch\",\n\t\t\t\"Tool provider policy providerId must match the catalog providerId.\",\n\t\t\t{\n\t\t\t\tsubjectId: typeof policy.policyId === \"string\" ? policy.policyId : undefined,\n\t\t\t\trefs: [\n\t\t\t\t\tref(\n\t\t\t\t\t\t\"tool-provider-execution-policy\",\n\t\t\t\t\t\ttypeof policy.policyId === \"string\" && policy.policyId.length > 0\n\t\t\t\t\t\t\t? policy.policyId\n\t\t\t\t\t\t\t: \"<missing>\",\n\t\t\t\t\t),\n\t\t\t\t\tref(\"tool-provider-catalog\", providerId),\n\t\t\t\t],\n\t\t\t},\n\t\t),\n\t]);\n}\n\nexport function policyRefsForProfile(\n\tpolicies: readonly ToolProviderExecutionPolicy[],\n\tprofileId: string,\n): readonly SourceRef[] {\n\treturn Object.freeze(\n\t\tpolicies\n\t\t\t.filter((policy) => policyAppliesToProfile(policy, profileId))\n\t\t\t.map((policy) => ref(\"tool-provider-execution-policy\", policy.policyId)),\n\t);\n}\n\nexport function policyRefsForTool(\n\tpolicies: readonly ToolProviderExecutionPolicy[],\n\tprofileId: string,\n\ttool: Omit<\n\t\tToolProviderCatalogEntry,\n\t\t\"kind\" | \"providerId\" | \"inputKind\" | \"profileId\" | \"executorId\"\n\t>,\n): readonly SourceRef[] {\n\treturn Object.freeze(\n\t\tpolicies\n\t\t\t.filter((policy) => policyAppliesToProfile(policy, profileId))\n\t\t\t.filter((policy) => policyAppliesToOptionalScope(policy.toolNames, tool.toolName))\n\t\t\t.filter((policy) => policyAppliesToOptionalScope(policy.operations, tool.operation))\n\t\t\t.map((policy) => ref(\"tool-provider-execution-policy\", policy.policyId)),\n\t);\n}\n\nexport function policyAppliesToProfile(\n\tpolicy: ToolProviderExecutionPolicy,\n\tprofileId: string,\n): boolean {\n\treturn policyAppliesToOptionalScope(policy.profileIds, profileId);\n}\n\nexport function policyAppliesToOptionalScope(\n\tscope: readonly string[] | undefined,\n\tvalue: string | undefined,\n): boolean {\n\treturn (\n\t\tscope === undefined || scope.length === 0 || (value !== undefined && scope.includes(value))\n\t);\n}\n\nexport function toolCallFromRequest(request: AgentRequestIssued): ToolCallInput | undefined {\n\tconst value = request.input?.value;\n\tif (request.input?.inputKind !== \"tool-call\" || !isRecord(value)) return undefined;\n\tif (\n\t\tvalue.kind !== \"tool-call\" ||\n\t\ttypeof value.toolName !== \"string\" ||\n\t\tvalue.toolName.length === 0\n\t) {\n\t\treturn undefined;\n\t}\n\treturn value as unknown as ToolCallInput;\n}\n\nexport function resolveToolProviderPolicyForRoute(\n\trequest: AgentRequestIssued,\n\troute: ExecutorRoute,\n\ttoolCall: ToolCallInput,\n\tcatalogs: readonly ToolProviderCatalog[],\n): ToolProviderPolicyResolution {\n\tconst sourceRefs = Object.freeze([\n\t\tref(\"agent-request\", request.requestId),\n\t\tref(\"executor-route\", route.routeId),\n\t]);\n\tconst matchingCatalogs = catalogs.filter((catalog) => catalogHasRouteProfile(catalog, route));\n\tif (matchingCatalogs.length === 0) {\n\t\treturn policyResolutionWithIssue({\n\t\t\trequest,\n\t\t\troute,\n\t\t\ttoolCall,\n\t\t\tstatus: \"missing-catalog\",\n\t\t\tsourceRefs,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-policy-missing-catalog\",\n\t\t\t\t`No tool provider catalog exposes route profile '${route.profileId}'.`,\n\t\t\t\t{ subjectId: request.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t});\n\t}\n\tif (matchingCatalogs.length > 1) {\n\t\treturn policyResolutionWithIssue({\n\t\t\trequest,\n\t\t\troute,\n\t\t\ttoolCall,\n\t\t\tstatus: \"ambiguous-catalog\",\n\t\t\tsourceRefs,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-policy-ambiguous-catalog\",\n\t\t\t\t`Multiple tool provider catalogs expose route profile '${route.profileId}'.`,\n\t\t\t\t{\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\trefs: [\n\t\t\t\t\t\t...sourceRefs,\n\t\t\t\t\t\t...matchingCatalogs.map((catalog) => ref(\"tool-provider-catalog\", catalog.providerId)),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t),\n\t\t});\n\t}\n\tconst catalog = matchingCatalogs[0];\n\tif (catalog === undefined) throw new Error(\"unreachable catalog match\");\n\tconst tool = catalog.tools.find(\n\t\t(entry) =>\n\t\t\tentry.profileId === route.profileId &&\n\t\t\tentry.executorId === route.executorId &&\n\t\t\tentry.toolName === toolCall.toolName &&\n\t\t\t(entry.operation === undefined ||\n\t\t\t\ttoolCall.operation === undefined ||\n\t\t\t\tentry.operation === toolCall.operation),\n\t);\n\tif (tool === undefined) {\n\t\treturn policyResolutionWithIssue({\n\t\t\trequest,\n\t\t\troute,\n\t\t\ttoolCall,\n\t\t\tstatus: \"missing-tool\",\n\t\t\tsourceRefs,\n\t\t\tproviderId: catalog.providerId,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-policy-missing-tool\",\n\t\t\t\t`Tool provider catalog '${catalog.providerId}' does not expose requested tool '${toolCall.toolName}'.`,\n\t\t\t\t{\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\trefs: [...sourceRefs, ref(\"tool-provider-catalog\", catalog.providerId)],\n\t\t\t\t},\n\t\t\t),\n\t\t});\n\t}\n\tconst policyRefs = policyRefsForResolution(catalog, route, tool);\n\tif (policyRefs.length === 0) {\n\t\treturn policyResolutionWithIssue({\n\t\t\trequest,\n\t\t\troute,\n\t\t\ttoolCall,\n\t\t\tstatus: \"missing-policy\",\n\t\t\tsourceRefs,\n\t\t\tproviderId: catalog.providerId,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-policy-missing-policy-ref\",\n\t\t\t\t`Tool '${tool.toolName}' has no D360 policy refs on its entry, profile, or catalog.`,\n\t\t\t\t{\n\t\t\t\t\tsubjectId: request.requestId,\n\t\t\t\t\trefs: [...sourceRefs, ref(\"tool-provider-catalog\", catalog.providerId)],\n\t\t\t\t},\n\t\t\t),\n\t\t});\n\t}\n\tconst issues = policyIssuesForRefs(catalog, policyRefs, request, sourceRefs);\n\tconst status = issues.length === 0 ? \"resolved\" : \"invalid-policy\";\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-policy-resolution\",\n\t\tresolutionId: `${request.requestId}:${request.operationId}:${route.routeId}:tool-policy`,\n\t\tstatus,\n\t\trequestId: request.requestId,\n\t\toperationId: request.operationId,\n\t\trouteId: route.routeId,\n\t\tproviderId: catalog.providerId,\n\t\texecutorId: route.executorId,\n\t\tprofileId: route.profileId,\n\t\ttoolName: toolCall.toolName,\n\t\toperation: toolCall.operation,\n\t\tpolicyRefs,\n\t\tissues: issues.length === 0 ? undefined : Object.freeze(issues),\n\t\tsourceRefs: Object.freeze([...sourceRefs, ref(\"tool-provider-catalog\", catalog.providerId)]),\n\t} satisfies ToolProviderPolicyResolution);\n}\n\nexport function catalogHasRouteProfile(\n\tcatalog: ToolProviderCatalog,\n\troute: ExecutorRoute,\n): boolean {\n\treturn catalog.profiles.some(\n\t\t(profile) => profile.profileId === route.profileId && profile.executorId === route.executorId,\n\t);\n}\n\nexport function policyRefsForResolution(\n\tcatalog: ToolProviderCatalog,\n\troute: ExecutorRoute,\n\ttool: ToolProviderCatalogEntry,\n): readonly SourceRef[] {\n\tconst profile = catalog.profiles.find(\n\t\t(candidate) =>\n\t\t\tcandidate.profileId === route.profileId && candidate.executorId === route.executorId,\n\t);\n\treturn Object.freeze([\n\t\t...(tool.policyRefs ?? []),\n\t\t...((tool.policyRefs?.length ?? 0) === 0 ? (profile?.policyRefs ?? []) : []),\n\t\t...((tool.policyRefs?.length ?? 0) === 0 && (profile?.policyRefs?.length ?? 0) === 0\n\t\t\t? (catalog.policyRefs ?? [])\n\t\t\t: []),\n\t]);\n}\n\nexport function policyIssuesForRefs(\n\tcatalog: ToolProviderCatalog,\n\tpolicyRefs: readonly SourceRef[],\n\trequest: AgentRequestIssued,\n\tsourceRefs: readonly SourceRef[],\n): readonly DataIssue[] {\n\tconst policiesById = new Map((catalog.policies ?? []).map((policy) => [policy.policyId, policy]));\n\tconst issues: DataIssue[] = [];\n\tfor (const policyRef of policyRefs) {\n\t\tif (policyRef.kind !== \"tool-provider-execution-policy\") {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-invalid-ref-kind\",\n\t\t\t\t\t\"Tool provider policy refs must point at ToolProviderExecutionPolicy facts.\",\n\t\t\t\t\t{ subjectId: request.requestId, refs: [...sourceRefs, policyRef] },\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst policy = policiesById.get(policyRef.id);\n\t\tif (policy === undefined) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-policy-ref-missing-material\",\n\t\t\t\t\t`Tool provider policy ref '${policyRef.id}' has no policy material in catalog '${catalog.providerId}'.`,\n\t\t\t\t\t{ subjectId: request.requestId, refs: [...sourceRefs, policyRef] },\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tissues.push(...validateToolProviderExecutionPolicy(policy));\n\t\tissues.push(...validateToolProviderPolicyProviderScope(policy, catalog.providerId));\n\t}\n\treturn Object.freeze(issues);\n}\n\nexport function policyResolutionWithIssue(opts: {\n\treadonly request: AgentRequestIssued;\n\treadonly route: ExecutorRoute;\n\treadonly toolCall: ToolCallInput;\n\treadonly status: ToolProviderPolicyResolutionStatus;\n\treadonly sourceRefs: readonly SourceRef[];\n\treadonly issue: DataIssue;\n\treadonly providerId?: string;\n}): ToolProviderPolicyResolution {\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-policy-resolution\",\n\t\tresolutionId: `${opts.request.requestId}:${opts.request.operationId}:${opts.route.routeId}:tool-policy:${opts.status}`,\n\t\tstatus: opts.status,\n\t\trequestId: opts.request.requestId,\n\t\toperationId: opts.request.operationId,\n\t\trouteId: opts.route.routeId,\n\t\tproviderId: opts.providerId,\n\t\texecutorId: opts.route.executorId,\n\t\tprofileId: opts.route.profileId,\n\t\ttoolName: opts.toolCall.toolName,\n\t\toperation: opts.toolCall.operation,\n\t\tissues: Object.freeze([opts.issue]),\n\t\tsourceRefs: opts.sourceRefs,\n\t} satisfies ToolProviderPolicyResolution);\n}\n\nexport function stableToolProviderPolicyResolutionKey(\n\tresolution: ToolProviderPolicyResolution,\n): string {\n\treturn JSON.stringify({\n\t\tid: resolution.resolutionId,\n\t\tstatus: resolution.status,\n\t\tpolicyRefs:\n\t\t\tresolution.policyRefs?.map((policyRef) => `${policyRef.kind}:${policyRef.id}`) ?? [],\n\t\tissues: resolution.issues?.map((issue) => issue.code) ?? [],\n\t});\n}\n\nexport function defaultLocalBuiltinToolProviderExecutionPolicy(opts: {\n\treadonly providerId: string;\n\treadonly profileId: string;\n\treadonly tools: readonly Omit<\n\t\tToolProviderCatalogEntry,\n\t\t\"kind\" | \"providerId\" | \"inputKind\" | \"profileId\" | \"executorId\"\n\t>[];\n\treadonly overrides?: Partial<\n\t\tOmit<ToolProviderExecutionPolicy, \"kind\" | \"policyId\" | \"providerId\">\n\t>;\n}): ToolProviderExecutionPolicy {\n\tconst toolNames = Object.freeze(Array.from(new Set(opts.tools.map((tool) => tool.toolName))));\n\tconst operations = Object.freeze(\n\t\tArray.from(new Set(opts.tools.map((tool) => tool.operation).filter((op) => op !== undefined))),\n\t);\n\tconst hasUrlFetch = toolNames.includes(\"url.fetch\");\n\tconst filesystemToolNames = toolNames.filter(\n\t\t(toolName) =>\n\t\t\ttoolName.startsWith(\"file.\") || toolName.startsWith(\"document/\") || toolName === \"bash.run\",\n\t);\n\tconst approvalToolNames = toolNames.filter(\n\t\t(toolName) => toolName === \"file.edit/apply-patch\" || toolName === \"bash.run\",\n\t);\n\tconst approvalOperations = operations.filter(\n\t\t(operation) => operation === \"edit\" || operation === \"run\",\n\t);\n\tconst policy = {\n\t\tkind: \"tool-provider-execution-policy\",\n\t\tpolicyId: `${opts.providerId}:policy:default`,\n\t\tproviderId: opts.providerId,\n\t\tprofileIds: Object.freeze([opts.profileId]),\n\t\ttoolNames,\n\t\toperations,\n\t\tsizeCapacity: Object.freeze({\n\t\t\tlimits: Object.freeze([\n\t\t\t\tObject.freeze({\n\t\t\t\t\tunit: \"chars\",\n\t\t\t\t\tsoftLimit: 16_384,\n\t\t\t\t\thardLimit: 65_536,\n\t\t\t\t\tperRequest: true,\n\t\t\t\t\tmeasurementSource: \"adapter-estimated\",\n\t\t\t\t} satisfies ToolProviderSizeLimit),\n\t\t\t\tObject.freeze({\n\t\t\t\t\tunit: \"bytes\",\n\t\t\t\t\tsoftLimit: 1_048_576,\n\t\t\t\t\thardLimit: 8_388_608,\n\t\t\t\t\tperArtifact: true,\n\t\t\t\t\tmeasurementSource: \"adapter-measured\",\n\t\t\t\t} satisfies ToolProviderSizeLimit),\n\t\t\t\tObject.freeze({\n\t\t\t\t\tunit: \"lines\",\n\t\t\t\t\tsoftLimit: 2_000,\n\t\t\t\t\thardLimit: 10_000,\n\t\t\t\t\tperStream: true,\n\t\t\t\t\tmeasurementSource: \"adapter-measured\",\n\t\t\t\t} satisfies ToolProviderSizeLimit),\n\t\t\t]),\n\t\t} satisfies ToolProviderSizeCapacityPolicy),\n\t\ttimeout: Object.freeze({\n\t\t\ttimeoutMs: 30_000,\n\t\t\tidleTimeoutMs: 5_000,\n\t\t} satisfies ToolProviderTimeoutPolicy),\n\t\tredaction: Object.freeze({\n\t\t\tmode: \"summary\",\n\t\t\tsensitivity: Object.freeze([\"private-material\", \"auth-material\", \"personal-data\"]),\n\t\t\tsummaryMaxChars: 512,\n\t\t} satisfies ToolProviderRedactionPolicy),\n\t\t...(filesystemToolNames.length > 0\n\t\t\t? {\n\t\t\t\t\tfilesystem: Object.freeze({\n\t\t\t\t\t\tcwd: \".\",\n\t\t\t\t\t\tallowRead: true,\n\t\t\t\t\t\tallowWrite: false,\n\t\t\t\t\t\tfollowSymlinks: false,\n\t\t\t\t\t\tsourceRefs: Object.freeze(filesystemToolNames.map((toolName) => ref(\"tool\", toolName))),\n\t\t\t\t\t\tpathRules: Object.freeze([\n\t\t\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t\t\teffect: \"allow\",\n\t\t\t\t\t\t\t\tpath: \".\",\n\t\t\t\t\t\t\t\toperation: \"read\",\n\t\t\t\t\t\t\t\treason: \"Default local builtin catalog is workspace-relative data material.\",\n\t\t\t\t\t\t\t} satisfies ToolProviderPathRule),\n\t\t\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t\t\teffect: \"deny\",\n\t\t\t\t\t\t\t\tglob: \"**/.env*\",\n\t\t\t\t\t\t\t\treason: \"D360 policies keep private material outside catalog DATA.\",\n\t\t\t\t\t\t\t} satisfies ToolProviderPathRule),\n\t\t\t\t\t\t]),\n\t\t\t\t\t} satisfies ToolProviderFilesystemPolicy),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(hasUrlFetch\n\t\t\t? {\n\t\t\t\t\tnetwork: Object.freeze({\n\t\t\t\t\t\tmode: \"custom\",\n\t\t\t\t\t\tprotocols: Object.freeze([\"https:\"]),\n\t\t\t\t\t\tallowedHosts: Object.freeze([\"*\"]),\n\t\t\t\t\t\tsourceRefs: Object.freeze([ref(\"tool\", \"url.fetch\")]),\n\t\t\t\t\t} satisfies ToolProviderNetworkPolicy),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tapproval: Object.freeze({\n\t\t\tmode: approvalToolNames.length > 0 ? \"require\" : \"auto\",\n\t\t\t...(approvalToolNames.length > 0\n\t\t\t\t? { requiredForToolNames: Object.freeze(approvalToolNames) }\n\t\t\t\t: {}),\n\t\t\t...(approvalOperations.length > 0\n\t\t\t\t? { requiredForOperations: Object.freeze(approvalOperations) }\n\t\t\t\t: {}),\n\t\t} satisfies ToolProviderApprovalPolicy),\n\t\tartifacts: Object.freeze({\n\t\t\tdefaultDataMode: \"summary\",\n\t\t\tartifactKinds: Object.freeze([\n\t\t\t\t\"text\",\n\t\t\t\t\"markdown\",\n\t\t\t\t\"file\",\n\t\t\t\t\"stdout\",\n\t\t\t\t\"stderr\",\n\t\t\t\t\"tool-output\",\n\t\t\t\t\"provider-raw\",\n\t\t\t]),\n\t\t\tinlineLimits: Object.freeze([\n\t\t\t\tObject.freeze({\n\t\t\t\t\tunit: \"chars\",\n\t\t\t\t\thardLimit: 4_096,\n\t\t\t\t\tperArtifact: true,\n\t\t\t\t\tmeasurementSource: \"adapter-estimated\",\n\t\t\t\t} satisfies ToolProviderSizeLimit),\n\t\t\t]),\n\t\t\trequireDigest: false,\n\t\t} satisfies ToolProviderArtifactPolicy),\n\t\tsourceRefs: Object.freeze([ref(\"decision\", \"D360\"), ref(\"tool-provider\", opts.providerId)]),\n\t\tmetadata: Object.freeze({\n\t\t\tdescription: \"Default data-only policy material for local builtin tools.\",\n\t\t}),\n\t\t...unlockedToolProviderPolicyOverrides(opts.overrides),\n\t} satisfies ToolProviderExecutionPolicy;\n\treturn Object.freeze(policy);\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tdataIssue,\n\tforbiddenAdapterInputMaterialIssues,\n\tforEachDepBatch,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tstableJsonStringify,\n} from \"./agent-runtime-common.js\";\nimport {\n\ttoolCallFromRequest,\n\tvalidateToolProviderExecutionPolicy,\n\tvalidateToolProviderPolicyProviderScope,\n} from \"./agent-runtime-tool-provider-policy.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestInput,\n\tAgentRequestIssued,\n\tExecutorRoute,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolCallInput,\n\tToolProviderAdapterInput,\n\tToolProviderAdapterInputBundle,\n\tToolProviderAdapterInputStatus,\n\tToolProviderCatalog,\n\tToolProviderCatalogEntry,\n\tToolProviderExecutionPolicy,\n\tToolProviderPolicyResolution,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function buildToolProviderAdapterInputs(opts: {\n\treadonly requests: readonly AgentRequestIssued[];\n\treadonly routes?: readonly ExecutorRoute[];\n\treadonly catalogs?: readonly ToolProviderCatalog[];\n\treadonly resolutions: readonly ToolProviderPolicyResolution[];\n}): readonly ToolProviderAdapterInput[] {\n\tconst requestsById = new Map(opts.requests.map((request) => [request.requestId, request]));\n\tconst routesById = new Map((opts.routes ?? []).map((route) => [route.routeId, route]));\n\tconst catalogsById = new Map(\n\t\t(opts.catalogs ?? []).map((catalog) => [catalog.providerId, catalog]),\n\t);\n\treturn Object.freeze(\n\t\topts.resolutions.map((resolution) =>\n\t\t\tbuildToolProviderAdapterInput({\n\t\t\t\tresolution,\n\t\t\t\trequest: requestsById.get(resolution.requestId),\n\t\t\t\troute: resolution.routeId === undefined ? undefined : routesById.get(resolution.routeId),\n\t\t\t\tcatalog:\n\t\t\t\t\tresolution.providerId === undefined ? undefined : catalogsById.get(resolution.providerId),\n\t\t\t}),\n\t\t),\n\t);\n}\n\nexport function toolProviderAdapterInputProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly requestFacts: Node<AgentRequestFact>;\n\t\treadonly executorRoutes?: readonly Node<ExecutorRoute>[];\n\t\treadonly toolProviderCatalogs?: readonly Node<ToolProviderCatalog>[];\n\t\treadonly policyResolutions: readonly Node<ToolProviderPolicyResolution>[];\n\t},\n): ToolProviderAdapterInputBundle {\n\tconst name = opts.name ?? \"toolProviderAdapterInput\";\n\tconst routeDeps = opts.executorRoutes ?? [];\n\tconst catalogDeps = opts.toolProviderCatalogs ?? [];\n\tconst routeStart = 1;\n\tconst catalogStart = routeStart + routeDeps.length;\n\tconst resolutionStart = catalogStart + catalogDeps.length;\n\tconst runtime = graph.node<ToolProviderAdapterInputFact>(\n\t\t[opts.requestFacts, ...routeDeps, ...catalogDeps, ...opts.policyResolutions],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ToolProviderAdapterInputState>() ?? {\n\t\t\t\trequests: new Map<string, AgentRequestIssued>(),\n\t\t\t\troutes: new Map<string, ExecutorRoute>(),\n\t\t\t\tcatalogs: new Map<string, ToolProviderCatalog>(),\n\t\t\t\tresolutions: new Map<string, ToolProviderPolicyResolution>(),\n\t\t\t\temittedKeys: new Set<string>(),\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as AgentRequestFact;\n\t\t\t\tif (fact.kind === \"issued\" && fact.input?.inputKind === \"tool-call\") {\n\t\t\t\t\tstate.requests.set(fact.requestId, fact);\n\t\t\t\t}\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, routeStart, routeDeps.length, (raw) => {\n\t\t\t\tconst route = raw as ExecutorRoute;\n\t\t\t\tstate.routes.set(route.routeId, route);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, catalogStart, catalogDeps.length, (raw) => {\n\t\t\t\tconst catalog = raw as ToolProviderCatalog;\n\t\t\t\tstate.catalogs.set(catalog.providerId, catalog);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, resolutionStart, opts.policyResolutions.length, (raw) => {\n\t\t\t\tconst resolution = raw as ToolProviderPolicyResolution;\n\t\t\t\tstate.resolutions.set(resolution.resolutionId, resolution);\n\t\t\t});\n\t\t\tconst inputs = buildToolProviderAdapterInputs({\n\t\t\t\trequests: Array.from(state.requests.values()),\n\t\t\t\troutes: Array.from(state.routes.values()),\n\t\t\t\tcatalogs: Array.from(state.catalogs.values()),\n\t\t\t\tresolutions: Array.from(state.resolutions.values()),\n\t\t\t});\n\t\t\tfor (const input of inputs) {\n\t\t\t\tconst key = stableToolProviderAdapterInputKey(input);\n\t\t\t\tif (state.emittedKeys.has(key)) continue;\n\t\t\t\tstate.emittedKeys.add(key);\n\t\t\t\tctx.down([[\"DATA\", { kind: \"input\", input } satisfies ToolProviderAdapterInputFact]]);\n\t\t\t\tfor (const issue of input.issues ?? []) {\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"issue\", issue } satisfies ToolProviderAdapterInputFact]]);\n\t\t\t\t}\n\t\t\t\tstate.auditSeq += 1;\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: \"audit\",\n\t\t\t\t\t\t\taudit: {\n\t\t\t\t\t\t\t\tid: `${name}:audit:${state.auditSeq}`,\n\t\t\t\t\t\t\t\tkind: \"tool-provider-adapter-input\",\n\t\t\t\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\t\t\t\tsourceRefs: input.sourceRefs,\n\t\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\t\tstatus: input.status,\n\t\t\t\t\t\t\t\t\trouteId: input.routeId,\n\t\t\t\t\t\t\t\t\tproviderId: input.providerId,\n\t\t\t\t\t\t\t\t\tprofileId: input.profileId,\n\t\t\t\t\t\t\t\t\ttoolName: input.toolName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies ToolProviderAdapterInputFact,\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},\n\t\t{ name: `${name}/runtime`, factory: \"toolProviderAdapterInputProjector\", partial: true },\n\t);\n\tconst inputs = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/inputs`,\n\t\t\"toolProviderAdapterInputs\",\n\t\t(fact) => (fact.kind === \"input\" ? fact.input : undefined),\n\t);\n\tconst issues = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/issues`,\n\t\t\"toolProviderAdapterInputIssues\",\n\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t);\n\tconst audit = projectRuntimeFact(\n\t\tgraph,\n\t\truntime,\n\t\t`${name}/audit`,\n\t\t\"toolProviderAdapterInputAudit\",\n\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t);\n\treturn { inputs, issues, audit };\n}\n\nexport type ToolProviderAdapterInputFact =\n\t| { readonly kind: \"input\"; readonly input: ToolProviderAdapterInput }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\nexport interface ToolProviderAdapterInputState {\n\trequests: Map<string, AgentRequestIssued>;\n\troutes: Map<string, ExecutorRoute>;\n\tcatalogs: Map<string, ToolProviderCatalog>;\n\tresolutions: Map<string, ToolProviderPolicyResolution>;\n\temittedKeys: Set<string>;\n\tauditSeq: number;\n}\n\nexport function buildToolProviderAdapterInput(opts: {\n\treadonly resolution: ToolProviderPolicyResolution;\n\treadonly request?: AgentRequestIssued;\n\treadonly route?: ExecutorRoute;\n\treadonly catalog?: ToolProviderCatalog;\n}): ToolProviderAdapterInput {\n\tconst { resolution, request, route, catalog } = opts;\n\tconst sourceRefs = sanitizeAdapterInputSourceRefs([\n\t\tref(\"tool-provider-policy-resolution\", resolution.resolutionId),\n\t\t...(resolution.sourceRefs ?? []),\n\t\t...(resolution.routeId === undefined ? [] : [ref(\"executor-route\", resolution.routeId)]),\n\t\t...(resolution.providerId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"tool-provider-catalog\", resolution.providerId)]),\n\t\t...(resolution.policyRefs ?? []),\n\t]);\n\tconst issues: DataIssue[] = (resolution.issues ?? []).map((issue) =>\n\t\tsanitizeAdapterInputIssue(issue),\n\t);\n\tlet statusOverride: Exclude<ToolProviderAdapterInputStatus, \"ready\"> | undefined;\n\tif (request === undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-request\",\n\t\t\t\t\"Tool provider adapter input requires the issued AgentRequest fact.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request !== undefined && request.requestId !== resolution.requestId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-request\",\n\t\t\t\t\"Tool provider adapter input request identity does not match its policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (request !== undefined && request.operationId !== resolution.operationId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-request-operation\",\n\t\t\t\t\"Tool provider adapter input request operationId does not match its policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (resolution.routeId !== undefined && route === undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-route\",\n\t\t\t\t\"Tool provider adapter input requires the selected ExecutorRoute fact.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (route !== undefined) {\n\t\tissues.push(...routeIdentityIssuesForAdapterInput(route, resolution, request, sourceRefs));\n\t}\n\tif (resolution.providerId !== undefined && catalog === undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-catalog\",\n\t\t\t\t\"Tool provider adapter input requires the selected ToolProviderCatalog fact.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (catalog !== undefined && catalog.status !== undefined && catalog.status !== \"ready\") {\n\t\tstatusOverride = \"invalid-policy\";\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-catalog-unavailable\",\n\t\t\t\t\"Tool provider adapter input requires a ready ToolProviderCatalog.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: resolution.requestId,\n\t\t\t\t\trefs: [...sourceRefs, ref(\"tool-provider-catalog\", catalog.providerId)],\n\t\t\t\t\tdetails: { status: catalog.status },\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t\tissues.push(...(catalog.issues ?? []).map((issue) => sanitizeAdapterInputIssue(issue)));\n\t}\n\tconst toolCall = request === undefined ? undefined : toolCallFromRequest(request);\n\tif (request !== undefined && toolCall === undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-tool-call\",\n\t\t\t\t\"Tool provider adapter input requires AgentRequest input.value to be a ToolCallInput.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tconst tool =\n\t\tcatalog === undefined || route === undefined || toolCall === undefined\n\t\t\t? undefined\n\t\t\t: selectedToolForAdapterInput(catalog, route, toolCall);\n\tif (resolution.status === \"resolved\" && tool === undefined) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-tool\",\n\t\t\t\t\"Tool provider adapter input requires the selected catalog tool entry.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tconst policies =\n\t\tcatalog === undefined\n\t\t\t? []\n\t\t\t: selectedPoliciesForAdapterInput(catalog, resolution.policyRefs ?? []);\n\tif (resolution.status === \"resolved\" && (resolution.policyRefs?.length ?? 0) === 0) {\n\t\tstatusOverride = \"missing-policy\";\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-missing-policy-ref\",\n\t\t\t\t\"Ready tool provider adapter input requires at least one D360 policy ref.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs: sourceRefs },\n\t\t\t),\n\t\t);\n\t}\n\tif (catalog !== undefined) {\n\t\tfor (const issue of policyMaterialIssuesForAdapterInput(catalog, resolution, sourceRefs)) {\n\t\t\tstatusOverride ??= \"invalid-policy\";\n\t\t\tissues.push(issue);\n\t\t}\n\t}\n\tfor (const policy of policies) {\n\t\tissues.push(...validateToolProviderExecutionPolicy(policy));\n\t\tif (catalog !== undefined)\n\t\t\tissues.push(...validateToolProviderPolicyProviderScope(policy, catalog.providerId));\n\t}\n\tif (request?.input !== undefined) {\n\t\tissues.push(\n\t\t\t...forbiddenAdapterInputMaterialIssues(\n\t\t\t\trequest.input,\n\t\t\t\tref(\"agent-request\", request.requestId),\n\t\t\t\t\"request-input\",\n\t\t\t),\n\t\t);\n\t}\n\tif (route !== undefined) {\n\t\tissues.push(\n\t\t\t...forbiddenAdapterInputMaterialIssues(\n\t\t\t\troute.allowedParams,\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\t\"route-allowed-params\",\n\t\t\t),\n\t\t\t...forbiddenAdapterInputMaterialIssues(\n\t\t\t\troute.metadata,\n\t\t\t\tref(\"executor-route\", route.routeId),\n\t\t\t\t\"route-metadata\",\n\t\t\t),\n\t\t);\n\t}\n\tif (tool !== undefined) {\n\t\tconst toolRef = ref(\"tool\", tool.toolName);\n\t\tissues.push(\n\t\t\t...forbiddenAdapterInputMaterialIssues(tool.capabilities, toolRef, \"tool-capabilities\"),\n\t\t\t...forbiddenAdapterInputMaterialIssues(tool.limits, toolRef, \"tool-limits\"),\n\t\t\t...forbiddenAdapterInputMaterialIssues(tool.metadata, toolRef, \"tool-metadata\"),\n\t\t);\n\t}\n\tfor (const policy of policies) {\n\t\tissues.push(\n\t\t\t...forbiddenAdapterInputMaterialIssues(\n\t\t\t\tpolicy,\n\t\t\t\tref(\"tool-provider-execution-policy\", policy.policyId),\n\t\t\t\t\"policy-material\",\n\t\t\t),\n\t\t);\n\t}\n\tconst status =\n\t\tresolution.status === \"resolved\"\n\t\t\t? issues.length === 0\n\t\t\t\t? \"ready\"\n\t\t\t\t: (statusOverride ?? \"invalid-policy\")\n\t\t\t: resolution.status;\n\tconst ready = status === \"ready\";\n\tconst candidate = {\n\t\tkind: \"tool-provider-adapter-input\",\n\t\tadapterInputId: `${resolution.requestId}:${resolution.operationId}:${resolution.routeId ?? resolution.resolutionId}:adapter-input`,\n\t\tstatus,\n\t\trequestId: resolution.requestId,\n\t\toperationId: resolution.operationId,\n\t\teffectRunId: request?.effectRunId,\n\t\tagentRunId: request?.agentRunId,\n\t\trouteId: resolution.routeId,\n\t\tproviderId: resolution.providerId,\n\t\texecutorId: resolution.executorId,\n\t\tprofileId: resolution.profileId,\n\t\ttoolName: resolution.toolName,\n\t\toperation: resolution.operation,\n\t\tinput: ready ? (request?.input as AgentRequestInput<ToolCallInput> | undefined) : undefined,\n\t\ttoolCall: ready ? toolCall : undefined,\n\t\troute: ready ? route : undefined,\n\t\ttool: ready ? tool : undefined,\n\t\tpolicies: ready ? Object.freeze(policies) : undefined,\n\t\tpolicyRefs: sanitizeAdapterInputSourceRefs(resolution.policyRefs ?? []),\n\t\tsourceRefs,\n\t\tissues: issues.length === 0 ? undefined : Object.freeze(issues),\n\t\tmetadata: { resolutionId: resolution.resolutionId },\n\t} satisfies ToolProviderAdapterInput;\n\tif (ready) {\n\t\tconst candidateIssues = forbiddenAdapterInputMaterialIssues(\n\t\t\tcandidate,\n\t\t\tref(\"tool-provider-adapter-input\", candidate.adapterInputId),\n\t\t\t\"adapter-input\",\n\t\t);\n\t\tif (candidateIssues.length > 0) {\n\t\t\tconst blockedIssues = Object.freeze([...issues, ...candidateIssues]);\n\t\t\treturn Object.freeze({\n\t\t\t\t...candidate,\n\t\t\t\tstatus: \"invalid-policy\",\n\t\t\t\tinput: undefined,\n\t\t\t\ttoolCall: undefined,\n\t\t\t\troute: undefined,\n\t\t\t\ttool: undefined,\n\t\t\t\tpolicies: undefined,\n\t\t\t\tissues: blockedIssues,\n\t\t\t} satisfies ToolProviderAdapterInput);\n\t\t}\n\t}\n\treturn Object.freeze(candidate);\n}\n\nexport function selectedToolForAdapterInput(\n\tcatalog: ToolProviderCatalog,\n\troute: ExecutorRoute,\n\ttoolCall: ToolCallInput,\n): ToolProviderCatalogEntry | undefined {\n\treturn catalog.tools.find(\n\t\t(entry) =>\n\t\t\tentry.profileId === route.profileId &&\n\t\t\tentry.executorId === route.executorId &&\n\t\t\tentry.toolName === toolCall.toolName &&\n\t\t\t(entry.operation === undefined ||\n\t\t\t\ttoolCall.operation === undefined ||\n\t\t\t\tentry.operation === toolCall.operation),\n\t);\n}\n\nexport function selectedPoliciesForAdapterInput(\n\tcatalog: ToolProviderCatalog,\n\tpolicyRefs: readonly SourceRef[],\n): ToolProviderExecutionPolicy[] {\n\tconst policiesById = new Map((catalog.policies ?? []).map((policy) => [policy.policyId, policy]));\n\tconst policies: ToolProviderExecutionPolicy[] = [];\n\tfor (const policyRef of policyRefs) {\n\t\tif (policyRef.kind !== \"tool-provider-execution-policy\") continue;\n\t\tconst policy = policiesById.get(policyRef.id);\n\t\tif (policy !== undefined) policies.push(policy);\n\t}\n\treturn policies;\n}\n\nexport function routeIdentityIssuesForAdapterInput(\n\troute: ExecutorRoute,\n\tresolution: ToolProviderPolicyResolution,\n\trequest: AgentRequestIssued | undefined,\n\tsourceRefs: readonly SourceRef[],\n): readonly DataIssue[] {\n\tconst issues: DataIssue[] = [];\n\tconst refs = [...sourceRefs, ref(\"executor-route\", route.routeId)];\n\tif (route.requestId !== resolution.requestId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-request\",\n\t\t\t\t\"ExecutorRoute requestId does not match the tool provider policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (route.operationId !== resolution.operationId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-operation\",\n\t\t\t\t\"ExecutorRoute operationId does not match the tool provider policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (resolution.routeId !== undefined && route.routeId !== resolution.routeId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-id\",\n\t\t\t\t\"ExecutorRoute routeId does not match the tool provider policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (resolution.executorId !== undefined && route.executorId !== resolution.executorId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-executor\",\n\t\t\t\t\"ExecutorRoute executorId does not match the tool provider policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (resolution.profileId !== undefined && route.profileId !== resolution.profileId) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-profile\",\n\t\t\t\t\"ExecutorRoute profileId does not match the tool provider policy resolution.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (\n\t\trequest !== undefined &&\n\t\troute.inputId !== undefined &&\n\t\troute.inputId !== request.input?.inputId\n\t) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-input\",\n\t\t\t\t\"ExecutorRoute inputId does not match the issued AgentRequest input.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (route.inputKind !== undefined && route.inputKind !== \"tool-call\") {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-invalid-route-input-kind\",\n\t\t\t\t\"Tool provider adapter input requires ExecutorRoute.inputKind to be tool-call when present.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\tif (\n\t\trequest !== undefined &&\n\t\troute.inputKind !== undefined &&\n\t\trequest.input?.inputKind !== undefined &&\n\t\troute.inputKind !== request.input.inputKind\n\t) {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-adapter-input-stale-route-input-kind\",\n\t\t\t\t\"ExecutorRoute inputKind does not match the issued AgentRequest input.\",\n\t\t\t\t{ subjectId: resolution.requestId, refs },\n\t\t\t),\n\t\t);\n\t}\n\treturn Object.freeze(issues);\n}\n\nexport function policyMaterialIssuesForAdapterInput(\n\tcatalog: ToolProviderCatalog,\n\tresolution: ToolProviderPolicyResolution,\n\tsourceRefs: readonly SourceRef[],\n): readonly DataIssue[] {\n\tconst policiesById = new Map((catalog.policies ?? []).map((policy) => [policy.policyId, policy]));\n\tconst issues: DataIssue[] = [];\n\tfor (const policyRef of resolution.policyRefs ?? []) {\n\t\tif (policyRef.kind !== \"tool-provider-execution-policy\") {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-adapter-input-invalid-policy-ref-kind\",\n\t\t\t\t\t\"Tool provider adapter input policy refs must point at ToolProviderExecutionPolicy facts.\",\n\t\t\t\t\t{ subjectId: resolution.requestId, refs: [...sourceRefs, policyRef] },\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!policiesById.has(policyRef.id)) {\n\t\t\tissues.push(\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-adapter-input-policy-ref-missing-material\",\n\t\t\t\t\t\"Tool provider adapter input policy ref has no selected policy material.\",\n\t\t\t\t\t{ subjectId: resolution.requestId, refs: [...sourceRefs, policyRef] },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn Object.freeze(issues);\n}\n\nexport function stableToolProviderAdapterInputKey(input: ToolProviderAdapterInput): string {\n\treturn stableJsonStringify({\n\t\tid: input.adapterInputId,\n\t\tstatus: input.status,\n\t\tpolicyRefs: input.policyRefs?.map((policyRef) => `${policyRef.kind}:${policyRef.id}`) ?? [],\n\t\tissues: input.issues?.map((issue) => issue.code) ?? [],\n\t\tinput,\n\t});\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\trequestToolProviderAdapterRun,\n\trunRequestIdentityIssues,\n} from \"./agent-runtime-adapter-run.js\";\nimport {\n\tdataIssue,\n\tforEachDepBatch,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeProviderGraphVisibleRecord,\n\tuniqueSourceRefs,\n} from \"./agent-runtime-common.js\";\nimport type { AgentNeed, AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterInput,\n\tToolProviderAdapterRunRequested,\n\tToolProviderApprovalPolicy,\n\tToolProviderExecutionPolicy,\n\tToolProviderRunAdmission,\n\tToolProviderRunAdmissionBundle,\n\tToolProviderRunAdmissionDecision,\n\tToolProviderRunAdmissionOutcome,\n\tToolProviderRunAdmissionProposal,\n\tToolProviderRunAdmissionState,\n\tToolProviderRunAdmissionStatus,\n\tToolProviderRunAdmissionViews,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function toolProviderRunAdmissionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly inputs: Node<ToolProviderAdapterInput>;\n\t\treadonly runRequests: readonly Node<ToolProviderAdapterRunRequested>[];\n\t\treadonly decisions?: readonly Node<ToolProviderRunAdmissionDecision>[];\n\t\treadonly now?: () => number;\n\t},\n): ToolProviderRunAdmissionBundle {\n\tconst name = opts.name ?? \"toolProviderRunAdmission\";\n\tconst decisionDeps = opts.decisions ?? [];\n\tconst runtime = graph.node<ToolProviderRunAdmissionFact>(\n\t\t[opts.inputs, ...opts.runRequests, ...decisionDeps],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ToolProviderRunAdmissionProjectorState>() ?? {\n\t\t\t\tinputs: new Map<string, ToolProviderAdapterInput>(),\n\t\t\t\tproposalsById: new Map<string, InternalAdmissionProposal>(),\n\t\t\t\tproposalsByRun: new Map<string, ToolProviderRunAdmissionProposal[]>(),\n\t\t\t\tdecisionsByProposal: new Map<string, ToolProviderRunAdmissionDecision>(),\n\t\t\t\tadmissionsByProposal: new Map<string, ToolProviderRunAdmission>(),\n\t\t\t\tadmissionsByRun: new Map<string, ToolProviderRunAdmission[]>(),\n\t\t\t\tproposalKeys: new Set<string>(),\n\t\t\t\tadmissionKeys: new Set<string>(),\n\t\t\t\tapprovedRunKeys: new Set<string>(),\n\t\t\t\tstatusKeys: new Set<string>(),\n\t\t\t\tissueKeys: new Set<string>(),\n\t\t\t\tauditSeq: 0,\n\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst input = raw as ToolProviderAdapterInput;\n\t\t\t\tstate.inputs.set(input.adapterInputId, input);\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, 1, opts.runRequests.length, (raw) => {\n\t\t\t\tconst request = raw as ToolProviderAdapterRunRequested;\n\t\t\t\tconst input = state.inputs.get(request.adapterInputId);\n\t\t\t\tif (input === undefined) {\n\t\t\t\t\temitAdmissionIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"tool-provider-run-admission-missing-input\",\n\t\t\t\t\t\t\t\"Tool provider run admission request references an unknown adapter input.\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\t\t\t\trefs: sanitizeAdapterInputSourceRefs([\n\t\t\t\t\t\t\t\t\tref(\"tool-provider-adapter-run\", request.runId),\n\t\t\t\t\t\t\t\t\t...(request.sourceRefs ?? []),\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\temitAdmissionStatus(ctx, state, {\n\t\t\t\t\t\tkind: \"tool-provider-run-admission-status\",\n\t\t\t\t\t\tproposalId: `${request.runId}:admission-proposal`,\n\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\trequestId: request.requestId,\n\t\t\t\t\t\toperationId: request.operationId,\n\t\t\t\t\t\tstate: \"issue\",\n\t\t\t\t\t\tsourceRefs: request.sourceRefs,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\thandleRunRequest(ctx, state, input, request, opts.now);\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, 1 + opts.runRequests.length, decisionDeps.length, (raw) => {\n\t\t\t\tconst decision = sanitizeAdmissionDecision(raw as ToolProviderRunAdmissionDecision);\n\t\t\t\tstate.decisionsByProposal.set(decision.proposalId, decision);\n\t\t\t\tconst internal = state.proposalsById.get(decision.proposalId);\n\t\t\t\tif (internal !== undefined) applyDecision(ctx, state, internal, decision, opts.now);\n\t\t\t});\n\t\t\tctx.down([[\"DATA\", { kind: \"views\", views: buildAdmissionViews(state) }]]);\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"toolProviderRunAdmissionProjector\", partial: true },\n\t);\n\treturn {\n\t\tproposals: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/proposals`,\n\t\t\t\"toolProviderRunAdmissionProposals\",\n\t\t\t(fact) => (fact.kind === \"proposal\" ? fact.proposal : undefined),\n\t\t),\n\t\tadmissions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/admissions`,\n\t\t\t\"toolProviderRunAdmissions\",\n\t\t\t(fact) => (fact.kind === \"admission\" ? fact.admission : undefined),\n\t\t),\n\t\tapprovedRunRequests: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/approvedRunRequests`,\n\t\t\t\"toolProviderRunAdmissionApprovedRunRequests\",\n\t\t\t(fact) => (fact.kind === \"approved-run-request\" ? fact.request : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"toolProviderRunAdmissionStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"toolProviderRunAdmissionIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"toolProviderRunAdmissionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/views`,\n\t\t\t\"toolProviderRunAdmissionViews\",\n\t\t\t(fact) => (fact.kind === \"views\" ? fact.views : undefined),\n\t\t),\n\t};\n}\n\ntype ToolProviderRunAdmissionFact =\n\t| { readonly kind: \"proposal\"; readonly proposal: ToolProviderRunAdmissionProposal }\n\t| { readonly kind: \"admission\"; readonly admission: ToolProviderRunAdmission }\n\t| { readonly kind: \"approved-run-request\"; readonly request: ToolProviderAdapterRunRequested }\n\t| { readonly kind: \"status\"; readonly status: ToolProviderRunAdmissionStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord }\n\t| { readonly kind: \"views\"; readonly views: ToolProviderRunAdmissionViews };\n\ninterface InternalAdmissionProposal {\n\treadonly proposal: ToolProviderRunAdmissionProposal;\n\treadonly request: ToolProviderAdapterRunRequested;\n\treadonly input: ToolProviderAdapterInput;\n}\n\ninterface ToolProviderRunAdmissionProjectorState {\n\tinputs: Map<string, ToolProviderAdapterInput>;\n\tproposalsById: Map<string, InternalAdmissionProposal>;\n\tproposalsByRun: Map<string, ToolProviderRunAdmissionProposal[]>;\n\tdecisionsByProposal: Map<string, ToolProviderRunAdmissionDecision>;\n\tadmissionsByProposal: Map<string, ToolProviderRunAdmission>;\n\tadmissionsByRun: Map<string, ToolProviderRunAdmission[]>;\n\tproposalKeys: Set<string>;\n\tadmissionKeys: Set<string>;\n\tapprovedRunKeys: Set<string>;\n\tstatusKeys: Set<string>;\n\tissueKeys: Set<string>;\n\tauditSeq: number;\n}\n\nfunction handleRunRequest(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tinput: ToolProviderAdapterInput,\n\trequest: ToolProviderAdapterRunRequested,\n\tnow: (() => number) | undefined,\n): void {\n\tconst issues = runRequestIdentityIssues(request, input);\n\tif (input.status !== \"ready\") {\n\t\tissues.push(\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-run-admission-input-not-ready\",\n\t\t\t\t\"Tool provider run admission requires a ready adapter input.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-input\", input.adapterInputId)],\n\t\t\t\t\tdetails: { status: input.status },\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\tif (issues.length > 0) {\n\t\tfor (const issue of issues) emitAdmissionIssue(ctx, state, issue);\n\t\temitAdmissionStatus(ctx, state, {\n\t\t\tkind: \"tool-provider-run-admission-status\",\n\t\t\tproposalId: `${request.runId}:admission-proposal`,\n\t\t\trunId: request.runId,\n\t\t\tadapterInputId: request.adapterInputId,\n\t\t\trequestId: request.requestId,\n\t\t\toperationId: request.operationId,\n\t\t\tstate: \"issue\",\n\t\t\tissues: Object.freeze(issues),\n\t\t\tsourceRefs: request.sourceRefs,\n\t\t});\n\t\temitAdmissionAudit(ctx, state, \"tool-provider-run-admission-request-rejected\", request, {\n\t\t\tissueCodes: issues.map((issue) => issue.code),\n\t\t});\n\t\treturn;\n\t}\n\tconst approval = resolveApprovalPolicy(input);\n\tconst proposal = admissionProposal(input, request, approval);\n\tconst internal = { proposal, request, input };\n\tstate.proposalsById.set(proposal.proposalId, internal);\n\tpushMapArrayBy(state.proposalsByRun, request.runId, proposal, (entry) => entry.proposalId);\n\temitProposal(ctx, state, proposal);\n\temitAdmissionAudit(ctx, state, \"tool-provider-run-admission-proposed\", proposal, {\n\t\tapprovalMode: proposal.approvalMode,\n\t});\n\tif (proposal.approvalMode === \"auto\") {\n\t\tadmit(ctx, state, internal, undefined, now);\n\t\treturn;\n\t}\n\tif (proposal.approvalMode === \"never\") {\n\t\trecordAdmission(ctx, state, internal, \"blocked\", {\n\t\t\treason: \"blocked by tool provider approval policy\",\n\t\t\tnow,\n\t\t});\n\t\treturn;\n\t}\n\tconst decision = state.decisionsByProposal.get(proposal.proposalId);\n\tif (decision === undefined) {\n\t\temitAdmissionStatus(ctx, state, {\n\t\t\tkind: \"tool-provider-run-admission-status\",\n\t\t\tproposalId: proposal.proposalId,\n\t\t\trunId: request.runId,\n\t\t\tadapterInputId: request.adapterInputId,\n\t\t\trequestId: request.requestId,\n\t\t\toperationId: request.operationId,\n\t\t\tstate: \"waiting\",\n\t\t\tsourceRefs: proposal.sourceRefs,\n\t\t});\n\t\treturn;\n\t}\n\tapplyDecision(ctx, state, internal, decision, now);\n}\n\nfunction applyDecision(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tinternal: InternalAdmissionProposal,\n\tdecision: ToolProviderRunAdmissionDecision,\n\tnow: (() => number) | undefined,\n): void {\n\tconst existing = state.admissionsByProposal.get(internal.proposal.proposalId);\n\tif (existing !== undefined) {\n\t\tif (existing.decisionId === decision.decisionId) return;\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-admission-duplicate-decision\",\n\t\t\t\"Tool provider run admission proposal already has a terminal admission decision.\",\n\t\t\t{\n\t\t\t\tsubjectId: internal.input.requestId,\n\t\t\t\trefs: admissionSourceRefs(internal, decision),\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tdetails: {\n\t\t\t\t\tproposalId: internal.proposal.proposalId,\n\t\t\t\t\texistingDecisionId: existing.decisionId,\n\t\t\t\t\trejectedDecisionId: decision.decisionId,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\temitAdmissionIssue(ctx, state, issue);\n\t\temitAdmissionStatus(ctx, state, {\n\t\t\tkind: \"tool-provider-run-admission-status\",\n\t\t\tproposalId: internal.proposal.proposalId,\n\t\t\trunId: internal.request.runId,\n\t\t\tadapterInputId: internal.input.adapterInputId,\n\t\t\trequestId: internal.input.requestId,\n\t\t\toperationId: internal.input.operationId,\n\t\t\tstate: \"issue\",\n\t\t\tissues: Object.freeze([issue]),\n\t\t\tsourceRefs: admissionSourceRefs(internal, decision),\n\t\t});\n\t\temitAdmissionAudit(ctx, state, \"tool-provider-run-admission-duplicate-decision\", decision, {\n\t\t\tproposalId: internal.proposal.proposalId,\n\t\t\texistingDecisionId: existing.decisionId,\n\t\t});\n\t\treturn;\n\t}\n\tif (decision.outcome === \"admit\") {\n\t\tadmit(ctx, state, internal, decision, now);\n\t\treturn;\n\t}\n\trecordAdmission(ctx, state, internal, admissionStateForOutcome(decision.outcome), {\n\t\tdecision,\n\t\treason: decision.reason,\n\t\tnow,\n\t});\n}\n\nfunction admit(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tinternal: InternalAdmissionProposal,\n\tdecision: ToolProviderRunAdmissionDecision | undefined,\n\tnow: (() => number) | undefined,\n): void {\n\tconst approvedRunId =\n\t\tdecision?.approvedRunId ??\n\t\t(decision === undefined\n\t\t\t? `${internal.request.runId}:admitted`\n\t\t\t: `${internal.request.runId}:admitted:${decision.decisionId}`);\n\tconst admission = recordAdmission(ctx, state, internal, \"admitted\", {\n\t\tdecision,\n\t\tapprovedRunId,\n\t\treason: decision?.reason,\n\t\tnow,\n\t});\n\tconst approvedRequest = requestToolProviderAdapterRun(internal.input, {\n\t\trunId: approvedRunId,\n\t\tattempt: internal.request.attempt,\n\t\treason: internal.request.reason,\n\t\tretryOfOutcomeId: internal.request.retryOfOutcomeId,\n\t\tpolicyRefs: internal.request.policyRefs ?? internal.input.policyRefs,\n\t\tsourceRefs: uniqueSourceRefs([\n\t\t\tref(\"tool-provider-adapter-run\", internal.request.runId),\n\t\t\tref(\"tool-provider-run-admission-proposal\", internal.proposal.proposalId),\n\t\t\tref(\"tool-provider-run-admission\", admission.admissionId),\n\t\t\t...(decision === undefined\n\t\t\t\t? []\n\t\t\t\t: [ref(\"tool-provider-run-admission-decision\", decision.decisionId)]),\n\t\t\t...(internal.request.sourceRefs ?? []),\n\t\t]),\n\t\tmetadata: {\n\t\t\t...(internal.request.metadata ?? {}),\n\t\t\tapproval: \"granted\",\n\t\t\tapprovalGranted: true,\n\t\t\tadmissionId: admission.admissionId,\n\t\t\tproposalId: internal.proposal.proposalId,\n\t\t\tapprovedFromRunId: internal.request.runId,\n\t\t\t...(decision === undefined ? {} : { decisionId: decision.decisionId }),\n\t\t},\n\t\trequestedAtMs: now?.(),\n\t});\n\temitApprovedRunRequest(ctx, state, approvedRequest);\n\temitAdmissionAudit(\n\t\tctx,\n\t\tstate,\n\t\t\"tool-provider-run-admission-approved-run-requested\",\n\t\t{\n\t\t\tproposalId: internal.proposal.proposalId,\n\t\t\trunId: approvedRequest.runId,\n\t\t},\n\t\t{\n\t\t\tapprovedFromRunId: internal.request.runId,\n\t\t\tdecisionId: decision?.decisionId,\n\t\t},\n\t);\n}\n\nfunction recordAdmission(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tinternal: InternalAdmissionProposal,\n\tadmissionState: ToolProviderRunAdmissionState,\n\topts: {\n\t\treadonly decision?: ToolProviderRunAdmissionDecision;\n\t\treadonly approvedRunId?: string;\n\t\treadonly reason?: string;\n\t\treadonly now?: (() => number) | undefined;\n\t},\n): ToolProviderRunAdmission {\n\tconst admissionId = opts.decision?.admissionId ?? `${internal.proposal.proposalId}:admission`;\n\tconst sourceRefs = admissionSourceRefs(internal, opts.decision);\n\tconst admission: ToolProviderRunAdmission = Object.freeze({\n\t\tkind: \"tool-provider-run-admission\",\n\t\tadmissionId,\n\t\tproposalId: internal.proposal.proposalId,\n\t\trunId: internal.request.runId,\n\t\tadapterInputId: internal.input.adapterInputId,\n\t\trequestId: internal.input.requestId,\n\t\toperationId: internal.input.operationId,\n\t\tstate: admissionState,\n\t\t...(opts.decision === undefined ? {} : { decisionId: opts.decision.decisionId }),\n\t\t...(opts.approvedRunId === undefined ? {} : { approvedRunId: opts.approvedRunId }),\n\t\t...(opts.reason === undefined ? {} : { reason: opts.reason }),\n\t\tsourceRefs,\n\t\tmetadata: sanitizeProviderGraphVisibleRecord({\n\t\t\tapprovalMode: internal.proposal.approvalMode,\n\t\t\toccurredAtMs: opts.now?.(),\n\t\t}),\n\t});\n\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\tpushMapArrayBy(state.admissionsByRun, admission.runId, admission, (entry) => entry.admissionId);\n\temitAdmission(ctx, state, admission);\n\tif (admissionState === \"blocked\") {\n\t\temitAdmissionIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\tdataIssue(\n\t\t\t\t\"tool-provider-run-admission-blocked\",\n\t\t\t\t\"Tool provider run admission blocked the candidate run request.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: internal.input.requestId,\n\t\t\t\t\trefs: sourceRefs,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tdetails: { approvalMode: internal.proposal.approvalMode },\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t}\n\temitAdmissionStatus(ctx, state, {\n\t\tkind: \"tool-provider-run-admission-status\",\n\t\tproposalId: admission.proposalId,\n\t\trunId: admission.runId,\n\t\tadapterInputId: admission.adapterInputId,\n\t\trequestId: admission.requestId,\n\t\toperationId: admission.operationId,\n\t\tstate: admission.state,\n\t\tadmissionId: admission.admissionId,\n\t\t...(admission.decisionId === undefined ? {} : { decisionId: admission.decisionId }),\n\t\t...(admission.approvedRunId === undefined ? {} : { approvedRunId: admission.approvedRunId }),\n\t\tsourceRefs,\n\t});\n\temitAdmissionAudit(ctx, state, `tool-provider-run-admission-${admissionState}`, admission, {\n\t\tdecisionId: opts.decision?.decisionId,\n\t});\n\treturn admission;\n}\n\nfunction admissionProposal(\n\tinput: ToolProviderAdapterInput,\n\trequest: ToolProviderAdapterRunRequested,\n\tapproval: ResolvedApprovalPolicy,\n): ToolProviderRunAdmissionProposal {\n\tconst sourceRefs = uniqueSourceRefs([\n\t\tref(\"tool-provider-adapter-run\", request.runId),\n\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t...(request.sourceRefs ?? []),\n\t\t...(input.sourceRefs ?? []),\n\t\t...(approval.policy?.approval?.sourceRefs ?? []),\n\t\t...(approval.policy?.sourceRefs ?? []),\n\t]);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-admission-proposal\",\n\t\tproposalId: `${request.runId}:admission-proposal`,\n\t\trunId: request.runId,\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\trouteId: input.routeId,\n\t\tproviderId: input.providerId,\n\t\texecutorId: input.executorId,\n\t\tprofileId: input.profileId,\n\t\ttoolName: input.toolName,\n\t\toperation: input.operation,\n\t\tattempt: request.attempt,\n\t\treason: request.reason,\n\t\tapprovalMode: approval.mode,\n\t\tpolicyRefs: sanitizeAdapterInputSourceRefs([\n\t\t\t...(request.policyRefs ?? []),\n\t\t\t...(input.policyRefs ?? []),\n\t\t\t...(approval.policy === undefined\n\t\t\t\t? []\n\t\t\t\t: [ref(\"tool-provider-execution-policy\", approval.policy.policyId)]),\n\t\t]),\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs(sourceRefs),\n\t\tneeds:\n\t\t\tapproval.mode === \"require\" || approval.mode === \"custom\"\n\t\t\t\t? approvalNeeds(approval.policy?.approval)\n\t\t\t\t: undefined,\n\t\tmetadata: sanitizeProviderGraphVisibleRecord({\n\t\t\tapprovalPolicyId: approval.policy?.policyId,\n\t\t\tapprovalMode: approval.mode,\n\t\t}),\n\t});\n}\n\nfunction resolveApprovalPolicy(input: ToolProviderAdapterInput): ResolvedApprovalPolicy {\n\tfor (const policy of input.policies ?? []) {\n\t\tconst approval = policy.approval;\n\t\tconst mode = approval?.mode ?? \"auto\";\n\t\tif (matchesApprovalSelector(input, approval)) return { mode, policy };\n\t}\n\treturn { mode: \"auto\" };\n}\n\ninterface ResolvedApprovalPolicy {\n\treadonly mode: \"auto\" | \"require\" | \"never\" | \"custom\" | (string & {});\n\treadonly policy?: ToolProviderExecutionPolicy;\n}\n\nfunction matchesApprovalSelector(\n\tinput: ToolProviderAdapterInput,\n\tapproval: ToolProviderApprovalPolicy | undefined,\n): boolean {\n\tif (approval === undefined) return true;\n\tconst names = approval.requiredForToolNames;\n\tconst operations = approval.requiredForOperations;\n\tconst matchesName =\n\t\tnames === undefined || (input.toolName !== undefined && names.includes(input.toolName));\n\tconst matchesOperation =\n\t\toperations === undefined ||\n\t\t(input.operation !== undefined && operations.includes(input.operation));\n\treturn matchesName && matchesOperation;\n}\n\nfunction approvalNeeds(approval: ToolProviderApprovalPolicy | undefined): readonly AgentNeed[] {\n\treturn Object.freeze([\n\t\t{\n\t\t\tkind: \"approval\",\n\t\t\tmessage: \"Tool provider run requires graph-visible admission.\",\n\t\t\trefs: sanitizeAdapterInputSourceRefs(approval?.approverRefs ?? []),\n\t\t\tmetadata: sanitizeProviderGraphVisibleRecord({ approvalMode: approval?.mode ?? \"require\" }),\n\t\t},\n\t]);\n}\n\nfunction admissionStateForOutcome(\n\toutcome: ToolProviderRunAdmissionOutcome,\n): ToolProviderRunAdmissionState {\n\tif (outcome === \"admit\") return \"admitted\";\n\tif (outcome === \"defer\") return \"deferred\";\n\treturn \"blocked\";\n}\n\nfunction admissionSourceRefs(\n\tinternal: InternalAdmissionProposal,\n\tdecision: ToolProviderRunAdmissionDecision | undefined,\n): readonly SourceRef[] {\n\treturn sanitizeAdapterInputSourceRefs([\n\t\tref(\"tool-provider-run-admission-proposal\", internal.proposal.proposalId),\n\t\tref(\"tool-provider-adapter-run\", internal.request.runId),\n\t\tref(\"tool-provider-adapter-input\", internal.input.adapterInputId),\n\t\t...(decision === undefined\n\t\t\t? []\n\t\t\t: [ref(\"tool-provider-run-admission-decision\", decision.decisionId)]),\n\t\t...(decision?.sourceRefs ?? []),\n\t]);\n}\n\nfunction sanitizeAdmissionDecision(\n\tdecision: ToolProviderRunAdmissionDecision,\n): ToolProviderRunAdmissionDecision {\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-admission-decision\",\n\t\tdecisionId: decision.decisionId,\n\t\tproposalId: decision.proposalId,\n\t\tadmissionId: decision.admissionId,\n\t\toutcome: decision.outcome,\n\t\t...(decision.approvedRunId === undefined ? {} : { approvedRunId: decision.approvedRunId }),\n\t\t...(decision.reason === undefined ? {} : { reason: decision.reason }),\n\t\t...(decision.decidedByRef === undefined\n\t\t\t? {}\n\t\t\t: { decidedByRef: sanitizeAdapterInputSourceRefs([decision.decidedByRef])[0] }),\n\t\t...(decision.sourceRefs === undefined\n\t\t\t? {}\n\t\t\t: { sourceRefs: sanitizeAdapterInputSourceRefs(decision.sourceRefs) }),\n\t\tmetadata: sanitizeProviderGraphVisibleRecord(decision.metadata),\n\t});\n}\n\nfunction emitProposal(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tproposal: ToolProviderRunAdmissionProposal,\n): void {\n\tconst key = `proposal:${proposal.proposalId}`;\n\tif (state.proposalKeys.has(key)) return;\n\tstate.proposalKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"proposal\", proposal }]]);\n}\n\nfunction emitAdmission(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tadmission: ToolProviderRunAdmission,\n): void {\n\tconst key = `admission:${admission.admissionId}:${admission.state}:${admission.decisionId ?? \"\"}:${admission.approvedRunId ?? \"\"}`;\n\tif (state.admissionKeys.has(key)) return;\n\tstate.admissionKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"admission\", admission }]]);\n}\n\nfunction emitApprovedRunRequest(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\trequest: ToolProviderAdapterRunRequested,\n): void {\n\tconst key = `approved-run:${request.runId}`;\n\tif (state.approvedRunKeys.has(key)) return;\n\tstate.approvedRunKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"approved-run-request\", request }]]);\n}\n\nfunction emitAdmissionStatus(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tstatus: ToolProviderRunAdmissionStatus,\n): void {\n\tconst key = `status:${status.proposalId}:${status.state}:${status.admissionId ?? \"\"}:${status.decisionId ?? \"\"}:${status.approvedRunId ?? \"\"}`;\n\tif (state.statusKeys.has(key)) return;\n\tstate.statusKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"status\", status }]]);\n}\n\nfunction emitAdmissionIssue(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tissue: DataIssue,\n): void {\n\tconst key = `issue:${issue.code}:${issue.subjectId ?? \"\"}:${JSON.stringify(issue.details ?? {})}`;\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"issue\", issue }]]);\n}\n\nfunction emitAdmissionAudit(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunAdmissionFact][]) => void },\n\tstate: ToolProviderRunAdmissionProjectorState,\n\tkind: string,\n\tsubject: unknown,\n\tmetadata?: Record<string, unknown>,\n): void {\n\tstate.auditSeq += 1;\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: Object.freeze({\n\t\t\t\t\tid: `tool-provider-run-admission-audit-${state.auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\tmessage: kind,\n\t\t\t\t\tsourceRefs: [],\n\t\t\t\t\tmetadata: sanitizeProviderGraphVisibleRecord({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t}),\n\t\t\t\t} satisfies AgentRuntimeAuditRecord),\n\t\t\t},\n\t\t],\n\t]);\n}\n\nfunction buildAdmissionViews(\n\tstate: ToolProviderRunAdmissionProjectorState,\n): ToolProviderRunAdmissionViews {\n\treturn Object.freeze({\n\t\tadmissionsByProposal: new Map(state.admissionsByProposal),\n\t\tadmissionsByRun: new Map(\n\t\t\tArray.from(state.admissionsByRun.entries()).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\tObject.freeze([...value]),\n\t\t\t]),\n\t\t),\n\t\tproposalsByRun: new Map(\n\t\t\tArray.from(state.proposalsByRun.entries()).map(([key, value]) => [\n\t\t\t\tkey,\n\t\t\t\tObject.freeze([...value]),\n\t\t\t]),\n\t\t),\n\t});\n}\n\nfunction pushMapArrayBy<T>(\n\tmap: Map<string, T[]>,\n\tkey: string,\n\tvalue: T,\n\tentryKey: (entry: T) => string,\n): void {\n\tconst existing = map.get(key);\n\tif (existing === undefined) {\n\t\tmap.set(key, [value]);\n\t\treturn;\n\t}\n\tconst valueKey = entryKey(value);\n\tif (existing.some((entry) => entryKey(entry) === valueKey)) return;\n\texisting.push(value);\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { RetryPolicy } from \"../graph/resilience.js\";\nimport { nextRetryDelayMs, shouldRetry } from \"../graph/resilience.js\";\nimport type { Node } from \"../node/node.js\";\nimport { requestToolProviderAdapterRun } from \"./agent-runtime-adapter-run.js\";\nimport {\n\tdataIssue,\n\tforEachDepBatch,\n\tisRecord,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeProviderGraphVisibleRecord,\n\tuniqueSourceRefs,\n} from \"./agent-runtime-common.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { ExecutorOutcome, SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterInput,\n\tToolProviderAdapterRunRequested,\n\tToolProviderRunRetryBundle,\n\tToolProviderRunRetryPolicy,\n\tToolProviderRunRetryProposal,\n\tToolProviderRunRetryScheduled,\n\tToolProviderRunRetryStatus,\n\tToolProviderRunRetryStatusState,\n\tToolProviderRunRetryViews,\n} from \"./agent-runtime-types-tool.js\";\nimport type {\n\tScheduledReadinessReady,\n\tScheduledReadinessRequested,\n} from \"./scheduled-readiness.js\";\n\nexport function toolProviderRunRetryProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly inputs: Node<ToolProviderAdapterInput>;\n\t\treadonly outcomes: Node<ExecutorOutcome>;\n\t\treadonly policies?: readonly Node<ToolProviderRunRetryPolicy>[];\n\t\treadonly nowMs?: Node<number>;\n\t\treadonly readiness?: readonly Node<ScheduledReadinessReady>[];\n\t},\n): ToolProviderRunRetryBundle {\n\tconst name = opts.name ?? \"toolProviderRunRetry\";\n\tconst policyDeps = opts.policies ?? [];\n\tconst nowDeps = opts.nowMs === undefined ? [] : [opts.nowMs];\n\tconst readinessDeps = opts.readiness ?? [];\n\tconst outcomeDepIndex = 1 + policyDeps.length;\n\tconst nowDepIndex = outcomeDepIndex + 1;\n\tconst readinessDepStart = nowDepIndex + nowDeps.length;\n\tconst runtime = graph.node<ToolProviderRunRetryFact>(\n\t\t[opts.inputs, ...policyDeps, opts.outcomes, ...nowDeps, ...readinessDeps],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ToolProviderRunRetryProjectorState>() ?? initialRetryState();\n\t\t\tstate.usesSharedReadiness = readinessDeps.length > 0;\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst input = raw as ToolProviderAdapterInput;\n\t\t\t\tstate.inputsById.set(input.adapterInputId, input);\n\t\t\t\tlet inputIds = state.inputIdsByRequest.get(input.requestId);\n\t\t\t\tif (inputIds === undefined) {\n\t\t\t\t\tinputIds = new Set();\n\t\t\t\t\tstate.inputIdsByRequest.set(input.requestId, inputIds);\n\t\t\t\t}\n\t\t\t\tinputIds.add(input.adapterInputId);\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, 1, policyDeps.length, (raw) => {\n\t\t\t\tconst policy = sanitizeToolProviderRunRetryPolicy(raw as ToolProviderRunRetryPolicy);\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tfor (const rawNow of depBatch(ctx, nowDepIndex) ?? []) {\n\t\t\t\tif (typeof rawNow === \"number\" && Number.isFinite(rawNow)) state.nowMs = rawNow;\n\t\t\t}\n\t\t\tforEachDepBatch(ctx, readinessDepStart, readinessDeps.length, (raw) => {\n\t\t\t\tconst ready = sanitizeRetryReadinessReady(raw);\n\t\t\t\tif (!ready.ok) {\n\t\t\t\t\temitIssue(ctx, state, ready.issue);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstate.readinessBySchedule.set(ready.scheduleId, ready);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, outcomeDepIndex) ?? []) {\n\t\t\t\tretainOutcome(state, raw as ExecutorOutcome);\n\t\t\t}\n\t\t\tevaluateOutcomes(ctx, state);\n\t\t\tprocessDueRetries(ctx, state);\n\t\t\tctx.down([[\"DATA\", { kind: \"views\", views: buildRetryViews(state) }]]);\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"toolProviderRunRetryProjector\", partial: true },\n\t);\n\treturn {\n\t\tproposals: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/proposals`,\n\t\t\t\"toolProviderRunRetryProposals\",\n\t\t\t(fact) => (fact.kind === \"proposal\" ? fact.proposal : undefined),\n\t\t),\n\t\tscheduled: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/scheduled`,\n\t\t\t\"toolProviderRunRetryScheduled\",\n\t\t\t(fact) => (fact.kind === \"scheduled\" ? fact.scheduled : undefined),\n\t\t),\n\t\treadinessSchedules: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/readinessSchedules`,\n\t\t\t\"toolProviderRunRetryReadinessSchedules\",\n\t\t\t(fact) => (fact.kind === \"readiness-schedule\" ? fact.schedule : undefined),\n\t\t),\n\t\trunRequests: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/runRequests`,\n\t\t\t\"toolProviderRunRetryRunRequests\",\n\t\t\t(fact) => (fact.kind === \"run-request\" ? fact.request : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"toolProviderRunRetryStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"toolProviderRunRetryIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/audit`,\n\t\t\t\"toolProviderRunRetryAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/views`,\n\t\t\t\"toolProviderRunRetryViews\",\n\t\t\t(fact) => (fact.kind === \"views\" ? fact.views : undefined),\n\t\t),\n\t};\n}\n\ntype ToolProviderRunRetryFact =\n\t| { readonly kind: \"proposal\"; readonly proposal: ToolProviderRunRetryProposal }\n\t| { readonly kind: \"scheduled\"; readonly scheduled: ToolProviderRunRetryScheduled }\n\t| { readonly kind: \"readiness-schedule\"; readonly schedule: ScheduledReadinessRequested }\n\t| { readonly kind: \"run-request\"; readonly request: ToolProviderAdapterRunRequested }\n\t| { readonly kind: \"status\"; readonly status: ToolProviderRunRetryStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord }\n\t| { readonly kind: \"views\"; readonly views: ToolProviderRunRetryViews };\n\ninterface ToolProviderRunRetryProjectorState {\n\tinputIdsByRequest: Map<string, Set<string>>;\n\tinputsById: Map<string, ToolProviderAdapterInput>;\n\tpolicies: Map<string, ToolProviderRunRetryPolicy>;\n\toutcomesById: Map<string, ExecutorOutcome>;\n\tproposalsByOutcome: Map<string, ToolProviderRunRetryProposal>;\n\tscheduledByOutcome: Map<string, ToolProviderRunRetryScheduled>;\n\treadinessSchedulesByOutcome: Map<string, ScheduledReadinessRequested>;\n\treadinessBySchedule: Map<string, ScheduledReadinessReady>;\n\tnextRequestsByOutcome: Map<string, ToolProviderAdapterRunRequested>;\n\tstatusByOutcome: Map<string, ToolProviderRunRetryStatus>;\n\tproposalKeys: Set<string>;\n\tscheduledKeys: Set<string>;\n\treadinessScheduleKeys: Set<string>;\n\trequestKeys: Set<string>;\n\tstatusKeys: Set<string>;\n\tissueKeys: Set<string>;\n\tauditSeq: number;\n\tnowMs: number | undefined;\n\tusesSharedReadiness: boolean;\n}\n\ninterface RetryPolicyChoice {\n\treadonly policy: ToolProviderRunRetryPolicy;\n\treadonly score: number;\n}\n\nfunction initialRetryState(): ToolProviderRunRetryProjectorState {\n\treturn {\n\t\tinputIdsByRequest: new Map(),\n\t\tinputsById: new Map(),\n\t\tpolicies: new Map(),\n\t\toutcomesById: new Map(),\n\t\tproposalsByOutcome: new Map(),\n\t\tscheduledByOutcome: new Map(),\n\t\treadinessSchedulesByOutcome: new Map(),\n\t\treadinessBySchedule: new Map(),\n\t\tnextRequestsByOutcome: new Map(),\n\t\tstatusByOutcome: new Map(),\n\t\tproposalKeys: new Set(),\n\t\tscheduledKeys: new Set(),\n\t\treadinessScheduleKeys: new Set(),\n\t\trequestKeys: new Set(),\n\t\tstatusKeys: new Set(),\n\t\tissueKeys: new Set(),\n\t\tauditSeq: 0,\n\t\tnowMs: undefined,\n\t\tusesSharedReadiness: false,\n\t};\n}\n\nfunction retainOutcome(state: ToolProviderRunRetryProjectorState, outcome: ExecutorOutcome): void {\n\tif (!state.outcomesById.has(outcome.outcomeId))\n\t\tstate.outcomesById.set(outcome.outcomeId, outcome);\n}\n\nfunction inputForOutcome(\n\tstate: ToolProviderRunRetryProjectorState,\n\toutcome: ExecutorOutcome,\n):\n\t| { readonly ok: true; readonly input: ToolProviderAdapterInput }\n\t| { readonly ok: false; readonly issue: DataIssue } {\n\tif (typeof outcome.inputId === \"string\" && outcome.inputId.length > 0) {\n\t\tconst exactInput = state.inputsById.get(outcome.inputId);\n\t\tif (exactInput !== undefined) return { ok: true, input: exactInput };\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-run-retry-missing-input\",\n\t\t\t\t\"Tool provider run retry requires the retained adapter input identified by the outcome.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: outcome.inputId,\n\t\t\t\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t},\n\t\t\t),\n\t\t};\n\t}\n\tconst inputIds = state.inputIdsByRequest.get(outcome.requestId);\n\tif (inputIds === undefined || inputIds.size === 0) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-run-retry-missing-input\",\n\t\t\t\t\"Tool provider run retry requires a retained adapter input for the outcome request.\",\n\t\t\t\t{ subjectId: outcome.requestId, refs: [ref(\"executor-outcome\", outcome.outcomeId)] },\n\t\t\t),\n\t\t};\n\t}\n\tif (inputIds.size > 1) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-run-retry-ambiguous-input\",\n\t\t\t\t\"Tool provider run retry requires an exact outcome inputId when multiple adapter inputs share a request.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: outcome.requestId,\n\t\t\t\t\trefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\t\t\t\tdetails: { inputIds: [...inputIds].sort() },\n\t\t\t\t},\n\t\t\t),\n\t\t};\n\t}\n\tconst [inputId] = inputIds;\n\tconst input = inputId === undefined ? undefined : state.inputsById.get(inputId);\n\tif (input !== undefined) return { ok: true, input };\n\treturn {\n\t\tok: false,\n\t\tissue: dataIssue(\n\t\t\t\"tool-provider-run-retry-missing-input\",\n\t\t\t\"Tool provider run retry requires a retained adapter input for the outcome request.\",\n\t\t\t{ subjectId: outcome.requestId, refs: [ref(\"executor-outcome\", outcome.outcomeId)] },\n\t\t),\n\t};\n}\n\nfunction evaluateOutcomes(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n): void {\n\tfor (const outcome of state.outcomesById.values()) evaluateOutcome(ctx, state, outcome);\n}\n\nfunction evaluateOutcome(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\toutcome: ExecutorOutcome,\n): void {\n\tconst inputResolution = inputForOutcome(state, outcome);\n\tif (!inputResolution.ok) {\n\t\temitIssue(ctx, state, inputResolution.issue);\n\t\temitStatus(ctx, state, statusForMissingInput(outcome, \"blocked\", [inputResolution.issue]));\n\t\treturn;\n\t}\n\tconst input = inputResolution.input;\n\tif (input.status !== \"ready\") {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-retry-input-not-ready\",\n\t\t\t\"Tool provider run retry requires a ready adapter input.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.adapterInputId,\n\t\t\t\trefs: [\n\t\t\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t\t\t],\n\t\t\t\tdetails: { status: input.status },\n\t\t\t},\n\t\t);\n\t\temitIssue(ctx, state, issue);\n\t\temitStatus(ctx, state, statusForOutcome(outcome, input, \"blocked\", { issues: [issue] }));\n\t\treturn;\n\t}\n\tif (!isRetryableOutcome(outcome)) {\n\t\temitStatus(ctx, state, statusForOutcome(outcome, input, \"not-retryable\"));\n\t\treturn;\n\t}\n\tif (\n\t\tstate.scheduledByOutcome.has(outcome.outcomeId) ||\n\t\tstate.nextRequestsByOutcome.has(outcome.outcomeId)\n\t) {\n\t\treturn;\n\t}\n\tconst choice = chooseRetryPolicy(state, input, outcome);\n\tif (choice === undefined) {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-retry-policy-missing\",\n\t\t\t\"Tool provider run retry requires an explicit retry policy fact.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.adapterInputId,\n\t\t\t\trefs: [\n\t\t\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t\t\t],\n\t\t\t},\n\t\t);\n\t\temitIssue(ctx, state, issue);\n\t\temitStatus(ctx, state, statusForOutcome(outcome, input, \"not-retryable\", { issues: [issue] }));\n\t\treturn;\n\t}\n\tif (!shouldRetry(choice.policy.retryPolicy, outcome.attempt)) {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-retry-exhausted\",\n\t\t\t\"Tool provider run retry policy exhausted available attempts.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.adapterInputId,\n\t\t\t\trefs: retrySourceRefs(input, outcome, choice.policy),\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tdetails: {\n\t\t\t\t\tattempt: outcome.attempt,\n\t\t\t\t\tmaxAttempts: choice.policy.retryPolicy.maxAttempts,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\temitIssue(ctx, state, issue);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\tstatusForOutcome(outcome, input, \"exhausted\", { choice, issues: [issue] }),\n\t\t);\n\t\treturn;\n\t}\n\tconst nextAttempt = outcome.attempt + 1;\n\tconst delayMs = nextRetryDelayMs(choice.policy.retryPolicy, nextAttempt);\n\tif (delayMs === undefined) {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-retry-delay-unavailable\",\n\t\t\t\"Tool provider run retry could not compute a delay for the next attempt.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.adapterInputId,\n\t\t\t\trefs: retrySourceRefs(input, outcome, choice.policy),\n\t\t\t},\n\t\t);\n\t\temitIssue(ctx, state, issue);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\tstatusForOutcome(outcome, input, \"blocked\", { choice, issues: [issue] }),\n\t\t);\n\t\treturn;\n\t}\n\tconst proposal = retryProposal(input, outcome, choice, delayMs);\n\tstate.proposalsByOutcome.set(outcome.outcomeId, proposal);\n\temitProposal(ctx, state, proposal);\n\tif (delayMs <= 0) {\n\t\temitRunRequest(ctx, state, input, proposal, \"immediate\");\n\t\treturn;\n\t}\n\tif (state.nowMs === undefined) {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-run-retry-now-missing\",\n\t\t\t\"Tool provider delayed retry requires a graph-visible nowMs input.\",\n\t\t\t{\n\t\t\t\tsubjectId: input.adapterInputId,\n\t\t\t\trefs: retrySourceRefs(input, outcome, choice.policy),\n\t\t\t},\n\t\t);\n\t\temitIssue(ctx, state, issue);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\tstatusForOutcome(outcome, input, \"blocked\", { choice, proposal, issues: [issue], delayMs }),\n\t\t);\n\t\treturn;\n\t}\n\tconst scheduled = retryScheduled(input, outcome, proposal, state.nowMs + delayMs, delayMs);\n\tstate.scheduledByOutcome.set(outcome.outcomeId, scheduled);\n\temitScheduled(ctx, state, scheduled);\n\tconst readinessSchedule = retryReadinessSchedule(input, outcome, proposal, scheduled);\n\tstate.readinessSchedulesByOutcome.set(outcome.outcomeId, readinessSchedule);\n\temitReadinessSchedule(ctx, state, readinessSchedule);\n\temitStatus(\n\t\tctx,\n\t\tstate,\n\t\tstatusForOutcome(outcome, input, \"scheduled\", {\n\t\t\tchoice,\n\t\t\tproposal,\n\t\t\tdelayMs,\n\t\t\tretryAtMs: scheduled.retryAtMs,\n\t\t}),\n\t);\n}\n\nfunction processDueRetries(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n): void {\n\tfor (const [outcomeId, scheduled] of state.scheduledByOutcome) {\n\t\tconst readiness = state.readinessBySchedule.get(\n\t\t\tscheduled.readinessScheduleId ?? scheduled.scheduleId,\n\t\t);\n\t\tconst readinessSchedule = state.readinessSchedulesByOutcome.get(outcomeId);\n\t\tconst readyByReadiness =\n\t\t\treadiness !== undefined &&\n\t\t\treadiness.readyAtMs === scheduled.retryAtMs &&\n\t\t\treadiness.nowMs >= scheduled.retryAtMs &&\n\t\t\treadinessSchedule !== undefined &&\n\t\t\treadinessMatchesSchedule(readiness, readinessSchedule);\n\t\tif (readiness !== undefined && !readyByReadiness) {\n\t\t\temitIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\tdataIssue(\n\t\t\t\t\t\"tool-provider-run-retry-readiness-mismatch\",\n\t\t\t\t\t\"Tool provider delayed retry readiness fact does not match the scheduled retry eligibility.\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsubjectId: scheduled.scheduleId,\n\t\t\t\t\t\trefs: sanitizeAdapterInputSourceRefs([\n\t\t\t\t\t\t\tref(\"tool-provider-run-retry-scheduled\", scheduled.scheduleId),\n\t\t\t\t\t\t\tref(\"scheduled-readiness-ready\", readiness.scheduleId),\n\t\t\t\t\t\t]),\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\tretryAtMs: scheduled.retryAtMs,\n\t\t\t\t\t\t\treadyAtMs: readiness.readyAtMs,\n\t\t\t\t\t\t\tnowMs: readiness.nowMs,\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\tconst readyByClock =\n\t\t\t!state.usesSharedReadiness && state.nowMs !== undefined && scheduled.retryAtMs <= state.nowMs;\n\t\tif (!readyByReadiness && !readyByClock) continue;\n\t\tif (state.nextRequestsByOutcome.has(outcomeId)) continue;\n\t\tconst proposal = state.proposalsByOutcome.get(outcomeId);\n\t\tif (proposal === undefined) continue;\n\t\tconst input = state.inputsById.get(proposal.adapterInputId);\n\t\tif (input === undefined) continue;\n\t\temitRunRequest(ctx, state, input, proposal, \"scheduled\", readiness);\n\t}\n}\n\nfunction sanitizeRetryReadinessReady(\n\traw: unknown,\n):\n\t| ({ readonly ok: true } & ScheduledReadinessReady)\n\t| { readonly ok: false; readonly issue: DataIssue } {\n\tif (\n\t\t!isRecord(raw) ||\n\t\traw.kind !== \"scheduled-readiness-ready\" ||\n\t\ttypeof raw.scheduleId !== \"string\" ||\n\t\traw.scheduleId.length === 0 ||\n\t\ttypeof raw.readyAtMs !== \"number\" ||\n\t\t!Number.isFinite(raw.readyAtMs) ||\n\t\ttypeof raw.nowMs !== \"number\" ||\n\t\t!Number.isFinite(raw.nowMs) ||\n\t\t!Array.isArray(raw.subjectRefs) ||\n\t\t(raw.sourceRefs !== undefined && !Array.isArray(raw.sourceRefs))\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"tool-provider-run-retry-readiness-malformed\",\n\t\t\t\t\"Tool provider delayed retry readiness fact must be graph-visible scheduled readiness material.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId:\n\t\t\t\t\t\tisRecord(raw) && typeof raw.scheduleId === \"string\"\n\t\t\t\t\t\t\t? raw.scheduleId\n\t\t\t\t\t\t\t: \"unknown-scheduled-readiness\",\n\t\t\t\t},\n\t\t\t),\n\t\t};\n\t}\n\treturn Object.freeze({\n\t\tok: true,\n\t\tkind: \"scheduled-readiness-ready\",\n\t\tscheduleId: raw.scheduleId,\n\t\tsubjectRefs: sanitizeAdapterInputSourceRefs(\n\t\t\traw.subjectRefs.flatMap((entry) => {\n\t\t\t\tconst sourceRef = sourceRefOrUndefined(entry);\n\t\t\t\treturn sourceRef === undefined ? [] : [sourceRef];\n\t\t\t}),\n\t\t),\n\t\treadyAtMs: raw.readyAtMs,\n\t\t...(typeof raw.deadlineMs === \"number\" && Number.isFinite(raw.deadlineMs)\n\t\t\t? { deadlineMs: raw.deadlineMs }\n\t\t\t: {}),\n\t\tnowMs: raw.nowMs,\n\t\t...(raw.sourceRefs === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tsourceRefs: sanitizeAdapterInputSourceRefs(\n\t\t\t\t\t\traw.sourceRefs.flatMap((entry) => {\n\t\t\t\t\t\t\tconst sourceRef = sourceRefOrUndefined(entry);\n\t\t\t\t\t\t\treturn sourceRef === undefined ? [] : [sourceRef];\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\t...(isRecord(raw.metadata)\n\t\t\t? { metadata: sanitizeProviderGraphVisibleRecord(raw.metadata) }\n\t\t\t: {}),\n\t});\n}\n\nfunction readinessMatchesSchedule(\n\treadiness: ScheduledReadinessReady,\n\tschedule: ScheduledReadinessRequested,\n): boolean {\n\tconst subjectRefs = sanitizeAdapterInputSourceRefs(schedule.subjectRefs);\n\tconst readySubjectRefs = sanitizeAdapterInputSourceRefs(readiness.subjectRefs);\n\tif (!sourceRefsContainAll(readySubjectRefs, subjectRefs)) return false;\n\treturn sourceRefsContainAll(sanitizeAdapterInputSourceRefs(readiness.sourceRefs ?? []), [\n\t\tref(\"scheduled-readiness\", schedule.scheduleId),\n\t\t...(schedule.sourceRefs ?? []),\n\t]);\n}\n\nfunction sourceRefsContainAll(\n\tactual: readonly SourceRef[],\n\texpected: readonly SourceRef[],\n): boolean {\n\tconst actualKeys = new Set(actual.map(sourceRefKey));\n\treturn expected.every((sourceRef) => actualKeys.has(sourceRefKey(sourceRef)));\n}\n\nfunction sourceRefKey(sourceRef: SourceRef): string {\n\treturn `${sourceRef.kind}:${sourceRef.id}`;\n}\n\nfunction sourceRefOrUndefined(value: unknown): SourceRef | undefined {\n\tif (!isRecord(value)) return undefined;\n\tif (typeof value.kind !== \"string\" || value.kind.length === 0) return undefined;\n\tif (typeof value.id !== \"string\" || value.id.length === 0) return undefined;\n\treturn isRecord(value.metadata)\n\t\t? { kind: value.kind, id: value.id, metadata: value.metadata }\n\t\t: { kind: value.kind, id: value.id };\n}\n\nfunction sanitizeToolProviderRunRetryPolicy(\n\traw: ToolProviderRunRetryPolicy,\n): ToolProviderRunRetryPolicy {\n\tconst metadata = sanitizeProviderGraphVisibleRecord(raw.metadata);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-policy\",\n\t\tpolicyId: raw.policyId,\n\t\tretryPolicy: sanitizeRetryPolicy(raw.retryPolicy),\n\t\t...(raw.runId === undefined ? {} : { runId: raw.runId }),\n\t\t...(raw.requestId === undefined ? {} : { requestId: raw.requestId }),\n\t\t...(raw.adapterInputId === undefined ? {} : { adapterInputId: raw.adapterInputId }),\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs(raw.sourceRefs ?? []),\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies ToolProviderRunRetryPolicy);\n}\n\nfunction sanitizeRetryPolicy(policy: RetryPolicy): RetryPolicy {\n\tif (!Number.isInteger(policy.maxAttempts) || policy.maxAttempts <= 0) {\n\t\treturn Object.freeze({ maxAttempts: 1, backoff: { kind: \"none\" as const } });\n\t}\n\treturn Object.freeze(policy);\n}\n\nfunction chooseRetryPolicy(\n\tstate: ToolProviderRunRetryProjectorState,\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n): RetryPolicyChoice | undefined {\n\tlet best: RetryPolicyChoice | undefined;\n\tfor (const policy of state.policies.values()) {\n\t\tconst score = retryPolicyScore(policy, input, outcome);\n\t\tif (score === undefined) continue;\n\t\tif (best === undefined || score > best.score) best = { policy, score };\n\t}\n\treturn best;\n}\n\nfunction retryPolicyScore(\n\tpolicy: ToolProviderRunRetryPolicy,\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n): number | undefined {\n\tlet score = 0;\n\tif (policy.adapterInputId !== undefined) {\n\t\tif (policy.adapterInputId !== input.adapterInputId) return undefined;\n\t\tscore += 8;\n\t}\n\tif (policy.requestId !== undefined) {\n\t\tif (policy.requestId !== outcome.requestId) return undefined;\n\t\tscore += 4;\n\t}\n\tif (policy.runId !== undefined) {\n\t\tif (policy.runId !== outcomeRunId(outcome)) return undefined;\n\t\tscore += 2;\n\t}\n\treturn score;\n}\n\nfunction retryProposal(\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n\tchoice: RetryPolicyChoice,\n\tdelayMs: number,\n): ToolProviderRunRetryProposal {\n\tconst fromRunId = outcomeRunId(outcome);\n\tconst nextAttempt = outcome.attempt + 1;\n\tconst policyRefs = retryPolicyRefs(input, choice.policy);\n\tconst sourceRefs = retrySourceRefs(input, outcome, choice.policy);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-proposal\",\n\t\tproposalId: `${outcome.outcomeId}:retry-proposal`,\n\t\toutcomeId: outcome.outcomeId,\n\t\tfromRunId,\n\t\tfromRequestId: outcome.requestId,\n\t\tfromAttempt: outcome.attempt,\n\t\tnextAttempt,\n\t\tnextRunId: `${fromRunId}:retry-${nextAttempt}`,\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\tpolicyId: choice.policy.policyId,\n\t\tpolicyRefs,\n\t\tmaxAttempts: choice.policy.retryPolicy.maxAttempts,\n\t\tnextDelayMs: delayMs,\n\t\tsourceRefs,\n\t\tmetadata: sanitizeProviderGraphVisibleRecord({ policyScore: choice.score }),\n\t} satisfies ToolProviderRunRetryProposal);\n}\n\nfunction retryScheduled(\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n\tproposal: ToolProviderRunRetryProposal,\n\tretryAtMs: number,\n\tdelayMs: number,\n): ToolProviderRunRetryScheduled {\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-scheduled\",\n\t\tscheduleId: `${proposal.proposalId}:scheduled`,\n\t\treadinessScheduleId: `${proposal.proposalId}:scheduled-readiness`,\n\t\toutcomeId: outcome.outcomeId,\n\t\tproposalId: proposal.proposalId,\n\t\tfromRunId: proposal.fromRunId,\n\t\tnextRunId: proposal.nextRunId,\n\t\tnextAttempt: proposal.nextAttempt,\n\t\tretryAtMs,\n\t\tretryAfterMs: delayMs,\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\tref(\"tool-provider-run-retry-proposal\", proposal.proposalId),\n\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t]),\n\t} satisfies ToolProviderRunRetryScheduled);\n}\n\nfunction retryReadinessSchedule(\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n\tproposal: ToolProviderRunRetryProposal,\n\tscheduled: ToolProviderRunRetryScheduled,\n): ScheduledReadinessRequested {\n\treturn Object.freeze({\n\t\tkind: \"scheduled-readiness-requested\",\n\t\tscheduleId: scheduled.readinessScheduleId ?? scheduled.scheduleId,\n\t\tsubjectRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"tool-provider-run-retry-proposal\", proposal.proposalId),\n\t\t\tref(\"tool-provider-run-retry-scheduled\", scheduled.scheduleId),\n\t\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t]),\n\t\treadyAtMs: scheduled.retryAtMs,\n\t\treason: \"tool-provider-retry\",\n\t\tpolicyRefs: proposal.policyRefs,\n\t\tsourceRefs: sanitizeAdapterInputSourceRefs([\n\t\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\t\tref(\"tool-provider-run-retry-proposal\", proposal.proposalId),\n\t\t\tref(\"tool-provider-run-retry-scheduled\", scheduled.scheduleId),\n\t\t\t...(scheduled.sourceRefs ?? []),\n\t\t]),\n\t\tmetadata: sanitizeProviderGraphVisibleRecord({\n\t\t\toutcomeId: outcome.outcomeId,\n\t\t\tnextRunId: proposal.nextRunId,\n\t\t\tnextAttempt: proposal.nextAttempt,\n\t\t\tretryAfterMs: scheduled.retryAfterMs,\n\t\t}),\n\t} satisfies ScheduledReadinessRequested);\n}\n\nfunction emitRunRequest(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tinput: ToolProviderAdapterInput,\n\tproposal: ToolProviderRunRetryProposal,\n\tmode: \"immediate\" | \"scheduled\",\n\treadiness?: ScheduledReadinessReady,\n): void {\n\tconst key = `request:${proposal.outcomeId}:${proposal.nextRunId}`;\n\tif (state.requestKeys.has(key)) return;\n\tstate.requestKeys.add(key);\n\tconst request = requestToolProviderAdapterRun(input, {\n\t\trunId: proposal.nextRunId,\n\t\tattempt: proposal.nextAttempt,\n\t\treason: \"retry\",\n\t\tretryOfOutcomeId: proposal.outcomeId,\n\t\tpolicyRefs: proposal.policyRefs,\n\t\tsourceRefs: uniqueSourceRefs([\n\t\t\t...(proposal.sourceRefs ?? []),\n\t\t\tref(\"tool-provider-run-retry-proposal\", proposal.proposalId),\n\t\t\t...(mode === \"scheduled\"\n\t\t\t\t? [ref(\"tool-provider-run-retry-scheduled\", `${proposal.proposalId}:scheduled`)]\n\t\t\t\t: []),\n\t\t\t...(readiness === undefined\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\tref(\"scheduled-readiness-ready\", readiness.scheduleId),\n\t\t\t\t\t\t...(readiness.sourceRefs ?? []),\n\t\t\t\t\t]),\n\t\t]),\n\t\tmetadata: {\n\t\t\tretryMode: mode,\n\t\t\tretryProposalId: proposal.proposalId,\n\t\t\tretryOfOutcomeId: proposal.outcomeId,\n\t\t\t...(readiness === undefined ? {} : { readinessScheduleId: readiness.scheduleId }),\n\t\t},\n\t});\n\tstate.nextRequestsByOutcome.set(proposal.outcomeId, request);\n\temitStatus(ctx, state, statusForProposal(input, proposal, \"ready\"));\n\temitAudit(ctx, state, \"tool-provider-run-retry-run-requested\", {\n\t\tsubjectId: request.requestId,\n\t\tsourceRefs: request.sourceRefs,\n\t\tmetadata: {\n\t\t\trunId: request.runId,\n\t\t\tadapterInputId: request.adapterInputId,\n\t\t\tattempt: request.attempt,\n\t\t\tretryOfOutcomeId: request.retryOfOutcomeId,\n\t\t\tretryMode: mode,\n\t\t},\n\t});\n\tctx.down([[\"DATA\", { kind: \"run-request\", request }]]);\n}\n\nfunction emitProposal(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tproposal: ToolProviderRunRetryProposal,\n): void {\n\tconst key = `proposal:${proposal.proposalId}`;\n\tif (state.proposalKeys.has(key)) return;\n\tstate.proposalKeys.add(key);\n\temitAudit(ctx, state, \"tool-provider-run-retry-proposed\", {\n\t\tsubjectId: proposal.requestId,\n\t\tsourceRefs: proposal.sourceRefs,\n\t\tmetadata: {\n\t\t\tproposalId: proposal.proposalId,\n\t\t\toutcomeId: proposal.outcomeId,\n\t\t\tnextAttempt: proposal.nextAttempt,\n\t\t\tnextDelayMs: proposal.nextDelayMs,\n\t\t},\n\t});\n\tctx.down([[\"DATA\", { kind: \"proposal\", proposal }]]);\n}\n\nfunction emitScheduled(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tscheduled: ToolProviderRunRetryScheduled,\n): void {\n\tconst key = `scheduled:${scheduled.scheduleId}`;\n\tif (state.scheduledKeys.has(key)) return;\n\tstate.scheduledKeys.add(key);\n\temitAudit(ctx, state, \"tool-provider-run-retry-scheduled\", {\n\t\tsourceRefs: scheduled.sourceRefs,\n\t\tmetadata: {\n\t\t\tscheduleId: scheduled.scheduleId,\n\t\t\toutcomeId: scheduled.outcomeId,\n\t\t\tnextAttempt: scheduled.nextAttempt,\n\t\t\tretryAtMs: scheduled.retryAtMs,\n\t\t},\n\t});\n\tctx.down([[\"DATA\", { kind: \"scheduled\", scheduled }]]);\n}\n\nfunction emitReadinessSchedule(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tschedule: ScheduledReadinessRequested,\n): void {\n\tconst key = `readiness-schedule:${schedule.scheduleId}`;\n\tif (state.readinessScheduleKeys.has(key)) return;\n\tstate.readinessScheduleKeys.add(key);\n\temitAudit(ctx, state, \"tool-provider-run-retry-readiness-scheduled\", {\n\t\tsourceRefs: schedule.sourceRefs,\n\t\tmetadata: {\n\t\t\tscheduleId: schedule.scheduleId,\n\t\t\treadyAtMs: schedule.readyAtMs,\n\t\t},\n\t});\n\tctx.down([[\"DATA\", { kind: \"readiness-schedule\", schedule }]]);\n}\n\nfunction emitStatus(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tstatus: ToolProviderRunRetryStatus,\n): void {\n\tconst key = `${status.outcomeId}:${status.state}:${status.nextAttempt ?? \"\"}:${status.nextRetryAtMs ?? \"\"}:${(status.issueCodes ?? []).join(\",\")}`;\n\tif (state.statusKeys.has(key)) return;\n\tstate.statusKeys.add(key);\n\tstate.statusByOutcome.set(status.outcomeId, status);\n\tctx.down([[\"DATA\", { kind: \"status\", status }]]);\n}\n\nfunction emitIssue(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tissue: DataIssue,\n): void {\n\tconst sanitized = sanitizeAdapterInputIssue(issue);\n\tconst key = `${sanitized.code}:${sanitized.subjectId ?? \"\"}:${JSON.stringify(sanitized.details ?? {})}`;\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"issue\", issue: sanitized }]]);\n}\n\nfunction emitAudit(\n\tctx: { down: (msgs: readonly [\"DATA\", ToolProviderRunRetryFact][]) => void },\n\tstate: ToolProviderRunRetryProjectorState,\n\tkind: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\treadonly metadata?: Record<string, unknown>;\n\t} = {},\n): void {\n\tstate.auditSeq += 1;\n\tconst metadata = sanitizeProviderGraphVisibleRecord(opts.metadata);\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: Object.freeze({\n\t\t\t\t\tid: `tool-provider-run-retry-audit-${state.auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\t...(opts.subjectId === undefined ? {} : { subjectId: opts.subjectId }),\n\t\t\t\t\t...(opts.sourceRefs === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { sourceRefs: sanitizeAdapterInputSourceRefs(opts.sourceRefs) }),\n\t\t\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t\t\t} satisfies AgentRuntimeAuditRecord),\n\t\t\t},\n\t\t],\n\t]);\n}\n\nfunction statusForOutcome(\n\toutcome: ExecutorOutcome,\n\tinput: ToolProviderAdapterInput,\n\tstate: ToolProviderRunRetryStatusState,\n\topts: {\n\t\treadonly choice?: RetryPolicyChoice;\n\t\treadonly proposal?: ToolProviderRunRetryProposal;\n\t\treadonly issues?: readonly DataIssue[];\n\t\treadonly delayMs?: number;\n\t\treadonly retryAtMs?: number;\n\t} = {},\n): ToolProviderRunRetryStatus {\n\tconst proposal = opts.proposal;\n\tconst nextAttempt =\n\t\tproposal?.nextAttempt ?? (opts.choice === undefined ? undefined : outcome.attempt + 1);\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-status\",\n\t\tstatusId: `${outcome.outcomeId}:retry-status:${state}`,\n\t\toutcomeId: outcome.outcomeId,\n\t\tproposalId: proposal?.proposalId ?? `${outcome.outcomeId}:retry-proposal`,\n\t\tfromRunId: outcomeRunId(outcome),\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\t...(proposal?.nextRunId === undefined ? {} : { nextRunId: proposal.nextRunId }),\n\t\t...(nextAttempt === undefined ? {} : { nextAttempt }),\n\t\t...(opts.retryAtMs === undefined ? {} : { nextRetryAtMs: opts.retryAtMs }),\n\t\tstate,\n\t\tsourceRefs: retrySourceRefs(input, outcome, opts.choice?.policy),\n\t\t...(opts.issues === undefined || opts.issues.length === 0\n\t\t\t? {}\n\t\t\t: { issueCodes: Object.freeze(opts.issues.map((issue) => issue.code)) }),\n\t\t...optionalMetadata({\n\t\t\t...(opts.delayMs === undefined ? {} : { delayMs: opts.delayMs }),\n\t\t\t...(opts.choice === undefined\n\t\t\t\t? {}\n\t\t\t\t: { maxAttempts: opts.choice.policy.retryPolicy.maxAttempts }),\n\t\t}),\n\t} satisfies ToolProviderRunRetryStatus);\n}\n\nfunction statusForProposal(\n\tinput: ToolProviderAdapterInput,\n\tproposal: ToolProviderRunRetryProposal,\n\tstate: ToolProviderRunRetryStatusState,\n): ToolProviderRunRetryStatus {\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-status\",\n\t\tstatusId: `${proposal.outcomeId}:retry-status:${state}`,\n\t\toutcomeId: proposal.outcomeId,\n\t\tproposalId: proposal.proposalId,\n\t\tfromRunId: proposal.fromRunId,\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\tnextRunId: proposal.nextRunId,\n\t\tnextAttempt: proposal.nextAttempt,\n\t\tstate,\n\t\tsourceRefs: proposal.sourceRefs,\n\t\t...optionalMetadata({ maxAttempts: proposal.maxAttempts }),\n\t} satisfies ToolProviderRunRetryStatus);\n}\n\nfunction statusForMissingInput(\n\toutcome: ExecutorOutcome,\n\tstate: ToolProviderRunRetryStatusState,\n\tissues: readonly DataIssue[],\n): ToolProviderRunRetryStatus {\n\treturn Object.freeze({\n\t\tkind: \"tool-provider-run-retry-status\",\n\t\tstatusId: `${outcome.outcomeId}:retry-status:${state}`,\n\t\toutcomeId: outcome.outcomeId,\n\t\tproposalId: `${outcome.outcomeId}:retry-proposal`,\n\t\tfromRunId: outcomeRunId(outcome),\n\t\tadapterInputId: outcome.inputId ?? outcome.requestId,\n\t\trequestId: outcome.requestId,\n\t\toperationId: outcome.operationId,\n\t\tstate,\n\t\tsourceRefs: [ref(\"executor-outcome\", outcome.outcomeId)],\n\t\tissueCodes: Object.freeze(issues.map((issue) => issue.code)),\n\t} satisfies ToolProviderRunRetryStatus);\n}\n\nfunction isRetryableOutcome(outcome: ExecutorOutcome): boolean {\n\treturn (outcome.kind === \"failure\" || outcome.kind === \"timeout\") && outcome.retryable === true;\n}\n\nfunction retryPolicyRefs(\n\tinput: ToolProviderAdapterInput,\n\tpolicy: ToolProviderRunRetryPolicy,\n): readonly SourceRef[] {\n\treturn sanitizeAdapterInputSourceRefs([\n\t\tref(\"tool-provider-run-retry-policy\", policy.policyId),\n\t\t...(policy.sourceRefs ?? []),\n\t\t...(input.policyRefs ?? []),\n\t]);\n}\n\nfunction retrySourceRefs(\n\tinput: ToolProviderAdapterInput,\n\toutcome: ExecutorOutcome,\n\tpolicy?: ToolProviderRunRetryPolicy,\n): readonly SourceRef[] {\n\treturn sanitizeAdapterInputSourceRefs([\n\t\tref(\"executor-outcome\", outcome.outcomeId),\n\t\tref(\"tool-provider-adapter-input\", input.adapterInputId),\n\t\t...(outcome.evidenceRefs ?? []),\n\t\t...(input.sourceRefs ?? []),\n\t\t...(policy === undefined ? [] : retryPolicyRefs(input, policy)),\n\t]);\n}\n\nfunction outcomeRunId(outcome: ExecutorOutcome): string {\n\tconst runId = isRecord(outcome.metadata) ? outcome.metadata.runId : undefined;\n\tif (typeof runId === \"string\" && runId.length > 0) return runId;\n\treturn `${outcome.requestId}:attempt-${outcome.attempt}`;\n}\n\nfunction optionalMetadata(value: Record<string, unknown>): {\n\treadonly metadata?: Record<string, unknown>;\n} {\n\tconst metadata = sanitizeProviderGraphVisibleRecord(value);\n\treturn metadata === undefined ? {} : { metadata };\n}\n\nfunction buildRetryViews(state: ToolProviderRunRetryProjectorState): ToolProviderRunRetryViews {\n\treturn Object.freeze({\n\t\tproposalsByOutcome: new Map(state.proposalsByOutcome),\n\t\tscheduledByOutcome: new Map(state.scheduledByOutcome),\n\t\treadinessSchedulesByOutcome: new Map(state.readinessSchedulesByOutcome),\n\t\treadinessBySchedule: new Map(state.readinessBySchedule),\n\t\tnextRunRequestsByOutcome: new Map(state.nextRequestsByOutcome),\n\t\tstatusByOutcome: new Map(state.statusByOutcome),\n\t});\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { AgentNeed, AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\n\nexport interface SourceRef {\n\treadonly kind: string;\n\treadonly id: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestInput<T = unknown> {\n\treadonly inputId: string;\n\treadonly inputKind: string;\n\treadonly dataMode?: \"ref\" | \"summary\" | \"inline\";\n\treadonly ref?: string;\n\treadonly summary?: string;\n\treadonly value?: T;\n\treadonly schemaRef?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunGoal<TInput = unknown> {\n\treadonly kind: string;\n\treadonly summary?: string;\n\treadonly detailRef?: string;\n\treadonly input?: AgentRequestInput<TInput>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunLimits {\n\treadonly maxSteps?: number;\n\treadonly maxRequests?: number;\n\treadonly maxAttemptsPerOperation?: number;\n\treadonly maxPendingRequests?: number;\n\treadonly maxCostUsd?: number;\n\treadonly timeoutMs?: number;\n}\n\nexport interface EffectRun<TInput = unknown> {\n\treadonly kind: \"effect-run\";\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly goal: EffectRunGoal<TInput>;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly limits?: EffectRunLimits;\n\treadonly createdBy?: string;\n\treadonly createdAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface EffectRunOptions<TInput = unknown> {\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly goal: EffectRunGoal<TInput>;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly limits?: EffectRunLimits;\n\treadonly createdBy?: string;\n\treadonly createdAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport function effectRun<TInput = unknown>(opts: EffectRunOptions<TInput>): EffectRun<TInput> {\n\treturn {\n\t\tkind: \"effect-run\",\n\t\teffectRunId: opts.effectRunId,\n\t\tagentRunId: opts.agentRunId,\n\t\tsubjectRefs: opts.subjectRefs,\n\t\tgoal: opts.goal,\n\t\tsourceRefs: opts.sourceRefs,\n\t\tpolicyRefs: opts.policyRefs,\n\t\tlimits: opts.limits,\n\t\tcreatedBy: opts.createdBy,\n\t\tcreatedAtMs: opts.createdAtMs,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nexport type AgentRequestKind = \"context\" | \"prompt\" | \"executor\";\n\nexport interface AgentRequestProposal<TPayload = unknown> {\n\treadonly kind: \"proposal\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly parentRequestId?: string;\n\treadonly sourceDecisionId?: string;\n\treadonly requestKind: AgentRequestKind;\n\treadonly required?: boolean;\n\treadonly subjectId?: string;\n\treadonly input?: AgentRequestInput<TPayload>;\n\treadonly payload?: TPayload;\n\treadonly reason?: string;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestAdmitted {\n\treadonly kind: \"admitted\";\n\treadonly proposalId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly admittedAtMs?: number;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestRejected {\n\treadonly kind: \"rejected\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly issue: DataIssue;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestDeferred {\n\treadonly kind: \"deferred\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly reason?: string;\n\treadonly untilRef?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestMerged {\n\treadonly kind: \"merged\";\n\treadonly proposalId: string;\n\treadonly effectRunId: string;\n\treadonly targetRequestId: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentRequestIssued<TPayload = unknown> {\n\treadonly kind: \"issued\";\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly effectRunId: string;\n\treadonly agentRunId?: string;\n\treadonly proposalId?: string;\n\treadonly parentRequestId?: string;\n\treadonly requestKind: AgentRequestKind;\n\treadonly required: boolean;\n\treadonly input?: AgentRequestInput<TPayload>;\n\treadonly payload?: TPayload;\n\treadonly issuedAtMs?: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type AgentRequestStatus =\n\t| \"proposed\"\n\t| \"admitted\"\n\t| \"rejected\"\n\t| \"deferred\"\n\t| \"merged\"\n\t| \"issued\"\n\t| \"awaiting-context\"\n\t| \"awaiting-prompt\"\n\t| \"awaiting-route\"\n\t| \"awaiting-provider\"\n\t| \"in-flight\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"blocked\"\n\t| \"canceled\"\n\t| \"timeout\"\n\t| \"waived\"\n\t| \"retry-exhausted\";\n\nexport interface AgentRequestStatusChanged {\n\treadonly kind: \"status\";\n\treadonly requestId: string;\n\treadonly operationId?: string;\n\treadonly effectRunId: string;\n\treadonly status: AgentRequestStatus;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type AgentRequestFact<TPayload = unknown> =\n\t| AgentRequestProposal<TPayload>\n\t| AgentRequestAdmitted\n\t| AgentRequestRejected\n\t| AgentRequestDeferred\n\t| AgentRequestMerged\n\t| AgentRequestIssued<TPayload>\n\t| AgentRequestStatusChanged;\n\nexport interface AgentRequestViews {\n\treadonly requestsById: ReadonlyMap<string, AgentRequestIssued>;\n\treadonly requestsByEffectRun: ReadonlyMap<string, readonly string[]>;\n\treadonly statusByRequest: ReadonlyMap<string, AgentRequestStatusChanged>;\n\treadonly pending: readonly AgentRequestIssued[];\n\treadonly awaitingProvider: readonly AgentRequestIssued[];\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface AgentRequestLedgerBundle {\n\treadonly views: Node<AgentRequestViews>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n}\n\nexport interface ExecutorProfile {\n\treadonly profileId: string;\n\treadonly executorId: string;\n\treadonly kind: \"llm\" | \"tool\" | \"human\" | \"agent\";\n\treadonly acceptedInputKinds?: readonly string[];\n\treadonly acceptedSchemaRefs?: readonly string[];\n\treadonly acceptedResultKinds?: readonly string[];\n\treadonly capabilities?: Record<string, unknown>;\n\treadonly limits?: Record<string, number>;\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutorRoute {\n\treadonly kind: \"executor-route\";\n\treadonly routeId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly inputId?: string;\n\treadonly inputKind?: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n\treadonly allowedParams?: Record<string, unknown>;\n\treadonly reason?: string;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ExecutorOutcomeStatus = \"result\" | \"failure\" | \"canceled\" | \"timeout\" | \"blocked\";\n\nexport interface ExecutorUsage {\n\treadonly inputTokens?: number;\n\treadonly outputTokens?: number;\n\treadonly cacheHitTokens?: number;\n\treadonly cacheMissTokens?: number;\n\treadonly cacheWriteTokens?: number;\n\treadonly cacheMode?: string;\n\treadonly costUsd?: number;\n\treadonly latencyMs?: number;\n}\n\nexport interface SizeCapacityEvidence {\n\treadonly kind: \"size-capacity-evidence\";\n\treadonly unit: string;\n\treadonly quantity: number;\n\treadonly measurementSource: string;\n\treadonly estimated?: boolean;\n\treadonly encoding?: string;\n\treadonly mediaType?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly refs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly sensitivity?: readonly string[];\n\treadonly redaction?: Record<string, unknown>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutorOutcomeBase {\n\treadonly kind: ExecutorOutcomeStatus;\n\treadonly outcomeId: string;\n\treadonly requestId: string;\n\treadonly operationId: string;\n\treadonly routeId: string;\n\treadonly executorId: string;\n\treadonly profileId: string;\n\treadonly attempt: number;\n\treadonly inputId?: string;\n\treadonly inputKind?: string;\n\treadonly occurredAtMs?: number;\n\treadonly evidenceRefs?: readonly SourceRef[];\n\treadonly issues?: readonly DataIssue[];\n\treadonly usage?: ExecutorUsage;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface AgentOutputEnvelope<T = unknown> {\n\treadonly kind: string;\n\treadonly value?: T;\n\treadonly refs?: readonly SourceRef[];\n\treadonly summary?: string;\n\treadonly artifacts?: readonly ExecutorArtifactMaterial[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutorArtifactMaterial<T = unknown> {\n\treadonly kind: string;\n\treadonly format?: string;\n\treadonly schemaRef?: string;\n\treadonly schemaKind?: string;\n\treadonly mimeType?: string;\n\treadonly mediaType?: string;\n\treadonly filename?: string;\n\treadonly byteLength?: number;\n\treadonly digest?: string;\n\treadonly encoding?: string;\n\treadonly dataMode: \"inline\" | \"summary\" | \"ref\" | (string & {});\n\treadonly summary?: string;\n\treadonly value?: T;\n\treadonly ref?: SourceRef;\n\treadonly refs?: readonly SourceRef[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly sizeEvidence?: readonly SizeCapacityEvidence[];\n\treadonly sensitivity?: readonly string[];\n\treadonly redaction?: Record<string, unknown>;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ExecutorOutcome<T = unknown> =\n\t| (ExecutorOutcomeBase & { readonly kind: \"result\"; readonly result: AgentOutputEnvelope<T> })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"failure\";\n\t\t\treadonly error: DataIssue;\n\t\t\treadonly retryable?: boolean;\n\t })\n\t| (ExecutorOutcomeBase & { readonly kind: \"canceled\"; readonly reason?: string })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"timeout\";\n\t\t\treadonly timeoutMs?: number;\n\t\t\treadonly retryable?: boolean;\n\t })\n\t| (ExecutorOutcomeBase & {\n\t\t\treadonly kind: \"blocked\";\n\t\t\treadonly needs: readonly AgentNeed[];\n\t });\n","export type CloneProcessStateResult<TState> =\n\t| { readonly ok: true; readonly value: TState }\n\t| { readonly ok: false; readonly message: string };\n\nexport function cloneProcessState<TState>(state: TState): CloneProcessStateResult<TState> {\n\tif (typeof state !== \"object\" || state === null) return { ok: true, value: state };\n\ttry {\n\t\tif (typeof globalThis.structuredClone === \"function\") {\n\t\t\treturn { ok: true, value: globalThis.structuredClone(state) as TState };\n\t\t}\n\t\treturn { ok: true, value: JSON.parse(JSON.stringify(state)) as TState };\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: `processBundle: state must be cloneable before reducer execution (${errorMessage(error)})`,\n\t\t};\n\t}\n}\n\nexport function readTimestampMs(now: () => number): number | string {\n\ttry {\n\t\tconst timestampMs = now();\n\t\tif (!Number.isFinite(timestampMs)) return \"processBundle: now() must return a finite number\";\n\t\treturn timestampMs;\n\t} catch (error) {\n\t\treturn errorMessage(error);\n\t}\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 isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Graph-visible ProcessBundle orchestration helpers (D136/D156).\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport type { Graph, TopologyGroup } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type {\n\tProcessAuditRecord,\n\tProcessBundle,\n\tProcessBundleOptions,\n\tProcessCommand,\n\tProcessCursor,\n\tProcessEffectCommandPayload,\n\tProcessEffectCommandType,\n\tProcessEffectOutcome,\n\tProcessEffectRequest,\n\tProcessEffectRequestDraft,\n\tProcessEffectRunnerBundle,\n\tProcessEffectRunnerError,\n\tProcessEffectRunnerOptions,\n\tProcessEffectRunnerStatus,\n\tProcessError,\n\tProcessErrorCode,\n\tProcessEvent,\n\tProcessEventDraft,\n\tProcessReducer,\n\tProcessReduction,\n\tProcessStatus,\n} from \"./process-types.js\";\nimport {\n\tcloneProcessState,\n\terrorMessage,\n\tisObjectRecord,\n\treadTimestampMs,\n\trethrowGraphRuntimeInvariant,\n} from \"./process-utils.js\";\n\nexport type {\n\tProcessAuditRecord,\n\tProcessBundle,\n\tProcessBundleOptions,\n\tProcessCommand,\n\tProcessCursor,\n\tProcessEffectCommandPayload,\n\tProcessEffectCommandType,\n\tProcessEffectOutcome,\n\tProcessEffectRequest,\n\tProcessEffectRequestDraft,\n\tProcessEffectRunnerBundle,\n\tProcessEffectRunnerError,\n\tProcessEffectRunnerOptions,\n\tProcessEffectRunnerStatus,\n\tProcessError,\n\tProcessErrorCode,\n\tProcessEvent,\n\tProcessEventDraft,\n\tProcessReducer,\n\tProcessReduction,\n\tProcessStatus,\n} from \"./process-types.js\";\n\ntype ProcessRuntimeFact<TState = unknown, TEvent = unknown, TEffect = unknown> =\n\t| { readonly kind: \"state\"; readonly state: TState; readonly cursor: ProcessCursor }\n\t| { readonly kind: \"event\"; readonly event: ProcessEvent<TEvent> }\n\t| { readonly kind: \"effect-request\"; readonly effect: ProcessEffectRequest<TEffect> }\n\t| { readonly kind: \"status\"; readonly status: ProcessStatus }\n\t| { readonly kind: \"error\"; readonly error: ProcessError }\n\t| { readonly kind: \"audit\"; readonly audit: ProcessAuditRecord }\n\t| { readonly kind: \"cursor\"; readonly cursor: ProcessCursor };\n\ntype ProcessEffectRunnerFact<TResult = unknown> =\n\t| { readonly kind: \"outcome\"; readonly outcome: ProcessEffectOutcome<TResult> }\n\t| {\n\t\t\treadonly kind: \"command\";\n\t\t\treadonly command: ProcessCommand<ProcessEffectCommandPayload<TResult>>;\n\t }\n\t| { readonly kind: \"error\"; readonly error: ProcessEffectRunnerError };\n\ninterface AttachedProcessCommandSources<TCommand> {\n\tsources: Node<ProcessCommand<TCommand>>[];\n}\n\nconst processCommandSources = new WeakMap<\n\tProcessBundle<unknown, unknown, unknown, unknown>,\n\tAttachedProcessCommandSources<unknown>\n>();\n\n/**\n * Build a D136 ProcessBundle from graph-visible command facts and a reducer.\n *\n * The bundle retains its runtime/projection nodes until `release()` is called.\n * Reducer and validation failures are emitted as DATA error/status/audit facts;\n * they do not mint protocol ERROR messages or own restore/hydration behavior.\n */\nexport function processBundle<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n>(\n\tgraph: Graph,\n\topts: ProcessBundleOptions<TCommand, TState, TEvent, TEffect>,\n): ProcessBundle<TCommand, TState, TEvent, TEffect> {\n\tif (typeof opts.reduce !== \"function\") {\n\t\tthrow new TypeError(\"processBundle: reduce must be a function\");\n\t}\n\tif (opts.initialState === undefined) {\n\t\tthrow new TypeError(\"processBundle: initialState must not be undefined\");\n\t}\n\tconst name = opts.name ?? \"process\";\n\tconst now = opts.now ?? Date.now;\n\tconst topology = graph.topologyGroup({ name: `${name}.process` });\n\tconst command = topology.node<ProcessCommand<TCommand>>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"processCommand\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst runtime = topology.node<ProcessRuntimeFact<TState, TEvent, TEffect>>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessRuntimeState<TState>>() ??\n\t\t\t\t({\n\t\t\t\t\teventSeq: 0,\n\t\t\t\t\teffectSeq: 0,\n\t\t\t\t\tcommandCount: 0,\n\t\t\t\t\terrorCount: 0,\n\t\t\t\t\tauditSeq: 0,\n\t\t\t\t\tseenEventIds: [],\n\t\t\t\t\tseenEffectIds: [],\n\t\t\t\t\tstate: opts.initialState,\n\t\t\t\t} satisfies ProcessRuntimeState<TState>);\n\t\t\tctx.state.persist(true);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = reduceProcessCommandFact(\n\t\t\t\t\traw,\n\t\t\t\t\tstate,\n\t\t\t\t\topts.reduce as ProcessReducer<unknown, TState, unknown, unknown>,\n\t\t\t\t\tnow,\n\t\t\t\t\t(fact) => ctx.down([[\"DATA\", fact as ProcessRuntimeFact<TState, TEvent, TEffect>]]),\n\t\t\t\t);\n\t\t\t\tctx.state.set(state);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processRuntime\",\n\t\t\tmeta: { process: \"facts-plus-reducer\", d: \"D136\" },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst events = processProjection<ProcessEvent<TEvent>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/events`,\n\t\t\"processEvents\",\n\t\t(fact) => (fact.kind === \"event\" ? fact.event : undefined),\n\t);\n\tconst state = processProjection<TState, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/state`,\n\t\t\"processState\",\n\t\t(fact) => (fact.kind === \"state\" ? fact.state : undefined),\n\t);\n\tconst audit = processProjection<ProcessAuditRecord, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/audit`,\n\t\t\"processAudit\",\n\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t);\n\tconst effectRequests = processProjection<ProcessEffectRequest<TEffect>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/effectRequests`,\n\t\t\"processEffectRequests\",\n\t\t(fact) => (fact.kind === \"effect-request\" ? fact.effect : undefined),\n\t);\n\tconst status = processProjection<ProcessStatus, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/status`,\n\t\t\"processStatus\",\n\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t);\n\tconst errors = processProjection<ProcessError, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst cursor = processProjection<ProcessCursor, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/cursor`,\n\t\t\"processCursor\",\n\t\t(fact) => (fact.kind === \"cursor\" ? fact.cursor : undefined),\n\t);\n\tconst retainProcessNodes = () => [\n\t\tgraph.retain(runtime, { reason: `${name}.process.runtime` }),\n\t\tgraph.retain(events, { reason: `${name}.process.events` }),\n\t\tgraph.retain(state, { reason: `${name}.process.state` }),\n\t\tgraph.retain(audit, { reason: `${name}.process.audit` }),\n\t\tgraph.retain(effectRequests, { reason: `${name}.process.effectRequests` }),\n\t\tgraph.retain(status, { reason: `${name}.process.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.process.errors` }),\n\t\tgraph.retain(cursor, { reason: `${name}.process.cursor` }),\n\t];\n\tlet releaseRetains = retainProcessNodes();\n\tlet released = false;\n\tconst bundle: ProcessBundle<TCommand, TState, TEvent, TEffect> = {\n\t\tcommand,\n\t\tevents,\n\t\tstate,\n\t\taudit,\n\t\teffectRequests,\n\t\tstatus,\n\t\terrors,\n\t\tcursor,\n\t\tdispatch(next) {\n\t\t\tcommand.down([[\"DATA\", next]]);\n\t\t\treturn next;\n\t\t},\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.process.release` });\n\t\t\t\treleased = true;\n\t\t\t\tprocessCommandSources.delete(\n\t\t\t\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treleaseRetains = retainProcessNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n\tprocessCommandSources.set(\n\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t{ sources: [] },\n\t);\n\treturn bundle;\n}\n\n/**\n * Build a D156 graph-visible effect runner adapter over a ProcessBundle.\n *\n * The runner consumes visible effect-request and outcome facts, then publishes\n * ordinary ProcessCommand DATA facts back through process.command via a declared\n * graph edge. Async handlers, timers, and process state ownership stay outside\n * this helper.\n */\nexport function processEffectRunner<TEffect = unknown, TResult = unknown>(\n\tgraph: Graph,\n\tprocess: ProcessBundle<unknown, unknown, unknown, TEffect>,\n\topts: ProcessEffectRunnerOptions<TResult>,\n): ProcessEffectRunnerBundle<TEffect, TResult> {\n\tif (opts.outcomes.length === 0) {\n\t\tthrow new RangeError(\"processEffectRunner: outcomes must contain at least one node\");\n\t}\n\tconst name = opts.name ?? \"processEffectRunner\";\n\tconst topology = graph.topologyGroup({ name: `${name}.effectRunner` });\n\tconst requests = topology.node<ProcessEffectRequest<TEffect>>(\n\t\t[process.effectRequests],\n\t\t(ctx) => {\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", request as ProcessEffectRequest<TEffect>]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/requests`,\n\t\t\tfactory: \"processEffectRunnerRequests\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst runtime = topology.node<ProcessEffectRunnerFact<TResult>>(\n\t\t[...opts.outcomes],\n\t\t(ctx) => {\n\t\t\tfor (let i = 0; i < opts.outcomes.length; i += 1) {\n\t\t\t\tfor (const raw of depBatch(ctx, i) ?? []) {\n\t\t\t\t\tconst parsed = parseProcessEffectOutcome<TResult>(raw);\n\t\t\t\t\tif (typeof parsed === \"string\") {\n\t\t\t\t\t\tconst error = {\n\t\t\t\t\t\t\tcode: \"malformed-outcome\",\n\t\t\t\t\t\t\tmessage: parsed,\n\t\t\t\t\t\t\toutcome: raw,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerError;\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", error }]]);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst outcome = parsed as ProcessEffectOutcome<TResult>;\n\t\t\t\t\tconst command = processEffectOutcomeCommand(outcome);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"outcome\", outcome }]]);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"command\", command }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processEffectRunner\",\n\t\t\tmeta: { process: \"effect-runner\", d: \"D156\" },\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outcomes = processEffectRunnerProjection<ProcessEffectOutcome<TResult>, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/outcomes`,\n\t\t\"processEffectRunnerOutcomes\",\n\t\t(fact) => (fact.kind === \"outcome\" ? fact.outcome : undefined),\n\t);\n\tconst commands = processEffectRunnerProjection<\n\t\tProcessCommand<ProcessEffectCommandPayload<TResult>>,\n\t\tTResult\n\t>(topology, runtime, `${name}/commands`, \"processEffectRunnerCommands\", (fact) =>\n\t\tfact.kind === \"command\" ? fact.command : undefined,\n\t);\n\tconst errors = processEffectRunnerProjection<ProcessEffectRunnerError, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processEffectRunnerErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst status = topology.node<ProcessEffectRunnerStatus>(\n\t\t[requests, runtime],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessEffectRunnerState>() ??\n\t\t\t\t({ requested: 0, commanded: 0, rejected: 0 } satisfies ProcessEffectRunnerState);\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = { ...state, requested: state.requested + 1 };\n\t\t\t\tconst typedRequest = request as ProcessEffectRequest<TEffect>;\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\tstate: \"requested\",\n\t\t\t\t\t\t\teffectId: typedRequest.id,\n\t\t\t\t\t\t\teffectType: typedRequest.type,\n\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tfor (const fact of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst typedFact = fact as ProcessEffectRunnerFact<TResult>;\n\t\t\t\tif (typedFact.kind === \"command\") {\n\t\t\t\t\tstate = { ...state, commanded: state.commanded + 1 };\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\tstate: \"commanded\",\n\t\t\t\t\t\t\t\teffectId: typedFact.command.payload.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.command.payload.effectType,\n\t\t\t\t\t\t\t\tcommandId: typedFact.command.id,\n\t\t\t\t\t\t\t\tcommandType: typedFact.command.type as ProcessEffectCommandType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tif (typedFact.kind === \"error\") {\n\t\t\t\t\tstate = { ...state, rejected: state.rejected + 1 };\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\tstate: \"rejected\",\n\t\t\t\t\t\t\t\teffectId: typedFact.error.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.error.effectType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\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(state);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"processEffectRunnerStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst retainRunnerNodes = () => [\n\t\tgraph.retain(requests, { reason: `${name}.effectRunner.requests` }),\n\t\tgraph.retain(outcomes, { reason: `${name}.effectRunner.outcomes` }),\n\t\tgraph.retain(commands, { reason: `${name}.effectRunner.commands` }),\n\t\tgraph.retain(status, { reason: `${name}.effectRunner.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.effectRunner.errors` }),\n\t];\n\tlet releaseRetains = retainRunnerNodes();\n\ttry {\n\t\tattachProcessCommandSource(process, commands);\n\t} catch (error) {\n\t\tfor (const releaseRetain of releaseRetains) releaseRetain();\n\t\treleaseRetains = [];\n\t\ttopology.release({ reason: `${name}.effectRunner.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\trequests,\n\t\toutcomes,\n\t\tcommands,\n\t\tstatus,\n\t\terrors,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\tdetachProcessCommandSource(process, commands);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.effectRunner.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachProcessCommandSource(process, commands);\n\t\t\t\treleaseRetains = retainRunnerNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\ninterface ProcessEffectRunnerState {\n\trequested: number;\n\tcommanded: number;\n\trejected: number;\n}\n\ninterface ProcessRuntimeState<TState> {\n\teventSeq: number;\n\teffectSeq: number;\n\tcommandCount: number;\n\terrorCount: number;\n\tauditSeq: number;\n\tseenEventIds: string[];\n\tseenEffectIds: string[];\n\tstate: TState;\n}\n\nfunction processEffectRunnerProjection<T, TResult>(\n\ttopology: TopologyGroup,\n\truntime: Node<ProcessEffectRunnerFact<TResult>>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: ProcessEffectRunnerFact<TResult>) => T | undefined,\n): Node<T> {\n\treturn topology.node<T>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst value = pick(fact as ProcessEffectRunnerFact<TResult>);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction parseProcessEffectOutcome<TResult>(raw: unknown): ProcessEffectOutcome<TResult> | string {\n\tif (!isObjectRecord(raw)) return \"processEffectRunner: outcome must be an object\";\n\tif (typeof raw.kind !== \"string\") {\n\t\treturn \"processEffectRunner: outcome kind must be a string\";\n\t}\n\tif (\n\t\traw.kind !== \"result\" &&\n\t\traw.kind !== \"failure\" &&\n\t\traw.kind !== \"cancel\" &&\n\t\traw.kind !== \"timeout\"\n\t) {\n\t\treturn \"processEffectRunner: outcome kind must be result, failure, cancel, or timeout\";\n\t}\n\tif (typeof raw.effectId !== \"string\" || raw.effectId.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectId must be a non-empty string\";\n\t}\n\tif (typeof raw.effectType !== \"string\" || raw.effectType.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectType must be a non-empty string\";\n\t}\n\tif (\"commandId\" in raw && raw.commandId !== undefined) {\n\t\tif (typeof raw.commandId !== \"string\" || raw.commandId.length === 0) {\n\t\t\treturn \"processEffectRunner: outcome commandId must be a non-empty string\";\n\t\t}\n\t}\n\tfor (const key of [\"processId\", \"correlationId\", \"causationId\"] as const) {\n\t\tif (key in raw && raw[key] !== undefined && typeof raw[key] !== \"string\") {\n\t\t\treturn `processEffectRunner: outcome ${key} must be a string`;\n\t\t}\n\t}\n\tif (\"metadata\" in raw && raw.metadata !== undefined && !isObjectRecord(raw.metadata)) {\n\t\treturn \"processEffectRunner: outcome metadata must be a plain object\";\n\t}\n\tif (raw.kind === \"result\" && !(\"value\" in raw)) {\n\t\treturn \"processEffectRunner: result outcome must carry value\";\n\t}\n\tif ((raw.kind === \"failure\" || raw.kind === \"timeout\") && !(\"error\" in raw)) {\n\t\treturn `processEffectRunner: ${raw.kind} outcome must carry error`;\n\t}\n\tif (\n\t\traw.kind === \"cancel\" &&\n\t\t\"reason\" in raw &&\n\t\traw.reason !== undefined &&\n\t\ttypeof raw.reason !== \"string\"\n\t) {\n\t\treturn \"processEffectRunner: cancel outcome reason must be a string\";\n\t}\n\treturn raw as unknown as ProcessEffectOutcome<TResult>;\n}\n\nfunction processEffectOutcomeCommand<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessCommand<ProcessEffectCommandPayload<TResult>> {\n\tconst commandType = processEffectCommandType(outcome.kind);\n\treturn {\n\t\tid: outcome.commandId ?? `${outcome.effectId}:${commandType}`,\n\t\ttype: commandType,\n\t\tpayload: processEffectCommandPayload(outcome),\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n}\n\nfunction processEffectCommandType(kind: ProcessEffectOutcome[\"kind\"]): ProcessEffectCommandType {\n\tswitch (kind) {\n\t\tcase \"result\":\n\t\t\treturn \"effect.result\";\n\t\tcase \"failure\":\n\t\t\treturn \"effect.failure\";\n\t\tcase \"cancel\":\n\t\t\treturn \"effect.cancel\";\n\t\tcase \"timeout\":\n\t\t\treturn \"effect.timeout\";\n\t}\n}\n\nfunction processEffectCommandPayload<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessEffectCommandPayload<TResult> {\n\tconst base = {\n\t\teffectId: outcome.effectId,\n\t\teffectType: outcome.effectType,\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n\tswitch (outcome.kind) {\n\t\tcase \"result\":\n\t\t\treturn { ...base, kind: \"result\", value: outcome.value };\n\t\tcase \"failure\":\n\t\t\treturn { ...base, kind: \"failure\", error: outcome.error };\n\t\tcase \"cancel\":\n\t\t\treturn { ...base, kind: \"cancel\", reason: outcome.reason };\n\t\tcase \"timeout\":\n\t\t\treturn { ...base, kind: \"timeout\", error: outcome.error };\n\t}\n}\n\nfunction attachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\tprocess.command.replaceDeps([...sources], processCommandSourceFn(sources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\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\tprocess.command.replaceDeps([...nextSources], processCommandSourceFn(nextSources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction processCommandSourceFn(sourceCount: number) {\n\treturn (ctx: Parameters<NodeFn>[0]) => {\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 ProcessCommand<unknown>]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction processRuntimeDraft<TState>(\n\tstate: ProcessRuntimeState<TState>,\n): ProcessRuntimeState<TState> {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t\tseenEventIds: [...state.seenEventIds],\n\t\tseenEffectIds: [...state.seenEffectIds],\n\t\tstate: state.state,\n\t};\n}\n\nfunction reduceProcessCommandFact<TState>(\n\traw: unknown,\n\tstate: ProcessRuntimeState<TState>,\n\treduce: ProcessReducer<unknown, TState, unknown, unknown>,\n\tnow: () => number,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n): ProcessRuntimeState<TState> {\n\tconst draft = processRuntimeDraft(state);\n\tdraft.commandCount += 1;\n\tconst parsed = parseProcessCommand(raw);\n\tif (typeof parsed === \"string\") {\n\t\temitProcessFailure(draft, emit, raw, undefined, \"malformed-command\", parsed);\n\t\treturn draft;\n\t}\n\tconst command = parsed as ProcessCommand<unknown>;\n\tlet reduction: ProcessReduction<TState, unknown, unknown>;\n\tconst reducerState = cloneProcessState(state.state);\n\tif (!reducerState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", reducerState.message);\n\t\treturn draft;\n\t}\n\ttry {\n\t\treduction = reduce(command, reducerState.value);\n\t} catch (error) {\n\t\trethrowGraphRuntimeInvariant(error);\n\t\temitProcessFailure(draft, emit, command, command, \"reducer-threw\", errorMessage(error));\n\t\treturn draft;\n\t}\n\tif (!isObjectRecord(reduction) || !(\"state\" in reduction)) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer must return { state, events?, effects? }\",\n\t\t);\n\t\treturn draft;\n\t}\n\tif (reduction.state === undefined) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer state must not be undefined\",\n\t\t);\n\t\treturn draft;\n\t}\n\tconst privateState = cloneProcessState(reduction.state);\n\tif (!privateState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", privateState.message);\n\t\treturn draft;\n\t}\n\tconst visibleState = cloneProcessState(privateState.value);\n\tif (!visibleState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", visibleState.message);\n\t\treturn draft;\n\t}\n\tconst preparedEvents = prepareProcessEvents(command, draft, reduction.events ?? []);\n\tif (typeof preparedEvents === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-event\", preparedEvents);\n\t\treturn draft;\n\t}\n\tconst preparedEffects = prepareProcessEffects(command, draft, reduction.effects ?? []);\n\tif (typeof preparedEffects === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-effect\", preparedEffects);\n\t\treturn draft;\n\t}\n\tconst timestampMs = readTimestampMs(now);\n\tif (typeof timestampMs === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"clock-threw\", timestampMs);\n\t\treturn draft;\n\t}\n\tdraft.state = privateState.value;\n\temit({ kind: \"state\", state: visibleState.value, cursor: processCursorOf(draft) });\n\tconst events: ProcessEvent<unknown>[] = [];\n\tfor (const eventDraft of preparedEvents) {\n\t\tdraft.eventSeq += 1;\n\t\tdraft.seenEventIds.push(eventDraft.id);\n\t\tconst event: ProcessEvent<unknown> = {\n\t\t\tid: eventDraft.id,\n\t\t\ttype: eventDraft.type,\n\t\t\tseq: draft.eventSeq,\n\t\t\tcursor: draft.eventSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: eventDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(eventDraft.processId === undefined ? {} : { processId: eventDraft.processId }),\n\t\t\t...(eventDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: eventDraft.correlationId }),\n\t\t\t...(eventDraft.causationId === undefined ? {} : { causationId: eventDraft.causationId }),\n\t\t\t...(eventDraft.metadata === undefined ? {} : { metadata: eventDraft.metadata }),\n\t\t};\n\t\tevents.push(event);\n\t\temit({ kind: \"event\", event });\n\t}\n\tconst effects: ProcessEffectRequest<unknown>[] = [];\n\tfor (const effectDraft of preparedEffects) {\n\t\tdraft.effectSeq += 1;\n\t\tdraft.seenEffectIds.push(effectDraft.id);\n\t\tconst effect: ProcessEffectRequest<unknown> = {\n\t\t\tid: effectDraft.id,\n\t\t\ttype: effectDraft.type,\n\t\t\tseq: draft.effectSeq,\n\t\t\tcursor: draft.effectSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: effectDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(effectDraft.processId === undefined ? {} : { processId: effectDraft.processId }),\n\t\t\t...(effectDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: effectDraft.correlationId }),\n\t\t\t...(effectDraft.causationId === undefined ? {} : { causationId: effectDraft.causationId }),\n\t\t\t...(effectDraft.metadata === undefined ? {} : { metadata: effectDraft.metadata }),\n\t\t};\n\t\teffects.push(effect);\n\t\temit({ kind: \"effect-request\", effect });\n\t}\n\temitProcessStatus(draft, emit, command, \"accepted\", events.length, effects.length);\n\temitProcessAudit(draft, emit, command, \"success\", events, effects, undefined, undefined);\n\temit({ kind: \"cursor\", cursor: processCursorOf(draft) });\n\treturn draft;\n}\n\nfunction processProjection<TOut, TState, TEvent, TEffect>(\n\tgraph: Graph | TopologyGroup,\n\truntime: Node<ProcessRuntimeFact<TState, TEvent, TEffect>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: ProcessRuntimeFact<TState, TEvent, TEffect>) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst selected = select(raw as ProcessRuntimeFact<TState, TEvent, TEffect>);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false },\n\t);\n}\n\nfunction parseProcessCommand(value: unknown): ProcessCommand<unknown> | string {\n\tif (!isObjectRecord(value)) return \"processBundle: command fact must be an object\";\n\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\treturn \"processBundle: command id must be a non-empty string\";\n\t}\n\tif (typeof value.type !== \"string\" || value.type.length === 0) {\n\t\treturn \"processBundle: command type must be a non-empty string\";\n\t}\n\treturn {\n\t\tid: value.id,\n\t\ttype: value.type,\n\t\tpayload: value.payload,\n\t\t...(typeof value.processId === \"string\" ? { processId: value.processId } : {}),\n\t\t...(typeof value.correlationId === \"string\" ? { correlationId: value.correlationId } : {}),\n\t\t...(typeof value.causationId === \"string\" ? { causationId: value.causationId } : {}),\n\t\t...(isObjectRecord(value.metadata) ? { metadata: value.metadata } : {}),\n\t};\n}\n\nfunction prepareProcessEvents(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEventDraft<unknown>[],\n): Array<ProcessEventDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: events must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEventDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: event draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:event:${state.eventSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate event '${id}'`;\n\t\tif (state.seenEventIds.includes(id)) return `processBundle: duplicate event '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction prepareProcessEffects(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEffectRequestDraft<unknown>[],\n): Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: effects must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: effect draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:effect:${state.effectSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tif (state.seenEffectIds.includes(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction emitProcessFailure<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\traw: unknown,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tcode: ProcessErrorCode,\n\tmessage: string,\n): void {\n\tstate.errorCount += 1;\n\tconst cursor = processCursorOf(state);\n\tconst error: ProcessError = {\n\t\tcode,\n\t\tmessage,\n\t\tcommand: raw,\n\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\tcursor,\n\t};\n\temit({ kind: \"error\", error });\n\temitProcessStatus(state, emit, command, \"rejected\", 0, 0, code);\n\temitProcessAudit(state, emit, command, \"failure\", [], [], code, message);\n\temit({ kind: \"cursor\", cursor: processCursorOf(state) });\n}\n\nfunction emitProcessStatus<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tstatusState: ProcessStatus[\"state\"],\n\teventCount: number,\n\teffectCount: number,\n\terrorCode?: ProcessErrorCode,\n): void {\n\temit({\n\t\tkind: \"status\",\n\t\tstatus: {\n\t\t\tstate: statusState,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\teventCount,\n\t\t\teffectCount,\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction emitProcessAudit<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\toutcome: ProcessAuditRecord[\"outcome\"],\n\tevents: readonly ProcessEvent<unknown>[],\n\teffects: readonly ProcessEffectRequest<unknown>[],\n\terrorCode: ProcessErrorCode | undefined,\n\terrorMessage: string | undefined,\n): void {\n\tstate.auditSeq += 1;\n\temit({\n\t\tkind: \"audit\",\n\t\taudit: {\n\t\t\tseq: state.auditSeq,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\toutcome,\n\t\t\teventIds: events.map((event) => event.id),\n\t\t\teventTypes: events.map((event) => event.type),\n\t\t\teffectIds: effects.map((effect) => effect.id),\n\t\t\teffectTypes: effects.map((effect) => effect.type),\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\t...(errorMessage === undefined ? {} : { errorMessage }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction processCursorOf(state: ProcessRuntimeState<unknown>): ProcessCursor {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t};\n}\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 * 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","/**\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 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","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 * 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 * 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 * 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 * Wall-clock time operators (CSP-2.7 / D52 / B23). Authored as COMPOSITIONS over the already-active\n * higher-order *Map machinery (D47) + the `timer` source — NO raw `setTimeout` in any operator body\n * (R-no-raw-async / check-no-raw-async; `setTimeout` stays confined to `sources.ts`'s `timer`). The\n * timer source's `onDeactivation` clearTimeout IS the reset/cancel: switchMap's unsubscribeDep on a new\n * source value tears the in-flight timer down (the declarative equivalent of the frozen reference's\n * imperative clearTimeout-then-setTimeout). Per-language (D6/D24), never in parity.\n *\n * Shipped this cut (clean *Map+timer):\n * - delay = mergeMap(v → timer(ms)→v) (every value delayed ms, ALL kept, order preserved)\n * - debounce(Time) = switchMap(v → timer(ms)→v) (cancel-and-restart; emit the latest after quiet ms)\n * - throttle(Time) = exhaustMap(v → [v now, alive ms]) (leading edge: emit v, ignore for ms)\n *\n * Behavior on source COMPLETE (per-operator, NOT a uniform DROP): debounce/debounceTime EMIT their\n * pending trailing value — switchMap does not cancel the in-flight inner on source COMPLETE (only a\n * superseding source value cancels it via unsubscribeDep→onDeactivation→clearTimeout), so the timer still\n * fires at `ms`, emits the debounced value, and only THEN does the operator COMPLETE (RxJS\n * debounceTime parity). delay emits every still-pending delayed value then COMPLETEs (mergeMap keeps\n * all inners). throttle/throttleTime have NO trailing value (leading-edge only, RxJS default\n * trailing:false) — an open window inner is dropped when the operator completes.\n *\n * B41 tail (landed 2026-05-31, the two shapes reflect WHEN the clock arms):\n * - audit / auditTime — VALUE-TRIGGERED trailing edge: a source value opens a duration window\n * (`audit(durationSelector)` = the general/notifier form, mirroring the *Map\n * `Project` idiom + D46; `auditTime(ms)` = `audit(() => timer(ms))`), emits the\n * window's LATEST value at the window's close. Self-wires the notifier via\n * ctx.rewireNext — a normal `g.initNode(audit(sel), [source])` operator.\n * - timeout / bufferTime — SUBSCRIBE-ARMED (RxJS-cold): the clock must run from activation, before\n * any source value, so the timer/interval is a CONSTRUCTION-time dep (a depless\n * source arms lazily on subscribe per node `_activate`). A dep-bearing operator\n * body never runs at activation (only depless nodes do, node.ts), so these ship\n * as graph composition HELPERS `timeout(source, ms)` / `bufferTime(source, ms)`\n * returning a Node — NOT `g.initNode(op, [deps])` operators. timeout resets its\n * idle timer per source value via ctx.rewireNext (ERROR on the gap); bufferTime\n * is buffer-over-interval with terminal cleanup via ctx.rewireNext.\n *\n * NOT ported (D58): window/windowCount/windowTime — the Node<Node<T>> higher-order forms are a D45\n * describe island; the array forms (buffer/bufferCount/bufferTime) are the graph-first equivalent.\n *\n * Inspection caveat (timeout/bufferTime): the helper returns a BARE node (free initNode) self-carrying\n * its factory for describe auto-discovery (D51), but it is NOT in a graph's _entries — so g.describe()\n * lists it only when it is a live dep of a registered node (a first-cut limit, like the *Map inners).\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { exhaustMap, mergeMap, switchMap } from \"./higher-order.js\";\nimport { filter, initNode, map, merge, type Operator } from \"./operators.js\";\nimport { fromAny, interval, type NodeInput, of, timer } from \"./sources.js\";\n\n/** A bare inner that emits `v` once after `ms`, then COMPLETEs (timer(ms)→map(v); auto-completes). */\nfunction delayedValue<S>(v: S, ms: number): Node<S> {\n\treturn initNode(\n\t\tmap(() => v),\n\t\t[initNode(timer(ms), [])],\n\t);\n}\n\n/**\n * An inner that emits `v` IMMEDIATELY (on activation) and stays alive for `ms` (then COMPLETEs),\n * emitting nothing more — the leading-edge throttle window. `merge(of(v), silentTimer)`: `of(v)`\n * emits v + COMPLETE at t=0; `filter(()=>false)` over `timer(ms)` emits no DATA and COMPLETEs at\n * t=ms; merge forwards v at t=0 and COMPLETEs (all deps complete) at t=ms.\n */\nfunction throttleWindow<S>(v: S, ms: number): Node<S> {\n\tconst silentTimer = initNode(\n\t\tfilter<number>(() => false),\n\t\t[initNode(timer(ms), [])],\n\t) as Node<S>;\n\treturn initNode(merge<S>(), [initNode(of(v), []), silentTimer]);\n}\n\n/**\n * delay: shift every value by `ms`, preserving all values + order. `mergeMap` keeps every inner\n * timer live (equal `ms`, so they fire in arrival order).\n */\nexport function delay<S>(ms: number): Operator<S, S> {\n\treturn { ...mergeMap<S, S>((v) => delayedValue(v, ms)), factory: \"delay\" };\n}\n\n/**\n * debounce (alias `debounceTime`): emit the latest value only after `ms` of quiet. `switchMap`\n * cancels the prior timer (its onDeactivation clearTimeout) on each new source value and restarts —\n * the declarative debounce.\n *\n * RxJS-7 divergence (reference rxjs@7.8, B44): RxJS `debounceTime` FLUSHES the pending value\n * IMMEDIATELY when the source COMPLETEs (its `_complete` calls `debouncedNext()` before\n * `complete()`). This composition instead emits the pending value when the in-flight `timer(ms)`\n * fires — i.e. at `(last-value-time + ms)` — so if the source completes mid-window the trailing\n * value arrives up to `ms` later than RxJS. Inherent to the `*Map`+`timer` form (the composition\n * cannot flush early without detecting COMPLETE inside the switchMap inner); accepted, not a bug.\n */\nexport function debounce<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounce\" };\n}\n\n/** debounceTime: RxJS-named alias of {@link debounce}. */\nexport function debounceTime<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounceTime\" };\n}\n\n/**\n * throttle (alias `throttleTime`): leading-edge — emit a value immediately, then ignore the source\n * for `ms`. `exhaustMap` drops new source values while the current window inner is alive; the\n * window emits v at its leading edge and stays alive `ms`.\n *\n * Matches the RxJS-7 `throttleTime` DEFAULT (leading:true, trailing:false). The leading/trailing\n * OPTIONS RxJS exposes are NOT provided (a capability gap, not a behavior divergence; B44) — add a\n * trailing-window form if a consumer needs it.\n */\nexport function throttle<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttle\" };\n}\n\n/** throttleTime: RxJS-named alias of {@link throttle}. */\nexport function throttleTime<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttleTime\" };\n}\n\n// ── B41 tail: value-triggered (audit) + subscribe-armed (timeout/bufferTime) ──\n\n/** Per-node bookkeeping for {@link audit}: the open window's notifier + the latest value seen. */\ninterface AuditState<S> {\n\twindowOpen: boolean;\n\tlatest: { v: S } | undefined;\n\tnotifier: Node<unknown> | null;\n}\n\n/**\n * audit: VALUE-TRIGGERED trailing throttle. A source value (when no window is open) opens a duration\n * window via `durationSelector(value)` → a notifier `NodeInput` wired as dep 1 with `ctx.rewireNext`\n * (D47 — the *Map self-rewire idiom, NOT an internal subscribe, D45); during the window new source\n * values only UPDATE the tracked latest (no emit); when the notifier fires (its first DATA / COMPLETE)\n * the window closes and the LATEST value is emitted. This is throttle's trailing-edge twin\n * (throttle emits the window's FIRST value at the leading edge; audit emits the LAST at the close).\n *\n * `durationSelector` is the general/notifier form (mirrors the *Map `Project` idiom + D46); the source\n * is dep 0, the live notifier (if any) is dep 1. On source COMPLETE the pending latest is FLUSHED then\n * COMPLETE (RxJS-7 audit flush-on-complete, B44). A source/notifier ERROR is read as a real terminal\n * input so the live notifier can be removed before ERROR. Self-catching (D30); re-supplies its body on\n * every rewire.\n */\nexport function audit<S>(durationSelector: (v: S) => NodeInput<unknown>): Operator<S, S> {\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: AuditState<S> = ctx.state.get<AuditState<S>>() ?? {\n\t\t\t\twindowOpen: false,\n\t\t\t\tlatest: undefined,\n\t\t\t\tnotifier: null,\n\t\t\t};\n\t\t\tconst sourceBatch = depBatch(ctx, 0);\n\t\t\tconst notifierBatch = depBatch(ctx, 1); // live duration notifier while a window is open\n\t\t\tconst sourceTerminal = depTerminal(ctx, 0);\n\t\t\tconst notifierTerminal = depTerminal(ctx, 1);\n\n\t\t\t// every source value updates the window's latest (the value emitted at the window's close).\n\t\t\tconst sb = sourceBatch as readonly S[] | null;\n\t\t\tif (sb) for (const v of sb) st.latest = { v };\n\n\t\t\t// the window closes when its duration notifier fires (DATA or COMPLETE) → emit the latest.\n\t\t\tconst notifierFired =\n\t\t\t\tst.windowOpen &&\n\t\t\t\t((notifierBatch != null && notifierBatch.length > 0) ||\n\t\t\t\t\tisTerminalComplete(notifierTerminal));\n\t\t\tif (notifierFired) {\n\t\t\t\tif (st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tconst old = st.notifier;\n\t\t\t\tst.windowOpen = false;\n\t\t\t\tst.notifier = null;\n\t\t\t\tst.latest = undefined;\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body);\n\t\t\t}\n\n\t\t\t// source/notifier ERROR → forward ERROR, but first remove the helper-owned notifier.\n\t\t\tconst sourceError = isTerminalError(sourceTerminal);\n\t\t\tconst notifierError = isTerminalError(notifierTerminal);\n\t\t\tif (sourceError || notifierError) {\n\t\t\t\tconst err = terminalErrorValue(sourceError ? sourceTerminal : notifierTerminal);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// source COMPLETE → flush the pending latest (B44 audit flush-on-complete) then COMPLETE.\n\t\t\tif (isTerminalComplete(sourceTerminal)) {\n\t\t\t\tif (st.windowOpen && st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// a fresh source value with no open window → open one (value-triggered, trailing edge).\n\t\t\tif (!st.windowOpen && sb != null && sb.length > 0 && st.latest !== undefined) {\n\t\t\t\tconst n = fromAny<unknown>(durationSelector(st.latest.v), { iter: true });\n\t\t\t\tst.windowOpen = true;\n\t\t\t\tst.notifier = n;\n\t\t\t\tctx.rewireNext.subscribeDep(n, body); // (a same-wave close+reopen issues remove-before-add)\n\t\t\t}\n\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"audit threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn {\n\t\tfactory: \"audit\",\n\t\tbody,\n\t\topts: {\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}\n\n/** auditTime: the `ms`-specialization of {@link audit} — the window is a `timer(ms)`. */\nexport function auditTime<S>(ms: number): Operator<S, S> {\n\treturn { ...audit<S>(() => initNode(timer(ms), [])), factory: \"auditTime\" };\n}\n\n/** Per-node bookkeeping for {@link timeout}: the live idle timer (reset on each source value). */\ninterface TimeoutState {\n\ttimer: Node<unknown> | null;\n}\n\n/**\n * timeout: idle watchdog — forward every source value, but ERROR if more than `ms` elapses with no\n * value (RxJS `timeout(ms)`, `first === each === ms`). SUBSCRIBE-ARMED: the first `timer(ms)` is a\n * CONSTRUCTION-time dep, so it arms when `timeout`'s node is subscribed/activated (a depless source\n * runs lazily on `_activate`) — i.e. a source that never emits its FIRST value within `ms` still\n * errors. A dep-bearing operator body never runs at activation (only depless nodes do, node.ts), which\n * is why this is a HELPER returning a Node, not a `g.initNode(op, [source])` operator.\n *\n * Each source value forwards as-is and RESETS the idle timer (unsubscribeDep the current `timer(ms)`,\n * subscribeDep a fresh one — its `onDeactivation` clearTimeout cancels the prior countdown). The timer\n * firing (its DATA/COMPLETE) is the timeout → `[[ERROR]]`. Source COMPLETE forwards COMPLETE (no\n * error) and removes the idle timer during the terminal wave (D62 terminal-drains-queued-rewire);\n * a source ERROR forwards likewise. The idle timer is also torn down when the consumer unsubscribes\n * (timeout deactivates → dep unsub → timer onDeactivation). Self-catching (D30).\n */\nexport function timeout<S>(source: Node<S>, ms: number): Node<S> {\n\tconst makeTimer = (): Node<unknown> => initNode(timer(ms), []);\n\tconst initial = makeTimer();\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: TimeoutState = ctx.state.get<TimeoutState>() ?? { timer: initial };\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\n\t\t\t// a source value forwards as-is and resets the idle window.\n\t\t\tconst sb = srcBatch as readonly S[] | null;\n\t\t\tif (sb != null && sb.length > 0) {\n\t\t\t\tfor (const v of sb) ctx.down([[\"DATA\", v]]);\n\t\t\t\tconst old = st.timer;\n\t\t\t\tconst next = makeTimer();\n\t\t\t\tst.timer = next;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body); // remove-before-add (alignment)\n\t\t\t\tctx.rewireNext.subscribeDep(next, body);\n\t\t\t\treturn; // a value-bearing wave is never also a timeout-fire wave\n\t\t\t}\n\n\t\t\t// source COMPLETE → forward COMPLETE (no timeout fires).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// source ERROR (absorbed via errorWhenDepsError:false) → forward it.\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise this wave is the idle timer firing → timeout ERROR.\n\t\t\tconst timerBatch = depBatch(ctx, 1);\n\t\t\tif (\n\t\t\t\t(timerBatch != null && timerBatch.length > 0) ||\n\t\t\t\tisTerminalComplete(depTerminal(ctx, 1))\n\t\t\t) {\n\t\t\t\tctx.down([[\"ERROR\", new Error(`timeout: no value within ${ms}ms`)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"timeout threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn initNode<S, S>(\n\t\t{\n\t\t\tfactory: \"timeout\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, initial],\n\t);\n}\n\n/**\n * bufferTime: buffer source values and flush them as an array every `ms` (RxJS `bufferTime(ms)`).\n * SUBSCRIBE-ARMED: the `interval(ms)` notifier is a CONSTRUCTION-time dep (arms on subscribe), so an\n * empty window flushes `[]` even before the first source value — matching the landed {@link buffer}\n * (which flushes on every notifier signal). On source COMPLETE the remainder flushes then COMPLETE\n * (B44), and D62 lets the terminal wave still drain `unsubscribeDep(interval)` so the helper-owned\n * interval source deactivates instead of ticking forever.\n */\nexport function bufferTime<S>(source: Node<S>, ms: number): Node<S[]> {\n\tconst iv: Node<unknown> = initNode(interval(ms), []);\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\tconst srcBatch = depBatch(ctx, 0);\n\t\tconst tickBatch = depBatch(ctx, 1);\n\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\tconst buf = ctx.state.get<S[]>() ?? [];\n\t\tif (srcBatch) for (const v of srcBatch) buf.push(v as S);\n\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\tif (buf.length > 0) ctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\treturn;\n\t\t}\n\t\tif (isTerminalError(srcTerminal)) {\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\treturn;\n\t\t}\n\t\tif (tickBatch && tickBatch.length > 0) {\n\t\t\tctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\treturn;\n\t\t}\n\t\tctx.state.set(buf);\n\t};\n\treturn initNode<unknown, S[]>(\n\t\t{\n\t\t\tfactory: \"bufferTime\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, iv],\n\t);\n}\n","import { depBatch } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\ttype BackoffPolicy,\n\tnextRetryDelayMs,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport { timeout as timeoutOperator } from \"../graph/time.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport type ResilienceEvent =\n\t| { readonly kind: \"attempt\"; readonly attempt: number }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"success\"; readonly attempt?: number }\n\t| { readonly kind: \"failure\"; readonly attempt?: number; readonly error: unknown }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\nexport interface RetryStatusBundle {\n\treadonly status: Node<RetryStatus>;\n\treadonly errors: Node<unknown>;\n}\n\nexport interface BreakerOptions {\n\treadonly failureThreshold: number;\n\treadonly resetAfterMs?: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface BreakerStatus {\n\treadonly state: \"closed\" | \"open\" | \"half-open\";\n\treadonly failures: number;\n\treadonly openedAtMs?: number;\n}\n\nexport interface BreakerBundle {\n\treadonly status: Node<BreakerStatus>;\n\treadonly allowed: Node<boolean>;\n}\n\nexport interface RateLimitOptions {\n\treadonly max: number;\n\treadonly windowMs: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface RateLimitStatus {\n\treadonly allowed: number;\n\treadonly dropped: number;\n\treadonly remaining: number;\n\treadonly resetAtMs: number;\n}\n\nexport interface RateLimitBundle<T> {\n\treadonly allowed: Node<T>;\n\treadonly dropped: Node<T>;\n\treadonly status: Node<RateLimitStatus>;\n}\n\ntype RateLimitEvent<T> =\n\t| { readonly kind: \"allowed\"; readonly value: T; readonly status: RateLimitStatus }\n\t| { readonly kind: \"dropped\"; readonly value: T; readonly status: RateLimitStatus };\n\nexport interface TimeoutBundle<T> {\n\treadonly node: Node<T>;\n\treadonly status: Node<\"running\" | \"completed\" | \"errored\">;\n\treadonly errors: Node<unknown>;\n}\n\nexport function retryStatusBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: { name?: string; policy?: RetryPolicy } = {},\n): RetryStatusBundle {\n\tconst policy = opts.policy ?? retryPolicy();\n\tconst name = opts.name ?? \"retry\";\n\tconst status = graph.node<RetryStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<RetryStatus>() ??\n\t\t\t\t({ state: \"idle\", attempt: 0, maxAttempts: policy.maxAttempts } satisfies RetryStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tnext = { state: \"running\", attempt: event.attempt, maxAttempts: policy.maxAttempts };\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"success\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"succeeded\",\n\t\t\t\t\t\tattempt: event.attempt ?? next.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"failure\") {\n\t\t\t\t\tconst attempt = event.attempt ?? next.attempt;\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: shouldRetry(policy, attempt) ? \"failed\" : \"exhausted\",\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: shouldRetry(policy, attempt)\n\t\t\t\t\t\t\t? nextRetryDelayMs(policy, attempt + 1)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\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: \"retryStatus\" },\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 ResilienceEvent;\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: \"retryErrors\" },\n\t);\n\treturn { status, errors };\n}\n\nexport function breakerBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: BreakerOptions,\n): BreakerBundle {\n\tif (!Number.isInteger(opts.failureThreshold) || opts.failureThreshold <= 0) {\n\t\tthrow new RangeError(\"breakerBundle: failureThreshold must be a positive integer\");\n\t}\n\tconst name = opts.name ?? \"breaker\";\n\tconst now = opts.now ?? Date.now;\n\tconst status = graph.node<BreakerStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<BreakerStatus>() ??\n\t\t\t\t({ state: \"closed\", failures: 0 } satisfies BreakerStatus);\n\t\t\tif (\n\t\t\t\tnext.state === \"open\" &&\n\t\t\t\topts.resetAfterMs !== undefined &&\n\t\t\t\tnext.openedAtMs !== undefined &&\n\t\t\t\tnow() - next.openedAtMs >= opts.resetAfterMs\n\t\t\t) {\n\t\t\t\tnext = { ...next, state: \"half-open\" };\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"success\") {\n\t\t\t\t\tnext = { state: \"closed\", failures: 0 };\n\t\t\t\t} else if (event.kind === \"failure\" || event.kind === \"exhausted\") {\n\t\t\t\t\tconst failures = next.failures + 1;\n\t\t\t\t\tnext =\n\t\t\t\t\t\tfailures >= opts.failureThreshold\n\t\t\t\t\t\t\t? { state: \"open\", failures, openedAtMs: now() }\n\t\t\t\t\t\t\t: { ...next, failures };\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: \"breakerStatus\" },\n\t);\n\tconst allowed = graph.node<boolean>(\n\t\t[status],\n\t\t(ctx) => {\n\t\t\tconst statusBatch = depBatch(ctx, 0) ?? [];\n\t\t\tfor (const value of statusBatch) {\n\t\t\t\tctx.down([[\"DATA\", (value as BreakerStatus).state !== \"open\"]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"breakerAllowed\" },\n\t);\n\treturn { status, allowed };\n}\n\nexport function rateLimitBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\topts: RateLimitOptions,\n): RateLimitBundle<T> {\n\tif (!Number.isInteger(opts.max) || opts.max <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: max must be a positive integer\");\n\t}\n\tif (!Number.isFinite(opts.windowMs) || opts.windowMs <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: windowMs must be positive\");\n\t}\n\tconst now = opts.now ?? Date.now;\n\tconst name = opts.name ?? \"rateLimit\";\n\tconst events = graph.node<RateLimitEvent<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\ttype State = { count: number; resetAtMs: number; allowed: number; dropped: number };\n\t\t\tconst current = now();\n\t\t\tlet state =\n\t\t\t\tctx.state.get<State>() ??\n\t\t\t\t({ count: 0, resetAtMs: current + opts.windowMs, allowed: 0, dropped: 0 } satisfies State);\n\t\t\tif (current >= state.resetAtMs) {\n\t\t\t\tstate = { ...state, count: 0, resetAtMs: current + opts.windowMs };\n\t\t\t}\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst allowed = state.count < opts.max;\n\t\t\t\tstate = allowed\n\t\t\t\t\t? { ...state, count: state.count + 1, allowed: state.allowed + 1 }\n\t\t\t\t\t: { ...state, dropped: state.dropped + 1 };\n\t\t\t\tconst status = {\n\t\t\t\t\tallowed: state.allowed,\n\t\t\t\t\tdropped: state.dropped,\n\t\t\t\t\tremaining: Math.max(0, opts.max - state.count),\n\t\t\t\t\tresetAtMs: state.resetAtMs,\n\t\t\t\t} satisfies RateLimitStatus;\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\tallowed\n\t\t\t\t\t\t\t? ({ kind: \"allowed\", value: value as T, status } satisfies RateLimitEvent<T>)\n\t\t\t\t\t\t\t: ({ kind: \"dropped\", value: value as T, status } satisfies RateLimitEvent<T>),\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},\n\t\t{ name: `${name}/events`, factory: \"rateLimitEvents\" },\n\t);\n\tconst allowed = graph.node<T>(\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 RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"allowed\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"rateLimitAllowed\" },\n\t);\n\tconst dropped = graph.node<T>(\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 RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"dropped\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/dropped`, factory: \"rateLimitDropped\" },\n\t);\n\tconst status = graph.node<RateLimitStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", (event as RateLimitEvent<T>).status]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"rateLimitStatus\" },\n\t);\n\treturn { allowed, dropped, status };\n}\n\nexport function timeoutBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tms: number,\n\topts: { name?: string } = {},\n): TimeoutBundle<T> {\n\tconst name = opts.name ?? \"timeout\";\n\tconst node = timeoutOperator(source, ms);\n\tconst status = graph.node<\"running\" | \"completed\" | \"errored\">(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal === true) ctx.down([[\"DATA\", \"completed\"]]);\n\t\t\telse if (terminal !== false && terminal !== undefined) ctx.down([[\"DATA\", \"errored\"]]);\n\t\t\telse if ((depBatch(ctx, 0) ?? []).length > 0) ctx.down([[\"DATA\", \"running\"]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"timeoutStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal !== true && terminal !== false && terminal !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", terminal]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"timeoutErrors\" },\n\t);\n\treturn { node, status, errors };\n}\n\nexport function constantBackoff(delayMs: number): BackoffPolicy {\n\treturn { kind: \"constant\", delayMs };\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tcanonicalPublicSourceRefs,\n\tdataIssue,\n\tforEachDepBatch,\n\tprojectRuntimeFact,\n\tref,\n\tsanitizeGraphVisibleRecord,\n\tstableJsonStringify,\n\tuniqueSourceRefs,\n} from \"./agent-runtime-common.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { SourceRef } from \"./agent-runtime-types-core.js\";\n\nexport interface ScheduledReadinessRequested {\n\treadonly kind: \"scheduled-readiness-requested\";\n\treadonly scheduleId: string;\n\treadonly subjectRefs: readonly SourceRef[];\n\treadonly readyAtMs: number;\n\treadonly deadlineMs?: number;\n\treadonly reason?: string;\n\treadonly policyRefs?: readonly SourceRef[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ScheduledReadinessClock {\n\treadonly kind: \"scheduled-readiness-clock\";\n\treadonly clockId: string;\n\treadonly nowMs: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ScheduledReadinessPending {\n\treadonly kind: \"scheduled-readiness-pending\";\n\treadonly scheduleId: string;\n\treadonly subjectRefs: readonly SourceRef[];\n\treadonly readyAtMs: number;\n\treadonly deadlineMs?: number;\n\treadonly nowMs?: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ScheduledReadinessReady {\n\treadonly kind: \"scheduled-readiness-ready\";\n\treadonly scheduleId: string;\n\treadonly subjectRefs: readonly SourceRef[];\n\treadonly readyAtMs: number;\n\treadonly deadlineMs?: number;\n\treadonly nowMs: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ScheduledReadinessOverdue {\n\treadonly kind: \"scheduled-readiness-overdue\";\n\treadonly scheduleId: string;\n\treadonly subjectRefs: readonly SourceRef[];\n\treadonly readyAtMs: number;\n\treadonly deadlineMs: number;\n\treadonly nowMs: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ScheduledReadinessStatusState = \"pending\" | \"ready\" | \"overdue\" | \"issue\";\n\nexport interface ScheduledReadinessStatus {\n\treadonly kind: \"scheduled-readiness-status\";\n\treadonly statusId: string;\n\treadonly scheduleId: string;\n\treadonly state: ScheduledReadinessStatusState;\n\treadonly subjectRefs?: readonly SourceRef[];\n\treadonly readyAtMs?: number;\n\treadonly deadlineMs?: number;\n\treadonly nowMs?: number;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly issueCodes?: readonly string[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface ScheduledReadinessViews {\n\treadonly schedulesById: ReadonlyMap<string, ScheduledReadinessRequested>;\n\treadonly pendingById: ReadonlyMap<string, ScheduledReadinessPending>;\n\treadonly readyById: ReadonlyMap<string, ScheduledReadinessReady>;\n\treadonly overdueById: ReadonlyMap<string, ScheduledReadinessOverdue>;\n\treadonly statusById: ReadonlyMap<string, ScheduledReadinessStatus>;\n\treadonly nowMs?: number;\n}\n\nexport interface ScheduledReadinessBundle {\n\treadonly pending: Node<ScheduledReadinessPending>;\n\treadonly ready: Node<ScheduledReadinessReady>;\n\treadonly overdue: Node<ScheduledReadinessOverdue>;\n\treadonly status: Node<ScheduledReadinessStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<ScheduledReadinessViews>;\n}\n\nexport function scheduledReadinessProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly schedules: readonly Node<ScheduledReadinessRequested>[];\n\t\treadonly clocks?: readonly Node<ScheduledReadinessClock>[];\n\t},\n): ScheduledReadinessBundle {\n\tconst name = opts.name ?? \"scheduledReadiness\";\n\tconst clockDeps = opts.clocks ?? [];\n\tconst runtime = graph.node<ScheduledReadinessFact>(\n\t\t[...opts.schedules, ...clockDeps],\n\t\t(ctx) => {\n\t\t\tconst state = ctx.state.get<ScheduledReadinessProjectorState>() ?? initialState();\n\t\t\tforEachDepBatch(ctx, 0, opts.schedules.length, (raw) => {\n\t\t\t\tconst retained = sanitizeSchedule(raw);\n\t\t\t\tif (retained.ok) {\n\t\t\t\t\tconst existing = state.schedules.get(retained.schedule.scheduleId);\n\t\t\t\t\tif (existing === undefined) {\n\t\t\t\t\t\tstate.schedules.set(retained.schedule.scheduleId, retained.schedule);\n\t\t\t\t\t} else if (scheduleIdentity(existing) !== scheduleIdentity(retained.schedule)) {\n\t\t\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\t\t\"scheduled-readiness-schedule-conflict\",\n\t\t\t\t\t\t\t\"Scheduled readiness scheduleId was replayed with conflicting schedule material; the first valid schedule was retained.\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsubjectId: retained.schedule.scheduleId,\n\t\t\t\t\t\t\t\trefs: scheduleSourceRefs(retained.schedule, state.clockSourceRefs),\n\t\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t\texistingReadyAtMs: readinessMs(existing),\n\t\t\t\t\t\t\t\t\tincomingReadyAtMs: readinessMs(retained.schedule),\n\t\t\t\t\t\t\t\t\texistingDeadlineMs: existing.deadlineMs,\n\t\t\t\t\t\t\t\t\tincomingDeadlineMs: retained.schedule.deadlineMs,\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\temitIssue(ctx, state, issue);\n\t\t\t\t\t\temitStatus(ctx, state, {\n\t\t\t\t\t\t\tkind: \"scheduled-readiness-status\",\n\t\t\t\t\t\t\tstatusId: `${retained.schedule.scheduleId}:scheduled-readiness-status:issue`,\n\t\t\t\t\t\t\tscheduleId: retained.schedule.scheduleId,\n\t\t\t\t\t\t\tstate: \"issue\",\n\t\t\t\t\t\t\tsubjectRefs: scheduleSubjectRefs(existing),\n\t\t\t\t\t\t\treadyAtMs: readinessMs(existing),\n\t\t\t\t\t\t\t...(existing.deadlineMs === undefined ? {} : { deadlineMs: existing.deadlineMs }),\n\t\t\t\t\t\t\tnowMs: state.nowMs,\n\t\t\t\t\t\t\tsourceRefs: scheduleSourceRefs(existing, state.clockSourceRefs),\n\t\t\t\t\t\t\tissueCodes: [issue.code],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\temitIssue(ctx, state, retained.issue);\n\t\t\t\t\temitStatus(ctx, state, {\n\t\t\t\t\t\tkind: \"scheduled-readiness-status\",\n\t\t\t\t\t\tstatusId: `${retained.scheduleId}:scheduled-readiness-status:issue`,\n\t\t\t\t\t\tscheduleId: retained.scheduleId,\n\t\t\t\t\t\tstate: \"issue\",\n\t\t\t\t\t\tsourceRefs: retained.sourceRefs,\n\t\t\t\t\t\tissueCodes: [retained.issue.code],\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\tforEachDepBatch(ctx, opts.schedules.length, clockDeps.length, (raw) => {\n\t\t\t\tconst clock = sanitizeClock(raw);\n\t\t\t\tif (clock.ok) {\n\t\t\t\t\tif (state.nowMs !== undefined && clock.clock.nowMs < state.nowMs) {\n\t\t\t\t\t\temitIssue(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\t\"scheduled-readiness-clock-rollback\",\n\t\t\t\t\t\t\t\t\"Scheduled readiness clock facts must be monotonic; rollback was ignored.\",\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsubjectId: clock.clock.clockId,\n\t\t\t\t\t\t\t\t\trefs: clock.clock.sourceRefs,\n\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t\tdetails: { nowMs: clock.clock.nowMs, previousNowMs: state.nowMs },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstate.nowMs = clock.clock.nowMs;\n\t\t\t\t\tstate.clockSourceRefs = clock.clock.sourceRefs;\n\t\t\t\t} else {\n\t\t\t\t\temitIssue(ctx, state, clock.issue);\n\t\t\t\t}\n\t\t\t});\n\t\t\tevaluateSchedules(ctx, state);\n\t\t\tctx.down([[\"DATA\", { kind: \"views\", views: buildViews(state) }]]);\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"scheduledReadinessProjector\", partial: true },\n\t);\n\treturn {\n\t\tpending: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/pending`,\n\t\t\t\"scheduledReadinessPending\",\n\t\t\t(fact) => (fact.kind === \"pending\" ? fact.pending : undefined),\n\t\t),\n\t\tready: projectRuntimeFact(graph, runtime, `${name}/ready`, \"scheduledReadinessReady\", (fact) =>\n\t\t\tfact.kind === \"ready\" ? fact.ready : undefined,\n\t\t),\n\t\toverdue: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/overdue`,\n\t\t\t\"scheduledReadinessOverdue\",\n\t\t\t(fact) => (fact.kind === \"overdue\" ? fact.overdue : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"scheduledReadinessStatus\",\n\t\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t\t),\n\t\tissues: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/issues`,\n\t\t\t\"scheduledReadinessIssues\",\n\t\t\t(fact) => (fact.kind === \"issue\" ? fact.issue : undefined),\n\t\t),\n\t\taudit: projectRuntimeFact(graph, runtime, `${name}/audit`, \"scheduledReadinessAudit\", (fact) =>\n\t\t\tfact.kind === \"audit\" ? fact.audit : undefined,\n\t\t),\n\t\tviews: projectRuntimeFact(graph, runtime, `${name}/views`, \"scheduledReadinessViews\", (fact) =>\n\t\t\tfact.kind === \"views\" ? fact.views : undefined,\n\t\t),\n\t};\n}\n\ntype ScheduledReadinessFact =\n\t| { readonly kind: \"pending\"; readonly pending: ScheduledReadinessPending }\n\t| { readonly kind: \"ready\"; readonly ready: ScheduledReadinessReady }\n\t| { readonly kind: \"overdue\"; readonly overdue: ScheduledReadinessOverdue }\n\t| { readonly kind: \"status\"; readonly status: ScheduledReadinessStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord }\n\t| { readonly kind: \"views\"; readonly views: ScheduledReadinessViews };\n\ninterface ScheduledReadinessProjectorState {\n\tschedules: Map<string, ScheduledReadinessRequested>;\n\tpendingById: Map<string, ScheduledReadinessPending>;\n\treadyById: Map<string, ScheduledReadinessReady>;\n\toverdueById: Map<string, ScheduledReadinessOverdue>;\n\tstatusById: Map<string, ScheduledReadinessStatus>;\n\temittedKeys: Set<string>;\n\tissueKeys: Set<string>;\n\tauditSeq: number;\n\tnowMs: number | undefined;\n\tclockSourceRefs: readonly SourceRef[] | undefined;\n}\n\nfunction initialState(): ScheduledReadinessProjectorState {\n\treturn {\n\t\tschedules: new Map(),\n\t\tpendingById: new Map(),\n\t\treadyById: new Map(),\n\t\toverdueById: new Map(),\n\t\tstatusById: new Map(),\n\t\temittedKeys: new Set(),\n\t\tissueKeys: new Set(),\n\t\tauditSeq: 0,\n\t\tnowMs: undefined,\n\t\tclockSourceRefs: undefined,\n\t};\n}\n\nfunction evaluateSchedules(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n): void {\n\tfor (const schedule of state.schedules.values()) {\n\t\tconst readyAtMs = readinessMs(schedule);\n\t\tconst subjectRefs = scheduleSubjectRefs(schedule);\n\t\tconst sourceRefs = scheduleSourceRefs(schedule, state.clockSourceRefs);\n\t\tconst baseMetadata = sanitizeScheduledReadinessMetadata({\n\t\t\t...(schedule.reason === undefined ? {} : { reason: schedule.reason }),\n\t\t\t...(schedule.metadata ?? {}),\n\t\t});\n\t\tif (state.nowMs === undefined || state.nowMs < readyAtMs) {\n\t\t\tconst pending = Object.freeze({\n\t\t\t\tkind: \"scheduled-readiness-pending\",\n\t\t\t\tscheduleId: schedule.scheduleId,\n\t\t\t\tsubjectRefs,\n\t\t\t\treadyAtMs,\n\t\t\t\t...(schedule.deadlineMs === undefined ? {} : { deadlineMs: schedule.deadlineMs }),\n\t\t\t\t...(state.nowMs === undefined ? {} : { nowMs: state.nowMs }),\n\t\t\t\tsourceRefs,\n\t\t\t\t...(baseMetadata === undefined ? {} : { metadata: baseMetadata }),\n\t\t\t} satisfies ScheduledReadinessPending);\n\t\t\temitPending(ctx, state, pending);\n\t\t\temitStatus(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\tstatusFor(schedule, \"pending\", {\n\t\t\t\t\tsubjectRefs,\n\t\t\t\t\treadyAtMs,\n\t\t\t\t\tsourceRefs,\n\t\t\t\t\tnowMs: state.nowMs,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst ready = Object.freeze({\n\t\t\tkind: \"scheduled-readiness-ready\",\n\t\t\tscheduleId: schedule.scheduleId,\n\t\t\tsubjectRefs,\n\t\t\treadyAtMs,\n\t\t\t...(schedule.deadlineMs === undefined ? {} : { deadlineMs: schedule.deadlineMs }),\n\t\t\tnowMs: state.nowMs,\n\t\t\tsourceRefs,\n\t\t\t...(baseMetadata === undefined ? {} : { metadata: baseMetadata }),\n\t\t} satisfies ScheduledReadinessReady);\n\t\temitReady(ctx, state, ready);\n\t\temitStatus(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\tstatusFor(schedule, \"ready\", {\n\t\t\t\tsubjectRefs,\n\t\t\t\treadyAtMs,\n\t\t\t\tsourceRefs,\n\t\t\t\tnowMs: state.nowMs,\n\t\t\t}),\n\t\t);\n\t\tif (schedule.deadlineMs !== undefined && state.nowMs > schedule.deadlineMs) {\n\t\t\tconst overdue = Object.freeze({\n\t\t\t\tkind: \"scheduled-readiness-overdue\",\n\t\t\t\tscheduleId: schedule.scheduleId,\n\t\t\t\tsubjectRefs,\n\t\t\t\treadyAtMs,\n\t\t\t\tdeadlineMs: schedule.deadlineMs,\n\t\t\t\tnowMs: state.nowMs,\n\t\t\t\tsourceRefs,\n\t\t\t\t...(baseMetadata === undefined ? {} : { metadata: baseMetadata }),\n\t\t\t} satisfies ScheduledReadinessOverdue);\n\t\t\temitOverdue(ctx, state, overdue);\n\t\t\temitStatus(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\tstatusFor(schedule, \"overdue\", {\n\t\t\t\t\tsubjectRefs,\n\t\t\t\t\treadyAtMs,\n\t\t\t\t\tsourceRefs,\n\t\t\t\t\tnowMs: state.nowMs,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction sanitizeSchedule(raw: unknown):\n\t| { readonly ok: true; readonly schedule: ScheduledReadinessRequested }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly scheduleId: string;\n\t\t\treadonly issue: DataIssue;\n\t\t\treadonly sourceRefs?: readonly SourceRef[];\n\t } {\n\tif (!isPlainRecord(raw)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tscheduleId: \"unknown-scheduled-readiness\",\n\t\t\tsourceRefs: [],\n\t\t\tissue: dataIssue(\n\t\t\t\t\"scheduled-readiness-malformed-schedule\",\n\t\t\t\t\"Scheduled readiness requires a stable scheduleId, subjectRefs array, and finite readyAtMs.\",\n\t\t\t\t{ subjectId: \"unknown-scheduled-readiness\", refs: [] },\n\t\t\t),\n\t\t};\n\t}\n\tconst scheduleId =\n\t\ttypeof raw.scheduleId === \"string\" && raw.scheduleId.length > 0\n\t\t\t? raw.scheduleId\n\t\t\t: \"unknown-scheduled-readiness\";\n\tconst refs = sourceRefArray(raw.sourceRefs);\n\tconst hasDeadlineMs = Object.hasOwn(raw, \"deadlineMs\");\n\tconst readyAtMs = finiteNumberOrUndefined(raw.readyAtMs);\n\tconst deadlineMs = finiteNumberOrUndefined(raw.deadlineMs);\n\tif (\n\t\traw.kind !== \"scheduled-readiness-requested\" ||\n\t\ttypeof raw.scheduleId !== \"string\" ||\n\t\traw.scheduleId.length === 0 ||\n\t\treadyAtMs === undefined ||\n\t\t(hasDeadlineMs && deadlineMs === undefined) ||\n\t\traw.subjectRef !== undefined ||\n\t\t!Array.isArray(raw.subjectRefs) ||\n\t\traw.notBeforeMs !== undefined ||\n\t\t(raw.policyRefs !== undefined && !Array.isArray(raw.policyRefs)) ||\n\t\t(raw.sourceRefs !== undefined && !Array.isArray(raw.sourceRefs))\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tscheduleId,\n\t\t\tsourceRefs: refs,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"scheduled-readiness-malformed-schedule\",\n\t\t\t\t\"Scheduled readiness requires a stable scheduleId, subjectRefs array, and finite readyAtMs.\",\n\t\t\t\t{ subjectId: scheduleId, refs },\n\t\t\t),\n\t\t};\n\t}\n\tconst subjectRefs = sourceRefArray(raw.subjectRefs);\n\tconst policyRefs = sourceRefArray(raw.policyRefs);\n\tconst metadata = sanitizeScheduledReadinessMetadata(\n\t\tisPlainRecord(raw.metadata) ? raw.metadata : undefined,\n\t);\n\treturn {\n\t\tok: true,\n\t\tschedule: Object.freeze({\n\t\t\tkind: \"scheduled-readiness-requested\",\n\t\t\tscheduleId: raw.scheduleId,\n\t\t\tsubjectRefs,\n\t\t\treadyAtMs,\n\t\t\t...(deadlineMs === undefined ? {} : { deadlineMs }),\n\t\t\t...(typeof raw.reason === \"string\" ? { reason: raw.reason } : {}),\n\t\t\t...(policyRefs.length === 0 ? {} : { policyRefs }),\n\t\t\tsourceRefs: refs,\n\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t} satisfies ScheduledReadinessRequested),\n\t};\n}\n\nfunction sanitizeClock(\n\traw: unknown,\n):\n\t| { readonly ok: true; readonly clock: ScheduledReadinessClock }\n\t| { readonly ok: false; readonly issue: DataIssue } {\n\tif (!isPlainRecord(raw)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"scheduled-readiness-malformed-clock\",\n\t\t\t\t\"Scheduled readiness clock facts require a stable clockId and finite nowMs.\",\n\t\t\t\t{ subjectId: \"unknown-scheduled-readiness-clock\", refs: [] },\n\t\t\t),\n\t\t};\n\t}\n\tconst refs = sourceRefArray(raw.sourceRefs);\n\tconst nowMs = finiteNumberOrUndefined(raw.nowMs);\n\tif (\n\t\traw.kind !== \"scheduled-readiness-clock\" ||\n\t\ttypeof raw.clockId !== \"string\" ||\n\t\traw.clockId.length === 0 ||\n\t\tnowMs === undefined ||\n\t\t(raw.sourceRefs !== undefined && !Array.isArray(raw.sourceRefs))\n\t) {\n\t\tconst clockSubjectId =\n\t\t\ttypeof raw.clockId === \"string\" && raw.clockId.length > 0\n\t\t\t\t? raw.clockId\n\t\t\t\t: \"unknown-scheduled-readiness-clock\";\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissue: dataIssue(\n\t\t\t\t\"scheduled-readiness-malformed-clock\",\n\t\t\t\t\"Scheduled readiness clock facts require a stable clockId and finite nowMs.\",\n\t\t\t\t{ subjectId: clockSubjectId, refs },\n\t\t\t),\n\t\t};\n\t}\n\tconst metadata = sanitizeScheduledReadinessMetadata(\n\t\tisPlainRecord(raw.metadata) ? raw.metadata : undefined,\n\t);\n\treturn {\n\t\tok: true,\n\t\tclock: Object.freeze({\n\t\t\tkind: \"scheduled-readiness-clock\",\n\t\t\tclockId: raw.clockId,\n\t\t\tnowMs,\n\t\t\tsourceRefs: refs,\n\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t} satisfies ScheduledReadinessClock),\n\t};\n}\n\nfunction emitPending(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\tpending: ScheduledReadinessPending,\n): void {\n\tstate.pendingById.set(pending.scheduleId, pending);\n\tconst key = `pending:${pending.scheduleId}`;\n\tif (state.emittedKeys.has(key)) return;\n\tstate.emittedKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"pending\", pending }]]);\n}\n\nfunction emitReady(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\tready: ScheduledReadinessReady,\n): void {\n\tconst key = `ready:${ready.scheduleId}`;\n\tif (state.emittedKeys.has(key)) return;\n\tstate.emittedKeys.add(key);\n\tstate.readyById.set(ready.scheduleId, ready);\n\tstate.pendingById.delete(ready.scheduleId);\n\temitAudit(ctx, state, \"scheduled-readiness-ready\", {\n\t\tsubjectId: ready.scheduleId,\n\t\tsourceRefs: ready.sourceRefs,\n\t\tmetadata: { nowMs: ready.nowMs, readyAtMs: ready.readyAtMs },\n\t});\n\tctx.down([[\"DATA\", { kind: \"ready\", ready }]]);\n}\n\nfunction emitOverdue(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\toverdue: ScheduledReadinessOverdue,\n): void {\n\tconst key = `overdue:${overdue.scheduleId}`;\n\tif (state.emittedKeys.has(key)) return;\n\tstate.emittedKeys.add(key);\n\tstate.overdueById.set(overdue.scheduleId, overdue);\n\temitAudit(ctx, state, \"scheduled-readiness-overdue\", {\n\t\tsubjectId: overdue.scheduleId,\n\t\tsourceRefs: overdue.sourceRefs,\n\t\tmetadata: {\n\t\t\tnowMs: overdue.nowMs,\n\t\t\treadyAtMs: overdue.readyAtMs,\n\t\t\tdeadlineMs: overdue.deadlineMs,\n\t\t},\n\t});\n\tctx.down([[\"DATA\", { kind: \"overdue\", overdue }]]);\n}\n\nfunction emitStatus(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\tstatus: ScheduledReadinessStatus,\n): void {\n\tstate.statusById.set(status.scheduleId, status);\n\tconst key = `status:${stableJsonStringify(status)}`;\n\tif (state.emittedKeys.has(key)) return;\n\tstate.emittedKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"status\", status }]]);\n}\n\nfunction emitIssue(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\tissue: DataIssue,\n): void {\n\tconst key = `${issue.code}:${issue.subjectId ?? \"\"}:${JSON.stringify(issue.details ?? {})}`;\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tctx.down([[\"DATA\", { kind: \"issue\", issue }]]);\n}\n\nfunction emitAudit(\n\tctx: { down: (msgs: readonly [\"DATA\", ScheduledReadinessFact][]) => void },\n\tstate: ScheduledReadinessProjectorState,\n\tkind: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\treadonly metadata?: Record<string, unknown>;\n\t} = {},\n): void {\n\tstate.auditSeq += 1;\n\tconst metadata = sanitizeGraphVisibleRecord(opts.metadata);\n\tctx.down([\n\t\t[\n\t\t\t\"DATA\",\n\t\t\t{\n\t\t\t\tkind: \"audit\",\n\t\t\t\taudit: Object.freeze({\n\t\t\t\t\tid: `scheduled-readiness-audit-${state.auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\t...(opts.subjectId === undefined ? {} : { subjectId: opts.subjectId }),\n\t\t\t\t\t...(opts.sourceRefs === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { sourceRefs: canonicalPublicSourceRefs(opts.sourceRefs) }),\n\t\t\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t\t\t} satisfies AgentRuntimeAuditRecord),\n\t\t\t},\n\t\t],\n\t]);\n}\n\nfunction statusFor(\n\tschedule: ScheduledReadinessRequested,\n\tstate: ScheduledReadinessStatusState,\n\topts: {\n\t\treadonly subjectRefs: readonly SourceRef[];\n\t\treadonly readyAtMs: number;\n\t\treadonly sourceRefs: readonly SourceRef[];\n\t\treadonly nowMs?: number;\n\t},\n): ScheduledReadinessStatus {\n\tconst metadata = sanitizeGraphVisibleRecord({\n\t\t...(schedule.reason === undefined ? {} : { reason: schedule.reason }),\n\t});\n\treturn Object.freeze({\n\t\tkind: \"scheduled-readiness-status\",\n\t\tstatusId: `${schedule.scheduleId}:scheduled-readiness-status:${state}`,\n\t\tscheduleId: schedule.scheduleId,\n\t\tstate,\n\t\tsubjectRefs: opts.subjectRefs,\n\t\treadyAtMs: opts.readyAtMs,\n\t\t...(schedule.deadlineMs === undefined ? {} : { deadlineMs: schedule.deadlineMs }),\n\t\t...(opts.nowMs === undefined ? {} : { nowMs: opts.nowMs }),\n\t\tsourceRefs: opts.sourceRefs,\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t} satisfies ScheduledReadinessStatus);\n}\n\nfunction readinessMs(schedule: ScheduledReadinessRequested): number {\n\treturn schedule.readyAtMs;\n}\n\nfunction scheduleIdentity(schedule: ScheduledReadinessRequested): string {\n\treturn stableJsonStringify({\n\t\tscheduleId: schedule.scheduleId,\n\t\tsubjectRefs: schedule.subjectRefs,\n\t\treadyAtMs: schedule.readyAtMs,\n\t\tdeadlineMs: schedule.deadlineMs,\n\t\treason: schedule.reason,\n\t\tpolicyRefs: schedule.policyRefs,\n\t\tsourceRefs: schedule.sourceRefs,\n\t\tmetadata: schedule.metadata,\n\t});\n}\n\nfunction scheduleSubjectRefs(schedule: ScheduledReadinessRequested): readonly SourceRef[] {\n\treturn canonicalPublicSourceRefs(uniqueSourceRefs(schedule.subjectRefs));\n}\n\nfunction scheduleSourceRefs(\n\tschedule: ScheduledReadinessRequested,\n\tclockSourceRefs: readonly SourceRef[] | undefined,\n): readonly SourceRef[] {\n\treturn canonicalPublicSourceRefs(\n\t\tuniqueSourceRefs([\n\t\t\tref(\"scheduled-readiness\", schedule.scheduleId),\n\t\t\t...(schedule.sourceRefs ?? []),\n\t\t\t...(schedule.policyRefs ?? []),\n\t\t\t...(clockSourceRefs ?? []),\n\t\t]),\n\t);\n}\n\nfunction sanitizeScheduledReadinessMetadata(\n\tvalue: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tconst filtered = omitRuntimeMetadata(value);\n\treturn sanitizeGraphVisibleRecord(filtered);\n}\n\nfunction omitRuntimeMetadata(value: unknown): Record<string, unknown> | undefined {\n\tif (!isPlainRecord(value)) return undefined;\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tif (isRuntimeMetadataKey(key)) continue;\n\t\tconst filteredChild = Array.isArray(child)\n\t\t\t? child.map((entry) => (isPlainRecord(entry) ? omitRuntimeMetadata(entry) : entry))\n\t\t\t: isPlainRecord(child)\n\t\t\t\t? omitRuntimeMetadata(child)\n\t\t\t\t: child;\n\t\tif (filteredChild !== undefined) out[key] = filteredChild;\n\t}\n\treturn Object.keys(out).length === 0 ? undefined : out;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction finiteNumberOrUndefined(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction sourceRefArray(value: unknown): readonly SourceRef[] {\n\tif (!Array.isArray(value)) return [];\n\treturn canonicalPublicSourceRefs(\n\t\tvalue.flatMap((entry) => {\n\t\t\tconst sourceRef = sourceRefOrUndefined(entry);\n\t\t\treturn sourceRef === undefined ? [] : [sourceRef];\n\t\t}),\n\t);\n}\n\nfunction sourceRefOrUndefined(value: unknown): SourceRef | undefined {\n\tif (!isPlainRecord(value)) return undefined;\n\tif (typeof value.kind !== \"string\" || value.kind.length === 0) return undefined;\n\tif (typeof value.id !== \"string\" || value.id.length === 0) return undefined;\n\treturn isPlainRecord(value.metadata)\n\t\t? { kind: value.kind, id: value.id, metadata: value.metadata }\n\t\t: { kind: value.kind, id: value.id };\n}\n\nfunction isRuntimeMetadataKey(key: string): boolean {\n\treturn /^(apiKey|api_key|secret|client|transport|subprocess|sdk|oauth|credential|credentials|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|token|password|passphrase|authorization|authHeader|auth_header|bearer|privateKey|private_key|sessionCookie|session_cookie|cookie|stdout|stderr|stack|stackTrace|stack_trace|providerRaw|provider_raw|rawResponse|raw_response|rawResponseBody|raw_response_body|diff|patch|fileContents|file_contents|binary|media)$/i.test(\n\t\tkey,\n\t);\n}\n\nfunction buildViews(state: ScheduledReadinessProjectorState): ScheduledReadinessViews {\n\treturn Object.freeze({\n\t\tschedulesById: new Map(state.schedules),\n\t\tpendingById: new Map(state.pendingById),\n\t\treadyById: new Map(state.readyById),\n\t\toverdueById: new Map(state.overdueById),\n\t\tstatusById: new Map(state.statusById),\n\t\t...(state.nowMs === undefined ? {} : { nowMs: state.nowMs }),\n\t});\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;;;ACuCO,IAAM,YAA2B,OAAO,OAAO,EAAE,MAAM,OAAO,CAAC;AAE/D,SAAS,YAAY,cAAc,GAAG,UAAyB,WAAwB;AAC7F,MAAI,CAAC,OAAO,UAAU,WAAW,KAAK,eAAe,GAAG;AACvD,UAAM,IAAI,WAAW,qDAAqD;AAAA,EAC3E;AACA,SAAO,OAAO,OAAO,EAAE,aAAa,QAAQ,CAAC;AAC9C;AAEO,SAAS,YAAY,QAAqB,eAAgC;AAChF,SAAO,gBAAgB,OAAO;AAC/B;AAEO,SAAS,iBAAiB,QAAqB,aAAyC;AAC9F,MAAI,CAAC,OAAO,UAAU,WAAW,KAAK,eAAe,KAAK,cA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CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;AAAA,EAC3D,CAAC;AACF;","names":["out","request","source","issue","resolutions","catalog","inputs","map","emitIssue","emitStatus","emitProposal","state","source","errorMessage","out","source","source","allowed","status","emitIssue","emitStatus","isPlainRecord","emitAudit","sourceRefOrUndefined"]}
|