@graphrefly/ts 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions-types-CSC3NMDl.d.ts +657 -0
- package/dist/actions-types-wl9Mgkmr.d.cts +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-DZTJ3C-p.d.cts → agent-runtime-types-core-CaXfKNtY.d.cts} +171 -320
- package/dist/{agent-runtime-BesGDZcB.d.ts → agent-runtime-types-core-hU299uIC.d.ts} +171 -320
- package/dist/agent-runtime-types-tool-BEpSINol.d.ts +695 -0
- package/dist/agent-runtime-types-tool-DninPEzk.d.cts +695 -0
- package/dist/agentic-memory-retention-BmGX368S.d.ts +14 -0
- package/dist/agentic-memory-retention-Ih1qhX9Z.d.cts +14 -0
- package/dist/{agentic-memory-BmRCvh0d.d.ts → agentic-memory-types-CVSUS6XR.d.ts} +13 -57
- package/dist/{agentic-memory-DfuVZ-lY.d.cts → agentic-memory-types-FnnYlVUs.d.cts} +13 -57
- package/dist/{capability-admission-g0mn9hpq.d.ts → capability-admission-BW2CziT6.d.ts} +3 -3
- package/dist/{capability-admission-B0BzqAm5.d.cts → capability-admission-lwSecxXs.d.cts} +3 -3
- package/dist/chunk-2KUAG2GZ.js +9693 -0
- package/dist/chunk-2KUAG2GZ.js.map +1 -0
- package/dist/chunk-2NJP6GO4.js +1320 -0
- package/dist/chunk-2NJP6GO4.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-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-IXZBUWSP.js → chunk-7HZRJMN6.js} +2 -2
- package/dist/{chunk-SS2A464I.js → chunk-CJIFGJQG.js} +3 -3
- package/dist/{chunk-V7CIJE4B.js → chunk-CX6B6PO2.js} +92 -9
- package/dist/chunk-CX6B6PO2.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-HKK2JD7Z.js → chunk-ECURQ3HD.js} +12 -125
- package/dist/chunk-ECURQ3HD.js.map +1 -0
- package/dist/{chunk-3JR3EDB2.js → chunk-EOKT4QFF.js} +121 -115
- package/dist/chunk-EOKT4QFF.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-H75VXTGT.js → chunk-L6LDXRWE.js} +3 -3
- package/dist/{chunk-H75VXTGT.js.map → chunk-L6LDXRWE.js.map} +1 -1
- package/dist/{chunk-YXMZ2N6J.js → chunk-M7J6Z4IJ.js} +1071 -1025
- package/dist/chunk-M7J6Z4IJ.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-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-XKXWK2KP.js → chunk-SHZDP2MQ.js} +1157 -1021
- package/dist/chunk-SHZDP2MQ.js.map +1 -0
- package/dist/{chunk-CZNV3VXM.js → chunk-SIDJO2T4.js} +11 -11
- package/dist/chunk-STXRMPW4.js +4131 -0
- package/dist/chunk-STXRMPW4.js.map +1 -0
- package/dist/{chunk-2747WN4Y.js → chunk-TPND5MJS.js} +3 -3
- package/dist/chunk-TQPCAIQI.js +612 -0
- package/dist/chunk-TQPCAIQI.js.map +1 -0
- package/dist/{chunk-43BKLFZU.js → chunk-YDWBXXQZ.js} +10 -10
- 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 +1 -1
- package/dist/core/index.d.ts +1 -1
- 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-BpyJuWkw.d.ts → describe-B_A5fbXH.d.ts} +1 -1
- package/dist/{describe-DYMw_l1C.d.cts → describe-CQRrkv-Q.d.cts} +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-CWK3HLPB.d.cts} +133 -131
- package/dist/{graph-D-1-SQeC.d.ts → graph-ho5sotHP.d.ts} +133 -131
- package/dist/{index-Bmxeu0nK.d.ts → index-CQWcE0Dw.d.ts} +18 -4
- package/dist/{index-72VZC0-E.d.cts → index-DHA1i67c.d.cts} +18 -4
- 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-C0mAvWU1.d.cts +164 -0
- package/dist/measurements-OMpCeBwh.d.ts +164 -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-C9uMYz3i.d.ts +200 -0
- package/dist/process-types-h3uRlzDc.d.cts +200 -0
- package/dist/{reactive-collection-DNV0-gFi.d.cts → reactive-collection-B9R0Bl1P.d.cts} +4 -34
- package/dist/{reactive-collection-BAmfrGjd.d.ts → reactive-collection-BXFrH0U2.d.ts} +4 -34
- package/dist/{reactive-collection-storage-BNEldDyi.d.cts → reactive-collection-storage-BLGv8Xp8.d.cts} +5 -5
- package/dist/{reactive-collection-storage-YZsAQsWK.d.ts → reactive-collection-storage-a4zD3665.d.ts} +5 -5
- package/dist/{reactive-map-DRD1LJ2H.d.cts → reactive-map-C_8sOfdS.d.cts} +3 -2
- package/dist/{reactive-map-EsDiCmJk.d.ts → reactive-map-jle5dnok.d.ts} +3 -2
- package/dist/render/index.d.cts +2 -2
- package/dist/render/index.d.ts +2 -2
- package/dist/scheduled-readiness-5rwQlyjV.d.ts +91 -0
- package/dist/scheduled-readiness-DpRY8jI0.d.cts +91 -0
- package/dist/semantic-memory-graph-C2ZUwIlq.d.ts +30 -0
- package/dist/semantic-memory-graph-DlZBD_Eu.d.cts +30 -0
- package/dist/{semantic-memory-graph-DKuNzuWw.d.cts → semantic-memory-graph-types-BvzdqmkY.d.cts} +2 -28
- package/dist/{semantic-memory-graph-uwbwJdhe.d.ts → semantic-memory-graph-types-Ci-OtahO.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 +4 -4
- package/dist/sources/browser.d.ts +4 -4
- package/dist/sources/browser.js +4 -4
- 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-BmtEs9mG.d.ts} +1 -1
- package/dist/{store-CNJwmT-h.d.cts → store-PAAsYvML.d.cts} +1 -1
- package/dist/types-BRNKoFHj.d.ts +357 -0
- package/dist/{types-CcPIn7sy.d.cts → types-BS6CyR-x.d.cts} +27 -108
- package/dist/types-BWK2ay3e.d.cts +457 -0
- package/dist/types-BXKSAoE1.d.cts +357 -0
- package/dist/types-BaPpZItj.d.ts +457 -0
- package/dist/types-BhveCMg5.d.cts +274 -0
- package/dist/{types-BsJvElYZ.d.ts → types-C9NOgNJw.d.ts} +27 -108
- package/dist/types-CTsQ8Ww4.d.ts +274 -0
- package/dist/types-DL_05n2M.d.ts +34 -0
- package/dist/types-XDoqxYO9.d.cts +34 -0
- package/dist/{work-item-runtime-C3M79vE9.d.ts → work-item-runtime-types-BqtWnSCS.d.ts} +3 -93
- package/dist/{work-item-runtime-qaVgsL0T.d.cts → work-item-runtime-types-CHO03AKh.d.cts} +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 +603 -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-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-Z2ANQ6JW.js.map → chunk-4Q77MMJY.js.map} +0 -0
- /package/dist/{chunk-IXZBUWSP.js.map → chunk-7HZRJMN6.js.map} +0 -0
- /package/dist/{chunk-SS2A464I.js.map → chunk-CJIFGJQG.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-VTHLCFN4.js.map → chunk-RAHNUYA5.js.map} +0 -0
- /package/dist/{chunk-CZNV3VXM.js.map → chunk-SIDJO2T4.js.map} +0 -0
- /package/dist/{chunk-2747WN4Y.js.map → chunk-TPND5MJS.js.map} +0 -0
- /package/dist/{chunk-43BKLFZU.js.map → chunk-YDWBXXQZ.js.map} +0 -0
- /package/dist/{chunk-6PHB5CJS.js.map → chunk-ZLFRB6FI.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/executors/tool-provider.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/orchestration/agent-runtime-common.ts","../../src/orchestration/agent-runtime-executor-outcome.ts","../../src/orchestration/agent-runtime-outcome-view.ts","../../src/orchestration/agent-runtime-tool-provider-policy.ts","../../src/orchestration/agent-runtime-tool-provider-input.ts","../../src/graph/policies/collection.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/orchestration/agent-runtime-adapter-retention.ts","../../src/orchestration/agent-runtime-adapter-run.ts","../../src/orchestration/agent-runtime-adapter-runtime-execute.ts","../../src/orchestration/agent-runtime-adapter-runtime-retention-gaps.ts","../../src/orchestration/agent-runtime-adapter-runtime-state.ts","../../src/orchestration/agent-runtime-adapter-runtime.ts"],"sourcesContent":["/**\n * Optional Layer C tool-provider execution recipe (D283/D359-D362).\n *\n * This module composes the provider-neutral catalog/policy/input projectors\n * with the runtime-private adapter binding boundary. It does not provide\n * concrete bash, filesystem, URL, MCP, CLI, Composio, or SDK bindings.\n */\n\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport { executorOutcomeViewProjector } from \"../orchestration/agent-runtime-outcome-view.js\";\nimport { toolProviderAdapterInputProjector } from \"../orchestration/agent-runtime-tool-provider-input.js\";\nimport { toolProviderPolicyResolutionProjector } from \"../orchestration/agent-runtime-tool-provider-policy.js\";\nimport type { AgentRuntimeAuditRecord } from \"../orchestration/agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestFact,\n\tAgentRequestStatusChanged,\n\tExecutorOutcome,\n\tExecutorRoute,\n} from \"../orchestration/agent-runtime-types-core.js\";\nimport type {\n\tExecutorOutcomeViewBundle,\n\tExecutorOutcomeViewPolicy,\n\tToolProviderAdapterInputBundle,\n\tToolProviderAdapterRunRequested,\n\tToolProviderCatalog,\n\tToolProviderPolicyResolutionBundle,\n} from \"../orchestration/agent-runtime-types-tool.js\";\nimport {\n\tattachToolProviderAdapterRuntime,\n\ttype ToolProviderAdapterBinding,\n\ttype ToolProviderAdapterRuntimeHandle,\n\ttype ToolProviderAdapterRuntimeRetentionPolicy,\n\ttype ToolProviderPublicTextPolicy,\n} from \"./tool-provider-runtime.js\";\n\nexport interface ToolProviderExecutionRecipeOptions<TArguments = unknown, TResult = unknown> {\n\treadonly name?: string;\n\treadonly requestFacts: Node<AgentRequestFact>;\n\treadonly executorRoutes?: readonly Node<ExecutorRoute>[];\n\treadonly toolProviderCatalogs?: readonly Node<ToolProviderCatalog>[];\n\treadonly catalogs?: readonly ToolProviderCatalog[];\n\treadonly bindings:\n\t\t| readonly ToolProviderAdapterBinding<TArguments, TResult>[]\n\t\t| ReadonlyMap<string, ToolProviderAdapterBinding<TArguments, TResult>>;\n\treadonly runRequests?: readonly Node<ToolProviderAdapterRunRequested>[];\n\treadonly autoRunReadyInputs?: boolean;\n\treadonly retention?: ToolProviderAdapterRuntimeRetentionPolicy;\n\treadonly now?: () => number;\n\treadonly publicText?: ToolProviderPublicTextPolicy;\n\treadonly outcomeViewPolicy?: ExecutorOutcomeViewPolicy;\n}\n\nexport interface ToolProviderExecutionRecipeBundle {\n\treadonly catalogs?: Node<ToolProviderCatalog>;\n\treadonly policy: ToolProviderPolicyResolutionBundle;\n\treadonly adapterInputs: ToolProviderAdapterInputBundle;\n\treadonly runtime: ToolProviderAdapterRuntimeHandle;\n\treadonly outcomeViews: ExecutorOutcomeViewBundle;\n\treadonly outcomes: Node<ExecutorOutcome>;\n\treadonly status: Node<AgentRequestStatusChanged>;\n\treadonly issues: {\n\t\treadonly policy: Node<DataIssue>;\n\t\treadonly adapterInputs: Node<DataIssue>;\n\t\treadonly runtime: Node<DataIssue>;\n\t\treadonly outcomeViews: Node<DataIssue>;\n\t};\n\treadonly audit: {\n\t\treadonly policy: Node<AgentRuntimeAuditRecord>;\n\t\treadonly adapterInputs: Node<AgentRuntimeAuditRecord>;\n\t\treadonly runtime: Node<AgentRuntimeAuditRecord>;\n\t\treadonly outcomeViews: Node<AgentRuntimeAuditRecord>;\n\t};\n\tdispose(): void;\n}\n\nexport function toolProviderExecutionRecipe<TArguments = unknown, TResult = unknown>(\n\tgraph: Graph,\n\topts: ToolProviderExecutionRecipeOptions<TArguments, TResult>,\n): ToolProviderExecutionRecipeBundle {\n\tconst name = opts.name ?? \"toolProviderExecution\";\n\tconst staticCatalogs = staticToolProviderCatalogNode(graph, name, opts.catalogs);\n\tconst catalogDeps = [\n\t\t...(staticCatalogs === undefined ? [] : [staticCatalogs]),\n\t\t...(opts.toolProviderCatalogs ?? []),\n\t];\n\tconst policy = toolProviderPolicyResolutionProjector(graph, {\n\t\tname: `${name}/policy`,\n\t\trequestFacts: opts.requestFacts,\n\t\texecutorRoutes: opts.executorRoutes,\n\t\ttoolProviderCatalogs: catalogDeps,\n\t});\n\tconst adapterInputs = toolProviderAdapterInputProjector(graph, {\n\t\tname: `${name}/adapterInput`,\n\t\trequestFacts: opts.requestFacts,\n\t\texecutorRoutes: opts.executorRoutes,\n\t\ttoolProviderCatalogs: catalogDeps,\n\t\tpolicyResolutions: [policy.resolutions],\n\t});\n\tconst runtime = attachToolProviderAdapterRuntime(graph, {\n\t\tname: `${name}/runtime`,\n\t\tinputs: adapterInputs.inputs,\n\t\trunRequests: opts.runRequests,\n\t\tbindings: opts.bindings,\n\t\tautoRunReadyInputs: opts.autoRunReadyInputs,\n\t\tretention: opts.retention,\n\t\tnow: opts.now,\n\t\tpublicText: opts.publicText,\n\t});\n\tconst outcomeViews = executorOutcomeViewProjector(graph, {\n\t\tname: `${name}/outcomeView`,\n\t\toutcomes: runtime.outcomes,\n\t\tpolicy: opts.outcomeViewPolicy,\n\t});\n\treturn {\n\t\t...(staticCatalogs === undefined ? {} : { catalogs: staticCatalogs }),\n\t\tpolicy,\n\t\tadapterInputs,\n\t\truntime,\n\t\toutcomeViews,\n\t\toutcomes: runtime.outcomes,\n\t\tstatus: runtime.status,\n\t\tissues: {\n\t\t\tpolicy: policy.issues,\n\t\t\tadapterInputs: adapterInputs.issues,\n\t\t\truntime: runtime.issues,\n\t\t\toutcomeViews: outcomeViews.issues,\n\t\t},\n\t\taudit: {\n\t\t\tpolicy: policy.audit,\n\t\t\tadapterInputs: adapterInputs.audit,\n\t\t\truntime: runtime.audit,\n\t\t\toutcomeViews: outcomeViews.audit,\n\t\t},\n\t\tdispose: () => runtime.dispose(),\n\t};\n}\n\nfunction staticToolProviderCatalogNode(\n\tgraph: Graph,\n\tname: string,\n\tcatalogs: readonly ToolProviderCatalog[] | undefined,\n): Node<ToolProviderCatalog> | undefined {\n\tif (catalogs === undefined || catalogs.length === 0) return undefined;\n\treturn graph.producer<ToolProviderCatalog>(\n\t\t(ctx) => {\n\t\t\tctx.down(catalogs.map((catalog) => [\"DATA\", catalog] as const));\n\t\t},\n\t\t{ name: `${name}/catalogs`, factory: \"toolProviderExecutionCatalogs\" },\n\t);\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","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 { 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 { 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\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","/**\n * Internal graph-layer policy helpers (D70).\n *\n * This module is deliberately NOT exported from the package index. It centralizes policy plumbing\n * shared by collection structures while each structure still owns backend mutation + delta emission\n * in its apply/mutation path (D60/D61/D68/D69).\n */\n\nimport { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport type { Node } from \"../../node/node.js\";\n\nexport type PolicyOpt<T> = T | Node<T>;\n\nexport interface PolicyReader<T> {\n\treadonly index: number;\n\tread(ctx: Ctx, current: T | undefined): T | undefined;\n}\n\nexport class PolicyInputs {\n\treadonly deps: Node<unknown>[];\n\n\tconstructor(initial: readonly Node<unknown>[] = []) {\n\t\tthis.deps = [...initial];\n\t}\n\n\tadd<T>(node: Node<T> | undefined): PolicyReader<T> {\n\t\tif (node === undefined) return missingPolicyReader<T>();\n\t\tconst index = this.deps.push(node as Node<unknown>) - 1;\n\t\treturn policyReader<T>(index);\n\t}\n}\n\nfunction missingPolicyReader<T>(): PolicyReader<T> {\n\treturn {\n\t\tindex: -1,\n\t\tread: (_ctx, current) => current,\n\t};\n}\n\nfunction policyReader<T>(index: number): PolicyReader<T> {\n\treturn {\n\t\tindex,\n\t\tread(ctx, current) {\n\t\t\tconst latest = depLatest(ctx, index);\n\t\t\treturn latest === undefined ? current : (latest as T);\n\t\t},\n\t};\n}\n\nexport interface KeyOrderPolicy<K> {\n\tkeys(): Iterable<K>;\n}\n\nexport function lruKeys<K>(keys: Iterable<K>): KeyOrderPolicy<K> {\n\treturn {\n\t\tkeys: () => keys,\n\t};\n}\n\nexport interface CapacityConfig {\n\treadonly maxSize?: number;\n}\n\nexport interface SizedCapacityConfig extends CapacityConfig {\n\treadonly size: number;\n}\n\nexport function trimHeadOverflow<T>(items: T[], config: CapacityConfig): T[];\nexport function trimHeadOverflow<T>(items: Iterable<T>, config: SizedCapacityConfig): T[];\nexport function trimHeadOverflow<T>(\n\titems: T[] | Iterable<T>,\n\tconfig: CapacityConfig | SizedCapacityConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 1)\n\t\tthrow new RangeError(`maxSize must be a positive integer (got ${maxSize})`);\n\n\tconst size = \"size\" in config ? config.size : Array.isArray(items) ? items.length : undefined;\n\tif (size === undefined) throw new Error(\"trimHeadOverflow requires size for non-array iterables\");\n\tconst overflow = size - maxSize;\n\tif (overflow <= 0) return [];\n\n\tif (Array.isArray(items) && !(\"size\" in config)) return items.splice(0, overflow);\n\n\tconst victims: T[] = [];\n\tfor (const item of items) {\n\t\tvictims.push(item);\n\t\tif (victims.length === overflow) break;\n\t}\n\treturn victims;\n}\n\nexport interface DeadlineEntry<K> {\n\treadonly key: K;\n\treadonly expiresAt: number;\n}\n\nexport interface DeadlinePolicy<K> {\n\treadonly size: number;\n\tpush(item: DeadlineEntry<K>): void;\n\tpeek(): DeadlineEntry<K> | undefined;\n\tpop(): DeadlineEntry<K> | undefined;\n}\n\nexport function deadlines<K>(): DeadlinePolicy<K> {\n\treturn new MinDeadlineHeap<K>();\n}\n\nclass MinDeadlineHeap<K> implements DeadlinePolicy<K> {\n\tprivate readonly items: DeadlineEntry<K>[] = [];\n\n\tget size(): number {\n\t\treturn this.items.length;\n\t}\n\n\tpush(item: DeadlineEntry<K>): void {\n\t\tthis.items.push(item);\n\t\tthis.up(this.items.length - 1);\n\t}\n\n\tpeek(): DeadlineEntry<K> | undefined {\n\t\treturn this.items[0];\n\t}\n\n\tpop(): DeadlineEntry<K> | undefined {\n\t\tconst top = this.items[0];\n\t\tconst last = this.items.pop();\n\t\tif (top !== undefined && last !== undefined && this.items.length > 0) {\n\t\t\tthis.items[0] = last;\n\t\t\tthis.down(0);\n\t\t}\n\t\treturn top;\n\t}\n\n\tprivate up(i: number): void {\n\t\twhile (i > 0) {\n\t\t\tconst p = (i - 1) >> 1;\n\t\t\tif (\n\t\t\t\t(this.items[p] as DeadlineEntry<K>).expiresAt <=\n\t\t\t\t(this.items[i] as DeadlineEntry<K>).expiresAt\n\t\t\t)\n\t\t\t\treturn;\n\t\t\t[this.items[p], this.items[i]] = [\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t\tthis.items[p] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = p;\n\t\t}\n\t}\n\n\tprivate down(i: number): void {\n\t\tfor (;;) {\n\t\t\tconst left = i * 2 + 1;\n\t\t\tconst right = left + 1;\n\t\t\tlet smallest = i;\n\t\t\tif (left < this.items.length && this.expiresAt(left) < this.expiresAt(smallest))\n\t\t\t\tsmallest = left;\n\t\t\tif (right < this.items.length && this.expiresAt(right) < this.expiresAt(smallest))\n\t\t\t\tsmallest = right;\n\t\t\tif (smallest === i) return;\n\t\t\t[this.items[i], this.items[smallest]] = [\n\t\t\t\tthis.items[smallest] as DeadlineEntry<K>,\n\t\t\t\tthis.items[i] as DeadlineEntry<K>,\n\t\t\t];\n\t\t\ti = smallest;\n\t\t}\n\t}\n\n\tprivate expiresAt(i: number): number {\n\t\treturn (this.items[i] as DeadlineEntry<K>).expiresAt;\n\t}\n}\n\nexport interface ScoredEntry<T> {\n\treadonly entry: T;\n\treadonly score: number;\n}\n\nexport interface RetentionSelectionConfig {\n\treadonly maxSize?: number;\n}\n\nexport function selectRetentionVictims<T>(\n\tscoredEntries: readonly ScoredEntry<T>[],\n\tconfig: RetentionSelectionConfig,\n): T[] {\n\tconst { maxSize } = config;\n\tif (maxSize === undefined) return [];\n\tif (!Number.isInteger(maxSize) || maxSize < 0)\n\t\tthrow new RangeError(`retention maxSize must be a non-negative integer (got ${maxSize})`);\n\tconst overflow = scoredEntries.length - maxSize;\n\tif (overflow <= 0) return [];\n\n\treturn scoredEntries\n\t\t.map((item, index) => {\n\t\t\tif (!Number.isFinite(item.score))\n\t\t\t\tthrow new RangeError(`retention score must be finite (got ${item.score})`);\n\t\t\treturn { ...item, index };\n\t\t})\n\t\t.sort((a, b) => a.score - b.score || a.index - b.index)\n\t\t.slice(0, overflow)\n\t\t.map((item) => item.entry);\n}\n","/**\n * 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/** 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 * 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\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 */\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","import type { Ctx } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\tPolicyInputs,\n\ttype PolicyReader,\n\tselectRetentionVictims,\n\ttrimHeadOverflow,\n} from \"../graph/policies/collection.js\";\nimport type { CapacityPolicy, ReactiveOpt } from \"../graph/policies/types.js\";\nimport { Node } from \"../node/node.js\";\nimport {\n\tcanonicalPublicSourceRefs,\n\tdataIssue,\n\tisPlainRecord,\n\tpublicMaterialForbiddenKeys,\n\tstableStringHash,\n} from \"./agent-runtime-common.js\";\nimport type { SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterExecutionRetentionEntry,\n\tToolProviderAdapterInput,\n\tToolProviderAdapterInputRetentionEntry,\n\tToolProviderAdapterRunIssueRetentionEntry,\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunRequestRetentionEntry,\n\tToolProviderAdapterRunStatus,\n\tToolProviderAdapterRunStatusRetentionEntry,\n\tToolProviderAdapterRuntimeIndexRetentionPolicy,\n\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\tToolProviderAdapterRuntimeRetentionIndex,\n\tToolProviderAdapterRuntimeRetentionPolicy,\n} from \"./agent-runtime-types-tool.js\";\n\nexport type RuntimeRetentionMode = \"fifo\" | \"score\";\n\nexport interface RuntimeRetentionIndexConfig {\n\treadonly maxSize?: number;\n\treadonly mode: RuntimeRetentionMode;\n}\n\nexport interface RuntimeRetentionPolicyFact {\n\treadonly kind: \"tool-provider-adapter-runtime-retention-policy\";\n\treadonly policies: ReadonlyMap<\n\t\tToolProviderAdapterRuntimeRetentionIndex,\n\t\tRuntimeRetentionIndexConfig\n\t>;\n\treadonly issues?: readonly DataIssue[];\n}\n\nexport interface RuntimeRetentionPolicyReaders {\n\treadonly inputs: PolicyInputs;\n\treadonly readers: ReadonlyMap<ToolProviderAdapterRuntimeRetentionIndex, PolicyReader<number>>;\n\treadonly statics: ReadonlyMap<ToolProviderAdapterRuntimeRetentionIndex, number | undefined>;\n}\n\nexport type EffectiveRuntimeRetentionPolicy = Partial<{\n\treadonly adapterInputs: RuntimeRetentionIndexConfig;\n\treadonly runRequests: RuntimeRetentionIndexConfig;\n\treadonly executions: RuntimeRetentionIndexConfig;\n\treadonly runStatuses: RuntimeRetentionIndexConfig;\n\treadonly runIssues: RuntimeRetentionIndexConfig;\n\treadonly retentionEvidence: RuntimeRetentionIndexConfig;\n}>;\n\nexport type ReplayEvidenceGapKind =\n\t| \"adapter-input-trimmed\"\n\t| \"execution-proof-trimmed\"\n\t| \"evidence-horizon\"\n\t| \"evidence-horizon-closed\";\n\nexport type ReplayEvidenceClassification =\n\t| { readonly kind: \"fresh\" }\n\t| { readonly kind: \"missing-input\" }\n\t| {\n\t\t\treadonly kind: \"retention-gap\";\n\t\t\treadonly index: ToolProviderAdapterRuntimeRetentionIndex;\n\t\t\treadonly gapKind: ReplayEvidenceGapKind;\n\t\t\treadonly key?: string;\n\t };\n\nexport interface RuntimeIndexItem<Entry, Value> {\n\treadonly key: string;\n\treadonly entry: Entry;\n\treadonly value: Value;\n}\n\nexport interface RuntimeRetentionTrackedValue<Value> {\n\treadonly fact: Value;\n\treadonly dropKey?: () => void;\n}\n\nexport interface ToolProviderAdapterRunProjectorPrivateRetentionHooks {\n\treadonly onAdapterInputKey?: (entry: {\n\t\treadonly adapterInputId: string;\n\t\treadonly dropInput: () => void;\n\t}) => void;\n\treadonly classifyRetainedRunRequestReplayEvidence?: (\n\t\trequest: ToolProviderAdapterRunRequested,\n\t) => ReplayEvidenceClassification;\n\treadonly onRunRequestKey?: (entry: {\n\t\treadonly key: string;\n\t\treadonly request: ToolProviderAdapterRunRequested;\n\t\treadonly dropKey: () => void;\n\t}) => void;\n\treadonly onRunStatusKey?: (entry: {\n\t\treadonly key: string;\n\t\treadonly status: ToolProviderAdapterRunStatus;\n\t\treadonly dropKey: () => void;\n\t}) => void;\n\treadonly onRunIssueKey?: (entry: {\n\t\treadonly key: string;\n\t\treadonly issue: DataIssue;\n\t\treadonly dropKey: () => void;\n\t}) => void;\n}\n\nexport class RuntimeRetentionIndex<Entry extends { readonly sequence: number }, Value> {\n\tprivate readonly items = new Map<string, RuntimeIndexItem<Entry, Value>>();\n\n\tget size(): number {\n\t\treturn this.items.size;\n\t}\n\n\tget(key: string): RuntimeIndexItem<Entry, Value> | undefined {\n\t\treturn this.items.get(key);\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.items.has(key);\n\t}\n\n\tset(key: string, entry: Entry, value: Value): RuntimeIndexItem<Entry, Value> {\n\t\tconst item = { key, entry, value };\n\t\tthis.items.set(key, item);\n\t\treturn item;\n\t}\n\n\tdelete(key: string): RuntimeIndexItem<Entry, Value> | undefined {\n\t\tconst item = this.items.get(key);\n\t\tif (item !== undefined) this.items.delete(key);\n\t\treturn item;\n\t}\n\n\ttrimFifo(maxSize: number): RuntimeIndexItem<Entry, Value>[] {\n\t\tconst items = Array.from(this.items.values()).sort(\n\t\t\t(a, b) => a.entry.sequence - b.entry.sequence,\n\t\t);\n\t\treturn trimHeadOverflow(items, { maxSize })\n\t\t\t.map((item) => this.delete(item.key))\n\t\t\t.filter((item): item is RuntimeIndexItem<Entry, Value> => item !== undefined);\n\t}\n\n\ttrimScored(\n\t\tmaxSize: number,\n\t\tscore: (entry: Entry) => number,\n\t): {\n\t\treadonly victims?: RuntimeIndexItem<Entry, Value>[];\n\t\treadonly invalid?: \"threw\" | \"non-finite\";\n\t} {\n\t\tconst scored: { readonly entry: RuntimeIndexItem<Entry, Value>; readonly score: number }[] = [];\n\t\tfor (const item of this.items.values()) {\n\t\t\tlet value: number;\n\t\t\ttry {\n\t\t\t\tvalue = score(item.entry);\n\t\t\t} catch {\n\t\t\t\treturn { invalid: \"threw\" };\n\t\t\t}\n\t\t\tif (!Number.isFinite(value)) return { invalid: \"non-finite\" };\n\t\t\tscored.push({ entry: item, score: value });\n\t\t}\n\t\tconst victims = selectRetentionVictims(scored, { maxSize }).map((item) =>\n\t\t\tthis.delete(item.key),\n\t\t);\n\t\treturn {\n\t\t\tvictims: victims.filter((item): item is RuntimeIndexItem<Entry, Value> => item !== undefined),\n\t\t};\n\t}\n}\n\nexport const toolProviderAdapterRuntimeRetentionIndexes = Object.freeze([\n\t\"adapterInputs\",\n\t\"runRequests\",\n\t\"executions\",\n\t\"runStatuses\",\n\t\"runIssues\",\n\t\"retentionEvidence\",\n] as const satisfies readonly ToolProviderAdapterRuntimeRetentionIndex[]);\n\nexport function toolProviderAdapterRuntimeRetentionIndex(\n\tvalue: string | undefined,\n): ToolProviderAdapterRuntimeRetentionIndex | undefined {\n\treturn toolProviderAdapterRuntimeRetentionIndexes.find((index) => index === value);\n}\n\nexport function isNodeOpt<T>(value: ReactiveOpt<T> | undefined): value is Node<T> {\n\treturn value instanceof Node;\n}\n\nexport function retentionIndexSourceRef(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n): SourceRef {\n\treturn { kind: \"tool-provider-adapter-runtime-retention-index\", id: index };\n}\n\nexport function runtimeEvidenceSourceRefs(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\trefs: readonly SourceRef[] = [],\n): readonly SourceRef[] {\n\treturn canonicalPublicSourceRefs([...refs, retentionIndexSourceRef(index)]);\n}\n\nexport function runtimeEvidenceMetadata(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\topts: {\n\t\treadonly key?: string;\n\t\treadonly extra?: Record<string, unknown>;\n\t} = {},\n): Record<string, unknown> {\n\treturn {\n\t\tindex,\n\t\t...(opts.key === undefined ? {} : { key: runtimeDiagnosticKey(opts.key) }),\n\t\t...(opts.extra ?? {}),\n\t};\n}\n\nexport function runtimeDiagnosticKey(key: string): string {\n\treturn `key:${stableStringHash(key)}:${key.length}`;\n}\n\nexport const maxRuntimeRetentionScorerStringChars = 256;\n\nexport function runtimeRetentionScorerEntry<Entry>(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\tentry: Entry,\n): Entry {\n\tif (!isPlainRecord(entry) || publicMaterialForbiddenKeys(entry, \"provider\").length > 0) {\n\t\tthrow new TypeError(`unsafe ${index} retention scorer entry`);\n\t}\n\tconst bounded: Record<string, unknown> = {};\n\tfor (const value of Object.values(entry)) {\n\t\tif (value !== undefined && typeof value !== \"string\" && typeof value !== \"number\") {\n\t\t\tthrow new TypeError(`unsafe ${index} retention scorer entry`);\n\t\t}\n\t}\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tbounded[key] =\n\t\t\tkey === \"key\" && typeof value === \"string\"\n\t\t\t\t? runtimeDiagnosticKey(value)\n\t\t\t\t: typeof value === \"string\" && value.length > maxRuntimeRetentionScorerStringChars\n\t\t\t\t\t? `bounded:${stableStringHash(value)}:${value.length}`\n\t\t\t\t\t: value;\n\t}\n\treturn Object.freeze(bounded) as Entry;\n}\n\nexport function retentionPolicyMaxSize(\n\tpolicy: ToolProviderAdapterRuntimeIndexRetentionPolicy<unknown> | undefined,\n): ReactiveOpt<number> | undefined {\n\treturn policy?.maxSize;\n}\n\nexport function retentionPolicyMode(\n\tpolicy: ToolProviderAdapterRuntimeIndexRetentionPolicy<unknown> | undefined,\n): RuntimeRetentionMode | undefined {\n\tif (policy === undefined) return undefined;\n\treturn \"score\" in policy && policy.score !== undefined ? \"score\" : \"fifo\";\n}\n\nexport function buildRetentionPolicyReaders(\n\tgraph: Graph,\n\tname: string,\n\tretention: ToolProviderAdapterRuntimeRetentionPolicy | undefined,\n): RuntimeRetentionPolicyReaders {\n\tconst inputs = new PolicyInputs();\n\tconst readers = new Map<ToolProviderAdapterRuntimeRetentionIndex, PolicyReader<number>>();\n\tconst statics = new Map<ToolProviderAdapterRuntimeRetentionIndex, number | undefined>();\n\tfor (const index of toolProviderAdapterRuntimeRetentionIndexes) {\n\t\tconst policy = retention?.[index] as\n\t\t\t| ToolProviderAdapterRuntimeIndexRetentionPolicy<unknown>\n\t\t\t| undefined;\n\t\tconst maxSize = retentionPolicyMaxSize(policy);\n\t\tif (maxSize === undefined) {\n\t\t\tstatics.set(index, undefined);\n\t\t\treaders.set(index, inputs.add(undefined));\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = isNodeOpt(maxSize)\n\t\t\t? maxSize\n\t\t\t: graph.node<number>([], null, {\n\t\t\t\t\tname: `${name}/retentionPolicy/${index}/maxSize`,\n\t\t\t\t\tfactory: \"toolProviderAdapterRuntimeRetentionPolicy.maxSize\",\n\t\t\t\t\tinitial: maxSize,\n\t\t\t\t});\n\t\tif (!isNodeOpt(maxSize)) statics.set(index, maxSize);\n\t\treaders.set(index, inputs.add(node));\n\t}\n\treturn { inputs, readers, statics };\n}\n\nexport function readRetentionPolicyFact(\n\tctx: Ctx,\n\tretention: ToolProviderAdapterRuntimeRetentionPolicy | undefined,\n\treaders: RuntimeRetentionPolicyReaders,\n\tcurrent: RuntimeRetentionPolicyFact | undefined,\n): RuntimeRetentionPolicyFact {\n\tconst policies = new Map<ToolProviderAdapterRuntimeRetentionIndex, RuntimeRetentionIndexConfig>();\n\tconst issues: DataIssue[] = [];\n\tfor (const index of toolProviderAdapterRuntimeRetentionIndexes) {\n\t\tconst raw = retention?.[index] as\n\t\t\t| ToolProviderAdapterRuntimeIndexRetentionPolicy<unknown>\n\t\t\t| undefined;\n\t\tif (raw === undefined) continue;\n\t\tconst reader = readers.readers.get(index);\n\t\tconst previous = current?.policies.get(index)?.maxSize ?? readers.statics.get(index);\n\t\tconst maxSize = reader?.read(ctx, previous);\n\t\tconst issue = validateRuntimeRetentionPolicy(index, raw, maxSize);\n\t\tif (issue !== undefined) {\n\t\t\tissues.push(issue);\n\t\t\tcontinue;\n\t\t}\n\t\tpolicies.set(index, {\n\t\t\tmaxSize,\n\t\t\tmode: retentionPolicyMode(raw) ?? \"fifo\",\n\t\t});\n\t}\n\treturn {\n\t\tkind: \"tool-provider-adapter-runtime-retention-policy\",\n\t\tpolicies,\n\t\t...(issues.length === 0 ? {} : { issues: Object.freeze(issues) }),\n\t};\n}\n\nexport function validateRuntimeRetentionPolicy(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\tpolicy: ToolProviderAdapterRuntimeIndexRetentionPolicy<unknown>,\n\tmaxSize: number | undefined,\n): DataIssue | undefined {\n\tif (\"score\" in policy && policy.score !== undefined && typeof policy.score !== \"function\")\n\t\treturn invalidRetentionPolicyIssue(index, \"score must be a function\");\n\tif (!(\"score\" in policy) || policy.score === undefined) {\n\t\tconst order = (policy as CapacityPolicy<string>).order ?? \"fifo\";\n\t\tif (order !== \"fifo\") return invalidRetentionPolicyIssue(index, \"order must be fifo\");\n\t}\n\tif (maxSize === undefined || !Number.isSafeInteger(maxSize) || maxSize < 1)\n\t\treturn invalidRetentionPolicyIssue(index, \"maxSize must be a safe integer >= 1\");\n\treturn undefined;\n}\n\nexport function invalidRetentionPolicyIssue(\n\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\treason: string,\n): DataIssue {\n\treturn dataIssue(\n\t\t\"tool-provider-adapter-runtime-invalid-retention-policy\",\n\t\t\"Tool provider adapter runtime retention policy is invalid; last-known-good policy remains active.\",\n\t\t{\n\t\t\tsubjectId: index,\n\t\t\trefs: [retentionIndexSourceRef(index)],\n\t\t\tdetails: { index, reason },\n\t\t\tseverity: \"warning\",\n\t\t},\n\t);\n}\n\nexport function adapterInputRetentionEntry(\n\tkey: string,\n\tsequence: number,\n\tinput: ToolProviderAdapterInput,\n\tinsertedAtMs: number | undefined,\n): ToolProviderAdapterInputRetentionEntry {\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(insertedAtMs === undefined ? {} : { insertedAtMs }),\n\t\tadapterInputId: input.adapterInputId,\n\t\trequestId: input.requestId,\n\t\toperationId: input.operationId,\n\t\t...(input.routeId === undefined ? {} : { routeId: input.routeId }),\n\t\t...(input.providerId === undefined ? {} : { providerId: input.providerId }),\n\t\t...(input.executorId === undefined ? {} : { executorId: input.executorId }),\n\t\t...(input.profileId === undefined ? {} : { profileId: input.profileId }),\n\t\tstatus: input.status,\n\t});\n}\n\nexport function runRequestRetentionEntry(\n\tkey: string,\n\tsequence: number,\n\trequest: ToolProviderAdapterRunRequested,\n): ToolProviderAdapterRunRequestRetentionEntry {\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(request.requestedAtMs === undefined ? {} : { requestedAtMs: request.requestedAtMs }),\n\t\tadapterInputId: request.adapterInputId,\n\t\trunId: request.runId,\n\t\tattempt: request.attempt,\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\treason: request.reason,\n\t});\n}\n\nexport function executionRetentionEntry(\n\tkey: string,\n\tsequence: number,\n\trequest: ToolProviderAdapterRunRequested,\n\tstatus: ToolProviderAdapterExecutionRetentionEntry[\"status\"],\n\toccurredAtMs: number | undefined,\n\toutcomeId?: string,\n): ToolProviderAdapterExecutionRetentionEntry {\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\tadapterInputId: request.adapterInputId,\n\t\trunId: request.runId,\n\t\tattempt: request.attempt,\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\t...(outcomeId === undefined ? {} : { outcomeId }),\n\t\tstatus,\n\t\treason: request.reason,\n\t});\n}\n\nexport function runStatusRetentionEntry(\n\tkey: string,\n\tsequence: number,\n\tstatus: ToolProviderAdapterRunStatus,\n\toccurredAtMs: number | undefined,\n): ToolProviderAdapterRunStatusRetentionEntry {\n\tconst issueCode = status.issues?.[0]?.code;\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\tadapterInputId: status.adapterInputId,\n\t\trunId: status.runId,\n\t\t...(status.attempt === undefined ? {} : { attempt: status.attempt }),\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.outcomeId === undefined ? {} : { outcomeId: status.outcomeId }),\n\t\t...(issueCode === undefined ? {} : { issueCode }),\n\t});\n}\n\nexport function runIssueRetentionEntry(\n\tkey: string,\n\tsequence: number,\n\tissue: DataIssue,\n\toccurredAtMs: number | undefined,\n\tcontext: {\n\t\treadonly adapterInputId?: string;\n\t\treadonly runId?: string;\n\t\treadonly attempt?: number;\n\t\treadonly requestId?: string;\n\t\treadonly operationId?: string;\n\t} = {},\n): ToolProviderAdapterRunIssueRetentionEntry {\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\t...(context.adapterInputId === undefined ? {} : { adapterInputId: context.adapterInputId }),\n\t\t...(context.runId === undefined ? {} : { runId: context.runId }),\n\t\t...(context.attempt === undefined ? {} : { attempt: context.attempt }),\n\t\t...(context.requestId === undefined ? {} : { requestId: context.requestId }),\n\t\t...(context.operationId === undefined ? {} : { operationId: context.operationId }),\n\t\tissueCode: issue.code,\n\t\t...(issue.severity === undefined ? {} : { severity: issue.severity }),\n\t\t...(issue.subjectId === undefined ? {} : { subjectId: issue.subjectId }),\n\t});\n}\n\nexport function retentionEvidenceEntry(\n\tkey: string,\n\tsequence: number,\n\topts: {\n\t\treadonly adapterInputId: string;\n\t\treadonly evidenceKind: ToolProviderAdapterRuntimeRetentionEvidenceEntry[\"evidenceKind\"];\n\t\treadonly occurredAtMs?: number;\n\t\treadonly attemptHighWater?: number;\n\t\treadonly reason: ToolProviderAdapterRuntimeRetentionEvidenceEntry[\"reason\"];\n\t},\n): ToolProviderAdapterRuntimeRetentionEvidenceEntry {\n\treturn Object.freeze({\n\t\tkey,\n\t\tsequence,\n\t\t...(opts.occurredAtMs === undefined ? {} : { occurredAtMs: opts.occurredAtMs }),\n\t\tadapterInputId: opts.adapterInputId,\n\t\tevidenceKind: opts.evidenceKind,\n\t\t...(opts.attemptHighWater === undefined ? {} : { attemptHighWater: opts.attemptHighWater }),\n\t\treason: opts.reason,\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 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 { DataIssue } from \"../data/index.js\";\nimport type {\n\tReplayEvidenceClassification,\n\tRuntimeRetentionIndex,\n} from \"./agent-runtime-adapter-retention.js\";\nimport { runRequestIdentityIssues } from \"./agent-runtime-adapter-run.js\";\nimport { dataIssue, ref } from \"./agent-runtime-common.js\";\nimport type { AgentRequestStatus } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterBinding,\n\tToolProviderAdapterExecutionRetentionEntry,\n\tToolProviderAdapterInput,\n\tToolProviderAdapterInputRetentionEntry,\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunResult,\n\tToolProviderAdapterRunStatus,\n} from \"./agent-runtime-types-tool.js\";\n\nexport interface AdapterRuntimeRunRequestContext<TArguments = unknown, TResult = unknown> {\n\tisDisposed(): boolean;\n\tadapterInputs: RuntimeRetentionIndex<\n\t\tToolProviderAdapterInputRetentionEntry,\n\t\tToolProviderAdapterInput<TArguments>\n\t>;\n\texecutions: RuntimeRetentionIndex<\n\t\tToolProviderAdapterExecutionRetentionEntry,\n\t\tToolProviderAdapterRunRequested\n\t>;\n\tbindings: ReadonlyMap<string, ToolProviderAdapterBinding<TArguments, TResult>>;\n\tnow?: () => number;\n\tclassifyRunRequestReplayEvidence(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tinput?: ToolProviderAdapterInput<TArguments>,\n\t): ReplayEvidenceClassification;\n\tpublishReplayClassification(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tclassification: ReplayEvidenceClassification,\n\t): boolean;\n\tstartExecutionProof(request: ToolProviderAdapterRunRequested): boolean;\n\texecutionCoordinate(request: ToolProviderAdapterRunRequested): string;\n\tpublishIssue(issue: DataIssue, track?: boolean): void;\n\tpublishRunStatus(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tstatusValue: ToolProviderAdapterRunStatus[\"status\"],\n\t\tissueList?: readonly DataIssue[],\n\t): void;\n\tpublishStatus(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tstatusValue: AgentRequestStatus,\n\t\tissueList?: readonly DataIssue[],\n\t): void;\n\tpublishAudit(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tkind: string,\n\t\tmetadata?: Record<string, unknown>,\n\t): void;\n\tpublishOutcome(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tresult: ToolProviderAdapterRunResult<TResult>,\n\t\trequest: ToolProviderAdapterRunRequested,\n\t): void;\n\tpublishRuntimeFailure(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tcode: string,\n\t\terror: unknown,\n\t): void;\n}\n\nexport function runAdapterRuntimeRequest<TArguments = unknown, TResult = unknown>(\n\tctx: AdapterRuntimeRunRequestContext<TArguments, TResult>,\n\trequest: ToolProviderAdapterRunRequested,\n): void {\n\tif (ctx.isDisposed()) return;\n\tconst input = ctx.adapterInputs.get(request.adapterInputId)?.value;\n\tif (input === undefined) {\n\t\tconst missingInputClassification = ctx.classifyRunRequestReplayEvidence(request);\n\t\tctx.publishReplayClassification(request, missingInputClassification);\n\t\treturn;\n\t}\n\tif (input.status !== \"ready\") {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-adapter-runtime-input-not-ready\",\n\t\t\t\"Tool provider adapter runtime requires a ready adapter input.\",\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\tdetails: { status: input.status },\n\t\t\t},\n\t\t);\n\t\tctx.publishIssue(issue);\n\t\tctx.publishRunStatus(request, \"stale-request\", [issue]);\n\t\tctx.publishStatus(input, \"blocked\", [issue]);\n\t\treturn;\n\t}\n\tconst requestIssues = runRequestIdentityIssues(request, input);\n\tif (requestIssues.length > 0) {\n\t\tfor (const issue of requestIssues) ctx.publishIssue(issue);\n\t\tctx.publishRunStatus(request, \"mismatched-request\", requestIssues);\n\t\tctx.publishStatus(input, \"blocked\", requestIssues);\n\t\tctx.publishAudit(input, \"tool-provider-adapter-runtime-run-request-rejected\", {\n\t\t\trunId: request.runId,\n\t\t\tattempt: request.attempt,\n\t\t\tissueCodes: requestIssues.map((issue) => issue.code),\n\t\t});\n\t\treturn;\n\t}\n\tif (ctx.executions.has(ctx.executionCoordinate(request))) {\n\t\tctx.startExecutionProof(request);\n\t\treturn;\n\t}\n\tconst classification = ctx.classifyRunRequestReplayEvidence(request, input);\n\tif (ctx.publishReplayClassification(request, classification)) return;\n\tif (!ctx.startExecutionProof(request)) return;\n\tconst binding = input.providerId === undefined ? undefined : ctx.bindings.get(input.providerId);\n\tif (binding === undefined) {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-adapter-runtime-missing-binding\",\n\t\t\t\"Tool provider adapter runtime requires a matching runtime-private binding.\",\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\tdetails: { providerId: input.providerId },\n\t\t\t},\n\t\t);\n\t\tctx.publishOutcome(\n\t\t\tinput,\n\t\t\t{\n\t\t\t\tkind: \"blocked\",\n\t\t\t\tneeds: [\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: \"tool-provider-binding\",\n\t\t\t\t\t\tmessage: \"Matching runtime-private tool provider binding is unavailable.\",\n\t\t\t\t\t\t...(input.providerId === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { refs: [ref(\"tool-provider\", input.providerId)] }),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tissues: [issue],\n\t\t\t},\n\t\t\trequest,\n\t\t);\n\t\treturn;\n\t}\n\tctx.publishRunStatus(request, \"started\");\n\tctx.publishStatus(input, \"in-flight\");\n\tctx.publishAudit(input, \"tool-provider-adapter-runtime-started\", {\n\t\tproviderId: binding.providerId,\n\t\trunId: request.runId,\n\t\tattempt: request.attempt,\n\t\treason: request.reason,\n\t});\n\tlet result: ToolProviderAdapterRunResult<TResult>;\n\ttry {\n\t\tresult = binding.run(input, {\n\t\t\trunId: request.runId,\n\t\t\tattempt: request.attempt,\n\t\t\treason: request.reason,\n\t\t\tsourceRefs: request.sourceRefs ?? input.sourceRefs ?? [],\n\t\t\tnow: ctx.now,\n\t\t});\n\t} catch (error) {\n\t\tctx.publishRuntimeFailure(input, request, \"tool-provider-adapter-runtime-threw\", error);\n\t\treturn;\n\t}\n\tif (isThenableResult(result)) {\n\t\tctx.publishRuntimeFailure(\n\t\t\tinput,\n\t\t\trequest,\n\t\t\t\"tool-provider-adapter-runtime-async-result-unsupported\",\n\t\t\tnew Error(\"Tool provider adapter runtime bindings must return synchronously.\"),\n\t\t);\n\t\treturn;\n\t}\n\tctx.publishOutcome(input, result, request);\n}\n\nfunction isThenableResult(value: unknown): boolean {\n\tif (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return false;\n\ttry {\n\t\treturn typeof (value as { readonly then?: unknown }).then === \"function\";\n\t} catch {\n\t\treturn true;\n\t}\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport {\n\ttype ReplayEvidenceClassification,\n\ttype ReplayEvidenceGapKind,\n\ttype RuntimeIndexItem,\n\truntimeDiagnosticKey,\n\truntimeEvidenceMetadata,\n\truntimeEvidenceSourceRefs,\n} from \"./agent-runtime-adapter-retention.js\";\nimport { dataIssue, ref } from \"./agent-runtime-common.js\";\nimport type { SourceRef } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunStatus,\n\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\tToolProviderAdapterRuntimeStatus,\n} from \"./agent-runtime-types-tool.js\";\n\nexport interface AdapterRuntimeRetentionGapContext {\n\tpublishIssue(issue: DataIssue, track?: boolean): void;\n\tpublishRunStatus(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tstatusValue: ToolProviderAdapterRunStatus[\"status\"],\n\t\tissueList?: readonly DataIssue[],\n\t): void;\n\tpublishRuntimeStatus(fact: Omit<ToolProviderAdapterRuntimeStatus, \"kind\">): void;\n\tpublishRuntimeAudit(\n\t\tkind: string,\n\t\tauditOpts?: {\n\t\t\treadonly subjectId?: string;\n\t\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\t\treadonly issueCode?: string;\n\t\t\treadonly metadata?: Record<string, unknown>;\n\t\t},\n\t): void;\n}\n\nfunction retentionGapIssueCode(gapKind: ReplayEvidenceGapKind): string {\n\tswitch (gapKind) {\n\t\tcase \"evidence-horizon\":\n\t\t\treturn \"tool-provider-adapter-runtime-retention-evidence-gap\";\n\t\tcase \"evidence-horizon-closed\":\n\t\t\treturn \"tool-provider-adapter-runtime-retention-evidence-horizon-closed\";\n\t\tcase \"adapter-input-trimmed\":\n\t\tcase \"execution-proof-trimmed\":\n\t\t\treturn \"tool-provider-adapter-runtime-retention-gap\";\n\t}\n}\n\nfunction retentionGapMessage(gapKind: ReplayEvidenceGapKind): string {\n\tswitch (gapKind) {\n\t\tcase \"evidence-horizon\":\n\t\t\treturn \"Tool provider adapter runtime retention evidence horizon no longer proves this request is fresh.\";\n\t\tcase \"evidence-horizon-closed\":\n\t\t\treturn \"Tool provider adapter runtime retention evidence horizon is closed; this request must fail closed.\";\n\t\tcase \"adapter-input-trimmed\":\n\t\t\treturn \"Tool provider adapter runtime retention removed the requested adapter input proof.\";\n\t\tcase \"execution-proof-trimmed\":\n\t\t\treturn \"Tool provider adapter runtime retention removed execution proof needed to safely replay this request.\";\n\t}\n}\n\nfunction retentionGapEvidenceKind(\n\tgapKind: ReplayEvidenceGapKind,\n): ToolProviderAdapterRuntimeRetentionEvidenceEntry[\"evidenceKind\"] | undefined {\n\tswitch (gapKind) {\n\t\tcase \"adapter-input-trimmed\":\n\t\t\treturn \"adapter-input-trimmed\";\n\t\tcase \"execution-proof-trimmed\":\n\t\t\treturn \"execution-high-water\";\n\t\tcase \"evidence-horizon\":\n\t\tcase \"evidence-horizon-closed\":\n\t\t\treturn undefined;\n\t}\n}\n\nexport function publishAdapterRuntimeRetentionGap(\n\tctx: AdapterRuntimeRetentionGapContext,\n\trequest: ToolProviderAdapterRunRequested,\n\tclassification: Extract<ReplayEvidenceClassification, { readonly kind: \"retention-gap\" }>,\n): void {\n\tconst { index, gapKind } = classification;\n\tconst key = classification.key ?? request.adapterInputId;\n\tconst issueCode = retentionGapIssueCode(gapKind);\n\tconst evidenceKind = retentionGapEvidenceKind(gapKind);\n\tconst sourceRefs = runtimeEvidenceSourceRefs(index, [\n\t\tref(\"tool-provider-adapter-run\", request.runId),\n\t\tref(\"tool-provider-adapter-input\", request.adapterInputId),\n\t]);\n\tconst metadata = runtimeEvidenceMetadata(index, {\n\t\tkey,\n\t\textra: {\n\t\t\tgapKind,\n\t\t\t...(evidenceKind === undefined ? {} : { evidenceKind }),\n\t\t},\n\t});\n\tconst issue = dataIssue(issueCode, retentionGapMessage(gapKind), {\n\t\tsubjectId: request.adapterInputId,\n\t\trefs: sourceRefs,\n\t\tdetails: {\n\t\t\tindex,\n\t\t\tadapterInputId: request.adapterInputId,\n\t\t\trunId: request.runId,\n\t\t\tattempt: request.attempt,\n\t\t\tissueCode,\n\t\t\tgapKind,\n\t\t\tkey: runtimeDiagnosticKey(key),\n\t\t\t...(evidenceKind === undefined ? {} : { evidenceKind }),\n\t\t},\n\t});\n\tctx.publishIssue(issue);\n\tctx.publishRunStatus(request, \"retention-gap\", [issue]);\n\tctx.publishRuntimeStatus({\n\t\tstatus: \"retention-gap\",\n\t\tindex,\n\t\tkey,\n\t\tadapterInputId: request.adapterInputId,\n\t\trunId: request.runId,\n\t\tattempt: request.attempt,\n\t\tissueCode: issue.code,\n\t\tsourceRefs,\n\t\tmetadata,\n\t});\n\tctx.publishRuntimeAudit(\"tool-provider-adapter-runtime-retention-gap\", {\n\t\tsubjectId: request.adapterInputId,\n\t\tsourceRefs,\n\t\tissueCode: issue.code,\n\t\tmetadata,\n\t});\n}\n\nexport function publishAdapterRuntimeRetentionEvidenceGlobalFailClosed(\n\tctx: AdapterRuntimeRetentionGapContext,\n\tvictim: RuntimeIndexItem<\n\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry\n\t>,\n): void {\n\tconst sourceRefs = runtimeEvidenceSourceRefs(\"retentionEvidence\");\n\tconst metadata = runtimeEvidenceMetadata(\"retentionEvidence\", {\n\t\tkey: victim.key,\n\t\textra: {\n\t\t\tevidenceKind: victim.value.evidenceKind,\n\t\t\tgapKind: \"evidence-horizon-closed\",\n\t\t},\n\t});\n\tconst issue = dataIssue(\n\t\t\"tool-provider-adapter-runtime-retention-evidence-horizon-closed\",\n\t\t\"Tool provider adapter runtime retention evidence closed-marker horizon overflowed; future requests fail closed until runtime reset.\",\n\t\t{\n\t\t\tsubjectId: victim.value.adapterInputId,\n\t\t\trefs: sourceRefs,\n\t\t\tdetails: {\n\t\t\t\tindex: \"retentionEvidence\",\n\t\t\t\tkey: runtimeDiagnosticKey(victim.key),\n\t\t\t\tgapKind: \"evidence-horizon-closed\",\n\t\t\t},\n\t\t},\n\t);\n\tctx.publishIssue(issue, false);\n\tctx.publishRuntimeStatus({\n\t\tstatus: \"retention-gap\",\n\t\tindex: \"retentionEvidence\",\n\t\tkey: victim.key,\n\t\tadapterInputId: victim.value.adapterInputId,\n\t\t...(victim.value.attemptHighWater === undefined\n\t\t\t? {}\n\t\t\t: { attempt: victim.value.attemptHighWater }),\n\t\tissueCode: issue.code,\n\t\tsourceRefs,\n\t\tmetadata,\n\t});\n\tctx.publishRuntimeAudit(\"tool-provider-adapter-runtime-retention-evidence-horizon-closed\", {\n\t\tsubjectId: victim.value.adapterInputId,\n\t\tsourceRefs,\n\t\tissueCode: issue.code,\n\t\tmetadata,\n\t});\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { RuntimeRetentionTrackedValue } from \"./agent-runtime-adapter-retention.js\";\nimport { RuntimeRetentionIndex } from \"./agent-runtime-adapter-retention.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type { AgentRequestStatusChanged, ExecutorOutcome } from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterExecutionRetentionEntry,\n\tToolProviderAdapterInput,\n\tToolProviderAdapterInputRetentionEntry,\n\tToolProviderAdapterRunIssueRetentionEntry,\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunRequestRetentionEntry,\n\tToolProviderAdapterRunStatus,\n\tToolProviderAdapterRunStatusRetentionEntry,\n\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\tToolProviderAdapterRuntimeStatus,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function createAdapterRuntimeRetentionIndexes<TArguments>() {\n\treturn {\n\t\tadapterInputs: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterInputRetentionEntry,\n\t\t\tToolProviderAdapterInput<TArguments>\n\t\t>(),\n\t\trunRequests: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterRunRequestRetentionEntry,\n\t\t\tRuntimeRetentionTrackedValue<ToolProviderAdapterRunRequested>\n\t\t>(),\n\t\texecutions: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterExecutionRetentionEntry,\n\t\t\tToolProviderAdapterRunRequested\n\t\t>(),\n\t\trunStatuses: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterRunStatusRetentionEntry,\n\t\t\tRuntimeRetentionTrackedValue<ToolProviderAdapterRunStatus>\n\t\t>(),\n\t\trunIssues: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterRunIssueRetentionEntry,\n\t\t\tRuntimeRetentionTrackedValue<DataIssue>\n\t\t>(),\n\t\tretentionEvidence: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry\n\t\t>(),\n\t\tclosedRetentionEvidence: new RuntimeRetentionIndex<\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry\n\t\t>(),\n\t};\n}\n\nexport function createAdapterRuntimeOutputNodes(graph: Graph, name: string) {\n\treturn {\n\t\toutcomes: graph.node<ExecutorOutcome>([], null, {\n\t\t\tname: `${name}/outcomes`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeOutcomes\",\n\t\t}),\n\t\trunStatus: graph.node<ToolProviderAdapterRunStatus>([], null, {\n\t\t\tname: `${name}/runStatus`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeRunStatus\",\n\t\t}),\n\t\tstatus: graph.node<AgentRequestStatusChanged>([], null, {\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeStatus\",\n\t\t}),\n\t\truntimeStatus: graph.node<ToolProviderAdapterRuntimeStatus>([], null, {\n\t\t\tname: `${name}/runtimeStatus`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeStatus\",\n\t\t}),\n\t\tissues: graph.node<DataIssue>([], null, {\n\t\t\tname: `${name}/issues`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeIssues\",\n\t\t}),\n\t\taudit: graph.node<AgentRuntimeAuditRecord>([], null, {\n\t\t\tname: `${name}/audit`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeAudit\",\n\t\t}),\n\t};\n}\n","import type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { RetentionPolicy } from \"../graph/policies/types.js\";\nimport type {\n\tEffectiveRuntimeRetentionPolicy,\n\tReplayEvidenceClassification,\n\tRuntimeIndexItem,\n\tRuntimeRetentionIndex,\n\tRuntimeRetentionIndexConfig,\n\tRuntimeRetentionPolicyFact,\n} from \"./agent-runtime-adapter-retention.js\";\nimport {\n\tadapterInputRetentionEntry,\n\tbuildRetentionPolicyReaders,\n\texecutionRetentionEntry,\n\treadRetentionPolicyFact,\n\tretentionEvidenceEntry,\n\trunIssueRetentionEntry,\n\trunRequestRetentionEntry,\n\trunStatusRetentionEntry,\n\truntimeDiagnosticKey,\n\truntimeEvidenceMetadata,\n\truntimeEvidenceSourceRefs,\n\truntimeRetentionScorerEntry,\n\ttoolProviderAdapterRuntimeRetentionIndex,\n} from \"./agent-runtime-adapter-retention.js\";\nimport {\n\tnormalizeToolProviderAdapterBindings,\n\ttoolProviderAdapterRunProjectorInternal,\n} from \"./agent-runtime-adapter-run.js\";\nimport { runAdapterRuntimeRequest } from \"./agent-runtime-adapter-runtime-execute.js\";\nimport {\n\tpublishAdapterRuntimeRetentionEvidenceGlobalFailClosed,\n\tpublishAdapterRuntimeRetentionGap,\n} from \"./agent-runtime-adapter-runtime-retention-gaps.js\";\nimport {\n\tcreateAdapterRuntimeOutputNodes,\n\tcreateAdapterRuntimeRetentionIndexes,\n} from \"./agent-runtime-adapter-runtime-state.js\";\nimport {\n\tboundPublicText,\n\tdataIssue,\n\tisRecord,\n\tmaxPublicMetadataStringChars,\n\tref,\n\tsanitizeAdapterInputIssue,\n\tsanitizeAdapterInputSourceRefs,\n\tsanitizeGraphVisibleRecord,\n\tsanitizeProviderGraphVisibleRecord,\n} from \"./agent-runtime-common.js\";\nimport {\n\tadapterRuntimeIssue,\n\tagentRequestStatusForExecutorOutcome,\n\tbuildToolProviderExecutorOutcome,\n\tdefaultToolProviderAdapterEvidenceRefs,\n\toutcomeIssues,\n} from \"./agent-runtime-executor-outcome.js\";\nimport type { AgentRuntimeAuditRecord } from \"./agent-runtime-types-agent.js\";\nimport type {\n\tAgentRequestStatus,\n\tAgentRequestStatusChanged,\n\tExecutorOutcome,\n\tSourceRef,\n} from \"./agent-runtime-types-core.js\";\nimport type {\n\tToolProviderAdapterInput,\n\tToolProviderAdapterRunRequested,\n\tToolProviderAdapterRunResult,\n\tToolProviderAdapterRunStatus,\n\tToolProviderAdapterRuntimeHandle,\n\tToolProviderAdapterRuntimeOptions,\n\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\tToolProviderAdapterRuntimeRetentionIndex,\n\tToolProviderAdapterRuntimeStatus,\n} from \"./agent-runtime-types-tool.js\";\n\nexport function attachToolProviderAdapterRuntime<TArguments = unknown, TResult = unknown>(\n\tgraph: Graph,\n\topts: ToolProviderAdapterRuntimeOptions<TArguments, TResult>,\n): ToolProviderAdapterRuntimeHandle {\n\tconst name = opts.name ?? \"toolProviderAdapterRuntime\";\n\tconst bindings = normalizeToolProviderAdapterBindings(opts.bindings);\n\tconst retentionReaders = buildRetentionPolicyReaders(graph, name, opts.retention);\n\tconst retentionPolicy = graph.node<RuntimeRetentionPolicyFact>(\n\t\tretentionReaders.inputs.deps,\n\t\t(ctx) => {\n\t\t\tconst current = ctx.state.get<RuntimeRetentionPolicyFact>();\n\t\t\tconst fact = readRetentionPolicyFact(ctx, opts.retention, retentionReaders, current);\n\t\t\tctx.state.set(fact);\n\t\t\tctx.down([[\"DATA\", fact]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/retentionPolicy`,\n\t\t\tfactory: \"toolProviderAdapterRuntimeRetentionPolicy\",\n\t\t\tpartial: true,\n\t\t},\n\t);\n\tconst {\n\t\tadapterInputs,\n\t\trunRequests,\n\t\texecutions,\n\t\trunStatuses,\n\t\trunIssues,\n\t\tretentionEvidence,\n\t\tclosedRetentionEvidence,\n\t} = createAdapterRuntimeRetentionIndexes<TArguments>();\n\tconst executionHighWaterByInput = new Map<string, number>();\n\tconst trimmedAdapterInputIds = new Set<string>();\n\tconst projectorInputDropById = new Map<string, () => void>();\n\tlet retentionEvidenceHorizonExceeded = false;\n\tconst { outcomes, runStatus, status, runtimeStatus, issues, audit } =\n\t\tcreateAdapterRuntimeOutputNodes(graph, name);\n\tlet disposed = false;\n\tlet auditSeq = 0;\n\tlet retentionSeq = 0;\n\tlet effectiveRetention: EffectiveRuntimeRetentionPolicy = {};\n\n\tfunction nowMs(): number | undefined {\n\t\treturn opts.now?.();\n\t}\n\n\tfunction nextRetentionSequence(): number {\n\t\tretentionSeq += 1;\n\t\treturn retentionSeq;\n\t}\n\n\tfunction publishRuntimeStatus(fact: Omit<ToolProviderAdapterRuntimeStatus, \"kind\">): void {\n\t\tconst occurredAtMs = nowMs();\n\t\tconst { sourceRefs: rawSourceRefs, metadata: rawMetadata, key: rawKey, ...statusFields } = fact;\n\t\tconst sourceRefs =\n\t\t\trawSourceRefs === undefined ? undefined : sanitizeAdapterInputSourceRefs(rawSourceRefs);\n\t\tconst metadata = sanitizeProviderGraphVisibleRecord(rawMetadata, opts.publicText);\n\t\tconst key =\n\t\t\trawKey === undefined\n\t\t\t\t? undefined\n\t\t\t\t: boundPublicText(\n\t\t\t\t\t\truntimeDiagnosticKey(rawKey),\n\t\t\t\t\t\tmaxPublicMetadataStringChars(opts.publicText),\n\t\t\t\t\t).text;\n\t\truntimeStatus.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"tool-provider-adapter-runtime-status\",\n\t\t\t\t\t...(occurredAtMs === undefined ? {} : { occurredAtMs }),\n\t\t\t\t\t...statusFields,\n\t\t\t\t\t...(key === undefined ? {} : { key }),\n\t\t\t\t\t...(sourceRefs === undefined ? {} : { sourceRefs }),\n\t\t\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t\t\t} satisfies ToolProviderAdapterRuntimeStatus,\n\t\t\t],\n\t\t]);\n\t}\n\n\tfunction publishRuntimeAudit(\n\t\tkind: string,\n\t\tauditOpts: {\n\t\t\treadonly subjectId?: string;\n\t\t\treadonly sourceRefs?: readonly SourceRef[];\n\t\t\treadonly issueCode?: string;\n\t\t\treadonly metadata?: Record<string, unknown>;\n\t\t} = {},\n\t): void {\n\t\tauditSeq += 1;\n\t\tconst metadata = sanitizeProviderGraphVisibleRecord(auditOpts.metadata, opts.publicText);\n\t\taudit.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tid: `${name}:audit:${auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\t...(auditOpts.subjectId === undefined ? {} : { subjectId: auditOpts.subjectId }),\n\t\t\t\t\t...(auditOpts.sourceRefs === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { sourceRefs: sanitizeAdapterInputSourceRefs(auditOpts.sourceRefs) }),\n\t\t\t\t\t...(auditOpts.issueCode === undefined ? {} : { issueCode: auditOpts.issueCode }),\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\tfunction trackRunIssue(issue: DataIssue, emittedKey?: string, dropKey?: () => void): void {\n\t\tconst sequence = nextRetentionSequence();\n\t\tconst key = emittedKey ?? `${sequence}:${issue.code}:${issue.subjectId ?? \"\"}`;\n\t\trunIssues.set(key, runIssueRetentionEntry(key, sequence, issue, nowMs()), {\n\t\t\tfact: issue,\n\t\t\tdropKey,\n\t\t});\n\t\ttrimRunIssues();\n\t}\n\n\tfunction publishIssue(issue: DataIssue, track = true): void {\n\t\tissues.down([[\"DATA\", sanitizeAdapterInputIssue(issue)]]);\n\t\tif (track) trackRunIssue(issue);\n\t}\n\n\tfunction publishRunStatus(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tnextStatus: ToolProviderAdapterRunStatus[\"status\"],\n\t\tstatusIssues?: readonly DataIssue[],\n\t\toutcomeId?: string,\n\t): void {\n\t\tconst statusFact = {\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: nextStatus,\n\t\t\tattempt: request.attempt,\n\t\t\toutcomeId,\n\t\t\tissues: statusIssues,\n\t\t\tsourceRefs: sanitizeAdapterInputSourceRefs(request.sourceRefs ?? []),\n\t\t\tmetadata: sanitizeGraphVisibleRecord(\n\t\t\t\t{\n\t\t\t\t\tproviderId: request.providerId,\n\t\t\t\t\trouteId: request.routeId,\n\t\t\t\t\treason: request.reason,\n\t\t\t\t},\n\t\t\t\topts.publicText,\n\t\t\t),\n\t\t} satisfies ToolProviderAdapterRunStatus;\n\t\trunStatus.down([[\"DATA\", statusFact]]);\n\t\ttrackRunStatus(statusFact);\n\t}\n\n\tfunction trackRunStatus(\n\t\tstatusFact: ToolProviderAdapterRunStatus,\n\t\temittedKey?: string,\n\t\tdropKey?: () => void,\n\t): void {\n\t\tconst sequence = nextRetentionSequence();\n\t\tconst key = emittedKey ?? `${sequence}:${statusFact.runId}:${statusFact.status}`;\n\t\trunStatuses.set(key, runStatusRetentionEntry(key, sequence, statusFact, nowMs()), {\n\t\t\tfact: statusFact,\n\t\t\tdropKey,\n\t\t});\n\t\ttrimRunStatuses();\n\t}\n\n\tfunction retentionScore<Entry>(\n\t\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\t): ((entry: Entry) => number) | undefined {\n\t\tconst policy = opts.retention?.[index] as RetentionPolicy<Entry> | undefined;\n\t\treturn typeof policy?.score === \"function\" ? policy.score : undefined;\n\t}\n\n\tfunction trimRuntimeIndex<Entry extends { readonly sequence: number }, Value>(\n\t\tindexName: ToolProviderAdapterRuntimeRetentionIndex,\n\t\tstore: RuntimeRetentionIndex<Entry, Value>,\n\t\tconfig: RuntimeRetentionIndexConfig | undefined,\n\t\tonVictim?: (victim: RuntimeIndexItem<Entry, Value>) => void,\n\t): void {\n\t\tif (config?.maxSize === undefined) return;\n\t\tlet victims: RuntimeIndexItem<Entry, Value>[];\n\t\tif (config.mode === \"score\") {\n\t\t\tconst score = retentionScore<Entry>(indexName);\n\t\t\tif (score === undefined) return;\n\t\t\tconst selected = store.trimScored(config.maxSize, (entry) => {\n\t\t\t\treturn score(runtimeRetentionScorerEntry(indexName, entry));\n\t\t\t});\n\t\t\tif (selected.invalid !== undefined) {\n\t\t\t\tpublishRetentionScoreInvalid(indexName, selected.invalid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvictims = selected.victims ?? [];\n\t\t} else {\n\t\t\tvictims = store.trimFifo(config.maxSize);\n\t\t}\n\t\tfor (const victim of victims) {\n\t\t\tonVictim?.(victim);\n\t\t\tpublishRetentionTrimmed(indexName, victim.key, victim.entry);\n\t\t}\n\t}\n\n\tfunction trackAdapterInputTrimmedEvidence(adapterInputId: string): void {\n\t\ttrimmedAdapterInputIds.add(adapterInputId);\n\t\tconst sequence = nextRetentionSequence();\n\t\tconst key = `adapter-input-trimmed:${adapterInputId}`;\n\t\tconst entry = retentionEvidenceEntry(key, sequence, {\n\t\t\tadapterInputId,\n\t\t\tevidenceKind: \"adapter-input-trimmed\",\n\t\t\toccurredAtMs: nowMs(),\n\t\t\treason: \"adapter-input-retention\",\n\t\t});\n\t\tretentionEvidence.set(key, entry, entry);\n\t\ttrimRetentionEvidence();\n\t}\n\n\tfunction trackExecutionHighWaterEvidence(adapterInputId: string, attempt: number): void {\n\t\tconst previous = executionHighWaterByInput.get(adapterInputId) ?? 0;\n\t\tconst attemptHighWater = Math.max(previous, attempt);\n\t\texecutionHighWaterByInput.set(adapterInputId, attemptHighWater);\n\t\tconst sequence = nextRetentionSequence();\n\t\tconst key = `execution-high-water:${adapterInputId}`;\n\t\tconst entry = retentionEvidenceEntry(key, sequence, {\n\t\t\tadapterInputId,\n\t\t\tevidenceKind: \"execution-high-water\",\n\t\t\toccurredAtMs: nowMs(),\n\t\t\tattemptHighWater,\n\t\t\treason: \"execution-proof-retention\",\n\t\t});\n\t\tretentionEvidence.set(key, entry, entry);\n\t\ttrimRetentionEvidence();\n\t}\n\n\tfunction retentionEvidenceClosedKey(adapterInputId: string): string {\n\t\treturn `closed:${adapterInputId}`;\n\t}\n\n\tfunction isRetentionEvidenceClosed(adapterInputId: string): boolean {\n\t\treturn (\n\t\t\tretentionEvidenceHorizonExceeded ||\n\t\t\tclosedRetentionEvidence.has(retentionEvidenceClosedKey(adapterInputId))\n\t\t);\n\t}\n\n\tfunction classifyRunRequestReplayEvidence(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tinput?: ToolProviderAdapterInput<TArguments>,\n\t): ReplayEvidenceClassification {\n\t\tif (isRetentionEvidenceClosed(request.adapterInputId)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retention-gap\",\n\t\t\t\tindex: \"retentionEvidence\",\n\t\t\t\tgapKind: \"evidence-horizon-closed\",\n\t\t\t\tkey: retentionEvidenceClosedKey(request.adapterInputId),\n\t\t\t};\n\t\t}\n\t\tif (input === undefined && trimmedAdapterInputIds.has(request.adapterInputId)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retention-gap\",\n\t\t\t\tindex: \"adapterInputs\",\n\t\t\t\tgapKind: \"adapter-input-trimmed\",\n\t\t\t\tkey: `adapter-input-trimmed:${request.adapterInputId}`,\n\t\t\t};\n\t\t}\n\t\tconst highWater = executionHighWaterByInput.get(request.adapterInputId) ?? 0;\n\t\tif (highWater >= request.attempt) {\n\t\t\treturn {\n\t\t\t\tkind: \"retention-gap\",\n\t\t\t\tindex: \"executions\",\n\t\t\t\tgapKind: \"execution-proof-trimmed\",\n\t\t\t\tkey: `execution-high-water:${request.adapterInputId}`,\n\t\t\t};\n\t\t}\n\t\tif (input === undefined) return { kind: \"missing-input\" };\n\t\treturn { kind: \"fresh\" };\n\t}\n\n\tfunction classifyRetainedRunRequestReplayEvidence(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t): ReplayEvidenceClassification {\n\t\treturn classifyRunRequestReplayEvidence(request);\n\t}\n\n\tfunction dropProjectorInput(adapterInputId: string): void {\n\t\tprojectorInputDropById.get(adapterInputId)?.();\n\t\tprojectorInputDropById.delete(adapterInputId);\n\t}\n\n\tfunction closeRetentionEvidenceHorizon(\n\t\tvictim: RuntimeIndexItem<\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry\n\t\t>,\n\t): void {\n\t\tconst key = retentionEvidenceClosedKey(victim.value.adapterInputId);\n\t\tconst sequence = nextRetentionSequence();\n\t\tconst entry = retentionEvidenceEntry(key, sequence, {\n\t\t\tadapterInputId: victim.value.adapterInputId,\n\t\t\tevidenceKind: victim.value.evidenceKind,\n\t\t\toccurredAtMs: nowMs(),\n\t\t\t...(victim.value.attemptHighWater === undefined\n\t\t\t\t? {}\n\t\t\t\t: { attemptHighWater: victim.value.attemptHighWater }),\n\t\t\treason: victim.value.reason,\n\t\t});\n\t\tclosedRetentionEvidence.set(key, entry, entry);\n\t\ttrimClosedRetentionEvidence();\n\t}\n\n\tfunction trimClosedRetentionEvidence(): void {\n\t\tconst maxSize = effectiveRetention.retentionEvidence?.maxSize;\n\t\tif (maxSize === undefined) return;\n\t\tconst victims = closedRetentionEvidence.trimFifo(maxSize);\n\t\tfor (const victim of victims) {\n\t\t\tconst firstGlobalClosure = !retentionEvidenceHorizonExceeded;\n\t\t\tif (firstGlobalClosure) retentionEvidenceHorizonExceeded = true;\n\t\t\tpublishRetentionTrimmed(\"retentionEvidence\", victim.key, victim.entry);\n\t\t\tif (firstGlobalClosure) {\n\t\t\t\tpublishRetentionEvidenceGlobalFailClosed(victim);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction trimAdapterInputs(): void {\n\t\ttrimRuntimeIndex(\"adapterInputs\", adapterInputs, effectiveRetention.adapterInputs, (victim) => {\n\t\t\tdropProjectorInput(victim.value.adapterInputId);\n\t\t\ttrackAdapterInputTrimmedEvidence(victim.value.adapterInputId);\n\t\t});\n\t}\n\n\tfunction trimRunRequests(): void {\n\t\ttrimRuntimeIndex(\"runRequests\", runRequests, effectiveRetention.runRequests, (victim) => {\n\t\t\tvictim.value.dropKey?.();\n\t\t});\n\t}\n\n\tfunction trimExecutions(): void {\n\t\ttrimRuntimeIndex(\"executions\", executions, effectiveRetention.executions, (victim) => {\n\t\t\ttrackExecutionHighWaterEvidence(victim.value.adapterInputId, victim.value.attempt);\n\t\t});\n\t}\n\n\tfunction trimRunStatuses(): void {\n\t\ttrimRuntimeIndex(\"runStatuses\", runStatuses, effectiveRetention.runStatuses, (victim) => {\n\t\t\tvictim.value.dropKey?.();\n\t\t});\n\t}\n\n\tfunction trimRunIssues(): void {\n\t\ttrimRuntimeIndex(\"runIssues\", runIssues, effectiveRetention.runIssues, (victim) => {\n\t\t\tvictim.value.dropKey?.();\n\t\t});\n\t}\n\n\tfunction trimRetentionEvidence(): void {\n\t\ttrimRuntimeIndex(\n\t\t\t\"retentionEvidence\",\n\t\t\tretentionEvidence,\n\t\t\teffectiveRetention.retentionEvidence,\n\t\t\t(victim) => {\n\t\t\t\tcloseRetentionEvidenceHorizon(victim);\n\t\t\t\tif (victim.value.evidenceKind === \"adapter-input-trimmed\") {\n\t\t\t\t\ttrimmedAdapterInputIds.delete(victim.value.adapterInputId);\n\t\t\t\t} else {\n\t\t\t\t\texecutionHighWaterByInput.delete(victim.value.adapterInputId);\n\t\t\t\t}\n\t\t\t\tadapterInputs.delete(victim.value.adapterInputId);\n\t\t\t\tdropProjectorInput(victim.value.adapterInputId);\n\t\t\t},\n\t\t);\n\t}\n\n\tfunction trimAllRetentionIndexes(): void {\n\t\ttrimAdapterInputs();\n\t\ttrimRunRequests();\n\t\ttrimExecutions();\n\t\ttrimRunStatuses();\n\t\ttrimRunIssues();\n\t\ttrimRetentionEvidence();\n\t}\n\n\tfunction publishRetentionTrimmed(\n\t\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\t\tkey: string,\n\t\tentry: unknown,\n\t): void {\n\t\tconst record = isRecord(entry) ? entry : {};\n\t\tconst evidenceKind = typeof record.evidenceKind === \"string\" ? record.evidenceKind : undefined;\n\t\tconst code =\n\t\t\tindex === \"retentionEvidence\"\n\t\t\t\t? \"tool-provider-adapter-runtime-retention-evidence-trimmed\"\n\t\t\t\t: \"tool-provider-adapter-runtime-retention-trimmed\";\n\t\tconst issue = dataIssue(\n\t\t\tcode,\n\t\t\tindex === \"retentionEvidence\"\n\t\t\t\t? \"Tool provider adapter runtime retention trimmed replay proof evidence and closed the affected horizon.\"\n\t\t\t\t: \"Tool provider adapter runtime retention trimmed a runtime-private index entry.\",\n\t\t\t{\n\t\t\t\tsubjectId:\n\t\t\t\t\ttypeof record.adapterInputId === \"string\"\n\t\t\t\t\t\t? record.adapterInputId\n\t\t\t\t\t\t: typeof record.key === \"string\"\n\t\t\t\t\t\t\t? runtimeDiagnosticKey(record.key)\n\t\t\t\t\t\t\t: index,\n\t\t\t\trefs: runtimeEvidenceSourceRefs(index),\n\t\t\t\tdetails: runtimeEvidenceMetadata(index, { key }),\n\t\t\t\tseverity: \"info\",\n\t\t\t},\n\t\t);\n\t\tpublishIssue(issue, false);\n\t\tconst sourceRefs = runtimeEvidenceSourceRefs(index);\n\t\tconst metadata = runtimeEvidenceMetadata(index, {\n\t\t\tkey,\n\t\t\textra: evidenceKind === undefined ? {} : { evidenceKind },\n\t\t});\n\t\tpublishRuntimeStatus({\n\t\t\tstatus: \"retention-trimmed\",\n\t\t\tindex,\n\t\t\tkey,\n\t\t\t...(typeof record.adapterInputId === \"string\"\n\t\t\t\t? { adapterInputId: record.adapterInputId }\n\t\t\t\t: {}),\n\t\t\t...(typeof record.runId === \"string\" ? { runId: record.runId } : {}),\n\t\t\t...(typeof record.attempt === \"number\" ? { attempt: record.attempt } : {}),\n\t\t\tissueCode: issue.code,\n\t\t\tsourceRefs,\n\t\t\tmetadata,\n\t\t});\n\t\tpublishRuntimeAudit(\"tool-provider-adapter-runtime-retention-trimmed\", {\n\t\t\tsubjectId: issue.subjectId,\n\t\t\tsourceRefs,\n\t\t\tissueCode: issue.code,\n\t\t\tmetadata,\n\t\t});\n\t}\n\n\tfunction publishRetentionScoreInvalid(\n\t\tindex: ToolProviderAdapterRuntimeRetentionIndex,\n\t\treason: \"threw\" | \"non-finite\",\n\t): void {\n\t\tconst issue = dataIssue(\n\t\t\t\"tool-provider-adapter-retention-score-invalid\",\n\t\t\t\"Tool provider adapter runtime retention scorer returned invalid material; last-known-good policy remains active.\",\n\t\t\t{\n\t\t\t\tsubjectId: index,\n\t\t\t\trefs: runtimeEvidenceSourceRefs(index),\n\t\t\t\tdetails: runtimeEvidenceMetadata(index, { extra: { reason } }),\n\t\t\t\tseverity: \"warning\",\n\t\t\t},\n\t\t);\n\t\tpublishIssue(issue, index !== \"runIssues\");\n\t\tconst sourceRefs = runtimeEvidenceSourceRefs(index);\n\t\tconst metadata = runtimeEvidenceMetadata(index, { extra: { reason } });\n\t\tpublishRuntimeStatus({\n\t\t\tstatus: \"invalid-retention-policy\",\n\t\t\tindex,\n\t\t\tissueCode: issue.code,\n\t\t\tsourceRefs,\n\t\t\tmetadata,\n\t\t});\n\t\tpublishRuntimeAudit(\"tool-provider-adapter-runtime-invalid-retention-policy\", {\n\t\t\tsubjectId: index,\n\t\t\tsourceRefs,\n\t\t\tissueCode: issue.code,\n\t\t\tmetadata,\n\t\t});\n\t}\n\n\tfunction applyRetentionPolicyFact(fact: RuntimeRetentionPolicyFact): void {\n\t\tconst invalidIndexes = new Set<ToolProviderAdapterRuntimeRetentionIndex>();\n\t\tif (fact.issues !== undefined && fact.issues.length > 0) {\n\t\t\tfor (const issue of fact.issues) {\n\t\t\t\tpublishIssue(issue);\n\t\t\t\tconst index = toolProviderAdapterRuntimeRetentionIndex(issue.subjectId);\n\t\t\t\tif (index !== undefined) invalidIndexes.add(index);\n\t\t\t\tpublishRuntimeStatus({\n\t\t\t\t\tstatus: \"invalid-retention-policy\",\n\t\t\t\t\t...(index === undefined ? {} : { index }),\n\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\t...(index === undefined ? {} : { sourceRefs: runtimeEvidenceSourceRefs(index) }),\n\t\t\t\t});\n\t\t\t\tpublishRuntimeAudit(\"tool-provider-adapter-runtime-invalid-retention-policy\", {\n\t\t\t\t\t...(issue.subjectId === undefined ? {} : { subjectId: issue.subjectId }),\n\t\t\t\t\t...(index === undefined ? {} : { sourceRefs: runtimeEvidenceSourceRefs(index) }),\n\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst adapterInputsPolicy = fact.policies.get(\"adapterInputs\");\n\t\tconst runRequestsPolicy = fact.policies.get(\"runRequests\");\n\t\tconst executionsPolicy = fact.policies.get(\"executions\");\n\t\tconst runStatusesPolicy = fact.policies.get(\"runStatuses\");\n\t\tconst runIssuesPolicy = fact.policies.get(\"runIssues\");\n\t\tconst retentionEvidencePolicy = fact.policies.get(\"retentionEvidence\");\n\t\teffectiveRetention = {\n\t\t\t...(invalidIndexes.has(\"adapterInputs\")\n\t\t\t\t? effectiveRetention.adapterInputs === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { adapterInputs: effectiveRetention.adapterInputs }\n\t\t\t\t: adapterInputsPolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { adapterInputs: adapterInputsPolicy }),\n\t\t\t...(invalidIndexes.has(\"runRequests\")\n\t\t\t\t? effectiveRetention.runRequests === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runRequests: effectiveRetention.runRequests }\n\t\t\t\t: runRequestsPolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runRequests: runRequestsPolicy }),\n\t\t\t...(invalidIndexes.has(\"executions\")\n\t\t\t\t? effectiveRetention.executions === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { executions: effectiveRetention.executions }\n\t\t\t\t: executionsPolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { executions: executionsPolicy }),\n\t\t\t...(invalidIndexes.has(\"runStatuses\")\n\t\t\t\t? effectiveRetention.runStatuses === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runStatuses: effectiveRetention.runStatuses }\n\t\t\t\t: runStatusesPolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runStatuses: runStatusesPolicy }),\n\t\t\t...(invalidIndexes.has(\"runIssues\")\n\t\t\t\t? effectiveRetention.runIssues === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runIssues: effectiveRetention.runIssues }\n\t\t\t\t: runIssuesPolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { runIssues: runIssuesPolicy }),\n\t\t\t...(invalidIndexes.has(\"retentionEvidence\")\n\t\t\t\t? effectiveRetention.retentionEvidence === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { retentionEvidence: effectiveRetention.retentionEvidence }\n\t\t\t\t: retentionEvidencePolicy === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { retentionEvidence: retentionEvidencePolicy }),\n\t\t};\n\t\ttrimAllRetentionIndexes();\n\t}\n\n\tfunction publishStatus(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tnextStatus: AgentRequestStatus,\n\t\tstatusIssues?: readonly DataIssue[],\n\t): void {\n\t\tif (input.effectRunId === undefined) return;\n\t\tconst metadata = sanitizeGraphVisibleRecord({\n\t\t\tadapterInputId: input.adapterInputId,\n\t\t\tproviderId: input.providerId,\n\t\t\ttoolName: input.toolName,\n\t\t});\n\t\tstatus.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tkind: \"status\",\n\t\t\t\t\trequestId: input.requestId,\n\t\t\t\t\toperationId: input.operationId,\n\t\t\t\t\teffectRunId: input.effectRunId,\n\t\t\t\t\tstatus: nextStatus,\n\t\t\t\t\tsourceRefs: defaultToolProviderAdapterEvidenceRefs(input),\n\t\t\t\t\t...(statusIssues === undefined ? {} : { issues: statusIssues }),\n\t\t\t\t\t...(metadata === undefined ? {} : { metadata }),\n\t\t\t\t} satisfies AgentRequestStatusChanged,\n\t\t\t],\n\t\t]);\n\t}\n\n\tfunction publishAudit(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tkind: string,\n\t\tmetadata?: Record<string, unknown>,\n\t\tissueCode?: string,\n\t): void {\n\t\tauditSeq += 1;\n\t\tconst cleanMetadata = sanitizeGraphVisibleRecord({\n\t\t\tadapterInputId: input.adapterInputId,\n\t\t\tproviderId: input.providerId,\n\t\t\ttoolName: input.toolName,\n\t\t\t...metadata,\n\t\t});\n\t\taudit.down([\n\t\t\t[\n\t\t\t\t\"DATA\",\n\t\t\t\t{\n\t\t\t\t\tid: `${name}:audit:${auditSeq}`,\n\t\t\t\t\tkind,\n\t\t\t\t\tsubjectId: input.requestId,\n\t\t\t\t\tsourceRefs: defaultToolProviderAdapterEvidenceRefs(input),\n\t\t\t\t\t...(issueCode === undefined ? {} : { issueCode }),\n\t\t\t\t\t...(cleanMetadata === undefined ? {} : { metadata: cleanMetadata }),\n\t\t\t\t} satisfies AgentRuntimeAuditRecord,\n\t\t\t],\n\t\t]);\n\t}\n\n\tfunction publishOutcome(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\tresult: ToolProviderAdapterRunResult<TResult>,\n\t\trequest: ToolProviderAdapterRunRequested,\n\t): void {\n\t\tif (disposed) return;\n\t\tlet outcome: ExecutorOutcome<TResult>;\n\t\ttry {\n\t\t\toutcome = buildToolProviderExecutorOutcome(input, result, {\n\t\t\t\tattempt: request.attempt,\n\t\t\t\trunId: request.runId,\n\t\t\t\toccurredAtMs: opts.now?.(),\n\t\t\t\tpublicText: opts.publicText,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst issue = adapterRuntimeIssue(\n\t\t\t\tinput,\n\t\t\t\t\"tool-provider-adapter-runtime-invalid-input\",\n\t\t\t\terror,\n\t\t\t);\n\t\t\tpublishIssue(issue);\n\t\t\tpublishRunStatus(request, \"failure\", [issue]);\n\t\t\tpublishStatus(input, \"failed\", [issue]);\n\t\t\tpublishAudit(input, \"tool-provider-adapter-runtime-invalid-input\", undefined, issue.code);\n\t\t\treturn;\n\t\t}\n\t\toutcomes.down([[\"DATA\", outcome]]);\n\t\tconst execution = executions.get(executionCoordinate(request));\n\t\tif (execution !== undefined) {\n\t\t\texecutions.set(\n\t\t\t\texecution.key,\n\t\t\t\texecutionRetentionEntry(\n\t\t\t\t\texecution.key,\n\t\t\t\t\texecution.entry.sequence,\n\t\t\t\t\trequest,\n\t\t\t\t\toutcome.kind,\n\t\t\t\t\toutcome.occurredAtMs,\n\t\t\t\t\toutcome.outcomeId,\n\t\t\t\t),\n\t\t\t\trequest,\n\t\t\t);\n\t\t}\n\t\tconst publishedIssueKeys = new Set<string>();\n\t\tfor (const issue of outcome.issues ?? []) {\n\t\t\tpublishedIssueKeys.add(`${issue.code}:${issue.message}`);\n\t\t\tpublishIssue(issue);\n\t\t}\n\t\tif (\n\t\t\toutcome.kind === \"failure\" &&\n\t\t\t!publishedIssueKeys.has(`${outcome.error.code}:${outcome.error.message}`)\n\t\t) {\n\t\t\tpublishIssue(outcome.error);\n\t\t}\n\t\tconst statusIssues = outcomeIssues(outcome);\n\t\tpublishStatus(\n\t\t\tinput,\n\t\t\tagentRequestStatusForExecutorOutcome(outcome),\n\t\t\tstatusIssues.length === 0 ? undefined : statusIssues,\n\t\t);\n\t\tpublishRunStatus(\n\t\t\trequest,\n\t\t\toutcome.kind,\n\t\t\tstatusIssues.length === 0 ? undefined : statusIssues,\n\t\t\toutcome.outcomeId,\n\t\t);\n\t\tpublishAudit(input, \"tool-provider-adapter-runtime-finished\", {\n\t\t\tstatus: outcome.kind,\n\t\t\toutcomeId: outcome.outcomeId,\n\t\t\trunId: request.runId,\n\t\t\tattempt: request.attempt,\n\t\t});\n\t}\n\n\tfunction publishRuntimeFailure(\n\t\tinput: ToolProviderAdapterInput<TArguments>,\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tcode: string,\n\t\terror: unknown,\n\t): void {\n\t\tconst issue = adapterRuntimeIssue(input, code, error);\n\t\tpublishOutcome(\n\t\t\tinput,\n\t\t\t{\n\t\t\t\tkind: \"failure\",\n\t\t\t\terror: issue,\n\t\t\t\tretryable: false,\n\t\t\t\tissues: [issue],\n\t\t\t},\n\t\t\trequest,\n\t\t);\n\t}\n\n\tfunction executionCoordinate(request: ToolProviderAdapterRunRequested): string {\n\t\treturn `${request.adapterInputId}:${request.attempt}`;\n\t}\n\n\tfunction trackRunRequest(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\temittedKey: string,\n\t\tdropKey: () => void,\n\t): void {\n\t\tconst sequence = nextRetentionSequence();\n\t\trunRequests.set(emittedKey, runRequestRetentionEntry(emittedKey, sequence, request), {\n\t\t\tfact: request,\n\t\t\tdropKey,\n\t\t});\n\t\ttrimRunRequests();\n\t}\n\n\tfunction startExecutionProof(request: ToolProviderAdapterRunRequested): boolean {\n\t\tconst coordinate = executionCoordinate(request);\n\t\tconst existing = executions.get(coordinate);\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.value.runId !== request.runId) {\n\t\t\t\tconst issue = dataIssue(\n\t\t\t\t\t\"tool-provider-adapter-runtime-duplicate-execution-coordinate\",\n\t\t\t\t\t\"Tool provider adapter runtime requires one visible runId per adapterInputId and attempt.\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\t\trefs: [ref(\"tool-provider-adapter-run\", request.runId)],\n\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tpublishIssue(issue);\n\t\t\t\tpublishRunStatus(request, \"mismatched-request\", [issue]);\n\t\t\t\tpublishRuntimeAudit(\"tool-provider-adapter-runtime-duplicate-execution-coordinate\", {\n\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\tsourceRefs: [ref(\"tool-provider-adapter-run\", request.runId)],\n\t\t\t\t\tissueCode: issue.code,\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\tkey: runtimeDiagnosticKey(coordinate),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tconst sequence = nextRetentionSequence();\n\t\texecutions.set(\n\t\t\tcoordinate,\n\t\t\texecutionRetentionEntry(coordinate, sequence, request, \"started\", nowMs()),\n\t\t\trequest,\n\t\t);\n\t\ttrimExecutions();\n\t\tconst classification = classifyRunRequestReplayEvidence(\n\t\t\trequest,\n\t\t\tadapterInputs.get(request.adapterInputId)?.value,\n\t\t);\n\t\tif (classification.kind !== \"fresh\") {\n\t\t\texecutions.delete(coordinate);\n\t\t\tpublishReplayClassification(request, classification);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tfunction publishReplayClassification(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tclassification: ReplayEvidenceClassification,\n\t): boolean {\n\t\tif (classification.kind === \"fresh\") return false;\n\t\tif (classification.kind === \"missing-input\") {\n\t\t\tconst issueCode = \"tool-provider-adapter-runtime-missing-input\";\n\t\t\tconst issue = dataIssue(\n\t\t\t\tissueCode,\n\t\t\t\t\"Tool provider adapter runtime requires the requested adapter input.\",\n\t\t\t\t{\n\t\t\t\t\tsubjectId: request.adapterInputId,\n\t\t\t\t\trefs: [ref(\"tool-provider-adapter-run\", request.runId)],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tadapterInputId: request.adapterInputId,\n\t\t\t\t\t\trunId: request.runId,\n\t\t\t\t\t\tattempt: request.attempt,\n\t\t\t\t\t\tissueCode,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tpublishIssue(issue);\n\t\t\tpublishRunStatus(request, \"missing-input\", [issue]);\n\t\t\treturn true;\n\t\t}\n\t\tpublishRetentionGap(request, classification);\n\t\treturn true;\n\t}\n\n\tfunction publishRetentionGap(\n\t\trequest: ToolProviderAdapterRunRequested,\n\t\tclassification: Extract<ReplayEvidenceClassification, { readonly kind: \"retention-gap\" }>,\n\t): void {\n\t\tpublishAdapterRuntimeRetentionGap(\n\t\t\t{ publishIssue, publishRunStatus, publishRuntimeStatus, publishRuntimeAudit },\n\t\t\trequest,\n\t\t\tclassification,\n\t\t);\n\t}\n\n\tfunction publishRetentionEvidenceGlobalFailClosed(\n\t\tvictim: RuntimeIndexItem<\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry,\n\t\t\tToolProviderAdapterRuntimeRetentionEvidenceEntry\n\t\t>,\n\t): void {\n\t\tpublishAdapterRuntimeRetentionEvidenceGlobalFailClosed(\n\t\t\t{ publishIssue, publishRunStatus, publishRuntimeStatus, publishRuntimeAudit },\n\t\t\tvictim,\n\t\t);\n\t}\n\n\tfunction runRequest(request: ToolProviderAdapterRunRequested): void {\n\t\trunAdapterRuntimeRequest(\n\t\t\t{\n\t\t\t\tisDisposed: () => disposed,\n\t\t\t\tadapterInputs,\n\t\t\t\texecutions,\n\t\t\t\tbindings,\n\t\t\t\tnow: opts.now,\n\t\t\t\tclassifyRunRequestReplayEvidence,\n\t\t\t\tpublishReplayClassification,\n\t\t\t\tstartExecutionProof,\n\t\t\t\texecutionCoordinate,\n\t\t\t\tpublishIssue,\n\t\t\t\tpublishRunStatus,\n\t\t\t\tpublishStatus,\n\t\t\t\tpublishAudit,\n\t\t\t\tpublishOutcome,\n\t\t\t\tpublishRuntimeFailure,\n\t\t\t},\n\t\t\trequest,\n\t\t);\n\t}\n\n\tconst unsubscribeRetentionPolicy = retentionPolicy.subscribe((msg) => {\n\t\tif (msg[0] === \"DATA\") applyRetentionPolicyFact(msg[1] as RuntimeRetentionPolicyFact);\n\t});\n\tconst unsubscribeInputs = opts.inputs.subscribe((msg) => {\n\t\tif (msg[0] !== \"DATA\") return;\n\t\tconst input = msg[1] as ToolProviderAdapterInput<TArguments>;\n\t\tif (isRetentionEvidenceClosed(input.adapterInputId)) {\n\t\t\tadapterInputs.delete(input.adapterInputId);\n\t\t\tdropProjectorInput(input.adapterInputId);\n\t\t\treturn;\n\t\t}\n\t\tif (trimmedAdapterInputIds.delete(input.adapterInputId)) {\n\t\t\tretentionEvidence.delete(`adapter-input-trimmed:${input.adapterInputId}`);\n\t\t}\n\t\tconst sequence = nextRetentionSequence();\n\t\tadapterInputs.set(\n\t\t\tinput.adapterInputId,\n\t\t\tadapterInputRetentionEntry(input.adapterInputId, sequence, input, nowMs()),\n\t\t\tinput,\n\t\t);\n\t\ttrimAdapterInputs();\n\t});\n\tconst runProjector = toolProviderAdapterRunProjectorInternal(graph, {\n\t\tname: `${name}/runs`,\n\t\tinputs: opts.inputs,\n\t\trunRequests: opts.runRequests,\n\t\tautoRunReadyInputs: opts.autoRunReadyInputs,\n\t\tnow: opts.now,\n\t\tpublicText: opts.publicText,\n\t\tprivateRetentionHooks: {\n\t\t\tonRunRequestKey(entry) {\n\t\t\t\ttrackRunRequest(entry.request, entry.key, entry.dropKey);\n\t\t\t},\n\t\t\tonRunStatusKey(entry) {\n\t\t\t\ttrackRunStatus(entry.status, entry.key, entry.dropKey);\n\t\t\t},\n\t\t\tonRunIssueKey(entry) {\n\t\t\t\ttrackRunIssue(entry.issue, entry.key, entry.dropKey);\n\t\t\t},\n\t\t\tonAdapterInputKey(entry) {\n\t\t\t\tif (\n\t\t\t\t\tisRetentionEvidenceClosed(entry.adapterInputId) ||\n\t\t\t\t\t!adapterInputs.has(entry.adapterInputId)\n\t\t\t\t) {\n\t\t\t\t\tentry.dropInput();\n\t\t\t\t\tprojectorInputDropById.delete(entry.adapterInputId);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprojectorInputDropById.set(entry.adapterInputId, entry.dropInput);\n\t\t\t},\n\t\t\tclassifyRetainedRunRequestReplayEvidence,\n\t\t},\n\t});\n\tconst unsubscribeRunProjectorStatus = runProjector.status.subscribe((msg) => {\n\t\tif (msg[0] === \"DATA\") {\n\t\t\tconst statusFact = msg[1] as ToolProviderAdapterRunStatus;\n\t\t\trunStatus.down([[\"DATA\", statusFact]]);\n\t\t}\n\t});\n\tconst unsubscribeRunProjectorIssues = runProjector.issues.subscribe((msg) => {\n\t\tif (msg[0] === \"DATA\") publishIssue(msg[1] as DataIssue, false);\n\t});\n\tconst unsubscribeRunProjectorAudit = runProjector.audit.subscribe((msg) => {\n\t\tif (msg[0] === \"DATA\") audit.down([[\"DATA\", msg[1] as AgentRuntimeAuditRecord]]);\n\t});\n\tconst unsubscribeRunRequests = runProjector.requests.subscribe((msg) => {\n\t\tif (msg[0] !== \"DATA\") return;\n\t\tconst request = msg[1] as ToolProviderAdapterRunRequested;\n\t\trunRequest(request);\n\t});\n\n\treturn {\n\t\trunRequests: runProjector.requests,\n\t\trunStatus,\n\t\truntimeStatus,\n\t\toutcomes,\n\t\tstatus,\n\t\tissues,\n\t\taudit,\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tunsubscribeRetentionPolicy();\n\t\t\tunsubscribeInputs();\n\t\t\tunsubscribeRunProjectorStatus();\n\t\t\tunsubscribeRunProjectorIssues();\n\t\t\tunsubscribeRunProjectorAudit();\n\t\t\tunsubscribeRunRequests();\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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,IAAI;AAC9D;AAEO,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAM7B,IAAM,OAAoC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,OAAO;AAAA,EACP,UAAU;AACX;AAEO,SAAS,YAAY,GAAwB;AACnD,SAAO,KAAK,CAAC;AACd;AAGO,SAAS,eAAe,GAAyB;AACvD,SAAO,KAAK,CAAC,KAAK;A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