@graphrefly/ts 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +197 -117
- package/dist/actions-types-CH-XCU9O.d.cts +657 -0
- package/dist/actions-types-w2iPQTkv.d.ts +657 -0
- package/dist/adapters/index.cjs +5157 -2951
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +207 -70
- package/dist/adapters/index.d.ts +207 -70
- package/dist/adapters/index.js +3738 -1688
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/nestjs/microservices.cjs +841 -0
- package/dist/adapters/nestjs/microservices.cjs.map +1 -0
- package/dist/adapters/nestjs/microservices.d.cts +45 -0
- package/dist/adapters/nestjs/microservices.d.ts +45 -0
- package/dist/adapters/nestjs/microservices.js +206 -0
- package/dist/adapters/nestjs/microservices.js.map +1 -0
- package/dist/adapters/nestjs/native.cjs +1391 -0
- package/dist/adapters/nestjs/native.cjs.map +1 -0
- package/dist/adapters/nestjs/native.d.cts +111 -0
- package/dist/adapters/nestjs/native.d.ts +111 -0
- package/dist/adapters/nestjs/native.js +577 -0
- package/dist/adapters/nestjs/native.js.map +1 -0
- package/dist/adapters/nestjs/websockets.cjs +924 -0
- package/dist/adapters/nestjs/websockets.cjs.map +1 -0
- package/dist/adapters/nestjs/websockets.d.cts +47 -0
- package/dist/adapters/nestjs/websockets.d.ts +47 -0
- package/dist/adapters/nestjs/websockets.js +286 -0
- package/dist/adapters/nestjs/websockets.js.map +1 -0
- package/dist/adapters/nestjs.cjs +1085 -0
- package/dist/adapters/nestjs.cjs.map +1 -0
- package/dist/adapters/nestjs.d.cts +385 -0
- package/dist/adapters/nestjs.d.ts +385 -0
- package/dist/adapters/nestjs.js +112 -0
- package/dist/adapters/nestjs.js.map +1 -0
- package/dist/adapters/observe-storage.d.cts +3 -3
- package/dist/adapters/observe-storage.d.ts +3 -3
- package/dist/adapters/observe-storage.js +4 -4
- package/dist/adapters/react.cjs.map +1 -1
- package/dist/adapters/react.d.cts +2 -2
- package/dist/adapters/react.d.ts +2 -2
- package/dist/adapters/react.js +1 -1
- package/dist/adapters/solid.cjs.map +1 -1
- package/dist/adapters/solid.d.cts +2 -2
- package/dist/adapters/solid.d.ts +2 -2
- package/dist/adapters/solid.js +1 -1
- package/dist/adapters/svelte.cjs.map +1 -1
- package/dist/adapters/svelte.d.cts +2 -2
- package/dist/adapters/svelte.d.ts +2 -2
- package/dist/adapters/svelte.js +1 -1
- package/dist/adapters/vue.cjs.map +1 -1
- package/dist/adapters/vue.d.cts +2 -2
- package/dist/adapters/vue.d.ts +2 -2
- package/dist/adapters/vue.js +1 -1
- package/dist/{agent-runtime-BesGDZcB.d.ts → agent-runtime-types-core-CKwrBDyi.d.ts} +171 -320
- package/dist/{agent-runtime-DZTJ3C-p.d.cts → agent-runtime-types-core-bfl4m0vM.d.cts} +171 -320
- package/dist/agent-runtime-types-tool-BLPV3azj.d.cts +695 -0
- package/dist/agent-runtime-types-tool-hwqvVqNt.d.ts +695 -0
- package/dist/agentic-memory-retention-CLwI76JK.d.ts +14 -0
- package/dist/agentic-memory-retention-Cz8GR6ie.d.cts +14 -0
- package/dist/{agentic-memory-DfuVZ-lY.d.cts → agentic-memory-types-JDr7MPhh.d.cts} +13 -57
- package/dist/{agentic-memory-BmRCvh0d.d.ts → agentic-memory-types-khYJgzKL.d.ts} +13 -57
- package/dist/{capability-admission-B0BzqAm5.d.cts → capability-admission-B8RNFyaZ.d.cts} +3 -3
- package/dist/{capability-admission-g0mn9hpq.d.ts → capability-admission-Dkw1Xz3r.d.ts} +3 -3
- package/dist/chunk-2KUAG2GZ.js +9693 -0
- package/dist/chunk-2KUAG2GZ.js.map +1 -0
- package/dist/{chunk-CZNV3VXM.js → chunk-3J7UPZL5.js} +11 -11
- package/dist/{chunk-HKK2JD7Z.js → chunk-3LYI6ADX.js} +12 -125
- package/dist/chunk-3LYI6ADX.js.map +1 -0
- package/dist/{chunk-YXMZ2N6J.js → chunk-4M37FH2I.js} +1071 -1025
- package/dist/chunk-4M37FH2I.js.map +1 -0
- package/dist/{chunk-YDSIVHRR.js → chunk-4NWSNI4K.js} +1598 -1584
- package/dist/chunk-4NWSNI4K.js.map +1 -0
- package/dist/{chunk-Z2ANQ6JW.js → chunk-4Q77MMJY.js} +2 -2
- package/dist/{chunk-SS2A464I.js → chunk-54WPEODM.js} +3 -3
- package/dist/chunk-54WPEODM.js.map +1 -0
- package/dist/chunk-6E76H4OU.js +132 -0
- package/dist/chunk-6E76H4OU.js.map +1 -0
- package/dist/chunk-7GOTIIQ7.js +819 -0
- package/dist/chunk-7GOTIIQ7.js.map +1 -0
- package/dist/{chunk-V7CIJE4B.js → chunk-DKFWDTVY.js} +92 -9
- package/dist/chunk-DKFWDTVY.js.map +1 -0
- package/dist/{chunk-FBUU43PM.js → chunk-E4QCH32M.js} +448 -446
- package/dist/chunk-E4QCH32M.js.map +1 -0
- package/dist/{chunk-XKXWK2KP.js → chunk-GXU6WFEJ.js} +1157 -1021
- package/dist/chunk-GXU6WFEJ.js.map +1 -0
- package/dist/{chunk-K3FXTC3I.js → chunk-HJACH5PU.js} +3 -3
- package/dist/{chunk-GTPCOEOZ.js → chunk-IDMLXLLG.js} +3 -3
- package/dist/{chunk-DKP56CSW.js → chunk-JKAYLDQV.js} +2 -2
- package/dist/{chunk-4VLAQHZI.js → chunk-K7FB3JTD.js} +17 -1
- package/dist/chunk-K7FB3JTD.js.map +1 -0
- package/dist/{chunk-43BKLFZU.js → chunk-KFURM6FM.js} +10 -10
- package/dist/{chunk-H75VXTGT.js → chunk-L6LDXRWE.js} +3 -3
- package/dist/{chunk-H75VXTGT.js.map → chunk-L6LDXRWE.js.map} +1 -1
- package/dist/chunk-MCOFHMUU.js +4131 -0
- package/dist/chunk-MCOFHMUU.js.map +1 -0
- package/dist/chunk-MQEQMS7B.js +1009 -0
- package/dist/chunk-MQEQMS7B.js.map +1 -0
- package/dist/chunk-MTELVIYR.js +1421 -0
- package/dist/chunk-MTELVIYR.js.map +1 -0
- package/dist/{chunk-3JR3EDB2.js → chunk-NNDIFUKX.js} +121 -115
- package/dist/chunk-NNDIFUKX.js.map +1 -0
- package/dist/{chunk-2747WN4Y.js → chunk-PUSRRALM.js} +3 -3
- package/dist/{chunk-QFY4AFY4.js → chunk-PVC7WDKI.js} +58 -52
- package/dist/chunk-PVC7WDKI.js.map +1 -0
- package/dist/{chunk-VTHLCFN4.js → chunk-RAHNUYA5.js} +2 -2
- package/dist/chunk-TQPCAIQI.js +612 -0
- package/dist/chunk-TQPCAIQI.js.map +1 -0
- package/dist/{chunk-IXZBUWSP.js → chunk-UEMN5URK.js} +2 -2
- package/dist/chunk-WOS7RJYZ.js +1320 -0
- package/dist/chunk-WOS7RJYZ.js.map +1 -0
- package/dist/{chunk-6PHB5CJS.js → chunk-ZLFRB6FI.js} +2 -2
- package/dist/composition/index.cjs +1228 -1076
- package/dist/composition/index.cjs.map +1 -1
- package/dist/composition/index.d.cts +3 -3
- package/dist/composition/index.d.ts +3 -3
- package/dist/composition/index.js +4 -4
- package/dist/core/index.cjs +1198 -1046
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +23 -2
- package/dist/core/index.d.ts +23 -2
- package/dist/core/index.js +2 -2
- package/dist/cqrs/index.d.cts +3 -3
- package/dist/cqrs/index.d.ts +3 -3
- package/dist/cqrs/messaging.d.cts +4 -4
- package/dist/cqrs/messaging.d.ts +4 -4
- package/dist/cqrs/work-queue.d.cts +5 -5
- package/dist/cqrs/work-queue.d.ts +5 -5
- package/dist/data-structures/index.cjs +1226 -1074
- package/dist/data-structures/index.cjs.map +1 -1
- package/dist/data-structures/index.d.cts +8 -7
- package/dist/data-structures/index.d.ts +8 -7
- package/dist/data-structures/index.js +6 -5
- package/dist/{describe-DYMw_l1C.d.cts → describe-BumQ-3_0.d.cts} +1 -1
- package/dist/{describe-BpyJuWkw.d.ts → describe-cYr_Z5zm.d.ts} +1 -1
- package/dist/executors/tool-provider-adapters.cjs +3091 -0
- package/dist/executors/tool-provider-adapters.cjs.map +1 -0
- package/dist/executors/tool-provider-adapters.d.cts +174 -0
- package/dist/executors/tool-provider-adapters.d.ts +174 -0
- package/dist/executors/tool-provider-adapters.js +1336 -0
- package/dist/executors/tool-provider-adapters.js.map +1 -0
- package/dist/executors/tool-provider-runtime.cjs +5178 -0
- package/dist/executors/tool-provider-runtime.cjs.map +1 -0
- package/dist/executors/tool-provider-runtime.d.cts +17 -0
- package/dist/executors/tool-provider-runtime.d.ts +17 -0
- package/dist/executors/tool-provider-runtime.js +15 -0
- package/dist/executors/tool-provider-runtime.js.map +1 -0
- package/dist/executors/tool-provider.cjs +6392 -0
- package/dist/executors/tool-provider.cjs.map +1 -0
- package/dist/executors/tool-provider.d.cts +60 -0
- package/dist/executors/tool-provider.d.ts +60 -0
- package/dist/executors/tool-provider.js +89 -0
- package/dist/executors/tool-provider.js.map +1 -0
- package/dist/executors/work-queue.d.cts +6 -6
- package/dist/executors/work-queue.d.ts +6 -6
- package/dist/graph/index.cjs +1499 -1341
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +9 -8
- package/dist/graph/index.d.ts +9 -8
- package/dist/graph/index.js +23 -22
- package/dist/{graph-DCEWh4T2.d.cts → graph-C1C-wb0L.d.cts} +266 -137
- package/dist/{graph-D-1-SQeC.d.ts → graph-CS0b4V9B.d.ts} +266 -137
- package/dist/{index-72VZC0-E.d.cts → index-DLrNopda.d.cts} +151 -10
- package/dist/{index-Bmxeu0nK.d.ts → index-DzJni3_6.d.ts} +151 -10
- package/dist/index.cjs +3397 -3140
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -9
- package/dist/index.d.ts +12 -9
- package/dist/index.js +110 -109
- package/dist/inspection/boundary.d.cts +4 -4
- package/dist/inspection/boundary.d.ts +4 -4
- package/dist/measurements-BWAnochv.d.ts +294 -0
- package/dist/measurements-B_gJfD8h.d.cts +294 -0
- package/dist/messaging/index.cjs +57 -51
- package/dist/messaging/index.cjs.map +1 -1
- package/dist/messaging/index.d.cts +11 -276
- package/dist/messaging/index.d.ts +11 -276
- package/dist/messaging/index.js +1 -1
- package/dist/operators/index.cjs +1228 -1076
- package/dist/operators/index.cjs.map +1 -1
- package/dist/operators/index.d.cts +5 -5
- package/dist/operators/index.d.ts +5 -5
- package/dist/operators/index.js +5 -5
- package/dist/orchestration/index.cjs +8844 -6071
- package/dist/orchestration/index.cjs.map +1 -1
- package/dist/orchestration/index.d.cts +171 -224
- package/dist/orchestration/index.d.ts +171 -224
- package/dist/orchestration/index.js +42 -991
- package/dist/orchestration/index.js.map +1 -1
- package/dist/orchestration/messaging.d.cts +5 -8
- package/dist/orchestration/messaging.d.ts +5 -8
- package/dist/orchestration/work-queue.cjs +1243 -5
- package/dist/orchestration/work-queue.cjs.map +1 -1
- package/dist/orchestration/work-queue.d.cts +121 -10
- package/dist/orchestration/work-queue.d.ts +121 -10
- package/dist/orchestration/work-queue.js +1067 -4
- package/dist/orchestration/work-queue.js.map +1 -1
- package/dist/patterns/event-flow.cjs +6 -20
- package/dist/patterns/event-flow.cjs.map +1 -1
- package/dist/patterns/event-flow.d.cts +4 -4
- package/dist/patterns/event-flow.d.ts +4 -4
- package/dist/patterns/event-flow.js +2 -2
- package/dist/patterns/index.cjs +453 -465
- package/dist/patterns/index.cjs.map +1 -1
- package/dist/patterns/index.d.cts +6 -5
- package/dist/patterns/index.d.ts +6 -5
- package/dist/patterns/index.js +3 -3
- package/dist/process-types-BB7oRhX3.d.cts +200 -0
- package/dist/process-types-QNhyoYJ8.d.ts +200 -0
- package/dist/{reactive-collection-DNV0-gFi.d.cts → reactive-collection-BYlWvtnp.d.cts} +4 -34
- package/dist/{reactive-collection-BAmfrGjd.d.ts → reactive-collection-efOEdGFN.d.ts} +4 -34
- package/dist/{reactive-collection-storage-BNEldDyi.d.cts → reactive-collection-storage-BjoLsoiC.d.cts} +5 -5
- package/dist/{reactive-collection-storage-YZsAQsWK.d.ts → reactive-collection-storage-DwW6UuK_.d.ts} +5 -5
- package/dist/{reactive-map-DRD1LJ2H.d.cts → reactive-map-BHacbIqz.d.cts} +7 -2
- package/dist/{reactive-map-EsDiCmJk.d.ts → reactive-map-DN4Jyqnf.d.ts} +7 -2
- package/dist/render/index.d.cts +2 -2
- package/dist/render/index.d.ts +2 -2
- package/dist/scheduled-readiness-BmqXxnzX.d.ts +91 -0
- package/dist/scheduled-readiness-CYSw7KDE.d.cts +91 -0
- package/dist/semantic-memory-graph-B_LwbM-E.d.cts +30 -0
- package/dist/semantic-memory-graph-rsFNNhwn.d.ts +30 -0
- package/dist/{semantic-memory-graph-DKuNzuWw.d.cts → semantic-memory-graph-types-Y73bbwVI.d.cts} +2 -28
- package/dist/{semantic-memory-graph-uwbwJdhe.d.ts → semantic-memory-graph-types-safmPkuX.d.ts} +2 -28
- package/dist/solutions/index.cjs +6353 -6169
- package/dist/solutions/index.cjs.map +1 -1
- package/dist/solutions/index.d.cts +12 -10
- package/dist/solutions/index.d.ts +12 -10
- package/dist/solutions/index.js +5 -5
- package/dist/solutions/reactive-layout/browser/index.cjs +116 -108
- package/dist/solutions/reactive-layout/browser/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/browser/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/browser/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/browser/index.js +3 -3
- package/dist/solutions/reactive-layout/index.cjs +3578 -3350
- package/dist/solutions/reactive-layout/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/index.d.cts +32 -576
- package/dist/solutions/reactive-layout/index.d.ts +32 -576
- package/dist/solutions/reactive-layout/index.js +65 -5
- package/dist/solutions/reactive-layout/node-canvas/index.cjs +127 -117
- package/dist/solutions/reactive-layout/node-canvas/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/node-canvas/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/node-canvas/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/node-canvas/index.js +3 -3
- package/dist/solutions/reactive-layout/react-native/index.cjs +127 -117
- package/dist/solutions/reactive-layout/react-native/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/react-native/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/react-native/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/react-native/index.js +3 -3
- package/dist/solutions/reactive-layout/skia/index.cjs +127 -117
- package/dist/solutions/reactive-layout/skia/index.cjs.map +1 -1
- package/dist/solutions/reactive-layout/skia/index.d.cts +4 -4
- package/dist/solutions/reactive-layout/skia/index.d.ts +4 -4
- package/dist/solutions/reactive-layout/skia/index.js +3 -3
- package/dist/solutions/work-item/actions.cjs +1609 -1428
- package/dist/solutions/work-item/actions.cjs.map +1 -1
- package/dist/solutions/work-item/actions.d.cts +23 -184
- package/dist/solutions/work-item/actions.d.ts +23 -184
- package/dist/solutions/work-item/actions.js +1558 -934
- package/dist/solutions/work-item/actions.js.map +1 -1
- package/dist/solutions/work-item/scheduling.cjs +9181 -1838
- package/dist/solutions/work-item/scheduling.cjs.map +1 -1
- package/dist/solutions/work-item/scheduling.d.cts +1763 -328
- package/dist/solutions/work-item/scheduling.d.ts +1763 -328
- package/dist/solutions/work-item/scheduling.js +117 -3
- package/dist/solutions/work-item/work-queue.d.cts +7 -7
- package/dist/solutions/work-item/work-queue.d.ts +7 -7
- package/dist/sources/browser.cjs +1318 -1083
- package/dist/sources/browser.cjs.map +1 -1
- package/dist/sources/browser.d.cts +22 -6
- package/dist/sources/browser.d.ts +22 -6
- package/dist/sources/browser.js +4 -4
- package/dist/sources/browser.js.map +1 -1
- package/dist/sources/index.cjs +1318 -1083
- package/dist/sources/index.cjs.map +1 -1
- package/dist/sources/index.d.cts +4 -4
- package/dist/sources/index.d.ts +4 -4
- package/dist/sources/index.js +4 -4
- package/dist/sources/node.d.cts +3 -3
- package/dist/sources/node.d.ts +3 -3
- package/dist/storage/browser.cjs +16 -0
- package/dist/storage/browser.cjs.map +1 -1
- package/dist/storage/browser.js +3 -3
- package/dist/storage/index.cjs +16 -0
- package/dist/storage/index.cjs.map +1 -1
- package/dist/storage/index.d.cts +5 -4
- package/dist/storage/index.d.ts +5 -4
- package/dist/storage/index.js +6 -6
- package/dist/storage/node.cjs +16 -0
- package/dist/storage/node.cjs.map +1 -1
- package/dist/storage/node.js +3 -3
- package/dist/{store-C-joM4gh.d.ts → store-6_CHF6Ge.d.ts} +1 -1
- package/dist/{store-CNJwmT-h.d.cts → store-BljX8RkQ.d.cts} +1 -1
- package/dist/types-BAw2QVVE.d.cts +274 -0
- package/dist/types-BUbbbh4f.d.cts +34 -0
- package/dist/types-CMnzoL54.d.cts +457 -0
- package/dist/{types-CcPIn7sy.d.cts → types-CTN3XoMl.d.cts} +57 -108
- package/dist/types-CV_ohy5T.d.cts +357 -0
- package/dist/{types-BsJvElYZ.d.ts → types-DChxk1vK.d.ts} +57 -108
- package/dist/types-DRu7SnLV.d.ts +274 -0
- package/dist/types-DeID_FRl.d.ts +34 -0
- package/dist/types-IhKH0hGW.d.ts +357 -0
- package/dist/types-ePlD2uyT.d.ts +457 -0
- package/dist/{work-item-runtime-qaVgsL0T.d.cts → work-item-runtime-types-BTxLskN5.d.cts} +3 -93
- package/dist/{work-item-runtime-C3M79vE9.d.ts → work-item-runtime-types-DAsZbb2y.d.ts} +3 -93
- package/dist/work-queue/index.cjs +957 -953
- package/dist/work-queue/index.cjs.map +1 -1
- package/dist/work-queue/index.d.cts +9 -357
- package/dist/work-queue/index.d.ts +9 -357
- package/dist/work-queue/index.js +957 -953
- package/dist/work-queue/index.js.map +1 -1
- package/package.json +611 -513
- package/dist/chunk-3JR3EDB2.js.map +0 -1
- package/dist/chunk-4VLAQHZI.js.map +0 -1
- package/dist/chunk-6XAIOL3X.js +0 -2407
- package/dist/chunk-6XAIOL3X.js.map +0 -1
- package/dist/chunk-FBUU43PM.js.map +0 -1
- package/dist/chunk-HKK2JD7Z.js.map +0 -1
- package/dist/chunk-PC3BTTBE.js +0 -3217
- package/dist/chunk-PC3BTTBE.js.map +0 -1
- package/dist/chunk-QFY4AFY4.js.map +0 -1
- package/dist/chunk-SS2A464I.js.map +0 -1
- package/dist/chunk-V7CIJE4B.js.map +0 -1
- package/dist/chunk-XKXWK2KP.js.map +0 -1
- package/dist/chunk-YDSIVHRR.js.map +0 -1
- package/dist/chunk-YXMZ2N6J.js.map +0 -1
- /package/dist/{chunk-CZNV3VXM.js.map → chunk-3J7UPZL5.js.map} +0 -0
- /package/dist/{chunk-Z2ANQ6JW.js.map → chunk-4Q77MMJY.js.map} +0 -0
- /package/dist/{chunk-K3FXTC3I.js.map → chunk-HJACH5PU.js.map} +0 -0
- /package/dist/{chunk-GTPCOEOZ.js.map → chunk-IDMLXLLG.js.map} +0 -0
- /package/dist/{chunk-DKP56CSW.js.map → chunk-JKAYLDQV.js.map} +0 -0
- /package/dist/{chunk-43BKLFZU.js.map → chunk-KFURM6FM.js.map} +0 -0
- /package/dist/{chunk-2747WN4Y.js.map → chunk-PUSRRALM.js.map} +0 -0
- /package/dist/{chunk-VTHLCFN4.js.map → chunk-RAHNUYA5.js.map} +0 -0
- /package/dist/{chunk-IXZBUWSP.js.map → chunk-UEMN5URK.js.map} +0 -0
- /package/dist/{chunk-6PHB5CJS.js.map → chunk-ZLFRB6FI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/solutions/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/json/codec.ts","../../src/patterns/semantic-memory.ts","../../src/patterns/semantic-memory-graph.ts","../../src/solutions/agentic-memory.ts","../../src/solutions/capability-admission.ts","../../src/batch/boundary.ts","../../src/batch/batch.ts","../../src/dispatcher/index.ts","../../src/graph/environment.ts","../../src/node/core.ts","../../src/node/versioning.ts","../../src/node/node.ts","../../src/solutions/reactive-layout/index.ts"],"sourcesContent":["/**\n * Vertical application solution kits.\n *\n * Agentic memory, harness, and data-agent surfaces land here after B63/B62\n * classify and re-derive them onto lower D125 layers.\n */\n\nexport {\n\tAGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\tAGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\ttype AgenticMemoryArtifactKind,\n\ttype AgenticMemoryBundle,\n\ttype AgenticMemoryBundleOptions,\n\ttype AgenticMemoryConsolidationBundle,\n\ttype AgenticMemoryConsolidationBundleOptions,\n\ttype AgenticMemoryConsolidationCommand,\n\ttype AgenticMemoryConsolidationCursor,\n\ttype AgenticMemoryConsolidationError,\n\ttype AgenticMemoryConsolidationErrorCode,\n\ttype AgenticMemoryConsolidationOutcome,\n\ttype AgenticMemoryConsolidationRecordDraft,\n\ttype AgenticMemoryConsolidationRequest,\n\ttype AgenticMemoryConsolidationResult,\n\ttype AgenticMemoryConsolidationSnapshot,\n\ttype AgenticMemoryConsolidationStatus,\n\ttype AgenticMemoryContext,\n\ttype AgenticMemoryContextEntry,\n\ttype AgenticMemoryContextPackingBundle,\n\ttype AgenticMemoryContextPackingBundleOptions,\n\ttype AgenticMemoryContextPackingCursor,\n\ttype AgenticMemoryContextPackingError,\n\ttype AgenticMemoryContextPackingErrorCode,\n\ttype AgenticMemoryContextPackingPolicy,\n\ttype AgenticMemoryContextPackingSnapshot,\n\ttype AgenticMemoryContextPackingStatus,\n\ttype AgenticMemoryContextState,\n\ttype AgenticMemoryContextText,\n\ttype AgenticMemoryError,\n\ttype AgenticMemoryErrorCode,\n\ttype AgenticMemoryFragmentFrame,\n\ttype AgenticMemoryKgAssertionDraft,\n\ttype AgenticMemoryKgProjectionBundle,\n\ttype AgenticMemoryKgProjectionBundleOptions,\n\ttype AgenticMemoryKgProjectionCursor,\n\ttype AgenticMemoryKgProjectionError,\n\ttype AgenticMemoryKgProjectionErrorCode,\n\ttype AgenticMemoryKgProjectionSnapshot,\n\ttype AgenticMemoryKgProjectionStatus,\n\ttype AgenticMemoryKgProjectionStatusState,\n\ttype AgenticMemoryKind,\n\ttype AgenticMemoryPackedContext,\n\ttype AgenticMemoryPackedContextEntry,\n\ttype AgenticMemoryPersistenceLevel,\n\ttype AgenticMemoryProjectionCursor,\n\ttype AgenticMemoryProjectionSnapshot,\n\ttype AgenticMemoryRecord,\n\ttype AgenticMemoryRecordFrame,\n\ttype AgenticMemoryRecordMetadata,\n\ttype AgenticMemoryRetentionBundle,\n\ttype AgenticMemoryRetentionBundleOptions,\n\ttype AgenticMemoryRetentionCommand,\n\ttype AgenticMemoryRetentionCursor,\n\ttype AgenticMemoryRetentionError,\n\ttype AgenticMemoryRetentionErrorCode,\n\ttype AgenticMemoryRetentionSnapshot,\n\ttype AgenticMemoryRetentionStatus,\n\ttype AgenticMemoryScope,\n\ttype AgenticMemorySourceProjection,\n\ttype AgenticMemoryStatus,\n\ttype AgenticMemoryStatusState,\n\ttype AgenticMemoryStrictJsonValue,\n\tagenticMemoryBundle,\n\tagenticMemoryConsolidationBundle,\n\tagenticMemoryContextPackingBundle,\n\tagenticMemoryKgProjectionBundle,\n\tagenticMemoryRecordCodec,\n\tagenticMemoryRecordFrame,\n\tagenticMemoryRecordFrameCodec,\n\tagenticMemoryRetentionBundle,\n\tassertAgenticMemoryRecordFrame,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n} from \"./agentic-memory.js\";\n\nexport {\n\ttype CapabilityAdmission,\n\ttype CapabilityAdmissionBundle,\n\ttype CapabilityAdmissionDecision,\n\ttype CapabilityAdmissionOutcome,\n\ttype CapabilityAdmissionPolicy,\n\ttype CapabilityAdmissionProposal,\n\ttype CapabilityAdmissionState,\n\ttype CapabilityAdmissionStatus,\n\ttype CapabilityAdmissionViews,\n\tcapabilityAdmissionProjector,\n\tcapabilityAdmissionProposal,\n} from \"./capability-admission.js\";\n\nexport {\n\tanalyzeAndMeasure,\n\ttype BaseContentBlock,\n\tBLOCKS_MEASUREMENT_KIND,\n\ttype BlockAdapters,\n\ttype BlockAdaptersProviderOptions,\n\ttype BlockMeasurementProviderOptions,\n\ttype BlocksMeasurement,\n\tblockAdaptersProvider,\n\tblockMeasurementProvider,\n\tCapabilityMeasureAdapter,\n\ttype CapabilityTextMeasurementsOptions,\n\tCellMeasureAdapter,\n\ttype CellMeasureAdapterOptions,\n\ttype CellTextMeasurementsOptions,\n\ttype CircleObstacle,\n\ttype ComputeFlowLinesOptions,\n\ttype ContentBlock,\n\tcapabilityTextMeasurements,\n\tcarveTextLineSlots,\n\tcellTextMeasurements,\n\tcircleIntervalForBand,\n\tcomputeBlockFlow,\n\tcomputeCharPositions,\n\tcomputeFlowLines,\n\tcomputeLineBreaks,\n\tcomputeTotalHeight,\n\ttype FlowColumns,\n\ttype FlowContainer,\n\ttype FlowLinesResult,\n\tIMAGE_SIZE_MEASUREMENT_KIND,\n\ttype ImageContentBlock,\n\ttype ImageMeasurer,\n\tImageSizeAdapter,\n\ttype ImageSizeLookup,\n\ttype ImageSizeMeasurementsOptions,\n\ttype ImageSizeMeasurementTarget,\n\tInjectedMeasureAdapter,\n\ttype InjectedMeasureAdapterOptions,\n\ttype InjectedTextMeasurementsOptions,\n\timageSizeMeasurements,\n\tinjectedTextMeasurements,\n\ttype LayoutCursor,\n\ttype LayoutLine,\n\ttype LayoutNextLineContext,\n\ttype LayoutNextLineResult,\n\ttype LineBreaksResult,\n\tlayoutNextLine,\n\ttype MeasureBlockOptions,\n\ttype MeasuredBlock,\n\ttype MeasureFn,\n\ttype MeasurementAdapter,\n\ttype MeasurementFact,\n\ttype MeasurementIssue,\n\ttype MeasurementReadiness,\n\ttype MeasurementResult,\n\ttype Measurements,\n\ttype MergeMeasurementsOptions,\n\tmeasureBlock,\n\tmeasureBlocks,\n\tmergeMeasurements,\n\ttype Obstacle,\n\ttype PositionedBlock,\n\ttype PositionedLine,\n\tPrecomputedMeasureAdapter,\n\ttype PrecomputedMeasureAdapterOptions,\n\ttype PrecomputedTextMeasurementsOptions,\n\ttype PreparedSegment,\n\tprecomputedTextMeasurements,\n\tREADINESS_MEASUREMENT_KIND,\n\ttype ReactiveBlockLayoutBundle,\n\ttype ReactiveBlockLayoutOptions,\n\ttype ReactiveFlowLayoutBundle,\n\ttype ReactiveFlowLayoutOptions,\n\ttype ReactiveLayoutBundle,\n\ttype ReactiveLayoutOptions,\n\ttype ReadinessMeasurementsOptions,\n\ttype ReadinessTextMeasurementsOptions,\n\ttype RectObstacle,\n\treactiveBlockLayout,\n\treactiveFlowLayout,\n\treactiveLayout,\n\treadinessMeasurements,\n\treadinessTextMeasurements,\n\trectIntervalForBand,\n\ttype SegmentAdapter,\n\ttype SegmentBreakKind,\n\ttype SegmentInfo,\n\ttype SegmentMeasureStats,\n\ttype Size,\n\tSVG_BOUNDS_MEASUREMENT_KIND,\n\tSvgBoundsAdapter,\n\ttype SvgBoundsMeasurementsOptions,\n\ttype SvgBoundsMeasurementTarget,\n\ttype SvgContentBlock,\n\ttype SvgMeasurer,\n\tsvgBoundsMeasurements,\n\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\ttype TextContentBlock,\n\ttype TextMeasureCapability,\n\ttype TextMeasurementProviderOptions,\n\ttype TextSegmentsMeasurement,\n\ttextMeasurementProvider,\n} from \"./reactive-layout/index.js\";\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Neutral JSON/encoding utilities (D96).\n *\n * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON\n * scanner/canonicalization contract.\n */\n\n/** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */\nexport interface Codec<T> {\n\tencode(value: T): Uint8Array;\n\tdecode(bytes: Uint8Array): T;\n}\n\nexport type StrictJsonScalar = null | boolean | number | string;\nexport type StrictJsonValue =\n\t| StrictJsonScalar\n\t| readonly StrictJsonValue[]\n\t| { readonly [key: string]: StrictJsonValue };\nexport type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;\n\ntype JsonValue = StrictJsonValue;\n\nconst JS_MIN_NORMAL_NUMBER = 2 ** -1022;\n\nfunction assertStableJsonNumber(value: number, path: string): void {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new TypeError(`stableJsonString: non-finite number at ${path}`);\n\t}\n}\n\nfunction assertStrictJsonNumber(value: number, path: string): void {\n\tassertStableJsonNumber(value, path);\n\tif (Object.is(value, -0)) {\n\t\tthrow new TypeError(`stableJsonString: non-canonical number at ${path}`);\n\t}\n\tconst abs = Math.abs(value);\n\tif (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {\n\t\tthrow new TypeError(`stableJsonString: subnormal number at ${path}`);\n\t}\n\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`stableJsonString: integer outside safe range at ${path}`);\n\t}\n}\n\nfunction sortedJsonValue(\n\tvalue: unknown,\n\tseen = new Set<object>(),\n\tpath = \"$\",\n\tstrictNumbers = false,\n): JsonValue {\n\tif (value === null) return null;\n\tif (typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (strictNumbers) assertStrictJsonNumber(value, path);\n\t\telse assertStableJsonNumber(value, path);\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);\n\t}\n\tif (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\tthrow new TypeError(`stableJsonString: non-plain object at ${path}`);\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst isIndex =\n\t\t\t\t\t/^(0|[1-9]\\d*)$/.test(key) &&\n\t\t\t\t\tNumber.isSafeInteger(Number(key)) &&\n\t\t\t\t\tNumber(key) < value.length;\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: JsonValue[] = [];\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tif (!(i in value)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);\n\t\t\t\t}\n\t\t\t\tout.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t}\n\t\tconst out: Record<string, JsonValue> = Object.create(null);\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tout[key] = sortedJsonValue(\n\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\tseen,\n\t\t\t\t`${path}.${key}`,\n\t\t\t\tstrictNumbers,\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value, new Set<object>(), \"$\", true));\n}\n\n/** Build a JSON codec using stable object-key ordering. */\nexport function jsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder();\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\treturn encoder.encode(stableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\treturn JSON.parse(decoder.decode(bytes)) as T;\n\t\t},\n\t};\n}\n\n/** Default stable JSON codec for unknown values. */\nexport const jsonCodec: Codec<unknown> = jsonCodecFor<unknown>();\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.byteLength !== b.byteLength) return false;\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction hasUnpairedSurrogate(value: string): boolean {\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tconst code = value.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (code >= 0xdc00 && code <= 0xdfff) return true;\n\t}\n\treturn false;\n}\n\nfunction assertNoUnpairedSurrogates(value: unknown, seen = new Set<object>(), path = \"$\"): void {\n\tif (typeof value === \"string\") {\n\t\tif (hasUnpairedSurrogate(value)) {\n\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (value === null || typeof value !== \"object\") return;\n\tif (seen.has(value)) return;\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tassertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value as Record<string, unknown>)) {\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertNoUnpairedSurrogates((value as Record<string, unknown>)[key], seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction assertNoDuplicateJsonObjectKeys(text: string): void {\n\tlet index = 0;\n\n\tfunction fail(message: string): never {\n\t\tthrow new TypeError(`strictJsonCodec: ${message}`);\n\t}\n\n\tfunction skipWhitespace(): void {\n\t\twhile (/\\s/.test(text[index] ?? \"\")) index += 1;\n\t}\n\n\tfunction readJsonString(): string {\n\t\tconst start = index;\n\t\tindex += 1;\n\t\twhile (index < text.length) {\n\t\t\tconst ch = text[index];\n\t\t\tif (ch === '\"') {\n\t\t\t\tindex += 1;\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.parse(text.slice(start, index)) as string;\n\t\t\t\t} catch {\n\t\t\t\t\tfail(\"malformed JSON string\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ch === \"\\\\\") {\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t\tfail(\"unterminated JSON string\");\n\t}\n\n\tfunction consumeLiteral(literal: string): void {\n\t\tif (text.slice(index, index + literal.length) !== literal) {\n\t\t\tfail(`malformed JSON near byte ${index}`);\n\t\t}\n\t\tindex += literal.length;\n\t}\n\n\tfunction consumeNumber(): void {\n\t\tconst match = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/.exec(text.slice(index));\n\t\tif (!match) fail(`malformed JSON number near byte ${index}`);\n\t\tindex += match[0].length;\n\t}\n\n\tfunction parseValue(path: string): void {\n\t\tskipWhitespace();\n\t\tconst ch = text[index];\n\t\tif (ch === \"{\") {\n\t\t\tparseObject(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tparseArray(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\treadJsonString();\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"t\") {\n\t\t\tconsumeLiteral(\"true\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"f\") {\n\t\t\tconsumeLiteral(\"false\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"n\") {\n\t\t\tconsumeLiteral(\"null\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"-\" || (ch !== undefined && ch >= \"0\" && ch <= \"9\")) {\n\t\t\tconsumeNumber();\n\t\t\treturn;\n\t\t}\n\t\tfail(`malformed JSON near byte ${index}`);\n\t}\n\n\tfunction parseObject(path: string): void {\n\t\tconst keys = new Set<string>();\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"}\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\twhile (index < text.length) {\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== '\"') fail(`expected object key near byte ${index}`);\n\t\t\tconst key = readJsonString();\n\t\t\tif (keys.has(key)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tkeys.add(key);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== \":\") fail(`expected ':' after object key near byte ${index}`);\n\t\t\tindex += 1;\n\t\t\tparseValue(`${path}.${key}`);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"}\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or '}' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON object\");\n\t}\n\n\tfunction parseArray(path: string): void {\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"]\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\tlet item = 0;\n\t\twhile (index < text.length) {\n\t\t\tparseValue(`${path}[${item}]`);\n\t\t\titem += 1;\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"]\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or ']' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON array\");\n\t}\n\n\tparseValue(\"$\");\n\tskipWhitespace();\n\tif (index !== text.length) fail(`trailing JSON token near byte ${index}`);\n}\n\n/**\n * Build a strict canonical JSON codec (D84/D87/D96).\n * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,\n * unpaired surrogates, and values that cannot round-trip through stable JSON.\n */\nexport function strictJsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\tassertNoUnpairedSurrogates(value);\n\t\t\treturn encoder.encode(strictStableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\tconst text = decoder.decode(bytes);\n\t\t\tassertNoDuplicateJsonObjectKeys(text);\n\t\t\tconst decoded = JSON.parse(text) as unknown;\n\t\t\tassertNoUnpairedSurrogates(decoded);\n\t\t\tconst canonical = encoder.encode(strictStableJsonString(decoded));\n\t\t\tif (!bytesEqual(bytes, canonical)) {\n\t\t\t\tthrow new TypeError(\"strictJsonCodec: bytes are not canonical stable JSON\");\n\t\t\t}\n\t\t\treturn decoded as T;\n\t\t},\n\t};\n}\n\n/** Default strict canonical JSON codec for unknown values. */\nexport const strictJsonCodec: Codec<unknown> = strictJsonCodecFor<unknown>();\n\n/** D113 neutral helper for strict canonical JSON UTF-8 bytes. */\nexport function strictCanonicalJsonBytes(value: unknown): Uint8Array {\n\treturn strictJsonCodec.encode(value);\n}\n\n/** Validate and normalize a host value into strict canonical JSON data. */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as StrictJsonValue;\n\t} catch (cause) {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tthrow new TypeError(`${label}: value is not strict JSON compatible: ${message}`, { cause });\n\t}\n}\n\n/** Validate and normalize a host value into a strict canonical JSON object. */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst normalized = assertStrictJsonValue(value, label);\n\tif (normalized === null || typeof normalized !== \"object\" || Array.isArray(normalized)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn normalized as StrictJsonObject;\n}\n","/**\n * Passive semantic-memory vocabulary and deterministic helpers.\n *\n * D158 splits semantic memory into horizontal patterns and vertical solutions.\n * This module intentionally owns no graph nodes, storage restore, timers,\n * subscriptions, vector indexes, knowledge graphs, or agentic runtime.\n */\n\nimport type { StrictJsonValue } from \"../json/codec.js\";\n\n/** Stable identity for a semantic-memory fact. */\nexport type FactId = string;\n\n/** Shard partition key used by passive sharding helpers. */\nexport type ShardKey = string | number;\n\n/**\n * A single semantic-memory fact. Pattern convention only: this is not a\n * protocol message, storage record owner, restore contract, or graph runtime.\n */\nexport interface MemoryFragment<T = unknown> {\n\treadonly id: FactId;\n\treadonly payload: T;\n\t/** Transaction time, typically monotonic nanoseconds. */\n\treadonly tNs: bigint;\n\t/** Valid-time start. Undefined means unbounded past. */\n\treadonly validFrom?: bigint;\n\t/** Valid-time end. Undefined means currently valid. */\n\treadonly validTo?: bigint;\n\t/** Confidence score in the closed interval [0, 1]. */\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\t/** Fact ids this fragment derives from or depends on. */\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** Columnar passive store vocabulary for callers that keep memory facts outside GraphReFly. */\nexport interface FactStore<T = unknown> {\n\treadonly byId: ReadonlyMap<FactId, MemoryFragment<T>>;\n}\n\n/** Read-only projection passed to scoring policies; it exposes no mutation surface. */\nexport interface StoreReadHandle<T = unknown> {\n\tget(id: FactId): MemoryFragment<T> | undefined;\n\thas(id: FactId): boolean;\n\treadonly size: number;\n\tvalues(): IterableIterator<MemoryFragment<T>>;\n}\n\nexport type ScoringPolicy<T = unknown> = (\n\tfragment: MemoryFragment<T>,\n\tstore: StoreReadHandle<T>,\n) => number;\nexport type DecayPolicy = (confidence: number, ageNs: bigint) => number;\nexport type AdmissionFilter<T = unknown> = (fragment: MemoryFragment<T>) => boolean;\n\n/** Outcome signal for policy learning. This is an application fact, not a protocol event. */\nexport interface OutcomeSignal {\n\treadonly factId: FactId;\n\treadonly reward: number;\n}\n\n/** Passive structured query over semantic-memory facts. */\nexport interface MemoryQuery {\n\treadonly tags?: readonly string[];\n\treadonly asOf?: bigint;\n\treadonly minConfidence?: number;\n\treadonly limit?: number;\n}\n\nexport interface MemoryAnswer<T = unknown> {\n\treadonly query: MemoryQuery;\n\treadonly results: readonly MemoryFragment<T>[];\n}\n\nexport type KnowledgeAssertionStrictJsonValue = StrictJsonValue;\n\n/** Passive KG endpoint vocabulary. Entity ids are DATA keys, not graph node ids. */\nexport interface KnowledgeAssertionSubject {\n\treadonly id: FactId;\n\treadonly type?: string;\n}\n\n/** Passive KG object/value vocabulary. */\nexport type KnowledgeAssertionObject =\n\t| {\n\t\t\treadonly kind: \"entity\";\n\t\t\treadonly id: FactId;\n\t\t\treadonly type?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"value\";\n\t\t\treadonly value: KnowledgeAssertionStrictJsonValue;\n\t\t\treadonly valueType?: string;\n\t };\n\n/** Passive KG assertion fact consumed by lower semantic-memory graph patterns. */\nexport interface KnowledgeAssertion {\n\treadonly id: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\n/** Entry vocabulary for ranked collection-like memory views. */\nexport interface CollectionEntry<T = unknown> {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: bigint;\n\treadonly lastAccessNs: bigint;\n\treadonly baseScore: number;\n}\n\nexport type RankedCollectionEntry<T = unknown> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionScoreFn<T = unknown> = (value: T) => number;\n\n/** Query shape shared by passive retrieval/ranking helpers. */\nexport interface RetrievalQuery {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n\treadonly context?: readonly string[];\n}\n\nexport interface VectorSearchResult<TMeta = unknown> {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n}\n\nexport interface RetrievalEntry<TMem = unknown> {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n\treadonly context?: readonly string[];\n}\n\nexport interface RetrievalTrace<TMem = unknown> {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n}\n\n/** Generic per-dimension thresholds. Any configured dimension below threshold is rejected. */\nexport type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;\n\nexport interface AdmissionScoredOptions<Dims extends string, TRaw = unknown> {\n\treadonly scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;\n\treadonly thresholds?: AdmissionThresholds<Dims>;\n}\n\nexport interface AdmissionScores {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n}\n\nexport interface AdmissionScore3DOptions {\n\treadonly scoreFn: (raw: unknown) => AdmissionScores;\n\treadonly persistenceThreshold?: number;\n\treadonly personalValueThreshold?: number;\n\treadonly requireStructured?: boolean;\n}\n\nexport interface ShardByTenantOptions {\n\treadonly tenants?: readonly string[];\n\treadonly shardCount?: number;\n}\n\nexport interface ShardByTenantConfig<T = unknown> {\n\treadonly shardBy: (fragment: MemoryFragment<T>) => ShardKey;\n\treadonly shardCount: number;\n}\n\nexport interface MemoryFragmentValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n}\n\n/** Cosine similarity over zero-padded vectors. Non-finite results normalize to 0. */\nexport function cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\tconst score = dot / Math.sqrt(na * nb);\n\treturn Number.isFinite(score) ? score : 0;\n}\n\n/**\n * Returns true when a fragment is valid at `asOf`.\n *\n * Omitted `asOf` has no clock to compare against, so it admits only fragments\n * that are live and not valid-time delayed.\n */\nexport function memoryFragmentValidAt(fragment: MemoryFragment, asOf?: bigint): boolean {\n\tif (asOf === undefined) return fragment.validTo === undefined && fragment.validFrom === undefined;\n\tif (fragment.validFrom !== undefined && fragment.validFrom > asOf) return false;\n\tif (fragment.validTo !== undefined && fragment.validTo <= asOf) return false;\n\treturn true;\n}\n\n/** Pure structured-query predicate over a single fragment. */\nexport function memoryFragmentMatchesQuery(\n\tfragment: MemoryFragment,\n\tquery: MemoryQuery = {},\n): boolean {\n\tif (!memoryFragmentValidAt(fragment, query.asOf)) return false;\n\tif (query.minConfidence !== undefined && fragment.confidence < query.minConfidence) return false;\n\tif (\n\t\tquery.tags &&\n\t\tquery.tags.length > 0 &&\n\t\t!query.tags.some((tag) => fragment.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filter and rank fragments by confidence desc, then transaction time desc. */\nexport function filterMemoryFragments<T>(\n\tfragments: Iterable<MemoryFragment<T>>,\n\tquery: MemoryQuery = {},\n): readonly MemoryFragment<T>[] {\n\tconst results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tresults.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));\n\treturn query.limit === undefined ? results : results.slice(0, Math.max(0, query.limit));\n}\n\n/** Validate the passive MemoryFragment shape without throwing. */\nexport function validateMemoryFragment(value: unknown): MemoryFragmentValidation {\n\tconst errors: string[] = [];\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn { ok: false, errors: [\"fragment must be an object\"] };\n\t}\n\tconst fragment = value as Partial<MemoryFragment>;\n\tif (typeof fragment.id !== \"string\" || fragment.id.length === 0) {\n\t\terrors.push(\"id must be a non-empty string\");\n\t}\n\tif (!Object.hasOwn(fragment, \"payload\")) {\n\t\terrors.push(\"payload must be present\");\n\t}\n\tif (typeof fragment.tNs !== \"bigint\") {\n\t\terrors.push(\"tNs must be a bigint\");\n\t}\n\tconst confidence = fragment.confidence;\n\tif (\n\t\t!Number.isFinite(confidence) ||\n\t\tconfidence === undefined ||\n\t\tconfidence < 0 ||\n\t\tconfidence > 1\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1]\");\n\t}\n\tif (!isDenseArrayOf(fragment.tags, (tag): tag is string => typeof tag === \"string\")) {\n\t\terrors.push(\"tags must be a readonly string array\");\n\t}\n\tif (!isDenseArrayOf(fragment.sources, (source): source is string => typeof source === \"string\")) {\n\t\terrors.push(\"sources must be a readonly string array\");\n\t}\n\tif (fragment.validFrom !== undefined && typeof fragment.validFrom !== \"bigint\") {\n\t\terrors.push(\"validFrom must be a bigint when present\");\n\t}\n\tif (fragment.validTo !== undefined && typeof fragment.validTo !== \"bigint\") {\n\t\terrors.push(\"validTo must be a bigint when present\");\n\t}\n\tif (\n\t\ttypeof fragment.validFrom === \"bigint\" &&\n\t\ttypeof fragment.validTo === \"bigint\" &&\n\t\tfragment.validFrom >= fragment.validTo\n\t) {\n\t\terrors.push(\"validFrom must be earlier than validTo\");\n\t}\n\tif (\n\t\tfragment.embedding !== undefined &&\n\t\t!isDenseArrayOf(fragment.embedding, (component): component is number =>\n\t\t\tNumber.isFinite(component),\n\t\t)\n\t) {\n\t\terrors.push(\"embedding must be a finite number array when present\");\n\t}\n\tif (fragment.parentFragmentId !== undefined && typeof fragment.parentFragmentId !== \"string\") {\n\t\terrors.push(\"parentFragmentId must be a string when present\");\n\t}\n\tif (fragment.provenance !== undefined && typeof fragment.provenance !== \"string\") {\n\t\terrors.push(\"provenance must be a string when present\");\n\t}\n\treturn { ok: errors.length === 0, errors };\n}\n\nexport function isMemoryFragment(value: unknown): value is MemoryFragment {\n\treturn validateMemoryFragment(value).ok;\n}\n\n/**\n * Generic N-dimension admission filter. Missing or non-finite thresholded scores reject.\n */\nexport function admissionScored<Dims extends string, TRaw = unknown>(\n\topts: AdmissionScoredOptions<Dims, TRaw>,\n): (raw: TRaw) => boolean {\n\tconst thresholds = opts.thresholds ?? ({} as AdmissionThresholds<Dims>);\n\treturn (raw: TRaw): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tfor (const dim of Object.keys(thresholds) as Dims[]) {\n\t\t\tconst min = thresholds[dim];\n\t\t\tif (min === undefined) continue;\n\t\t\tconst score = scores[dim];\n\t\t\tconst safe = Number.isFinite(score) ? (score as number) : Number.NEGATIVE_INFINITY;\n\t\t\tif (safe < min) return false;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/** Three-axis admission sugar for persistence / structure / personal-value scoring. */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean {\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tif (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;\n\t\tif (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;\n\t\tif (!opts.requireStructured) return true;\n\t\treturn scoreAtLeast(scores.structure, Number.MIN_VALUE);\n\t};\n}\n\n/** Build a passive `{ shardBy, shardCount }` pair for tenant-isolated sharding. */\nexport function shardByTenant<T>(\n\ttenantOf: (fragment: MemoryFragment<T>) => string,\n\topts: ShardByTenantOptions = {},\n): ShardByTenantConfig<T> {\n\tif (opts.tenants && opts.tenants.length > 0) {\n\t\tconst tenants = [...new Set(opts.tenants)];\n\t\tconst index = new Map(tenants.map((tenant, i) => [tenant, i] as const));\n\t\tconst overflow = tenants.length;\n\t\treturn {\n\t\t\tshardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,\n\t\t\tshardCount: tenants.length + 1,\n\t\t};\n\t}\n\tconst configuredShardCount = opts.shardCount ?? 4;\n\tconst shardCount = Number.isSafeInteger(configuredShardCount)\n\t\t? Math.max(1, configuredShardCount)\n\t\t: 4;\n\treturn { shardBy: (fragment) => tenantOf(fragment), shardCount };\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction scoreAtLeast(score: number, min: number): boolean {\n\treturn Number.isFinite(score) && score >= min;\n}\n","/**\n * Graph-visible semantic-memory retrieval patterns.\n *\n * D158 allows horizontal semantic-memory patterns when they are ordinary graph\n * nodes with declared deps and graph-visible facts. This file intentionally\n * owns no storage restore/hydration, scheduler, hidden subscription, vector DB,\n * retention loop, consolidation loop, Graph subclass, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\tcosineSimilarity,\n\ttype FactId,\n\tfilterMemoryFragments,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\ttype MemoryQuery,\n\tmemoryFragmentMatchesQuery,\n\tvalidateMemoryFragment,\n} from \"./semantic-memory.js\";\n\n/** Query shape for the first graph-visible retrieval bundle. */\nexport interface MemoryRetrievalQuery extends MemoryQuery {\n\t/** Optional dense embedding used only for deterministic in-memory ranking. */\n\treadonly vector?: readonly number[];\n}\n\nexport interface MemoryRetrievalCursor {\n\treadonly evaluation: number;\n\treadonly validFragments: number;\n\treadonly invalidFragments: number;\n\treadonly resultCount: number;\n}\n\nexport type MemoryRetrievalStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface MemoryRetrievalStatus {\n\treadonly state: MemoryRetrievalStatusState;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport interface MemoryRetrievalIndex<T = unknown> {\n\treadonly ids: readonly FactId[];\n\treadonly byId: Readonly<Record<FactId, MemoryFragment<T>>>;\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport type MemoryRetrievalErrorCode =\n\t| \"duplicate-fragment-id\"\n\t| \"invalid-fragments-input\"\n\t| \"invalid-fragment\"\n\t| \"invalid-query\"\n\t| \"invalid-query-vector\";\n\nexport interface MemoryRetrievalError {\n\treadonly code: MemoryRetrievalErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly fragment?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport interface MemoryRetrievalSnapshot<T = unknown> {\n\treadonly fragments: readonly MemoryFragment<T>[];\n\treadonly indexed: MemoryRetrievalIndex<T>;\n\treadonly ranked: MemoryAnswer<T>;\n\treadonly status: MemoryRetrievalStatus;\n\treadonly errors: readonly MemoryRetrievalError[];\n\treadonly cursor: MemoryRetrievalCursor;\n}\n\nexport type MemoryRetrievalFact<T = unknown> = MemoryRetrievalSnapshot<T>;\n\nexport interface KnowledgeGraphEntity {\n\treadonly id: FactId;\n\treadonly type?: string;\n\treadonly assertionIds: readonly FactId[];\n\treadonly subjectAssertionIds: readonly FactId[];\n\treadonly objectAssertionIds: readonly FactId[];\n}\n\nexport interface KnowledgeGraphRelation {\n\treadonly assertionId: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources: readonly FactId[];\n\treadonly provenance?: string;\n}\n\nexport interface KnowledgeGraphTopic {\n\treadonly predicate: string;\n\treadonly assertionIds: readonly FactId[];\n\treadonly entityIds: readonly FactId[];\n}\n\nexport interface KnowledgeGraphIndex {\n\treadonly assertionIds: readonly FactId[];\n\treadonly entityIds: readonly FactId[];\n\treadonly relationIds: readonly FactId[];\n\treadonly predicates: readonly string[];\n}\n\nexport interface KnowledgeGraphPolicy {\n\treadonly allowedPredicates?: readonly string[];\n\treadonly requireEntityTypes?: boolean;\n}\n\nexport interface KnowledgeGraphCursor {\n\treadonly evaluation: number;\n\treadonly validAssertions: number;\n\treadonly invalidAssertions: number;\n\treadonly entityCount: number;\n\treadonly relationCount: number;\n\treadonly predicateCount: number;\n}\n\nexport type KnowledgeGraphStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface KnowledgeGraphStatus {\n\treadonly state: KnowledgeGraphStatusState;\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport type KnowledgeGraphErrorCode =\n\t| \"invalid-assertions-input\"\n\t| \"invalid-assertion\"\n\t| \"duplicate-assertion-id\"\n\t| \"invalid-policy\"\n\t| \"policy-conflict\";\n\nexport interface KnowledgeGraphError {\n\treadonly code: KnowledgeGraphErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly assertionId?: FactId;\n\treadonly assertion?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport interface KnowledgeGraphSnapshot {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n\treadonly status: KnowledgeGraphStatus;\n\treadonly errors: readonly KnowledgeGraphError[];\n\treadonly cursor: KnowledgeGraphCursor;\n}\n\nexport interface KnowledgeGraphReducerBundle {\n\treadonly input: {\n\t\treadonly assertions: Node<readonly unknown[]>;\n\t\treadonly policy?: Node<KnowledgeGraphPolicy>;\n\t};\n\treadonly snapshot: Node<KnowledgeGraphSnapshot>;\n\treadonly assertions: Node<readonly KnowledgeAssertion[]>;\n\treadonly entities: Node<readonly KnowledgeGraphEntity[]>;\n\treadonly relations: Node<readonly KnowledgeGraphRelation[]>;\n\treadonly topics: Node<readonly KnowledgeGraphTopic[]>;\n\treadonly index: Node<KnowledgeGraphIndex>;\n\treadonly status: Node<KnowledgeGraphStatus>;\n\treadonly errors: Node<readonly KnowledgeGraphError[]>;\n\treadonly cursor: Node<KnowledgeGraphCursor>;\n}\n\nexport interface KnowledgeGraphReducerBundleOptions {\n\treadonly name?: string;\n\treadonly assertions: Node<readonly unknown[]>;\n\treadonly policy?: Node<KnowledgeGraphPolicy>;\n}\n\nexport interface MemoryRetrievalBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly fragments: Node<readonly unknown[]>;\n\t\treadonly query: Node<MemoryRetrievalQuery>;\n\t};\n\treadonly snapshot: Node<MemoryRetrievalSnapshot<T>>;\n\treadonly fragments: Node<readonly MemoryFragment<T>[]>;\n\treadonly indexed: Node<MemoryRetrievalIndex<T>>;\n\treadonly ranked: Node<MemoryAnswer<T>>;\n\treadonly status: Node<MemoryRetrievalStatus>;\n\treadonly errors: Node<readonly MemoryRetrievalError[]>;\n\treadonly cursor: Node<MemoryRetrievalCursor>;\n}\n\nexport interface MemoryRetrievalBundleOptions {\n\treadonly name?: string;\n\treadonly fragments: Node<readonly unknown[]>;\n\treadonly query: Node<MemoryRetrievalQuery>;\n}\n\ninterface MemoryRetrievalRuntimeState {\n\tevaluation: number;\n}\n\ninterface MemoryRetrievalQueryValidation {\n\treadonly ok: boolean;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly errors: readonly Omit<MemoryRetrievalError, \"cursor\">[];\n}\n\ninterface FragmentValidationResult<T> {\n\treadonly fragment?: MemoryFragment<T>;\n\treadonly error?: Omit<MemoryRetrievalError, \"cursor\">;\n}\n\n/**\n * Build a graph-visible memory retrieval bundle from explicit fragment/query deps.\n *\n * Invalid fragments and ranking status are emitted as ordinary DATA facts. The\n * bundle never owns storage restore or hidden mutation; callers that need\n * persistence compose D161 collection/storage sidecars outside this pattern.\n */\nexport function memoryRetrievalBundle<T = unknown>(\n\tgraph: Graph,\n\topts: MemoryRetrievalBundleOptions,\n): MemoryRetrievalBundle<T> {\n\tconst name = opts.name ?? \"memoryRetrieval\";\n\tconst { fragments, query } = opts;\n\tconst snapshot = graph.node<MemoryRetrievalSnapshot<T>>(\n\t\t[fragments, query],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<MemoryRetrievalRuntimeState>() ??\n\t\t\t\t({ evaluation: 0 } satisfies MemoryRetrievalRuntimeState);\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawFragments = depLatest(ctx, 0);\n\t\t\tconst rawQuery = depLatest(ctx, 1);\n\t\t\tconst queryValidation = validateMemoryRetrievalQuery(rawQuery);\n\t\t\tconst currentQuery = queryValidation.query;\n\t\t\tconst valid: MemoryFragment<T>[] = [];\n\t\t\tconst seenIds = new Set<FactId>();\n\t\t\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [...queryValidation.errors];\n\n\t\t\tif (!Array.isArray(rawFragments)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input must be an array\",\n\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst length = safeArrayLength(rawFragments);\n\t\t\t\tif (length === undefined) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input length could not be read\",\n\t\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < (length ?? 0); i += 1) {\n\t\t\t\t\tconst result = validateAndSnapshotFragment<T>(rawFragments, i);\n\t\t\t\t\tif (result.error !== undefined) {\n\t\t\t\t\t\terrors.push(result.error);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst fragment = result.fragment as MemoryFragment<T>;\n\t\t\t\t\tif (seenIds.has(fragment.id)) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: duplicate fragment id\",\n\t\t\t\t\t\t\tindex: i,\n\t\t\t\t\t\t\tfragment,\n\t\t\t\t\t\t\tvalidationErrors: [`duplicate fragment id '${fragment.id}'`],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tseenIds.add(fragment.id);\n\t\t\t\t\tvalid.push(fragment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ranked = errors.some((error) => !isRecoverableFragmentError(error))\n\t\t\t\t? []\n\t\t\t\t: rankFragments(valid, currentQuery);\n\t\t\tconst cursor: MemoryRetrievalCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidFragments: valid.length,\n\t\t\t\tinvalidFragments: errors.filter(\n\t\t\t\t\t(error) => error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\",\n\t\t\t\t).length,\n\t\t\t\tresultCount: ranked.length,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tconst answer: MemoryAnswer<T> = Object.freeze({\n\t\t\t\tquery: currentQuery,\n\t\t\t\tresults: Object.freeze(ranked),\n\t\t\t});\n\t\t\tconst status: MemoryRetrievalStatus = Object.freeze({\n\t\t\t\tstate: statusState(errors, ranked.length),\n\t\t\t\tquery: currentQuery,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst indexed: MemoryRetrievalIndex<T> = Object.freeze({\n\t\t\t\tids: Object.freeze(valid.map((fragment) => fragment.id)),\n\t\t\t\tbyId: indexById(valid),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errorFacts = Object.freeze(\n\t\t\t\terrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragments: Object.freeze([...valid]),\n\t\t\t\t\t\tindexed,\n\t\t\t\t\t\tranked: answer,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors: errorFacts,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"memoryRetrievalSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { fragments, query },\n\t\tsnapshot,\n\t\tfragments: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/fragments`,\n\t\t\t\"memoryRetrievalFragments\",\n\t\t\t(fact) => fact.fragments,\n\t\t),\n\t\tindexed: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/indexed`,\n\t\t\t\"memoryRetrievalIndexed\",\n\t\t\t(fact) => fact.indexed,\n\t\t),\n\t\tranked: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/ranked`,\n\t\t\t\"memoryRetrievalRanked\",\n\t\t\t(fact) => fact.ranked,\n\t\t),\n\t\tstatus: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"memoryRetrievalStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"memoryRetrievalErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"memoryRetrievalCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D170 lower semantic-memory KG materializer.\n *\n * Assertion, entity, relation, and topic ids remain DATA keys. The bundle has\n * static describe-visible topology and owns no storage, LLM extraction,\n * scheduler, agent runtime, or dynamic graph node lifecycle.\n */\nexport function knowledgeGraphReducerBundle(\n\tgraph: Graph,\n\topts: KnowledgeGraphReducerBundleOptions,\n): KnowledgeGraphReducerBundle {\n\tconst name = opts.name ?? \"knowledgeGraph\";\n\tconst deps = opts.policy === undefined ? [opts.assertions] : [opts.assertions, opts.policy];\n\tconst snapshot = graph.node<KnowledgeGraphSnapshot>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst policy = validateKnowledgeGraphPolicy(\n\t\t\t\topts.policy === undefined ? undefined : depLatest(ctx, 1),\n\t\t\t);\n\t\t\tconst reduced = reduceKnowledgeAssertions(depLatest(ctx, 0), policy.policy);\n\t\t\tconst pendingErrors = [...policy.errors, ...reduced.errors];\n\t\t\tconst cursor: KnowledgeGraphCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidAssertions: reduced.assertions.length,\n\t\t\t\tinvalidAssertions: reduced.invalidAssertions,\n\t\t\t\tentityCount: reduced.entities.length,\n\t\t\t\trelationCount: reduced.relations.length,\n\t\t\t\tpredicateCount: reduced.topics.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tpendingErrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: KnowledgeGraphStatus = Object.freeze({\n\t\t\t\tstate:\n\t\t\t\t\treduced.assertions.length === 0 && errors.length === 0\n\t\t\t\t\t\t? \"empty\"\n\t\t\t\t\t\t: errors.length === 0\n\t\t\t\t\t\t\t? \"ready\"\n\t\t\t\t\t\t\t: reduced.assertions.length > 0\n\t\t\t\t\t\t\t\t? \"partial\"\n\t\t\t\t\t\t\t\t: \"error\",\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(reduced.assertions),\n\t\t\t\t\t\tentities: Object.freeze(reduced.entities),\n\t\t\t\t\t\trelations: Object.freeze(reduced.relations),\n\t\t\t\t\t\ttopics: Object.freeze(reduced.topics),\n\t\t\t\t\t\tindex: reduced.index,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"knowledgeGraphReducerSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: {\n\t\t\tassertions: opts.assertions,\n\t\t\t...(opts.policy === undefined ? {} : { policy: opts.policy }),\n\t\t},\n\t\tsnapshot,\n\t\tassertions: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/assertions`,\n\t\t\t\"knowledgeGraphAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tentities: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/entities`,\n\t\t\t\"knowledgeGraphEntities\",\n\t\t\t(fact) => fact.entities,\n\t\t),\n\t\trelations: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/relations`,\n\t\t\t\"knowledgeGraphRelations\",\n\t\t\t(fact) => fact.relations,\n\t\t),\n\t\ttopics: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/topics`,\n\t\t\t\"knowledgeGraphTopics\",\n\t\t\t(fact) => fact.topics,\n\t\t),\n\t\tindex: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/index`,\n\t\t\t\"knowledgeGraphIndex\",\n\t\t\t(fact) => fact.index,\n\t\t),\n\t\tstatus: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"knowledgeGraphStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"knowledgeGraphErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"knowledgeGraphCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction retrievalProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: MemoryRetrievalSnapshot<T>) => TFact | undefined,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as MemoryRetrievalSnapshot<T>;\n\t\t\t\tconst selected = select(fact);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction kgProjection<TFact>(\n\tgraph: Graph,\n\tsnapshot: Node<KnowledgeGraphSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: KnowledgeGraphSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as KnowledgeGraphSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction validateKnowledgeGraphPolicy(value: unknown): {\n\treadonly policy?: KnowledgeGraphPolicy;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n} {\n\tif (value === undefined) return { policy: undefined, errors: [] };\n\tif (!isPlainObject(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy must be an object\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst policy = value as Partial<KnowledgeGraphPolicy>;\n\tif (\n\t\tpolicy.allowedPredicates !== undefined &&\n\t\t!isDenseArrayOf(policy.allowedPredicates, (item): item is string => typeof item === \"string\")\n\t) {\n\t\terrors.push(\"allowedPredicates must be a readonly string array\");\n\t}\n\tif (policy.requireEntityTypes !== undefined && typeof policy.requireEntityTypes !== \"boolean\") {\n\t\terrors.push(\"requireEntityTypes must be a boolean when present\");\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy is invalid\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: Object.freeze({\n\t\t\t...(policy.allowedPredicates === undefined\n\t\t\t\t? {}\n\t\t\t\t: { allowedPredicates: Object.freeze([...policy.allowedPredicates]) }),\n\t\t\t...(policy.requireEntityTypes === undefined\n\t\t\t\t? {}\n\t\t\t\t: { requireEntityTypes: policy.requireEntityTypes }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction reduceKnowledgeAssertions(\n\tvalue: unknown,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n\treadonly invalidAssertions: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<KnowledgeGraphError, \"cursor\">[] = [];\n\tconst seenAssertions = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input must be an array\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input length could not be read\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tconst result = validateKnowledgeAssertion(value[i], i, policy);\n\t\tif (result.error !== undefined) {\n\t\t\terrors.push(result.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst assertion = result.assertion as KnowledgeAssertion;\n\t\tif (seenAssertions.has(assertion.id)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\tmessage: \"knowledgeGraphReducerBundle: duplicate assertion id\",\n\t\t\t\tindex: i,\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tassertion,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate assertion id '${assertion.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenAssertions.add(assertion.id);\n\t\tassertions.push(assertion);\n\t}\n\tconst materialized = materializeKnowledgeGraph(assertions);\n\treturn {\n\t\tassertions: Object.freeze(assertions),\n\t\t...materialized,\n\t\terrors,\n\t\tinvalidAssertions: errors.filter((error) => error.code !== \"invalid-policy\").length,\n\t};\n}\n\nfunction validateKnowledgeAssertion(\n\tvalue: unknown,\n\tindex: number,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertion?: KnowledgeAssertion;\n\treadonly error?: Omit<KnowledgeGraphError, \"cursor\">;\n} {\n\tif (!isPlainObject(value)) {\n\t\treturn invalidKnowledgeAssertion(index, value, [\"assertion must be an object\"]);\n\t}\n\tconst raw = value as Partial<KnowledgeAssertion>;\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(raw.id)) errors.push(\"id must be a non-empty string\");\n\tif (!isKnowledgeSubject(raw.subject)) errors.push(\"subject.id must be a non-empty string\");\n\tif (!isNonEmptyString(raw.predicate)) errors.push(\"predicate must be a non-empty string\");\n\tif (!isKnowledgeObject(raw.object)) errors.push(\"object shape is invalid\");\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1] when present\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\terrors.push(\"sources must be a readonly non-empty string array when present\");\n\t}\n\tif (\n\t\tpolicy?.allowedPredicates !== undefined &&\n\t\t!policy.allowedPredicates.includes(raw.predicate ?? \"\")\n\t) {\n\t\terrors.push(`predicate '${String(raw.predicate)}' is not allowed by policy`);\n\t}\n\tif (policy?.requireEntityTypes === true) {\n\t\tif (isKnowledgeSubject(raw.subject) && raw.subject.type === undefined) {\n\t\t\terrors.push(\"subject.type is required by policy\");\n\t\t}\n\t\tif (\n\t\t\tisKnowledgeObject(raw.object) &&\n\t\t\traw.object.kind === \"entity\" &&\n\t\t\traw.object.type === undefined\n\t\t) {\n\t\t\terrors.push(\"object.type is required by policy for entity objects\");\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn invalidKnowledgeAssertion(index, value, errors, raw.id);\n\t}\n\treturn {\n\t\tassertion: Object.freeze({\n\t\t\tid: raw.id as FactId,\n\t\t\t...(raw.recordId === undefined ? {} : { recordId: raw.recordId }),\n\t\t\t...(raw.fragmentId === undefined ? {} : { fragmentId: raw.fragmentId }),\n\t\t\tsubject: snapshotSubject(raw.subject as KnowledgeAssertionSubject),\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: snapshotObject(raw.object as KnowledgeAssertionObject),\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\tsources: Object.freeze([...(raw.sources ?? [])]),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t};\n}\n\nfunction invalidKnowledgeAssertion(\n\tindex: number,\n\tassertion: unknown,\n\tvalidationErrors: readonly string[],\n\tassertionId?: unknown,\n): { readonly error: Omit<KnowledgeGraphError, \"cursor\"> } {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"invalid-assertion\",\n\t\t\tmessage: \"knowledgeGraphReducerBundle: assertion is invalid\",\n\t\t\tindex,\n\t\t\tassertionId: typeof assertionId === \"string\" ? assertionId : undefined,\n\t\t\tassertion,\n\t\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t\t},\n\t};\n}\n\nfunction materializeKnowledgeGraph(assertions: readonly KnowledgeAssertion[]): {\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n} {\n\tconst entityAssertions = new Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>();\n\tconst topics = new Map<FactId, { assertionIds: Set<FactId>; entityIds: Set<FactId> }>();\n\tconst relations: KnowledgeGraphRelation[] = [];\n\tfor (const assertion of assertions) {\n\t\tconst subject = touchEntity(entityAssertions, assertion.subject.id, assertion.subject.type);\n\t\tsubject.assertionIds.add(assertion.id);\n\t\tsubject.subjectAssertionIds.add(assertion.id);\n\t\tlet topic = topics.get(assertion.predicate);\n\t\tif (topic === undefined) {\n\t\t\ttopic = { assertionIds: new Set(), entityIds: new Set() };\n\t\t\ttopics.set(assertion.predicate, topic);\n\t\t}\n\t\ttopic.assertionIds.add(assertion.id);\n\t\ttopic.entityIds.add(assertion.subject.id);\n\t\tif (assertion.object.kind === \"entity\") {\n\t\t\tconst object = touchEntity(entityAssertions, assertion.object.id, assertion.object.type);\n\t\t\tobject.assertionIds.add(assertion.id);\n\t\t\tobject.objectAssertionIds.add(assertion.id);\n\t\t\ttopic.entityIds.add(assertion.object.id);\n\t\t}\n\t\trelations.push(\n\t\t\tObject.freeze({\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tsubject: assertion.subject,\n\t\t\t\tpredicate: assertion.predicate,\n\t\t\t\tobject: assertion.object,\n\t\t\t\t...(assertion.confidence === undefined ? {} : { confidence: assertion.confidence }),\n\t\t\t\tsources: Object.freeze([...(assertion.sources ?? [])]),\n\t\t\t\t...(assertion.provenance === undefined ? {} : { provenance: assertion.provenance }),\n\t\t\t}),\n\t\t);\n\t}\n\tconst entities = [...entityAssertions.entries()].map(([id, entity]) =>\n\t\tObject.freeze({\n\t\t\tid,\n\t\t\t...(entity.type === undefined ? {} : { type: entity.type }),\n\t\t\tassertionIds: freezeSortedSet(entity.assertionIds),\n\t\t\tsubjectAssertionIds: freezeSortedSet(entity.subjectAssertionIds),\n\t\t\tobjectAssertionIds: freezeSortedSet(entity.objectAssertionIds),\n\t\t}),\n\t);\n\tentities.sort((a, b) => compareString(a.id, b.id));\n\trelations.sort((a, b) => compareString(a.assertionId, b.assertionId));\n\tconst topicFacts = [...topics.entries()].map(([predicate, topic]) =>\n\t\tObject.freeze({\n\t\t\tpredicate,\n\t\t\tassertionIds: freezeSortedSet(topic.assertionIds),\n\t\t\tentityIds: freezeSortedSet(topic.entityIds),\n\t\t}),\n\t);\n\ttopicFacts.sort((a, b) => compareString(a.predicate, b.predicate));\n\tconst index: KnowledgeGraphIndex = Object.freeze({\n\t\tassertionIds: Object.freeze(assertions.map((assertion) => assertion.id).sort(compareString)),\n\t\tentityIds: Object.freeze(entities.map((entity) => entity.id)),\n\t\trelationIds: Object.freeze(relations.map((relation) => relation.assertionId)),\n\t\tpredicates: Object.freeze(topicFacts.map((topic) => topic.predicate)),\n\t});\n\treturn {\n\t\tentities: Object.freeze(entities),\n\t\trelations: Object.freeze(relations),\n\t\ttopics: Object.freeze(topicFacts),\n\t\tindex,\n\t};\n}\n\nfunction touchEntity(\n\tentities: Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>,\n\tid: FactId,\n\ttype?: string,\n) {\n\tlet entity = entities.get(id);\n\tif (entity === undefined) {\n\t\tentity = {\n\t\t\t...(type === undefined ? {} : { type }),\n\t\t\tassertionIds: new Set(),\n\t\t\tsubjectAssertionIds: new Set(),\n\t\t\tobjectAssertionIds: new Set(),\n\t\t};\n\t\tentities.set(id, entity);\n\t} else if (entity.type === undefined && type !== undefined) {\n\t\tentity.type = type;\n\t}\n\treturn entity;\n}\n\nfunction emptyKnowledgeGraphIndex(): KnowledgeGraphIndex {\n\treturn Object.freeze({\n\t\tassertionIds: Object.freeze([]),\n\t\tentityIds: Object.freeze([]),\n\t\trelationIds: Object.freeze([]),\n\t\tpredicates: Object.freeze([]),\n\t});\n}\n\nfunction snapshotSubject(subject: KnowledgeAssertionSubject): KnowledgeAssertionSubject {\n\treturn Object.freeze({\n\t\tid: subject.id,\n\t\t...(subject.type === undefined ? {} : { type: subject.type }),\n\t});\n}\n\nfunction snapshotObject(object: KnowledgeAssertionObject): KnowledgeAssertionObject {\n\treturn object.kind === \"entity\"\n\t\t? Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: object.id,\n\t\t\t\t...(object.type === undefined ? {} : { type: object.type }),\n\t\t\t})\n\t\t: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: object.value,\n\t\t\t\t...(object.valueType === undefined ? {} : { valueType: object.valueType }),\n\t\t\t});\n}\n\nfunction isKnowledgeSubject(value: unknown): value is KnowledgeAssertionSubject {\n\treturn (\n\t\tisPlainObject(value) &&\n\t\tisNonEmptyString(value.id) &&\n\t\t(value.type === undefined || isNonEmptyString(value.type))\n\t);\n}\n\nfunction isKnowledgeObject(value: unknown): value is KnowledgeAssertionObject {\n\tif (!isPlainObject(value)) return false;\n\tif (value.kind === \"entity\") {\n\t\treturn isNonEmptyString(value.id) && (value.type === undefined || isNonEmptyString(value.type));\n\t}\n\tif (value.kind !== \"value\") return false;\n\treturn (\n\t\tisStrictJsonValue(value.value) &&\n\t\t(value.valueType === undefined || isNonEmptyString(value.valueType))\n\t);\n}\n\nfunction isStrictJsonValue(value: unknown): boolean {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\tif (!Object.hasOwn(value, i) || !isStrictJsonValue(value[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (!isPlainObject(value)) return false;\n\tfor (const key of Object.keys(value)) {\n\t\tif (!isStrictJsonValue(value[key])) return false;\n\t}\n\treturn Object.getOwnPropertySymbols(value).length === 0;\n}\n\nfunction freezeSortedSet(value: ReadonlySet<FactId>): readonly FactId[] {\n\treturn Object.freeze([...value].sort(compareString));\n}\n\nfunction rankFragments<T>(\n\tfragments: readonly MemoryFragment<T>[],\n\tquery: MemoryRetrievalQuery,\n): readonly MemoryFragment<T>[] {\n\tif (query.vector === undefined) return filterMemoryFragments(fragments, query);\n\tconst ranked = fragments.filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tranked.sort((a, b) => {\n\t\tconst vectorDelta = vectorScore(b, query) - vectorScore(a, query);\n\t\tif (vectorDelta !== 0) return vectorDelta;\n\t\tconst confidenceDelta = b.confidence - a.confidence;\n\t\tif (confidenceDelta !== 0) return confidenceDelta;\n\t\treturn compareBigIntDesc(a.tNs, b.tNs);\n\t});\n\treturn query.limit === undefined ? ranked : ranked.slice(0, Math.max(0, query.limit));\n}\n\nfunction vectorScore(fragment: MemoryFragment, query: MemoryRetrievalQuery): number {\n\tif (query.vector === undefined || fragment.embedding === undefined) return 0;\n\treturn cosineSimilarity(query.vector, fragment.embedding);\n}\n\nfunction statusState(\n\terrors: readonly Omit<MemoryRetrievalError, \"cursor\">[],\n\tresultCount: number,\n): MemoryRetrievalStatusState {\n\tif (errors.some((error) => !isRecoverableFragmentError(error))) return \"error\";\n\tif (errors.length > 0) return \"partial\";\n\treturn resultCount > 0 ? \"ready\" : \"empty\";\n}\n\nfunction isRecoverableFragmentError(error: Omit<MemoryRetrievalError, \"cursor\">): boolean {\n\treturn error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\";\n}\n\nfunction indexById<T>(\n\tfragments: readonly MemoryFragment<T>[],\n): Readonly<Record<FactId, MemoryFragment<T>>> {\n\tconst byId = Object.create(null) as Record<FactId, MemoryFragment<T>>;\n\tfor (const fragment of fragments) byId[fragment.id] = fragment;\n\treturn Object.freeze(byId);\n}\n\nfunction isFiniteVector(value: unknown): value is readonly number[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !Number.isFinite(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction validateMemoryRetrievalQuery(value: unknown): MemoryRetrievalQueryValidation {\n\ttry {\n\t\treturn validateMemoryRetrievalQueryInner(value);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tquery: {},\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-query\",\n\t\t\t\t\tmessage: `memoryRetrievalBundle: query access failed: ${errorMessage(error)}`,\n\t\t\t\t\tfragment: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateMemoryRetrievalQueryInner(value: unknown): MemoryRetrievalQueryValidation {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn invalidQuery(value, \"memoryRetrievalBundle: query must be an object\");\n\t}\n\tconst query = value as Partial<MemoryRetrievalQuery>;\n\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [];\n\tif (\n\t\tquery.tags !== undefined &&\n\t\t!isDenseArrayOf(query.tags, (tag): tag is string => typeof tag === \"string\")\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.tags must be a readonly string array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"tags must be a readonly string array\"],\n\t\t});\n\t}\n\tif (query.asOf !== undefined && typeof query.asOf !== \"bigint\") {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.asOf must be a bigint\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"asOf must be a bigint when present\"],\n\t\t});\n\t}\n\tif (\n\t\tquery.minConfidence !== undefined &&\n\t\t(!Number.isFinite(query.minConfidence) || query.minConfidence < 0 || query.minConfidence > 1)\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.minConfidence must be a finite number in [0, 1]\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"minConfidence must be a finite number in [0, 1]\"],\n\t\t});\n\t}\n\tif (query.limit !== undefined && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.limit must be a non-negative safe integer\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"limit must be a non-negative safe integer\"],\n\t\t});\n\t}\n\tif (query.vector !== undefined && !isFiniteVector(query.vector)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query-vector\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.vector must be a finite number array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"vector must be a finite number array\"],\n\t\t});\n\t}\n\tif (errors.length > 0) return { ok: false, query: {}, errors };\n\treturn { ok: true, query: snapshotQuery(query), errors };\n}\n\nfunction invalidQuery(value: unknown, message: string): MemoryRetrievalQueryValidation {\n\treturn {\n\t\tok: false,\n\t\tquery: {},\n\t\terrors: [\n\t\t\t{\n\t\t\t\tcode: \"invalid-query\",\n\t\t\t\tmessage,\n\t\t\t\tfragment: value,\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction snapshotQuery(query: Partial<MemoryRetrievalQuery>): MemoryRetrievalQuery {\n\treturn Object.freeze({\n\t\t...(query.tags === undefined ? {} : { tags: Object.freeze([...query.tags]) }),\n\t\t...(query.asOf === undefined ? {} : { asOf: query.asOf }),\n\t\t...(query.minConfidence === undefined ? {} : { minConfidence: query.minConfidence }),\n\t\t...(query.limit === undefined ? {} : { limit: query.limit }),\n\t\t...(query.vector === undefined ? {} : { vector: Object.freeze([...query.vector]) }),\n\t});\n}\n\nfunction safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateAndSnapshotFragment<T>(\n\trawFragments: readonly unknown[],\n\tindex: number,\n): FragmentValidationResult<T> {\n\tlet raw: unknown;\n\ttry {\n\t\traw = rawFragments[index];\n\t\tconst validation = validateMemoryFragment(raw);\n\t\tif (!validation.ok) {\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: invalid memory fragment\",\n\t\t\t\t\tindex,\n\t\t\t\t\tfragment: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze([...validation.errors]),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn { fragment: snapshotFragment(raw as MemoryFragment<T>) };\n\t} catch (error) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\tmessage: `memoryRetrievalBundle: fragment access failed: ${errorMessage(error)}`,\n\t\t\t\tindex,\n\t\t\t\tfragment: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"fragment access failed\"]),\n\t\t\t},\n\t\t};\n\t}\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction compareString(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n","/**\n * Thin agentic-memory solution surface.\n *\n * D125 places vertical application kits under solutions, while D158 keeps\n * semantic-memory retrieval/ranking in horizontal patterns. This v0 bundle\n * composes those lower layers into graph-visible facts only: no agent runtime,\n * hidden scheduler, storage restore/hydration, LLM loop, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport {\n\ttype Codec,\n\ttype StrictJsonValue as SharedStrictJsonValue,\n\tstrictJsonCodec,\n} from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport {\n\ttype FactId,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryAnswer,\n\ttype MemoryFragment,\n\tvalidateMemoryFragment,\n} from \"../patterns/semantic-memory.js\";\nimport {\n\ttype MemoryRetrievalBundle,\n\ttype MemoryRetrievalCursor,\n\ttype MemoryRetrievalError,\n\ttype MemoryRetrievalIndex,\n\ttype MemoryRetrievalQuery,\n\ttype MemoryRetrievalSnapshot,\n\ttype MemoryRetrievalStatus,\n\tmemoryRetrievalBundle,\n} from \"../patterns/semantic-memory-graph.js\";\n\nexport type AgenticMemoryStrictJsonValue = SharedStrictJsonValue;\n\ntype StrictJsonValue = SharedStrictJsonValue;\n\nexport type {\n\tKnowledgeAssertion,\n\tKnowledgeAssertionObject,\n\tKnowledgeAssertionSubject,\n} from \"../patterns/semantic-memory.js\";\n\n/** Agent-facing memory category. D164 keeps this separate from durability and artifact kind. */\nexport type AgenticMemoryKind = \"working\" | \"episodic\" | \"semantic\" | \"procedural\" | \"profile\";\n\n/** Semantic durability/retention policy metadata. This is not a storage tier handle. */\nexport type AgenticMemoryPersistenceLevel =\n\t| \"turn\"\n\t| \"session\"\n\t| \"project\"\n\t| \"longTerm\"\n\t| \"permanent\"\n\t| \"archived\";\n\n/** Whether the record is raw evidence or a derived artifact. */\nexport type AgenticMemoryArtifactKind = \"raw\" | \"insight\" | \"profile\" | \"procedure\";\n\n/** Optional solution-facing scope metadata. Scope ids are ordinary DATA facts. */\nexport interface AgenticMemoryScope {\n\treadonly sessionId?: string;\n\treadonly projectId?: string;\n\treadonly userId?: string;\n\treadonly tenantId?: string;\n}\n\n/**\n * D164 solution envelope over a lower-layer MemoryFragment.\n *\n * The envelope carries agentic-memory metadata only. It intentionally owns no\n * storage tiers/keys/adapters, restore/hydration behavior, timers, schedulers,\n * LLM/tool/runner handles, or protocol semantics.\n */\nexport interface AgenticMemoryRecord<T = unknown> {\n\treadonly id: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport interface AgenticMemoryRecordMetadata {\n\treadonly recordId: FactId;\n\treadonly kind: AgenticMemoryKind;\n\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\treadonly artifactKind: AgenticMemoryArtifactKind;\n\treadonly scope?: AgenticMemoryScope;\n}\n\nexport interface AgenticMemoryProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly invalidRecords: number;\n\treadonly projectedFragments: number;\n}\n\nexport type AgenticMemoryStatusState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\nexport interface AgenticMemoryStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport type AgenticMemoryErrorCode =\n\t| \"duplicate-record-id\"\n\t| \"duplicate-fragment-id\"\n\t| \"invalid-records-input\"\n\t| \"invalid-record\"\n\t| \"invalid-record-kind\"\n\t| \"invalid-persistence-level\"\n\t| \"invalid-artifact-kind\"\n\t| \"invalid-scope\"\n\t| \"invalid-fragment\";\n\nexport interface AgenticMemoryError {\n\treadonly code: AgenticMemoryErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\nexport interface AgenticMemoryProjectionSnapshot<T = unknown> {\n\treadonly records: readonly AgenticMemoryRecord<T>[];\n\treadonly fragments: readonly MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Readonly<Record<FactId, AgenticMemoryRecordMetadata>>;\n\treadonly status: AgenticMemoryStatus;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly cursor: AgenticMemoryProjectionCursor;\n}\n\n/** Source/provenance projection for a valid memory fragment. */\nexport interface AgenticMemorySourceProjection {\n\treadonly fragmentId: FactId;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly sources: readonly FactId[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** A context-ready item derived from ranked memory retrieval results. */\nexport interface AgenticMemoryContextEntry<T = unknown> {\n\treadonly fragmentId: FactId;\n\treadonly payload: T;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly fragment: MemoryFragment<T>;\n}\n\nexport type AgenticMemoryContextState = \"ready\" | \"empty\" | \"partial\" | \"error\";\n\n/**\n * Context-ready ranked memory output for callers such as prompt builders.\n *\n * This is still only a DATA fact. It does not extract, summarize, reflect, run\n * tools, or choose an autonomous action.\n */\nexport interface AgenticMemoryContext<T = unknown> {\n\treadonly state: AgenticMemoryContextState;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly entries: readonly AgenticMemoryContextEntry<T>[];\n\treadonly cursor: MemoryRetrievalCursor;\n\treadonly errors: readonly AgenticMemoryError[];\n\treadonly retrievalErrors: readonly MemoryRetrievalError[];\n\treadonly contextReady: boolean;\n}\n\n/** Explicit KG assertion draft fact; extraction/LLM work happens outside this bundle. */\nexport interface AgenticMemoryKgAssertionDraft {\n\treadonly id: FactId;\n\treadonly recordId: FactId;\n\treadonly fragmentId: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryKgProjectionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validDrafts: number;\n\treadonly invalidDrafts: number;\n\treadonly projectedAssertions: number;\n}\n\nexport type AgenticMemoryKgProjectionStatusState = AgenticMemoryStatusState;\n\nexport interface AgenticMemoryKgProjectionStatus {\n\treadonly state: AgenticMemoryKgProjectionStatusState;\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport type AgenticMemoryKgProjectionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-drafts-input\"\n\t| \"invalid-draft\"\n\t| \"duplicate-assertion-id\"\n\t| \"missing-record-ref\"\n\t| \"missing-fragment-ref\"\n\t| \"fragment-record-mismatch\"\n\t| \"invalid-assertion-shape\";\n\nexport interface AgenticMemoryKgProjectionError {\n\treadonly code: AgenticMemoryKgProjectionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly assertionId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly draft?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionSnapshot {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly status: AgenticMemoryKgProjectionStatus;\n\treadonly errors: readonly AgenticMemoryKgProjectionError[];\n\treadonly cursor: AgenticMemoryKgProjectionCursor;\n}\n\nexport interface AgenticMemoryKgProjectionBundle {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\t\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryKgProjectionSnapshot>;\n\treadonly assertions: Node<readonly KnowledgeAssertion[]>;\n\treadonly status: Node<AgenticMemoryKgProjectionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryKgProjectionError[]>;\n\treadonly cursor: Node<AgenticMemoryKgProjectionCursor>;\n}\n\nexport interface AgenticMemoryKgProjectionBundleOptions {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord[]>;\n\treadonly drafts: Node<readonly AgenticMemoryKgAssertionDraft[]>;\n}\n\nexport const AGENTIC_MEMORY_RECORD_FRAME_FORMAT = \"graphrefly.agenticMemoryRecord\";\nexport const AGENTIC_MEMORY_RECORD_FRAME_VERSION = 1;\n\nexport interface AgenticMemoryFragmentFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly id: FactId;\n\treadonly payload: TJson;\n\treadonly tNs: string;\n\treadonly validFrom?: string;\n\treadonly validTo?: string;\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue> {\n\treadonly format: typeof AGENTIC_MEMORY_RECORD_FRAME_FORMAT;\n\treadonly version: typeof AGENTIC_MEMORY_RECORD_FRAME_VERSION;\n\treadonly record: {\n\t\treadonly id: FactId;\n\t\treadonly kind: AgenticMemoryKind;\n\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\treadonly artifactKind: AgenticMemoryArtifactKind;\n\t\treadonly scope?: AgenticMemoryScope;\n\t\treadonly fragment: AgenticMemoryFragmentFrame<TJson>;\n\t};\n}\n\nexport type AgenticMemoryRetentionCommand =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"archive\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"restore\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel?: Exclude<AgenticMemoryPersistenceLevel, \"archived\">;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"setPersistenceLevel\";\n\t\t\treadonly recordId: FactId;\n\t\t\treadonly persistenceLevel: AgenticMemoryPersistenceLevel;\n\t\t\treadonly reason?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly kind: \"requestConsolidation\";\n\t\t\treadonly recordIds: readonly FactId[];\n\t\t\treadonly requestId?: FactId;\n\t\t\treadonly reason?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRequest {\n\treadonly id: FactId;\n\treadonly commandId: FactId;\n\treadonly recordIds: readonly FactId[];\n\treadonly reason?: string;\n}\n\nexport interface AgenticMemoryRetentionCursor {\n\treadonly evaluation: number;\n\treadonly validRecords: number;\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n\treadonly activeRecords: number;\n\treadonly archivedRecords: number;\n\treadonly consolidationRequests: number;\n}\n\nexport interface AgenticMemoryRetentionStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport type AgenticMemoryRetentionErrorCode =\n\t| AgenticMemoryErrorCode\n\t| \"invalid-commands-input\"\n\t| \"invalid-command\"\n\t| \"duplicate-command-id\"\n\t| \"missing-record-ref\";\n\nexport interface AgenticMemoryRetentionError {\n\treadonly code: AgenticMemoryRetentionErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly commandId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly recordIds?: readonly FactId[];\n\treadonly command?: unknown;\n\treadonly record?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionSnapshot<T = unknown> {\n\treadonly activeRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: readonly AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly status: AgenticMemoryRetentionStatus;\n\treadonly errors: readonly AgenticMemoryRetentionError[];\n\treadonly cursor: AgenticMemoryRetentionCursor;\n}\n\nexport interface AgenticMemoryRetentionBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryRetentionSnapshot<T>>;\n\treadonly activeRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly archivedRecords: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly consolidationRequests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly status: Node<AgenticMemoryRetentionStatus>;\n\treadonly errors: Node<readonly AgenticMemoryRetentionError[]>;\n\treadonly cursor: Node<AgenticMemoryRetentionCursor>;\n}\n\nexport interface AgenticMemoryRetentionBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryRetentionCommand[]>;\n}\n\nexport type AgenticMemoryConsolidationOutcome<T = unknown> =\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"proposedRecords\";\n\t\t\treadonly records: readonly AgenticMemoryRecord<T>[];\n\t\t\treadonly provenance?: string;\n\t }\n\t| {\n\t\t\treadonly id: FactId;\n\t\t\treadonly requestId: FactId;\n\t\t\treadonly kind: \"failed\";\n\t\t\treadonly message: string;\n\t\t\treadonly provenance?: string;\n\t };\n\nexport interface AgenticMemoryConsolidationRecordDraft<T = unknown> {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly record: AgenticMemoryRecord<T>;\n}\n\nexport interface AgenticMemoryConsolidationCommand {\n\treadonly id: FactId;\n\treadonly kind: \"proposeRecords\" | \"markFailed\";\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly draftIds?: readonly FactId[];\n\treadonly message?: string;\n}\n\nexport interface AgenticMemoryConsolidationResult {\n\treadonly id: FactId;\n\treadonly requestId: FactId;\n\treadonly outcomeId: FactId;\n\treadonly state: \"proposed\" | \"failed\";\n\treadonly sourceRecordIds: readonly FactId[];\n\treadonly proposedRecordIds: readonly FactId[];\n\treadonly message?: string;\n\treadonly provenance?: string;\n}\n\nexport interface AgenticMemoryConsolidationCursor {\n\treadonly evaluation: number;\n\treadonly validRequests: number;\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n\treadonly results: number;\n\treadonly proposedRecordDrafts: number;\n}\n\nexport interface AgenticMemoryConsolidationStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport type AgenticMemoryConsolidationErrorCode =\n\t| AgenticMemoryRetentionErrorCode\n\t| \"invalid-outcomes-input\"\n\t| \"invalid-outcome\"\n\t| \"duplicate-outcome-id\"\n\t| \"missing-request-ref\"\n\t| \"invalid-proposed-record\";\n\nexport interface AgenticMemoryConsolidationError {\n\treadonly code: AgenticMemoryConsolidationErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly outcomeId?: FactId;\n\treadonly requestId?: FactId;\n\treadonly recordId?: FactId;\n\treadonly outcome?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationSnapshot<T = unknown> {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly status: AgenticMemoryConsolidationStatus;\n\treadonly errors: readonly AgenticMemoryConsolidationError[];\n\treadonly cursor: AgenticMemoryConsolidationCursor;\n}\n\nexport interface AgenticMemoryConsolidationBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\t\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n\t};\n\treadonly projection: Node<AgenticMemoryConsolidationSnapshot<T>>;\n\treadonly results: Node<readonly AgenticMemoryConsolidationResult[]>;\n\treadonly proposedRecordDrafts: Node<readonly AgenticMemoryConsolidationRecordDraft<T>[]>;\n\treadonly commands: Node<readonly AgenticMemoryConsolidationCommand[]>;\n\treadonly status: Node<AgenticMemoryConsolidationStatus>;\n\treadonly errors: Node<readonly AgenticMemoryConsolidationError[]>;\n\treadonly cursor: Node<AgenticMemoryConsolidationCursor>;\n}\n\nexport interface AgenticMemoryConsolidationBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly requests: Node<readonly AgenticMemoryConsolidationRequest[]>;\n\treadonly outcomes: Node<readonly AgenticMemoryConsolidationOutcome<T>[]>;\n}\n\nexport interface AgenticMemoryContextText {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost?: number;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryContextPackingPolicy {\n\treadonly maxEntries?: number;\n\treadonly maxChars?: number;\n\treadonly maxCost?: number;\n\treadonly includeMetadata?: boolean;\n}\n\nexport interface AgenticMemoryPackedContextEntry {\n\treadonly fragmentId: FactId;\n\treadonly text: string;\n\treadonly cost: number;\n\treadonly chars: number;\n\treadonly record?: AgenticMemoryRecordMetadata;\n\treadonly metadata?: Readonly<Record<string, StrictJsonValue>>;\n}\n\nexport interface AgenticMemoryPackedContext {\n\treadonly entries: readonly AgenticMemoryPackedContextEntry[];\n\treadonly text: string;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n\treadonly truncated: boolean;\n}\n\nexport interface AgenticMemoryContextPackingCursor {\n\treadonly evaluation: number;\n\treadonly inputEntries: number;\n\treadonly packedEntries: number;\n\treadonly omittedEntries: number;\n\treadonly totalChars: number;\n\treadonly totalCost: number;\n}\n\nexport interface AgenticMemoryContextPackingStatus {\n\treadonly state: AgenticMemoryStatusState;\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport type AgenticMemoryContextPackingErrorCode =\n\t| \"invalid-context\"\n\t| \"invalid-texts-input\"\n\t| \"invalid-text\"\n\t| \"duplicate-text-fragment-id\"\n\t| \"missing-text\"\n\t| \"invalid-policy\";\n\nexport interface AgenticMemoryContextPackingError {\n\treadonly code: AgenticMemoryContextPackingErrorCode;\n\treadonly message: string;\n\treadonly index?: number;\n\treadonly fragmentId?: FactId;\n\treadonly value?: unknown;\n\treadonly validationErrors?: readonly string[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingSnapshot {\n\treadonly packedContext: AgenticMemoryPackedContext;\n\treadonly status: AgenticMemoryContextPackingStatus;\n\treadonly errors: readonly AgenticMemoryContextPackingError[];\n\treadonly cursor: AgenticMemoryContextPackingCursor;\n}\n\nexport interface AgenticMemoryContextPackingBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly context: Node<AgenticMemoryContext<T>>;\n\t\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\t\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n\t};\n\treadonly projection: Node<AgenticMemoryContextPackingSnapshot>;\n\treadonly packedContext: Node<AgenticMemoryPackedContext>;\n\treadonly status: Node<AgenticMemoryContextPackingStatus>;\n\treadonly errors: Node<readonly AgenticMemoryContextPackingError[]>;\n\treadonly cursor: Node<AgenticMemoryContextPackingCursor>;\n}\n\nexport interface AgenticMemoryContextPackingBundleOptions<T = unknown> {\n\treadonly name?: string;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly texts: Node<readonly AgenticMemoryContextText[]>;\n\treadonly policy: Node<AgenticMemoryContextPackingPolicy>;\n}\n\ninterface ValidatedPackingContext {\n\treadonly entries: readonly AgenticMemoryContextEntry[];\n}\n\nexport interface AgenticMemoryBundle<T = unknown> {\n\treadonly input: {\n\t\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t\treadonly query: Node<MemoryRetrievalQuery>;\n\t};\n\treadonly projection: Node<AgenticMemoryProjectionSnapshot<T>>;\n\treadonly retrieval: MemoryRetrievalBundle<T>;\n\treadonly retrievalSnapshot: Node<MemoryRetrievalSnapshot<T>>;\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\treadonly fragments: Node<readonly MemoryFragment<T>[]>;\n\treadonly sources: Node<readonly AgenticMemorySourceProjection[]>;\n\treadonly indexed: Node<MemoryRetrievalIndex<T>>;\n\treadonly ranked: Node<MemoryAnswer<T>>;\n\treadonly context: Node<AgenticMemoryContext<T>>;\n\treadonly status: Node<AgenticMemoryStatus>;\n\treadonly errors: Node<readonly AgenticMemoryError[]>;\n\treadonly retrievalStatus: Node<MemoryRetrievalStatus>;\n\treadonly retrievalErrors: Node<readonly MemoryRetrievalError[]>;\n\treadonly cursor: Node<MemoryRetrievalCursor>;\n}\n\nexport interface AgenticMemoryBundleOptions<T = unknown> {\n\treadonly name?: string;\n\t/** Explicit record-envelope input. Persistence, if needed, composes D161 outside this bundle. */\n\treadonly records: Node<readonly AgenticMemoryRecord<T>[]>;\n\t/** Explicit retrieval query input. */\n\treadonly query: Node<MemoryRetrievalQuery>;\n}\n\n/**\n * Compose graph-visible semantic-memory retrieval into an agentic-memory v0 bundle.\n *\n * The returned nodes are ordinary graph nodes with declared deps and DATA facts.\n * Invalid record envelopes and duplicate record ids stay graph-visible through\n * solution-level status/errors DATA facts. The lower retrieval bundle remains\n * visible and receives only projected MemoryFragment values.\n */\nexport function agenticMemoryBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryBundleOptions<T>,\n): AgenticMemoryBundle<T> {\n\tconst name = opts.name ?? \"agenticMemory\";\n\tconst projection = agenticMemoryRecordProjection<T>(graph, opts.records, `${name}/projection`);\n\tconst projectedRecords = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/records`,\n\t\t\"agenticMemoryRecords\",\n\t\t(fact) => fact.records,\n\t);\n\tconst projectedFragments = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/fragments`,\n\t\t\"agenticMemoryFragments\",\n\t\t(fact) => fact.fragments,\n\t);\n\tconst status = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/status`,\n\t\t\"agenticMemoryStatus\",\n\t\t(fact) => fact.status,\n\t);\n\tconst errors = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/errors`,\n\t\t\"agenticMemoryErrors\",\n\t\t(fact) => fact.errors,\n\t);\n\tconst retrieval = memoryRetrievalBundle<T>(graph, {\n\t\tname: `${name}/retrieval`,\n\t\tfragments: projectedFragments,\n\t\tquery: opts.query,\n\t});\n\tconst sources = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/sources`,\n\t\t\"agenticMemorySources\",\n\t\t(fact) =>\n\t\t\tObject.freeze(\n\t\t\t\tfact.fragments.map((fragment) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragmentId: fragment.id,\n\t\t\t\t\t\t...(fact.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { record: fact.metadataByFragmentId[fragment.id] }),\n\t\t\t\t\t\tsources: Object.freeze([...fragment.sources]),\n\t\t\t\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t\t\t\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t);\n\tconst context = agenticMemoryContextProjection(\n\t\tgraph,\n\t\tprojection,\n\t\tretrieval.snapshot,\n\t\t`${name}/context`,\n\t);\n\n\treturn {\n\t\tinput: { records: opts.records, query: opts.query },\n\t\tprojection,\n\t\tretrieval,\n\t\tretrievalSnapshot: retrieval.snapshot,\n\t\trecords: projectedRecords,\n\t\tfragments: projectedFragments,\n\t\tsources,\n\t\tindexed: retrieval.indexed,\n\t\tranked: retrieval.ranked,\n\t\tcontext,\n\t\tstatus,\n\t\terrors,\n\t\tretrievalStatus: retrieval.status,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcursor: retrieval.cursor,\n\t};\n}\n\n/**\n * D165 solution-level KG assertion projection.\n *\n * Records and explicit assertion drafts stay visible as declared deps. This\n * bundle validates references and shape, then emits DATA facts only; it does\n * not extract assertions, call LLMs, read/write storage, or mutate topology.\n */\nexport function agenticMemoryKgProjectionBundle(\n\tgraph: Graph,\n\topts: AgenticMemoryKgProjectionBundleOptions,\n): AgenticMemoryKgProjectionBundle {\n\tconst name = opts.name ?? \"agenticMemoryKgProjection\";\n\tconst projection = graph.node<AgenticMemoryKgProjectionSnapshot>(\n\t\t[opts.records, opts.drafts],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords(depLatest(ctx, 0));\n\t\t\tconst draftProjection = validateAndProjectKgDrafts(\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\trecordProjection.records,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryKgProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidDrafts: draftProjection.assertions.length,\n\t\t\t\tinvalidDrafts: draftProjection.invalidDrafts,\n\t\t\t\tprojectedAssertions: draftProjection.assertions.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(kgErrorFromRecordError), ...draftProjection.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryKgProjectionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, draftProjection.assertions.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(draftProjection.assertions),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryKgProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, drafts: opts.drafts },\n\t\tprojection,\n\t\tassertions: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/assertions`,\n\t\t\t\"agenticMemoryKgAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryKgStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryKgErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryKgCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** Build a D166 strict-JSON frame from an in-memory AgenticMemoryRecord. */\nexport function agenticMemoryRecordFrame<TJson extends StrictJsonValue>(\n\trecord: AgenticMemoryRecord<TJson>,\n): AgenticMemoryRecordFrame<TJson> {\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: invalid record: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\tassertAgenticMemoryRecordCodecShape(record);\n\tassertStrictJsonValue(result.record.fragment.payload, \"record.fragment.payload\");\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\t\trecord: Object.freeze({\n\t\t\tid: result.record.id,\n\t\t\tkind: result.record.kind,\n\t\t\tpersistenceLevel: result.record.persistenceLevel,\n\t\t\tartifactKind: result.record.artifactKind,\n\t\t\t...(result.record.scope === undefined ? {} : { scope: result.record.scope }),\n\t\t\tfragment: fragmentFrame(result.record.fragment as MemoryFragment<TJson>),\n\t\t}),\n\t});\n}\n\n/** Assert and snapshot a decoded D166 record frame. Unknown fields fail honestly. */\nexport function assertAgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue>(\n\tvalue: unknown,\n): AgenticMemoryRecordFrame<TJson> {\n\tif (!isPlainRecord(value))\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: frame must be an object\");\n\tassertStrictJsonValue(value, \"agenticMemoryRecordFrame\");\n\tassertExactKeys(value, [\"format\", \"record\", \"version\"], \"agenticMemoryRecordFrame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_FRAME_FORMAT) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid version\");\n\t}\n\tconst rawRecord = value.record;\n\tif (!isPlainRecord(rawRecord)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawRecord,\n\t\trawRecord.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst rawFragment = rawRecord.fragment;\n\tif (!isPlainRecord(rawFragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawFragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(rawFragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(rawFragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(rawFragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(rawFragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(rawFragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tif (rawRecord.scope !== undefined) assertScopeFrame(rawRecord.scope);\n\tconst frame = value as unknown as AgenticMemoryRecordFrame<TJson>;\n\tconst decoded = recordFromFrame(frame);\n\tconst roundtrip = agenticMemoryRecordFrame(decoded);\n\treturn roundtrip as AgenticMemoryRecordFrame<TJson>;\n}\n\n/** Strict canonical JSON codec for D166 AgenticMemoryRecordFrame values. */\nexport function agenticMemoryRecordFrameCodec<\n\tTJson extends StrictJsonValue = StrictJsonValue,\n>(): Codec<AgenticMemoryRecordFrame<TJson>> {\n\treturn {\n\t\tencode(value: AgenticMemoryRecordFrame<TJson>): Uint8Array {\n\t\t\treturn strictJsonCodec.encode(assertAgenticMemoryRecordFrame<TJson>(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecordFrame<TJson> {\n\t\t\treturn assertAgenticMemoryRecordFrame<TJson>(strictJsonCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/** Strict canonical JSON codec that persists records and decodes bigint fields back to bigint. */\nexport function agenticMemoryRecordCodec<TJson extends StrictJsonValue = StrictJsonValue>(): Codec<\n\tAgenticMemoryRecord<TJson>\n> {\n\tconst frameCodec = agenticMemoryRecordFrameCodec<TJson>();\n\treturn {\n\t\tencode(value: AgenticMemoryRecord<TJson>): Uint8Array {\n\t\t\treturn frameCodec.encode(agenticMemoryRecordFrame(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecord<TJson> {\n\t\t\treturn recordFromFrame(frameCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/**\n * D167 solution-level retention command projection.\n *\n * Archive/restore/setPersistenceLevel are derived views over current records;\n * requestConsolidation emits request facts only.\n */\nexport function agenticMemoryRetentionBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryRetentionBundleOptions<T>,\n): AgenticMemoryRetentionBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryRetention\";\n\tconst projection = graph.node<AgenticMemoryRetentionSnapshot<T>>(\n\t\t[opts.records, opts.commands],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst retention = projectRetention<T>(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst cursor: AgenticMemoryRetentionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidCommands: retention.validCommands,\n\t\t\t\tinvalidCommands: retention.invalidCommands,\n\t\t\t\tactiveRecords: retention.activeRecords.length,\n\t\t\t\tarchivedRecords: retention.archivedRecords.length,\n\t\t\t\tconsolidationRequests: retention.consolidationRequests.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(retentionErrorFromRecordError), ...retention.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryRetentionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, recordProjection.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tactiveRecords: Object.freeze(retention.activeRecords),\n\t\t\t\t\t\tarchivedRecords: Object.freeze(retention.archivedRecords),\n\t\t\t\t\t\tconsolidationRequests: Object.freeze(retention.consolidationRequests),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryRetention\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, commands: opts.commands },\n\t\tprojection,\n\t\tactiveRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/activeRecords`,\n\t\t\t\"agenticMemoryRetentionActiveRecords\",\n\t\t\t(fact) => fact.activeRecords,\n\t\t),\n\t\tarchivedRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/archivedRecords`,\n\t\t\t\"agenticMemoryRetentionArchivedRecords\",\n\t\t\t(fact) => fact.archivedRecords,\n\t\t),\n\t\tconsolidationRequests: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/consolidationRequests`,\n\t\t\t\"agenticMemoryRetentionConsolidationRequests\",\n\t\t\t(fact) => fact.consolidationRequests,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryRetentionStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryRetentionErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryRetentionCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D171 consolidation outcome projection.\n *\n * The bundle does not execute consolidation. External adapters may publish\n * outcome facts, and this projection turns them into visible result/proposal\n * facts for downstream record-creation policy.\n */\nexport function agenticMemoryConsolidationBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryConsolidationBundleOptions<T>,\n): AgenticMemoryConsolidationBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryConsolidation\";\n\tconst projection = graph.node<AgenticMemoryConsolidationSnapshot<T>>(\n\t\t[opts.records, opts.requests, opts.outcomes],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst requests = validateConsolidationRequests(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst outcomes = projectConsolidationOutcomes<T>(\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\trequests.requests,\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryConsolidationCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRequests: requests.requests.length,\n\t\t\t\tvalidOutcomes: outcomes.validOutcomes,\n\t\t\t\tinvalidOutcomes: outcomes.invalidOutcomes,\n\t\t\t\tresults: outcomes.results.length,\n\t\t\t\tproposedRecordDrafts: outcomes.proposedRecordDrafts.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...recordProjection.errors.map(consolidationErrorFromRecordError),\n\t\t\t\t\t...requests.errors.map(consolidationErrorFromRetentionError),\n\t\t\t\t\t...outcomes.errors,\n\t\t\t\t].map((error) => freezeError({ ...error, cursor })),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryConsolidationStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, outcomes.results.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tresults: Object.freeze(outcomes.results),\n\t\t\t\t\t\tproposedRecordDrafts: Object.freeze(outcomes.proposedRecordDrafts),\n\t\t\t\t\t\tcommands: Object.freeze(outcomes.commands),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryConsolidation\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, requests: opts.requests, outcomes: opts.outcomes },\n\t\tprojection,\n\t\tresults: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/results`,\n\t\t\t\"agenticMemoryConsolidationResults\",\n\t\t\t(fact) => fact.results,\n\t\t),\n\t\tproposedRecordDrafts: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/proposedRecordDrafts`,\n\t\t\t\"agenticMemoryConsolidationRecordDrafts\",\n\t\t\t(fact) => fact.proposedRecordDrafts,\n\t\t),\n\t\tcommands: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/commands`,\n\t\t\t\"agenticMemoryConsolidationCommands\",\n\t\t\t(fact) => fact.commands,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryConsolidationStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryConsolidationErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryConsolidationCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** D168 deterministic context-packing bundle over explicit context text facts. */\nexport function agenticMemoryContextPackingBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryContextPackingBundleOptions<T>,\n): AgenticMemoryContextPackingBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryContextPacking\";\n\tconst projection = graph.node<AgenticMemoryContextPackingSnapshot>(\n\t\t[opts.context, opts.texts, opts.policy],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst packed = packContext(\n\t\t\t\tdepLatest(ctx, 0),\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", packed]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryContextPacking\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { context: opts.context, texts: opts.texts, policy: opts.policy },\n\t\tprojection,\n\t\tpackedContext: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/packedContext`,\n\t\t\t\"agenticMemoryPackedContext\",\n\t\t\t(fact) => fact.packedContext,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryContextPackingStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryContextPackingErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryContextPackingCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction solutionProjection<TFact, TSnapshot>(\n\tgraph: Graph,\n\tsnapshot: Node<TSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: TSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as TSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: AgenticMemoryProjectionSnapshot<T>) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as AgenticMemoryProjectionSnapshot<T>)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction agenticMemoryContextProjection<T>(\n\tgraph: Graph,\n\tprojection: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tretrieval: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n): Node<AgenticMemoryContext<T>> {\n\treturn graph.node<AgenticMemoryContext<T>>(\n\t\t[projection, retrieval],\n\t\t(ctx) => {\n\t\t\tconst projectionFact = depLatest(ctx, 0) as AgenticMemoryProjectionSnapshot<T> | undefined;\n\t\t\tconst retrievalFacts = depBatch(ctx, 1) ?? [];\n\t\t\tif (projectionFact === undefined || retrievalFacts.length === 0) return;\n\t\t\tfor (const raw of retrievalFacts) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", contextFromSnapshot(projectionFact, raw as MemoryRetrievalSnapshot<T>)],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryContext\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction contextFromSnapshot<T>(\n\tprojection: AgenticMemoryProjectionSnapshot<T>,\n\tretrieval: MemoryRetrievalSnapshot<T>,\n): AgenticMemoryContext<T> {\n\tconst entries = retrieval.ranked.results.map((fragment) =>\n\t\tObject.freeze({\n\t\t\tfragmentId: fragment.id,\n\t\t\tpayload: fragment.payload,\n\t\t\tconfidence: fragment.confidence,\n\t\t\ttags: fragment.tags,\n\t\t\tsources: fragment.sources,\n\t\t\t...(projection.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t? {}\n\t\t\t\t: { record: projection.metadataByFragmentId[fragment.id] }),\n\t\t\tfragment,\n\t\t}),\n\t);\n\tconst hasContext = entries.length > 0;\n\tconst state = contextState(projection.status.state, retrieval.status.state);\n\treturn Object.freeze({\n\t\tstate,\n\t\tquery: retrieval.ranked.query,\n\t\tentries: Object.freeze(entries),\n\t\tcursor: retrieval.cursor,\n\t\terrors: projection.errors,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcontextReady: hasContext && (state === \"ready\" || state === \"partial\"),\n\t});\n}\n\nfunction agenticMemoryRecordProjection<T>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<T>[]>,\n\tname: string,\n): Node<AgenticMemoryProjectionSnapshot<T>> {\n\treturn graph.node<AgenticMemoryProjectionSnapshot<T>>(\n\t\t[records],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawRecords = (depBatch(ctx, 0) ?? []).at(-1);\n\t\t\tconst projected = validateAndProjectRecords<T>(rawRecords);\n\t\t\tconst cursor: AgenticMemoryProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: projected.records.length,\n\t\t\t\tinvalidRecords: projected.invalidRecordIndexes.size,\n\t\t\t\tprojectedFragments: projected.fragments.length,\n\t\t\t});\n\t\t\tconst status: AgenticMemoryStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(projected.errors.length, projected.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tprojected.errors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\trecords: Object.freeze(projected.records),\n\t\t\t\t\t\tfragments: Object.freeze(projected.fragments),\n\t\t\t\t\t\tmetadataByFragmentId: Object.freeze(projected.metadataByFragmentId),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction validateAndProjectKgDrafts(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord[],\n): {\n\treadonly assertions: KnowledgeAssertion[];\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n\treadonly invalidDrafts: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tlet invalidDrafts = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input must be an array\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input length could not be read\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst recordById = new Map(records.map((record) => [record.id, record]));\n\tconst fragmentToRecord = new Map(records.map((record) => [record.fragment.id, record.id]));\n\tconst seenAssertions = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateKgDraft(raw, i);\n\t\t\tif (result.errors.length > 0 || result.draft === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst draft = result.draft;\n\t\t\tif (seenAssertions.has(draft.id)) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: duplicate assertion id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate assertion id '${draft.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = recordById.get(draft.recordId);\n\t\t\tif (record === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing record\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`record '${draft.recordId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst owner = fragmentToRecord.get(draft.fragmentId);\n\t\t\tif (owner === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-fragment-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing fragment\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`fragment '${draft.fragmentId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (owner !== draft.recordId || record.fragment.id !== draft.fragmentId) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"fragment-record-mismatch\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft record and fragment refs disagree\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [\n\t\t\t\t\t\t`fragment '${draft.fragmentId}' belongs to record '${owner}', not '${draft.recordId}'`,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenAssertions.add(draft.id);\n\t\t\tassertions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tsubject: draft.subject,\n\t\t\t\t\tpredicate: draft.predicate,\n\t\t\t\t\tobject: draft.object,\n\t\t\t\t\t...(draft.confidence === undefined ? {} : { confidence: draft.confidence }),\n\t\t\t\t\tsources: Object.freeze(draft.sources ?? [draft.fragmentId]),\n\t\t\t\t\t...(draft.provenance === undefined ? {} : { provenance: draft.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tinvalidDrafts += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\tmessage: `agenticMemoryKgProjectionBundle: draft access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tdraft: raw,\n\t\t\t\tvalidationErrors: [\"draft access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn { assertions, errors, invalidDrafts };\n}\n\nfunction validateKgDraft(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly draft?: AgenticMemoryKgAssertionDraft;\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst raw = value as Partial<AgenticMemoryKgAssertionDraft>;\n\tconst id = typeof raw.id === \"string\" && raw.id.length > 0 ? raw.id : undefined;\n\tconst recordId =\n\t\ttypeof raw.recordId === \"string\" && raw.recordId.length > 0 ? raw.recordId : undefined;\n\tconst fragmentId =\n\t\ttypeof raw.fragmentId === \"string\" && raw.fragmentId.length > 0 ? raw.fragmentId : undefined;\n\tconst subject = validateAssertionSubject(raw.subject);\n\tconst object = validateAssertionObject(raw.object);\n\tconst shapeErrors: string[] = [];\n\tif (id === undefined) shapeErrors.push(\"draft.id must be a non-empty string\");\n\tif (recordId === undefined) {\n\t\tshapeErrors.push(\"draft.recordId must be a non-empty string\");\n\t}\n\tif (fragmentId === undefined) {\n\t\tshapeErrors.push(\"draft.fragmentId must be a non-empty string\");\n\t}\n\tshapeErrors.push(...subject.errors);\n\tif (typeof raw.predicate !== \"string\" || raw.predicate.length === 0) {\n\t\tshapeErrors.push(\"draft.predicate must be a non-empty string\");\n\t}\n\tshapeErrors.push(...object.errors);\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\tshapeErrors.push(\"draft.confidence must be a finite number in [0, 1]\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\tshapeErrors.push(\"draft.sources must be a readonly string array\");\n\t}\n\tif (raw.provenance !== undefined && typeof raw.provenance !== \"string\") {\n\t\tshapeErrors.push(\"draft.provenance must be a string when present\");\n\t}\n\tif (shapeErrors.length > 0) errors.push(kgShapeError(index, value, ...shapeErrors));\n\tif (errors.length > 0 || id === undefined || recordId === undefined || fragmentId === undefined) {\n\t\treturn { errors };\n\t}\n\treturn {\n\t\tdraft: Object.freeze({\n\t\t\tid,\n\t\t\trecordId,\n\t\t\tfragmentId,\n\t\t\tsubject: subject.subject as KnowledgeAssertionSubject,\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: object.object as KnowledgeAssertionObject,\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\t...(raw.sources === undefined ? {} : { sources: Object.freeze([...raw.sources]) }),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionSubject(value: unknown): {\n\treadonly subject?: KnowledgeAssertionSubject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"subject must be an object\"] };\n\tconst id = value.id;\n\tconst type = value.type;\n\tconst errors: string[] = [];\n\tif (typeof id !== \"string\" || id.length === 0) errors.push(\"subject.id must be non-empty\");\n\tif (type !== undefined && (typeof type !== \"string\" || type.length === 0)) {\n\t\terrors.push(\"subject.type must be a non-empty string when present\");\n\t}\n\tif (errors.length > 0) return { errors };\n\treturn {\n\t\tsubject: Object.freeze({\n\t\t\tid: id as string,\n\t\t\t...(type === undefined ? {} : { type: type as string }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionObject(value: unknown): {\n\treadonly object?: KnowledgeAssertionObject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"object must be an object\"] };\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (kind === \"entity\") {\n\t\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\t\terrors.push(\"object.id must be non-empty for entity objects\");\n\t\t}\n\t\tif (value.type !== undefined && (typeof value.type !== \"string\" || value.type.length === 0)) {\n\t\t\terrors.push(\"object.type must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"value\")) errors.push(\"entity object must not include value\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: value.id as string,\n\t\t\t\t...(value.type === undefined ? {} : { type: value.type as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\tif (kind === \"value\") {\n\t\tif (!Object.hasOwn(value, \"value\")) errors.push(\"value object must include value\");\n\t\telse {\n\t\t\ttry {\n\t\t\t\tassertStrictJsonValue(value.value, \"object.value\");\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(errorMessage(error));\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tvalue.valueType !== undefined &&\n\t\t\t(typeof value.valueType !== \"string\" || value.valueType.length === 0)\n\t\t) {\n\t\t\terrors.push(\"object.valueType must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"id\")) errors.push(\"value object must not include id\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: value.value as StrictJsonValue,\n\t\t\t\t...(value.valueType === undefined ? {} : { valueType: value.valueType as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\treturn { errors: [\"object.kind must be entity or value\"] };\n}\n\nfunction kgShapeError(\n\tindex: number,\n\tdraft: unknown,\n\t...validationErrors: readonly string[]\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\tcode: \"invalid-assertion-shape\",\n\t\tmessage: \"agenticMemoryKgProjectionBundle: draft assertion shape is invalid\",\n\t\tindex,\n\t\tdraft,\n\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t};\n}\n\nfunction kgErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction fragmentFrame<TJson extends StrictJsonValue>(\n\tfragment: MemoryFragment<TJson>,\n): AgenticMemoryFragmentFrame<TJson> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: decimalBigIntString(fragment.tNs, \"fragment.tNs\"),\n\t\t...(fragment.validFrom === undefined\n\t\t\t? {}\n\t\t\t: { validFrom: decimalBigIntString(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t...(fragment.validTo === undefined\n\t\t\t? {}\n\t\t\t: { validTo: decimalBigIntString(fragment.validTo, \"fragment.validTo\") }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordFromFrame<TJson extends StrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\tconst fragment = frame.record.fragment;\n\tconst record: AgenticMemoryRecord<TJson> = {\n\t\tid: assertNonEmptyString(frame.record.id, \"record.id\"),\n\t\tkind: assertKindValue(frame.record.kind),\n\t\tpersistenceLevel: assertPersistenceLevelValue(frame.record.persistenceLevel),\n\t\tartifactKind: assertArtifactKindValue(frame.record.artifactKind),\n\t\t...(frame.record.scope === undefined ? {} : { scope: assertScopeFrame(frame.record.scope) }),\n\t\tfragment: {\n\t\t\tid: assertNonEmptyString(fragment.id, \"fragment.id\"),\n\t\t\tpayload: assertStrictJsonValue(fragment.payload, \"fragment.payload\") as TJson,\n\t\t\ttNs: parseDecimalBigInt(fragment.tNs, \"fragment.tNs\"),\n\t\t\t...(fragment.validFrom === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validFrom: parseDecimalBigInt(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t\t...(fragment.validTo === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validTo: parseDecimalBigInt(fragment.validTo, \"fragment.validTo\") }),\n\t\t\tconfidence: assertConfidence(fragment.confidence, \"fragment.confidence\"),\n\t\t\ttags: assertStringArray(fragment.tags, \"fragment.tags\"),\n\t\t\tsources: assertStringArray(fragment.sources, \"fragment.sources\"),\n\t\t\t...(fragment.embedding === undefined\n\t\t\t\t? {}\n\t\t\t\t: { embedding: assertFiniteNumberArray(fragment.embedding, \"fragment.embedding\") }),\n\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparentFragmentId: assertNonEmptyString(fragment.parentFragmentId, \"parentFragmentId\"),\n\t\t\t\t\t}),\n\t\t\t...(fragment.provenance === undefined\n\t\t\t\t? {}\n\t\t\t\t: { provenance: assertString(fragment.provenance, \"provenance\") }),\n\t\t},\n\t};\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: decoded record is invalid: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn result.record;\n}\n\nfunction projectRetention<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly activeRecords: AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: AgenticMemoryConsolidationRequest[];\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst view = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tlet validCommands = 0;\n\tlet invalidCommands = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenCommands = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateRetentionCommand(raw, i);\n\t\t\tif (result.errors.length > 0 || result.command === undefined) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst command = result.command;\n\t\t\tif (seenCommands.has(command.id)) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-command-id\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: duplicate command id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate command id '${command.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst missing = retentionMissingRecords(command, byId);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command references missing records\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\trecordId: \"recordId\" in command ? command.recordId : undefined,\n\t\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(missing.map((id) => `record '${id}' is not projected`)),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenCommands.add(command.id);\n\t\t\tvalidCommands += 1;\n\t\t\tapplyRetentionCommand(command, byId, view, requests);\n\t\t} catch (error) {\n\t\t\tinvalidCommands += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryRetentionBundle: command access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: [\"command access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\tconst projected = records.map((record) => view.get(record.id) ?? record);\n\treturn {\n\t\tactiveRecords: projected.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\tarchivedRecords: projected.filter((record) => record.persistenceLevel === \"archived\"),\n\t\tconsolidationRequests: requests,\n\t\terrors,\n\t\tvalidCommands,\n\t\tinvalidCommands,\n\t};\n}\n\nfunction validateRetentionCommand(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly command?: AgenticMemoryRetentionCommand;\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst id = typeof value.id === \"string\" && value.id.length > 0 ? value.id : undefined;\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (id === undefined) errors.push(\"command.id must be a non-empty string\");\n\tif (\n\t\tkind !== \"archive\" &&\n\t\tkind !== \"restore\" &&\n\t\tkind !== \"setPersistenceLevel\" &&\n\t\tkind !== \"requestConsolidation\"\n\t) {\n\t\terrors.push(\"command.kind is invalid\");\n\t}\n\tif (value.reason !== undefined && typeof value.reason !== \"string\") {\n\t\terrors.push(\"command.reason must be a string when present\");\n\t}\n\tif (kind === \"archive\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t} else if (kind === \"restore\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (\n\t\t\tvalue.persistenceLevel !== undefined &&\n\t\t\t(!isAgenticMemoryPersistenceLevel(value.persistenceLevel) ||\n\t\t\t\tvalue.persistenceLevel === \"archived\")\n\t\t) {\n\t\t\terrors.push(\"restore.persistenceLevel must be a non-archived persistence level when present\");\n\t\t}\n\t} else if (kind === \"setPersistenceLevel\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\t\terrors.push(\"setPersistenceLevel.persistenceLevel is invalid\");\n\t\t}\n\t} else if (kind === \"requestConsolidation\") {\n\t\tif (!isDenseArrayOf(value.recordIds, isNonEmptyString) || value.recordIds.length === 0) {\n\t\t\terrors.push(\"requestConsolidation.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (\n\t\t\tvalue.requestId !== undefined &&\n\t\t\t(typeof value.requestId !== \"string\" || value.requestId.length === 0)\n\t\t) {\n\t\t\terrors.push(\"requestConsolidation.requestId must be non-empty when present\");\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command is invalid\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommandId: id,\n\t\t\t\t\tcommand: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst base = { id, reason: value.reason as string | undefined };\n\tif (kind === \"archive\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"restore\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(value.persistenceLevel === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tpersistenceLevel: value.persistenceLevel as Exclude<\n\t\t\t\t\t\t\t\tAgenticMemoryPersistenceLevel,\n\t\t\t\t\t\t\t\t\"archived\"\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t}),\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"setPersistenceLevel\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: Object.freeze({\n\t\t\t...base,\n\t\t\tkind: \"requestConsolidation\",\n\t\t\trecordIds: Object.freeze([...(value.recordIds as readonly string[])]),\n\t\t\t...(value.requestId === undefined ? {} : { requestId: value.requestId as string }),\n\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction retentionMissingRecords(\n\tcommand: AgenticMemoryRetentionCommand,\n\trecords: ReadonlyMap<FactId, AgenticMemoryRecord>,\n): readonly FactId[] {\n\tif (\"recordId\" in command) return records.has(command.recordId) ? [] : [command.recordId];\n\treturn command.recordIds.filter((recordId) => !records.has(recordId));\n}\n\nfunction applyRetentionCommand<T>(\n\tcommand: AgenticMemoryRetentionCommand,\n\tsource: ReadonlyMap<FactId, AgenticMemoryRecord<T>>,\n\tview: Map<FactId, AgenticMemoryRecord<T>>,\n\trequests: AgenticMemoryConsolidationRequest[],\n): void {\n\tif (command.kind === \"requestConsolidation\") {\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: command.requestId ?? command.id,\n\t\t\t\tcommandId: command.id,\n\t\t\t\trecordIds: Object.freeze([...command.recordIds]),\n\t\t\t\t...(command.reason === undefined ? {} : { reason: command.reason }),\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tconst record = view.get(command.recordId) ?? source.get(command.recordId);\n\tif (record === undefined) return;\n\tconst persistenceLevel =\n\t\tcommand.kind === \"archive\"\n\t\t\t? \"archived\"\n\t\t\t: command.kind === \"restore\"\n\t\t\t\t? (command.persistenceLevel ?? nonArchivedLevel(source.get(command.recordId) ?? record))\n\t\t\t\t: command.persistenceLevel;\n\tview.set(command.recordId, withPersistenceLevel(record, persistenceLevel));\n}\n\nfunction nonArchivedLevel(\n\trecord: AgenticMemoryRecord,\n): Exclude<AgenticMemoryPersistenceLevel, \"archived\"> {\n\treturn record.persistenceLevel === \"archived\" ? \"session\" : record.persistenceLevel;\n}\n\nfunction withPersistenceLevel<T>(\n\trecord: AgenticMemoryRecord<T>,\n\tpersistenceLevel: AgenticMemoryPersistenceLevel,\n): AgenticMemoryRecord<T> {\n\treturn Object.freeze({\n\t\t...record,\n\t\tpersistenceLevel,\n\t});\n}\n\nfunction retentionErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryRetentionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction validateConsolidationRequests<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly requests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly errors: readonly Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seen = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"request array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: request access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"request access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!isPlainRecord(raw)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request must be an object\",\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = isNonEmptyString(raw.id) ? raw.id : undefined;\n\t\tconst commandId = isNonEmptyString(raw.commandId) ? raw.commandId : undefined;\n\t\tconst recordIds = isDenseArrayOf(raw.recordIds, isNonEmptyString)\n\t\t\t? Object.freeze([...raw.recordIds])\n\t\t\t: undefined;\n\t\tconst validationErrors: string[] = [];\n\t\tif (id === undefined) validationErrors.push(\"request.id must be a non-empty string\");\n\t\tif (commandId === undefined) {\n\t\t\tvalidationErrors.push(\"request.commandId must be a non-empty string\");\n\t\t}\n\t\tif (recordIds === undefined || recordIds.length === 0) {\n\t\t\tvalidationErrors.push(\"request.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (raw.reason !== undefined && typeof raw.reason !== \"string\") {\n\t\t\tvalidationErrors.push(\"request.reason must be a string when present\");\n\t\t}\n\t\tif (id !== undefined && seen.has(id)) {\n\t\t\tvalidationErrors.push(`duplicate request id '${id}'`);\n\t\t}\n\t\tconst missing = (recordIds ?? []).filter((recordId) => !byId.has(recordId));\n\t\tif (missing.length > 0) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request references missing records\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\t\tmissing.map((recordId) => `record '${recordId}' is not projected`),\n\t\t\t\t),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tvalidationErrors.length > 0 ||\n\t\t\tid === undefined ||\n\t\t\tcommandId === undefined ||\n\t\t\trecordIds === undefined\n\t\t) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request is invalid\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(validationErrors),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(id);\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\t...(raw.reason === undefined ? {} : { reason: raw.reason as string }),\n\t\t\t}),\n\t\t);\n\t}\n\treturn { requests: Object.freeze(requests), errors };\n}\n\nfunction projectConsolidationOutcomes<T>(\n\tvalue: unknown,\n\trequests: readonly AgenticMemoryConsolidationRequest[],\n\tevaluation: number,\n): {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly errors: readonly Omit<AgenticMemoryConsolidationError, \"cursor\">[];\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n} {\n\tconst byRequest = new Map(requests.map((request) => [request.id, request]));\n\tconst results: AgenticMemoryConsolidationResult[] = [];\n\tconst proposedRecordDrafts: AgenticMemoryConsolidationRecordDraft<T>[] = [];\n\tconst commands: AgenticMemoryConsolidationCommand[] = [];\n\tconst errors: Omit<AgenticMemoryConsolidationError, \"cursor\">[] = [];\n\tlet validOutcomes = 0;\n\tlet invalidOutcomes = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input must be an array\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input length could not be read\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenOutcomes = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\tlet outcome: {\n\t\t\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\t\t\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n\t\t};\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"outcome array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t\toutcome = validateConsolidationOutcome<T>(raw, i);\n\t\t} catch (error) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: outcome access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"outcome access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.error !== undefined || outcome.outcome === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\tif (outcome.error !== undefined) errors.push(outcome.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst validOutcome = outcome.outcome;\n\t\tif (seenOutcomes.has(validOutcome.id)) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-outcome-id\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: duplicate outcome id\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate outcome id '${validOutcome.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst request = byRequest.get(validOutcome.requestId);\n\t\tif (request === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-request-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome references missing request\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`request '${validOutcome.requestId}' is not projected`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenOutcomes.add(validOutcome.id);\n\t\tvalidOutcomes += 1;\n\t\tif (validOutcome.kind === \"failed\") {\n\t\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: resultId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\t\tproposedRecordIds: Object.freeze([]),\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcommands.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: `${resultId}:markFailed`,\n\t\t\t\t\tkind: \"markFailed\",\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst draftIds = validOutcome.records.map(\n\t\t\t(record) => `${validOutcome.requestId}:${validOutcome.id}:${record.id}`,\n\t\t);\n\t\tfor (let recordIndex = 0; recordIndex < validOutcome.records.length; recordIndex += 1) {\n\t\t\tproposedRecordDrafts.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draftIds[recordIndex] as FactId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\trecord: validOutcome.records[recordIndex] as AgenticMemoryRecord<T>,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\tresults.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: resultId,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tstate: \"proposed\",\n\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\tproposedRecordIds: Object.freeze(validOutcome.records.map((record) => record.id)),\n\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t}),\n\t\t);\n\t\tcommands.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: `${resultId}:proposeRecords`,\n\t\t\t\tkind: \"proposeRecords\",\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tdraftIds: Object.freeze(draftIds),\n\t\t\t}),\n\t\t);\n\t}\n\tvoid evaluation;\n\treturn {\n\t\tresults: Object.freeze(results),\n\t\tproposedRecordDrafts: Object.freeze(proposedRecordDrafts),\n\t\tcommands: Object.freeze(commands),\n\t\terrors,\n\t\tvalidOutcomes,\n\t\tinvalidOutcomes,\n\t};\n}\n\nfunction validateConsolidationOutcome<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome must be an object\",\n\t\t\t\tindex,\n\t\t\t\toutcome: value,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst id = isNonEmptyString(value.id) ? value.id : undefined;\n\tconst requestId = isNonEmptyString(value.requestId) ? value.requestId : undefined;\n\tif (id === undefined) errors.push(\"outcome.id must be a non-empty string\");\n\tif (requestId === undefined) errors.push(\"outcome.requestId must be a non-empty string\");\n\tif (value.kind !== \"proposedRecords\" && value.kind !== \"failed\") {\n\t\terrors.push(\"outcome.kind must be proposedRecords or failed\");\n\t}\n\tif (value.provenance !== undefined && typeof value.provenance !== \"string\") {\n\t\terrors.push(\"outcome.provenance must be a string when present\");\n\t}\n\tif (value.kind === \"failed\" && !isNonEmptyString(value.message)) {\n\t\terrors.push(\"failed outcome.message must be a non-empty string\");\n\t}\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tif (value.kind === \"proposedRecords\") {\n\t\tif (!Array.isArray(value.records)) {\n\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t} else {\n\t\t\tconst recordsLength = safeArrayLength(value.records);\n\t\t\tconst seenRecordIds = new Set<FactId>();\n\t\t\tif (recordsLength === undefined || recordsLength === 0) {\n\t\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t\t}\n\t\t\tfor (let i = 0; i < (recordsLength ?? 0); i += 1) {\n\t\t\t\tlet result: {\n\t\t\t\t\treadonly record?: AgenticMemoryRecord<T>;\n\t\t\t\t\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (!Object.hasOwn(value.records, i)) {\n\t\t\t\t\t\tthrow new TypeError(\"proposedRecords.records must be dense\");\n\t\t\t\t\t}\n\t\t\t\t\tresult = validateAndSnapshotRecord<T>(value.records[i], i);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(`records[${i}]: record access failed: ${errorMessage(error)}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (result.record === undefined || result.errors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...result.errors\n\t\t\t\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t\t\t\t.map((error) => `records[${i}]: ${error}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (seenRecordIds.has(result.record.id)) {\n\t\t\t\t\terrors.push(`records[${i}]: duplicate proposed record id '${result.record.id}'`);\n\t\t\t\t} else {\n\t\t\t\t\tseenRecordIds.add(result.record.id);\n\t\t\t\t\trecords.push(result.record);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined || requestId === undefined) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: value.kind === \"proposedRecords\" ? \"invalid-proposed-record\" : \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome is invalid\",\n\t\t\t\tindex,\n\t\t\t\toutcomeId: id,\n\t\t\t\trequestId,\n\t\t\t\toutcome: value,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\tif (value.kind === \"failed\") {\n\t\treturn {\n\t\t\toutcome: Object.freeze({\n\t\t\t\tid,\n\t\t\t\trequestId,\n\t\t\t\tkind: \"failed\",\n\t\t\t\tmessage: value.message as string,\n\t\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t\t}),\n\t\t};\n\t}\n\treturn {\n\t\toutcome: Object.freeze({\n\t\t\tid,\n\t\t\trequestId,\n\t\t\tkind: \"proposedRecords\",\n\t\t\trecords: Object.freeze(records),\n\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t}),\n\t};\n}\n\nfunction consolidationErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction consolidationErrorFromRetentionError(\n\terror: Omit<AgenticMemoryRetentionError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction packContext(\n\tcontextValue: unknown,\n\ttextsValue: unknown,\n\tpolicyValue: unknown,\n\tevaluation: number,\n): AgenticMemoryContextPackingSnapshot {\n\tconst errors: Omit<AgenticMemoryContextPackingError, \"cursor\">[] = [];\n\tconst context = validatePackingContext(contextValue, errors);\n\tconst texts = validateContextTexts(textsValue, errors);\n\tconst policy = validatePackingPolicy(policyValue, errors);\n\tconst packedEntries: AgenticMemoryPackedContextEntry[] = [];\n\tlet omittedEntries = 0;\n\tlet totalChars = 0;\n\tlet totalCost = 0;\n\tif (context !== undefined && policy !== undefined) {\n\t\tfor (const entry of context.entries) {\n\t\t\tconst textFact = texts.get(entry.fragmentId);\n\t\t\tif (textFact === undefined) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: missing text projection for context entry\",\n\t\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\t\tvalidationErrors: [`missing text for fragment '${entry.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst cost = textFact.cost ?? textFact.text.length;\n\t\t\tconst nextEntries = packedEntries.length + 1;\n\t\t\tconst separatorChars = packedEntries.length === 0 ? 0 : 2;\n\t\t\tconst nextChars = totalChars + separatorChars + textFact.text.length;\n\t\t\tconst nextCost = totalCost + cost;\n\t\t\tconst exceeds =\n\t\t\t\t(policy.maxEntries !== undefined && nextEntries > policy.maxEntries) ||\n\t\t\t\t(policy.maxChars !== undefined && nextChars > policy.maxChars) ||\n\t\t\t\t(policy.maxCost !== undefined && nextCost > policy.maxCost);\n\t\t\tif (exceeds) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst packedEntry: AgenticMemoryPackedContextEntry = Object.freeze({\n\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\ttext: textFact.text,\n\t\t\t\tcost,\n\t\t\t\tchars: textFact.text.length,\n\t\t\t\t...(entry.record === undefined ? {} : { record: entry.record }),\n\t\t\t\t...(policy.includeMetadata && textFact.metadata !== undefined\n\t\t\t\t\t? { metadata: textFact.metadata }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tpackedEntries.push(packedEntry);\n\t\t\ttotalChars = nextChars;\n\t\t\ttotalCost = nextCost;\n\t\t}\n\t}\n\tconst cursor: AgenticMemoryContextPackingCursor = Object.freeze({\n\t\tevaluation,\n\t\tinputEntries: context?.entries.length ?? 0,\n\t\tpackedEntries: packedEntries.length,\n\t\tomittedEntries,\n\t\ttotalChars,\n\t\ttotalCost,\n\t});\n\tconst errorFacts = Object.freeze(\n\t\terrors.map((error) =>\n\t\t\tfreezeError({\n\t\t\t\t...error,\n\t\t\t\tcursor,\n\t\t\t}),\n\t\t),\n\t);\n\tconst packedContext: AgenticMemoryPackedContext = Object.freeze({\n\t\tentries: Object.freeze(packedEntries),\n\t\ttext: packedEntries.map((entry) => entry.text).join(\"\\n\\n\"),\n\t\ttotalChars,\n\t\ttotalCost,\n\t\ttruncated: omittedEntries > 0,\n\t});\n\tconst status: AgenticMemoryContextPackingStatus = Object.freeze({\n\t\tstate: agenticStatusState(errorFacts.length, packedEntries.length),\n\t\tcursor,\n\t});\n\treturn Object.freeze({\n\t\tpackedContext,\n\t\tstatus,\n\t\terrors: errorFacts,\n\t\tcursor,\n\t});\n}\n\nfunction validatePackingContext(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): ValidatedPackingContext | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tlet entriesValue: unknown;\n\ttry {\n\t\tentriesValue = value.entries;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: context entries access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context entries access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(entriesValue)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries must be an array\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst length = safeArrayLength(entriesValue);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entries length could not be read\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries length could not be read\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst entries: AgenticMemoryContextEntry[] = [];\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = entriesValue[i];\n\t\t\tif (!isPlainRecord(raw) || !isNonEmptyString(raw.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"context entry fragmentId must be a non-empty string\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = validateRecordMetadata(raw.record);\n\t\t\tif (!record.ok) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry record metadata is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(record.errors),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tentries.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\t...(record.metadata === undefined ? {} : { record: record.metadata }),\n\t\t\t\t}) as AgenticMemoryContextEntry,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-context\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: context entry access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalue: raw,\n\t\t\t\tvalidationErrors: [\"context entry access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn Object.freeze({\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction validateContextTexts(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): Map<FactId, AgenticMemoryContextText> {\n\tconst out = new Map<FactId, AgenticMemoryContextText>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input must be an array\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input length could not be read\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\ttry {\n\t\t\tconst raw = value[i];\n\t\t\tconst result = validateContextText(raw, i);\n\t\t\tif (result.error !== undefined) {\n\t\t\t\terrors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.text === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"text validation returned no fact\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (out.has(result.text.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-text-fragment-id\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: duplicate text fragment id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: result.text.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate text fragment id '${result.text.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.set(result.text.fragmentId, result.text);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: text access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: [\"text access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction validateContextText(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly text?: AgenticMemoryContextText;\n\treadonly error?: Omit<AgenticMemoryContextPackingError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact must be an object\",\n\t\t\t\tindex,\n\t\t\t\tvalue,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(value.fragmentId)) errors.push(\"fragmentId must be a non-empty string\");\n\tif (typeof value.text !== \"string\") errors.push(\"text must be a string\");\n\tif (\n\t\tvalue.cost !== undefined &&\n\t\t(typeof value.cost !== \"number\" || !Number.isFinite(value.cost) || value.cost < 0)\n\t) {\n\t\terrors.push(\"cost must be a finite number >= 0\");\n\t}\n\tif (value.metadata !== undefined) {\n\t\ttry {\n\t\t\tif (!isPlainRecord(value.metadata)) {\n\t\t\t\tthrow new TypeError(\"metadata must be a plain object when present\");\n\t\t\t}\n\t\t\tassertStrictJsonValue(value.metadata, \"metadata\");\n\t\t} catch (error) {\n\t\t\terrors.push(errorMessage(error));\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\tindex,\n\t\t\t\tfragmentId: typeof value.fragmentId === \"string\" ? value.fragmentId : undefined,\n\t\t\t\tvalue,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\ttext: Object.freeze({\n\t\t\tfragmentId: value.fragmentId as string,\n\t\t\ttext: value.text as string,\n\t\t\t...(value.cost === undefined ? {} : { cost: value.cost as number }),\n\t\t\t...(value.metadata === undefined\n\t\t\t\t? {}\n\t\t\t\t: { metadata: Object.freeze({ ...(value.metadata as Record<string, StrictJsonValue>) }) }),\n\t\t}),\n\t};\n}\n\nfunction validatePackingPolicy(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): AgenticMemoryContextPackingPolicy | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy must be an object\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst validation: string[] = [];\n\tlet maxEntries: unknown;\n\tlet maxChars: unknown;\n\tlet maxCost: unknown;\n\tlet includeMetadata: unknown;\n\ttry {\n\t\tmaxEntries = value.maxEntries;\n\t\tmaxChars = value.maxChars;\n\t\tmaxCost = value.maxCost;\n\t\tincludeMetadata = value.includeMetadata;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: policy access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"policy access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (\n\t\tmaxEntries !== undefined &&\n\t\t(typeof maxEntries !== \"number\" || !Number.isSafeInteger(maxEntries) || maxEntries < 0)\n\t) {\n\t\tvalidation.push(\"maxEntries must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxChars !== undefined &&\n\t\t(typeof maxChars !== \"number\" || !Number.isSafeInteger(maxChars) || maxChars < 0)\n\t) {\n\t\tvalidation.push(\"maxChars must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxCost !== undefined &&\n\t\t(typeof maxCost !== \"number\" || !Number.isFinite(maxCost) || maxCost < 0)\n\t) {\n\t\tvalidation.push(\"maxCost must be a finite number >= 0\");\n\t}\n\tif (includeMetadata !== undefined && typeof includeMetadata !== \"boolean\") {\n\t\tvalidation.push(\"includeMetadata must be a boolean when present\");\n\t}\n\tif (validation.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy is invalid\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: Object.freeze(validation),\n\t\t});\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\t...(maxEntries === undefined ? {} : { maxEntries: maxEntries as number }),\n\t\t...(maxChars === undefined ? {} : { maxChars: maxChars as number }),\n\t\t...(maxCost === undefined ? {} : { maxCost: maxCost as number }),\n\t\t...(includeMetadata === undefined ? {} : { includeMetadata: includeMetadata as boolean }),\n\t});\n}\n\nfunction validateAndProjectRecords<T>(value: unknown): {\n\treadonly records: AgenticMemoryRecord<T>[];\n\treadonly fragments: MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Record<FactId, AgenticMemoryRecordMetadata>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\treadonly invalidRecordIndexes: Set<number>;\n} {\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tconst fragments: MemoryFragment<T>[] = [];\n\tconst metadataByFragmentId = Object.create(null) as Record<FactId, AgenticMemoryRecordMetadata>;\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tconst invalidRecordIndexes = new Set<number>();\n\tconst seenRecordIds = new Set<FactId>();\n\tconst seenFragmentIds = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input must be an array\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input length could not be read\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-record\",\n\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = validateAndSnapshotRecord<T>(raw, i);\n\t\tif (result.errors.length > 0) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push(...result.errors);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.record === undefined) continue;\n\t\tif (seenRecordIds.has(result.record.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-record-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate record id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate record id '${result.record.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (seenFragmentIds.has(result.record.fragment.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate fragment id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\tfragmentId: result.record.fragment.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate fragment id '${result.record.fragment.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenRecordIds.add(result.record.id);\n\t\tseenFragmentIds.add(result.record.fragment.id);\n\t\trecords.push(result.record);\n\t\tfragments.push(result.record.fragment);\n\t\tmetadataByFragmentId[result.record.fragment.id] = recordMetadata(result.record);\n\t}\n\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n}\n\nfunction validateAndSnapshotRecord<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\ttry {\n\t\treturn validateAndSnapshotRecordInner<T>(value, index);\n\t} catch (error) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateAndSnapshotRecordInner<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: \"agenticMemoryBundle: record must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst record = value as Partial<AgenticMemoryRecord<T>> & Record<string, unknown>;\n\tconst recordId = typeof record.id === \"string\" ? record.id : undefined;\n\tif (recordId === undefined || recordId.length === 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record.id must be a non-empty string\",\n\t\t\tindex,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"record.id must be a non-empty string\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryKind(record.kind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.kind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"kind must be one of working, episodic, semantic, procedural, profile\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(record.persistenceLevel)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-persistence-level\",\n\t\t\tmessage: \"agenticMemoryBundle: record.persistenceLevel is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\n\t\t\t\t\"persistenceLevel must be one of turn, session, project, longTerm, permanent, archived\",\n\t\t\t],\n\t\t});\n\t}\n\tif (!isAgenticMemoryArtifactKind(record.artifactKind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-artifact-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.artifactKind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"artifactKind must be one of raw, insight, profile, procedure\"],\n\t\t});\n\t}\n\tconst scopeValidation = validateScope(record.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-scope\",\n\t\t\tmessage: \"agenticMemoryBundle: record.scope is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(scopeValidation.errors),\n\t\t});\n\t}\n\tconst fragmentValidation = validateMemoryFragment(record.fragment);\n\tif (!fragmentValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-fragment\",\n\t\t\tmessage: \"agenticMemoryBundle: record.fragment is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\tfragmentId:\n\t\t\t\ttypeof record.fragment === \"object\" &&\n\t\t\t\trecord.fragment !== null &&\n\t\t\t\ttypeof (record.fragment as Partial<MemoryFragment>).id === \"string\"\n\t\t\t\t\t? (record.fragment as Partial<MemoryFragment>).id\n\t\t\t\t\t: undefined,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze([...fragmentValidation.errors]),\n\t\t});\n\t}\n\tconst forbiddenFields = [\n\t\t\"storageTier\",\n\t\t\"storageKey\",\n\t\t\"adapter\",\n\t\t\"collection\",\n\t\t\"collections\",\n\t\t\"ttl\",\n\t\t\"ttlMs\",\n\t\t\"ttlNs\",\n\t\t\"expiresAt\",\n\t\t\"timer\",\n\t\t\"scheduler\",\n\t\t\"schedule\",\n\t\t\"retentionTimer\",\n\t\t\"consolidationSchedule\",\n\t\t\"reflectionSchedule\",\n\t\t\"llm\",\n\t\t\"llmHandle\",\n\t\t\"tool\",\n\t\t\"toolHandle\",\n\t\t\"runner\",\n\t\t\"runnerHandle\",\n\t\t\"restore\",\n\t\t\"hydrate\",\n\t\t\"hydration\",\n\t\t\"graphMutation\",\n\t\t\"protocol\",\n\t] as const;\n\tconst presentForbidden = forbiddenFields.filter((field) => Object.hasOwn(record, field));\n\tif (presentForbidden.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record contains forbidden runtime/persistence fields\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\tpresentForbidden.map((field) => `${field} is not part of AgenticMemoryRecord`),\n\t\t\t),\n\t\t});\n\t}\n\tif (errors.length > 0) return { errors };\n\tconst scope = scopeValidation.scope;\n\tconst fragment = snapshotFragment(record.fragment as MemoryFragment<T>);\n\treturn {\n\t\trecord: Object.freeze({\n\t\t\tid: recordId as FactId,\n\t\t\tkind: record.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: record.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: record.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tfragment,\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordMetadata(record: AgenticMemoryRecord): AgenticMemoryRecordMetadata {\n\treturn Object.freeze({\n\t\trecordId: record.id,\n\t\tkind: record.kind,\n\t\tpersistenceLevel: record.persistenceLevel,\n\t\tartifactKind: record.artifactKind,\n\t\t...(record.scope === undefined ? {} : { scope: record.scope }),\n\t});\n}\n\nfunction validateRecordMetadata(value: unknown): {\n\treadonly ok: boolean;\n\treadonly metadata?: AgenticMemoryRecordMetadata;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (!isPlainRecord(value)) {\n\t\treturn { ok: false, errors: [\"record metadata must be an object when present\"] };\n\t}\n\tconst errors: string[] = [];\n\tfor (const key of Object.keys(value)) {\n\t\tif (\n\t\t\tkey !== \"recordId\" &&\n\t\t\tkey !== \"kind\" &&\n\t\t\tkey !== \"persistenceLevel\" &&\n\t\t\tkey !== \"artifactKind\" &&\n\t\t\tkey !== \"scope\"\n\t\t) {\n\t\t\terrors.push(`record.${key} is not part of AgenticMemoryRecordMetadata`);\n\t\t}\n\t}\n\tif (!isNonEmptyString(value.recordId)) {\n\t\terrors.push(\"record.recordId must be a non-empty string\");\n\t}\n\tif (!isAgenticMemoryKind(value.kind)) {\n\t\terrors.push(\"record.kind is invalid\");\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\terrors.push(\"record.persistenceLevel is invalid\");\n\t}\n\tif (!isAgenticMemoryArtifactKind(value.artifactKind)) {\n\t\terrors.push(\"record.artifactKind is invalid\");\n\t}\n\tconst scopeValidation = validateScope(value.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push(...scopeValidation.errors.map((error) => `record.${error}`));\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tmetadata: Object.freeze({\n\t\t\trecordId: value.recordId as FactId,\n\t\t\tkind: value.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: value.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scopeValidation.scope === undefined ? {} : { scope: scopeValidation.scope }),\n\t\t}),\n\t};\n}\n\nfunction contextState(\n\tprojection: AgenticMemoryStatusState,\n\tretrieval: MemoryRetrievalStatus[\"state\"],\n): AgenticMemoryContextState {\n\tif (projection === \"error\" || retrieval === \"error\") return \"error\";\n\tif (projection === \"partial\" || retrieval === \"partial\") return \"partial\";\n\treturn retrieval;\n}\n\nfunction agenticStatusState(errorCount: number, validRecords: number): AgenticMemoryStatusState {\n\tif (errorCount > 0 && validRecords === 0) return \"error\";\n\tif (errorCount > 0) return \"partial\";\n\treturn validRecords > 0 ? \"ready\" : \"empty\";\n}\n\nfunction isAgenticMemoryKind(value: unknown): value is AgenticMemoryKind {\n\treturn (\n\t\tvalue === \"working\" ||\n\t\tvalue === \"episodic\" ||\n\t\tvalue === \"semantic\" ||\n\t\tvalue === \"procedural\" ||\n\t\tvalue === \"profile\"\n\t);\n}\n\nfunction isAgenticMemoryPersistenceLevel(value: unknown): value is AgenticMemoryPersistenceLevel {\n\treturn (\n\t\tvalue === \"turn\" ||\n\t\tvalue === \"session\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"longTerm\" ||\n\t\tvalue === \"permanent\" ||\n\t\tvalue === \"archived\"\n\t);\n}\n\nfunction isAgenticMemoryArtifactKind(value: unknown): value is AgenticMemoryArtifactKind {\n\treturn value === \"raw\" || value === \"insight\" || value === \"profile\" || value === \"procedure\";\n}\n\nfunction validateScope(value: unknown): {\n\treadonly ok: boolean;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn { ok: false, errors: [\"scope must be an object when present\"] };\n\t}\n\tconst scope = value as Record<string, unknown>;\n\tconst errors: string[] = [];\n\tconst allowed = new Set([\"sessionId\", \"projectId\", \"userId\", \"tenantId\"]);\n\tfor (const key of Object.keys(scope)) {\n\t\tif (!allowed.has(key)) errors.push(`scope.${key} is not part of AgenticMemoryScope`);\n\t}\n\tfor (const key of allowed) {\n\t\tif (scope[key] !== undefined && (typeof scope[key] !== \"string\" || scope[key].length === 0)) {\n\t\t\terrors.push(`scope.${key} must be a non-empty string when present`);\n\t\t}\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tscope: Object.freeze({\n\t\t\t...(scope.sessionId === undefined ? {} : { sessionId: scope.sessionId as string }),\n\t\t\t...(scope.projectId === undefined ? {} : { projectId: scope.projectId as string }),\n\t\t\t...(scope.userId === undefined ? {} : { userId: scope.userId as string }),\n\t\t\t...(scope.tenantId === undefined ? {} : { tenantId: scope.tenantId as string }),\n\t\t}),\n\t};\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nfunction assertExactKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected fields ${actual.join(\",\")}`);\n\t}\n}\n\nfunction assertAgenticMemoryRecordCodecShape(value: unknown): void {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertNoSymbolKeys(value, \"agenticMemoryRecordFrame.record\");\n\tassertExactKeys(\n\t\tvalue,\n\t\tvalue.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst fragment = value.fragment;\n\tif (!isPlainRecord(fragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertNoSymbolKeys(fragment, \"agenticMemoryRecordFrame.record.fragment\");\n\tassertExactKeys(\n\t\tfragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(fragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(fragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(fragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(fragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(fragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tassertStrictJsonValue(fragment.tags, \"record.fragment.tags\");\n\tassertStrictJsonValue(fragment.sources, \"record.fragment.sources\");\n\tif (fragment.embedding !== undefined) {\n\t\tassertStrictJsonValue(fragment.embedding, \"record.fragment.embedding\");\n\t}\n\tif (value.scope !== undefined) assertScopeFrame(value.scope);\n}\n\nfunction assertNoSymbolKeys(value: object, label: string): void {\n\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\tthrow new TypeError(`${label}: unexpected symbol fields`);\n\t}\n}\n\nfunction decimalBigIntString(value: bigint, label: string): string {\n\tconst out = value.toString(10);\n\tif (!/^-?(0|[1-9]\\d*)$/.test(out)) {\n\t\tthrow new TypeError(`${label} must encode as a canonical decimal bigint string`);\n\t}\n\treturn out;\n}\n\nfunction parseDecimalBigInt(value: unknown, label: string): bigint {\n\tif (typeof value !== \"string\" || !/^(0|-?[1-9]\\d*)$/.test(value)) {\n\t\tthrow new TypeError(`${label} must be a canonical decimal bigint string`);\n\t}\n\treturn BigInt(value);\n}\n\nfunction assertStrictJsonValue(value: unknown, label: string): StrictJsonValue {\n\ttry {\n\t\tstrictJsonCodec.encode(value);\n\t\treturn value as StrictJsonValue;\n\t} catch (error) {\n\t\tthrow new TypeError(`${label} must be strict JSON: ${errorMessage(error)}`);\n\t}\n}\n\nfunction assertScopeFrame(value: unknown): AgenticMemoryScope {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: scope must be an object when present\");\n\t}\n\tassertStrictJsonValue(value, \"record.scope\");\n\tconst validation = validateScope(value);\n\tif (!validation.ok || validation.scope === undefined) {\n\t\tthrow new TypeError(`agenticMemoryRecordFrame: invalid scope: ${validation.errors.join(\"; \")}`);\n\t}\n\tassertExactKeys(\n\t\tvalue as Record<string, unknown>,\n\t\t[\n\t\t\t...((value as Record<string, unknown>).sessionId === undefined ? [] : [\"sessionId\"]),\n\t\t\t...((value as Record<string, unknown>).projectId === undefined ? [] : [\"projectId\"]),\n\t\t\t...((value as Record<string, unknown>).userId === undefined ? [] : [\"userId\"]),\n\t\t\t...((value as Record<string, unknown>).tenantId === undefined ? [] : [\"tenantId\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.scope\",\n\t);\n\treturn validation.scope;\n}\n\nfunction assertKindValue(value: unknown): AgenticMemoryKind {\n\tif (!isAgenticMemoryKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid memory kind\");\n\t}\n\treturn value;\n}\n\nfunction assertPersistenceLevelValue(value: unknown): AgenticMemoryPersistenceLevel {\n\tif (!isAgenticMemoryPersistenceLevel(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid persistence level\");\n\t}\n\treturn value;\n}\n\nfunction assertArtifactKindValue(value: unknown): AgenticMemoryArtifactKind {\n\tif (!isAgenticMemoryArtifactKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid artifact kind\");\n\t}\n\treturn value;\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): string {\n\tif (!isNonEmptyString(value)) throw new TypeError(`${label} must be a non-empty string`);\n\treturn value;\n}\n\nfunction assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new TypeError(`${label} must be a string`);\n\treturn value;\n}\n\nfunction assertConfidence(value: unknown, label: string): number {\n\tif (!Number.isFinite(value) || (value as number) < 0 || (value as number) > 1) {\n\t\tthrow new TypeError(`${label} must be a finite number in [0, 1]`);\n\t}\n\treturn value as number;\n}\n\nfunction assertStringArray(value: unknown, label: string): readonly string[] {\n\tif (!isDenseArrayOf(value, (item): item is string => typeof item === \"string\")) {\n\t\tthrow new TypeError(`${label} must be a readonly string array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction assertFiniteNumberArray(value: unknown, label: string): readonly number[] {\n\tif (!isDenseArrayOf(value, (item): item is number => Number.isFinite(item))) {\n\t\tthrow new TypeError(`${label} must be a finite number array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction freezeError<T extends { readonly validationErrors?: readonly string[] }>(error: T): T {\n\treturn Object.freeze({\n\t\t...error,\n\t\t...(error.validationErrors === undefined\n\t\t\t? {}\n\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t}) as T;\n}\n\nfunction safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Product-owned capability admission facts (D357).\n *\n * This helper consumes generic BoundaryCapabilityRef data and emits ordinary DATA\n * facts for product admission state. It is not AutoPanel security, not a provider\n * registry, and not protocol ERROR/tier/message semantics.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { BoundaryCapabilityRef, BoundaryRole } from \"../inspection/boundary.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { AgentRuntimeAuditRecord, SourceRef } from \"../orchestration/agent-runtime.js\";\n\nexport type CapabilityAdmissionOutcome = \"allow\" | \"block\" | \"defer\";\nexport type CapabilityAdmissionState = \"allowed\" | \"blocked\" | \"deferred\";\n\nexport interface CapabilityAdmissionProposal {\n\treadonly kind: \"capability-admission-proposal\";\n\treadonly proposalId: string;\n\treadonly subjectId: string;\n\treadonly capability: BoundaryCapabilityRef;\n\treadonly boundaryName?: string;\n\treadonly role?: BoundaryRole;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly proposedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionPolicy {\n\treadonly kind: \"capability-admission-policy\";\n\treadonly policyId: string;\n\treadonly capabilityIds?: readonly string[];\n\treadonly capabilityKinds?: readonly BoundaryCapabilityRef[\"kind\"][];\n\treadonly requiredOnly?: boolean;\n\treadonly allowedOutcomes?: readonly CapabilityAdmissionOutcome[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionDecision {\n\treadonly kind: \"capability-admission-decision\";\n\treadonly decisionId: string;\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly outcome: CapabilityAdmissionOutcome;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly decidedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmission {\n\treadonly kind: \"capability-admission\";\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly subjectId: string;\n\treadonly capability: BoundaryCapabilityRef;\n\treadonly state: CapabilityAdmissionState;\n\treadonly decisionId: string;\n\treadonly boundaryName?: string;\n\treadonly role?: BoundaryRole;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly admittedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionStatus {\n\treadonly kind: \"capability-admission-status\";\n\treadonly statusId: string;\n\treadonly state:\n\t\t| \"capability-admission-allowed\"\n\t\t| \"capability-admission-blocked\"\n\t\t| \"capability-admission-deferred\"\n\t\t| \"capability-admission-issue\";\n\treadonly proposalId?: string;\n\treadonly admissionId?: string;\n\treadonly subjectId?: string;\n\treadonly capabilityId?: string;\n\treadonly capabilityKind?: BoundaryCapabilityRef[\"kind\"];\n\treadonly policyId?: string;\n\treadonly issues?: readonly DataIssue[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionViews {\n\treadonly admissionsByProposal: ReadonlyMap<string, CapabilityAdmission>;\n\treadonly admissionsBySubject: ReadonlyMap<string, readonly CapabilityAdmission[]>;\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface CapabilityAdmissionBundle {\n\treadonly admissions: Node<CapabilityAdmission>;\n\treadonly status: Node<CapabilityAdmissionStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<CapabilityAdmissionViews>;\n}\n\ntype CapabilityAdmissionFact =\n\t| { readonly kind: \"admission\"; readonly admission: CapabilityAdmission }\n\t| { readonly kind: \"status\"; readonly status: CapabilityAdmissionStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ninterface CapabilityAdmissionStateInternal {\n\tproposals: Map<string, CapabilityAdmissionProposal>;\n\tpolicies: Map<string, CapabilityAdmissionPolicy>;\n\tdecisions: Map<string, CapabilityAdmissionDecision>;\n\tadmissionsById: Map<string, CapabilityAdmission>;\n\tadmissionsByProposal: Map<string, CapabilityAdmission>;\n\tterminalDecisionIds: Set<string>;\n\tissueKeys: Set<string>;\n\tissueSeq: number;\n\tstatusSeq: number;\n\tauditSeq: number;\n}\n\ninterface CapabilityAdmissionViewsState {\n\tadmissionsByProposal: Map<string, CapabilityAdmission>;\n\tadmissionsBySubject: Map<string, CapabilityAdmission[]>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\nexport function capabilityAdmissionProposal(\n\topts: Omit<CapabilityAdmissionProposal, \"kind\">,\n): CapabilityAdmissionProposal {\n\treturn { kind: \"capability-admission-proposal\", ...opts };\n}\n\nexport function capabilityAdmissionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly proposals: Node<CapabilityAdmissionProposal>;\n\t\treadonly decisions: Node<CapabilityAdmissionDecision>;\n\t\treadonly admissionPolicies?: readonly Node<CapabilityAdmissionPolicy>[];\n\t\treadonly now?: () => number;\n\t},\n): CapabilityAdmissionBundle {\n\tconst name = opts.name ?? \"capabilityAdmissions\";\n\tconst policyDeps = opts.admissionPolicies ?? [];\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<CapabilityAdmissionFact>(\n\t\t[opts.proposals, opts.decisions, ...policyDeps],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<CapabilityAdmissionStateInternal>() ?? emptyCapabilityAdmissionState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst proposal = raw as CapabilityAdmissionProposal;\n\t\t\t\tconst issue = capabilityAdmissionProposalIssue(proposal);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"proposal\", proposalKeyFallback(proposal)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (state.proposals.has(proposal.proposalId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-proposal:${proposal.proposalId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-proposal\",\n\t\t\t\t\t\t\t`CapabilityAdmissionProposal '${proposal.proposalId}' was already seen`,\n\t\t\t\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityProposalRefs(proposal) },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.proposals.set(proposal.proposalId, proposal);\n\t\t\t}\n\t\t\tforEachPolicyDepBatch(ctx, 2, policyDeps.length, (raw) => {\n\t\t\t\tconst policy = raw as CapabilityAdmissionPolicy;\n\t\t\t\tconst issue = capabilityAdmissionPolicyIssue(policy);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"policy\", policyKeyFallback(policy)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.policies.has(policy.policyId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-policy:${policy.policyId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-policy\",\n\t\t\t\t\t\t\t`CapabilityAdmissionPolicy '${policy.policyId}' was already seen`,\n\t\t\t\t\t\t\t{ refs: [ref(\"capability-admission-policy\", policy.policyId)] },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst decision = raw as CapabilityAdmissionDecision;\n\t\t\t\tconst issue = capabilityAdmissionDecisionIssue(decision);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"decision\", decisionKeyFallback(decision)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (state.decisions.has(decision.decisionId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-decision:${decision.decisionId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-decision\",\n\t\t\t\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' was already seen`,\n\t\t\t\t\t\t\t{ refs: capabilityDecisionRefs(decision) },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.decisions.set(decision.decisionId, decision);\n\t\t\t}\n\t\t\tevaluateCapabilityAdmissions(ctx, state, now());\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"capabilityAdmissionProjector\", partial: true },\n\t);\n\treturn {\n\t\tadmissions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/admissions`,\n\t\t\t\"capabilityAdmissions\",\n\t\t\t(fact) => (fact.kind === \"admission\" ? fact.admission : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"capabilityAdmissionStatus\",\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\"capabilityAdmissionIssues\",\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\"capabilityAdmissionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: capabilityAdmissionViews(graph, runtime, `${name}/views`),\n\t};\n}\n\nfunction evaluateCapabilityAdmissions(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tadmittedAtMs: number,\n): void {\n\tfor (const decision of state.decisions.values()) {\n\t\tif (state.terminalDecisionIds.has(decision.decisionId)) continue;\n\t\tevaluateCapabilityAdmission(ctx, state, decision, admittedAtMs);\n\t}\n}\n\nfunction evaluateCapabilityAdmission(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tdecision: CapabilityAdmissionDecision,\n\tadmittedAtMs: number,\n): void {\n\tconst proposal = state.proposals.get(decision.proposalId);\n\tif (proposal === undefined) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-proposal:${decision.decisionId}:${decision.proposalId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"missing-capability-admission-proposal\",\n\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' references missing proposal '${decision.proposalId}'`,\n\t\t\t\t{ subjectId: decision.proposalId, refs: capabilityDecisionRefs(decision) },\n\t\t\t),\n\t\t);\n\t\treturn;\n\t}\n\tconst policy = capabilityPolicyForDecision(state, decision);\n\tif (typeof policy === \"string\") {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`${policy}:${decision.decisionId}:${decision.policyId ?? \"missing\"}`,\n\t\t\tdataIssue(policy, capabilityPolicyIssueMessage(policy, decision), {\n\t\t\t\tsubjectId: proposal.subjectId,\n\t\t\t\trefs: capabilityDecisionRefs(decision, proposal),\n\t\t\t}),\n\t\t);\n\t\tif (policy === \"stale-capability-admission-policy-ref\")\n\t\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tif (policy !== undefined) {\n\t\tconst policyIssue = validateCapabilityAdmissionPolicy(policy, decision, proposal);\n\t\tif (policyIssue !== undefined) {\n\t\t\temitIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`${policyIssue.code}:${decision.decisionId}:${policy.policyId}`,\n\t\t\t\tdataIssue(policyIssue.code, policyIssue.message, {\n\t\t\t\t\tsubjectId: proposal.subjectId,\n\t\t\t\t\trefs: capabilityDecisionRefs(decision, proposal, policy),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}\n\tif (state.admissionsById.has(decision.admissionId)) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-id:${decision.admissionId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"duplicate-capability-admission\",\n\t\t\t\t`CapabilityAdmission '${decision.admissionId}' was already emitted`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tif (state.admissionsByProposal.has(decision.proposalId)) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-proposal:${decision.proposalId}:${decision.decisionId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"duplicate-capability-admission-proposal\",\n\t\t\t\t`CapabilityAdmissionProposal '${decision.proposalId}' already has an admission decision`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tconst admissionState = admissionStateForOutcome(decision.outcome);\n\tif (admissionState === undefined) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unsupported-outcome:${decision.decisionId}:${String(decision.outcome)}`,\n\t\t\tdataIssue(\n\t\t\t\t\"unsupported-capability-admission-outcome\",\n\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' uses unsupported outcome '${String(decision.outcome)}'`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tconst admission: CapabilityAdmission = {\n\t\tkind: \"capability-admission\",\n\t\tadmissionId: decision.admissionId,\n\t\tproposalId: proposal.proposalId,\n\t\tsubjectId: proposal.subjectId,\n\t\tcapability: cloneCapabilityRef(proposal.capability),\n\t\tstate: admissionState,\n\t\tdecisionId: decision.decisionId,\n\t\tboundaryName: proposal.boundaryName,\n\t\trole: proposal.role,\n\t\tpolicyId: decision.policyId,\n\t\treason: decision.reason ?? proposal.reason,\n\t\tsourceRefs: capabilityDecisionRefs(decision, proposal, policy),\n\t\tadmittedAtMs: decision.decidedAtMs ?? admittedAtMs,\n\t\tmetadata: {\n\t\t\t...(proposal.metadata ?? {}),\n\t\t\t...(policy?.metadata ?? {}),\n\t\t\t...(decision.metadata ?? {}),\n\t\t},\n\t};\n\tstate.admissionsById.set(admission.admissionId, admission);\n\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\tstate.terminalDecisionIds.add(decision.decisionId);\n\temitAdmission(ctx, state, admission);\n}\n\nfunction capabilityAdmissionViews(\n\tgraph: Graph,\n\truntime: Node<CapabilityAdmissionFact>,\n\tname: string,\n): Node<CapabilityAdmissionViews> {\n\treturn graph.node<CapabilityAdmissionViews>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tconst state: CapabilityAdmissionViewsState =\n\t\t\t\tctx.state.get<CapabilityAdmissionViewsState>() ?? {\n\t\t\t\t\tadmissionsByProposal: new Map(),\n\t\t\t\t\tadmissionsBySubject: new Map(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as CapabilityAdmissionFact;\n\t\t\t\tif (fact.kind === \"admission\") {\n\t\t\t\t\tconst admission = fact.admission;\n\t\t\t\t\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\t\t\t\t\tconst bySubject = state.admissionsBySubject.get(admission.subjectId) ?? [];\n\t\t\t\t\tbySubject.push(admission);\n\t\t\t\t\tstate.admissionsBySubject.set(admission.subjectId, bySubject);\n\t\t\t\t}\n\t\t\t\tif (fact.kind === \"issue\") state.issues.push(fact.issue);\n\t\t\t\tif (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", freezeCapabilityAdmissionViews(state)]]);\n\t\t},\n\t\t{ name, factory: \"capabilityAdmissionViews\" },\n\t);\n}\n\nfunction emitAdmission(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tadmission: CapabilityAdmission,\n): void {\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst statusState = capabilityAdmissionStatusState(admission.state);\n\tconst status: CapabilityAdmissionStatus = {\n\t\tkind: \"capability-admission-status\",\n\t\tstatusId: `${admission.subjectId}:${statusState}:${state.statusSeq}`,\n\t\tstate: statusState,\n\t\tproposalId: admission.proposalId,\n\t\tadmissionId: admission.admissionId,\n\t\tsubjectId: admission.subjectId,\n\t\tcapabilityId: admission.capability.id,\n\t\tcapabilityKind: admission.capability.kind,\n\t\tpolicyId: admission.policyId,\n\t\tsourceRefs: admission.sourceRefs,\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${admission.subjectId}:${statusState}:${state.auditSeq}`,\n\t\tkind: `capability-admission-${admission.state}`,\n\t\tsubjectId: admission.subjectId,\n\t\tsourceRefs: admission.sourceRefs,\n\t\tmetadata: {\n\t\t\tadmissionId: admission.admissionId,\n\t\t\tcapabilityId: admission.capability.id,\n\t\t\tcapabilityKind: admission.capability.kind,\n\t\t\tpolicyId: admission.policyId,\n\t\t\tproposalId: admission.proposalId,\n\t\t},\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"admission\", admission } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies CapabilityAdmissionFact],\n\t]);\n}\n\nfunction emitIssue(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tkey: string,\n\tissue: DataIssue,\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst status: CapabilityAdmissionStatus = {\n\t\tkind: \"capability-admission-status\",\n\t\tstatusId: `capability-admission-issue:${state.statusSeq}`,\n\t\tstate: \"capability-admission-issue\",\n\t\tsubjectId: issue.subjectId,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `capability-admission-issue:${state.auditSeq}`,\n\t\tkind: \"capability-admission-issue\",\n\t\tsubjectId: issue.subjectId,\n\t\tmessage: issue.message,\n\t\tissueCode: issue.code,\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies CapabilityAdmissionFact],\n\t]);\n}\n\nfunction capabilityAdmissionProposalIssue(\n\tproposal: CapabilityAdmissionProposal,\n): DataIssue | undefined {\n\tif (\n\t\tproposal.kind !== \"capability-admission-proposal\" ||\n\t\ttypeof proposal.proposalId !== \"string\" ||\n\t\tproposal.proposalId.length === 0 ||\n\t\ttypeof proposal.subjectId !== \"string\" ||\n\t\tproposal.subjectId.length === 0 ||\n\t\t!isBoundaryCapabilityRef(proposal.capability)\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-proposal\",\n\t\t\t\"CapabilityAdmissionProposal requires proposalId, subjectId, and a D348 BoundaryCapabilityRef\",\n\t\t\t{ subjectId: typeof proposal.subjectId === \"string\" ? proposal.subjectId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction capabilityAdmissionPolicyIssue(policy: CapabilityAdmissionPolicy): DataIssue | undefined {\n\tif (\n\t\tpolicy.kind !== \"capability-admission-policy\" ||\n\t\ttypeof policy.policyId !== \"string\" ||\n\t\tpolicy.policyId.length === 0 ||\n\t\t(policy.capabilityIds !== undefined &&\n\t\t\t(!Array.isArray(policy.capabilityIds) ||\n\t\t\t\t!policy.capabilityIds.every((id) => typeof id === \"string\" && id.length > 0))) ||\n\t\t(policy.capabilityKinds !== undefined &&\n\t\t\t(!Array.isArray(policy.capabilityKinds) ||\n\t\t\t\t!policy.capabilityKinds.every(isBoundaryCapabilityKind))) ||\n\t\t(policy.requiredOnly !== undefined && typeof policy.requiredOnly !== \"boolean\") ||\n\t\t(policy.allowedOutcomes !== undefined &&\n\t\t\t(!Array.isArray(policy.allowedOutcomes) ||\n\t\t\t\t!policy.allowedOutcomes.every(isCapabilityAdmissionOutcome)))\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-policy\",\n\t\t\t\"CapabilityAdmissionPolicy requires a policyId and D348 capability/outcome filters\",\n\t\t\t{ subjectId: typeof policy.policyId === \"string\" ? policy.policyId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction capabilityAdmissionDecisionIssue(\n\tdecision: CapabilityAdmissionDecision,\n): DataIssue | undefined {\n\tif (\n\t\tdecision.kind !== \"capability-admission-decision\" ||\n\t\ttypeof decision.decisionId !== \"string\" ||\n\t\tdecision.decisionId.length === 0 ||\n\t\ttypeof decision.admissionId !== \"string\" ||\n\t\tdecision.admissionId.length === 0 ||\n\t\ttypeof decision.proposalId !== \"string\" ||\n\t\tdecision.proposalId.length === 0 ||\n\t\t!isCapabilityAdmissionOutcome(decision.outcome) ||\n\t\t(decision.policyId !== undefined &&\n\t\t\t(typeof decision.policyId !== \"string\" || decision.policyId.length === 0))\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-decision\",\n\t\t\t\"CapabilityAdmissionDecision requires decisionId, admissionId, proposalId, and allow/block/defer outcome\",\n\t\t\t{ subjectId: typeof decision.proposalId === \"string\" ? decision.proposalId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction validateCapabilityAdmissionPolicy(\n\tpolicy: CapabilityAdmissionPolicy,\n\tdecision: CapabilityAdmissionDecision,\n\tproposal: CapabilityAdmissionProposal,\n): { readonly code: string; readonly message: string } | undefined {\n\tif (\n\t\tpolicy.capabilityIds !== undefined &&\n\t\t!policy.capabilityIds.includes(proposal.capability.id)\n\t) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not apply to capability '${proposal.capability.id}'`,\n\t\t};\n\t}\n\tif (\n\t\tpolicy.capabilityKinds !== undefined &&\n\t\t!policy.capabilityKinds.includes(proposal.capability.kind)\n\t) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not apply to capability kind '${proposal.capability.kind}'`,\n\t\t};\n\t}\n\tif (policy.requiredOnly === true && !proposal.capability.required) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' applies only to required capabilities`,\n\t\t};\n\t}\n\tif (policy.allowedOutcomes !== undefined && !policy.allowedOutcomes.includes(decision.outcome)) {\n\t\treturn {\n\t\t\tcode: \"unsupported-capability-admission-outcome\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not allow outcome '${decision.outcome}'`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction capabilityPolicyForDecision(\n\tstate: CapabilityAdmissionStateInternal,\n\tdecision: CapabilityAdmissionDecision,\n):\n\t| CapabilityAdmissionPolicy\n\t| \"missing-capability-admission-policy\"\n\t| \"stale-capability-admission-policy-ref\"\n\t| undefined {\n\tif (decision.policyId === undefined) return undefined;\n\tconst stalePolicyRef = (decision.sourceRefs ?? []).find(\n\t\t(sourceRef) =>\n\t\t\tsourceRef.kind === \"capability-admission-policy\" && sourceRef.id !== decision.policyId,\n\t);\n\tif (stalePolicyRef !== undefined) return \"stale-capability-admission-policy-ref\";\n\treturn state.policies.get(decision.policyId) ?? \"missing-capability-admission-policy\";\n}\n\nfunction capabilityPolicyIssueMessage(\n\tcode: \"missing-capability-admission-policy\" | \"stale-capability-admission-policy-ref\",\n\tdecision: CapabilityAdmissionDecision,\n): string {\n\tif (code === \"missing-capability-admission-policy\") {\n\t\treturn `CapabilityAdmissionPolicy '${decision.policyId}' was referenced but not present`;\n\t}\n\treturn `CapabilityAdmissionDecision '${decision.decisionId}' carries a stale admission policy source ref`;\n}\n\nfunction admissionStateForOutcome(\n\toutcome: CapabilityAdmissionOutcome,\n): CapabilityAdmissionState | undefined {\n\tif (outcome === \"allow\") return \"allowed\";\n\tif (outcome === \"block\") return \"blocked\";\n\tif (outcome === \"defer\") return \"deferred\";\n\treturn undefined;\n}\n\nfunction capabilityAdmissionStatusState(\n\tstate: CapabilityAdmissionState,\n): CapabilityAdmissionStatus[\"state\"] {\n\tif (state === \"allowed\") return \"capability-admission-allowed\";\n\tif (state === \"blocked\") return \"capability-admission-blocked\";\n\treturn \"capability-admission-deferred\";\n}\n\nfunction cloneCapabilityRef(ref: BoundaryCapabilityRef): BoundaryCapabilityRef {\n\treturn {\n\t\tid: ref.id,\n\t\tkind: ref.kind,\n\t\trequired: ref.required,\n\t\t...(ref.sourceRefs === undefined ? {} : { sourceRefs: [...ref.sourceRefs] }),\n\t};\n}\n\nfunction isBoundaryCapabilityRef(value: unknown): value is BoundaryCapabilityRef {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Partial<BoundaryCapabilityRef>;\n\treturn (\n\t\ttypeof record.id === \"string\" &&\n\t\trecord.id.length > 0 &&\n\t\tisBoundaryCapabilityKind(record.kind) &&\n\t\ttypeof record.required === \"boolean\" &&\n\t\t(record.sourceRefs === undefined ||\n\t\t\t(Array.isArray(record.sourceRefs) &&\n\t\t\t\trecord.sourceRefs.every((sourceRef) => typeof sourceRef === \"string\")))\n\t);\n}\n\nfunction isBoundaryCapabilityKind(value: unknown): value is BoundaryCapabilityRef[\"kind\"] {\n\treturn value === \"auth\" || value === \"permission\" || value === \"config\" || value === \"resource\";\n}\n\nfunction isCapabilityAdmissionOutcome(value: unknown): value is CapabilityAdmissionOutcome {\n\treturn value === \"allow\" || value === \"block\" || value === \"defer\";\n}\n\nfunction proposalKeyFallback(proposal: CapabilityAdmissionProposal): string {\n\treturn typeof proposal.proposalId === \"string\" && proposal.proposalId.length > 0\n\t\t? proposal.proposalId\n\t\t: `${stringValue(proposal.subjectId) ?? \"unknown\"}:${capabilityKeyFallback(proposal.capability)}`;\n}\n\nfunction policyKeyFallback(policy: CapabilityAdmissionPolicy): string {\n\treturn typeof policy.policyId === \"string\" && policy.policyId.length > 0\n\t\t? policy.policyId\n\t\t: \"unknown\";\n}\n\nfunction decisionKeyFallback(decision: CapabilityAdmissionDecision): string {\n\treturn typeof decision.decisionId === \"string\" && decision.decisionId.length > 0\n\t\t? decision.decisionId\n\t\t: `${stringValue(decision.proposalId) ?? \"unknown\"}:${stringValue(decision.admissionId) ?? \"unknown\"}`;\n}\n\nfunction capabilityKeyFallback(value: unknown): string {\n\tif (!isBoundaryCapabilityRef(value)) return \"unknown-capability\";\n\treturn `${value.kind}:${value.id}`;\n}\n\nfunction nextMalformedIssueKey(\n\tstate: CapabilityAdmissionStateInternal,\n\tkind: \"decision\" | \"policy\" | \"proposal\",\n\tfallback: string,\n): string {\n\tstate.issueSeq += 1;\n\treturn `malformed-${kind}:${state.issueSeq}:${fallback}`;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction capabilityProposalRefs(proposal: CapabilityAdmissionProposal): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"capability-admission-proposal\", proposal.proposalId),\n\t\tref(\"boundary-capability\", `${proposal.capability.kind}:${proposal.capability.id}`),\n\t\t...(proposal.sourceRefs ?? []),\n\t]);\n}\n\nfunction capabilityDecisionRefs(\n\tdecision: CapabilityAdmissionDecision,\n\tproposal?: CapabilityAdmissionProposal,\n\tpolicy?: CapabilityAdmissionPolicy,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"capability-admission-decision\", decision.decisionId),\n\t\tref(\"capability-admission\", decision.admissionId),\n\t\tref(\"capability-admission-proposal\", decision.proposalId),\n\t\t...(proposal === undefined ? [] : capabilityProposalRefs(proposal)),\n\t\t...(decision.policyId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"capability-admission-policy\", decision.policyId)]),\n\t\t...(policy === undefined ? [] : [ref(\"capability-admission-policy\", policy.policyId)]),\n\t\t...(decision.sourceRefs ?? []),\n\t]);\n}\n\nfunction forEachPolicyDepBatch(\n\tctx: Ctx,\n\tstart: number,\n\tcount: number,\n\tfn: (value: unknown) => void,\n): void {\n\tfor (let i = 0; i < count; i += 1) {\n\t\tfor (const value of depBatch(ctx, start + i) ?? []) fn(value);\n\t}\n}\n\nfunction projectRuntimeFact<T, TOut>(\n\tgraph: Graph,\n\truntime: Node<T>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: T) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as T;\n\t\t\t\tconst value = pick(typed);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory },\n\t);\n}\n\nfunction freezeCapabilityAdmissionViews(\n\tstate: CapabilityAdmissionViewsState,\n): CapabilityAdmissionViews {\n\treturn {\n\t\tadmissionsByProposal: new Map(state.admissionsByProposal),\n\t\tadmissionsBySubject: new Map(\n\t\t\tArray.from(state.admissionsBySubject, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction emptyCapabilityAdmissionState(): CapabilityAdmissionStateInternal {\n\treturn {\n\t\tproposals: new Map(),\n\t\tpolicies: new Map(),\n\t\tdecisions: new Map(),\n\t\tadmissionsById: new Map(),\n\t\tadmissionsByProposal: new Map(),\n\t\tterminalDecisionIds: new Set(),\n\t\tissueKeys: new Set(),\n\t\tissueSeq: 0,\n\t\tstatusSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction dataIssue(\n\tcode: string,\n\tmessage: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly refs?: readonly SourceRef[];\n\t\treadonly details?: unknown;\n\t} = {},\n): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsubjectId: opts.subjectId,\n\t\trefs: opts.refs?.map((sourceRef) => `${sourceRef.kind}:${sourceRef.id}`),\n\t\tdetails: opts.details,\n\t};\n}\n\nfunction uniqueSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\tconst seen = new Set<string>();\n\tconst out: 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\tout.push(sourceRef);\n\t}\n\treturn out;\n}\n\nfunction ref(kind: string, id: string): SourceRef {\n\treturn { kind, id };\n}\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Declarative batch (R-batch-coalesce / D12).\n *\n * Inside a batch, DIRTY propagates immediately but the tier-3 settle slice\n * (DATA/RESOLVED/INVALIDATE) is deferred to commit, so a shared downstream\n * recomputes ONCE after all batched sources settle. Success -> commit; a thrown\n * error -> rollback; `bctx.rollback()` is the explicit escape hatch.\n *\n * Coalescing note: this kernel coalesces multiple emits to the SAME node within\n * one batch to the latest tier-3 wave (last-value-wins). Full per-item batch-array\n * delivery (downstream fn receiving [v1..vK]) is a documented refinement — the\n * dominant use (coalescing a diamond join to one recompute) is exact here.\n */\n\nimport type { Wave } from \"../protocol/messages.js\";\nimport { dropBoundaryTasksForBatch, enterWave, exitWave } from \"./boundary.js\";\n\n/** A node target the batch can commit/rollback against (structural, avoids an import cycle). */\nexport interface BatchTarget {\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport interface BatchCtx {\n\t/** Discard all deferred emissions in this batch instead of committing. */\n\trollback(): void;\n}\n\ninterface ActiveBatch {\n\torder: BatchTarget[];\n\tdeferred: Map<BatchTarget, Wave>;\n\tcommitted: boolean;\n\trolledBack: boolean;\n}\n\nlet active: ActiveBatch | null = null;\nlet boundaryOwner: ActiveBatch | null = null;\n\nexport function currentBatch(): boolean {\n\treturn active !== null;\n}\n\nexport function currentBoundaryBatchToken(): object | undefined {\n\treturn active ?? boundaryOwner ?? undefined;\n}\n\n/**\n * Defer a node's tier-3 settle slice into the active batch. Returns true if a batch\n * captured it; false if there is no active batch (caller emits normally).\n */\nexport function deferToBatch(target: BatchTarget, tier3Wave: Wave): boolean {\n\tif (active === null) return false;\n\tif (!active.deferred.has(target)) active.order.push(target);\n\tactive.deferred.set(target, tier3Wave); // last-value coalescing\n\treturn true;\n}\n\n/**\n * Defer a topology mutation until after the active batch has committed/rolled back,\n * but only when this target has an uncommitted settle slice in the current batch.\n */\nexport function deferAfterBatchForTarget(target: BatchTarget, fn: () => void): boolean {\n\tif (active === null || !active.deferred.has(target)) return false;\n\tconst owner = active;\n\ttarget.__deferBoundary(() => {\n\t\tif (owner.committed) fn();\n\t}, owner);\n\treturn true;\n}\n\nfunction commit(b: ActiveBatch): void {\n\tconst prev = boundaryOwner;\n\tboundaryOwner = b;\n\ttry {\n\t\tfor (const target of b.order) {\n\t\t\tconst wave = b.deferred.get(target);\n\t\t\tif (wave) target.__commitBatchedWave(wave);\n\t\t}\n\t\tb.committed = true;\n\t} catch (e) {\n\t\tdropBoundaryTasksForBatch(b);\n\t\tthrow e;\n\t} finally {\n\t\tboundaryOwner = prev;\n\t}\n}\n\nfunction rollback(b: ActiveBatch): void {\n\tdropBoundaryTasksForBatch(b);\n\tfor (const target of b.order) target.__rollbackBatched();\n}\n\n/** Run `fn` as a batch (D12). DATA deferred to commit; throw/rollback discards. */\nexport function batch<R>(fn: (bctx: BatchCtx) => R): R {\n\t// Wave-owner boundary (R-rewire-deferred / D47): bracket the whole batch (fn + commit) so a\n\t// ctx.rewireNext issued by a fn that runs during COMMIT drains AFTER the commit, never on the\n\t// un-committed view. Inner waves (state.set, commit cascade) nest under this owner.\n\tenterWave();\n\ttry {\n\t\tif (active !== null) {\n\t\t\t// Nested batch joins the outer frame (one commit at the outermost exit).\n\t\t\tconst outer = active;\n\t\t\treturn fn({\n\t\t\t\trollback: () => {\n\t\t\t\t\touter.rolledBack = true;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst b: ActiveBatch = { order: [], deferred: new Map(), committed: false, rolledBack: false };\n\t\tactive = b;\n\t\tconst bctx: BatchCtx = {\n\t\t\trollback: () => {\n\t\t\t\tb.rolledBack = true;\n\t\t\t},\n\t\t};\n\t\tlet result: R;\n\t\ttry {\n\t\t\tresult = fn(bctx);\n\t\t} catch (e) {\n\t\t\tactive = null;\n\t\t\trollback(b);\n\t\t\tthrow e;\n\t\t}\n\t\tactive = null;\n\t\tif (b.rolledBack) rollback(b);\n\t\telse {\n\t\t\tcommit(b);\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\texitWave();\n\t}\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated handle-dispatch PoC (packages/pure-ts r8-poc, R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/**\n * First-class dispatcher (D21). Owns pools; graph binds to one (default = process-global,\n * D26 — the only global singleton). Pool trait is pluggable for WorkerPool/RemotePool (D20).\n */\n/** Per-handle profiling counters (D39 / R-profile). Lives on the dispatcher — the invoke\n * funnel (F-DISPATCH-ALL) — NEVER on the thin node (R-node-thin). */\nexport interface HandleStat {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n}\n\nconst statKey = (h: Handle): string => `${h.poolId}:${h.handleId}`;\n\nexport class Dispatcher {\n\tprivate pools: Pool[] = [];\n\treadonly syncPoolId: number;\n\treadonly asyncPoolId: number;\n\n\t// opt-in profile recorder (default OFF → zero overhead, F-PERF).\n\tprivate _recording = false;\n\tprivate _stats = new Map<string, HandleStat>();\n\tprivate _totalInvokes = 0;\n\n\tconstructor() {\n\t\tthis.syncPoolId = this.addPool(new PoolTable(\"sync\"));\n\t\tthis.asyncPoolId = this.addPool(new PoolTable(\"async\"));\n\t}\n\n\t/** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */\n\tsetRecording(on: boolean): void {\n\t\tthis._recording = on;\n\t}\n\t/** Reset accumulated profiling counters. */\n\tclearStats(): void {\n\t\tthis._stats.clear();\n\t\tthis._totalInvokes = 0;\n\t}\n\t/** Read a handle's accumulated counters (undefined if it never ran while recording). */\n\tstatFor(handle: Handle): HandleStat | undefined {\n\t\treturn this._stats.get(statKey(handle));\n\t}\n\t/** Total fn invocations recorded across the dispatcher. */\n\tget totalInvokes(): number {\n\t\treturn this._totalInvokes;\n\t}\n\n\taddPool(pool: Pool): number {\n\t\tconst id = this.pools.length;\n\t\tthis.pools.push(pool);\n\t\treturn id;\n\t}\n\n\t/** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */\n\tregister(fn: NodeFn, pool: PoolKind | number = \"sync\"): Handle {\n\t\tconst poolId = pool === \"sync\" ? this.syncPoolId : pool === \"async\" ? this.asyncPoolId : pool;\n\t\tconst handleId = this.pools[poolId].register(fn);\n\t\treturn { poolId, handleId };\n\t}\n\n\t/**\n\t * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any\n\t * accumulated profile stat so a reused id never inherits the previous tenant's counters.\n\t * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node\n\t * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives\n\t * activate↔deactivate and is reused on reactivation; only a rewire swaps it).\n\t */\n\tunregister(handle: Handle): void {\n\t\tthis.pools[handle.poolId].unregister(handle.handleId);\n\t\t// Drop the stat UNCONDITIONALLY (QA F2.1), not only while recording: if recording was\n\t\t// OFF at unregister time the key would linger, and a later register reusing this id (the\n\t\t// free-list) would inherit the prior tenant's counters once recording resumes. delete of\n\t\t// an absent key is a cheap no-op; unregister is off the hot invoke path (F-PERF intact).\n\t\tthis._stats.delete(statKey(handle));\n\t}\n\n\t/** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */\n\tinvoke(handle: Handle, ctx: Ctx): void {\n\t\tif (!this._recording) {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t\treturn;\n\t\t}\n\t\tthis._totalInvokes++;\n\t\tconst t0 = performance.now();\n\t\ttry {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t} finally {\n\t\t\tconst dur = (performance.now() - t0) * 1e6; // ms → ns\n\t\t\tconst key = statKey(handle);\n\t\t\tconst s = this._stats.get(key) ?? {\n\t\t\t\tinvokes: 0,\n\t\t\t\ttotalDurationNs: 0,\n\t\t\t\tlastDurationNs: 0,\n\t\t\t};\n\t\t\ts.invokes++;\n\t\t\ts.lastDurationNs = dur;\n\t\t\ts.totalDurationNs += dur;\n\t\t\tthis._stats.set(key, s);\n\t\t}\n\t}\n\n\tpoolKind(poolId: number): PoolKind {\n\t\treturn this.pools[poolId].kind;\n\t}\n}\n\n/** The only global singleton (D26). Overridable by passing an explicit dispatcher. */\nexport const defaultDispatcher = new Dispatcher();\n","/**\n * Graph-owned environment driver bag (D130/D131).\n *\n * Drivers host process/network/messaging/runtime boundary work outside the synchronous wave core.\n * The bag is graph-local and is read from ctx by source/adapter bodies.\n */\n\nexport type DriverCancel = () => void;\n\nexport type DriverResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport interface ProcessCommand {\n\treadonly program: string;\n\treadonly args: readonly string[];\n\treadonly cwd?: string;\n\treadonly env?: readonly (readonly [string, string])[];\n}\n\nexport interface ProcessResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number | null;\n\treadonly signal: string | null;\n}\n\nexport interface HttpRequest {\n\treadonly method: string;\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n\treadonly body?: Uint8Array | string;\n}\n\nexport interface HttpResponse {\n\treadonly status: number;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport interface SseRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport interface SseEvent {\n\treadonly event?: string;\n\treadonly data: string;\n\treadonly id?: string;\n\treadonly retryMs?: number;\n}\n\nexport type SseDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: SseEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebSocketRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport type WebSocketEvent =\n\t| { readonly kind: \"open\" }\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\nexport interface WebSocketSend {\n\treadonly data: string | Uint8Array;\n}\n\nexport interface WebSocketSendResult {\n\treadonly sent: true;\n}\n\n/** Live WebSocket session handle for D133 SessionBundle adapters. */\nexport interface WebSocketSessionHandle {\n\tsend(\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\tclose(code?: number, reason?: string): void;\n\tcancel(): void;\n}\n\nexport type WebSocketDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebSocketEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebhookRegistration {\n\treadonly id: string;\n\treadonly method?: string;\n\treadonly path?: string;\n}\n\nexport interface WebhookEvent {\n\treadonly registrationId: string;\n\treadonly method: string;\n\treadonly path: string;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly query: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport type WebhookDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebhookEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface LocalProcessDriver {\n\trun(\n\t\tcommand: ProcessCommand,\n\t\tcallback: (result: DriverResult<ProcessResult>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalHttpDriver {\n\trequest(\n\t\trequest: HttpRequest,\n\t\tcallback: (result: DriverResult<HttpResponse>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalSseDriver {\n\tconnect(request: SseRequest, callback: (event: SseDriverEvent) => void): DriverCancel;\n}\n\nexport interface LocalWebSocketDriver {\n\tconnect(request: WebSocketRequest, callback: (event: WebSocketDriverEvent) => void): DriverCancel;\n\tsend?(\n\t\trequest: WebSocketRequest,\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\t/** Open a live bidirectional session; unlike send(), outbound messages use this same connection. */\n\tconnectSession?(\n\t\trequest: WebSocketRequest,\n\t\tcallback: (event: WebSocketDriverEvent) => void,\n\t): WebSocketSessionHandle;\n}\n\nexport interface LocalWebhookDriver {\n\tregister(\n\t\tregistration: WebhookRegistration,\n\t\tcallback: (event: WebhookDriverEvent) => void,\n\t): DriverCancel;\n}\n\nexport interface FetchResponseLike {\n\treadonly status: number;\n\treadonly headers?: { forEach?(fn: (value: string, key: string) => void): void };\n\tarrayBuffer(): PromiseLike<ArrayBuffer>;\n}\n\nexport type FetchLike = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: readonly (readonly [string, string])[];\n\t\treadonly body?: Uint8Array | string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => PromiseLike<FetchResponseLike>;\n\nexport interface WebSocketLike {\n\tsend(data: string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n\tremoveEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n}\n\nexport type WebSocketConstructorLike = new (url: string) => WebSocketLike;\n\nexport interface EnvironmentDriversInit {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n}\n\nexport class EnvironmentDrivers {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n\n\tconstructor(init: EnvironmentDriversInit = {}) {\n\t\tthis.process = init.process;\n\t\tthis.http = init.http;\n\t\tthis.sse = init.sse;\n\t\tthis.websocket = init.websocket;\n\t\tthis.webhook = init.webhook;\n\t\tObject.freeze(this);\n\t}\n\n\tstatic empty(): EnvironmentDrivers {\n\t\treturn EMPTY_ENVIRONMENT;\n\t}\n\n\twithProcess(driver: LocalProcessDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, process: driver });\n\t}\n\n\twithHttp(driver: LocalHttpDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, http: driver });\n\t}\n\n\twithSse(driver: LocalSseDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, sse: driver });\n\t}\n\n\twithWebSocket(driver: LocalWebSocketDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, websocket: driver });\n\t}\n\n\twithWebhook(driver: LocalWebhookDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, webhook: driver });\n\t}\n\n\tprocessDriver(): LocalProcessDriver | undefined {\n\t\treturn this.process;\n\t}\n\n\thttpDriver(): LocalHttpDriver | undefined {\n\t\treturn this.http;\n\t}\n\n\tsseDriver(): LocalSseDriver | undefined {\n\t\treturn this.sse;\n\t}\n\n\twebSocketDriver(): LocalWebSocketDriver | undefined {\n\t\treturn this.websocket;\n\t}\n\n\twebhookDriver(): LocalWebhookDriver | undefined {\n\t\treturn this.webhook;\n\t}\n}\n\nconst EMPTY_ENVIRONMENT = new EnvironmentDrivers();\n\nexport function fetchHttpDriver(fetchFn: FetchLike = requireGlobalFetch()): LocalHttpDriver {\n\treturn {\n\t\trequest(request, callback) {\n\t\t\tconst controller = new AbortController();\n\t\t\tvoid Promise.resolve(\n\t\t\t\tfetchFn(request.url, {\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\theaders: request.headers,\n\t\t\t\t\tbody: request.body,\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t}),\n\t\t\t).then(\n\t\t\t\tasync (response) => {\n\t\t\t\t\tconst headers: Array<readonly [string, string]> = [];\n\t\t\t\t\tresponse.headers?.forEach?.((value, key) => {\n\t\t\t\t\t\theaders.push([key, value]);\n\t\t\t\t\t});\n\t\t\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\tcallback({ ok: true, value: { status: response.status, headers, body } });\n\t\t\t\t},\n\t\t\t\t(error) => callback({ ok: false, error }),\n\t\t\t);\n\t\t\treturn () => controller.abort();\n\t\t},\n\t};\n}\n\nexport function domWebSocketDriver(\n\tWebSocketCtor: WebSocketConstructorLike = requireGlobalWebSocket(),\n): LocalWebSocketDriver {\n\treturn {\n\t\tconnect(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tsend(request, message, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet settled = false;\n\t\t\tconst finish = (result: DriverResult<WebSocketSendResult>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcallback(result);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t\tconst onOpen = () => {\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\tfinish({ ok: true, value: { sent: true } });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinish({ ok: false, error });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => finish({ ok: false, error: event });\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tconnectSession(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet active = true;\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tconst removeListeners = () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn {\n\t\t\t\tsend(message, sendCallback) {\n\t\t\t\t\tlet canceled = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: true, value: { sent: true } });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: false, error });\n\t\t\t\t\t}\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tclose(code, reason) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t},\n\t\t\t\tcancel() {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tactive = false;\n\t\t\t\t\tremoveListeners();\n\t\t\t\t\tsocket.close();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction requireGlobalFetch(): FetchLike {\n\tconst fetchFn = (globalThis as { fetch?: FetchLike }).fetch;\n\tif (fetchFn === undefined) throw new Error(\"fetchHttpDriver: global fetch is not available\");\n\treturn fetchFn;\n}\n\nfunction requireGlobalWebSocket(): WebSocketConstructorLike {\n\tconst ctor = (globalThis as { WebSocket?: WebSocketConstructorLike }).WebSocket;\n\tif (ctor === undefined) throw new Error(\"domWebSocketDriver: global WebSocket is not available\");\n\treturn ctor;\n}\n","import type { Ctx, Sink } from \"../ctx/types.js\";\nimport type { Dispatcher, Handle } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport { type LockId, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\nimport type { Node, Status } from \"./node.js\";\nimport type { NodeVersion, ResolvedNodeVersioningPolicy } from \"./versioning.js\";\n\nexport type NodeId = number & { readonly __nodeId: unique symbol };\n\nexport interface DepBookkeeping {\n\tbatch: Array<unknown[] | null>;\n\twaveData: unknown[][][];\n\twaveTokens: Array<object | undefined>;\n\tprev: unknown[];\n\thasData: boolean[];\n\tdirty: boolean[];\n\ttier: number[];\n\tterminal: Array<true | unknown | undefined>;\n\tterminalInput: Array<true | unknown | undefined>;\n\tunsubs: Array<() => void>;\n\tidxBoxes: Array<{ v: number }>;\n}\n\nexport interface ValueState<T> {\n\tcache: T | undefined;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasTorndown: boolean;\n\treplayRing: T[];\n}\n\nexport interface VersionState {\n\tpolicy: ResolvedNodeVersioningPolicy;\n\tvalue: NodeVersion | undefined;\n}\n\nexport interface WaveState {\n\tpending: number;\n\thasCalledFnOnce: boolean;\n\temittedDirtyThisWave: boolean;\n\temittedSettleThisWave: boolean;\n\tinsideRunWave: boolean;\n\tinDepMutation: boolean;\n\trewireRunPending: boolean;\n\tbatchDirtyOwed: boolean;\n}\n\nexport interface ControlState {\n\tpauseLockset: Set<unknown>;\n\tpausedDepWaveOccurred: boolean;\n\tpauseBuffer: Wave[];\n\tdemandOwed: PullDemand | undefined;\n\tactivePull: PullDemand | undefined;\n\tpullDirtyOwed: boolean;\n\tinDeliverDemand: boolean;\n}\n\nexport interface PrivateState {\n\tvalue: unknown;\n\tpersist: boolean;\n}\n\nexport interface CleanupHooks {\n\tonDeactivation: Array<() => void>;\n\tonInvalidate: Array<() => void>;\n}\n\nexport interface SyncCtxState {\n\tvalue: Ctx | null;\n}\n\nexport interface LifecycleState {\n\tsubscribers: Set<Sink>;\n\tactivated: boolean;\n}\n\nexport interface BoundaryTask {\n\tapply: () => void;\n\tbatchToken?: object;\n\tisReady?: () => boolean;\n}\n\nexport interface BoundaryState {\n\tqueue: BoundaryTask[];\n\thead: number;\n}\n\nexport interface NodeSlot<_T> {\n\tid: NodeId;\n\tdeps: Node<unknown>[];\n\thandle: Handle | null;\n\tpool: \"sync\" | \"async\";\n\tdispatcher: Dispatcher;\n\tenvironment: EnvironmentDrivers;\n\tpartial: boolean;\n\tterminalAsRealInput: boolean;\n\tcompleteWhenDepsComplete: boolean;\n\terrorWhenDepsError: boolean;\n\tresubscribable: boolean;\n\tresetOnTeardown: boolean;\n\tpausable: boolean | \"resumeAll\";\n\tpull: boolean;\n\tpullLock: LockId | undefined;\n\treplayN: number;\n\tdynamic: boolean;\n\tname?: string;\n\tfactory?: string;\n}\n\nexport interface NodeState<T> {\n\tdep: DepBookkeeping;\n\tlifecycle: LifecycleState;\n\tvalue: ValueState<T>;\n\tversion: VersionState;\n\twave: WaveState;\n\tcontrol: ControlState;\n\tprivateState: PrivateState;\n\thooks: CleanupHooks;\n\tsyncCtx: SyncCtxState;\n}\n\nexport class NodeCore {\n\tprivate nextId = 0;\n\tprivate readonly slots: Array<NodeSlot<unknown> | undefined> = [];\n\tprivate readonly values: Array<ValueState<unknown> | undefined> = [];\n\tprivate readonly waves: Array<WaveState | undefined> = [];\n\tprivate readonly controls: Array<ControlState | undefined> = [];\n\tprivate readonly lifecycles: Array<LifecycleState | undefined> = [];\n\tprivate readonly depStates: Array<DepBookkeeping | undefined> = [];\n\tprivate readonly privateStates: Array<PrivateState | undefined> = [];\n\tprivate readonly hooks: Array<CleanupHooks | undefined> = [];\n\tprivate readonly syncCtxs: Array<SyncCtxState | undefined> = [];\n\tprivate readonly versionStates: Array<VersionState | undefined> = [];\n\tprivate readonly boundary: BoundaryState = { queue: [], head: 0 };\n\n\tcreateSlot<T>(\n\t\tslot: Omit<NodeSlot<T>, \"id\">,\n\t\tstate: NodeState<T>,\n\t): { id: NodeId; slot: NodeSlot<T> } {\n\t\tconst id = this.nextId++ as NodeId;\n\t\tconst full = { ...slot, id };\n\t\tthis.slots[id] = full as NodeSlot<unknown>;\n\t\tthis.depStates[id] = state.dep;\n\t\tthis.lifecycles[id] = state.lifecycle;\n\t\tthis.values[id] = state.value as ValueState<unknown>;\n\t\tthis.waves[id] = state.wave;\n\t\tthis.controls[id] = state.control;\n\t\tthis.privateStates[id] = state.privateState;\n\t\tthis.hooks[id] = state.hooks;\n\t\tthis.syncCtxs[id] = state.syncCtx;\n\t\tthis.versionStates[id] = state.version;\n\t\treturn { id, slot: full };\n\t}\n\n\tget<T>(id: NodeId): NodeSlot<T> {\n\t\tconst slot = this.slots[id];\n\t\tif (slot === undefined) throw new Error(\"NodeCore: unknown node slot\");\n\t\treturn slot as NodeSlot<T>;\n\t}\n\n\tgetValue<T>(id: NodeId): ValueState<T> {\n\t\tconst value = this.values[id];\n\t\tif (value === undefined) throw new Error(\"NodeCore: unknown node value state\");\n\t\treturn value as ValueState<T>;\n\t}\n\n\tgetWave(id: NodeId): WaveState {\n\t\tconst wave = this.waves[id];\n\t\tif (wave === undefined) throw new Error(\"NodeCore: unknown node wave state\");\n\t\treturn wave;\n\t}\n\n\tgetControl(id: NodeId): ControlState {\n\t\tconst control = this.controls[id];\n\t\tif (control === undefined) throw new Error(\"NodeCore: unknown node control state\");\n\t\treturn control;\n\t}\n\n\tgetLifecycle(id: NodeId): LifecycleState {\n\t\tconst lifecycle = this.lifecycles[id];\n\t\tif (lifecycle === undefined) throw new Error(\"NodeCore: unknown node lifecycle state\");\n\t\treturn lifecycle;\n\t}\n\n\tgetDep(id: NodeId): DepBookkeeping {\n\t\tconst dep = this.depStates[id];\n\t\tif (dep === undefined) throw new Error(\"NodeCore: unknown node dep state\");\n\t\treturn dep;\n\t}\n\n\tgetPrivateState(id: NodeId): PrivateState {\n\t\tconst state = this.privateStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node private state\");\n\t\treturn state;\n\t}\n\n\tgetHooks(id: NodeId): CleanupHooks {\n\t\tconst hooks = this.hooks[id];\n\t\tif (hooks === undefined) throw new Error(\"NodeCore: unknown node cleanup hooks\");\n\t\treturn hooks;\n\t}\n\n\tgetSyncCtx(id: NodeId): SyncCtxState {\n\t\tconst state = this.syncCtxs[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node ctx state\");\n\t\treturn state;\n\t}\n\n\tgetVersion(id: NodeId): VersionState {\n\t\tconst state = this.versionStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node version state\");\n\t\treturn state;\n\t}\n\n\t/** @internal D122: release graph-owned ephemeral node runtime state from core retention. */\n\treleaseSlot(id: NodeId): void {\n\t\tthis.slots[id] = undefined;\n\t\tthis.depStates[id] = undefined;\n\t\tthis.lifecycles[id] = undefined;\n\t\tthis.values[id] = undefined;\n\t\tthis.waves[id] = undefined;\n\t\tthis.controls[id] = undefined;\n\t\tthis.privateStates[id] = undefined;\n\t\tthis.hooks[id] = undefined;\n\t\tthis.syncCtxs[id] = undefined;\n\t\tthis.versionStates[id] = undefined;\n\t}\n\n\t/** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */\n\tenqueueBoundaryTask(task: BoundaryTask): void {\n\t\tthis.boundary.queue.push(task);\n\t}\n\n\t/** @internal */\n\thasBoundaryTasks(): boolean {\n\t\treturn this.boundary.head < this.boundary.queue.length;\n\t}\n\n\t/** @internal */\n\tboundaryTaskCount(): number {\n\t\treturn this.boundary.queue.length - this.boundary.head;\n\t}\n\n\t/** @internal */\n\tshiftBoundaryTask(): BoundaryTask | undefined {\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst task = this.boundary.queue[this.boundary.head++];\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** @internal Put a not-yet-ready task back at this core's FIFO head. */\n\tunshiftBoundaryTask(task: BoundaryTask): void {\n\t\tconst remaining = this.boundary.queue.slice(this.boundary.head);\n\t\tthis.boundary.queue = [task, ...remaining];\n\t\tthis.boundary.head = 0;\n\t}\n\n\t/** @internal D110: discard all pending tasks caused by an uncommitted batch. */\n\tdropBoundaryTasksForBatch(batchToken: object): void {\n\t\tconst remaining = this.boundary.queue\n\t\t\t.slice(this.boundary.head)\n\t\t\t.filter((task) => task.batchToken !== batchToken);\n\t\tthis.boundary.queue = remaining;\n\t\tthis.boundary.head = 0;\n\t}\n}\n\nexport function makeDepBookkeeping(depCount: number): DepBookkeeping {\n\treturn {\n\t\tbatch: new Array(depCount).fill(null),\n\t\twaveData: Array.from({ length: depCount }, () => []),\n\t\twaveTokens: new Array(depCount).fill(undefined),\n\t\tprev: new Array(depCount).fill(SENTINEL),\n\t\thasData: new Array(depCount).fill(false),\n\t\tdirty: new Array(depCount).fill(false),\n\t\ttier: new Array(depCount).fill(0),\n\t\tterminal: new Array(depCount).fill(undefined),\n\t\tterminalInput: new Array(depCount).fill(undefined),\n\t\tunsubs: [],\n\t\tidxBoxes: [],\n\t};\n}\n","import { strictCanonicalJsonBytes, strictJsonCodec } from \"../json/codec.js\";\n\nexport type NodeVersioningLevel = 0 | 1;\n\n/**\n * D112 V1 node-version hash callback.\n *\n * The callback receives strict canonical JSON UTF-8 DATA bytes, not the raw host value.\n * Runtime V1 versioning encodes DATA with `strictCanonicalJsonBytes(value)` before calling hash.\n */\nexport type NodeVersionHashFn = (bytes: Uint8Array) => string;\n\nexport type NodeVersioningPolicy =\n\t| false\n\t| 0\n\t| 1\n\t| {\n\t\t\tlevel: NodeVersioningLevel;\n\t\t\thash?: NodeVersionHashFn;\n\t };\n\nexport type ResolvedNodeVersioningPolicy =\n\t| { readonly enabled: false }\n\t| { readonly enabled: true; readonly level: 0 }\n\t| { readonly enabled: true; readonly level: 1; readonly hash: NodeVersionHashFn };\n\nexport type NodeVersionV0 = {\n\treadonly level: 0;\n\treadonly counter: number;\n};\n\nexport type NodeVersionV1 = {\n\treadonly level: 1;\n\treadonly counter: number;\n\treadonly cid: string;\n\treadonly prev: string | null;\n};\n\nexport type NodeVersion = NodeVersionV0 | NodeVersionV1;\n\nexport type NodeVersionJson = NodeVersion;\n\nconst ABSENT_V1_SEED = Object.freeze({\n\t\"@graphrefly/node-version\": \"v1-absent\",\n});\n\nfunction fnv1a64(input: Uint8Array): string {\n\tlet hash = 0xcbf29ce484222325n;\n\tconst prime = 0x100000001b3n;\n\tfor (const byte of input) {\n\t\thash ^= BigInt(byte);\n\t\thash = BigInt.asUintN(64, hash * prime);\n\t}\n\treturn hash.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Default synchronous D112 V1 node-version hash over strict canonical JSON UTF-8 bytes.\n *\n * When hashing a host value directly, encode first:\n * `defaultNodeVersionHash(strictCanonicalJsonBytes(value))`.\n */\nexport function defaultNodeVersionHash(bytes: Uint8Array): string {\n\treturn `fnv1a64:${fnv1a64(bytes)}`;\n}\n\nfunction computeV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\tvalue: unknown,\n): string {\n\treturn policy.hash(strictCanonicalJsonBytes(value));\n}\n\nexport function assertNodeVersionDataCompatible(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): void {\n\tif (!policy.enabled || policy.level === 0) return;\n\tstrictCanonicalJsonBytes(value);\n}\n\nexport function snapshotNodeVersionData(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): unknown {\n\tif (!policy.enabled || policy.level === 0) return value;\n\tconst bytes = strictCanonicalJsonBytes(value);\n\treturn strictJsonCodec.decode(bytes);\n}\n\nexport function resolveNodeVersioningPolicy(\n\tpolicy: NodeVersioningPolicy | undefined,\n): ResolvedNodeVersioningPolicy {\n\tif (policy === false) return { enabled: false };\n\tif (policy === undefined || policy === 0) return { enabled: true, level: 0 };\n\tif (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };\n\tif (typeof policy === \"object\" && policy !== null) {\n\t\tif (policy.level === 0) return { enabled: true, level: 0 };\n\t\tif (policy.level === 1) {\n\t\t\treturn { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };\n\t\t}\n\t}\n\tthrow new Error(\"node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)\");\n}\n\nexport function createNodeVersion(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tinitialValue: unknown = ABSENT_V1_SEED,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: 0,\n\t\tcid: computeV1Cid(policy, initialValue),\n\t\tprev: null,\n\t});\n}\n\nexport function advanceNodeVersion(\n\tcurrent: NodeVersion | undefined,\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (current === undefined) return createNodeVersion(policy, value);\n\tif (policy.level === 0) {\n\t\treturn Object.freeze({ level: 0, counter: current.counter + 1 });\n\t}\n\tconst previous = current.level === 1 ? current.cid : null;\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: current.counter + 1,\n\t\tcid: computeV1Cid(policy, value),\n\t\tprev: previous,\n\t});\n}\n\nexport function cloneNodeVersion(version: NodeVersion | undefined): NodeVersion | undefined {\n\tif (version === undefined) return undefined;\n\tif (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: version.counter,\n\t\tcid: version.cid,\n\t\tprev: version.prev,\n\t});\n}\n\nexport function restoredV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\thasData: boolean,\n\tcache: unknown,\n): string {\n\treturn computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);\n}\n\nexport function validateNodeVersionJson(value: unknown, path: string): NodeVersionJson {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new Error(`restoreGraph: ${path} must be an object`);\n\t}\n\tconst record = value as Record<string, unknown>;\n\tif (record.level === 0) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\treturn Object.freeze({ level: 0, counter: record.counter as number });\n\t}\n\tif (record.level === 1) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\tif (typeof record.cid !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.cid must be a string`);\n\t\t}\n\t\tif (record.prev !== null && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string or null`);\n\t\t}\n\t\tif ((record.counter as number) === 0 && record.prev !== null) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be null when counter is 0`);\n\t\t}\n\t\tif ((record.counter as number) > 0 && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string when counter is > 0`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tlevel: 1,\n\t\t\tcounter: record.counter as number,\n\t\t\tcid: record.cid,\n\t\t\tprev: record.prev,\n\t\t});\n\t}\n\tthrow new Error(`restoreGraph: ${path}.level must be 0 or 1`);\n}\n","/**\n * The node primitive — the thinnest substrate object (R-node-thin / D5).\n *\n * Holds a fn handle + deps + the wave state machine; ZERO inspection cruft\n * (naming/find/describe are the graph layer, CSP-2). Canonical authority:\n * ~/src/graphrefly/spec/rules.jsonl (R-node-*, R-two-phase, R-diamond, R-resolved-undirty,\n * R-first-run-gate, R-push-subscribe, R-rom-ram, R-fn-contract, R-initial, R-ctx-up).\n *\n * Slice 1 = core wave: state node, compute node, two-phase DIRTY->DATA, diamond\n * pending-counter join, first-run gate, substrate-synthesized undirty RESOLVED\n * (R-resolved-undirty / D49 — no equals-substitution; every occurrence is DATA),\n * push-on-subscribe, lazy activation, ROM/RAM. Lifecycle (terminal/INVALIDATE/cleanup),\n * control (PAUSE/async), batch, and dynamicNode land in later slices.\n */\n\nimport {\n\tcurrentBatch,\n\tcurrentBoundaryBatchToken,\n\tdeferAfterBatchForTarget,\n\tdeferToBatch,\n} from \"../batch/batch.js\";\nimport { deferRewire, enterWave, exitWave, scheduleBoundaryDrain } from \"../batch/boundary.js\";\nimport {\n\tCTX_DEP_CACHE,\n\tCTX_NODE_BINDING,\n\ttype Ctx,\n\ttype CtxState,\n\ttype DeliveryMeta,\n\ttype NodeFn,\n\ttype Sink,\n\ttype TerminalData,\n\ttype WaveData,\n} from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher, type Handle } from \"../dispatcher/index.js\";\nimport { EnvironmentDrivers } from \"../graph/environment.js\";\nimport {\n\terrorPayload,\n\tisDeferredTier,\n\tisInvalidErrorPayload,\n\tisPauseBufferedTier,\n\tisTerminal,\n\tisUpAllowed,\n\tisValueTier,\n\ttype LockId,\n\ttype Message,\n\tmessageTier,\n\ttype PullDemand,\n\tSENTINEL,\n\ttype Wave,\n} from \"../protocol/messages.js\";\nimport {\n\ttype CleanupHooks,\n\ttype ControlState,\n\ttype DepBookkeeping,\n\ttype LifecycleState,\n\tmakeDepBookkeeping,\n\tNodeCore,\n\ttype NodeId,\n\ttype NodeSlot,\n\ttype PrivateState,\n\ttype SyncCtxState,\n\ttype ValueState,\n\ttype VersionState,\n\ttype WaveState,\n} from \"./core.js\";\nimport {\n\tadvanceNodeVersion,\n\tassertNodeVersionDataCompatible,\n\tcloneNodeVersion,\n\tcreateNodeVersion,\n\ttype NodeVersion,\n\ttype NodeVersioningPolicy,\n\tresolveNodeVersioningPolicy,\n\trestoredV1Cid,\n\tsnapshotNodeVersionData,\n} from \"./versioning.js\";\n\nexport type Status =\n\t| \"sentinel\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\nexport interface NodeOptions<T = unknown> {\n\t/** Pre-populate cache; source pushes [DATA, initial] on subscribe (R-initial). `null` is valid. */\n\tinitial?: T | null;\n\t/** First-run gate off when true; fn body must guard SENTINEL per dep (R-first-run-gate). */\n\tpartial?: boolean;\n\t/** A dep terminal also settles the first-run gate (Reduce-class, R-first-run-gate). */\n\tterminalAsRealInput?: boolean;\n\t/** Auto-emit COMPLETE when ALL deps complete (R-deps-terminal). Default true. */\n\tcompleteWhenDepsComplete?: boolean;\n\t/** Auto-emit ERROR when any dep errors (R-deps-terminal). Default true. */\n\terrorWhenDepsError?: boolean;\n\t/** Allow re-activation after terminal; late subscribe resets the lifecycle (R-terminal). Default false. */\n\tresubscribable?: boolean;\n\t/** Clear cached value on TEARDOWN. Default false. */\n\tresetOnTeardown?: boolean;\n\t/** PAUSE/RESUME behavior (R-pause-modes). Default true. */\n\tpausable?: boolean | \"resumeAll\";\n\t/**\n\t * Pull-mode node (R-pull / D269): a quiet-until-demanded source, identified by this\n\t * author-supplied `pullId` (a unique LockId — a `Symbol` recommended; NOT the node name, NOT a\n\t * bare string if callers may also use strings as pause locks). QUIET by default: it ABSORBS\n\t * an upstream DIRTY WITHOUT relaying it downstream\n\t * (the wedge fix) and does NOT push-on-subscribe its cached value (START only). A DEMAND =\n\t * cone-routed `PULL({pullId, params?})`: a downstream consumer issues\n\t * `ctx.up([[\"PULL\", { pullId, params }]])` (broadcast up the declared cone) or\n\t * `ctx.up(msgs, towardDep)` (directed) WITHOUT holding this node's reference; the PULL travels\n\t * up to the pullId-holder, which fires EXACTLY ONE delivery (DIRTY-before-DATA when it emits)\n\t * then RE-QUIETS (1:1). Delivery content =\n\t * the orthogonal `pausable` mode: `true` → coalesced LATEST (one DATA); `'resumeAll'` → buffered\n\t * BACKLOG. `pullId` + `pausable:false` is REJECTED at construction. A SELF-triggered demand (a\n\t * consumer demanding a dep it ALSO reads) must defer via {@link Ctx.upNext} (R-rewire-deferred /\n\t * D37). Author the pullId as a shared module const used at both this node and the demander's fn.\n\t */\n\tpullId?: LockId;\n\t/** Buffer the last N outgoing DATA for late subscribers (R-replay-buffer). */\n\treplayBuffer?: number;\n\t/**\n\t * D109 node runtime versioning policy. Default is nodev0 (`{level:0,counter}`); `false`\n\t * disables runtime version metadata for this node.\n\t */\n\tversioning?: NodeVersioningPolicy;\n\t/** Mark this as a dynamicNode — fn gets ctx.track(i) for read-selection (R-dynamic-node / D35). */\n\tdynamic?: boolean;\n\t/** Dispatch pool for the fn (R-sync-core). Default sync. */\n\tpool?: \"sync\" | \"async\";\n\t/** Dispatcher to register/invoke against. Default = process-global (D26). */\n\tdispatcher?: Dispatcher;\n\t/** Optional debug name (graph layer owns real naming/inspection). */\n\tname?: string;\n\t/**\n\t * Real operator/source factory name for a STANDALONE graph-less node (D43-reserved; D51).\n\t * The graph index (`_entries`) carries the factory for g.*-registered nodes, so this is only\n\t * read for a node NOT in any graph index — a runtime *Map inner (bare `fromAny`/`initNode`\n\t * node) auto-discovered by `describe` (R-describe / R-edges-derived / D51). Off the canonical\n\t * wave path (R-node-thin intact — a pure annotation, never touched by the wave machinery).\n\t */\n\tfactory?: string;\n}\n\nexport interface NodeCheckpointState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly terminal: true | unknown | undefined;\n\treadonly activated: boolean;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | undefined;\n\treadonly handle: Handle | null;\n}\n\nexport interface NodeRestoreState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly status: Status;\n\treadonly terminal: true | unknown | undefined;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | false;\n}\n\ntype TopologyDepsChangedObserver = (\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n) => void;\n\nlet constructingCore: NodeCore | undefined;\nlet constructingEnvironment: EnvironmentDrivers | undefined;\nconst ownerTokens = new WeakMap<Node<unknown>, unknown>();\nconst topologyDepsChangedObservers = new WeakMap<Node<unknown>, TopologyDepsChangedObserver>();\nconst checkpointReaders = new WeakMap<Node<unknown>, () => NodeCheckpointState>();\nconst restoreWriters = new WeakMap<Node<unknown>, (state: NodeRestoreState) => void>();\nconst runtimeReleasers = new WeakMap<Node<unknown>, () => void>();\nconst runtimeQuiescenceReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst subscriberCountReaders = new WeakMap<Node<unknown>, () => number>();\nconst activationReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst releasedNodes = new WeakSet<Node<unknown>>();\n\n/** @internal Run a Node/StateNode constructor against a graph-local core without widening the public constructor. */\nexport function withNodeCore<TNode extends Node<unknown>>(\n\tcore: NodeCore,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingCore;\n\tconstructingCore = core;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingCore = prev;\n\t}\n}\n\n/** @internal Run a Node/StateNode constructor with graph-owned environment drivers (D130/D131). */\nexport function withEnvironmentDrivers<TNode extends Node<unknown>>(\n\tenvironment: EnvironmentDrivers,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingEnvironment;\n\tconstructingEnvironment = environment;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingEnvironment = prev;\n\t}\n}\n\n/** @internal Graph-domain ownership token for D22 intra-graph guards. */\nexport function getNodeOwner(n: Node<unknown>): unknown {\n\treturn ownerTokens.get(n);\n}\n\n/** @internal Assign graph-domain ownership after graph registration. */\nexport function setNodeOwner(n: Node<unknown>, owner: unknown): void {\n\townerTokens.set(n, owner);\n}\n\n/** @internal Graph-layer D145 topology egress hook. */\nexport function setNodeTopologyDepsChangedObserver(\n\tn: Node<unknown>,\n\tobserver: TopologyDepsChangedObserver,\n): void {\n\ttopologyDepsChangedObservers.set(n, observer);\n}\n\nfunction notifyTopologyDepsChanged(\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n): void {\n\ttopologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);\n}\n\n/** @internal Graph checkpoint inspection, kept as a module helper so Node stays method-thin. */\nexport function checkpointStateOfNode(n: Node<unknown>): NodeCheckpointState {\n\tconst read = checkpointReaders.get(n);\n\tif (read === undefined) throw new Error(\"checkpoint: unknown node state\");\n\treturn read();\n}\n\n/** @internal D94 restore commit: install runtime state without a protocol wave or subscription. */\nexport function restoreStateOfNode(n: Node<unknown>, state: NodeRestoreState): void {\n\tconst write = restoreWriters.get(n);\n\tif (write === undefined) throw new Error(\"restoreGraph: unknown node state\");\n\twrite(state);\n}\n\n/** @internal D122 graph-owned ephemeral lifecycle release. */\nexport function releaseRuntimeOfNode(n: Node<unknown>): void {\n\truntimeReleasers.get(n)?.();\n}\n\n/** @internal D124 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeQuiescentForRelease(n: Node<unknown>): boolean {\n\treturn runtimeQuiescenceReaders.get(n)?.() ?? false;\n}\n\n/** @internal D124 graph-owned release subscriber accounting. */\nexport function subscriberCountOfNode(n: Node<unknown>): number {\n\treturn subscriberCountReaders.get(n)?.() ?? 0;\n}\n\n/** @internal D124 graph-owned release internal-subscriber accounting. */\nexport function isNodeActiveForRelease(n: Node<unknown>): boolean {\n\treturn activationReaders.get(n)?.() ?? false;\n}\n\n/** @internal D122 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeReleased(n: Node<unknown>): boolean {\n\treturn releasedNodes.has(n);\n}\n\nfunction terminalView(t: unknown): unknown {\n\treturn t === undefined ? false : t;\n}\n\nfunction normalizePullDemand(demand: PullDemand): PullDemand {\n\tif (typeof demand !== \"object\" || demand === null || Array.isArray(demand)) {\n\t\tthrow new Error(\"ctx.up: PULL requires { pullId, params? } demand payload (D269)\");\n\t}\n\tconst pullId = (demand as { pullId?: unknown }).pullId;\n\tif (typeof pullId !== \"string\" && typeof pullId !== \"symbol\") {\n\t\tthrow new Error(\"ctx.up: PULL demand requires a string or symbol pullId (D269)\");\n\t}\n\tconst params = (demand as { params?: unknown }).params;\n\treturn params === undefined ? { pullId } : { pullId, params };\n}\n\nfunction validateDownPayloads(msgs: Wave): void {\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"DATA\" && m[1] === undefined) {\n\t\t\tthrow new Error(\"down: DATA requires a non-SENTINEL payload (R-data-payload)\");\n\t\t}\n\t\tif (m[0] === \"ERROR\" && isInvalidErrorPayload(m[1])) {\n\t\t\tthrow new Error(\"down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)\");\n\t\t}\n\t}\n}\n\n/** A queued deferred self-rewire op (R-rewire-deferred / D47), drained at the wave boundary. */\ntype RewireOp =\n\t| { kind: \"add\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"remove\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"set\"; deps: Node<unknown>[]; fn: NodeFn };\n\n/** Internal routing state for one up-going control wave. */\ntype UpRouteState = {\n\tdemandFired: Map<LockId, Set<Node<unknown>>>;\n};\n\nexport class Node<T = unknown> {\n\tprivate readonly _core: NodeCore;\n\tprivate readonly _id: NodeId;\n\tprivate readonly _slot: NodeSlot<T>;\n\tprivate readonly _dep: DepBookkeeping;\n\tprivate readonly _value: ValueState<T>;\n\tprivate readonly _wave: WaveState;\n\tprivate readonly _control: ControlState;\n\tprivate readonly _lifecycle: LifecycleState;\n\tprivate readonly _privateState: PrivateState;\n\tprivate readonly _hooks: CleanupHooks;\n\tprivate readonly _syncCtxState: SyncCtxState;\n\tprivate readonly _version: VersionState;\n\tprivate _restoredActivationPending = false;\n\tprivate _released = false;\n\n\tprivate get _syncCtx(): Ctx | null {\n\t\treturn this._syncCtxState.value;\n\t}\n\n\tprivate set _syncCtx(ctx: Ctx | null) {\n\t\tthis._syncCtxState.value = ctx;\n\t}\n\n\tconstructor(\n\t\tdeps: Node<unknown>[],\n\t\thandleOrFn: Handle | NodeFn | null,\n\t\topts: NodeOptions<T> = {},\n\t) {\n\t\tconst core = constructingCore;\n\t\tconstructingCore = undefined;\n\t\tconst dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tconst environment = constructingEnvironment ?? EnvironmentDrivers.empty();\n\t\tconstructingEnvironment = undefined;\n\t\tconst pool = opts.pool ?? \"sync\";\n\t\tconst pausable = opts.pausable ?? true;\n\t\tconst pullLock = opts.pullId;\n\t\tconst pull = opts.pullId !== undefined;\n\t\t// R-pull (D269): pull-mode is keyed by an author-supplied pullId (its quiet latch).\n\t\t// R-pull (D55, pin 3): pull still uses the pausable delivery-content axis; pausable:false\n\t\t// ignores PAUSE/RESUME buffering and contradicts quiet pull delivery. Reject at construction.\n\t\tif (pull && pausable === false)\n\t\t\tthrow new Error(\n\t\t\t\t\"node: pullId is incompatible with pausable:false — a pull node uses the pausable delivery-content axis (R-pull / R-pause-modes / D55,D269)\",\n\t\t\t);\n\n\t\tlet handle: Handle | null;\n\t\tif (handleOrFn === null) handle = null;\n\t\telse if (typeof handleOrFn === \"function\") handle = dispatcher.register(handleOrFn, pool);\n\t\telse handle = handleOrFn;\n\n\t\tconst n = deps.length;\n\t\tconst dep = makeDepBookkeeping(n);\n\t\tconst versioning = resolveNodeVersioningPolicy(opts.versioning);\n\t\tconst value = {\n\t\t\tcache: SENTINEL as T | undefined,\n\t\t\thasData: false,\n\t\t\tstatus: \"sentinel\" as Status,\n\t\t\tterminal: undefined,\n\t\t\thasTorndown: false,\n\t\t\treplayRing: [] as T[],\n\t\t};\n\t\tif (opts.initial !== undefined) {\n\t\t\tvalue.cache = opts.initial as T;\n\t\t\tvalue.hasData = true;\n\t\t\tvalue.status = \"settled\";\n\t\t}\n\t\tconst pauseLockset = new Set<unknown>();\n\t\tthis._core = core ?? new NodeCore();\n\t\tconst created = this._core.createSlot<T>(\n\t\t\t{\n\t\t\t\tdeps,\n\t\t\t\thandle,\n\t\t\t\tpool,\n\t\t\t\tdispatcher,\n\t\t\t\tenvironment,\n\t\t\t\tpartial: opts.partial ?? false,\n\t\t\t\tterminalAsRealInput: opts.terminalAsRealInput ?? false,\n\t\t\t\tcompleteWhenDepsComplete: opts.completeWhenDepsComplete ?? true,\n\t\t\t\terrorWhenDepsError: opts.errorWhenDepsError ?? true,\n\t\t\t\tresubscribable: opts.resubscribable ?? false,\n\t\t\t\tresetOnTeardown: opts.resetOnTeardown ?? false,\n\t\t\t\tpausable,\n\t\t\t\tpull,\n\t\t\t\tpullLock,\n\t\t\t\treplayN: opts.replayBuffer ?? 0,\n\t\t\t\tdynamic: opts.dynamic ?? false,\n\t\t\t\tname: opts.name,\n\t\t\t\tfactory: opts.factory,\n\t\t\t},\n\t\t\t{\n\t\t\t\tdep,\n\t\t\t\tlifecycle: { subscribers: new Set<Sink>(), activated: false },\n\t\t\t\tvalue,\n\t\t\t\twave: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\thasCalledFnOnce: false,\n\t\t\t\t\temittedDirtyThisWave: false,\n\t\t\t\t\temittedSettleThisWave: false,\n\t\t\t\t\tinsideRunWave: false,\n\t\t\t\t\tinDepMutation: false,\n\t\t\t\t\trewireRunPending: false,\n\t\t\t\t\tbatchDirtyOwed: false,\n\t\t\t\t},\n\t\t\t\tcontrol: {\n\t\t\t\t\tpauseLockset,\n\t\t\t\t\tpausedDepWaveOccurred: false,\n\t\t\t\t\tpauseBuffer: [],\n\t\t\t\t\tdemandOwed: undefined,\n\t\t\t\t\tactivePull: undefined,\n\t\t\t\t\tpullDirtyOwed: false,\n\t\t\t\t\tinDeliverDemand: false,\n\t\t\t\t},\n\t\t\t\tprivateState: { value: SENTINEL, persist: false },\n\t\t\t\thooks: { onDeactivation: [], onInvalidate: [] },\n\t\t\t\tsyncCtx: { value: null },\n\t\t\t\tversion: {\n\t\t\t\t\tpolicy: versioning,\n\t\t\t\t\tvalue: createNodeVersion(\n\t\t\t\t\t\tversioning,\n\t\t\t\t\t\topts.initial !== undefined ? opts.initial : undefined,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tthis._id = created.id;\n\t\tthis._slot = this._core.get<T>(this._id);\n\t\tthis._dep = this._core.getDep(this._id);\n\t\tthis._value = this._core.getValue<T>(this._id);\n\t\tthis._wave = this._core.getWave(this._id);\n\t\tthis._control = this._core.getControl(this._id);\n\t\tthis._lifecycle = this._core.getLifecycle(this._id);\n\t\tthis._privateState = this._core.getPrivateState(this._id);\n\t\tthis._hooks = this._core.getHooks(this._id);\n\t\tthis._syncCtxState = this._core.getSyncCtx(this._id);\n\t\tthis._version = this._core.getVersion(this._id);\n\t\tcheckpointReaders.set(this as Node<unknown>, () => ({\n\t\t\tcache: this._value.cache,\n\t\t\thasData: this._value.hasData,\n\t\t\tterminal: this._value.terminal,\n\t\t\tactivated: this._lifecycle.activated,\n\t\t\thasCalledFnOnce: this._wave.hasCalledFnOnce,\n\t\t\tctxState: {\n\t\t\t\tvalue: this._privateState.value,\n\t\t\t\tpersist: this._privateState.persist,\n\t\t\t},\n\t\t\tversion: cloneNodeVersion(this._version.value),\n\t\t\thandle: this._slot.handle,\n\t\t}));\n\t\trestoreWriters.set(this as Node<unknown>, (state) => {\n\t\t\tthis._assertNotReleased(\"restoreGraph\");\n\t\t\tthis._value.cache = state.cache as T;\n\t\t\tthis._value.hasData = state.hasData;\n\t\t\tthis._value.status = state.status;\n\t\t\tthis._value.terminal = state.terminal;\n\t\t\tthis._value.hasTorndown = false;\n\t\t\tthis._value.replayRing = [];\n\t\t\tthis._wave.hasCalledFnOnce = state.hasCalledFnOnce;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._wave.emittedSettleThisWave = false;\n\t\t\tthis._wave.pending = 0;\n\t\t\tthis._wave.insideRunWave = false;\n\t\t\tthis._wave.inDepMutation = false;\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t\tthis._control.pauseLockset.clear();\n\t\t\tthis._privateState.value = state.ctxState.value;\n\t\t\tthis._privateState.persist = state.ctxState.persist;\n\t\t\tif (state.version === false) {\n\t\t\t\tthis._version.policy = { enabled: false };\n\t\t\t\tthis._version.value = undefined;\n\t\t\t} else if (state.version.level === 0) {\n\t\t\t\tthis._version.policy = { enabled: true, level: 0 };\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t} else {\n\t\t\t\tif (!this._version.policy.enabled || this._version.policy.level !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// D109: V1 restore must match the selected hash lane. After DATA then\n\t\t\t\t// INVALIDATE/resetOnTeardown, cache is absent while cid remains the last DATA cid;\n\t\t\t\t// without the DATA value, restore cannot verify the lane, so fail honestly.\n\t\t\t\tif (!state.hasData && state.version.counter > 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);\n\t\t\t\tif (expectedCid !== state.version.cid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t}\n\t\t\tthis._syncCtx = null;\n\t\t\tthis._resetDepState();\n\t\t\t// A fresh restored graph has no subscribers before return. Keep activation closed so the\n\t\t\t// first real subscriber wires deps normally; D94's preserved lifecycle bit is the first-run\n\t\t\t// gate (`hasCalledFnOnce`), not a hidden subscription graph.\n\t\t\tthis._lifecycle.activated = false;\n\t\t\tthis._lifecycle.subscribers.clear();\n\t\t\tthis._restoredActivationPending = true;\n\t\t});\n\t\truntimeReleasers.set(this as Node<unknown>, () => this._releaseRuntime());\n\t\truntimeQuiescenceReaders.set(this as Node<unknown>, () => this._isRuntimeQuiescentForRelease());\n\t\tsubscriberCountReaders.set(this as Node<unknown>, () => this._subscriberCount());\n\t\tactivationReaders.set(this as Node<unknown>, () => this._lifecycle.activated);\n\t}\n\n\t/** R-pull (D55/D272): true while a pull node is not serving a PULL demand pulse. */\n\tprivate _isPullQuiet(): boolean {\n\t\treturn this._slot.pull && this._control.activePull === undefined;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): this pull node's pullId (pure data, like {@link cache}/{@link handle} —\n\t * never triggers computation). A consumer demands one delivery by cone-routing PULL of it (no\n\t * node reference): `ctx.up([[\"PULL\", { pullId }]])` (immediate; loops back → D37 for a self-read\n\t * dep) or `ctx.upNext([[\"PULL\", { pullId }]])` (boundary-deferred self-demand). Undefined for a\n\t * non-pull node. The author writes the pullId verbatim; routing matches by identity.\n\t */\n\tget pullId(): LockId | undefined {\n\t\treturn this._slot.pullLock;\n\t}\n\n\tget cache(): T | undefined {\n\t\treturn this._value.cache;\n\t}\n\n\tget status(): Status {\n\t\treturn this._value.status;\n\t}\n\n\tget version(): NodeVersion | undefined {\n\t\treturn cloneNodeVersion(this._version.value);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._slot.name;\n\t}\n\n\t/** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */\n\tget factory(): string | undefined {\n\t\treturn this._slot.factory;\n\t}\n\n\t/**\n\t * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the\n\t * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a\n\t * construction-time snapshot) so every edge corresponds to a real current subscription (D3).\n\t * Inspection-only, like cache/status; never triggers computation.\n\t */\n\tget deps(): readonly Node<unknown>[] {\n\t\treturn this._slot.deps;\n\t}\n\n\t/**\n\t * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough\n\t * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph\n\t * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node\n\t * (R-node-thin / D39).\n\t */\n\tget handle(): Handle | null {\n\t\treturn this._slot.handle;\n\t}\n\n\t/** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */\n\tsubscribe(sink: Sink): () => void {\n\t\tthis._assertNotReleased(\"subscribe\");\n\t\t// Wave-owner boundary (R-rewire-deferred / D47): the activation cascade can run fns that\n\t\t// issue ctx.rewireNext; the OUTERMOST exit drains them. Nested subscribes (dep wiring)\n\t\t// just inc/dec the depth.\n\t\tenterWave();\n\t\ttry {\n\t\t\t// R-terminal: late subscribe to a terminal node either resets (resubscribable)\n\t\t\t// or is rejected (non-resubscribable, R2.2.7.b).\n\t\t\tif (this._value.terminal !== undefined) {\n\t\t\t\tif (this._slot.resubscribable) {\n\t\t\t\t\tthis._restoredActivationPending = false;\n\t\t\t\t\tthis._resetLifecycle();\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)\",\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis._lifecycle.subscribers.add(sink);\n\t\t\tsink([\"START\"]);\n\t\t\tif (this._slot.replayN > 0 && this._value.replayRing.length > 0) {\n\t\t\t\t// R-replay-buffer: late subscriber gets the last N DATA after START.\n\t\t\t\tfor (const v of this._value.replayRing) sink([\"DATA\", v]);\n\t\t\t} else if (this._value.hasData && !this._slot.pull) {\n\t\t\t\t// R-pull (D55): a pull node NEVER push-on-subscribes its cached value — quiet by\n\t\t\t\t// default, it stays silent until demanded (START only). QA-B4: gated on `_pull`, not\n\t\t\t\t// activePull, so a REACTIVATED pull node still does not leak its cache.\n\t\t\t\tsink([\"DATA\", this._value.cache]);\n\t\t\t} else if (this._value.status === \"dirty\" && !this._slot.pull) {\n\t\t\t\tsink([\"DIRTY\"]);\n\t\t\t}\n\n\t\t\tif (!this._lifecycle.activated) this._activate();\n\n\t\t\treturn () => {\n\t\t\t\tif (!this._lifecycle.subscribers.delete(sink)) return;\n\t\t\t\tif (this._lifecycle.subscribers.size === 0) this._deactivate();\n\t\t\t};\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */\n\tdown(msgs: Wave): void {\n\t\tthis._assertNotReleased(\"down\");\n\t\t// Wave-owner boundary (D47): a state.set / external push that drives a fn issuing\n\t\t// ctx.rewireNext drains at this outermost exit.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._down(msgs);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up\n\t * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t */\n\tup(msgs: Wave, towardDep?: number): void {\n\t\tthis._assertNotReleased(\"up\");\n\t\t// Wave-owner boundary (D47). Internal dep-forwarding calls dep.up() nest under this.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._up(msgs, towardDep);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t// ── deferred self-rewire (R-rewire-deferred / D47): ctx.rewireNext drain support ──\n\n\t/**\n\t * Enqueue a deferred self-rewire op (issued from this node's fn via `ctx.rewireNext`).\n\t * Applied at the committed wave boundary (boundary.ts drain), never in place — the in-fn\n\t * immediate path (`subscribeDep`/`replaceDeps`/`unsubscribeDep`) still throws mid-run (D37/R-reentrancy).\n\t */\n\tprivate _requestRewireNext(op: RewireOp): void {\n\t\tdeferRewire(this._core, () => this._applyRewireNext(op), {\n\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n\n\t/**\n\t * Enqueue a deferred up-going control/demand wave (R-up-routing / R-pull / D269): at the committed wave\n\t * boundary, route `msgs` up from THIS node (broadcast, or up the single `towardDep` edge). The\n\t * deferred form of `ctx.up` — the SELF-demand path: a consumer issues `ctx.upNext([[PULL,\n\t * { pullId }]])` to demand a dep it ALSO reads; the demand applies at the boundary (not mid-fn), so\n\t * the pull node's delivery loops back as a FRESH wave rather than re-entering the consumer (D37 /\n\t * R-reentrancy). Rides the same R-rewire-deferred (D47) drain as ctx.rewireNext.\n\t */\n\tprivate _requestUpNext(msgs: Wave, towardDep?: number): void {\n\t\tdeferRewire(\n\t\t\tthis._core,\n\t\t\t() => {\n\t\t\t\tif (!this._released) this._up(msgs, towardDep);\n\t\t\t},\n\t\t\t{\n\t\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Apply one queued self-rewire at the boundary (drain thunk). */\n\tprivate _applyRewireNext(op: RewireOp): void {\n\t\tif (this._released) return;\n\t\ttry {\n\t\t\t// D62 / R-rewire-deferred: terminal seals output but does NOT cancel queued topology.\n\t\t\t// Public/immediate rewire of a terminal node still rejects; the exception is only for\n\t\t\t// self-triggered ops already issued before terminal and now draining at the boundary.\n\t\t\tif (op.kind === \"add\") {\n\t\t\t\tconst next = this._slot.deps.includes(op.dep)\n\t\t\t\t\t? [...this._slot.deps]\n\t\t\t\t\t: [...this._slot.deps, op.dep];\n\t\t\t\tthis._rewire(next, op.fn, { allowTerminalOwner: true });\n\t\t\t} else if (op.kind === \"remove\") {\n\t\t\t\tthis._rewire(\n\t\t\t\t\tthis._slot.deps.filter((d) => d !== op.dep),\n\t\t\t\t\top.fn,\n\t\t\t\t\t{ allowTerminalOwner: true },\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis._rewire(this._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// An invalid deferred op (cycle / self / non-resubscribable terminal dep) surfaces as\n\t\t\t// an ERROR on this node (D30-consistent) rather than stranding the rest of the drain\n\t\t\t// queue. Reachable only on misuse — higher-order operator inners are fresh, acyclic\n\t\t\t// leaf sources. Coerce a SENTINEL reason (a rewire fn that `throw undefined`s) to a real\n\t\t\t// Error so _down's R-data-payload guard does not itself throw out of the drain.\n\t\t\tthis._down([[\"ERROR\", errorPayload(e, \"rewireNext op failed\")]]);\n\t\t}\n\t}\n\n\t// ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──\n\n\t/**\n\t * Replace this node's deps atomically (surgical, Option-C). Requires an explicit\n\t * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps\n\t * keep their subscription + per-dep state; only removed deps unsubscribe and only\n\t * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The\n\t * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).\n\t */\n\treplaceDeps(newDeps: Node<unknown>[], fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"replaceDeps\");\n\t\tthis._rewire(this._dedupDeps(newDeps), fn);\n\t}\n\n\t/** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */\n\tsubscribeDep(depNode: Node<unknown>, fn: NodeFn): number {\n\t\tthis._assertNotReleased(\"subscribeDep\");\n\t\tconst next = this._slot.deps.includes(depNode)\n\t\t\t? [...this._slot.deps]\n\t\t\t: [...this._slot.deps, depNode];\n\t\tconst deferred = this._rewire(next, fn);\n\t\treturn deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);\n\t}\n\n\t/** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */\n\tunsubscribeDep(depNode: Node<unknown>, fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"unsubscribeDep\");\n\t\tthis._rewire(\n\t\t\tthis._slot.deps.filter((d) => d !== depNode),\n\t\t\tfn,\n\t\t);\n\t}\n\n\tprivate _dedupDeps(deps: Node<unknown>[]): Node<unknown>[] {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst out: Node<unknown>[] = [];\n\t\tfor (const d of deps)\n\t\t\tif (!seen.has(d)) {\n\t\t\t\tseen.add(d);\n\t\t\t\tout.push(d);\n\t\t\t}\n\t\treturn out;\n\t}\n\n\t/** Is `target` reachable upstream from `from` (following deps)? Cycle-prevention DFS. */\n\tprivate _reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst stack: Node<unknown>[] = [from];\n\t\twhile (stack.length > 0) {\n\t\t\tconst n = stack.pop();\n\t\t\tif (n === undefined) continue;\n\t\t\tif (n === target) return true;\n\t\t\tif (seen.has(n)) continue;\n\t\t\tseen.add(n);\n\t\t\tfor (const d of n._slot.deps) stack.push(d);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _assertRewireDepOwner(dep: Node<unknown>): void {\n\t\tconst selfOwner = getNodeOwner(this as unknown as Node<unknown>);\n\t\tconst depOwner = getNodeOwner(dep);\n\t\tif (selfOwner !== undefined && depOwner !== undefined && selfOwner !== depOwner) {\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _rewire(\n\t\tnewDeps: Node<unknown>[],\n\t\tfn: NodeFn,\n\t\topts: { allowTerminalOwner?: boolean } = {},\n\t): boolean {\n\t\t// ── rejects (R-rewire / D42) ──\n\t\tif (this._value.terminal !== undefined && !opts.allowTerminalOwner)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: node is terminal (completed/errored) — cannot rewire (R-rewire / D42)\",\n\t\t\t);\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: mid-fn topology mutation — a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)\",\n\t\t\t);\n\t\tif (this._wave.inDepMutation)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: reentrant dep mutation — another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)\",\n\t\t\t);\n\t\tif (newDeps.includes(this as unknown as Node<unknown>))\n\t\t\tthrow new Error(\"rewire: self-dependency rejected (R-rewire / D42)\");\n\t\tconst oldDeps = this._slot.deps;\n\t\tconst added = newDeps.filter((d) => !oldDeps.includes(d));\n\t\tfor (const d of added) {\n\t\t\tif (this._reachableUpstream(d, this as unknown as Node<unknown>))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: would create a cycle — dep already transitively depends on this node (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tif (d._value.terminal !== undefined && !d._slot.resubscribable)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: cannot add a non-resubscribable terminal dep — would wedge (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tthis._assertRewireDepOwner(d);\n\t\t}\n\n\t\tif (\n\t\t\tdeferAfterBatchForTarget(this, () => {\n\t\t\t\tthis._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });\n\t\t\t})\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!this._lifecycle.activated) this._restoredActivationPending = false;\n\n\t\tthis._wave.inDepMutation = true;\n\t\tthis._wave.rewireRunPending = false;\n\t\tlet zeroDepUnDirty = false;\n\t\ttry {\n\t\t\t// fn swap (SD-1): re-register against the same pool, then release the old handle\n\t\t\t// (B15) so the rewired-away fn closure is GC'd and its dispatcher slot is reused —\n\t\t\t// a rewire-heavy graph (CSP-2.7 *Map) no longer leaks a handle per swap. Register\n\t\t\t// first, then unregister the old: this._slot.handle never points at a freed slot, and a\n\t\t\t// null old handle (a passthrough/state node gaining a fn) has nothing to free.\n\t\t\tconst oldHandle = this._slot.handle;\n\t\t\tthis._slot.handle = this._slot.dispatcher.register(fn, this._slot.pool);\n\t\t\tif (oldHandle !== null) this._slot.dispatcher.unregister(oldHandle);\n\n\t\t\tconst removed = oldDeps.filter((d) => !newDeps.includes(d));\n\t\t\tlet removedDirtyContributor = false;\n\t\t\tfor (const d of removed) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(d);\n\t\t\t\tif (this._dep.dirty[oldIdx]) {\n\t\t\t\t\tremovedDirtyContributor = true;\n\t\t\t\t\tthis._wave.pending--;\n\t\t\t\t}\n\t\t\t\tif (this._lifecycle.activated) {\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = -1; // drain: any stale in-flight callback drops\n\t\t\t\t\tconst unsub = this._dep.unsubs[oldIdx];\n\t\t\t\t\tif (unsub) unsub(); // stops the removed dep's edge — no further delivery\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rebuild per-dep parallel arrays in newDeps order; kept deps carry their state\n\t\t\t// + subscription, added deps start fresh (R-rewire Q1/Q4).\n\t\t\tconst n = newDeps.length;\n\t\t\tconst newBatch: Array<unknown[] | null> = new Array(n).fill(null);\n\t\t\tconst newPrev: unknown[] = new Array(n).fill(SENTINEL);\n\t\t\tconst newHasData: boolean[] = new Array(n).fill(false);\n\t\t\tconst newDirty: boolean[] = new Array(n).fill(false);\n\t\t\tconst newTier: number[] = new Array(n).fill(0);\n\t\t\tconst newTerminal: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newTerminalInput: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newUnsubs: Array<() => void> = new Array(n);\n\t\t\tconst newBoxes: Array<{ v: number }> = new Array(n);\n\t\t\tfor (let j = 0; j < n; j++) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(newDeps[j]);\n\t\t\t\tif (oldIdx !== -1) {\n\t\t\t\t\tnewBatch[j] = this._dep.batch[oldIdx];\n\t\t\t\t\tnewPrev[j] = this._dep.prev[oldIdx];\n\t\t\t\t\tnewHasData[j] = this._dep.hasData[oldIdx];\n\t\t\t\t\tnewDirty[j] = this._dep.dirty[oldIdx];\n\t\t\t\t\tnewTier[j] = this._dep.tier[oldIdx];\n\t\t\t\t\tnewTerminal[j] = this._dep.terminal[oldIdx];\n\t\t\t\t\tnewUnsubs[j] = this._dep.unsubs[oldIdx];\n\t\t\t\t\t// carry the kept dep's subscription box and point it at the new index (O(1) reroute)\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = j;\n\t\t\t\t\tnewBoxes[j] = box;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._slot.deps = newDeps;\n\t\t\tthis._dep.batch = newBatch;\n\t\t\tthis._dep.prev = newPrev;\n\t\t\tthis._dep.hasData = newHasData;\n\t\t\tthis._dep.dirty = newDirty;\n\t\t\tthis._dep.tier = newTier;\n\t\t\tthis._dep.terminal = newTerminal;\n\t\t\tthis._dep.terminalInput = newTerminalInput;\n\t\t\tthis._dep.unsubs = newUnsubs;\n\t\t\tthis._dep.idxBoxes = newBoxes;\n\t\t\tthis._dep.waveData = newDeps.map(() => []);\n\t\t\tthis._dep.waveTokens = new Array(newDeps.length).fill(undefined);\n\t\t\tthis._syncCtx = null;\n\n\t\t\t// Subscribe added deps — push-on-subscribe (R-push-subscribe) delivers a cached\n\t\t\t// dep's DATA here, which drives _maybeRun; a SENTINEL dep delivers START only.\n\t\t\tif (this._lifecycle.activated) {\n\t\t\t\tfor (const d of added) this._subscribeDepAt(d);\n\t\t\t}\n\t\t\tnotifyTopologyDepsChanged(this as unknown as Node<unknown>, oldDeps, newDeps);\n\n\t\t\t// Q6 auto-settle: removing the sole dirty contributor closes the wave. With deps\n\t\t\t// remaining, request the atomic settle (recompute → DATA for a value; a no-emit fn\n\t\t\t// gets a substrate-synthesized undirty RESOLVED per R-resolved-undirty/D49 — NOT\n\t\t\t// equals-absorption, which is gone). With zero deps the node is inert (degenerate\n\t\t\t// fn-no-deps) — just un-dirty downstream. Cache is preserved either way (Q7).\n\t\t\tif (removedDirtyContributor && this._wave.pending === 0 && this._value.status === \"dirty\") {\n\t\t\t\tif (newDeps.length > 0) this._wave.rewireRunPending = true;\n\t\t\t\telse zeroDepUnDirty = true;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._wave.inDepMutation = false;\n\t\t}\n\n\t\t// Atomic post-mutation settle (outside the reentrancy guard so a fresh wave runs\n\t\t// normally): ONE two-phase DIRTY→DATA recompute if any added dep delivered data or a\n\t\t// sole-dirty dep was removed; else the zero-dep un-dirty via _down (pause/batch-safe).\n\t\tif (this._wave.rewireRunPending) {\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._settleRewire();\n\t\t} else if (zeroDepUnDirty) {\n\t\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t\t\telse this._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\treturn false;\n\t}\n\n\t// ── activation / deactivation (lazy; R-rom-ram) ──\n\n\tprivate _activate(): void {\n\t\tthis._lifecycle.activated = true;\n\t\tconst seedRestoredDeps = this._restoredActivationPending;\n\t\tthis._restoredActivationPending = false;\n\t\t// R-pull (D55/D272): activePull is undefined before wiring deps, so each dep's\n\t\t// push-on-subscribe DIRTY/DATA is absorbed quietly, not relayed downstream.\n\t\tthis._dep.unsubs = new Array(this._slot.deps.length);\n\t\tthis._dep.idxBoxes = new Array(this._slot.deps.length);\n\t\tfor (const dep of this._slot.deps)\n\t\t\tthis._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });\n\t\t// Depless producer (fn, no deps): run once on activation.\n\t\tif (this._slot.deps.length === 0 && this._slot.handle !== null && !this._wave.hasCalledFnOnce) {\n\t\t\tthis._runWave();\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to a dep. The dispatch callback reads the dep's CURRENT index from a\n\t * mutable box (O(1)); a surgical rewire that reorders kept deps just updates the box\n\t * (R-rewire Option-C / D42) — no re-subscribe, no per-message indexOf scan. A removed\n\t * dep's box is set to -1 so any stale in-flight callback drops (drain).\n\t */\n\tprivate _subscribeDepAt(depNode: Node<unknown>, opts: { seedRestored?: boolean } = {}): void {\n\t\tconst idx0 = this._slot.deps.indexOf(depNode);\n\t\tconst box = { v: idx0 };\n\t\tlet ignoreInitialPush = opts.seedRestored === true;\n\t\tif (ignoreInitialPush && idx0 !== -1) {\n\t\t\tthis._seedRestoredDepAt(idx0, depNode);\n\t\t\tif (depNode._value.terminal !== undefined && !depNode._slot.resubscribable) {\n\t\t\t\tthis._dep.unsubs[idx0] = () => {};\n\t\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst unsub = depNode.subscribe((msg, delivery) => {\n\t\t\tif (ignoreInitialPush && delivery === undefined) return;\n\t\t\tif (ignoreInitialPush) ignoreInitialPush = false;\n\t\t\tif (box.v === -1) return; // dep removed — stale callback, drop (drain)\n\t\t\tthis._receiveFromDep(box.v, msg, delivery);\n\t\t});\n\t\tif (ignoreInitialPush && idx0 !== -1 && box.v !== -1) this._seedRestoredDepAt(idx0, depNode);\n\t\tignoreInitialPush = false;\n\t\tif (idx0 !== -1) {\n\t\t\tthis._dep.unsubs[idx0] = unsub;\n\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t}\n\t}\n\n\tprivate _seedRestoredDepAt(idx: number, depNode: Node<unknown>): void {\n\t\tconst seedData = depNode._value.hasData && !depNode._slot.pull;\n\t\tthis._dep.batch[idx] = null;\n\t\tthis._dep.waveData[idx] = [];\n\t\tthis._dep.waveTokens[idx] = undefined;\n\t\tthis._dep.prev[idx] = seedData ? depNode._value.cache : SENTINEL;\n\t\tthis._dep.hasData[idx] = seedData;\n\t\tthis._dep.dirty[idx] = false;\n\t\tthis._dep.tier[idx] = seedData ? 3 : 0;\n\t\tthis._dep.terminal[idx] = depNode._value.terminal;\n\t\tthis._dep.terminalInput[idx] = undefined;\n\t}\n\n\tprivate _deactivate(): void {\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tfor (const fn of this._hooks.onDeactivation) fn();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\t// RAM: compute nodes clear cache; reconnect re-runs fn fresh.\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t}\n\t\tthis._resetDepState();\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._value.replayRing = []; // BH6: don't replay stale values to a post-reactivation subscriber\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _assertNotReleased(op: string): void {\n\t\tif (this._released)\n\t\t\tthrow new Error(`${op}: node has been released from its graph lifecycle (D122)`);\n\t}\n\n\tprivate _subscriberCount(): number {\n\t\treturn this._lifecycle.subscribers.size;\n\t}\n\n\tprivate _isRuntimeQuiescentForRelease(): boolean {\n\t\treturn (\n\t\t\t!this._released &&\n\t\t\tthis._value.status !== \"dirty\" &&\n\t\t\tthis._value.status !== \"pending\" &&\n\t\t\tthis._wave.pending === 0 &&\n\t\t\t!this._wave.insideRunWave &&\n\t\t\t!this._wave.inDepMutation &&\n\t\t\t!this._wave.rewireRunPending &&\n\t\t\t!this._wave.batchDirtyOwed &&\n\t\t\tthis._dep.dirty.every((dirty) => !dirty) &&\n\t\t\tthis._control.pauseBuffer.length === 0 &&\n\t\t\t!this._control.pausedDepWaveOccurred &&\n\t\t\tthis._control.demandOwed === undefined &&\n\t\t\tthis._control.activePull === undefined &&\n\t\t\t!this._control.inDeliverDemand &&\n\t\t\tthis._control.pauseLockset.size === 0\n\t\t);\n\t}\n\n\tprivate _releaseRuntime(): void {\n\t\tif (this._released) return;\n\t\tthis._released = true;\n\t\treleasedNodes.add(this as Node<unknown>);\n\t\tlet releaseError: unknown;\n\t\tconst recordReleaseError = (error: unknown): void => {\n\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t};\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) {\n\t\t\ttry {\n\t\t\t\tu();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release is graph-owned and atomic; user cleanup must not split commit.\n\t\t\t}\n\t\t}\n\t\tfor (const fn of this._hooks.onDeactivation) {\n\t\t\ttry {\n\t\t\t\tfn();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release cleans runtime without synthesizing protocol ERROR/COMPLETE.\n\t\t\t}\n\t\t}\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tif (this._slot.handle !== null) {\n\t\t\tthis._slot.dispatcher.unregister(this._slot.handle);\n\t\t\tthis._slot.handle = null;\n\t\t}\n\t\tthis._slot.deps = [];\n\t\tthis._dep.batch = [];\n\t\tthis._dep.waveData = [];\n\t\tthis._dep.waveTokens = [];\n\t\tthis._dep.prev = [];\n\t\tthis._dep.hasData = [];\n\t\tthis._dep.dirty = [];\n\t\tthis._dep.tier = [];\n\t\tthis._dep.terminal = [];\n\t\tthis._dep.terminalInput = [];\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.replayRing = [];\n\t\tthis._privateState.value = SENTINEL;\n\t\tthis._privateState.persist = false;\n\t\tthis._syncCtx = null;\n\t\tthis._resetDepState();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined;\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._restoredActivationPending = false;\n\t\tcheckpointReaders.delete(this as Node<unknown>);\n\t\trestoreWriters.delete(this as Node<unknown>);\n\t\truntimeReleasers.delete(this as Node<unknown>);\n\t\truntimeQuiescenceReaders.delete(this as Node<unknown>);\n\t\tsubscriberCountReaders.delete(this as Node<unknown>);\n\t\tactivationReaders.delete(this as Node<unknown>);\n\t\townerTokens.delete(this as Node<unknown>);\n\t\ttopologyDepsChangedObservers.delete(this as Node<unknown>);\n\t\tthis._core.releaseSlot(this._id);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\tprivate _resetDepState(): void {\n\t\tconst n = this._slot.deps.length;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.prev[i] = SENTINEL;\n\t\t\tthis._dep.hasData[i] = false;\n\t\t\tthis._dep.dirty[i] = false;\n\t\t\tthis._dep.tier[i] = 0;\n\t\t\tthis._dep.terminal[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.pending = 0;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── upstream wave receive (two-phase + diamond) ──\n\n\tprivate _recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[] {\n\t\tconst token = delivery?.wave ?? {};\n\t\tif (this._dep.waveTokens[idx] !== token) {\n\t\t\tthis._dep.waveData[idx].push([]);\n\t\t\tthis._dep.waveTokens[idx] = token;\n\t\t}\n\t\treturn this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t}\n\n\tprivate _depProjectionHasData(idx: number): boolean {\n\t\tconst projection = this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t\treturn projection?.some((v) => v !== SENTINEL) ?? false;\n\t}\n\n\tprivate _receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\tconst t = msg[0];\n\t\tif (t === \"START\") return;\n\t\tconst isLastInDeliveredWave = delivery?.last ?? true;\n\t\t// Terminal-is-forever, except terminal intermediates still relay upstream TEARDOWN\n\t\t// downstream for lifecycle unwire (R-teardown-terminal-relay / D65).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (t === \"TEARDOWN\") this._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"INVALIDATE\") {\n\t\t\tconst projection = this._recordDepProjection(idx, delivery);\n\t\t\tprojection.push(SENTINEL);\n\t\t\tif (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) this._maybeRun();\n\t\t\t// The dep's value is gone — drop our cached latest view to SENTINEL so the\n\t\t\t// never-emitted detector reads correctly, C-3) and cascade (idempotent).\n\t\t\tthis._dep.prev[idx] = SENTINEL;\n\t\t\tthis._dep.hasData[idx] = false;\n\t\t\tthis._dep.batch[idx] = null;\n\t\t\t// EC3: un-wedge the dirty bookkeeping if this dep had gone DIRTY first, so an\n\t\t\t// INVALIDATE-before-DATA doesn't strand _pending / downstream forever\n\t\t\t// (R-invalidate-idempotent — exists to prevent the wedged-DIRTY deadlock).\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\t// D50 / R-paused-invalidate: this INVALIDATE SUPERSEDES the dep's buffered\n\t\t\t// paused dep-wave (_depBatch[idx] just cleared). Re-derive the paused-recompute\n\t\t\t// flag — if no dep still carries a buffered DATA, CANCEL the paused recompute\n\t\t\t// (attributed cancellation; the node has settled to SENTINEL via its own\n\t\t\t// INVALIDATE, so a RESUME must not recompute against a now-SENTINEL dep). A\n\t\t\t// surviving dep keeps it set; a later DATA re-arms it ([DATA,INVALIDATE,DATA2]).\n\t\t\tif (this._control.pausedDepWaveOccurred && this._dep.batch.every((b) => b === null)) {\n\t\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\t}\n\t\t\tconst hadData = this._value.hasData;\n\t\t\tthis._invalidate(); // cascades INVALIDATE iff populated; no-op otherwise\n\t\t\t// If we broadcast DIRTY this wave but _invalidate produced no settle (the node\n\t\t\t// was never populated, so the cascade is suppressed per the rule), un-dirty\n\t\t\t// downstream with a RESOLVED once all deps have settled.\n\t\t\tif (this._wave.pending === 0 && this._wave.emittedDirtyThisWave) {\n\t\t\t\tif (!hadData) this._down([[\"RESOLVED\"]]);\n\t\t\t\telse this._wave.emittedDirtyThisWave = false;\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): an INVALIDATE settle can drain _pending → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (isTerminal(t)) {\n\t\t\t// Tier 5 (R-tier / D34): COMPLETE | ERROR — ONE branch routed by the CENTRAL tier table,\n\t\t\t// not a per-variant string check (feedback_use_tier_for_signal_routing). The shared terminal\n\t\t\t// bookkeeping (record the terminal + release the in-wave DIRTY) runs for ANY tier-5 message;\n\t\t\t// only the COMPLETE-vs-ERROR cascade differs, so discriminate by the type within the tier.\n\t\t\tconst isError = t === \"ERROR\";\n\t\t\tconst errPayload = isError ? (msg as readonly [\"ERROR\", unknown])[1] : undefined;\n\t\t\tthis._dep.terminal[idx] = isError ? errPayload : true;\n\t\t\tthis._dep.terminalInput[idx] = isError ? errPayload : true;\n\t\t\t// R-terminal-settles-dirty (B35): a terminal RELEASES this dep's outstanding in-wave DIRTY\n\t\t\t// contribution (the exactly-one-settle invariant) — exactly as DATA/RESOLVED/INVALIDATE do\n\t\t\t// (a dirty-then-terminal-without-DATA dep would otherwise strand _pending and wedge the node,\n\t\t\t// the deadlock R-invalidate-idempotent prevents for INVALIDATE).\n\t\t\tthis._releaseDepDirty(idx);\n\t\t\tconst ranValueBeforeTerminal = this._depProjectionHasData(idx) && isLastInDeliveredWave;\n\t\t\tif (ranValueBeforeTerminal) this._maybeRun();\n\t\t\tif (isError && this._slot.errorWhenDepsError) {\n\t\t\t\tthis._down([[\"ERROR\", errPayload]]); // auto-cascade ERROR → node itself terminal\n\t\t\t} else if (this._slot.terminalAsRealInput) {\n\t\t\t\tif (ranValueBeforeTerminal) {\n\t\t\t\t\tthis._fireOwedDemandIfReady();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis._maybeRun(); // rescue/reduce/catch/*Map: the fn reads depTerminal(ctx, idx)\n\t\t\t} else if (this._slot.completeWhenDepsComplete && this._allDepsTerminal()) {\n\t\t\t\t// R-deps-terminal auto-COMPLETE + B42: COMPLETE once ALL deps are TERMINAL (each COMPLETE\n\t\t\t\t// or an absorbed ERROR) — so an absorbed-error dep terminating LAST still fires the\n\t\t\t\t// cascade. terminalAsRealInput is checked FIRST so a rescue recovers via _maybeRun rather\n\t\t\t\t// than being preempted (no operator sets both completeWhenDepsComplete:true + tari:true).\n\t\t\t\tthis._down([[\"COMPLETE\"]]);\n\t\t\t} else {\n\t\t\t\t// absorbed terminal, NOT an input + not auto-completing: the dep's signalled change did\n\t\t\t\t// not materialise (no DATA) → un-dirty downstream, keep cache (R-resolved-undirty balance).\n\t\t\t\tthis._settleAfterAbsorbedTerminal();\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): a dep terminal can drain _pending → fire a deferred demand (no-op if this node went terminal)\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"TEARDOWN\") {\n\t\t\tthis._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DIRTY\") {\n\t\t\tif (!this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = true;\n\t\t\t\tthis._wave.pending++;\n\t\t\t\tthis._dep.tier[idx] = 2;\n\t\t\t\tthis._markDirty();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DATA\") {\n\t\t\tconst v = msg[1];\n\t\t\tthis._recordDepProjection(idx, delivery).push(v);\n\t\t\tconst b = this._dep.batch[idx];\n\t\t\tif (b === null) this._dep.batch[idx] = [v];\n\t\t\telse b.push(v);\n\t\t\tthis._dep.prev[idx] = v;\n\t\t\tthis._dep.hasData[idx] = true;\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"RESOLVED\") {\n\t\t\tthis._recordDepProjection(idx, delivery);\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\t\t// PAUSE / RESUME are not delivered downstream to a dep-subscriber; a node is\n\t\t// paused via its own up() (lockset), not by an upstream dep.\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): release a dep's outstanding in-wave DIRTY contribution.\n\t * A settle-class event for that dep (DATA/RESOLVED inline above, INVALIDATE, and now\n\t * COMPLETE/ERROR) clears its dirty flag + decrements _pending. No-op if the dep already\n\t * settled this wave (DATA/RESOLVED ran first) — so the normal DATA-then-COMPLETE flow is\n\t * unaffected. This makes the exactly-one-settle invariant a single, shared step.\n\t */\n\tprivate _releaseDepDirty(idx: number): void {\n\t\tif (this._dep.dirty[idx]) {\n\t\t\tthis._dep.dirty[idx] = false;\n\t\t\tthis._wave.pending--;\n\t\t}\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): settle a node whose dirtied dep was released by an ABSORBED\n\t * terminal that is NOT a real input (a plain derived/effect — the common default-node case when\n\t * one of several deps completes while others stay live). Runs only when the release drained\n\t * _pending while the node still owes a downstream settle (it broadcast DIRTY this wave):\n\t * - if some OTHER dep delivered real DATA this wave (a value occurred) → recompute (→ DATA);\n\t * - else the terminal's signalled change did not materialise (no value) → one undirty RESOLVED\n\t * (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t * A terminalAsRealInput node instead recomputes unconditionally (its fn reads the terminal).\n\t */\n\tprivate _settleAfterAbsorbedTerminal(): void {\n\t\tif (this._wave.pending !== 0 || !this._wave.emittedDirtyThisWave) return;\n\t\t// A real value occurred this wave (some OTHER dep delivered DATA) → recompute. _maybeRun\n\t\t// runs the fn ONLY if it's not gated (first-run gate open, not paused); it may emit DATA, a\n\t\t// fn-synthesized undirty RESOLVED, or nothing (gated / gate still holds).\n\t\tconst sawData = this._dep.batch.some((b) => b !== null && b.length > 0);\n\t\tif (sawData) this._maybeRun();\n\t\t// If after that the node STILL owes a downstream settle (no DATA occurred, OR the recompute\n\t\t// was gated — e.g. the first-run gate holds because the terminated dep never delivered and\n\t\t// terminalAsRealInput is false), balance the broadcast DIRTY with one undirty RESOLVED\n\t\t// (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t\t// Without this fallback a DIRTY-then-terminal-without-DATA dep on a pre-first-run multi-dep\n\t\t// node would strand the DIRTY → downstream wedged (the B35 class, in the gate-holds corner).\n\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t}\n\n\tprivate _markDirty(): void {\n\t\tthis._value.status = \"dirty\";\n\t\t// SPIKE (protocol-pull): while quiet, ABSORB the upstream DIRTY — do NOT relay it downstream.\n\t\t// This is the P0b wedge fix: a quiet pull node that relayed DIRTY but withheld the settle\n\t\t// (coalesced by pause) wedged every downstream's two-phase _pending. The downstream learns of\n\t\t// changes via the push STREAM port, not the silent snapshot port; on demand the pull node\n\t\t// emits a fresh wave. Internal dep dirty-accounting (the DIRTY-branch _pending++) is untouched.\n\t\tif (this._isPullQuiet()) return;\n\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._emitToSubs([\"DIRTY\"]);\n\t\t}\n\t}\n\n\tprivate _maybeRun(): void {\n\t\t// R-rewire: an added cached dep's push-on-subscribe lands here mid-mutation. Defer\n\t\t// the fn-run to ONE atomic two-phase settle after every added dep is wired, so the\n\t\t// fn never fires on a partially-populated added-dep view (multi-add) — _settleRewire\n\t\t// drains this flag.\n\t\tif (this._wave.inDepMutation) {\n\t\t\tthis._wave.rewireRunPending = true;\n\t\t\treturn;\n\t\t}\n\t\t// R-pause-modes + R-pull: while externally paused or pull-quiet, default pull mode\n\t\t// coalesces. `resumeAll` still runs so its outgoing settle slice can enter pauseBuffer.\n\t\tif (this._slot.pausable === true && (this._isPaused() || this._isPullQuiet())) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tthis._tryRun();\n\t}\n\n\t/**\n\t * R-rewire atomic settle (after a rewire that warrants a recompute): emit a proper\n\t * two-phase DIRTY→DATA wave (R-dirty-before-data — a rewire-triggered settle is a wave),\n\t * once, with every added dep already wired. Mirrors _maybeRun/_tryRun's pause + gate +\n\t * pending guards, then injects the phase-1 DIRTY the added dep's [START,DATA] handshake\n\t * did not carry.\n\t */\n\tprivate _settleRewire(): void {\n\t\tif (this._slot.pausable === true && this._isPaused()) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;\n\t\tthis._markDirty(); // phase 1 (no-op if already dirty, e.g. unsubscribeDep auto-settle)\n\t\tthis._runWave(); // phase 2: fn → DATA/RESOLVED\n\t}\n\n\tprivate _tryRun(): void {\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\t// Passthrough wire (deps, no fn): forward the latest dep DATA downstream.\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce) {\n\t\t\tif (this._slot.partial || this._allDepsSettled()) this._runWave();\n\t\t\t// else: first-run gate holds fn until every dep has settled (R-first-run-gate).\n\t\t\treturn;\n\t\t}\n\t\tthis._runWave();\n\t}\n\n\tprivate _allDepsSettled(): boolean {\n\t\tfor (let i = 0; i < this._slot.deps.length; i++) {\n\t\t\tif (this._dep.hasData[i]) continue;\n\t\t\tif (this._slot.terminalAsRealInput && this._dep.terminal[i] !== undefined) continue;\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate _passthroughEmit(): void {\n\t\t// Single-dep wire: relay dep 0's latest batch value as DATA.\n\t\tconst b = this._dep.batch[0];\n\t\tif (b !== null && b.length > 0) {\n\t\t\tthis._down([[\"DATA\", b[b.length - 1]]]);\n\t\t} else if (this._wave.emittedDirtyThisWave) {\n\t\t\t// R-resolved-undirty (D49): the dep settled via an undirty RESOLVED (no DATA in the\n\t\t\t// batch), but this wire already broadcast DIRTY downstream this wave — balance it with\n\t\t\t// a RESOLVED so downstream un-dirties instead of wedging. Routed through _down (NOT a\n\t\t\t// bare _emitToSubs) so the balance respects batch-defer (D12) + pause-buffer, matching\n\t\t\t// the zero-dep un-dirty path. Without this, a passthrough over a filter-reject /\n\t\t\t// distinctUntilChanged-dup leaves a dangling DIRTY (the wedge D49 made common).\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\t\tthis._dep.batch[0] = null;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _runWave(): void {\n\t\t// R-reentrancy (D37): a fn that re-drives its own dep mid-wave re-enters here while\n\t\t// _insideRunWave is still set — a synchronous feedback cycle. Reject (throw); the graph\n\t\t// layer catches it and converts to [[ERROR, e]] (D30). The try/finally resets the flag\n\t\t// on every frame as the throw unwinds, leaving the graph clean for the catch. Detection\n\t\t// is node-local and free — it reuses the existing _insideRunWave flag (no new structure,\n\t\t// dispatcher stays a pure funnel).\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)\",\n\t\t\t);\n\t\tthis._wave.hasCalledFnOnce = true;\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification): clear BOTH hook lists\n\t\t// before the fn runs; the fn body re-registers the current run's hooks. Only the\n\t\t// latest run's registrations are live — a re-run supersedes the prior run's hooks,\n\t\t// discarded WITHOUT firing (no fire-on-rerun; onRerun stays cut). Fixes the push-only\n\t\t// accumulation (K stale hooks fired after K runs). C-14.\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._hooks.onDeactivation = [];\n\t\tconst ctx = this._buildCtx();\n\t\tconst wasDirty = this._wave.emittedDirtyThisWave;\n\t\tthis._wave.emittedSettleThisWave = false;\n\t\tthis._wave.insideRunWave = true;\n\t\ttry {\n\t\t\tthis._slot.dispatcher.invoke(this._slot.handle as Handle, ctx);\n\t\t} finally {\n\t\t\tthis._wave.insideRunWave = false;\n\t\t}\n\n\t\t// R-resolved-undirty (D49): a SYNC fn DIRTY'd in phase 1 that produced NO tier-3 value\n\t\t// this wave (filter-reject / distinctUntilChanged-dup / any no-emit fn) gets a substrate-\n\t\t// SYNTHESIZED undirty RESOLVED to clear the downstream dirty — operator bodies stay\n\t\t// protocol-clean (R-primary-api-clean). Status reflects cache freshness: a carried value\n\t\t// -> resolved, never-valued -> sentinel. EXEMPT: terminal/INVALIDATE waves (they set\n\t\t// _emittedSettleThisWave and balance their own dirty), and ASYNC-pool nodes — an async fn\n\t\t// that returns without emitting has DEFERRED its result (it emits later via the stashed\n\t\t// ctx), NOT rejected; synthesizing here would prematurely settle a still-pending diamond\n\t\t// leg (R-async-paused / C-4). The eventual async ctx.down carries its own DIRTY balance.\n\t\tif (\n\t\t\twasDirty &&\n\t\t\t!this._wave.emittedSettleThisWave &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._isAsyncPool()\n\t\t) {\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\n\t\t// roll wave-local state forward\n\t\tfor (let i = 0; i < this._dep.batch.length; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── ctx construction (L3-Q5: sync = node-stable reused ctx; async = per-invocation) ──\n\n\tprivate _buildCtx(): Ctx {\n\t\tconst kind = this._slot.handle\n\t\t\t? this._slot.dispatcher.poolKind(this._slot.handle.poolId)\n\t\t\t: \"sync\";\n\t\tif (kind === \"sync\") {\n\t\t\tif (this._syncCtx === null) this._syncCtx = this._makeCtx();\n\t\t\tthis._refreshCtx(this._syncCtx);\n\t\t\treturn this._syncCtx;\n\t\t}\n\t\t// async: snapshot dep inputs so a deferred late-emit reads this wave's view.\n\t\treturn this._makeCtx({\n\t\t\twaveData: this._dep.waveData.map((waves) => waves.map((w) => [...w])),\n\t\t\tterminal: this._dep.terminalInput.map(terminalView),\n\t\t\tlatest: [...this._dep.prev],\n\t\t});\n\t}\n\n\tprivate _makeCtx(snapshot?: {\n\t\twaveData: unknown[][][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): Ctx {\n\t\tconst ctx: Ctx = {\n\t\t\t// Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove\n\t\t\t// it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed\n\t\t\t// ctx at depth 0, so this is the boundary that drains any rewireNext it issued.\n\t\t\tup: (msgs, towardDep) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._up(msgs, towardDep);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\tdown: (msgs) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._down(msgs);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\twaveData: snapshot?.waveData ?? this._dep.waveData,\n\t\t\tterminal: snapshot?.terminal ?? this._dep.terminalInput.map(terminalView),\n\t\t\tstate: this._makeState(),\n\t\t\tonDeactivation: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onDeactivation.push(fn);\n\t\t\t},\n\t\t\tonInvalidate: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onInvalidate.push(fn);\n\t\t\t},\n\t\t\tenvironment: () => this._slot.environment,\n\t\t\t// R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.\n\t\t\trewireNext: {\n\t\t\t\tsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"add\", dep, fn }),\n\t\t\t\tunsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"remove\", dep, fn }),\n\t\t\t\treplaceDeps: (deps, fn) => this._requestRewireNext({ kind: \"set\", deps, fn }),\n\t\t\t},\n\t\t\t// R-up-routing / R-pull (D269): deferred up — route a control/demand wave (e.g. PULL)\n\t\t\t// up the declared cone at the committed boundary. The SELF-demand path: an\n\t\t\t// immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).\n\t\t\tupNext: (msgs, towardDep) => this._requestUpNext(msgs, towardDep),\n\t\t\t...(this._control.activePull === undefined ? {} : { pull: this._control.activePull }),\n\t\t\t[CTX_DEP_CACHE]: { latest: snapshot?.latest ?? this._dep.prev },\n\t\t\t[CTX_NODE_BINDING]: {\n\t\t\t\tdispatcher: this._slot.dispatcher,\n\t\t\t\tcreate: <U>(factory: () => Node<U>) =>\n\t\t\t\t\twithEnvironmentDrivers(this._slot.environment, () => withNodeCore(this._core, factory)),\n\t\t\t},\n\t\t};\n\t\tif (this._slot.dynamic) {\n\t\t\t// R-dynamic-node: read a dep's latest by index. Untracked deps still drive waves and\n\t\t\t// re-run the fn; under D49 (no equals-substitution) the fn re-emits its current value\n\t\t\t// as DATA — to suppress redundant downstream propagation, pair with distinctUntilChanged.\n\t\t\tctx.track = (i: number) => ctx[CTX_DEP_CACHE]?.latest[i];\n\t\t}\n\t\treturn ctx;\n\t}\n\n\tprivate _refreshCtx(ctx: Ctx): void {\n\t\t(ctx as { waveData: WaveData }).waveData = this._dep.waveData;\n\t\t(ctx as { terminal: TerminalData }).terminal = this._dep.terminalInput.map(terminalView);\n\t\tif (this._control.activePull === undefined) {\n\t\t\tdelete (ctx as { pull?: PullDemand }).pull;\n\t\t} else {\n\t\t\t(ctx as { pull?: PullDemand }).pull = this._control.activePull;\n\t\t}\n\t\tctx[CTX_DEP_CACHE] = { latest: this._dep.prev };\n\t}\n\n\tprivate _makeState(): CtxState {\n\t\treturn {\n\t\t\tget: <S>() => this._privateState.value as S | undefined,\n\t\t\tset: <S>(v: S) => {\n\t\t\t\tthis._privateState.value = v;\n\t\t\t},\n\t\t\tpersist: (on = true) => {\n\t\t\t\tthis._privateState.persist = on;\n\t\t\t},\n\t\t};\n\t}\n\n\t// ── downstream emission pipeline (the unified waist) ──\n\n\tprivate _down(msgs: Wave): void {\n\t\tif (this._released) return;\n\t\tvalidateDownPayloads(msgs);\n\t\tconst deliveryWave = {};\n\t\tconst assertVersionDataCompatible = (wave: readonly Message[]) => {\n\t\t\tfor (const m of wave) {\n\t\t\t\tif (m[0] === \"DATA\") assertNodeVersionDataCompatible(this._version.policy, m[1]);\n\t\t\t}\n\t\t};\n\t\tconst snapshotVersionData = (wave: readonly Message[]): Message[] =>\n\t\t\twave.map((m) =>\n\t\t\t\tm[0] === \"DATA\"\n\t\t\t\t\t? ([\"DATA\", snapshotNodeVersionData(this._version.policy, m[1])] as Message)\n\t\t\t\t\t: m,\n\t\t\t);\n\t\tassertVersionDataCompatible(msgs);\n\t\t// Terminal-is-forever (R-terminal / D17 / B30): once COMPLETE/ERROR has been emitted the\n\t\t// node is final — a self-emit (state.set / ctx.down) in a LATER wave is a no-op, never\n\t\t// resurrecting the cache or re-emitting. The COMPLETE/ERROR arms below also self-guard\n\t\t// against a double terminal, but DATA/RESOLVED/INVALIDATE had no entry guard, so a\n\t\t// post-terminal set() would overwrite cache + emit DATA. R-teardown-terminal-relay / D65\n\t\t// carves out the only post-terminal exception: TEARDOWN still relays downstream for unwire\n\t\t// without reopening value output. A single wave that goes terminal mid-loop (e.g.\n\t\t// [COMPLETE, TEARDOWN]) is unaffected: _terminal is still undefined at entry.\n\t\t// Resubscribable reset clears _terminal before any re-emit.\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (!msgs.some((m) => m[0] === \"TEARDOWN\")) return;\n\t\t\tthis._value.hasTorndown = true;\n\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\tthis._value.hasData = false;\n\t\t\t}\n\t\t\tthis._emitToSubs([\"TEARDOWN\"], { wave: deliveryWave, last: true });\n\t\t\treturn;\n\t\t}\n\t\tlet sorted: Message[] = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));\n\t\t// R-same-wave-merge: collapse repeated INVALIDATE in one wave (Q9) so the\n\t\t// cleanup hook + downstream broadcast fire at most once.\n\t\tconst firstInvalidate = sorted.findIndex((m) => m[0] === \"INVALIDATE\");\n\t\tif (firstInvalidate !== -1) {\n\t\t\tsorted = sorted.filter((m, i) => m[0] !== \"INVALIDATE\" || i === firstInvalidate);\n\t\t}\n\t\t// R-teardown-complete: a TEARDOWN reaching a non-terminal node synthesizes a\n\t\t// COMPLETE prefix (so firstValueFrom-style bridges resolve), unless the wave\n\t\t// already carries a terminal or the node already tore down.\n\t\tconst hasTeardown = sorted.some((m) => m[0] === \"TEARDOWN\");\n\t\tconst hasTerminal = sorted.some((m) => m[0] === \"COMPLETE\" || m[0] === \"ERROR\");\n\t\tif (\n\t\t\thasTeardown &&\n\t\t\t!hasTerminal &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._value.hasTorndown\n\t\t) {\n\t\t\tsorted = [[\"COMPLETE\"], ...sorted];\n\t\t}\n\t\t// R-batch-coalesce (D12): inside a batch, emit DIRTY immediately but defer the\n\t\t// tier-3 settle slice to commit so a shared downstream recomputes once. Only\n\t\t// external emits defer (fn emits during commit run normally).\n\t\tif (!this._wave.insideRunWave && currentBatch()) {\n\t\t\tconst deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));\n\t\t\tif (deferred.length > 0) {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t\t\t}\n\t\t\t\tthis._wave.batchDirtyOwed = true; // BH1: owe a balancing RESOLVED on rollback\n\t\t\t\tdeferToBatch(this, deferred);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// R-pause-modes / R-async-paused: defer the settle slice (tier 3/4) into the\n\t\t// pause buffer while paused; tier 0-2 (DIRTY/PAUSE/RESUME), tier 5 (terminal),\n\t\t// tier 6 (TEARDOWN) bypass so end-of-stream + control always reach observers.\n\t\tif (this._shouldBufferOnPause()) {\n\t\t\tconst buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));\n\t\t\tif (buffered.length > 0) {\n\t\t\t\t// B36 / R-resolved-undirty: buffering a settle slice still means this fn wave\n\t\t\t\t// produced a settle. Without this, _runWave sees \"dirty + no settle\" and\n\t\t\t\t// synthesizes a RESOLVED that pierces the pause while the DATA waits in the buffer.\n\t\t\t\tthis._wave.emittedSettleThisWave = true;\n\t\t\t\tthis._control.pauseBuffer.push(buffered);\n\t\t\t}\n\t\t\tsorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));\n\t\t\tif (sorted.length === 0) return;\n\t\t}\n\t\tlet dataCount = 0;\n\t\tlet hasTier3 = false;\n\t\tlet hasResolved = false;\n\t\tfor (const m of sorted) {\n\t\t\tif (m[0] === \"DATA\") dataCount++;\n\t\t\tif (m[0] === \"RESOLVED\") hasResolved = true;\n\t\t\tif (isValueTier(m[0])) hasTier3 = true;\n\t\t}\n\t\t// EC2 / R-resolved-undirty tier-3 exclusivity: a wave's tier-3 slot is >=1 DATA\n\t\t// (occurrence) XOR exactly 1 RESOLVED (undirty) — never mixed. Reject fail-fast.\n\t\tif (dataCount >= 1 && hasResolved) {\n\t\t\tthrow new Error(\n\t\t\t\t\"down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)\",\n\t\t\t);\n\t\t}\n\t\tconst plannedVersions: Array<NodeVersion | undefined> = new Array(sorted.length);\n\t\tif (dataCount > 0) {\n\t\t\tlet plannedVersion = this._version.value;\n\t\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\t\tconst m = sorted[i];\n\t\t\t\tif (m[0] !== \"DATA\") continue;\n\t\t\t\tplannedVersion = advanceNodeVersion(plannedVersion, this._version.policy, m[1]);\n\t\t\t\tplannedVersions[i] = plannedVersion;\n\t\t\t}\n\t\t}\n\n\t\t// Synthesize a leading DIRTY for an EXTERNAL tier-3 emit (R-dirty-before-data), and for\n\t\t// PULL demand fns only when they actually emit tier-3. A no-op pull helper must stay silent.\n\t\tif (\n\t\t\thasTier3 &&\n\t\t\t(!this._wave.insideRunWave || this._control.pullDirtyOwed) &&\n\t\t\t!this._wave.emittedDirtyThisWave\n\t\t) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._value.status = \"dirty\";\n\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t}\n\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst m = sorted[i];\n\t\t\tconst delivery = { wave: deliveryWave, last: i === sorted.length - 1 };\n\t\t\t// R-resolved-undirty (D49): a tier-3+ emit this wave means the fn produced a settle,\n\t\t\t// so no synthesized undirty RESOLVED is owed (see _runWave).\n\t\t\tif (isDeferredTier(m[0])) this._wave.emittedSettleThisWave = true;\n\t\t\tif (m[0] === \"DIRTY\") {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], delivery);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"DATA\") {\n\t\t\t\tconst v = m[1] as T;\n\t\t\t\t// R-resolved-undirty (D49): every value-occurrence is emitted as DATA — the\n\t\t\t\t// substrate never substitutes DATA->RESOLVED on value-equality. Dedup is opt-in\n\t\t\t\t// at the operator layer (distinctUntilChanged), never a substrate behavior.\n\t\t\t\tthis._value.cache = v;\n\t\t\t\tthis._value.hasData = true;\n\t\t\t\tthis._value.status = \"settled\";\n\t\t\t\tthis._version.value = plannedVersions[i];\n\t\t\t\tif (this._slot.replayN > 0) {\n\t\t\t\t\tthis._value.replayRing.push(v);\n\t\t\t\t\tif (this._value.replayRing.length > this._slot.replayN) this._value.replayRing.shift();\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"DATA\", v], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"RESOLVED\") {\n\t\t\t\tthis._value.status = this._value.hasData ? \"resolved\" : \"sentinel\";\n\t\t\t\tthis._emitToSubs([\"RESOLVED\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"INVALIDATE\") {\n\t\t\t\tthis._invalidate(delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"COMPLETE\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = true;\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"completed\";\n\t\t\t\tthis._emitToSubs([\"COMPLETE\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"ERROR\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = m[1];\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"errored\";\n\t\t\t\tthis._emitToSubs([\"ERROR\", m[1]], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"TEARDOWN\") {\n\t\t\t\tthis._value.hasTorndown = true;\n\t\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\t\tthis._value.hasData = false;\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"TEARDOWN\"], delivery);\n\t\t\t}\n\t\t\t// PAUSE / RESUME — control slice.\n\t\t}\n\n\t\tif (!this._wave.insideRunWave) this._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _up(msgs: Wave, towardDep?: number, route?: UpRouteState): void {\n\t\tif (this._released) return;\n\t\tconst routeState = route ?? { demandFired: new Map() };\n\t\tfor (const m of msgs) {\n\t\t\tif (!isUpAllowed(m[0])) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === \"PAUSE\") {\n\t\t\t\t// PAUSE is NODE-TARGETED (R-up-routing): it ACQUIRES a lock, so there is no\n\t\t\t\t// pre-existing holder to route to — a controller targets the node directly.\n\t\t\t\tthis._pauseAcquire(m[1]);\n\t\t\t} else if (m[0] === \"RESUME\") {\n\t\t\t\t// R-up-routing (D269): RESUME is pause-lock release only.\n\t\t\t\tif (this._control.pauseLockset.has(m[1])) {\n\t\t\t\t\t// a pause lock held HERE → release LOCALLY (normal pause/resume, R-pause-lockset).\n\t\t\t\t\tthis._pauseRelease(m[1]);\n\t\t\t\t} else {\n\t\t\t\t\t// not held here → forward UP the declared cone to find the holder.\n\t\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t\t}\n\t\t\t} else if (m[0] === \"PULL\") {\n\t\t\t\t// R-up-routing / R-pull (D269/D272): DEMAND-IF-PULL-HOLDER-ELSE-FORWARD-UP.\n\t\t\t\tconst demand = normalizePullDemand(m[1]);\n\t\t\t\tif (this._slot.pull && demand.pullId === this._slot.pullLock) {\n\t\t\t\t\tif (!this._markDemandRouted(demand.pullId, routeState)) this._onDemand(demand);\n\t\t\t\t} else {\n\t\t\t\t\tthis._forwardUp([\"PULL\", demand], towardDep, routeState);\n\t\t\t\t}\n\t\t\t} else if (this._slot.deps.length === 0) {\n\t\t\t\t// R-up-at-source (D38): a depless source is the terminus of upstream control.\n\t\t\t\t// INVALIDATE → HONOR the invalidate-request. Routed through _down (NOT a direct\n\t\t\t\t// _invalidate call, QA A-2) so the invalidate-request respects batch-defer (D12)\n\t\t\t\t// and pause-buffer exactly like a downstream-originated INVALIDATE; _down's\n\t\t\t\t// INVALIDATE branch calls _invalidate() (clear cache → SENTINEL, fire onInvalidate,\n\t\t\t\t// broadcast downstream). Outside batch/pause it is identical to a direct call.\n\t\t\t\t// DIRTY / TEARDOWN → DROP (no coherent terminus action; self-dirty would wedge\n\t\t\t\t// downstream awaiting a settle that never comes; source lifecycle is source-owned).\n\t\t\t\tif (m[0] === \"INVALIDATE\") this._down([[\"INVALIDATE\"]]);\n\t\t\t} else {\n\t\t\t\t// dep-bearing intermediate: forward DIRTY/INVALIDATE/TEARDOWN up toward deps.\n\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _markDemandRouted(lockId: LockId, route: UpRouteState): boolean {\n\t\tlet holders = route.demandFired.get(lockId);\n\t\tif (holders === undefined) {\n\t\t\tholders = new Set();\n\t\t\troute.demandFired.set(lockId, holders);\n\t\t}\n\t\tif (holders.has(this as unknown as Node<unknown>)) return true;\n\t\tholders.add(this as unknown as Node<unknown>);\n\t\treturn false;\n\t}\n\n\t/**\n\t * Forward one up-going control message toward deps (R-up-routing): up the single declared edge\n\t * `towardDep` (directed — prunes other branches; only meaningful on the issuer's FIRST hop) or\n\t * broadcast up ALL deps. A depless source has no deps → the message DROPS here (the terminus —\n\t * e.g. a cone-routed PULL whose pullId no node up this cone holds, R-up-at-source). Recursive\n\t * forwarding carries the same per-wave route state and no `towardDep` → broadcast beyond the\n\t * first hop.\n\t */\n\tprivate _forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void {\n\t\tif (this._slot.deps.length === 0) return; // depless source terminus → drop\n\t\tif (towardDep !== undefined) {\n\t\t\tconst d = this._slot.deps[towardDep];\n\t\t\tif (d !== undefined) d._up([m], undefined, route);\n\t\t} else {\n\t\t\tfor (const dep of this._slot.deps) dep._up([m], undefined, route);\n\t\t}\n\t}\n\n\t// ── PAUSE/RESUME lockset (R-pause-lockset) + modes (R-pause-modes) ──\n\n\tprivate _isPaused(): boolean {\n\t\treturn this._control.pauseLockset.size > 0;\n\t}\n\n\tprivate _hasBoundaryPauseLock(): boolean {\n\t\tif (this._slot.pausable === false) return false;\n\t\treturn this._control.pauseLockset.size > 0;\n\t}\n\n\tprivate _isAsyncPool(): boolean {\n\t\treturn (\n\t\t\tthis._slot.handle !== null &&\n\t\t\tthis._slot.dispatcher.poolKind(this._slot.handle.poolId) === \"async\"\n\t\t);\n\t}\n\n\tprivate _pauseAcquire(lockId: unknown): void {\n\t\tthis._control.pauseLockset.add(lockId); // Set => same-id repeat PAUSE is idempotent\n\t}\n\n\tprivate _pauseRelease(lockId: unknown): void {\n\t\tif (!this._control.pauseLockset.has(lockId)) return; // unknown id => no-op\n\t\tthis._control.pauseLockset.delete(lockId);\n\t\t// R-pull (D59 / D272): releasing an EXTERNAL pause lock can unblock an owed demand.\n\t\t// Pull quiet is activePull-derived and never stored in pauseLockset.\n\t\tif (this._slot.pull && this._control.demandOwed !== undefined) this._fireOwedDemandIfReady();\n\t\tif (this._hasBoundaryPauseLock()) return; // another external lock still held => stay paused\n\t\tscheduleBoundaryDrain(this._core);\n\t\tif (this._slot.pull) return; // pull nodes stay quiet until PULL, even after external resume\n\t\tthis._onResume();\n\t}\n\n\tprivate _onResume(): void {\n\t\t// BH3: a node that terminated while paused discards its buffer and never\n\t\t// replays/recomputes (terminal-is-forever).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\treturn;\n\t\t}\n\t\t// Non-pull pause/resume (R-pause-modes): drain buffered settle slices (resumeAll /\n\t\t// async-at-paused, R-async-paused), then fire a coalesced dep-wave once (default mode).\n\t\t// A PULL node does not resume by draining here; its demand fires through _onDemand.\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t}\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._tryRun();\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): can this pull node fire a demand NOW? — not terminal, settle-ready (_pending===0),\n\t * and no OTHER (non-pullId) lock holds it paused. The gate that decides fire-now vs OWE.\n\t */\n\tprivate _canFireDemand(): boolean {\n\t\tif (this._value.terminal !== undefined || this._wave.pending > 0) return false;\n\t\treturn this._control.pauseLockset.size === 0;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): deliver ONE demand pulse — install activePull so the demand wave may\n\t * emit, fire it, then clear activePull so the node is quiet again (1:1).\n\t */\n\tprivate _deliverPullDemand(demand: PullDemand): void {\n\t\tthis._control.demandOwed = undefined;\n\t\tthis._control.activePull = demand;\n\t\tthis._control.inDeliverDemand = true;\n\t\ttry {\n\t\t\tthis._firePullDemand();\n\t\t} finally {\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): a cone-routed PULL of THIS node's pullId arrived (R-up-routing) = a DEMAND.\n\t * Fire immediately if able; else OWE it — pin-5 (a dep DIRTY in flight, _pending>0) or F4/F5 (an\n\t * external PAUSE lock co-holds the node) — and fire when the node next becomes able. A demand\n\t * arriving WHILE a delivery is in flight (synchronous re-entry) is DROPPED (1:1, QA guard).\n\t */\n\tprivate _onDemand(demand: PullDemand): void {\n\t\tif (this._control.inDeliverDemand) return; // re-entrant demand during an active delivery → drop (1:1)\n\t\tif (this._canFireDemand()) this._deliverPullDemand(demand);\n\t\telse this._control.demandOwed = demand; // latest owed params wins (D269/D272)\n\t}\n\n\t/**\n\t * R-pull (D55): service ONE demand. Delivery content = the orthogonal pausable mode:\n\t * - 'resumeAll' → drain the buffered BACKLOG (each `_down` re-synthesizes a leading DIRTY, so\n\t * the per-entry replay is DIRTY-before-DATA — R-pause-modes per-entry arrival order);\n\t * - true → deliver the coalesced LATEST as ONE DIRTY-before-DATA wave (pin 2: the quiet absorb\n\t * suppressed the dep's original DIRTY, so the demand wave restores it before the value).\n\t * Neither branch fires when nothing changed since the last demand → the demand is SILENT.\n\t * Called by `_deliverPullDemand` only when settle-ready; the caller has released the pullId, so\n\t * `_markDirty` relays the leading DIRTY (not absorbed).\n\t */\n\tprivate _firePullDemand(): void {\n\t\tlet drainedBuffer = false;\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t\tdrainedBuffer = true;\n\t\t}\n\t\tif (drainedBuffer) return;\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\t// QA-B2: only deliver if the fn can actually run this wave (settle-ready + first-run gate\n\t\t\t// open). A gated run emits no DATA, so emitting the leading DIRTY would STRAND downstream\n\t\t\t// — the exact wedge this feature exists to prevent (NoWedgeWhileQuiet). When gated, stay\n\t\t\t// SILENT and KEEP _pausedDepWaveOccurred so a later demand (once every dep has settled)\n\t\t\t// delivers. Mirrors _settleRewire's pre-_markDirty gate.\n\t\t\tconst gated =\n\t\t\t\tthis._slot.handle !== null &&\n\t\t\t\t!this._wave.hasCalledFnOnce &&\n\t\t\t\t!(this._slot.partial || this._allDepsSettled());\n\t\t\tif (this._wave.pending > 0 || gated) return;\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._control.pullDirtyOwed = true;\n\t\t\ttry {\n\t\t\t\tthis._tryRun(); // fn DATA triggers DIRTY-before-DATA; no DATA means no output.\n\t\t\t} finally {\n\t\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this._slot.handle !== null) {\n\t\t\tif (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._control.pullDirtyOwed = true;\n\t\t\ttry {\n\t\t\t\tthis._runWave();\n\t\t\t} finally {\n\t\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D269): fire a demand that was OWED (deferred at demand time) once the node becomes\n\t * able — called from the dep-settle arms (DATA/RESOLVED/INVALIDATE/terminal drain _pending, pin-5\n\t * + B1/F6) and from `_pauseRelease` (an external PAUSE lock releases, F4/F5).\n\t */\n\tprivate _fireOwedDemandIfReady(): void {\n\t\tif (this._control.inDeliverDemand) return; // don't re-enter during an active delivery (1:1, QA guard)\n\t\tif (this._slot.pull && this._control.demandOwed !== undefined && this._canFireDemand()) {\n\t\t\tthis._deliverPullDemand(this._control.demandOwed);\n\t\t}\n\t}\n\n\t/** Should an outgoing settle slice be deferred into the pause buffer? */\n\tprivate _shouldBufferOnPause(): boolean {\n\t\t// D44: pausable mode is the OUTER gate over R-async-paused buffering.\n\t\t// false: ignore PAUSE/RESUME ENTIRELY — never buffer, keep producing (R-pause-modes; resolves B20).\n\t\tif (this._slot.pausable === false) return false;\n\t\tif (!this._isPaused() && !this._isPullQuiet()) return false;\n\t\t// resumeAll: production-gating — buffer the node's own (sync/async) settle slice too.\n\t\tif (this._slot.pausable === \"resumeAll\") return true;\n\t\t// true (default): PAUSE gates recomputation/propagation, NOT a leaf source's own production.\n\t\t// An async COMPUTE node's (deps>0) in-flight result buffers (R-async-paused / C-2); a depless\n\t\t// async leaf source's own production delivers immediately (R-pause-modes / C-10).\n\t\tif (!this._wave.insideRunWave && this._isAsyncPool() && this._slot.deps.length > 0) return true;\n\t\treturn false;\n\t}\n\n\t/** R-invalidate-idempotent: clear cache + flush + cascade; no-op if nothing cached. */\n\tprivate _invalidate(delivery?: DeliveryMeta): void {\n\t\tif (!this._value.hasData) return; // never-populated or already-reset → no-op\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.replayRing = []; // BH6: invalidated values are stale — don't replay them\n\t\tfor (const fn of this._hooks.onInvalidate) fn();\n\t\tthis._emitToSubs([\"INVALIDATE\"], delivery);\n\t}\n\n\t// B42 (R-deps-terminal): ALL deps TERMINAL = every dep has reached COMPLETE *or* an ABSORBED\n\t// ERROR. Block only on a LIVE dep (_depTerminal[i] === undefined); an errored dep (terminal = the\n\t// error payload, which R-data-payload guarantees is !== undefined and non-boolean) COUNTS as\n\t// terminal-done. Was\n\t// `tm !== true`, which wedged a node whose errorWhenDepsError:false dep ERRORed (it never\n\t// auto-completed even after every other dep completed). Drives the completeWhenDepsComplete cascade.\n\tprivate _allDepsTerminal(): boolean {\n\t\tif (this._slot.deps.length === 0) return false;\n\t\tfor (const tm of this._dep.terminal) if (tm === undefined) return false;\n\t\treturn true;\n\t}\n\n\t/** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */\n\tprivate _resetLifecycle(): void {\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tthis._lifecycle.activated = false;\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.hasTorndown = false;\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._resetDepState();\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\t\tthis._control.activePull = undefined;\n\t\tthis._control.pullDirtyOwed = false;\n\t\tthis._value.replayRing = []; // BH6\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t} else {\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _emitToSubs(msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\t// Copy guards against subscribe/unsubscribe during iteration.\n\t\tconst subs = [...this._lifecycle.subscribers];\n\t\tfor (const sink of subs) sink(msg, delivery);\n\t}\n\n\t/** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */\n\t__commitBatchedWave(wave: Wave): void {\n\t\tthis._wave.batchDirtyOwed = false; // commit delivers the real settle (BH1)\n\t\tthis._down(wave); // batch is inactive at commit -> processes normally\n\t}\n\n\t/** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */\n\t__rollbackBatched(): void {\n\t\t// BH1: keyed on _batchDirtyOwed (not _emittedDirtyThisWave, which a fn wave between\n\t\t// defer and rollback would have reset) so the balancing RESOLVED is never skipped.\n\t\tif (this._wave.batchDirtyOwed) {\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t\tthis._emitToSubs([\"RESOLVED\"]);\n\t\t}\n\t}\n\n\t/** B49: enqueue a committed-boundary task on this node's graph-local core. */\n\t__deferBoundary(fn: () => void, batchToken?: object): void {\n\t\tdeferRewire(this._core, fn, {\n\t\t\tbatchToken,\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n}\n\n/**\n * Construct a node (R-node-iface / D5 / L1.9 deps-first).\n * node([], null, { initial }) — state node (manual source; emit via .down)\n * node([], fn) — producer (runs on activation)\n * node([a, b], fn) — compute / derived\n * node([dep]) — passthrough wire\n */\nexport function node<T = unknown>(\n\tdeps: Node<unknown>[] = [],\n\thandleOrFn: Handle | NodeFn | null = null,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, handleOrFn, opts);\n}\n\n/**\n * Construct a dynamicNode (R-dynamic-node / D35) — a node variant whose fn reads a\n * subset of a fixed superset of deps per invocation via `ctx.track(i)`. All declared\n * deps participate in wave tracking; an unread dep's change re-runs the fn, which re-emits\n * its current value as DATA (D49 removed equals-absorption — dedup is opt-in via\n * distinctUntilChanged). Intra-graph only (D22).\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","import { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport type { DataIssue } from \"../../data/index.js\";\nimport type { Graph, StateNode } from \"../../graph/graph.js\";\nimport { Node } from \"../../node/node.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\n\n/**\n * Synchronous text measurement contract for the D181 reactive-layout solution core.\n *\n * Implementations are injected by the caller; the universal subpath never imports DOM,\n * Canvas, React Native, storage, GraphSpec, or async image loading.\n */\nexport interface MeasurementAdapter {\n\tmeasureSegment(text: string, font: string): { readonly width: number };\n\tclearCache?(): void;\n}\n\n/** Caller-owned platform text capability, for NodeCanvas/Skia/RN-style wrappers. */\nexport interface TextMeasureCapability {\n\tmeasureText(text: string, font: string): number | { readonly width: number };\n\tclearCache?(): void;\n}\n\n/** One text segment returned by a caller-provided segmenter. */\nexport interface SegmentInfo {\n\treadonly segment: string;\n\treadonly index: number;\n\treadonly isWordLike?: boolean;\n}\n\n/** Synchronous word/grapheme segmentation contract for hosts without Intl.Segmenter. */\nexport interface SegmentAdapter {\n\tsegmentWords(text: string): Iterable<SegmentInfo>;\n\tsegmentGraphemes(text: string): Iterable<SegmentInfo>;\n}\n\n/** Layout segment class used by the line breaker. */\nexport type SegmentBreakKind = \"text\" | \"space\" | \"zero-width-break\" | \"soft-hyphen\" | \"hard-break\";\n\n/** Measured text run consumed by pure line/block/flow helpers. */\nexport interface PreparedSegment {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly kind: SegmentBreakKind;\n\treadonly graphemeWidths: readonly number[] | null;\n}\n\n/** One laid-out line with segment/grapheme cursor bounds. */\nexport interface LayoutLine {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly startSegment: number;\n\treadonly startGrapheme: number;\n\treadonly endSegment: number;\n\treadonly endGrapheme: number;\n}\n\n/** Positioned grapheme box for hit testing or custom renderers. */\nexport interface CharPosition {\n\treadonly x: number;\n\treadonly y: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly line: number;\n}\n\n/** Result emitted by `reactiveLayout().lineBreaks`. */\nexport interface LineBreaksResult {\n\treadonly lines: readonly LayoutLine[];\n\treadonly lineCount: number;\n}\n\n/** Cursor into a prepared segment array. */\nexport interface LayoutCursor {\n\treadonly segmentIndex: number;\n\treadonly graphemeIndex: number;\n}\n\n/** Pure helper result for one `layoutNextLine` step. */\nexport interface LayoutNextLineResult {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly start: LayoutCursor;\n\treadonly end: LayoutCursor;\n}\n\n/** Horizontal interval used by obstacle carving. */\nexport interface Interval {\n\treadonly left: number;\n\treadonly right: number;\n}\n\nexport const TEXT_SEGMENTS_MEASUREMENT_KIND = \"text-segments\";\nexport const BLOCKS_MEASUREMENT_KIND = \"blocks\";\n/** Measurement kind for standalone readiness facts. */\nexport const READINESS_MEASUREMENT_KIND = \"readiness\";\n/** Measurement kind for standalone image-size facts. */\nexport const IMAGE_SIZE_MEASUREMENT_KIND = \"image-size\";\n/** Measurement kind for standalone SVG-bounds facts. */\nexport const SVG_BOUNDS_MEASUREMENT_KIND = \"svg-bounds\";\n\nexport interface TextSegmentsMeasurement {\n\treadonly segments: readonly PreparedSegment[];\n\treadonly hyphenWidth?: number;\n}\n\nexport interface BlocksMeasurement {\n\treadonly blocks: readonly MeasuredBlock[];\n}\n\nexport interface MeasurementResult<T = unknown> {\n\treadonly kind: \"ok\";\n\treadonly targetId: string;\n\treadonly measurementKind: string;\n\treadonly value: T;\n\treadonly source?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface MeasurementIssue extends DataIssue {\n\treadonly subjectId: string;\n\treadonly measurementKind: string;\n}\n\nexport type MeasurementFact<T = unknown> = MeasurementResult<T> | MeasurementIssue;\n\nexport type Measurements = readonly MeasurementFact[];\n\nexport interface MergeMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly sources: readonly Node<Measurements>[];\n\treadonly name?: string;\n}\n\nexport interface TextMeasurementProviderOptions {\n\treadonly graph: Graph;\n\treadonly text: Node<string>;\n\treadonly font: Node<string>;\n\treadonly adapter: Node<MeasurementAdapter>;\n\treadonly segmentAdapter?: Node<SegmentAdapter>;\n\treadonly targetId?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface InjectedTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\"> {\n\treadonly measure: MeasureFn;\n\treadonly cache?: boolean;\n}\n\nexport interface PrecomputedTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\">,\n\t\tPrecomputedMeasureAdapterOptions {}\n\nexport interface CellTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\">,\n\t\tCellMeasureAdapterOptions {}\n\nexport interface CapabilityTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\"> {\n\treadonly capability: Node<TextMeasureCapability>;\n}\n\nexport interface MeasurementReadiness {\n\treadonly ready: boolean;\n\treadonly code?: string;\n\treadonly message?: string;\n\treadonly source?: string;\n\treadonly details?: unknown;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting readiness into graph-visible measurement facts. */\nexport interface ReadinessMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly readiness: Node<MeasurementReadiness>;\n\treadonly targetId?: string;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface ReadinessTextMeasurementsOptions extends TextMeasurementProviderOptions {\n\treadonly readiness: Node<MeasurementReadiness>;\n}\n\n/** Minimal caller-owned lookup for explicit image sizes. */\nexport interface ImageSizeLookup {\n\tget(src: string): Size | undefined;\n}\n\n/** One image-size fact target for `imageSizeMeasurements`. */\nexport interface ImageSizeMeasurementTarget {\n\treadonly id?: string;\n\treadonly src: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting image-size facts from a caller-owned synchronous measurer. */\nexport interface ImageSizeMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly images: Node<readonly ImageSizeMeasurementTarget[]>;\n\treadonly measurer: Node<ImageMeasurer>;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\n/** One SVG-bounds fact target for `svgBoundsMeasurements`. */\nexport interface SvgBoundsMeasurementTarget {\n\treadonly id?: string;\n\treadonly svg: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting SVG bounds from a caller-owned synchronous measurer. */\nexport interface SvgBoundsMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly svgs: Node<readonly SvgBoundsMeasurementTarget[]>;\n\treadonly measurer: Node<SvgMeasurer>;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface BlockMeasurementProviderOptions {\n\treadonly graph: Graph;\n\treadonly blocks: Node<readonly ContentBlock[]>;\n\treadonly maxWidth: Node<number>;\n\treadonly adapters: Node<BlockAdapters>;\n\treadonly segmentAdapter?: Node<SegmentAdapter>;\n\treadonly font?: Node<string>;\n\treadonly lineHeight?: Node<number>;\n\treadonly targetId?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface BlockAdaptersProviderOptions {\n\treadonly graph: Graph;\n\treadonly text?: Node<MeasurementAdapter>;\n\treadonly svg?: Node<SvgMeasurer>;\n\treadonly image?: Node<ImageMeasurer>;\n\treadonly name?: string;\n}\n\n/**\n * Graph-visible bundle returned by `reactiveLayout`.\n *\n * The setters are state-node sugar over real graph inputs; the output nodes are ordinary\n * inspectable nodes visible through `graph.describe()`.\n */\nexport interface ReactiveLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly lineHeight: Node<number>;\n\t\treadonly maxWidth: Node<number>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetLineHeight(lineHeight: number): void;\n\tsetMaxWidth(maxWidth: number): void;\n\treadonly segments: Node<readonly PreparedSegment[]>;\n\treadonly lineBreaks: Node<LineBreaksResult>;\n\treadonly height: Node<number>;\n\treadonly charPositions: Node<readonly CharPosition[]>;\n}\n\n/** Optional context shared by pure line-breaking helpers. */\nexport interface LayoutNextLineContext {\n\treadonly adapter?: MeasurementAdapter;\n\treadonly font?: string;\n\treadonly cache?: Map<string, Map<string, number>>;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Cache accounting object callers can pass into `analyzeAndMeasure`. */\nexport interface SegmentMeasureStats {\n\thits: number;\n\tmisses: number;\n}\n\n/** Options for the single-column reactive text layout bundle. */\nexport interface ReactiveLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly segmentAdapter?: SegmentAdapter;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly lineHeight?: number | Node<number>;\n\treadonly maxWidth?: number | Node<number>;\n}\n\n/** Host text measurement function accepted by `InjectedMeasureAdapter`. */\nexport type MeasureFn = (text: string, font: string) => number | { readonly width: number };\n\n/** Options for caller-injected synchronous measurement. */\nexport interface InjectedMeasureAdapterOptions {\n\treadonly cache?: boolean;\n}\n\n/** Options for deterministic precomputed text metrics. */\nexport interface PrecomputedMeasureAdapterOptions {\n\treadonly metrics: ReadonlyMap<string, number> | Record<string, number>;\n\treadonly fallback?: \"per-char\" | \"error\";\n\treadonly cellWidth?: number;\n}\n\n/** Fixed-cell measurement options for terminal/snapshot rendering. */\nexport interface CellMeasureAdapterOptions {\n\treadonly cellWidth?: number;\n\treadonly wideCellWidth?: number;\n\treadonly tabCells?: number;\n}\n\n/** Width/height pair in CSS-like pixels. */\nexport interface Size {\n\treadonly width: number;\n\treadonly height: number;\n}\n\n/** Synchronous SVG measurement seam; no DOM parser is provided by the core. */\nexport interface SvgMeasurer {\n\tmeasureSvg(svg: string): Size;\n}\n\n/** Synchronous image measurement seam; no loading/fetching is provided by the core. */\nexport interface ImageMeasurer {\n\tmeasureImage(src: string): Size;\n}\n\n/** Optional per-kind block measurement adapters. */\nexport interface BlockAdapters {\n\treadonly text?: MeasurementAdapter;\n\treadonly svg?: SvgMeasurer;\n\treadonly image?: ImageMeasurer;\n}\n\n/** Shared spacing/id fields for block layout inputs. */\nexport interface BaseContentBlock {\n\treadonly id?: string;\n\treadonly marginTop?: number;\n\treadonly marginBottom?: number;\n}\n\n/** Text block input for `measureBlock` and `reactiveBlockLayout`. */\nexport interface TextContentBlock extends BaseContentBlock {\n\treadonly kind: \"text\";\n\treadonly text: string;\n\treadonly font?: string;\n\treadonly lineHeight?: number;\n\treadonly maxWidth?: number;\n}\n\n/** Image block input with explicit dimensions or an injected `ImageMeasurer`. */\nexport interface ImageContentBlock extends BaseContentBlock {\n\treadonly kind: \"image\";\n\treadonly src: string;\n\treadonly width?: number;\n\treadonly height?: number;\n\treadonly maxWidth?: number;\n}\n\n/** SVG block input with explicit dimensions or an injected `SvgMeasurer`. */\nexport interface SvgContentBlock extends BaseContentBlock {\n\treadonly kind: \"svg\";\n\treadonly svg: string;\n\treadonly width?: number;\n\treadonly height?: number;\n\treadonly maxWidth?: number;\n}\n\n/** Heterogeneous block-layout input. */\nexport type ContentBlock = TextContentBlock | ImageContentBlock | SvgContentBlock;\n\n/** Measured block produced by `measureBlock` or `measureBlocks`. */\nexport interface MeasuredBlock {\n\treadonly block: ContentBlock;\n\treadonly kind: ContentBlock[\"kind\"];\n\treadonly id?: string;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly marginTop: number;\n\treadonly marginBottom: number;\n\treadonly segments?: readonly PreparedSegment[];\n\treadonly lineBreaks?: LineBreaksResult;\n\treadonly charPositions?: readonly CharPosition[];\n}\n\n/** Block with vertical-flow coordinates. */\nexport interface PositionedBlock extends MeasuredBlock {\n\treadonly x: number;\n\treadonly y: number;\n}\n\n/** Options for pure block measurement helpers. */\nexport interface MeasureBlockOptions {\n\treadonly adapter?: MeasurementAdapter;\n\treadonly adapters?: BlockAdapters;\n\treadonly font?: string;\n\treadonly lineHeight?: number;\n\treadonly maxWidth?: number;\n\treadonly cache?: Map<string, Map<string, number>>;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Options for the graph-visible block layout bundle. */\nexport interface ReactiveBlockLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly gap?: number | Node<number>;\n}\n\n/** Graph-visible vertical block layout bundle. */\nexport interface ReactiveBlockLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly gap: Node<number>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetGap(gap: number): void;\n\treadonly measuredBlocks: Node<readonly MeasuredBlock[]>;\n\treadonly blockFlow: Node<readonly PositionedBlock[]>;\n\treadonly totalHeight: Node<number>;\n}\n\n/** Circular obstacle for flow layout slot carving. */\nexport interface CircleObstacle {\n\treadonly kind: \"circle\";\n\treadonly cx: number;\n\treadonly cy: number;\n\treadonly r: number;\n}\n\n/** Rectangular obstacle for flow layout slot carving. */\nexport interface RectObstacle {\n\treadonly kind: \"rect\";\n\treadonly x: number;\n\treadonly y: number;\n\treadonly width: number;\n\treadonly height: number;\n}\n\n/** Obstacle shape accepted by flow layout. */\nexport type Obstacle = CircleObstacle | RectObstacle;\n\n/** Flow container geometry. */\nexport interface FlowContainer {\n\treadonly width: number;\n\treadonly height: number;\n\treadonly paddingX?: number;\n\treadonly paddingY?: number;\n}\n\n/** Optional column geometry for flow layout. */\nexport interface FlowColumns {\n\treadonly count?: number;\n\treadonly gap?: number;\n}\n\n/** Positioned line emitted by `computeFlowLines` / `reactiveFlowLayout`. */\nexport interface PositionedLine extends LayoutLine {\n\treadonly x: number;\n\treadonly y: number;\n\treadonly slotWidth: number;\n\treadonly columnIndex: number;\n}\n\n/** Flow layout result plus the continuation cursor. */\nexport interface FlowLinesResult {\n\treadonly lines: readonly PositionedLine[];\n\treadonly cursor: LayoutCursor;\n\treadonly done: boolean;\n}\n\n/** Options for pure flow layout computation. */\nexport interface ComputeFlowLinesOptions {\n\treadonly container: FlowContainer;\n\treadonly columns?: FlowColumns;\n\treadonly obstacles?: readonly Obstacle[];\n\treadonly lineHeight: number;\n\treadonly minSlotWidth?: number;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Options for the graph-visible flow layout bundle. */\nexport interface ReactiveFlowLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly segmentAdapter?: SegmentAdapter;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly lineHeight?: number | Node<number>;\n\treadonly container?: FlowContainer | Node<FlowContainer>;\n\treadonly columns?: FlowColumns | Node<FlowColumns>;\n\treadonly obstacles?: readonly Obstacle[] | Node<readonly Obstacle[]>;\n\treadonly minSlotWidth?: number;\n}\n\n/** Graph-visible multi-column flow layout bundle. */\nexport interface ReactiveFlowLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly lineHeight: Node<number>;\n\t\treadonly container: Node<FlowContainer>;\n\t\treadonly columns: Node<FlowColumns>;\n\t\treadonly obstacles: Node<readonly Obstacle[]>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetLineHeight(lineHeight: number): void;\n\tsetContainer(container: FlowContainer): void;\n\tsetColumns(columns: FlowColumns): void;\n\tsetObstacles(obstacles: readonly Obstacle[]): void;\n\treadonly segments: Node<readonly PreparedSegment[]>;\n\treadonly flowLines: Node<FlowLinesResult>;\n}\n\nconst kinsokuStart = /* @__PURE__ */ new Set([\n\t\"\\u3001\",\n\t\"\\u3002\",\n\t\"\\u30FB\",\n\t\"\\uFF09\",\n\t\"\\u3015\",\n\t\"\\u3009\",\n\t\"\\u300B\",\n\t\"\\u300D\",\n\t\"\\u300F\",\n\t\"\\u3011\",\n]);\n\nconst leftStickyPunctuation = /* @__PURE__ */ new Set([\n\t\".\",\n\t\",\",\n\t\"!\",\n\t\"?\",\n\t\":\",\n\t\";\",\n\t\")\",\n\t\"]\",\n\t\"}\",\n\t\"%\",\n\t'\"',\n\t\"\\u201D\",\n\t\"\\u2019\",\n\t\"\\xBB\",\n\t\"\\u203A\",\n\t\"\\u2026\",\n]);\n\nfunction isCJK(text: string): boolean {\n\tfor (const ch of text) {\n\t\tconst c = ch.codePointAt(0);\n\t\tif (\n\t\t\t(c !== undefined && c >= 19968 && c <= 40959) ||\n\t\t\t(c !== undefined && c >= 13312 && c <= 19903) ||\n\t\t\t(c !== undefined && c >= 12288 && c <= 12351) ||\n\t\t\t(c !== undefined && c >= 12352 && c <= 12447) ||\n\t\t\t(c !== undefined && c >= 44032 && c <= 55215) ||\n\t\t\t(c !== undefined && c >= 65280 && c <= 65519)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction normalizeWhitespace(text: string): string {\n\treturn text.replace(/[\\t\\f ]+/g, \" \").replace(/^ | $/g, \"\");\n}\n\nfunction segmentText(\n\ttext: string,\n\tsegmentAdapter: SegmentAdapter,\n): {\n\treadonly texts: string[];\n\treadonly isWordLike: boolean[];\n\treadonly kinds: SegmentBreakKind[];\n}[] {\n\tconst pieces: {\n\t\ttexts: string[];\n\t\tisWordLike: boolean[];\n\t\tkinds: SegmentBreakKind[];\n\t}[] = [];\n\tfor (const s of segmentAdapter.segmentWords(text)) {\n\t\tconst wordSegment = s.segment;\n\t\tconst rawWordLike = s.isWordLike ?? false;\n\t\tconst pieceTexts: string[] = [];\n\t\tconst pieceWordLikes: boolean[] = [];\n\t\tconst pieceKinds: SegmentBreakKind[] = [];\n\t\tlet currentText = \"\";\n\t\tlet currentKind: SegmentBreakKind | null = null;\n\t\tfor (const ch of wordSegment) {\n\t\t\tlet kind: SegmentBreakKind;\n\t\t\tif (ch === \" \") {\n\t\t\t\tkind = \"space\";\n\t\t\t} else if (ch === \"\\u200B\") {\n\t\t\t\tkind = \"zero-width-break\";\n\t\t\t} else if (ch === \"\\xAD\") {\n\t\t\t\tkind = \"soft-hyphen\";\n\t\t\t} else if (ch === \"\\n\") {\n\t\t\t\tkind = \"hard-break\";\n\t\t\t} else {\n\t\t\t\tkind = \"text\";\n\t\t\t}\n\t\t\tif (currentKind !== null && kind === currentKind) {\n\t\t\t\tcurrentText += ch;\n\t\t\t} else {\n\t\t\t\tif (currentKind !== null) {\n\t\t\t\t\tpieceTexts.push(currentText);\n\t\t\t\t\tpieceWordLikes.push(currentKind === \"text\" && rawWordLike);\n\t\t\t\t\tpieceKinds.push(currentKind);\n\t\t\t\t}\n\t\t\t\tcurrentText = ch;\n\t\t\t\tcurrentKind = kind;\n\t\t\t}\n\t\t}\n\t\tif (currentKind !== null) {\n\t\t\tpieceTexts.push(currentText);\n\t\t\tpieceWordLikes.push(currentKind === \"text\" && rawWordLike);\n\t\t\tpieceKinds.push(currentKind);\n\t\t}\n\t\tpieces.push({ texts: pieceTexts, isWordLike: pieceWordLikes, kinds: pieceKinds });\n\t}\n\treturn pieces;\n}\n\nfunction* fallbackSegmentWords(text: string): Iterable<SegmentInfo> {\n\tlet index = 0;\n\tlet current = \"\";\n\tlet currentIndex = 0;\n\tlet currentWordLike: boolean | null = null;\n\tconst flush = () => {\n\t\tif (current.length === 0 || currentWordLike === null) return undefined;\n\t\tconst out = { segment: current, index: currentIndex, isWordLike: currentWordLike };\n\t\tcurrent = \"\";\n\t\tcurrentWordLike = null;\n\t\treturn out;\n\t};\n\tfor (const ch of text) {\n\t\tconst isWordLike = !/[\\s\\u200B\\u00AD]/u.test(ch);\n\t\tif (currentWordLike !== null && currentWordLike !== isWordLike) {\n\t\t\tconst out = flush();\n\t\t\tif (out) yield out;\n\t\t}\n\t\tif (currentWordLike === null) {\n\t\t\tcurrentWordLike = isWordLike;\n\t\t\tcurrentIndex = index;\n\t\t}\n\t\tcurrent += ch;\n\t\tindex += ch.length;\n\t}\n\tconst out = flush();\n\tif (out) yield out;\n}\n\nfunction* fallbackSegmentGraphemes(text: string): Iterable<SegmentInfo> {\n\tlet index = 0;\n\tfor (const ch of text) {\n\t\tyield { segment: ch, index };\n\t\tindex += ch.length;\n\t}\n}\n\nfunction createDefaultSegmentAdapter(): SegmentAdapter {\n\treturn {\n\t\tsegmentWords(text: string): Iterable<SegmentInfo> {\n\t\t\treturn fallbackSegmentWords(text);\n\t\t},\n\t\tsegmentGraphemes(text: string): Iterable<SegmentInfo> {\n\t\t\treturn fallbackSegmentGraphemes(text);\n\t\t},\n\t};\n}\n\nlet defaultSegmentAdapter: SegmentAdapter | null = null;\n\nfunction getDefaultSegmentAdapter(): SegmentAdapter {\n\tif (defaultSegmentAdapter === null) {\n\t\tdefaultSegmentAdapter = createDefaultSegmentAdapter();\n\t}\n\treturn defaultSegmentAdapter;\n}\n\nfunction measuredWidth(value: number | { readonly width: number }): number {\n\tconst width = typeof value === \"number\" ? value : value.width;\n\treturn Number.isFinite(width) && width >= 0 ? width : 0;\n}\n\nfunction metricKey(text: string, font: string): string {\n\treturn `${font}\\0${text}`;\n}\n\n/** Adapter that wraps a caller-owned synchronous measurement function. */\nexport class InjectedMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly measure: MeasureFn;\n\tprivate readonly shouldCache: boolean;\n\tprivate readonly cache = new Map<string, number>();\n\n\tconstructor(measure: MeasureFn, opts: InjectedMeasureAdapterOptions = {}) {\n\t\tthis.measure = measure;\n\t\tthis.shouldCache = opts.cache ?? true;\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\tconst key = metricKey(text, font);\n\t\tif (this.shouldCache) {\n\t\t\tconst cached = this.cache.get(key);\n\t\t\tif (cached !== undefined) return { width: cached };\n\t\t}\n\t\tconst width = measuredWidth(this.measure(text, font));\n\t\tif (this.shouldCache) this.cache.set(key, width);\n\t\treturn { width };\n\t}\n\n\tclearCache(): void {\n\t\tthis.cache.clear();\n\t}\n}\n\n/** Deterministic adapter backed by caller-supplied width metrics. */\nexport class PrecomputedMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly metrics: ReadonlyMap<string, number>;\n\tprivate readonly fallback: \"per-char\" | \"error\";\n\tprivate readonly cellWidth: number;\n\n\tconstructor(opts: PrecomputedMeasureAdapterOptions) {\n\t\tthis.metrics =\n\t\t\topts.metrics instanceof Map ? opts.metrics : new Map(Object.entries(opts.metrics));\n\t\tthis.fallback = opts.fallback ?? \"error\";\n\t\tthis.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\tconst fontScoped = this.metrics.get(metricKey(text, font));\n\t\tif (fontScoped !== undefined) return { width: nonNegativeFinite(fontScoped, 0) };\n\t\tconst unscoped = this.metrics.get(text);\n\t\tif (unscoped !== undefined) return { width: nonNegativeFinite(unscoped, 0) };\n\t\tif (this.fallback === \"per-char\") {\n\t\t\treturn { width: Array.from(text).length * this.cellWidth };\n\t\t}\n\t\tthrow new Error(`No precomputed metric for segment ${JSON.stringify(text)}`);\n\t}\n}\n\n/** Fixed-cell adapter for CLI, snapshots, and tests. */\nexport class CellMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly cellWidth: number;\n\tprivate readonly wideCellWidth: number;\n\tprivate readonly tabCells: number;\n\n\tconstructor(opts: CellMeasureAdapterOptions = {}) {\n\t\tthis.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);\n\t\tthis.wideCellWidth = nonNegativeFinite(\n\t\t\topts.wideCellWidth ?? this.cellWidth * 2,\n\t\t\tthis.cellWidth * 2,\n\t\t);\n\t\tthis.tabCells = Math.max(1, Math.floor(nonNegativeFinite(opts.tabCells ?? 4, 4)));\n\t}\n\n\tmeasureSegment(text: string): { readonly width: number } {\n\t\tlet width = 0;\n\t\tfor (const char of text) {\n\t\t\tif (char === \"\\t\") width += this.cellWidth * this.tabCells;\n\t\t\telse width += isCJK(char) ? this.wideCellWidth : this.cellWidth;\n\t\t}\n\t\treturn { width };\n\t}\n}\n\n/** Adapter over a caller-owned platform capability such as NodeCanvas, Skia, or RN text APIs. */\nexport class CapabilityMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly capability: TextMeasureCapability;\n\n\tconstructor(capability: TextMeasureCapability) {\n\t\tthis.capability = capability;\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\treturn { width: measuredWidth(this.capability.measureText(text, font)) };\n\t}\n\n\tclearCache(): void {\n\t\tthis.capability.clearCache?.();\n\t}\n}\n\nfunction stripSvgIgnoredContent(svg: string): string {\n\treturn svg.replace(/<!--[\\s\\S]*?-->/g, \"\").replace(/<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/g, \"\");\n}\n\nfunction readSvgRootTag(svg: string): string | null {\n\treturn /<svg\\b[^>]*>/i.exec(svg)?.[0] ?? null;\n}\n\nfunction readNumericAttr(tag: string, attr: string): number | null {\n\tconst pattern = new RegExp(`(?:^|\\\\s)${attr}\\\\s*=\\\\s*[\"']?(-?\\\\d+(?:\\\\.\\\\d+)?)`, \"i\");\n\tconst match = pattern.exec(tag);\n\tif (!match) return null;\n\tconst value = Number(match[1]);\n\treturn Number.isFinite(value) && value >= 0 ? value : null;\n}\n\nfunction readViewBox(tag: string): Size | null {\n\tconst match =\n\t\t/\\bviewBox\\s*=\\s*[\"']\\s*(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s*[\"']/i.exec(\n\t\t\ttag,\n\t\t);\n\tif (!match) return null;\n\tconst width = Number(match[3]);\n\tconst height = Number(match[4]);\n\tif (!Number.isFinite(width) || !Number.isFinite(height) || width < 0 || height < 0) {\n\t\treturn null;\n\t}\n\treturn { width, height };\n}\n\n/**\n * Minimal string-based SVG bounds reader for explicit width/height or viewBox.\n *\n * This is not a DOM SVG parser and does not resolve external resources.\n */\nexport class SvgBoundsAdapter implements SvgMeasurer {\n\tmeasureSvg(svg: string): Size {\n\t\tconst cleaned = stripSvgIgnoredContent(svg);\n\t\tconst rootTag = readSvgRootTag(cleaned);\n\t\tif (rootTag === null) throw new Error(\"Cannot measure SVG without a root <svg> element\");\n\t\tconst width = readNumericAttr(rootTag, \"width\");\n\t\tconst height = readNumericAttr(rootTag, \"height\");\n\t\tif (width !== null && height !== null) return { width, height };\n\t\tconst viewBox = readViewBox(rootTag);\n\t\tif (viewBox) return viewBox;\n\t\tthrow new Error(\"Cannot measure SVG without width/height or viewBox\");\n\t}\n}\n\n/** Image measurer backed by explicit caller-provided dimensions; it never loads images. */\nexport class ImageSizeAdapter implements ImageMeasurer {\n\tprivate readonly sizes: ImageSizeLookup;\n\n\tconstructor(sizes: ImageSizeLookup | Record<string, Size>) {\n\t\tthis.sizes = isImageSizeLookup(sizes) ? sizes : new Map(Object.entries(sizes));\n\t}\n\n\tmeasureImage(src: string): Size {\n\t\tconst size = this.sizes.get(src);\n\t\tif (!size) throw new Error(`No image size registered for ${JSON.stringify(src)}`);\n\t\treturn size;\n\t}\n}\n\nfunction isImageSizeLookup(value: unknown): value is ImageSizeLookup {\n\tif (value === null) return false;\n\tconst valueType = typeof value;\n\tif (valueType !== \"object\" && valueType !== \"function\") return false;\n\treturn typeof (value as { readonly get?: unknown }).get === \"function\";\n}\n\nfunction measurementIssue(\n\tcode: string,\n\tmessage: string,\n\ttargetId: string,\n\tmeasurementKind: string,\n\topts: {\n\t\treadonly source?: string;\n\t\treadonly details?: unknown;\n\t\treadonly metadata?: Record<string, unknown>;\n\t\treadonly severity?: DataIssue[\"severity\"];\n\t} = {},\n): MeasurementIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: opts.severity ?? \"warning\",\n\t\tsource: opts.source,\n\t\tsubjectId: targetId,\n\t\tmeasurementKind,\n\t\tdetails: opts.details,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nfunction measurementOk<T>(\n\ttargetId: string,\n\tmeasurementKind: string,\n\tvalue: T,\n\topts: { readonly source?: string; readonly metadata?: Record<string, unknown> } = {},\n): MeasurementResult<T> {\n\treturn {\n\t\tkind: \"ok\",\n\t\ttargetId,\n\t\tmeasurementKind,\n\t\tvalue,\n\t\tsource: opts.source,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nfunction latestMeasurementValue<T>(\n\tmeasurements: Measurements,\n\ttargetId: string,\n\tmeasurementKind: string,\n): T | undefined {\n\tlet value: T | undefined;\n\tfor (const fact of measurements) {\n\t\tif (\n\t\t\tfact.kind === \"ok\" &&\n\t\t\tfact.targetId === targetId &&\n\t\t\tfact.measurementKind === measurementKind\n\t\t) {\n\t\t\tvalue = fact.value as T;\n\t\t}\n\t}\n\treturn value;\n}\n\nfunction tryMeasureHyphenWidth(adapter: MeasurementAdapter, font: string): number | undefined {\n\ttry {\n\t\treturn nonNegativeFinite(adapter.measureSegment(\"-\", font).width, 0);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validMeasurementSize(size: Size, label: string): Size {\n\tif (\n\t\t!Number.isFinite(size.width) ||\n\t\t!Number.isFinite(size.height) ||\n\t\tsize.width < 0 ||\n\t\tsize.height < 0\n\t) {\n\t\tthrow new Error(`Invalid ${label} measurement size`);\n\t}\n\treturn size;\n}\n\nfunction textMeasurementFacts(\n\ttext: string,\n\tfont: string,\n\tadapter: MeasurementAdapter,\n\tcache: Map<string, Map<string, number>>,\n\tsegmentAdapter: SegmentAdapter,\n\ttargetId: string,\n\tsource: string,\n): Measurements {\n\ttry {\n\t\tconst segments = analyzeAndMeasure(text, font, adapter, cache, undefined, segmentAdapter);\n\t\tconst hyphenWidth = tryMeasureHyphenWidth(adapter, font);\n\t\tconst facts: MeasurementFact<TextSegmentsMeasurement>[] = [\n\t\t\tmeasurementOk<TextSegmentsMeasurement>(\n\t\t\t\ttargetId,\n\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\thyphenWidth === undefined ? { segments } : { segments, hyphenWidth },\n\t\t\t\t{ source },\n\t\t\t),\n\t\t];\n\t\tif (hyphenWidth === undefined) {\n\t\t\tfacts.push(\n\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\"measurement.hyphen.failed\",\n\t\t\t\t\t`Hyphen measurement failed for '${targetId}'`,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t\t{ source, severity: \"warning\" },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn facts;\n\t} catch (error) {\n\t\treturn [\n\t\t\tmeasurementIssue(\n\t\t\t\t\"measurement.failed\",\n\t\t\t\t`Text measurement failed for '${targetId}'`,\n\t\t\t\ttargetId,\n\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t{ source, details: error, severity: \"error\" },\n\t\t\t),\n\t\t];\n\t}\n}\n\nfunction inputNode<T>(\n\tg: Graph,\n\tinput: T | Node<T> | undefined,\n\tfallback: T,\n\tname: string,\n): { readonly node: Node<T>; readonly set: (value: T) => void } {\n\tif (input instanceof Node) {\n\t\treturn {\n\t\t\tnode: input,\n\t\t\tset(value: T): void {\n\t\t\t\tconst maybeState = input as Node<T> & { set?: (next: T) => void };\n\t\t\t\tif (typeof maybeState.set !== \"function\") {\n\t\t\t\t\tthrow new TypeError(`reactive-layout input '${name}' is not a writable state node`);\n\t\t\t\t}\n\t\t\t\tmaybeState.set(value);\n\t\t\t},\n\t\t};\n\t}\n\tconst state: StateNode<T> = g.state(input ?? fallback, { name });\n\treturn { node: state, set: (value: T) => state.set(value) };\n}\n\nfunction scopedName(scope: string, local: string): string {\n\treturn scope === local ? local : `${scope}:${local}`;\n}\n\n/** Generic sync text measurement provider that emits graph-visible measurement facts. */\nexport function textMeasurementProvider(opts: TextMeasurementProviderOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeAdapter: MeasurementAdapter | null = null;\n\treturn opts.graph.node<Measurements>(\n\t\topts.segmentAdapter\n\t\t\t? [opts.text, opts.font, opts.adapter, opts.segmentAdapter]\n\t\t\t: [opts.text, opts.font, opts.adapter],\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\t(depLatest(ctx, 2) as MeasurementAdapter).clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\tconst text = depLatest(ctx, 0) as string;\n\t\t\tconst font = depLatest(ctx, 1) as string;\n\t\t\tconst adapter = depLatest(ctx, 2) as MeasurementAdapter;\n\t\t\tif (adapter !== activeAdapter) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveAdapter = adapter;\n\t\t\t}\n\t\t\tconst segmentAdapter =\n\t\t\t\topts.segmentAdapter === undefined\n\t\t\t\t\t? getDefaultSegmentAdapter()\n\t\t\t\t\t: (depLatest(ctx, 3) as SegmentAdapter);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\ttextMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for caller-injected synchronous text measurement. */\nexport function injectedTextMeasurements(\n\topts: InjectedTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(\n\t\tnew InjectedMeasureAdapter(opts.measure, { cache: opts.cache }),\n\t\t{\n\t\t\tname: opts.name\n\t\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t\t: `${targetId}-measure-capability`,\n\t\t},\n\t);\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"injectedTextMeasurements\",\n\t});\n}\n\n/** Provider helper for deterministic precomputed text metrics. */\nexport function precomputedTextMeasurements(\n\topts: PrecomputedTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(new PrecomputedMeasureAdapter(opts), {\n\t\tname: opts.name\n\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t: `${targetId}-measure-capability`,\n\t});\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"precomputedTextMeasurements\",\n\t});\n}\n\n/** Provider helper for fixed-cell terminal/snapshot text measurement. */\nexport function cellTextMeasurements(opts: CellTextMeasurementsOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(new CellMeasureAdapter(opts), {\n\t\tname: opts.name\n\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t: `${targetId}-measure-capability`,\n\t});\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"cellTextMeasurements\",\n\t});\n}\n\n/** Provider helper for caller-injected platform text capability nodes. */\nexport function capabilityTextMeasurements(\n\topts: CapabilityTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.node<MeasurementAdapter>(\n\t\t[opts.capability],\n\t\t(ctx: Ctx) => {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", new CapabilityMeasureAdapter(depLatest(ctx, 0) as TextMeasureCapability)],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: opts.name\n\t\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t\t: `${targetId}-measure-capability`,\n\t\t},\n\t);\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"capabilityTextMeasurements\",\n\t});\n}\n\n/** Provider helper that makes readiness facts an explicit measurement dependency. */\nexport function readinessTextMeasurements(\n\topts: ReadinessTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeAdapter: MeasurementAdapter | null = null;\n\tlet activeReadiness: MeasurementReadiness | null = null;\n\tconst deps = opts.segmentAdapter\n\t\t? [opts.text, opts.font, opts.adapter, opts.readiness, opts.segmentAdapter]\n\t\t: [opts.text, opts.font, opts.adapter, opts.readiness];\n\treturn opts.graph.node<Measurements>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\t(depLatest(ctx, 2) as MeasurementAdapter).clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\tconst text = depLatest(ctx, 0) as string;\n\t\t\tconst font = depLatest(ctx, 1) as string;\n\t\t\tconst adapter = depLatest(ctx, 2) as MeasurementAdapter;\n\t\t\tif (adapter !== activeAdapter) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveAdapter = adapter;\n\t\t\t}\n\t\t\tconst readiness = depLatest(ctx, 3) as MeasurementReadiness;\n\t\t\tif (readiness !== activeReadiness) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveReadiness = readiness;\n\t\t\t}\n\t\t\tif (!readiness.ready) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\treadiness.code ?? \"measurement.not-ready\",\n\t\t\t\t\t\t\t\treadiness.message ?? `Measurement readiness blocked '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\t\t\tdetails: readiness.details,\n\t\t\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst segmentAdapter =\n\t\t\t\topts.segmentAdapter === undefined\n\t\t\t\t\t? getDefaultSegmentAdapter()\n\t\t\t\t\t: (depLatest(ctx, 4) as SegmentAdapter);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\ttextMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper that emits graph-visible readiness facts without measuring layout. */\nexport function readinessMeasurements(opts: ReadinessMeasurementsOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"measurement-readiness\";\n\tconst measurementKind = opts.measurementKind ?? READINESS_MEASUREMENT_KIND;\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.readiness],\n\t\t(ctx: Ctx) => {\n\t\t\tconst readiness = depLatest(ctx, 0) as MeasurementReadiness;\n\t\t\tif (!readiness.ready) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\treadiness.code ?? \"measurement.not-ready\",\n\t\t\t\t\t\t\t\treadiness.message ?? `Measurement readiness blocked '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\t\t\tdetails: readiness.details,\n\t\t\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t[\n\t\t\t\t\t\tmeasurementOk<MeasurementReadiness>(targetId, measurementKind, readiness, {\n\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t}),\n\t\t\t\t\t],\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for image-size facts from caller-owned synchronous image measurers. */\nexport function imageSizeMeasurements(opts: ImageSizeMeasurementsOptions): Node<Measurements> {\n\tconst measurementKind = opts.measurementKind ?? IMAGE_SIZE_MEASUREMENT_KIND;\n\tconst name = opts.name ?? \"image-size-measurements\";\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.images, opts.measurer],\n\t\t(ctx: Ctx) => {\n\t\t\tconst images = depLatest(ctx, 0) as readonly ImageSizeMeasurementTarget[];\n\t\t\tconst measurer = depLatest(ctx, 1) as ImageMeasurer;\n\t\t\tconst facts: MeasurementFact<Size>[] = [];\n\t\t\tfor (let i = 0; i < images.length; i += 1) {\n\t\t\t\tconst image = (images as readonly (ImageSizeMeasurementTarget | undefined)[])[i];\n\t\t\t\tconst subjectId = image?.id ?? image?.src ?? `image:${i}`;\n\t\t\t\ttry {\n\t\t\t\t\tif (image === undefined) throw new Error(`Missing image target at index ${i}`);\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementOk<Size>(\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\tvalidMeasurementSize(measurer.measureImage(image.src), \"image\"),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tmetadata: image.metadata,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\"measurement.image-size.failed\",\n\t\t\t\t\t\t\t`Image size measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tdetails: { error, index: i, src: image?.src },\n\t\t\t\t\t\t\t\tmetadata: image?.metadata,\n\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for SVG bounds facts from caller-owned synchronous SVG measurers. */\nexport function svgBoundsMeasurements(opts: SvgBoundsMeasurementsOptions): Node<Measurements> {\n\tconst measurementKind = opts.measurementKind ?? SVG_BOUNDS_MEASUREMENT_KIND;\n\tconst name = opts.name ?? \"svg-bounds-measurements\";\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.svgs, opts.measurer],\n\t\t(ctx: Ctx) => {\n\t\t\tconst svgs = depLatest(ctx, 0) as readonly SvgBoundsMeasurementTarget[];\n\t\t\tconst measurer = depLatest(ctx, 1) as SvgMeasurer;\n\t\t\tconst facts: MeasurementFact<Size>[] = [];\n\t\t\tfor (let i = 0; i < svgs.length; i += 1) {\n\t\t\t\tconst svg = (svgs as readonly (SvgBoundsMeasurementTarget | undefined)[])[i];\n\t\t\t\tconst subjectId = svg?.id ?? `svg:${i}`;\n\t\t\t\ttry {\n\t\t\t\t\tif (svg === undefined) throw new Error(`Missing SVG target at index ${i}`);\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementOk<Size>(\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\tvalidMeasurementSize(measurer.measureSvg(svg.svg), \"SVG\"),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tmetadata: svg.metadata,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\"measurement.svg-bounds.failed\",\n\t\t\t\t\t\t\t`SVG bounds measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tdetails: { error, index: i },\n\t\t\t\t\t\t\t\tmetadata: svg?.metadata,\n\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Merge provider fact nodes into the single measurements node consumed by layout bundles. */\nexport function mergeMeasurements(opts: MergeMeasurementsOptions): Node<Measurements> {\n\tconst sources = [...opts.sources];\n\treturn opts.graph.node<Measurements>(\n\t\tsources as readonly Node<unknown>[],\n\t\t(ctx: Ctx) => {\n\t\t\tconst facts: MeasurementFact[] = [];\n\t\t\tfor (let i = 0; i < sources.length; i += 1) {\n\t\t\t\tfacts.push(...(depLatest(ctx, i) as Measurements));\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name: opts.name ?? \"measurements\" },\n\t);\n}\n\n/** Compose optional block measurement capability nodes into one graph-visible adapter node. */\nexport function blockAdaptersProvider(opts: BlockAdaptersProviderOptions): Node<BlockAdapters> {\n\tconst deps: Node<unknown>[] = [];\n\tconst positions: { text?: number; svg?: number; image?: number } = {};\n\tif (opts.text) {\n\t\tpositions.text = deps.length;\n\t\tdeps.push(opts.text);\n\t}\n\tif (opts.svg) {\n\t\tpositions.svg = deps.length;\n\t\tdeps.push(opts.svg);\n\t}\n\tif (opts.image) {\n\t\tpositions.image = deps.length;\n\t\tdeps.push(opts.image);\n\t}\n\treturn opts.graph.node<BlockAdapters>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst adapters: BlockAdapters = {\n\t\t\t\ttext:\n\t\t\t\t\tpositions.text === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: (depLatest(ctx, positions.text) as MeasurementAdapter),\n\t\t\t\tsvg:\n\t\t\t\t\tpositions.svg === undefined ? undefined : (depLatest(ctx, positions.svg) as SvgMeasurer),\n\t\t\t\timage:\n\t\t\t\t\tpositions.image === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: (depLatest(ctx, positions.image) as ImageMeasurer),\n\t\t\t};\n\t\t\tctx.down([[\"DATA\", adapters]]);\n\t\t},\n\t\t{ name: opts.name ?? \"block-adapters\" },\n\t);\n}\n\n/** Provider helper for block measurement facts over declared block/max-width deps. */\nexport function blockMeasurementProvider(\n\topts: BlockMeasurementProviderOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"blocks\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeTextAdapter: MeasurementAdapter | undefined;\n\tconst deps = [opts.blocks, opts.maxWidth, opts.adapters] as Node<unknown>[];\n\tif (opts.font) deps.push(opts.font);\n\tif (opts.lineHeight) deps.push(opts.lineHeight);\n\tif (opts.segmentAdapter) deps.push(opts.segmentAdapter);\n\treturn opts.graph.node<Measurements>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\tconst adapters = depLatest(ctx, 2) as BlockAdapters;\n\t\t\t\tadapters.text?.clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\ttry {\n\t\t\t\tconst blocks = depLatest(ctx, 0) as readonly ContentBlock[];\n\t\t\t\tconst maxWidth = nonNegativeFinite(depLatest(ctx, 1) as number, 0);\n\t\t\t\tconst adapters = depLatest(ctx, 2) as BlockAdapters;\n\t\t\t\tif (adapters.text !== activeTextAdapter) {\n\t\t\t\t\tcache.clear();\n\t\t\t\t\tactiveTextAdapter = adapters.text;\n\t\t\t\t}\n\t\t\t\tlet depIndex = 3;\n\t\t\t\tconst font = opts.font ? (depLatest(ctx, depIndex++) as string) : undefined;\n\t\t\t\tconst lineHeight = opts.lineHeight\n\t\t\t\t\t? nonNegativeFinite(depLatest(ctx, depIndex++) as number, 0)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst segmentAdapter = opts.segmentAdapter\n\t\t\t\t\t? (depLatest(ctx, depIndex) as SegmentAdapter)\n\t\t\t\t\t: getDefaultSegmentAdapter();\n\t\t\t\tconst measured: MeasuredBlock[] = [];\n\t\t\t\tconst issues: MeasurementIssue[] = [];\n\t\t\t\tfor (let i = 0; i < blocks.length; i += 1) {\n\t\t\t\t\tconst block = (blocks as readonly (ContentBlock | undefined)[])[i];\n\t\t\t\t\tconst subjectId = block?.id ?? `${targetId}:${i}`;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (block === undefined) {\n\t\t\t\t\t\t\tthrow new Error(`Missing content block at index ${i}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst blockFont =\n\t\t\t\t\t\t\tblock.kind === \"text\" ? (block.font ?? font ?? \"16px sans-serif\") : undefined;\n\t\t\t\t\t\tconst hyphenWidth =\n\t\t\t\t\t\t\tblock.kind === \"text\" && adapters.text\n\t\t\t\t\t\t\t\t? tryMeasureHyphenWidth(adapters.text, blockFont ?? \"16px sans-serif\")\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tmeasured.push(\n\t\t\t\t\t\t\tmeasureBlock(block, {\n\t\t\t\t\t\t\t\tadapters,\n\t\t\t\t\t\t\t\tfont,\n\t\t\t\t\t\t\t\thyphenWidth,\n\t\t\t\t\t\t\t\tlineHeight,\n\t\t\t\t\t\t\t\tmaxWidth,\n\t\t\t\t\t\t\t\tcache,\n\t\t\t\t\t\t\t\tsegmentAdapter,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (block.kind === \"text\" && adapters.text) {\n\t\t\t\t\t\t\tif (hyphenWidth === undefined) {\n\t\t\t\t\t\t\t\tissues.push(\n\t\t\t\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\t\t\"measurement.hyphen.failed\",\n\t\t\t\t\t\t\t\t\t\t`Hyphen measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\t\t\t\tdetails: { targetId, index: i },\n\t\t\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tissues.push(\n\t\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\"measurement.block.failed\",\n\t\t\t\t\t\t\t\t`Block measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\t\tdetails: { error, targetId, index: i, blockKind: block?.kind },\n\t\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\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\tmeasurementOk<BlocksMeasurement>(\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{ blocks: measured },\n\t\t\t\t\t\t\t\t{ source },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...issues,\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t} catch (error) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\"measurement.failed\",\n\t\t\t\t\t\t\t\t`Block measurement failed for '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{ source, details: error, severity: \"error\" },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Segment text and measure every resulting segment with a caller-owned synchronous adapter. */\nexport function analyzeAndMeasure(\n\ttext: string,\n\tfont: string,\n\tadapter: MeasurementAdapter,\n\tcache: Map<string, Map<string, number>>,\n\tstats?: SegmentMeasureStats,\n\tsegmentAdapter?: SegmentAdapter,\n): PreparedSegment[] {\n\tconst normalized = normalizeWhitespace(text);\n\tif (normalized.length === 0) {\n\t\treturn [];\n\t}\n\tconst segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst pieces = segmentText(normalized, segAdapter);\n\tconst rawTexts: string[] = [];\n\tconst rawKinds: SegmentBreakKind[] = [];\n\tconst rawWordLike: boolean[] = [];\n\tfor (const piece of pieces) {\n\t\tfor (let i = 0; i < piece.texts.length; i += 1) {\n\t\t\trawTexts.push(piece.texts[i]);\n\t\t\trawKinds.push(piece.kinds[i]);\n\t\t\trawWordLike.push(piece.isWordLike[i]);\n\t\t}\n\t}\n\tconst mergedTexts: string[] = [];\n\tconst mergedKinds: SegmentBreakKind[] = [];\n\tconst mergedWordLike: boolean[] = [];\n\tfor (let i = 0; i < rawTexts.length; i += 1) {\n\t\tconst t = rawTexts[i];\n\t\tconst k = rawKinds[i];\n\t\tconst wl = rawWordLike[i];\n\t\tif (\n\t\t\tk === \"text\" &&\n\t\t\t!wl &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedTexts.length - 1] === \"text\"\n\t\t) {\n\t\t\tconst isSticky = t.length === 1 && (leftStickyPunctuation.has(t) || kinsokuStart.has(t));\n\t\t\tif (isSticky) {\n\t\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tt === \"-\" &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedKinds.length - 1] === \"text\" &&\n\t\t\tmergedWordLike[mergedWordLike.length - 1]\n\t\t) {\n\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\tcontinue;\n\t\t}\n\t\tmergedTexts.push(t);\n\t\tmergedKinds.push(k);\n\t\tmergedWordLike.push(wl);\n\t}\n\tconst fontCache = cache.get(font) ?? new Map<string, number>();\n\tif (!cache.has(font)) cache.set(font, fontCache);\n\tfunction measureCached(segment: string): number {\n\t\tconst cached = fontCache.get(segment);\n\t\tif (cached === undefined) {\n\t\t\tif (stats) stats.misses += 1;\n\t\t\tconst measured = adapter.measureSegment(segment, font).width;\n\t\t\tconst width = Number.isFinite(measured) && measured >= 0 ? measured : 0;\n\t\t\tfontCache.set(segment, width);\n\t\t\treturn width;\n\t\t}\n\t\tif (stats) stats.hits += 1;\n\t\treturn cached;\n\t}\n\tconst out: PreparedSegment[] = [];\n\tfor (let i = 0; i < mergedTexts.length; i += 1) {\n\t\tconst t = mergedTexts[i];\n\t\tconst kind = mergedKinds[i];\n\t\tif (kind !== \"text\") {\n\t\t\tout.push({\n\t\t\t\ttext: t,\n\t\t\t\twidth: kind === \"space\" ? measureCached(\" \") * t.length : 0,\n\t\t\t\tkind,\n\t\t\t\tgraphemeWidths: null,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (isCJK(t)) {\n\t\t\tlet unitText = \"\";\n\t\t\tfor (const graphemeSegment of segAdapter.segmentGraphemes(t)) {\n\t\t\t\tconst grapheme = graphemeSegment.segment;\n\t\t\t\tif (unitText.length > 0 && kinsokuStart.has(grapheme)) {\n\t\t\t\t\tunitText += grapheme;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (unitText.length > 0) {\n\t\t\t\t\tout.push({\n\t\t\t\t\t\ttext: unitText,\n\t\t\t\t\t\twidth: measureCached(unitText),\n\t\t\t\t\t\tkind: \"text\",\n\t\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tunitText = grapheme;\n\t\t\t}\n\t\t\tif (unitText.length > 0) {\n\t\t\t\tout.push({\n\t\t\t\t\ttext: unitText,\n\t\t\t\t\twidth: measureCached(unitText),\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst textWidth = measureCached(t);\n\t\tlet graphemeWidths: number[] | null = null;\n\t\tif (mergedWordLike[i] && t.length > 1) {\n\t\t\tconst widths = [];\n\t\t\tfor (const grapheme of segAdapter.segmentGraphemes(t)) {\n\t\t\t\twidths.push(measureCached(grapheme.segment));\n\t\t\t}\n\t\t\tif (widths.length > 1) graphemeWidths = widths;\n\t\t}\n\t\tout.push({\n\t\t\ttext: t,\n\t\t\twidth: textWidth,\n\t\t\tkind: \"text\",\n\t\t\tgraphemeWidths,\n\t\t});\n\t}\n\treturn out;\n}\n\n/** Greedy single-column line breaking over prepared segments. */\nexport function computeLineBreaks(\n\tsegments: readonly PreparedSegment[],\n\tmaxWidth: number,\n\topts: { readonly hyphenWidth?: number; readonly segmentAdapter?: SegmentAdapter } = {},\n): LineBreaksResult {\n\tif (segments.length === 0) return { lines: [], lineCount: 0 };\n\tconst segAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst lines: LayoutLine[] = [];\n\tlet cursor: LayoutCursor = { segmentIndex: 0, graphemeIndex: 0 };\n\twhile (cursor.segmentIndex < segments.length) {\n\t\tconst next = layoutNextLine(segments, cursor, maxWidth, {\n\t\t\thyphenWidth: opts.hyphenWidth,\n\t\t\tsegmentAdapter: segAdapter,\n\t\t});\n\t\tif (next === null) break;\n\t\tlines.push({\n\t\t\ttext: next.text,\n\t\t\twidth: next.width,\n\t\t\tstartSegment: next.start.segmentIndex,\n\t\t\tstartGrapheme: next.start.graphemeIndex,\n\t\t\tendSegment: next.end.segmentIndex,\n\t\t\tendGrapheme: next.end.graphemeIndex,\n\t\t});\n\t\tif (\n\t\t\tnext.end.segmentIndex === cursor.segmentIndex &&\n\t\t\tnext.end.graphemeIndex === cursor.graphemeIndex\n\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tcursor = next.end;\n\t}\n\treturn { lines, lineCount: lines.length };\n}\n\nfunction canBreakAfter(kind: SegmentBreakKind): boolean {\n\treturn kind === \"space\" || kind === \"zero-width-break\" || kind === \"soft-hyphen\";\n}\n\nfunction sliceSegmentText(\n\tseg: PreparedSegment,\n\tstartGrapheme: number,\n\tendGrapheme: number,\n\tsegmentAdapter: SegmentAdapter,\n): string {\n\tif (startGrapheme === 0 && endGrapheme < 0) return seg.text;\n\tconst graphemes = [...segmentAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);\n\tconst stop = endGrapheme < 0 ? graphemes.length : endGrapheme;\n\treturn graphemes.slice(startGrapheme, stop).join(\"\");\n}\n\nfunction buildLineText(\n\tsegments: readonly PreparedSegment[],\n\tstartSegment: number,\n\tstartGrapheme: number,\n\tendSegment: number,\n\tendGrapheme: number,\n\tappendHyphen: boolean,\n\tsegmentAdapter: SegmentAdapter,\n): string {\n\tlet text = \"\";\n\tfor (let i = startSegment; i < endSegment; i += 1) {\n\t\tconst seg = segments[i];\n\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") continue;\n\t\tif (i === startSegment && startGrapheme > 0) {\n\t\t\ttext += sliceSegmentText(seg, startGrapheme, -1, segmentAdapter);\n\t\t} else {\n\t\t\ttext += seg.text;\n\t\t}\n\t}\n\tif (endGrapheme > 0 && endSegment < segments.length) {\n\t\tconst seg = segments[endSegment];\n\t\tconst from = startSegment === endSegment ? startGrapheme : 0;\n\t\ttext += sliceSegmentText(seg, from, endGrapheme, segmentAdapter);\n\t}\n\tif (appendHyphen) text += \"-\";\n\treturn text;\n}\n\nfunction resolveHyphenWidth(ctx: LayoutNextLineContext | undefined): number {\n\tif (ctx?.hyphenWidth !== undefined) return nonNegativeFinite(ctx.hyphenWidth, 0);\n\tif (ctx?.adapter === undefined || ctx.font === undefined) return 0;\n\tconst cache = ctx.cache;\n\tif (cache) {\n\t\tlet fontCache = cache.get(ctx.font);\n\t\tif (fontCache === undefined) {\n\t\t\tfontCache = new Map();\n\t\t\tcache.set(ctx.font, fontCache);\n\t\t}\n\t\tlet width = fontCache.get(\"-\");\n\t\tif (width === undefined) {\n\t\t\twidth = ctx.adapter.measureSegment(\"-\", ctx.font).width;\n\t\t\tfontCache.set(\"-\", width);\n\t\t}\n\t\treturn width;\n\t}\n\treturn ctx.adapter.measureSegment(\"-\", ctx.font).width;\n}\n\n/** Lay out one line from a cursor, returning the next cursor for continuation. */\nexport function layoutNextLine(\n\tsegments: readonly PreparedSegment[],\n\tcursor: LayoutCursor,\n\tslotWidth: number,\n\tctx?: LayoutNextLineContext,\n): LayoutNextLineResult | null {\n\tlet i = cursor.segmentIndex;\n\tconst initialGrapheme = cursor.graphemeIndex;\n\tconst segmentAdapter = ctx?.segmentAdapter ?? getDefaultSegmentAdapter();\n\tif (i >= segments.length) return null;\n\tif (initialGrapheme === 0) {\n\t\twhile (i < segments.length) {\n\t\t\tconst seg = segments[i];\n\t\t\tif (seg.kind === \"hard-break\") {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\twidth: 0,\n\t\t\t\t\tstart: { segmentIndex: cursor.segmentIndex, graphemeIndex: 0 },\n\t\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (seg.kind === \"space\" || seg.kind === \"zero-width-break\" || seg.kind === \"soft-hyphen\") {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (i >= segments.length) return null;\n\t}\n\tconst hyphenWidth = resolveHyphenWidth(ctx);\n\tconst startSegment = i;\n\tconst startGrapheme = i === cursor.segmentIndex ? initialGrapheme : 0;\n\tlet lineW = 0;\n\tlet lineEndSegment = startSegment;\n\tlet lineEndGrapheme = 0;\n\tlet hasContent = false;\n\tlet pendingBreakSegment = -1;\n\tlet pendingBreakGrapheme = 0;\n\tlet pendingBreakWidth = 0;\n\tlet pendingBreakSoftHyphen = false;\n\tconst recordPending = (\n\t\tsIdx: number,\n\t\tgIdx: number,\n\t\twidth: number,\n\t\tkind: SegmentBreakKind,\n\t): void => {\n\t\tpendingBreakSegment = sIdx;\n\t\tpendingBreakGrapheme = gIdx;\n\t\tpendingBreakWidth = width;\n\t\tpendingBreakSoftHyphen = kind === \"soft-hyphen\";\n\t};\n\tconst consumeBreakable = (segIdx: number, startG: number, widths: readonly number[]): boolean => {\n\t\tfor (let g = startG; g < widths.length; g += 1) {\n\t\t\tconst gw = widths[g];\n\t\t\tif (!hasContent) {\n\t\t\t\tlineW = gw;\n\t\t\t\tlineEndSegment = segIdx;\n\t\t\t\tlineEndGrapheme = g + 1;\n\t\t\t\thasContent = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lineW + gw > slotWidth + 1e-3) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tlineW += gw;\n\t\t\tlineEndSegment = segIdx;\n\t\t\tlineEndGrapheme = g + 1;\n\t\t}\n\t\tif (lineEndSegment === segIdx && lineEndGrapheme === widths.length) {\n\t\t\tlineEndSegment = segIdx + 1;\n\t\t\tlineEndGrapheme = 0;\n\t\t}\n\t\treturn false;\n\t};\n\tif (startGrapheme > 0 && startSegment < segments.length) {\n\t\tconst seg = segments[startSegment];\n\t\tif (seg.graphemeWidths) {\n\t\t\tconst overflow = consumeBreakable(startSegment, startGrapheme, seg.graphemeWidths);\n\t\t\tif (overflow) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tfalse,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW,\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\ti = lineEndSegment;\n\t\t}\n\t}\n\tfor (; i < segments.length; i += 1) {\n\t\tconst seg = segments[i];\n\t\tif (seg.kind === \"hard-break\") {\n\t\t\tif (hasContent) {\n\t\t\t\tconst endsAtSoftHyphen =\n\t\t\t\t\tlineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === \"soft-hyphen\";\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tendsAtSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttext: \"\",\n\t\t\t\twidth: 0,\n\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t};\n\t\t}\n\t\tconst w = seg.width;\n\t\tif (!hasContent) {\n\t\t\tif (w > slotWidth && seg.graphemeWidths) {\n\t\t\t\tconst overflow = consumeBreakable(i, 0, seg.graphemeWidths);\n\t\t\t\tif (overflow) {\n\t\t\t\t\tconst text = buildLineText(\n\t\t\t\t\t\tsegments,\n\t\t\t\t\t\tstartSegment,\n\t\t\t\t\t\tstartGrapheme,\n\t\t\t\t\t\tlineEndSegment,\n\t\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tsegmentAdapter,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\twidth: lineW,\n\t\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\ti = lineEndSegment - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlineW = w;\n\t\t\tlineEndSegment = i + 1;\n\t\t\tlineEndGrapheme = 0;\n\t\t\thasContent = true;\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\trecordPending(i + 1, 0, seg.kind === \"space\" ? lineW - w : lineW, seg.kind);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst projectedWidth = lineW + w;\n\t\tif (projectedWidth > slotWidth + 1e-3) {\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\tlineEndSegment = i + 1;\n\t\t\t\tlineEndGrapheme = 0;\n\t\t\t\tconst endsAtSoftHyphen = seg.kind === \"soft-hyphen\";\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tendsAtSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: seg.kind === \"space\" ? lineW : lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (pendingBreakSegment >= 0) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tpendingBreakSegment,\n\t\t\t\t\tpendingBreakGrapheme,\n\t\t\t\t\tpendingBreakSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: pendingBreakWidth + (pendingBreakSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: pendingBreakSegment, graphemeIndex: pendingBreakGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (w > slotWidth && seg.graphemeWidths) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tfalse,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW,\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst text = buildLineText(\n\t\t\t\tsegments,\n\t\t\t\tstartSegment,\n\t\t\t\tstartGrapheme,\n\t\t\t\tlineEndSegment,\n\t\t\t\tlineEndGrapheme,\n\t\t\t\tfalse,\n\t\t\t\tsegmentAdapter,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\ttext,\n\t\t\t\twidth: lineW,\n\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t};\n\t\t}\n\t\tlineW = projectedWidth;\n\t\tlineEndSegment = i + 1;\n\t\tlineEndGrapheme = 0;\n\t\tif (canBreakAfter(seg.kind)) {\n\t\t\trecordPending(i + 1, 0, seg.kind === \"space\" ? lineW - w : lineW, seg.kind);\n\t\t}\n\t}\n\tif (!hasContent) return null;\n\tconst endsAtSoftHyphen =\n\t\tlineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === \"soft-hyphen\";\n\tconst text = buildLineText(\n\t\tsegments,\n\t\tstartSegment,\n\t\tstartGrapheme,\n\t\tlineEndSegment,\n\t\tlineEndGrapheme,\n\t\tendsAtSoftHyphen,\n\t\tsegmentAdapter,\n\t);\n\treturn {\n\t\ttext,\n\t\twidth: lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t};\n}\n\n/** Subtract obstacle intervals from a horizontal text band. */\nexport function carveTextLineSlots(\n\tbase: Interval,\n\tblocked: readonly Interval[],\n\tminSlotWidth = 0,\n): Interval[] {\n\tlet slots: Interval[] = [base];\n\tfor (const block of blocked) {\n\t\tconst next: Interval[] = [];\n\t\tfor (const slot of slots) {\n\t\t\tif (block.right <= slot.left || block.left >= slot.right) {\n\t\t\t\tnext.push(slot);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (block.left > slot.left) next.push({ left: slot.left, right: block.left });\n\t\t\tif (block.right < slot.right) next.push({ left: block.right, right: slot.right });\n\t\t}\n\t\tslots = next;\n\t}\n\tif (minSlotWidth > 0) return slots.filter((slot) => slot.right - slot.left >= minSlotWidth);\n\treturn slots;\n}\n\n/** Compute per-grapheme boxes for already-broken lines. */\nexport function computeCharPositions(\n\tlineBreaks: LineBreaksResult,\n\tsegments: readonly PreparedSegment[],\n\tlineHeight: number,\n\tsegmentAdapter?: SegmentAdapter,\n): readonly CharPosition[] {\n\tconst positions: CharPosition[] = [];\n\tconst segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();\n\tfor (let lineIdx = 0; lineIdx < lineBreaks.lines.length; lineIdx += 1) {\n\t\tconst line = lineBreaks.lines[lineIdx];\n\t\tconst y = lineIdx * lineHeight;\n\t\tlet x = 0;\n\t\tfor (let si = line.startSegment; si < segments.length; si += 1) {\n\t\t\tconst seg = segments[si];\n\t\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") {\n\t\t\t\tif (si >= line.endSegment && line.endGrapheme === 0) break;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst graphemes = [...segAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);\n\t\t\tif (graphemes.length === 0) continue;\n\t\t\tconst startGrapheme = si === line.startSegment ? line.startGrapheme : 0;\n\t\t\tlet endGrapheme: number;\n\t\t\tif (si < line.endSegment) {\n\t\t\t\tendGrapheme = graphemes.length;\n\t\t\t} else if (si === line.endSegment && line.endGrapheme > 0) {\n\t\t\t\tendGrapheme = line.endGrapheme;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor (let g = startGrapheme; g < endGrapheme; g += 1) {\n\t\t\t\tconst width = seg.graphemeWidths ? seg.graphemeWidths[g] : seg.width / graphemes.length;\n\t\t\t\tpositions.push({ x, y, width, height: lineHeight, line: lineIdx });\n\t\t\t\tx += width;\n\t\t\t}\n\t\t}\n\t}\n\treturn positions;\n}\n\nfunction nonNegativeFinite(value: number, fallback: number): number {\n\treturn Number.isFinite(value) ? Math.max(0, value) : fallback;\n}\n\nfunction finiteNumber(value: number, fallback: number): number {\n\treturn Number.isFinite(value) ? value : fallback;\n}\n\nfunction emitLayoutError(ctx: Ctx, error: unknown, fallback: string): void {\n\tctx.down([[\"ERROR\", errorPayload(error, fallback)]]);\n}\n\nfunction positiveFinite(value: number, fallback: number): number {\n\treturn Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nfunction clampDimension(value: number | undefined): number {\n\treturn nonNegativeFinite(value ?? 0, 0);\n}\n\nfunction fitSize(size: Size, maxWidth: number): Size {\n\tconst width = nonNegativeFinite(size.width, 0);\n\tconst height = nonNegativeFinite(size.height, 0);\n\tif (width === 0 || maxWidth <= 0 || width <= maxWidth) return { width, height };\n\tconst scale = maxWidth / width;\n\treturn { width: maxWidth, height: height * scale };\n}\n\nfunction blockMaxWidth(blockMaxWidth: number | undefined, maxWidth: number): number {\n\tconst own = blockMaxWidth === undefined ? maxWidth : nonNegativeFinite(blockMaxWidth, maxWidth);\n\tif (maxWidth <= 0) return own;\n\tif (own <= 0) return maxWidth;\n\treturn Math.min(own, maxWidth);\n}\n\nfunction resolveTextAdapter(opts: MeasureBlockOptions): MeasurementAdapter {\n\tconst adapter = opts.adapters?.text ?? opts.adapter;\n\tif (!adapter) throw new Error(\"Text blocks require a MeasurementAdapter\");\n\treturn adapter;\n}\n\n/** Measure one text/image/SVG block using only explicit or injected synchronous adapters. */\nexport function measureBlock(block: ContentBlock, opts: MeasureBlockOptions): MeasuredBlock {\n\tconst maxWidth = nonNegativeFinite(opts.maxWidth ?? 800, 800);\n\tconst marginTop = nonNegativeFinite(block.marginTop ?? 0, 0);\n\tconst marginBottom = nonNegativeFinite(block.marginBottom ?? 0, 0);\n\tif (block.kind === \"text\") {\n\t\tconst adapter = resolveTextAdapter(opts);\n\t\tconst font = block.font ?? opts.font ?? \"16px sans-serif\";\n\t\tconst lineHeight = positiveFinite(block.lineHeight ?? opts.lineHeight ?? 20, 20);\n\t\tconst cache = opts.cache ?? new Map<string, Map<string, number>>();\n\t\tconst width = blockMaxWidth(block.maxWidth, maxWidth);\n\t\tconst segments = analyzeAndMeasure(\n\t\t\tblock.text,\n\t\t\tfont,\n\t\t\tadapter,\n\t\t\tcache,\n\t\t\tundefined,\n\t\t\topts.segmentAdapter,\n\t\t);\n\t\tconst hyphenWidth = Object.hasOwn(opts, \"hyphenWidth\")\n\t\t\t? opts.hyphenWidth\n\t\t\t: tryMeasureHyphenWidth(adapter, font);\n\t\tconst lineBreaks = computeLineBreaks(segments, width, {\n\t\t\thyphenWidth,\n\t\t\tsegmentAdapter: opts.segmentAdapter,\n\t\t});\n\t\tconst charPositions = computeCharPositions(\n\t\t\tlineBreaks,\n\t\t\tsegments,\n\t\t\tlineHeight,\n\t\t\topts.segmentAdapter,\n\t\t);\n\t\treturn {\n\t\t\tblock,\n\t\t\tkind: block.kind,\n\t\t\tid: block.id,\n\t\t\twidth: lineBreaks.lines.reduce((acc, line) => Math.max(acc, line.width), 0),\n\t\t\theight: lineBreaks.lineCount * lineHeight,\n\t\t\tmarginTop,\n\t\t\tmarginBottom,\n\t\t\tsegments,\n\t\t\tlineBreaks,\n\t\t\tcharPositions,\n\t\t};\n\t}\n\tif (block.kind === \"image\") {\n\t\tconst explicit =\n\t\t\tblock.width !== undefined && block.height !== undefined\n\t\t\t\t? { width: clampDimension(block.width), height: clampDimension(block.height) }\n\t\t\t\t: opts.adapters?.image?.measureImage(block.src);\n\t\tif (!explicit) throw new Error(\"Image blocks require width/height or an ImageMeasurer\");\n\t\tconst size = fitSize(explicit, blockMaxWidth(block.maxWidth, maxWidth));\n\t\treturn {\n\t\t\tblock,\n\t\t\tkind: block.kind,\n\t\t\tid: block.id,\n\t\t\twidth: size.width,\n\t\t\theight: size.height,\n\t\t\tmarginTop,\n\t\t\tmarginBottom,\n\t\t};\n\t}\n\tconst explicit =\n\t\tblock.width !== undefined && block.height !== undefined\n\t\t\t? { width: clampDimension(block.width), height: clampDimension(block.height) }\n\t\t\t: opts.adapters?.svg?.measureSvg(block.svg);\n\tif (!explicit) throw new Error(\"SVG blocks require width/height or a SvgMeasurer\");\n\tconst size = fitSize(explicit, blockMaxWidth(block.maxWidth, maxWidth));\n\treturn {\n\t\tblock,\n\t\tkind: block.kind,\n\t\tid: block.id,\n\t\twidth: size.width,\n\t\theight: size.height,\n\t\tmarginTop,\n\t\tmarginBottom,\n\t};\n}\n\n/** Measure a block list while sharing a measurement cache across text blocks. */\nexport function measureBlocks(\n\tblocks: readonly ContentBlock[],\n\topts: MeasureBlockOptions,\n): readonly MeasuredBlock[] {\n\tconst cache = opts.cache ?? new Map<string, Map<string, number>>();\n\treturn blocks.map((block) => measureBlock(block, { ...opts, cache }));\n}\n\n/** Stack measured blocks vertically with margins and a fixed gap. */\nexport function computeBlockFlow(\n\tblocks: readonly MeasuredBlock[],\n\tgap = 0,\n): readonly PositionedBlock[] {\n\tconst spacing = nonNegativeFinite(gap, 0);\n\tlet y = 0;\n\treturn blocks.map((block) => {\n\t\ty += block.marginTop;\n\t\tconst positioned: PositionedBlock = { ...block, x: 0, y };\n\t\ty += block.height + block.marginBottom + spacing;\n\t\treturn positioned;\n\t});\n}\n\n/** Compute the bottom edge of a positioned block flow. */\nexport function computeTotalHeight(blocks: readonly PositionedBlock[]): number {\n\tif (blocks.length === 0) return 0;\n\tlet bottom = 0;\n\tfor (const block of blocks) {\n\t\tbottom = Math.max(bottom, block.y + block.height + block.marginBottom);\n\t}\n\treturn bottom;\n}\n\nfunction columnGeometry(\n\tcontainer: FlowContainer,\n\tcolumns: FlowColumns | undefined,\n): {\n\treadonly paddingX: number;\n\treadonly paddingY: number;\n\treadonly count: number;\n\treadonly gap: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly columnWidth: number;\n} {\n\tconst paddingX = nonNegativeFinite(container.paddingX ?? 0, 0);\n\tconst paddingY = nonNegativeFinite(container.paddingY ?? 0, 0);\n\tconst count = Math.max(1, Math.floor(nonNegativeFinite(columns?.count ?? 1, 1)));\n\tconst gap = nonNegativeFinite(columns?.gap ?? 0, 0);\n\tconst width = nonNegativeFinite(container.width, 0);\n\tconst height = nonNegativeFinite(container.height, 0);\n\tconst innerWidth = Math.max(0, width - paddingX * 2 - gap * (count - 1));\n\tconst columnWidth = count > 0 ? innerWidth / count : 0;\n\treturn { paddingX, paddingY, count, gap, width, height, columnWidth };\n}\n\nfunction sanitizeFlowContainer(container: FlowContainer): FlowContainer {\n\treturn {\n\t\twidth: nonNegativeFinite(container.width, 0),\n\t\theight: nonNegativeFinite(container.height, 0),\n\t\tpaddingX:\n\t\t\tcontainer.paddingX === undefined ? undefined : nonNegativeFinite(container.paddingX, 0),\n\t\tpaddingY:\n\t\t\tcontainer.paddingY === undefined ? undefined : nonNegativeFinite(container.paddingY, 0),\n\t};\n}\n\nfunction sanitizeFlowColumns(columns: FlowColumns): FlowColumns {\n\treturn {\n\t\tcount:\n\t\t\tcolumns.count === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Math.max(1, Math.floor(nonNegativeFinite(columns.count, 1))),\n\t\tgap: columns.gap === undefined ? undefined : nonNegativeFinite(columns.gap, 0),\n\t};\n}\n\nfunction sanitizeObstacles(obstacles: readonly Obstacle[]): readonly Obstacle[] {\n\treturn obstacles.map((obstacle) => {\n\t\tif (obstacle.kind === \"circle\") {\n\t\t\treturn {\n\t\t\t\tkind: obstacle.kind,\n\t\t\t\tcx: finiteNumber(obstacle.cx, 0),\n\t\t\t\tcy: finiteNumber(obstacle.cy, 0),\n\t\t\t\tr: nonNegativeFinite(obstacle.r, 0),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: obstacle.kind,\n\t\t\tx: finiteNumber(obstacle.x, 0),\n\t\t\ty: finiteNumber(obstacle.y, 0),\n\t\t\twidth: nonNegativeFinite(obstacle.width, 0),\n\t\t\theight: nonNegativeFinite(obstacle.height, 0),\n\t\t};\n\t});\n}\n\n/** Intersect a circle obstacle with a horizontal line band. */\nexport function circleIntervalForBand(\n\tobstacle: CircleObstacle,\n\tbandTop: number,\n\tbandBottom: number,\n): Interval | null {\n\tconst radius = nonNegativeFinite(obstacle.r, 0);\n\tconst centerY = obstacle.cy;\n\tconst nearestY = Math.max(bandTop, Math.min(centerY, bandBottom));\n\tconst dy = nearestY - centerY;\n\tif (Math.abs(dy) > radius) return null;\n\tconst dx = Math.sqrt(Math.max(0, radius * radius - dy * dy));\n\treturn { left: obstacle.cx - dx, right: obstacle.cx + dx };\n}\n\n/** Intersect a rectangle obstacle with a horizontal line band. */\nexport function rectIntervalForBand(\n\tobstacle: RectObstacle,\n\tbandTop: number,\n\tbandBottom: number,\n): Interval | null {\n\tconst left = obstacle.x;\n\tconst right = obstacle.x + nonNegativeFinite(obstacle.width, 0);\n\tconst top = obstacle.y;\n\tconst bottom = obstacle.y + nonNegativeFinite(obstacle.height, 0);\n\tif (bottom <= bandTop || top >= bandBottom || right <= left) return null;\n\treturn { left, right };\n}\n\nfunction blockedIntervalsForBand(\n\tobstacles: readonly Obstacle[],\n\tbandTop: number,\n\tbandBottom: number,\n): Interval[] {\n\tconst intervals: Interval[] = [];\n\tfor (const obstacle of obstacles) {\n\t\tconst interval =\n\t\t\tobstacle.kind === \"circle\"\n\t\t\t\t? circleIntervalForBand(obstacle, bandTop, bandBottom)\n\t\t\t\t: rectIntervalForBand(obstacle, bandTop, bandBottom);\n\t\tif (interval) intervals.push(interval);\n\t}\n\treturn intervals.sort((a, b) => a.left - b.left);\n}\n\n/** Flow prepared text through columns and carved obstacle slots. */\nexport function computeFlowLines(\n\tsegments: readonly PreparedSegment[],\n\topts: ComputeFlowLinesOptions,\n): FlowLinesResult {\n\tconst geometry = columnGeometry(opts.container, opts.columns);\n\tconst lineHeight = positiveFinite(opts.lineHeight, 20);\n\tconst minSlotWidth = nonNegativeFinite(opts.minSlotWidth ?? 0, 0);\n\tconst obstacles = opts.obstacles ?? [];\n\tconst segmentAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst lines: PositionedLine[] = [];\n\tlet cursor: LayoutCursor = { segmentIndex: 0, graphemeIndex: 0 };\n\tconst contentBottom = Math.max(geometry.paddingY, geometry.height - geometry.paddingY);\n\tfor (let columnIndex = 0; columnIndex < geometry.count; columnIndex += 1) {\n\t\tconst columnLeft = geometry.paddingX + columnIndex * (geometry.columnWidth + geometry.gap);\n\t\tconst columnRight = columnLeft + geometry.columnWidth;\n\t\tfor (\n\t\t\tlet y = geometry.paddingY;\n\t\t\ty + lineHeight <= contentBottom + 1e-3 && cursor.segmentIndex < segments.length;\n\t\t\ty += lineHeight\n\t\t) {\n\t\t\tconst blocked = blockedIntervalsForBand(obstacles, y, y + lineHeight);\n\t\t\tconst slots = carveTextLineSlots(\n\t\t\t\t{ left: columnLeft, right: columnRight },\n\t\t\t\tblocked,\n\t\t\t\tMath.max(minSlotWidth, 1e-6),\n\t\t\t);\n\t\t\tfor (const slot of slots) {\n\t\t\t\tif (cursor.segmentIndex >= segments.length) break;\n\t\t\t\tconst slotWidth = slot.right - slot.left;\n\t\t\t\tconst next = layoutNextLine(segments, cursor, slotWidth, {\n\t\t\t\t\thyphenWidth: opts.hyphenWidth,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t});\n\t\t\t\tif (next === null) {\n\t\t\t\t\tcursor = { segmentIndex: segments.length, graphemeIndex: 0 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tnext.end.segmentIndex === cursor.segmentIndex &&\n\t\t\t\t\tnext.end.graphemeIndex === cursor.graphemeIndex\n\t\t\t\t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcursor = next.end;\n\t\t\t\tif (next.text.length === 0 && next.width === 0) break;\n\t\t\t\tlines.push({\n\t\t\t\t\ttext: next.text,\n\t\t\t\t\twidth: next.width,\n\t\t\t\t\tstartSegment: next.start.segmentIndex,\n\t\t\t\t\tstartGrapheme: next.start.graphemeIndex,\n\t\t\t\t\tendSegment: next.end.segmentIndex,\n\t\t\t\t\tendGrapheme: next.end.graphemeIndex,\n\t\t\t\t\tx: slot.left,\n\t\t\t\t\ty,\n\t\t\t\t\tslotWidth,\n\t\t\t\t\tcolumnIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tlines,\n\t\tcursor,\n\t\tdone: cursor.segmentIndex >= segments.length,\n\t};\n}\n\n/**\n * Create a graph-visible single-column text layout bundle.\n *\n * D181: this adds ordinary state/output nodes only; it does not add protocol behavior,\n * hidden subscriptions, GraphSpec ownership, storage, or platform globals.\n */\nexport function reactiveLayout(opts: ReactiveLayoutOptions): ReactiveLayoutBundle {\n\tconst { measurements, segmentAdapter: segmentAdapterOpt, name = \"reactive-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();\n\tconst g = opts.graph;\n\tconst lineHeightInput = inputNode(\n\t\tg,\n\t\topts.lineHeight instanceof Node\n\t\t\t? opts.lineHeight\n\t\t\t: nonNegativeFinite(opts.lineHeight ?? 20, 20),\n\t\tnonNegativeFinite(20, 20),\n\t\tscopedName(name, \"line-height\"),\n\t);\n\tconst maxWidthInput = inputNode(\n\t\tg,\n\t\topts.maxWidth instanceof Node ? opts.maxWidth : nonNegativeFinite(opts.maxWidth ?? 800, 800),\n\t\tnonNegativeFinite(800, 800),\n\t\tscopedName(name, \"max-width\"),\n\t);\n\tconst segments = g.node<readonly PreparedSegment[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.segments ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout segments failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"segments\") },\n\t);\n\tconst lineBreaks = g.node<LineBreaksResult>(\n\t\t[segments, maxWidthInput.node, measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 2) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tconst computed = computeLineBreaks(\n\t\t\t\t\tdepLatest(ctx, 0) as readonly PreparedSegment[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t\t{ hyphenWidth: measured?.hyphenWidth, segmentAdapter: segAdapter },\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", computed]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout line breaks failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"line-breaks\") },\n\t);\n\tconst height = g.node<number>(\n\t\t[lineBreaks, lineHeightInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst lines = depLatest(ctx, 0) as LineBreaksResult;\n\t\t\t\tconst lineHeight = nonNegativeFinite(depLatest(ctx, 1) as number, 0);\n\t\t\t\tctx.down([[\"DATA\", lines.lineCount * lineHeight]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout height failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"height\") },\n\t);\n\tconst charPositions = g.node<readonly CharPosition[]>(\n\t\t[lineBreaks, segments, lineHeightInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst positions = computeCharPositions(\n\t\t\t\t\tdepLatest(ctx, 0) as LineBreaksResult,\n\t\t\t\t\tdepLatest(ctx, 1) as readonly PreparedSegment[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 2) as number, 0),\n\t\t\t\t\tsegAdapter,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", positions]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout char positions failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"char-positions\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tlineHeight: lineHeightInput.node,\n\t\t\tmaxWidth: maxWidthInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetLineHeight(lineHeight: number): void {\n\t\t\tlineHeightInput.set(nonNegativeFinite(lineHeight, 0));\n\t\t},\n\t\tsetMaxWidth(maxWidth: number): void {\n\t\t\tmaxWidthInput.set(nonNegativeFinite(maxWidth, 0));\n\t\t},\n\t\tsegments,\n\t\tlineBreaks,\n\t\theight,\n\t\tcharPositions,\n\t};\n}\n\n/**\n * Create a graph-visible vertical block layout bundle over the same DOM-free core.\n *\n * Image/SVG sizing is explicit or injected; no async image loading or DOM SVG parsing occurs.\n */\nexport function reactiveBlockLayout(opts: ReactiveBlockLayoutOptions): ReactiveBlockLayoutBundle {\n\tconst { measurements, name = \"reactive-block-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"blocks\";\n\tconst g = opts.graph;\n\tconst gapInput = inputNode(\n\t\tg,\n\t\topts.gap instanceof Node ? opts.gap : nonNegativeFinite(opts.gap ?? 0, 0),\n\t\tnonNegativeFinite(0, 0),\n\t\tscopedName(name, \"gap\"),\n\t);\n\tconst measuredBlocks = g.node<readonly MeasuredBlock[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<BlocksMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.blocks ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout measured-blocks failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"measured-blocks\") },\n\t);\n\tconst blockFlow = g.node<readonly PositionedBlock[]>(\n\t\t[measuredBlocks, gapInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst positioned = computeBlockFlow(\n\t\t\t\t\tdepLatest(ctx, 0) as readonly MeasuredBlock[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", positioned]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout flow failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"block-flow\") },\n\t);\n\tconst totalHeight = g.node<number>(\n\t\t[blockFlow],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tctx.down([[\"DATA\", computeTotalHeight(depLatest(ctx, 0) as readonly PositionedBlock[])]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout total height failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"total-height\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tgap: gapInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetGap(gap: number): void {\n\t\t\tgapInput.set(nonNegativeFinite(gap, 0));\n\t\t},\n\t\tmeasuredBlocks,\n\t\tblockFlow,\n\t\ttotalHeight,\n\t};\n}\n\n/** Create a graph-visible multi-column flow layout bundle with rectangle/circle obstacles. */\nexport function reactiveFlowLayout(opts: ReactiveFlowLayoutOptions): ReactiveFlowLayoutBundle {\n\tconst { measurements, segmentAdapter: segmentAdapterOpt, name = \"reactive-flow-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();\n\tconst g = opts.graph;\n\tconst lineHeightInput = inputNode(\n\t\tg,\n\t\topts.lineHeight instanceof Node\n\t\t\t? opts.lineHeight\n\t\t\t: nonNegativeFinite(opts.lineHeight ?? 20, 20),\n\t\tnonNegativeFinite(20, 20),\n\t\tscopedName(name, \"line-height\"),\n\t);\n\tconst containerInput = inputNode(\n\t\tg,\n\t\topts.container,\n\t\t{ width: 800, height: 600 },\n\t\tscopedName(name, \"container\"),\n\t);\n\tconst columnsInput = inputNode(\n\t\tg,\n\t\topts.columns,\n\t\t{ count: 1, gap: 0 },\n\t\tscopedName(name, \"columns\"),\n\t);\n\tconst obstaclesInput = inputNode(g, opts.obstacles, [], scopedName(name, \"obstacles\"));\n\tconst segments = g.node<readonly PreparedSegment[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.segments ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveFlowLayout segments failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"segments\") },\n\t);\n\tconst flowLines = g.node<FlowLinesResult>(\n\t\t[\n\t\t\tsegments,\n\t\t\tlineHeightInput.node,\n\t\t\tcontainerInput.node,\n\t\t\tcolumnsInput.node,\n\t\t\tobstaclesInput.node,\n\t\t\tmeasurements,\n\t\t],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 5) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tconst computed = computeFlowLines(depLatest(ctx, 0) as readonly PreparedSegment[], {\n\t\t\t\t\tlineHeight: nonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t\tcontainer: sanitizeFlowContainer(depLatest(ctx, 2) as FlowContainer),\n\t\t\t\t\tcolumns: sanitizeFlowColumns(depLatest(ctx, 3) as FlowColumns),\n\t\t\t\t\tobstacles: sanitizeObstacles(depLatest(ctx, 4) as readonly Obstacle[]),\n\t\t\t\t\tminSlotWidth: nonNegativeFinite(opts.minSlotWidth ?? 0, 0),\n\t\t\t\t\thyphenWidth: measured?.hyphenWidth,\n\t\t\t\t\tsegmentAdapter: segAdapter,\n\t\t\t\t});\n\t\t\t\tctx.down([[\"DATA\", computed]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveFlowLayout flow lines failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"flow-lines\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tlineHeight: lineHeightInput.node,\n\t\t\tcontainer: containerInput.node,\n\t\t\tcolumns: columnsInput.node,\n\t\t\tobstacles: obstaclesInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetLineHeight(lineHeight: number): void {\n\t\t\tlineHeightInput.set(nonNegativeFinite(lineHeight, 0));\n\t\t},\n\t\tsetContainer(container: FlowContainer): void {\n\t\t\tcontainerInput.set(container);\n\t\t},\n\t\tsetColumns(columns: FlowColumns): void {\n\t\t\tcolumnsInput.set(columns);\n\t\t},\n\t\tsetObstacles(obstacles: readonly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;AAAA,IACD;AAAA,IACA,EAAE,MAAM,WAAW,MAAM,YAAY,EAAE;AAAA,EACxC;AACA,SAAO;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,MACN,YAAY,gBAAgB;AAAA,MAC5B,WAAW,eAAe;AAAA,MAC1B,SAAS,aAAa;AAAA,MACtB,WAAW,eAAe;AAAA,MAC1B;AAAA,IACD;AAAA,IACA,cAAc,YAA0B;AACvC,sBAAgB,IAAI,kBAAkB,YAAY,CAAC,CAAC;AAAA,IACrD;AAAA,IACA,aAAa,WAAgC;AAC5C,qBAAe,IAAI,SAAS;AAAA,IAC7B;AAAA,IACA,WAAW,SAA4B;AACtC,mBAAa,IAAI,OAAO;AAAA,IACzB;AAAA,IACA,aAAa,WAAsC;AAClD,qBAAe,IAAI,SAAS;AAAA,IAC7B;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;","names":["out","compareBigIntDesc","isDenseArrayOf","compareBigIntDesc","safeArrayLength","errorMessage","isDenseArrayOf","resultId","snapshotFragment","statusState","ref","out","text","endsAtSoftHyphen","blockMaxWidth","explicit","size"]}
|
|
1
|
+
{"version":3,"sources":["../../src/solutions/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/patterns/semantic-memory.ts","../../src/patterns/semantic-memory-graph-utils.ts","../../src/patterns/semantic-memory-graph.ts","../../src/json/codec.ts","../../src/solutions/agentic-memory-shared.ts","../../src/solutions/agentic-memory-projection.ts","../../src/solutions/agentic-memory-bundle.ts","../../src/solutions/agentic-memory-consolidation.ts","../../src/solutions/agentic-memory-context-packing.ts","../../src/solutions/agentic-memory-frame.ts","../../src/solutions/agentic-memory-kg.ts","../../src/solutions/agentic-memory-retention.ts","../../src/solutions/capability-admission.ts","../../src/solutions/reactive-layout/segment.ts","../../src/solutions/reactive-layout/utils.ts","../../src/solutions/reactive-layout/adapters.ts","../../src/solutions/reactive-layout/line.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/node/versioning.ts","../../src/node/node-output-runtime.ts","../../src/node/node-rewire-runtime.ts","../../src/node/node.ts","../../src/solutions/reactive-layout/types.ts","../../src/solutions/reactive-layout/measurements.ts","../../src/solutions/reactive-layout/block.ts","../../src/solutions/reactive-layout/flow.ts","../../src/solutions/reactive-layout/bundles.ts"],"sourcesContent":["/**\n * Vertical application solution kits.\n *\n * Agentic memory, harness, and data-agent surfaces land here after B63/B62\n * classify and re-derive them onto lower D125 layers.\n */\n\nexport {\n\tAGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\tAGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\ttype AgenticMemoryArtifactKind,\n\ttype AgenticMemoryBundle,\n\ttype AgenticMemoryBundleOptions,\n\ttype AgenticMemoryConsolidationBundle,\n\ttype AgenticMemoryConsolidationBundleOptions,\n\ttype AgenticMemoryConsolidationCommand,\n\ttype AgenticMemoryConsolidationCursor,\n\ttype AgenticMemoryConsolidationError,\n\ttype AgenticMemoryConsolidationErrorCode,\n\ttype AgenticMemoryConsolidationOutcome,\n\ttype AgenticMemoryConsolidationRecordDraft,\n\ttype AgenticMemoryConsolidationRequest,\n\ttype AgenticMemoryConsolidationResult,\n\ttype AgenticMemoryConsolidationSnapshot,\n\ttype AgenticMemoryConsolidationStatus,\n\ttype AgenticMemoryContext,\n\ttype AgenticMemoryContextEntry,\n\ttype AgenticMemoryContextPackingBundle,\n\ttype AgenticMemoryContextPackingBundleOptions,\n\ttype AgenticMemoryContextPackingCursor,\n\ttype AgenticMemoryContextPackingError,\n\ttype AgenticMemoryContextPackingErrorCode,\n\ttype AgenticMemoryContextPackingPolicy,\n\ttype AgenticMemoryContextPackingSnapshot,\n\ttype AgenticMemoryContextPackingStatus,\n\ttype AgenticMemoryContextState,\n\ttype AgenticMemoryContextText,\n\ttype AgenticMemoryError,\n\ttype AgenticMemoryErrorCode,\n\ttype AgenticMemoryFragmentFrame,\n\ttype AgenticMemoryKgAssertionDraft,\n\ttype AgenticMemoryKgProjectionBundle,\n\ttype AgenticMemoryKgProjectionBundleOptions,\n\ttype AgenticMemoryKgProjectionCursor,\n\ttype AgenticMemoryKgProjectionError,\n\ttype AgenticMemoryKgProjectionErrorCode,\n\ttype AgenticMemoryKgProjectionSnapshot,\n\ttype AgenticMemoryKgProjectionStatus,\n\ttype AgenticMemoryKgProjectionStatusState,\n\ttype AgenticMemoryKind,\n\ttype AgenticMemoryPackedContext,\n\ttype AgenticMemoryPackedContextEntry,\n\ttype AgenticMemoryPersistenceLevel,\n\ttype AgenticMemoryProjectionCursor,\n\ttype AgenticMemoryProjectionSnapshot,\n\ttype AgenticMemoryRecord,\n\ttype AgenticMemoryRecordFrame,\n\ttype AgenticMemoryRecordMetadata,\n\ttype AgenticMemoryRetentionBundle,\n\ttype AgenticMemoryRetentionBundleOptions,\n\ttype AgenticMemoryRetentionCommand,\n\ttype AgenticMemoryRetentionCursor,\n\ttype AgenticMemoryRetentionError,\n\ttype AgenticMemoryRetentionErrorCode,\n\ttype AgenticMemoryRetentionSnapshot,\n\ttype AgenticMemoryRetentionStatus,\n\ttype AgenticMemoryScope,\n\ttype AgenticMemorySourceProjection,\n\ttype AgenticMemoryStatus,\n\ttype AgenticMemoryStatusState,\n\ttype AgenticMemoryStrictJsonValue,\n\tagenticMemoryBundle,\n\tagenticMemoryConsolidationBundle,\n\tagenticMemoryContextPackingBundle,\n\tagenticMemoryKgProjectionBundle,\n\tagenticMemoryRecordCodec,\n\tagenticMemoryRecordFrame,\n\tagenticMemoryRecordFrameCodec,\n\tagenticMemoryRetentionBundle,\n\tassertAgenticMemoryRecordFrame,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n} from \"./agentic-memory.js\";\n\nexport {\n\ttype CapabilityAdmission,\n\ttype CapabilityAdmissionBundle,\n\ttype CapabilityAdmissionDecision,\n\ttype CapabilityAdmissionOutcome,\n\ttype CapabilityAdmissionPolicy,\n\ttype CapabilityAdmissionProposal,\n\ttype CapabilityAdmissionState,\n\ttype CapabilityAdmissionStatus,\n\ttype CapabilityAdmissionViews,\n\tcapabilityAdmissionProjector,\n\tcapabilityAdmissionProposal,\n} from \"./capability-admission.js\";\n\nexport {\n\tanalyzeAndMeasure,\n\ttype BaseContentBlock,\n\tBLOCKS_MEASUREMENT_KIND,\n\ttype BlockAdapters,\n\ttype BlockAdaptersProviderOptions,\n\ttype BlockMeasurementProviderOptions,\n\ttype BlocksMeasurement,\n\tblockAdaptersProvider,\n\tblockMeasurementProvider,\n\tCapabilityMeasureAdapter,\n\ttype CapabilityTextMeasurementsOptions,\n\tCellMeasureAdapter,\n\ttype CellMeasureAdapterOptions,\n\ttype CellTextMeasurementsOptions,\n\ttype CircleObstacle,\n\ttype ComputeFlowLinesOptions,\n\ttype ContentBlock,\n\tcapabilityTextMeasurements,\n\tcarveTextLineSlots,\n\tcellTextMeasurements,\n\tcircleIntervalForBand,\n\tcomputeBlockFlow,\n\tcomputeCharPositions,\n\tcomputeFlowLines,\n\tcomputeLineBreaks,\n\tcomputeTotalHeight,\n\ttype FlowColumns,\n\ttype FlowContainer,\n\ttype FlowLinesResult,\n\tIMAGE_SIZE_MEASUREMENT_KIND,\n\ttype ImageContentBlock,\n\ttype ImageMeasurer,\n\tImageSizeAdapter,\n\ttype ImageSizeLookup,\n\ttype ImageSizeMeasurementsOptions,\n\ttype ImageSizeMeasurementTarget,\n\tInjectedMeasureAdapter,\n\ttype InjectedMeasureAdapterOptions,\n\ttype InjectedTextMeasurementsOptions,\n\timageSizeMeasurements,\n\tinjectedTextMeasurements,\n\ttype LayoutCursor,\n\ttype LayoutLine,\n\ttype LayoutNextLineContext,\n\ttype LayoutNextLineResult,\n\ttype LineBreaksResult,\n\tlayoutNextLine,\n\ttype MeasureBlockOptions,\n\ttype MeasuredBlock,\n\ttype MeasureFn,\n\ttype MeasurementAdapter,\n\ttype MeasurementFact,\n\ttype MeasurementIssue,\n\ttype MeasurementReadiness,\n\ttype MeasurementResult,\n\ttype Measurements,\n\ttype MergeMeasurementsOptions,\n\tmeasureBlock,\n\tmeasureBlocks,\n\tmergeMeasurements,\n\ttype Obstacle,\n\ttype PositionedBlock,\n\ttype PositionedLine,\n\tPrecomputedMeasureAdapter,\n\ttype PrecomputedMeasureAdapterOptions,\n\ttype PrecomputedTextMeasurementsOptions,\n\ttype PreparedSegment,\n\tprecomputedTextMeasurements,\n\tREADINESS_MEASUREMENT_KIND,\n\ttype ReactiveBlockLayoutBundle,\n\ttype ReactiveBlockLayoutOptions,\n\ttype ReactiveFlowLayoutBundle,\n\ttype ReactiveFlowLayoutOptions,\n\ttype ReactiveLayoutBundle,\n\ttype ReactiveLayoutOptions,\n\ttype ReadinessMeasurementsOptions,\n\ttype ReadinessTextMeasurementsOptions,\n\ttype RectObstacle,\n\treactiveBlockLayout,\n\treactiveFlowLayout,\n\treactiveLayout,\n\treadinessMeasurements,\n\treadinessTextMeasurements,\n\trectIntervalForBand,\n\ttype SegmentAdapter,\n\ttype SegmentBreakKind,\n\ttype SegmentInfo,\n\ttype SegmentMeasureStats,\n\ttype Size,\n\tSVG_BOUNDS_MEASUREMENT_KIND,\n\tSvgBoundsAdapter,\n\ttype SvgBoundsMeasurementsOptions,\n\ttype SvgBoundsMeasurementTarget,\n\ttype SvgContentBlock,\n\ttype SvgMeasurer,\n\tsvgBoundsMeasurements,\n\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\ttype TextContentBlock,\n\ttype TextMeasureCapability,\n\ttype TextMeasurementProviderOptions,\n\ttype TextSegmentsMeasurement,\n\ttextMeasurementProvider,\n} from \"./reactive-layout/index.js\";\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock / pull identifier (R-pause-lockset, R-pull). */\nexport type LockId = string | symbol;\n\n/** Explicit pull demand payload (D269/D272). Params are holder-visible context, never DATA-up. */\nexport interface PullDemand {\n\treadonly pullId: LockId;\n\treadonly params?: unknown;\n}\n\n/**\n * The CLOSED set of 11 message types (R-msg-closed-set / D9 + D269 + START handshake).\n * No open set, no user-defined custom types. Adding a type is a spec change.\n */\nexport type Message =\n\t| readonly [\"START\"]\n\t| readonly [\"DIRTY\"]\n\t| readonly [\"DATA\", unknown]\n\t| readonly [\"RESOLVED\"]\n\t| readonly [\"INVALIDATE\"]\n\t| readonly [\"COMPLETE\"]\n\t| readonly [\"ERROR\", unknown]\n\t| readonly [\"TEARDOWN\"]\n\t| readonly [\"PAUSE\", LockId]\n\t| readonly [\"RESUME\", LockId]\n\t| readonly [\"PULL\", PullDemand];\n\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tPULL: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control/demand tiers only (R-ctx-up / D269): DIRTY, PAUSE, RESUME, PULL,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[PULL, { pullId, params }]])` — but for a SELF-demand (demanding a dep\n\t * this fn also reads) use {@link Ctx.upNext} instead, since an immediate demand whose delivery loops back\n\t * re-enters this fn mid-wave (D37 / R-reentrancy).\n\t */\n\tup(msgs: Wave, towardDep?: number): void;\n\t/** Emit downstream toward sinks. */\n\tdown(msgs: Wave): void;\n\t/**\n\t * The single raw dep-value input surface (R-ctx-wave-data / D77): dep -> upstream waves ->\n\t * per-wave DATA payloads and INVALIDATE/SENTINEL markers. `waveData[i] = []` means dep i\n\t * delivered no wave to this invocation; `waveData[i] = [[]]` means RESOLVED-only.\n\t */\n\twaveData: WaveData;\n\t/** Terminal metadata for the same invocation; terminal values never enter `waveData`. */\n\tterminal: TerminalData;\n\tstate: CtxState;\n\t/** Release external resources on deactivation (R-cleanup-hooks). */\n\tonDeactivation(fn: () => void): void;\n\t/** Flush on INVALIDATE (R-cleanup-hooks). */\n\tonInvalidate(fn: () => void): void;\n\t/** Graph-owned environment drivers for source/adapter boundaries (D130/D131). */\n\tenvironment(): EnvironmentDrivers;\n\t/** Holder-visible context for a PULL-caused invocation (D272); absent for ordinary waves. */\n\treadonly pull?: PullDemand;\n\t/**\n\t * Deferred SELF-rewire (R-rewire-deferred / D47) — the substrate affordance higher-order\n\t * operators (switchMap/mergeMap/concatMap/exhaustMap/flatMap) use to grow/shrink their own\n\t * inner-source dep set in response to their own data. Always present; see {@link RewireNext}.\n\t */\n\trewireNext: RewireNext;\n\t/**\n\t * Deferred up — the boundary-deferred form of {@link Ctx.up} (R-up-routing / R-pull / D59). Routes\n\t * `msgs` up from this node at the COMMITTED wave boundary (broadcast, or up the single `towardDep`\n\t * edge), riding the same R-rewire-deferred (D47) drain as {@link RewireNext}. This is the\n\t * SELF-DEMAND path: a consumer issues `ctx.upNext([[PULL, { pullId, params }]])` to demand a pull\n\t * dep it ALSO reads — the cone-routed PULL reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Passive semantic-memory vocabulary and deterministic helpers.\n *\n * D158 splits semantic memory into horizontal patterns and vertical solutions.\n * This module intentionally owns no graph nodes, storage restore, timers,\n * subscriptions, vector indexes, knowledge graphs, or agentic runtime.\n */\n\nimport type { StrictJsonValue } from \"../json/codec.js\";\n\n/** Stable identity for a semantic-memory fact. */\nexport type FactId = string;\n\n/** Shard partition key used by passive sharding helpers. */\nexport type ShardKey = string | number;\n\n/**\n * A single semantic-memory fact. Pattern convention only: this is not a\n * protocol message, storage record owner, restore contract, or graph runtime.\n */\nexport interface MemoryFragment<T = unknown> {\n\treadonly id: FactId;\n\treadonly payload: T;\n\t/** Transaction time, typically monotonic nanoseconds. */\n\treadonly tNs: bigint;\n\t/** Valid-time start. Undefined means unbounded past. */\n\treadonly validFrom?: bigint;\n\t/** Valid-time end. Undefined means currently valid. */\n\treadonly validTo?: bigint;\n\t/** Confidence score in the closed interval [0, 1]. */\n\treadonly confidence: number;\n\treadonly tags: readonly string[];\n\t/** Fact ids this fragment derives from or depends on. */\n\treadonly sources: readonly FactId[];\n\treadonly embedding?: readonly number[];\n\treadonly parentFragmentId?: FactId;\n\treadonly provenance?: string;\n}\n\n/** Columnar passive store vocabulary for callers that keep memory facts outside GraphReFly. */\nexport interface FactStore<T = unknown> {\n\treadonly byId: ReadonlyMap<FactId, MemoryFragment<T>>;\n}\n\n/** Read-only projection passed to scoring policies; it exposes no mutation surface. */\nexport interface StoreReadHandle<T = unknown> {\n\tget(id: FactId): MemoryFragment<T> | undefined;\n\thas(id: FactId): boolean;\n\treadonly size: number;\n\tvalues(): IterableIterator<MemoryFragment<T>>;\n}\n\nexport type ScoringPolicy<T = unknown> = (\n\tfragment: MemoryFragment<T>,\n\tstore: StoreReadHandle<T>,\n) => number;\nexport type DecayPolicy = (confidence: number, ageNs: bigint) => number;\nexport type AdmissionFilter<T = unknown> = (fragment: MemoryFragment<T>) => boolean;\n\n/** Outcome signal for policy learning. This is an application fact, not a protocol event. */\nexport interface OutcomeSignal {\n\treadonly factId: FactId;\n\treadonly reward: number;\n}\n\n/** Passive structured query over semantic-memory facts. */\nexport interface MemoryQuery {\n\treadonly tags?: readonly string[];\n\treadonly asOf?: bigint;\n\treadonly minConfidence?: number;\n\treadonly limit?: number;\n}\n\nexport interface MemoryAnswer<T = unknown> {\n\treadonly query: MemoryQuery;\n\treadonly results: readonly MemoryFragment<T>[];\n}\n\nexport type KnowledgeAssertionStrictJsonValue = StrictJsonValue;\n\n/** Passive KG endpoint vocabulary. Entity ids are DATA keys, not graph node ids. */\nexport interface KnowledgeAssertionSubject {\n\treadonly id: FactId;\n\treadonly type?: string;\n}\n\n/** Passive KG object/value vocabulary. */\nexport type KnowledgeAssertionObject =\n\t| {\n\t\t\treadonly kind: \"entity\";\n\t\t\treadonly id: FactId;\n\t\t\treadonly type?: string;\n\t }\n\t| {\n\t\t\treadonly kind: \"value\";\n\t\t\treadonly value: KnowledgeAssertionStrictJsonValue;\n\t\t\treadonly valueType?: string;\n\t };\n\n/** Passive KG assertion fact consumed by lower semantic-memory graph patterns. */\nexport interface KnowledgeAssertion {\n\treadonly id: FactId;\n\treadonly recordId?: FactId;\n\treadonly fragmentId?: FactId;\n\treadonly subject: KnowledgeAssertionSubject;\n\treadonly predicate: string;\n\treadonly object: KnowledgeAssertionObject;\n\treadonly confidence?: number;\n\treadonly sources?: readonly FactId[];\n\treadonly provenance?: string;\n}\n\n/** Entry vocabulary for ranked collection-like memory views. */\nexport interface CollectionEntry<T = unknown> {\n\treadonly id: string;\n\treadonly value: T;\n\treadonly createdAtNs: bigint;\n\treadonly lastAccessNs: bigint;\n\treadonly baseScore: number;\n}\n\nexport type RankedCollectionEntry<T = unknown> = CollectionEntry<T> & {\n\treadonly score: number;\n};\n\nexport type CollectionScoreFn<T = unknown> = (value: T) => number;\n\n/** Query shape shared by passive retrieval/ranking helpers. */\nexport interface RetrievalQuery {\n\treadonly text?: string;\n\treadonly vector?: readonly number[];\n\treadonly entityIds?: readonly string[];\n\treadonly context?: readonly string[];\n}\n\nexport interface VectorSearchResult<TMeta = unknown> {\n\treadonly id: string;\n\treadonly score: number;\n\treadonly meta?: TMeta;\n}\n\nexport interface RetrievalEntry<TMem = unknown> {\n\treadonly key: string;\n\treadonly value: TMem;\n\treadonly score: number;\n\treadonly sources: ReadonlyArray<\"vector\" | \"graph\" | \"store\">;\n\treadonly context?: readonly string[];\n}\n\nexport interface RetrievalTrace<TMem = unknown> {\n\treadonly vectorCandidates: ReadonlyArray<VectorSearchResult<TMem>>;\n\treadonly graphExpanded: ReadonlyArray<string>;\n\treadonly ranked: ReadonlyArray<RetrievalEntry<TMem>>;\n\treadonly packed: ReadonlyArray<RetrievalEntry<TMem>>;\n}\n\n/** Generic per-dimension thresholds. Any configured dimension below threshold is rejected. */\nexport type AdmissionThresholds<Dims extends string> = Partial<Record<Dims, number>>;\n\nexport interface AdmissionScoredOptions<Dims extends string, TRaw = unknown> {\n\treadonly scoreFn: (raw: TRaw) => Readonly<Record<Dims, number>>;\n\treadonly thresholds?: AdmissionThresholds<Dims>;\n}\n\nexport interface AdmissionScores {\n\treadonly persistence: number;\n\treadonly structure: number;\n\treadonly personalValue: number;\n}\n\nexport interface AdmissionScore3DOptions {\n\treadonly scoreFn: (raw: unknown) => AdmissionScores;\n\treadonly persistenceThreshold?: number;\n\treadonly personalValueThreshold?: number;\n\treadonly requireStructured?: boolean;\n}\n\nexport interface ShardByTenantOptions {\n\treadonly tenants?: readonly string[];\n\treadonly shardCount?: number;\n}\n\nexport interface ShardByTenantConfig<T = unknown> {\n\treadonly shardBy: (fragment: MemoryFragment<T>) => ShardKey;\n\treadonly shardCount: number;\n}\n\nexport interface MemoryFragmentValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n}\n\n/** Cosine similarity over zero-padded vectors. Non-finite results normalize to 0. */\nexport function cosineSimilarity(a: readonly number[], b: readonly number[]): number {\n\tconst n = Math.max(a.length, b.length);\n\tlet dot = 0;\n\tlet na = 0;\n\tlet nb = 0;\n\tfor (let i = 0; i < n; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\tna += av * av;\n\t\tnb += bv * bv;\n\t}\n\tif (na === 0 || nb === 0) return 0;\n\tconst score = dot / Math.sqrt(na * nb);\n\treturn Number.isFinite(score) ? score : 0;\n}\n\n/**\n * Returns true when a fragment is valid at `asOf`.\n *\n * Omitted `asOf` has no clock to compare against, so it admits only fragments\n * that are live and not valid-time delayed.\n */\nexport function memoryFragmentValidAt(fragment: MemoryFragment, asOf?: bigint): boolean {\n\tif (asOf === undefined) return fragment.validTo === undefined && fragment.validFrom === undefined;\n\tif (fragment.validFrom !== undefined && fragment.validFrom > asOf) return false;\n\tif (fragment.validTo !== undefined && fragment.validTo <= asOf) return false;\n\treturn true;\n}\n\n/** Pure structured-query predicate over a single fragment. */\nexport function memoryFragmentMatchesQuery(\n\tfragment: MemoryFragment,\n\tquery: MemoryQuery = {},\n): boolean {\n\tif (!memoryFragmentValidAt(fragment, query.asOf)) return false;\n\tif (query.minConfidence !== undefined && fragment.confidence < query.minConfidence) return false;\n\tif (\n\t\tquery.tags &&\n\t\tquery.tags.length > 0 &&\n\t\t!query.tags.some((tag) => fragment.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Filter and rank fragments by confidence desc, then transaction time desc. */\nexport function filterMemoryFragments<T>(\n\tfragments: Iterable<MemoryFragment<T>>,\n\tquery: MemoryQuery = {},\n): readonly MemoryFragment<T>[] {\n\tconst results = [...fragments].filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tresults.sort((a, b) => b.confidence - a.confidence || compareBigIntDesc(a.tNs, b.tNs));\n\treturn query.limit === undefined ? results : results.slice(0, Math.max(0, query.limit));\n}\n\n/** Validate the passive MemoryFragment shape without throwing. */\nexport function validateMemoryFragment(value: unknown): MemoryFragmentValidation {\n\tconst errors: string[] = [];\n\tif (typeof value !== \"object\" || value === null) {\n\t\treturn { ok: false, errors: [\"fragment must be an object\"] };\n\t}\n\tconst fragment = value as Partial<MemoryFragment>;\n\tif (typeof fragment.id !== \"string\" || fragment.id.length === 0) {\n\t\terrors.push(\"id must be a non-empty string\");\n\t}\n\tif (!Object.hasOwn(fragment, \"payload\")) {\n\t\terrors.push(\"payload must be present\");\n\t}\n\tif (typeof fragment.tNs !== \"bigint\") {\n\t\terrors.push(\"tNs must be a bigint\");\n\t}\n\tconst confidence = fragment.confidence;\n\tif (\n\t\t!Number.isFinite(confidence) ||\n\t\tconfidence === undefined ||\n\t\tconfidence < 0 ||\n\t\tconfidence > 1\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1]\");\n\t}\n\tif (!isDenseArrayOf(fragment.tags, (tag): tag is string => typeof tag === \"string\")) {\n\t\terrors.push(\"tags must be a readonly string array\");\n\t}\n\tif (!isDenseArrayOf(fragment.sources, (source): source is string => typeof source === \"string\")) {\n\t\terrors.push(\"sources must be a readonly string array\");\n\t}\n\tif (fragment.validFrom !== undefined && typeof fragment.validFrom !== \"bigint\") {\n\t\terrors.push(\"validFrom must be a bigint when present\");\n\t}\n\tif (fragment.validTo !== undefined && typeof fragment.validTo !== \"bigint\") {\n\t\terrors.push(\"validTo must be a bigint when present\");\n\t}\n\tif (\n\t\ttypeof fragment.validFrom === \"bigint\" &&\n\t\ttypeof fragment.validTo === \"bigint\" &&\n\t\tfragment.validFrom >= fragment.validTo\n\t) {\n\t\terrors.push(\"validFrom must be earlier than validTo\");\n\t}\n\tif (\n\t\tfragment.embedding !== undefined &&\n\t\t!isDenseArrayOf(fragment.embedding, (component): component is number =>\n\t\t\tNumber.isFinite(component),\n\t\t)\n\t) {\n\t\terrors.push(\"embedding must be a finite number array when present\");\n\t}\n\tif (fragment.parentFragmentId !== undefined && typeof fragment.parentFragmentId !== \"string\") {\n\t\terrors.push(\"parentFragmentId must be a string when present\");\n\t}\n\tif (fragment.provenance !== undefined && typeof fragment.provenance !== \"string\") {\n\t\terrors.push(\"provenance must be a string when present\");\n\t}\n\treturn { ok: errors.length === 0, errors };\n}\n\nexport function isMemoryFragment(value: unknown): value is MemoryFragment {\n\treturn validateMemoryFragment(value).ok;\n}\n\n/**\n * Generic N-dimension admission filter. Missing or non-finite thresholded scores reject.\n */\nexport function admissionScored<Dims extends string, TRaw = unknown>(\n\topts: AdmissionScoredOptions<Dims, TRaw>,\n): (raw: TRaw) => boolean {\n\tconst thresholds = opts.thresholds ?? ({} as AdmissionThresholds<Dims>);\n\treturn (raw: TRaw): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tfor (const dim of Object.keys(thresholds) as Dims[]) {\n\t\t\tconst min = thresholds[dim];\n\t\t\tif (min === undefined) continue;\n\t\t\tconst score = scores[dim];\n\t\t\tconst safe = Number.isFinite(score) ? (score as number) : Number.NEGATIVE_INFINITY;\n\t\t\tif (safe < min) return false;\n\t\t}\n\t\treturn true;\n\t};\n}\n\n/** Three-axis admission sugar for persistence / structure / personal-value scoring. */\nexport function admissionFilter3D(opts: AdmissionScore3DOptions): (raw: unknown) => boolean {\n\treturn (raw: unknown): boolean => {\n\t\tconst scores = opts.scoreFn(raw);\n\t\tif (!scoreAtLeast(scores.persistence, opts.persistenceThreshold ?? 0.3)) return false;\n\t\tif (!scoreAtLeast(scores.personalValue, opts.personalValueThreshold ?? 0.3)) return false;\n\t\tif (!opts.requireStructured) return true;\n\t\treturn scoreAtLeast(scores.structure, Number.MIN_VALUE);\n\t};\n}\n\n/** Build a passive `{ shardBy, shardCount }` pair for tenant-isolated sharding. */\nexport function shardByTenant<T>(\n\ttenantOf: (fragment: MemoryFragment<T>) => string,\n\topts: ShardByTenantOptions = {},\n): ShardByTenantConfig<T> {\n\tif (opts.tenants && opts.tenants.length > 0) {\n\t\tconst tenants = [...new Set(opts.tenants)];\n\t\tconst index = new Map(tenants.map((tenant, i) => [tenant, i] as const));\n\t\tconst overflow = tenants.length;\n\t\treturn {\n\t\t\tshardBy: (fragment) => index.get(tenantOf(fragment)) ?? overflow,\n\t\t\tshardCount: tenants.length + 1,\n\t\t};\n\t}\n\tconst configuredShardCount = opts.shardCount ?? 4;\n\tconst shardCount = Number.isSafeInteger(configuredShardCount)\n\t\t? Math.max(1, configuredShardCount)\n\t\t: 4;\n\treturn { shardBy: (fragment) => tenantOf(fragment), shardCount };\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction scoreAtLeast(score: number, min: number): boolean {\n\treturn Number.isFinite(score) && score >= min;\n}\n","/**\n * Graph-visible semantic-memory retrieval patterns.\n *\n * D158 allows horizontal semantic-memory patterns when they are ordinary graph\n * nodes with declared deps and graph-visible facts. This file intentionally\n * owns no storage restore/hydration, scheduler, hidden subscription, vector DB,\n * retention loop, consolidation loop, Graph subclass, or protocol behavior.\n */\n\nimport {\n\tcosineSimilarity,\n\ttype FactId,\n\tfilterMemoryFragments,\n\ttype KnowledgeAssertion,\n\ttype KnowledgeAssertionObject,\n\ttype KnowledgeAssertionSubject,\n\ttype MemoryFragment,\n\tmemoryFragmentMatchesQuery,\n\tvalidateMemoryFragment,\n} from \"./semantic-memory.js\";\nimport type {\n\tKnowledgeGraphEntity,\n\tKnowledgeGraphError,\n\tKnowledgeGraphIndex,\n\tKnowledgeGraphPolicy,\n\tKnowledgeGraphRelation,\n\tKnowledgeGraphTopic,\n\tMemoryRetrievalError,\n\tMemoryRetrievalQuery,\n\tMemoryRetrievalStatusState,\n} from \"./semantic-memory-graph-types.js\";\n\ninterface MemoryRetrievalQueryValidation {\n\treadonly ok: boolean;\n\treadonly query: MemoryRetrievalQuery;\n\treadonly errors: readonly Omit<MemoryRetrievalError, \"cursor\">[];\n}\n\ninterface FragmentValidationResult<T> {\n\treadonly fragment?: MemoryFragment<T>;\n\treadonly error?: Omit<MemoryRetrievalError, \"cursor\">;\n}\n\nexport function validateKnowledgeGraphPolicy(value: unknown): {\n\treadonly policy?: KnowledgeGraphPolicy;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n} {\n\tif (value === undefined) return { policy: undefined, errors: [] };\n\tif (!isPlainObject(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy must be an object\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst policy = value as Partial<KnowledgeGraphPolicy>;\n\tif (\n\t\tpolicy.allowedPredicates !== undefined &&\n\t\t!isDenseArrayOf(policy.allowedPredicates, (item): item is string => typeof item === \"string\")\n\t) {\n\t\terrors.push(\"allowedPredicates must be a readonly string array\");\n\t}\n\tif (policy.requireEntityTypes !== undefined && typeof policy.requireEntityTypes !== \"boolean\") {\n\t\terrors.push(\"requireEntityTypes must be a boolean when present\");\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-policy\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: policy is invalid\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn {\n\t\tpolicy: Object.freeze({\n\t\t\t...(policy.allowedPredicates === undefined\n\t\t\t\t? {}\n\t\t\t\t: { allowedPredicates: Object.freeze([...policy.allowedPredicates]) }),\n\t\t\t...(policy.requireEntityTypes === undefined\n\t\t\t\t? {}\n\t\t\t\t: { requireEntityTypes: policy.requireEntityTypes }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nexport function reduceKnowledgeAssertions(\n\tvalue: unknown,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertions: readonly KnowledgeAssertion[];\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n\treadonly errors: readonly Omit<KnowledgeGraphError, \"cursor\">[];\n\treadonly invalidAssertions: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<KnowledgeGraphError, \"cursor\">[] = [];\n\tconst seenAssertions = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input must be an array\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tentities: [],\n\t\t\trelations: [],\n\t\t\ttopics: [],\n\t\t\tindex: emptyKnowledgeGraphIndex(),\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-assertions-input\",\n\t\t\t\t\tmessage: \"knowledgeGraphReducerBundle: assertions input length could not be read\",\n\t\t\t\t\tassertion: value,\n\t\t\t\t},\n\t\t\t],\n\t\t\tinvalidAssertions: 0,\n\t\t};\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tconst result = validateKnowledgeAssertion(value[i], i, policy);\n\t\tif (result.error !== undefined) {\n\t\t\terrors.push(result.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst assertion = result.assertion as KnowledgeAssertion;\n\t\tif (seenAssertions.has(assertion.id)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\tmessage: \"knowledgeGraphReducerBundle: duplicate assertion id\",\n\t\t\t\tindex: i,\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tassertion,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate assertion id '${assertion.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenAssertions.add(assertion.id);\n\t\tassertions.push(assertion);\n\t}\n\tconst materialized = materializeKnowledgeGraph(assertions);\n\treturn {\n\t\tassertions: Object.freeze(assertions),\n\t\t...materialized,\n\t\terrors,\n\t\tinvalidAssertions: errors.filter((error) => error.code !== \"invalid-policy\").length,\n\t};\n}\n\nfunction validateKnowledgeAssertion(\n\tvalue: unknown,\n\tindex: number,\n\tpolicy?: KnowledgeGraphPolicy,\n): {\n\treadonly assertion?: KnowledgeAssertion;\n\treadonly error?: Omit<KnowledgeGraphError, \"cursor\">;\n} {\n\tif (!isPlainObject(value)) {\n\t\treturn invalidKnowledgeAssertion(index, value, [\"assertion must be an object\"]);\n\t}\n\tconst raw = value as Partial<KnowledgeAssertion>;\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(raw.id)) errors.push(\"id must be a non-empty string\");\n\tif (!isKnowledgeSubject(raw.subject)) errors.push(\"subject.id must be a non-empty string\");\n\tif (!isNonEmptyString(raw.predicate)) errors.push(\"predicate must be a non-empty string\");\n\tif (!isKnowledgeObject(raw.object)) errors.push(\"object shape is invalid\");\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\terrors.push(\"confidence must be a finite number in [0, 1] when present\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\terrors.push(\"sources must be a readonly non-empty string array when present\");\n\t}\n\tif (\n\t\tpolicy?.allowedPredicates !== undefined &&\n\t\t!policy.allowedPredicates.includes(raw.predicate ?? \"\")\n\t) {\n\t\terrors.push(`predicate '${String(raw.predicate)}' is not allowed by policy`);\n\t}\n\tif (policy?.requireEntityTypes === true) {\n\t\tif (isKnowledgeSubject(raw.subject) && raw.subject.type === undefined) {\n\t\t\terrors.push(\"subject.type is required by policy\");\n\t\t}\n\t\tif (\n\t\t\tisKnowledgeObject(raw.object) &&\n\t\t\traw.object.kind === \"entity\" &&\n\t\t\traw.object.type === undefined\n\t\t) {\n\t\t\terrors.push(\"object.type is required by policy for entity objects\");\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn invalidKnowledgeAssertion(index, value, errors, raw.id);\n\t}\n\treturn {\n\t\tassertion: Object.freeze({\n\t\t\tid: raw.id as FactId,\n\t\t\t...(raw.recordId === undefined ? {} : { recordId: raw.recordId }),\n\t\t\t...(raw.fragmentId === undefined ? {} : { fragmentId: raw.fragmentId }),\n\t\t\tsubject: snapshotSubject(raw.subject as KnowledgeAssertionSubject),\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: snapshotObject(raw.object as KnowledgeAssertionObject),\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\tsources: Object.freeze([...(raw.sources ?? [])]),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t};\n}\n\nfunction invalidKnowledgeAssertion(\n\tindex: number,\n\tassertion: unknown,\n\tvalidationErrors: readonly string[],\n\tassertionId?: unknown,\n): { readonly error: Omit<KnowledgeGraphError, \"cursor\"> } {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"invalid-assertion\",\n\t\t\tmessage: \"knowledgeGraphReducerBundle: assertion is invalid\",\n\t\t\tindex,\n\t\t\tassertionId: typeof assertionId === \"string\" ? assertionId : undefined,\n\t\t\tassertion,\n\t\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t\t},\n\t};\n}\n\nfunction materializeKnowledgeGraph(assertions: readonly KnowledgeAssertion[]): {\n\treadonly entities: readonly KnowledgeGraphEntity[];\n\treadonly relations: readonly KnowledgeGraphRelation[];\n\treadonly topics: readonly KnowledgeGraphTopic[];\n\treadonly index: KnowledgeGraphIndex;\n} {\n\tconst entityAssertions = new Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>();\n\tconst topics = new Map<FactId, { assertionIds: Set<FactId>; entityIds: Set<FactId> }>();\n\tconst relations: KnowledgeGraphRelation[] = [];\n\tfor (const assertion of assertions) {\n\t\tconst subject = touchEntity(entityAssertions, assertion.subject.id, assertion.subject.type);\n\t\tsubject.assertionIds.add(assertion.id);\n\t\tsubject.subjectAssertionIds.add(assertion.id);\n\t\tlet topic = topics.get(assertion.predicate);\n\t\tif (topic === undefined) {\n\t\t\ttopic = { assertionIds: new Set(), entityIds: new Set() };\n\t\t\ttopics.set(assertion.predicate, topic);\n\t\t}\n\t\ttopic.assertionIds.add(assertion.id);\n\t\ttopic.entityIds.add(assertion.subject.id);\n\t\tif (assertion.object.kind === \"entity\") {\n\t\t\tconst object = touchEntity(entityAssertions, assertion.object.id, assertion.object.type);\n\t\t\tobject.assertionIds.add(assertion.id);\n\t\t\tobject.objectAssertionIds.add(assertion.id);\n\t\t\ttopic.entityIds.add(assertion.object.id);\n\t\t}\n\t\trelations.push(\n\t\t\tObject.freeze({\n\t\t\t\tassertionId: assertion.id,\n\t\t\t\tsubject: assertion.subject,\n\t\t\t\tpredicate: assertion.predicate,\n\t\t\t\tobject: assertion.object,\n\t\t\t\t...(assertion.confidence === undefined ? {} : { confidence: assertion.confidence }),\n\t\t\t\tsources: Object.freeze([...(assertion.sources ?? [])]),\n\t\t\t\t...(assertion.provenance === undefined ? {} : { provenance: assertion.provenance }),\n\t\t\t}),\n\t\t);\n\t}\n\tconst entities = [...entityAssertions.entries()].map(([id, entity]) =>\n\t\tObject.freeze({\n\t\t\tid,\n\t\t\t...(entity.type === undefined ? {} : { type: entity.type }),\n\t\t\tassertionIds: freezeSortedSet(entity.assertionIds),\n\t\t\tsubjectAssertionIds: freezeSortedSet(entity.subjectAssertionIds),\n\t\t\tobjectAssertionIds: freezeSortedSet(entity.objectAssertionIds),\n\t\t}),\n\t);\n\tentities.sort((a, b) => compareString(a.id, b.id));\n\trelations.sort((a, b) => compareString(a.assertionId, b.assertionId));\n\tconst topicFacts = [...topics.entries()].map(([predicate, topic]) =>\n\t\tObject.freeze({\n\t\t\tpredicate,\n\t\t\tassertionIds: freezeSortedSet(topic.assertionIds),\n\t\t\tentityIds: freezeSortedSet(topic.entityIds),\n\t\t}),\n\t);\n\ttopicFacts.sort((a, b) => compareString(a.predicate, b.predicate));\n\tconst index: KnowledgeGraphIndex = Object.freeze({\n\t\tassertionIds: Object.freeze(assertions.map((assertion) => assertion.id).sort(compareString)),\n\t\tentityIds: Object.freeze(entities.map((entity) => entity.id)),\n\t\trelationIds: Object.freeze(relations.map((relation) => relation.assertionId)),\n\t\tpredicates: Object.freeze(topicFacts.map((topic) => topic.predicate)),\n\t});\n\treturn {\n\t\tentities: Object.freeze(entities),\n\t\trelations: Object.freeze(relations),\n\t\ttopics: Object.freeze(topicFacts),\n\t\tindex,\n\t};\n}\n\nfunction touchEntity(\n\tentities: Map<\n\t\tFactId,\n\t\t{\n\t\t\ttype?: string;\n\t\t\tassertionIds: Set<FactId>;\n\t\t\tsubjectAssertionIds: Set<FactId>;\n\t\t\tobjectAssertionIds: Set<FactId>;\n\t\t}\n\t>,\n\tid: FactId,\n\ttype?: string,\n) {\n\tlet entity = entities.get(id);\n\tif (entity === undefined) {\n\t\tentity = {\n\t\t\t...(type === undefined ? {} : { type }),\n\t\t\tassertionIds: new Set(),\n\t\t\tsubjectAssertionIds: new Set(),\n\t\t\tobjectAssertionIds: new Set(),\n\t\t};\n\t\tentities.set(id, entity);\n\t} else if (entity.type === undefined && type !== undefined) {\n\t\tentity.type = type;\n\t}\n\treturn entity;\n}\n\nfunction emptyKnowledgeGraphIndex(): KnowledgeGraphIndex {\n\treturn Object.freeze({\n\t\tassertionIds: Object.freeze([]),\n\t\tentityIds: Object.freeze([]),\n\t\trelationIds: Object.freeze([]),\n\t\tpredicates: Object.freeze([]),\n\t});\n}\n\nfunction snapshotSubject(subject: KnowledgeAssertionSubject): KnowledgeAssertionSubject {\n\treturn Object.freeze({\n\t\tid: subject.id,\n\t\t...(subject.type === undefined ? {} : { type: subject.type }),\n\t});\n}\n\nfunction snapshotObject(object: KnowledgeAssertionObject): KnowledgeAssertionObject {\n\treturn object.kind === \"entity\"\n\t\t? Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: object.id,\n\t\t\t\t...(object.type === undefined ? {} : { type: object.type }),\n\t\t\t})\n\t\t: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: object.value,\n\t\t\t\t...(object.valueType === undefined ? {} : { valueType: object.valueType }),\n\t\t\t});\n}\n\nfunction isKnowledgeSubject(value: unknown): value is KnowledgeAssertionSubject {\n\treturn (\n\t\tisPlainObject(value) &&\n\t\tisNonEmptyString(value.id) &&\n\t\t(value.type === undefined || isNonEmptyString(value.type))\n\t);\n}\n\nfunction isKnowledgeObject(value: unknown): value is KnowledgeAssertionObject {\n\tif (!isPlainObject(value)) return false;\n\tif (value.kind === \"entity\") {\n\t\treturn isNonEmptyString(value.id) && (value.type === undefined || isNonEmptyString(value.type));\n\t}\n\tif (value.kind !== \"value\") return false;\n\treturn (\n\t\tisStrictJsonValue(value.value) &&\n\t\t(value.valueType === undefined || isNonEmptyString(value.valueType))\n\t);\n}\n\nfunction isStrictJsonValue(value: unknown): boolean {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n\tif (typeof value === \"number\") return Number.isFinite(value);\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\tif (!Object.hasOwn(value, i) || !isStrictJsonValue(value[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (!isPlainObject(value)) return false;\n\tfor (const key of Object.keys(value)) {\n\t\tif (!isStrictJsonValue(value[key])) return false;\n\t}\n\treturn Object.getOwnPropertySymbols(value).length === 0;\n}\n\nfunction freezeSortedSet(value: ReadonlySet<FactId>): readonly FactId[] {\n\treturn Object.freeze([...value].sort(compareString));\n}\n\nexport function rankFragments<T>(\n\tfragments: readonly MemoryFragment<T>[],\n\tquery: MemoryRetrievalQuery,\n): readonly MemoryFragment<T>[] {\n\tif (query.vector === undefined) return filterMemoryFragments(fragments, query);\n\tconst ranked = fragments.filter((fragment) => memoryFragmentMatchesQuery(fragment, query));\n\tranked.sort((a, b) => {\n\t\tconst vectorDelta = vectorScore(b, query) - vectorScore(a, query);\n\t\tif (vectorDelta !== 0) return vectorDelta;\n\t\tconst confidenceDelta = b.confidence - a.confidence;\n\t\tif (confidenceDelta !== 0) return confidenceDelta;\n\t\treturn compareBigIntDesc(a.tNs, b.tNs);\n\t});\n\treturn query.limit === undefined ? ranked : ranked.slice(0, Math.max(0, query.limit));\n}\n\nfunction vectorScore(fragment: MemoryFragment, query: MemoryRetrievalQuery): number {\n\tif (query.vector === undefined || fragment.embedding === undefined) return 0;\n\treturn cosineSimilarity(query.vector, fragment.embedding);\n}\n\nexport function statusState(\n\terrors: readonly Omit<MemoryRetrievalError, \"cursor\">[],\n\tresultCount: number,\n): MemoryRetrievalStatusState {\n\tif (errors.some((error) => !isRecoverableFragmentError(error))) return \"error\";\n\tif (errors.length > 0) return \"partial\";\n\treturn resultCount > 0 ? \"ready\" : \"empty\";\n}\n\nexport function isRecoverableFragmentError(error: Omit<MemoryRetrievalError, \"cursor\">): boolean {\n\treturn error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\";\n}\n\nexport function indexById<T>(\n\tfragments: readonly MemoryFragment<T>[],\n): Readonly<Record<FactId, MemoryFragment<T>>> {\n\tconst byId = Object.create(null) as Record<FactId, MemoryFragment<T>>;\n\tfor (const fragment of fragments) byId[fragment.id] = fragment;\n\treturn Object.freeze(byId);\n}\n\nfunction isFiniteVector(value: unknown): value is readonly number[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !Number.isFinite(value[i])) return false;\n\t}\n\treturn true;\n}\n\nexport function validateMemoryRetrievalQuery(value: unknown): MemoryRetrievalQueryValidation {\n\ttry {\n\t\treturn validateMemoryRetrievalQueryInner(value);\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tquery: {},\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-query\",\n\t\t\t\t\tmessage: `memoryRetrievalBundle: query access failed: ${errorMessage(error)}`,\n\t\t\t\t\tfragment: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nfunction validateMemoryRetrievalQueryInner(value: unknown): MemoryRetrievalQueryValidation {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn invalidQuery(value, \"memoryRetrievalBundle: query must be an object\");\n\t}\n\tconst query = value as Partial<MemoryRetrievalQuery>;\n\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [];\n\tif (\n\t\tquery.tags !== undefined &&\n\t\t!isDenseArrayOf(query.tags, (tag): tag is string => typeof tag === \"string\")\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.tags must be a readonly string array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"tags must be a readonly string array\"],\n\t\t});\n\t}\n\tif (query.asOf !== undefined && typeof query.asOf !== \"bigint\") {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.asOf must be a bigint\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"asOf must be a bigint when present\"],\n\t\t});\n\t}\n\tif (\n\t\tquery.minConfidence !== undefined &&\n\t\t(!Number.isFinite(query.minConfidence) || query.minConfidence < 0 || query.minConfidence > 1)\n\t) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.minConfidence must be a finite number in [0, 1]\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"minConfidence must be a finite number in [0, 1]\"],\n\t\t});\n\t}\n\tif (query.limit !== undefined && (!Number.isSafeInteger(query.limit) || query.limit < 0)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.limit must be a non-negative safe integer\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"limit must be a non-negative safe integer\"],\n\t\t});\n\t}\n\tif (query.vector !== undefined && !isFiniteVector(query.vector)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-query-vector\",\n\t\t\tmessage: \"memoryRetrievalBundle: query.vector must be a finite number array\",\n\t\t\tfragment: value,\n\t\t\tvalidationErrors: [\"vector must be a finite number array\"],\n\t\t});\n\t}\n\tif (errors.length > 0) return { ok: false, query: {}, errors };\n\treturn { ok: true, query: snapshotQuery(query), errors };\n}\n\nfunction invalidQuery(value: unknown, message: string): MemoryRetrievalQueryValidation {\n\treturn {\n\t\tok: false,\n\t\tquery: {},\n\t\terrors: [\n\t\t\t{\n\t\t\t\tcode: \"invalid-query\",\n\t\t\t\tmessage,\n\t\t\t\tfragment: value,\n\t\t\t},\n\t\t],\n\t};\n}\n\nfunction snapshotQuery(query: Partial<MemoryRetrievalQuery>): MemoryRetrievalQuery {\n\treturn Object.freeze({\n\t\t...(query.tags === undefined ? {} : { tags: Object.freeze([...query.tags]) }),\n\t\t...(query.asOf === undefined ? {} : { asOf: query.asOf }),\n\t\t...(query.minConfidence === undefined ? {} : { minConfidence: query.minConfidence }),\n\t\t...(query.limit === undefined ? {} : { limit: query.limit }),\n\t\t...(query.vector === undefined ? {} : { vector: Object.freeze([...query.vector]) }),\n\t});\n}\n\nexport function safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function validateAndSnapshotFragment<T>(\n\trawFragments: readonly unknown[],\n\tindex: number,\n): FragmentValidationResult<T> {\n\tlet raw: unknown;\n\ttry {\n\t\traw = rawFragments[index];\n\t\tconst validation = validateMemoryFragment(raw);\n\t\tif (!validation.ok) {\n\t\t\treturn {\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: invalid memory fragment\",\n\t\t\t\t\tindex,\n\t\t\t\t\tfragment: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze([...validation.errors]),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn { fragment: snapshotFragment(raw as MemoryFragment<T>) };\n\t} catch (error) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-fragment\",\n\t\t\t\tmessage: `memoryRetrievalBundle: fragment access failed: ${errorMessage(error)}`,\n\t\t\t\tindex,\n\t\t\t\tfragment: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"fragment access failed\"]),\n\t\t\t},\n\t\t};\n\t}\n}\n\nfunction snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction isDenseArrayOf<T>(value: unknown, predicate: (item: unknown) => item is T): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction compareString(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction compareBigIntDesc(a: bigint, b: bigint): number {\n\tif (a === b) return 0;\n\treturn a > b ? -1 : 1;\n}\n","/**\n * Graph-visible semantic-memory retrieval patterns.\n *\n * D158 allows horizontal semantic-memory patterns when they are ordinary graph\n * nodes with declared deps and graph-visible facts. This file intentionally\n * owns no storage restore/hydration, scheduler, hidden subscription, vector DB,\n * retention loop, consolidation loop, Graph subclass, or protocol behavior.\n */\n\nimport { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { FactId, MemoryAnswer, MemoryFragment } from \"./semantic-memory.js\";\nimport type {\n\tKnowledgeGraphCursor,\n\tKnowledgeGraphReducerBundle,\n\tKnowledgeGraphReducerBundleOptions,\n\tKnowledgeGraphSnapshot,\n\tKnowledgeGraphStatus,\n\tMemoryRetrievalBundle,\n\tMemoryRetrievalBundleOptions,\n\tMemoryRetrievalCursor,\n\tMemoryRetrievalError,\n\tMemoryRetrievalIndex,\n\tMemoryRetrievalSnapshot,\n\tMemoryRetrievalStatus,\n} from \"./semantic-memory-graph-types.js\";\nimport {\n\tindexById,\n\tisRecoverableFragmentError,\n\trankFragments,\n\treduceKnowledgeAssertions,\n\tsafeArrayLength,\n\tstatusState,\n\tvalidateAndSnapshotFragment,\n\tvalidateKnowledgeGraphPolicy,\n\tvalidateMemoryRetrievalQuery,\n} from \"./semantic-memory-graph-utils.js\";\n\nexport type {\n\tKnowledgeGraphCursor,\n\tKnowledgeGraphEntity,\n\tKnowledgeGraphError,\n\tKnowledgeGraphErrorCode,\n\tKnowledgeGraphIndex,\n\tKnowledgeGraphPolicy,\n\tKnowledgeGraphReducerBundle,\n\tKnowledgeGraphReducerBundleOptions,\n\tKnowledgeGraphRelation,\n\tKnowledgeGraphSnapshot,\n\tKnowledgeGraphStatus,\n\tKnowledgeGraphStatusState,\n\tKnowledgeGraphTopic,\n\tMemoryRetrievalBundle,\n\tMemoryRetrievalBundleOptions,\n\tMemoryRetrievalCursor,\n\tMemoryRetrievalError,\n\tMemoryRetrievalErrorCode,\n\tMemoryRetrievalFact,\n\tMemoryRetrievalIndex,\n\tMemoryRetrievalQuery,\n\tMemoryRetrievalSnapshot,\n\tMemoryRetrievalStatus,\n\tMemoryRetrievalStatusState,\n} from \"./semantic-memory-graph-types.js\";\n\ninterface MemoryRetrievalRuntimeState {\n\tevaluation: number;\n}\n\n/**\n * Build a graph-visible memory retrieval bundle from explicit fragment/query deps.\n *\n * Invalid fragments and ranking status are emitted as ordinary DATA facts. The\n * bundle never owns storage restore or hidden mutation; callers that need\n * persistence compose D161 collection/storage sidecars outside this pattern.\n */\nexport function memoryRetrievalBundle<T = unknown>(\n\tgraph: Graph,\n\topts: MemoryRetrievalBundleOptions,\n): MemoryRetrievalBundle<T> {\n\tconst name = opts.name ?? \"memoryRetrieval\";\n\tconst { fragments, query } = opts;\n\tconst snapshot = graph.node<MemoryRetrievalSnapshot<T>>(\n\t\t[fragments, query],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<MemoryRetrievalRuntimeState>() ??\n\t\t\t\t({ evaluation: 0 } satisfies MemoryRetrievalRuntimeState);\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawFragments = depLatest(ctx, 0);\n\t\t\tconst rawQuery = depLatest(ctx, 1);\n\t\t\tconst queryValidation = validateMemoryRetrievalQuery(rawQuery);\n\t\t\tconst currentQuery = queryValidation.query;\n\t\t\tconst valid: MemoryFragment<T>[] = [];\n\t\t\tconst seenIds = new Set<FactId>();\n\t\t\tconst errors: Omit<MemoryRetrievalError, \"cursor\">[] = [...queryValidation.errors];\n\n\t\t\tif (!Array.isArray(rawFragments)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input must be an array\",\n\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst length = safeArrayLength(rawFragments);\n\t\t\t\tif (length === undefined) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tcode: \"invalid-fragments-input\",\n\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: fragments input length could not be read\",\n\t\t\t\t\t\tfragment: rawFragments,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < (length ?? 0); i += 1) {\n\t\t\t\t\tconst result = validateAndSnapshotFragment<T>(rawFragments, i);\n\t\t\t\t\tif (result.error !== undefined) {\n\t\t\t\t\t\terrors.push(result.error);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst fragment = result.fragment as MemoryFragment<T>;\n\t\t\t\t\tif (seenIds.has(fragment.id)) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\t\t\t\tmessage: \"memoryRetrievalBundle: duplicate fragment id\",\n\t\t\t\t\t\t\tindex: i,\n\t\t\t\t\t\t\tfragment,\n\t\t\t\t\t\t\tvalidationErrors: [`duplicate fragment id '${fragment.id}'`],\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tseenIds.add(fragment.id);\n\t\t\t\t\tvalid.push(fragment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ranked = errors.some((error) => !isRecoverableFragmentError(error))\n\t\t\t\t? []\n\t\t\t\t: rankFragments(valid, currentQuery);\n\t\t\tconst cursor: MemoryRetrievalCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidFragments: valid.length,\n\t\t\t\tinvalidFragments: errors.filter(\n\t\t\t\t\t(error) => error.code === \"invalid-fragment\" || error.code === \"duplicate-fragment-id\",\n\t\t\t\t).length,\n\t\t\t\tresultCount: ranked.length,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tconst answer: MemoryAnswer<T> = Object.freeze({\n\t\t\t\tquery: currentQuery,\n\t\t\t\tresults: Object.freeze(ranked),\n\t\t\t});\n\t\t\tconst status: MemoryRetrievalStatus = Object.freeze({\n\t\t\t\tstate: statusState(errors, ranked.length),\n\t\t\t\tquery: currentQuery,\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst indexed: MemoryRetrievalIndex<T> = Object.freeze({\n\t\t\t\tids: Object.freeze(valid.map((fragment) => fragment.id)),\n\t\t\t\tbyId: indexById(valid),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errorFacts = Object.freeze(\n\t\t\t\terrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragments: Object.freeze([...valid]),\n\t\t\t\t\t\tindexed,\n\t\t\t\t\t\tranked: answer,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors: errorFacts,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"memoryRetrievalSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { fragments, query },\n\t\tsnapshot,\n\t\tfragments: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/fragments`,\n\t\t\t\"memoryRetrievalFragments\",\n\t\t\t(fact) => fact.fragments,\n\t\t),\n\t\tindexed: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/indexed`,\n\t\t\t\"memoryRetrievalIndexed\",\n\t\t\t(fact) => fact.indexed,\n\t\t),\n\t\tranked: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/ranked`,\n\t\t\t\"memoryRetrievalRanked\",\n\t\t\t(fact) => fact.ranked,\n\t\t),\n\t\tstatus: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"memoryRetrievalStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"memoryRetrievalErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: retrievalProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"memoryRetrievalCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D170 lower semantic-memory KG materializer.\n *\n * Assertion, entity, relation, and topic ids remain DATA keys. The bundle has\n * static describe-visible topology and owns no storage, LLM extraction,\n * scheduler, agent runtime, or dynamic graph node lifecycle.\n */\nexport function knowledgeGraphReducerBundle(\n\tgraph: Graph,\n\topts: KnowledgeGraphReducerBundleOptions,\n): KnowledgeGraphReducerBundle {\n\tconst name = opts.name ?? \"knowledgeGraph\";\n\tconst deps = opts.policy === undefined ? [opts.assertions] : [opts.assertions, opts.policy];\n\tconst snapshot = graph.node<KnowledgeGraphSnapshot>(\n\t\tdeps,\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst policy = validateKnowledgeGraphPolicy(\n\t\t\t\topts.policy === undefined ? undefined : depLatest(ctx, 1),\n\t\t\t);\n\t\t\tconst reduced = reduceKnowledgeAssertions(depLatest(ctx, 0), policy.policy);\n\t\t\tconst pendingErrors = [...policy.errors, ...reduced.errors];\n\t\t\tconst cursor: KnowledgeGraphCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidAssertions: reduced.assertions.length,\n\t\t\t\tinvalidAssertions: reduced.invalidAssertions,\n\t\t\t\tentityCount: reduced.entities.length,\n\t\t\t\trelationCount: reduced.relations.length,\n\t\t\t\tpredicateCount: reduced.topics.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tpendingErrors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: KnowledgeGraphStatus = Object.freeze({\n\t\t\t\tstate:\n\t\t\t\t\treduced.assertions.length === 0 && errors.length === 0\n\t\t\t\t\t\t? \"empty\"\n\t\t\t\t\t\t: errors.length === 0\n\t\t\t\t\t\t\t? \"ready\"\n\t\t\t\t\t\t\t: reduced.assertions.length > 0\n\t\t\t\t\t\t\t\t? \"partial\"\n\t\t\t\t\t\t\t\t: \"error\",\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(reduced.assertions),\n\t\t\t\t\t\tentities: Object.freeze(reduced.entities),\n\t\t\t\t\t\trelations: Object.freeze(reduced.relations),\n\t\t\t\t\t\ttopics: Object.freeze(reduced.topics),\n\t\t\t\t\t\tindex: reduced.index,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/snapshot`,\n\t\t\tfactory: \"knowledgeGraphReducerSnapshot\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: {\n\t\t\tassertions: opts.assertions,\n\t\t\t...(opts.policy === undefined ? {} : { policy: opts.policy }),\n\t\t},\n\t\tsnapshot,\n\t\tassertions: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/assertions`,\n\t\t\t\"knowledgeGraphAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tentities: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/entities`,\n\t\t\t\"knowledgeGraphEntities\",\n\t\t\t(fact) => fact.entities,\n\t\t),\n\t\trelations: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/relations`,\n\t\t\t\"knowledgeGraphRelations\",\n\t\t\t(fact) => fact.relations,\n\t\t),\n\t\ttopics: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/topics`,\n\t\t\t\"knowledgeGraphTopics\",\n\t\t\t(fact) => fact.topics,\n\t\t),\n\t\tindex: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/index`,\n\t\t\t\"knowledgeGraphIndex\",\n\t\t\t(fact) => fact.index,\n\t\t),\n\t\tstatus: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/status`,\n\t\t\t\"knowledgeGraphStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/errors`,\n\t\t\t\"knowledgeGraphErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: kgProjection(\n\t\t\tgraph,\n\t\t\tsnapshot,\n\t\t\t`${name}/cursor`,\n\t\t\t\"knowledgeGraphCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction retrievalProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: MemoryRetrievalSnapshot<T>) => TFact | undefined,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as MemoryRetrievalSnapshot<T>;\n\t\t\t\tconst selected = select(fact);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction kgProjection<TFact>(\n\tgraph: Graph,\n\tsnapshot: Node<KnowledgeGraphSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: KnowledgeGraphSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as KnowledgeGraphSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n","/**\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 { strictJsonCodec } from \"../json/codec.js\";\nimport type { MemoryFragment } from \"../patterns/semantic-memory.js\";\nimport { validateMemoryFragment } from \"../patterns/semantic-memory.js\";\nimport type {\n\tAgenticMemoryArtifactKind,\n\tAgenticMemoryError,\n\tAgenticMemoryKind,\n\tAgenticMemoryPersistenceLevel,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRecordMetadata,\n\tAgenticMemoryScope,\n\tAgenticMemoryStatusState,\n\tStrictJsonValue,\n} from \"./agentic-memory-types.js\";\n\nexport function validateAndProjectRecords<T>(value: unknown): {\n\treadonly records: AgenticMemoryRecord<T>[];\n\treadonly fragments: MemoryFragment<T>[];\n\treadonly metadataByFragmentId: Record<FactId, AgenticMemoryRecordMetadata>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\treadonly invalidRecordIndexes: Set<number>;\n} {\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tconst fragments: MemoryFragment<T>[] = [];\n\tconst metadataByFragmentId = Object.create(null) as Record<FactId, AgenticMemoryRecordMetadata>;\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tconst invalidRecordIndexes = new Set<number>();\n\tconst seenRecordIds = new Set<FactId>();\n\tconst seenFragmentIds = new Set<FactId>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input must be an array\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-records-input\",\n\t\t\tmessage: \"agenticMemoryBundle: records input length could not be read\",\n\t\t\trecord: value,\n\t\t});\n\t\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-record\",\n\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst result = validateAndSnapshotRecord<T>(raw, i);\n\t\tif (result.errors.length > 0) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push(...result.errors);\n\t\t\tcontinue;\n\t\t}\n\t\tif (result.record === undefined) continue;\n\t\tif (seenRecordIds.has(result.record.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-record-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate record id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate record id '${result.record.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (seenFragmentIds.has(result.record.fragment.id)) {\n\t\t\tinvalidRecordIndexes.add(i);\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-fragment-id\",\n\t\t\t\tmessage: \"agenticMemoryBundle: duplicate fragment id\",\n\t\t\t\tindex: i,\n\t\t\t\trecordId: result.record.id,\n\t\t\t\tfragmentId: result.record.fragment.id,\n\t\t\t\trecord: raw,\n\t\t\t\tvalidationErrors: [`duplicate fragment id '${result.record.fragment.id}'`],\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenRecordIds.add(result.record.id);\n\t\tseenFragmentIds.add(result.record.fragment.id);\n\t\trecords.push(result.record);\n\t\tfragments.push(result.record.fragment);\n\t\tmetadataByFragmentId[result.record.fragment.id] = recordMetadata(result.record);\n\t}\n\treturn { records, fragments, metadataByFragmentId, errors, invalidRecordIndexes };\n}\n\nexport function validateAndSnapshotRecord<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\ttry {\n\t\treturn validateAndSnapshotRecordInner<T>(value, index);\n\t} catch (error) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: `agenticMemoryBundle: record access failed: ${errorMessage(error)}`,\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t\tvalidationErrors: Object.freeze([\"record access failed\"]),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n}\n\nexport function validateAndSnapshotRecordInner<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly record?: AgenticMemoryRecord<T>;\n\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryError, \"cursor\">[] = [];\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-record\",\n\t\t\t\t\tmessage: \"agenticMemoryBundle: record must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\trecord: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst record = value as Partial<AgenticMemoryRecord<T>> & Record<string, unknown>;\n\tconst recordId = typeof record.id === \"string\" ? record.id : undefined;\n\tif (recordId === undefined || recordId.length === 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record.id must be a non-empty string\",\n\t\t\tindex,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"record.id must be a non-empty string\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryKind(record.kind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.kind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"kind must be one of working, episodic, semantic, procedural, profile\"],\n\t\t});\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(record.persistenceLevel)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-persistence-level\",\n\t\t\tmessage: \"agenticMemoryBundle: record.persistenceLevel is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\n\t\t\t\t\"persistenceLevel must be one of turn, session, project, longTerm, permanent, archived\",\n\t\t\t],\n\t\t});\n\t}\n\tif (!isAgenticMemoryArtifactKind(record.artifactKind)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-artifact-kind\",\n\t\t\tmessage: \"agenticMemoryBundle: record.artifactKind is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: [\"artifactKind must be one of raw, insight, profile, procedure\"],\n\t\t});\n\t}\n\tconst scopeValidation = validateScope(record.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-scope\",\n\t\t\tmessage: \"agenticMemoryBundle: record.scope is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(scopeValidation.errors),\n\t\t});\n\t}\n\tconst fragmentValidation = validateMemoryFragment(record.fragment);\n\tif (!fragmentValidation.ok) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-fragment\",\n\t\t\tmessage: \"agenticMemoryBundle: record.fragment is invalid\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\tfragmentId:\n\t\t\t\ttypeof record.fragment === \"object\" &&\n\t\t\t\trecord.fragment !== null &&\n\t\t\t\ttypeof (record.fragment as Partial<MemoryFragment>).id === \"string\"\n\t\t\t\t\t? (record.fragment as Partial<MemoryFragment>).id\n\t\t\t\t\t: undefined,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze([...fragmentValidation.errors]),\n\t\t});\n\t}\n\tconst forbiddenFields = [\n\t\t\"storageTier\",\n\t\t\"storageKey\",\n\t\t\"adapter\",\n\t\t\"collection\",\n\t\t\"collections\",\n\t\t\"ttl\",\n\t\t\"ttlMs\",\n\t\t\"ttlNs\",\n\t\t\"expiresAt\",\n\t\t\"timer\",\n\t\t\"scheduler\",\n\t\t\"schedule\",\n\t\t\"retentionTimer\",\n\t\t\"consolidationSchedule\",\n\t\t\"reflectionSchedule\",\n\t\t\"llm\",\n\t\t\"llmHandle\",\n\t\t\"tool\",\n\t\t\"toolHandle\",\n\t\t\"runner\",\n\t\t\"runnerHandle\",\n\t\t\"restore\",\n\t\t\"hydrate\",\n\t\t\"hydration\",\n\t\t\"graphMutation\",\n\t\t\"protocol\",\n\t] as const;\n\tconst presentForbidden = forbiddenFields.filter((field) => Object.hasOwn(record, field));\n\tif (presentForbidden.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-record\",\n\t\t\tmessage: \"agenticMemoryBundle: record contains forbidden runtime/persistence fields\",\n\t\t\tindex,\n\t\t\trecordId,\n\t\t\trecord: value,\n\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\tpresentForbidden.map((field) => `${field} is not part of AgenticMemoryRecord`),\n\t\t\t),\n\t\t});\n\t}\n\tif (errors.length > 0) return { errors };\n\tconst scope = scopeValidation.scope;\n\tconst fragment = snapshotFragment(record.fragment as MemoryFragment<T>);\n\treturn {\n\t\trecord: Object.freeze({\n\t\t\tid: recordId as FactId,\n\t\t\tkind: record.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: record.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: record.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\tfragment,\n\t\t}),\n\t\terrors,\n\t};\n}\n\nexport function snapshotFragment<T>(fragment: MemoryFragment<T>): MemoryFragment<T> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: fragment.tNs,\n\t\t...(fragment.validFrom === undefined ? {} : { validFrom: fragment.validFrom }),\n\t\t...(fragment.validTo === undefined ? {} : { validTo: fragment.validTo }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nexport function recordMetadata(record: AgenticMemoryRecord): AgenticMemoryRecordMetadata {\n\treturn Object.freeze({\n\t\trecordId: record.id,\n\t\tkind: record.kind,\n\t\tpersistenceLevel: record.persistenceLevel,\n\t\tartifactKind: record.artifactKind,\n\t\t...(record.scope === undefined ? {} : { scope: record.scope }),\n\t});\n}\n\nexport function validateRecordMetadata(value: unknown): {\n\treadonly ok: boolean;\n\treadonly metadata?: AgenticMemoryRecordMetadata;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (!isPlainRecord(value)) {\n\t\treturn { ok: false, errors: [\"record metadata must be an object when present\"] };\n\t}\n\tconst errors: string[] = [];\n\tfor (const key of Object.keys(value)) {\n\t\tif (\n\t\t\tkey !== \"recordId\" &&\n\t\t\tkey !== \"kind\" &&\n\t\t\tkey !== \"persistenceLevel\" &&\n\t\t\tkey !== \"artifactKind\" &&\n\t\t\tkey !== \"scope\"\n\t\t) {\n\t\t\terrors.push(`record.${key} is not part of AgenticMemoryRecordMetadata`);\n\t\t}\n\t}\n\tif (!isNonEmptyString(value.recordId)) {\n\t\terrors.push(\"record.recordId must be a non-empty string\");\n\t}\n\tif (!isAgenticMemoryKind(value.kind)) {\n\t\terrors.push(\"record.kind is invalid\");\n\t}\n\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\terrors.push(\"record.persistenceLevel is invalid\");\n\t}\n\tif (!isAgenticMemoryArtifactKind(value.artifactKind)) {\n\t\terrors.push(\"record.artifactKind is invalid\");\n\t}\n\tconst scopeValidation = validateScope(value.scope);\n\tif (!scopeValidation.ok) {\n\t\terrors.push(...scopeValidation.errors.map((error) => `record.${error}`));\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tmetadata: Object.freeze({\n\t\t\trecordId: value.recordId as FactId,\n\t\t\tkind: value.kind as AgenticMemoryKind,\n\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\tartifactKind: value.artifactKind as AgenticMemoryArtifactKind,\n\t\t\t...(scopeValidation.scope === undefined ? {} : { scope: scopeValidation.scope }),\n\t\t}),\n\t};\n}\n\nexport function contextState(\n\tprojection: AgenticMemoryStatusState,\n\tretrieval: MemoryRetrievalStatus[\"state\"],\n): AgenticMemoryContextState {\n\tif (projection === \"error\" || retrieval === \"error\") return \"error\";\n\tif (projection === \"partial\" || retrieval === \"partial\") return \"partial\";\n\treturn retrieval;\n}\n\nexport function agenticStatusState(\n\terrorCount: number,\n\tvalidRecords: number,\n): AgenticMemoryStatusState {\n\tif (errorCount > 0 && validRecords === 0) return \"error\";\n\tif (errorCount > 0) return \"partial\";\n\treturn validRecords > 0 ? \"ready\" : \"empty\";\n}\n\nexport function isAgenticMemoryKind(value: unknown): value is AgenticMemoryKind {\n\treturn (\n\t\tvalue === \"working\" ||\n\t\tvalue === \"episodic\" ||\n\t\tvalue === \"semantic\" ||\n\t\tvalue === \"procedural\" ||\n\t\tvalue === \"profile\"\n\t);\n}\n\nexport function isAgenticMemoryPersistenceLevel(\n\tvalue: unknown,\n): value is AgenticMemoryPersistenceLevel {\n\treturn (\n\t\tvalue === \"turn\" ||\n\t\tvalue === \"session\" ||\n\t\tvalue === \"project\" ||\n\t\tvalue === \"longTerm\" ||\n\t\tvalue === \"permanent\" ||\n\t\tvalue === \"archived\"\n\t);\n}\n\nexport function isAgenticMemoryArtifactKind(value: unknown): value is AgenticMemoryArtifactKind {\n\treturn value === \"raw\" || value === \"insight\" || value === \"profile\" || value === \"procedure\";\n}\n\nexport function validateScope(value: unknown): {\n\treadonly ok: boolean;\n\treadonly scope?: AgenticMemoryScope;\n\treadonly errors: readonly string[];\n} {\n\tif (value === undefined) return { ok: true, errors: [] };\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn { ok: false, errors: [\"scope must be an object when present\"] };\n\t}\n\tconst scope = value as Record<string, unknown>;\n\tconst errors: string[] = [];\n\tconst allowed = new Set([\"sessionId\", \"projectId\", \"userId\", \"tenantId\"]);\n\tfor (const key of Object.keys(scope)) {\n\t\tif (!allowed.has(key)) errors.push(`scope.${key} is not part of AgenticMemoryScope`);\n\t}\n\tfor (const key of allowed) {\n\t\tif (scope[key] !== undefined && (typeof scope[key] !== \"string\" || scope[key].length === 0)) {\n\t\t\terrors.push(`scope.${key} must be a non-empty string when present`);\n\t\t}\n\t}\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn {\n\t\tok: true,\n\t\terrors,\n\t\tscope: Object.freeze({\n\t\t\t...(scope.sessionId === undefined ? {} : { sessionId: scope.sessionId as string }),\n\t\t\t...(scope.projectId === undefined ? {} : { projectId: scope.projectId as string }),\n\t\t\t...(scope.userId === undefined ? {} : { userId: scope.userId as string }),\n\t\t\t...(scope.tenantId === undefined ? {} : { tenantId: scope.tenantId as string }),\n\t\t}),\n\t};\n}\n\nexport function isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function ownKeys(value: Record<string, unknown>): readonly string[] {\n\treturn Object.keys(value).sort();\n}\n\nexport function assertExactKeys(\n\tvalue: Record<string, unknown>,\n\texpected: readonly string[],\n\tlabel: string,\n): void {\n\tconst actual = ownKeys(value);\n\tconst want = [...expected].sort();\n\tif (actual.length !== want.length || actual.some((key, i) => key !== want[i])) {\n\t\tthrow new TypeError(`${label}: unexpected fields ${actual.join(\",\")}`);\n\t}\n}\n\nexport function assertAgenticMemoryRecordCodecShape(value: unknown): void {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertNoSymbolKeys(value, \"agenticMemoryRecordFrame.record\");\n\tassertExactKeys(\n\t\tvalue,\n\t\tvalue.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst fragment = value.fragment;\n\tif (!isPlainRecord(fragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertNoSymbolKeys(fragment, \"agenticMemoryRecordFrame.record.fragment\");\n\tassertExactKeys(\n\t\tfragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(fragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(fragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(fragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(fragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(fragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tassertStrictJsonValue(fragment.tags, \"record.fragment.tags\");\n\tassertStrictJsonValue(fragment.sources, \"record.fragment.sources\");\n\tif (fragment.embedding !== undefined) {\n\t\tassertStrictJsonValue(fragment.embedding, \"record.fragment.embedding\");\n\t}\n\tif (value.scope !== undefined) assertScopeFrame(value.scope);\n}\n\nexport function assertNoSymbolKeys(value: object, label: string): void {\n\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\tthrow new TypeError(`${label}: unexpected symbol fields`);\n\t}\n}\n\nexport function decimalBigIntString(value: bigint, label: string): string {\n\tconst out = value.toString(10);\n\tif (!/^-?(0|[1-9]\\d*)$/.test(out)) {\n\t\tthrow new TypeError(`${label} must encode as a canonical decimal bigint string`);\n\t}\n\treturn out;\n}\n\nexport function parseDecimalBigInt(value: unknown, label: string): bigint {\n\tif (typeof value !== \"string\" || !/^(0|-?[1-9]\\d*)$/.test(value)) {\n\t\tthrow new TypeError(`${label} must be a canonical decimal bigint string`);\n\t}\n\treturn BigInt(value);\n}\n\nexport function assertStrictJsonValue(value: unknown, label: string): StrictJsonValue {\n\ttry {\n\t\tstrictJsonCodec.encode(value);\n\t\treturn value as StrictJsonValue;\n\t} catch (error) {\n\t\tthrow new TypeError(`${label} must be strict JSON: ${errorMessage(error)}`);\n\t}\n}\n\nexport function assertScopeFrame(value: unknown): AgenticMemoryScope {\n\tif (!isPlainRecord(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: scope must be an object when present\");\n\t}\n\tassertStrictJsonValue(value, \"record.scope\");\n\tconst validation = validateScope(value);\n\tif (!validation.ok || validation.scope === undefined) {\n\t\tthrow new TypeError(`agenticMemoryRecordFrame: invalid scope: ${validation.errors.join(\"; \")}`);\n\t}\n\tassertExactKeys(\n\t\tvalue as Record<string, unknown>,\n\t\t[\n\t\t\t...((value as Record<string, unknown>).sessionId === undefined ? [] : [\"sessionId\"]),\n\t\t\t...((value as Record<string, unknown>).projectId === undefined ? [] : [\"projectId\"]),\n\t\t\t...((value as Record<string, unknown>).userId === undefined ? [] : [\"userId\"]),\n\t\t\t...((value as Record<string, unknown>).tenantId === undefined ? [] : [\"tenantId\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.scope\",\n\t);\n\treturn validation.scope;\n}\n\nexport function assertKindValue(value: unknown): AgenticMemoryKind {\n\tif (!isAgenticMemoryKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid memory kind\");\n\t}\n\treturn value;\n}\n\nexport function assertPersistenceLevelValue(value: unknown): AgenticMemoryPersistenceLevel {\n\tif (!isAgenticMemoryPersistenceLevel(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid persistence level\");\n\t}\n\treturn value;\n}\n\nexport function assertArtifactKindValue(value: unknown): AgenticMemoryArtifactKind {\n\tif (!isAgenticMemoryArtifactKind(value)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid artifact kind\");\n\t}\n\treturn value;\n}\n\nexport function assertNonEmptyString(value: unknown, label: string): string {\n\tif (!isNonEmptyString(value)) throw new TypeError(`${label} must be a non-empty string`);\n\treturn value;\n}\n\nexport function assertString(value: unknown, label: string): string {\n\tif (typeof value !== \"string\") throw new TypeError(`${label} must be a string`);\n\treturn value;\n}\n\nexport function assertConfidence(value: unknown, label: string): number {\n\tif (!Number.isFinite(value) || (value as number) < 0 || (value as number) > 1) {\n\t\tthrow new TypeError(`${label} must be a finite number in [0, 1]`);\n\t}\n\treturn value as number;\n}\n\nexport function assertStringArray(value: unknown, label: string): readonly string[] {\n\tif (!isDenseArrayOf(value, (item): item is string => typeof item === \"string\")) {\n\t\tthrow new TypeError(`${label} must be a readonly string array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nexport function assertFiniteNumberArray(value: unknown, label: string): readonly number[] {\n\tif (!isDenseArrayOf(value, (item): item is number => Number.isFinite(item))) {\n\t\tthrow new TypeError(`${label} must be a finite number array`);\n\t}\n\treturn Object.freeze([...value]);\n}\n\nexport function isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nexport function isDenseArrayOf<T>(\n\tvalue: unknown,\n\tpredicate: (item: unknown) => item is T,\n): value is T[] {\n\tif (!Array.isArray(value)) return false;\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tif (!Object.hasOwn(value, i) || !predicate(value[i])) return false;\n\t}\n\treturn true;\n}\n\nexport function freezeError<T extends { readonly validationErrors?: readonly string[] }>(\n\terror: T,\n): T {\n\treturn Object.freeze({\n\t\t...error,\n\t\t...(error.validationErrors === undefined\n\t\t\t? {}\n\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t}) as T;\n}\n\nexport function safeArrayLength(value: readonly unknown[]): number | undefined {\n\ttry {\n\t\treturn value.length;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","import { depBatch, depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { MemoryRetrievalSnapshot } from \"../patterns/semantic-memory-graph.js\";\nimport {\n\tagenticStatusState,\n\tcontextState,\n\tvalidateAndProjectRecords,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryContext,\n\tAgenticMemoryProjectionCursor,\n\tAgenticMemoryProjectionSnapshot,\n\tAgenticMemoryRecord,\n\tAgenticMemoryStatus,\n} from \"./agentic-memory-types.js\";\n\nexport function solutionProjection<TFact, TSnapshot>(\n\tgraph: Graph,\n\tsnapshot: Node<TSnapshot>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: TSnapshot) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as TSnapshot)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nexport function agenticMemoryProjection<TFact, T>(\n\tgraph: Graph,\n\tsnapshot: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: AgenticMemoryProjectionSnapshot<T>) => TFact,\n): Node<TFact> {\n\treturn graph.node<TFact>(\n\t\t[snapshot],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", select(raw as AgenticMemoryProjectionSnapshot<T>)]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nexport function agenticMemoryContextProjection<T>(\n\tgraph: Graph,\n\tprojection: Node<AgenticMemoryProjectionSnapshot<T>>,\n\tretrieval: Node<MemoryRetrievalSnapshot<T>>,\n\tname: string,\n): Node<AgenticMemoryContext<T>> {\n\treturn graph.node<AgenticMemoryContext<T>>(\n\t\t[projection, retrieval],\n\t\t(ctx) => {\n\t\t\tconst projectionFact = depLatest(ctx, 0) as AgenticMemoryProjectionSnapshot<T> | undefined;\n\t\t\tconst retrievalFacts = depBatch(ctx, 1) ?? [];\n\t\t\tif (projectionFact === undefined || retrievalFacts.length === 0) return;\n\t\t\tfor (const raw of retrievalFacts) {\n\t\t\t\tctx.down([\n\t\t\t\t\t[\"DATA\", contextFromSnapshot(projectionFact, raw as MemoryRetrievalSnapshot<T>)],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryContext\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nexport function contextFromSnapshot<T>(\n\tprojection: AgenticMemoryProjectionSnapshot<T>,\n\tretrieval: MemoryRetrievalSnapshot<T>,\n): AgenticMemoryContext<T> {\n\tconst entries = retrieval.ranked.results.map((fragment) =>\n\t\tObject.freeze({\n\t\t\tfragmentId: fragment.id,\n\t\t\tpayload: fragment.payload,\n\t\t\tconfidence: fragment.confidence,\n\t\t\ttags: fragment.tags,\n\t\t\tsources: fragment.sources,\n\t\t\t...(projection.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t? {}\n\t\t\t\t: { record: projection.metadataByFragmentId[fragment.id] }),\n\t\t\tfragment,\n\t\t}),\n\t);\n\tconst hasContext = entries.length > 0;\n\tconst state = contextState(projection.status.state, retrieval.status.state);\n\treturn Object.freeze({\n\t\tstate,\n\t\tquery: retrieval.ranked.query,\n\t\tentries: Object.freeze(entries),\n\t\tcursor: retrieval.cursor,\n\t\terrors: projection.errors,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcontextReady: hasContext && (state === \"ready\" || state === \"partial\"),\n\t});\n}\n\nexport function agenticMemoryRecordProjection<T>(\n\tgraph: Graph,\n\trecords: Node<readonly AgenticMemoryRecord<T>[]>,\n\tname: string,\n): Node<AgenticMemoryProjectionSnapshot<T>> {\n\treturn graph.node<AgenticMemoryProjectionSnapshot<T>>(\n\t\t[records],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst rawRecords = (depBatch(ctx, 0) ?? []).at(-1);\n\t\t\tconst projected = validateAndProjectRecords<T>(rawRecords);\n\t\t\tconst cursor: AgenticMemoryProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: projected.records.length,\n\t\t\t\tinvalidRecords: projected.invalidRecordIndexes.size,\n\t\t\t\tprojectedFragments: projected.fragments.length,\n\t\t\t});\n\t\t\tconst status: AgenticMemoryStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(projected.errors.length, projected.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\tprojected.errors.map((error) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\t...error,\n\t\t\t\t\t\t...(error.validationErrors === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { validationErrors: Object.freeze([...error.validationErrors]) }),\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\trecords: Object.freeze(projected.records),\n\t\t\t\t\t\tfragments: Object.freeze(projected.fragments),\n\t\t\t\t\t\tmetadataByFragmentId: Object.freeze(projected.metadataByFragmentId),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory: \"agenticMemoryProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n","import type { Graph } from \"../graph/graph.js\";\nimport { memoryRetrievalBundle } from \"../patterns/semantic-memory-graph.js\";\nimport {\n\tagenticMemoryContextProjection,\n\tagenticMemoryProjection,\n\tagenticMemoryRecordProjection,\n} from \"./agentic-memory-projection.js\";\nimport type { AgenticMemoryBundle, AgenticMemoryBundleOptions } from \"./agentic-memory-types.js\";\n\nexport function agenticMemoryBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryBundleOptions<T>,\n): AgenticMemoryBundle<T> {\n\tconst name = opts.name ?? \"agenticMemory\";\n\tconst projection = agenticMemoryRecordProjection<T>(graph, opts.records, `${name}/projection`);\n\tconst projectedRecords = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/records`,\n\t\t\"agenticMemoryRecords\",\n\t\t(fact) => fact.records,\n\t);\n\tconst projectedFragments = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/fragments`,\n\t\t\"agenticMemoryFragments\",\n\t\t(fact) => fact.fragments,\n\t);\n\tconst status = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/status`,\n\t\t\"agenticMemoryStatus\",\n\t\t(fact) => fact.status,\n\t);\n\tconst errors = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/errors`,\n\t\t\"agenticMemoryErrors\",\n\t\t(fact) => fact.errors,\n\t);\n\tconst retrieval = memoryRetrievalBundle<T>(graph, {\n\t\tname: `${name}/retrieval`,\n\t\tfragments: projectedFragments,\n\t\tquery: opts.query,\n\t});\n\tconst sources = agenticMemoryProjection(\n\t\tgraph,\n\t\tprojection,\n\t\t`${name}/sources`,\n\t\t\"agenticMemorySources\",\n\t\t(fact) =>\n\t\t\tObject.freeze(\n\t\t\t\tfact.fragments.map((fragment) =>\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tfragmentId: fragment.id,\n\t\t\t\t\t\t...(fact.metadataByFragmentId[fragment.id] === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { record: fact.metadataByFragmentId[fragment.id] }),\n\t\t\t\t\t\tsources: Object.freeze([...fragment.sources]),\n\t\t\t\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t\t\t\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t);\n\tconst context = agenticMemoryContextProjection(\n\t\tgraph,\n\t\tprojection,\n\t\tretrieval.snapshot,\n\t\t`${name}/context`,\n\t);\n\n\treturn {\n\t\tinput: { records: opts.records, query: opts.query },\n\t\tprojection,\n\t\tretrieval,\n\t\tretrievalSnapshot: retrieval.snapshot,\n\t\trecords: projectedRecords,\n\t\tfragments: projectedFragments,\n\t\tsources,\n\t\tindexed: retrieval.indexed,\n\t\tranked: retrieval.ranked,\n\t\tcontext,\n\t\tstatus,\n\t\terrors,\n\t\tretrievalStatus: retrieval.status,\n\t\tretrievalErrors: retrieval.errors,\n\t\tcursor: retrieval.cursor,\n\t};\n}\n\n/**\n * D165 solution-level KG assertion projection.\n *\n * Records and explicit assertion drafts stay visible as declared deps. This\n * bundle validates references and shape, then emits DATA facts only; it does\n * not extract assertions, call LLMs, read/write storage, or mutate topology.\n */\n","import { depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { FactId } from \"../patterns/semantic-memory.js\";\nimport { solutionProjection } from \"./agentic-memory-projection.js\";\nimport {\n\tagenticStatusState,\n\terrorMessage,\n\tfreezeError,\n\tisDenseArrayOf,\n\tisNonEmptyString,\n\tisPlainRecord,\n\tsafeArrayLength,\n\tvalidateAndProjectRecords,\n\tvalidateAndSnapshotRecord,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryConsolidationBundle,\n\tAgenticMemoryConsolidationBundleOptions,\n\tAgenticMemoryConsolidationCommand,\n\tAgenticMemoryConsolidationCursor,\n\tAgenticMemoryConsolidationError,\n\tAgenticMemoryConsolidationOutcome,\n\tAgenticMemoryConsolidationRecordDraft,\n\tAgenticMemoryConsolidationRequest,\n\tAgenticMemoryConsolidationResult,\n\tAgenticMemoryConsolidationSnapshot,\n\tAgenticMemoryConsolidationStatus,\n\tAgenticMemoryError,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRetentionError,\n} from \"./agentic-memory-types.js\";\n\nexport function agenticMemoryConsolidationBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryConsolidationBundleOptions<T>,\n): AgenticMemoryConsolidationBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryConsolidation\";\n\tconst projection = graph.node<AgenticMemoryConsolidationSnapshot<T>>(\n\t\t[opts.records, opts.requests, opts.outcomes],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst requests = validateConsolidationRequests(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst outcomes = projectConsolidationOutcomes<T>(\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\trequests.requests,\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryConsolidationCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRequests: requests.requests.length,\n\t\t\t\tvalidOutcomes: outcomes.validOutcomes,\n\t\t\t\tinvalidOutcomes: outcomes.invalidOutcomes,\n\t\t\t\tresults: outcomes.results.length,\n\t\t\t\tproposedRecordDrafts: outcomes.proposedRecordDrafts.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[\n\t\t\t\t\t...recordProjection.errors.map(consolidationErrorFromRecordError),\n\t\t\t\t\t...requests.errors.map(consolidationErrorFromRetentionError),\n\t\t\t\t\t...outcomes.errors,\n\t\t\t\t].map((error) => freezeError({ ...error, cursor })),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryConsolidationStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, outcomes.results.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tresults: Object.freeze(outcomes.results),\n\t\t\t\t\t\tproposedRecordDrafts: Object.freeze(outcomes.proposedRecordDrafts),\n\t\t\t\t\t\tcommands: Object.freeze(outcomes.commands),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryConsolidation\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, requests: opts.requests, outcomes: opts.outcomes },\n\t\tprojection,\n\t\tresults: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/results`,\n\t\t\t\"agenticMemoryConsolidationResults\",\n\t\t\t(fact) => fact.results,\n\t\t),\n\t\tproposedRecordDrafts: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/proposedRecordDrafts`,\n\t\t\t\"agenticMemoryConsolidationRecordDrafts\",\n\t\t\t(fact) => fact.proposedRecordDrafts,\n\t\t),\n\t\tcommands: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/commands`,\n\t\t\t\"agenticMemoryConsolidationCommands\",\n\t\t\t(fact) => fact.commands,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryConsolidationStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryConsolidationErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryConsolidationCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** D168 deterministic context-packing bundle over explicit context text facts. */\n\nfunction validateConsolidationRequests<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly requests: readonly AgenticMemoryConsolidationRequest[];\n\treadonly errors: readonly Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\trequests,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: requests input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seen = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"request array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: request access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: Object.freeze([\"request access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (!isPlainRecord(raw)) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request must be an object\",\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = isNonEmptyString(raw.id) ? raw.id : undefined;\n\t\tconst commandId = isNonEmptyString(raw.commandId) ? raw.commandId : undefined;\n\t\tconst recordIds = isDenseArrayOf(raw.recordIds, isNonEmptyString)\n\t\t\t? Object.freeze([...raw.recordIds])\n\t\t\t: undefined;\n\t\tconst validationErrors: string[] = [];\n\t\tif (id === undefined) validationErrors.push(\"request.id must be a non-empty string\");\n\t\tif (commandId === undefined) {\n\t\t\tvalidationErrors.push(\"request.commandId must be a non-empty string\");\n\t\t}\n\t\tif (recordIds === undefined || recordIds.length === 0) {\n\t\t\tvalidationErrors.push(\"request.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (raw.reason !== undefined && typeof raw.reason !== \"string\") {\n\t\t\tvalidationErrors.push(\"request.reason must be a string when present\");\n\t\t}\n\t\tif (id !== undefined && seen.has(id)) {\n\t\t\tvalidationErrors.push(`duplicate request id '${id}'`);\n\t\t}\n\t\tconst missing = (recordIds ?? []).filter((recordId) => !byId.has(recordId));\n\t\tif (missing.length > 0) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request references missing records\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(\n\t\t\t\t\tmissing.map((recordId) => `record '${recordId}' is not projected`),\n\t\t\t\t),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tvalidationErrors.length > 0 ||\n\t\t\tid === undefined ||\n\t\t\tcommandId === undefined ||\n\t\t\trecordIds === undefined\n\t\t) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: request is invalid\",\n\t\t\t\tindex: i,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: Object.freeze(validationErrors),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(id);\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid,\n\t\t\t\tcommandId,\n\t\t\t\trecordIds,\n\t\t\t\t...(raw.reason === undefined ? {} : { reason: raw.reason as string }),\n\t\t\t}),\n\t\t);\n\t}\n\treturn { requests: Object.freeze(requests), errors };\n}\n\nfunction projectConsolidationOutcomes<T>(\n\tvalue: unknown,\n\trequests: readonly AgenticMemoryConsolidationRequest[],\n\tevaluation: number,\n): {\n\treadonly results: readonly AgenticMemoryConsolidationResult[];\n\treadonly proposedRecordDrafts: readonly AgenticMemoryConsolidationRecordDraft<T>[];\n\treadonly commands: readonly AgenticMemoryConsolidationCommand[];\n\treadonly errors: readonly Omit<AgenticMemoryConsolidationError, \"cursor\">[];\n\treadonly validOutcomes: number;\n\treadonly invalidOutcomes: number;\n} {\n\tconst byRequest = new Map(requests.map((request) => [request.id, request]));\n\tconst results: AgenticMemoryConsolidationResult[] = [];\n\tconst proposedRecordDrafts: AgenticMemoryConsolidationRecordDraft<T>[] = [];\n\tconst commands: AgenticMemoryConsolidationCommand[] = [];\n\tconst errors: Omit<AgenticMemoryConsolidationError, \"cursor\">[] = [];\n\tlet validOutcomes = 0;\n\tlet invalidOutcomes = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input must be an array\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tresults,\n\t\t\tproposedRecordDrafts,\n\t\t\tcommands,\n\t\t\tvalidOutcomes,\n\t\t\tinvalidOutcomes: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-outcomes-input\",\n\t\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcomes input length could not be read\",\n\t\t\t\t\toutcome: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenOutcomes = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\tlet outcome: {\n\t\t\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\t\t\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n\t\t};\n\t\ttry {\n\t\t\tif (!Object.hasOwn(value, i)) {\n\t\t\t\tthrow new TypeError(\"outcome array must be dense\");\n\t\t\t}\n\t\t\traw = value[i];\n\t\t\toutcome = validateConsolidationOutcome<T>(raw, i);\n\t\t} catch (error) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: `agenticMemoryConsolidationBundle: outcome access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([\"outcome access failed\"]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (outcome.error !== undefined || outcome.outcome === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\tif (outcome.error !== undefined) errors.push(outcome.error);\n\t\t\tcontinue;\n\t\t}\n\t\tconst validOutcome = outcome.outcome;\n\t\tif (seenOutcomes.has(validOutcome.id)) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"duplicate-outcome-id\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: duplicate outcome id\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`duplicate outcome id '${validOutcome.id}'`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst request = byRequest.get(validOutcome.requestId);\n\t\tif (request === undefined) {\n\t\t\tinvalidOutcomes += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"missing-request-ref\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome references missing request\",\n\t\t\t\tindex: i,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcome: raw,\n\t\t\t\tvalidationErrors: Object.freeze([`request '${validOutcome.requestId}' is not projected`]),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tseenOutcomes.add(validOutcome.id);\n\t\tvalidOutcomes += 1;\n\t\tif (validOutcome.kind === \"failed\") {\n\t\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: resultId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\t\tproposedRecordIds: Object.freeze([]),\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcommands.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: `${resultId}:markFailed`,\n\t\t\t\t\tkind: \"markFailed\",\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\tmessage: validOutcome.message,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst draftIds = validOutcome.records.map(\n\t\t\t(record) => `${validOutcome.requestId}:${validOutcome.id}:${record.id}`,\n\t\t);\n\t\tfor (let recordIndex = 0; recordIndex < validOutcome.records.length; recordIndex += 1) {\n\t\t\tproposedRecordDrafts.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draftIds[recordIndex] as FactId,\n\t\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\t\trecord: validOutcome.records[recordIndex] as AgenticMemoryRecord<T>,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst resultId = `${validOutcome.requestId}:${validOutcome.id}`;\n\t\tresults.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: resultId,\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tstate: \"proposed\",\n\t\t\t\tsourceRecordIds: request.recordIds,\n\t\t\t\tproposedRecordIds: Object.freeze(validOutcome.records.map((record) => record.id)),\n\t\t\t\t...(validOutcome.provenance === undefined ? {} : { provenance: validOutcome.provenance }),\n\t\t\t}),\n\t\t);\n\t\tcommands.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: `${resultId}:proposeRecords`,\n\t\t\t\tkind: \"proposeRecords\",\n\t\t\t\trequestId: validOutcome.requestId,\n\t\t\t\toutcomeId: validOutcome.id,\n\t\t\t\tdraftIds: Object.freeze(draftIds),\n\t\t\t}),\n\t\t);\n\t}\n\tvoid evaluation;\n\treturn {\n\t\tresults: Object.freeze(results),\n\t\tproposedRecordDrafts: Object.freeze(proposedRecordDrafts),\n\t\tcommands: Object.freeze(commands),\n\t\terrors,\n\t\tvalidOutcomes,\n\t\tinvalidOutcomes,\n\t};\n}\n\nfunction validateConsolidationOutcome<T>(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly outcome?: AgenticMemoryConsolidationOutcome<T>;\n\treadonly error?: Omit<AgenticMemoryConsolidationError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome must be an object\",\n\t\t\t\tindex,\n\t\t\t\toutcome: value,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tconst id = isNonEmptyString(value.id) ? value.id : undefined;\n\tconst requestId = isNonEmptyString(value.requestId) ? value.requestId : undefined;\n\tif (id === undefined) errors.push(\"outcome.id must be a non-empty string\");\n\tif (requestId === undefined) errors.push(\"outcome.requestId must be a non-empty string\");\n\tif (value.kind !== \"proposedRecords\" && value.kind !== \"failed\") {\n\t\terrors.push(\"outcome.kind must be proposedRecords or failed\");\n\t}\n\tif (value.provenance !== undefined && typeof value.provenance !== \"string\") {\n\t\terrors.push(\"outcome.provenance must be a string when present\");\n\t}\n\tif (value.kind === \"failed\" && !isNonEmptyString(value.message)) {\n\t\terrors.push(\"failed outcome.message must be a non-empty string\");\n\t}\n\tconst records: AgenticMemoryRecord<T>[] = [];\n\tif (value.kind === \"proposedRecords\") {\n\t\tif (!Array.isArray(value.records)) {\n\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t} else {\n\t\t\tconst recordsLength = safeArrayLength(value.records);\n\t\t\tconst seenRecordIds = new Set<FactId>();\n\t\t\tif (recordsLength === undefined || recordsLength === 0) {\n\t\t\t\terrors.push(\"proposedRecords.records must be a non-empty array\");\n\t\t\t}\n\t\t\tfor (let i = 0; i < (recordsLength ?? 0); i += 1) {\n\t\t\t\tlet result: {\n\t\t\t\t\treadonly record?: AgenticMemoryRecord<T>;\n\t\t\t\t\treadonly errors: Omit<AgenticMemoryError, \"cursor\">[];\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (!Object.hasOwn(value.records, i)) {\n\t\t\t\t\t\tthrow new TypeError(\"proposedRecords.records must be dense\");\n\t\t\t\t\t}\n\t\t\t\t\tresult = validateAndSnapshotRecord<T>(value.records[i], i);\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(`records[${i}]: record access failed: ${errorMessage(error)}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (result.record === undefined || result.errors.length > 0) {\n\t\t\t\t\terrors.push(\n\t\t\t\t\t\t...result.errors\n\t\t\t\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t\t\t\t.map((error) => `records[${i}]: ${error}`),\n\t\t\t\t\t);\n\t\t\t\t} else if (seenRecordIds.has(result.record.id)) {\n\t\t\t\t\terrors.push(`records[${i}]: duplicate proposed record id '${result.record.id}'`);\n\t\t\t\t} else {\n\t\t\t\t\tseenRecordIds.add(result.record.id);\n\t\t\t\t\trecords.push(result.record);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined || requestId === undefined) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: value.kind === \"proposedRecords\" ? \"invalid-proposed-record\" : \"invalid-outcome\",\n\t\t\t\tmessage: \"agenticMemoryConsolidationBundle: outcome is invalid\",\n\t\t\t\tindex,\n\t\t\t\toutcomeId: id,\n\t\t\t\trequestId,\n\t\t\t\toutcome: value,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\tif (value.kind === \"failed\") {\n\t\treturn {\n\t\t\toutcome: Object.freeze({\n\t\t\t\tid,\n\t\t\t\trequestId,\n\t\t\t\tkind: \"failed\",\n\t\t\t\tmessage: value.message as string,\n\t\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t\t}),\n\t\t};\n\t}\n\treturn {\n\t\toutcome: Object.freeze({\n\t\t\tid,\n\t\t\trequestId,\n\t\t\tkind: \"proposedRecords\",\n\t\t\trecords: Object.freeze(records),\n\t\t\t...(value.provenance === undefined ? {} : { provenance: value.provenance as string }),\n\t\t}),\n\t};\n}\n\nfunction consolidationErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n\nfunction consolidationErrorFromRetentionError(\n\terror: Omit<AgenticMemoryRetentionError, \"cursor\">,\n): Omit<AgenticMemoryConsolidationError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n","import { depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { FactId } from \"../patterns/semantic-memory.js\";\nimport { solutionProjection } from \"./agentic-memory-projection.js\";\nimport {\n\tagenticStatusState,\n\tassertStrictJsonValue,\n\terrorMessage,\n\tfreezeError,\n\tisNonEmptyString,\n\tisPlainRecord,\n\tsafeArrayLength,\n\tvalidateRecordMetadata,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryContextEntry,\n\tAgenticMemoryContextPackingBundle,\n\tAgenticMemoryContextPackingBundleOptions,\n\tAgenticMemoryContextPackingCursor,\n\tAgenticMemoryContextPackingError,\n\tAgenticMemoryContextPackingPolicy,\n\tAgenticMemoryContextPackingSnapshot,\n\tAgenticMemoryContextPackingStatus,\n\tAgenticMemoryContextText,\n\tAgenticMemoryPackedContext,\n\tAgenticMemoryPackedContextEntry,\n\tStrictJsonValue,\n\tValidatedPackingContext,\n} from \"./agentic-memory-types.js\";\n\nexport function agenticMemoryContextPackingBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryContextPackingBundleOptions<T>,\n): AgenticMemoryContextPackingBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryContextPacking\";\n\tconst projection = graph.node<AgenticMemoryContextPackingSnapshot>(\n\t\t[opts.context, opts.texts, opts.policy],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst packed = packContext(\n\t\t\t\tdepLatest(ctx, 0),\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\tdepLatest(ctx, 2),\n\t\t\t\tstate.evaluation,\n\t\t\t);\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", packed]]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryContextPacking\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { context: opts.context, texts: opts.texts, policy: opts.policy },\n\t\tprojection,\n\t\tpackedContext: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/packedContext`,\n\t\t\t\"agenticMemoryPackedContext\",\n\t\t\t(fact) => fact.packedContext,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryContextPackingStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryContextPackingErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryContextPackingCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\nfunction packContext(\n\tcontextValue: unknown,\n\ttextsValue: unknown,\n\tpolicyValue: unknown,\n\tevaluation: number,\n): AgenticMemoryContextPackingSnapshot {\n\tconst errors: Omit<AgenticMemoryContextPackingError, \"cursor\">[] = [];\n\tconst context = validatePackingContext(contextValue, errors);\n\tconst texts = validateContextTexts(textsValue, errors);\n\tconst policy = validatePackingPolicy(policyValue, errors);\n\tconst packedEntries: AgenticMemoryPackedContextEntry[] = [];\n\tlet omittedEntries = 0;\n\tlet totalChars = 0;\n\tlet totalCost = 0;\n\tif (context !== undefined && policy !== undefined) {\n\t\tfor (const entry of context.entries) {\n\t\t\tconst textFact = texts.get(entry.fragmentId);\n\t\t\tif (textFact === undefined) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: missing text projection for context entry\",\n\t\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\t\tvalidationErrors: [`missing text for fragment '${entry.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst cost = textFact.cost ?? textFact.text.length;\n\t\t\tconst nextEntries = packedEntries.length + 1;\n\t\t\tconst separatorChars = packedEntries.length === 0 ? 0 : 2;\n\t\t\tconst nextChars = totalChars + separatorChars + textFact.text.length;\n\t\t\tconst nextCost = totalCost + cost;\n\t\t\tconst exceeds =\n\t\t\t\t(policy.maxEntries !== undefined && nextEntries > policy.maxEntries) ||\n\t\t\t\t(policy.maxChars !== undefined && nextChars > policy.maxChars) ||\n\t\t\t\t(policy.maxCost !== undefined && nextCost > policy.maxCost);\n\t\t\tif (exceeds) {\n\t\t\t\tomittedEntries += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst packedEntry: AgenticMemoryPackedContextEntry = Object.freeze({\n\t\t\t\tfragmentId: entry.fragmentId,\n\t\t\t\ttext: textFact.text,\n\t\t\t\tcost,\n\t\t\t\tchars: textFact.text.length,\n\t\t\t\t...(entry.record === undefined ? {} : { record: entry.record }),\n\t\t\t\t...(policy.includeMetadata && textFact.metadata !== undefined\n\t\t\t\t\t? { metadata: textFact.metadata }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tpackedEntries.push(packedEntry);\n\t\t\ttotalChars = nextChars;\n\t\t\ttotalCost = nextCost;\n\t\t}\n\t}\n\tconst cursor: AgenticMemoryContextPackingCursor = Object.freeze({\n\t\tevaluation,\n\t\tinputEntries: context?.entries.length ?? 0,\n\t\tpackedEntries: packedEntries.length,\n\t\tomittedEntries,\n\t\ttotalChars,\n\t\ttotalCost,\n\t});\n\tconst errorFacts = Object.freeze(\n\t\terrors.map((error) =>\n\t\t\tfreezeError({\n\t\t\t\t...error,\n\t\t\t\tcursor,\n\t\t\t}),\n\t\t),\n\t);\n\tconst packedContext: AgenticMemoryPackedContext = Object.freeze({\n\t\tentries: Object.freeze(packedEntries),\n\t\ttext: packedEntries.map((entry) => entry.text).join(\"\\n\\n\"),\n\t\ttotalChars,\n\t\ttotalCost,\n\t\ttruncated: omittedEntries > 0,\n\t});\n\tconst status: AgenticMemoryContextPackingStatus = Object.freeze({\n\t\tstate: agenticStatusState(errorFacts.length, packedEntries.length),\n\t\tcursor,\n\t});\n\treturn Object.freeze({\n\t\tpackedContext,\n\t\tstatus,\n\t\terrors: errorFacts,\n\t\tcursor,\n\t});\n}\n\nfunction validatePackingContext(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): ValidatedPackingContext | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tlet entriesValue: unknown;\n\ttry {\n\t\tentriesValue = value.entries;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: context entries access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context entries access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(entriesValue)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context must be an AgenticMemoryContext fact\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries must be an array\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst length = safeArrayLength(entriesValue);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-context\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entries length could not be read\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"context.entries length could not be read\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst entries: AgenticMemoryContextEntry[] = [];\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = entriesValue[i];\n\t\t\tif (!isPlainRecord(raw) || !isNonEmptyString(raw.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"context entry fragmentId must be a non-empty string\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = validateRecordMetadata(raw.record);\n\t\t\tif (!record.ok) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-context\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: context entry record metadata is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(record.errors),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tentries.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tfragmentId: raw.fragmentId,\n\t\t\t\t\t...(record.metadata === undefined ? {} : { record: record.metadata }),\n\t\t\t\t}) as AgenticMemoryContextEntry,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-context\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: context entry access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalue: raw,\n\t\t\t\tvalidationErrors: [\"context entry access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn Object.freeze({\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction validateContextTexts(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): Map<FactId, AgenticMemoryContextText> {\n\tconst out = new Map<FactId, AgenticMemoryContextText>();\n\tif (!Array.isArray(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input must be an array\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-texts-input\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: texts input length could not be read\",\n\t\t\tvalue,\n\t\t});\n\t\treturn out;\n\t}\n\tfor (let i = 0; i < length; i += 1) {\n\t\ttry {\n\t\t\tconst raw = value[i];\n\t\t\tconst result = validateContextText(raw, i);\n\t\t\tif (result.error !== undefined) {\n\t\t\t\terrors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.text === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"invalid-text\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [\"text validation returned no fact\"],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (out.has(result.text.fragmentId)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-text-fragment-id\",\n\t\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: duplicate text fragment id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tfragmentId: result.text.fragmentId,\n\t\t\t\t\tvalue: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate text fragment id '${result.text.fragmentId}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.set(result.text.fragmentId, result.text);\n\t\t} catch (error) {\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: `agenticMemoryContextPackingBundle: text access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tvalidationErrors: [\"text access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\nfunction validateContextText(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly text?: AgenticMemoryContextText;\n\treadonly error?: Omit<AgenticMemoryContextPackingError, \"cursor\">;\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact must be an object\",\n\t\t\t\tindex,\n\t\t\t\tvalue,\n\t\t\t},\n\t\t};\n\t}\n\tconst errors: string[] = [];\n\tif (!isNonEmptyString(value.fragmentId)) errors.push(\"fragmentId must be a non-empty string\");\n\tif (typeof value.text !== \"string\") errors.push(\"text must be a string\");\n\tif (\n\t\tvalue.cost !== undefined &&\n\t\t(typeof value.cost !== \"number\" || !Number.isFinite(value.cost) || value.cost < 0)\n\t) {\n\t\terrors.push(\"cost must be a finite number >= 0\");\n\t}\n\tif (value.metadata !== undefined) {\n\t\ttry {\n\t\t\tif (!isPlainRecord(value.metadata)) {\n\t\t\t\tthrow new TypeError(\"metadata must be a plain object when present\");\n\t\t\t}\n\t\t\tassertStrictJsonValue(value.metadata, \"metadata\");\n\t\t} catch (error) {\n\t\t\terrors.push(errorMessage(error));\n\t\t}\n\t}\n\tif (errors.length > 0) {\n\t\treturn {\n\t\t\terror: {\n\t\t\t\tcode: \"invalid-text\",\n\t\t\t\tmessage: \"agenticMemoryContextPackingBundle: text fact is invalid\",\n\t\t\t\tindex,\n\t\t\t\tfragmentId: typeof value.fragmentId === \"string\" ? value.fragmentId : undefined,\n\t\t\t\tvalue,\n\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\ttext: Object.freeze({\n\t\t\tfragmentId: value.fragmentId as string,\n\t\t\ttext: value.text as string,\n\t\t\t...(value.cost === undefined ? {} : { cost: value.cost as number }),\n\t\t\t...(value.metadata === undefined\n\t\t\t\t? {}\n\t\t\t\t: { metadata: Object.freeze({ ...(value.metadata as Record<string, StrictJsonValue>) }) }),\n\t\t}),\n\t};\n}\n\nfunction validatePackingPolicy(\n\tvalue: unknown,\n\terrors: Omit<AgenticMemoryContextPackingError, \"cursor\">[],\n): AgenticMemoryContextPackingPolicy | undefined {\n\tif (!isPlainRecord(value)) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy must be an object\",\n\t\t\tvalue,\n\t\t});\n\t\treturn undefined;\n\t}\n\tconst validation: string[] = [];\n\tlet maxEntries: unknown;\n\tlet maxChars: unknown;\n\tlet maxCost: unknown;\n\tlet includeMetadata: unknown;\n\ttry {\n\t\tmaxEntries = value.maxEntries;\n\t\tmaxChars = value.maxChars;\n\t\tmaxCost = value.maxCost;\n\t\tincludeMetadata = value.includeMetadata;\n\t} catch (error) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: `agenticMemoryContextPackingBundle: policy access failed: ${errorMessage(error)}`,\n\t\t\tvalue,\n\t\t\tvalidationErrors: [\"policy access failed\"],\n\t\t});\n\t\treturn undefined;\n\t}\n\tif (\n\t\tmaxEntries !== undefined &&\n\t\t(typeof maxEntries !== \"number\" || !Number.isSafeInteger(maxEntries) || maxEntries < 0)\n\t) {\n\t\tvalidation.push(\"maxEntries must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxChars !== undefined &&\n\t\t(typeof maxChars !== \"number\" || !Number.isSafeInteger(maxChars) || maxChars < 0)\n\t) {\n\t\tvalidation.push(\"maxChars must be a safe integer >= 0\");\n\t}\n\tif (\n\t\tmaxCost !== undefined &&\n\t\t(typeof maxCost !== \"number\" || !Number.isFinite(maxCost) || maxCost < 0)\n\t) {\n\t\tvalidation.push(\"maxCost must be a finite number >= 0\");\n\t}\n\tif (includeMetadata !== undefined && typeof includeMetadata !== \"boolean\") {\n\t\tvalidation.push(\"includeMetadata must be a boolean when present\");\n\t}\n\tif (validation.length > 0) {\n\t\terrors.push({\n\t\t\tcode: \"invalid-policy\",\n\t\t\tmessage: \"agenticMemoryContextPackingBundle: policy is invalid\",\n\t\t\tvalue,\n\t\t\tvalidationErrors: Object.freeze(validation),\n\t\t});\n\t\treturn undefined;\n\t}\n\treturn Object.freeze({\n\t\t...(maxEntries === undefined ? {} : { maxEntries: maxEntries as number }),\n\t\t...(maxChars === undefined ? {} : { maxChars: maxChars as number }),\n\t\t...(maxCost === undefined ? {} : { maxCost: maxCost as number }),\n\t\t...(includeMetadata === undefined ? {} : { includeMetadata: includeMetadata as boolean }),\n\t});\n}\n","import { type Codec, strictJsonCodec } from \"../json/codec.js\";\nimport type { MemoryFragment } from \"../patterns/semantic-memory.js\";\nimport {\n\tassertAgenticMemoryRecordCodecShape,\n\tassertArtifactKindValue,\n\tassertConfidence,\n\tassertExactKeys,\n\tassertFiniteNumberArray,\n\tassertKindValue,\n\tassertNonEmptyString,\n\tassertPersistenceLevelValue,\n\tassertScopeFrame,\n\tassertStrictJsonValue,\n\tassertString,\n\tassertStringArray,\n\tdecimalBigIntString,\n\tisPlainRecord,\n\tparseDecimalBigInt,\n\tvalidateAndSnapshotRecord,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryFragmentFrame,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRecordFrame,\n\tStrictJsonValue,\n} from \"./agentic-memory-types.js\";\n\nexport const AGENTIC_MEMORY_RECORD_FRAME_FORMAT = \"graphrefly.agenticMemoryRecord\";\nexport const AGENTIC_MEMORY_RECORD_FRAME_VERSION = 1;\n\nexport function agenticMemoryRecordFrame<TJson extends StrictJsonValue>(\n\trecord: AgenticMemoryRecord<TJson>,\n): AgenticMemoryRecordFrame<TJson> {\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: invalid record: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\tassertAgenticMemoryRecordCodecShape(record);\n\tassertStrictJsonValue(result.record.fragment.payload, \"record.fragment.payload\");\n\treturn Object.freeze({\n\t\tformat: AGENTIC_MEMORY_RECORD_FRAME_FORMAT,\n\t\tversion: AGENTIC_MEMORY_RECORD_FRAME_VERSION,\n\t\trecord: Object.freeze({\n\t\t\tid: result.record.id,\n\t\t\tkind: result.record.kind,\n\t\t\tpersistenceLevel: result.record.persistenceLevel,\n\t\t\tartifactKind: result.record.artifactKind,\n\t\t\t...(result.record.scope === undefined ? {} : { scope: result.record.scope }),\n\t\t\tfragment: fragmentFrame(result.record.fragment as MemoryFragment<TJson>),\n\t\t}),\n\t});\n}\n\n/** Assert and snapshot a decoded D166 record frame. Unknown fields fail honestly. */\nexport function assertAgenticMemoryRecordFrame<TJson extends StrictJsonValue = StrictJsonValue>(\n\tvalue: unknown,\n): AgenticMemoryRecordFrame<TJson> {\n\tif (!isPlainRecord(value))\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: frame must be an object\");\n\tassertStrictJsonValue(value, \"agenticMemoryRecordFrame\");\n\tassertExactKeys(value, [\"format\", \"record\", \"version\"], \"agenticMemoryRecordFrame\");\n\tif (value.format !== AGENTIC_MEMORY_RECORD_FRAME_FORMAT) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid format\");\n\t}\n\tif (value.version !== AGENTIC_MEMORY_RECORD_FRAME_VERSION) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: invalid version\");\n\t}\n\tconst rawRecord = value.record;\n\tif (!isPlainRecord(rawRecord)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: record must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawRecord,\n\t\trawRecord.scope === undefined\n\t\t\t? [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\"]\n\t\t\t: [\"artifactKind\", \"fragment\", \"id\", \"kind\", \"persistenceLevel\", \"scope\"],\n\t\t\"agenticMemoryRecordFrame.record\",\n\t);\n\tconst rawFragment = rawRecord.fragment;\n\tif (!isPlainRecord(rawFragment)) {\n\t\tthrow new TypeError(\"agenticMemoryRecordFrame: fragment must be an object\");\n\t}\n\tassertExactKeys(\n\t\trawFragment,\n\t\t[\n\t\t\t\"id\",\n\t\t\t\"payload\",\n\t\t\t\"tNs\",\n\t\t\t...(rawFragment.validFrom === undefined ? [] : [\"validFrom\"]),\n\t\t\t...(rawFragment.validTo === undefined ? [] : [\"validTo\"]),\n\t\t\t\"confidence\",\n\t\t\t\"tags\",\n\t\t\t\"sources\",\n\t\t\t...(rawFragment.embedding === undefined ? [] : [\"embedding\"]),\n\t\t\t...(rawFragment.parentFragmentId === undefined ? [] : [\"parentFragmentId\"]),\n\t\t\t...(rawFragment.provenance === undefined ? [] : [\"provenance\"]),\n\t\t],\n\t\t\"agenticMemoryRecordFrame.record.fragment\",\n\t);\n\tif (rawRecord.scope !== undefined) assertScopeFrame(rawRecord.scope);\n\tconst frame = value as unknown as AgenticMemoryRecordFrame<TJson>;\n\tconst decoded = recordFromFrame(frame);\n\tconst roundtrip = agenticMemoryRecordFrame(decoded);\n\treturn roundtrip as AgenticMemoryRecordFrame<TJson>;\n}\n\n/** Strict canonical JSON codec for D166 AgenticMemoryRecordFrame values. */\nexport function agenticMemoryRecordFrameCodec<\n\tTJson extends StrictJsonValue = StrictJsonValue,\n>(): Codec<AgenticMemoryRecordFrame<TJson>> {\n\treturn {\n\t\tencode(value: AgenticMemoryRecordFrame<TJson>): Uint8Array {\n\t\t\treturn strictJsonCodec.encode(assertAgenticMemoryRecordFrame<TJson>(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecordFrame<TJson> {\n\t\t\treturn assertAgenticMemoryRecordFrame<TJson>(strictJsonCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/** Strict canonical JSON codec that persists records and decodes bigint fields back to bigint. */\nexport function agenticMemoryRecordCodec<TJson extends StrictJsonValue = StrictJsonValue>(): Codec<\n\tAgenticMemoryRecord<TJson>\n> {\n\tconst frameCodec = agenticMemoryRecordFrameCodec<TJson>();\n\treturn {\n\t\tencode(value: AgenticMemoryRecord<TJson>): Uint8Array {\n\t\t\treturn frameCodec.encode(agenticMemoryRecordFrame(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): AgenticMemoryRecord<TJson> {\n\t\t\treturn recordFromFrame(frameCodec.decode(bytes));\n\t\t},\n\t};\n}\n\n/**\n * D167 solution-level retention command projection.\n *\n * Archive/restore/setPersistenceLevel are derived views over current records;\n * requestConsolidation emits request facts only.\n */\n\nfunction fragmentFrame<TJson extends StrictJsonValue>(\n\tfragment: MemoryFragment<TJson>,\n): AgenticMemoryFragmentFrame<TJson> {\n\treturn Object.freeze({\n\t\tid: fragment.id,\n\t\tpayload: fragment.payload,\n\t\ttNs: decimalBigIntString(fragment.tNs, \"fragment.tNs\"),\n\t\t...(fragment.validFrom === undefined\n\t\t\t? {}\n\t\t\t: { validFrom: decimalBigIntString(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t...(fragment.validTo === undefined\n\t\t\t? {}\n\t\t\t: { validTo: decimalBigIntString(fragment.validTo, \"fragment.validTo\") }),\n\t\tconfidence: fragment.confidence,\n\t\ttags: Object.freeze([...fragment.tags]),\n\t\tsources: Object.freeze([...fragment.sources]),\n\t\t...(fragment.embedding === undefined\n\t\t\t? {}\n\t\t\t: { embedding: Object.freeze([...fragment.embedding]) }),\n\t\t...(fragment.parentFragmentId === undefined\n\t\t\t? {}\n\t\t\t: { parentFragmentId: fragment.parentFragmentId }),\n\t\t...(fragment.provenance === undefined ? {} : { provenance: fragment.provenance }),\n\t});\n}\n\nfunction recordFromFrame<TJson extends StrictJsonValue>(\n\tframe: AgenticMemoryRecordFrame<TJson>,\n): AgenticMemoryRecord<TJson> {\n\tconst fragment = frame.record.fragment;\n\tconst record: AgenticMemoryRecord<TJson> = {\n\t\tid: assertNonEmptyString(frame.record.id, \"record.id\"),\n\t\tkind: assertKindValue(frame.record.kind),\n\t\tpersistenceLevel: assertPersistenceLevelValue(frame.record.persistenceLevel),\n\t\tartifactKind: assertArtifactKindValue(frame.record.artifactKind),\n\t\t...(frame.record.scope === undefined ? {} : { scope: assertScopeFrame(frame.record.scope) }),\n\t\tfragment: {\n\t\t\tid: assertNonEmptyString(fragment.id, \"fragment.id\"),\n\t\t\tpayload: assertStrictJsonValue(fragment.payload, \"fragment.payload\") as TJson,\n\t\t\ttNs: parseDecimalBigInt(fragment.tNs, \"fragment.tNs\"),\n\t\t\t...(fragment.validFrom === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validFrom: parseDecimalBigInt(fragment.validFrom, \"fragment.validFrom\") }),\n\t\t\t...(fragment.validTo === undefined\n\t\t\t\t? {}\n\t\t\t\t: { validTo: parseDecimalBigInt(fragment.validTo, \"fragment.validTo\") }),\n\t\t\tconfidence: assertConfidence(fragment.confidence, \"fragment.confidence\"),\n\t\t\ttags: assertStringArray(fragment.tags, \"fragment.tags\"),\n\t\t\tsources: assertStringArray(fragment.sources, \"fragment.sources\"),\n\t\t\t...(fragment.embedding === undefined\n\t\t\t\t? {}\n\t\t\t\t: { embedding: assertFiniteNumberArray(fragment.embedding, \"fragment.embedding\") }),\n\t\t\t...(fragment.parentFragmentId === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparentFragmentId: assertNonEmptyString(fragment.parentFragmentId, \"parentFragmentId\"),\n\t\t\t\t\t}),\n\t\t\t...(fragment.provenance === undefined\n\t\t\t\t? {}\n\t\t\t\t: { provenance: assertString(fragment.provenance, \"provenance\") }),\n\t\t},\n\t};\n\tconst result = validateAndSnapshotRecord<TJson>(record, 0);\n\tif (result.errors.length > 0 || result.record === undefined) {\n\t\tthrow new TypeError(\n\t\t\t`agenticMemoryRecordFrame: decoded record is invalid: ${result.errors\n\t\t\t\t.flatMap((error) => error.validationErrors ?? [error.message])\n\t\t\t\t.join(\"; \")}`,\n\t\t);\n\t}\n\treturn result.record;\n}\n","import { depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type {\n\tFactId,\n\tKnowledgeAssertion,\n\tKnowledgeAssertionObject,\n\tKnowledgeAssertionSubject,\n} from \"../patterns/semantic-memory.js\";\nimport { solutionProjection } from \"./agentic-memory-projection.js\";\nimport {\n\tagenticStatusState,\n\tassertStrictJsonValue,\n\terrorMessage,\n\tfreezeError,\n\tisDenseArrayOf,\n\tisNonEmptyString,\n\tisPlainRecord,\n\tsafeArrayLength,\n\tvalidateAndProjectRecords,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryError,\n\tAgenticMemoryKgAssertionDraft,\n\tAgenticMemoryKgProjectionBundle,\n\tAgenticMemoryKgProjectionBundleOptions,\n\tAgenticMemoryKgProjectionCursor,\n\tAgenticMemoryKgProjectionError,\n\tAgenticMemoryKgProjectionSnapshot,\n\tAgenticMemoryKgProjectionStatus,\n\tAgenticMemoryRecord,\n\tStrictJsonValue,\n} from \"./agentic-memory-types.js\";\n\nexport function agenticMemoryKgProjectionBundle(\n\tgraph: Graph,\n\topts: AgenticMemoryKgProjectionBundleOptions,\n): AgenticMemoryKgProjectionBundle {\n\tconst name = opts.name ?? \"agenticMemoryKgProjection\";\n\tconst projection = graph.node<AgenticMemoryKgProjectionSnapshot>(\n\t\t[opts.records, opts.drafts],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords(depLatest(ctx, 0));\n\t\t\tconst draftProjection = validateAndProjectKgDrafts(\n\t\t\t\tdepLatest(ctx, 1),\n\t\t\t\trecordProjection.records,\n\t\t\t);\n\t\t\tconst cursor: AgenticMemoryKgProjectionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidDrafts: draftProjection.assertions.length,\n\t\t\t\tinvalidDrafts: draftProjection.invalidDrafts,\n\t\t\t\tprojectedAssertions: draftProjection.assertions.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(kgErrorFromRecordError), ...draftProjection.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryKgProjectionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, draftProjection.assertions.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tassertions: Object.freeze(draftProjection.assertions),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryKgProjection\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, drafts: opts.drafts },\n\t\tprojection,\n\t\tassertions: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/assertions`,\n\t\t\t\"agenticMemoryKgAssertions\",\n\t\t\t(fact) => fact.assertions,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryKgStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryKgErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryKgCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/** Build a D166 strict-JSON frame from an in-memory AgenticMemoryRecord. */\n\nfunction validateAndProjectKgDrafts(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord[],\n): {\n\treadonly assertions: KnowledgeAssertion[];\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n\treadonly invalidDrafts: number;\n} {\n\tconst assertions: KnowledgeAssertion[] = [];\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tlet invalidDrafts = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input must be an array\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tassertions,\n\t\t\tinvalidDrafts: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-drafts-input\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: drafts input length could not be read\",\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst recordById = new Map(records.map((record) => [record.id, record]));\n\tconst fragmentToRecord = new Map(records.map((record) => [record.fragment.id, record.id]));\n\tconst seenAssertions = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateKgDraft(raw, i);\n\t\t\tif (result.errors.length > 0 || result.draft === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst draft = result.draft;\n\t\t\tif (seenAssertions.has(draft.id)) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-assertion-id\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: duplicate assertion id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate assertion id '${draft.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst record = recordById.get(draft.recordId);\n\t\t\tif (record === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing record\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`record '${draft.recordId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst owner = fragmentToRecord.get(draft.fragmentId);\n\t\t\tif (owner === undefined) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-fragment-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft references a missing fragment\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [`fragment '${draft.fragmentId}' is not projected`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (owner !== draft.recordId || record.fragment.id !== draft.fragmentId) {\n\t\t\t\tinvalidDrafts += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"fragment-record-mismatch\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft record and fragment refs disagree\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tassertionId: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tdraft: raw,\n\t\t\t\t\tvalidationErrors: [\n\t\t\t\t\t\t`fragment '${draft.fragmentId}' belongs to record '${owner}', not '${draft.recordId}'`,\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenAssertions.add(draft.id);\n\t\t\tassertions.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: draft.id,\n\t\t\t\t\trecordId: draft.recordId,\n\t\t\t\t\tfragmentId: draft.fragmentId,\n\t\t\t\t\tsubject: draft.subject,\n\t\t\t\t\tpredicate: draft.predicate,\n\t\t\t\t\tobject: draft.object,\n\t\t\t\t\t...(draft.confidence === undefined ? {} : { confidence: draft.confidence }),\n\t\t\t\t\tsources: Object.freeze(draft.sources ?? [draft.fragmentId]),\n\t\t\t\t\t...(draft.provenance === undefined ? {} : { provenance: draft.provenance }),\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tinvalidDrafts += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\tmessage: `agenticMemoryKgProjectionBundle: draft access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tdraft: raw,\n\t\t\t\tvalidationErrors: [\"draft access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\treturn { assertions, errors, invalidDrafts };\n}\n\nfunction validateKgDraft(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly draft?: AgenticMemoryKgAssertionDraft;\n\treadonly errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[];\n} {\n\tconst errors: Omit<AgenticMemoryKgProjectionError, \"cursor\">[] = [];\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-draft\",\n\t\t\t\t\tmessage: \"agenticMemoryKgProjectionBundle: draft must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tdraft: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst raw = value as Partial<AgenticMemoryKgAssertionDraft>;\n\tconst id = typeof raw.id === \"string\" && raw.id.length > 0 ? raw.id : undefined;\n\tconst recordId =\n\t\ttypeof raw.recordId === \"string\" && raw.recordId.length > 0 ? raw.recordId : undefined;\n\tconst fragmentId =\n\t\ttypeof raw.fragmentId === \"string\" && raw.fragmentId.length > 0 ? raw.fragmentId : undefined;\n\tconst subject = validateAssertionSubject(raw.subject);\n\tconst object = validateAssertionObject(raw.object);\n\tconst shapeErrors: string[] = [];\n\tif (id === undefined) shapeErrors.push(\"draft.id must be a non-empty string\");\n\tif (recordId === undefined) {\n\t\tshapeErrors.push(\"draft.recordId must be a non-empty string\");\n\t}\n\tif (fragmentId === undefined) {\n\t\tshapeErrors.push(\"draft.fragmentId must be a non-empty string\");\n\t}\n\tshapeErrors.push(...subject.errors);\n\tif (typeof raw.predicate !== \"string\" || raw.predicate.length === 0) {\n\t\tshapeErrors.push(\"draft.predicate must be a non-empty string\");\n\t}\n\tshapeErrors.push(...object.errors);\n\tif (\n\t\traw.confidence !== undefined &&\n\t\t(!Number.isFinite(raw.confidence) || raw.confidence < 0 || raw.confidence > 1)\n\t) {\n\t\tshapeErrors.push(\"draft.confidence must be a finite number in [0, 1]\");\n\t}\n\tif (raw.sources !== undefined && !isDenseArrayOf(raw.sources, isNonEmptyString)) {\n\t\tshapeErrors.push(\"draft.sources must be a readonly string array\");\n\t}\n\tif (raw.provenance !== undefined && typeof raw.provenance !== \"string\") {\n\t\tshapeErrors.push(\"draft.provenance must be a string when present\");\n\t}\n\tif (shapeErrors.length > 0) errors.push(kgShapeError(index, value, ...shapeErrors));\n\tif (errors.length > 0 || id === undefined || recordId === undefined || fragmentId === undefined) {\n\t\treturn { errors };\n\t}\n\treturn {\n\t\tdraft: Object.freeze({\n\t\t\tid,\n\t\t\trecordId,\n\t\t\tfragmentId,\n\t\t\tsubject: subject.subject as KnowledgeAssertionSubject,\n\t\t\tpredicate: raw.predicate as string,\n\t\t\tobject: object.object as KnowledgeAssertionObject,\n\t\t\t...(raw.confidence === undefined ? {} : { confidence: raw.confidence }),\n\t\t\t...(raw.sources === undefined ? {} : { sources: Object.freeze([...raw.sources]) }),\n\t\t\t...(raw.provenance === undefined ? {} : { provenance: raw.provenance }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionSubject(value: unknown): {\n\treadonly subject?: KnowledgeAssertionSubject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"subject must be an object\"] };\n\tconst id = value.id;\n\tconst type = value.type;\n\tconst errors: string[] = [];\n\tif (typeof id !== \"string\" || id.length === 0) errors.push(\"subject.id must be non-empty\");\n\tif (type !== undefined && (typeof type !== \"string\" || type.length === 0)) {\n\t\terrors.push(\"subject.type must be a non-empty string when present\");\n\t}\n\tif (errors.length > 0) return { errors };\n\treturn {\n\t\tsubject: Object.freeze({\n\t\t\tid: id as string,\n\t\t\t...(type === undefined ? {} : { type: type as string }),\n\t\t}),\n\t\terrors,\n\t};\n}\n\nfunction validateAssertionObject(value: unknown): {\n\treadonly object?: KnowledgeAssertionObject;\n\treadonly errors: readonly string[];\n} {\n\tif (!isPlainRecord(value)) return { errors: [\"object must be an object\"] };\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (kind === \"entity\") {\n\t\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\t\terrors.push(\"object.id must be non-empty for entity objects\");\n\t\t}\n\t\tif (value.type !== undefined && (typeof value.type !== \"string\" || value.type.length === 0)) {\n\t\t\terrors.push(\"object.type must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"value\")) errors.push(\"entity object must not include value\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"entity\",\n\t\t\t\tid: value.id as string,\n\t\t\t\t...(value.type === undefined ? {} : { type: value.type as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\tif (kind === \"value\") {\n\t\tif (!Object.hasOwn(value, \"value\")) errors.push(\"value object must include value\");\n\t\telse {\n\t\t\ttry {\n\t\t\t\tassertStrictJsonValue(value.value, \"object.value\");\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(errorMessage(error));\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tvalue.valueType !== undefined &&\n\t\t\t(typeof value.valueType !== \"string\" || value.valueType.length === 0)\n\t\t) {\n\t\t\terrors.push(\"object.valueType must be a non-empty string when present\");\n\t\t}\n\t\tif (Object.hasOwn(value, \"id\")) errors.push(\"value object must not include id\");\n\t\tif (errors.length > 0) return { errors };\n\t\treturn {\n\t\t\tobject: Object.freeze({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue: value.value as StrictJsonValue,\n\t\t\t\t...(value.valueType === undefined ? {} : { valueType: value.valueType as string }),\n\t\t\t}),\n\t\t\terrors,\n\t\t};\n\t}\n\treturn { errors: [\"object.kind must be entity or value\"] };\n}\n\nfunction kgShapeError(\n\tindex: number,\n\tdraft: unknown,\n\t...validationErrors: readonly string[]\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\tcode: \"invalid-assertion-shape\",\n\t\tmessage: \"agenticMemoryKgProjectionBundle: draft assertion shape is invalid\",\n\t\tindex,\n\t\tdraft,\n\t\tvalidationErrors: Object.freeze([...validationErrors]),\n\t};\n}\n\nfunction kgErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryKgProjectionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n","import { depLatest } from \"../ctx/types.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { FactId } from \"../patterns/semantic-memory.js\";\nimport { solutionProjection } from \"./agentic-memory-projection.js\";\nimport {\n\tagenticStatusState,\n\terrorMessage,\n\tfreezeError,\n\tisAgenticMemoryPersistenceLevel,\n\tisDenseArrayOf,\n\tisNonEmptyString,\n\tisPlainRecord,\n\tsafeArrayLength,\n\tvalidateAndProjectRecords,\n} from \"./agentic-memory-shared.js\";\nimport type {\n\tAgenticMemoryConsolidationRequest,\n\tAgenticMemoryError,\n\tAgenticMemoryPersistenceLevel,\n\tAgenticMemoryRecord,\n\tAgenticMemoryRetentionBundle,\n\tAgenticMemoryRetentionBundleOptions,\n\tAgenticMemoryRetentionCommand,\n\tAgenticMemoryRetentionCursor,\n\tAgenticMemoryRetentionError,\n\tAgenticMemoryRetentionSnapshot,\n\tAgenticMemoryRetentionStatus,\n} from \"./agentic-memory-types.js\";\n\nexport function agenticMemoryRetentionBundle<T = unknown>(\n\tgraph: Graph,\n\topts: AgenticMemoryRetentionBundleOptions<T>,\n): AgenticMemoryRetentionBundle<T> {\n\tconst name = opts.name ?? \"agenticMemoryRetention\";\n\tconst projection = graph.node<AgenticMemoryRetentionSnapshot<T>>(\n\t\t[opts.records, opts.commands],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<{ evaluation: number }>() ??\n\t\t\t\t({ evaluation: 0 } satisfies { evaluation: number });\n\t\t\tstate.evaluation += 1;\n\t\t\tconst recordProjection = validateAndProjectRecords<T>(depLatest(ctx, 0));\n\t\t\tconst retention = projectRetention<T>(depLatest(ctx, 1), recordProjection.records);\n\t\t\tconst cursor: AgenticMemoryRetentionCursor = Object.freeze({\n\t\t\t\tevaluation: state.evaluation,\n\t\t\t\tvalidRecords: recordProjection.records.length,\n\t\t\t\tvalidCommands: retention.validCommands,\n\t\t\t\tinvalidCommands: retention.invalidCommands,\n\t\t\t\tactiveRecords: retention.activeRecords.length,\n\t\t\t\tarchivedRecords: retention.archivedRecords.length,\n\t\t\t\tconsolidationRequests: retention.consolidationRequests.length,\n\t\t\t});\n\t\t\tconst errors = Object.freeze(\n\t\t\t\t[...recordProjection.errors.map(retentionErrorFromRecordError), ...retention.errors].map(\n\t\t\t\t\t(error) => freezeError({ ...error, cursor }),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst status: AgenticMemoryRetentionStatus = Object.freeze({\n\t\t\t\tstate: agenticStatusState(errors.length, recordProjection.records.length),\n\t\t\t\tcursor,\n\t\t\t});\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tactiveRecords: Object.freeze(retention.activeRecords),\n\t\t\t\t\t\tarchivedRecords: Object.freeze(retention.archivedRecords),\n\t\t\t\t\t\tconsolidationRequests: Object.freeze(retention.consolidationRequests),\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\terrors,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/projection`,\n\t\t\tfactory: \"agenticMemoryRetention\",\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\treturn {\n\t\tinput: { records: opts.records, commands: opts.commands },\n\t\tprojection,\n\t\tactiveRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/activeRecords`,\n\t\t\t\"agenticMemoryRetentionActiveRecords\",\n\t\t\t(fact) => fact.activeRecords,\n\t\t),\n\t\tarchivedRecords: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/archivedRecords`,\n\t\t\t\"agenticMemoryRetentionArchivedRecords\",\n\t\t\t(fact) => fact.archivedRecords,\n\t\t),\n\t\tconsolidationRequests: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/consolidationRequests`,\n\t\t\t\"agenticMemoryRetentionConsolidationRequests\",\n\t\t\t(fact) => fact.consolidationRequests,\n\t\t),\n\t\tstatus: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/status`,\n\t\t\t\"agenticMemoryRetentionStatus\",\n\t\t\t(fact) => fact.status,\n\t\t),\n\t\terrors: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/errors`,\n\t\t\t\"agenticMemoryRetentionErrors\",\n\t\t\t(fact) => fact.errors,\n\t\t),\n\t\tcursor: solutionProjection(\n\t\t\tgraph,\n\t\t\tprojection,\n\t\t\t`${name}/cursor`,\n\t\t\t\"agenticMemoryRetentionCursor\",\n\t\t\t(fact) => fact.cursor,\n\t\t),\n\t};\n}\n\n/**\n * D171 consolidation outcome projection.\n *\n * The bundle does not execute consolidation. External adapters may publish\n * outcome facts, and this projection turns them into visible result/proposal\n * facts for downstream record-creation policy.\n */\n\nfunction projectRetention<T>(\n\tvalue: unknown,\n\trecords: readonly AgenticMemoryRecord<T>[],\n): {\n\treadonly activeRecords: AgenticMemoryRecord<T>[];\n\treadonly archivedRecords: AgenticMemoryRecord<T>[];\n\treadonly consolidationRequests: AgenticMemoryConsolidationRequest[];\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n\treadonly validCommands: number;\n\treadonly invalidCommands: number;\n} {\n\tconst byId = new Map(records.map((record) => [record.id, record]));\n\tconst view = new Map(records.map((record) => [record.id, record]));\n\tconst requests: AgenticMemoryConsolidationRequest[] = [];\n\tconst errors: Omit<AgenticMemoryRetentionError, \"cursor\">[] = [];\n\tlet validCommands = 0;\n\tlet invalidCommands = 0;\n\tif (!Array.isArray(value)) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input must be an array\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst length = safeArrayLength(value);\n\tif (length === undefined) {\n\t\treturn {\n\t\t\tactiveRecords: records.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\t\tarchivedRecords: records.filter((record) => record.persistenceLevel === \"archived\"),\n\t\t\tconsolidationRequests: requests,\n\t\t\tvalidCommands,\n\t\t\tinvalidCommands: 1,\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-commands-input\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: commands input length could not be read\",\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst seenCommands = new Set<FactId>();\n\tfor (let i = 0; i < length; i += 1) {\n\t\tlet raw: unknown;\n\t\ttry {\n\t\t\traw = value[i];\n\t\t\tconst result = validateRetentionCommand(raw, i);\n\t\t\tif (result.errors.length > 0 || result.command === undefined) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push(...result.errors);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst command = result.command;\n\t\t\tif (seenCommands.has(command.id)) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"duplicate-command-id\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: duplicate command id\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: [`duplicate command id '${command.id}'`],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst missing = retentionMissingRecords(command, byId);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tinvalidCommands += 1;\n\t\t\t\terrors.push({\n\t\t\t\t\tcode: \"missing-record-ref\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command references missing records\",\n\t\t\t\t\tindex: i,\n\t\t\t\t\tcommandId: command.id,\n\t\t\t\t\trecordId: \"recordId\" in command ? command.recordId : undefined,\n\t\t\t\t\trecordIds: Object.freeze(missing),\n\t\t\t\t\tcommand: raw,\n\t\t\t\t\tvalidationErrors: Object.freeze(missing.map((id) => `record '${id}' is not projected`)),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenCommands.add(command.id);\n\t\t\tvalidCommands += 1;\n\t\t\tapplyRetentionCommand(command, byId, view, requests);\n\t\t} catch (error) {\n\t\t\tinvalidCommands += 1;\n\t\t\terrors.push({\n\t\t\t\tcode: \"invalid-command\",\n\t\t\t\tmessage: `agenticMemoryRetentionBundle: command access failed: ${errorMessage(error)}`,\n\t\t\t\tindex: i,\n\t\t\t\tcommand: raw,\n\t\t\t\tvalidationErrors: [\"command access failed\"],\n\t\t\t});\n\t\t}\n\t}\n\tconst projected = records.map((record) => view.get(record.id) ?? record);\n\treturn {\n\t\tactiveRecords: projected.filter((record) => record.persistenceLevel !== \"archived\"),\n\t\tarchivedRecords: projected.filter((record) => record.persistenceLevel === \"archived\"),\n\t\tconsolidationRequests: requests,\n\t\terrors,\n\t\tvalidCommands,\n\t\tinvalidCommands,\n\t};\n}\n\nfunction validateRetentionCommand(\n\tvalue: unknown,\n\tindex: number,\n): {\n\treadonly command?: AgenticMemoryRetentionCommand;\n\treadonly errors: Omit<AgenticMemoryRetentionError, \"cursor\">[];\n} {\n\tif (!isPlainRecord(value)) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command must be an object\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommand: value,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst id = typeof value.id === \"string\" && value.id.length > 0 ? value.id : undefined;\n\tconst kind = value.kind;\n\tconst errors: string[] = [];\n\tif (id === undefined) errors.push(\"command.id must be a non-empty string\");\n\tif (\n\t\tkind !== \"archive\" &&\n\t\tkind !== \"restore\" &&\n\t\tkind !== \"setPersistenceLevel\" &&\n\t\tkind !== \"requestConsolidation\"\n\t) {\n\t\terrors.push(\"command.kind is invalid\");\n\t}\n\tif (value.reason !== undefined && typeof value.reason !== \"string\") {\n\t\terrors.push(\"command.reason must be a string when present\");\n\t}\n\tif (kind === \"archive\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t} else if (kind === \"restore\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (\n\t\t\tvalue.persistenceLevel !== undefined &&\n\t\t\t(!isAgenticMemoryPersistenceLevel(value.persistenceLevel) ||\n\t\t\t\tvalue.persistenceLevel === \"archived\")\n\t\t) {\n\t\t\terrors.push(\"restore.persistenceLevel must be a non-archived persistence level when present\");\n\t\t}\n\t} else if (kind === \"setPersistenceLevel\") {\n\t\tif (!isNonEmptyString(value.recordId)) errors.push(\"command.recordId must be non-empty\");\n\t\tif (!isAgenticMemoryPersistenceLevel(value.persistenceLevel)) {\n\t\t\terrors.push(\"setPersistenceLevel.persistenceLevel is invalid\");\n\t\t}\n\t} else if (kind === \"requestConsolidation\") {\n\t\tif (!isDenseArrayOf(value.recordIds, isNonEmptyString) || value.recordIds.length === 0) {\n\t\t\terrors.push(\"requestConsolidation.recordIds must be a non-empty string array\");\n\t\t}\n\t\tif (\n\t\t\tvalue.requestId !== undefined &&\n\t\t\t(typeof value.requestId !== \"string\" || value.requestId.length === 0)\n\t\t) {\n\t\t\terrors.push(\"requestConsolidation.requestId must be non-empty when present\");\n\t\t}\n\t}\n\tif (errors.length > 0 || id === undefined) {\n\t\treturn {\n\t\t\terrors: [\n\t\t\t\t{\n\t\t\t\t\tcode: \"invalid-command\",\n\t\t\t\t\tmessage: \"agenticMemoryRetentionBundle: command is invalid\",\n\t\t\t\t\tindex,\n\t\t\t\t\tcommandId: id,\n\t\t\t\t\tcommand: value,\n\t\t\t\t\tvalidationErrors: Object.freeze(errors),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst base = { id, reason: value.reason as string | undefined };\n\tif (kind === \"archive\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"restore\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\t...(value.persistenceLevel === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tpersistenceLevel: value.persistenceLevel as Exclude<\n\t\t\t\t\t\t\t\tAgenticMemoryPersistenceLevel,\n\t\t\t\t\t\t\t\t\"archived\"\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t}),\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\tif (kind === \"setPersistenceLevel\") {\n\t\treturn {\n\t\t\tcommand: Object.freeze({\n\t\t\t\t...base,\n\t\t\t\tkind,\n\t\t\t\trecordId: value.recordId as string,\n\t\t\t\tpersistenceLevel: value.persistenceLevel as AgenticMemoryPersistenceLevel,\n\t\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t\t}),\n\t\t\terrors: [],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: Object.freeze({\n\t\t\t...base,\n\t\t\tkind: \"requestConsolidation\",\n\t\t\trecordIds: Object.freeze([...(value.recordIds as readonly string[])]),\n\t\t\t...(value.requestId === undefined ? {} : { requestId: value.requestId as string }),\n\t\t\t...(base.reason === undefined ? {} : { reason: base.reason }),\n\t\t}),\n\t\terrors: [],\n\t};\n}\n\nfunction retentionMissingRecords(\n\tcommand: AgenticMemoryRetentionCommand,\n\trecords: ReadonlyMap<FactId, AgenticMemoryRecord>,\n): readonly FactId[] {\n\tif (\"recordId\" in command) return records.has(command.recordId) ? [] : [command.recordId];\n\treturn command.recordIds.filter((recordId) => !records.has(recordId));\n}\n\nfunction applyRetentionCommand<T>(\n\tcommand: AgenticMemoryRetentionCommand,\n\tsource: ReadonlyMap<FactId, AgenticMemoryRecord<T>>,\n\tview: Map<FactId, AgenticMemoryRecord<T>>,\n\trequests: AgenticMemoryConsolidationRequest[],\n): void {\n\tif (command.kind === \"requestConsolidation\") {\n\t\trequests.push(\n\t\t\tObject.freeze({\n\t\t\t\tid: command.requestId ?? command.id,\n\t\t\t\tcommandId: command.id,\n\t\t\t\trecordIds: Object.freeze([...command.recordIds]),\n\t\t\t\t...(command.reason === undefined ? {} : { reason: command.reason }),\n\t\t\t}),\n\t\t);\n\t\treturn;\n\t}\n\tconst record = view.get(command.recordId) ?? source.get(command.recordId);\n\tif (record === undefined) return;\n\tconst persistenceLevel =\n\t\tcommand.kind === \"archive\"\n\t\t\t? \"archived\"\n\t\t\t: command.kind === \"restore\"\n\t\t\t\t? (command.persistenceLevel ?? nonArchivedLevel(source.get(command.recordId) ?? record))\n\t\t\t\t: command.persistenceLevel;\n\tview.set(command.recordId, withPersistenceLevel(record, persistenceLevel));\n}\n\nfunction nonArchivedLevel(\n\trecord: AgenticMemoryRecord,\n): Exclude<AgenticMemoryPersistenceLevel, \"archived\"> {\n\treturn record.persistenceLevel === \"archived\" ? \"session\" : record.persistenceLevel;\n}\n\nfunction withPersistenceLevel<T>(\n\trecord: AgenticMemoryRecord<T>,\n\tpersistenceLevel: AgenticMemoryPersistenceLevel,\n): AgenticMemoryRecord<T> {\n\treturn Object.freeze({\n\t\t...record,\n\t\tpersistenceLevel,\n\t});\n}\n\nfunction retentionErrorFromRecordError(\n\terror: Omit<AgenticMemoryError, \"cursor\">,\n): Omit<AgenticMemoryRetentionError, \"cursor\"> {\n\treturn {\n\t\t...error,\n\t\tcode: error.code,\n\t};\n}\n","/**\n * Product-owned capability admission facts (D357).\n *\n * This helper consumes generic BoundaryCapabilityRef data and emits ordinary DATA\n * facts for product admission state. It is not AutoPanel security, not a provider\n * registry, and not protocol ERROR/tier/message semantics.\n */\n\nimport { type Ctx, depBatch } from \"../ctx/types.js\";\nimport type { DataIssue } from \"../data/index.js\";\nimport type { Graph } from \"../graph/graph.js\";\nimport type { BoundaryCapabilityRef, BoundaryRole } from \"../inspection/boundary.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { AgentRuntimeAuditRecord, SourceRef } from \"../orchestration/agent-runtime.js\";\n\nexport type CapabilityAdmissionOutcome = \"allow\" | \"block\" | \"defer\";\nexport type CapabilityAdmissionState = \"allowed\" | \"blocked\" | \"deferred\";\n\nexport interface CapabilityAdmissionProposal {\n\treadonly kind: \"capability-admission-proposal\";\n\treadonly proposalId: string;\n\treadonly subjectId: string;\n\treadonly capability: BoundaryCapabilityRef;\n\treadonly boundaryName?: string;\n\treadonly role?: BoundaryRole;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly proposedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionPolicy {\n\treadonly kind: \"capability-admission-policy\";\n\treadonly policyId: string;\n\treadonly capabilityIds?: readonly string[];\n\treadonly capabilityKinds?: readonly BoundaryCapabilityRef[\"kind\"][];\n\treadonly requiredOnly?: boolean;\n\treadonly allowedOutcomes?: readonly CapabilityAdmissionOutcome[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionDecision {\n\treadonly kind: \"capability-admission-decision\";\n\treadonly decisionId: string;\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly outcome: CapabilityAdmissionOutcome;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly decidedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmission {\n\treadonly kind: \"capability-admission\";\n\treadonly admissionId: string;\n\treadonly proposalId: string;\n\treadonly subjectId: string;\n\treadonly capability: BoundaryCapabilityRef;\n\treadonly state: CapabilityAdmissionState;\n\treadonly decisionId: string;\n\treadonly boundaryName?: string;\n\treadonly role?: BoundaryRole;\n\treadonly policyId?: string;\n\treadonly reason?: string;\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly admittedAtMs?: number;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionStatus {\n\treadonly kind: \"capability-admission-status\";\n\treadonly statusId: string;\n\treadonly state:\n\t\t| \"capability-admission-allowed\"\n\t\t| \"capability-admission-blocked\"\n\t\t| \"capability-admission-deferred\"\n\t\t| \"capability-admission-issue\";\n\treadonly proposalId?: string;\n\treadonly admissionId?: string;\n\treadonly subjectId?: string;\n\treadonly capabilityId?: string;\n\treadonly capabilityKind?: BoundaryCapabilityRef[\"kind\"];\n\treadonly policyId?: string;\n\treadonly issues?: readonly DataIssue[];\n\treadonly sourceRefs?: readonly SourceRef[];\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface CapabilityAdmissionViews {\n\treadonly admissionsByProposal: ReadonlyMap<string, CapabilityAdmission>;\n\treadonly admissionsBySubject: ReadonlyMap<string, readonly CapabilityAdmission[]>;\n\treadonly issues: readonly DataIssue[];\n\treadonly audit: readonly AgentRuntimeAuditRecord[];\n}\n\nexport interface CapabilityAdmissionBundle {\n\treadonly admissions: Node<CapabilityAdmission>;\n\treadonly status: Node<CapabilityAdmissionStatus>;\n\treadonly issues: Node<DataIssue>;\n\treadonly audit: Node<AgentRuntimeAuditRecord>;\n\treadonly views: Node<CapabilityAdmissionViews>;\n}\n\ntype CapabilityAdmissionFact =\n\t| { readonly kind: \"admission\"; readonly admission: CapabilityAdmission }\n\t| { readonly kind: \"status\"; readonly status: CapabilityAdmissionStatus }\n\t| { readonly kind: \"issue\"; readonly issue: DataIssue }\n\t| { readonly kind: \"audit\"; readonly audit: AgentRuntimeAuditRecord };\n\ninterface CapabilityAdmissionStateInternal {\n\tproposals: Map<string, CapabilityAdmissionProposal>;\n\tpolicies: Map<string, CapabilityAdmissionPolicy>;\n\tdecisions: Map<string, CapabilityAdmissionDecision>;\n\tadmissionsById: Map<string, CapabilityAdmission>;\n\tadmissionsByProposal: Map<string, CapabilityAdmission>;\n\tterminalDecisionIds: Set<string>;\n\tissueKeys: Set<string>;\n\tissueSeq: number;\n\tstatusSeq: number;\n\tauditSeq: number;\n}\n\ninterface CapabilityAdmissionViewsState {\n\tadmissionsByProposal: Map<string, CapabilityAdmission>;\n\tadmissionsBySubject: Map<string, CapabilityAdmission[]>;\n\tissues: DataIssue[];\n\taudit: AgentRuntimeAuditRecord[];\n}\n\nexport function capabilityAdmissionProposal(\n\topts: Omit<CapabilityAdmissionProposal, \"kind\">,\n): CapabilityAdmissionProposal {\n\treturn { kind: \"capability-admission-proposal\", ...opts };\n}\n\nexport function capabilityAdmissionProjector(\n\tgraph: Graph,\n\topts: {\n\t\treadonly name?: string;\n\t\treadonly proposals: Node<CapabilityAdmissionProposal>;\n\t\treadonly decisions: Node<CapabilityAdmissionDecision>;\n\t\treadonly admissionPolicies?: readonly Node<CapabilityAdmissionPolicy>[];\n\t\treadonly now?: () => number;\n\t},\n): CapabilityAdmissionBundle {\n\tconst name = opts.name ?? \"capabilityAdmissions\";\n\tconst policyDeps = opts.admissionPolicies ?? [];\n\tconst now = opts.now ?? Date.now;\n\tconst runtime = graph.node<CapabilityAdmissionFact>(\n\t\t[opts.proposals, opts.decisions, ...policyDeps],\n\t\t(ctx) => {\n\t\t\tconst state =\n\t\t\t\tctx.state.get<CapabilityAdmissionStateInternal>() ?? emptyCapabilityAdmissionState();\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst proposal = raw as CapabilityAdmissionProposal;\n\t\t\t\tconst issue = capabilityAdmissionProposalIssue(proposal);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"proposal\", proposalKeyFallback(proposal)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (state.proposals.has(proposal.proposalId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-proposal:${proposal.proposalId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-proposal\",\n\t\t\t\t\t\t\t`CapabilityAdmissionProposal '${proposal.proposalId}' was already seen`,\n\t\t\t\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityProposalRefs(proposal) },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.proposals.set(proposal.proposalId, proposal);\n\t\t\t}\n\t\t\tforEachPolicyDepBatch(ctx, 2, policyDeps.length, (raw) => {\n\t\t\t\tconst policy = raw as CapabilityAdmissionPolicy;\n\t\t\t\tconst issue = capabilityAdmissionPolicyIssue(policy);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"policy\", policyKeyFallback(policy)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (state.policies.has(policy.policyId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-policy:${policy.policyId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-policy\",\n\t\t\t\t\t\t\t`CapabilityAdmissionPolicy '${policy.policyId}' was already seen`,\n\t\t\t\t\t\t\t{ refs: [ref(\"capability-admission-policy\", policy.policyId)] },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstate.policies.set(policy.policyId, policy);\n\t\t\t});\n\t\t\tfor (const raw of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst decision = raw as CapabilityAdmissionDecision;\n\t\t\t\tconst issue = capabilityAdmissionDecisionIssue(decision);\n\t\t\t\tif (issue !== undefined) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tnextMalformedIssueKey(state, \"decision\", decisionKeyFallback(decision)),\n\t\t\t\t\t\tissue,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (state.decisions.has(decision.decisionId)) {\n\t\t\t\t\temitIssue(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t`duplicate-decision:${decision.decisionId}`,\n\t\t\t\t\t\tdataIssue(\n\t\t\t\t\t\t\t\"duplicate-capability-admission-decision\",\n\t\t\t\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' was already seen`,\n\t\t\t\t\t\t\t{ refs: capabilityDecisionRefs(decision) },\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstate.decisions.set(decision.decisionId, decision);\n\t\t\t}\n\t\t\tevaluateCapabilityAdmissions(ctx, state, now());\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/runtime`, factory: \"capabilityAdmissionProjector\", partial: true },\n\t);\n\treturn {\n\t\tadmissions: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/admissions`,\n\t\t\t\"capabilityAdmissions\",\n\t\t\t(fact) => (fact.kind === \"admission\" ? fact.admission : undefined),\n\t\t),\n\t\tstatus: projectRuntimeFact(\n\t\t\tgraph,\n\t\t\truntime,\n\t\t\t`${name}/status`,\n\t\t\t\"capabilityAdmissionStatus\",\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\"capabilityAdmissionIssues\",\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\"capabilityAdmissionAudit\",\n\t\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t\t),\n\t\tviews: capabilityAdmissionViews(graph, runtime, `${name}/views`),\n\t};\n}\n\nfunction evaluateCapabilityAdmissions(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tadmittedAtMs: number,\n): void {\n\tfor (const decision of state.decisions.values()) {\n\t\tif (state.terminalDecisionIds.has(decision.decisionId)) continue;\n\t\tevaluateCapabilityAdmission(ctx, state, decision, admittedAtMs);\n\t}\n}\n\nfunction evaluateCapabilityAdmission(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tdecision: CapabilityAdmissionDecision,\n\tadmittedAtMs: number,\n): void {\n\tconst proposal = state.proposals.get(decision.proposalId);\n\tif (proposal === undefined) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`missing-proposal:${decision.decisionId}:${decision.proposalId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"missing-capability-admission-proposal\",\n\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' references missing proposal '${decision.proposalId}'`,\n\t\t\t\t{ subjectId: decision.proposalId, refs: capabilityDecisionRefs(decision) },\n\t\t\t),\n\t\t);\n\t\treturn;\n\t}\n\tconst policy = capabilityPolicyForDecision(state, decision);\n\tif (typeof policy === \"string\") {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`${policy}:${decision.decisionId}:${decision.policyId ?? \"missing\"}`,\n\t\t\tdataIssue(policy, capabilityPolicyIssueMessage(policy, decision), {\n\t\t\t\tsubjectId: proposal.subjectId,\n\t\t\t\trefs: capabilityDecisionRefs(decision, proposal),\n\t\t\t}),\n\t\t);\n\t\tif (policy === \"stale-capability-admission-policy-ref\")\n\t\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tif (policy !== undefined) {\n\t\tconst policyIssue = validateCapabilityAdmissionPolicy(policy, decision, proposal);\n\t\tif (policyIssue !== undefined) {\n\t\t\temitIssue(\n\t\t\t\tctx,\n\t\t\t\tstate,\n\t\t\t\t`${policyIssue.code}:${decision.decisionId}:${policy.policyId}`,\n\t\t\t\tdataIssue(policyIssue.code, policyIssue.message, {\n\t\t\t\t\tsubjectId: proposal.subjectId,\n\t\t\t\t\trefs: capabilityDecisionRefs(decision, proposal, policy),\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}\n\tif (state.admissionsById.has(decision.admissionId)) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-id:${decision.admissionId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"duplicate-capability-admission\",\n\t\t\t\t`CapabilityAdmission '${decision.admissionId}' was already emitted`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tif (state.admissionsByProposal.has(decision.proposalId)) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`duplicate-admission-proposal:${decision.proposalId}:${decision.decisionId}`,\n\t\t\tdataIssue(\n\t\t\t\t\"duplicate-capability-admission-proposal\",\n\t\t\t\t`CapabilityAdmissionProposal '${decision.proposalId}' already has an admission decision`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tconst admissionState = admissionStateForOutcome(decision.outcome);\n\tif (admissionState === undefined) {\n\t\temitIssue(\n\t\t\tctx,\n\t\t\tstate,\n\t\t\t`unsupported-outcome:${decision.decisionId}:${String(decision.outcome)}`,\n\t\t\tdataIssue(\n\t\t\t\t\"unsupported-capability-admission-outcome\",\n\t\t\t\t`CapabilityAdmissionDecision '${decision.decisionId}' uses unsupported outcome '${String(decision.outcome)}'`,\n\t\t\t\t{ subjectId: proposal.subjectId, refs: capabilityDecisionRefs(decision, proposal, policy) },\n\t\t\t),\n\t\t);\n\t\tstate.terminalDecisionIds.add(decision.decisionId);\n\t\treturn;\n\t}\n\tconst admission: CapabilityAdmission = {\n\t\tkind: \"capability-admission\",\n\t\tadmissionId: decision.admissionId,\n\t\tproposalId: proposal.proposalId,\n\t\tsubjectId: proposal.subjectId,\n\t\tcapability: cloneCapabilityRef(proposal.capability),\n\t\tstate: admissionState,\n\t\tdecisionId: decision.decisionId,\n\t\tboundaryName: proposal.boundaryName,\n\t\trole: proposal.role,\n\t\tpolicyId: decision.policyId,\n\t\treason: decision.reason ?? proposal.reason,\n\t\tsourceRefs: capabilityDecisionRefs(decision, proposal, policy),\n\t\tadmittedAtMs: decision.decidedAtMs ?? admittedAtMs,\n\t\tmetadata: {\n\t\t\t...(proposal.metadata ?? {}),\n\t\t\t...(policy?.metadata ?? {}),\n\t\t\t...(decision.metadata ?? {}),\n\t\t},\n\t};\n\tstate.admissionsById.set(admission.admissionId, admission);\n\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\tstate.terminalDecisionIds.add(decision.decisionId);\n\temitAdmission(ctx, state, admission);\n}\n\nfunction capabilityAdmissionViews(\n\tgraph: Graph,\n\truntime: Node<CapabilityAdmissionFact>,\n\tname: string,\n): Node<CapabilityAdmissionViews> {\n\treturn graph.node<CapabilityAdmissionViews>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tconst state: CapabilityAdmissionViewsState =\n\t\t\t\tctx.state.get<CapabilityAdmissionViewsState>() ?? {\n\t\t\t\t\tadmissionsByProposal: new Map(),\n\t\t\t\t\tadmissionsBySubject: new Map(),\n\t\t\t\t\tissues: [],\n\t\t\t\t\taudit: [],\n\t\t\t\t};\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst fact = raw as CapabilityAdmissionFact;\n\t\t\t\tif (fact.kind === \"admission\") {\n\t\t\t\t\tconst admission = fact.admission;\n\t\t\t\t\tstate.admissionsByProposal.set(admission.proposalId, admission);\n\t\t\t\t\tconst bySubject = state.admissionsBySubject.get(admission.subjectId) ?? [];\n\t\t\t\t\tbySubject.push(admission);\n\t\t\t\t\tstate.admissionsBySubject.set(admission.subjectId, bySubject);\n\t\t\t\t}\n\t\t\t\tif (fact.kind === \"issue\") state.issues.push(fact.issue);\n\t\t\t\tif (fact.kind === \"audit\") state.audit.push(fact.audit);\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t\tctx.down([[\"DATA\", freezeCapabilityAdmissionViews(state)]]);\n\t\t},\n\t\t{ name, factory: \"capabilityAdmissionViews\" },\n\t);\n}\n\nfunction emitAdmission(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tadmission: CapabilityAdmission,\n): void {\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst statusState = capabilityAdmissionStatusState(admission.state);\n\tconst status: CapabilityAdmissionStatus = {\n\t\tkind: \"capability-admission-status\",\n\t\tstatusId: `${admission.subjectId}:${statusState}:${state.statusSeq}`,\n\t\tstate: statusState,\n\t\tproposalId: admission.proposalId,\n\t\tadmissionId: admission.admissionId,\n\t\tsubjectId: admission.subjectId,\n\t\tcapabilityId: admission.capability.id,\n\t\tcapabilityKind: admission.capability.kind,\n\t\tpolicyId: admission.policyId,\n\t\tsourceRefs: admission.sourceRefs,\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `${admission.subjectId}:${statusState}:${state.auditSeq}`,\n\t\tkind: `capability-admission-${admission.state}`,\n\t\tsubjectId: admission.subjectId,\n\t\tsourceRefs: admission.sourceRefs,\n\t\tmetadata: {\n\t\t\tadmissionId: admission.admissionId,\n\t\t\tcapabilityId: admission.capability.id,\n\t\t\tcapabilityKind: admission.capability.kind,\n\t\t\tpolicyId: admission.policyId,\n\t\t\tproposalId: admission.proposalId,\n\t\t},\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"admission\", admission } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies CapabilityAdmissionFact],\n\t]);\n}\n\nfunction emitIssue(\n\tctx: Ctx,\n\tstate: CapabilityAdmissionStateInternal,\n\tkey: string,\n\tissue: DataIssue,\n): void {\n\tif (state.issueKeys.has(key)) return;\n\tstate.issueKeys.add(key);\n\tstate.statusSeq += 1;\n\tstate.auditSeq += 1;\n\tconst status: CapabilityAdmissionStatus = {\n\t\tkind: \"capability-admission-status\",\n\t\tstatusId: `capability-admission-issue:${state.statusSeq}`,\n\t\tstate: \"capability-admission-issue\",\n\t\tsubjectId: issue.subjectId,\n\t\tissues: [issue],\n\t};\n\tconst audit: AgentRuntimeAuditRecord = {\n\t\tid: `capability-admission-issue:${state.auditSeq}`,\n\t\tkind: \"capability-admission-issue\",\n\t\tsubjectId: issue.subjectId,\n\t\tmessage: issue.message,\n\t\tissueCode: issue.code,\n\t};\n\tctx.down([\n\t\t[\"DATA\", { kind: \"issue\", issue } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"status\", status } satisfies CapabilityAdmissionFact],\n\t\t[\"DATA\", { kind: \"audit\", audit } satisfies CapabilityAdmissionFact],\n\t]);\n}\n\nfunction capabilityAdmissionProposalIssue(\n\tproposal: CapabilityAdmissionProposal,\n): DataIssue | undefined {\n\tif (\n\t\tproposal.kind !== \"capability-admission-proposal\" ||\n\t\ttypeof proposal.proposalId !== \"string\" ||\n\t\tproposal.proposalId.length === 0 ||\n\t\ttypeof proposal.subjectId !== \"string\" ||\n\t\tproposal.subjectId.length === 0 ||\n\t\t!isBoundaryCapabilityRef(proposal.capability)\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-proposal\",\n\t\t\t\"CapabilityAdmissionProposal requires proposalId, subjectId, and a D348 BoundaryCapabilityRef\",\n\t\t\t{ subjectId: typeof proposal.subjectId === \"string\" ? proposal.subjectId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction capabilityAdmissionPolicyIssue(policy: CapabilityAdmissionPolicy): DataIssue | undefined {\n\tif (\n\t\tpolicy.kind !== \"capability-admission-policy\" ||\n\t\ttypeof policy.policyId !== \"string\" ||\n\t\tpolicy.policyId.length === 0 ||\n\t\t(policy.capabilityIds !== undefined &&\n\t\t\t(!Array.isArray(policy.capabilityIds) ||\n\t\t\t\t!policy.capabilityIds.every((id) => typeof id === \"string\" && id.length > 0))) ||\n\t\t(policy.capabilityKinds !== undefined &&\n\t\t\t(!Array.isArray(policy.capabilityKinds) ||\n\t\t\t\t!policy.capabilityKinds.every(isBoundaryCapabilityKind))) ||\n\t\t(policy.requiredOnly !== undefined && typeof policy.requiredOnly !== \"boolean\") ||\n\t\t(policy.allowedOutcomes !== undefined &&\n\t\t\t(!Array.isArray(policy.allowedOutcomes) ||\n\t\t\t\t!policy.allowedOutcomes.every(isCapabilityAdmissionOutcome)))\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-policy\",\n\t\t\t\"CapabilityAdmissionPolicy requires a policyId and D348 capability/outcome filters\",\n\t\t\t{ subjectId: typeof policy.policyId === \"string\" ? policy.policyId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction capabilityAdmissionDecisionIssue(\n\tdecision: CapabilityAdmissionDecision,\n): DataIssue | undefined {\n\tif (\n\t\tdecision.kind !== \"capability-admission-decision\" ||\n\t\ttypeof decision.decisionId !== \"string\" ||\n\t\tdecision.decisionId.length === 0 ||\n\t\ttypeof decision.admissionId !== \"string\" ||\n\t\tdecision.admissionId.length === 0 ||\n\t\ttypeof decision.proposalId !== \"string\" ||\n\t\tdecision.proposalId.length === 0 ||\n\t\t!isCapabilityAdmissionOutcome(decision.outcome) ||\n\t\t(decision.policyId !== undefined &&\n\t\t\t(typeof decision.policyId !== \"string\" || decision.policyId.length === 0))\n\t) {\n\t\treturn dataIssue(\n\t\t\t\"malformed-capability-admission-decision\",\n\t\t\t\"CapabilityAdmissionDecision requires decisionId, admissionId, proposalId, and allow/block/defer outcome\",\n\t\t\t{ subjectId: typeof decision.proposalId === \"string\" ? decision.proposalId : undefined },\n\t\t);\n\t}\n\treturn undefined;\n}\n\nfunction validateCapabilityAdmissionPolicy(\n\tpolicy: CapabilityAdmissionPolicy,\n\tdecision: CapabilityAdmissionDecision,\n\tproposal: CapabilityAdmissionProposal,\n): { readonly code: string; readonly message: string } | undefined {\n\tif (\n\t\tpolicy.capabilityIds !== undefined &&\n\t\t!policy.capabilityIds.includes(proposal.capability.id)\n\t) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not apply to capability '${proposal.capability.id}'`,\n\t\t};\n\t}\n\tif (\n\t\tpolicy.capabilityKinds !== undefined &&\n\t\t!policy.capabilityKinds.includes(proposal.capability.kind)\n\t) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not apply to capability kind '${proposal.capability.kind}'`,\n\t\t};\n\t}\n\tif (policy.requiredOnly === true && !proposal.capability.required) {\n\t\treturn {\n\t\t\tcode: \"capability-admission-policy-mismatch\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' applies only to required capabilities`,\n\t\t};\n\t}\n\tif (policy.allowedOutcomes !== undefined && !policy.allowedOutcomes.includes(decision.outcome)) {\n\t\treturn {\n\t\t\tcode: \"unsupported-capability-admission-outcome\",\n\t\t\tmessage: `CapabilityAdmissionPolicy '${policy.policyId}' does not allow outcome '${decision.outcome}'`,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction capabilityPolicyForDecision(\n\tstate: CapabilityAdmissionStateInternal,\n\tdecision: CapabilityAdmissionDecision,\n):\n\t| CapabilityAdmissionPolicy\n\t| \"missing-capability-admission-policy\"\n\t| \"stale-capability-admission-policy-ref\"\n\t| undefined {\n\tif (decision.policyId === undefined) return undefined;\n\tconst stalePolicyRef = (decision.sourceRefs ?? []).find(\n\t\t(sourceRef) =>\n\t\t\tsourceRef.kind === \"capability-admission-policy\" && sourceRef.id !== decision.policyId,\n\t);\n\tif (stalePolicyRef !== undefined) return \"stale-capability-admission-policy-ref\";\n\treturn state.policies.get(decision.policyId) ?? \"missing-capability-admission-policy\";\n}\n\nfunction capabilityPolicyIssueMessage(\n\tcode: \"missing-capability-admission-policy\" | \"stale-capability-admission-policy-ref\",\n\tdecision: CapabilityAdmissionDecision,\n): string {\n\tif (code === \"missing-capability-admission-policy\") {\n\t\treturn `CapabilityAdmissionPolicy '${decision.policyId}' was referenced but not present`;\n\t}\n\treturn `CapabilityAdmissionDecision '${decision.decisionId}' carries a stale admission policy source ref`;\n}\n\nfunction admissionStateForOutcome(\n\toutcome: CapabilityAdmissionOutcome,\n): CapabilityAdmissionState | undefined {\n\tif (outcome === \"allow\") return \"allowed\";\n\tif (outcome === \"block\") return \"blocked\";\n\tif (outcome === \"defer\") return \"deferred\";\n\treturn undefined;\n}\n\nfunction capabilityAdmissionStatusState(\n\tstate: CapabilityAdmissionState,\n): CapabilityAdmissionStatus[\"state\"] {\n\tif (state === \"allowed\") return \"capability-admission-allowed\";\n\tif (state === \"blocked\") return \"capability-admission-blocked\";\n\treturn \"capability-admission-deferred\";\n}\n\nfunction cloneCapabilityRef(ref: BoundaryCapabilityRef): BoundaryCapabilityRef {\n\treturn {\n\t\tid: ref.id,\n\t\tkind: ref.kind,\n\t\trequired: ref.required,\n\t\t...(ref.sourceRefs === undefined ? {} : { sourceRefs: [...ref.sourceRefs] }),\n\t};\n}\n\nfunction isBoundaryCapabilityRef(value: unknown): value is BoundaryCapabilityRef {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst record = value as Partial<BoundaryCapabilityRef>;\n\treturn (\n\t\ttypeof record.id === \"string\" &&\n\t\trecord.id.length > 0 &&\n\t\tisBoundaryCapabilityKind(record.kind) &&\n\t\ttypeof record.required === \"boolean\" &&\n\t\t(record.sourceRefs === undefined ||\n\t\t\t(Array.isArray(record.sourceRefs) &&\n\t\t\t\trecord.sourceRefs.every((sourceRef) => typeof sourceRef === \"string\")))\n\t);\n}\n\nfunction isBoundaryCapabilityKind(value: unknown): value is BoundaryCapabilityRef[\"kind\"] {\n\treturn value === \"auth\" || value === \"permission\" || value === \"config\" || value === \"resource\";\n}\n\nfunction isCapabilityAdmissionOutcome(value: unknown): value is CapabilityAdmissionOutcome {\n\treturn value === \"allow\" || value === \"block\" || value === \"defer\";\n}\n\nfunction proposalKeyFallback(proposal: CapabilityAdmissionProposal): string {\n\treturn typeof proposal.proposalId === \"string\" && proposal.proposalId.length > 0\n\t\t? proposal.proposalId\n\t\t: `${stringValue(proposal.subjectId) ?? \"unknown\"}:${capabilityKeyFallback(proposal.capability)}`;\n}\n\nfunction policyKeyFallback(policy: CapabilityAdmissionPolicy): string {\n\treturn typeof policy.policyId === \"string\" && policy.policyId.length > 0\n\t\t? policy.policyId\n\t\t: \"unknown\";\n}\n\nfunction decisionKeyFallback(decision: CapabilityAdmissionDecision): string {\n\treturn typeof decision.decisionId === \"string\" && decision.decisionId.length > 0\n\t\t? decision.decisionId\n\t\t: `${stringValue(decision.proposalId) ?? \"unknown\"}:${stringValue(decision.admissionId) ?? \"unknown\"}`;\n}\n\nfunction capabilityKeyFallback(value: unknown): string {\n\tif (!isBoundaryCapabilityRef(value)) return \"unknown-capability\";\n\treturn `${value.kind}:${value.id}`;\n}\n\nfunction nextMalformedIssueKey(\n\tstate: CapabilityAdmissionStateInternal,\n\tkind: \"decision\" | \"policy\" | \"proposal\",\n\tfallback: string,\n): string {\n\tstate.issueSeq += 1;\n\treturn `malformed-${kind}:${state.issueSeq}:${fallback}`;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction capabilityProposalRefs(proposal: CapabilityAdmissionProposal): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"capability-admission-proposal\", proposal.proposalId),\n\t\tref(\"boundary-capability\", `${proposal.capability.kind}:${proposal.capability.id}`),\n\t\t...(proposal.sourceRefs ?? []),\n\t]);\n}\n\nfunction capabilityDecisionRefs(\n\tdecision: CapabilityAdmissionDecision,\n\tproposal?: CapabilityAdmissionProposal,\n\tpolicy?: CapabilityAdmissionPolicy,\n): readonly SourceRef[] {\n\treturn uniqueSourceRefs([\n\t\tref(\"capability-admission-decision\", decision.decisionId),\n\t\tref(\"capability-admission\", decision.admissionId),\n\t\tref(\"capability-admission-proposal\", decision.proposalId),\n\t\t...(proposal === undefined ? [] : capabilityProposalRefs(proposal)),\n\t\t...(decision.policyId === undefined\n\t\t\t? []\n\t\t\t: [ref(\"capability-admission-policy\", decision.policyId)]),\n\t\t...(policy === undefined ? [] : [ref(\"capability-admission-policy\", policy.policyId)]),\n\t\t...(decision.sourceRefs ?? []),\n\t]);\n}\n\nfunction forEachPolicyDepBatch(\n\tctx: Ctx,\n\tstart: number,\n\tcount: number,\n\tfn: (value: unknown) => void,\n): void {\n\tfor (let i = 0; i < count; i += 1) {\n\t\tfor (const value of depBatch(ctx, start + i) ?? []) fn(value);\n\t}\n}\n\nfunction projectRuntimeFact<T, TOut>(\n\tgraph: Graph,\n\truntime: Node<T>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: T) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = fact as T;\n\t\t\t\tconst value = pick(typed);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory },\n\t);\n}\n\nfunction freezeCapabilityAdmissionViews(\n\tstate: CapabilityAdmissionViewsState,\n): CapabilityAdmissionViews {\n\treturn {\n\t\tadmissionsByProposal: new Map(state.admissionsByProposal),\n\t\tadmissionsBySubject: new Map(\n\t\t\tArray.from(state.admissionsBySubject, ([key, value]) => [key, Object.freeze([...value])]),\n\t\t),\n\t\tissues: Object.freeze([...state.issues]),\n\t\taudit: Object.freeze([...state.audit]),\n\t};\n}\n\nfunction emptyCapabilityAdmissionState(): CapabilityAdmissionStateInternal {\n\treturn {\n\t\tproposals: new Map(),\n\t\tpolicies: new Map(),\n\t\tdecisions: new Map(),\n\t\tadmissionsById: new Map(),\n\t\tadmissionsByProposal: new Map(),\n\t\tterminalDecisionIds: new Set(),\n\t\tissueKeys: new Set(),\n\t\tissueSeq: 0,\n\t\tstatusSeq: 0,\n\t\tauditSeq: 0,\n\t};\n}\n\nfunction dataIssue(\n\tcode: string,\n\tmessage: string,\n\topts: {\n\t\treadonly subjectId?: string;\n\t\treadonly refs?: readonly SourceRef[];\n\t\treadonly details?: unknown;\n\t} = {},\n): DataIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: \"error\",\n\t\tsubjectId: opts.subjectId,\n\t\trefs: opts.refs?.map((sourceRef) => `${sourceRef.kind}:${sourceRef.id}`),\n\t\tdetails: opts.details,\n\t};\n}\n\nfunction uniqueSourceRefs(sourceRefs: readonly SourceRef[]): readonly SourceRef[] {\n\tconst seen = new Set<string>();\n\tconst out: 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\tout.push(sourceRef);\n\t}\n\treturn out;\n}\n\nfunction ref(kind: string, id: string): SourceRef {\n\treturn { kind, id };\n}\n","import type { SegmentAdapter, SegmentBreakKind, SegmentInfo } from \"./types.js\";\n\nexport const kinsokuStart = /* @__PURE__ */ new Set([\n\t\"\\u3001\",\n\t\"\\u3002\",\n\t\"\\u30FB\",\n\t\"\\uFF09\",\n\t\"\\u3015\",\n\t\"\\u3009\",\n\t\"\\u300B\",\n\t\"\\u300D\",\n\t\"\\u300F\",\n\t\"\\u3011\",\n]);\n\nexport const leftStickyPunctuation = /* @__PURE__ */ new Set([\n\t\".\",\n\t\",\",\n\t\"!\",\n\t\"?\",\n\t\":\",\n\t\";\",\n\t\")\",\n\t\"]\",\n\t\"}\",\n\t\"%\",\n\t'\"',\n\t\"\\u201D\",\n\t\"\\u2019\",\n\t\"\\xBB\",\n\t\"\\u203A\",\n\t\"\\u2026\",\n]);\n\nexport function isCJK(text: string): boolean {\n\tfor (const ch of text) {\n\t\tconst c = ch.codePointAt(0);\n\t\tif (\n\t\t\t(c !== undefined && c >= 19968 && c <= 40959) ||\n\t\t\t(c !== undefined && c >= 13312 && c <= 19903) ||\n\t\t\t(c !== undefined && c >= 12288 && c <= 12351) ||\n\t\t\t(c !== undefined && c >= 12352 && c <= 12447) ||\n\t\t\t(c !== undefined && c >= 44032 && c <= 55215) ||\n\t\t\t(c !== undefined && c >= 65280 && c <= 65519)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nexport function normalizeWhitespace(text: string): string {\n\treturn text.replace(/[\\t\\f ]+/g, \" \").replace(/^ | $/g, \"\");\n}\n\nexport function segmentText(\n\ttext: string,\n\tsegmentAdapter: SegmentAdapter,\n): {\n\treadonly texts: string[];\n\treadonly isWordLike: boolean[];\n\treadonly kinds: SegmentBreakKind[];\n}[] {\n\tconst pieces: {\n\t\ttexts: string[];\n\t\tisWordLike: boolean[];\n\t\tkinds: SegmentBreakKind[];\n\t}[] = [];\n\tfor (const s of segmentAdapter.segmentWords(text)) {\n\t\tconst wordSegment = s.segment;\n\t\tconst rawWordLike = s.isWordLike ?? false;\n\t\tconst pieceTexts: string[] = [];\n\t\tconst pieceWordLikes: boolean[] = [];\n\t\tconst pieceKinds: SegmentBreakKind[] = [];\n\t\tlet currentText = \"\";\n\t\tlet currentKind: SegmentBreakKind | null = null;\n\t\tfor (const ch of wordSegment) {\n\t\t\tlet kind: SegmentBreakKind;\n\t\t\tif (ch === \" \") {\n\t\t\t\tkind = \"space\";\n\t\t\t} else if (ch === \"\\u200B\") {\n\t\t\t\tkind = \"zero-width-break\";\n\t\t\t} else if (ch === \"\\xAD\") {\n\t\t\t\tkind = \"soft-hyphen\";\n\t\t\t} else if (ch === \"\\n\") {\n\t\t\t\tkind = \"hard-break\";\n\t\t\t} else {\n\t\t\t\tkind = \"text\";\n\t\t\t}\n\t\t\tif (currentKind !== null && kind === currentKind) {\n\t\t\t\tcurrentText += ch;\n\t\t\t} else {\n\t\t\t\tif (currentKind !== null) {\n\t\t\t\t\tpieceTexts.push(currentText);\n\t\t\t\t\tpieceWordLikes.push(currentKind === \"text\" && rawWordLike);\n\t\t\t\t\tpieceKinds.push(currentKind);\n\t\t\t\t}\n\t\t\t\tcurrentText = ch;\n\t\t\t\tcurrentKind = kind;\n\t\t\t}\n\t\t}\n\t\tif (currentKind !== null) {\n\t\t\tpieceTexts.push(currentText);\n\t\t\tpieceWordLikes.push(currentKind === \"text\" && rawWordLike);\n\t\t\tpieceKinds.push(currentKind);\n\t\t}\n\t\tpieces.push({ texts: pieceTexts, isWordLike: pieceWordLikes, kinds: pieceKinds });\n\t}\n\treturn pieces;\n}\n\nfunction* fallbackSegmentWords(text: string): Iterable<SegmentInfo> {\n\tlet index = 0;\n\tlet current = \"\";\n\tlet currentIndex = 0;\n\tlet currentWordLike: boolean | null = null;\n\tconst flush = () => {\n\t\tif (current.length === 0 || currentWordLike === null) return undefined;\n\t\tconst out = { segment: current, index: currentIndex, isWordLike: currentWordLike };\n\t\tcurrent = \"\";\n\t\tcurrentWordLike = null;\n\t\treturn out;\n\t};\n\tfor (const ch of text) {\n\t\tconst isWordLike = !/[\\s\\u200B\\u00AD]/u.test(ch);\n\t\tif (currentWordLike !== null && currentWordLike !== isWordLike) {\n\t\t\tconst out = flush();\n\t\t\tif (out) yield out;\n\t\t}\n\t\tif (currentWordLike === null) {\n\t\t\tcurrentWordLike = isWordLike;\n\t\t\tcurrentIndex = index;\n\t\t}\n\t\tcurrent += ch;\n\t\tindex += ch.length;\n\t}\n\tconst out = flush();\n\tif (out) yield out;\n}\n\nfunction* fallbackSegmentGraphemes(text: string): Iterable<SegmentInfo> {\n\tlet index = 0;\n\tfor (const ch of text) {\n\t\tyield { segment: ch, index };\n\t\tindex += ch.length;\n\t}\n}\n\nexport function createDefaultSegmentAdapter(): SegmentAdapter {\n\treturn {\n\t\tsegmentWords(text: string): Iterable<SegmentInfo> {\n\t\t\treturn fallbackSegmentWords(text);\n\t\t},\n\t\tsegmentGraphemes(text: string): Iterable<SegmentInfo> {\n\t\t\treturn fallbackSegmentGraphemes(text);\n\t\t},\n\t};\n}\n\nlet defaultSegmentAdapter: SegmentAdapter | null = null;\n\nexport function getDefaultSegmentAdapter(): SegmentAdapter {\n\tif (defaultSegmentAdapter === null) {\n\t\tdefaultSegmentAdapter = createDefaultSegmentAdapter();\n\t}\n\treturn defaultSegmentAdapter;\n}\n\nexport function measuredWidth(value: number | { readonly width: number }): number {\n\tconst width = typeof value === \"number\" ? value : value.width;\n\treturn Number.isFinite(width) && width >= 0 ? width : 0;\n}\n\nexport function metricKey(text: string, font: string): string {\n\treturn `${font}\\0${text}`;\n}\n","import type { Ctx } from \"../../ctx/types.js\";\nimport { errorPayload } from \"../../protocol/messages.js\";\nimport type { MeasureBlockOptions, MeasurementAdapter, Size } from \"./types.js\";\n\nexport function nonNegativeFinite(value: number, fallback: number): number {\n\treturn Number.isFinite(value) ? Math.max(0, value) : fallback;\n}\n\nexport function finiteNumber(value: number, fallback: number): number {\n\treturn Number.isFinite(value) ? value : fallback;\n}\n\nexport function emitLayoutError(ctx: Ctx, error: unknown, fallback: string): void {\n\tctx.down([[\"ERROR\", errorPayload(error, fallback)]]);\n}\n\nexport function positiveFinite(value: number, fallback: number): number {\n\treturn Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nexport function clampDimension(value: number | undefined): number {\n\treturn nonNegativeFinite(value ?? 0, 0);\n}\n\nexport function fitSize(size: Size, maxWidth: number): Size {\n\tconst width = nonNegativeFinite(size.width, 0);\n\tconst height = nonNegativeFinite(size.height, 0);\n\tif (width === 0 || maxWidth <= 0 || width <= maxWidth) return { width, height };\n\tconst scale = maxWidth / width;\n\treturn { width: maxWidth, height: height * scale };\n}\n\nexport function blockMaxWidth(blockMaxWidth: number | undefined, maxWidth: number): number {\n\tconst own = blockMaxWidth === undefined ? maxWidth : nonNegativeFinite(blockMaxWidth, maxWidth);\n\tif (maxWidth <= 0) return own;\n\tif (own <= 0) return maxWidth;\n\treturn Math.min(own, maxWidth);\n}\n\nexport function resolveTextAdapter(opts: MeasureBlockOptions): MeasurementAdapter {\n\tconst adapter = opts.adapters?.text ?? opts.adapter;\n\tif (!adapter) throw new Error(\"Text blocks require a MeasurementAdapter\");\n\treturn adapter;\n}\n","import { isCJK, measuredWidth, metricKey } from \"./segment.js\";\nimport type {\n\tCellMeasureAdapterOptions,\n\tImageMeasurer,\n\tImageSizeLookup,\n\tInjectedMeasureAdapterOptions,\n\tMeasureFn,\n\tMeasurementAdapter,\n\tPrecomputedMeasureAdapterOptions,\n\tSize,\n\tSvgMeasurer,\n\tTextMeasureCapability,\n} from \"./types.js\";\nimport { nonNegativeFinite } from \"./utils.js\";\n\n/** Adapter that wraps a caller-owned synchronous measurement function. */\nexport class InjectedMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly measure: MeasureFn;\n\tprivate readonly shouldCache: boolean;\n\tprivate readonly cache = new Map<string, number>();\n\n\tconstructor(measure: MeasureFn, opts: InjectedMeasureAdapterOptions = {}) {\n\t\tthis.measure = measure;\n\t\tthis.shouldCache = opts.cache ?? true;\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\tconst key = metricKey(text, font);\n\t\tif (this.shouldCache) {\n\t\t\tconst cached = this.cache.get(key);\n\t\t\tif (cached !== undefined) return { width: cached };\n\t\t}\n\t\tconst width = measuredWidth(this.measure(text, font));\n\t\tif (this.shouldCache) this.cache.set(key, width);\n\t\treturn { width };\n\t}\n\n\tclearCache(): void {\n\t\tthis.cache.clear();\n\t}\n}\n\n/** Deterministic adapter backed by caller-supplied width metrics. */\nexport class PrecomputedMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly metrics: ReadonlyMap<string, number>;\n\tprivate readonly fallback: \"per-char\" | \"error\";\n\tprivate readonly cellWidth: number;\n\n\tconstructor(opts: PrecomputedMeasureAdapterOptions) {\n\t\tthis.metrics =\n\t\t\topts.metrics instanceof Map ? opts.metrics : new Map(Object.entries(opts.metrics));\n\t\tthis.fallback = opts.fallback ?? \"error\";\n\t\tthis.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\tconst fontScoped = this.metrics.get(metricKey(text, font));\n\t\tif (fontScoped !== undefined) return { width: nonNegativeFinite(fontScoped, 0) };\n\t\tconst unscoped = this.metrics.get(text);\n\t\tif (unscoped !== undefined) return { width: nonNegativeFinite(unscoped, 0) };\n\t\tif (this.fallback === \"per-char\") {\n\t\t\treturn { width: Array.from(text).length * this.cellWidth };\n\t\t}\n\t\tthrow new Error(`No precomputed metric for segment ${JSON.stringify(text)}`);\n\t}\n}\n\n/** Fixed-cell adapter for CLI, snapshots, and tests. */\nexport class CellMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly cellWidth: number;\n\tprivate readonly wideCellWidth: number;\n\tprivate readonly tabCells: number;\n\n\tconstructor(opts: CellMeasureAdapterOptions = {}) {\n\t\tthis.cellWidth = nonNegativeFinite(opts.cellWidth ?? 8, 8);\n\t\tthis.wideCellWidth = nonNegativeFinite(\n\t\t\topts.wideCellWidth ?? this.cellWidth * 2,\n\t\t\tthis.cellWidth * 2,\n\t\t);\n\t\tthis.tabCells = Math.max(1, Math.floor(nonNegativeFinite(opts.tabCells ?? 4, 4)));\n\t}\n\n\tmeasureSegment(text: string): { readonly width: number } {\n\t\tlet width = 0;\n\t\tfor (const char of text) {\n\t\t\tif (char === \"\\t\") width += this.cellWidth * this.tabCells;\n\t\t\telse width += isCJK(char) ? this.wideCellWidth : this.cellWidth;\n\t\t}\n\t\treturn { width };\n\t}\n}\n\n/** Adapter over a caller-owned platform capability such as NodeCanvas, Skia, or RN text APIs. */\nexport class CapabilityMeasureAdapter implements MeasurementAdapter {\n\tprivate readonly capability: TextMeasureCapability;\n\n\tconstructor(capability: TextMeasureCapability) {\n\t\tthis.capability = capability;\n\t}\n\n\tmeasureSegment(text: string, font: string): { readonly width: number } {\n\t\treturn { width: measuredWidth(this.capability.measureText(text, font)) };\n\t}\n\n\tclearCache(): void {\n\t\tthis.capability.clearCache?.();\n\t}\n}\n\nfunction stripSvgIgnoredContent(svg: string): string {\n\treturn svg.replace(/<!--[\\s\\S]*?-->/g, \"\").replace(/<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/g, \"\");\n}\n\nfunction readSvgRootTag(svg: string): string | null {\n\treturn /<svg\\b[^>]*>/i.exec(svg)?.[0] ?? null;\n}\n\nfunction readNumericAttr(tag: string, attr: string): number | null {\n\tconst pattern = new RegExp(`(?:^|\\\\s)${attr}\\\\s*=\\\\s*[\"']?(-?\\\\d+(?:\\\\.\\\\d+)?)`, \"i\");\n\tconst match = pattern.exec(tag);\n\tif (!match) return null;\n\tconst value = Number(match[1]);\n\treturn Number.isFinite(value) && value >= 0 ? value : null;\n}\n\nfunction readViewBox(tag: string): Size | null {\n\tconst match =\n\t\t/\\bviewBox\\s*=\\s*[\"']\\s*(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s+(-?\\d+(?:\\.\\d+)?)\\s*[\"']/i.exec(\n\t\t\ttag,\n\t\t);\n\tif (!match) return null;\n\tconst width = Number(match[3]);\n\tconst height = Number(match[4]);\n\tif (!Number.isFinite(width) || !Number.isFinite(height) || width < 0 || height < 0) {\n\t\treturn null;\n\t}\n\treturn { width, height };\n}\n\n/**\n * Minimal string-based SVG bounds reader for explicit width/height or viewBox.\n *\n * This is not a DOM SVG parser and does not resolve external resources.\n */\nexport class SvgBoundsAdapter implements SvgMeasurer {\n\tmeasureSvg(svg: string): Size {\n\t\tconst cleaned = stripSvgIgnoredContent(svg);\n\t\tconst rootTag = readSvgRootTag(cleaned);\n\t\tif (rootTag === null) throw new Error(\"Cannot measure SVG without a root <svg> element\");\n\t\tconst width = readNumericAttr(rootTag, \"width\");\n\t\tconst height = readNumericAttr(rootTag, \"height\");\n\t\tif (width !== null && height !== null) return { width, height };\n\t\tconst viewBox = readViewBox(rootTag);\n\t\tif (viewBox) return viewBox;\n\t\tthrow new Error(\"Cannot measure SVG without width/height or viewBox\");\n\t}\n}\n\n/** Image measurer backed by explicit caller-provided dimensions; it never loads images. */\nexport class ImageSizeAdapter implements ImageMeasurer {\n\tprivate readonly sizes: ImageSizeLookup;\n\n\tconstructor(sizes: ImageSizeLookup | Record<string, Size>) {\n\t\tthis.sizes = isImageSizeLookup(sizes) ? sizes : new Map(Object.entries(sizes));\n\t}\n\n\tmeasureImage(src: string): Size {\n\t\tconst size = this.sizes.get(src);\n\t\tif (!size) throw new Error(`No image size registered for ${JSON.stringify(src)}`);\n\t\treturn size;\n\t}\n}\n\nfunction isImageSizeLookup(value: unknown): value is ImageSizeLookup {\n\tif (value === null) return false;\n\tconst valueType = typeof value;\n\tif (valueType !== \"object\" && valueType !== \"function\") return false;\n\treturn typeof (value as { readonly get?: unknown }).get === \"function\";\n}\n","import {\n\tgetDefaultSegmentAdapter,\n\tisCJK,\n\tkinsokuStart,\n\tleftStickyPunctuation,\n\tnormalizeWhitespace,\n\tsegmentText,\n} from \"./segment.js\";\nimport type {\n\tCharPosition,\n\tInterval,\n\tLayoutCursor,\n\tLayoutLine,\n\tLayoutNextLineContext,\n\tLayoutNextLineResult,\n\tLineBreaksResult,\n\tMeasurementAdapter,\n\tPreparedSegment,\n\tSegmentAdapter,\n\tSegmentBreakKind,\n\tSegmentMeasureStats,\n} from \"./types.js\";\nimport { nonNegativeFinite } from \"./utils.js\";\n\n/**\n * Segment text and measure every resulting segment with a caller-owned synchronous adapter.\n *\n * @param text - Text to normalize, segment, and measure.\n * @param font - Font descriptor passed through to the measurement adapter.\n * @param adapter - Synchronous measurement adapter used for each segment or grapheme.\n * @param cache - Caller-owned cache keyed by font and segment text.\n * @param stats - Optional cache hit/miss accounting object updated during measurement.\n * @param segmentAdapter - Optional segmentation adapter; defaults to the built-in adapter.\n * @returns A prepared segment list with widths, break kinds, and optional grapheme widths for\n * word-like segments.\n * @example\n * ```ts\n * import { analyzeAndMeasure } from \"@graphrefly/ts/solutions/reactive-layout\";\n *\n * const segments = analyzeAndMeasure(\n * \"Hello world\",\n * \"16px system-ui\",\n * { measureSegment: (segment) => ({ width: segment.length * 8 }) },\n * new Map(),\n * );\n * ```\n * @remarks **Caller-owned adapter:** Measurement stays synchronous and host-injected; browser\n * Canvas, Skia, React Native, or test adapters live outside this helper.\n * @category solutions\n */\nexport function analyzeAndMeasure(\n\ttext: string,\n\tfont: string,\n\tadapter: MeasurementAdapter,\n\tcache: Map<string, Map<string, number>>,\n\tstats?: SegmentMeasureStats,\n\tsegmentAdapter?: SegmentAdapter,\n): PreparedSegment[] {\n\tconst normalized = normalizeWhitespace(text);\n\tif (normalized.length === 0) {\n\t\treturn [];\n\t}\n\tconst segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst pieces = segmentText(normalized, segAdapter);\n\tconst rawTexts: string[] = [];\n\tconst rawKinds: SegmentBreakKind[] = [];\n\tconst rawWordLike: boolean[] = [];\n\tfor (const piece of pieces) {\n\t\tfor (let i = 0; i < piece.texts.length; i += 1) {\n\t\t\trawTexts.push(piece.texts[i]);\n\t\t\trawKinds.push(piece.kinds[i]);\n\t\t\trawWordLike.push(piece.isWordLike[i]);\n\t\t}\n\t}\n\tconst mergedTexts: string[] = [];\n\tconst mergedKinds: SegmentBreakKind[] = [];\n\tconst mergedWordLike: boolean[] = [];\n\tfor (let i = 0; i < rawTexts.length; i += 1) {\n\t\tconst t = rawTexts[i];\n\t\tconst k = rawKinds[i];\n\t\tconst wl = rawWordLike[i];\n\t\tif (\n\t\t\tk === \"text\" &&\n\t\t\t!wl &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedTexts.length - 1] === \"text\"\n\t\t) {\n\t\t\tconst isSticky = t.length === 1 && (leftStickyPunctuation.has(t) || kinsokuStart.has(t));\n\t\t\tif (isSticky) {\n\t\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tt === \"-\" &&\n\t\t\tmergedTexts.length > 0 &&\n\t\t\tmergedKinds[mergedKinds.length - 1] === \"text\" &&\n\t\t\tmergedWordLike[mergedWordLike.length - 1]\n\t\t) {\n\t\t\tmergedTexts[mergedTexts.length - 1] += t;\n\t\t\tcontinue;\n\t\t}\n\t\tmergedTexts.push(t);\n\t\tmergedKinds.push(k);\n\t\tmergedWordLike.push(wl);\n\t}\n\tconst fontCache = cache.get(font) ?? new Map<string, number>();\n\tif (!cache.has(font)) cache.set(font, fontCache);\n\tfunction measureCached(segment: string): number {\n\t\tconst cached = fontCache.get(segment);\n\t\tif (cached === undefined) {\n\t\t\tif (stats) stats.misses += 1;\n\t\t\tconst measured = adapter.measureSegment(segment, font).width;\n\t\t\tconst width = Number.isFinite(measured) && measured >= 0 ? measured : 0;\n\t\t\tfontCache.set(segment, width);\n\t\t\treturn width;\n\t\t}\n\t\tif (stats) stats.hits += 1;\n\t\treturn cached;\n\t}\n\tconst out: PreparedSegment[] = [];\n\tfor (let i = 0; i < mergedTexts.length; i += 1) {\n\t\tconst t = mergedTexts[i];\n\t\tconst kind = mergedKinds[i];\n\t\tif (kind !== \"text\") {\n\t\t\tout.push({\n\t\t\t\ttext: t,\n\t\t\t\twidth: kind === \"space\" ? measureCached(\" \") * t.length : 0,\n\t\t\t\tkind,\n\t\t\t\tgraphemeWidths: null,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (isCJK(t)) {\n\t\t\tlet unitText = \"\";\n\t\t\tfor (const graphemeSegment of segAdapter.segmentGraphemes(t)) {\n\t\t\t\tconst grapheme = graphemeSegment.segment;\n\t\t\t\tif (unitText.length > 0 && kinsokuStart.has(grapheme)) {\n\t\t\t\t\tunitText += grapheme;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (unitText.length > 0) {\n\t\t\t\t\tout.push({\n\t\t\t\t\t\ttext: unitText,\n\t\t\t\t\t\twidth: measureCached(unitText),\n\t\t\t\t\t\tkind: \"text\",\n\t\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tunitText = grapheme;\n\t\t\t}\n\t\t\tif (unitText.length > 0) {\n\t\t\t\tout.push({\n\t\t\t\t\ttext: unitText,\n\t\t\t\t\twidth: measureCached(unitText),\n\t\t\t\t\tkind: \"text\",\n\t\t\t\t\tgraphemeWidths: null,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst textWidth = measureCached(t);\n\t\tlet graphemeWidths: number[] | null = null;\n\t\tif (mergedWordLike[i] && t.length > 1) {\n\t\t\tconst widths = [];\n\t\t\tfor (const grapheme of segAdapter.segmentGraphemes(t)) {\n\t\t\t\twidths.push(measureCached(grapheme.segment));\n\t\t\t}\n\t\t\tif (widths.length > 1) graphemeWidths = widths;\n\t\t}\n\t\tout.push({\n\t\t\ttext: t,\n\t\t\twidth: textWidth,\n\t\t\tkind: \"text\",\n\t\t\tgraphemeWidths,\n\t\t});\n\t}\n\treturn out;\n}\n\n/**\n * Compute greedy single-column line breaks over prepared segments.\n *\n * @param segments - Prepared segments from `analyzeAndMeasure` or a measurement provider.\n * @param maxWidth - Maximum line width in pixels; non-finite or negative values produce no useful\n * width budget.\n * @param opts - Optional hyphen width and segment adapter for grapheme-aware slicing.\n * @returns A `LineBreaksResult` containing ordered layout lines and the line count.\n * @example\n * ```ts\n * import { analyzeAndMeasure, computeLineBreaks } from \"@graphrefly/ts/solutions/reactive-layout\";\n *\n * const segments = analyzeAndMeasure(\n * \"Hello world\",\n * \"16px system-ui\",\n * { measureSegment: (segment) => ({ width: segment.length * 8 }) },\n * new Map(),\n * );\n * const lineBreaks = computeLineBreaks(segments, 64);\n * ```\n * @remarks **Pure helper:** This does not subscribe, schedule, or emit messages; reactive bundles\n * call it from ordinary graph nodes.\n * @category solutions\n */\nexport function computeLineBreaks(\n\tsegments: readonly PreparedSegment[],\n\tmaxWidth: number,\n\topts: { readonly hyphenWidth?: number; readonly segmentAdapter?: SegmentAdapter } = {},\n): LineBreaksResult {\n\tif (segments.length === 0) return { lines: [], lineCount: 0 };\n\tconst segAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst lines: LayoutLine[] = [];\n\tlet cursor: LayoutCursor = { segmentIndex: 0, graphemeIndex: 0 };\n\twhile (cursor.segmentIndex < segments.length) {\n\t\tconst next = layoutNextLine(segments, cursor, maxWidth, {\n\t\t\thyphenWidth: opts.hyphenWidth,\n\t\t\tsegmentAdapter: segAdapter,\n\t\t});\n\t\tif (next === null) break;\n\t\tlines.push({\n\t\t\ttext: next.text,\n\t\t\twidth: next.width,\n\t\t\tstartSegment: next.start.segmentIndex,\n\t\t\tstartGrapheme: next.start.graphemeIndex,\n\t\t\tendSegment: next.end.segmentIndex,\n\t\t\tendGrapheme: next.end.graphemeIndex,\n\t\t});\n\t\tif (\n\t\t\tnext.end.segmentIndex === cursor.segmentIndex &&\n\t\t\tnext.end.graphemeIndex === cursor.graphemeIndex\n\t\t) {\n\t\t\tbreak;\n\t\t}\n\t\tcursor = next.end;\n\t}\n\treturn { lines, lineCount: lines.length };\n}\n\nfunction canBreakAfter(kind: SegmentBreakKind): boolean {\n\treturn kind === \"space\" || kind === \"zero-width-break\" || kind === \"soft-hyphen\";\n}\n\nfunction sliceSegmentText(\n\tseg: PreparedSegment,\n\tstartGrapheme: number,\n\tendGrapheme: number,\n\tsegmentAdapter: SegmentAdapter,\n): string {\n\tif (startGrapheme === 0 && endGrapheme < 0) return seg.text;\n\tconst graphemes = [...segmentAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);\n\tconst stop = endGrapheme < 0 ? graphemes.length : endGrapheme;\n\treturn graphemes.slice(startGrapheme, stop).join(\"\");\n}\n\nfunction buildLineText(\n\tsegments: readonly PreparedSegment[],\n\tstartSegment: number,\n\tstartGrapheme: number,\n\tendSegment: number,\n\tendGrapheme: number,\n\tappendHyphen: boolean,\n\tsegmentAdapter: SegmentAdapter,\n): string {\n\tlet text = \"\";\n\tfor (let i = startSegment; i < endSegment; i += 1) {\n\t\tconst seg = segments[i];\n\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") continue;\n\t\tif (i === startSegment && startGrapheme > 0) {\n\t\t\ttext += sliceSegmentText(seg, startGrapheme, -1, segmentAdapter);\n\t\t} else {\n\t\t\ttext += seg.text;\n\t\t}\n\t}\n\tif (endGrapheme > 0 && endSegment < segments.length) {\n\t\tconst seg = segments[endSegment];\n\t\tconst from = startSegment === endSegment ? startGrapheme : 0;\n\t\ttext += sliceSegmentText(seg, from, endGrapheme, segmentAdapter);\n\t}\n\tif (appendHyphen) text += \"-\";\n\treturn text;\n}\n\nfunction resolveHyphenWidth(ctx: LayoutNextLineContext | undefined): number {\n\tif (ctx?.hyphenWidth !== undefined) return nonNegativeFinite(ctx.hyphenWidth, 0);\n\tif (ctx?.adapter === undefined || ctx.font === undefined) return 0;\n\tconst cache = ctx.cache;\n\tif (cache) {\n\t\tlet fontCache = cache.get(ctx.font);\n\t\tif (fontCache === undefined) {\n\t\t\tfontCache = new Map();\n\t\t\tcache.set(ctx.font, fontCache);\n\t\t}\n\t\tlet width = fontCache.get(\"-\");\n\t\tif (width === undefined) {\n\t\t\twidth = ctx.adapter.measureSegment(\"-\", ctx.font).width;\n\t\t\tfontCache.set(\"-\", width);\n\t\t}\n\t\treturn width;\n\t}\n\treturn ctx.adapter.measureSegment(\"-\", ctx.font).width;\n}\n\n/** Lay out one line from a cursor, returning the next cursor for continuation. */\nexport function layoutNextLine(\n\tsegments: readonly PreparedSegment[],\n\tcursor: LayoutCursor,\n\tslotWidth: number,\n\tctx?: LayoutNextLineContext,\n): LayoutNextLineResult | null {\n\tlet i = cursor.segmentIndex;\n\tconst initialGrapheme = cursor.graphemeIndex;\n\tconst segmentAdapter = ctx?.segmentAdapter ?? getDefaultSegmentAdapter();\n\tif (i >= segments.length) return null;\n\tif (initialGrapheme === 0) {\n\t\twhile (i < segments.length) {\n\t\t\tconst seg = segments[i];\n\t\t\tif (seg.kind === \"hard-break\") {\n\t\t\t\treturn {\n\t\t\t\t\ttext: \"\",\n\t\t\t\t\twidth: 0,\n\t\t\t\t\tstart: { segmentIndex: cursor.segmentIndex, graphemeIndex: 0 },\n\t\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (seg.kind === \"space\" || seg.kind === \"zero-width-break\" || seg.kind === \"soft-hyphen\") {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (i >= segments.length) return null;\n\t}\n\tconst hyphenWidth = resolveHyphenWidth(ctx);\n\tconst startSegment = i;\n\tconst startGrapheme = i === cursor.segmentIndex ? initialGrapheme : 0;\n\tlet lineW = 0;\n\tlet lineEndSegment = startSegment;\n\tlet lineEndGrapheme = 0;\n\tlet hasContent = false;\n\tlet pendingBreakSegment = -1;\n\tlet pendingBreakGrapheme = 0;\n\tlet pendingBreakWidth = 0;\n\tlet pendingBreakSoftHyphen = false;\n\tconst recordPending = (\n\t\tsIdx: number,\n\t\tgIdx: number,\n\t\twidth: number,\n\t\tkind: SegmentBreakKind,\n\t): void => {\n\t\tpendingBreakSegment = sIdx;\n\t\tpendingBreakGrapheme = gIdx;\n\t\tpendingBreakWidth = width;\n\t\tpendingBreakSoftHyphen = kind === \"soft-hyphen\";\n\t};\n\tconst consumeBreakable = (segIdx: number, startG: number, widths: readonly number[]): boolean => {\n\t\tfor (let g = startG; g < widths.length; g += 1) {\n\t\t\tconst gw = widths[g];\n\t\t\tif (!hasContent) {\n\t\t\t\tlineW = gw;\n\t\t\t\tlineEndSegment = segIdx;\n\t\t\t\tlineEndGrapheme = g + 1;\n\t\t\t\thasContent = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lineW + gw > slotWidth + 1e-3) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tlineW += gw;\n\t\t\tlineEndSegment = segIdx;\n\t\t\tlineEndGrapheme = g + 1;\n\t\t}\n\t\tif (lineEndSegment === segIdx && lineEndGrapheme === widths.length) {\n\t\t\tlineEndSegment = segIdx + 1;\n\t\t\tlineEndGrapheme = 0;\n\t\t}\n\t\treturn false;\n\t};\n\tif (startGrapheme > 0 && startSegment < segments.length) {\n\t\tconst seg = segments[startSegment];\n\t\tif (seg.graphemeWidths) {\n\t\t\tconst overflow = consumeBreakable(startSegment, startGrapheme, seg.graphemeWidths);\n\t\t\tif (overflow) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tfalse,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW,\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\ti = lineEndSegment;\n\t\t}\n\t}\n\tfor (; i < segments.length; i += 1) {\n\t\tconst seg = segments[i];\n\t\tif (seg.kind === \"hard-break\") {\n\t\t\tif (hasContent) {\n\t\t\t\tconst endsAtSoftHyphen =\n\t\t\t\t\tlineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === \"soft-hyphen\";\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tendsAtSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\ttext: \"\",\n\t\t\t\twidth: 0,\n\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\tend: { segmentIndex: i + 1, graphemeIndex: 0 },\n\t\t\t};\n\t\t}\n\t\tconst w = seg.width;\n\t\tif (!hasContent) {\n\t\t\tif (w > slotWidth && seg.graphemeWidths) {\n\t\t\t\tconst overflow = consumeBreakable(i, 0, seg.graphemeWidths);\n\t\t\t\tif (overflow) {\n\t\t\t\t\tconst text = buildLineText(\n\t\t\t\t\t\tsegments,\n\t\t\t\t\t\tstartSegment,\n\t\t\t\t\t\tstartGrapheme,\n\t\t\t\t\t\tlineEndSegment,\n\t\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tsegmentAdapter,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext,\n\t\t\t\t\t\twidth: lineW,\n\t\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\ti = lineEndSegment - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlineW = w;\n\t\t\tlineEndSegment = i + 1;\n\t\t\tlineEndGrapheme = 0;\n\t\t\thasContent = true;\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\trecordPending(i + 1, 0, seg.kind === \"space\" ? lineW - w : lineW, seg.kind);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst projectedWidth = lineW + w;\n\t\tif (projectedWidth > slotWidth + 1e-3) {\n\t\t\tif (canBreakAfter(seg.kind)) {\n\t\t\t\tlineEndSegment = i + 1;\n\t\t\t\tlineEndGrapheme = 0;\n\t\t\t\tconst endsAtSoftHyphen = seg.kind === \"soft-hyphen\";\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tendsAtSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: seg.kind === \"space\" ? lineW : lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (pendingBreakSegment >= 0) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tpendingBreakSegment,\n\t\t\t\t\tpendingBreakGrapheme,\n\t\t\t\t\tpendingBreakSoftHyphen,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: pendingBreakWidth + (pendingBreakSoftHyphen ? hyphenWidth : 0),\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: pendingBreakSegment, graphemeIndex: pendingBreakGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (w > slotWidth && seg.graphemeWidths) {\n\t\t\t\tconst text = buildLineText(\n\t\t\t\t\tsegments,\n\t\t\t\t\tstartSegment,\n\t\t\t\t\tstartGrapheme,\n\t\t\t\t\tlineEndSegment,\n\t\t\t\t\tlineEndGrapheme,\n\t\t\t\t\tfalse,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\ttext,\n\t\t\t\t\twidth: lineW,\n\t\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst text = buildLineText(\n\t\t\t\tsegments,\n\t\t\t\tstartSegment,\n\t\t\t\tstartGrapheme,\n\t\t\t\tlineEndSegment,\n\t\t\t\tlineEndGrapheme,\n\t\t\t\tfalse,\n\t\t\t\tsegmentAdapter,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\ttext,\n\t\t\t\twidth: lineW,\n\t\t\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\t\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t\t\t};\n\t\t}\n\t\tlineW = projectedWidth;\n\t\tlineEndSegment = i + 1;\n\t\tlineEndGrapheme = 0;\n\t\tif (canBreakAfter(seg.kind)) {\n\t\t\trecordPending(i + 1, 0, seg.kind === \"space\" ? lineW - w : lineW, seg.kind);\n\t\t}\n\t}\n\tif (!hasContent) return null;\n\tconst endsAtSoftHyphen =\n\t\tlineEndSegment > 0 && segments[lineEndSegment - 1]?.kind === \"soft-hyphen\";\n\tconst text = buildLineText(\n\t\tsegments,\n\t\tstartSegment,\n\t\tstartGrapheme,\n\t\tlineEndSegment,\n\t\tlineEndGrapheme,\n\t\tendsAtSoftHyphen,\n\t\tsegmentAdapter,\n\t);\n\treturn {\n\t\ttext,\n\t\twidth: lineW + (endsAtSoftHyphen ? hyphenWidth : 0),\n\t\tstart: { segmentIndex: startSegment, graphemeIndex: startGrapheme },\n\t\tend: { segmentIndex: lineEndSegment, graphemeIndex: lineEndGrapheme },\n\t};\n}\n\n/** Subtract obstacle intervals from a horizontal text band. */\nexport function carveTextLineSlots(\n\tbase: Interval,\n\tblocked: readonly Interval[],\n\tminSlotWidth = 0,\n): Interval[] {\n\tlet slots: Interval[] = [base];\n\tfor (const block of blocked) {\n\t\tconst next: Interval[] = [];\n\t\tfor (const slot of slots) {\n\t\t\tif (block.right <= slot.left || block.left >= slot.right) {\n\t\t\t\tnext.push(slot);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (block.left > slot.left) next.push({ left: slot.left, right: block.left });\n\t\t\tif (block.right < slot.right) next.push({ left: block.right, right: slot.right });\n\t\t}\n\t\tslots = next;\n\t}\n\tif (minSlotWidth > 0) return slots.filter((slot) => slot.right - slot.left >= minSlotWidth);\n\treturn slots;\n}\n\n/**\n * Compute per-grapheme boxes for already-broken lines.\n *\n * @param lineBreaks - Line break result whose cursors identify the visible grapheme ranges.\n * @param segments - Prepared segments used to produce the line breaks.\n * @param lineHeight - Height assigned to every line box.\n * @param segmentAdapter - Optional segmentation adapter; defaults to the built-in adapter.\n * @returns Character-position boxes in visual order, each with `x`, `y`, `width`, `height`, and\n * zero-based line index.\n * @example\n * ```ts\n * import {\n * analyzeAndMeasure,\n * computeCharPositions,\n * computeLineBreaks,\n * } from \"@graphrefly/ts/solutions/reactive-layout\";\n *\n * const segments = analyzeAndMeasure(\n * \"Hello world\",\n * \"16px system-ui\",\n * { measureSegment: (segment) => ({ width: segment.length * 8 }) },\n * new Map(),\n * );\n * const lineBreaks = computeLineBreaks(segments, 64);\n * const positions = computeCharPositions(lineBreaks, segments, 20);\n * ```\n * @remarks **Already measured:** Widths come from the prepared segments; this helper only maps the\n * line cursors into per-grapheme rectangles.\n * @category solutions\n */\nexport function computeCharPositions(\n\tlineBreaks: LineBreaksResult,\n\tsegments: readonly PreparedSegment[],\n\tlineHeight: number,\n\tsegmentAdapter?: SegmentAdapter,\n): readonly CharPosition[] {\n\tconst positions: CharPosition[] = [];\n\tconst segAdapter = segmentAdapter ?? getDefaultSegmentAdapter();\n\tfor (let lineIdx = 0; lineIdx < lineBreaks.lines.length; lineIdx += 1) {\n\t\tconst line = lineBreaks.lines[lineIdx];\n\t\tconst y = lineIdx * lineHeight;\n\t\tlet x = 0;\n\t\tfor (let si = line.startSegment; si < segments.length; si += 1) {\n\t\t\tconst seg = segments[si];\n\t\t\tif (seg.kind === \"soft-hyphen\" || seg.kind === \"hard-break\") {\n\t\t\t\tif (si >= line.endSegment && line.endGrapheme === 0) break;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst graphemes = [...segAdapter.segmentGraphemes(seg.text)].map((g) => g.segment);\n\t\t\tif (graphemes.length === 0) continue;\n\t\t\tconst startGrapheme = si === line.startSegment ? line.startGrapheme : 0;\n\t\t\tlet endGrapheme: number;\n\t\t\tif (si < line.endSegment) {\n\t\t\t\tendGrapheme = graphemes.length;\n\t\t\t} else if (si === line.endSegment && line.endGrapheme > 0) {\n\t\t\t\tendGrapheme = line.endGrapheme;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor (let g = startGrapheme; g < endGrapheme; g += 1) {\n\t\t\t\tconst width = seg.graphemeWidths ? seg.graphemeWidths[g] : seg.width / graphemes.length;\n\t\t\t\tpositions.push({ x, y, width, height: lineHeight, line: lineIdx });\n\t\t\t\tx += width;\n\t\t\t}\n\t\t}\n\t}\n\treturn positions;\n}\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated retired handle-dispatch PoC (R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/**\n * First-class dispatcher (D21). Owns pools; graph binds to one (default = process-global,\n * D26 — the only global singleton). Pool trait is pluggable for WorkerPool/RemotePool (D20).\n */\n/** Per-handle profiling counters (D39 / R-profile). Lives on the dispatcher — the invoke\n * funnel (F-DISPATCH-ALL) — NEVER on the thin node (R-node-thin). */\nexport interface HandleStat {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n}\n\nconst statKey = (h: Handle): string => `${h.poolId}:${h.handleId}`;\n\nexport class Dispatcher {\n\tprivate pools: Pool[] = [];\n\treadonly syncPoolId: number;\n\treadonly asyncPoolId: number;\n\n\t// opt-in profile recorder (default OFF → zero overhead, F-PERF).\n\tprivate _recording = false;\n\tprivate _stats = new Map<string, HandleStat>();\n\tprivate _totalInvokes = 0;\n\n\tconstructor() {\n\t\tthis.syncPoolId = this.addPool(new PoolTable(\"sync\"));\n\t\tthis.asyncPoolId = this.addPool(new PoolTable(\"async\"));\n\t}\n\n\t/** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */\n\tsetRecording(on: boolean): void {\n\t\tthis._recording = on;\n\t}\n\t/** Reset accumulated profiling counters. */\n\tclearStats(): void {\n\t\tthis._stats.clear();\n\t\tthis._totalInvokes = 0;\n\t}\n\t/** Read a handle's accumulated counters (undefined if it never ran while recording). */\n\tstatFor(handle: Handle): HandleStat | undefined {\n\t\treturn this._stats.get(statKey(handle));\n\t}\n\t/** Total fn invocations recorded across the dispatcher. */\n\tget totalInvokes(): number {\n\t\treturn this._totalInvokes;\n\t}\n\n\taddPool(pool: Pool): number {\n\t\tconst id = this.pools.length;\n\t\tthis.pools.push(pool);\n\t\treturn id;\n\t}\n\n\t/** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */\n\tregister(fn: NodeFn, pool: PoolKind | number = \"sync\"): Handle {\n\t\tconst poolId = pool === \"sync\" ? this.syncPoolId : pool === \"async\" ? this.asyncPoolId : pool;\n\t\tconst handleId = this.pools[poolId].register(fn);\n\t\treturn { poolId, handleId };\n\t}\n\n\t/**\n\t * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any\n\t * accumulated profile stat so a reused id never inherits the previous tenant's counters.\n\t * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node\n\t * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives\n\t * activate↔deactivate and is reused on reactivation; only a rewire swaps it).\n\t */\n\tunregister(handle: Handle): void {\n\t\tthis.pools[handle.poolId].unregister(handle.handleId);\n\t\t// Drop the stat UNCONDITIONALLY (QA F2.1), not only while recording: if recording was\n\t\t// OFF at unregister time the key would linger, and a later register reusing this id (the\n\t\t// free-list) would inherit the prior tenant's counters once recording resumes. delete of\n\t\t// an absent key is a cheap no-op; unregister is off the hot invoke path (F-PERF intact).\n\t\tthis._stats.delete(statKey(handle));\n\t}\n\n\t/** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */\n\tinvoke(handle: Handle, ctx: Ctx): void {\n\t\tif (!this._recording) {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t\treturn;\n\t\t}\n\t\tthis._totalInvokes++;\n\t\tconst t0 = performance.now();\n\t\ttry {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t} finally {\n\t\t\tconst dur = (performance.now() - t0) * 1e6; // ms → ns\n\t\t\tconst key = statKey(handle);\n\t\t\tconst s = this._stats.get(key) ?? {\n\t\t\t\tinvokes: 0,\n\t\t\t\ttotalDurationNs: 0,\n\t\t\t\tlastDurationNs: 0,\n\t\t\t};\n\t\t\ts.invokes++;\n\t\t\ts.lastDurationNs = dur;\n\t\t\ts.totalDurationNs += dur;\n\t\t\tthis._stats.set(key, s);\n\t\t}\n\t}\n\n\tpoolKind(poolId: number): PoolKind {\n\t\treturn this.pools[poolId].kind;\n\t}\n}\n\n/** The only global singleton (D26). Overridable by passing an explicit dispatcher. */\nexport const defaultDispatcher = new Dispatcher();\n","/**\n * Graph-owned environment driver bag (D130/D131).\n *\n * Drivers host process/network/messaging/runtime boundary work outside the synchronous wave core.\n * The bag is graph-local and is read from ctx by source/adapter bodies.\n */\n\nexport type DriverCancel = () => void;\n\nexport type DriverResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport interface ProcessCommand {\n\treadonly program: string;\n\treadonly args: readonly string[];\n\treadonly cwd?: string;\n\treadonly env?: readonly (readonly [string, string])[];\n}\n\nexport interface ProcessResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number | null;\n\treadonly signal: string | null;\n}\n\nexport interface HttpRequest {\n\treadonly method: string;\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n\treadonly body?: Uint8Array | string;\n}\n\nexport interface HttpResponse {\n\treadonly status: number;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport interface SseRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport interface SseEvent {\n\treadonly event?: string;\n\treadonly data: string;\n\treadonly id?: string;\n\treadonly retryMs?: number;\n}\n\nexport type SseDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: SseEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebSocketRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport type WebSocketEvent =\n\t| { readonly kind: \"open\" }\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\nexport interface WebSocketSend {\n\treadonly data: string | Uint8Array;\n}\n\nexport interface WebSocketSendResult {\n\treadonly sent: true;\n}\n\n/** Live WebSocket session handle for D133 SessionBundle adapters. */\nexport interface WebSocketSessionHandle {\n\tsend(\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\tclose(code?: number, reason?: string): void;\n\tcancel(): void;\n}\n\nexport type WebSocketDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebSocketEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebhookRegistration {\n\treadonly id: string;\n\treadonly method?: string;\n\treadonly path?: string;\n}\n\nexport interface WebhookEvent {\n\treadonly registrationId: string;\n\treadonly method: string;\n\treadonly path: string;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly query: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport type WebhookDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebhookEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface LocalProcessDriver {\n\trun(\n\t\tcommand: ProcessCommand,\n\t\tcallback: (result: DriverResult<ProcessResult>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalHttpDriver {\n\trequest(\n\t\trequest: HttpRequest,\n\t\tcallback: (result: DriverResult<HttpResponse>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalSseDriver {\n\tconnect(request: SseRequest, callback: (event: SseDriverEvent) => void): DriverCancel;\n}\n\nexport interface LocalWebSocketDriver {\n\tconnect(request: WebSocketRequest, callback: (event: WebSocketDriverEvent) => void): DriverCancel;\n\tsend?(\n\t\trequest: WebSocketRequest,\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\t/** Open a live bidirectional session; unlike send(), outbound messages use this same connection. */\n\tconnectSession?(\n\t\trequest: WebSocketRequest,\n\t\tcallback: (event: WebSocketDriverEvent) => void,\n\t): WebSocketSessionHandle;\n}\n\nexport interface LocalWebhookDriver {\n\tregister(\n\t\tregistration: WebhookRegistration,\n\t\tcallback: (event: WebhookDriverEvent) => void,\n\t): DriverCancel;\n}\n\nexport interface FetchResponseLike {\n\treadonly status: number;\n\treadonly headers?: { forEach?(fn: (value: string, key: string) => void): void };\n\tarrayBuffer(): PromiseLike<ArrayBuffer>;\n}\n\nexport type FetchLike = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: readonly (readonly [string, string])[];\n\t\treadonly body?: Uint8Array | string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => PromiseLike<FetchResponseLike>;\n\nexport interface WebSocketLike {\n\tsend(data: string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n\tremoveEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n}\n\nexport type WebSocketConstructorLike = new (url: string) => WebSocketLike;\n\nexport interface EnvironmentDriversInit {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n}\n\nexport class EnvironmentDrivers {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n\n\tconstructor(init: EnvironmentDriversInit = {}) {\n\t\tthis.process = init.process;\n\t\tthis.http = init.http;\n\t\tthis.sse = init.sse;\n\t\tthis.websocket = init.websocket;\n\t\tthis.webhook = init.webhook;\n\t\tObject.freeze(this);\n\t}\n\n\tstatic empty(): EnvironmentDrivers {\n\t\treturn EMPTY_ENVIRONMENT;\n\t}\n\n\twithProcess(driver: LocalProcessDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, process: driver });\n\t}\n\n\twithHttp(driver: LocalHttpDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, http: driver });\n\t}\n\n\twithSse(driver: LocalSseDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, sse: driver });\n\t}\n\n\twithWebSocket(driver: LocalWebSocketDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, websocket: driver });\n\t}\n\n\twithWebhook(driver: LocalWebhookDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, webhook: driver });\n\t}\n\n\tprocessDriver(): LocalProcessDriver | undefined {\n\t\treturn this.process;\n\t}\n\n\thttpDriver(): LocalHttpDriver | undefined {\n\t\treturn this.http;\n\t}\n\n\tsseDriver(): LocalSseDriver | undefined {\n\t\treturn this.sse;\n\t}\n\n\twebSocketDriver(): LocalWebSocketDriver | undefined {\n\t\treturn this.websocket;\n\t}\n\n\twebhookDriver(): LocalWebhookDriver | undefined {\n\t\treturn this.webhook;\n\t}\n}\n\nconst EMPTY_ENVIRONMENT = new EnvironmentDrivers();\n\nexport function fetchHttpDriver(fetchFn: FetchLike = requireGlobalFetch()): LocalHttpDriver {\n\treturn {\n\t\trequest(request, callback) {\n\t\t\tconst controller = new AbortController();\n\t\t\tvoid Promise.resolve(\n\t\t\t\tfetchFn(request.url, {\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\theaders: request.headers,\n\t\t\t\t\tbody: request.body,\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t}),\n\t\t\t).then(\n\t\t\t\tasync (response) => {\n\t\t\t\t\tconst headers: Array<readonly [string, string]> = [];\n\t\t\t\t\tresponse.headers?.forEach?.((value, key) => {\n\t\t\t\t\t\theaders.push([key, value]);\n\t\t\t\t\t});\n\t\t\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\tcallback({ ok: true, value: { status: response.status, headers, body } });\n\t\t\t\t},\n\t\t\t\t(error) => callback({ ok: false, error }),\n\t\t\t);\n\t\t\treturn () => controller.abort();\n\t\t},\n\t};\n}\n\nexport function domWebSocketDriver(\n\tWebSocketCtor: WebSocketConstructorLike = requireGlobalWebSocket(),\n): LocalWebSocketDriver {\n\treturn {\n\t\tconnect(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tsend(request, message, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet settled = false;\n\t\t\tconst finish = (result: DriverResult<WebSocketSendResult>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcallback(result);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t\tconst onOpen = () => {\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\tfinish({ ok: true, value: { sent: true } });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinish({ ok: false, error });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => finish({ ok: false, error: event });\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tconnectSession(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet active = true;\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tconst removeListeners = () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn {\n\t\t\t\tsend(message, sendCallback) {\n\t\t\t\t\tlet canceled = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: true, value: { sent: true } });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: false, error });\n\t\t\t\t\t}\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tclose(code, reason) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t},\n\t\t\t\tcancel() {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tactive = false;\n\t\t\t\t\tremoveListeners();\n\t\t\t\t\tsocket.close();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction requireGlobalFetch(): FetchLike {\n\tconst fetchFn = (globalThis as { fetch?: FetchLike }).fetch;\n\tif (fetchFn === undefined) throw new Error(\"fetchHttpDriver: global fetch is not available\");\n\treturn fetchFn;\n}\n\nfunction requireGlobalWebSocket(): WebSocketConstructorLike {\n\tconst ctor = (globalThis as { WebSocket?: WebSocketConstructorLike }).WebSocket;\n\tif (ctor === undefined) throw new Error(\"domWebSocketDriver: global WebSocket is not available\");\n\treturn ctor;\n}\n","import type { Ctx, Sink } from \"../ctx/types.js\";\nimport type { Dispatcher, Handle } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport { type LockId, type PullDemand, SENTINEL, type Wave } from \"../protocol/messages.js\";\nimport type { Node, Status } from \"./node.js\";\nimport type { NodeVersion, ResolvedNodeVersioningPolicy } from \"./versioning.js\";\n\nexport type NodeId = number & { readonly __nodeId: unique symbol };\n\nexport interface DepBookkeeping {\n\tbatch: Array<unknown[] | null>;\n\twaveData: unknown[][][];\n\twaveTokens: Array<object | undefined>;\n\tprev: unknown[];\n\thasData: boolean[];\n\tdirty: boolean[];\n\ttier: number[];\n\tterminal: Array<true | unknown | undefined>;\n\tterminalInput: Array<true | unknown | undefined>;\n\tunsubs: Array<() => void>;\n\tidxBoxes: Array<{ v: number }>;\n}\n\nexport interface ValueState<T> {\n\tcache: T | undefined;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasTorndown: boolean;\n\treplayRing: T[];\n}\n\nexport interface VersionState {\n\tpolicy: ResolvedNodeVersioningPolicy;\n\tvalue: NodeVersion | undefined;\n}\n\nexport interface WaveState {\n\tpending: number;\n\thasCalledFnOnce: boolean;\n\temittedDirtyThisWave: boolean;\n\temittedSettleThisWave: boolean;\n\tinsideRunWave: boolean;\n\tinDepMutation: boolean;\n\trewireRunPending: boolean;\n\tbatchDirtyOwed: boolean;\n}\n\nexport interface ControlState {\n\tpauseLockset: Set<unknown>;\n\tpausedDepWaveOccurred: boolean;\n\tpauseBuffer: Wave[];\n\tdemandOwed: PullDemand | undefined;\n\tactivePull: PullDemand | undefined;\n\tpullDirtyOwed: boolean;\n\tinDeliverDemand: boolean;\n}\n\nexport interface PrivateState {\n\tvalue: unknown;\n\tpersist: boolean;\n}\n\nexport interface CleanupHooks {\n\tonDeactivation: Array<() => void>;\n\tonInvalidate: Array<() => void>;\n}\n\nexport interface SyncCtxState {\n\tvalue: Ctx | null;\n}\n\nexport interface LifecycleState {\n\tsubscribers: Set<Sink>;\n\tactivated: boolean;\n}\n\nexport interface BoundaryTask {\n\tapply: () => void;\n\tbatchToken?: object;\n\tisReady?: () => boolean;\n}\n\nexport interface BoundaryState {\n\tqueue: BoundaryTask[];\n\thead: number;\n}\n\nexport interface NodeSlot<_T> {\n\tid: NodeId;\n\tdeps: Node<unknown>[];\n\thandle: Handle | null;\n\tpool: \"sync\" | \"async\";\n\tdispatcher: Dispatcher;\n\tenvironment: EnvironmentDrivers;\n\tpartial: boolean;\n\tterminalAsRealInput: boolean;\n\tcompleteWhenDepsComplete: boolean;\n\terrorWhenDepsError: boolean;\n\tresubscribable: boolean;\n\tresetOnTeardown: boolean;\n\tpausable: boolean | \"resumeAll\";\n\tpull: boolean;\n\tpullLock: LockId | undefined;\n\treplayN: number;\n\tdynamic: boolean;\n\tname?: string;\n\tfactory?: string;\n}\n\nexport interface NodeState<T> {\n\tdep: DepBookkeeping;\n\tlifecycle: LifecycleState;\n\tvalue: ValueState<T>;\n\tversion: VersionState;\n\twave: WaveState;\n\tcontrol: ControlState;\n\tprivateState: PrivateState;\n\thooks: CleanupHooks;\n\tsyncCtx: SyncCtxState;\n}\n\nexport class NodeCore {\n\tprivate nextId = 0;\n\tprivate readonly slots: Array<NodeSlot<unknown> | undefined> = [];\n\tprivate readonly values: Array<ValueState<unknown> | undefined> = [];\n\tprivate readonly waves: Array<WaveState | undefined> = [];\n\tprivate readonly controls: Array<ControlState | undefined> = [];\n\tprivate readonly lifecycles: Array<LifecycleState | undefined> = [];\n\tprivate readonly depStates: Array<DepBookkeeping | undefined> = [];\n\tprivate readonly privateStates: Array<PrivateState | undefined> = [];\n\tprivate readonly hooks: Array<CleanupHooks | undefined> = [];\n\tprivate readonly syncCtxs: Array<SyncCtxState | undefined> = [];\n\tprivate readonly versionStates: Array<VersionState | undefined> = [];\n\tprivate readonly boundary: BoundaryState = { queue: [], head: 0 };\n\n\tcreateSlot<T>(\n\t\tslot: Omit<NodeSlot<T>, \"id\">,\n\t\tstate: NodeState<T>,\n\t): { id: NodeId; slot: NodeSlot<T> } {\n\t\tconst id = this.nextId++ as NodeId;\n\t\tconst full = { ...slot, id };\n\t\tthis.slots[id] = full as NodeSlot<unknown>;\n\t\tthis.depStates[id] = state.dep;\n\t\tthis.lifecycles[id] = state.lifecycle;\n\t\tthis.values[id] = state.value as ValueState<unknown>;\n\t\tthis.waves[id] = state.wave;\n\t\tthis.controls[id] = state.control;\n\t\tthis.privateStates[id] = state.privateState;\n\t\tthis.hooks[id] = state.hooks;\n\t\tthis.syncCtxs[id] = state.syncCtx;\n\t\tthis.versionStates[id] = state.version;\n\t\treturn { id, slot: full };\n\t}\n\n\tget<T>(id: NodeId): NodeSlot<T> {\n\t\tconst slot = this.slots[id];\n\t\tif (slot === undefined) throw new Error(\"NodeCore: unknown node slot\");\n\t\treturn slot as NodeSlot<T>;\n\t}\n\n\tgetValue<T>(id: NodeId): ValueState<T> {\n\t\tconst value = this.values[id];\n\t\tif (value === undefined) throw new Error(\"NodeCore: unknown node value state\");\n\t\treturn value as ValueState<T>;\n\t}\n\n\tgetWave(id: NodeId): WaveState {\n\t\tconst wave = this.waves[id];\n\t\tif (wave === undefined) throw new Error(\"NodeCore: unknown node wave state\");\n\t\treturn wave;\n\t}\n\n\tgetControl(id: NodeId): ControlState {\n\t\tconst control = this.controls[id];\n\t\tif (control === undefined) throw new Error(\"NodeCore: unknown node control state\");\n\t\treturn control;\n\t}\n\n\tgetLifecycle(id: NodeId): LifecycleState {\n\t\tconst lifecycle = this.lifecycles[id];\n\t\tif (lifecycle === undefined) throw new Error(\"NodeCore: unknown node lifecycle state\");\n\t\treturn lifecycle;\n\t}\n\n\tgetDep(id: NodeId): DepBookkeeping {\n\t\tconst dep = this.depStates[id];\n\t\tif (dep === undefined) throw new Error(\"NodeCore: unknown node dep state\");\n\t\treturn dep;\n\t}\n\n\tgetPrivateState(id: NodeId): PrivateState {\n\t\tconst state = this.privateStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node private state\");\n\t\treturn state;\n\t}\n\n\tgetHooks(id: NodeId): CleanupHooks {\n\t\tconst hooks = this.hooks[id];\n\t\tif (hooks === undefined) throw new Error(\"NodeCore: unknown node cleanup hooks\");\n\t\treturn hooks;\n\t}\n\n\tgetSyncCtx(id: NodeId): SyncCtxState {\n\t\tconst state = this.syncCtxs[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node ctx state\");\n\t\treturn state;\n\t}\n\n\tgetVersion(id: NodeId): VersionState {\n\t\tconst state = this.versionStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node version state\");\n\t\treturn state;\n\t}\n\n\t/** @internal D122: release graph-owned ephemeral node runtime state from core retention. */\n\treleaseSlot(id: NodeId): void {\n\t\tthis.slots[id] = undefined;\n\t\tthis.depStates[id] = undefined;\n\t\tthis.lifecycles[id] = undefined;\n\t\tthis.values[id] = undefined;\n\t\tthis.waves[id] = undefined;\n\t\tthis.controls[id] = undefined;\n\t\tthis.privateStates[id] = undefined;\n\t\tthis.hooks[id] = undefined;\n\t\tthis.syncCtxs[id] = undefined;\n\t\tthis.versionStates[id] = undefined;\n\t}\n\n\t/** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */\n\tenqueueBoundaryTask(task: BoundaryTask): void {\n\t\tthis.boundary.queue.push(task);\n\t}\n\n\t/** @internal */\n\thasBoundaryTasks(): boolean {\n\t\treturn this.boundary.head < this.boundary.queue.length;\n\t}\n\n\t/** @internal */\n\tboundaryTaskCount(): number {\n\t\treturn this.boundary.queue.length - this.boundary.head;\n\t}\n\n\t/** @internal */\n\tshiftBoundaryTask(): BoundaryTask | undefined {\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst task = this.boundary.queue[this.boundary.head++];\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** @internal Put a not-yet-ready task back at this core's FIFO head. */\n\tunshiftBoundaryTask(task: BoundaryTask): void {\n\t\tconst remaining = this.boundary.queue.slice(this.boundary.head);\n\t\tthis.boundary.queue = [task, ...remaining];\n\t\tthis.boundary.head = 0;\n\t}\n\n\t/** @internal D110: discard all pending tasks caused by an uncommitted batch. */\n\tdropBoundaryTasksForBatch(batchToken: object): void {\n\t\tconst remaining = this.boundary.queue\n\t\t\t.slice(this.boundary.head)\n\t\t\t.filter((task) => task.batchToken !== batchToken);\n\t\tthis.boundary.queue = remaining;\n\t\tthis.boundary.head = 0;\n\t}\n}\n\nexport function makeDepBookkeeping(depCount: number): DepBookkeeping {\n\treturn {\n\t\tbatch: new Array(depCount).fill(null),\n\t\twaveData: Array.from({ length: depCount }, () => []),\n\t\twaveTokens: new Array(depCount).fill(undefined),\n\t\tprev: new Array(depCount).fill(SENTINEL),\n\t\thasData: new Array(depCount).fill(false),\n\t\tdirty: new Array(depCount).fill(false),\n\t\ttier: new Array(depCount).fill(0),\n\t\tterminal: new Array(depCount).fill(undefined),\n\t\tterminalInput: new Array(depCount).fill(undefined),\n\t\tunsubs: [],\n\t\tidxBoxes: [],\n\t};\n}\n","import { isInvalidErrorPayload, type PullDemand, type Wave } from \"../protocol/messages.js\";\n\nexport function terminalView(t: unknown): unknown {\n\treturn t === undefined ? false : t;\n}\n\nexport function normalizePullDemand(demand: PullDemand): PullDemand {\n\tif (typeof demand !== \"object\" || demand === null || Array.isArray(demand)) {\n\t\tthrow new Error(\"ctx.up: PULL requires { pullId, params? } demand payload (D269)\");\n\t}\n\tconst pullId = (demand as { pullId?: unknown }).pullId;\n\tif (typeof pullId !== \"string\" && typeof pullId !== \"symbol\") {\n\t\tthrow new Error(\"ctx.up: PULL demand requires a string or symbol pullId (D269)\");\n\t}\n\tconst params = (demand as { params?: unknown }).params;\n\treturn params === undefined ? { pullId } : { pullId, params };\n}\n\nexport function validateDownPayloads(msgs: Wave): void {\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"DATA\" && m[1] === undefined) {\n\t\t\tthrow new Error(\"down: DATA requires a non-SENTINEL payload (R-data-payload)\");\n\t\t}\n\t\tif (m[0] === \"ERROR\" && isInvalidErrorPayload(m[1])) {\n\t\t\tthrow new Error(\"down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)\");\n\t\t}\n\t}\n}\n","import type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { NodeCore } from \"./core.js\";\nimport type { Node } from \"./node.js\";\nimport type { NodeCheckpointState, NodeRestoreState } from \"./types.js\";\n\ntype TopologyDepsChangedObserver = (\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n) => void;\n\nlet constructingCore: NodeCore | undefined;\nlet constructingEnvironment: EnvironmentDrivers | undefined;\nexport const ownerTokens = new WeakMap<Node<unknown>, unknown>();\nexport const topologyDepsChangedObservers = new WeakMap<\n\tNode<unknown>,\n\tTopologyDepsChangedObserver\n>();\nexport const checkpointReaders = new WeakMap<Node<unknown>, () => NodeCheckpointState>();\nexport const restoreWriters = new WeakMap<Node<unknown>, (state: NodeRestoreState) => void>();\nexport const runtimeReleasers = new WeakMap<Node<unknown>, () => void>();\nexport const runtimeQuiescenceReaders = new WeakMap<Node<unknown>, () => boolean>();\nexport const subscriberCountReaders = new WeakMap<Node<unknown>, () => number>();\nexport const activationReaders = new WeakMap<Node<unknown>, () => boolean>();\nexport const releasedNodes = new WeakSet<Node<unknown>>();\n\n/** @internal Run a Node/StateNode constructor against a graph-local core without widening the public constructor. */\nexport function withNodeCore<TNode extends Node<unknown>>(\n\tcore: NodeCore,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingCore;\n\tconstructingCore = core;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingCore = prev;\n\t}\n}\n\n/** @internal Consume the graph-local NodeCore staged by withNodeCore. */\nexport function takeConstructingNodeCore(): NodeCore | undefined {\n\tconst core = constructingCore;\n\tconstructingCore = undefined;\n\treturn core;\n}\n\n/** @internal Run a Node/StateNode constructor with graph-owned environment drivers (D130/D131). */\nexport function withEnvironmentDrivers<TNode extends Node<unknown>>(\n\tenvironment: EnvironmentDrivers,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingEnvironment;\n\tconstructingEnvironment = environment;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingEnvironment = prev;\n\t}\n}\n\n/** @internal Consume graph-owned environment drivers staged by withEnvironmentDrivers. */\nexport function takeConstructingEnvironmentDrivers(): EnvironmentDrivers | undefined {\n\tconst environment = constructingEnvironment;\n\tconstructingEnvironment = undefined;\n\treturn environment;\n}\n\n/** @internal Graph-domain ownership token for D22 intra-graph guards. */\nexport function getNodeOwner(n: Node<unknown>): unknown {\n\treturn ownerTokens.get(n);\n}\n\n/** @internal Assign graph-domain ownership after graph registration. */\nexport function setNodeOwner(n: Node<unknown>, owner: unknown): void {\n\townerTokens.set(n, owner);\n}\n\n/** @internal Graph-layer D145 topology egress hook. */\nexport function setNodeTopologyDepsChangedObserver(\n\tn: Node<unknown>,\n\tobserver: TopologyDepsChangedObserver,\n): void {\n\ttopologyDepsChangedObservers.set(n, observer);\n}\n\nexport function notifyTopologyDepsChanged(\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n): void {\n\ttopologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);\n}\n\n/** @internal Graph checkpoint inspection, kept as a module helper so Node stays method-thin. */\nexport function checkpointStateOfNode(n: Node<unknown>): NodeCheckpointState {\n\tconst read = checkpointReaders.get(n);\n\tif (read === undefined) throw new Error(\"checkpoint: unknown node state\");\n\treturn read();\n}\n\n/** @internal D94 restore commit: install runtime state without a protocol wave or subscription. */\nexport function restoreStateOfNode(n: Node<unknown>, state: NodeRestoreState): void {\n\tconst write = restoreWriters.get(n);\n\tif (write === undefined) throw new Error(\"restoreGraph: unknown node state\");\n\twrite(state);\n}\n\n/** @internal D122 graph-owned ephemeral lifecycle release. */\nexport function releaseRuntimeOfNode(n: Node<unknown>): void {\n\truntimeReleasers.get(n)?.();\n}\n\n/** @internal D124 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeQuiescentForRelease(n: Node<unknown>): boolean {\n\treturn runtimeQuiescenceReaders.get(n)?.() ?? false;\n}\n\n/** @internal D124 graph-owned release subscriber accounting. */\nexport function subscriberCountOfNode(n: Node<unknown>): number {\n\treturn subscriberCountReaders.get(n)?.() ?? 0;\n}\n\n/** @internal D124 graph-owned release internal-subscriber accounting. */\nexport function isNodeActiveForRelease(n: Node<unknown>): boolean {\n\treturn activationReaders.get(n)?.() ?? false;\n}\n\n/** @internal D122 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeReleased(n: Node<unknown>): boolean {\n\treturn releasedNodes.has(n);\n}\n","import { enterWave, exitWave } from \"../batch/boundary.js\";\nimport {\n\tCTX_DEP_CACHE,\n\tCTX_NODE_BINDING,\n\ttype Ctx,\n\ttype CtxState,\n\ttype TerminalData,\n\ttype WaveData,\n} from \"../ctx/types.js\";\nimport type { PullDemand } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport type { NodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { terminalView } from \"./protocol-guards.js\";\nimport { withEnvironmentDrivers, withNodeCore } from \"./runtime-accessors.js\";\n\nexport function nodeBuildCtx<T>(self: NodeRuntimeHost<T>): Ctx {\n\tconst kind = self._slot.handle\n\t\t? self._slot.dispatcher.poolKind(self._slot.handle.poolId)\n\t\t: \"sync\";\n\tif (kind === \"sync\") {\n\t\tif (self._syncCtx === null) self._syncCtx = self._makeCtx();\n\t\tself._refreshCtx(self._syncCtx);\n\t\treturn self._syncCtx;\n\t}\n\t// async: snapshot dep inputs so a deferred late-emit reads this wave's view.\n\treturn self._makeCtx({\n\t\twaveData: self._dep.waveData.map((waves) => waves.map((w) => [...w])),\n\t\tterminal: self._dep.terminalInput.map(terminalView),\n\t\tlatest: [...self._dep.prev],\n\t});\n}\n\nexport function nodeMakeCtx<T>(\n\tself: NodeRuntimeHost<T>,\n\tsnapshot?: { waveData: unknown[][][]; terminal: unknown[]; latest: unknown[] },\n): Ctx {\n\tconst ctx: Ctx = {\n\t\t// Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove\n\t\t// it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed\n\t\t// ctx at depth 0, so this is the boundary that drains any rewireNext it issued.\n\t\tup: (msgs, towardDep) => {\n\t\t\tif (self._released) return;\n\t\t\tenterWave();\n\t\t\ttry {\n\t\t\t\tself._up(msgs, towardDep);\n\t\t\t} finally {\n\t\t\t\texitWave();\n\t\t\t}\n\t\t},\n\t\tdown: (msgs) => {\n\t\t\tif (self._released) return;\n\t\t\tenterWave();\n\t\t\ttry {\n\t\t\t\tself._down(msgs);\n\t\t\t} finally {\n\t\t\t\texitWave();\n\t\t\t}\n\t\t},\n\t\twaveData: snapshot?.waveData ?? self._dep.waveData,\n\t\tterminal: snapshot?.terminal ?? self._dep.terminalInput.map(terminalView),\n\t\tstate: self._makeState(),\n\t\tonDeactivation: (fn) => {\n\t\t\tif (self._released) return;\n\t\t\tself._hooks.onDeactivation.push(fn);\n\t\t},\n\t\tonInvalidate: (fn) => {\n\t\t\tif (self._released) return;\n\t\t\tself._hooks.onInvalidate.push(fn);\n\t\t},\n\t\tenvironment: () => self._slot.environment,\n\t\t// R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.\n\t\trewireNext: {\n\t\t\tsubscribeDep: (dep, fn) => self._requestRewireNext({ kind: \"add\", dep, fn }),\n\t\t\tunsubscribeDep: (dep, fn) => self._requestRewireNext({ kind: \"remove\", dep, fn }),\n\t\t\treplaceDeps: (deps, fn) => self._requestRewireNext({ kind: \"set\", deps, fn }),\n\t\t},\n\t\t// R-up-routing / R-pull (D269): deferred up — route a control/demand wave (e.g. PULL)\n\t\t// up the declared cone at the committed boundary. The SELF-demand path: an\n\t\t// immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).\n\t\tupNext: (msgs, towardDep) => self._requestUpNext(msgs, towardDep),\n\t\t...(self._control.activePull === undefined ? {} : { pull: self._control.activePull }),\n\t\t[CTX_DEP_CACHE]: { latest: snapshot?.latest ?? self._dep.prev },\n\t\t[CTX_NODE_BINDING]: {\n\t\t\tdispatcher: self._slot.dispatcher,\n\t\t\tcreate: <U>(factory: () => Node<U>) =>\n\t\t\t\twithEnvironmentDrivers(self._slot.environment, () => withNodeCore(self._core, factory)),\n\t\t},\n\t};\n\tif (self._slot.dynamic) {\n\t\t// R-dynamic-node: read a dep's latest by index. Untracked deps still drive waves and\n\t\t// re-run the fn; under D49 (no equals-substitution) the fn re-emits its current value\n\t\t// as DATA — to suppress redundant downstream propagation, pair with distinctUntilChanged.\n\t\tctx.track = (i: number) => ctx[CTX_DEP_CACHE]?.latest[i];\n\t}\n\treturn ctx;\n}\n\nexport function nodeRefreshCtx<T>(self: NodeRuntimeHost<T>, ctx: Ctx): void {\n\t(ctx as { waveData: WaveData }).waveData = self._dep.waveData;\n\t(ctx as { terminal: TerminalData }).terminal = self._dep.terminalInput.map(terminalView);\n\tif (self._control.activePull === undefined) {\n\t\tdelete (ctx as { pull?: PullDemand }).pull;\n\t} else {\n\t\t(ctx as { pull?: PullDemand }).pull = self._control.activePull;\n\t}\n\tctx[CTX_DEP_CACHE] = { latest: self._dep.prev };\n}\n\nexport function nodeMakeState<T>(self: NodeRuntimeHost<T>): CtxState {\n\treturn {\n\t\tget: <S>() => self._privateState.value as S | undefined,\n\t\tset: <S>(v: S) => {\n\t\t\tself._privateState.value = v;\n\t\t},\n\t\tpersist: (on = true) => {\n\t\t\tself._privateState.persist = on;\n\t\t},\n\t};\n}\n","import type { DeliveryMeta } from \"../ctx/types.js\";\nimport type { Handle } from \"../dispatcher/index.js\";\nimport type { Message } from \"../protocol/messages.js\";\nimport { isTerminal, SENTINEL } from \"../protocol/messages.js\";\nimport type { NodeRuntimeHost } from \"./node-runtime-host.js\";\n\nexport function nodeRecordDepProjection<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tdelivery: DeliveryMeta | undefined,\n): unknown[] {\n\tconst token = delivery?.wave ?? {};\n\tif (self._dep.waveTokens[idx] !== token) {\n\t\tself._dep.waveData[idx].push([]);\n\t\tself._dep.waveTokens[idx] = token;\n\t}\n\treturn self._dep.waveData[idx][self._dep.waveData[idx].length - 1];\n}\n\nexport function nodeDepProjectionHasData<T>(self: NodeRuntimeHost<T>, idx: number): boolean {\n\tconst projection = self._dep.waveData[idx][self._dep.waveData[idx].length - 1];\n\treturn projection?.some((v) => v !== SENTINEL) ?? false;\n}\n\nexport function nodeReceiveFromDep<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tmsg: Message,\n\tdelivery?: DeliveryMeta,\n): void {\n\tif (self._released) return;\n\tconst t = msg[0];\n\tif (t === \"START\") return;\n\tconst isLastInDeliveredWave = delivery?.last ?? true;\n\t// Terminal-is-forever, except terminal intermediates still relay upstream TEARDOWN\n\t// downstream for lifecycle unwire (R-teardown-terminal-relay / D65).\n\tif (self._value.terminal !== undefined) {\n\t\tif (t === \"TEARDOWN\") self._down([[\"TEARDOWN\"]]);\n\t\treturn;\n\t}\n\n\tif (t === \"INVALIDATE\") {\n\t\tconst projection = self._recordDepProjection(idx, delivery);\n\t\tprojection.push(SENTINEL);\n\t\tif (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) self._maybeRun();\n\t\t// The dep's value is gone — drop our cached latest view to SENTINEL so the\n\t\t// never-emitted detector reads correctly, C-3) and cascade (idempotent).\n\t\tself._dep.prev[idx] = SENTINEL;\n\t\tself._dep.hasData[idx] = false;\n\t\tself._dep.batch[idx] = null;\n\t\t// EC3: un-wedge the dirty bookkeeping if this dep had gone DIRTY first, so an\n\t\t// INVALIDATE-before-DATA doesn't strand _pending / downstream forever\n\t\t// (R-invalidate-idempotent — exists to prevent the wedged-DIRTY deadlock).\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\t// D50 / R-paused-invalidate: this INVALIDATE SUPERSEDES the dep's buffered\n\t\t// paused dep-wave (_depBatch[idx] just cleared). Re-derive the paused-recompute\n\t\t// flag — if no dep still carries a buffered DATA, CANCEL the paused recompute\n\t\t// (attributed cancellation; the node has settled to SENTINEL via its own\n\t\t// INVALIDATE, so a RESUME must not recompute against a now-SENTINEL dep). A\n\t\t// surviving dep keeps it set; a later DATA re-arms it ([DATA,INVALIDATE,DATA2]).\n\t\tif (self._control.pausedDepWaveOccurred && self._dep.batch.every((b) => b === null)) {\n\t\t\tself._control.pausedDepWaveOccurred = false;\n\t\t}\n\t\tconst hadData = self._value.hasData;\n\t\tself._invalidate(); // cascades INVALIDATE iff populated; no-op otherwise\n\t\t// If we broadcast DIRTY this wave but _invalidate produced no settle (the node\n\t\t// was never populated, so the cascade is suppressed per the rule), un-dirty\n\t\t// downstream with a RESOLVED once all deps have settled.\n\t\tif (self._wave.pending === 0 && self._wave.emittedDirtyThisWave) {\n\t\t\tif (!hadData) self._down([[\"RESOLVED\"]]);\n\t\t\telse self._wave.emittedDirtyThisWave = false;\n\t\t}\n\t\tself._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): an INVALIDATE settle can drain _pending → fire a deferred demand\n\t\treturn;\n\t}\n\n\tif (isTerminal(t)) {\n\t\t// Tier 5 (R-tier / D34): COMPLETE | ERROR — ONE branch routed by the CENTRAL tier table,\n\t\t// not a per-variant string check (feedback_use_tier_for_signal_routing). The shared terminal\n\t\t// bookkeeping (record the terminal + release the in-wave DIRTY) runs for ANY tier-5 message;\n\t\t// only the COMPLETE-vs-ERROR cascade differs, so discriminate by the type within the tier.\n\t\tconst isError = t === \"ERROR\";\n\t\tconst errPayload = isError ? (msg as readonly [\"ERROR\", unknown])[1] : undefined;\n\t\tself._dep.terminal[idx] = isError ? errPayload : true;\n\t\tself._dep.terminalInput[idx] = isError ? errPayload : true;\n\t\t// R-terminal-settles-dirty (B35): a terminal RELEASES this dep's outstanding in-wave DIRTY\n\t\t// contribution (the exactly-one-settle invariant) — exactly as DATA/RESOLVED/INVALIDATE do\n\t\t// (a dirty-then-terminal-without-DATA dep would otherwise strand _pending and wedge the node,\n\t\t// the deadlock R-invalidate-idempotent prevents for INVALIDATE).\n\t\tself._releaseDepDirty(idx);\n\t\tconst ranValueBeforeTerminal = self._depProjectionHasData(idx) && isLastInDeliveredWave;\n\t\tif (ranValueBeforeTerminal) self._maybeRun();\n\t\tif (isError && self._slot.errorWhenDepsError) {\n\t\t\tself._down([[\"ERROR\", errPayload]]); // auto-cascade ERROR → node itself terminal\n\t\t} else if (self._slot.terminalAsRealInput) {\n\t\t\tif (ranValueBeforeTerminal) {\n\t\t\t\tself._fireOwedDemandIfReady();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tself._maybeRun(); // rescue/reduce/catch/*Map: the fn reads depTerminal(ctx, idx)\n\t\t} else if (self._slot.completeWhenDepsComplete && self._allDepsTerminal()) {\n\t\t\t// R-deps-terminal auto-COMPLETE + B42: COMPLETE once ALL deps are TERMINAL (each COMPLETE\n\t\t\t// or an absorbed ERROR) — so an absorbed-error dep terminating LAST still fires the\n\t\t\t// cascade. terminalAsRealInput is checked FIRST so a rescue recovers via _maybeRun rather\n\t\t\t// than being preempted (no operator sets both completeWhenDepsComplete:true + tari:true).\n\t\t\tself._down([[\"COMPLETE\"]]);\n\t\t} else {\n\t\t\t// absorbed terminal, NOT an input + not auto-completing: the dep's signalled change did\n\t\t\t// not materialise (no DATA) → un-dirty downstream, keep cache (R-resolved-undirty balance).\n\t\t\tself._settleAfterAbsorbedTerminal();\n\t\t}\n\t\tself._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): a dep terminal can drain _pending → fire a deferred demand (no-op if this node went terminal)\n\t\treturn;\n\t}\n\n\tif (t === \"TEARDOWN\") {\n\t\tself._down([[\"TEARDOWN\"]]);\n\t\treturn;\n\t}\n\n\tif (t === \"DIRTY\") {\n\t\tif (!self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = true;\n\t\t\tself._wave.pending++;\n\t\t\tself._dep.tier[idx] = 2;\n\t\t\tself._markDirty();\n\t\t}\n\t\treturn;\n\t}\n\n\tif (t === \"DATA\") {\n\t\tconst v = msg[1];\n\t\tself._recordDepProjection(idx, delivery).push(v);\n\t\tconst b = self._dep.batch[idx];\n\t\tif (b === null) self._dep.batch[idx] = [v];\n\t\telse b.push(v);\n\t\tself._dep.prev[idx] = v;\n\t\tself._dep.hasData[idx] = true;\n\t\tself._dep.tier[idx] = 3;\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\tif (isLastInDeliveredWave) self._maybeRun();\n\t\tself._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\treturn;\n\t}\n\n\tif (t === \"RESOLVED\") {\n\t\tself._recordDepProjection(idx, delivery);\n\t\tself._dep.tier[idx] = 3;\n\t\tif (self._dep.dirty[idx]) {\n\t\t\tself._dep.dirty[idx] = false;\n\t\t\tself._wave.pending--;\n\t\t}\n\t\tif (isLastInDeliveredWave) self._maybeRun();\n\t\tself._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\treturn;\n\t}\n\t// PAUSE / RESUME are not delivered downstream to a dep-subscriber; a node is\n\t// paused via its own up() (lockset), not by an upstream dep.\n}\n\nexport function nodeReleaseDepDirty<T>(self: NodeRuntimeHost<T>, idx: number): void {\n\tif (self._dep.dirty[idx]) {\n\t\tself._dep.dirty[idx] = false;\n\t\tself._wave.pending--;\n\t}\n}\n\nexport function nodeSettleAfterAbsorbedTerminal<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._wave.pending !== 0 || !self._wave.emittedDirtyThisWave) return;\n\t// A real value occurred this wave (some OTHER dep delivered DATA) → recompute. _maybeRun\n\t// runs the fn ONLY if it's not gated (first-run gate open, not paused); it may emit DATA, a\n\t// fn-synthesized undirty RESOLVED, or nothing (gated / gate still holds).\n\tconst sawData = self._dep.batch.some((b) => b !== null && b.length > 0);\n\tif (sawData) self._maybeRun();\n\t// If after that the node STILL owes a downstream settle (no DATA occurred, OR the recompute\n\t// was gated — e.g. the first-run gate holds because the terminated dep never delivered and\n\t// terminalAsRealInput is false), balance the broadcast DIRTY with one undirty RESOLVED\n\t// (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t// Without this fallback a DIRTY-then-terminal-without-DATA dep on a pre-first-run multi-dep\n\t// node would strand the DIRTY → downstream wedged (the B35 class, in the gate-holds corner).\n\tif (self._wave.emittedDirtyThisWave) self._down([[\"RESOLVED\"]]);\n}\n\nexport function nodeMarkDirty<T>(self: NodeRuntimeHost<T>): void {\n\tself._value.status = \"dirty\";\n\t// SPIKE (protocol-pull): while quiet, ABSORB the upstream DIRTY — do NOT relay it downstream.\n\t// This is the P0b wedge fix: a quiet pull node that relayed DIRTY but withheld the settle\n\t// (coalesced by pause) wedged every downstream's two-phase _pending. The downstream learns of\n\t// changes via the push STREAM port, not the silent snapshot port; on demand the pull node\n\t// emits a fresh wave. Internal dep dirty-accounting (the DIRTY-branch _pending++) is untouched.\n\tif (self._isPullQuiet()) return;\n\tif (!self._wave.emittedDirtyThisWave) {\n\t\tself._wave.emittedDirtyThisWave = true;\n\t\tself._emitToSubs([\"DIRTY\"]);\n\t}\n}\n\nexport function nodeMaybeRun<T>(self: NodeRuntimeHost<T>): void {\n\t// R-rewire: an added cached dep's push-on-subscribe lands here mid-mutation. Defer\n\t// the fn-run to ONE atomic two-phase settle after every added dep is wired, so the\n\t// fn never fires on a partially-populated added-dep view (multi-add) — _settleRewire\n\t// drains this flag.\n\tif (self._wave.inDepMutation) {\n\t\tself._wave.rewireRunPending = true;\n\t\treturn;\n\t}\n\t// R-pause-modes + R-pull: while externally paused or pull-quiet, default pull mode\n\t// coalesces. `resumeAll` still runs so its outgoing settle slice can enter pauseBuffer.\n\tif (self._slot.pausable === true && (self._isPaused() || self._isPullQuiet())) {\n\t\tself._control.pausedDepWaveOccurred = true;\n\t\treturn;\n\t}\n\tself._tryRun();\n}\n\nexport function nodeSettleRewire<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._slot.pausable === true && self._isPaused()) {\n\t\tself._control.pausedDepWaveOccurred = true;\n\t\treturn;\n\t}\n\tif (self._wave.pending > 0) return;\n\tif (self._slot.handle === null) {\n\t\tself._passthroughEmit();\n\t\treturn;\n\t}\n\tif (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;\n\tself._markDirty(); // phase 1 (no-op if already dirty, e.g. unsubscribeDep auto-settle)\n\tself._runWave(); // phase 2: fn → DATA/RESOLVED\n}\n\nexport function nodeTryRun<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._wave.pending > 0) return;\n\tif (self._slot.handle === null) {\n\t\t// Passthrough wire (deps, no fn): forward the latest dep DATA downstream.\n\t\tself._passthroughEmit();\n\t\treturn;\n\t}\n\tif (!self._wave.hasCalledFnOnce) {\n\t\tif (self._slot.partial || self._allDepsSettled()) self._runWave();\n\t\t// else: first-run gate holds fn until every dep has settled (R-first-run-gate).\n\t\treturn;\n\t}\n\tself._runWave();\n}\n\nexport function nodeAllDepsSettled<T>(self: NodeRuntimeHost<T>): boolean {\n\tfor (let i = 0; i < self._slot.deps.length; i++) {\n\t\tif (self._dep.hasData[i]) continue;\n\t\tif (self._slot.terminalAsRealInput && self._dep.terminal[i] !== undefined) continue;\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function nodePassthroughEmit<T>(self: NodeRuntimeHost<T>): void {\n\t// Single-dep wire: relay dep 0's latest batch value as DATA.\n\tconst b = self._dep.batch[0];\n\tif (b !== null && b.length > 0) {\n\t\tself._down([[\"DATA\", b[b.length - 1]]]);\n\t} else if (self._wave.emittedDirtyThisWave) {\n\t\t// R-resolved-undirty (D49): the dep settled via an undirty RESOLVED (no DATA in the\n\t\t// batch), but this wire already broadcast DIRTY downstream this wave — balance it with\n\t\t// a RESOLVED so downstream un-dirties instead of wedging. Routed through _down (NOT a\n\t\t// bare _emitToSubs) so the balance respects batch-defer (D12) + pause-buffer, matching\n\t\t// the zero-dep un-dirty path. Without this, a passthrough over a filter-reject /\n\t\t// distinctUntilChanged-dup leaves a dangling DIRTY (the wedge D49 made common).\n\t\tself._down([[\"RESOLVED\"]]);\n\t}\n\tself._dep.batch[0] = null;\n\tself._wave.emittedDirtyThisWave = false;\n}\n\nexport function nodeRunWave<T>(self: NodeRuntimeHost<T>): void {\n\t// R-reentrancy (D37): a fn that re-drives its own dep mid-wave re-enters here while\n\t// _insideRunWave is still set — a synchronous feedback cycle. Reject (throw); the graph\n\t// layer catches it and converts to [[ERROR, e]] (D30). The try/finally resets the flag\n\t// on every frame as the throw unwinds, leaving the graph clean for the catch. Detection\n\t// is node-local and free — it reuses the existing _insideRunWave flag (no new structure,\n\t// dispatcher stays a pure funnel).\n\tif (self._wave.insideRunWave)\n\t\tthrow new Error(\n\t\t\t\"synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)\",\n\t\t);\n\tself._wave.hasCalledFnOnce = true;\n\t// R-cleanup-hooks per-run lifecycle (D28 clarification): clear BOTH hook lists\n\t// before the fn runs; the fn body re-registers the current run's hooks. Only the\n\t// latest run's registrations are live — a re-run supersedes the prior run's hooks,\n\t// discarded WITHOUT firing (no fire-on-rerun; onRerun stays cut). Fixes the push-only\n\t// accumulation (K stale hooks fired after K runs). C-14.\n\tself._hooks.onInvalidate = [];\n\tself._hooks.onDeactivation = [];\n\tconst ctx = self._buildCtx();\n\tconst wasDirty = self._wave.emittedDirtyThisWave;\n\tself._wave.emittedSettleThisWave = false;\n\tself._wave.insideRunWave = true;\n\ttry {\n\t\tself._slot.dispatcher.invoke(self._slot.handle as Handle, ctx);\n\t} finally {\n\t\tself._wave.insideRunWave = false;\n\t}\n\n\t// R-resolved-undirty (D49): a SYNC fn DIRTY'd in phase 1 that produced NO tier-3 value\n\t// this wave (filter-reject / distinctUntilChanged-dup / any no-emit fn) gets a substrate-\n\t// SYNTHESIZED undirty RESOLVED to clear the downstream dirty — operator bodies stay\n\t// protocol-clean (R-primary-api-clean). Status reflects cache freshness: a carried value\n\t// -> resolved, never-valued -> sentinel. EXEMPT: terminal/INVALIDATE waves (they set\n\t// _emittedSettleThisWave and balance their own dirty), and ASYNC-pool nodes — an async fn\n\t// that returns without emitting has DEFERRED its result (it emits later via the stashed\n\t// ctx), NOT rejected; synthesizing here would prematurely settle a still-pending diamond\n\t// leg (R-async-paused / C-4). The eventual async ctx.down carries its own DIRTY balance.\n\tif (\n\t\twasDirty &&\n\t\t!self._wave.emittedSettleThisWave &&\n\t\tself._value.terminal === undefined &&\n\t\t!self._isAsyncPool()\n\t) {\n\t\tself._down([[\"RESOLVED\"]]);\n\t}\n\n\t// roll wave-local state forward\n\tfor (let i = 0; i < self._dep.batch.length; i++) {\n\t\tself._dep.batch[i] = null;\n\t\tself._dep.waveData[i] = [];\n\t\tself._dep.waveTokens[i] = undefined;\n\t\tself._dep.terminalInput[i] = undefined;\n\t}\n\tself._wave.emittedDirtyThisWave = false;\n}\n","import type { Ctx, CtxState, DeliveryMeta, NodeFn } from \"../ctx/types.js\";\nimport type { LockId, Message, PullDemand, Wave } from \"../protocol/messages.js\";\nimport type {\n\tCleanupHooks,\n\tControlState,\n\tDepBookkeeping,\n\tLifecycleState,\n\tNodeCore,\n\tNodeId,\n\tNodeSlot,\n\tPrivateState,\n\tSyncCtxState,\n\tValueState,\n\tVersionState,\n\tWaveState,\n} from \"./core.js\";\nimport type { Node } from \"./node.js\";\nimport type { RewireOp, UpRouteState } from \"./types.js\";\n\nexport interface NodeRuntimeHost<T = unknown> {\n\t_core: NodeCore;\n\t_id: NodeId;\n\t_slot: NodeSlot<T>;\n\t_dep: DepBookkeeping;\n\t_value: ValueState<T>;\n\t_wave: WaveState;\n\t_control: ControlState;\n\t_lifecycle: LifecycleState;\n\t_privateState: PrivateState;\n\t_hooks: CleanupHooks;\n\t_syncCtxState: SyncCtxState;\n\t_version: VersionState;\n\t_syncCtx: Ctx | null;\n\t_restoredActivationPending: boolean;\n\t_released: boolean;\n\t_assertNotReleased(op: string): void;\n\t_isPullQuiet(): boolean;\n\t_requestRewireNext(op: RewireOp): void;\n\t_requestUpNext(msgs: Wave, towardDep?: number): void;\n\t_applyRewireNext(op: RewireOp): void;\n\t_dedupDeps(deps: Node<unknown>[]): Node<unknown>[];\n\t_reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean;\n\t_assertRewireDepOwner(dep: Node<unknown>): void;\n\t_rewire(newDeps: Node<unknown>[], fn: NodeFn, opts?: { allowTerminalOwner?: boolean }): boolean;\n\t_activate(): void;\n\t_subscribeDepAt(depNode: Node<unknown>, opts?: { seedRestored?: boolean }): void;\n\t_seedRestoredDepAt(idx: number, depNode: Node<unknown>): void;\n\t_deactivate(): void;\n\t_subscriberCount(): number;\n\t_isRuntimeQuiescentForRelease(): boolean;\n\t_releaseRuntime(): void;\n\t_resetDepState(): void;\n\t_recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[];\n\t_depProjectionHasData(idx: number): boolean;\n\t_receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void;\n\t_releaseDepDirty(idx: number): void;\n\t_settleAfterAbsorbedTerminal(): void;\n\t_markDirty(): void;\n\t_maybeRun(): void;\n\t_settleRewire(): void;\n\t_tryRun(): void;\n\t_allDepsSettled(): boolean;\n\t_passthroughEmit(): void;\n\t_runWave(): void;\n\t_buildCtx(): Ctx;\n\t_makeCtx(snapshot?: { waveData: unknown[][][]; terminal: unknown[]; latest: unknown[] }): Ctx;\n\t_refreshCtx(ctx: Ctx): void;\n\t_makeState(): CtxState;\n\t_down(msgs: Wave): void;\n\t_up(msgs: Wave, towardDep?: number, route?: UpRouteState): void;\n\t_markDemandRouted(lockId: LockId, route: UpRouteState): boolean;\n\t_forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void;\n\t_isPaused(): boolean;\n\t_hasBoundaryPauseLock(): boolean;\n\t_isAsyncPool(): boolean;\n\t_pauseAcquire(lockId: unknown): void;\n\t_pauseRelease(lockId: unknown): void;\n\t_onResume(): void;\n\t_canFireDemand(): boolean;\n\t_deliverPullDemand(demand: PullDemand): void;\n\t_onDemand(demand: PullDemand): void;\n\t_firePullDemand(): void;\n\t_fireOwedDemandIfReady(): void;\n\t_shouldBufferOnPause(): boolean;\n\t_invalidate(delivery?: DeliveryMeta): void;\n\t_allDepsTerminal(): boolean;\n\t_resetLifecycle(): void;\n\t_emitToSubs(msg: Message, delivery?: DeliveryMeta): void;\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport function nodeRuntimeHost<T>(node: Node<T>): NodeRuntimeHost<T> {\n\treturn node as unknown as NodeRuntimeHost<T>;\n}\n","import { SENTINEL } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport {\n\tactivationReaders,\n\tcheckpointReaders,\n\townerTokens,\n\treleasedNodes,\n\trestoreWriters,\n\truntimeQuiescenceReaders,\n\truntimeReleasers,\n\tsubscriberCountReaders,\n\ttopologyDepsChangedObservers,\n} from \"./runtime-accessors.js\";\n\nexport function nodeActivate<T>(self: NodeRuntimeHost<T>): void {\n\tself._lifecycle.activated = true;\n\tconst seedRestoredDeps = self._restoredActivationPending;\n\tself._restoredActivationPending = false;\n\t// R-pull (D55/D272): activePull is undefined before wiring deps, so each dep's\n\t// push-on-subscribe DIRTY/DATA is absorbed quietly, not relayed downstream.\n\tself._dep.unsubs = new Array(self._slot.deps.length);\n\tself._dep.idxBoxes = new Array(self._slot.deps.length);\n\tfor (const dep of self._slot.deps) self._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });\n\t// Depless producer (fn, no deps): run once on activation.\n\tif (self._slot.deps.length === 0 && self._slot.handle !== null && !self._wave.hasCalledFnOnce) {\n\t\tself._runWave();\n\t}\n}\n\nexport function nodeSubscribeDepAt<T>(\n\tself: NodeRuntimeHost<T>,\n\tdepNode: Node<unknown>,\n\topts: { seedRestored?: boolean } = {},\n): void {\n\tconst idx0 = self._slot.deps.indexOf(depNode);\n\tconst box = { v: idx0 };\n\tlet ignoreInitialPush = opts.seedRestored === true;\n\tif (ignoreInitialPush && idx0 !== -1) {\n\t\tself._seedRestoredDepAt(idx0, depNode);\n\t\tconst dep = nodeRuntimeHost(depNode);\n\t\tif (dep._value.terminal !== undefined && !dep._slot.resubscribable) {\n\t\t\tself._dep.unsubs[idx0] = () => {};\n\t\t\tself._dep.idxBoxes[idx0] = box;\n\t\t\treturn;\n\t\t}\n\t}\n\tconst unsub = depNode.subscribe((msg, delivery) => {\n\t\tif (ignoreInitialPush && delivery === undefined) return;\n\t\tif (ignoreInitialPush) ignoreInitialPush = false;\n\t\tif (box.v === -1) return; // dep removed — stale callback, drop (drain)\n\t\tself._receiveFromDep(box.v, msg, delivery);\n\t});\n\tif (ignoreInitialPush && idx0 !== -1 && box.v !== -1) self._seedRestoredDepAt(idx0, depNode);\n\tignoreInitialPush = false;\n\tif (idx0 !== -1) {\n\t\tself._dep.unsubs[idx0] = unsub;\n\t\tself._dep.idxBoxes[idx0] = box;\n\t}\n}\n\nexport function nodeSeedRestoredDepAt<T>(\n\tself: NodeRuntimeHost<T>,\n\tidx: number,\n\tdepNode: Node<unknown>,\n): void {\n\tconst dep = nodeRuntimeHost(depNode);\n\tconst seedData = dep._value.hasData && !dep._slot.pull;\n\tself._dep.batch[idx] = null;\n\tself._dep.waveData[idx] = [];\n\tself._dep.waveTokens[idx] = undefined;\n\tself._dep.prev[idx] = seedData ? dep._value.cache : SENTINEL;\n\tself._dep.hasData[idx] = seedData;\n\tself._dep.dirty[idx] = false;\n\tself._dep.tier[idx] = seedData ? 3 : 0;\n\tself._dep.terminal[idx] = dep._value.terminal;\n\tself._dep.terminalInput[idx] = undefined;\n}\n\nexport function nodeDeactivate<T>(self: NodeRuntimeHost<T>): void {\n\tself._lifecycle.activated = false;\n\tfor (const u of self._dep.unsubs) if (u) u();\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tfor (const fn of self._hooks.onDeactivation) fn();\n\tself._hooks.onDeactivation = [];\n\tself._hooks.onInvalidate = [];\n\n\tconst isCompute = self._slot.handle !== null || self._slot.deps.length > 0;\n\tif (isCompute) {\n\t\t// RAM: compute nodes clear cache; reconnect re-runs fn fresh.\n\t\tself._value.cache = SENTINEL;\n\t\tself._value.hasData = false;\n\t\tself._value.status = \"sentinel\";\n\t}\n\tself._resetDepState();\n\tself._wave.hasCalledFnOnce = false;\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._value.replayRing = []; // BH6: don't replay stale values to a post-reactivation subscriber\n\tif (!self._privateState.persist) self._privateState.value = SENTINEL;\n}\n\nexport function nodeSubscriberCount<T>(self: NodeRuntimeHost<T>): number {\n\treturn self._lifecycle.subscribers.size;\n}\n\nexport function nodeIsRuntimeQuiescentForRelease<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn (\n\t\t!self._released &&\n\t\tself._value.status !== \"dirty\" &&\n\t\tself._value.status !== \"pending\" &&\n\t\tself._wave.pending === 0 &&\n\t\t!self._wave.insideRunWave &&\n\t\t!self._wave.inDepMutation &&\n\t\t!self._wave.rewireRunPending &&\n\t\t!self._wave.batchDirtyOwed &&\n\t\tself._dep.dirty.every((dirty) => !dirty) &&\n\t\tself._control.pauseBuffer.length === 0 &&\n\t\t!self._control.pausedDepWaveOccurred &&\n\t\tself._control.demandOwed === undefined &&\n\t\tself._control.activePull === undefined &&\n\t\t!self._control.inDeliverDemand &&\n\t\tself._control.pauseLockset.size === 0\n\t);\n}\n\nexport function nodeReleaseRuntime<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._released) return;\n\tself._released = true;\n\tconst node = self as unknown as Node<unknown>;\n\treleasedNodes.add(node);\n\tlet releaseError: unknown;\n\tconst recordReleaseError = (error: unknown): void => {\n\t\tif (releaseError === undefined) releaseError = error;\n\t};\n\tself._lifecycle.activated = false;\n\tfor (const u of self._dep.unsubs) {\n\t\ttry {\n\t\t\tu();\n\t\t} catch (error) {\n\t\t\trecordReleaseError(error);\n\t\t\t// D124 release is graph-owned and atomic; user cleanup must not split commit.\n\t\t}\n\t}\n\tfor (const fn of self._hooks.onDeactivation) {\n\t\ttry {\n\t\t\tfn();\n\t\t} catch (error) {\n\t\t\trecordReleaseError(error);\n\t\t\t// D124 release cleans runtime without synthesizing protocol ERROR/COMPLETE.\n\t\t}\n\t}\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tself._lifecycle.subscribers.clear();\n\tif (self._slot.handle !== null) {\n\t\tself._slot.dispatcher.unregister(self._slot.handle);\n\t\tself._slot.handle = null;\n\t}\n\tself._slot.deps = [];\n\tself._dep.batch = [];\n\tself._dep.waveData = [];\n\tself._dep.waveTokens = [];\n\tself._dep.prev = [];\n\tself._dep.hasData = [];\n\tself._dep.dirty = [];\n\tself._dep.tier = [];\n\tself._dep.terminal = [];\n\tself._dep.terminalInput = [];\n\tself._value.cache = SENTINEL;\n\tself._value.hasData = false;\n\tself._value.status = \"sentinel\";\n\tself._value.terminal = undefined;\n\tself._value.replayRing = [];\n\tself._privateState.value = SENTINEL;\n\tself._privateState.persist = false;\n\tself._syncCtx = null;\n\tself._resetDepState();\n\tself._hooks.onDeactivation = [];\n\tself._hooks.onInvalidate = [];\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined;\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._restoredActivationPending = false;\n\tcheckpointReaders.delete(node);\n\trestoreWriters.delete(node);\n\truntimeReleasers.delete(node);\n\truntimeQuiescenceReaders.delete(node);\n\tsubscriberCountReaders.delete(node);\n\tactivationReaders.delete(node);\n\townerTokens.delete(node);\n\ttopologyDepsChangedObservers.delete(node);\n\tself._core.releaseSlot(self._id);\n\tif (releaseError !== undefined) throw releaseError;\n}\n\nexport function nodeResetDepState<T>(self: NodeRuntimeHost<T>): void {\n\tconst n = self._slot.deps.length;\n\tfor (let i = 0; i < n; i++) {\n\t\tself._dep.batch[i] = null;\n\t\tself._dep.waveData[i] = [];\n\t\tself._dep.waveTokens[i] = undefined;\n\t\tself._dep.prev[i] = SENTINEL;\n\t\tself._dep.hasData[i] = false;\n\t\tself._dep.dirty[i] = false;\n\t\tself._dep.tier[i] = 0;\n\t\tself._dep.terminal[i] = undefined;\n\t\tself._dep.terminalInput[i] = undefined;\n\t}\n\tself._wave.pending = 0;\n\tself._wave.emittedDirtyThisWave = false;\n}\n","/**\n * Declarative batch (R-batch-coalesce / D12).\n *\n * Inside a batch, DIRTY propagates immediately but the tier-3 settle slice\n * (DATA/RESOLVED/INVALIDATE) is deferred to commit, so a shared downstream\n * recomputes ONCE after all batched sources settle. Success -> commit; a thrown\n * error -> rollback; `bctx.rollback()` is the explicit escape hatch.\n *\n * Coalescing note: this kernel coalesces multiple emits to the SAME node within\n * one batch to the latest tier-3 wave (last-value-wins). Full per-item batch-array\n * delivery (downstream fn receiving [v1..vK]) is a documented refinement — the\n * dominant use (coalescing a diamond join to one recompute) is exact here.\n */\n\nimport type { Wave } from \"../protocol/messages.js\";\nimport { dropBoundaryTasksForBatch, enterWave, exitWave } from \"./boundary.js\";\n\n/** A node target the batch can commit/rollback against (structural, avoids an import cycle). */\nexport interface BatchTarget {\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport interface BatchCtx {\n\t/** Discard all deferred emissions in this batch instead of committing. */\n\trollback(): void;\n}\n\ninterface ActiveBatch {\n\torder: BatchTarget[];\n\tdeferred: Map<BatchTarget, Wave>;\n\tcommitted: boolean;\n\trolledBack: boolean;\n}\n\nlet active: ActiveBatch | null = null;\nlet boundaryOwner: ActiveBatch | null = null;\n\nexport function currentBatch(): boolean {\n\treturn active !== null;\n}\n\nexport function currentBoundaryBatchToken(): object | undefined {\n\treturn active ?? boundaryOwner ?? undefined;\n}\n\n/**\n * Defer a node's tier-3 settle slice into the active batch. Returns true if a batch\n * captured it; false if there is no active batch (caller emits normally).\n */\nexport function deferToBatch(target: BatchTarget, tier3Wave: Wave): boolean {\n\tif (active === null) return false;\n\tif (!active.deferred.has(target)) active.order.push(target);\n\tactive.deferred.set(target, tier3Wave); // last-value coalescing\n\treturn true;\n}\n\n/**\n * Defer a topology mutation until after the active batch has committed/rolled back,\n * but only when this target has an uncommitted settle slice in the current batch.\n */\nexport function deferAfterBatchForTarget(target: BatchTarget, fn: () => void): boolean {\n\tif (active === null || !active.deferred.has(target)) return false;\n\tconst owner = active;\n\ttarget.__deferBoundary(() => {\n\t\tif (owner.committed) fn();\n\t}, owner);\n\treturn true;\n}\n\nfunction commit(b: ActiveBatch): void {\n\tconst prev = boundaryOwner;\n\tboundaryOwner = b;\n\ttry {\n\t\tfor (const target of b.order) {\n\t\t\tconst wave = b.deferred.get(target);\n\t\t\tif (wave) target.__commitBatchedWave(wave);\n\t\t}\n\t\tb.committed = true;\n\t} catch (e) {\n\t\tdropBoundaryTasksForBatch(b);\n\t\tthrow e;\n\t} finally {\n\t\tboundaryOwner = prev;\n\t}\n}\n\nfunction rollback(b: ActiveBatch): void {\n\tdropBoundaryTasksForBatch(b);\n\tfor (const target of b.order) target.__rollbackBatched();\n}\n\n/**\n * Run updates as one coalesced batch.\n *\n * @param fn - Synchronous callback that performs node updates and may call `rollback()`.\n * @returns The callback return value when the batch commits.\n * @example\n * ```ts\n * import { batch, graph } from \"@graphrefly/ts\";\n *\n * const g = graph();\n * const left = g.state(0);\n * const right = g.state(0);\n *\n * batch(() => {\n * left.set(1);\n * right.set(2);\n * });\n * ```\n * @remarks **Coalescing:** DATA/RESOLVED/INVALIDATE settle slices are deferred until commit so\n * shared downstream nodes recompute once for the batch.\n * @category core\n */\nexport function batch<R>(fn: (bctx: BatchCtx) => R): R {\n\t// Wave-owner boundary (R-rewire-deferred / D47): bracket the whole batch (fn + commit) so a\n\t// ctx.rewireNext issued by a fn that runs during COMMIT drains AFTER the commit, never on the\n\t// un-committed view. Inner waves (state.set, commit cascade) nest under this owner.\n\tenterWave();\n\ttry {\n\t\tif (active !== null) {\n\t\t\t// Nested batch joins the outer frame (one commit at the outermost exit).\n\t\t\tconst outer = active;\n\t\t\treturn fn({\n\t\t\t\trollback: () => {\n\t\t\t\t\touter.rolledBack = true;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst b: ActiveBatch = { order: [], deferred: new Map(), committed: false, rolledBack: false };\n\t\tactive = b;\n\t\tconst bctx: BatchCtx = {\n\t\t\trollback: () => {\n\t\t\t\tb.rolledBack = true;\n\t\t\t},\n\t\t};\n\t\tlet result: R;\n\t\ttry {\n\t\t\tresult = fn(bctx);\n\t\t} catch (e) {\n\t\t\tactive = null;\n\t\t\trollback(b);\n\t\t\tthrow e;\n\t\t}\n\t\tactive = null;\n\t\tif (b.rolledBack) rollback(b);\n\t\telse {\n\t\t\tcommit(b);\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\texitWave();\n\t}\n}\n","import { strictCanonicalJsonBytes, strictJsonCodec } from \"../json/codec.js\";\n\nexport type NodeVersioningLevel = 0 | 1;\n\n/**\n * D112 V1 node-version hash callback.\n *\n * The callback receives strict canonical JSON UTF-8 DATA bytes, not the raw host value.\n * Runtime V1 versioning encodes DATA with `strictCanonicalJsonBytes(value)` before calling hash.\n */\nexport type NodeVersionHashFn = (bytes: Uint8Array) => string;\n\nexport type NodeVersioningPolicy =\n\t| false\n\t| 0\n\t| 1\n\t| {\n\t\t\tlevel: NodeVersioningLevel;\n\t\t\thash?: NodeVersionHashFn;\n\t };\n\nexport type ResolvedNodeVersioningPolicy =\n\t| { readonly enabled: false }\n\t| { readonly enabled: true; readonly level: 0 }\n\t| { readonly enabled: true; readonly level: 1; readonly hash: NodeVersionHashFn };\n\nexport type NodeVersionV0 = {\n\treadonly level: 0;\n\treadonly counter: number;\n};\n\nexport type NodeVersionV1 = {\n\treadonly level: 1;\n\treadonly counter: number;\n\treadonly cid: string;\n\treadonly prev: string | null;\n};\n\nexport type NodeVersion = NodeVersionV0 | NodeVersionV1;\n\nexport type NodeVersionJson = NodeVersion;\n\nconst ABSENT_V1_SEED = Object.freeze({\n\t\"@graphrefly/node-version\": \"v1-absent\",\n});\n\nfunction fnv1a64(input: Uint8Array): string {\n\tlet hash = 0xcbf29ce484222325n;\n\tconst prime = 0x100000001b3n;\n\tfor (const byte of input) {\n\t\thash ^= BigInt(byte);\n\t\thash = BigInt.asUintN(64, hash * prime);\n\t}\n\treturn hash.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Default synchronous D112 V1 node-version hash over strict canonical JSON UTF-8 bytes.\n *\n * When hashing a host value directly, encode first:\n * `defaultNodeVersionHash(strictCanonicalJsonBytes(value))`.\n */\nexport function defaultNodeVersionHash(bytes: Uint8Array): string {\n\treturn `fnv1a64:${fnv1a64(bytes)}`;\n}\n\nfunction computeV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\tvalue: unknown,\n): string {\n\treturn policy.hash(strictCanonicalJsonBytes(value));\n}\n\nexport function assertNodeVersionDataCompatible(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): void {\n\tif (!policy.enabled || policy.level === 0) return;\n\tstrictCanonicalJsonBytes(value);\n}\n\nexport function snapshotNodeVersionData(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): unknown {\n\tif (!policy.enabled || policy.level === 0) return value;\n\tconst bytes = strictCanonicalJsonBytes(value);\n\treturn strictJsonCodec.decode(bytes);\n}\n\nexport function resolveNodeVersioningPolicy(\n\tpolicy: NodeVersioningPolicy | undefined,\n): ResolvedNodeVersioningPolicy {\n\tif (policy === false) return { enabled: false };\n\tif (policy === undefined || policy === 0) return { enabled: true, level: 0 };\n\tif (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };\n\tif (typeof policy === \"object\" && policy !== null) {\n\t\tif (policy.level === 0) return { enabled: true, level: 0 };\n\t\tif (policy.level === 1) {\n\t\t\treturn { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };\n\t\t}\n\t}\n\tthrow new Error(\"node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)\");\n}\n\nexport function createNodeVersion(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tinitialValue: unknown = ABSENT_V1_SEED,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: 0,\n\t\tcid: computeV1Cid(policy, initialValue),\n\t\tprev: null,\n\t});\n}\n\nexport function advanceNodeVersion(\n\tcurrent: NodeVersion | undefined,\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (current === undefined) return createNodeVersion(policy, value);\n\tif (policy.level === 0) {\n\t\treturn Object.freeze({ level: 0, counter: current.counter + 1 });\n\t}\n\tconst previous = current.level === 1 ? current.cid : null;\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: current.counter + 1,\n\t\tcid: computeV1Cid(policy, value),\n\t\tprev: previous,\n\t});\n}\n\nexport function cloneNodeVersion(version: NodeVersion | undefined): NodeVersion | undefined {\n\tif (version === undefined) return undefined;\n\tif (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: version.counter,\n\t\tcid: version.cid,\n\t\tprev: version.prev,\n\t});\n}\n\nexport function restoredV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\thasData: boolean,\n\tcache: unknown,\n): string {\n\treturn computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);\n}\n\nexport function validateNodeVersionJson(value: unknown, path: string): NodeVersionJson {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new Error(`restoreGraph: ${path} must be an object`);\n\t}\n\tconst record = value as Record<string, unknown>;\n\tif (record.level === 0) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\treturn Object.freeze({ level: 0, counter: record.counter as number });\n\t}\n\tif (record.level === 1) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\tif (typeof record.cid !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.cid must be a string`);\n\t\t}\n\t\tif (record.prev !== null && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string or null`);\n\t\t}\n\t\tif ((record.counter as number) === 0 && record.prev !== null) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be null when counter is 0`);\n\t\t}\n\t\tif ((record.counter as number) > 0 && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string when counter is > 0`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tlevel: 1,\n\t\t\tcounter: record.counter as number,\n\t\t\tcid: record.cid,\n\t\t\tprev: record.prev,\n\t\t});\n\t}\n\tthrow new Error(`restoreGraph: ${path}.level must be 0 or 1`);\n}\n","import { currentBatch, deferToBatch } from \"../batch/batch.js\";\nimport { deferRewire, scheduleBoundaryDrain } from \"../batch/boundary.js\";\nimport type { DeliveryMeta } from \"../ctx/types.js\";\nimport type { LockId, Message, PullDemand, Wave } from \"../protocol/messages.js\";\nimport {\n\tisDeferredTier,\n\tisPauseBufferedTier,\n\tisUpAllowed,\n\tisValueTier,\n\tmessageTier,\n\tSENTINEL,\n} from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { normalizePullDemand, validateDownPayloads } from \"./protocol-guards.js\";\nimport type { UpRouteState } from \"./types.js\";\nimport {\n\tadvanceNodeVersion,\n\tassertNodeVersionDataCompatible,\n\tsnapshotNodeVersionData,\n} from \"./versioning.js\";\n\nexport function nodeDown<T>(self: NodeRuntimeHost<T>, msgs: Wave): void {\n\tif (self._released) return;\n\tvalidateDownPayloads(msgs);\n\tconst deliveryWave = {};\n\tconst assertVersionDataCompatible = (wave: readonly Message[]) => {\n\t\tfor (const m of wave) {\n\t\t\tif (m[0] === \"DATA\") assertNodeVersionDataCompatible(self._version.policy, m[1]);\n\t\t}\n\t};\n\tconst snapshotVersionData = (wave: readonly Message[]): Message[] =>\n\t\twave.map((m) =>\n\t\t\tm[0] === \"DATA\"\n\t\t\t\t? ([\"DATA\", snapshotNodeVersionData(self._version.policy, m[1])] as Message)\n\t\t\t\t: m,\n\t\t);\n\tassertVersionDataCompatible(msgs);\n\t// Terminal-is-forever (R-terminal / D17 / B30): once COMPLETE/ERROR has been emitted the\n\t// node is final — a self-emit (state.set / ctx.down) in a LATER wave is a no-op, never\n\t// resurrecting the cache or re-emitting. The COMPLETE/ERROR arms below also self-guard\n\t// against a double terminal, but DATA/RESOLVED/INVALIDATE had no entry guard, so a\n\t// post-terminal set() would overwrite cache + emit DATA. R-teardown-terminal-relay / D65\n\t// carves out the only post-terminal exception: TEARDOWN still relays downstream for unwire\n\t// without reopening value output. A single wave that goes terminal mid-loop (e.g.\n\t// [COMPLETE, TEARDOWN]) is unaffected: _terminal is still undefined at entry.\n\t// Resubscribable reset clears _terminal before any re-emit.\n\tif (self._value.terminal !== undefined) {\n\t\tif (!msgs.some((m) => m[0] === \"TEARDOWN\")) return;\n\t\tself._value.hasTorndown = true;\n\t\tif (self._slot.resetOnTeardown) {\n\t\t\tself._value.cache = SENTINEL;\n\t\t\tself._value.hasData = false;\n\t\t}\n\t\tself._emitToSubs([\"TEARDOWN\"], { wave: deliveryWave, last: true });\n\t\treturn;\n\t}\n\tlet sorted: Message[] = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));\n\t// R-same-wave-merge: collapse repeated INVALIDATE in one wave (Q9) so the\n\t// cleanup hook + downstream broadcast fire at most once.\n\tconst firstInvalidate = sorted.findIndex((m) => m[0] === \"INVALIDATE\");\n\tif (firstInvalidate !== -1) {\n\t\tsorted = sorted.filter((m, i) => m[0] !== \"INVALIDATE\" || i === firstInvalidate);\n\t}\n\t// R-teardown-complete: a TEARDOWN reaching a non-terminal node synthesizes a\n\t// COMPLETE prefix (so firstValueFrom-style bridges resolve), unless the wave\n\t// already carries a terminal or the node already tore down.\n\tconst hasTeardown = sorted.some((m) => m[0] === \"TEARDOWN\");\n\tconst hasTerminal = sorted.some((m) => m[0] === \"COMPLETE\" || m[0] === \"ERROR\");\n\tif (\n\t\thasTeardown &&\n\t\t!hasTerminal &&\n\t\tself._value.terminal === undefined &&\n\t\t!self._value.hasTorndown\n\t) {\n\t\tsorted = [[\"COMPLETE\"], ...sorted];\n\t}\n\t// R-batch-coalesce (D12): inside a batch, emit DIRTY immediately but defer the\n\t// tier-3 settle slice to commit so a shared downstream recomputes once. Only\n\t// external emits defer (fn emits during commit run normally).\n\tif (!self._wave.insideRunWave && currentBatch()) {\n\t\tconst deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));\n\t\tif (deferred.length > 0) {\n\t\t\tif (!self._wave.emittedDirtyThisWave) {\n\t\t\t\tself._wave.emittedDirtyThisWave = true;\n\t\t\t\tself._value.status = \"dirty\";\n\t\t\t\tself._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t\t}\n\t\t\tself._wave.batchDirtyOwed = true; // BH1: owe a balancing RESOLVED on rollback\n\t\t\tdeferToBatch(self as unknown as Node<unknown>, deferred);\n\t\t\treturn;\n\t\t}\n\t}\n\t// R-pause-modes / R-async-paused: defer the settle slice (tier 3/4) into the\n\t// pause buffer while paused; tier 0-2 (DIRTY/PAUSE/RESUME), tier 5 (terminal),\n\t// tier 6 (TEARDOWN) bypass so end-of-stream + control always reach observers.\n\tif (self._shouldBufferOnPause()) {\n\t\tconst buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));\n\t\tif (buffered.length > 0) {\n\t\t\t// B36 / R-resolved-undirty: buffering a settle slice still means this fn wave\n\t\t\t// produced a settle. Without this, _runWave sees \"dirty + no settle\" and\n\t\t\t// synthesizes a RESOLVED that pierces the pause while the DATA waits in the buffer.\n\t\t\tself._wave.emittedSettleThisWave = true;\n\t\t\tself._control.pauseBuffer.push(buffered);\n\t\t}\n\t\tsorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));\n\t\tif (sorted.length === 0) return;\n\t}\n\tlet dataCount = 0;\n\tlet hasTier3 = false;\n\tlet hasResolved = false;\n\tfor (const m of sorted) {\n\t\tif (m[0] === \"DATA\") dataCount++;\n\t\tif (m[0] === \"RESOLVED\") hasResolved = true;\n\t\tif (isValueTier(m[0])) hasTier3 = true;\n\t}\n\t// EC2 / R-resolved-undirty tier-3 exclusivity: a wave's tier-3 slot is >=1 DATA\n\t// (occurrence) XOR exactly 1 RESOLVED (undirty) — never mixed. Reject fail-fast.\n\tif (dataCount >= 1 && hasResolved) {\n\t\tthrow new Error(\n\t\t\t\"down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)\",\n\t\t);\n\t}\n\tconst plannedVersions: Array<NodeVersion | undefined> = new Array(sorted.length);\n\tif (dataCount > 0) {\n\t\tlet plannedVersion = self._version.value;\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst m = sorted[i];\n\t\t\tif (m[0] !== \"DATA\") continue;\n\t\t\tplannedVersion = advanceNodeVersion(plannedVersion, self._version.policy, m[1]);\n\t\t\tplannedVersions[i] = plannedVersion;\n\t\t}\n\t}\n\n\t// Synthesize a leading DIRTY for an EXTERNAL tier-3 emit (R-dirty-before-data), and for\n\t// PULL demand fns only when they actually emit tier-3. A no-op pull helper must stay silent.\n\tif (\n\t\thasTier3 &&\n\t\t(!self._wave.insideRunWave || self._control.pullDirtyOwed) &&\n\t\t!self._wave.emittedDirtyThisWave\n\t) {\n\t\tself._wave.emittedDirtyThisWave = true;\n\t\tself._value.status = \"dirty\";\n\t\tself._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t}\n\n\tfor (let i = 0; i < sorted.length; i++) {\n\t\tconst m = sorted[i];\n\t\tconst delivery = { wave: deliveryWave, last: i === sorted.length - 1 };\n\t\t// R-resolved-undirty (D49): a tier-3+ emit this wave means the fn produced a settle,\n\t\t// so no synthesized undirty RESOLVED is owed (see _runWave).\n\t\tif (isDeferredTier(m[0])) self._wave.emittedSettleThisWave = true;\n\t\tif (m[0] === \"DIRTY\") {\n\t\t\tif (!self._wave.emittedDirtyThisWave) {\n\t\t\t\tself._wave.emittedDirtyThisWave = true;\n\t\t\t\tself._value.status = \"dirty\";\n\t\t\t\tself._emitToSubs([\"DIRTY\"], delivery);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"DATA\") {\n\t\t\tconst v = m[1] as T;\n\t\t\t// R-resolved-undirty (D49): every value-occurrence is emitted as DATA — the\n\t\t\t// substrate never substitutes DATA->RESOLVED on value-equality. Dedup is opt-in\n\t\t\t// at the operator layer (distinctUntilChanged), never a substrate behavior.\n\t\t\tself._value.cache = v;\n\t\t\tself._value.hasData = true;\n\t\t\tself._value.status = \"settled\";\n\t\t\tself._version.value = plannedVersions[i];\n\t\t\tif (self._slot.replayN > 0) {\n\t\t\t\tself._value.replayRing.push(v);\n\t\t\t\tif (self._value.replayRing.length > self._slot.replayN) self._value.replayRing.shift();\n\t\t\t}\n\t\t\tself._emitToSubs([\"DATA\", v], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"RESOLVED\") {\n\t\t\tself._value.status = self._value.hasData ? \"resolved\" : \"sentinel\";\n\t\t\tself._emitToSubs([\"RESOLVED\"], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"INVALIDATE\") {\n\t\t\tself._invalidate(delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"COMPLETE\") {\n\t\t\tif (self._value.terminal !== undefined) continue;\n\t\t\tself._value.terminal = true;\n\t\t\tself._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\tself._value.status = \"completed\";\n\t\t\tself._emitToSubs([\"COMPLETE\"], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"ERROR\") {\n\t\t\tif (self._value.terminal !== undefined) continue;\n\t\t\tself._value.terminal = m[1];\n\t\t\tself._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\tself._value.status = \"errored\";\n\t\t\tself._emitToSubs([\"ERROR\", m[1]], delivery);\n\t\t\tcontinue;\n\t\t}\n\t\tif (m[0] === \"TEARDOWN\") {\n\t\t\tself._value.hasTorndown = true;\n\t\t\tif (self._slot.resetOnTeardown) {\n\t\t\t\tself._value.cache = SENTINEL;\n\t\t\t\tself._value.hasData = false;\n\t\t\t}\n\t\t\tself._emitToSubs([\"TEARDOWN\"], delivery);\n\t\t}\n\t\t// PAUSE / RESUME — control slice.\n\t}\n\n\tif (!self._wave.insideRunWave) self._wave.emittedDirtyThisWave = false;\n}\n\nexport function nodeUp<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsgs: Wave,\n\ttowardDep?: number,\n\troute?: UpRouteState,\n): void {\n\tif (self._released) return;\n\tconst routeState = route ?? { demandFired: new Map() };\n\tfor (const m of msgs) {\n\t\tif (!isUpAllowed(m[0])) {\n\t\t\tthrow new Error(\n\t\t\t\t`ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`,\n\t\t\t);\n\t\t}\n\t}\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"PAUSE\") {\n\t\t\t// PAUSE is NODE-TARGETED (R-up-routing): it ACQUIRES a lock, so there is no\n\t\t\t// pre-existing holder to route to — a controller targets the node directly.\n\t\t\tself._pauseAcquire(m[1]);\n\t\t} else if (m[0] === \"RESUME\") {\n\t\t\t// R-up-routing (D269): RESUME is pause-lock release only.\n\t\t\tif (self._control.pauseLockset.has(m[1])) {\n\t\t\t\t// a pause lock held HERE → release LOCALLY (normal pause/resume, R-pause-lockset).\n\t\t\t\tself._pauseRelease(m[1]);\n\t\t\t} else {\n\t\t\t\t// not held here → forward UP the declared cone to find the holder.\n\t\t\t\tself._forwardUp(m, towardDep, routeState);\n\t\t\t}\n\t\t} else if (m[0] === \"PULL\") {\n\t\t\t// R-up-routing / R-pull (D269/D272): DEMAND-IF-PULL-HOLDER-ELSE-FORWARD-UP.\n\t\t\tconst demand = normalizePullDemand(m[1]);\n\t\t\tif (self._slot.pull && demand.pullId === self._slot.pullLock) {\n\t\t\t\tif (!self._markDemandRouted(demand.pullId, routeState)) self._onDemand(demand);\n\t\t\t} else {\n\t\t\t\tself._forwardUp([\"PULL\", demand], towardDep, routeState);\n\t\t\t}\n\t\t} else if (self._slot.deps.length === 0) {\n\t\t\t// R-up-at-source (D38): a depless source is the terminus of upstream control.\n\t\t\t// INVALIDATE → HONOR the invalidate-request. Routed through _down (NOT a direct\n\t\t\t// _invalidate call, QA A-2) so the invalidate-request respects batch-defer (D12)\n\t\t\t// and pause-buffer exactly like a downstream-originated INVALIDATE; _down's\n\t\t\t// INVALIDATE branch calls _invalidate() (clear cache → SENTINEL, fire onInvalidate,\n\t\t\t// broadcast downstream). Outside batch/pause it is identical to a direct call.\n\t\t\t// DIRTY / TEARDOWN → DROP (no coherent terminus action; self-dirty would wedge\n\t\t\t// downstream awaiting a settle that never comes; source lifecycle is source-owned).\n\t\t\tif (m[0] === \"INVALIDATE\") self._down([[\"INVALIDATE\"]]);\n\t\t} else {\n\t\t\t// dep-bearing intermediate: forward DIRTY/INVALIDATE/TEARDOWN up toward deps.\n\t\t\tself._forwardUp(m, towardDep, routeState);\n\t\t}\n\t}\n}\n\nexport function nodeMarkDemandRouted<T>(\n\tself: NodeRuntimeHost<T>,\n\tlockId: LockId,\n\troute: UpRouteState,\n): boolean {\n\tlet holders = route.demandFired.get(lockId);\n\tif (holders === undefined) {\n\t\tholders = new Set();\n\t\troute.demandFired.set(lockId, holders);\n\t}\n\tconst node = self as unknown as Node<unknown>;\n\tif (holders.has(node)) return true;\n\tholders.add(node);\n\treturn false;\n}\n\nexport function nodeForwardUp<T>(\n\tself: NodeRuntimeHost<T>,\n\tm: Message,\n\ttowardDep: number | undefined,\n\troute: UpRouteState,\n): void {\n\tif (self._slot.deps.length === 0) return; // depless source terminus → drop\n\tif (towardDep !== undefined) {\n\t\tconst d = self._slot.deps[towardDep];\n\t\tif (d !== undefined) nodeRuntimeHost(d)._up([m], undefined, route);\n\t} else {\n\t\tfor (const dep of self._slot.deps) nodeRuntimeHost(dep)._up([m], undefined, route);\n\t}\n}\n\nexport function nodeIsPaused<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn self._control.pauseLockset.size > 0;\n}\n\nexport function nodeHasBoundaryPauseLock<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._slot.pausable === false) return false;\n\treturn self._control.pauseLockset.size > 0;\n}\n\nexport function nodeIsAsyncPool<T>(self: NodeRuntimeHost<T>): boolean {\n\treturn (\n\t\tself._slot.handle !== null &&\n\t\tself._slot.dispatcher.poolKind(self._slot.handle.poolId) === \"async\"\n\t);\n}\n\nexport function nodePauseAcquire<T>(self: NodeRuntimeHost<T>, lockId: unknown): void {\n\tself._control.pauseLockset.add(lockId); // Set => same-id repeat PAUSE is idempotent\n}\n\nexport function nodePauseRelease<T>(self: NodeRuntimeHost<T>, lockId: unknown): void {\n\tif (!self._control.pauseLockset.has(lockId)) return; // unknown id => no-op\n\tself._control.pauseLockset.delete(lockId);\n\t// R-pull (D59 / D272): releasing an EXTERNAL pause lock can unblock an owed demand.\n\t// Pull quiet is activePull-derived and never stored in pauseLockset.\n\tif (self._slot.pull && self._control.demandOwed !== undefined) self._fireOwedDemandIfReady();\n\tif (self._hasBoundaryPauseLock()) return; // another external lock still held => stay paused\n\tscheduleBoundaryDrain(self._core);\n\tif (self._slot.pull) return; // pull nodes stay quiet until PULL, even after external resume\n\tself._onResume();\n}\n\nexport function nodeOnResume<T>(self: NodeRuntimeHost<T>): void {\n\t// BH3: a node that terminated while paused discards its buffer and never\n\t// replays/recomputes (terminal-is-forever).\n\tif (self._value.terminal !== undefined) {\n\t\tself._control.pauseBuffer = [];\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._control.demandOwed = undefined;\n\t\tself._control.activePull = undefined;\n\t\tself._control.pullDirtyOwed = false;\n\t\treturn;\n\t}\n\t// Non-pull pause/resume (R-pause-modes): drain buffered settle slices (resumeAll /\n\t// async-at-paused, R-async-paused), then fire a coalesced dep-wave once (default mode).\n\t// A PULL node does not resume by draining here; its demand fires through _onDemand.\n\tif (self._control.pauseBuffer.length > 0) {\n\t\tconst buf = self._control.pauseBuffer;\n\t\tself._control.pauseBuffer = [];\n\t\tfor (const wave of buf) self._down(wave);\n\t}\n\tif (self._control.pausedDepWaveOccurred) {\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._tryRun();\n\t}\n}\n\nexport function nodeCanFireDemand<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._value.terminal !== undefined || self._wave.pending > 0) return false;\n\treturn self._control.pauseLockset.size === 0;\n}\n\nexport function nodeDeliverPullDemand<T>(self: NodeRuntimeHost<T>, demand: PullDemand): void {\n\tself._control.demandOwed = undefined;\n\tself._control.activePull = demand;\n\tself._control.inDeliverDemand = true;\n\ttry {\n\t\tself._firePullDemand();\n\t} finally {\n\t\tself._control.activePull = undefined;\n\t\tself._control.inDeliverDemand = false;\n\t}\n}\n\nexport function nodeOnDemand<T>(self: NodeRuntimeHost<T>, demand: PullDemand): void {\n\tif (self._control.inDeliverDemand) return; // re-entrant demand during an active delivery → drop (1:1)\n\tif (self._canFireDemand()) self._deliverPullDemand(demand);\n\telse self._control.demandOwed = demand; // latest owed params wins (D269/D272)\n}\n\nexport function nodeFirePullDemand<T>(self: NodeRuntimeHost<T>): void {\n\tlet drainedBuffer = false;\n\tif (self._control.pauseBuffer.length > 0) {\n\t\tconst buf = self._control.pauseBuffer;\n\t\tself._control.pauseBuffer = [];\n\t\tfor (const wave of buf) self._down(wave);\n\t\tdrainedBuffer = true;\n\t}\n\tif (drainedBuffer) return;\n\tif (self._control.pausedDepWaveOccurred) {\n\t\t// QA-B2: only deliver if the fn can actually run this wave (settle-ready + first-run gate\n\t\t// open). A gated run emits no DATA, so emitting the leading DIRTY would STRAND downstream\n\t\t// — the exact wedge this feature exists to prevent (NoWedgeWhileQuiet). When gated, stay\n\t\t// SILENT and KEEP _pausedDepWaveOccurred so a later demand (once every dep has settled)\n\t\t// delivers. Mirrors _settleRewire's pre-_markDirty gate.\n\t\tconst gated =\n\t\t\tself._slot.handle !== null &&\n\t\t\t!self._wave.hasCalledFnOnce &&\n\t\t\t!(self._slot.partial || self._allDepsSettled());\n\t\tif (self._wave.pending > 0 || gated) return;\n\t\tself._control.pausedDepWaveOccurred = false;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._control.pullDirtyOwed = true;\n\t\ttry {\n\t\t\tself._tryRun(); // fn DATA triggers DIRTY-before-DATA; no DATA means no output.\n\t\t} finally {\n\t\t\tself._control.pullDirtyOwed = false;\n\t\t}\n\t\treturn;\n\t}\n\tif (self._slot.handle !== null) {\n\t\tif (!self._wave.hasCalledFnOnce && !(self._slot.partial || self._allDepsSettled())) return;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._control.pullDirtyOwed = true;\n\t\ttry {\n\t\t\tself._runWave();\n\t\t} finally {\n\t\t\tself._control.pullDirtyOwed = false;\n\t\t}\n\t}\n}\n\nexport function nodeFireOwedDemandIfReady<T>(self: NodeRuntimeHost<T>): void {\n\tif (self._control.inDeliverDemand) return; // don't re-enter during an active delivery (1:1, QA guard)\n\tif (self._slot.pull && self._control.demandOwed !== undefined && self._canFireDemand()) {\n\t\tself._deliverPullDemand(self._control.demandOwed);\n\t}\n}\n\nexport function nodeShouldBufferOnPause<T>(self: NodeRuntimeHost<T>): boolean {\n\t// D44: pausable mode is the OUTER gate over R-async-paused buffering.\n\t// false: ignore PAUSE/RESUME ENTIRELY — never buffer, keep producing (R-pause-modes; resolves B20).\n\tif (self._slot.pausable === false) return false;\n\tif (!self._isPaused() && !self._isPullQuiet()) return false;\n\t// resumeAll: production-gating — buffer the node's own (sync/async) settle slice too.\n\tif (self._slot.pausable === \"resumeAll\") return true;\n\t// true (default): PAUSE gates recomputation/propagation, NOT a leaf source's own production.\n\t// An async COMPUTE node's (deps>0) in-flight result buffers (R-async-paused / C-2); a depless\n\t// async leaf source's own production delivers immediately (R-pause-modes / C-10).\n\tif (!self._wave.insideRunWave && self._isAsyncPool() && self._slot.deps.length > 0) return true;\n\treturn false;\n}\n\nexport function nodeInvalidate<T>(self: NodeRuntimeHost<T>, delivery?: DeliveryMeta): void {\n\tif (!self._value.hasData) return; // never-populated or already-reset → no-op\n\tself._value.cache = SENTINEL;\n\tself._value.hasData = false;\n\tself._value.status = \"sentinel\";\n\tself._value.replayRing = []; // BH6: invalidated values are stale — don't replay them\n\tfor (const fn of self._hooks.onInvalidate) fn();\n\tself._emitToSubs([\"INVALIDATE\"], delivery);\n}\n\nexport function nodeAllDepsTerminal<T>(self: NodeRuntimeHost<T>): boolean {\n\tif (self._slot.deps.length === 0) return false;\n\tfor (const tm of self._dep.terminal) if (tm === undefined) return false;\n\treturn true;\n}\n\nexport function nodeResetLifecycle<T>(self: NodeRuntimeHost<T>): void {\n\tfor (const u of self._dep.unsubs) if (u) u();\n\tself._dep.unsubs = [];\n\tself._dep.idxBoxes = [];\n\tself._lifecycle.subscribers.clear();\n\tself._lifecycle.activated = false;\n\tself._value.terminal = undefined;\n\tself._value.hasTorndown = false;\n\tself._wave.hasCalledFnOnce = false;\n\tself._resetDepState();\n\tself._control.pauseLockset.clear();\n\tself._control.pauseBuffer = [];\n\tself._control.pausedDepWaveOccurred = false;\n\tself._control.demandOwed = undefined; // R-pull (D269): drop any deferred demand\n\tself._control.activePull = undefined;\n\tself._control.pullDirtyOwed = false;\n\tself._value.replayRing = []; // BH6\n\tconst isCompute = self._slot.handle !== null || self._slot.deps.length > 0;\n\tif (isCompute) {\n\t\tself._value.cache = SENTINEL;\n\t\tself._value.hasData = false;\n\t\tself._value.status = \"sentinel\";\n\t} else {\n\t\tself._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t}\n\tif (!self._privateState.persist) self._privateState.value = SENTINEL;\n}\n\nexport function nodeEmitToSubs<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsg: Message,\n\tdelivery?: DeliveryMeta,\n): void {\n\tif (self._released) return;\n\t// Copy guards against subscribe/unsubscribe during iteration.\n\tconst subs = [...self._lifecycle.subscribers];\n\tfor (const sink of subs) sink(msg, delivery);\n}\n\nexport function nodeCommitBatchedWave<T>(self: NodeRuntimeHost<T>, wave: Wave): void {\n\tself._wave.batchDirtyOwed = false; // commit delivers the real settle (BH1)\n\tself._down(wave); // batch is inactive at commit -> processes normally\n}\n\nexport function nodeRollbackBatched<T>(self: NodeRuntimeHost<T>): void {\n\t// BH1: keyed on _batchDirtyOwed (not _emittedDirtyThisWave, which a fn wave between\n\t// defer and rollback would have reset) so the balancing RESOLVED is never skipped.\n\tif (self._wave.batchDirtyOwed) {\n\t\tself._wave.batchDirtyOwed = false;\n\t\tself._wave.emittedDirtyThisWave = false;\n\t\tself._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t\tself._emitToSubs([\"RESOLVED\"]);\n\t}\n}\n\nexport function nodeDeferBoundary<T>(\n\tself: NodeRuntimeHost<T>,\n\tfn: () => void,\n\tbatchToken?: object,\n): void {\n\tdeferRewire(self._core, fn, {\n\t\tbatchToken,\n\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t});\n}\n","import { currentBoundaryBatchToken, deferAfterBatchForTarget } from \"../batch/batch.js\";\nimport { deferRewire } from \"../batch/boundary.js\";\nimport type { NodeFn } from \"../ctx/types.js\";\nimport type { Wave } from \"../protocol/messages.js\";\nimport { errorPayload, SENTINEL } from \"../protocol/messages.js\";\nimport type { Node } from \"./node.js\";\nimport { type NodeRuntimeHost, nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport { notifyTopologyDepsChanged } from \"./runtime-accessors.js\";\nimport type { RewireOp } from \"./types.js\";\n\nexport function nodeRequestRewireNext<T>(self: NodeRuntimeHost<T>, op: RewireOp): void {\n\tdeferRewire(self._core, () => self._applyRewireNext(op), {\n\t\tbatchToken: currentBoundaryBatchToken(),\n\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t});\n}\n\nexport function nodeRequestUpNext<T>(\n\tself: NodeRuntimeHost<T>,\n\tmsgs: Wave,\n\ttowardDep?: number,\n): void {\n\tdeferRewire(\n\t\tself._core,\n\t\t() => {\n\t\t\tif (!self._released) self._up(msgs, towardDep);\n\t\t},\n\t\t{\n\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\tisReady: () => !self._hasBoundaryPauseLock(),\n\t\t},\n\t);\n}\n\nexport function nodeApplyRewireNext<T>(self: NodeRuntimeHost<T>, op: RewireOp): void {\n\tif (self._released) return;\n\ttry {\n\t\t// D62 / R-rewire-deferred: terminal seals output but does NOT cancel queued topology.\n\t\t// Public/immediate rewire of a terminal node still rejects; the exception is only for\n\t\t// self-triggered ops already issued before terminal and now draining at the boundary.\n\t\tif (op.kind === \"add\") {\n\t\t\tconst next = self._slot.deps.includes(op.dep)\n\t\t\t\t? [...self._slot.deps]\n\t\t\t\t: [...self._slot.deps, op.dep];\n\t\t\tself._rewire(next, op.fn, { allowTerminalOwner: true });\n\t\t} else if (op.kind === \"remove\") {\n\t\t\tself._rewire(\n\t\t\t\tself._slot.deps.filter((d) => d !== op.dep),\n\t\t\t\top.fn,\n\t\t\t\t{ allowTerminalOwner: true },\n\t\t\t);\n\t\t} else {\n\t\t\tself._rewire(self._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });\n\t\t}\n\t} catch (e) {\n\t\t// An invalid deferred op (cycle / self / non-resubscribable terminal dep) surfaces as\n\t\t// an ERROR on this node (D30-consistent) rather than stranding the rest of the drain\n\t\t// queue. Reachable only on misuse — higher-order operator inners are fresh, acyclic\n\t\t// leaf sources. Coerce a SENTINEL reason (a rewire fn that `throw undefined`s) to a real\n\t\t// Error so _down's R-data-payload guard does not itself throw out of the drain.\n\t\tself._down([[\"ERROR\", errorPayload(e, \"rewireNext op failed\")]]);\n\t}\n}\n\nexport function nodeRewire<T>(\n\tself: NodeRuntimeHost<T>,\n\tnewDeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: { allowTerminalOwner?: boolean } = {},\n): boolean {\n\tconst node = self as unknown as Node<unknown>;\n\t// ── rejects (R-rewire / D42) ──\n\tif (self._value.terminal !== undefined && !opts.allowTerminalOwner)\n\t\tthrow new Error(\n\t\t\t\"rewire: node is terminal (completed/errored) — cannot rewire (R-rewire / D42)\",\n\t\t);\n\tif (self._wave.insideRunWave)\n\t\tthrow new Error(\n\t\t\t\"rewire: mid-fn topology mutation — a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)\",\n\t\t);\n\tif (self._wave.inDepMutation)\n\t\tthrow new Error(\n\t\t\t\"rewire: reentrant dep mutation — another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)\",\n\t\t);\n\tif (newDeps.includes(node)) throw new Error(\"rewire: self-dependency rejected (R-rewire / D42)\");\n\tconst oldDeps = self._slot.deps;\n\tconst added = newDeps.filter((d) => !oldDeps.includes(d));\n\tfor (const d of added) {\n\t\tif (self._reachableUpstream(d, node))\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: would create a cycle — dep already transitively depends on this node (R-rewire / D42)\",\n\t\t\t);\n\t\tconst dep = nodeRuntimeHost(d);\n\t\tif (dep._value.terminal !== undefined && !dep._slot.resubscribable)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: cannot add a non-resubscribable terminal dep — would wedge (R-rewire / D42)\",\n\t\t\t);\n\t\tself._assertRewireDepOwner(d);\n\t}\n\n\tif (\n\t\tdeferAfterBatchForTarget(node, () => {\n\t\t\tself._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });\n\t\t})\n\t) {\n\t\treturn true;\n\t}\n\tif (!self._lifecycle.activated) self._restoredActivationPending = false;\n\n\tself._wave.inDepMutation = true;\n\tself._wave.rewireRunPending = false;\n\tlet zeroDepUnDirty = false;\n\ttry {\n\t\t// fn swap (SD-1): re-register against the same pool, then release the old handle\n\t\t// (B15) so the rewired-away fn closure is GC'd and its dispatcher slot is reused —\n\t\t// a rewire-heavy graph (CSP-2.7 *Map) no longer leaks a handle per swap. Register\n\t\t// first, then unregister the old: self._slot.handle never points at a freed slot, and a\n\t\t// null old handle (a passthrough/state node gaining a fn) has nothing to free.\n\t\tconst oldHandle = self._slot.handle;\n\t\tself._slot.handle = self._slot.dispatcher.register(fn, self._slot.pool);\n\t\tif (oldHandle !== null) self._slot.dispatcher.unregister(oldHandle);\n\n\t\tconst removed = oldDeps.filter((d) => !newDeps.includes(d));\n\t\tlet removedDirtyContributor = false;\n\t\tfor (const d of removed) {\n\t\t\tconst oldIdx = oldDeps.indexOf(d);\n\t\t\tif (self._dep.dirty[oldIdx]) {\n\t\t\t\tremovedDirtyContributor = true;\n\t\t\t\tself._wave.pending--;\n\t\t\t}\n\t\t\tif (self._lifecycle.activated) {\n\t\t\t\tconst box = self._dep.idxBoxes[oldIdx];\n\t\t\t\tif (box) box.v = -1; // drain: any stale in-flight callback drops\n\t\t\t\tconst unsub = self._dep.unsubs[oldIdx];\n\t\t\t\tif (unsub) unsub(); // stops the removed dep's edge — no further delivery\n\t\t\t}\n\t\t}\n\n\t\t// Rebuild per-dep parallel arrays in newDeps order; kept deps carry their state\n\t\t// + subscription, added deps start fresh (R-rewire Q1/Q4).\n\t\tconst n = newDeps.length;\n\t\tconst newBatch: Array<unknown[] | null> = new Array(n).fill(null);\n\t\tconst newPrev: unknown[] = new Array(n).fill(SENTINEL);\n\t\tconst newHasData: boolean[] = new Array(n).fill(false);\n\t\tconst newDirty: boolean[] = new Array(n).fill(false);\n\t\tconst newTier: number[] = new Array(n).fill(0);\n\t\tconst newTerminal: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\tconst newTerminalInput: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\tconst newUnsubs: Array<() => void> = new Array(n);\n\t\tconst newBoxes: Array<{ v: number }> = new Array(n);\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tconst oldIdx = oldDeps.indexOf(newDeps[j]);\n\t\t\tif (oldIdx !== -1) {\n\t\t\t\tnewBatch[j] = self._dep.batch[oldIdx];\n\t\t\t\tnewPrev[j] = self._dep.prev[oldIdx];\n\t\t\t\tnewHasData[j] = self._dep.hasData[oldIdx];\n\t\t\t\tnewDirty[j] = self._dep.dirty[oldIdx];\n\t\t\t\tnewTier[j] = self._dep.tier[oldIdx];\n\t\t\t\tnewTerminal[j] = self._dep.terminal[oldIdx];\n\t\t\t\tnewUnsubs[j] = self._dep.unsubs[oldIdx];\n\t\t\t\t// carry the kept dep's subscription box and point it at the new index (O(1) reroute)\n\t\t\t\tconst box = self._dep.idxBoxes[oldIdx];\n\t\t\t\tif (box) box.v = j;\n\t\t\t\tnewBoxes[j] = box;\n\t\t\t}\n\t\t}\n\t\tself._slot.deps = newDeps;\n\t\tself._dep.batch = newBatch;\n\t\tself._dep.prev = newPrev;\n\t\tself._dep.hasData = newHasData;\n\t\tself._dep.dirty = newDirty;\n\t\tself._dep.tier = newTier;\n\t\tself._dep.terminal = newTerminal;\n\t\tself._dep.terminalInput = newTerminalInput;\n\t\tself._dep.unsubs = newUnsubs;\n\t\tself._dep.idxBoxes = newBoxes;\n\t\tself._dep.waveData = newDeps.map(() => []);\n\t\tself._dep.waveTokens = new Array(newDeps.length).fill(undefined);\n\t\tself._syncCtx = null;\n\n\t\t// Subscribe added deps — push-on-subscribe (R-push-subscribe) delivers a cached\n\t\t// dep's DATA here, which drives _maybeRun; a SENTINEL dep delivers START only.\n\t\tif (self._lifecycle.activated) {\n\t\t\tfor (const d of added) self._subscribeDepAt(d);\n\t\t}\n\t\tnotifyTopologyDepsChanged(node, oldDeps, newDeps);\n\n\t\t// Q6 auto-settle: removing the sole dirty contributor closes the wave. With deps\n\t\t// remaining, request the atomic settle (recompute → DATA for a value; a no-emit fn\n\t\t// gets a substrate-synthesized undirty RESOLVED per R-resolved-undirty/D49 — NOT\n\t\t// equals-absorption, which is gone). With zero deps the node is inert (degenerate\n\t\t// fn-no-deps) — just un-dirty downstream. Cache is preserved either way (Q7).\n\t\tif (removedDirtyContributor && self._wave.pending === 0 && self._value.status === \"dirty\") {\n\t\t\tif (newDeps.length > 0) self._wave.rewireRunPending = true;\n\t\t\telse zeroDepUnDirty = true;\n\t\t}\n\t} finally {\n\t\tself._wave.inDepMutation = false;\n\t}\n\n\t// Atomic post-mutation settle (outside the reentrancy guard so a fresh wave runs\n\t// normally): ONE two-phase DIRTY→DATA recompute if any added dep delivered data or a\n\t// sole-dirty dep was removed; else the zero-dep un-dirty via _down (pause/batch-safe).\n\tif (self._wave.rewireRunPending) {\n\t\tself._wave.rewireRunPending = false;\n\t\tself._settleRewire();\n\t} else if (zeroDepUnDirty) {\n\t\tif (self._wave.emittedDirtyThisWave) self._down([[\"RESOLVED\"]]);\n\t\telse self._value.status = self._value.hasData ? \"settled\" : \"sentinel\";\n\t}\n\treturn false;\n}\n","/**\n * The node primitive — the thinnest substrate object (R-node-thin / D5).\n *\n * Holds a fn handle + deps + the wave state machine; ZERO inspection cruft\n * (naming/find/describe are the graph layer, CSP-2). Canonical authority:\n * ~/src/graphrefly/spec/rules.jsonl (R-node-*, R-two-phase, R-diamond, R-resolved-undirty,\n * R-first-run-gate, R-push-subscribe, R-rom-ram, R-fn-contract, R-initial, R-ctx-up).\n *\n * Slice 1 = core wave: state node, compute node, two-phase DIRTY->DATA, diamond\n * pending-counter join, first-run gate, substrate-synthesized undirty RESOLVED\n * (R-resolved-undirty / D49 — no equals-substitution; every occurrence is DATA),\n * push-on-subscribe, lazy activation, ROM/RAM. Lifecycle (terminal/INVALIDATE/cleanup),\n * control (PAUSE/async), batch, and dynamicNode land in later slices.\n */\n\nimport { enterWave, exitWave } from \"../batch/boundary.js\";\nimport type { Ctx, CtxState, DeliveryMeta, NodeFn, Sink } from \"../ctx/types.js\";\nimport { defaultDispatcher, type Handle } from \"../dispatcher/index.js\";\nimport { EnvironmentDrivers } from \"../graph/environment.js\";\nimport {\n\ttype LockId,\n\ttype Message,\n\ttype PullDemand,\n\tSENTINEL,\n\ttype Wave,\n} from \"../protocol/messages.js\";\nimport {\n\ttype CleanupHooks,\n\ttype ControlState,\n\ttype DepBookkeeping,\n\ttype LifecycleState,\n\tmakeDepBookkeeping,\n\tNodeCore,\n\ttype NodeId,\n\ttype NodeSlot,\n\ttype PrivateState,\n\ttype SyncCtxState,\n\ttype ValueState,\n\ttype VersionState,\n\ttype WaveState,\n} from \"./core.js\";\nimport {\n\tnodeBuildCtx,\n\tnodeMakeCtx,\n\tnodeMakeState,\n\tnodeRefreshCtx,\n} from \"./node-context-runtime.js\";\nimport {\n\tnodeAllDepsSettled,\n\tnodeDepProjectionHasData,\n\tnodeMarkDirty,\n\tnodeMaybeRun,\n\tnodePassthroughEmit,\n\tnodeReceiveFromDep,\n\tnodeRecordDepProjection,\n\tnodeReleaseDepDirty,\n\tnodeRunWave,\n\tnodeSettleAfterAbsorbedTerminal,\n\tnodeSettleRewire,\n\tnodeTryRun,\n} from \"./node-input-runtime.js\";\nimport {\n\tnodeActivate,\n\tnodeDeactivate,\n\tnodeIsRuntimeQuiescentForRelease,\n\tnodeReleaseRuntime,\n\tnodeResetDepState,\n\tnodeSeedRestoredDepAt,\n\tnodeSubscribeDepAt,\n\tnodeSubscriberCount,\n} from \"./node-lifecycle-runtime.js\";\nimport {\n\tnodeAllDepsTerminal,\n\tnodeCanFireDemand,\n\tnodeCommitBatchedWave,\n\tnodeDeferBoundary,\n\tnodeDeliverPullDemand,\n\tnodeDown,\n\tnodeEmitToSubs,\n\tnodeFireOwedDemandIfReady,\n\tnodeFirePullDemand,\n\tnodeForwardUp,\n\tnodeHasBoundaryPauseLock,\n\tnodeInvalidate,\n\tnodeIsAsyncPool,\n\tnodeIsPaused,\n\tnodeMarkDemandRouted,\n\tnodeOnDemand,\n\tnodeOnResume,\n\tnodePauseAcquire,\n\tnodePauseRelease,\n\tnodeResetLifecycle,\n\tnodeRollbackBatched,\n\tnodeShouldBufferOnPause,\n\tnodeUp,\n} from \"./node-output-runtime.js\";\nimport {\n\tnodeApplyRewireNext,\n\tnodeRequestRewireNext,\n\tnodeRequestUpNext,\n\tnodeRewire,\n} from \"./node-rewire-runtime.js\";\nimport { nodeRuntimeHost } from \"./node-runtime-host.js\";\nimport {\n\tactivationReaders,\n\tcheckpointReaders,\n\tgetNodeOwner,\n\trestoreWriters,\n\truntimeQuiescenceReaders,\n\truntimeReleasers,\n\tsubscriberCountReaders,\n\ttakeConstructingEnvironmentDrivers,\n\ttakeConstructingNodeCore,\n} from \"./runtime-accessors.js\";\nimport type { NodeOptions, RewireOp, Status, UpRouteState } from \"./types.js\";\nimport {\n\tcloneNodeVersion,\n\tcreateNodeVersion,\n\ttype NodeVersion,\n\tresolveNodeVersioningPolicy,\n\trestoredV1Cid,\n} from \"./versioning.js\";\n\nexport {\n\tcheckpointStateOfNode,\n\tgetNodeOwner,\n\tisNodeActiveForRelease,\n\tisNodeRuntimeQuiescentForRelease,\n\tisNodeRuntimeReleased,\n\treleaseRuntimeOfNode,\n\trestoreStateOfNode,\n\tsetNodeOwner,\n\tsetNodeTopologyDepsChangedObserver,\n\tsubscriberCountOfNode,\n\twithEnvironmentDrivers,\n\twithNodeCore,\n} from \"./runtime-accessors.js\";\nexport type { NodeCheckpointState, NodeOptions, NodeRestoreState, Status } from \"./types.js\";\n\n/**\n * Reactive substrate node that owns dependencies, wave handling, lifecycle, and subscribers.\n *\n * @example\n * ```ts\n * import { node } from \"@graphrefly/ts\";\n *\n * const source = node<number>([], null);\n * source.subscribe((value) => console.log(value));\n * source.down([[\"DATA\", 1]]);\n * ```\n * @remarks **Substrate primitive:** `Node` is graph-agnostic; use `graph().node`,\n * `graph().state`, or `graph().derived` when you want inspection and lifecycle ownership.\n * @category core\n */\nexport class Node<T = unknown> {\n\tprivate readonly _core: NodeCore;\n\tprivate readonly _id: NodeId;\n\tprivate readonly _slot: NodeSlot<T>;\n\tprivate readonly _dep: DepBookkeeping;\n\tprivate readonly _value: ValueState<T>;\n\tprivate readonly _wave: WaveState;\n\tprivate readonly _control: ControlState;\n\tprivate readonly _lifecycle: LifecycleState;\n\tprivate readonly _privateState: PrivateState;\n\tprivate readonly _hooks: CleanupHooks;\n\tprivate readonly _syncCtxState: SyncCtxState;\n\tprivate readonly _version: VersionState;\n\tprivate _restoredActivationPending = false;\n\tprivate _released = false;\n\n\tprivate get _syncCtx(): Ctx | null {\n\t\treturn this._syncCtxState.value;\n\t}\n\n\tprivate set _syncCtx(ctx: Ctx | null) {\n\t\tthis._syncCtxState.value = ctx;\n\t}\n\n\tprivate static _retainIndirectRuntimeMethods(node: Node<unknown>): void {\n\t\tvoid node._dep;\n\t\tvoid node._hooks;\n\t\tvoid node._restoredActivationPending;\n\t\tvoid node._requestRewireNext;\n\t\tvoid node._requestUpNext;\n\t\tvoid node._applyRewireNext;\n\t\tvoid node._reachableUpstream;\n\t\tvoid node._assertRewireDepOwner;\n\t\tvoid node._subscribeDepAt;\n\t\tvoid node._seedRestoredDepAt;\n\t\tvoid node._recordDepProjection;\n\t\tvoid node._depProjectionHasData;\n\t\tvoid node._receiveFromDep;\n\t\tvoid node._releaseDepDirty;\n\t\tvoid node._settleAfterAbsorbedTerminal;\n\t\tvoid node._markDirty;\n\t\tvoid node._maybeRun;\n\t\tvoid node._settleRewire;\n\t\tvoid node._tryRun;\n\t\tvoid node._allDepsSettled;\n\t\tvoid node._passthroughEmit;\n\t\tvoid node._runWave;\n\t\tvoid node._buildCtx;\n\t\tvoid node._makeCtx;\n\t\tvoid node._refreshCtx;\n\t\tvoid node._makeState;\n\t\tvoid node._markDemandRouted;\n\t\tvoid node._forwardUp;\n\t\tvoid node._isPullQuiet;\n\t\tvoid node._isPaused;\n\t\tvoid node._hasBoundaryPauseLock;\n\t\tvoid node._isAsyncPool;\n\t\tvoid node._pauseAcquire;\n\t\tvoid node._pauseRelease;\n\t\tvoid node._onResume;\n\t\tvoid node._canFireDemand;\n\t\tvoid node._deliverPullDemand;\n\t\tvoid node._onDemand;\n\t\tvoid node._firePullDemand;\n\t\tvoid node._fireOwedDemandIfReady;\n\t\tvoid node._shouldBufferOnPause;\n\t\tvoid node._invalidate;\n\t\tvoid node._allDepsTerminal;\n\t\tvoid node._emitToSubs;\n\t}\n\n\tconstructor(\n\t\tdeps: Node<unknown>[],\n\t\thandleOrFn: Handle | NodeFn | null,\n\t\topts: NodeOptions<T> = {},\n\t) {\n\t\tconst core = takeConstructingNodeCore();\n\t\tconst dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tconst environment = takeConstructingEnvironmentDrivers() ?? EnvironmentDrivers.empty();\n\t\tconst pool = opts.pool ?? \"sync\";\n\t\tconst pausable = opts.pausable ?? true;\n\t\tconst pullLock = opts.pullId;\n\t\tconst pull = opts.pullId !== undefined;\n\t\t// R-pull (D269): pull-mode is keyed by an author-supplied pullId (its quiet latch).\n\t\t// R-pull (D55, pin 3): pull still uses the pausable delivery-content axis; pausable:false\n\t\t// ignores PAUSE/RESUME buffering and contradicts quiet pull delivery. Reject at construction.\n\t\tif (pull && pausable === false)\n\t\t\tthrow new Error(\n\t\t\t\t\"node: pullId is incompatible with pausable:false — a pull node uses the pausable delivery-content axis (R-pull / R-pause-modes / D55,D269)\",\n\t\t\t);\n\n\t\tlet handle: Handle | null;\n\t\tif (handleOrFn === null) handle = null;\n\t\telse if (typeof handleOrFn === \"function\") handle = dispatcher.register(handleOrFn, pool);\n\t\telse handle = handleOrFn;\n\n\t\tconst n = deps.length;\n\t\tconst dep = makeDepBookkeeping(n);\n\t\tconst versioning = resolveNodeVersioningPolicy(opts.versioning);\n\t\tconst value = {\n\t\t\tcache: SENTINEL as T | undefined,\n\t\t\thasData: false,\n\t\t\tstatus: \"sentinel\" as Status,\n\t\t\tterminal: undefined,\n\t\t\thasTorndown: false,\n\t\t\treplayRing: [] as T[],\n\t\t};\n\t\tif (opts.initial !== undefined) {\n\t\t\tvalue.cache = opts.initial as T;\n\t\t\tvalue.hasData = true;\n\t\t\tvalue.status = \"settled\";\n\t\t}\n\t\tconst pauseLockset = new Set<unknown>();\n\t\tthis._core = core ?? new NodeCore();\n\t\tconst created = this._core.createSlot<T>(\n\t\t\t{\n\t\t\t\tdeps,\n\t\t\t\thandle,\n\t\t\t\tpool,\n\t\t\t\tdispatcher,\n\t\t\t\tenvironment,\n\t\t\t\tpartial: opts.partial ?? false,\n\t\t\t\tterminalAsRealInput: opts.terminalAsRealInput ?? false,\n\t\t\t\tcompleteWhenDepsComplete: opts.completeWhenDepsComplete ?? true,\n\t\t\t\terrorWhenDepsError: opts.errorWhenDepsError ?? true,\n\t\t\t\tresubscribable: opts.resubscribable ?? false,\n\t\t\t\tresetOnTeardown: opts.resetOnTeardown ?? false,\n\t\t\t\tpausable,\n\t\t\t\tpull,\n\t\t\t\tpullLock,\n\t\t\t\treplayN: opts.replayBuffer ?? 0,\n\t\t\t\tdynamic: opts.dynamic ?? false,\n\t\t\t\tname: opts.name,\n\t\t\t\tfactory: opts.factory,\n\t\t\t},\n\t\t\t{\n\t\t\t\tdep,\n\t\t\t\tlifecycle: { subscribers: new Set<Sink>(), activated: false },\n\t\t\t\tvalue,\n\t\t\t\twave: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\thasCalledFnOnce: false,\n\t\t\t\t\temittedDirtyThisWave: false,\n\t\t\t\t\temittedSettleThisWave: false,\n\t\t\t\t\tinsideRunWave: false,\n\t\t\t\t\tinDepMutation: false,\n\t\t\t\t\trewireRunPending: false,\n\t\t\t\t\tbatchDirtyOwed: false,\n\t\t\t\t},\n\t\t\t\tcontrol: {\n\t\t\t\t\tpauseLockset,\n\t\t\t\t\tpausedDepWaveOccurred: false,\n\t\t\t\t\tpauseBuffer: [],\n\t\t\t\t\tdemandOwed: undefined,\n\t\t\t\t\tactivePull: undefined,\n\t\t\t\t\tpullDirtyOwed: false,\n\t\t\t\t\tinDeliverDemand: false,\n\t\t\t\t},\n\t\t\t\tprivateState: { value: SENTINEL, persist: false },\n\t\t\t\thooks: { onDeactivation: [], onInvalidate: [] },\n\t\t\t\tsyncCtx: { value: null },\n\t\t\t\tversion: {\n\t\t\t\t\tpolicy: versioning,\n\t\t\t\t\tvalue: createNodeVersion(\n\t\t\t\t\t\tversioning,\n\t\t\t\t\t\topts.initial !== undefined ? opts.initial : undefined,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tthis._id = created.id;\n\t\tthis._slot = this._core.get<T>(this._id);\n\t\tthis._dep = this._core.getDep(this._id);\n\t\tthis._value = this._core.getValue<T>(this._id);\n\t\tthis._wave = this._core.getWave(this._id);\n\t\tthis._control = this._core.getControl(this._id);\n\t\tthis._lifecycle = this._core.getLifecycle(this._id);\n\t\tthis._privateState = this._core.getPrivateState(this._id);\n\t\tthis._hooks = this._core.getHooks(this._id);\n\t\tthis._syncCtxState = this._core.getSyncCtx(this._id);\n\t\tthis._version = this._core.getVersion(this._id);\n\t\tcheckpointReaders.set(this as Node<unknown>, () => ({\n\t\t\tcache: this._value.cache,\n\t\t\thasData: this._value.hasData,\n\t\t\tterminal: this._value.terminal,\n\t\t\tactivated: this._lifecycle.activated,\n\t\t\thasCalledFnOnce: this._wave.hasCalledFnOnce,\n\t\t\tctxState: {\n\t\t\t\tvalue: this._privateState.value,\n\t\t\t\tpersist: this._privateState.persist,\n\t\t\t},\n\t\t\tversion: cloneNodeVersion(this._version.value),\n\t\t\thandle: this._slot.handle,\n\t\t}));\n\t\trestoreWriters.set(this as Node<unknown>, (state) => {\n\t\t\tthis._assertNotReleased(\"restoreGraph\");\n\t\t\tthis._value.cache = state.cache as T;\n\t\t\tthis._value.hasData = state.hasData;\n\t\t\tthis._value.status = state.status;\n\t\t\tthis._value.terminal = state.terminal;\n\t\t\tthis._value.hasTorndown = false;\n\t\t\tthis._value.replayRing = [];\n\t\t\tthis._wave.hasCalledFnOnce = state.hasCalledFnOnce;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._wave.emittedSettleThisWave = false;\n\t\t\tthis._wave.pending = 0;\n\t\t\tthis._wave.insideRunWave = false;\n\t\t\tthis._wave.inDepMutation = false;\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = undefined;\n\t\t\tthis._control.activePull = undefined;\n\t\t\tthis._control.pullDirtyOwed = false;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t\tthis._control.pauseLockset.clear();\n\t\t\tthis._privateState.value = state.ctxState.value;\n\t\t\tthis._privateState.persist = state.ctxState.persist;\n\t\t\tif (state.version === false) {\n\t\t\t\tthis._version.policy = { enabled: false };\n\t\t\t\tthis._version.value = undefined;\n\t\t\t} else if (state.version.level === 0) {\n\t\t\t\tthis._version.policy = { enabled: true, level: 0 };\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t} else {\n\t\t\t\tif (!this._version.policy.enabled || this._version.policy.level !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// D109: V1 restore must match the selected hash lane. After DATA then\n\t\t\t\t// INVALIDATE/resetOnTeardown, cache is absent while cid remains the last DATA cid;\n\t\t\t\t// without the DATA value, restore cannot verify the lane, so fail honestly.\n\t\t\t\tif (!state.hasData && state.version.counter > 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);\n\t\t\t\tif (expectedCid !== state.version.cid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t}\n\t\t\tthis._syncCtx = null;\n\t\t\tthis._resetDepState();\n\t\t\t// A fresh restored graph has no subscribers before return. Keep activation closed so the\n\t\t\t// first real subscriber wires deps normally; D94's preserved lifecycle bit is the first-run\n\t\t\t// gate (`hasCalledFnOnce`), not a hidden subscription graph.\n\t\t\tthis._lifecycle.activated = false;\n\t\t\tthis._lifecycle.subscribers.clear();\n\t\t\tthis._restoredActivationPending = true;\n\t\t});\n\t\truntimeReleasers.set(this as Node<unknown>, () => this._releaseRuntime());\n\t\truntimeQuiescenceReaders.set(this as Node<unknown>, () => this._isRuntimeQuiescentForRelease());\n\t\tsubscriberCountReaders.set(this as Node<unknown>, () => this._subscriberCount());\n\t\tactivationReaders.set(this as Node<unknown>, () => this._lifecycle.activated);\n\t\tNode._retainIndirectRuntimeMethods(this as Node<unknown>);\n\t}\n\n\t/** R-pull (D55/D272): true while a pull node is not serving a PULL demand pulse. */\n\tprivate _isPullQuiet(): boolean {\n\t\treturn this._slot.pull && this._control.activePull === undefined;\n\t}\n\n\t/**\n\t * R-pull (D269/D272): this pull node's pullId (pure data, like {@link cache}/{@link handle} —\n\t * never triggers computation). A consumer demands one delivery by cone-routing PULL of it (no\n\t * node reference): `ctx.up([[\"PULL\", { pullId }]])` (immediate; loops back → D37 for a self-read\n\t * dep) or `ctx.upNext([[\"PULL\", { pullId }]])` (boundary-deferred self-demand). Undefined for a\n\t * non-pull node. The author writes the pullId verbatim; routing matches by identity.\n\t */\n\tget pullId(): LockId | undefined {\n\t\treturn this._slot.pullLock;\n\t}\n\n\tget cache(): T | undefined {\n\t\treturn this._value.cache;\n\t}\n\n\tget status(): Status {\n\t\treturn this._value.status;\n\t}\n\n\tget version(): NodeVersion | undefined {\n\t\treturn cloneNodeVersion(this._version.value);\n\t}\n\n\tget name(): string | undefined {\n\t\treturn this._slot.name;\n\t}\n\n\t/** R-describe/D51: real factory name for a standalone graph-less node (a runtime *Map inner). */\n\tget factory(): string | undefined {\n\t\treturn this._slot.factory;\n\t}\n\n\t/**\n\t * The node's CURRENT/LIVE deps (R-describe / R-edges-derived / D51) — readonly view of the\n\t * live `_deps`, which a rewire (C-8 / C-11) mutates. The graph's describe() reads this (NOT a\n\t * construction-time snapshot) so every edge corresponds to a real current subscription (D3).\n\t * Inspection-only, like cache/status; never triggers computation.\n\t */\n\tget deps(): readonly Node<unknown>[] {\n\t\treturn this._slot.deps;\n\t}\n\n\t/**\n\t * The fn handle (pure data `(poolId, handleId)`, D7) or null for state/passthrough\n\t * nodes. Inspection-only (L1.6 handle is referenceable/inspectable) — lets the graph\n\t * layer key a dispatcher-backed profile recorder WITHOUT putting counters on the node\n\t * (R-node-thin / D39).\n\t */\n\tget handle(): Handle | null {\n\t\treturn this._slot.handle;\n\t}\n\n\t/** R-push-subscribe: a new sink receives START, then cached DATA (or DIRTY if dirty). */\n\tsubscribe(sink: Sink): () => void {\n\t\tthis._assertNotReleased(\"subscribe\");\n\t\t// Wave-owner boundary (R-rewire-deferred / D47): the activation cascade can run fns that\n\t\t// issue ctx.rewireNext; the OUTERMOST exit drains them. Nested subscribes (dep wiring)\n\t\t// just inc/dec the depth.\n\t\tenterWave();\n\t\ttry {\n\t\t\t// R-terminal: late subscribe to a terminal node either resets (resubscribable)\n\t\t\t// or is rejected (non-resubscribable, R2.2.7.b).\n\t\t\tif (this._value.terminal !== undefined) {\n\t\t\t\tif (this._slot.resubscribable) {\n\t\t\t\t\tthis._restoredActivationPending = false;\n\t\t\t\t\tthis._resetLifecycle();\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"subscribe: node is non-resubscribable and has terminated; the stream is permanently over (R-terminal / R2.2.7.b)\",\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis._lifecycle.subscribers.add(sink);\n\t\t\tsink([\"START\"]);\n\t\t\tif (this._slot.replayN > 0 && this._value.replayRing.length > 0) {\n\t\t\t\t// R-replay-buffer: late subscriber gets the last N DATA after START.\n\t\t\t\tfor (const v of this._value.replayRing) sink([\"DATA\", v]);\n\t\t\t} else if (this._value.hasData && !this._slot.pull) {\n\t\t\t\t// R-pull (D55): a pull node NEVER push-on-subscribes its cached value — quiet by\n\t\t\t\t// default, it stays silent until demanded (START only). QA-B4: gated on `_pull`, not\n\t\t\t\t// activePull, so a REACTIVATED pull node still does not leak its cache.\n\t\t\t\tsink([\"DATA\", this._value.cache]);\n\t\t\t} else if (this._value.status === \"dirty\" && !this._slot.pull) {\n\t\t\t\tsink([\"DIRTY\"]);\n\t\t\t}\n\n\t\t\tif (!this._lifecycle.activated) this._activate();\n\n\t\t\treturn () => {\n\t\t\t\tif (!this._lifecycle.subscribers.delete(sink)) return;\n\t\t\t\tif (this._lifecycle.subscribers.size === 0) this._deactivate();\n\t\t\t};\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */\n\tdown(msgs: Wave): void {\n\t\tthis._assertNotReleased(\"down\");\n\t\t// Wave-owner boundary (D47): a state.set / external push that drives a fn issuing\n\t\t// ctx.rewireNext drains at this outermost exit.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._down(msgs);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up\n\t * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t */\n\tup(msgs: Wave, towardDep?: number): void {\n\t\tthis._assertNotReleased(\"up\");\n\t\t// Wave-owner boundary (D47). Internal dep-forwarding calls dep.up() nest under this.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._up(msgs, towardDep);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t// ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──\n\n\t/**\n\t * Replace this node's deps atomically (surgical, Option-C). Requires an explicit\n\t * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps\n\t * keep their subscription + per-dep state; only removed deps unsubscribe and only\n\t * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The\n\t * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).\n\t */\n\treplaceDeps(newDeps: Node<unknown>[], fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"replaceDeps\");\n\t\tthis._rewire(this._dedupDeps(newDeps), fn);\n\t}\n\n\t/** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */\n\tsubscribeDep(depNode: Node<unknown>, fn: NodeFn): number {\n\t\tthis._assertNotReleased(\"subscribeDep\");\n\t\tconst next = this._slot.deps.includes(depNode)\n\t\t\t? [...this._slot.deps]\n\t\t\t: [...this._slot.deps, depNode];\n\t\tconst deferred = this._rewire(next, fn);\n\t\treturn deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);\n\t}\n\n\t/** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */\n\tunsubscribeDep(depNode: Node<unknown>, fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"unsubscribeDep\");\n\t\tthis._rewire(\n\t\t\tthis._slot.deps.filter((d) => d !== depNode),\n\t\t\tfn,\n\t\t);\n\t}\n\n\tprivate _requestRewireNext(op: RewireOp): void {\n\t\tnodeRequestRewireNext(nodeRuntimeHost(this), op);\n\t}\n\n\tprivate _requestUpNext(msgs: Wave, towardDep?: number): void {\n\t\tnodeRequestUpNext(nodeRuntimeHost(this), msgs, towardDep);\n\t}\n\n\tprivate _applyRewireNext(op: RewireOp): void {\n\t\tnodeApplyRewireNext(nodeRuntimeHost(this), op);\n\t}\n\n\tprivate _dedupDeps(deps: Node<unknown>[]): Node<unknown>[] {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst out: Node<unknown>[] = [];\n\t\tfor (const d of deps)\n\t\t\tif (!seen.has(d)) {\n\t\t\t\tseen.add(d);\n\t\t\t\tout.push(d);\n\t\t\t}\n\t\treturn out;\n\t}\n\n\tprivate _reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst stack: Node<unknown>[] = [from];\n\t\twhile (stack.length > 0) {\n\t\t\tconst n = stack.pop();\n\t\t\tif (n === undefined) continue;\n\t\t\tif (n === target) return true;\n\t\t\tif (seen.has(n)) continue;\n\t\t\tseen.add(n);\n\t\t\tfor (const d of nodeRuntimeHost(n)._slot.deps) stack.push(d);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _assertRewireDepOwner(dep: Node<unknown>): void {\n\t\tconst selfOwner = getNodeOwner(this as unknown as Node<unknown>);\n\t\tconst depOwner = getNodeOwner(dep);\n\t\tif (selfOwner !== undefined && depOwner !== undefined && selfOwner !== depOwner)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)\",\n\t\t\t);\n\t}\n\n\tprivate _rewire(\n\t\tnewDeps: Node<unknown>[],\n\t\tfn: NodeFn,\n\t\topts: { allowTerminalOwner?: boolean } = {},\n\t): boolean {\n\t\treturn nodeRewire(nodeRuntimeHost(this), newDeps, fn, opts);\n\t}\n\n\t// ── activation / deactivation (lazy; R-rom-ram) ──\n\n\tprivate _activate(): void {\n\t\tnodeActivate(nodeRuntimeHost(this));\n\t}\n\n\tprivate _deactivate(): void {\n\t\tnodeDeactivate(nodeRuntimeHost(this));\n\t}\n\n\tprivate _assertNotReleased(op: string): void {\n\t\tif (this._released)\n\t\t\tthrow new Error(`${op}: node has been released from its graph lifecycle (D122)`);\n\t}\n\n\tprivate _subscriberCount(): number {\n\t\treturn nodeSubscriberCount(nodeRuntimeHost(this));\n\t}\n\n\tprivate _isRuntimeQuiescentForRelease(): boolean {\n\t\treturn nodeIsRuntimeQuiescentForRelease(nodeRuntimeHost(this));\n\t}\n\n\tprivate _releaseRuntime(): void {\n\t\tnodeReleaseRuntime(nodeRuntimeHost(this));\n\t}\n\n\tprivate _resetDepState(): void {\n\t\tnodeResetDepState(nodeRuntimeHost(this));\n\t}\n\n\tprivate _subscribeDepAt(depNode: Node<unknown>, opts: { seedRestored?: boolean } = {}): void {\n\t\tnodeSubscribeDepAt(nodeRuntimeHost(this), depNode, opts);\n\t}\n\n\tprivate _seedRestoredDepAt(idx: number, depNode: Node<unknown>): void {\n\t\tnodeSeedRestoredDepAt(nodeRuntimeHost(this), idx, depNode);\n\t}\n\n\tprivate _recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[] {\n\t\treturn nodeRecordDepProjection(nodeRuntimeHost(this), idx, delivery);\n\t}\n\n\tprivate _depProjectionHasData(idx: number): boolean {\n\t\treturn nodeDepProjectionHasData(nodeRuntimeHost(this), idx);\n\t}\n\n\tprivate _receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void {\n\t\tnodeReceiveFromDep(nodeRuntimeHost(this), idx, msg, delivery);\n\t}\n\n\tprivate _releaseDepDirty(idx: number): void {\n\t\tnodeReleaseDepDirty(nodeRuntimeHost(this), idx);\n\t}\n\n\tprivate _settleAfterAbsorbedTerminal(): void {\n\t\tnodeSettleAfterAbsorbedTerminal(nodeRuntimeHost(this));\n\t}\n\n\tprivate _markDirty(): void {\n\t\tnodeMarkDirty(nodeRuntimeHost(this));\n\t}\n\n\tprivate _maybeRun(): void {\n\t\tnodeMaybeRun(nodeRuntimeHost(this));\n\t}\n\n\tprivate _settleRewire(): void {\n\t\tnodeSettleRewire(nodeRuntimeHost(this));\n\t}\n\n\tprivate _tryRun(): void {\n\t\tnodeTryRun(nodeRuntimeHost(this));\n\t}\n\n\tprivate _allDepsSettled(): boolean {\n\t\treturn nodeAllDepsSettled(nodeRuntimeHost(this));\n\t}\n\n\tprivate _passthroughEmit(): void {\n\t\tnodePassthroughEmit(nodeRuntimeHost(this));\n\t}\n\n\tprivate _runWave(): void {\n\t\tnodeRunWave(nodeRuntimeHost(this));\n\t}\n\n\tprivate _buildCtx(): Ctx {\n\t\treturn nodeBuildCtx(nodeRuntimeHost(this));\n\t}\n\n\tprivate _makeCtx(snapshot?: {\n\t\twaveData: unknown[][][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): Ctx {\n\t\treturn nodeMakeCtx(nodeRuntimeHost(this), snapshot);\n\t}\n\n\tprivate _refreshCtx(ctx: Ctx): void {\n\t\tnodeRefreshCtx(nodeRuntimeHost(this), ctx);\n\t}\n\n\tprivate _makeState(): CtxState {\n\t\treturn nodeMakeState(nodeRuntimeHost(this));\n\t}\n\n\t// ── downstream emission pipeline (the unified waist) ──\n\n\tprivate _down(msgs: Wave): void {\n\t\tnodeDown(nodeRuntimeHost(this), msgs);\n\t}\n\n\tprivate _up(msgs: Wave, towardDep?: number, route?: UpRouteState): void {\n\t\tnodeUp(nodeRuntimeHost(this), msgs, towardDep, route);\n\t}\n\n\tprivate _markDemandRouted(lockId: LockId, route: UpRouteState): boolean {\n\t\treturn nodeMarkDemandRouted(nodeRuntimeHost(this), lockId, route);\n\t}\n\n\tprivate _forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void {\n\t\tnodeForwardUp(nodeRuntimeHost(this), m, towardDep, route);\n\t}\n\n\tprivate _isPaused(): boolean {\n\t\treturn nodeIsPaused(nodeRuntimeHost(this));\n\t}\n\n\tprivate _hasBoundaryPauseLock(): boolean {\n\t\treturn nodeHasBoundaryPauseLock(nodeRuntimeHost(this));\n\t}\n\n\tprivate _isAsyncPool(): boolean {\n\t\treturn nodeIsAsyncPool(nodeRuntimeHost(this));\n\t}\n\n\tprivate _pauseAcquire(lockId: unknown): void {\n\t\tnodePauseAcquire(nodeRuntimeHost(this), lockId);\n\t}\n\n\tprivate _pauseRelease(lockId: unknown): void {\n\t\tnodePauseRelease(nodeRuntimeHost(this), lockId);\n\t}\n\n\tprivate _onResume(): void {\n\t\tnodeOnResume(nodeRuntimeHost(this));\n\t}\n\n\tprivate _canFireDemand(): boolean {\n\t\treturn nodeCanFireDemand(nodeRuntimeHost(this));\n\t}\n\n\tprivate _deliverPullDemand(demand: PullDemand): void {\n\t\tnodeDeliverPullDemand(nodeRuntimeHost(this), demand);\n\t}\n\n\tprivate _onDemand(demand: PullDemand): void {\n\t\tnodeOnDemand(nodeRuntimeHost(this), demand);\n\t}\n\n\tprivate _firePullDemand(): void {\n\t\tnodeFirePullDemand(nodeRuntimeHost(this));\n\t}\n\n\tprivate _fireOwedDemandIfReady(): void {\n\t\tnodeFireOwedDemandIfReady(nodeRuntimeHost(this));\n\t}\n\n\tprivate _shouldBufferOnPause(): boolean {\n\t\treturn nodeShouldBufferOnPause(nodeRuntimeHost(this));\n\t}\n\n\tprivate _invalidate(delivery?: DeliveryMeta): void {\n\t\tnodeInvalidate(nodeRuntimeHost(this), delivery);\n\t}\n\n\tprivate _allDepsTerminal(): boolean {\n\t\treturn nodeAllDepsTerminal(nodeRuntimeHost(this));\n\t}\n\n\tprivate _emitToSubs(msg: Message, delivery?: DeliveryMeta): void {\n\t\tnodeEmitToSubs(nodeRuntimeHost(this), msg, delivery);\n\t}\n\n\t/** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */\n\tprivate _resetLifecycle(): void {\n\t\tnodeResetLifecycle(nodeRuntimeHost(this));\n\t}\n\n\t/** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */\n\t__commitBatchedWave(wave: Wave): void {\n\t\tnodeCommitBatchedWave(nodeRuntimeHost(this), wave);\n\t}\n\n\t/** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */\n\t__rollbackBatched(): void {\n\t\tnodeRollbackBatched(nodeRuntimeHost(this));\n\t}\n\n\t/** B49: enqueue a committed-boundary task on this node's graph-local core. */\n\t__deferBoundary(fn: () => void, batchToken?: object): void {\n\t\tnodeDeferBoundary(nodeRuntimeHost(this), fn, batchToken);\n\t}\n}\n\n/**\n * Construct a node (R-node-iface / D5 / L1.9 deps-first).\n * node([], null, { initial }) — state node (manual source; emit via .down)\n * node([], fn) — producer (runs on activation)\n * node([a, b], fn) — compute / derived\n * node([dep]) — passthrough wire\n *\n * @param deps - Upstream nodes this node reads positionally from `ctx`.\n * @param handleOrFn - Dispatcher handle, node function, or `null` for a manual source/state node.\n * @param opts - Node runtime options such as `initial`, `name`, pool, dispatcher, and restore data.\n * @returns A graph-agnostic `Node`.\n * @example\n * ```ts\n * import { depLatest, node } from \"@graphrefly/ts\";\n *\n * const source = node<number>([], null, { initial: 1 });\n * const doubled = node<number>([source], (ctx) => {\n * ctx.down([[\"DATA\", Number(depLatest(ctx, 0)) * 2]]);\n * });\n * ```\n * @category core\n */\nexport function node<T = unknown>(\n\tdeps: Node<unknown>[] = [],\n\thandleOrFn: Handle | NodeFn | null = null,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, handleOrFn, opts);\n}\n\n/**\n * Construct a dynamicNode (R-dynamic-node / D35) — a node variant whose fn reads a\n * subset of a fixed superset of deps per invocation via `ctx.track(i)`. All declared\n * deps participate in wave tracking; an unread dep's change re-runs the fn, which re-emits\n * its current value as DATA (D49 removed equals-absorption — dedup is opt-in via\n * distinctUntilChanged). Intra-graph only (D22).\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","import type { DataIssue } from \"../../data/index.js\";\nimport type { Graph } from \"../../graph/graph.js\";\nimport type { Node } from \"../../node/node.js\";\n\n/**\n * Synchronous text measurement contract for the D181 reactive-layout solution core.\n *\n * Implementations are injected by the caller; the universal subpath never imports DOM,\n * Canvas, React Native, storage, GraphSpec, or async image loading.\n */\nexport interface MeasurementAdapter {\n\tmeasureSegment(text: string, font: string): { readonly width: number };\n\tclearCache?(): void;\n}\n\n/** Caller-owned platform text capability, for NodeCanvas/Skia/RN-style wrappers. */\nexport interface TextMeasureCapability {\n\tmeasureText(text: string, font: string): number | { readonly width: number };\n\tclearCache?(): void;\n}\n\n/** One text segment returned by a caller-provided segmenter. */\nexport interface SegmentInfo {\n\treadonly segment: string;\n\treadonly index: number;\n\treadonly isWordLike?: boolean;\n}\n\n/** Synchronous word/grapheme segmentation contract for hosts without Intl.Segmenter. */\nexport interface SegmentAdapter {\n\tsegmentWords(text: string): Iterable<SegmentInfo>;\n\tsegmentGraphemes(text: string): Iterable<SegmentInfo>;\n}\n\n/** Layout segment class used by the line breaker. */\nexport type SegmentBreakKind = \"text\" | \"space\" | \"zero-width-break\" | \"soft-hyphen\" | \"hard-break\";\n\n/** Measured text run consumed by pure line/block/flow helpers. */\nexport interface PreparedSegment {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly kind: SegmentBreakKind;\n\treadonly graphemeWidths: readonly number[] | null;\n}\n\n/** One laid-out line with segment/grapheme cursor bounds. */\nexport interface LayoutLine {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly startSegment: number;\n\treadonly startGrapheme: number;\n\treadonly endSegment: number;\n\treadonly endGrapheme: number;\n}\n\n/** Positioned grapheme box for hit testing or custom renderers. */\nexport interface CharPosition {\n\treadonly x: number;\n\treadonly y: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly line: number;\n}\n\n/** Result emitted by `reactiveLayout().lineBreaks`. */\nexport interface LineBreaksResult {\n\treadonly lines: readonly LayoutLine[];\n\treadonly lineCount: number;\n}\n\n/** Cursor into a prepared segment array. */\nexport interface LayoutCursor {\n\treadonly segmentIndex: number;\n\treadonly graphemeIndex: number;\n}\n\n/** Pure helper result for one `layoutNextLine` step. */\nexport interface LayoutNextLineResult {\n\treadonly text: string;\n\treadonly width: number;\n\treadonly start: LayoutCursor;\n\treadonly end: LayoutCursor;\n}\n\n/** Horizontal interval used by obstacle carving. */\nexport interface Interval {\n\treadonly left: number;\n\treadonly right: number;\n}\n\nexport const TEXT_SEGMENTS_MEASUREMENT_KIND = \"text-segments\";\nexport const BLOCKS_MEASUREMENT_KIND = \"blocks\";\n/** Measurement kind for standalone readiness facts. */\nexport const READINESS_MEASUREMENT_KIND = \"readiness\";\n/** Measurement kind for standalone image-size facts. */\nexport const IMAGE_SIZE_MEASUREMENT_KIND = \"image-size\";\n/** Measurement kind for standalone SVG-bounds facts. */\nexport const SVG_BOUNDS_MEASUREMENT_KIND = \"svg-bounds\";\n\nexport interface TextSegmentsMeasurement {\n\treadonly segments: readonly PreparedSegment[];\n\treadonly hyphenWidth?: number;\n}\n\nexport interface BlocksMeasurement {\n\treadonly blocks: readonly MeasuredBlock[];\n}\n\nexport interface MeasurementResult<T = unknown> {\n\treadonly kind: \"ok\";\n\treadonly targetId: string;\n\treadonly measurementKind: string;\n\treadonly value: T;\n\treadonly source?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport interface MeasurementIssue extends DataIssue {\n\treadonly subjectId: string;\n\treadonly measurementKind: string;\n}\n\nexport type MeasurementFact<T = unknown> = MeasurementResult<T> | MeasurementIssue;\n\nexport type Measurements = readonly MeasurementFact[];\n\nexport interface MergeMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly sources: readonly Node<Measurements>[];\n\treadonly name?: string;\n}\n\nexport interface TextMeasurementProviderOptions {\n\treadonly graph: Graph;\n\treadonly text: Node<string>;\n\treadonly font: Node<string>;\n\treadonly adapter: Node<MeasurementAdapter>;\n\treadonly segmentAdapter?: Node<SegmentAdapter>;\n\treadonly targetId?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface InjectedTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\"> {\n\treadonly measure: MeasureFn;\n\treadonly cache?: boolean;\n}\n\nexport interface PrecomputedTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\">,\n\t\tPrecomputedMeasureAdapterOptions {}\n\nexport interface CellTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\">,\n\t\tCellMeasureAdapterOptions {}\n\nexport interface CapabilityTextMeasurementsOptions\n\textends Omit<TextMeasurementProviderOptions, \"adapter\"> {\n\treadonly capability: Node<TextMeasureCapability>;\n}\n\nexport interface MeasurementReadiness {\n\treadonly ready: boolean;\n\treadonly code?: string;\n\treadonly message?: string;\n\treadonly source?: string;\n\treadonly details?: unknown;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting readiness into graph-visible measurement facts. */\nexport interface ReadinessMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly readiness: Node<MeasurementReadiness>;\n\treadonly targetId?: string;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface ReadinessTextMeasurementsOptions extends TextMeasurementProviderOptions {\n\treadonly readiness: Node<MeasurementReadiness>;\n}\n\n/** Minimal caller-owned lookup for explicit image sizes. */\nexport interface ImageSizeLookup {\n\tget(src: string): Size | undefined;\n}\n\n/** One image-size fact target for `imageSizeMeasurements`. */\nexport interface ImageSizeMeasurementTarget {\n\treadonly id?: string;\n\treadonly src: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting image-size facts from a caller-owned synchronous measurer. */\nexport interface ImageSizeMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly images: Node<readonly ImageSizeMeasurementTarget[]>;\n\treadonly measurer: Node<ImageMeasurer>;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\n/** One SVG-bounds fact target for `svgBoundsMeasurements`. */\nexport interface SvgBoundsMeasurementTarget {\n\treadonly id?: string;\n\treadonly svg: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Options for projecting SVG bounds from a caller-owned synchronous measurer. */\nexport interface SvgBoundsMeasurementsOptions {\n\treadonly graph: Graph;\n\treadonly svgs: Node<readonly SvgBoundsMeasurementTarget[]>;\n\treadonly measurer: Node<SvgMeasurer>;\n\treadonly measurementKind?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface BlockMeasurementProviderOptions {\n\treadonly graph: Graph;\n\treadonly blocks: Node<readonly ContentBlock[]>;\n\treadonly maxWidth: Node<number>;\n\treadonly adapters: Node<BlockAdapters>;\n\treadonly segmentAdapter?: Node<SegmentAdapter>;\n\treadonly font?: Node<string>;\n\treadonly lineHeight?: Node<number>;\n\treadonly targetId?: string;\n\treadonly source?: string;\n\treadonly name?: string;\n}\n\nexport interface BlockAdaptersProviderOptions {\n\treadonly graph: Graph;\n\treadonly text?: Node<MeasurementAdapter>;\n\treadonly svg?: Node<SvgMeasurer>;\n\treadonly image?: Node<ImageMeasurer>;\n\treadonly name?: string;\n}\n\n/**\n * Graph-visible bundle returned by `reactiveLayout`.\n *\n * The setters are state-node sugar over real graph inputs; the output nodes are ordinary\n * inspectable nodes visible through `graph.describe()`.\n */\nexport interface ReactiveLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly lineHeight: Node<number>;\n\t\treadonly maxWidth: Node<number>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetLineHeight(lineHeight: number): void;\n\tsetMaxWidth(maxWidth: number): void;\n\treadonly segments: Node<readonly PreparedSegment[]>;\n\treadonly lineBreaks: Node<LineBreaksResult>;\n\treadonly height: Node<number>;\n\treadonly charPositions: Node<readonly CharPosition[]>;\n}\n\n/** Optional context shared by pure line-breaking helpers. */\nexport interface LayoutNextLineContext {\n\treadonly adapter?: MeasurementAdapter;\n\treadonly font?: string;\n\treadonly cache?: Map<string, Map<string, number>>;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Cache accounting object callers can pass into `analyzeAndMeasure`. */\nexport interface SegmentMeasureStats {\n\thits: number;\n\tmisses: number;\n}\n\n/** Options for the single-column reactive text layout bundle. */\nexport interface ReactiveLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly segmentAdapter?: SegmentAdapter;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly lineHeight?: number | Node<number>;\n\treadonly maxWidth?: number | Node<number>;\n}\n\n/** Host text measurement function accepted by `InjectedMeasureAdapter`. */\nexport type MeasureFn = (text: string, font: string) => number | { readonly width: number };\n\n/** Options for caller-injected synchronous measurement. */\nexport interface InjectedMeasureAdapterOptions {\n\treadonly cache?: boolean;\n}\n\n/** Options for deterministic precomputed text metrics. */\nexport interface PrecomputedMeasureAdapterOptions {\n\treadonly metrics: ReadonlyMap<string, number> | Record<string, number>;\n\treadonly fallback?: \"per-char\" | \"error\";\n\treadonly cellWidth?: number;\n}\n\n/** Fixed-cell measurement options for terminal/snapshot rendering. */\nexport interface CellMeasureAdapterOptions {\n\treadonly cellWidth?: number;\n\treadonly wideCellWidth?: number;\n\treadonly tabCells?: number;\n}\n\n/** Width/height pair in CSS-like pixels. */\nexport interface Size {\n\treadonly width: number;\n\treadonly height: number;\n}\n\n/** Synchronous SVG measurement seam; no DOM parser is provided by the core. */\nexport interface SvgMeasurer {\n\tmeasureSvg(svg: string): Size;\n}\n\n/** Synchronous image measurement seam; no loading/fetching is provided by the core. */\nexport interface ImageMeasurer {\n\tmeasureImage(src: string): Size;\n}\n\n/** Optional per-kind block measurement adapters. */\nexport interface BlockAdapters {\n\treadonly text?: MeasurementAdapter;\n\treadonly svg?: SvgMeasurer;\n\treadonly image?: ImageMeasurer;\n}\n\n/** Shared spacing/id fields for block layout inputs. */\nexport interface BaseContentBlock {\n\treadonly id?: string;\n\treadonly marginTop?: number;\n\treadonly marginBottom?: number;\n}\n\n/** Text block input for `measureBlock` and `reactiveBlockLayout`. */\nexport interface TextContentBlock extends BaseContentBlock {\n\treadonly kind: \"text\";\n\treadonly text: string;\n\treadonly font?: string;\n\treadonly lineHeight?: number;\n\treadonly maxWidth?: number;\n}\n\n/** Image block input with explicit dimensions or an injected `ImageMeasurer`. */\nexport interface ImageContentBlock extends BaseContentBlock {\n\treadonly kind: \"image\";\n\treadonly src: string;\n\treadonly width?: number;\n\treadonly height?: number;\n\treadonly maxWidth?: number;\n}\n\n/** SVG block input with explicit dimensions or an injected `SvgMeasurer`. */\nexport interface SvgContentBlock extends BaseContentBlock {\n\treadonly kind: \"svg\";\n\treadonly svg: string;\n\treadonly width?: number;\n\treadonly height?: number;\n\treadonly maxWidth?: number;\n}\n\n/** Heterogeneous block-layout input. */\nexport type ContentBlock = TextContentBlock | ImageContentBlock | SvgContentBlock;\n\n/** Measured block produced by `measureBlock` or `measureBlocks`. */\nexport interface MeasuredBlock {\n\treadonly block: ContentBlock;\n\treadonly kind: ContentBlock[\"kind\"];\n\treadonly id?: string;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly marginTop: number;\n\treadonly marginBottom: number;\n\treadonly segments?: readonly PreparedSegment[];\n\treadonly lineBreaks?: LineBreaksResult;\n\treadonly charPositions?: readonly CharPosition[];\n}\n\n/** Block with vertical-flow coordinates. */\nexport interface PositionedBlock extends MeasuredBlock {\n\treadonly x: number;\n\treadonly y: number;\n}\n\n/** Options for pure block measurement helpers. */\nexport interface MeasureBlockOptions {\n\treadonly adapter?: MeasurementAdapter;\n\treadonly adapters?: BlockAdapters;\n\treadonly font?: string;\n\treadonly lineHeight?: number;\n\treadonly maxWidth?: number;\n\treadonly cache?: Map<string, Map<string, number>>;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Options for the graph-visible block layout bundle. */\nexport interface ReactiveBlockLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly gap?: number | Node<number>;\n}\n\n/** Graph-visible vertical block layout bundle. */\nexport interface ReactiveBlockLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly gap: Node<number>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetGap(gap: number): void;\n\treadonly measuredBlocks: Node<readonly MeasuredBlock[]>;\n\treadonly blockFlow: Node<readonly PositionedBlock[]>;\n\treadonly totalHeight: Node<number>;\n}\n\n/** Circular obstacle for flow layout slot carving. */\nexport interface CircleObstacle {\n\treadonly kind: \"circle\";\n\treadonly cx: number;\n\treadonly cy: number;\n\treadonly r: number;\n}\n\n/** Rectangular obstacle for flow layout slot carving. */\nexport interface RectObstacle {\n\treadonly kind: \"rect\";\n\treadonly x: number;\n\treadonly y: number;\n\treadonly width: number;\n\treadonly height: number;\n}\n\n/** Obstacle shape accepted by flow layout. */\nexport type Obstacle = CircleObstacle | RectObstacle;\n\n/** Flow container geometry. */\nexport interface FlowContainer {\n\treadonly width: number;\n\treadonly height: number;\n\treadonly paddingX?: number;\n\treadonly paddingY?: number;\n}\n\n/** Optional column geometry for flow layout. */\nexport interface FlowColumns {\n\treadonly count?: number;\n\treadonly gap?: number;\n}\n\n/** Positioned line emitted by `computeFlowLines` / `reactiveFlowLayout`. */\nexport interface PositionedLine extends LayoutLine {\n\treadonly x: number;\n\treadonly y: number;\n\treadonly slotWidth: number;\n\treadonly columnIndex: number;\n}\n\n/** Flow layout result plus the continuation cursor. */\nexport interface FlowLinesResult {\n\treadonly lines: readonly PositionedLine[];\n\treadonly cursor: LayoutCursor;\n\treadonly done: boolean;\n}\n\n/** Options for pure flow layout computation. */\nexport interface ComputeFlowLinesOptions {\n\treadonly container: FlowContainer;\n\treadonly columns?: FlowColumns;\n\treadonly obstacles?: readonly Obstacle[];\n\treadonly lineHeight: number;\n\treadonly minSlotWidth?: number;\n\treadonly hyphenWidth?: number;\n\treadonly segmentAdapter?: SegmentAdapter;\n}\n\n/** Options for the graph-visible flow layout bundle. */\nexport interface ReactiveFlowLayoutOptions {\n\treadonly measurements: Node<Measurements>;\n\treadonly graph: Graph;\n\treadonly segmentAdapter?: SegmentAdapter;\n\treadonly targetId?: string;\n\treadonly name?: string;\n\treadonly lineHeight?: number | Node<number>;\n\treadonly container?: FlowContainer | Node<FlowContainer>;\n\treadonly columns?: FlowColumns | Node<FlowColumns>;\n\treadonly obstacles?: readonly Obstacle[] | Node<readonly Obstacle[]>;\n\treadonly minSlotWidth?: number;\n}\n\n/** Graph-visible multi-column flow layout bundle. */\nexport interface ReactiveFlowLayoutBundle {\n\treadonly graph: Graph;\n\treadonly input: {\n\t\treadonly lineHeight: Node<number>;\n\t\treadonly container: Node<FlowContainer>;\n\t\treadonly columns: Node<FlowColumns>;\n\t\treadonly obstacles: Node<readonly Obstacle[]>;\n\t\treadonly measurements: Node<Measurements>;\n\t};\n\tsetLineHeight(lineHeight: number): void;\n\tsetContainer(container: FlowContainer): void;\n\tsetColumns(columns: FlowColumns): void;\n\tsetObstacles(obstacles: readonly Obstacle[]): void;\n\treadonly segments: Node<readonly PreparedSegment[]>;\n\treadonly flowLines: Node<FlowLinesResult>;\n}\n","import { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport type { DataIssue } from \"../../data/index.js\";\nimport type { Graph, StateNode } from \"../../graph/graph.js\";\nimport { Node } from \"../../node/node.js\";\nimport {\n\tCapabilityMeasureAdapter,\n\tCellMeasureAdapter,\n\tInjectedMeasureAdapter,\n\tPrecomputedMeasureAdapter,\n} from \"./adapters.js\";\nimport { measureBlock } from \"./block.js\";\nimport { analyzeAndMeasure } from \"./line.js\";\nimport { getDefaultSegmentAdapter } from \"./segment.js\";\nimport type {\n\tBlockAdapters,\n\tBlockAdaptersProviderOptions,\n\tBlockMeasurementProviderOptions,\n\tBlocksMeasurement,\n\tCapabilityTextMeasurementsOptions,\n\tCellTextMeasurementsOptions,\n\tContentBlock,\n\tImageMeasurer,\n\tImageSizeMeasurementsOptions,\n\tImageSizeMeasurementTarget,\n\tInjectedTextMeasurementsOptions,\n\tMeasuredBlock,\n\tMeasurementAdapter,\n\tMeasurementFact,\n\tMeasurementIssue,\n\tMeasurementReadiness,\n\tMeasurementResult,\n\tMeasurements,\n\tMergeMeasurementsOptions,\n\tPrecomputedTextMeasurementsOptions,\n\tReadinessMeasurementsOptions,\n\tReadinessTextMeasurementsOptions,\n\tSegmentAdapter,\n\tSize,\n\tSvgBoundsMeasurementsOptions,\n\tSvgBoundsMeasurementTarget,\n\tSvgMeasurer,\n\tTextMeasureCapability,\n\tTextMeasurementProviderOptions,\n\tTextSegmentsMeasurement,\n} from \"./types.js\";\nimport {\n\tBLOCKS_MEASUREMENT_KIND,\n\tIMAGE_SIZE_MEASUREMENT_KIND,\n\tREADINESS_MEASUREMENT_KIND,\n\tSVG_BOUNDS_MEASUREMENT_KIND,\n\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n} from \"./types.js\";\nimport { nonNegativeFinite } from \"./utils.js\";\n\nexport function measurementIssue(\n\tcode: string,\n\tmessage: string,\n\ttargetId: string,\n\tmeasurementKind: string,\n\topts: {\n\t\treadonly source?: string;\n\t\treadonly details?: unknown;\n\t\treadonly metadata?: Record<string, unknown>;\n\t\treadonly severity?: DataIssue[\"severity\"];\n\t} = {},\n): MeasurementIssue {\n\treturn {\n\t\tkind: \"issue\",\n\t\tcode,\n\t\tmessage,\n\t\tseverity: opts.severity ?? \"warning\",\n\t\tsource: opts.source,\n\t\tsubjectId: targetId,\n\t\tmeasurementKind,\n\t\tdetails: opts.details,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nexport function measurementOk<T>(\n\ttargetId: string,\n\tmeasurementKind: string,\n\tvalue: T,\n\topts: { readonly source?: string; readonly metadata?: Record<string, unknown> } = {},\n): MeasurementResult<T> {\n\treturn {\n\t\tkind: \"ok\",\n\t\ttargetId,\n\t\tmeasurementKind,\n\t\tvalue,\n\t\tsource: opts.source,\n\t\tmetadata: opts.metadata,\n\t};\n}\n\nexport function latestMeasurementValue<T>(\n\tmeasurements: Measurements,\n\ttargetId: string,\n\tmeasurementKind: string,\n): T | undefined {\n\tlet value: T | undefined;\n\tfor (const fact of measurements) {\n\t\tif (\n\t\t\tfact.kind === \"ok\" &&\n\t\t\tfact.targetId === targetId &&\n\t\t\tfact.measurementKind === measurementKind\n\t\t) {\n\t\t\tvalue = fact.value as T;\n\t\t}\n\t}\n\treturn value;\n}\n\nexport function tryMeasureHyphenWidth(\n\tadapter: MeasurementAdapter,\n\tfont: string,\n): number | undefined {\n\ttry {\n\t\treturn nonNegativeFinite(adapter.measureSegment(\"-\", font).width, 0);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function validMeasurementSize(size: Size, label: string): Size {\n\tif (\n\t\t!Number.isFinite(size.width) ||\n\t\t!Number.isFinite(size.height) ||\n\t\tsize.width < 0 ||\n\t\tsize.height < 0\n\t) {\n\t\tthrow new Error(`Invalid ${label} measurement size`);\n\t}\n\treturn size;\n}\n\nexport function textMeasurementFacts(\n\ttext: string,\n\tfont: string,\n\tadapter: MeasurementAdapter,\n\tcache: Map<string, Map<string, number>>,\n\tsegmentAdapter: SegmentAdapter,\n\ttargetId: string,\n\tsource: string,\n): Measurements {\n\ttry {\n\t\tconst segments = analyzeAndMeasure(text, font, adapter, cache, undefined, segmentAdapter);\n\t\tconst hyphenWidth = tryMeasureHyphenWidth(adapter, font);\n\t\tconst facts: MeasurementFact<TextSegmentsMeasurement>[] = [\n\t\t\tmeasurementOk<TextSegmentsMeasurement>(\n\t\t\t\ttargetId,\n\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\thyphenWidth === undefined ? { segments } : { segments, hyphenWidth },\n\t\t\t\t{ source },\n\t\t\t),\n\t\t];\n\t\tif (hyphenWidth === undefined) {\n\t\t\tfacts.push(\n\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\"measurement.hyphen.failed\",\n\t\t\t\t\t`Hyphen measurement failed for '${targetId}'`,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t\t{ source, severity: \"warning\" },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn facts;\n\t} catch (error) {\n\t\treturn [\n\t\t\tmeasurementIssue(\n\t\t\t\t\"measurement.failed\",\n\t\t\t\t`Text measurement failed for '${targetId}'`,\n\t\t\t\ttargetId,\n\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t{ source, details: error, severity: \"error\" },\n\t\t\t),\n\t\t];\n\t}\n}\n\nexport function inputNode<T>(\n\tg: Graph,\n\tinput: T | Node<T> | undefined,\n\tfallback: T,\n\tname: string,\n): { readonly node: Node<T>; readonly set: (value: T) => void } {\n\tif (input instanceof Node) {\n\t\treturn {\n\t\t\tnode: input,\n\t\t\tset(value: T): void {\n\t\t\t\tconst maybeState = input as Node<T> & { set?: (next: T) => void };\n\t\t\t\tif (typeof maybeState.set !== \"function\") {\n\t\t\t\t\tthrow new TypeError(`reactive-layout input '${name}' is not a writable state node`);\n\t\t\t\t}\n\t\t\t\tmaybeState.set(value);\n\t\t\t},\n\t\t};\n\t}\n\tconst state: StateNode<T> = g.state(input ?? fallback, { name });\n\treturn { node: state, set: (value: T) => state.set(value) };\n}\n\nexport function scopedName(scope: string, local: string): string {\n\treturn scope === local ? local : `${scope}:${local}`;\n}\n\n/** Generic sync text measurement provider that emits graph-visible measurement facts. */\nexport function textMeasurementProvider(opts: TextMeasurementProviderOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeAdapter: MeasurementAdapter | null = null;\n\treturn opts.graph.node<Measurements>(\n\t\topts.segmentAdapter\n\t\t\t? [opts.text, opts.font, opts.adapter, opts.segmentAdapter]\n\t\t\t: [opts.text, opts.font, opts.adapter],\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\t(depLatest(ctx, 2) as MeasurementAdapter).clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\tconst text = depLatest(ctx, 0) as string;\n\t\t\tconst font = depLatest(ctx, 1) as string;\n\t\t\tconst adapter = depLatest(ctx, 2) as MeasurementAdapter;\n\t\t\tif (adapter !== activeAdapter) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveAdapter = adapter;\n\t\t\t}\n\t\t\tconst segmentAdapter =\n\t\t\t\topts.segmentAdapter === undefined\n\t\t\t\t\t? getDefaultSegmentAdapter()\n\t\t\t\t\t: (depLatest(ctx, 3) as SegmentAdapter);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\ttextMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for caller-injected synchronous text measurement. */\nexport function injectedTextMeasurements(\n\topts: InjectedTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(\n\t\tnew InjectedMeasureAdapter(opts.measure, { cache: opts.cache }),\n\t\t{\n\t\t\tname: opts.name\n\t\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t\t: `${targetId}-measure-capability`,\n\t\t},\n\t);\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"injectedTextMeasurements\",\n\t});\n}\n\n/** Provider helper for deterministic precomputed text metrics. */\nexport function precomputedTextMeasurements(\n\topts: PrecomputedTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(new PrecomputedMeasureAdapter(opts), {\n\t\tname: opts.name\n\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t: `${targetId}-measure-capability`,\n\t});\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"precomputedTextMeasurements\",\n\t});\n}\n\n/** Provider helper for fixed-cell terminal/snapshot text measurement. */\nexport function cellTextMeasurements(opts: CellTextMeasurementsOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.state<MeasurementAdapter>(new CellMeasureAdapter(opts), {\n\t\tname: opts.name\n\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t: `${targetId}-measure-capability`,\n\t});\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"cellTextMeasurements\",\n\t});\n}\n\n/** Provider helper for caller-injected platform text capability nodes. */\nexport function capabilityTextMeasurements(\n\topts: CapabilityTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst adapter = opts.graph.node<MeasurementAdapter>(\n\t\t[opts.capability],\n\t\t(ctx: Ctx) => {\n\t\t\tctx.down([\n\t\t\t\t[\"DATA\", new CapabilityMeasureAdapter(depLatest(ctx, 0) as TextMeasureCapability)],\n\t\t\t]);\n\t\t},\n\t\t{\n\t\t\tname: opts.name\n\t\t\t\t? scopedName(opts.name, \"measure-capability\")\n\t\t\t\t: `${targetId}-measure-capability`,\n\t\t},\n\t);\n\treturn textMeasurementProvider({\n\t\t...opts,\n\t\tadapter,\n\t\tsource: opts.source ?? \"capabilityTextMeasurements\",\n\t});\n}\n\n/** Provider helper that makes readiness facts an explicit measurement dependency. */\nexport function readinessTextMeasurements(\n\topts: ReadinessTextMeasurementsOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeAdapter: MeasurementAdapter | null = null;\n\tlet activeReadiness: MeasurementReadiness | null = null;\n\tconst deps = opts.segmentAdapter\n\t\t? [opts.text, opts.font, opts.adapter, opts.readiness, opts.segmentAdapter]\n\t\t: [opts.text, opts.font, opts.adapter, opts.readiness];\n\treturn opts.graph.node<Measurements>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\t(depLatest(ctx, 2) as MeasurementAdapter).clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\tconst text = depLatest(ctx, 0) as string;\n\t\t\tconst font = depLatest(ctx, 1) as string;\n\t\t\tconst adapter = depLatest(ctx, 2) as MeasurementAdapter;\n\t\t\tif (adapter !== activeAdapter) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveAdapter = adapter;\n\t\t\t}\n\t\t\tconst readiness = depLatest(ctx, 3) as MeasurementReadiness;\n\t\t\tif (readiness !== activeReadiness) {\n\t\t\t\tcache.clear();\n\t\t\t\tactiveReadiness = readiness;\n\t\t\t}\n\t\t\tif (!readiness.ready) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\treadiness.code ?? \"measurement.not-ready\",\n\t\t\t\t\t\t\t\treadiness.message ?? `Measurement readiness blocked '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\t\t\tdetails: readiness.details,\n\t\t\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst segmentAdapter =\n\t\t\t\topts.segmentAdapter === undefined\n\t\t\t\t\t? getDefaultSegmentAdapter()\n\t\t\t\t\t: (depLatest(ctx, 4) as SegmentAdapter);\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\ttextMeasurementFacts(text, font, adapter, cache, segmentAdapter, targetId, source),\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper that emits graph-visible readiness facts without measuring layout. */\nexport function readinessMeasurements(opts: ReadinessMeasurementsOptions): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"measurement-readiness\";\n\tconst measurementKind = opts.measurementKind ?? READINESS_MEASUREMENT_KIND;\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.readiness],\n\t\t(ctx: Ctx) => {\n\t\t\tconst readiness = depLatest(ctx, 0) as MeasurementReadiness;\n\t\t\tif (!readiness.ready) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\treadiness.code ?? \"measurement.not-ready\",\n\t\t\t\t\t\t\t\treadiness.message ?? `Measurement readiness blocked '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\t\t\tdetails: readiness.details,\n\t\t\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.down([\n\t\t\t\t[\n\t\t\t\t\t\"DATA\",\n\t\t\t\t\t[\n\t\t\t\t\t\tmeasurementOk<MeasurementReadiness>(targetId, measurementKind, readiness, {\n\t\t\t\t\t\t\tsource: readiness.source ?? source,\n\t\t\t\t\t\t\tmetadata: readiness.metadata,\n\t\t\t\t\t\t}),\n\t\t\t\t\t],\n\t\t\t\t],\n\t\t\t]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for image-size facts from caller-owned synchronous image measurers. */\nexport function imageSizeMeasurements(opts: ImageSizeMeasurementsOptions): Node<Measurements> {\n\tconst measurementKind = opts.measurementKind ?? IMAGE_SIZE_MEASUREMENT_KIND;\n\tconst name = opts.name ?? \"image-size-measurements\";\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.images, opts.measurer],\n\t\t(ctx: Ctx) => {\n\t\t\tconst images = depLatest(ctx, 0) as readonly ImageSizeMeasurementTarget[];\n\t\t\tconst measurer = depLatest(ctx, 1) as ImageMeasurer;\n\t\t\tconst facts: MeasurementFact<Size>[] = [];\n\t\t\tfor (let i = 0; i < images.length; i += 1) {\n\t\t\t\tconst image = (images as readonly (ImageSizeMeasurementTarget | undefined)[])[i];\n\t\t\t\tconst subjectId = image?.id ?? image?.src ?? `image:${i}`;\n\t\t\t\ttry {\n\t\t\t\t\tif (image === undefined) throw new Error(`Missing image target at index ${i}`);\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementOk<Size>(\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\tvalidMeasurementSize(measurer.measureImage(image.src), \"image\"),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tmetadata: image.metadata,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\"measurement.image-size.failed\",\n\t\t\t\t\t\t\t`Image size measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tdetails: { error, index: i, src: image?.src },\n\t\t\t\t\t\t\t\tmetadata: image?.metadata,\n\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Provider helper for SVG bounds facts from caller-owned synchronous SVG measurers. */\nexport function svgBoundsMeasurements(opts: SvgBoundsMeasurementsOptions): Node<Measurements> {\n\tconst measurementKind = opts.measurementKind ?? SVG_BOUNDS_MEASUREMENT_KIND;\n\tconst name = opts.name ?? \"svg-bounds-measurements\";\n\tconst source = opts.source ?? name;\n\treturn opts.graph.node<Measurements>(\n\t\t[opts.svgs, opts.measurer],\n\t\t(ctx: Ctx) => {\n\t\t\tconst svgs = depLatest(ctx, 0) as readonly SvgBoundsMeasurementTarget[];\n\t\t\tconst measurer = depLatest(ctx, 1) as SvgMeasurer;\n\t\t\tconst facts: MeasurementFact<Size>[] = [];\n\t\t\tfor (let i = 0; i < svgs.length; i += 1) {\n\t\t\t\tconst svg = (svgs as readonly (SvgBoundsMeasurementTarget | undefined)[])[i];\n\t\t\t\tconst subjectId = svg?.id ?? `svg:${i}`;\n\t\t\t\ttry {\n\t\t\t\t\tif (svg === undefined) throw new Error(`Missing SVG target at index ${i}`);\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementOk<Size>(\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\tvalidMeasurementSize(measurer.measureSvg(svg.svg), \"SVG\"),\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tmetadata: svg.metadata,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfacts.push(\n\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\"measurement.svg-bounds.failed\",\n\t\t\t\t\t\t\t`SVG bounds measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\tmeasurementKind,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\tdetails: { error, index: i },\n\t\t\t\t\t\t\t\tmetadata: svg?.metadata,\n\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name },\n\t);\n}\n\n/** Merge provider fact nodes into the single measurements node consumed by layout bundles. */\nexport function mergeMeasurements(opts: MergeMeasurementsOptions): Node<Measurements> {\n\tconst sources = [...opts.sources];\n\treturn opts.graph.node<Measurements>(\n\t\tsources as readonly Node<unknown>[],\n\t\t(ctx: Ctx) => {\n\t\t\tconst facts: MeasurementFact[] = [];\n\t\t\tfor (let i = 0; i < sources.length; i += 1) {\n\t\t\t\tfacts.push(...(depLatest(ctx, i) as Measurements));\n\t\t\t}\n\t\t\tctx.down([[\"DATA\", facts]]);\n\t\t},\n\t\t{ name: opts.name ?? \"measurements\" },\n\t);\n}\n\n/** Compose optional block measurement capability nodes into one graph-visible adapter node. */\nexport function blockAdaptersProvider(opts: BlockAdaptersProviderOptions): Node<BlockAdapters> {\n\tconst deps: Node<unknown>[] = [];\n\tconst positions: { text?: number; svg?: number; image?: number } = {};\n\tif (opts.text) {\n\t\tpositions.text = deps.length;\n\t\tdeps.push(opts.text);\n\t}\n\tif (opts.svg) {\n\t\tpositions.svg = deps.length;\n\t\tdeps.push(opts.svg);\n\t}\n\tif (opts.image) {\n\t\tpositions.image = deps.length;\n\t\tdeps.push(opts.image);\n\t}\n\treturn opts.graph.node<BlockAdapters>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst adapters: BlockAdapters = {\n\t\t\t\ttext:\n\t\t\t\t\tpositions.text === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: (depLatest(ctx, positions.text) as MeasurementAdapter),\n\t\t\t\tsvg:\n\t\t\t\t\tpositions.svg === undefined ? undefined : (depLatest(ctx, positions.svg) as SvgMeasurer),\n\t\t\t\timage:\n\t\t\t\t\tpositions.image === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: (depLatest(ctx, positions.image) as ImageMeasurer),\n\t\t\t};\n\t\t\tctx.down([[\"DATA\", adapters]]);\n\t\t},\n\t\t{ name: opts.name ?? \"block-adapters\" },\n\t);\n}\n\n/** Provider helper for block measurement facts over declared block/max-width deps. */\nexport function blockMeasurementProvider(\n\topts: BlockMeasurementProviderOptions,\n): Node<Measurements> {\n\tconst targetId = opts.targetId ?? \"blocks\";\n\tconst name = opts.name ?? `${targetId}-measurements`;\n\tconst source = opts.source ?? name;\n\tconst cache = new Map<string, Map<string, number>>();\n\tlet activeTextAdapter: MeasurementAdapter | undefined;\n\tconst deps = [opts.blocks, opts.maxWidth, opts.adapters] as Node<unknown>[];\n\tif (opts.font) deps.push(opts.font);\n\tif (opts.lineHeight) deps.push(opts.lineHeight);\n\tif (opts.segmentAdapter) deps.push(opts.segmentAdapter);\n\treturn opts.graph.node<Measurements>(\n\t\tdeps,\n\t\t(ctx: Ctx) => {\n\t\t\tconst flush = () => {\n\t\t\t\tcache.clear();\n\t\t\t\tconst adapters = depLatest(ctx, 2) as BlockAdapters;\n\t\t\t\tadapters.text?.clearCache?.();\n\t\t\t};\n\t\t\tctx.onDeactivation(flush);\n\t\t\tctx.onInvalidate(flush);\n\t\t\ttry {\n\t\t\t\tconst blocks = depLatest(ctx, 0) as readonly ContentBlock[];\n\t\t\t\tconst maxWidth = nonNegativeFinite(depLatest(ctx, 1) as number, 0);\n\t\t\t\tconst adapters = depLatest(ctx, 2) as BlockAdapters;\n\t\t\t\tif (adapters.text !== activeTextAdapter) {\n\t\t\t\t\tcache.clear();\n\t\t\t\t\tactiveTextAdapter = adapters.text;\n\t\t\t\t}\n\t\t\t\tlet depIndex = 3;\n\t\t\t\tconst font = opts.font ? (depLatest(ctx, depIndex++) as string) : undefined;\n\t\t\t\tconst lineHeight = opts.lineHeight\n\t\t\t\t\t? nonNegativeFinite(depLatest(ctx, depIndex++) as number, 0)\n\t\t\t\t\t: undefined;\n\t\t\t\tconst segmentAdapter = opts.segmentAdapter\n\t\t\t\t\t? (depLatest(ctx, depIndex) as SegmentAdapter)\n\t\t\t\t\t: getDefaultSegmentAdapter();\n\t\t\t\tconst measured: MeasuredBlock[] = [];\n\t\t\t\tconst issues: MeasurementIssue[] = [];\n\t\t\t\tfor (let i = 0; i < blocks.length; i += 1) {\n\t\t\t\t\tconst block = (blocks as readonly (ContentBlock | undefined)[])[i];\n\t\t\t\t\tconst subjectId = block?.id ?? `${targetId}:${i}`;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (block === undefined) {\n\t\t\t\t\t\t\tthrow new Error(`Missing content block at index ${i}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst blockFont =\n\t\t\t\t\t\t\tblock.kind === \"text\" ? (block.font ?? font ?? \"16px sans-serif\") : undefined;\n\t\t\t\t\t\tconst hyphenWidth =\n\t\t\t\t\t\t\tblock.kind === \"text\" && adapters.text\n\t\t\t\t\t\t\t\t? tryMeasureHyphenWidth(adapters.text, blockFont ?? \"16px sans-serif\")\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tmeasured.push(\n\t\t\t\t\t\t\tmeasureBlock(block, {\n\t\t\t\t\t\t\t\tadapters,\n\t\t\t\t\t\t\t\tfont,\n\t\t\t\t\t\t\t\thyphenWidth,\n\t\t\t\t\t\t\t\tlineHeight,\n\t\t\t\t\t\t\t\tmaxWidth,\n\t\t\t\t\t\t\t\tcache,\n\t\t\t\t\t\t\t\tsegmentAdapter,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (block.kind === \"text\" && adapters.text) {\n\t\t\t\t\t\t\tif (hyphenWidth === undefined) {\n\t\t\t\t\t\t\t\tissues.push(\n\t\t\t\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\t\t\"measurement.hyphen.failed\",\n\t\t\t\t\t\t\t\t\t\t`Hyphen measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\t\t\t\tdetails: { targetId, index: i },\n\t\t\t\t\t\t\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tissues.push(\n\t\t\t\t\t\t\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\"measurement.block.failed\",\n\t\t\t\t\t\t\t\t`Block measurement failed for '${subjectId}'`,\n\t\t\t\t\t\t\t\tsubjectId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\t\t\tdetails: { error, targetId, index: i, blockKind: block?.kind },\n\t\t\t\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\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\tmeasurementOk<BlocksMeasurement>(\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{ blocks: measured },\n\t\t\t\t\t\t\t\t{ source },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...issues,\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t} catch (error) {\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\tmeasurementIssue(\n\t\t\t\t\t\t\t\t\"measurement.failed\",\n\t\t\t\t\t\t\t\t`Block measurement failed for '${targetId}'`,\n\t\t\t\t\t\t\t\ttargetId,\n\t\t\t\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t\t\t\t\t{ source, details: error, severity: \"error\" },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t],\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t},\n\t\t{ name },\n\t);\n}\n","import { analyzeAndMeasure, computeCharPositions, computeLineBreaks } from \"./line.js\";\nimport { tryMeasureHyphenWidth } from \"./measurements.js\";\nimport type { ContentBlock, MeasureBlockOptions, MeasuredBlock, PositionedBlock } from \"./types.js\";\nimport {\n\tblockMaxWidth,\n\tclampDimension,\n\tfitSize,\n\tnonNegativeFinite,\n\tpositiveFinite,\n\tresolveTextAdapter,\n} from \"./utils.js\";\n\n/** Measure one text/image/SVG block using only explicit or injected synchronous adapters. */\nexport function measureBlock(block: ContentBlock, opts: MeasureBlockOptions): MeasuredBlock {\n\tconst maxWidth = nonNegativeFinite(opts.maxWidth ?? 800, 800);\n\tconst marginTop = nonNegativeFinite(block.marginTop ?? 0, 0);\n\tconst marginBottom = nonNegativeFinite(block.marginBottom ?? 0, 0);\n\tif (block.kind === \"text\") {\n\t\tconst adapter = resolveTextAdapter(opts);\n\t\tconst font = block.font ?? opts.font ?? \"16px sans-serif\";\n\t\tconst lineHeight = positiveFinite(block.lineHeight ?? opts.lineHeight ?? 20, 20);\n\t\tconst cache = opts.cache ?? new Map<string, Map<string, number>>();\n\t\tconst width = blockMaxWidth(block.maxWidth, maxWidth);\n\t\tconst segments = analyzeAndMeasure(\n\t\t\tblock.text,\n\t\t\tfont,\n\t\t\tadapter,\n\t\t\tcache,\n\t\t\tundefined,\n\t\t\topts.segmentAdapter,\n\t\t);\n\t\tconst hyphenWidth = Object.hasOwn(opts, \"hyphenWidth\")\n\t\t\t? opts.hyphenWidth\n\t\t\t: tryMeasureHyphenWidth(adapter, font);\n\t\tconst lineBreaks = computeLineBreaks(segments, width, {\n\t\t\thyphenWidth,\n\t\t\tsegmentAdapter: opts.segmentAdapter,\n\t\t});\n\t\tconst charPositions = computeCharPositions(\n\t\t\tlineBreaks,\n\t\t\tsegments,\n\t\t\tlineHeight,\n\t\t\topts.segmentAdapter,\n\t\t);\n\t\treturn {\n\t\t\tblock,\n\t\t\tkind: block.kind,\n\t\t\tid: block.id,\n\t\t\twidth: lineBreaks.lines.reduce((acc, line) => Math.max(acc, line.width), 0),\n\t\t\theight: lineBreaks.lineCount * lineHeight,\n\t\t\tmarginTop,\n\t\t\tmarginBottom,\n\t\t\tsegments,\n\t\t\tlineBreaks,\n\t\t\tcharPositions,\n\t\t};\n\t}\n\tif (block.kind === \"image\") {\n\t\tconst explicit =\n\t\t\tblock.width !== undefined && block.height !== undefined\n\t\t\t\t? { width: clampDimension(block.width), height: clampDimension(block.height) }\n\t\t\t\t: opts.adapters?.image?.measureImage(block.src);\n\t\tif (!explicit) throw new Error(\"Image blocks require width/height or an ImageMeasurer\");\n\t\tconst size = fitSize(explicit, blockMaxWidth(block.maxWidth, maxWidth));\n\t\treturn {\n\t\t\tblock,\n\t\t\tkind: block.kind,\n\t\t\tid: block.id,\n\t\t\twidth: size.width,\n\t\t\theight: size.height,\n\t\t\tmarginTop,\n\t\t\tmarginBottom,\n\t\t};\n\t}\n\tconst explicit =\n\t\tblock.width !== undefined && block.height !== undefined\n\t\t\t? { width: clampDimension(block.width), height: clampDimension(block.height) }\n\t\t\t: opts.adapters?.svg?.measureSvg(block.svg);\n\tif (!explicit) throw new Error(\"SVG blocks require width/height or a SvgMeasurer\");\n\tconst size = fitSize(explicit, blockMaxWidth(block.maxWidth, maxWidth));\n\treturn {\n\t\tblock,\n\t\tkind: block.kind,\n\t\tid: block.id,\n\t\twidth: size.width,\n\t\theight: size.height,\n\t\tmarginTop,\n\t\tmarginBottom,\n\t};\n}\n\n/** Measure a block list while sharing a measurement cache across text blocks. */\nexport function measureBlocks(\n\tblocks: readonly ContentBlock[],\n\topts: MeasureBlockOptions,\n): readonly MeasuredBlock[] {\n\tconst cache = opts.cache ?? new Map<string, Map<string, number>>();\n\treturn blocks.map((block) => measureBlock(block, { ...opts, cache }));\n}\n\n/** Stack measured blocks vertically with margins and a fixed gap. */\nexport function computeBlockFlow(\n\tblocks: readonly MeasuredBlock[],\n\tgap = 0,\n): readonly PositionedBlock[] {\n\tconst spacing = nonNegativeFinite(gap, 0);\n\tlet y = 0;\n\treturn blocks.map((block) => {\n\t\ty += block.marginTop;\n\t\tconst positioned: PositionedBlock = { ...block, x: 0, y };\n\t\ty += block.height + block.marginBottom + spacing;\n\t\treturn positioned;\n\t});\n}\n\n/** Compute the bottom edge of a positioned block flow. */\nexport function computeTotalHeight(blocks: readonly PositionedBlock[]): number {\n\tif (blocks.length === 0) return 0;\n\tlet bottom = 0;\n\tfor (const block of blocks) {\n\t\tbottom = Math.max(bottom, block.y + block.height + block.marginBottom);\n\t}\n\treturn bottom;\n}\n","import { carveTextLineSlots, layoutNextLine } from \"./line.js\";\nimport { getDefaultSegmentAdapter } from \"./segment.js\";\nimport type {\n\tCircleObstacle,\n\tComputeFlowLinesOptions,\n\tFlowColumns,\n\tFlowContainer,\n\tFlowLinesResult,\n\tInterval,\n\tLayoutCursor,\n\tObstacle,\n\tPositionedLine,\n\tPreparedSegment,\n\tRectObstacle,\n} from \"./types.js\";\nimport { finiteNumber, nonNegativeFinite, positiveFinite } from \"./utils.js\";\n\nexport function columnGeometry(\n\tcontainer: FlowContainer,\n\tcolumns: FlowColumns | undefined,\n): {\n\treadonly paddingX: number;\n\treadonly paddingY: number;\n\treadonly count: number;\n\treadonly gap: number;\n\treadonly width: number;\n\treadonly height: number;\n\treadonly columnWidth: number;\n} {\n\tconst paddingX = nonNegativeFinite(container.paddingX ?? 0, 0);\n\tconst paddingY = nonNegativeFinite(container.paddingY ?? 0, 0);\n\tconst count = Math.max(1, Math.floor(nonNegativeFinite(columns?.count ?? 1, 1)));\n\tconst gap = nonNegativeFinite(columns?.gap ?? 0, 0);\n\tconst width = nonNegativeFinite(container.width, 0);\n\tconst height = nonNegativeFinite(container.height, 0);\n\tconst innerWidth = Math.max(0, width - paddingX * 2 - gap * (count - 1));\n\tconst columnWidth = count > 0 ? innerWidth / count : 0;\n\treturn { paddingX, paddingY, count, gap, width, height, columnWidth };\n}\n\nexport function sanitizeFlowContainer(container: FlowContainer): FlowContainer {\n\treturn {\n\t\twidth: nonNegativeFinite(container.width, 0),\n\t\theight: nonNegativeFinite(container.height, 0),\n\t\tpaddingX:\n\t\t\tcontainer.paddingX === undefined ? undefined : nonNegativeFinite(container.paddingX, 0),\n\t\tpaddingY:\n\t\t\tcontainer.paddingY === undefined ? undefined : nonNegativeFinite(container.paddingY, 0),\n\t};\n}\n\nexport function sanitizeFlowColumns(columns: FlowColumns): FlowColumns {\n\treturn {\n\t\tcount:\n\t\t\tcolumns.count === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Math.max(1, Math.floor(nonNegativeFinite(columns.count, 1))),\n\t\tgap: columns.gap === undefined ? undefined : nonNegativeFinite(columns.gap, 0),\n\t};\n}\n\nexport function sanitizeObstacles(obstacles: readonly Obstacle[]): readonly Obstacle[] {\n\treturn obstacles.map((obstacle) => {\n\t\tif (obstacle.kind === \"circle\") {\n\t\t\treturn {\n\t\t\t\tkind: obstacle.kind,\n\t\t\t\tcx: finiteNumber(obstacle.cx, 0),\n\t\t\t\tcy: finiteNumber(obstacle.cy, 0),\n\t\t\t\tr: nonNegativeFinite(obstacle.r, 0),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: obstacle.kind,\n\t\t\tx: finiteNumber(obstacle.x, 0),\n\t\t\ty: finiteNumber(obstacle.y, 0),\n\t\t\twidth: nonNegativeFinite(obstacle.width, 0),\n\t\t\theight: nonNegativeFinite(obstacle.height, 0),\n\t\t};\n\t});\n}\n\n/** Intersect a circle obstacle with a horizontal line band. */\nexport function circleIntervalForBand(\n\tobstacle: CircleObstacle,\n\tbandTop: number,\n\tbandBottom: number,\n): Interval | null {\n\tconst radius = nonNegativeFinite(obstacle.r, 0);\n\tconst centerY = obstacle.cy;\n\tconst nearestY = Math.max(bandTop, Math.min(centerY, bandBottom));\n\tconst dy = nearestY - centerY;\n\tif (Math.abs(dy) > radius) return null;\n\tconst dx = Math.sqrt(Math.max(0, radius * radius - dy * dy));\n\treturn { left: obstacle.cx - dx, right: obstacle.cx + dx };\n}\n\n/** Intersect a rectangle obstacle with a horizontal line band. */\nexport function rectIntervalForBand(\n\tobstacle: RectObstacle,\n\tbandTop: number,\n\tbandBottom: number,\n): Interval | null {\n\tconst left = obstacle.x;\n\tconst right = obstacle.x + nonNegativeFinite(obstacle.width, 0);\n\tconst top = obstacle.y;\n\tconst bottom = obstacle.y + nonNegativeFinite(obstacle.height, 0);\n\tif (bottom <= bandTop || top >= bandBottom || right <= left) return null;\n\treturn { left, right };\n}\n\nexport function blockedIntervalsForBand(\n\tobstacles: readonly Obstacle[],\n\tbandTop: number,\n\tbandBottom: number,\n): Interval[] {\n\tconst intervals: Interval[] = [];\n\tfor (const obstacle of obstacles) {\n\t\tconst interval =\n\t\t\tobstacle.kind === \"circle\"\n\t\t\t\t? circleIntervalForBand(obstacle, bandTop, bandBottom)\n\t\t\t\t: rectIntervalForBand(obstacle, bandTop, bandBottom);\n\t\tif (interval) intervals.push(interval);\n\t}\n\treturn intervals.sort((a, b) => a.left - b.left);\n}\n\n/** Flow prepared text through columns and carved obstacle slots. */\nexport function computeFlowLines(\n\tsegments: readonly PreparedSegment[],\n\topts: ComputeFlowLinesOptions,\n): FlowLinesResult {\n\tconst geometry = columnGeometry(opts.container, opts.columns);\n\tconst lineHeight = positiveFinite(opts.lineHeight, 20);\n\tconst minSlotWidth = nonNegativeFinite(opts.minSlotWidth ?? 0, 0);\n\tconst obstacles = opts.obstacles ?? [];\n\tconst segmentAdapter = opts.segmentAdapter ?? getDefaultSegmentAdapter();\n\tconst lines: PositionedLine[] = [];\n\tlet cursor: LayoutCursor = { segmentIndex: 0, graphemeIndex: 0 };\n\tconst contentBottom = Math.max(geometry.paddingY, geometry.height - geometry.paddingY);\n\tfor (let columnIndex = 0; columnIndex < geometry.count; columnIndex += 1) {\n\t\tconst columnLeft = geometry.paddingX + columnIndex * (geometry.columnWidth + geometry.gap);\n\t\tconst columnRight = columnLeft + geometry.columnWidth;\n\t\tfor (\n\t\t\tlet y = geometry.paddingY;\n\t\t\ty + lineHeight <= contentBottom + 1e-3 && cursor.segmentIndex < segments.length;\n\t\t\ty += lineHeight\n\t\t) {\n\t\t\tconst blocked = blockedIntervalsForBand(obstacles, y, y + lineHeight);\n\t\t\tconst slots = carveTextLineSlots(\n\t\t\t\t{ left: columnLeft, right: columnRight },\n\t\t\t\tblocked,\n\t\t\t\tMath.max(minSlotWidth, 1e-6),\n\t\t\t);\n\t\t\tfor (const slot of slots) {\n\t\t\t\tif (cursor.segmentIndex >= segments.length) break;\n\t\t\t\tconst slotWidth = slot.right - slot.left;\n\t\t\t\tconst next = layoutNextLine(segments, cursor, slotWidth, {\n\t\t\t\t\thyphenWidth: opts.hyphenWidth,\n\t\t\t\t\tsegmentAdapter,\n\t\t\t\t});\n\t\t\t\tif (next === null) {\n\t\t\t\t\tcursor = { segmentIndex: segments.length, graphemeIndex: 0 };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tnext.end.segmentIndex === cursor.segmentIndex &&\n\t\t\t\t\tnext.end.graphemeIndex === cursor.graphemeIndex\n\t\t\t\t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcursor = next.end;\n\t\t\t\tif (next.text.length === 0 && next.width === 0) break;\n\t\t\t\tlines.push({\n\t\t\t\t\ttext: next.text,\n\t\t\t\t\twidth: next.width,\n\t\t\t\t\tstartSegment: next.start.segmentIndex,\n\t\t\t\t\tstartGrapheme: next.start.graphemeIndex,\n\t\t\t\t\tendSegment: next.end.segmentIndex,\n\t\t\t\t\tendGrapheme: next.end.graphemeIndex,\n\t\t\t\t\tx: slot.left,\n\t\t\t\t\ty,\n\t\t\t\t\tslotWidth,\n\t\t\t\t\tcolumnIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tlines,\n\t\tcursor,\n\t\tdone: cursor.segmentIndex >= segments.length,\n\t};\n}\n","import { type Ctx, depLatest } from \"../../ctx/types.js\";\nimport { Node } from \"../../node/node.js\";\nimport { computeBlockFlow, computeTotalHeight } from \"./block.js\";\nimport {\n\tcomputeFlowLines,\n\tsanitizeFlowColumns,\n\tsanitizeFlowContainer,\n\tsanitizeObstacles,\n} from \"./flow.js\";\nimport { computeCharPositions, computeLineBreaks } from \"./line.js\";\nimport { inputNode, latestMeasurementValue, scopedName } from \"./measurements.js\";\nimport { getDefaultSegmentAdapter } from \"./segment.js\";\nimport type {\n\tBlocksMeasurement,\n\tCharPosition,\n\tFlowColumns,\n\tFlowContainer,\n\tFlowLinesResult,\n\tLineBreaksResult,\n\tMeasuredBlock,\n\tMeasurements,\n\tObstacle,\n\tPositionedBlock,\n\tPreparedSegment,\n\tReactiveBlockLayoutBundle,\n\tReactiveBlockLayoutOptions,\n\tReactiveFlowLayoutBundle,\n\tReactiveFlowLayoutOptions,\n\tReactiveLayoutBundle,\n\tReactiveLayoutOptions,\n\tTextSegmentsMeasurement,\n} from \"./types.js\";\nimport { BLOCKS_MEASUREMENT_KIND, TEXT_SEGMENTS_MEASUREMENT_KIND } from \"./types.js\";\nimport { emitLayoutError, nonNegativeFinite } from \"./utils.js\";\n\n/**\n * Create a graph-visible single-column text layout bundle.\n *\n * @param opts - Requires a graph and a graph-visible `measurements` node, plus optional\n * `lineHeight`, `maxWidth`, `targetId`, `segmentAdapter`, and bundle `name`.\n * @returns A `ReactiveLayoutBundle` containing input nodes, setters, and graph-visible output\n * nodes for segments, line breaks, height, and character positions.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts\";\n * import {\n * cellTextMeasurements,\n * reactiveLayout,\n * } from \"@graphrefly/ts/solutions/reactive-layout\";\n *\n * const g = graph({ name: \"article\" });\n * const text = g.state(\"Hello GraphReFly\", { name: \"text\" });\n * const font = g.state(\"16px system-ui\", { name: \"font\" });\n * const measurements = cellTextMeasurements({ graph: g, text, font });\n *\n * const layout = reactiveLayout({ graph: g, measurements, maxWidth: 320, lineHeight: 20 });\n * layout.setMaxWidth(280);\n * ```\n * @remarks **Graph-visible:** This creates ordinary state/output nodes only; it does not add\n * protocol behavior, hidden subscriptions, GraphSpec ownership, storage, or platform globals.\n * @category solutions\n */\nexport function reactiveLayout(opts: ReactiveLayoutOptions): ReactiveLayoutBundle {\n\tconst { measurements, segmentAdapter: segmentAdapterOpt, name = \"reactive-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();\n\tconst g = opts.graph;\n\tconst lineHeightInput = inputNode(\n\t\tg,\n\t\topts.lineHeight instanceof Node\n\t\t\t? opts.lineHeight\n\t\t\t: nonNegativeFinite(opts.lineHeight ?? 20, 20),\n\t\tnonNegativeFinite(20, 20),\n\t\tscopedName(name, \"line-height\"),\n\t);\n\tconst maxWidthInput = inputNode(\n\t\tg,\n\t\topts.maxWidth instanceof Node ? opts.maxWidth : nonNegativeFinite(opts.maxWidth ?? 800, 800),\n\t\tnonNegativeFinite(800, 800),\n\t\tscopedName(name, \"max-width\"),\n\t);\n\tconst segments = g.node<readonly PreparedSegment[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.segments ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout segments failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"segments\") },\n\t);\n\tconst lineBreaks = g.node<LineBreaksResult>(\n\t\t[segments, maxWidthInput.node, measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 2) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tconst computed = computeLineBreaks(\n\t\t\t\t\tdepLatest(ctx, 0) as readonly PreparedSegment[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t\t{ hyphenWidth: measured?.hyphenWidth, segmentAdapter: segAdapter },\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", computed]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout line breaks failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"line-breaks\") },\n\t);\n\tconst height = g.node<number>(\n\t\t[lineBreaks, lineHeightInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst lines = depLatest(ctx, 0) as LineBreaksResult;\n\t\t\t\tconst lineHeight = nonNegativeFinite(depLatest(ctx, 1) as number, 0);\n\t\t\t\tctx.down([[\"DATA\", lines.lineCount * lineHeight]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout height failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"height\") },\n\t);\n\tconst charPositions = g.node<readonly CharPosition[]>(\n\t\t[lineBreaks, segments, lineHeightInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst positions = computeCharPositions(\n\t\t\t\t\tdepLatest(ctx, 0) as LineBreaksResult,\n\t\t\t\t\tdepLatest(ctx, 1) as readonly PreparedSegment[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 2) as number, 0),\n\t\t\t\t\tsegAdapter,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", positions]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveLayout char positions failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"char-positions\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tlineHeight: lineHeightInput.node,\n\t\t\tmaxWidth: maxWidthInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetLineHeight(lineHeight: number): void {\n\t\t\tlineHeightInput.set(nonNegativeFinite(lineHeight, 0));\n\t\t},\n\t\tsetMaxWidth(maxWidth: number): void {\n\t\t\tmaxWidthInput.set(nonNegativeFinite(maxWidth, 0));\n\t\t},\n\t\tsegments,\n\t\tlineBreaks,\n\t\theight,\n\t\tcharPositions,\n\t};\n}\n\n/**\n * Create a graph-visible vertical block layout bundle over the same DOM-free core.\n *\n * @param opts - Requires a graph and a graph-visible block `measurements` node, plus optional\n * `gap`, `targetId`, and bundle `name`.\n * @returns A `ReactiveBlockLayoutBundle` containing the gap input, measured block output,\n * positioned block flow, and total height node.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts\";\n * import {\n * blockAdaptersProvider,\n * blockMeasurementProvider,\n * reactiveBlockLayout,\n * type MeasurementAdapter,\n * } from \"@graphrefly/ts/solutions/reactive-layout\";\n *\n * const g = graph({ name: \"cards\" });\n * const blocks = g.state([{ id: \"title\", kind: \"text\", text: \"Hello\" }]);\n * const maxWidth = g.state(320);\n * const text = g.state<MeasurementAdapter>({\n * measureSegment: (segment) => ({ width: segment.length * 8 }),\n * });\n * const measurements = blockMeasurementProvider({\n * graph: g,\n * blocks,\n * maxWidth,\n * adapters: blockAdaptersProvider({ graph: g, text }),\n * });\n *\n * const layout = reactiveBlockLayout({ graph: g, measurements, gap: 12 });\n * layout.setGap(16);\n * ```\n * @remarks **DOM-free:** Image/SVG sizing is explicit or injected; no async image loading or\n * DOM SVG parsing occurs in the core layout bundle.\n * @category solutions\n */\nexport function reactiveBlockLayout(opts: ReactiveBlockLayoutOptions): ReactiveBlockLayoutBundle {\n\tconst { measurements, name = \"reactive-block-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"blocks\";\n\tconst g = opts.graph;\n\tconst gapInput = inputNode(\n\t\tg,\n\t\topts.gap instanceof Node ? opts.gap : nonNegativeFinite(opts.gap ?? 0, 0),\n\t\tnonNegativeFinite(0, 0),\n\t\tscopedName(name, \"gap\"),\n\t);\n\tconst measuredBlocks = g.node<readonly MeasuredBlock[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<BlocksMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tBLOCKS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.blocks ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout measured-blocks failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"measured-blocks\") },\n\t);\n\tconst blockFlow = g.node<readonly PositionedBlock[]>(\n\t\t[measuredBlocks, gapInput.node],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst positioned = computeBlockFlow(\n\t\t\t\t\tdepLatest(ctx, 0) as readonly MeasuredBlock[],\n\t\t\t\t\tnonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", positioned]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout flow failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"block-flow\") },\n\t);\n\tconst totalHeight = g.node<number>(\n\t\t[blockFlow],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tctx.down([[\"DATA\", computeTotalHeight(depLatest(ctx, 0) as readonly PositionedBlock[])]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveBlockLayout total height failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"total-height\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tgap: gapInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetGap(gap: number): void {\n\t\t\tgapInput.set(nonNegativeFinite(gap, 0));\n\t\t},\n\t\tmeasuredBlocks,\n\t\tblockFlow,\n\t\ttotalHeight,\n\t};\n}\n\n/** Create a graph-visible multi-column flow layout bundle with rectangle/circle obstacles. */\nexport function reactiveFlowLayout(opts: ReactiveFlowLayoutOptions): ReactiveFlowLayoutBundle {\n\tconst { measurements, segmentAdapter: segmentAdapterOpt, name = \"reactive-flow-layout\" } = opts;\n\tconst targetId = opts.targetId ?? \"text\";\n\tconst segAdapter = segmentAdapterOpt ?? getDefaultSegmentAdapter();\n\tconst g = opts.graph;\n\tconst lineHeightInput = inputNode(\n\t\tg,\n\t\topts.lineHeight instanceof Node\n\t\t\t? opts.lineHeight\n\t\t\t: nonNegativeFinite(opts.lineHeight ?? 20, 20),\n\t\tnonNegativeFinite(20, 20),\n\t\tscopedName(name, \"line-height\"),\n\t);\n\tconst containerInput = inputNode(\n\t\tg,\n\t\topts.container,\n\t\t{ width: 800, height: 600 },\n\t\tscopedName(name, \"container\"),\n\t);\n\tconst columnsInput = inputNode(\n\t\tg,\n\t\topts.columns,\n\t\t{ count: 1, gap: 0 },\n\t\tscopedName(name, \"columns\"),\n\t);\n\tconst obstaclesInput = inputNode(g, opts.obstacles, [], scopedName(name, \"obstacles\"));\n\tconst segments = g.node<readonly PreparedSegment[]>(\n\t\t[measurements],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 0) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tctx.down([[\"DATA\", measured?.segments ?? []]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveFlowLayout segments failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"segments\") },\n\t);\n\tconst flowLines = g.node<FlowLinesResult>(\n\t\t[\n\t\t\tsegments,\n\t\t\tlineHeightInput.node,\n\t\t\tcontainerInput.node,\n\t\t\tcolumnsInput.node,\n\t\t\tobstaclesInput.node,\n\t\t\tmeasurements,\n\t\t],\n\t\t(ctx: Ctx) => {\n\t\t\ttry {\n\t\t\t\tconst measured = latestMeasurementValue<TextSegmentsMeasurement>(\n\t\t\t\t\tdepLatest(ctx, 5) as Measurements,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tTEXT_SEGMENTS_MEASUREMENT_KIND,\n\t\t\t\t);\n\t\t\t\tconst computed = computeFlowLines(depLatest(ctx, 0) as readonly PreparedSegment[], {\n\t\t\t\t\tlineHeight: nonNegativeFinite(depLatest(ctx, 1) as number, 0),\n\t\t\t\t\tcontainer: sanitizeFlowContainer(depLatest(ctx, 2) as FlowContainer),\n\t\t\t\t\tcolumns: sanitizeFlowColumns(depLatest(ctx, 3) as FlowColumns),\n\t\t\t\t\tobstacles: sanitizeObstacles(depLatest(ctx, 4) as readonly Obstacle[]),\n\t\t\t\t\tminSlotWidth: nonNegativeFinite(opts.minSlotWidth ?? 0, 0),\n\t\t\t\t\thyphenWidth: measured?.hyphenWidth,\n\t\t\t\t\tsegmentAdapter: segAdapter,\n\t\t\t\t});\n\t\t\t\tctx.down([[\"DATA\", computed]]);\n\t\t\t} catch (error) {\n\t\t\t\temitLayoutError(ctx, error, \"reactiveFlowLayout flow lines failed\");\n\t\t\t}\n\t\t},\n\t\t{ name: scopedName(name, \"flow-lines\") },\n\t);\n\treturn {\n\t\tgraph: g,\n\t\tinput: {\n\t\t\tlineHeight: lineHeightInput.node,\n\t\t\tcontainer: containerInput.node,\n\t\t\tcolumns: columnsInput.node,\n\t\t\tobstacles: obstaclesInput.node,\n\t\t\tmeasurements,\n\t\t},\n\t\tsetLineHeight(lineHeight: number): void {\n\t\t\tlineHeightInput.set(nonNegativeFinite(lineHeight, 0));\n\t\t},\n\t\tsetContainer(container: FlowContainer): void {\n\t\t\tcontainerInput.set(container);\n\t\t},\n\t\tsetColumns(columns: FlowColumns): void {\n\t\t\tcolumnsInput.set(columns);\n\t\t},\n\t\tsetObstacles(obstacles: readonly Obstacle[]): void {\n\t\t\tobstaclesInput.set(obstacles);\n\t\t},\n\t\tsegments,\n\t\tflowLines,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,IAAM,WAAW;AAGjB,SAAS,sBAAsB,GAAqB;AAC1D,SAAO,MAAM,YAAY,OAAO,MAAM;AACvC;AAGO,SAAS,aAAa,QAAiB,WAAW,iCAA0C;AAClG,SAAO,sBAAsB,MAAM,IAAI,IAAI,MAAM,QAAQ,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,OA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","snapshotFragment","isDenseArrayOf","safeArrayLength","errorMessage","isDenseArrayOf","resultId","errorMessage","safeArrayLength","safeArrayLength","errorMessage","isDenseArrayOf","safeArrayLength","errorMessage","isDenseArrayOf","statusState","ref","out","blockMaxWidth","text","endsAtSoftHyphen","explicit","size"]}
|